Skip to content

Official Codebase of 3DCodeVerse

Python

D107 + D108: no track ships a cookbook; prompts state requirements; a stage that waits no longer starves the zones

gaoypeng7f06f3cc3f9d
diff --git a/eval/docs/EVAL.md b/eval/docs/EVAL.md
index b556b4d0..c35440f6 100644
--- a/eval/docs/EVAL.md
+++ b/eval/docs/EVAL.md
@@ -33,7 +33,7 @@ fooling ourselves. Tools: `bench/run_bench.py`, `bench/compare_backends.py`,
confidence.
6. **Cost and time are part of the result.** Every cell records `Usage` (USD, tokens)
and wall time; compare at equal budget where possible.
-7. **Reproducibility.** `record.prompt_hashes` (contract/cookbook/generate/refine),
+7. **Reproducibility.** `record.prompt_hashes` (contract/generate/refine; `cookbook` before D107),
rubric content hash (`ScoreBreakdown.rubric_hash`), `record.environment` (python,
codeverse3d, blender, node, three, host) are stored per run; keep seeds fixed
(`--seed`).
diff --git a/eval/llm/docs/inventory_harness_bench.md b/eval/llm/docs/inventory_harness_bench.md
index 02b8b245..8f3f10ec 100644
--- a/eval/llm/docs/inventory_harness_bench.md
+++ b/eval/llm/docs/inventory_harness_bench.md
@@ -40,7 +40,7 @@ Schema (`bench/run_bench.py:49-71`): `Battery{name, track, language, description
## 3. One-shot path (`bench/_oneshot.py`)
- `oneshot_prompt(spec)` = `"Model this object in raw bpy: <prompt>"` + dimensions + MUST HAVE/NOT + minimal contract (Blender 5.x, emptied scene, Z-up, −Y front, metres, on z=0, PascalCase names, material per mesh, no render/export/import/network, <500k tris, <120 s, call `main()`) + "reply with the COMPLETE file as ONE ```python block".
- Backends: `claude-code[:model]`, `codex[:model]`, `gemini:|anthropic:|openai:<model>` (ApiOneShot: temperature 0.5, thinking medium, max_output 32000). **Local open model works** via `openai:<model>` + `C3D_OPENAI_BASE_URL=http://host:8000/v1` (vLLM OpenAI server).
-- Contracts per language to reuse verbatim: `codeverse3d/prompts/{blender,cadquery,threejs,glsl_shader,opengl_python,scene_threejs,urdf}/{system.md,contract.md,cookbook.md}`.
+- Contracts per language to reuse verbatim: `codeverse3d/prompts/{blender,cadquery,threejs,glsl_shader,opengl_python,scene_threejs,scene_blender,urdf}/{system.md,contract.md}` (no language ships a cookbook since D106 / D107).
- Evaluate a workspace: `bench/_fixed_eval.FixedEvaluator(judge_model, n_samples, track, language).evaluate(ws, spec) -> EvalOutcome` (build → gates → 14-view render → judge).
## 4. Renderers / executors (`codeverse3d/languages/<lang>`)
diff --git a/eval/tests/test_loop.py b/eval/tests/test_loop.py
index f575f720..25c852f0 100644
--- a/eval/tests/test_loop.py
+++ b/eval/tests/test_loop.py
@@ -561,7 +561,7 @@ def test_accept_bumps_snapshots_and_rollback_restores(cfg: loop.LoopConfig, over
(it1 / "compare_scene_threejs.json").write_text(json.dumps({"decision": "keep"}))
# the iteration-1 edit of the overlay
(overlay.prompts_root / "scene_threejs").mkdir()
- (overlay.prompts_root / "scene_threejs" / "cookbook.md").write_text("# seat everything\n")
+ (overlay.prompts_root / "scene_threejs" / "system.md").write_text("# seat everything\n")
(overlay.skills_root / "routes.toml").write_text('[[boost]]\nskill = "c3d-scene-placement"\ndelta = 20\n')
before = overlay.overlay_hash()
row = loop.accept(cfg, 1, note="placement recipe", paths=overlay, data_dir=data_dir)
@@ -573,20 +573,20 @@ def test_accept_bumps_snapshots_and_rollback_restores(cfg: loop.LoopConfig, over
toml = overlay.toml.read_text()
assert "# the loop bumps it on accept" in toml and "version = 2" in toml and "[knobs]" in toml
snap2 = cfg.out / "snapshots" / "argon_v2"
- assert (snap2 / "prompts" / "scene_threejs" / "cookbook.md").is_file() and "delta = 20" in (snap2 / "skills" / "routes.toml").read_text()
+ assert (snap2 / "prompts" / "scene_threejs" / "system.md").is_file() and "delta = 20" in (snap2 / "skills" / "routes.toml").read_text()
assert json.loads((snap2 / "snapshot.json").read_text())["hash"] == row.variant_hash, "one number for the snapshot and the row"
ledger = loop.ledger_path(cfg, data_dir)
assert ledger == data_dir / "t_loop" / "ledger.jsonl" and len(loop.ledger_rows(ledger)) == 1
# iteration 2 edits, then a rollback: the edits go, version 2 stays
- (overlay.prompts_root / "scene_threejs" / "cookbook.md").write_text("# a worse idea\n")
+ (overlay.prompts_root / "scene_threejs" / "system.md").write_text("# a worse idea\n")
(overlay.prompts_root / "scene_threejs" / "extra.md").write_text("x\n")
it2 = cfg.iter_dir(2)
it2.mkdir()
row2 = loop.rollback(cfg, 2, note="worse", paths=overlay, data_dir=data_dir)
assert (row2.decision, row2.version_from, row2.version_to) == ("rollback", 2, 2)
- assert (overlay.prompts_root / "scene_threejs" / "cookbook.md").read_text() == "# seat everything\n"
+ assert (overlay.prompts_root / "scene_threejs" / "system.md").read_text() == "# seat everything\n"
assert not (overlay.prompts_root / "scene_threejs" / "extra.md").exists() and overlay.version() == 2
- # rolling back the accepted iteration itself un-accepts it: v1 comes back, cookbook and boost gone
+ # rolling back the accepted iteration itself un-accepts it: v1 comes back, the system.md overlay and boost gone
row3 = loop.rollback(cfg, 1, paths=overlay, data_dir=data_dir)
assert (row3.version_from, row3.version_to) == (2, 1) and overlay.version() == 1
assert not (overlay.prompts_root / "scene_threejs").exists() and (overlay.skills_root / "routes.toml").read_text() == "# no rows yet\n"
diff --git a/harness/CLAUDE.md b/harness/CLAUDE.md
index bfee559e..9af12e14 100644
--- a/harness/CLAUDE.md
+++ b/harness/CLAUDE.md
@@ -90,8 +90,9 @@ cd harness
3dcodeverse make "..." --track articulated_object --language urdf_blender
3dcodeverse make "..." --track scene --language scene_threejs --rounds 2 --max-minutes 60
3dcodeverse make "..." --track scene --language scene_blender --rounds 2 --max-minutes 90 # bpy scene on Blender 5.2.2 (D105): harness-owned src/lib, Cycles judged frames
-# The scene track states REQUIREMENTS, never templates (D106, 2026-10-15): no scene cookbook, no inlined recipes, placeholder
-# skeletons; a scene prompt / skill keeps only interface, sandbox rules and measured thresholds (+ the lib as an optional toolbox).
+# Every track states REQUIREMENTS, never templates (D106 scene, D107 the rest, 2026-10-15): no language ships a cookbook, no inlined
+# recipes, placeholder skeletons; a prompt / skill keeps only interface, sandbox rules and measured thresholds, each contract.md ONE
+# executable interface example (tests/prompts/test_snippets_run.py), the craft as short optional practices in the skills (fences ≤ ~12 lines).
3dcodeverse make "..." --variant argon # per-model prompt/skill overlay: prompts/variants/<name>/ + skills/variants/<name>/ (D105; C3D_VARIANT, C3D_VARIANTS='{"agy:gemini-4-argon": "argon"}')
3dcodeverse make "neon rain on a window" --track graphics --language glsl_shader
3dcodeverse make "..." --image ref.png --candidates 3 --rounds 2 --dim height=0.45 --must "three legs" --texture --no-run
diff --git a/harness/codeverse3d/agents/cli_common.py b/harness/codeverse3d/agents/cli_common.py
index e3e10295..ef263d96 100644
--- a/harness/codeverse3d/agents/cli_common.py
+++ b/harness/codeverse3d/agents/cli_common.py
@@ -426,7 +426,7 @@ def _enforce_scope(s: Session) -> dict[str, str]:
Post-hoc, because every backend is a vendor CLI and none has a write-time file gate
(the in-process one that did was deleted 2026-08-28). Three layers:
``job.read_only`` ALWAYS — harness-owned source the agent must call, never rewrite
- (``src/recipes.glsl``); ``job.write_roots`` ALWAYS — a CLI session used to be able
+ (a scene's ``src/lib/``); ``job.write_roots`` ALWAYS — a CLI session used to be able
to write and commit a root-level ``conftest.py``; then, for ``edit_only``, the
narrowing to ``files_hint`` + ``always_writable`` (a pre-existing file outside it is
out of scope; new files stay allowed). Only safe because sessions on one workspace
diff --git a/harness/codeverse3d/agents/materialize.py b/harness/codeverse3d/agents/materialize.py
index 8fed68a5..be884415 100644
--- a/harness/codeverse3d/agents/materialize.py
+++ b/harness/codeverse3d/agents/materialize.py
@@ -1,8 +1,8 @@
"""Materialise per-workspace agent instructions + ignore file.
One shared body is written to ``AGENTS.md`` (codex / agy) and ``CLAUDE.md`` (claude-code):
-task-agnostic rules, how to call the ``3dcode`` spatial tools, where the cookbook is, and the
-language contract. (agy reads ``GEMINI.md`` as well as ``AGENTS.md``; a third copy would be
+task-agnostic rules, how to call the ``3dcode`` spatial tools, and the language contract.
+(agy reads ``GEMINI.md`` as well as ``AGENTS.md``; a third copy would be
loaded twice.) MCP wiring — never a file in the workspace, which is agent-writable:
* claude-code → per-session ``trajectories/<label>_rNN/mcp.json`` (``agents/backends.py``)
@@ -30,11 +30,14 @@ import logging
from codeverse3d.agents.cli_common import default_mcp_command
from codeverse3d.proc import read_json_or_none
from codeverse3d.skills.materialize import BODY_FILES
-from codeverse3d.workspace import Workspace
+from codeverse3d.workspace import C3D_DIR, Workspace
log = logging.getLogger(__name__)
-C3D_DIR = ".3dcode" # harness-owned read-only docs inside the workspace
+#: a run made BEFORE D107 was handed its language's cookbook here (and a "## Cookbook" section in
+#: the body files). Materialising removes it, and its presence makes a resumed run re-materialise
+#: (``needs_rematerialize``) so the agent of a later round never reads a cookbook.
+LEGACY_COOKBOOK = f"{C3D_DIR}/cookbook.md"
MCP_SERVER_NAME = "3dcode"
MCP_TOOL_TIMEOUT_MS = 600_000
#: ``.antigravityignore`` — agy's own ignore file. The agent-facing artefacts must stay readable:
@@ -90,7 +93,7 @@ def _tool_section(agent_kind: str, spatial_tools: bool, mcp_command: list[str],
)
-def _body(agent_kind: str, contract_md: str, cookbook_section: str, spatial_tools: bool, mcp_command: list[str],
+def _body(agent_kind: str, contract_md: str, spatial_tools: bool, mcp_command: list[str],
ws: Workspace | None = None) -> str:
return (
"# 3dcode workspace — rules for the coding agent\n\n"
@@ -108,7 +111,6 @@ def _body(agent_kind: str, contract_md: str, cookbook_section: str, spatial_tool
"5. When you are done, reply with a SHORT summary of what you changed and what you verified. "
"Do not ask questions — there is no human in the loop; make a reasonable decision and proceed.\n\n"
f"{_tool_section(agent_kind, spatial_tools, mcp_command, ws)}\n"
- f"{cookbook_section}"
f"## Language contract\n\n{contract_md.strip()}\n"
)
@@ -144,7 +146,6 @@ def materialize_workspace(
*,
agent_kind: str,
contract_md: str,
- cookbook_text: str,
spatial_tools: bool,
mcp_command: list[str] | None = None,
) -> None:
@@ -155,37 +156,23 @@ def materialize_workspace(
here, which the body text and codex's ``-c`` overrides then quoted verbatim.
Returns nothing: the ``Materialized`` DTO this used to build (body/ignore paths, the
- cookbook path, the argv, a warnings list) was discarded by every production caller —
+ argv, a warnings list) was discarded by every production caller —
``tracks/common.Services.materialize`` is typed ``-> None``.
- ``cookbook_text`` is what the catalog loaded (``RunContext.cookbook_text``): until
- 2026-09-22 this took a path and resolved it itself, workspace first — so a
- ``<ws>/blender/cookbook.md`` the agent wrote shadowed the harness cookbook. A language
- that ships no cookbook (the two scene languages, owner 2026-10-15) passes ``""`` and the
- body carries no "## Cookbook" section at all: the contract and the skills are what there
- is, and a note saying a file is missing would only send the agent looking for one. (A
- stale ``.3dcode/cookbook.md`` from an earlier materialisation is removed for the same
- reason.)"""
+ The body is the hard rules, the tool cards and the language contract — nothing else is
+ written for the agent to read (D107, owner 2026-10-15: no language ships a cookbook; the
+ interface facts are in the contract, the craft in the routed skills)."""
mcp_command = list(mcp_command) if mcp_command else default_mcp_command(ws)
-
- # cookbook: copy into the harness-owned .3dcode/ dir so every CLI can read it in-workspace
- dest = ws.root / C3D_DIR / "cookbook.md"
- if cookbook_text:
- dest.parent.mkdir(parents=True, exist_ok=True)
- dest.write_text(cookbook_text, encoding="utf-8")
- cookbook_section = (
- "## Cookbook\n\n"
- f"The cookbook for this language — copyable, verified snippets and skeletons — is at "
- f"`{C3D_DIR}/cookbook.md` (relative to the workspace root). Read the relevant sections "
- "before writing code and copy its patterns exactly.\n\n"
- )
- else:
- dest.unlink(missing_ok=True)
- cookbook_section = ""
-
- body = _body(agent_kind, contract_md, cookbook_section, spatial_tools, mcp_command, ws)
+ body = _body(agent_kind, contract_md, spatial_tools, mcp_command, ws)
for name in BODY_FILES:
(ws.root / name).write_text(body)
+ (ws.root / LEGACY_COOKBOOK).unlink(missing_ok=True)
# No MCP server is written into the workspace: every CLI gets 3dcode from a harness-owned
# per-session file, so an agent-planted server cannot reach the next round (audit 2026-08-27).
(ws.root / IGNORE_FILE).write_text("\n".join(IGNORE_LINES) + "\n")
+
+
+def needs_rematerialize(ws: Workspace) -> bool:
+ """A workspace materialised before D107 (it still holds :data:`LEGACY_COOKBOOK`) — its body
+ files carry the old "## Cookbook" section, so a resumed run writes them again."""
+ return (ws.root / LEGACY_COOKBOOK).is_file()
diff --git a/harness/codeverse3d/cli/skills_cmd.py b/harness/codeverse3d/cli/skills_cmd.py
index 70434599..7e4f9e41 100644
--- a/harness/codeverse3d/cli/skills_cmd.py
+++ b/harness/codeverse3d/cli/skills_cmd.py
@@ -1,7 +1,7 @@
"""``3dcode skills`` — look at the library, validate it, and read the read-rate.
``report`` is the command that matters. The whole system exists because a tool that
-exists is not a tool that gets used (``read_cookbook``: 0 of 16 zone sessions), so the
+exists is not a tool that gets used (the former ``read_cookbook`` tool: 0 of 16 zone sessions), so the
first question about any battery is not "did the score move" but "did anyone open the
file". Everything else here is plumbing for that answer.
"""
diff --git a/harness/codeverse3d/config.py b/harness/codeverse3d/config.py
index cd4ddbe0..455ca5b7 100644
--- a/harness/codeverse3d/config.py
+++ b/harness/codeverse3d/config.py
@@ -153,18 +153,6 @@ class Limits(BaseModel):
"own A/B — docs/COST.md §17 — so no profile sets one; name it here or as "
"C3D_AGENT_MAX_TURNS if you want one).",
)
- seed_recipes: Flag = Field(
- default=True,
- description="graphics / glsl_shader: paste the cookbook recipes the brief calls for "
- "(curtain / aurora / stars / bokehSoft / dropsLayer + the hash / noise / fbm helpers "
- "they use) into the harness-owned, read-only src/recipes.glsl BEFORE the baseline session "
- "(tracks/graphics.py:seed_recipes; pasted above src/common.glsl at build time). "
- "ON by default: measured 2026-08-26 (refs_v2_graphics, aurora brief, gemini-3.7-flash) "
- "the prompt carried the verified curtain() recipe five times and the agent used it zero "
- "times — round 0 was again a comb of bars (comb_artefact, 0.33); and (eval/bench/out/seed_v1) "
- "recipes seeded into the agent's own common.glsl were overwritten before the end of the run. "
- "`C3D_SEED_RECIPES=0` is the control arm.",
- )
class Rate(BaseModel):
@@ -259,7 +247,6 @@ class Settings(BaseSettings):
FLAT: ClassVar[dict[str, tuple[str, str]]] = {
"C3D_MAX_IN_FLIGHT": ("rate", "max_in_flight"),
"C3D_RENDER_GPU": ("render", "gpu"),
- "C3D_SEED_RECIPES": ("limits", "seed_recipes"),
"C3D_AGENT_MAX_TURNS": ("limits", "agent_max_turns"),
}
diff --git a/harness/codeverse3d/contracts/agent.py b/harness/codeverse3d/contracts/agent.py
index 245fe1e6..82553041 100644
--- a/harness/codeverse3d/contracts/agent.py
+++ b/harness/codeverse3d/contracts/agent.py
@@ -71,7 +71,7 @@ class AgentJob(BaseModel):
read_only: list[str] = Field(
default_factory=list,
description="harness-owned files inside write_roots the agent may read but never write "
- "(src/recipes.glsl for glsl_shader: contracts.common.HARNESS_OWNED_SRC); enforced "
+ "(src/lib/ for the scene languages: contracts.common.HARNESS_OWNED_SRC); enforced "
"post-session: a write to one is reverted and the session failed",
)
mcp_command: list[str] | None = Field(
diff --git a/harness/codeverse3d/contracts/common.py b/harness/codeverse3d/contracts/common.py
index 871d2f39..8f32aef7 100644
--- a/harness/codeverse3d/contracts/common.py
+++ b/harness/codeverse3d/contracts/common.py
@@ -82,14 +82,14 @@ ENTRY_FILE: dict[Language, str] = {
#: source files the HARNESS writes under ``src/`` and owns: the agent reads them and calls what
#: they define, never writes them (``AgentJob.read_only`` — the agent's write scope excludes them).
-#: Measured 2026-08-26 (eval/bench/out/seed_v1, aurora brief, gemini-3.7-flash api-agent): recipes
-#: seeded into the agent's own ``src/common.glsl`` were gone by the end of the run — it rewrote
-#: the file with its own helpers — so a seeded file has to be one the agent cannot rewrite.
-#: An entry ending in ``/`` is a DIRECTORY prefix: every file under it is owned. That is
-#: how the 52-module effect library is named without listing 52 paths — and the list is
-#: the library's contents, so an entry per file would go stale the day one is added.
+#: Measured 2026-08-26 (eval/bench/out/seed_v1, aurora brief): helpers seeded into the agent's own
+#: ``src/common.glsl`` were gone by the end of the run — it rewrote the file — so a seeded file has
+#: to be one the agent cannot rewrite. (glsl_shader's seeded ``src/recipes.glsl`` went with the
+#: recipe seeding, D107.) An entry ending in ``/`` is a DIRECTORY prefix: every file under it is
+#: owned — the effect library is named without listing every path; an entry without one is an
+#: exact file (no language ships one since D107; the rule stays for the next seeded file, and
+#: ``tests`` exercise it on a synthetic entry).
HARNESS_OWNED_SRC: dict[Language, tuple[str, ...]] = {
- Language.GLSL_SHADER: ("src/recipes.glsl",),
# the effect library (D51): the agent imports and calls it, never rewrites it.
Language.SCENE_THREEJS: ("src/lib/",),
# the small bpy library (DESIGN phase 4, D51 extended): same rule, same directory
diff --git a/harness/codeverse3d/contracts/plan.py b/harness/codeverse3d/contracts/plan.py
index d467e97b..b2de9d43 100644
--- a/harness/codeverse3d/contracts/plan.py
+++ b/harness/codeverse3d/contracts/plan.py
@@ -754,14 +754,14 @@ class EngineeringBrief(BaseModel):
reference: str = Field(description="the real-world reference instance the numbers come from")
one_line: str = Field(description="what it is, one sentence")
dimensions_m: list[RefDimension] = Field(
- max_length=12, description="4-10 real-world reference dimensions in METERS, the small ones included")
- sub_assemblies: list[SubAssembly] = Field(max_length=10, description="3-8 assemblies a fitter would name")
+ max_length=12, description="up to 12 real-world reference dimensions in METERS, the small ones included")
+ sub_assemblies: list[SubAssembly] = Field(max_length=10, description="up to 10 assemblies a fitter would name")
mechanism: str = Field(description="how it works / how force or material moves through it")
visible_from_outside: list[str] = Field(
- max_length=16, description="8-16 things a viewer actually sees from outside — the only things worth modelling")
+ max_length=16, description="up to 16 things a viewer actually sees from outside — the only things worth modelling")
signature_features: list[str] = Field(
- max_length=6, description="3-6 features a viewer uses to recognise it — absence makes it the wrong object")
- materials: list[str] = Field(max_length=12, description="'<part>: <material, colour, finish>' lines, 6-12 of them")
+ max_length=6, description="up to 6 features a viewer uses to recognise it — absence makes it the wrong object")
+ materials: list[str] = Field(max_length=12, description="'<part>: <material, colour, finish>' lines, up to 12")
hidden_inside: list[str] = Field(default_factory=list, max_length=10,
description="real parts that are NOT visible and must not be modelled")
not_present: list[str] = Field(default_factory=list, max_length=10,
@@ -780,8 +780,7 @@ class PassPlan(BaseModel):
description: str = Field(description="what this pass draws / computes, concrete")
elements: list[str] = Field(
default_factory=list, max_length=8,
- description="named things this pass draws, each with its numbers "
- "(e.g. '7 gear wheels, 12-24 teeth, radii 0.06-0.22 screen units')")
+ description="optional: up to 8 named things this pass draws, each with its numbers")
detail_hint: str = Field(default="", description="one line: what makes THIS pass read as real")
@@ -796,7 +795,7 @@ class GraphicsPlan(BaseModel):
passes: list[PassPlan] = Field(min_length=1)
uniforms: list[str] = Field(default_factory=list, description="uniform names the program exposes (u_time, u_resolution, ...)")
motion: str = Field(default="", description="what animates over time and how")
- key_visuals: list[str] = Field(default_factory=list, description="3-8 visible elements a viewer must recognise")
+ key_visuals: list[str] = Field(default_factory=list, description="visible elements a viewer must recognise")
acceptance: list[AcceptanceItem] = Field(default_factory=list)
diff --git a/harness/codeverse3d/contracts/run.py b/harness/codeverse3d/contracts/run.py
index 17cae703..c3567676 100644
--- a/harness/codeverse3d/contracts/run.py
+++ b/harness/codeverse3d/contracts/run.py
@@ -45,7 +45,7 @@ class SkillRead(BaseModel):
class SkillsUsage(BaseModel):
"""``RoundRecord.skills`` — listed vs read vs what it cost, per round.
- The metric that replaces "0 of 16 read_cookbook calls" is :attr:`deep_read_rate`.
+ The metric that replaces the former ``read_cookbook`` tool's "0 of 16 calls" is :attr:`deep_read_rate`.
"""
listed: list[str] = Field(default_factory=list)
@@ -267,7 +267,7 @@ class SettingsSnapshot(BaseModel):
seed: int = 0
rubric: str = ""
rubric_hash: str = Field(default="", description="content hash of the judge rubric YAML")
- prompt_hashes: dict[str, str] = Field(default_factory=dict, description="contract / cookbook / generate / refine …")
+ prompt_hashes: dict[str, str] = Field(default_factory=dict, description="contract / generate / refine / repair / skill:<name> / judge …")
tool_versions: dict[str, str] = Field(default_factory=dict, description="python / blender / node / three / chrome / harness sha")
harness_version: str = ""
harness_git_sha: str = ""
diff --git a/harness/codeverse3d/judges/prompt_builder.py b/harness/codeverse3d/judges/prompt_builder.py
index dad80caf..aa76e420 100644
--- a/harness/codeverse3d/judges/prompt_builder.py
+++ b/harness/codeverse3d/judges/prompt_builder.py
@@ -290,7 +290,7 @@ def plan_detail_crops(shaded: list[RenderView], *, scene: bool, gates: Sequence[
return []
centre = Montage("detail", (shaded[0],), f"DETAIL CROP — centre of {shaded[0].name} at 2×",
crop=(0.25, 0.25, 0.75, 0.75),
- hint="look for bevels, seams, gaps and surface artefacts; judge detail at this scale")
+ hint="look for edge treatment, seams, gaps and surface artefacts at this scale; judge detail here")
if scene:
return [centre, *plan_contact_crops(shaded, gates)[:limit]]
out = [centre]
@@ -611,7 +611,7 @@ SCORING RULES
- DEFECT CHECKLIST: answer EVERY item with present=true/false. true ONLY when the defect is visible in an image, or a gate finding of severity ERROR / a measurement states it; gate WARNINGS (e.g. a few-mm weld overlap) are informational and never make a defect present. Cite where. These answers drive penalties and caps computed by the harness, so be literal: do not mark a defect to "be safe", and do not hide one to be kind.
- Do NOT compute an overall or decide pass/fail; the harness computes the weighted overall, subtracts defect penalties, applies floors and caps.
- Issues: observable defects, most severe first, with target = the part / zone / joint / asset name from the plan digest (or "overall"), a kind, a severity and evidence.
-- Improvement plan: at most 6 concrete, imperative instructions for the builder ("taper the four legs from 45 mm at the seat to 30 mm at the foot and extend them to touch y=0"), priority 1 first, each with a target name from the plan digest and an expected_gain estimate. Give items even for passing work if a named change would raise the score; leave empty only when nothing would.
+- Improvement plan: at most 6 concrete, imperative instructions for the builder ("rear_leg_left: ends 3 cm above y=0 in the ground-contact crop — extend it to touch the ground"; "seat: measured 62 mm thick against the brief's 25 mm — thin it to the stated size"), priority 1 first, each with a target name from the plan digest and an expected_gain estimate. Give items even for passing work if a named change would raise the score; leave empty only when nothing would.
- Acceptance items: answer verified=true ONLY when the renders or measurements prove the item; otherwise false with what is missing.
- Reply with ONE JSON object matching the requested schema; no prose outside it."""
diff --git a/harness/codeverse3d/judges/rubrics/articulated_v1.yaml b/harness/codeverse3d/judges/rubrics/articulated_v1.yaml
index d8bdac69..c0093725 100644
--- a/harness/codeverse3d/judges/rubrics/articulated_v1.yaml
+++ b/harness/codeverse3d/judges/rubrics/articulated_v1.yaml
@@ -58,8 +58,9 @@ criteria:
floor: 0.3
title: Articulation plausibility
description: 'In the pose sheet, does each joint move the way the real mechanism moves — the right TYPE of motion
- (swing vs slide), the right direction, and a believable amount? A drawer must slide out along its depth; a
- door must swing about its hinge edge; a lid must open upward; an arm link must rotate about its pivot.
+ (swing vs slide), the right direction, and a believable amount? Each joint must move the way the real
+ mechanism moves and the plan''s joint table states (a drawer slides along its depth, a door swings about its
+ hinge edge, a lid about the edge it is hinged on, an arm link about its pivot).
'
anchors:
@@ -90,19 +91,19 @@ criteria:
weight: 0.12
title: Geometry detail
description: 'How much SHAPE was actually modelled, mechanism included? Count REFINEMENT KINDS (the list is in
- the rubric notes) and how many of the links carry at least one, and count the mechanism parts that exist as
- geometry rather than as an implied joint: hinge leaves and knuckles, rails and runners, handles and knobs,
- catches, hinges'' screw plates, panel insets, edge thickness. Geometry only — colour and material variety
- never raise this criterion.
+ the rubric notes) and how many of the links carry at least one, and count the mechanism parts the real
+ object shows that exist here as geometry rather than as an implied joint: visible hinge leaves and knuckles,
+ exposed rails, handles and knobs, catches, panel insets, edge thickness; concealed hardware the real object
+ hides is not expected. Geometry only — colour and material variety never raise this criterion.
'
anchors:
- '1.0': Five or more refinement kinds visible AND the mechanism itself is modelled (hinge leaves, drawer runners,
- catches, handles) on at least two thirds of the links; finest features at real hardware scale.
+ '1.0': Five or more refinement kinds visible AND every piece of hardware the real mechanism shows is modelled,
+ on at least two thirds of the links; finest features at real hardware scale.
'0.85': Three or four refinement kinds on at least half the links, and at least one mechanism part modelled
rather than implied.
'0.7': Exactly two refinement kinds, or more but concentrated on one hero link; the joint is a bare abutment
- with no visible hardware.
+ although the real object shows hardware there.
'0.55': One refinement kind on a couple of links, the rest unmodified primitives.
'0.4': Primitive stack, at most one token detail on one link.
'0.25': Every link is an unmodified primitive; only size, position and colour vary.
@@ -273,12 +274,12 @@ defects:
cap: 0.6
- id: detail_below_part_count
text: The object has EIGHT or more links but fewer than THREE distinct refinement kinds (the numbered list in the
- rubric notes) are visible across all of them together, and the joints are bare abutments with no modelled
- hardware. Count kinds, not instances; do not count colour.
+ rubric notes) are visible across all of them together, and hardware the real mechanism shows is absent at the
+ joints. Count kinds, not instances; do not count colour.
penalty: 0.05
- id: primitive_only
- text: Every part is an unmodified box / cylinder with sharp 90° edges — no handles, bevels, insets, rails or thickness
- anywhere.
+ text: Every part is an unmodified box / cylinder with sharp 90° edges although the real object has handles, shaped
+ edges, insets, rails or visible thickness — none of them anywhere.
penalty: 0.08
- id: untextured_flat
text: Default grey / magenta placeholder materials are visible, or surfaces are unlit flat fills with no shading response. A uniform but sensible colour (an all-walnut chair, an all-oak cabinet) is NOT this defect.
diff --git a/harness/codeverse3d/judges/rubrics/asset_v1.yaml b/harness/codeverse3d/judges/rubrics/asset_v1.yaml
index 41f318b7..bce9125a 100644
--- a/harness/codeverse3d/judges/rubrics/asset_v1.yaml
+++ b/harness/codeverse3d/judges/rubrics/asset_v1.yaml
@@ -163,7 +163,7 @@ defects:
penalty: 0.08
cap: 0.65
- id: primitive_only
- text: Every part is an unmodified box / cylinder / sphere with sharp edges — no bevel, taper, profile or cut-out.
+ text: Every part is an unmodified box / cylinder / sphere with sharp edges although the thing the plan entry names has shaped edges, profiles or cut-outs — none anywhere.
penalty: 0.08
- id: untextured_flat
text: Default grey / magenta placeholder materials are visible, or surfaces are unlit flat fills with no shading response. A uniform but sensible colour (an all-walnut chair, an all-oak cabinet) is NOT this defect.
diff --git a/harness/codeverse3d/judges/rubrics/reference_v1.yaml b/harness/codeverse3d/judges/rubrics/reference_v1.yaml
index b12851c3..e9c0b699 100644
--- a/harness/codeverse3d/judges/rubrics/reference_v1.yaml
+++ b/harness/codeverse3d/judges/rubrics/reference_v1.yaml
@@ -145,7 +145,7 @@ defects:
penalty: 0.08
cap: 0.65
- id: primitive_only
- text: Every part is an unmodified box / cylinder / sphere with sharp edges — no bevel, taper, profile or cut-out.
+ text: Every part is an unmodified box / cylinder / sphere with sharp edges although the reference shows shaped edges, profiles or cut-outs.
penalty: 0.08
- id: untextured_flat
text: Default grey / magenta placeholder materials are visible, or surfaces are unlit flat fills with no shading response. A uniform but sensible colour (an all-walnut chair, an all-oak cabinet) is NOT this defect.
diff --git a/harness/codeverse3d/judges/rubrics/shader_v2.yaml b/harness/codeverse3d/judges/rubrics/shader_v2.yaml
index b658c1cc..186bf5a6 100644
--- a/harness/codeverse3d/judges/rubrics/shader_v2.yaml
+++ b/harness/codeverse3d/judges/rubrics/shader_v2.yaml
@@ -48,12 +48,13 @@ criteria:
weight: 0.16
title: Depth and detail
description: >
- Is there structure at several scales — near / mid / far layers with real depth cues
- (parallax, fog, size and brightness falloff), fbm or particle detail inside the large shapes,
- highlights and shadows — rather than one texture or gradient filling the frame? Credit only
- what is visible in the frames.
+ Is there structure at more than one scale, as the subject has it — depth cues where the subject
+ has depth (overlap, parallax, atmospheric or size falloff), fine detail inside the large shapes
+ where the real thing has it, highlights and shadows — rather than one texture or gradient filling
+ the frame? A flat style the brief allows is judged on its own detail, not on depth it does not
+ claim. Credit only what is visible in the frames.
anchors:
- "1.0": Several layers at different depths, each with its own detail; the image rewards a closer look.
+ "1.0": Detail at every scale the subject offers, each scale with its own structure; the image rewards a closer look.
"0.7": Two or three distinct layers; some areas plain.
"0.4": One dominant element on a flat background; little detail.
"0.1": A single gradient, blob, or field of uniform noise fills the frame.
@@ -199,7 +200,7 @@ defects:
text: Haze, bloom or fog lifts a large region toward white (a milky frame, or a blown patch that is not a light source).
penalty: 0.08
- id: candy_saturation
- text: Colours are uniformly candy-saturated or pastel with no neutral or dark counterweight.
+ text: Colours are uniformly candy-saturated or pastel with no neutral or dark counterweight, and the brief did not ask for that palette.
penalty: 0.06
- id: black_or_blown
text: At least one sampled frame is essentially solid black or blown-out white.
diff --git a/harness/codeverse3d/judges/rubrics/static_object_v1.yaml b/harness/codeverse3d/judges/rubrics/static_object_v1.yaml
index b30e3a61..bcb0bd55 100644
--- a/harness/codeverse3d/judges/rubrics/static_object_v1.yaml
+++ b/harness/codeverse3d/judges/rubrics/static_object_v1.yaml
@@ -15,8 +15,9 @@ extra_instructions: >
detail, and the GEOMETRY-ONLY montage (when present) for holes, inverted faces and
intersections. Hidden connectors (a bracket inside a shade, a dowel inside a joint)
are NOT defects when the parts visibly meet. CALIBRATION — use these fixed points:
- 0.9+ = every part crisp with bevels/chamfers/tapers/profiles, correct proportions,
- clean joins, sensible materials (a product photo); 0.7 = correct and complete but
+ 0.9+ = every part carries the edge treatment, profile and hardware the real object has, at
+ its scale, with correct proportions, clean joins and sensible materials (a product photo);
+ 0.7 = correct and complete but
plain; 0.5 = recognisable but a stack of primitives, or one major defect (a gap, a
floating part, a wrong proportion); 0.2 = wrong object, flat blobs, parts exploded
or lying on its back. A primitive box-stack and a crafted product must be ≥ 0.4
@@ -98,7 +99,7 @@ criteria:
(use the measurement table and any stated dimensions)? Seat height, leg
thickness, wheel diameter, handle size must read as real-world correct.
anchors:
- "1.0": Overall size and every part ratio are believable against the measurement table; stated dimensions are met within tolerance (±5%).
+ "1.0": Overall size and every part ratio are believable against the measurement table; stated dimensions are met within the contract gate's tolerance (max(10 mm, 10 % of the extent) per axis — the contract gate reports any excess; trust it over your eye).
"0.7": One part is somewhat thick/thin/short/long (legs 30% heavier than typical) but the object still reads correctly at the stated size.
"0.4": A clearly wrong proportion (legs twice as thick as they should be, a tiny seat on a huge frame, a 1.2 m tall dining chair) or the size is off by more than ~20%.
"0.1": Proportions are absurd (seat thicker than it is wide) or the object is the wrong order of magnitude.
@@ -212,10 +213,10 @@ defects:
penalty: 0.10
cap: 0.50
- id: primitive_only
- text: Two thirds or more of the nameable parts are unmodified boxes / cylinders / spheres with sharp 90° edges, and at most one part carries any bevel, taper, profile, curve or cut-out. Different colours on stock shapes do NOT count as refinement.
+ text: Two thirds or more of the nameable parts are unmodified boxes / cylinders / spheres with sharp 90° edges where the real object has shaped edges, profiles, curves or cut-outs (the plan digest names them); at most one part carries any. Different colours on stock shapes do NOT count as refinement.
penalty: 0.08
- id: detail_below_part_count
- text: The object has TEN or more nameable parts but fewer than THREE distinct refinement kinds (the numbered list in the rubric notes) are visible across all of them together — many primitives, little shape. Count kinds, not instances; do not count colour.
+ text: The object has TEN or more nameable parts but fewer than THREE distinct refinement kinds (the numbered list in the rubric notes) are visible across all of them together although the real object carries more — many primitives, little shape. Count kinds, not instances; do not count colour.
penalty: 0.05
- id: untextured_flat
text: Default grey / magenta placeholder materials are visible (the untinted "nothing was
diff --git a/harness/codeverse3d/languages/blender/__init__.py b/harness/codeverse3d/languages/blender/__init__.py
index ebd3b98d..b329aaab 100644
--- a/harness/codeverse3d/languages/blender/__init__.py
+++ b/harness/codeverse3d/languages/blender/__init__.py
@@ -235,8 +235,8 @@ def call_traps(c: BpyCollector, name: str, call: ast.Call) -> list[GateFinding]:
if name.endswith("modifier_apply") and not c.has_temp_override:
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
+ # the rule's own precondition: a script that sets the active object before joining (as a
+ # urdf_blender model does to get 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(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,
@@ -529,10 +529,6 @@ def instance_centers(bbox: BBox, n: int, symmetry: str) -> list[tuple[float, flo
return [(cx, cy, cz) for _ in range(n)]
-def _bevel(bbox: BBox) -> float:
- return max(0.0, min(0.01, 0.08 * min(bbox.extents)))
-
-
# ----------------------------------------------------------------------------- shared text blocks
IMPORTS = '''import math
import random
@@ -556,27 +552,22 @@ def make_material(name, rgb, roughness=0.5, metallic=0.0):
return mat
-def add_box(name, center, extents, material=None, bevel=0.0):
- """Axis-aligned box: size=1 cube scaled to `extents`, scale baked into the mesh."""
+def add_box(name, center, extents, material=None):
+ """PLACEHOLDER helper (replace freely): an axis-aligned box of exactly `extents`, scale baked."""
bpy.ops.mesh.primitive_cube_add(size=1, location=center, scale=extents)
obj = bpy.context.object
obj.name = name
bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
if material is not None:
obj.data.materials.append(material)
- if bevel > 0:
- mod = obj.modifiers.new("Bevel", "BEVEL")
- mod.width = bevel
- mod.segments = 3
- mod.limit_method = "ANGLE"
return obj
'''
SELFCHECK = '''
def _selfcheck():
- """What the harness checks first: meshes exist, no auto-suffixed names, stands on z=0 —
- over the meshes that export (a hidden boolean cutter does not)."""
+ """Optional: meshes exist, no auto-suffixed names, lowest point — over the meshes that
+ export (a hidden boolean cutter does not). Fails only past the ground gate's ERROR line."""
bpy.context.view_layer.update()
shown = set(bpy.context.view_layer.objects.keys())
meshes = [o for o in bpy.data.objects if o.type == "MESH" and o.name in shown
@@ -585,7 +576,7 @@ def _selfcheck():
for o in meshes:
assert "." not in o.name, f"auto-suffixed name {o.name!r}: give every instance its own name"
z_min = min((o.matrix_world @ Vector(c)).z for o in meshes for c in o.bound_box)
- assert abs(z_min) < __GROUND_TOL__, f"lowest point z={z_min:.4f}: the object must stand on z=0"
+ assert abs(z_min) < 3 * __GROUND_TOL__, f"lowest point z={z_min:.4f}: check_contract reports this as an ERROR"
print(f"[selfcheck] {len(meshes)} mesh objects, z_min={z_min:.4f}")
'''
@@ -595,7 +586,8 @@ def _constants(p: PartPlan) -> str:
mn, mx = p.bbox.min, p.bbox.max
pre = to_snake(p.name).upper()
return (
- f"# ---- plan numbers (metres) for {to_pascal(p.name)} — keep the finished part inside this bbox\n"
+ f"# ---- plan bbox (metres) for {to_pascal(p.name)}: the built AABB must match it within max(1 cm, 10 %) "
+ f"per axis (check_contract)\n"
f"{pre}_CENTER = ({fmt3(p.bbox.center)})\n"
f"{pre}_EXTENTS = ({fmt3(p.bbox.extents)})\n"
f"{pre}_MIN = ({fmt3(mn)})\n"
@@ -619,7 +611,7 @@ def _part_function(p: PartPlan) -> str:
f" x in [{mn[0]:.3f}, {mx[0]:.3f}] y in [{mn[1]:.3f}, {mx[1]:.3f}] z in [{mn[2]:.3f}, {mx[2]:.3f}]",
]
if p.attach_to:
- lines.append(f" Attaches to: {to_pascal(p.attach_to)} (surfaces must touch, no gap)")
+ lines.append(f" Attaches to: {to_pascal(p.attach_to)} (surface gap <= 2 mm, overlap <= 2 mm: check_connectivity)")
if p.instances > 1:
lines.append(f" Instances: {p.instances} ({p.symmetry}) -> named {pascal}_0..{pascal}_{p.instances - 1}, "
f"each TOP-LEVEL (no parent Empty — it would merge them into one measured part); returns the list")
@@ -628,7 +620,7 @@ def _part_function(p: PartPlan) -> str:
if p.instances == 1:
lines += [
" # TODO: replace this placeholder box with the real geometry (keep the name + bbox)",
- f" return add_box(\"{pascal}\", {pre}_CENTER, {pre}_EXTENTS, mat, bevel={_bevel(p.bbox):.4f})",
+ f" return add_box(\"{pascal}\", {pre}_CENTER, {pre}_EXTENTS, mat)",
]
else:
centers = [tuple(round(x, 4) for x in c) for c in instance_centers(p.bbox, p.instances, p.symmetry)]
@@ -636,7 +628,7 @@ def _part_function(p: PartPlan) -> str:
" objs = []",
f" for i, c in enumerate({centers}): # TODO: exact placement",
" # TODO: replace this placeholder box with the real geometry (keep the names + bbox)",
- f" objs.append(add_box(f\"{pascal}_{{i}}\", c, {pre}_EXTENTS, mat, bevel={_bevel(p.bbox):.4f}))",
+ f" objs.append(add_box(f\"{pascal}_{{i}}\", c, {pre}_EXTENTS, mat))",
" return objs",
]
return "\n".join(lines) + "\n"
@@ -652,8 +644,8 @@ def _plan_header(plan: StaticPlan) -> str:
accept = "\n".join(f" - [{a.id}] {a.text}" for a in plan.acceptance) or " (none listed)"
layout = (
f" * LAYOUT: this file is the ENTRY. Each part lives in src/{PARTS_DIR}/<snake>.py and exports\n"
- f" build_<snake>() -> bpy.types.Object; main() below imports and calls them in order.\n"
- " Edit geometry in the part files; keep this file to imports + calls + self-check.\n"
+ f" build_<snake>() -> bpy.types.Object; main() below imports and calls each once.\n"
+ " The lint checks that every part file is imported here; the rest of this file is yours.\n"
)
return f'''"""{plan.object_name} — Blender (bpy) model.
@@ -668,9 +660,12 @@ CONTRACT (the harness runs this file in an EMPTY scene with `blender -b --factor
each TOP-LEVEL (never parented under an Empty — that merges them into ONE measured part).
{layout} * Materials: Principled BSDF (Base Color / Roughness / Metallic). GLB keeps flat PBR + image
textures only (procedural node textures are NOT exported) — rely on geometry + flat PBR.
+ * Each part's built AABB matches its row within max(1 cm, 10 %) per axis (3x that is an ERROR);
+ touching parts: surface gap <= 2 mm, overlap <= 2 mm; every part reaches the ground through
+ its neighbours (check_contract, check_connectivity).
* Modifiers may stay unapplied (the exporter applies them).
* NEVER: cameras, lights, world, render settings, export/import, file IO, bpy.ops.wm.*.
- * Only bpy / bmesh / mathutils / math / random (seeded). No other imports.
+ * Imports: the contract's allow-list (bpy, bmesh, mathutils, math, random, numpy, ...); seed random.
PARTS:
{parts_doc}
@@ -690,11 +685,11 @@ def part_file_source(p: PartPlan) -> str:
f"{p.description}\n"
f"Material: {p.material or 'n/a'}. Instances: {p.instances}"
+ (f" ({p.symmetry})" if p.instances > 1 else "")
- + (f". Attaches to: {to_pascal(p.attach_to)} (must touch, no gap)" if p.attach_to else "")
+ + (f". Attaches to: {to_pascal(p.attach_to)} (gap <= 2 mm, overlap <= 2 mm)" if p.attach_to else "")
+ f".\n\nExports `{fn}() -> bpy.types.Object`: builds the part at its WORLD pose (Z up, -Y front,\n"
"metres) with the exact object name(s) and returns it (list of TOP-LEVEL objects when\n"
"instanced — never parent instances under an Empty). Do NOT call it here — model.py does.\n"
- "Keep this file self-contained (its own helpers); only bpy/bmesh/mathutils/math/random.\n"
+ "Shared helpers may live in src/parts/_<name>.py (not a part); imports per the contract's allow-list.\n"
'"""\n'
)
return doc + IMPORTS + "\n" + _constants(p) + HELPERS + "\n# ----------------------------------------------------------------------------- part\n" + _part_function(p)
diff --git a/harness/codeverse3d/languages/cadquery/__init__.py b/harness/codeverse3d/languages/cadquery/__init__.py
index 495a4ff0..d7b0f91a 100644
--- a/harness/codeverse3d/languages/cadquery/__init__.py
+++ b/harness/codeverse3d/languages/cadquery/__init__.py
@@ -168,9 +168,6 @@ def _rules(c: BpyCollector, tree: ast.Module, source: str) -> list[GateFinding]:
if name.endswith(".rotate") and len(call.args) == 3 and looks_like_radians(call.args[2]):
out.append(_f(E, ".rotate(...) takes DEGREES; this argument looks like radians (math.pi expression)", call.lineno,
"pass degrees: `.rotate((0,0,0), (0,0,1), 90)` or `math.degrees(angle_rad)`"))
- if name.endswith(".fillet") or name.endswith(".chamfer"):
- out.append(_f(I, f"{last}: OCC fails ('BRep_API: command not done') when radius >= wall thickness or edges conflict", call.lineno,
- "keep radius < 0.45 x min thickness; select few edges (`.edges('|Z')`); wrap cosmetic fillets in try/except"))
if c.add_calls:
unnamed = [a.lineno for a in c.add_calls if not any(k.arg == "name" for k in a.keywords)]
if unnamed:
@@ -225,11 +222,12 @@ def _part_function(p: PartPlan) -> str:
f" x in [{mn[0]:.3f}, {mx[0]:.3f}] y in [{mn[1]:.3f}, {mx[1]:.3f}] z in [{mn[2]:.3f}, {mx[2]:.3f}]",
]
if p.attach_to:
- lines.append(f" Attaches to: {to_pascal(p.attach_to)} (faces must touch; small overlaps are fine)")
+ lines.append(f" Attaches to: {to_pascal(p.attach_to)} — surface gap <= 2 mm, overlap <= 2 mm (check_connectivity)")
if p.instances > 1:
- lines.append(f" Instances: {p.instances} ({p.symmetry}); build ONE centred at the origin, main() places each copy.")
+ lines.append(f" Instances: {p.instances} ({p.symmetry}) — exported as {pascal}_0..{pascal}_{p.instances - 1}; the placeholder builds")
+ lines.append(" one at the origin and places each copy with `loc` below (authoring each in world coordinates is fine too).")
lines.append(' """')
- lines.append(" # TODO: replace the placeholder box (keep it centred on the origin; placement happens in main())")
+ lines.append(" # TODO: replace the placeholder box (keep the name + bbox)")
lines.append(f" return cq.Workplane(\"XY\").box({ex:.3f}, {ey:.3f}, {ez:.3f})")
else:
lines.append(' """')
@@ -270,14 +268,16 @@ def cadquery_skeleton_source(plan: StaticPlan) -> str:
Style: {plan.style_notes or "n/a"}
CONTRACT (the harness imports this file and exports `result` to GLB/STEP/STL itself):
- * Z is up, -Y is the FRONT, units are METERS. Object stands on z=0, footprint centred on Z.
+ * Z is up, -Y is the FRONT, units are METERS. Lowest point at z=0, footprint centred on Z (check_contract).
* Overall bbox: center ({fmt3(ob.center)}) extents ({fmt3(ob.extents)})
-> x in [{ob.min[0]:.3f}, {ob.max[0]:.3f}] y in [{ob.min[1]:.3f}, {ob.max[1]:.3f}] z in [{ob.min[2]:.3f}, {ob.max[2]:.3f}]
* `result` = cq.Assembly; one `.add(shape, name="PascalName", color=cq.Color(r, g, b))` per part,
instances Name_0..Name_N-1 (a shape built at the origin + `loc=cq.Location(cq.Vector(x, y, z))`).
- * Only `import cadquery as cq` (+ math / random). No file IO, no export, no show_object.
+ * Imports: cadquery, math, random, numpy and the stdlib data helpers (the lint's list). No file IO,
+ no export, no show_object.
* `.box(x, y, z)` is centred; `.cylinder(height, radius)`; `.rotate(p1, p2, DEGREES)`;
- `.translate()/.rotate()` return NEW objects (reassign). Keep fillet radius < 0.45 x wall thickness.
+ `.translate()/.rotate()` return NEW objects (reassign). OCC refuses a fillet whose radius reaches
+ the adjacent wall (the build's hint says < 0.45 x).
PARTS:
{parts_doc}
diff --git a/harness/codeverse3d/languages/glsl_shader/__init__.py b/harness/codeverse3d/languages/glsl_shader/__init__.py
index 65f377ac..3f27a6e8 100644
--- a/harness/codeverse3d/languages/glsl_shader/__init__.py
+++ b/harness/codeverse3d/languages/glsl_shader/__init__.py
@@ -3,7 +3,6 @@
from __future__ import annotations
import re
-from collections.abc import Collection
from dataclasses import dataclass
from pathlib import Path
@@ -113,15 +112,15 @@ def _piece(text: str) -> str:
return text if text.endswith("\n") else text + "\n"
-def compose(shader_src: str, common_src: str | None = None, *, recipes_src: str | None = None,
+def compose(shader_src: str, common_src: str | None = None, *,
shader_file: str = "src/shader.frag", common_file: str = "src/common.glsl",
- recipes_file: str = "src/recipes.glsl") -> Composed:
- """Header + recipes (harness-owned, first: self-contained, nothing in common.glsl can shadow it)
- + common + shader (+ trailer) with a line map back to the agent files."""
+ legacy_src: str | None = None) -> Composed:
+ """Header (+ a pre-D107 run's :data:`LEGACY_RECIPES`) + common + shader (+ trailer) with a line
+ map back to the agent files."""
convention = detect_convention(shader_src)
pieces: list[tuple[str, str]] = [("harness", HEADER)]
- if recipes_src and recipes_src.strip():
- pieces.append((recipes_file, _piece(recipes_src)))
+ if legacy_src and legacy_src.strip():
+ pieces.append((LEGACY_RECIPES, _piece(legacy_src)))
if common_src and common_src.strip():
pieces.append((common_file, _piece(common_src)))
pieces.append((shader_file, _piece(shader_src)))
@@ -136,7 +135,7 @@ def compose(shader_src: str, common_src: str | None = None, *, recipes_src: str
cursor += n
out.append(text)
src = "".join(out)
- code = strip_comments(shader_src) + "\n" + strip_comments(common_src or "") + "\n" + strip_comments(recipes_src or "")
+ code = strip_comments(shader_src) + "\n" + strip_comments(common_src or "")
uses_feedback = "u_prev" in code or "iChannel0" in code
return Composed(source=src, line_map=LineMap(segments), convention=convention, uses_feedback=uses_feedback)
@@ -156,10 +155,10 @@ GATE = "lint:glsl_shader"
SHADER = ENTRY_FILE[Language.GLSL_SHADER]
COMMON = "src/common.glsl"
BUFFER_A = "src/buffer_a.frag"
-#: harness-owned (``contracts.common.HARNESS_OWNED_SRC``): seeded cookbook recipes, pasted above common.glsl
-RECIPES = "src/recipes.glsl"
-#: a top-level GLSL function definition, ``group(1)`` = its name (match per line)
-FUNC_DEF = re.compile(r"^[ \t]*(?:float|int|bool|void|[bi]?vec[234]|mat[234])\s+(\w+)\s*\(")
+#: runs made BEFORE D107 had the harness seed this file and their shaders call its functions, so
+#: it is still composed (after the header, before common.glsl) when it exists — the only reason
+#: `resume` / `render` / `pick` on such a run still builds. No new run is given one.
+LEGACY_RECIPES = "src/recipes.glsl"
SAMPLERS = {"u_prev", "u_noise", "u_buffer_a", "iChannel0", "iChannel1"}
MAX_CHARS = 60_000
@@ -177,16 +176,9 @@ _LEGACY = {
}
_FLOAT_LITERAL_MOD = re.compile(r"(\d\.\d*|\.\d+)\s*%|%\s*(\d\.\d*|\.\d+)")
_PRECISION = re.compile(r"^[ \t]*precision\s+(lowp|mediump|highp)\s+\w+\s*;", re.M)
-def defined_functions(text: str) -> dict[str, int]:
- """``{name: line}`` of every top-level function definition in a GLSL text (comments blanked)."""
- out: dict[str, int] = {}
- for i, line in enumerate(strip_comments(text).splitlines(), 1):
- if (m := FUNC_DEF.match(line)) and m.group(1) not in out:
- out[m.group(1)] = i
- return out
-def _check_file(rel: str, text: str, *, role: str, recipe_names: Collection[str] = ()) -> list[GateFinding]:
+def _check_file(rel: str, text: str, *, role: str) -> list[GateFinding]:
out: list[GateFinding] = []
raw_len = len(text)
text = strip_comments(text)
@@ -220,7 +212,7 @@ def _check_file(rel: str, text: str, *, role: str, recipe_names: Collection[str]
if name not in SAMPLERS:
add(Severity.ERROR, "undeclared_sampler", f"texture() reads sampler `{name}` which does not exist",
"only u_prev (previous frame), u_noise (256² RGBA noise) and u_buffer_a (buffer pass) can be sampled; "
- "generate patterns procedurally (hash/noise/fbm from the cookbook)", line_of(text, m.start()))
+ "generate patterns procedurally (hash / noise / the u_noise texture)", line_of(text, m.start()))
for m in _MISSING_INPUTS.finditer(text):
add(Severity.ERROR, "missing_input", f"`{m.group(1)}` is not available in this harness",
"available: u_time/iTime, u_resolution/iResolution, u_frame/iFrame, u_mouse (always 0), u_prev/iChannel0, u_noise/iChannel1",
@@ -231,10 +223,6 @@ def _check_file(rel: str, text: str, *, role: str, recipe_names: Collection[str]
add(Severity.ERROR, "legacy_glsl", f"uses `{needle.strip()}` (GLSL 1.x)", hint, line_of(text, pos))
for m in _FLOAT_LITERAL_MOD.finditer(text):
add(Severity.ERROR, "float_modulo", "`%` on a float literal — GLSL `%` is integer-only", "use mod(x, y)", line_of(text, m.start()))
- for name, line in defined_functions(text).items():
- if name in recipe_names:
- add(Severity.ERROR, "redefines_recipe", f"`{name}` is already provided by {RECIPES} — call it instead of redefining it",
- f"delete this `{name}` definition; {RECIPES} is harness-owned and pasted above your code, so its `{name}` is in scope", line)
if role in ("shader", "buffer_a"):
if not _MAIN_IMAGE.search(text) and not _PLAIN_MAIN.search(text):
add(Severity.ERROR, "no_entry", "neither `void mainImage(out vec4 fragColor, in vec2 fragCoord)` nor `void main()` found",
@@ -254,91 +242,55 @@ def _check_file(rel: str, text: str, *, role: str, recipe_names: Collection[str]
return out
-def recipe_names(ws: Workspace) -> frozenset[str]:
- """The names the harness-owned ``src/recipes.glsl`` provides (empty when nothing was seeded)."""
- p = ws.root / RECIPES
- return frozenset(defined_functions(p.read_text(errors="replace"))) if p.is_file() else frozenset()
-
-
def lint_workspace(ws: Workspace) -> GateReport:
findings: list[GateFinding] = []
- reserved = recipe_names(ws)
shader = ws.root / SHADER
if not shader.is_file():
findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target=SHADER, message=f"{SHADER} is missing",
fix_hint="create src/shader.frag with a mainImage(out vec4 fragColor, in vec2 fragCoord) function",
data={"kind": "missing_entry", "file": SHADER}))
else:
- findings.extend(_check_file(SHADER, shader.read_text(errors="replace"), role="shader", recipe_names=reserved))
+ findings.extend(_check_file(SHADER, shader.read_text(errors="replace"), role="shader"))
for rel, role in ((COMMON, "common"), (BUFFER_A, "buffer_a")):
p = ws.root / rel
if p.is_file():
- findings.extend(_check_file(rel, p.read_text(errors="replace"), role=role, recipe_names=reserved))
+ findings.extend(_check_file(rel, p.read_text(errors="replace"), role=role))
stray = [ws_rel(ws, p) for p in ws.src.rglob("*") if p.is_file()
- and ws_rel(ws, p) not in (SHADER, COMMON, BUFFER_A, RECIPES) and p.suffix in (".frag", ".glsl", ".vert", ".py", ".js")]
+ and ws_rel(ws, p) not in (SHADER, COMMON, BUFFER_A, LEGACY_RECIPES)
+ and p.suffix in (".frag", ".glsl", ".vert", ".py", ".js")]
for rel in stray:
findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=rel, message=f"{rel} is not part of the shader contract and is ignored",
fix_hint="keep code in src/shader.frag (+ src/common.glsl, src/buffer_a.frag)", data={"kind": "stray_file", "file": rel}))
return GateReport.of(GATE, findings)
-def lint_text(shader_src: str, common_src: str | None = None, buffer_a_src: str | None = None, *,
- recipes_src: str | None = None) -> list[GateFinding]:
- """Lint in-memory sources (tests; the c3d-glsl-craft skill cites it); ``recipes_src`` is the harness-owned recipe file whose
- names the agent files may not redefine (it is not linted itself)."""
- reserved = frozenset(defined_functions(recipes_src)) if recipes_src else frozenset()
- out = _check_file(SHADER, shader_src, role="shader", recipe_names=reserved)
+def lint_text(shader_src: str, common_src: str | None = None, buffer_a_src: str | None = None) -> list[GateFinding]:
+ """Lint in-memory sources (tests; the c3d-glsl-craft skill cites it)."""
+ out = _check_file(SHADER, shader_src, role="shader")
if common_src is not None:
- out += _check_file(COMMON, common_src, role="common", recipe_names=reserved)
+ out += _check_file(COMMON, common_src, role="common")
if buffer_a_src is not None:
- out += _check_file(BUFFER_A, buffer_a_src, role="buffer_a", recipe_names=reserved)
+ out += _check_file(BUFFER_A, buffer_a_src, role="buffer_a")
return out
# ===================================================================== skeleton
-COMMON_GLSL = """// src/common.glsl — helpers pasted above shader.frag by the harness (no #include needed).
-// Keep ONLY functions / constants here; no main(), no uniforms, no #version.
+COMMON_GLSL = """// src/common.glsl — pasted above shader.frag (and buffer_a.frag) by the harness; no #include.
+// Functions and constants only: no main(), no uniforms, no #version. What goes here is yours.
#define PI 3.14159265359
#define TAU 6.28318530718
-
-float hash11(float p) { p = fract(p * 0.1031); p *= p + 33.33; p *= p + p; return fract(p); }
-float hash12(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
-vec2 hash22(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); }
-
-// value noise 2D (smooth, 0..1)
-float noise(vec2 p) {
- vec2 i = floor(p), f = fract(p);
- vec2 u = f * f * (3.0 - 2.0 * f);
- return mix(mix(hash12(i), hash12(i + vec2(1, 0)), u.x),
- mix(hash12(i + vec2(0, 1)), hash12(i + vec2(1, 1)), u.x), u.y);
-}
-
-// fractal brownian motion, 5 octaves (constant loop bound)
-float fbm(vec2 p) {
- float v = 0.0, a = 0.5;
- mat2 rot = mat2(0.8, 0.6, -0.6, 0.8);
- for (int i = 0; i < 5; i++) { v += a * noise(p); p = rot * p * 2.02; a *= 0.5; }
- return v;
-}
-
-mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); }
-
-// cosine palette (IQ): t in 0..1
-vec3 palette(float t, vec3 a, vec3 b, vec3 c, vec3 d) { return a + b * cos(TAU * (c * t + d)); }
-
-// filmic-ish tonemap + gamma
-vec3 tonemap(vec3 c) { c = c / (1.0 + c); return pow(clamp(c, 0.0, 1.0), vec3(1.0 / 2.2)); }
"""
_SHADER_TEMPLATE = """// src/shader.frag — {title}
-// CONTRACT (the harness prepends `#version 330 core` + these uniforms + `out vec4 fragColor`; DO NOT redeclare them):
-// uniform float u_time; uniform vec2 u_resolution; uniform vec2 u_mouse; uniform int u_frame;
-// uniform sampler2D u_prev; (previous frame of this pass) uniform sampler2D u_noise; (256x256 RGBA noise, repeat)
-// uniform sampler2D u_buffer_a; (output of src/buffer_a.frag when that file exists)
-// iTime / iResolution / iFrame / iMouse / iChannel0(=u_prev) / iChannel1(=u_noise) are #defined for Shadertoy ports.
+// CONTRACT: the harness prepends `#version 330 core`, the uniforms (u_time u_resolution u_mouse u_frame
+// u_prev u_noise u_buffer_a; iTime / iResolution / iFrame / iMouse / iChannel0 / iChannel1 for Shadertoy ports)
+// and `out vec4 fragColor` — do not redeclare them.
// Entry: void mainImage(out vec4 fragColor, in vec2 fragCoord) — fragCoord in pixels, origin BOTTOM-LEFT.
-// Helpers available from src/common.glsl: hash11 hash12 hash22 noise fbm rot2 palette tonemap PI TAU.
-// Duration {duration:g}s; judged frames at t = 0, 1, 2.5, 4, 6 s. Everything must MOVE with u_time.
+// src/common.glsl is pasted above this file (it starts with PI and TAU only); what goes in it is yours.
+// MEASURED on the frames at t = 0, 1, 2.5, 4, 6 s (loop {duration:g} s): no NaN / Inf pixel (score cap 0);
+// no frame essentially black or blown out (cap 0.5); when motion is planned, consecutive frames must differ
+// (mean |delta| >= 0.002, else `static`, cap 0.5) and never jump (> 0.35 is `flicker`, cap 0.7); any lint
+// ERROR caps the score at 0.6. What the frames show is the plan's business, not this file's.
//
// PLAN — {summary}
// Style: {style}
@@ -347,18 +299,10 @@ _SHADER_TEMPLATE = """// src/shader.frag — {title}
// Motion: {motion}
void mainImage(out vec4 fragColor, in vec2 fragCoord) {{
- vec2 uv = fragCoord / u_resolution.xy; // 0..1
- vec2 p = (fragCoord - 0.5 * u_resolution.xy) / u_resolution.y; // aspect-correct, centred
- float t = u_time;
-
- // TODO replace this placeholder look with the plan's passes above
- vec3 sky = mix(vec3(0.95, 0.55, 0.25), vec3(0.10, 0.20, 0.45), smoothstep(-0.2, 0.6, p.y));
- vec2 sunPos = vec2(0.35 * cos(t * 0.3), 0.15 + 0.1 * sin(t * 0.3));
- float sun = exp(-40.0 * length(p - sunPos));
- float haze = fbm(p * 3.0 + vec2(t * 0.15, 0.0));
- vec3 col = sky + vec3(1.0, 0.8, 0.5) * sun + 0.25 * haze * vec3(0.9, 0.7, 0.6);
- col *= 1.0 - 0.35 * length(p); // vignette
- fragColor = vec4(tonemap(col), 1.0);
+ vec2 uv = fragCoord / u_resolution.xy; // 0..1: the coordinate u_prev / u_buffer_a are sampled at
+ vec2 p = (fragCoord - 0.5 * u_resolution.xy) / u_resolution.y; // centred, aspect-correct, y up
+ // PLACEHOLDER — a flat grey the static gate rejects: replace this write with the plan's passes
+ fragColor = vec4(vec3(0.5), 1.0);
}}
"""
@@ -417,11 +361,11 @@ class GlslShaderRuntime(RuntimeLayout):
shader = (ws.root / SHADER).read_text(errors="replace")
common_p = ws.root / COMMON
common = common_p.read_text(errors="replace") if common_p.is_file() else None
- recipes_p = ws.root / RECIPES
- recipes = recipes_p.read_text(errors="replace") if recipes_p.is_file() else None
- image = compose(shader, common, recipes_src=recipes)
+ legacy_p = ws.root / LEGACY_RECIPES
+ legacy = legacy_p.read_text(errors="replace") if legacy_p.is_file() else None
+ image = compose(shader, common, legacy_src=legacy)
buf_p = ws.root / BUFFER_A
- buffer_a = (compose(buf_p.read_text(errors="replace"), common, recipes_src=recipes, shader_file=BUFFER_A)
+ buffer_a = (compose(buf_p.read_text(errors="replace"), common, shader_file=BUFFER_A, legacy_src=legacy)
if buf_p.is_file() else None)
return image, buffer_a
@@ -444,7 +388,7 @@ class GlslShaderRuntime(RuntimeLayout):
extra_times=gif_times(duration or 8.0) if preview else (),
)
census = {"convention": image.convention, "has_common": (ws.root / COMMON).is_file(), "has_buffer_a": buffer_a is not None,
- "has_recipes": (ws.root / RECIPES).is_file(), "resolution": [w, h]}
+ "resolution": [w, h]}
err_file, err_line, err_msg = "", None, None
if not res.ok and res.stage in ("compile", "compile_buffer_a"):
comp = buffer_a if res.stage == "compile_buffer_a" and buffer_a else image
diff --git a/harness/codeverse3d/languages/opengl_python/__init__.py b/harness/codeverse3d/languages/opengl_python/__init__.py
index b548ba06..e2b124db 100644
--- a/harness/codeverse3d/languages/opengl_python/__init__.py
+++ b/harness/codeverse3d/languages/opengl_python/__init__.py
@@ -74,8 +74,7 @@ class _Visitor(ast.NodeVisitor):
def _import_finding(kind: str, _mod: str, ln: int) -> GateFinding:
if kind == "forbidden":
return _finding(Severity.ERROR, "forbidden_import", f"imports `{name}` (not allowed in a rendering program)",
- "allowed: moderngl, numpy, math, random, struct, array, pathlib, typing, dataclasses, itertools, "
- "functools, collections, colorsys", ln)
+ "allowed: " + ", ".join(sorted(ALLOWED_MODULES)), ln)
return _finding(Severity.ERROR, "forbidden_import", f"imports `{name}` which is outside the allow-list",
"use only moderngl + numpy + stdlib math/random/struct/array/pathlib", ln)
@@ -113,6 +112,8 @@ class _Visitor(ast.NodeVisitor):
self.uses_random = True
if base in ("np", "numpy") and attr == "seed":
self.seeded = True
+ if attr == "default_rng": # np.random.default_rng(seed) — the seeding the contract recommends
+ self.seeded = True
if attr in ("write_text", "write_bytes", "unlink", "mkdir", "rmdir", "rename"):
self.findings.append(_finding(Severity.ERROR, "file_write", f"calls `.{attr}()` (file system write)", "programs never write files", node.lineno))
if attr == "read_text" or attr == "read_bytes":
@@ -159,7 +160,7 @@ def lint_source(text: str) -> list[GateFinding]:
findings.append(_finding(Severity.ERROR, "bad_signature", f"`{fn}` takes {len(node.args.args)} positional args, expected {nargs}",
"setup(ctx, width, height) / render(ctx, state, t, frame, fbo)", node.lineno))
if v.uses_random and not v.seeded:
- findings.append(_finding(Severity.WARN, "unseeded_random", "uses random.* without random.seed(...)",
+ findings.append(_finding(Severity.WARN, "unseeded_random", "uses random.* without random.seed(...) or a default_rng(...)",
"call random.seed(0) / np.random.default_rng(0) in setup() so frames are reproducible"))
return findings
@@ -174,7 +175,7 @@ def lint_workspace(ws: Workspace) -> GateReport:
for extra in sorted(ws.src.rglob("*.py")):
rel = ws_rel(ws, extra)
if rel != PROGRAM:
- findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=rel, message=f"{rel}: extra python module is ignored by the harness",
+ findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=rel, message=f"{rel}: extra python module is not part of the deliverable (only src/program.py and src/*.glsl are)",
fix_hint="keep all code in src/program.py (GLSL may live in src/*.glsl)", data={"kind": "stray_file", "file": rel}))
return GateReport.of(GATE, findings)
@@ -182,14 +183,17 @@ def lint_workspace(ws: Workspace) -> GateReport:
# ===================================================================== skeleton
_TEMPLATE = '''"""src/program.py — {title}
-CONTRACT (the harness imports this module in a headless moderngl process):
+CONTRACT (the harness imports this module in a headless moderngl process; the full text is the
+language contract):
def setup(ctx, width, height) -> state create programs / VAOs / textures / FBOs ONCE; return any object
def render(ctx, state, t, frame, fbo) draw the frame at time t (seconds) into `fbo` (already bound + cleared)
* `ctx` is a moderngl.Context (GL 3.3 core). Never create a context or window; never read the clock.
-* Multi-pass: render into your own FBOs, then call `fbo.use()` and draw the final image into it.
-* Deterministic: same t → same frame. Seed randomness. GLSL strings use `#version 330 core`.
-* Allowed imports: moderngl, numpy, math, random, struct, array, pathlib (+typing/dataclasses).
-Duration {duration:g}s; judged frames at t = 0, 1, 2.5, 4, 6 s — everything must MOVE with t.
+* The final draw of every call goes into `fbo` (bind it and reset ctx.viewport first if you used your own FBOs).
+* Same t → same frame, whatever was rendered before; `frame` is a schedule index, not time. Seed randomness
+ in setup. GLSL strings start with `#version 330 core`.
+Judged frames at t = 0, 1, 2.5, 4, 6 s (clipped to the {duration:g} s duration). Measured on them: largest
+frame-to-frame mean |Δ| below 0.002 → static (cap 0.5); above 0.35 → flicker (cap 0.7); NaN/Inf → cap 0;
+every frame black or blown → cap 0.5; mean edge density below 0.002 → reported as a near-flat gradient.
PLAN — {summary}
Style: {style}
@@ -197,115 +201,38 @@ Style: {style}
{visuals}
Motion: {motion}
"""
-import math
-
import moderngl
import numpy as np
-BACKGROUND_VERT = """#version 330 core
+# This stub only proves the interface: one full-screen pass whose output depends on t.
+STUB_VERT = """#version 330 core
in vec2 in_pos;
out vec2 v_uv;
void main() {{ v_uv = in_pos * 0.5 + 0.5; gl_Position = vec4(in_pos, 0.0, 1.0); }}
"""
-BACKGROUND_FRAG = """#version 330 core
+STUB_FRAG = """#version 330 core
uniform float u_time;
in vec2 v_uv;
out vec4 fragColor;
-void main() {{
- vec3 top = vec3(0.08, 0.10, 0.25), bottom = vec3(0.85, 0.45, 0.30);
- vec3 col = mix(bottom, top, smoothstep(0.0, 1.0, v_uv.y + 0.1 * sin(u_time * 0.5 + v_uv.x * 6.0)));
- fragColor = vec4(col, 1.0);
-}}
+void main() {{ fragColor = vec4(vec3(0.5 + 0.5 * sin(6.2832 * (v_uv.x - 0.05 * u_time))), 1.0); }}
"""
-CUBE_VERT = """#version 330 core
-uniform mat4 u_mvp;
-uniform mat4 u_model;
-in vec3 in_pos;
-in vec3 in_normal;
-out vec3 v_normal;
-void main() {{ v_normal = mat3(u_model) * in_normal; gl_Position = u_mvp * vec4(in_pos, 1.0); }}
-"""
-CUBE_FRAG = """#version 330 core
-uniform vec3 u_color;
-in vec3 v_normal;
-out vec4 fragColor;
-void main() {{
- vec3 n = normalize(v_normal);
- float diff = max(dot(n, normalize(vec3(0.4, 0.8, 0.5))), 0.0);
- fragColor = vec4(u_color * (0.25 + 0.75 * diff), 1.0);
-}}
-"""
-
-
-def _cube() -> np.ndarray:
- """36 vertices: position (3) + normal (3), interleaved float32."""
- faces = [((0, 0, 1), (-1, -1, 1), (1, -1, 1), (1, 1, 1), (-1, 1, 1)),
- ((0, 0, -1), (1, -1, -1), (-1, -1, -1), (-1, 1, -1), (1, 1, -1)),
- ((1, 0, 0), (1, -1, 1), (1, -1, -1), (1, 1, -1), (1, 1, 1)),
- ((-1, 0, 0), (-1, -1, -1), (-1, -1, 1), (-1, 1, 1), (-1, 1, -1)),
- ((0, 1, 0), (-1, 1, 1), (1, 1, 1), (1, 1, -1), (-1, 1, -1)),
- ((0, -1, 0), (-1, -1, -1), (1, -1, -1), (1, -1, 1), (-1, -1, 1))]
- out = []
- for n, a, b, c, d in faces:
- for v in (a, b, c, a, c, d):
- out.extend(v)
- out.extend(n)
- return np.array(out, dtype="f4") * np.tile([0.5, 0.5, 0.5, 1, 1, 1], 36).astype("f4")
-
-
-def _perspective(fov_deg: float, aspect: float, near: float, far: float) -> np.ndarray:
- f = 1.0 / math.tan(math.radians(fov_deg) / 2.0)
- m = np.zeros((4, 4), dtype="f4")
- m[0, 0], m[1, 1] = f / aspect, f
- m[2, 2], m[2, 3] = (far + near) / (near - far), (2 * far * near) / (near - far)
- m[3, 2] = -1.0
- return m
-
-
-def _look_at(eye, target, up=(0, 1, 0)) -> np.ndarray:
- eye, target, up = np.array(eye, dtype="f4"), np.array(target, dtype="f4"), np.array(up, dtype="f4")
- f = target - eye
- f /= np.linalg.norm(f)
- s = np.cross(f, up)
- s /= np.linalg.norm(s)
- u = np.cross(s, f)
- m = np.identity(4, dtype="f4")
- m[0, :3], m[1, :3], m[2, :3] = s, u, -f
- m[:3, 3] = -m[:3, :3] @ eye
- return m
-
-
-def _rot_y(a: float) -> np.ndarray:
- c, s = math.cos(a), math.sin(a)
- return np.array([[c, 0, s, 0], [0, 1, 0, 0], [-s, 0, c, 0], [0, 0, 0, 1]], dtype="f4")
def setup(ctx: moderngl.Context, width: int, height: int):
- bg_prog = ctx.program(vertex_shader=BACKGROUND_VERT, fragment_shader=BACKGROUND_FRAG)
+ prog = ctx.program(vertex_shader=STUB_VERT, fragment_shader=STUB_FRAG)
quad = ctx.buffer(np.array([-1, -1, 1, -1, -1, 1, 1, 1], dtype="f4").tobytes())
- bg_vao = ctx.vertex_array(bg_prog, [(quad, "2f", "in_pos")])
- cube_prog = ctx.program(vertex_shader=CUBE_VERT, fragment_shader=CUBE_FRAG)
- vbo = ctx.buffer(_cube().tobytes())
- cube_vao = ctx.vertex_array(cube_prog, [(vbo, "3f 3f", "in_pos", "in_normal")])
- proj = _perspective(45.0, width / height, 0.1, 100.0)
- view = _look_at((0.0, 1.2, 3.0), (0.0, 0.0, 0.0))
- # TODO build the plan's passes here (instancing, extra FBOs for post-processing, textures)
- return {{"bg_prog": bg_prog, "bg_vao": bg_vao, "cube_prog": cube_prog, "cube_vao": cube_vao, "proj": proj, "view": view}}
+ vao = ctx.vertex_array(prog, [(quad, "2f", "in_pos")])
+ # TODO build the plan's passes here (programs, buffers, textures, your own FBOs)
+ return {{"prog": prog, "vao": vao, "size": (width, height)}}
def render(ctx: moderngl.Context, state, t: float, frame: int, fbo: moderngl.Framebuffer) -> None:
fbo.use()
ctx.disable(moderngl.DEPTH_TEST)
- state["bg_prog"]["u_time"].value = t
- state["bg_vao"].render(mode=moderngl.TRIANGLE_STRIP)
- ctx.enable(moderngl.DEPTH_TEST)
- model = _rot_y(t * 0.8)
- mvp = state["proj"] @ state["view"] @ model
- state["cube_prog"]["u_mvp"].write(mvp.T.astype("f4").tobytes()) # column-major for GLSL
- state["cube_prog"]["u_model"].write(model.T.astype("f4").tobytes())
- state["cube_prog"]["u_color"].value = (0.9, 0.6, 0.2)
- state["cube_vao"].render(mode=moderngl.TRIANGLES)
- # TODO replace the placeholder cube with the plan's content; keep drawing into `fbo` last
+ ctx.viewport = (0, 0, *state["size"])
+ state["prog"]["u_time"].value = t
+ state["vao"].render(mode=moderngl.TRIANGLE_STRIP)
+ # TODO the plan's passes; the final draw goes into `fbo` (bind it and reset ctx.viewport first)
'''
diff --git a/harness/codeverse3d/languages/threejs/__init__.py b/harness/codeverse3d/languages/threejs/__init__.py
index 1ddba696..dc3a7a3c 100644
--- a/harness/codeverse3d/languages/threejs/__init__.py
+++ b/harness/codeverse3d/languages/threejs/__init__.py
@@ -42,8 +42,8 @@ OBJECT_HEADER = """\
// Y up, +Z front, meters; object stands on y=0, footprint centred on the Y axis.
// Parts live in ./parts/<snake>.js, each `export function build<Pascal>(THREE)`
// returning a Group already at its WORLD pose. object.js only assembles.
-// Optional idle animation: root.userData.tick = (t, dt) => {{ ... }}
-// Allowed imports: 'three', 'three/addons/...', relative './'. No network, no DOM.
+// root.userData.tick is recorded by the census but never called or exported on this track.
+// Imports that resolve: 'three', 'three/addons/...', relative './' under src/. No network, no DOM.
import * as THREE from 'three';
{imports}
@@ -60,31 +60,22 @@ PART_TEMPLATE = """\
// {description}
// Plan bbox (world, meters): centre {center} extents {extents}{material_line}
// Contract: export function build{pascal}(THREE) -> THREE.Group named '{pascal}', at WORLD pose.
-// Y up, +Z front. Use real sizes in meters. Name every mesh. No lights/cameras/renderers.
+// Y up, +Z front, metres. The Group's name '{pascal}' is how the gates find this part; a mesh
+// with no name is a build warning. Lights / cameras / renderers are lint findings.
+// Measured on this part: bbox centre + extents within max(10 mm, 10 % of the plan extent) per
+// axis; one connected shell (tiny islands are stray geometry); contact (surface gap <= 2 mm) with
+// its planned neighbours; penetration <= 2 mm; the whole object's lowest point within 10 mm of y = 0.
import * as THREE from 'three';
-import {{ RoundedBoxGeometry }} from 'three/addons/geometries/RoundedBoxGeometry.js';
export function build{pascal}(THREE_) {{
const group = new THREE.Group();
group.name = '{pascal}';
- // ---- PLACEHOLDER (replace with real construction; keep the group name) ----
- // A rounded box filling the planned bbox. Copyable recipes:
- // box: new THREE.BoxGeometry(w, h, d)
- // bevelled: new RoundedBoxGeometry(w, h, d, 4, Math.min(w, h, d) * 0.08)
- // cylinder: new THREE.CylinderGeometry(rTop, rBottom, h, 32)
- // lathe: new THREE.LatheGeometry(points /* Vector2[] (x=radius, y=height) */, 48)
- // extrude w/ bevel:
- // const shape = new THREE.Shape(); shape.moveTo(-w/2, -d/2); shape.lineTo(w/2, -d/2);
- // shape.lineTo(w/2, d/2); shape.lineTo(-w/2, d/2); shape.closePath();
- // const geo = new THREE.ExtrudeGeometry(shape, {{ depth: h, bevelEnabled: true,
- // bevelThickness: 0.004, bevelSize: 0.004, bevelSegments: 3 }});
- // geo.rotateX(-Math.PI / 2); // extrude along +Y instead of +Z
- // merge many: import {{ mergeGeometries }} from 'three/addons/utils/BufferGeometryUtils.js';
+ // ---- PLACEHOLDER: a plain box at the plan bbox so the first build passes. Replace it with the
+ // part the brief describes (keep the group name); what it is made of is yours to decide. ----
const size = [{ex}, {ey}, {ez}];
- const geometry = new RoundedBoxGeometry(size[0], size[1], size[2], 3, Math.min(...size) * 0.08);
- const material = new THREE.MeshStandardMaterial({{ color: {color}, roughness: 0.6, metalness: 0.05 }});
- const mesh = new THREE.Mesh(geometry, material);
+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(size[0], size[1], size[2]),
+ new THREE.MeshStandardMaterial({{ color: {color} }}));
mesh.name = '{pascal}Body';
mesh.position.set({cx}, {cy}, {cz}); // world pose (bbox centre)
group.add(mesh);
@@ -113,7 +104,7 @@ _FORBIDDEN: dict[str, tuple[Severity, str, str, LintKind]] = {
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"\brequestAnimationFrame\b": (Severity.ERROR, "no render loops: the harness renders the still object build(THREE) returns", "delete the loop; return the Group from build(THREE)", 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),
diff --git a/harness/codeverse3d/languages/urdf/__init__.py b/harness/codeverse3d/languages/urdf/__init__.py
index 8165b43a..69192e39 100644
--- a/harness/codeverse3d/languages/urdf/__init__.py
+++ b/harness/codeverse3d/languages/urdf/__init__.py
@@ -612,7 +612,7 @@ from mathutils import Vector # noqa: F401
def box(name, center, size):
- """Axis-aligned box helper: center/size in world meters; returns the object."""
+ """Placeholder box so the skeleton builds (center/size in world metres) — not a helper to build the object with."""
bpy.ops.mesh.primitive_cube_add(size=1.0, location=center)
ob = bpy.context.active_object
ob.name = name
diff --git a/harness/codeverse3d/languages/wrappers/_census.py b/harness/codeverse3d/languages/wrappers/_census.py
index faddb2a0..e5863671 100644
--- a/harness/codeverse3d/languages/wrappers/_census.py
+++ b/harness/codeverse3d/languages/wrappers/_census.py
@@ -113,8 +113,7 @@ def material_slot_warnings(meshes: list[dict[str, Any]]) -> list[str]:
warnings.append(
f"mesh(es) {_named(unused)} carry material slots no polygon uses — those colours never reach "
"the export; assign per face (for f in bm.faces: f.material_index = k, BEFORE bm.to_mesh, or "
- "poly.material_index on the built mesh — see the cookbook's material_index recipe) or drop the "
- "unused slots"
+ "poly.material_index on the built mesh) or drop the unused slots"
)
if clamped:
warnings.append(
diff --git a/harness/codeverse3d/languages/wrappers/render_bpy_scene.py b/harness/codeverse3d/languages/wrappers/render_bpy_scene.py
index dc3da7cf..76da0f75 100644
--- a/harness/codeverse3d/languages/wrappers/render_bpy_scene.py
+++ b/harness/codeverse3d/languages/wrappers/render_bpy_scene.py
@@ -46,6 +46,7 @@ from typing import Any
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
import bpy # noqa: E402
+from _census_glb import is_volume_only # noqa: E402 (sibling: the census's own fog test)
from _wrapper_common import ( # noqa: E402 (sibling, Blender-executed)
_write_json_atomic,
exit_after,
@@ -222,6 +223,37 @@ def relink(scene: Any, links: list[tuple[Any, Any]]) -> None:
scene.world.node_tree.links.new(a, b)
+# --------------------------------------------------------------------------- fog boxes
+#: a volume-only mesh at least this wide (largest evaluated bbox side, m) is a fog box, hidden from the
+#: fog-free views; anything smaller is a puff of steam, smoke or dust and stays in every view
+FOG_BOX_MIN_M = 8.0
+
+
+def hide_fog_boxes(scene: Any) -> list[Any]:
+ """Render-hide every bounded fog volume and return those objects (restore with ``hide_render = False``).
+
+ WHY. The ``no_fog`` views are the judge's placement views: ``unlink_world_volume`` takes the world's
+ Volume out, but ``lib.sky.haze`` — what 30/30 iteration-0 and 14/15 iteration-2 Blender envs used —
+ builds the fog as a volume-only BOX, which those views kept, so the judge read floating / sunken /
+ interpenetration through 0.003-0.008 /m of haze over a few hundred metres (2026-10-15: the
+ iteration-2 overview tiles came out milky). A fog box is a mesh every material of which is
+ volume-only (``_census_glb.is_volume_only``, the census's own test) and whose largest evaluated
+ bbox side is >= ``FOG_BOX_MIN_M``; a soft particle (``lib.materials.volume`` on a small Batch) is
+ smaller and stays. Linked library data and already hidden objects are left alone."""
+ depsgraph = bpy.context.evaluated_depsgraph_get()
+ boxes = []
+ for ob in scene.objects:
+ if ob.type != "MESH" or ob.hide_render or ob.library is not None or not is_volume_only(ob):
+ continue
+ ev = ob.evaluated_get(depsgraph)
+ corners = [ev.matrix_world @ Vector(c) for c in ev.bound_box]
+ if max(max(getattr(c, a) for c in corners) - min(getattr(c, a) for c in corners) for a in "xyz") >= FOG_BOX_MIN_M:
+ boxes.append(ob)
+ for ob in boxes:
+ ob.hide_render = True
+ return boxes
+
+
# --------------------------------------------------------------------------- room shells
ROOM_SHELL_PREFIX, LID_PREFIX = "RoomShell", "Ceiling"
@@ -305,6 +337,7 @@ def main() -> int:
scene.render.filepath = os.path.join(out, path)
fog = unlink_world_volume(scene) if s.get("no_fog") else []
lids = lift_lids(scene, s["object"]) if s.get("no_fog") else []
+ hazes = hide_fog_boxes(scene) if s.get("no_fog") else []
t0 = time.perf_counter()
try:
bpy.ops.render.render(write_still=True)
@@ -314,7 +347,7 @@ def main() -> int:
finally:
if fog:
relink(scene, fog)
- for ob in lids:
+ for ob in (*lids, *hazes):
ob.hide_render = False
ms = int((time.perf_counter() - t0) * 1000)
if not os.path.isfile(os.path.join(out, path)):
@@ -323,7 +356,8 @@ def main() -> int:
result["frames"].append({
"name": s["name"], "kind": s["kind"], "path": path, "time_s": t, "frame": frame,
"position": s["position"], "look_at": s["look_at"], "fov": s["fov"],
- "no_fog": bool(s.get("no_fog")), "hidden": sorted(ob.name for ob in lids), "render_ms": ms,
+ "no_fog": bool(s.get("no_fog")), "hidden": sorted(ob.name for ob in lids),
+ "fog_hidden": sorted(ob.name for ob in hazes), "render_ms": ms,
})
if result["engine"] in ("eevee", "workbench"):
result["gl_renderer"] = gl_renderer()
diff --git a/harness/codeverse3d/prompts/__init__.py b/harness/codeverse3d/prompts/__init__.py
index 2b84ce44..062e8234 100644
--- a/harness/codeverse3d/prompts/__init__.py
+++ b/harness/codeverse3d/prompts/__init__.py
@@ -71,7 +71,7 @@ def _load(variant: str, rel_path: str) -> str:
def load_text(rel_path: str) -> str:
- """Raw prompt text, e.g. ``load_text("blender/cookbook.md")`` — the active variant's copy first."""
+ """Raw prompt text, e.g. ``load_text("blender/contract.md")`` — the active variant's copy first."""
return _load(active_variant(), rel_path)
diff --git a/harness/codeverse3d/prompts/_claims.toml b/harness/codeverse3d/prompts/_claims.toml
index faa7dc4b..884dd2aa 100644
--- a/harness/codeverse3d/prompts/_claims.toml
+++ b/harness/codeverse3d/prompts/_claims.toml
@@ -238,3 +238,131 @@ text = "35%"
python = "codeverse3d.config:Placement"
format = "{0.model_fields[overlap_error].default:.0%}"
context = "ERROR at"
+
+# ---- D107: the per-built-object budget each object contract states (tracks/depth.py), the build
+# timeout (config.Limits), and the gl_frames thresholds generate_graphics.j2 states (frame_stats).
+
+[[claim]]
+key = "tris_per_unit_floor"
+file = "blender/contract.md"
+text = "350"
+python = "codeverse3d.tracks.depth:TRIS_PER_UNIT_FLOOR"
+context = "fewer than"
+
+[[claim]]
+key = "build_s_per_unit"
+file = "blender/contract.md"
+text = "3 s"
+python = "codeverse3d.tracks.depth:BUILD_S_PER_UNIT"
+format = "{:.0f} s"
+context = "per built object"
+
+[[claim]]
+key = "min_build_s"
+file = "blender/contract.md"
+text = "20 s"
+python = "codeverse3d.tracks.depth:MIN_BUILD_S"
+format = "{:.0f} s"
+context = "at least"
+
+[[claim]]
+key = "tris_per_unit_floor"
+file = "cadquery/contract.md"
+text = "350"
+python = "codeverse3d.tracks.depth:TRIS_PER_UNIT_FLOOR"
+context = "fewer than"
+
+[[claim]]
+key = "build_s_per_unit"
+file = "cadquery/contract.md"
+text = "3 s"
+python = "codeverse3d.tracks.depth:BUILD_S_PER_UNIT"
+format = "{:.0f} s"
+context = "per built object"
+
+[[claim]]
+key = "min_build_s"
+file = "cadquery/contract.md"
+text = "20 s"
+python = "codeverse3d.tracks.depth:MIN_BUILD_S"
+format = "{:.0f} s"
+context = "at least"
+
+[[claim]]
+key = "tris_per_unit_floor"
+file = "threejs/contract.md"
+text = "350"
+python = "codeverse3d.tracks.depth:TRIS_PER_UNIT_FLOOR"
+context = "triangles per built object"
+
+[[claim]]
+key = "build_s_per_unit"
+file = "threejs/contract.md"
+text = "3 s"
+python = "codeverse3d.tracks.depth:BUILD_S_PER_UNIT"
+format = "{:.0f} s"
+context = "per built object"
+
+[[claim]]
+key = "min_build_s"
+file = "threejs/contract.md"
+text = "20 s"
+python = "codeverse3d.tracks.depth:MIN_BUILD_S"
+format = "{:.0f} s"
+context = "at least"
+
+[[claim]]
+key = "build_timeout_s"
+file = "blender/contract.md"
+text = "300 s"
+python = "codeverse3d.config:Limits"
+format = "{0.model_fields[build_timeout_s].default} s"
+context = "build_timeout_s"
+
+[[claim]]
+key = "build_timeout_s"
+file = "cadquery/contract.md"
+text = "300 s"
+python = "codeverse3d.config:Limits"
+format = "{0.model_fields[build_timeout_s].default} s"
+context = "build_timeout_s"
+
+[[claim]]
+key = "build_timeout_s"
+file = "threejs/contract.md"
+text = "300 s"
+python = "codeverse3d.config:Limits"
+format = "{0.model_fields[build_timeout_s].default} s"
+context = "build_timeout_s"
+
+[[claim]]
+key = "build_timeout_s"
+file = "urdf/contract.md"
+text = "300 s"
+python = "codeverse3d.config:Limits"
+format = "{0.model_fields[build_timeout_s].default} s"
+context = "build_timeout_s"
+
+[[claim]]
+key = "build_timeout_s"
+file = "system/harness_contract.md"
+text = "300 s"
+python = "codeverse3d.config:Limits"
+format = "{0.model_fields[build_timeout_s].default} s"
+context = "build_timeout_s"
+
+[[claim]]
+key = "static_diff"
+file = "tracks/generate_graphics.j2"
+text = "0.002"
+python = "codeverse3d.spatial.frame_stats:STATIC_DIFF"
+format = "{:g}"
+context = "must reach"
+
+[[claim]]
+key = "flicker_diff"
+file = "tracks/generate_graphics.j2"
+text = "0.35"
+python = "codeverse3d.spatial.frame_stats:FLICKER_DIFF"
+format = "{:g}"
+context = "no consecutive pair"
diff --git a/harness/codeverse3d/prompts/blender/contract.md b/harness/codeverse3d/prompts/blender/contract.md
index a209c47f..a10ed6f5 100644
--- a/harness/codeverse3d/prompts/blender/contract.md
+++ b/harness/codeverse3d/prompts/blender/contract.md
@@ -1,149 +1,173 @@
# Blender (bpy) authoring contract — track `static_object`, language `blender`
-## Files (multi-file: one file per plan part, so parts can be refined in parallel)
-* `src/model.py` — the ENTRY: imports the part builders, calls them in plan order, runs the
- self-check. No geometry of its own beyond small glue.
-* `src/parts/<snake>.py` — ONE per plan part (`SeatCushion` → `src/parts/seat_cushion.py`),
- exporting `def build_seat_cushion() -> bpy.types.Object` that builds the part at its WORLD
- pose with the exact object name and returns it. Instances (`Leg_0 … Leg_3`) are looped
- INSIDE that one file, each TOP-LEVEL — NEVER under a parent Empty (parts are measured as
- top-level objects; an Empty merges them into one → part missing). Self-contained (own small
- helpers); it only DEFINES — never builds at import time (model.py calls each builder once).
-* `src/` is on `sys.path`: `from parts.seat import build_seat` or `import parts.seat`. Optional
- shared helpers: `src/parts/_common.py` (underscore = not a part). Small objects (1–2 parts)
- may use a single `src/model.py` (example B).
-* The harness runs `src/model.py` with `blender -b --factory-startup` in an **emptied scene**,
- takes a census and exports `artifacts/object.glb` (Y-up) + `object.stl`; build errors come
- back as `src/parts/<file>.py:<line>`. You never export or render.
-
-## Frame, units, placement
-* **Z is up, -Y is the front, +X is the right. Meters.** (glTF export maps this to
- Y-up / +Z-front automatically — do not pre-rotate.) The object stands on z = 0 (lowest
- vertex at z = 0), footprint centred on the Z axis; real-world dimensions.
-
-## Naming and structure
-* One Blender **object per plan part**, `obj.name = "<PartName>"` in PascalCase exactly as the
- plan says. Auto-suffixed duplicates (`Leg.001`) violate it: name instances `<Name>_0 … <Name>_N-1`.
-* Meshes only (no empties as parts, no un-converted curves, no cameras/lights); link every
- object to `bpy.context.scene.collection`. Plan numbers = constants at the top of each part
- file; keep each part inside its plan bbox; attached parts overlap 0.5–2 mm (deeper = interpenetration).
-
-## Allowed imports · forbidden calls
-* Imports: `bpy`, `bmesh`, `mathutils`, `math`, `random`, `itertools`, `functools`, `typing`,
- `dataclasses`, and your own `parts.*` modules. Nothing else (no numpy loops over vertices,
- no os/sys/subprocess/urllib/socket/pathlib, no `import codeverse3d`).
-* Forbidden: `bpy.ops.render.*`, `bpy.ops.export_*`, `bpy.ops.import_*`, `bpy.ops.wm.*`,
- `bpy.ops.image.*`, `bpy.ops.screen.*`, `bpy.ops.view3d.*`, `bpy.data.libraries`,
- `bpy.app.timers`, `open(`, `exec(`, `eval(`, `__import__`, camera / light creation, `input()`,
- network, file writes; never touch `bpy.context.scene.render` / `scene.world` (harness-owned).
-* Prefer modifiers (bevel / array / mirror) over dense meshes.
-
-## COMPLETE minimal example A — multi-file (verified with Blender 5.2.2 LTS headless)
-`src/parts/seat.py`
+What must be true, where, and how the harness measures it. Nothing here is a construction to
+copy: the gate constants are named so the numbers can be checked, not so they can be typed in.
+
+## Files (what the lint `lint:blender` and the wrapper read)
+* `src/model.py` — the ENTRY the wrapper runs: it imports each part's builder and calls it (a
+ builder called twice builds its part twice, `Name.001`).
+* `src/parts/<snake>.py` — one per plan part (`SeatCushion` → `src/parts/seat_cushion.py`),
+ defining `build_seat_cushion() -> bpy.types.Object` that builds the part at its WORLD pose with
+ its exact name, links it to `bpy.context.scene.collection` and returns it. Instances
+ (`Leg_0 … Leg_N-1`) are built inside that one file and returned as a list. A part file only
+ DEFINES — a module-level `build_*()` or `main()` call builds the part twice (`Name.001`, lint
+ WARN); a part file `model.py` never imports is never built (lint WARN); a builder not named
+ `build_<snake>` is a lint ERROR and an ImportError. `src/` is on `sys.path`
+ (`from parts.seat import build_seat`); `src/parts/_<name>.py` is a shared helper, not a part.
+* A single `src/model.py` with no `src/parts/` is also accepted (the lint then expects the part
+ names in that file).
+* The harness runs `src/model.py` with `blender -b --factory-startup` in an EMPTY scene, takes a
+ census and exports `artifacts/object.glb` (Y-up) + `object.stl`, applying modifiers on export.
+ Build errors come back as `src/parts/<file>.py:<line>`. The wrapper seeds `random`, numpy
+ and `mathutils.noise` (`--seed`, default 0) before your module runs, so unseeded draws repeat
+ from build to build; a `random.Random(n)` of your own is reproducible too.
+
+## Frame, units, placement (`check_contract`)
+* Frame and units are `conventions.py`'s: Z up, −Y front, +X right, metres (a 450 mm seat is
+ `0.45`; a measured bbox of 450 × 500 × 900 means the plan's numbers were typed in mm). The
+ glTF export maps this to Y-up itself — do not pre-rotate.
+* Lowest vertex at z = 0: off by more than 1 cm (`GROUND_TOL_M`) is a WARN, more than 3 × that an
+ ERROR. Footprint centre within max(1 cm, 10 % of the larger horizontal extent) of the Z axis
+ (WARN). Both findings print the translation that fixes them.
+* The harness exports AS AUTHORED and never re-centres or grounds: translating the whole assembly
+ so its lowest vertex is at z = 0 is fine; moving object origins (`bpy.ops.object.origin_set`)
+ changes what the gate measures.
+
+## Naming and structure (`check_contract`, the census)
+* One top-level mesh object per plan part, `obj.name` in PascalCase exactly as the plan spells it;
+ the gate matches on names, so a merged mesh reports every other part missing and a misspelt
+ name is an ERROR. Instances are `<Name>_0 … <Name>_N-1`; an auto-suffixed `Leg.001` means two
+ objects claimed one name.
+* Parts are measured as top-level objects: a parent Empty merges its whole subtree into ONE part
+ (plan part reported missing), and a scaled parent bakes its scale into the children.
+ Collections are organisation only (not exported as nodes). `bpy.ops.object.join` inherits the
+ ACTIVE object's transform (lint WARN when no active object is set).
+* Every object made through the data API must be linked to `bpy.context.scene.collection` or it
+ is not in the census. Every visible object exports: a leftover cutter or guide ships as a part
+ — delete it, or set `hide_render` / `hide_viewport` / `hide_set(True)` (any one keeps it out of
+ the GLB; an unapplied boolean still evaluates).
+* Measured on Blender 5.2.2 with the wrapper's export call: a curve object exports only when
+ `bevel_depth > 0` — a bare path exports no node at all and the part is reported missing.
+ Convert to a mesh when a later step needs real geometry.
+
+## Sizes and contact (`check_contract`, `check_connectivity`)
+* Each part's built AABB (after modifiers) matches its plan row: per axis
+ `tol = max(1 cm, 10 % of the planned extent)`; past `tol` is a WARN, past 3 × `tol` an ERROR,
+ and the finding prints the per-axis delta. Instanced parts are measured on extents only — each
+ copy or the union of copies, whichever fits the plan box better; a wrong copy count is a WARN.
+* Parts that touch: surface gap ≤ 2 mm (`CONTACT_GAP_M`) counts as contact; overlap deeper than
+ 2 mm (`PENETRATION_WARN_M`) is reported as interpenetration, deeper than 10 mm with at least 2 %
+ of one part's surface samples inside the other is an ERROR.
+ Every part must be in the ground-touching component: a floating part is an ERROR whose finding
+ prints the translation (or the extension) that closes the gap.
+* Islands: no shell inside a part may be smaller than 5 % of that part's largest extent
+ (`TINY_ISLAND_FRACTION`, WARN "tiny disconnected island") — boolean debris, a stray vertex, an
+ un-merged mirror half. Zero-thickness faces have no volume for the gate's inside test and break
+ booleans; coincident faces of two parts z-fight.
+* Budgets (`detail_budget`, sized from the plan's part × instance count): fewer than 350
+ triangles per built object is a WARN (floor clamped to 1 500 – 40 000), more than 20 000 per
+ built object an ERROR (ceiling clamped to 60 000 – 600 000); a build over 3 s per built object
+ (at least 20 s) is a WARN, and the build is killed at `build_timeout_s` (300 s by default).
+ Per-vertex Python loops over large meshes are what hits the time limit — `foreach_set`,
+ modifiers or fewer segments are the usual way out.
+
+## Sandbox (what the lint rejects)
+* Imports the lint allows: `bpy`, `bmesh`, `mathutils`, `bpy_extras`, `math`, `random`, `numpy`,
+ `itertools`, `functools`, `collections`, `typing`, `dataclasses`, `colorsys`, `statistics`,
+ `operator`, `enum`, `copy`, `sys`, `os`, `__future__` and your own `parts.*` modules
+ (`ALLOWED_IMPORTS`). Anything else is a WARN; `pathlib`, `subprocess`, `urllib`, `requests`,
+ `socket`, `http`, `shutil`, `ctypes`, `pickle` are ERRORs (`FORBIDDEN_IMPORTS`).
+* Forbidden calls (ERROR): `bpy.ops.render.*`, `bpy.ops.export_*`, `bpy.ops.import_*`,
+ `bpy.ops.wm.*`, `bpy.ops.image.save`, `bpy.data.libraries.*`, `open(`, `os.system` / file-IO
+ `os.*`, `subprocess.*`, `shutil.*`, network. WARN: cameras, lights, worlds, render settings,
+ `scene.camera`, `scene.world` (harness-owned), `bpy.ops.view3d.*` / `bpy.ops.screen.*` (no
+ viewport headless), `sys.exit`. No `exec` / `eval` / `__import__` / `input()` either: the
+ script runs unattended inside the harness's Blender process.
+
+## Materials (what the exporter keeps, what the census measures)
+* The GLB keeps flat PBR — base colour, metallic, roughness, emission, alpha — plus IMAGE textures
+ only; procedural node trees (noise, wave, ramps) are NOT exported, so the judge sees the flat
+ base colour. Every new material already has a node tree (`mat.use_nodes` is deprecated, lint
+ INFO); the Principled BSDF inputs are `Base Color`, `Roughness`, `Metallic`, `Alpha`,
+ `Emission Color` + `Emission Strength`, `Specular IOR Level`, `Transmission Weight`,
+ `Coat Weight`, `Sheen Weight`, `Subsurface Weight` — the pre-4.0 keys `Specular`,
+ `Transmission`, `Emission`, `Clearcoat`, `Sheen`, `Subsurface` raise KeyError (lint ERROR,
+ `REMOVED_BSDF_INPUTS`). Transparency: `mat.surface_render_method = 'BLENDED'` (the EEVEE
+ setting the exporter reads; `mat.blend_method` still exists on 5.2.2 but is legacy).
+* Several colours on one part = several slots on the mesh (`obj.data.materials.append`) and
+ `polygon.material_index` per face; every polygon starts on slot 0. The census warns when a
+ mesh carries slots no polygon uses or an index past the last slot — that warning means the
+ assignment did nothing and the part exports in one colour.
+
+## API traps (each is a build error on Blender 5.2.2 or a silent wrong size; the lint's severity is given where it checks one)
+* `bpy.ops.*` needs context: wrap it in `bpy.context.temp_override(object=obj, active_object=obj,
+ selected_objects=[obj])`; the dict-override form `bpy.ops.x({...})` was removed in 4.0 (ERROR).
+ `bpy.context.object` / `selected_objects` are unreliable headless — keep your own references.
+* `bmesh.ops.create_*` needs no context and centres the shape on the origin;
+ `bpy.ops.mesh.primitive_*_add` defaults to `size=2` — pass `size=1` with `scale=` (else extents
+ double, WARN) and then `transform_apply(location=False, rotation=False, scale=True)` with all
+ three keywords (an omitted one defaults to True and bakes the location, WARN). Keep
+ `obj.scale` at 1 by export time.
+* `bm.verts[i]` / `bm.faces[i]` need `ensure_lookup_table()` after `from_mesh` or any topology op
+ (ERROR, IndexError). `bmesh.ops.create_cube` / `create_cone` return only `verts`.
+* Modifiers may stay unapplied (the exporter applies them). `modifier_apply` needs
+ `temp_override` (WARN) and a single-user mesh (`obj.data = obj.data.copy()` first). Boolean
+ solvers are `MANIFOLD` (closed inputs), `EXACT`, `FLOAT` — `'FAST'` raises (ERROR); a cutter
+ coplanar with the face it cuts fails silently.
+* Removed in 4.x/5.x, lint ERROR: `use_auto_smooth` / `auto_smooth_angle` (use
+ `polygon.use_smooth` or `bpy.ops.object.shade_smooth_by_angle`), `Mesh.calc_normals()`,
+ geometry-nodes inputs by item access (`mod["Socket_2"] = v` →
+ `getattr(mod.properties.inputs, "Socket_2").value = v`). `BLENDER_EEVEE_NEXT` is a lint WARN
+ (render settings are the harness's).
+* Removed on 5.2.2 and NOT linted (the build fails with AttributeError / ImportError / TypeError):
+ `Mesh.calc_normals_split()`, `edge.crease` / `edge.bevel_weight` (attributes `crease_edge` /
+ `bevel_weight_edge`), `scene.node_tree`, the `bgl` module, constructing
+ `gpu.types.GPUShader(...)`.
+
+## The interface, executable (verified with Blender 5.2.2 LTS headless)
+Two plan parts, `Body` and `Knob` × 2 — the file names, builder names, linking, naming and the
+instance list the lint and the gates expect. Extents and positions are the plan row's numbers.
+
+`src/parts/body.py`
```py
import bpy, bmesh
-SEAT_D, SEAT_T, SEAT_Z = 0.34, 0.04, 0.45 # metres, from the plan (bbox top at 0.45)
-
-def build_seat() -> bpy.types.Object:
- """Seat — round wooden disc; top face at z = SEAT_Z. Returns the object at world pose."""
+def build_body() -> bpy.types.Object:
+ """Body: a mesh at its WORLD pose, named as the plan names it, linked to the scene."""
bm = bmesh.new()
- bmesh.ops.create_cone(bm, cap_ends=True, segments=48, radius1=SEAT_D / 2, radius2=SEAT_D / 2, depth=SEAT_T)
- me = bpy.data.meshes.new("Seat"); bm.to_mesh(me); bm.free()
- seat = bpy.data.objects.new("Seat", me); seat.location = (0, 0, SEAT_Z - SEAT_T / 2)
- bpy.context.scene.collection.objects.link(seat)
- bev = seat.modifiers.new("Bevel", 'BEVEL'); bev.width = 0.006; bev.segments = 3
- wood = bpy.data.materials.new("Wood")
- bsdf = wood.node_tree.nodes["Principled BSDF"] # nodes exist by default (4.x/5.x)
- bsdf.inputs["Base Color"].default_value, bsdf.inputs["Roughness"].default_value = (0.55, 0.33, 0.16, 1.0), 0.6
- seat.data.materials.append(wood)
- return seat
+ bmesh.ops.create_cube(bm, size=1.0)
+ bmesh.ops.scale(bm, vec=(0.12, 0.08, 0.05), verts=bm.verts) # the plan row's extents
+ me = bpy.data.meshes.new("Body"); bm.to_mesh(me); bm.free()
+ obj = bpy.data.objects.new("Body", me)
+ obj.location = (0.0, 0.0, 0.025) # lowest vertex on z = 0
+ bpy.context.scene.collection.objects.link(obj)
+ return obj
```
-`src/parts/leg.py`
+`src/parts/knob.py`
```py
-import bpy, bmesh, math
-
-LEG_R, LEG_N, LEG_RING = 0.02, 3, 0.12 # metres, from the plan
-LEG_H = 0.45 - 0.04 + 0.001 # reaches 1 mm into the seat (weld)
+import bpy, bmesh
-def build_leg() -> list[bpy.types.Object]:
- """Leg x3 — steel rods Leg_0..Leg_2 on a ring, each TOP-LEVEL (no parent Empty!)."""
- steel = bpy.data.materials.new("Steel"); bsdf = steel.node_tree.nodes["Principled BSDF"]
- bsdf.inputs["Base Color"].default_value = (0.6, 0.6, 0.62, 1.0)
- bsdf.inputs["Roughness"].default_value, bsdf.inputs["Metallic"].default_value = 0.35, 1.0
- legs = []
- for i in range(LEG_N):
- a = 2 * math.pi * i / LEG_N
+def build_knob() -> list[bpy.types.Object]:
+ """Knob x2: instances are TOP-LEVEL objects Knob_0, Knob_1 — never under a parent Empty."""
+ out = []
+ for i, x in enumerate((-0.04, 0.04)):
bm = bmesh.new()
- bmesh.ops.create_cone(bm, cap_ends=True, segments=24, radius1=LEG_R, radius2=LEG_R, depth=LEG_H)
- me = bpy.data.meshes.new(f"Leg_{i}"); bm.to_mesh(me); bm.free()
- leg = bpy.data.objects.new(f"Leg_{i}", me)
- leg.location = (LEG_RING * math.cos(a), LEG_RING * math.sin(a), LEG_H / 2)
- bpy.context.scene.collection.objects.link(leg)
- leg.data.materials.append(steel); legs.append(leg)
- return legs
+ bmesh.ops.create_cone(bm, cap_ends=True, segments=16, radius1=0.01, radius2=0.01, depth=0.02)
+ me = bpy.data.meshes.new(f"Knob_{i}"); bm.to_mesh(me); bm.free()
+ obj = bpy.data.objects.new(f"Knob_{i}", me); obj.location = (x, 0.0, 0.05 + 0.01)
+ bpy.context.scene.collection.objects.link(obj); out.append(obj) # flush on Body's top: contact
+ return out
```
`src/model.py`
```py
-"""Stool — entry: imports the part builders, calls them in plan order, self-checks."""
import bpy
-from parts.seat import build_seat
-from parts.leg import build_leg
-
-def _selfcheck() -> None:
- names = [o.name for o in bpy.data.objects if o.type == 'MESH']
- assert names and all('.' not in n for n in names), f"missing or auto-suffixed meshes: {names}"
-
-def main() -> None:
- build_seat()
- build_leg()
- _selfcheck()
-
-main()
-```
-
-## COMPLETE minimal example B — single file (small objects; verified with Blender 5.2.2 LTS)
-```python
-import bpy, bmesh, math
-
-SEAT_D, SEAT_T, SEAT_Z = 0.34, 0.04, 0.45 # metres, from the plan
-LEG_R, LEG_N, LEG_RING = 0.02, 3, 0.12
-
-def make_cylinder(name, radius, depth, location, segments=32):
- """Cylinder along Z centred at `location` via bmesh (no operator/context needed)."""
- bm = bmesh.new()
- bmesh.ops.create_cone(bm, cap_ends=True, segments=segments, radius1=radius, radius2=radius, depth=depth)
- me = bpy.data.meshes.new(name); bm.to_mesh(me); bm.free()
- obj = bpy.data.objects.new(name, me); obj.location = location
- bpy.context.scene.collection.objects.link(obj); return obj
-
-def make_material(name, rgb, roughness=0.5, metallic=0.0):
- mat = bpy.data.materials.new(name); bsdf = mat.node_tree.nodes["Principled BSDF"]
- bsdf.inputs["Base Color"].default_value = (*rgb, 1.0)
- bsdf.inputs["Roughness"].default_value, bsdf.inputs["Metallic"].default_value = roughness, metallic
- return mat
-
-def build_seat() -> bpy.types.Object:
- seat = make_cylinder("Seat", SEAT_D / 2, SEAT_T, (0, 0, SEAT_Z - SEAT_T / 2), 48)
- bev = seat.modifiers.new("Bevel", 'BEVEL'); bev.width = 0.006; bev.segments = 3
- seat.data.materials.append(make_material("Wood", (0.55, 0.33, 0.16), 0.6))
- return seat
-
-def build_leg(i: int) -> bpy.types.Object:
- a, h = 2 * math.pi * i / LEG_N, SEAT_Z - SEAT_T + 0.001 # 1 mm into the seat (weld)
- leg = make_cylinder(f"Leg_{i}", LEG_R, h, (LEG_RING * math.cos(a), LEG_RING * math.sin(a), h / 2), 24)
- leg.data.materials.append(make_material(f"Steel_{i}", (0.6, 0.6, 0.62), 0.35, 1.0))
- return leg
-
-def _selfcheck() -> None:
- names = [o.name for o in bpy.data.objects if o.type == 'MESH']
- assert names and all('.' not in n for n in names), f"missing or auto-suffixed meshes: {names}"
+from parts.body import build_body
+from parts.knob import build_knob
def main() -> None:
- build_seat()
- for i in range(LEG_N):
- build_leg(i)
- _selfcheck()
+ build_body()
+ build_knob()
+ assert all("." not in o.name for o in bpy.data.objects), "auto-suffixed name: two objects share a plan name"
main()
```
diff --git a/harness/codeverse3d/prompts/blender/cookbook.md b/harness/codeverse3d/prompts/blender/cookbook.md
deleted file mode 100644
index f7b3e456..00000000
--- a/harness/codeverse3d/prompts/blender/cookbook.md
+++ /dev/null
@@ -1,999 +0,0 @@
-# Blender (bpy) cookbook — static objects, Blender 5.2 LTS headless
-
-Every snippet below runs as-is in `blender -b --factory-startup` (they are executed in
-order by the harness test suite). Z-up, −Y front, meters, PascalCase object names.
-Files: `src/model.py` (entry) + `src/parts/<snake>.py` (one `build_<snake>()` per plan part) —
-see "File layout". The harness inlines the relevant chapters into your prompts; the full
-file is at `.3dcode/cookbook.md` in your workspace.
-
-## File layout (multi-file: model.py + parts/<snake>.py)
-
-The harness lays down one file per plan part so parts can be refined in parallel:
-
-```text
-src/model.py ENTRY — imports the builders, calls them in plan order, self-checks
-src/parts/seat.py def build_seat() -> bpy.types.Object (one per plan part, snake_case)
-src/parts/leg.py def build_leg() -> Leg_0..Leg_3, each TOP-LEVEL (instances loop here; no parent Empty)
-src/parts/_common.py optional shared helpers (underscore = not a part; never required)
-```
-
-Rules that the lint enforces: the part file `src/parts/<snake>.py` must define
-`build_<snake>()`; part files only DEFINE (no module-level `build_*()` / `main()` calls —
-model.py calls each builder once); `src/` is on `sys.path`, so model.py does
-`from parts.seat import build_seat` (or `import parts.seat`). Build errors come back as
-`src/parts/<file>.py:<line>`. A complete verified 3-file example is in the contract.
-
-A part file, fully self-contained (own helpers, plan numbers on top):
-
-`src/parts/mug_body.py`
-```py
-import bpy, bmesh
-
-MUG_R, MUG_H, WALL = 0.042, 0.095, 0.004 # plan numbers (metres)
-
-def _link(obj):
- bpy.context.scene.collection.objects.link(obj); return obj
-
-def build_mug_body() -> bpy.types.Object:
- """MugBody — cylinder on z=0, hollowed later with a boolean; returns the object at world pose."""
- bm = bmesh.new()
- bmesh.ops.create_cone(bm, cap_ends=True, segments=48, radius1=MUG_R, radius2=MUG_R, depth=MUG_H)
- me = bpy.data.meshes.new("MugBody"); bm.to_mesh(me); bm.free()
- body = bpy.data.objects.new("MugBody", me); body.location = (0, 0, MUG_H / 2)
- return _link(body)
-```
-`src/model.py`
-```py
-import bpy
-from parts.mug_body import build_mug_body
-
-def main() -> None:
- build_mug_body()
- assert all('.' not in o.name for o in bpy.data.objects), "auto-suffixed names"
-
-main()
-
-```
-
-Small objects (1–2 parts) may keep everything in one `src/model.py`; the rest of this
-cookbook is written that way. Every snippet below assumes these helpers (define them once
-per file that uses them — part files are self-contained):
-
-```python
-import bpy, bmesh, math, random
-from mathutils import Vector, Matrix
-
-random.seed(0) # deterministic everywhere
-
-# ---- plan numbers (metres) --------------------------------------------------
-MUG_R, MUG_H, WALL = 0.042, 0.095, 0.004
-HANDLE_R, HANDLE_TUBE = 0.030, 0.007
-
-# ---- helpers ----------------------------------------------------------------
-def link(obj: bpy.types.Object) -> bpy.types.Object:
- """Link into the scene collection (data-API objects are not linked by default)."""
- bpy.context.scene.collection.objects.link(obj)
- return obj
-
-def obj_from_bmesh(name: str, bm: bmesh.types.BMesh, location=(0, 0, 0)) -> bpy.types.Object:
- """bmesh → mesh → object, freed and linked. Name is the PLAN part name."""
- me = bpy.data.meshes.new(name)
- bm.to_mesh(me); bm.free(); me.update()
- o = bpy.data.objects.new(name, me)
- o.location = location
- return link(o)
-
-def activate(obj: bpy.types.Object) -> None:
- """Make `obj` the only selected + active object (needed before ANY bpy.ops)."""
- bpy.ops.object.select_all(action='DESELECT')
- obj.select_set(True)
- bpy.context.view_layer.objects.active = obj
-
-def apply_modifiers(obj: bpy.types.Object) -> None:
- """Apply every modifier in stack order (headless-safe via temp_override)."""
- if obj.data.users > 1: # linked duplicates cannot be applied
- obj.data = obj.data.copy()
- for m in list(obj.modifiers):
- with bpy.context.temp_override(object=obj, active_object=obj,
- selected_objects=[obj], selected_editable_objects=[obj]):
- bpy.ops.object.modifier_apply(modifier=m.name)
-
-def apply_transforms(obj: bpy.types.Object) -> None:
- """Bake location+rotation+scale into the mesh (all three explicit!)."""
- activate(obj)
- bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
-```
-
-## Primitives (data API, no operator context)
-
-`bmesh.ops.create_*` never depends on selection/active object, so it is safe in loops.
-Primitives are centred on their origin; translate with `location`.
-
-```python
-def make_box(name, size, location=(0, 0, 0)) -> bpy.types.Object:
- """Axis-aligned box, size=(sx, sy, sz) full extents, centred at `location`."""
- bm = bmesh.new()
- bmesh.ops.create_cube(bm, size=1.0)
- bmesh.ops.scale(bm, vec=size, verts=bm.verts)
- return obj_from_bmesh(name, bm, location)
-
-def make_cylinder(name, radius, depth, location=(0, 0, 0), segments=32, radius2=None, rings=1):
- """Cylinder (or cone when radius2 given) along local Z, centred at `location`.
- rings > 1 subdivides the length (needed before bending / lattice deforms)."""
- bm = bmesh.new()
- bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=segments,
- radius1=radius, radius2=radius if radius2 is None else radius2, depth=depth)
- if rings > 1:
- side = [e for e in bm.edges if abs(e.verts[0].co.z - e.verts[1].co.z) > 1e-9]
- bmesh.ops.subdivide_edges(bm, edges=side, cuts=rings - 1, use_grid_fill=True)
- return obj_from_bmesh(name, bm, location)
-
-def make_sphere(name, radius, location=(0, 0, 0), segments=32, rings=16):
- bm = bmesh.new()
- bmesh.ops.create_uvsphere(bm, u_segments=segments, v_segments=rings, radius=radius)
- return obj_from_bmesh(name, bm, location)
-
-def make_torus(name, major_r, minor_r, location=(0, 0, 0), major_seg=48, minor_seg=16):
- """Torus in the XY plane (operator version — fine headless, then we capture the object)."""
- bpy.ops.mesh.primitive_torus_add(major_radius=major_r, minor_radius=minor_r,
- major_segments=major_seg, minor_segments=minor_seg,
- location=location)
- o = bpy.context.active_object
- o.name = name
- return o
-
-def make_tube(name, radius, wall, depth, location=(0, 0, 0), segments=48):
- """Hollow open tube: outer cylinder minus inner, via bmesh solidify of a shell."""
- bm = bmesh.new()
- bmesh.ops.create_cone(bm, cap_ends=False, segments=segments,
- radius1=radius, radius2=radius, depth=depth)
- bmesh.ops.solidify(bm, geom=bm.faces[:], thickness=wall)
- return obj_from_bmesh(name, bm, location)
-
-# quick demo (the harness test runs this): a mug body + ring handle
-body = make_cylinder("MugBody", MUG_R, MUG_H, (0, 0, MUG_H / 2), 48)
-handle = make_torus("MugHandle", HANDLE_R, HANDLE_TUBE, (MUG_R + HANDLE_R - 0.004, 0, MUG_H * 0.55))
-handle.rotation_euler = (math.radians(90), 0, 0) # stand the ring up in the XZ plane
-```
-
-Why: operators (`bpy.ops.mesh.primitive_cube_add`) change selection, need a context and
-use `size=2` by default (a 2 m cube!) — data-API primitives avoid all three traps.
-Numbers: 24–48 segments for visible cylinders, 8–12 for thin rods/bolts.
-
-## Origins and placement
-
-```python
-def set_origin_to_bottom(obj: bpy.types.Object) -> None:
- """Move the origin to the bottom-centre of the mesh (world pose unchanged)."""
- me = obj.data
- xs = [v.co.x for v in me.vertices]; ys = [v.co.y for v in me.vertices]; zs = [v.co.z for v in me.vertices]
- c = Vector(((min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2, min(zs)))
- me.transform(Matrix.Translation(-c))
- obj.matrix_world = obj.matrix_world @ Matrix.Translation(c)
-
-def world_bbox(obj: bpy.types.Object):
- """(min, max) Vectors of the evaluated world-space bbox."""
- bpy.context.view_layer.update()
- pts = [obj.matrix_world @ Vector(c) for c in obj.bound_box]
- return (Vector(map(min, zip(*pts))), Vector(map(max, zip(*pts))))
-
-def drop_to_ground(objs) -> None:
- """Translate the whole assembly so its lowest point is z = 0."""
- zmin = min(world_bbox(o)[0].z for o in objs)
- for o in objs:
- o.location.z -= zmin
-
-set_origin_to_bottom(body)
-print("mug bbox", world_bbox(body))
-```
-
-Why: `obj.dimensions` ignores rotation; `bound_box` is object-space — always go through
-`matrix_world` and `view_layer.update()` after changing transforms.
-
-## Modifiers (bevel, boolean, array, mirror, solidify, screw, subsurf)
-
-Add with `obj.modifiers.new(name, TYPE)`, set properties, then `apply_modifiers(obj)`
-when you need the final mesh (booleans, joins, exports all behave better applied).
-
-```python
-def add_bevel(obj, width=0.003, segments=3, angle_deg=30.0):
- """Rounded edges: the single cheapest realism upgrade. width < half the thinnest wall."""
- b = obj.modifiers.new("Bevel", 'BEVEL')
- b.width = width; b.segments = segments
- b.limit_method = 'ANGLE'; b.angle_limit = math.radians(angle_deg)
- b.harden_normals = False
- return b
-
-def boolean_cut(obj, cutter, solver='MANIFOLD') -> None:
- """obj -= cutter, applied, cutter deleted. MANIFOLD is fast + robust on closed meshes;
- fall back to EXACT when inputs are not watertight (solvers: MANIFOLD / EXACT / FLOAT —
- there is no 'FAST'). Cutter must overshoot the face it pierces by ≥ 5 mm, never be
- coplanar with it."""
- m = obj.modifiers.new("Cut", 'BOOLEAN')
- m.operation = 'DIFFERENCE'; m.object = cutter
- m.solver = solver
- try:
- apply_modifiers(obj)
- except RuntimeError: # MANIFOLD refused (non-manifold input)
- m = obj.modifiers.new("Cut", 'BOOLEAN'); m.operation = 'DIFFERENCE'; m.object = cutter
- m.solver = 'EXACT'; apply_modifiers(obj)
- bpy.data.objects.remove(cutter, do_unlink=True)
-
-def boolean_union(obj, other) -> None:
- m = obj.modifiers.new("Union", 'BOOLEAN'); m.operation = 'UNION'; m.object = other
- m.solver = 'EXACT'; apply_modifiers(obj)
- bpy.data.objects.remove(other, do_unlink=True)
-
-def add_array(obj, count, offset_xyz):
- a = obj.modifiers.new("Array", 'ARRAY'); a.count = count
- a.use_relative_offset = False; a.use_constant_offset = True
- a.constant_offset_displace = offset_xyz
- return a
-
-def add_mirror(obj, axis='X', bisect=False):
- """Mirror across the OBJECT ORIGIN plane (put the origin on the symmetry plane!)."""
- m = obj.modifiers.new("Mirror", 'MIRROR')
- idx = 'XYZ'.index(axis)
- m.use_axis = [i == idx for i in range(3)]
- m.use_bisect_axis = [bisect and i == idx for i in range(3)]
- m.use_clip = True; m.merge_threshold = 0.0005
- return m
-
-def add_solidify(obj, thickness=0.003, inward=True):
- s = obj.modifiers.new("Solidify", 'SOLIDIFY')
- s.thickness = thickness; s.offset = -1 if inward else 1; s.use_even_offset = True
- return s
-
-def add_subsurf(obj, levels=1):
- s = obj.modifiers.new("Subsurf", 'SUBSURF'); s.levels = levels; s.render_levels = levels
- return s
-
-# demo: hollow the mug with a boolean, bevel the rim, mirror a pair of feet
-cutter = make_cylinder("MugCutter", MUG_R - WALL, MUG_H, (0, 0, MUG_H / 2 + WALL + 0.005), 48)
-boolean_cut(body, cutter)
-add_bevel(body, 0.0015, 2)
-apply_modifiers(body)
-foot = make_box("FootL", (0.02, 0.02, 0.01), (0, 0, 0.005))
-foot.data.transform(Matrix.Translation((-0.03, 0, 0))) # mesh offset so the origin stays on x=0
-add_mirror(foot, 'X'); apply_modifiers(foot); foot.name = "Feet"
-```
-
-Why: `MANIFOLD` is ~10× faster and never produces slivers but needs watertight inputs;
-`EXACT` is the universal fallback; never use `FLOAT`/`FAST` (self-intersections).
-Array/mirror/screw results are *one object* — correct for repeated detail that belongs to one part.
-
-## Screw and lathe (rotational parts: bottles, vases, knobs, threads)
-
-```python
-def lathe(name, profile_xz, segments=48, location=(0, 0, 0)) -> bpy.types.Object:
- """Revolve a polyline profile [(r, z), ...] about Z into a closed solid.
- Profile runs from the axis (r = 0) at the bottom up and back to the axis at the top."""
- bm = bmesh.new()
- verts = [bm.verts.new((r, 0.0, z)) for r, z in profile_xz]
- edges = [bm.edges.new((a, b)) for a, b in zip(verts, verts[1:])] # spin needs EDGES
- bmesh.ops.spin(bm, geom=verts + edges, cent=(0, 0, 0), axis=(0, 0, 1),
- angle=2 * math.pi, steps=segments, use_merge=True)
- bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-6) # weld the seam + axis points
- bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:])
- return obj_from_bmesh(name, bm, location)
-
-bottle = lathe("Bottle", [(0.0, 0.0), (0.032, 0.0), (0.034, 0.010), (0.034, 0.16),
- (0.014, 0.21), (0.014, 0.25), (0.0, 0.25)])
-bottle.data.shade_smooth()
-
-def add_screw_thread(profile_obj, turns=6, pitch=0.002, steps=24):
- """Thread from a small profile polygon placed at radius r: SCREW modifier."""
- s = profile_obj.modifiers.new("Screw", 'SCREW')
- s.angle = math.radians(360 * turns); s.screw_offset = pitch * turns
- s.steps = steps; s.render_steps = steps; s.iterations = 1; s.axis = 'Z'
- s.use_merge_vertices = True
- return s
-```
-
-Why: revolved profiles give smooth, correct silhouettes for anything round; one list of
-(r, z) points is the whole shape. Segments 48 for hero parts, 24 for small knobs.
-
-## Curves → tubes, ropes, cables, rails
-
-```python
-def make_tube_along(name, points, radius, resolution=12, smooth=True) -> bpy.types.Object:
- """Round tube following `points` (world coords), converted to a real mesh."""
- cu = bpy.data.curves.new(name, 'CURVE')
- cu.dimensions = '3D'; cu.bevel_depth = radius; cu.bevel_resolution = resolution // 2
- cu.use_fill_caps = True; cu.resolution_u = 12
- sp = cu.splines.new('NURBS' if smooth else 'POLY')
- sp.points.add(len(points) - 1)
- for p, (x, y, z) in zip(sp.points, points):
- p.co = (x, y, z, 1.0)
- if smooth:
- sp.use_endpoint_u = True; sp.order_u = min(4, len(points))
- o = link(bpy.data.objects.new(name, cu))
- with bpy.context.temp_override(object=o, active_object=o, selected_objects=[o],
- selected_editable_objects=[o]):
- bpy.ops.object.convert(target='MESH')
- bm = bmesh.new(); bm.from_mesh(o.data) # weld the bevel seam (else 1 island per strip)
- bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-6)
- bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:])
- bm.to_mesh(o.data); bm.free(); o.data.update()
- return o
-
-cable = make_tube_along("Cable", [(0.05, 0, 0.30), (0.10, 0.02, 0.20), (0.18, 0.0, 0.08),
- (0.30, -0.03, 0.01)], radius=0.004)
-```
-
-Why: a NURBS curve with `bevel_depth` is the cheapest correct pipe/rope; convert to mesh
-so the exporter sees geometry. Radius 3–6 mm cables, 10–25 mm rails, 20–40 mm pipes.
-
-## Deformation (bend, taper, lattice)
-
-```python
-def bend(obj, angle_deg, axis='X'):
- """Bend a Z-long part (pipe elbow, bow, hook) AROUND `axis` (X or Y, perpendicular to
- its length). The bend starts at the OBJECT ORIGIN: put the origin at one end and
- give the mesh ≥ 16 rings along its length (make_cylinder(..., rings=24))."""
- d = obj.modifiers.new("Bend", 'SIMPLE_DEFORM'); d.deform_method = 'BEND'
- d.angle = math.radians(angle_deg); d.deform_axis = axis
- return d
-
-def taper(obj, factor=0.5, axis='Z'):
- d = obj.modifiers.new("Taper", 'SIMPLE_DEFORM'); d.deform_method = 'TAPER'
- d.factor = factor; d.deform_axis = axis
- return d
-
-def lattice_squash(obj, scale_xyz, points=3):
- """Free-form squash/stretch via a lattice fitted to the object's bbox."""
- lat = bpy.data.lattices.new(obj.name + "Lat")
- lat.points_u = lat.points_v = lat.points_w = points
- lo = link(bpy.data.objects.new(obj.name + "Lat", lat))
- lo.location = obj.location; lo.scale = obj.dimensions
- m = obj.modifiers.new("Lattice", 'LATTICE'); m.object = lo
- return lo, m
-
-pipe = make_cylinder("Elbow", 0.012, 0.20, (0.2, 0.2, 0.0), 24, rings=24)
-pipe.data.transform(Matrix.Translation((0, 0, 0.10))) # mesh now spans z 0..0.2 from the origin
-bend(pipe, 90, 'X'); apply_modifiers(pipe) # quarter-circle elbow, r ≈ 0.127
-```
-
-Why: SIMPLE_DEFORM bends relative to the object origin and needs ≥ 16 loops along the
-length; a centred origin gives a symmetric "C" (±angle/2), an end origin a clean arc.
-
-## Subdivision + creases (smooth organic parts with sharp seams)
-
-```python
-def crease_edges(obj, predicate, value=1.0):
- """Set crease on edges where predicate(v1, v2) is True (data attribute API, 4.x+)."""
- me = obj.data
- attr = me.attributes.get("crease_edge") or me.attributes.new("crease_edge", 'FLOAT', 'EDGE')
- for e, slot in zip(me.edges, attr.data):
- v1, v2 = me.vertices[e.vertices[0]].co, me.vertices[e.vertices[1]].co
- slot.value = value if predicate(v1, v2) else 0.0
-
-cushion = make_box("Cushion", (0.40, 0.40, 0.08), (0.6, 0, 0.04))
-crease_edges(cushion, lambda a, b: abs(a.z - b.z) < 1e-6 and a.z > 0.0) # keep the top rim crisp
-add_subsurf(cushion, 2); apply_modifiers(cushion); cushion.data.shade_smooth()
-```
-
-Why: a box + subsurf 2 + creases = cushion/pillow/soft shell in four lines; without the
-crease it becomes a blob.
-
-## Materials (Principled BSDF; flat PBR survives GLB export)
-
-GLB keeps ONLY base colour, metallic, roughness, emission, alpha and normal *textures*.
-Procedural node trees (noise, wave) are NOT exported — use them only for your own
-preview, and prefer flat PBR + geometry detail + vertex colours for anything judged.
-
-```python
-def make_pbr(name, rgb, roughness=0.5, metallic=0.0, emission=None, alpha=1.0):
- mat = bpy.data.materials.new(name) # node tree exists by default
- bsdf = mat.node_tree.nodes["Principled BSDF"]
- bsdf.inputs["Base Color"].default_value = (*rgb, 1.0)
- bsdf.inputs["Roughness"].default_value = roughness
- bsdf.inputs["Metallic"].default_value = metallic
- if emission:
- bsdf.inputs["Emission Color"].default_value = (*emission, 1.0)
- bsdf.inputs["Emission Strength"].default_value = 3.0
- if alpha < 1.0:
- bsdf.inputs["Alpha"].default_value = alpha
- mat.surface_render_method = 'BLENDED' # 4.2+; blend_method is gone
- return mat
-
-PALETTE = { # rgb 0-1 linear, roughness, metallic
- "oak": ((0.55, 0.36, 0.18), 0.55, 0.0),
- "walnut": ((0.28, 0.17, 0.09), 0.50, 0.0),
- "steel": ((0.62, 0.63, 0.65), 0.30, 1.0),
- "brass": ((0.83, 0.62, 0.28), 0.35, 1.0),
- "black_plastic": ((0.02, 0.02, 0.02), 0.45, 0.0),
- "white_ceramic": ((0.92, 0.92, 0.90), 0.15, 0.0),
- "fabric": ((0.35, 0.40, 0.55), 0.95, 0.0),
- "glass": ((0.85, 0.90, 0.95), 0.05, 0.0), # + alpha 0.25
- "rubber": ((0.05, 0.05, 0.05), 0.85, 0.0),
-}
-def assign(obj, key):
- rgb, rough, metal = PALETTE[key]
- obj.data.materials.append(make_pbr(f"{obj.name}_{key}", rgb, rough, metal))
-
-assign(body, "white_ceramic"); assign(handle, "white_ceramic"); assign(bottle, "glass")
-
-def vertex_color_by_height(obj, low_rgb, high_rgb, name="Col"):
- """Per-vertex colour gradient (exported to GLB as COLOR_0; set vertexColors in viewers)."""
- me = obj.data
- zs = [v.co.z for v in me.vertices]; z0, z1 = min(zs), max(zs) or 1e-6
- col = me.color_attributes.new(name, 'FLOAT_COLOR', 'POINT')
- for v, slot in zip(me.vertices, col.data):
- t = (v.co.z - z0) / max(z1 - z0, 1e-6)
- slot.color = tuple(a + (b - a) * t for a, b in zip(low_rgb, high_rgb)) + (1.0,)
-
-vertex_color_by_height(bottle, (0.2, 0.5, 0.2), (0.8, 0.9, 0.8))
-
-# procedural wood (preview-only; judge renders via GLB will show the flat base colour)
-def make_wood_nodes(name="WoodProcedural"):
- mat = bpy.data.materials.new(name); nt = mat.node_tree
- bsdf = nt.nodes["Principled BSDF"]
- wave = nt.nodes.new("ShaderNodeTexWave"); wave.inputs["Scale"].default_value = 40.0
- wave.inputs["Distortion"].default_value = 6.0
- ramp = nt.nodes.new("ShaderNodeValToRGB")
- ramp.color_ramp.elements[0].color = (0.45, 0.28, 0.13, 1); ramp.color_ramp.elements[1].color = (0.62, 0.42, 0.22, 1)
- nt.links.new(wave.outputs["Fac"], ramp.inputs["Fac"]); nt.links.new(ramp.outputs["Color"], bsdf.inputs["Base Color"])
- bsdf.inputs["Roughness"].default_value = 0.55
- return mat
-```
-
-Why: Principled inputs since 4.0 are named `"Specular IOR Level"`, `"Transmission Weight"`,
-`"Coat Weight"`, `"Sheen Weight"`, `"Emission Color"` + `"Emission Strength"` — the old
-`"Specular"`, `"Transmission"`, `"Emission"` keys raise KeyError.
-
-### Several colours on ONE mesh (`material_index`)
-
-The contract is one mesh object per plan part, so a black collar on a white arm is a
-per-FACE material, not a second object: the slots live on the mesh, the index on the
-polygon, and every polygon starts on slot 0 — append the base material FIRST.
-
-```python
-def add_slot(obj, mat):
- """Append a material to the mesh; returns the slot index you write per face."""
- obj.data.materials.append(mat)
- return len(obj.data.materials) - 1
-
-
-def new_faces(bm, op, **kw):
- """`create_cube`/`create_cone` return {'verts'} ONLY, so `res["faces"]` raises and
- `res.get("faces", [])` paints nothing — diff the face set instead."""
- before = set(bm.faces)
- op(bm, **kw)
- return set(bm.faces) - before
-
-
-bm = bmesh.new()
-new_faces(bm, bmesh.ops.create_cube, size=0.04) # the tube stays on slot 0
-for f in new_faces(bm, bmesh.ops.create_cube, size=0.06,
- matrix=Matrix.Translation((0, 0, 0.04))):
- f.material_index = 1 # the collar; BEFORE bm.to_mesh(me)
-arm = obj_from_bmesh("DemoTwoTone", bm, (3.0, 0, 0.05))
-add_slot(arm, make_pbr("DemoWhite", (0.88, 0.88, 0.86), 0.45)) # slot 0 = the default
-add_slot(arm, make_pbr("DemoBlack", (0.02, 0.02, 0.02), 0.5))
-for poly in arm.data.polygons: # same thing on a finished mesh;
- if poly.center.z > 0.03: # poly.center is in LOCAL space
- poly.material_index = 1
-```
-
-Slots without indices are the silent failure: every material is there, the part exports in
-one flat colour, and the judge caps the run for `untextured_flat`. The build census warns
-when a mesh carries slots no polygon uses — that warning means the assignment no-opped,
-not that a material is missing.
-
-## Structure: names, collections, parenting, instancing, join/separate
-
-```python
-def collection(name: str) -> bpy.types.Collection:
- col = bpy.data.collections.get(name)
- if col is None:
- col = bpy.data.collections.new(name); bpy.context.scene.collection.children.link(col)
- return col
-
-def move_to(obj, col):
- for c in list(obj.users_collection):
- c.objects.unlink(obj)
- col.objects.link(obj)
-
-def linked_copy(src: bpy.types.Object, name: str, location) -> bpy.types.Object:
- """Instance: shares mesh data (cheap, identical detail). Give each its own plan name."""
- o = bpy.data.objects.new(name, src.data)
- o.location = location; o.rotation_euler = src.rotation_euler; o.scale = src.scale
- return link(o)
-
-def join(objs, name: str) -> bpy.types.Object:
- """Join into the FIRST object (its transform wins); result renamed to `name`."""
- target = objs[0]
- bpy.ops.object.select_all(action='DESELECT')
- for o in objs:
- o.select_set(True)
- bpy.context.view_layer.objects.active = target
- bpy.ops.object.join()
- target.name = name
- return target
-
-def separate_loose(obj) -> list:
- """Split an object into its mesh islands (returns all resulting objects)."""
- before = set(bpy.data.objects)
- with bpy.context.temp_override(object=obj, active_object=obj, selected_objects=[obj],
- selected_editable_objects=[obj]):
- bpy.ops.object.mode_set(mode='EDIT'); bpy.ops.mesh.separate(type='LOOSE')
- bpy.ops.object.mode_set(mode='OBJECT')
- return [obj] + sorted(set(bpy.data.objects) - before, key=lambda o: o.name)
-
-legs = collection("Legs")
-leg0 = make_cylinder("Leg_0", 0.02, 0.42, (0.18, 0.18, 0.21), 16)
-for i, (sx, sy) in enumerate([(-1, 1), (-1, -1), (1, -1)], start=1):
- linked_copy(leg0, f"Leg_{i}", (sx * 0.18, sy * 0.18, 0.21))
-for o in bpy.data.objects:
- if o.name.startswith("Leg"): move_to(o, legs)
-```
-
-Why: use COLLECTIONS for organisation (they are not exported as nodes). **Never parent
-parts or instances under an Empty**: the harness measures top-level GLB nodes as parts, so
-an Empty parent merges its whole subtree into ONE part (plan part reported missing) — and an
-empty with non-identity scale also skews the baked world transforms. `join()` inherits
-the ACTIVE object's transform; make the largest/identity object active.
-
-## Proportions and detail (how to look good cheaply)
-
-| feature | recipe | size |
-|---|---|---|
-| rounded edges | `add_bevel(width=t/4, segments=2–3)` | furniture 2–4 mm, devices 0.5–1 mm, vehicles 5–15 mm |
-| chamfer | bevel `segments=1` | 1–3 mm |
-| panel seam / gap | boolean-cut a 1 mm × 2 mm groove, or build panels 1 mm apart | 0.8–1.5 mm |
-| inset panel | `bmesh.ops.inset_region(thickness=…, depth=−…)` on the face | inset 5–10 mm, depth 1–3 mm |
-| fillet at a joint | small torus/cylinder collar overlapping both parts | r 3–8 mm |
-| fasteners | `make_cylinder(r=2–4 mm, depth=1–2 mm)` pressed 0.5 mm into the surface, arrayed | head Ø 5–8 mm |
-| rims / lips | lathe profile with a 2 mm bump | |
-| feet / glides | short cylinders Ø 15–25 mm, h 5–10 mm, under each leg | |
-| handles / knobs | torus or lathe, overlapping the panel ≥ 2 mm | knob Ø 25–35 mm |
-| cushions | box + subsurf 2 + creases + scale 0.98 | 60–120 mm thick |
-| spokes / slats / louvres | one part + `add_array` or a polar loop of `linked_copy` | slat 10–15 mm thick |
-
-```python
-def inset_top(obj, thickness=0.008, depth=-0.002):
- """Recessed top panel: inset the +Z face (bmesh on the real mesh)."""
- bm = bmesh.new(); bm.from_mesh(obj.data)
- bm.faces.ensure_lookup_table()
- top = max(bm.faces, key=lambda f: f.calc_center_median().z)
- bmesh.ops.inset_region(bm, faces=[top], thickness=thickness, depth=depth, use_even_offset=True)
- bm.to_mesh(obj.data); bm.free(); obj.data.update()
-
-def polar_copies(src, n, radius, center, name_fmt="{base}{i}"):
- """src + n-1 linked copies evenly on a circle (bolts, spokes, chair legs).
- center=(cx, cy, z); copies are named <Base>2..N, src itself is moved to slot 1."""
- cx, cy, z = center
- base = src.name.rstrip("0123456789")
- out = [src]
- for i in range(n):
- a = 2 * math.pi * i / n
- loc = (cx + radius * math.cos(a), cy + radius * math.sin(a), z)
- o = src if i == 0 else linked_copy(src, name_fmt.format(base=base, i=i + 1), loc)
- o.location = loc; o.rotation_euler.z = a
- if i: out.append(o)
- return out
-
-lid = make_box("Lid", (0.30, 0.20, 0.012), (0.9, 0, 0.306))
-inset_top(lid, 0.01, -0.002); add_bevel(lid, 0.002, 2); apply_modifiers(lid)
-bolt = make_cylinder("Bolt1", 0.003, 0.002, (0, 0, 0), 12)
-polar_copies(bolt, 6, 0.06, (0.9, 0, 0.3125)) # 6 bolt heads on a Ø 0.12 circle, sunk 0.5 mm into the lid
-```
-
-Rules of thumb: a silhouette needs ≥ 3 distinct masses; every large flat face needs one
-break (seam, inset, bevel, trim); thin things (blades, sheet, glass) are 1–3 mm, never 0;
-every part that a human would touch has a rounded edge.
-
-## Density: visual complexity without hand-modelling every screw
-
-Measured on this harness (183 judged rounds): **triangles inside a part are free score, extra
-top-level parts are not** — ρ(tri_per_part, geometry_detail) ≈ +0.08 while ρ(n_plan_parts,
-assembly_fit) = −0.48. Every recipe below adds density *inside* a part the plan already names.
-
-**Where the detail goes.** A viewer (and the judge's montage) looks, in order, at the
-silhouette, then the 2–3 largest faces, then whatever is at eye height and at the front, then the
-places where two materials meet. Spend there and stop.
-
-| priority | what | typical tri cost | recipe |
-|---|---|---|---|
-| 1 | silhouette breaks (taper, waist, overhang) | 0 (shape the primitive) | `taper`, `lathe`, profile sweep |
-| 2 | bevel every hard edge | ×2–3 verts on that part | `add_bevel(w, 2–3)` |
-| 3 | panel lines / shut lines on big faces | 200–600 | `panel_lines` |
-| 4 | fasteners at real joints | 60–200 each | `polar_copies`, `bolt_ring` |
-| 5 | repeated countable features (slats, spokes, dentils) | 100–400 each | `add_array`, `radial_array` |
-| 6 | greebles in a bounded patch | 300–1500 | `greeble_patch` |
-| 7 | wear/variation in materials | 0 | per-instance material tint |
-
-Do **not** spend budget on: the underside, the back of a wall-mounted object, interior volumes the
-camera cannot enter, or subdividing a flat panel.
-
-### Parametric repetition (one part, N features, one loop)
-
-```python
-def radial_array(obj, count, *, center=(0.0, 0.0), axis='Z'):
- """`count` copies of `obj` around `center` — ONE mesh, one modifier, N features.
- Spokes, dentils, flutes, cage wires, balusters, turbine blades.
- The Empty is a construction aid: it is applied and deleted here, so no non-mesh
- object ever reaches the export (the contract allows meshes only)."""
- piv = bpy.data.objects.new(f"{obj.name}_Pivot", None)
- piv.location = (center[0], center[1], 0.0)
- piv.rotation_euler['XYZ'.index(axis)] = 2 * math.pi / count
- link(piv)
- m = obj.modifiers.new("Radial", 'ARRAY')
- m.count, m.use_relative_offset, m.use_object_offset, m.offset_object = count, False, True, piv
- apply_modifiers(obj)
- bpy.data.objects.remove(piv, do_unlink=True)
- return obj
-
-
-def flutes(obj, count, radius, depth, height, z0, *, center=(0.0, 0.0), segments=8):
- """`count` vertical grooves cut into a cylindrical body of radius `radius` standing on
- `center` (pump bodies, columns, knurled knobs, fluted table legs)."""
- cutter = make_cylinder(f"{obj.name}_Flute", depth, height,
- (center[0] + radius, center[1], z0 + height / 2), segments)
- radial_array(cutter, count, center=center)
- boolean_cut(obj, cutter) # boolean_cut applies and deletes the cutter
- return obj
-
-
-# 24 spokes on a wheel, then 8 flutes cut into a column — two loops, two modifiers
-spoke = make_cylinder("DemoSpoke", 0.004, 0.30, (0.0, 0.0, 0.15), 8)
-radial_array(spoke, 24)
-column = make_cylinder("DemoColumn", 0.045, 0.60, (0.0, 0.0, 0.30), 48)
-flutes(column, 8, 0.045, 0.006, 0.55, 0.03)
-assert len(column.data.vertices) > 96, "the flutes did not cut: is the cutter overlapping the body?"
-```
-
-### Instancing with per-instance variation
-
-Linked copies share mesh data (free memory, free triangles in Blender's sense) but they may
-differ in transform and material. Identical repeats read as CG; 2–5 % variation reads as real.
-
-```python
-def varied_copies(src, n, place, *, seed=0, jitter_m=0.0, tilt_deg=0.0, scale_pct=0.0, mats=None):
- """n named copies of `src` (`Name_0..Name_{n-1}`), each with a seeded wobble.
- `place(i) -> (x, y, z)`; the copies stay TOP-LEVEL (never parented to an Empty)."""
- rnd = random.Random(seed)
- base = src.name
- out = []
- for i in range(n):
- o = src if i == 0 else linked_copy(src, f"{base}_{i}", (0, 0, 0))
- x, y, z = place(i)
- o.name = f"{base}_{i}"
- o.location = (x + rnd.uniform(-jitter_m, jitter_m), y + rnd.uniform(-jitter_m, jitter_m), z)
- o.rotation_euler = (math.radians(rnd.uniform(-tilt_deg, tilt_deg)),
- math.radians(rnd.uniform(-tilt_deg, tilt_deg)), o.rotation_euler.z)
- s = 1.0 + rnd.uniform(-scale_pct, scale_pct) / 100.0
- o.scale = (s, s, s)
- if mats:
- o.data = o.data.copy() # break the link ONLY to vary the material slot
- o.data.materials.clear()
- o.data.materials.append(mats[i % len(mats)])
- out.append(o)
- return out
-
-
-slat = make_box("DemoSlat", (0.30, 0.012, 0.05), (0, 0, 0))
-slats = varied_copies(slat, 7, lambda i: (0.0, 0.0, 0.10 + 0.07 * i), seed=3, jitter_m=0.0008,
- tilt_deg=0.6, scale_pct=1.5)
-assert [o.name for o in slats] == [f"DemoSlat_{i}" for i in range(7)]
-assert len({tuple(round(v, 5) for v in o.location) for o in slats}) == 7 # really varied
-```
-
-### Procedural greebles, bounded to a region
-
-Greebles are surface clutter (vents, boxes, ribs) that reads as machinery. Bound them to a patch
-so they never break the silhouette or the part's plan bbox.
-
-```python
-def greeble_patch(name, origin, size_xy, *, n=24, seed=0, h_range=(0.002, 0.010),
- cell=0.02, material=None):
- """One mesh of `n` seeded boxes inside an (x, y) patch at z=origin[2], heights in
- `h_range`. Join it INTO the host part afterwards so it stays one named object."""
- rnd = random.Random(seed)
- bm = bmesh.new()
- sx, sy = size_xy
- for _ in range(n):
- w = rnd.uniform(cell * 0.35, cell * 1.4)
- d = rnd.uniform(cell * 0.35, cell * 1.4)
- h = rnd.uniform(*h_range)
- cx = rnd.uniform(-sx / 2 + w / 2, sx / 2 - w / 2)
- cy = rnd.uniform(-sy / 2 + d / 2, sy / 2 - d / 2)
- m = Matrix.Translation((cx, cy, h / 2 - 0.0005)) @ Matrix.Diagonal((w, d, h, 1.0))
- bmesh.ops.create_cube(bm, size=1.0, matrix=m)
- obj = obj_from_bmesh(name, bm, origin)
- if material is not None:
- obj.data.materials.append(material)
- return obj
-
-
-host = make_box("DemoHousing", (0.24, 0.16, 0.10), (0.6, 0, 0.05))
-greebles = greeble_patch("DemoHousing_Greebles", (0.6, 0, 0.10), (0.20, 0.12), n=26, seed=7)
-housing = join([host, greebles], "DemoHousing") # ONE named part, 26 extra shapes of detail
-assert len(housing.data.polygons) == 6 + 26 * 6, "greebles were not joined into the host part"
-```
-
-### Profile sweeps (a section dragged along a path)
-
-The cheapest way to make mouldings, handrails, rims, tubing and cornices look machined: draw the
-*section* once, sweep it along the path.
-
-```python
-def sweep_profile(name, path_pts, profile_pts, *, closed_path=False, tilt_deg=0.0, resolution=6):
- """Sweep a 2-D `profile_pts` [(x, y) in the section plane] along `path_pts` [(x, y, z)]
- using a curve bevel object — cornices, handrails, rims, picture frames, gutters."""
- prof = bpy.data.curves.new(f"{name}_Prof", 'CURVE')
- prof.dimensions = '2D'
- sp = prof.splines.new('POLY')
- sp.points.add(len(profile_pts) - 1)
- for p, (x, y) in zip(sp.points, profile_pts):
- p.co = (x, y, 0.0, 1.0)
- sp.use_cyclic_u = True
- cu = bpy.data.curves.new(f"{name}_Path", 'CURVE')
- cu.dimensions = '3D'
- cu.bevel_mode, cu.bevel_object, cu.resolution_u = 'OBJECT', bpy.data.objects.new(f"{name}_ProfObj", prof), resolution
- bpy.context.scene.collection.objects.link(cu.bevel_object)
- ps = cu.splines.new('POLY')
- ps.points.add(len(path_pts) - 1)
- for p, (x, y, z) in zip(ps.points, path_pts):
- p.co = (x, y, z, 1.0)
- ps.use_cyclic_u = closed_path
- obj = bpy.data.objects.new(name, cu)
- link(obj)
- activate(obj)
- bpy.ops.object.convert(target='MESH')
- obj = bpy.context.object
- bpy.data.objects.remove(bpy.data.objects[f"{name}_ProfObj"], do_unlink=True)
- return obj
-
-
-CORNICE = [(0.0, 0.0), (0.045, 0.0), (0.045, 0.012), (0.030, 0.020), (0.030, 0.032), (0.0, 0.032)]
-cornice = sweep_profile("DemoCornice", [(-0.6, -0.3, 0.9), (0.6, -0.3, 0.9), (0.6, 0.3, 0.9), (-0.6, 0.3, 0.9)],
- CORNICE, closed_path=True)
-
-# a curved path needs SAMPLES: one point per 5-10 degrees, not four corners.
-HANDRAIL = [(0.045, 0.0), (0.020, 0.018), (-0.020, 0.018), (-0.045, 0.0), (0.0, -0.012)]
-helix = [(0.70 * math.cos(math.radians(a)), 0.70 * math.sin(math.radians(a)), 0.95 + 0.0075 * a)
- for a in range(0, 365, 5)]
-rail = sweep_profile("DemoHandrail", helix, HANDRAIL)
-assert len(cornice.data.polygons) >= 24 and len(rail.data.polygons) >= 300, "sweep produced no surface"
-```
-
-### Boolean detailing (grooves, slots, holes — in one cut)
-
-Build ALL cutters of one kind as a single mesh, then cut once: `n` booleans cost `n` evaluations
-and `n` chances to produce non-manifold garbage; one cutter costs one.
-
-```python
-def panel_lines(obj, lines, *, width=0.0015, depth=0.0015):
- """Cut shut-lines into a body. `lines` = [(center_xyz, size_xyz)] in world metres —
- make one thin box per line, join them, cut once."""
- bm = bmesh.new()
- for (cx, cy, cz), (sx, sy, sz) in lines:
- m = Matrix.Translation((cx, cy, cz)) @ Matrix.Diagonal(
- (max(sx, width), max(sy, width), max(sz, depth), 1.0))
- bmesh.ops.create_cube(bm, size=1.0, matrix=m)
- boolean_cut(obj, obj_from_bmesh(f"{obj.name}_Lines", bm))
- return obj
-
-
-def bolt_ring(obj, n, radius, center, *, head_r=0.004, head_h=0.0015, seg=12):
- """n bolt heads standing 1.5 mm proud on a circle, joined INTO `obj` (one part)."""
- cx, cy, cz = center
- bm = bmesh.new()
- for i in range(n):
- a = 2 * math.pi * i / n
- m = Matrix.Translation((cx + radius * math.cos(a), cy + radius * math.sin(a), cz))
- bmesh.ops.create_cone(bm, cap_ends=True, segments=seg, radius1=head_r, radius2=head_r * 0.9,
- depth=head_h, matrix=m)
- heads = obj_from_bmesh(f"{obj.name}_Bolts", bm)
- return join([obj, heads], obj.name)
-
-
-door = make_box("DemoDoor", (0.42, 0.018, 0.36), (1.2, 0, 0.18))
-panel_lines(door, [((1.2, -0.009, 0.36), (0.42, 0.004, 0.0015)),
- ((1.2, -0.009, 0.00), (0.42, 0.004, 0.0015))])
-door = bolt_ring(door, 6, 0.10, (1.2, -0.010, 0.18))
-assert len(door.data.polygons) > 6, "the panel lines / bolts did not land on the door"
-```
-
-### Bevel / solidify / weighted-normal stacks (sheet metal and cast parts)
-
-```python
-def shade_smooth(obj):
- """Smooth shading on the MESH (4.1+ removed `use_auto_smooth`; a Smooth-by-Angle
- modifier is what the UI now adds, and the GLB exporter bakes its normals)."""
- for poly in obj.data.polygons:
- poly.use_smooth = True
- return obj
-
-
-def sheet_metal(obj, *, thickness=0.0012, bevel=0.0008, segments=2):
- """Give a slab or zero-thickness shape a real sheet-metal read: wall, rounded edge,
- shading that follows the bevel. Order matters — solidify BEFORE bevel."""
- add_solidify(obj, thickness, inward=False)
- add_bevel(obj, bevel, segments)
- wn = obj.modifiers.new("WeightedNormal", 'WEIGHTED_NORMAL') # keeps the bevel crisp
- wn.keep_sharp = True
- return shade_smooth(obj)
-
-
-def cast_part(obj, *, fillet=0.004, segments=3):
- """Cast/moulded read: one generous fillet on every edge, smooth shading, no sharp corners."""
- add_bevel(obj, fillet, segments)
- return shade_smooth(obj)
-
-
-tray = make_box("DemoTray", (0.26, 0.18, 0.004), (1.8, 0, 0.002))
-sheet_metal(tray)
-housing = make_box("DemoCastHousing", (0.12, 0.09, 0.07), (2.2, 0, 0.035))
-cast_part(housing)
-```
-
-### The density check
-
-Before you finish, ask of each part: *what would tell a photograph of the real thing from this?*
-If the answer is "the edges are perfectly sharp" → bevel. "It is one flat face" → panel line or
-inset. "It has no fixings" → bolt ring. "The repeats are identical" → `varied_copies`. "It is
-all one grey" → split the materials, per face if it is one part (`material_index`, above). Then measure: `measure` reports the triangle count — compare
-it part by part with what the density table adds.
-
-## Common objects — dimensions (metres) and decomposition
-
-| object | overall (W × D × H) | parts (plan names) | key numbers |
-|---|---|---|---|
-| dining chair | 0.45 × 0.50 × 0.90 | Seat, Backrest, LegFrontLeft/Right, LegBackLeft/Right, Stretchers | seat h 0.45, seat t 0.04, leg Ø/□ 0.035, back top 0.90, back rake 8° |
-| armchair / sofa seat | 0.85 × 0.90 × 0.85 (sofa W 1.8–2.2) | Base, SeatCushion(s), BackCushion(s), ArmLeft, ArmRight, Legs | seat h 0.42, cushion 0.10–0.12, arm h 0.60, arm w 0.15–0.25 |
-| dining table | 1.6 × 0.9 × 0.75 | Top, Apron, Leg ×4 | top t 0.03–0.04, leg 0.07 □ at 0.05 inset |
-| coffee table | 1.2 × 0.6 × 0.45 | Top, Leg ×4 or Base | top t 0.025 |
-| desk lamp | 0.18 Ø base, H 0.45–0.60 | Base, ArmLower, ArmUpper, Shade, Bulb | base t 0.02, arm Ø 0.012, shade Ø 0.15 h 0.12 |
-| floor lamp | 0.30 Ø base, H 1.6 | Base, Pole, Shade | pole Ø 0.025, shade Ø 0.40 |
-| mug | Ø 0.085 × 0.095 | MugBody, MugHandle | wall 4 mm, bottom 6 mm, handle tube Ø 12 mm |
-| bottle (wine) | Ø 0.075 × 0.30 | Body, Neck, Cap | neck Ø 0.028, shoulder at 0.20 |
-| bicycle | 1.75 × 0.60 × 1.05 | Frame, FrontWheel, RearWheel, Fork, Handlebar, Saddle, SeatPost, Crank, PedalLeft/Right, Chain | wheel Ø 0.70 (700c), tyre w 0.03, BB height 0.27, saddle h 0.95 |
-| car (sedan) | 4.6 × 1.85 × 1.45 | Body, Cabin(glass), WheelFL/FR/RL/RR, Bumpers, Mirrors, Lights | wheel Ø 0.65, wheelbase 2.7, ground clearance 0.15 |
-| house (small) | 10 × 8 × 7 | Walls, Roof, Door, Windows, Chimney, Steps | wall h 2.8/storey, roof pitch 30–40°, door 0.9 × 2.1, window 1.2 × 1.2 at sill 0.9 |
-| tree (deciduous) | crown Ø 6–9, H 10–14 | Trunk, Branches, Crown(s) | trunk Ø 0.4 at base, first branch at 2.5, crown = 3–6 overlapping spheres |
-| door | 0.9 × 0.045 × 2.05 | Leaf, Frame, Handle, Hinges | handle h 1.05, frame 0.07 wide |
-| bookshelf | 0.80 × 0.30 × 1.80 | SideLeft, SideRight, Top, Bottom, Shelf ×4, Back | panel 18 mm, shelf pitch 0.33 |
-| kitchen cabinet | 0.60 × 0.58 × 0.87 | Carcass, Door(s)/Drawer(s), Handle(s), Plinth | plinth h 0.10, front 18 mm, handle proud 30 mm |
-| monitor | 0.62 × 0.20 × 0.45 | Panel, Stand, Base | panel t 0.02, bezel 8 mm, base 0.25 × 0.20 |
-| keyboard | 0.44 × 0.14 × 0.03 | Body, Keys(instanced) | key 0.018 pitch 0.019 |
-
-Decomposition recipe (any object): 1 main mass → 2–6 secondary masses that TOUCH it →
-attachments (handles, feet, trim) that overlap ≥ 2 mm → detail pass (bevels, seams,
-fasteners). Name every mass as the plan does; instances by `linked_copy`.
-
-## Keyframed motion for a scene hero (the harness exports it as a glTF clip)
-
-A scene hero may carry ONE 2 s loop (24 fps, frames 1–49, ends where it starts); the
-scene plays it by itself. Keyframe the moving object's OWN transform, and build that
-object's mesh AROUND ITS PIVOT so the rotation happens where the hinge is — an object whose
-origin sits at its centre swings about its centre, and the sails fly off the hub.
-
-```python
-import bpy, bmesh, math
-from mathutils import Matrix
-
-def build_sail_rotor() -> bpy.types.Object:
- """Four lattice sails on a hub; the mesh is centred on the hub axis so rotation is about it."""
- bm = bmesh.new()
- for i in range(4): # sails built AROUND (0, 0, 0)
- a = i * math.pi / 2
- sail = bmesh.new()
- bmesh.ops.create_cube(sail, size=1.0)
- sail.transform(Matrix.Diagonal((11.0, 0.15, 1.6, 1.0))) # a lattice sail, 11 m long
- sail.transform(Matrix.Translation((5.5, 0.0, 0.0))) # out from the hub
- sail.transform(Matrix.Rotation(a, 4, "Y")) # around the hub axis
- me_s = bpy.data.meshes.new("_sail"); sail.to_mesh(me_s); sail.free()
- bm.from_mesh(me_s); bpy.data.meshes.remove(me_s)
- me = bpy.data.meshes.new("SailRotor"); bm.to_mesh(me); bm.free()
- rotor = bpy.data.objects.new("SailRotor", me)
- rotor.location = (0.0, -3.2, 18.0) # the HUB's world position = the pivot
- bpy.context.scene.collection.objects.link(rotor)
- sc = bpy.context.scene; sc.frame_start, sc.frame_end = 1, 49
- for frame, ang in ((1, 0.0), (25, math.pi / 4), (49, math.pi / 2)): # a quarter turn: 4 sails loop seamlessly
- rotor.rotation_euler = (0.0, ang, 0.0) # about the hub axis (-Y is the front: the axis is Y here)
- rotor.keyframe_insert("rotation_euler", index=1, frame=frame)
- return rotor
-```
-
-* Keep the moving part a normal named MESH object (no Empty pivots — an Empty is not a
- part and the census counts it as junk); parent nothing to it.
-* A loop of a quarter turn for 4-fold sails, a half turn for 2-fold, a full turn for a
- wheel; a swing goes −a → +a → −a. Amplitude must read at scene distance (≥ 0.15 rad or
- ≥ 0.05 m); the scene samples t = 0 and t = 1.5 s.
-* Linear interpolation for a wheel (`kp.interpolation = 'LINEAR'` on the fcurve's
- keyframe points) so it does not ease at the loop seam.
-
-## Pitfalls (symptom → cause → fix)
-
-1. **`bm.verts[i]` raises "outdated internal index table"** → call
- `bm.verts.ensure_lookup_table()` (also `edges`/`faces`) after `from_mesh` or any
- topology op before indexing.
-2. **"context is incorrect" / poll() failed in background** → the operator needs an active +
- selected object or edit mode: use `activate(obj)` or `bpy.context.temp_override(...)`
- as in `apply_modifiers`; prefer data API (`bmesh`, `me.transform`) over `bpy.ops`.
-3. **`bpy.ops.object.transform_apply(scale=True)` moved my part to the origin** → the other
- flags default True and baked location. Always pass `location=, rotation=, scale=`
- explicitly (see `apply_transforms`).
-4. **Modifier apply fails "Modifier cannot be applied to a multi-user mesh"** →
- `obj.data = obj.data.copy()` first (`apply_modifiers` does it).
-5. **Names like `Leg.001`** → you created two objects/meshes with the same name; give every
- instance its plan name (`Leg_2`); rename meshes too if you care (`o.data.name = o.name`).
-6. **Boolean does nothing / leaves holes** → cutter coplanar with a face or not closed.
- Overshoot the cutter by ≥ 5 mm, make it watertight (`cap_ends=True`), use `EXACT`.
-7. **Dark/inverted shading, inside-out parts** → flipped normals after `bmesh.ops.scale`
- with negative factors or after mirroring: `bmesh.ops.recalc_face_normals(bm, faces=bm.faces)`
- or `bpy.ops.mesh.normals_make_consistent` in edit mode.
-8. **`mesh.use_auto_smooth` AttributeError** (removed 4.1) → `obj.data.shade_smooth()` then
- `bpy.ops.object.shade_smooth_by_angle(angle=math.radians(30))` under `temp_override`.
-9. **`bsdf.inputs["Specular"]` KeyError** → 4.x names: `"Specular IOR Level"`,
- `"Transmission Weight"`, `"Emission Color"`/`"Emission Strength"`, `"Coat Weight"`.
-10. **`mat.use_nodes = True`** is deprecated in 5.x (removed in 6.0) — every new material, world
- and light already has a node tree; never write it.
-11. **Object scaled with `obj.scale` looks right but exports wrong / bevels uneven** → bake
- with `apply_transforms(obj)` before bevel/boolean; keep scale (1,1,1) on export.
-12. **`bpy.ops.mesh.primitive_cube_add(size=1, scale=(…))`** — default size is 2 m; with
- `scale=` and `size=1` you get exact extents, but still bake the scale afterwards.
-13. **Degenerate geometry** (zero-area faces, zero-thickness walls, coincident faces of two
- parts) → z-fighting and boolean failures. Offset coincident faces by 0.5 mm or overlap
- parts by 2 mm; remove doubles `bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-5)`.
-14. **Units**: the scene is in meters; a 450 mm seat is `0.45`, never `450`. If you see a
- bbox of 450 × 500 × 900 the plan numbers were typed in mm.
-15. **`bpy.context.object` is None in background** → do not rely on it; keep your own refs.
-16. **Gone in 5.2 (do not use)**: `mesh.calc_normals()`, `mesh.calc_normals_split()`,
- `edge.crease` / `edge.bevel_weight` (use attributes `crease_edge`, `bevel_weight_edge`),
- `bpy.ops.*({'object': o})` dict overrides, `mat.blend_method`, `scene.node_tree`,
- `BLENDER_EEVEE_NEXT` (5.x is `BLENDER_EEVEE`), `bgl`, `gpu.types.GPUShader(...)`,
- the boolean solver `'FAST'` (now `'FLOAT'`; prefer `'MANIFOLD'` / `'EXACT'`), and
- geometry-nodes inputs by item access — `mod["Socket_2"] = v` raises TypeError in 5.2:
- `getattr(mod.properties.inputs, "Socket_2").value = v` (identifiers:
- `mod.properties.inputs.keys()`).
-17. **`bmesh.ops.create_cone` with `radius2=0`** makes a cone with a degenerate cap — fine
- for visuals; for booleans use `radius2=1e-4`.
-18. **A curve object left un-converted** exports nothing (the harness converts meshes
- only) → always `convert(target='MESH')` as in `make_tube_along`.
-19. **Huge scripts / per-vertex Python loops over big meshes** time out → use modifiers,
- `foreach_set`, or fewer segments.
-20. **Parenting with scaled parents** → children inherit scale; export bakes it, bevels go
- elliptical. Do not parent parts at all — an Empty parent also merges its children into
- ONE measured part (plan part reported missing); group with collections instead.
-21. **`ModuleNotFoundError: No module named 'parts.seat_cushion'`** → the part file must be
- `src/parts/seat_cushion.py` (snake_case of the plan name); `src/` is on `sys.path`, do
- not add path hacks. **`ImportError: cannot import name 'build_x'`** → the part file must
- define exactly `def build_<snake>()`.
-22. **A part appears twice (`Seat.001`)** → the part file calls `build_seat()` at module level
- AND model.py calls it. Part files only define; model.py calls each builder once.
-
-## Self-check (before you call it done)
-
-```python
-def selfcheck(expected_names, bbox_hint=None, tol=0.01):
- """Print a census the way the harness measures it; raise on contract violations."""
- bpy.context.view_layer.update()
- meshes = [o for o in bpy.data.objects if o.type == 'MESH']
- names = sorted(o.name for o in meshes)
- missing = [n for n in expected_names if n not in names]
- extra = [n for n in names if n not in expected_names]
- assert not missing, f"missing parts: {missing}"
- assert not extra, f"unexpected objects: {extra}"
- assert all('.' not in n for n in names), f"auto-suffixed names: {[n for n in names if '.' in n]}"
- lo = Vector((min(world_bbox(o)[0].x for o in meshes), min(world_bbox(o)[0].y for o in meshes),
- min(world_bbox(o)[0].z for o in meshes)))
- hi = Vector((max(world_bbox(o)[1].x for o in meshes), max(world_bbox(o)[1].y for o in meshes),
- max(world_bbox(o)[1].z for o in meshes)))
- assert abs(lo.z) < tol, f"lowest point z={lo.z:.4f}, expected 0"
- tris = sum(sum(len(p.vertices) - 2 for p in o.data.polygons) for o in meshes)
- print(f"[selfcheck] parts={len(meshes)} tris={tris} extents={tuple(round(v, 3) for v in (hi - lo))}")
- if bbox_hint:
- for a, b in zip(hi - lo, bbox_hint):
- assert abs(a - b) < 0.05, f"extents {tuple(hi - lo)} vs plan {bbox_hint}"
-
-# (the demo objects above are not one coherent object, so only run the census part here)
-print(len([o for o in bpy.data.objects if o.type == 'MESH']), "mesh objects")
-```
-
-Then use the tools: `build` → `render_sheet` → `check_connectivity` → `isolate` the part
-you doubt → `cross_section` through cavities → `check_contract`. Fix the worst finding,
-rebuild, repeat. Done = all green and the sheet reads as the object from every view.
diff --git a/harness/codeverse3d/prompts/blender/system.md b/harness/codeverse3d/prompts/blender/system.md
index b586cb1d..0a633f6b 100644
--- a/harness/codeverse3d/prompts/blender/system.md
+++ b/harness/codeverse3d/prompts/blender/system.md
@@ -26,28 +26,28 @@ What the gates name, measured over 265 recorded runs of this exact track:
* **Interpenetration** — the single most common defect by a wide margin (1,351 findings).
Two parts are allowed to overlap by **≤ 2 mm**; that is the welding allowance, not a
budget to spend. A leg sunk 8 mm into a seat is not "attached", it is a modelling error
- the gate measures in millimetres. Place a part by computing where its face lands, not by
- nudging it until it looks joined.
+ the gate measures in millimetres; a flush face is contact.
* **Stray islands** (963 findings) — "part 'X' contains N tiny disconnected islands".
- A boolean that missed, a mirror that duplicated, a stray vertex left at the origin.
- Every part must be one connected shell. Delete the fragment; do not ship it.
+ No island inside a part may be smaller than 5 % of that part's largest extent
+ (`check_connectivity`, WARN); a boolean leftover, a stray vertex at the origin or an
+ un-merged mirror half is what trips it. Delete the fragment; do not ship it.
* **Bbox deviates from the plan** (312 findings) — you wrote the plan's numbers, then built
- something else. The plan is a contract with yourself. If a dimension turns out wrong for
- the object, change the plan and say so; do not quietly build a different size.
+ something else. If a dimension turns out wrong for the object, keep the plan's value and
+ say why in a comment (the harness contract); do not quietly build a different size.
Rules that survive every brief:
-* **Author in world units, metres, at real scale.** A chair is 0.45 m to the seat, not 45.
- Set dimensions by computing vertex positions or by scaling a primitive of known size —
- never by eyeballing a scale factor.
+* **Author in world units, metres, at real scale.** A measured bbox in the hundreds means
+ the plan's numbers were typed in millimetres.
* **Name every object exactly as the plan names it**, and give it nothing else: no
`.001` duplicates, no leftover `Cube`, no empties. The gates match on names.
* **You place the object; the harness exports it as authored.** It never re-centres or
- grounds it and measures where you put it, so seating the whole assembly on the ground
- yourself (the cookbook's `drop_to_ground`) is fine — a helpful `origin_set` is not: it
- destroys the thing being measured.
-* **Build parts as separate objects**, joined only where the plan says they are one part.
- A single merged mesh cannot be checked, cannot be isolated, and scores worse.
+ grounds it and measures where you put it: translating the whole assembly so its lowest
+ vertex is at z = 0 is fine; moving object origins (`bpy.ops.object.origin_set`) changes
+ what is measured.
+* **One top-level mesh object per plan part**, joined only where the plan says they are one
+ part: `check_contract` matches on names, so a merged mesh reports every other part missing
+ and cannot be isolated or measured on its own.
A clean simpler object beats a richer one carrying a visible defect. Clear the two gates
first, then spend what is left on the detail the brief actually asked for.
diff --git a/harness/codeverse3d/prompts/cadquery/contract.md b/harness/codeverse3d/prompts/cadquery/contract.md
index 20e10483..96aea6fd 100644
--- a/harness/codeverse3d/prompts/cadquery/contract.md
+++ b/harness/codeverse3d/prompts/cadquery/contract.md
@@ -1,81 +1,96 @@
# CadQuery authoring contract — track `static_object`, language `cadquery`
## Files
-* `src/model.py` — ONE script, `import cadquery as cq` (+ stdlib `math`). The harness
- imports it in a subprocess and reads the module-level variable **`result`**.
- It exports STEP + STL per part and a GLB with one named node per part. You never
- export, print to files, or call `show_object`.
+* `src/model.py` is the entry. The harness runs it in a subprocess (`src/` first on
+ `sys.path`, so a helper module beside it imports) and reads the module-level variable
+ **`result`**. It exports STEP + STL and a GLB with one named node per part. You never
+ export, write files, print to files, or call `show_object`.
## `result`
-* Preferred: `result = cq.Assembly(name="<ObjectName>")` with one `assy.add(solid,
- name="<PartName>", color=cq.Color(r, g, b), loc=cq.Location(...))` per plan part.
- Part names PascalCase, unique, exactly as in the plan.
-* Allowed for a single-part object: `result = <cq.Workplane>` (one solid).
+* `result = cq.Assembly(name="<ObjectName>")` with one `.add(solid, name="<PartName>",
+ color=cq.Color(r, g, b), loc=cq.Location(...))` per plan part. Part names PascalCase,
+ unique (they become the GLB node names), exactly as in the plan; instances
+ `Name_0..Name_N-1`. `cq.Color` takes 0–1 floats. Assemblies nest; a child's `loc`
+ composes with its parent's.
+* A bare `result = <cq.Workplane>` builds (one solid, exported as the node `Object`), with a
+ lint WARN and a build warning: the plan's part names are then not in the GLB.
* `result` must exist at import time (module level, NOT under `if __name__ == "__main__"`).
+* Each part is a solid. A chain that ends on a selector (`.faces(">Z")`, `.edges("|Z")`)
+ exports the parent solid with a build warning; with no recoverable solid the build
+ errors naming the stack types. A bare `cq.Face` added to the assembly is flagged
+ "contains no solid".
-## Frame, units, placement
-* **Z up, -Y front, +X right, meters** (the harness converts to Y-up GLB). Author each
- part in world coordinates (leave `loc` identity) OR author at the origin and place with
- `loc=cq.Location(cq.Vector(x, y, z))` — pick one style per file.
-* Lowest point at z = 0, footprint centred on Z. Real-world dimensions.
-* Angles: `.rotate(p0, p1, deg)` and `cq.Location(v, axis, deg)` take **degrees**; `math`
- functions take radians.
+## Frame, units, placement — measured by `check_contract`
+* **Z up, -Y front, +X right, metres at real-world scale** (the harness converts to Y-up
+ GLB). A part may be authored in world coordinates (identity `loc`) or at the origin and
+ placed with `loc=cq.Location(cq.Vector(x, y, z))`; the wrapper applies `loc`.
+* Lowest point within 10 mm of z = 0 (WARN; 30 mm is ERROR). Footprint centre within
+ max(10 mm, 10 % of the footprint extent) of the up axis (WARN). Each part's bbox and the
+ overall bbox within max(10 mm, 10 % of the plan extent) per axis (WARN; 3× that is ERROR).
+ An exported part the plan does not name is an INFO — the judge still sees it.
+* Angles: `.rotate(p0, p1, deg)`, `cq.Location(v, axis, deg)`, `.revolve(deg)` and
+ `.twistExtrude(h, deg)` take **degrees**; `math` functions take radians. The lint checks
+ the three-argument `.rotate(...)` only (a `math.pi` expression there is an ERROR).
-## Allowed imports
-`cadquery` (as `cq`), `math`, `itertools`, `functools`, `typing`, `dataclasses`.
-No `OCP`/`OCC` direct calls, no numpy, no file I/O, no `cq.exporters`, no
-`cq.importers`, no `import codeverse3d`.
+## Contact — measured by `check_connectivity`
+* Touching parts: a surface gap ≤ 2 mm counts as contact; overlap > 2 mm is WARN
+ "interpenetrate", > 10 mm (with at least 2 % of one part's surface inside) is ERROR (judge
+ cap 0.70). Parts whose largest extent is under 10 mm are skipped.
+* Every part must be in the ground-touching component: a part the contact graph cannot reach
+ from the parts on z = 0 is a floating ERROR (judge cap 0.60) — two parts touching only each
+ other are both floating. The finding prints the translation that closes the gap.
+* Islands: a second solid inside a part (a cut that split it, a union that did not meet)
+ smaller than 5 % of that part's largest extent is a stray-island WARN. Each plan part is
+ its own assembly child — two plan parts unioned into one read as a missing part.
+* Budgets (`detail_budget`, sized from the plan's part × instance count): fewer than 350
+ triangles per built object after tessellation is a WARN (floor clamped to 1 500 – 40 000),
+ more than 20 000 per built object an ERROR (ceiling clamped to 60 000 – 600 000); a build
+ over 3 s per built object (at least 20 s) is a WARN, and the build is killed at
+ `build_timeout_s` (300 s by default).
-## Forbidden
-* No `show_object`, `exporters.export`, `open(`, `os`, `sys`, `subprocess`, network.
-* Each part a valid solid (`.val().isValid()`), no empty Workplanes; fillets
- < 0.45 × thinnest adjacent wall; feature sizes ≥ 0.5 mm.
-* Do not union parts across plan boundaries (keep one solid per part); small intentional
- overlap of **0.5–2 mm** between touching parts is required — that is how they "weld";
- deeper than 2 mm and the connectivity gate calls it interpenetration.
+## Imports — the lint's list
+* Allowed: `cadquery` (as `cq`), `math`, `random`, `numpy`, and the stdlib data helpers
+ `itertools`, `functools`, `collections`, `typing`, `dataclasses`, `enum`, `copy`,
+ `statistics`, `operator`. Anything else is a WARN "may not exist in the build sandbox".
+* Forbidden (lint ERROR): `os`, `sys`, `pathlib`, `subprocess`, `shutil`, `socket`,
+ `urllib`, `requests`, `http`, `ftplib`, `smtplib`, `webbrowser`, `ctypes`, `pickle`,
+ `multiprocessing`, `threading`, `importlib`, `OCP`, `OCC`, `ocp_vscode`, `cq_editor`,
+ `cq_warehouse`, `build123d`.
+* Forbidden calls (lint ERROR): `show_object`, `show`, `open(`, `cq.exporters.*`,
+ `cq.importers.*`, `.save()` / `.export*()` on the assembly, `exit` / `quit`.
-## Self-check (put at the end of the file)
-```python
-def _selfcheck(assy) -> None:
- names = [c.name for c in assy.children]
- assert names and len(names) == len(set(names)), f"duplicate/missing part names {names}"
- for c in assy.children:
- assert c.obj.val().isValid(), f"invalid solid in {c.name}"
-```
+## Kernel facts — what the build reports as an error
+* `cq.Workplane("XY")` has normal +Z (up), `"XZ"` normal -Y (the front elevation), `"YZ"`
+ normal +X. `.extrude(h)` goes along the plane normal from the workplane; `.hole(d)` cuts
+ in the -normal direction.
+* `.box(x, y, z)` is centred on the workplane unless `centered=(…)` — `centered=False`
+ puts the MIN corner at the origin on all three axes. `.cylinder(height, radius)` takes
+ height first.
+* `.rotate()`, `.translate()` and `.mirror()` return NEW objects — assign the result.
+* OCC refuses a fillet or chamfer whose radius reaches the adjacent wall, or whose edges
+ conflict: `StdFail_NotDone: BRep_API: command not done`. Uncaught, it fails the WHOLE build
+ (no GLB) with the wrapper's hint (radius < 0.45 × the thinnest adjacent wall is the hint,
+ not a gate); a cosmetic fillet wrapped in `try/except` that falls back to the unrounded
+ solid is the one allowed exception (harness contract §5). A selector that matches nothing
+ raises `ValueError`.
+* A revolve profile must stay at r ≥ 0; in `Workplane("XZ")` the axis `(0, 1, 0)` is
+ plane-local (world Z). `.center()` before a revolve moves the profile onto the axis and
+ the kernel refuses; `.moveTo()` does not.
+* `cq.Solid.makeSphere(r)` without angle arguments builds a hemisphere (lint WARN);
+ `cq.Workplane("XY").sphere(r)` is a full sphere.
+* Features under ~0.5 mm come out invalid at OCC tolerance.
+* `.text()` may raise headless (no fonts).
-## COMPLETE minimal example (verified with CadQuery 2.8)
+## Interface example — runs as-is (CadQuery 2.8); the interface, not a model to copy
+Two plan parts, `Body` and `Knob` × 2: a module-level `result`, one named, coloured child per
+part, instances `Name_i`, placement by `loc`. Sizes and positions are the plan rows' numbers.
```python
import cadquery as cq
-import math
-
-# --- plan numbers (metres) -------------------------------------------------
-TOP_W, TOP_D, TOP_T, TOP_Z = 0.60, 0.40, 0.025, 0.45 # table top, its top face at 0.45
-LEG_S, LEG_INSET = 0.035, 0.04 # square leg side, inset from edge
-WELD = 0.001 # legs poke 1 mm into the top
-
-def build_top() -> cq.Workplane:
- return (cq.Workplane("XY")
- .box(TOP_W, TOP_D, TOP_T, centered=(True, True, False)) # z from 0 up
- .edges("|Z").fillet(0.02) # round the 4 vertical corners
- .edges(">Z").chamfer(0.003) # soften the top rim
- .translate((0, 0, TOP_Z - TOP_T)))
-
-def build_leg(sx: int, sy: int) -> cq.Workplane:
- x = sx * (TOP_W / 2 - LEG_INSET - LEG_S / 2)
- y = sy * (TOP_D / 2 - LEG_INSET - LEG_S / 2)
- h = TOP_Z - TOP_T + WELD
- leg = cq.Workplane("XY").rect(LEG_S, LEG_S).extrude(h) # z 0 → h
- try:
- leg = leg.edges("|Z").fillet(0.004) # cosmetic: may fail
- except Exception:
- pass
- return leg.translate((x, y, 0))
-
-assy = cq.Assembly(name="SideTable")
-assy.add(build_top(), name="Top", color=cq.Color(0.55, 0.33, 0.16))
-for i, (sx, sy) in enumerate([(1, 1), (-1, 1), (-1, -1), (1, -1)]):
- assy.add(build_leg(sx, sy), name=f"Leg_{i}", color=cq.Color(0.2, 0.2, 0.22))
-_selfcheck(assy)
-result = assy
+body = cq.Workplane("XY").box(0.12, 0.08, 0.05, centered=(True, True, False)) # z 0 → 0.05
+knob = cq.Workplane("XY").circle(0.01).extrude(0.02) # z 0 → 0.02
+result = cq.Assembly(name="Object")
+result.add(body, name="Body", color=cq.Color(0.55, 0.57, 0.6))
+for i, x in enumerate((-0.04, 0.04)): # each copy sits flush on Body's top face: contact
+ result.add(knob, name=f"Knob_{i}", color=cq.Color(0.1, 0.1, 0.1), loc=cq.Location(cq.Vector(x, 0, 0.05)))
```
diff --git a/harness/codeverse3d/prompts/cadquery/cookbook.md b/harness/codeverse3d/prompts/cadquery/cookbook.md
deleted file mode 100644
index b3c1ab91..00000000
--- a/harness/codeverse3d/prompts/cadquery/cookbook.md
+++ /dev/null
@@ -1,413 +0,0 @@
-# CadQuery cookbook — static objects, CadQuery 2.4–2.8
-
-Every snippet runs as-is (the harness test suite executes them in order with plain
-`python3`). Z-up, −Y front, meters, PascalCase part names, `result = cq.Assembly`.
-The harness inlines the relevant chapters into your prompts; the full file is at
-`.3dcode/cookbook.md` in your workspace.
-
-## Skeleton
-
-```python
-import cadquery as cq
-import math
-
-# ---- plan numbers (metres) --------------------------------------------------
-BODY_W, BODY_D, BODY_H, WALL = 0.120, 0.080, 0.040, 0.002
-LID_T, LIP = 0.003, 0.0015
-WELD = 0.002 # parts overlap by this to "weld"
-
-def safe_fillet(wp: cq.Workplane, selector: str, r: float) -> cq.Workplane:
- """Cosmetic fillet that never breaks the build: shrink, then give up."""
- for rr in (r, r * 0.5, r * 0.25):
- try:
- return wp.edges(selector).fillet(rr)
- except Exception:
- continue
- return wp
-
-def safe_chamfer(wp: cq.Workplane, selector: str, d: float) -> cq.Workplane:
- try:
- return wp.edges(selector).chamfer(d)
- except Exception:
- return wp
-
-def bbox(wp: cq.Workplane):
- """(xmin, ymin, zmin, xmax, ymax, zmax) of the FIRST solid — use to self-check."""
- b = wp.val().BoundingBox()
- return (b.xmin, b.ymin, b.zmin, b.xmax, b.ymax, b.zmax)
-
-def build_body() -> cq.Workplane:
- outer = (cq.Workplane("XY").box(BODY_W, BODY_D, BODY_H, centered=(True, True, False))
- .edges("|Z").fillet(0.006)) # z from 0 upward
- body = outer.faces(">Z").shell(-WALL) # open-top box, 2 mm walls
- return safe_fillet(body, "<Z", 0.001) # soften the bottom rim LAST (r < wall/2)
-
-def build_lid() -> cq.Workplane:
- top = (cq.Workplane("XY").box(BODY_W, BODY_D, LID_T, centered=(True, True, False))
- .edges("|Z").fillet(0.006).translate((0, 0, BODY_H)))
- lip = (cq.Workplane("XY").rect(BODY_W - 2 * WALL - 0.0004, BODY_D - 2 * WALL - 0.0004)
- .rect(BODY_W - 2 * WALL - 0.0004 - 2 * LIP, BODY_D - 2 * WALL - 0.0004 - 2 * LIP)
- .extrude(0.004 + WELD).translate((0, 0, BODY_H - 0.004))) # lip drops into the box
- return top.union(lip)
-
-assy = cq.Assembly(name="Enclosure")
-assy.add(build_body(), name="Body", color=cq.Color(0.25, 0.25, 0.27))
-assy.add(build_lid(), name="Lid", color=cq.Color(0.85, 0.55, 0.15))
-result = assy
-print("body bbox", [round(v, 4) for v in bbox(build_body())])
-```
-
-Why: every part is a function returning one solid; `safe_*` keep cosmetic edge work from
-killing the build; the lid's lip overlaps the body (weld) so the assembly is connected.
-
-## Workplane idioms (the few you need)
-
-```python
-# Workplane names: "XY" (normal +Z, up), "XZ" (normal -Y: the FRONT elevation), "YZ" (normal +X)
-# .box(x, y, z) is CENTRED unless centered=(…); .extrude(h) goes along the plane normal from z=0
-plate = cq.Workplane("XY").box(0.10, 0.06, 0.004, centered=(True, True, False)) # bottom at z=0
-# workplane offset + faces: stack features relative to the last face
-boss = (plate.faces(">Z").workplane() # plane on the top face
- .center(0.03, 0.0) # local offset (resets per workplane)
- .circle(0.008).extrude(0.012)) # boss grows UP from the face
-# hole through everything from the top face
-boss = boss.faces(">Z").workplane().center(-0.03, 0).hole(0.005) # hole() is a THROUGH hole
-# cboreHole / cskHole for counterbores; .hole(d, depth) for blind
-# rotate(p0, p1, deg) about an arbitrary axis, translate(v): both RETURN NEW objects
-tilted = boss.rotate((0, 0, 0), (1, 0, 0), 15).translate((0, 0.2, 0))
-# pushPoints: put features at several local points
-grid = (cq.Workplane("XY").box(0.08, 0.08, 0.005, centered=(True, True, False))
- .faces(">Z").workplane().pushPoints([(-0.02, -0.02), (0.02, 0.02)]).hole(0.004))
-# selectors: "|Z" edges parallel Z, ">Z" max-Z face/edges, "<Y" min-Y, "%CIRCLE" round edges,
-# "#Z" edges perpendicular to Z, "not(|Z)". Combine: .edges("|Z and >X")
-print("boss bbox", [round(v, 4) for v in bbox(boss)])
-```
-
-Why: offset workplanes + `faces(">Z").workplane()` build features where they belong
-without hand-computing z; `centered=(True, True, False)` makes z = 0 the base so objects
-stand on the ground by construction.
-
-## 2D profiles: polyline, spline, slots, text, sketches
-
-```python
-# closed polyline profile (in metres) extruded; points in plane-local coords
-bracket_profile = [(0, 0), (0.06, 0), (0.06, 0.004), (0.004, 0.004), (0.004, 0.05), (0, 0.05)]
-lbracket = cq.Workplane("XZ").polyline(bracket_profile).close().extrude(-0.03) # XZ normal is -Y: negative = towards +Y
-# spline through points (smooth organic outline), mirrored for symmetry
-half = [(0, 0), (0.02, 0.003), (0.04, 0.012), (0.05, 0.03), (0.045, 0.05), (0.03, 0.06), (0, 0.062)]
-leaf = (cq.Workplane("XY").spline(half, includeCurrent=False).mirrorY().extrude(0.002))
-# slot and rounded rect via Sketch API
-s = cq.Sketch().rect(0.06, 0.03).vertices().fillet(0.006)
-tag = cq.Workplane("XY").placeSketch(s).extrude(0.003)
-slot = cq.Workplane("XY").slot2D(0.03, 0.006).extrude(0.002) # length 30 mm, width 6 mm
-# text (embossed label), font size in metres; fonts may be missing headless → wrap it
-try:
- label = cq.Workplane("XY").text("C3V", 0.012, 0.001, halign="center", valign="center")
-except Exception:
- label = None
-print("lbracket bbox", [round(v, 4) for v in bbox(lbracket)], "leaf ok", leaf.val().isValid())
-```
-
-Why: `Sketch().rect().vertices().fillet()` is the robust rounded rectangle; polylines need
-`.close()`; `mirrorY()` mirrors the pending wire about the plane's Y axis.
-
-## Extrude, revolve, loft, sweep (the solid makers)
-
-```python
-# revolve: profile in the XZ plane, axis = local Y of XZ plane = world Z; r >= 0 always
-vase_profile = [(0.0, 0.0), (0.035, 0.0), (0.045, 0.05), (0.03, 0.12), (0.02, 0.18), (0.025, 0.20), (0.0, 0.20)]
-vase = cq.Workplane("XZ").polyline(vase_profile).close().revolve(360, (0, 0, 0), (0, 1, 0))
-# loft between sections on parallel workplanes (same edge count/orientation is safest: circle→circle, rect→rect)
-funnel = (cq.Workplane("XY").circle(0.04)
- .workplane(offset=0.05).circle(0.015)
- .workplane(offset=0.03).circle(0.015).loft(ruled=False))
-# sweep a circle along a 3D path (tube / handle / pipe); profile plane must be perpendicular to the path start
-path = cq.Workplane("XZ").spline([(0, 0), (0.03, 0.02), (0.06, 0.06), (0.06, 0.10)])
-handle = (cq.Workplane("XY").circle(0.005).sweep(path, isFrenet=True))
-# twisted / tapered extrude
-twist = cq.Workplane("XY").rect(0.02, 0.02).twistExtrude(0.06, 90)
-taper = cq.Workplane("XY").circle(0.03).extrude(0.05, taper=10)
-print("vase ok", vase.val().isValid(), "funnel ok", funnel.val().isValid(), "handle ok", handle.val().isValid())
-```
-
-Why: these four make 90 % of non-boxy shapes; the classic failures are revolve profiles
-crossing the axis (r < 0), lofts between wires with different vertex counts, and sweep
-profiles not perpendicular to the path start. Verify with `.val().isValid()`.
-
-## Shell, fillet, chamfer — robustly
-
-```python
-cup = (cq.Workplane("XY").circle(0.04).extrude(0.09, taper=-3) # flared cup (taper < 0 widens)
- .faces(">Z").shell(-0.003)) # open top, 3 mm wall
-cup = safe_fillet(cup, ">Z", 0.001) # rim round-over; may legally fail on thin walls
-# shell() REFUSES lofted round bodies: hollow those by subtracting an inner loft instead
-shade = (cq.Workplane("XY").circle(0.06).workplane(offset=0.12).circle(0.10).loft()
- .cut(cq.Workplane("XY").circle(0.057).workplane(offset=0.12).circle(0.097).loft()
- .translate((0, 0, 0.003)))) # 3 mm wall, 3 mm floor
-box_ = (cq.Workplane("XY").box(0.06, 0.04, 0.03, centered=(True, True, False))
- .edges("|Z").fillet(0.008) # vertical corners first (big radius)
- .edges(">Z").chamfer(0.002)) # then the top rim (small)
-print("cup ok", cup.val().isValid(), "shade ok", shade.val().isValid(), "box ok", box_.val().isValid())
-```
-
-Rules: fillet BEFORE booleans that would split the edge; radius < 0.45 × the thinnest
-adjacent wall; biggest fillets first; shell from a single open face; if `BRep_API:
-command not done` appears, halve the radius or fillet fewer edges (`"|Z"` only).
-
-## Booleans (union / cut / intersect) and cavities
-
-```python
-block = cq.Workplane("XY").box(0.08, 0.05, 0.03, centered=(True, True, False))
-cutter = (cq.Workplane("XY").box(0.06, 0.03, 0.03, centered=(True, True, False))
- .translate((0, 0, 0.006 + 0.0001))) # cutter overshoots the top face by 6 mm+
-pocketed = block.cut(cutter) # 6 mm floor left
-pin = cq.Workplane("XY").circle(0.004).extrude(0.05).translate((0.03, 0, 0.02))
-joined = pocketed.union(pin).clean() # clean() merges coplanar faces
-core = block.intersect(cq.Workplane("XY").sphere(0.045).translate((0, 0, 0.015)))
-print("pocket solids", len(pocketed.solids().vals()), "joined valid", joined.val().isValid())
-```
-
-Why: booleans fail on exactly coplanar faces — always overshoot cutters by ≥ 0.1 mm;
-check `len(result.solids().vals()) == 1` after a cut (a cut that splits a part is a bug).
-
-## Assemblies: names, colours, locations
-
-```python
-def place(part: cq.Workplane, xyz=(0, 0, 0), rz_deg: float = 0.0) -> cq.Location:
- """Location = translation + yaw (degrees). Compose bigger rotations via .rotate() on the solid."""
- return cq.Location(cq.Vector(*xyz), cq.Vector(0, 0, 1), rz_deg)
-
-stool = cq.Assembly(name="Stool")
-seat = cq.Workplane("XY").circle(0.17).extrude(0.04).translate((0, 0, 0.41))
-stool.add(seat, name="Seat", color=cq.Color(0.55, 0.34, 0.16))
-leg = cq.Workplane("XY").circle(0.015).extrude(0.41 + WELD) # authored at the origin
-for i in range(3):
- a = math.radians(90 + 120 * i)
- stool.add(leg, name=f"Leg_{i}", color=cq.Color(0.3, 0.3, 0.32),
- loc=place(leg, (0.12 * math.cos(a), 0.12 * math.sin(a), 0)))
-# sub-assemblies nest: stool.add(other_assy, name="Footrest", loc=...)
-names = [c.name for c in stool.children]
-print("stool parts", names, "valid", all(c.obj.val().isValid() for c in stool.children))
-```
-
-Why: one authored solid + N locations = instances that stay identical; names must be
-unique (the GLB node names come from them); `cq.Color` takes 0–1 floats.
-
-## Patterns: rect arrays, polar arrays, point lists
-
-```python
-grille = (cq.Workplane("XY").box(0.10, 0.06, 0.002, centered=(True, True, False))
- .faces(">Z").workplane().rarray(0.008, 0.008, 10, 6).hole(0.004)) # 10×6 holes
-flange = (cq.Workplane("XY").circle(0.05).extrude(0.006)
- .faces(">Z").workplane().polarArray(0.04, 0, 360, 6).hole(0.005)) # 6 bolt holes
-spokes = cq.Workplane("XY")
-for i in range(8):
- a = 360 / 8 * i
- spokes = spokes.union(cq.Workplane("XY").box(0.08, 0.004, 0.004, centered=(False, True, False))
- .rotate((0, 0, 0), (0, 0, 1), a))
-print("grille holes ok", grille.val().isValid(), "spokes valid", spokes.val().isValid())
-```
-
-Why: `rarray`/`polarArray` + one cut are 10× faster than loops of cuts and never produce
-slivers; loops of `.union` are fine for ≤ 12 items.
-
-## Mechanical parts (recipes with numbers)
-
-```python
-def l_bracket(w=0.06, h=0.05, depth=0.03, t=0.004, hole_d=0.005) -> cq.Workplane:
- """Steel L-bracket with two slots; t 3–5 mm, fillet inside corner r = t."""
- prof = [(0, 0), (w, 0), (w, t), (t, t), (t, h), (0, h)]
- b = cq.Workplane("XZ").polyline(prof).close().extrude(-depth)
- b = safe_fillet(b, "|Y", t * 0.8)
- b = b.faces(">Z").workplane().center(0, 0).hole(hole_d)
- return b
-
-def enclosure(w=0.12, d=0.08, h=0.04, wall=0.002, lid_t=0.003):
- """Two parts: open box + lid with a drop-in lip (1.5 mm)."""
- body = (cq.Workplane("XY").box(w, d, h, centered=(True, True, False))
- .edges("|Z").fillet(0.005).faces(">Z").shell(-wall))
- lid = (cq.Workplane("XY").box(w, d, lid_t, centered=(True, True, False)).edges("|Z").fillet(0.005)
- .translate((0, 0, h)))
- lip = (cq.Workplane("XY").rect(w - 2 * wall - 0.0004, d - 2 * wall - 0.0004)
- .rect(w - 2 * wall - 0.0034, d - 2 * wall - 0.0034).extrude(0.005).translate((0, 0, h - 0.003)))
- return body, lid.union(lip)
-
-def spur_gear(module=0.002, teeth=20, thickness=0.008, bore=0.006) -> cq.Workplane:
- """Visual-grade gear: trapezoid teeth on a disc (not an involute; fine for renders)."""
- r_p = module * teeth / 2; r_o = r_p + module; r_r = r_p - 1.25 * module
- gear = cq.Workplane("XY").circle(r_r).extrude(thickness)
- tooth = (cq.Workplane("XY").polyline([(r_r - 0.0005, -module * 0.9), (r_o, -module * 0.45),
- (r_o, module * 0.45), (r_r - 0.0005, module * 0.9)]).close()
- .extrude(thickness))
- for i in range(teeth):
- gear = gear.union(tooth.rotate((0, 0, 0), (0, 0, 1), 360 / teeth * i))
- return gear.faces(">Z").workplane().hole(bore)
-
-def knob(d=0.03, h=0.018, ribs=12) -> cq.Workplane:
- """Rotary knob: tapered cylinder, rib grooves, domed top, D-shaft bore."""
- k = cq.Workplane("XY").circle(d / 2).extrude(h, taper=6)
- k = safe_fillet(k, ">Z", 0.003)
- groove = cq.Workplane("XY").box(0.0015, 0.004, h * 0.7, centered=(True, True, False)).translate((0, d / 2, h * 0.35))
- for i in range(ribs):
- k = k.cut(groove.rotate((0, 0, 0), (0, 0, 1), 360 / ribs * i))
- return k.faces("<Z").workplane().hole(0.006, 0.010)
-
-parts = [l_bracket(), *enclosure(), spur_gear(), knob()]
-print("mech valid", [p.val().isValid() for p in parts])
-```
-
-Dimensions (m): bracket t 3–5 mm, holes Ø 4–6 mm; enclosure walls 1.5–2.5 mm, lid 2–3 mm;
-gear module 1–3 mm, 12–40 teeth; knob Ø 20–35 mm, h 15–20 mm, shaft Ø 6 mm; handles
-Ø 10–14 mm tube; table legs 35–70 mm square; shelf panels 18 mm; plinths 100 mm.
-
-## Common objects — decomposition (CadQuery flavour)
-
-| object | parts | build with |
-|---|---|---|
-| mug | Body (revolve + shell), Handle (sweep circle along spline, overlap 2 mm) | revolve, sweep |
-| bottle | Body (revolve), Cap (cylinder + knurl polarArray cuts) | revolve, polarArray |
-| chair | Seat (box + fillets), Legs ×4 (extrude, located), Backrest (box + rotate 8°), Stretchers | box, rotate, Location |
-| table | Top (box + fillet), Apron ×4, Legs ×4 | box, translate |
-| lamp | Base (revolve), Pole (cylinder), Shade (taper extrude + shell, or loft − inner loft) | extrude(taper), shell |
-| enclosure | Body (shell), Lid (lip), Buttons (cylinders), Screws (polarArray) | shell, rarray |
-| wheel | Rim (revolve), Tyre (torus via revolve of circle), Spokes (polar union), Hub | revolve, polar |
-| bracket | L-profile polyline extrude + slots | polyline, cutThruAll |
-
-## Measure while you build (numbers beat squinting)
-
-```python
-def report(wp: cq.Workplane, name: str = "part") -> dict:
- """Print the facts the harness will measure — call it after building each part."""
- shp = wp.val()
- bb = shp.BoundingBox()
- info = {
- "name": name,
- "extents_m": (round(bb.xlen, 4), round(bb.ylen, 4), round(bb.zlen, 4)),
- "zmin": round(bb.zmin, 4),
- "solids": len(wp.solids().vals()),
- "valid": shp.isValid(),
- "volume_m3": round(shp.Volume(), 8),
- "faces": len(wp.faces().vals()),
- }
- print(f"[report] {info}")
- return info
-
-r = report(build_body(), "Body")
-assert r["solids"] == 1 and r["valid"]
-assert abs(r["extents_m"][2] - BODY_H) < 1e-6 # plan number check, in code
-```
-
-Why: `Volume()` catches hollow-when-it-should-be-solid (and vice versa) instantly;
-`solids == 1` catches a cut that split the part; `zmin` catches floaters — all before
-spending a render.
-
-## Pitfalls (symptom → cause → fix)
-
-1. **`.cylinder(height, radius)`** — height FIRST; `.box(x, y, z)` is centred unless
- `centered=(…)`; `.circle(r).extrude(h)` starts at the workplane (z = 0).
-2. **Degrees vs radians**: `.rotate(..., deg)`, `cq.Location(v, axis, deg)`,
- `revolve(deg)`, `twistExtrude(h, deg)` are DEGREES; `math.sin` wants radians.
-3. **`rotate/translate/mirror` return new objects** — assign the result (`wp = wp.rotate(...)`).
-4. **`BRep_API: command not done`** → fillet radius ≥ wall, a fillet radius EQUAL to a
- later shell thickness (inner radius 0), fillet after a boolean that split the edge, or
- a degenerate edge. Halve the radius, shell first and fillet last, select fewer edges,
- use `safe_fillet`.
-5. **`ValueError: No edges selected` / "Fillets requires that edges be selected"** →
- the selector matched nothing (rotated features are invisible to `|Z`-style selectors).
- Print `len(wp.edges(sel).vals())`; use `cq.selectors.BoxSelector(p0, p1)` or
- `NearestToPointSelector(p)`.
-6. **Shell fails** → pick ONE open face (`.faces(">Z").shell(-t)`), keep t < smallest
- feature, fillet outside corners first. Shell never works on lofted round bodies:
- use `extrude(h, taper=…)` + shell, `outer.cut(inner_loft)`, or revolve a profile that
- already contains the wall.
-7. **Two solids in one Workplane** (`len(wp.solids().vals()) > 1`) → a cut split your part
- or a union did not touch; overlap parts by ≥ 0.5 mm, check bounds.
-8. **Coplanar boolean faces** → invalid/empty result; overshoot cutters 0.1–5 mm; `.clean()`.
-9. **`cq.Solid.makeSphere(r)` gives a hemisphere** without angle args; use
- `cq.Workplane().sphere(r)`.
-10. **Revolve axis**: in `cq.Workplane("XZ")` the axis `(0,1,0)` is plane-LOCAL = world Z.
- Profile must stay at r ≥ 0.
-11. **`centered=False` on `.box`** puts the MIN corner at the origin on all three axes;
- use the tuple form `(True, True, False)` for "centred in XY, base on z = 0".
-12. **Tiny features (< 0.3 mm)** at OCC's 1e-7 tolerance produce invalid shapes; keep
- features ≥ 0.5 mm, or model in mm and scale at the end (`.val().scale(0.001)`).
-13. **`result` under `if __name__ == "__main__":`** → the harness never sees it. Module level.
-14. **`show_object`, `exporters.export`, file writes** → forbidden; the harness exports.
-15. **Selectors after booleans** — edge indices reshuffle; re-select by geometry
- (`">Z"`, `BoxSelector`), never by cached index.
-16. **Euler `cq.Location(x, y, z, rx, ry, rz)`** is easy to get wrong — build the solid
- in place with `.rotate(...).translate(...)` and use `Location` only for translation +
- one yaw.
-17. **Very slow builds** → long loops of `.union` with fillets inside; fillet once at the
- end, use `rarray`/`polarArray`.
-18. **`hole()` on the wrong side** → it cuts in the −normal direction of the workplane;
- stand on the top face (`faces(">Z").workplane()`).
-
-## Self-check (before you call it done)
-
-```python
-def selfcheck(assy: cq.Assembly, expected_parts, overall_hint=None, tol=0.01) -> None:
- names = [c.name for c in assy.children]
- assert names == list(dict.fromkeys(names)), f"duplicate part names: {names}"
- missing = [n for n in expected_parts if n not in names]
- assert not missing, f"missing parts: {missing}"
- for c in assy.children:
- shp = c.obj.val() if hasattr(c.obj, "val") else c.obj
- assert shp.isValid(), f"invalid solid: {c.name}"
- assert len(c.obj.solids().vals()) == 1, f"{c.name} is {len(c.obj.solids().vals())} solids (must be 1)"
- bb = assy.toCompound().BoundingBox()
- assert abs(bb.zmin) < tol, f"lowest point z={bb.zmin:.4f}, expected 0"
- ext = (bb.xlen, bb.ylen, bb.zlen)
- print(f"[selfcheck] parts={len(names)} extents={tuple(round(e, 3) for e in ext)}")
- if overall_hint:
- for a, b in zip(ext, overall_hint):
- assert abs(a - b) < 0.05, f"extents {ext} vs plan {overall_hint}"
-
-selfcheck(stool, ["Seat", "Leg_0", "Leg_1", "Leg_2"], (0.34, 0.34, 0.45))
-selfcheck(result, ["Body", "Lid"])
-```
-
-Then: `build` → `render_sheet` → `check_connectivity` → `cross_section` through shells
-→ `check_contract`. Fix the worst finding, rebuild, repeat.
-
-## Worked example: dining chair (8 parts, welded, on the ground)
-
-```python
-SEAT_W, SEAT_D, SEAT_T, SEAT_H = 0.44, 0.44, 0.035, 0.45
-LEG, BACK_H, RAKE_DEG = 0.035, 0.92, 8.0
-
-def chair_seat():
- return (cq.Workplane("XY").box(SEAT_W, SEAT_D, SEAT_T, centered=(True, True, False))
- .edges("|Z").fillet(0.02).edges(">Z").fillet(0.006).translate((0, 0, SEAT_H - SEAT_T)))
-
-def chair_leg(h):
- return cq.Workplane("XY").rect(LEG, LEG).extrude(h + WELD).edges("|Z").chamfer(0.003)
-
-def chair_back():
- """Two raked posts + 3 slats; built upright then raked back by RAKE_DEG about the seat rear edge."""
- post_h = BACK_H - SEAT_H
- posts = cq.Workplane("XY")
- for sx in (-1, 1):
- posts = posts.union(cq.Workplane("XY").rect(LEG, LEG * 0.8).extrude(post_h + WELD)
- .translate((sx * (SEAT_W / 2 - LEG / 2), 0, SEAT_H - WELD)))
- for i in range(3):
- z = SEAT_H + 0.14 + i * 0.10
- posts = posts.union(cq.Workplane("XY").box(SEAT_W - LEG, 0.012, 0.05).translate((0, 0, z)))
- pivot = (0, SEAT_D / 2 - LEG / 2, SEAT_H - WELD)
- return posts.translate((0, SEAT_D / 2 - LEG / 2, 0)).rotate(pivot, (pivot[0] + 1, pivot[1], pivot[2]), RAKE_DEG)
-
-chair = cq.Assembly(name="DiningChair")
-chair.add(chair_seat(), name="Seat", color=cq.Color(0.6, 0.4, 0.2))
-for i, (sx, sy) in enumerate([(1, 1), (-1, 1), (-1, -1), (1, -1)]):
- chair.add(chair_leg(SEAT_H - SEAT_T), name=f"Leg_{i}", color=cq.Color(0.45, 0.3, 0.15),
- loc=cq.Location(cq.Vector(sx * (SEAT_W / 2 - LEG / 2 - 0.01), sy * (SEAT_D / 2 - LEG / 2 - 0.01), 0)))
-chair.add(chair_back(), name="Backrest", color=cq.Color(0.45, 0.3, 0.15))
-stretch = cq.Workplane("XY").box(SEAT_W - LEG - 0.02 + 2 * WELD, 0.02, 0.02).translate((0, 0, 0.20))
-chair.add(stretch.translate((0, SEAT_D / 2 - LEG / 2 - 0.01, 0)), name="StretcherBack", color=cq.Color(0.45, 0.3, 0.15))
-chair.add(stretch.translate((0, -(SEAT_D / 2 - LEG / 2 - 0.01), 0)), name="StretcherFront", color=cq.Color(0.45, 0.3, 0.15))
-selfcheck(chair, ["Seat", "Leg_0", "Leg_1", "Leg_2", "Leg_3", "Backrest", "StretcherBack", "StretcherFront"])
-```
-
-Why: the plan's numbers appear once as constants; legs are one solid placed four times;
-the backrest is built upright and raked as a whole so its slats stay attached; every
-part overlaps a neighbour by `WELD`.
diff --git a/harness/codeverse3d/prompts/cadquery/system.md b/harness/codeverse3d/prompts/cadquery/system.md
index df474358..da35697f 100644
--- a/harness/codeverse3d/prompts/cadquery/system.md
+++ b/harness/codeverse3d/prompts/cadquery/system.md
@@ -1,52 +1,45 @@
-You are a CadQuery modeller writing RAW python for a headless harness. No SDKs beyond
-`cadquery` itself, no helper libraries. You are driving a real B-rep kernel (OCC): shapes
-are solids with topology, not meshes, and the kernel will refuse an operation it cannot
-make valid. The harness owns the export and the cameras — never save, never render.
-
-This track scores **0.410** baseline over 26 recorded runs, the lowest of the three
-static-object languages, and its failures are mostly the kernel saying no.
+You are a CadQuery modeller writing RAW python for a headless harness: `cadquery` itself,
+no SDKs, no helper libraries. You are driving a real B-rep kernel (OCC): shapes are solids
+with topology, not meshes, and the kernel refuses an operation it cannot make valid. The
+harness owns the export and the cameras — never save, never render.
{% if tools %}
The loop that decides whether your work ships:
- write → `build` → read the lint output → `check_contract` +
- `check_connectivity` → fix everything they report → repeat →
+ write → `build` → read the lint and build output → `check_contract` +
+ `check_connectivity` → fix what they report → repeat →
`render_views` → LOOK at the sheet → only then finish.
-`build` surfaces the OCC exceptions that silently drop a feature. Do not finish while the
-lint still reports one — a fillet that failed is a fillet that is not there.
+`build` surfaces the OCC exceptions. An uncaught `StdFail_NotDone` (`BRep_API: command not
+done`) fails the whole build — no GLB — and names the line.
{% else %}
You cannot run anything: this is a single-shot session with no tools, so the code you
-return is the code that ships. The kernel is unforgiving and you cannot see its complaint,
-so prefer the operation that is certain to succeed over the one that would look better if
-it worked.
+return is the code that ships. You cannot see a kernel refusal, so a cosmetic operation
+that may be refused belongs in `try/except` (optional — the solid without it still builds).
{% endif %}
-What the gates and the lint name, measured over 26 recorded runs of this exact track:
-
-* **`fillet`/`chamfer` failing in OCC** (52 findings) — "OCC fails when radius >= wall
- thickness or edges conflict". This is the CadQuery-specific killer. Keep every fillet
- radius **strictly below the thinnest wall it touches**, select edges narrowly rather than filleting everything, and apply fillets **last**, after
- the solid is otherwise final. A fillet that throws takes its whole feature with it.
-* **Interpenetration** (214 findings) — parts are allowed to overlap by **≤ 2 mm**. In a
- B-rep workflow the right fix is usually to `union` the parts that are genuinely one
- solid and to position the rest by computing the mating face, not by nudging.
-* **Parts that are not in the plan** (60 findings, reported as INFO) — "GLB part 'X' is not
- in the plan". Not a gate failure, but the judge sees the stray solid. Every exported solid must be a part the plan names. An intermediate workplane solid you
- forgot to consume, or a construction body left in the assembly, shows up here.
-* **Bbox deviates from the plan** (51) and **stray islands** (44) — you built a different
- size than you planned, or an operation left a fragment. Both are measured, not judged.
-
-Rules that survive every brief:
-
-* **Build from sketch → extrude → boolean, in that order**, and keep each named part its
- own solid in the assembly. Name it exactly as the plan names it.
-* **Author in millimetres if that is natural, but export at real scale in metres.** A
- chair is 0.45 m to the seat. State the unit conversion once, explicitly.
-* **Prefer a boolean to a fillet** when you need a soft edge on a thin wall. The kernel
- will do a `cut` with a rounded tool where it refuses a `fillet`.
-* **You place the object; the harness exports it as authored.** It never re-centres or
+What the gates and the lint measure (thresholds and kernel facts are in the contract):
+
+* **An OCC refusal in `build`** — uncaught, the build fails and names the line; a cosmetic
+ fillet in `try/except` that falls back to the unrounded solid builds without it.
+* **`check_connectivity`** — touching parts: a surface gap ≤ 2 mm is contact; overlap
+ > 2 mm is WARN, > 10 mm is ERROR (judge cap 0.70). A part not connected to the
+ ground-touching component is a floating ERROR. A second solid inside a part smaller than
+ 5 % of the part is a stray island.
+* **`check_contract`** — each part's bbox and the overall bbox against the plan (within
+ max(10 mm, 10 % of the extent) per axis), lowest point at z = 0, footprint centred. A
+ part the plan does not name is an INFO — not a gate failure, but the judge sees the
+ stray solid.
+* **`lint:cadquery`** — a module-level `result`, the import list, degrees arguments, part
+ names.
+
+What holds in every brief:
+
+* Each named part is its own solid in the assembly, named exactly as the plan names it.
+* `result` is in metres at real-world scale — the bbox gate compares it to the plan in
+ metres.
+* You place the object; the harness exports it as authored. It never re-centres or
grounds it, so seating the whole assembly on the ground yourself is fine.
-A clean simpler solid beats a richer one whose fillets silently failed. Get the build
-clean first, then add the detail the brief asked for.
+Detail the brief asks for is scored; a feature the kernel refused fails the build unless it
+was wrapped, and then it is not there.
diff --git a/harness/codeverse3d/prompts/catalog.py b/harness/codeverse3d/prompts/catalog.py
index 28a53e5b..4e047bdc 100644
--- a/harness/codeverse3d/prompts/catalog.py
+++ b/harness/codeverse3d/prompts/catalog.py
@@ -1,13 +1,13 @@
"""What prompt material exists, and how each piece reaches the model.
-ONE answer to a question that had six. `<lang>/cookbook.md` was once resolved in
-`languages/_docs.py`, `tracks/common.py`, `spatial/cookbook_tool.py`, `agents/materialize.py`
-and `tracks/scene_assets.py`, each with its own path arithmetic — and the
-``urdf_blender`` → ``prompts/urdf/`` mapping was written out three times and missing in a
-fourth, which is why the articulated agent received no cookbook at all for weeks. Until
-2026-09-22 the contract still came through the runtime (``contract_doc``), the cookbook
-through ``tracks/common``, the system prompt and the effects catalog through
-``tracks/prompting``: every per-language prompt file is now found by :func:`language_prompt`.
+ONE answer to a question that had six. A per-language prompt file was once resolved in
+`languages/_docs.py`, `tracks/common.py`, `agents/materialize.py` and `tracks/scene_assets.py`,
+each with its own path arithmetic — and the ``urdf_blender`` → ``prompts/urdf/`` mapping was
+written out three times and missing in a fourth, which is why the articulated agent received
+part of its prompt material late for weeks. Until 2026-09-22 the contract still came through
+the runtime (``contract_doc``), the system prompt and the effects catalog through
+``tracks/prompting``: every per-language prompt file (``contract.md`` first) is now found by
+:func:`language_prompt`.
The split this file encodes (owner, 2026-08-28):
@@ -33,17 +33,16 @@ PROMPT_DIRS: dict[Language, str] = {Language.URDF_BLENDER: "urdf"}
def language_prompt(language: Language, name: str) -> str:
- """``<dir>/<name>`` under ``prompts/`` — THE path of a language's ``contract.md``,
- ``cookbook.md`` and ``system.md`` (and scene_threejs's ``effects_catalog.md`` / ``asset.md``)."""
+ """``<dir>/<name>`` under ``prompts/`` — THE path of a language's ``contract.md`` and
+ ``system.md`` (and the scene languages' ``effects_catalog.md`` / ``asset.md``)."""
return f"{PROMPT_DIRS.get(language, language.value)}/{name}"
def language_text(language: Language, name: str) -> str:
- """The text of :func:`language_prompt`, or ``""`` for a file the language does not ship:
- only the two scene languages ship an effects catalog, and they ship NO ``cookbook.md``
- (owner, 2026-10-15: its interface facts went into contract.md / system.md, its craft into
- the skills) — ``RunContext.cookbook_text`` is ``""`` for them, so no prompt, workspace
- note or error report carries a cookbook on the scene track."""
+ """The text of :func:`language_prompt`, or ``""`` for a file the language does not ship
+ (only the two scene languages ship an effects catalog / ``asset.md``). No language ships
+ a cookbook (D107, owner 2026-10-15): interface and language facts are in ``contract.md`` /
+ ``system.md``, the craft in the skills as short optional practices."""
try:
return load_text(language_prompt(language, name))
except FileNotFoundError:
diff --git a/harness/codeverse3d/prompts/glsl_shader/contract.md b/harness/codeverse3d/prompts/glsl_shader/contract.md
index 0faab786..c6c8ab15 100644
--- a/harness/codeverse3d/prompts/glsl_shader/contract.md
+++ b/harness/codeverse3d/prompts/glsl_shader/contract.md
@@ -1,28 +1,28 @@
# glsl_shader authoring contract (Shadertoy-style fragment shader, GLSL 330 core)
-You write ONE fragment shader body; the harness wraps it, compiles it with moderngl (OpenGL 3.3 core,
-headless), renders frames at the plan's resolution for t = 0, 1, 2.5, 4, 6 s (plus a preview GIF) and
-measures / judges the frames. The code is the deliverable.
+You write ONE fragment-shader body; the harness wraps it, compiles it with moderngl (OpenGL 3.3 core,
+headless), renders frames at the plan's resolution for t = 0, 1, 2.5, 4, 6 s (plus a preview GIF up to
+`duration_s`) and measures / judges those frames. The code is the deliverable. This file states the
+interface and what is measured; what the frames show is the brief's business.
## Files
```
src/shader.frag REQUIRED the image pass (your code; no #version, no uniform/out declarations)
-src/common.glsl optional helper functions / constants, pasted ABOVE shader.frag (and buffer_a.frag) automatically
+src/common.glsl optional helper functions / constants, pasted ABOVE shader.frag (and buffer_a.frag) at build time
src/buffer_a.frag optional ONE feedback buffer pass (Shadertoy "Buffer A"): rendered every frame before the image pass
-src/recipes.glsl HARNESS-OWNED, READ-ONLY verified cookbook recipes the harness seeded for this brief, pasted ABOVE
- common.glsl: call its functions, never edit, redefine or copy them (a write is reverted and fails the session)
```
-Nothing else is read. No textures, no files, no includes.
+Nothing else is read — no textures, files or includes; any other file under `src/` is a lint WARN
+(`stray_file`) and ignored. The skeleton's `src/common.glsl` is starter text you may keep, change or delete.
## What the harness prepends (DO NOT write these lines yourself — redeclaring them is a lint ERROR)
```glsl
#version 330 core
-uniform float u_time; // seconds (frames sampled at 0, 1, 2.5, 4, 6 s; preview up to duration_s)
+uniform float u_time; // seconds; the judged frames are at t = 0, 1, 2.5, 4, 6 s (preview GIF up to duration_s)
uniform vec2 u_resolution; // pixels, e.g. 1280x720
uniform vec2 u_mouse; // always (0,0) headless — do not depend on it
-uniform int u_frame; // frame counter
+uniform int u_frame; // frame counter — NOT a clock: the sampled times are not evenly spaced
uniform sampler2D u_prev; // previous frame of THIS pass (feedback / trails); black at frame 0
-uniform sampler2D u_noise; // 256x256 RGBA white noise, repeat, linear (texture(u_noise, uv*k).r)
+uniform sampler2D u_noise; // 256x256 RGBA white noise, repeat, linear: one fetch is a bilinear-interpolated hash
uniform sampler2D u_buffer_a; // output of src/buffer_a.frag (only when that file exists)
#define iTime u_time // Shadertoy aliases: iTime iResolution iFrame iMouse iChannel0(=u_prev) iChannel1(=u_noise)
out vec4 fragColor; // the ONLY output
@@ -34,78 +34,58 @@ NOT available: iChannel2/3, iDate, iSampleRate, iChannelResolution, textures/ima
void mainImage(out vec4 fragColor, in vec2 fragCoord) { ...; fragColor = vec4(col, 1.0); } // preferred
// or: void main() { ...; fragColor = vec4(col, 1.0); } using gl_FragCoord.xy
```
-`fragCoord` / `gl_FragCoord.xy` are PIXEL coordinates with origin BOTTOM-LEFT (y up). Use
-`vec2 p = (fragCoord - 0.5*u_resolution) / u_resolution.y;` for aspect-correct centred coords (|y| ≤ 0.5).
-`uv = fragCoord / u_resolution` for 0..1 (also the coordinate to sample u_prev / u_buffer_a).
+`fragCoord` / `gl_FragCoord.xy` are PIXEL coordinates, origin BOTTOM-LEFT, y up (the harness flips rows when
+it writes PNGs, so what you compute is what you see). `u_prev` / `u_buffer_a` are sampled at
+`fragCoord / u_resolution` (0..1). Circles must stay round at the plan's resolution — the judge's
+`stretched_aspect` defect (−0.06): e.g. normalise both axes by `u_resolution.y`.
-## Rules (lint + gates enforce them)
-* GLSL 330 core only: `texture()` not `texture2D`, `in/out` not `varying`, `fragColor` not `gl_FragColor`,
- `mod(x,y)` not `%` on floats, constant loop bounds, `float` literals with a decimal point when in doubt.
-* Do not declare uniforms, `out` variables, `#version`, `precision`, `#include`.
-* Everything must MOVE with `u_time` (unless the brief says "static"): frames at t=0 and t=1 must differ.
- A static result caps the score at 0.5; NaN/Inf pixels cap it at 0; all-black / blown-out frames cap at 0.5.
-* Guard the maths: `x / max(d, 1e-4)`, `sqrt(max(x, 0.0))`, `normalize()` only of non-zero vectors,
- `clamp()` acos/asin inputs, `pow(max(x,0.0), k)`.
-* Keep loop bounds constant and small.
-* Feedback (`u_prev`): sample at `uv` (optionally offset / scaled), mix with the new frame, and DECAY it
- (`prev * 0.9`) — unbounded accumulation blows out. buffer_a.frag reads its own previous frame as `u_prev`;
- shader.frag reads the buffer as `u_buffer_a` and its own previous frame as `u_prev`.
-* Deterministic: no randomness that changes per frame other than as a function of u_time / u_frame.
+## What is measured (the `gl_frames` gate on the judged frames, then the `shader_v2` judge)
+* A NaN / Inf pixel in any frame → ERROR, score cap 0. NaN sources in GLSL: division by zero, sqrt / pow /
+ log of a negative, normalize of a zero vector, acos / asin outside [-1, 1].
+* Every frame essentially black (more than 97 % of its pixels under luminance 0.03) or blown (more than 97 %
+ over 0.98) → ERROR, cap 0.5.
+* When the plan's `motion` is non-empty: the largest mean |Δ| between consecutive sampled frames under 0.002 →
+ `static` WARN, cap 0.5. A brief that asks for a static image is exempt.
+* A consecutive pair with mean |Δ| over 0.35 → `flicker` WARN, cap 0.7.
+* Mean edge density under 0.002 → `low_detail` WARN (no cap; the judge is told).
+* Any lint ERROR → cap 0.6; a build failure (compile error, render timeout) → 0.
+* The judge grades likeness 0.26, depth_and_detail 0.16, light_and_tone 0.16, motion_quality 0.14,
+ composition 0.10, technical_cleanliness 0.10, craft 0.08, with the defect list the system prompt names.
-## Build errors come back as `src/shader.frag:LINE: error: …` (line numbers refer to YOUR file).
-Common messages: "`x' undeclared" (typo / missing helper), "no matching function" (int vs float args →
-add `.0`), "too few components" (vec4(col) where col is vec3 → vec4(col, 1.0)), "redeclaration" (you declared
-a harness uniform — delete it).
+## Rules the lint enforces (ERROR unless noted)
+* GLSL 330 core: `texture()` not `texture2D`; `fragColor` not `gl_FragColor`; no `varying` / `attribute`;
+ `%` is integer-only — `mod(x, y)` on floats.
+* No uniform declarations (the harness's are redeclarations; your own would never be set — use `const`),
+ no `out` variable, no `#version`, no `#include`; a `precision` qualifier is ignored (INFO).
+* Only `u_prev`, `u_noise`, `u_buffer_a` (iChannel0 / iChannel1) may be sampled.
+* `src/common.glsl` must not define `main()` / `mainImage()`. Inside `src/buffer_a.frag` the previous buffer is
+ `u_prev`; sampling `u_buffer_a` there is a WARN.
+* A file over 60 000 characters is a WARN.
-## COMPLETE VERIFIED EXAMPLE — `src/shader.frag` (fbm clouds, drifting, sun on an arc; renders clean)
-```glsl
-// src/shader.frag — "Afternoon cumulus": fbm clouds drifting over a gradient sky with a warm sun.
-// Harness provides: u_time, u_resolution, u_mouse, u_frame, u_prev, u_noise, u_buffer_a, out vec4 fragColor.
-const vec3 SKY_TOP = vec3(0.10, 0.32, 0.78);
-const vec3 SKY_HORIZ = vec3(0.62, 0.78, 0.95);
-const vec3 SUN_COL = vec3(1.00, 0.92, 0.75);
-const vec3 CLOUD_LIT = vec3(1.00, 0.98, 0.95);
-const vec3 CLOUD_SHAD = vec3(0.42, 0.50, 0.68);
+## Build errors
+They come back as `src/shader.frag:LINE: error: …` (line numbers refer to YOUR file). Language facts behind
+the common messages: "no matching function" — an int literal where a float is expected (`pow(2, 3)`,
+`mod(x, 2)`): write `2.0`; "too few components" — `vec4(col)` of a vec3 needs `vec4(col, 1.0)`;
+"redeclaration" — a harness uniform declared again; "`x' undeclared" — a typo or a helper that is not in
+`src/common.glsl`. Loop bounds must be compile-time constants (break early inside); `smoothstep(a, b, x)` is
+undefined for a ≥ b. The render has a wall-clock timeout: a frame that does not finish fails the build.
-float hash12(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
-float noise(vec2 p) {
- vec2 i = floor(p), f = fract(p);
- vec2 u = f * f * (3.0 - 2.0 * f);
- return mix(mix(hash12(i), hash12(i + vec2(1, 0)), u.x), mix(hash12(i + vec2(0, 1)), hash12(i + vec2(1, 1)), u.x), u.y);
-}
-float fbm(vec2 p) { // 6 octaves, constant bound
- float v = 0.0, a = 0.5;
- mat2 m = mat2(0.8, 0.6, -0.6, 0.8);
- for (int i = 0; i < 6; i++) { v += a * noise(p); p = m * p * 2.03 + 0.31; a *= 0.5; }
- return v;
-}
-// cloud density in 0..1 at screen point p (y up), layer k selects parallax speed / scale
-float cloudLayer(vec2 p, float k, float t) {
- vec2 q = p * (2.2 + 0.8 * k) + vec2(t * (0.04 + 0.03 * k), k * 7.3);
- float d = fbm(q + 0.35 * fbm(q * 1.7 - t * 0.02)); // domain warp for billowy edges
- return smoothstep(0.50, 0.70, d);
-}
+## Feedback (`u_prev` / `src/buffer_a.frag`)
+`u_prev` is black at frame 0 and is THIS pass's previous frame. `src/buffer_a.frag` reads its own previous
+output as `u_prev` (its neighbours are at `uv ± 1.0 / u_resolution`) and `src/shader.frag` reads the buffer's
+output as `u_buffer_a`. An accumulation whose gain is ≥ 1 saturates by t = 6 s and trips `blown` (cap 0.5).
+
+## Determinism
+Every frame is a function of the pixel, `u_time` and the samplers only: no per-frame random seeds (the
+`flicker` measure above), nothing that depends on `u_frame` alone.
+## Interface example — `src/shader.frag` (the names in use; lints clean, builds, moves — what it draws is not a suggestion)
+```glsl
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
- vec2 p = (fragCoord - 0.5 * u_resolution.xy) / u_resolution.y; // aspect-correct, centred, y up
- float t = u_time;
- // sky gradient
- vec3 col = mix(SKY_HORIZ, SKY_TOP, smoothstep(-0.35, 0.55, p.y));
- // sun: slow arc; disc + soft glow
- vec2 sunPos = vec2(0.45 * cos(0.12 * t + 2.6), 0.18 + 0.12 * sin(0.12 * t + 2.6));
- float sd = length(p - sunPos);
- col += SUN_COL * (smoothstep(0.05, 0.035, sd) + 0.35 * exp(-8.0 * sd) + 0.08 * exp(-2.0 * sd));
- // two cloud layers, far (dim, slow) then near (bright, fast), lit from the sun side
- for (int k = 0; k < 2; k++) {
- float fk = float(k);
- float dens = cloudLayer(p, fk, t);
- float lit = cloudLayer(p + 0.03 * normalize(sunPos - p + 1e-4), fk, t); // thinner towards the sun = lit
- vec3 cloudCol = mix(CLOUD_SHAD, CLOUD_LIT, clamp(0.9 - 2.5 * (lit - dens) - 0.25 * fk, 0.0, 1.0));
- col = mix(col, cloudCol, dens * (0.55 + 0.45 * fk));
- }
- // haze near the horizon + gentle vignette (colours above are already display-space: just clamp)
- col = mix(col, SKY_HORIZ, 0.25 * smoothstep(0.1, -0.5, p.y));
- col *= 1.0 - 0.20 * dot(p, p);
- fragColor = vec4(clamp(col, 0.0, 1.0), 1.0);
+ vec2 p = (fragCoord - 0.5 * u_resolution) / u_resolution.y; // centred, y up, circles stay round
+ float n = texture(u_noise, p * 0.5 + 0.02 * u_time).r; // the noise texture as a hash
+ float d = length(p - vec2(0.3 * cos(u_time), 0.0));
+ vec3 col = vec3(0.2, 0.3, 0.5) * (0.5 + 0.5 * n) + vec3(1.0, 0.8, 0.5) * exp(-8.0 * d);
+ fragColor = vec4(col, 1.0);
}
```
diff --git a/harness/codeverse3d/prompts/glsl_shader/cookbook.md b/harness/codeverse3d/prompts/glsl_shader/cookbook.md
deleted file mode 100644
index a462e882..00000000
--- a/harness/codeverse3d/prompts/glsl_shader/cookbook.md
+++ /dev/null
@@ -1,293 +0,0 @@
-# glsl_shader cookbook — copyable snippets (GLSL 330 core, harness uniforms u_time / u_resolution / u_prev / u_noise)
-
-All snippets assume `vec2 p = (fragCoord - 0.5*u_resolution) / u_resolution.y;` (centred, aspect-correct,
-y up) and `vec2 uv = fragCoord / u_resolution;` (0..1) unless stated. Put helpers in `src/common.glsl`.
-
-## Hash / noise / fbm
-```glsl
-float hash11(float p) { p = fract(p * 0.1031); p *= p + 33.33; p *= p + p; return fract(p); }
-float hash12(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
-vec2 hash22(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); }
-vec3 hash33(vec3 p) { p = fract(p * vec3(0.1031, 0.1030, 0.0973)); p += dot(p, p.yxz + 33.33); return fract((p.xxy + p.yxx) * p.zyx); }
-float noise(vec2 p) { // value noise 0..1, smooth
- vec2 i = floor(p), f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f);
- return mix(mix(hash12(i), hash12(i + vec2(1, 0)), u.x), mix(hash12(i + vec2(0, 1)), hash12(i + vec2(1, 1)), u.x), u.y);
-}
-float noise3(vec3 p) { // 3D value noise (volumes, time as z)
- vec3 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);
- float n000 = hash33(i).x, n100 = hash33(i + vec3(1,0,0)).x, n010 = hash33(i + vec3(0,1,0)).x, n110 = hash33(i + vec3(1,1,0)).x;
- float n001 = hash33(i + vec3(0,0,1)).x, n101 = hash33(i + vec3(1,0,1)).x, n011 = hash33(i + vec3(0,1,1)).x, n111 = hash33(i + vec3(1,1,1)).x;
- return mix(mix(mix(n000, n100, f.x), mix(n010, n110, f.x), f.y), mix(mix(n001, n101, f.x), mix(n011, n111, f.x), f.y), f.z);
-}
-float fbm(vec2 p) { // 6 octaves, constant bound, rotated per octave
- float v = 0.0, a = 0.5; mat2 m = mat2(0.8, 0.6, -0.6, 0.8);
- for (int i = 0; i < 6; i++) { v += a * noise(p); p = m * p * 2.03 + 0.31; a *= 0.5; }
- return v;
-}
-float ridged(vec2 p) { float v = 0.0, a = 0.5; for (int i = 0; i < 5; i++) { v += a * (1.0 - abs(2.0 * noise(p) - 1.0)); p *= 2.1; a *= 0.5; } return v; }
-// cheap texture noise (GPU-fast): float n = texture(u_noise, p * 0.37 + u_time * 0.01).r;
-```
-
-## Domain warping (billowy clouds, smoke, marble)
-```glsl
-float warped(vec2 p, float t) {
- vec2 q = vec2(fbm(p + vec2(0.0, t * 0.05)), fbm(p + vec2(5.2, 1.3)));
- vec2 r = vec2(fbm(p + 4.0 * q + vec2(1.7, 9.2) + 0.15 * t), fbm(p + 4.0 * q + vec2(8.3, 2.8)));
- return fbm(p + 4.0 * r);
-}
-```
-
-## Volume lighting (smoke, clouds, fog)
-These are transport helpers for a bounded raymarch, not a fluid simulation. Use world metres for
-distance and inverse metres for extinction; density is a nonnegative multiplier. Accumulate front
-to back as `colour += transmittance * (1.0-stepT) * litColour; transmittance *= stepT`, then composite
-`colour + transmittance * background`. A light-direction density march supplies self-shadowing.
-For `phaseHG`, cosTheta is the dot of the incoming and outgoing LIGHT TRAVEL directions; +1 is forward
-scattering. If `rd` points from camera into the scene and `toSun` points toward the sun, use `dot(rd,toSun)`.
-```glsl
-float fbmVolume(vec3 p) {
- float value = 0.0, amplitude = 0.5;
- for (int i = 0; i < 5; i++) {
- value += amplitude * noise3(p);
- p = p.yzx * 2.03 + vec3(13.1, 7.7, 19.3); amplitude *= 0.5;
- }
- return value / 0.96875;
-}
-float beerTransmittance(float extinction, float distance) {
- return exp(-max(extinction, 0.0) * max(distance, 0.0));
-}
-float phaseHG(float cosTheta, float g) {
- g = clamp(g, -0.95, 0.95);
- float d = max(1.0 + g*g - 2.0*g*clamp(cosTheta, -1.0, 1.0), 1e-5);
- return (1.0-g*g) / (12.56637061 * d * sqrt(d));
-}
-```
-The phase function integrates to one over the sphere. Do not silently omit its `1/(4*pi)` and then
-compensate with exposure. See [PBRT's phase-function discussion](https://pbr-book.org/4ed/Volume_Scattering/Phase_Functions)
-for direction conventions; this recipe uses travel directions, whereas PBRT's API uses two outward directions.
-
-## Physical surface lighting (metal, dielectric, roughness)
-Direct single-scattering GGX with correlated Smith visibility and Schlick Fresnel. Inputs are LINEAR;
-`n`, `v` (toward camera) and `l` (toward light) are unit vectors in the same coordinate space. The
-result includes the incident cosine. Supply actual light radiance; use an environment reflection for
-indirect specular. This is a surface BRDF, without transmission, multiple scattering or area-light integration.
-```glsl
-vec3 fresnelSchlick(float cosine, vec3 f0) {
- return f0 + (vec3(1.0)-f0) * pow(1.0-clamp(cosine,0.0,1.0),5.0);
-}
-vec3 pbrDirect(vec3 albedo, float metallic, float roughness, vec3 n, vec3 v, vec3 l, vec3 radiance) {
- float nv = max(dot(n,v),0.0), nl = max(dot(n,l),0.0);
- if (nv <= 0.0 || nl <= 0.0) return vec3(0.0);
- vec3 h = normalize(v+l);
- float nh = max(dot(n,h),0.0), vh = max(dot(v,h),0.0);
- float a = pow(clamp(roughness,0.045,1.0),2.0), a2 = a*a;
- float d = nh*nh*(a2-1.0)+1.0;
- float distribution = a2 / max(3.14159265*d*d,1e-12);
- float visibility = 0.5 / max(nl*sqrt(nv*nv*(1.0-a2)+a2) + nv*sqrt(nl*nl*(1.0-a2)+a2),1e-7);
- metallic = clamp(metallic,0.0,1.0); albedo = clamp(albedo,0.0,1.0);
- vec3 f = fresnelSchlick(vh,mix(vec3(0.04),albedo,metallic));
- vec3 diffuse = (1.0-metallic)*(vec3(1.0)-f)*albedo/3.14159265;
- return (diffuse + f*distribution*visibility) * max(radiance,0.0) * nl;
-}
-```
-Roughness changes the distribution and masking of microfacet reflections; a shiny colour alone cannot
-replace it. See [PBRT's microfacet model](https://pbr-book.org/4ed/Reflection_Models/Roughness_Using_Microfacet_Theory).
-
-## Palettes, tonemapping, grading
-```glsl
-vec3 palette(float t, vec3 a, vec3 b, vec3 c, vec3 d) { return a + b * cos(6.28318 * (c * t + d)); }
-// e.g. neon: palette(t, vec3(0.5), vec3(0.5), vec3(1.0), vec3(0.0, 0.33, 0.67))
-// sunset: palette(t, vec3(0.5,0.4,0.3), vec3(0.5,0.4,0.3), vec3(1.0), vec3(0.0,0.1,0.2))
-vec3 tonemapACES(vec3 x) { return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), 0.0, 1.0); }
-vec3 gamma(vec3 c) { return pow(max(c, 0.0), vec3(1.0 / 2.2)); }
-// final line for HDR-ish accumulations: fragColor = vec4(gamma(tonemapACES(col)), 1.0);
-// vignette: col *= 1.0 - 0.35 * dot(p, p); // dithering against banding: col += (hash12(fragCoord) - 0.5) / 255.0;
-```
-
-## SDF 2D shapes + anti-aliased edges
-```glsl
-float sdCircle(vec2 p, float r) { return length(p) - r; }
-float sdBox(vec2 p, vec2 b) { vec2 d = abs(p) - b; return length(max(d, 0.0)) + min(max(d.x, d.y), 0.0); }
-float sdSegment(vec2 p, vec2 a, vec2 b) { vec2 pa = p - a, ba = b - a; float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-12), 0.0, 1.0); return length(pa - ba * h); }
-// A concave n-point star, outer radius r, inner radius 0.45*r; first tip points +x.
-// Fold into one half-sector, then measure the actual outer-to-inner edge.
-float sdStar(vec2 p, float r, float n) {
- if (r <= 0.0) return length(p);
- float halfSector = 3.14159265 / clamp(floor(n + 0.5), 2.0, 64.0);
- float angle = abs(mod(atan(p.y, p.x) + halfSector, 2.0 * halfSector) - halfSector);
- vec2 q = length(p) * vec2(cos(angle), sin(angle));
- vec2 a = vec2(r, 0.0), b = 0.45 * r * vec2(cos(halfSector), sin(halfSector));
- vec2 edge = b - a, fromTip = q - a;
- float side = edge.x * fromTip.y - edge.y * fromTip.x;
- return sdSegment(q, a, b) * (side >= 0.0 ? -1.0 : 1.0);
-}
-float fill(float d) { float aa = max(fwidth(d), 1e-6); return 1.0 - smoothstep(-0.5 * aa, 0.5 * aa, d); }
-float stroke(float d, float w) { float aa = max(fwidth(d), 1e-6); return w <= 0.0 ? 0.0 : 1.0 - smoothstep(w - 0.5 * aa, w + 0.5 * aa, abs(d)); }
-float glow(float d, float k) { return exp(-k * max(d, 0.0)); }
-mat2 rot2(float a) { float c = cos(a), s = sin(a); return mat2(c, -s, s, c); }
-```
-
-## Raymarching template (3D sdf scene with lighting, fog, sky)
-```glsl
-float sdSphere(vec3 p, float r) { return length(p) - r; }
-float sdBox3(vec3 p, vec3 b) { vec3 q = abs(p) - b; return length(max(q, 0.0)) + min(max(q.x, max(q.y, q.z)), 0.0); }
-float sdTorus(vec3 p, vec2 t) { vec2 q = vec2(length(p.xz) - t.x, p.y); return length(q) - t.y; }
-float smin(float a, float b, float k) { if (k <= 0.0) return min(a, b); float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); }
-float map(vec3 p) { // the scene: ground + bobbing blobs
- float ground = p.y + 1.0;
- vec3 q = p; q.xz = mod(q.xz + 2.0, 4.0) - 2.0; // repetition
- float blob = sdSphere(q - vec3(0.0, 0.3 * sin(u_time + p.x), 0.0), 0.7);
- return smin(ground, blob, 0.5);
-}
-vec3 calcNormal(vec3 p) { vec2 e = vec2(1e-3, 0.0); return normalize(vec3(map(p + e.xyy) - map(p - e.xyy), map(p + e.yxy) - map(p - e.yxy), map(p + e.yyx) - map(p - e.yyx))); }
-float softShadow(vec3 ro, vec3 rd) { float res = 1.0, t = 0.05; for (int i = 0; i < 32; i++) { float h = map(ro + rd * t); res = min(res, 10.0 * h / t); t += clamp(h, 0.02, 0.5); if (h < 1e-3 || t > 20.0) break; } return clamp(res, 0.0, 1.0); }
-void mainImage(out vec4 fragColor, in vec2 fragCoord) {
- vec2 p = (fragCoord - 0.5 * u_resolution.xy) / u_resolution.y;
- vec3 ro = vec3(3.0 * cos(0.2 * u_time), 1.0, 3.0 * sin(0.2 * u_time)); // orbiting camera
- vec3 ta = vec3(0.0, 0.0, 0.0);
- vec3 ww = normalize(ta - ro), uu = normalize(cross(ww, vec3(0, 1, 0))), vv = cross(uu, ww);
- vec3 rd = normalize(p.x * uu + p.y * vv + 1.6 * ww);
- float t = 0.0; bool hit = false;
- for (int i = 0; i < 96; i++) { float d = map(ro + rd * t); if (d < 1e-3) { hit = true; break; } t += d; if (t > 40.0) break; }
- vec3 sky = mix(vec3(0.9, 0.8, 0.7), vec3(0.2, 0.4, 0.8), smoothstep(-0.1, 0.5, rd.y));
- vec3 col = sky;
- if (hit) {
- vec3 pos = ro + rd * t, n = calcNormal(pos), lig = normalize(vec3(0.6, 0.8, 0.3));
- float dif = max(dot(n, lig), 0.0) * softShadow(pos + n * 0.01, lig), amb = 0.5 + 0.5 * n.y;
- vec3 mat = vec3(0.8, 0.5, 0.3);
- col = mat * (dif * vec3(1.0, 0.9, 0.7) + amb * vec3(0.2, 0.3, 0.45));
- col = mix(col, sky, 1.0 - exp(-0.02 * t * t)); // fog
- }
- fragColor = vec4(pow(col, vec3(0.4545)), 1.0);
-}
-```
-
-## Gradient sky, sun, stars, water
-```glsl
-vec3 skyGrad(vec2 p) { return mix(vec3(0.95, 0.6, 0.35), vec3(0.1, 0.25, 0.6), smoothstep(-0.3, 0.6, p.y)); }
-float sun(vec2 p, vec2 c, float r) { float d = length(p - c); r = max(r, 1e-6); return 1.0 - smoothstep(r * 0.8, r, d) + 0.3 * exp(-8.0 * d); }
-// DENSE STARS: thousands of sub-pixel points, a few brighter; keep = fraction of cells that hold a star (0.2-0.3).
-// Two layers (density 160 and 70) read as a real sky; twenty twinkling sparkles do not (that version cost a run).
-float stars(vec2 p, float density, float keep) {
- vec2 g = floor(p * density), f = fract(p * density);
- float h = hash12(g); vec2 o = hash22(g) * 0.7 + 0.15;
- float d = length(f - o); // cell units
- float size = 0.07 + 0.10 * step(0.97, h); // a few are bigger / brighter
- return step(1.0 - keep, h) * exp(-d * d / (size * size)) * (0.35 + 0.65 * hash12(g + 9.0));
-}
-// usage: col += vec3(0.9, 0.95, 1.0) * (stars(p, 160.0, 0.22) * 0.55 + stars(p + 3.7, 70.0, 0.25) * 0.9);
-float waterHeight(vec2 xz, float t) { return 0.05 * sin(xz.x * 4.0 + t * 1.5) + 0.03 * sin(xz.y * 6.0 - t * 1.1) + 0.04 * (noise(xz * 3.0 + t * 0.4) - 0.5); }
-// water colour: mix(deep, shallow, fresnel) + specular: pow(max(dot(reflect(-lig, n), -rd), 0.0), 64.0)
-```
-
-## Rain / drops on glass (grid cells + trails, refracted background)
-```glsl
-vec2 dropsLayer(vec2 uv, float t, float scale) { // returns (mask, trail)
- vec2 asp = vec2(2.0, 1.0); vec2 st = uv * scale * asp + vec2(0.0, t * 0.25);
- vec2 id = floor(st); float n = hash12(id); // identities move WITH the falling cells
- vec2 f = fract(st) - 0.5;
- f.x += (hash12(id + 17.0) - 0.5) * 0.35;
- float w = sin(t + n * 6.28) * (0.5 - abs(f.y)) ; f.x += w * 0.3; // wobble
- vec2 d = f * vec2(1.0, 2.0);
- float drop = 1.0 - smoothstep(0.05, 0.1, length(d));
- float trail = (1.0 - smoothstep(0.0, 0.1, abs(f.x))) *
- (1.0 - smoothstep(0.1, 0.5, f.y)) * smoothstep(0.02, 0.1, f.y) * 0.5;
- return vec2(drop, trail) * step(0.3, n);
-}
-// usage: vec2 dr = dropsLayer(uv, u_time, 8.0); vec2 off = dr.x * 0.03 * normalize(p + 1e-3); col = background(uv + off);
-```
-
-## Bokeh city lights (soft discs ADDED on a dark ground, depth layers, pulsing)
-Soft gaussian discs added on a near-black ground with muted warm/cool tints — the hard `smoothstep` discs in
-full-saturation `palette()` colours this recipe used to hold read as opaque candy and cost a run.
-```glsl
-// SOFT BOKEH: gaussian discs ADDED on a dark ground, dim, muted tints — not opaque smoothstep circles.
-vec3 bokehSoft(vec2 p, float t) {
- vec3 acc = vec3(0.0);
- for (int layer = 0; layer < 3; layer++) {
- float fl = float(layer), scale = 4.0 + 3.0 * fl;
- vec2 q = p * scale + vec2(t * (0.02 + 0.01 * fl), 0.0);
- vec2 id = floor(q), f = fract(q) - 0.5;
- for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) {
- vec2 o = vec2(i, j); vec2 h = hash22(id + o); vec2 c = o + h - 0.5;
- float r = 0.12 + 0.12 * hash12(id + o + 7.0);
- float d = length(f - c);
- float disc = exp(-d * d / (r * r)) * (1.0 - smoothstep(r * 0.6, r * 1.6, d)); // soft core, soft rim
- disc *= 0.7 + 0.3 * sin(t * (0.5 + h.x) + h.y * 6.28); // gentle pulsing
- vec3 tint = mix(vec3(0.9, 0.6, 0.3), vec3(0.3, 0.6, 0.9), h.x) * (0.5 + 0.5 * h.y); // warm/cool, muted
- acc += disc * tint * (0.28 + 0.18 * fl); // many small adds on a dark ground, never a flat fill
- }
- }
- return acc;
-}
-```
-
-## Light phenomena look like LIGHT, not paint (aurora, curtains, glow)
-Three habits, each one cost a real run (2026-08-26, frames judged by eye): an aurora drawn as a comb of evenly
-spaced vertical bars; bokeh as hard opaque candy discs; a "star field" of twenty sparkles. Light has soft
-falloff, sits on real darks, and is dense at fine scale. Verified recipe (rendered and looked at):
-```glsl
-// ORGANIC CURTAIN (aurora, drapery, flame sheets): a ribbon whose LOWER EDGE wanders and folds, sharp below,
-// fading upward, with fine vertical rays grouped in bundles and gaps where the ribbon thins out. Never a comb.
-// k = 0 at the lower edge .. 1 at the top (drive the green -> violet gradient with it).
-float curtain(vec2 p, float t, float seed, out float k) {
- float xw = p.x + 0.55 * (fbm(vec2(p.x * 0.7 + seed, t * 0.05 + seed * 2.0)) - 0.5); // horizontal folding (domain warp)
- float base = -0.08 + 0.11 * sin(xw * 2.3 + seed * 1.7 + t * 0.07)
- + 0.16 * fbm(vec2(xw * 2.0 + seed * 3.1, 0.7 + t * 0.06)); // a long arc + a sinuous lower edge
- float h = 0.22 + 0.25 * fbm(vec2(xw * 0.6 + seed * 5.0, 2.0 + t * 0.03)); // how tall the curtain is here
- float d = p.y - base; k = clamp(d / h, 0.0, 1.0);
- float rays = 0.45 + 0.55 * noise(vec2(xw * 55.0 + t * 0.9, seed)); // fine vertical striations ...
- rays *= 0.55 + 0.45 * noise(vec2(xw * 12.0 - t * 0.25, seed + 3.0)); // ... grouped into bundles
- float lower = smoothstep(-0.02 - 0.05 * rays, 0.012, d); // bright lower edge, ragged by the rays
- float upper = exp(-max(d, 0.0) / h * 1.7); // fades out upward
- float gaps = smoothstep(0.36, 0.66, fbm(vec2(xw * 1.6 + seed * 7.0, t * 0.04))); // the ribbon thins and breaks
- return lower * upper * rays * gaps;
-}
-vec3 auroraCol(float k) { return mix(vec3(0.10, 0.95, 0.42), vec3(0.70, 0.20, 0.85), smoothstep(0.18, 0.9, k)); } // green low, violet crown
-vec3 aurora(vec2 p, float t) { // three curtains at different depths: nearest brightest
- vec3 acc = vec3(0.0); float k = 0.0;
- float a = curtain(p, t, 0.0, k); acc += auroraCol(k) * a; // curtain() sets k
- a = curtain(p - vec2(0.3, 0.12), t * 0.8, 11.0, k); acc += auroraCol(k) * a * 0.55;
- a = curtain(p - vec2(-0.5, 0.22), t * 0.6, 23.0, k); acc += auroraCol(k) * a * 0.30;
- return acc; // then: col += au * 1.7 + au * au * 0.5; (bloom on the bright edge)
-}
-```
-Tonal discipline for any night / space / dusk subject: start from a near-black ground (`vec3(0.02, 0.035, 0.08)` at
-the horizon → `vec3(0, 0, 0.012)` at the zenith), ADD light, tonemap `c / (1 + 0.6 c)`, and check `gl_frames`: mean
-luminance 0.06–0.15 is a night scene; 0.3 with no black pixels is a wash. Haze and bloom go on the light, not on
-the frame. Stars: `stars()` above (two layers, keep 0.2–0.3); city lights: `bokehSoft()` above. Complete verified
-example (aurora over a ridge with a frozen lake, three curtains, 5 k stars, blurred reflection): the harness ships
-it as `codeverse3d/prompts/glsl_shader/examples/aurora_ridge.frag`.
-
-## Feedback trails (u_prev) and Buffer A
-```glsl
-// shader.frag: decayed feedback + new emitter (particles / light streaks)
-vec3 prev = texture(u_prev, uv + vec2(0.0, -0.002)).rgb * 0.94; // drift + decay keeps it bounded
-vec3 col = max(prev, newFrameColour); // or prev + newFrameColour * 0.2
-fragColor = vec4(col, 1.0);
-// buffer_a.frag computes a simulation (e.g. reaction-diffusion, fluid-ish blur) reading texture(u_prev, uv) and its
-// 4 neighbours (uv ± 1.0/u_resolution); shader.frag then colours texture(u_buffer_a, uv).
-```
-
-## Instancing-like repetition in 2D (many shapes cheaply)
-```glsl
-// grid of rotating squares: vec2 g = p * 8.0; vec2 id = floor(g); vec2 f = fract(g) - 0.5;
-// f = rot2(u_time * (0.5 + hash12(id))) * f; float d = sdBox(f, vec2(0.25)); col += fill(d) * palette(hash12(id), ...);
-```
-
-## PITFALLS (each one cost a real run)
-* Integer division / int literals: `1/2 == 0`; `float x = 3;` is fine but `pow(2, 3)` / `mod(x, 2)` may fail on strict
- drivers → always `2.0`. `%` is integer-only → `mod()`.
-* Loop bounds must be constant expressions (`for (int i = 0; i < 64; i++)`), break early inside.
-* `normalize(vec3(0))` / `0/0` / `sqrt(-x)` / `pow(neg, 0.5)` / `log(0)` → NaN → black speckles → score 0. Guard them.
-* `texture(u_prev, uv)` needs uv in 0..1 (fragCoord / u_resolution), NOT the centred `p`.
-* Aspect: divide by `u_resolution.y`, never by `u_resolution.xy` for shapes (ellipses otherwise).
-* `smoothstep(a, b, x)` needs a < b; AA width ≈ `1.5 / u_resolution.y`.
-* Brightness: accumulations (glow, bokeh sums) blow out → tonemap (`c/(1+c)` or ACES) before gamma; do not gamma twice.
-* Motion: use u_time directly (`sin(u_time)`, `u_time*0.2` as a noise offset); do NOT use u_frame alone (frames are sampled at
- arbitrary times) and never seed per-frame randomness with u_frame (flicker).
-* `precision` qualifiers, `#version`, `#extension`, `#include`, `uniform` / `out` declarations: leave them out.
-* gl_FragCoord origin is bottom-left; y up. (The harness flips rows when writing PNGs, so what you compute is what you see.)
-* Symmetric patterns at t=0 (everything at the origin) look dead — offset phases with hashes.
-* A light phenomenon drawn as evenly spaced bars / hard discs / a flat wash: the judge's likeness criterion scores it
- 0.4 — see the Light section.
diff --git a/harness/codeverse3d/prompts/glsl_shader/examples/aurora_ridge.frag b/harness/codeverse3d/prompts/glsl_shader/examples/aurora_ridge.frag
deleted file mode 100644
index 1b85fe73..00000000
--- a/harness/codeverse3d/prompts/glsl_shader/examples/aurora_ridge.frag
+++ /dev/null
@@ -1,83 +0,0 @@
-// Aurora over a ridge with a frozen lake — organic curtains, dense stars, real darks.
-float hash12(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
-vec2 hash22(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); }
-float noise(vec2 p) { vec2 i = floor(p), f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f);
- return mix(mix(hash12(i), hash12(i + vec2(1, 0)), u.x), mix(hash12(i + vec2(0, 1)), hash12(i + vec2(1, 1)), u.x), u.y); }
-float fbm(vec2 p) { float v = 0.0, a = 0.5; mat2 m = mat2(0.8, 0.6, -0.6, 0.8);
- for (int i = 0; i < 6; i++) { v += a * noise(p); p = m * p * 2.03 + 0.31; a *= 0.5; } return v; }
-
-// ---- ORGANIC CURTAIN: a ribbon whose lower edge wanders and folds, sharp below, fading above, with fine vertical rays
-// returns intensity 0..1 and writes k = 0 at the lower edge .. 1 at the top (for the green->violet gradient)
-float curtain(vec2 p, float t, float seed, out float k) {
- float xw = p.x + 0.55 * (fbm(vec2(p.x * 0.7 + seed, t * 0.05 + seed * 2.0)) - 0.5); // horizontal folding (domain warp)
- float base = -0.08 + 0.11 * sin(xw * 2.3 + seed * 1.7 + t * 0.07) + 0.16 * fbm(vec2(xw * 2.0 + seed * 3.1, 0.7 + t * 0.06)); // a long arc + sinuous lower edge
- float h = 0.22 + 0.25 * fbm(vec2(xw * 0.6 + seed * 5.0, 2.0 + t * 0.03)); // how tall the curtain is here
- float d = p.y - base; // height above the lower edge
- k = clamp(d / h, 0.0, 1.0);
- float rays = 0.45 + 0.55 * noise(vec2(xw * 55.0 + t * 0.9, seed)); // fine vertical striations
- rays *= 0.55 + 0.45 * noise(vec2(xw * 12.0 - t * 0.25, seed + 3.0)); // grouped into bundles
- float lower = smoothstep(-0.02 - 0.05 * rays, 0.012, d); // bright lower edge, ragged by the rays
- float upper = exp(-max(d, 0.0) / h * 1.7); // fades out upward
- float gaps = smoothstep(0.36, 0.66, fbm(vec2(xw * 1.6 + seed * 7.0, t * 0.04))); // the ribbon thins and breaks
- return lower * upper * rays * gaps;
-}
-vec3 auroraCol(float k) { return mix(vec3(0.10, 0.95, 0.42), vec3(0.70, 0.20, 0.85), smoothstep(0.18, 0.9, k)); }
-vec3 aurora(vec2 p, float t) {
- vec3 acc = vec3(0.0);
- float k = 0.0;
- float a0 = curtain(p, t, 0.0, k); acc += auroraCol(k) * a0 * 1.00; // nearest, brightest
- float a1 = curtain(p - vec2(0.3, 0.12), t * 0.8, 11.0, k); acc += auroraCol(k) * a1 * 0.55;
- float a2 = curtain(p - vec2(-0.5, 0.22), t * 0.6, 23.0, k); acc += auroraCol(k) * a2 * 0.30;
- return acc;
-}
-// ---- DENSE STARS: two layers, thousands of points, two brightness classes, no twinkle blobs
-float stars(vec2 p, float density, float keep) {
- vec2 g = floor(p * density), f = fract(p * density);
- float h = hash12(g); vec2 o = hash22(g) * 0.7 + 0.15;
- float d = length(f - o); // distance in cell units (0..0.7)
- float bright = step(1.0 - keep, h); // keep-fraction of cells hold a star
- float size = 0.07 + 0.10 * step(0.97, h); // a few are bigger/brighter
- return bright * exp(-d * d / (size * size)) * (0.35 + 0.65 * hash12(g + 9.0));
-}
-float ridge(float x) { return -0.02 + 0.16 * fbm(vec2(x * 1.7 + 3.0, 1.0)) + 0.06 * fbm(vec2(x * 6.0, 4.0)); }
-
-void mainImage(out vec4 fragColor, in vec2 fragCoord) {
- vec2 p = (fragCoord - 0.5 * u_resolution.xy) / u_resolution.y; // |y| <= 0.5, y up
- float t = u_time;
- float horizon = -0.18; // lake surface
- vec3 col = mix(vec3(0.02, 0.035, 0.08), vec3(0.0, 0.0, 0.012), smoothstep(-0.15, 0.45, p.y)); // near-black sky, faint blue at the horizon
- // stars (only above the ridge; dense, small)
- col += vec3(0.9, 0.95, 1.0) * (stars(p, 160.0, 0.22) * 0.55 + stars(p + 3.7, 70.0, 0.25) * 0.9);
- // aurora — the brightest thing in the frame, drifting sideways
- vec3 au = aurora(vec2(p.x + t * 0.015, p.y - horizon - 0.16), t);
- col += au * 1.7;
- col += au * au * 0.5; // a little bloom on the bright lower edges
- // mountain ridge silhouette (flat near-black, thin snow line on the sunlit crest)
- float r = horizon + 0.06 + ridge(p.x);
- float ridgeMask = smoothstep(r + 0.002, r - 0.002, p.y);
- vec3 ridgeCol = vec3(0.012, 0.014, 0.02) + au * 0.03; // a hint of aurora light on the rock
- ridgeCol += vec3(0.5, 0.6, 0.7) * smoothstep(0.006, 0.0, abs(p.y - r)) * 0.25; // snow line
- col = mix(col, ridgeCol, ridgeMask);
- // frozen lake: blurred vertical mirror of the sky + ridge, dimmer, with faint shimmer lines
- if (p.y < horizon) {
- float dy = horizon - p.y;
- float shimmer = 0.006 * sin(p.y * 220.0 + t * 1.5) * noise(vec2(p.x * 8.0, t * 0.3));
- vec2 rp = vec2(p.x + shimmer, horizon + dy * 1.05); // mirrored point
- vec3 refl = vec3(0.0);
- for (int i = 0; i < 4; i++) { // cheap vertical blur
- vec2 q = rp + vec2(0.0, float(i) * 0.006);
- vec3 c = mix(vec3(0.02, 0.035, 0.08), vec3(0.0), smoothstep(-0.15, 0.45, q.y));
- vec3 a = aurora(vec2(q.x + t * 0.015, q.y - horizon - 0.16), t);
- float rr = horizon + 0.06 + ridge(q.x);
- c += a * 1.15; c = mix(c, vec3(0.012, 0.014, 0.02), smoothstep(rr + 0.002, rr - 0.002, q.y));
- refl += c;
- }
- refl *= 0.25;
- col = refl * 0.55 * (1.0 - smoothstep(0.0, 0.32, dy) * 0.5) + vec3(0.005, 0.008, 0.015);
- col += vec3(0.02, 0.05, 0.05) * smoothstep(0.02, 0.0, dy); // faint bright shore line
- }
- // grade: keep the darks, tonemap the aurora, vignette
- col = col / (1.0 + col * 0.6);
- col *= 1.0 - 0.35 * dot(p * vec2(0.9, 1.4), p * vec2(0.9, 1.4));
- fragColor = vec4(pow(max(col, 0.0), vec3(0.95)), 1.0);
-}
diff --git a/harness/codeverse3d/prompts/glsl_shader/system.md b/harness/codeverse3d/prompts/glsl_shader/system.md
index ffc2ada6..62d187f8 100644
--- a/harness/codeverse3d/prompts/glsl_shader/system.md
+++ b/harness/codeverse3d/prompts/glsl_shader/system.md
@@ -2,8 +2,7 @@ You are a GLSL fragment-shader artist writing a raw Shadertoy-style body for a h
harness. You own every pixel of one image pass. There is no state between pixels, and none
between frames unless you opt into the feedback buffer (`u_prev` / `buffer_a.frag`, see the
contract): otherwise every frame is a pure function of the pixel and of absolute `u_time`.
-The harness owns the `#version` header, the uniform block and `recipes.glsl` — never
-redeclare them.
+The harness owns the `#version` header and the uniform block — never redeclare them.
{% if tools %}
The loop that decides whether your work ships:
@@ -15,46 +14,42 @@ Do not finish while `gl_probe` reports anything. This is not advice. On a measur
ten-rung ladder of shader briefs, the agent that ran this loop compiled 10 of 10 and the
one given the same reference material WITHOUT the loop compiled 5 of 10 — and the loop's
code came out shorter and cheaper, not longer. A single unreported compile error reads to
-you as "this idea does not work" when the truth is "you left out an include".
+you as "this idea does not work" when the truth is "you left out a declaration".
{% else %}
You cannot run anything: this is a single-shot session with no tools, so the code you
return is the code that ships. Read it back before you finish as if you were the
-compiler — an undeclared name, a missing include, a term multiplied to zero. On a
+compiler — an undeclared name, a function used before its definition, a term multiplied to zero. On a
measured ten-rung ladder of shader briefs, the sessions that could compile-and-fix
before finishing got 10 of 10 to build and the ones that could not got 5 of 10; you
are in the second group, so spend the care up front.
-
-* **Compiles but invisible** — the effect is in source and contributes nothing to the
- frame. Check the final `fragColor` write, the raymarch hit test, the ray direction,
- and whether a term is multiplied to zero.
{% endif %}
-What the judge will name if you skip it:
-
-* **Compiles but invisible** — the effect is there in source and contributes nothing to the
- frame. Check the final `fragColor` write, the raymarch hit test, the ray direction, and
- whether a term is multiplied to zero.
-* **One-scale noise** — a single octave at a single frequency both aliases and reads flat.
- Real surfaces carry structure at two or three scales.
-* **Scrolled uv standing in for motion** — a still image with a sliding texture over it. Move
- what is *in* the scene, at more than one rate.
-* **A radial blob standing in for directional light** — a light shaft has a direction and a
- soft edge; a centred falloff has neither.
-* **Stepped gradients** — smooth skies, glows and fog quantise into visible bands on an
- 8-bit screen (banding_or_aliasing: 3 of 6 fancy-battery runs, 2026-08-31). The cause is
- almost always a missing final dither.
-
-Three rules that survive every brief:
-
-* Everything is a smooth function of absolute `u_time`. No frame counters, no per-frame
- seeds, and never a hand-rolled `fract`/`mod` wrap of raw time — that is a visible cut
- between two sampled frames.
-* **Light before colour.** Get the frame into a readable band first; hue and palette work
- is invisible on dark, low-chroma pixels. A subject in daylight sits near half the
- brightness of its own sky — a fifth is underlit, not moody.
-* **Dither last.** The final colour op of every shader, after tonemap and gamma:
- `col += (hash12(fragCoord) - 0.5) / 255.0;` — it breaks the 8-bit steps that band in
- every smooth gradient. Nothing writes to `fragColor` after it.
+What the harness measures before any judge looks (thresholds in the contract): the frames at
+t = 0, 1, 2.5, 4, 6 s must differ when motion is planned (`static`, cap 0.5) and never jump
+(`flicker`, cap 0.7); no NaN pixel (cap 0); no black or blown frame (cap 0.5); no lint ERROR
+(cap 0.6). `u_frame` is not a clock — the sampled times are not evenly spaced.
+
+What the judge (`shader_v2`) names, and what each costs:
+
+* **Likeness (0.26)** — the thing drawn with the wrong physics scores 0.4 however complete
+ its inventory: evenly spaced bars standing in for curtains, rays, flames or waves
+ (`comb_artefact`, −0.10, cap 0.65); hard-edged opaque shapes standing in for light —
+ bokeh, glow, aurora, neon (`opaque_shapes_for_light`, −0.08); a few sparkles for a star
+ field (the judge's own scale relation: a star field is thousands of points); a flat wash
+ for a nebula.
+* **Depth and detail (0.16)** — one texture, gradient or noise field filling the frame is
+ `flat_fill` (−0.08) and the criterion's 0.1 anchor; staircase edges and stepped gradients are
+ `banding_or_aliasing` (−0.05, and a technical_cleanliness deduction).
+* **Light and tone (0.16)** — a night, space or dusk subject with nothing near-black is
+ `no_dark_range` (−0.06); haze or bloom lifting a region toward white is `white_wash`
+ (−0.08); uniformly candy-saturated colour with no dark counterweight is
+ `candy_saturation` (−0.06).
+* **Motion (0.14)** — a texture scrolling under a fixed shape is 0.5; a hard cut between two
+ sampled times is `flicker` (−0.08, cap 0.70).
+* **Placeholder look (−0.10)** — a textbook demo with the brief's colours swapped in.
+* **Compiles but invisible** — the effect is in source and contributes nothing to the frame
+ (`wrong_subject`, cap 0.40). Check the final `fragColor` write, the raymarch hit test,
+ the ray direction, and whether a term is multiplied to zero.
A clean simpler effect beats a richer one carrying a visible defect. Clear NaN, black,
blown and static before you add the next layer; deleting a layer is a legitimate fix.
diff --git a/harness/codeverse3d/prompts/opengl_python/contract.md b/harness/codeverse3d/prompts/opengl_python/contract.md
index 0262dc5b..48f3ff5e 100644
--- a/harness/codeverse3d/prompts/opengl_python/contract.md
+++ b/harness/codeverse3d/prompts/opengl_python/contract.md
@@ -1,15 +1,18 @@
# opengl_python authoring contract (raw OpenGL 3.3 core through moderngl, headless)
-You write ONE python module, `src/program.py`, that draws frames with raw OpenGL calls (moderngl API)
+You write ONE python module, `src/program.py`, that draws frames with raw OpenGL calls (the moderngl API)
and inline GLSL. The harness imports it in a headless EGL process, creates the context and an output
-framebuffer, calls your two functions, reads the pixels back (PNG per frame at t = 0, 1, 2.5, 4, 6 s +
-preview GIF), measures and judges them. The code is the deliverable.
+framebuffer, calls your two functions and reads the pixels back (a PNG per frame at t = 0, 1, 2.5, 4, 6 s,
+clipped to the plan's duration and never fewer than 3 samples, plus about 12 preview frames for the GIF),
+measures the judged frames and shows them to a judge. The code is the deliverable.
## Files
```
src/program.py REQUIRED defines setup() and render()
src/*.glsl optional shader sources you ship; read with Path(__file__).with_name("x.glsl").read_text()
```
+Only these two globs are delivered. Another `src/*.py` imports at build time but draws a lint WARN
+(`stray_file`) and is not part of what the harness hands over — keep the code in `program.py`.
## The two entry points (exact signatures)
```python
@@ -19,221 +22,99 @@ def setup(ctx: moderngl.Context, width: int, height: int): # called ONCE
def render(ctx: moderngl.Context, state, t: float, frame: int, fbo: moderngl.Framebuffer) -> None:
...draw the frame for time t (seconds) — multi-pass allowed into your own FBOs...
- fbo.use() # the harness framebuffer (RGBA float, depth attached) — draw the FINAL image into it LAST
+ fbo.use() # the harness framebuffer (RGBA f4 colour + depth) — draw the FINAL image into it LAST
```
-* `fbo` is already bound and cleared to (0,0,0,1) + depth 1.0 when render() is called; `ctx.viewport` is the
- full size. If you switch to your own FBOs, call `fbo.use()` and reset `ctx.viewport = (0, 0, width, height)` before the
- final pass. Never call `ctx.screen`.
-* `t` is absolute time in seconds; `frame` is the sample index (0, 1, 2 …; NOT a 60 fps counter). Frames must be a
- pure function of `t` (same t → same image). Seed any randomness in setup (`np.random.default_rng(0)`).
-* Width/height come from the plan's resolution (default 1280x720).
-
-## Allowed / forbidden (AST lint enforces)
-* Imports: `moderngl`, `numpy`, `math`, `random`, `struct`, `array`, `pathlib`, `typing`, `dataclasses`, `itertools`,
- `functools`, `collections`, `colorsys`. Nothing else — no glfw / pygame / pyglet / PyOpenGL / moderngl_window / PIL.
-* No `moderngl.create_context()` / `create_standalone_context()` (the harness owns the context), no windows, no
- `time.time()` / clocks, no `open()` / file writes / subprocess / network / `os` / `sys`.
-* GLSL strings: `#version 330 core`, `in`/`out` qualifiers, `out vec4 fragColor;` (no gl_FragColor / varying).
-* Keep frame cost sane.
-
-## Errors come back as `src/program.py:LINE: <Exception>`. GLSL compile errors show the driver log with line
-numbers inside the shader STRING; moderngl raises `KeyError: 'u_name'` when you set a uniform the compiler
-optimised away (unused) — remove the assignment or guard with `if "u_name" in prog:`.
-
-## Gates on the frames: NaN/Inf pixels → score 0; all frames identical (no motion) → ≤ 0.5; black / blown-out → ≤ 0.5.
-
-## COMPLETE VERIFIED EXAMPLE — `src/program.py` (200 instanced rotating cubes, orbiting camera, separable blur bloom)
+* The harness builds ONE sorted schedule from the judged times and the preview times; for each entry it
+ binds `fbo`, clears it to (0, 0, 0, 1) with depth 1.0, sets `ctx.viewport` to the full size and calls
+ `render(ctx, state, t, frame, fbo)`. `frame` is the index into that merged schedule (0, 1, 2 …), not a
+ 60 fps counter and not "the n-th judged frame".
+* After `render` returns, the harness reads `fbo` back as float and flips the rows itself (GL read-back is
+ bottom-up): draw with y up and do not flip in your shader. If you draw into your own FBOs, call
+ `fbo.use()` and reset `ctx.viewport = (0, 0, width, height)` before the final pass. Never call `ctx.screen`.
+* `render` may be called for any `t`, any number of times, in any order (the build renders the sorted
+ schedule; the `gl_probe` / `gl_frames` tools re-render single times). The frame for a `t` must not
+ depend on which `t`s were rendered before: same `t` → same image.
+* `t` is absolute time in seconds. Width / height come from the plan's resolution (1280x720 when the plan
+ states none or an unusable one; at most 1920x1080 pixels).
+* The whole schedule must render inside the host's timeout (`limits.render_timeout_s`, 300 s by default);
+ a render that overruns is a failed build.
+
+## Executable interface example — `src/program.py` (one full-screen pass driven by `t`)
```python
-"""src/program.py — 200 instanced rotating cubes in a swirling cloud, lit, with a bloom-style post blur.
-Harness calls setup(ctx, width, height) once, then render(ctx, state, t, frame, fbo) per frame."""
-import math
-
import moderngl
import numpy as np
-N_CUBES = 200
-PALETTE = np.array([[0.95, 0.35, 0.25], [0.25, 0.65, 0.95], [0.95, 0.80, 0.30], [0.55, 0.90, 0.55]], dtype="f4")
-
-CUBE_VERT = """#version 330 core
-uniform mat4 u_view_proj;
-uniform float u_time;
-in vec3 in_pos; // per vertex
-in vec3 in_normal; // per vertex
-in vec3 in_offset; // per instance: orbit centre
-in vec3 in_color; // per instance
-in float in_phase; // per instance: spin phase / speed
-out vec3 v_normal;
-out vec3 v_color;
-out vec3 v_world;
-mat3 rotY(float a) { float c = cos(a), s = sin(a); return mat3(c, 0, s, 0, 1, 0, -s, 0, c); }
-mat3 rotX(float a) { float c = cos(a), s = sin(a); return mat3(1, 0, 0, 0, c, -s, 0, s, c); }
-void main() {
- float spin = u_time * (0.6 + in_phase) + in_phase * 6.2831;
- mat3 R = rotY(spin) * rotX(spin * 0.7);
- // orbit the whole cloud slowly around Y and bob
- vec3 centre = rotY(u_time * 0.25) * in_offset + vec3(0.0, 0.15 * sin(u_time * 1.3 + in_phase * 6.2831), 0.0);
- vec3 world = centre + R * (in_pos * 0.18);
- v_normal = R * in_normal;
- v_color = in_color;
- v_world = world;
- gl_Position = u_view_proj * vec4(world, 1.0);
-}
-"""
-CUBE_FRAG = """#version 330 core
-in vec3 v_normal;
-in vec3 v_color;
-in vec3 v_world;
-out vec4 fragColor;
-void main() {
- vec3 n = normalize(v_normal);
- vec3 l1 = normalize(vec3(0.5, 0.9, 0.4)), l2 = normalize(vec3(-0.6, -0.2, -0.7));
- float diff = max(dot(n, l1), 0.0) + 0.35 * max(dot(n, l2), 0.0);
- float rim = pow(1.0 - max(dot(n, vec3(0.0, 0.0, 1.0)), 0.0), 3.0);
- vec3 col = v_color * (0.15 + 0.85 * diff) + 0.4 * rim * v_color;
- float fog = exp(-0.12 * max(0.0, -v_world.z - 4.0));
- fragColor = vec4(col * fog, 1.0);
-}
-"""
-QUAD_VERT = """#version 330 core
-in vec2 in_pos;
-out vec2 v_uv;
-void main() { v_uv = in_pos * 0.5 + 0.5; gl_Position = vec4(in_pos, 0.0, 1.0); }
-"""
-BLUR_FRAG = """#version 330 core
-uniform sampler2D u_tex;
-uniform vec2 u_dir; // (1/w, 0) or (0, 1/h)
-in vec2 v_uv;
-out vec4 fragColor;
-void main() {
- float w[5] = float[](0.227027, 0.1945946, 0.1216216, 0.054054, 0.016216);
- vec3 acc = texture(u_tex, v_uv).rgb * w[0];
- for (int i = 1; i < 5; i++) {
- acc += texture(u_tex, v_uv + u_dir * float(i) * 2.0).rgb * w[i];
- acc += texture(u_tex, v_uv - u_dir * float(i) * 2.0).rgb * w[i];
- }
- fragColor = vec4(acc, 1.0);
-}
-"""
-COMPOSITE_FRAG = """#version 330 core
-uniform sampler2D u_scene;
-uniform sampler2D u_blur;
-in vec2 v_uv;
-out vec4 fragColor;
-void main() {
- vec3 scene = texture(u_scene, v_uv).rgb;
- vec3 bloom = texture(u_blur, v_uv).rgb;
- vec2 p = v_uv - 0.5;
- vec3 bg = mix(vec3(0.05, 0.04, 0.10), vec3(0.12, 0.10, 0.22), 1.0 - length(p) * 1.2); // dark vignette gradient
- vec3 col = bg + scene + 0.5 * bloom;
- col = col / (1.0 + col); // tonemap
- fragColor = vec4(pow(col, vec3(1.0 / 2.2)), 1.0);
-}
-"""
-
-
-def _cube_mesh() -> np.ndarray:
- """36 vertices × (pos3 + normal3), unit cube centred at origin."""
- faces = [((0, 0, 1), (-1, -1, 1), (1, -1, 1), (1, 1, 1), (-1, 1, 1)),
- ((0, 0, -1), (1, -1, -1), (-1, -1, -1), (-1, 1, -1), (1, 1, -1)),
- ((1, 0, 0), (1, -1, 1), (1, -1, -1), (1, 1, -1), (1, 1, 1)),
- ((-1, 0, 0), (-1, -1, -1), (-1, -1, 1), (-1, 1, 1), (-1, 1, -1)),
- ((0, 1, 0), (-1, 1, 1), (1, 1, 1), (1, 1, -1), (-1, 1, -1)),
- ((0, -1, 0), (-1, -1, -1), (1, -1, -1), (1, -1, 1), (-1, -1, 1))]
- data = []
- for n, a, b, c, d in faces:
- for v in (a, b, c, a, c, d):
- data += [v[0] * 0.5, v[1] * 0.5, v[2] * 0.5, *n]
- return np.array(data, dtype="f4")
-
-
-def _perspective(fov_deg, aspect, near, far):
- f = 1.0 / math.tan(math.radians(fov_deg) / 2)
- m = np.zeros((4, 4), dtype="f4")
- m[0, 0], m[1, 1] = f / aspect, f
- m[2, 2], m[2, 3], m[3, 2] = (far + near) / (near - far), 2 * far * near / (near - far), -1.0
- return m
-
-
-def _look_at(eye, target, up=(0.0, 1.0, 0.0)):
- eye, target, up = (np.array(v, dtype="f4") for v in (eye, target, up))
- f = target - eye
- f /= np.linalg.norm(f)
- s = np.cross(f, up)
- s /= np.linalg.norm(s)
- u = np.cross(s, f)
- m = np.identity(4, dtype="f4")
- m[0, :3], m[1, :3], m[2, :3] = s, u, -f
- m[:3, 3] = -m[:3, :3] @ eye
- return m
+VERT = "#version 330 core\nin vec2 in_pos; out vec2 v_uv;\nvoid main() { v_uv = in_pos * 0.5 + 0.5; gl_Position = vec4(in_pos, 0.0, 1.0); }\n"
+FRAG = "#version 330 core\nuniform float u_time; in vec2 v_uv; out vec4 fragColor;\nvoid main() { fragColor = vec4(vec3(0.5 + 0.5 * sin(6.2832 * (v_uv.x - 0.05 * u_time))), 1.0); }\n"
def setup(ctx: moderngl.Context, width: int, height: int):
- rng = np.random.default_rng(7) # deterministic layout
- # instance data: offsets on a thick torus-ish ring, colours from the palette, phases
- ang = rng.uniform(0, 2 * math.pi, N_CUBES)
- rad = rng.uniform(1.2, 2.6, N_CUBES)
- offsets = np.stack([rad * np.cos(ang), rng.uniform(-0.8, 0.8, N_CUBES), rad * np.sin(ang)], axis=1).astype("f4")
- colors = PALETTE[rng.integers(0, len(PALETTE), N_CUBES)]
- phases = rng.uniform(0, 1, N_CUBES).astype("f4")
- inst = np.concatenate([offsets, colors, phases[:, None]], axis=1).astype("f4") # 7 floats per instance
-
- cube_prog = ctx.program(vertex_shader=CUBE_VERT, fragment_shader=CUBE_FRAG)
- vbo = ctx.buffer(_cube_mesh().tobytes())
- ibo = ctx.buffer(inst.tobytes())
- cube_vao = ctx.vertex_array(cube_prog, [(vbo, "3f 3f", "in_pos", "in_normal"),
- (ibo, "3f 3f 1f/i", "in_offset", "in_color", "in_phase")])
- # offscreen scene FBO (with depth) + two half-res blur FBOs (ping-pong)
- scene_tex = ctx.texture((width, height), 4, dtype="f2")
- scene_fbo = ctx.framebuffer(color_attachments=[scene_tex], depth_attachment=ctx.depth_renderbuffer((width, height)))
- bw, bh = width // 2, height // 2
- blur_tex = [ctx.texture((bw, bh), 4, dtype="f2") for _ in range(2)]
- for tex in blur_tex + [scene_tex]:
- tex.filter = (moderngl.LINEAR, moderngl.LINEAR)
- tex.repeat_x = tex.repeat_y = False
- blur_fbo = [ctx.framebuffer(color_attachments=[tex]) for tex in blur_tex]
-
+ prog = ctx.program(vertex_shader=VERT, fragment_shader=FRAG)
quad = ctx.buffer(np.array([-1, -1, 1, -1, -1, 1, 1, 1], dtype="f4").tobytes())
- blur_prog = ctx.program(vertex_shader=QUAD_VERT, fragment_shader=BLUR_FRAG)
- comp_prog = ctx.program(vertex_shader=QUAD_VERT, fragment_shader=COMPOSITE_FRAG)
- blur_vao = ctx.vertex_array(blur_prog, [(quad, "2f", "in_pos")])
- comp_vao = ctx.vertex_array(comp_prog, [(quad, "2f", "in_pos")])
- proj = _perspective(50.0, width / height, 0.1, 50.0)
- return dict(cube_prog=cube_prog, cube_vao=cube_vao, scene_fbo=scene_fbo, scene_tex=scene_tex, blur_fbo=blur_fbo,
- blur_tex=blur_tex, blur_prog=blur_prog, blur_vao=blur_vao, comp_prog=comp_prog, comp_vao=comp_vao,
- proj=proj, size=(width, height), bsize=(bw, bh))
+ return {"prog": prog, "vao": ctx.vertex_array(prog, [(quad, "2f", "in_pos")]), "size": (width, height)}
def render(ctx: moderngl.Context, state, t: float, frame: int, fbo: moderngl.Framebuffer) -> None:
- w, h = state["size"]
- bw, bh = state["bsize"]
- # pass 1: cubes into the scene FBO (depth on)
- state["scene_fbo"].use()
- ctx.viewport = (0, 0, w, h)
- state["scene_fbo"].clear(0.0, 0.0, 0.0, 0.0, depth=1.0)
- ctx.enable(moderngl.DEPTH_TEST)
- eye = (5.5 * math.cos(t * 0.15), 1.8 + 0.5 * math.sin(t * 0.2), 5.5 * math.sin(t * 0.15))
- view_proj = state["proj"] @ _look_at(eye, (0.0, 0.0, 0.0))
- state["cube_prog"]["u_view_proj"].write(view_proj.T.astype("f4").tobytes()) # column-major for GLSL
- state["cube_prog"]["u_time"].value = t
- state["cube_vao"].render(mode=moderngl.TRIANGLES, instances=N_CUBES)
- ctx.disable(moderngl.DEPTH_TEST)
- # pass 2: separable blur, half resolution, horizontal then vertical
- ctx.viewport = (0, 0, bw, bh)
- state["blur_fbo"][0].use()
- state["scene_tex"].use(location=0)
- state["blur_prog"]["u_tex"].value = 0
- state["blur_prog"]["u_dir"].value = (1.0 / bw, 0.0)
- state["blur_vao"].render(mode=moderngl.TRIANGLE_STRIP)
- state["blur_fbo"][1].use()
- state["blur_tex"][0].use(location=0)
- state["blur_prog"]["u_dir"].value = (0.0, 1.0 / bh)
- state["blur_vao"].render(mode=moderngl.TRIANGLE_STRIP)
- # pass 3: composite into the harness framebuffer (ALWAYS the last thing you draw)
fbo.use()
- ctx.viewport = (0, 0, w, h)
- state["scene_tex"].use(location=0)
- state["blur_tex"][1].use(location=1)
- state["comp_prog"]["u_scene"].value = 0
- state["comp_prog"]["u_blur"].value = 1
- state["comp_vao"].render(mode=moderngl.TRIANGLE_STRIP)
+ ctx.viewport = (0, 0, *state["size"])
+ ctx.disable(moderngl.DEPTH_TEST)
+ state["prog"]["u_time"].value = t
+ state["vao"].render(mode=moderngl.TRIANGLE_STRIP)
```
+It shows the interface only — what the harness calls, how a uniform takes `t`, where the final draw lands.
+What you draw, in how many passes, with what geometry or camera, is the brief's business.
+
+## Allowed / forbidden (the AST lint enforces; an ERROR caps the score at 0.6)
+* Imports (the allow-list; anything else is an ERROR): `moderngl`, `numpy`, `math`, `random`, `struct`,
+ `array`, `pathlib`, `typing`, `dataclasses`, `itertools`, `functools`, `collections`, `colorsys`, `enum`,
+ `__future__`.
+* ERROR: window / input libraries (glfw, pygame, pyglet, PyQt, PySide, tkinter, moderngl_window, sdl2, wx,
+ PyOpenGL); `os`, `sys`, `io`, `time`, `datetime`, `signal`, `tempfile`, subprocess and network modules;
+ the calls `open` / `exec` / `eval` / `compile` / `__import__` / `input` / `exit` / `quit` / `breakpoint`;
+ file-system writes (`.write_text` / `.write_bytes` / `.unlink` / `.mkdir` / `.rmdir` / `.rename`);
+ `moderngl.create_context()` / `create_standalone_context()` (the harness owns the context);
+ `time.time()` / `perf_counter()` / `monotonic()`; `gl_FragColor`, `attribute` / `varying` in a shader string.
+* WARN: a `#version` other than `330 core` in a shader string (`glsl_version`); `random.*` called without
+ `random.seed(...)` or a `default_rng(...)` (`unseeded_random`) — seed in `setup`; a file over 120 000
+ characters (`too_long`); an extra `src/*.py` (`stray_file`).
+* The harness tears the context down at job end and has no `cleanup()` callback. When you replace
+ resources, release each VAO, buffer, texture, framebuffer and program you own (a framebuffer does not
+ own its attachments); never release the supplied `ctx` or `fbo`.
+
+## moderngl facts that decide whether the build runs (not style)
+* Every shader string starts with `#version 330 core` on its first line (nothing before it, not even a
+ blank line), uses `in` / `out` qualifiers and declares `out vec4 fragColor;`.
+* `ctx.vertex_array(prog, [(buffer, "3f 3f 2f", "in_pos", "in_normal", "in_uv")], index_buffer=ibo)`:
+ the names must match the vertex shader's `in`s; one count+type per attribute; `x` pads bytes you skip
+ (`"3f 3f 2x4"`); `/i` makes a buffer per-instance (`"3f 1f/i"`, drawn with `vao.render(instances=n)`).
+ A wrong float count does not raise — it silently shuffles the data. A buffer rewritten with
+ `buffer.write(...)` keeps its byte size.
+* An `in` or uniform the compiler optimised away is absent from `prog`: setting it raises
+ `KeyError: 'u_name'`. Remove the assignment, pad the attribute out, or guard with `if "u_name" in prog:`.
+* Scalars and vectors: `prog["u"].value = 1.0` / `(r, g, b)`. Matrices: numpy is row-major and GLSL is
+ column-major, so `prog["u_m"].write(M.T.astype("f4").tobytes())` — never `.value = m.tolist()`.
+* A sampler is a texture unit: `prog["u_tex"].value = k` once, and `tex.use(location=k)` on every call of
+ `render` before the draw that samples it.
+* `ctx.clear(...)` clears whatever framebuffer is bound. Clear your own with `my_fbo.clear(...)`. An
+ offscreen framebuffer tests depth only when you attach one (`ctx.depth_renderbuffer((w, h))` as
+ `depth_attachment=`); reading and writing the same texture in one pass is undefined.
+* With `ctx.enable(moderngl.CULL_FACE)` a front face is counter-clockwise as seen from outside
+ (`ctx.front_face` defaults to `"ccw"`); wind your triangles that way or the mesh is inside out.
+* The context is GL 3.3 core: `ctx.line_width` above 1 and GL_QUADS do not exist (draw geometry for thick
+ lines); `ctx.wireframe = True` is a debugging aid, not a look.
+
+## Errors come back as `src/program.py:LINE: <Exception>`. GLSL compile errors show the driver log with line
+numbers inside the shader STRING; `KeyError: 'u_name'` is the optimised-away uniform above.
+
+## Gates on the judged frames (`gl_frames`; the cap is the highest score the round can get)
+| measured | threshold | finding | cap |
+|---|---|---|---|
+| any NaN / Inf pixel in the float read-back | ≥ 1 | `nan` ERROR | 0 |
+| every frame black | over 97 % of pixels under luminance 0.03 in each frame | `black` ERROR | 0.5 |
+| every frame blown | over 97 % of pixels over luminance 0.98 in each frame | `blown` ERROR | 0.5 |
+| largest mean \|Δ\| between consecutive sampled frames | < 0.002 (motion planned) | `static` WARN | 0.5 |
+| largest mean \|Δ\| between consecutive sampled frames | > 0.35 | `flicker` WARN | 0.7 |
+| mean edge density over the frames | < 0.002 | `low_detail` WARN ("a near-flat gradient") | none — the judge sees it |
+| a lint ERROR | any | | 0.6 |
+| the build fails (import, setup, render, timeout) | | | 0 |
+The judge then checks every acceptance item of the plan against the frames; an unmet `must` item caps 0.7.
diff --git a/harness/codeverse3d/prompts/opengl_python/cookbook.md b/harness/codeverse3d/prompts/opengl_python/cookbook.md
deleted file mode 100644
index 50534065..00000000
--- a/harness/codeverse3d/prompts/opengl_python/cookbook.md
+++ /dev/null
@@ -1,166 +0,0 @@
-# opengl_python cookbook — copyable moderngl snippets (GL 3.3 core, headless; harness calls setup()/render())
-
-## Fullscreen quad (every post-process / procedural pass starts here)
-```python
-QUAD_VERT = """#version 330 core
-in vec2 in_pos; out vec2 v_uv;
-void main() { v_uv = in_pos * 0.5 + 0.5; gl_Position = vec4(in_pos, 0.0, 1.0); }
-"""
-quad = ctx.buffer(np.array([-1, -1, 1, -1, -1, 1, 1, 1], dtype="f4").tobytes())
-prog = ctx.program(vertex_shader=QUAD_VERT, fragment_shader=FRAG) # FRAG: `in vec2 v_uv; out vec4 fragColor; ...`
-vao = ctx.vertex_array(prog, [(quad, "2f", "in_pos")])
-vao.render(mode=moderngl.TRIANGLE_STRIP) # 4 vertices
-```
-A fragment-only effect (Shadertoy style) in this language = one quad pass with `uniform float u_time; uniform vec2 u_resolution;`
-set from render(): `prog["u_time"].value = t`.
-
-## VBO / VAO with interleaved attributes, index buffer
-```python
-verts = np.array([...], dtype="f4") # x y z nx ny nz u v per vertex
-vbo = ctx.buffer(verts.tobytes())
-ibo = ctx.buffer(np.array([...], dtype="i4").tobytes())
-vao = ctx.vertex_array(prog, [(vbo, "3f 3f 2f", "in_pos", "in_normal", "in_uv")], index_buffer=ibo)
-vao.render(mode=moderngl.TRIANGLES)
-# attribute names MUST match the `in` names in the vertex shader; unused `in`s are optimised away → skip them
-# with "3f 3f 2x4" (x = padding) or check `prog.get("in_uv", None)`.
-```
-
-## Instancing (hundreds–thousands of objects in one draw)
-```python
-inst = np.concatenate([offsets, colors, scales[:, None]], axis=1).astype("f4") # per-instance rows
-ibo = ctx.buffer(inst.tobytes())
-vao = ctx.vertex_array(prog, [(vbo, "3f 3f", "in_pos", "in_normal"),
- (ibo, "3f 3f 1f/i", "in_offset", "in_color", "in_scale")]) # "/i" = per instance
-vao.render(mode=moderngl.TRIANGLES, instances=len(inst))
-# vertex shader: `in vec3 in_offset; ... vec3 world = in_offset + in_scale * (R * in_pos);`
-# animate per-instance in the SHADER from u_time + a per-instance phase attribute → no per-frame buffer uploads
-```
-Updating instance data per frame (CPU particles): `ibo.write(new_rows.astype("f4").tobytes())` (keep row count constant; use `orphan()` for speed).
-
-## Uniforms and matrices (numpy → GLSL is column-major: transpose!)
-```python
-prog["u_color"].value = (1.0, 0.5, 0.2) # vec3
-prog["u_time"].value = float(t) # float
-prog["u_mvp"].write(mvp.T.astype("f4").tobytes()) # mat4: transpose a row-major numpy matrix
-prog["u_tex"].value = 0 # sampler → texture unit; then tex.use(location=0)
-if "u_optional" in prog: prog["u_optional"].value = 1.0 # uniforms unused by the shader are optimised away → KeyError
-```
-```python
-def perspective(fov_deg, aspect, near, far):
- f = 1.0 / math.tan(math.radians(fov_deg) / 2); m = np.zeros((4, 4), dtype="f4")
- m[0, 0], m[1, 1] = f / aspect, f
- m[2, 2], m[2, 3], m[3, 2] = (far + near) / (near - far), 2 * far * near / (near - far), -1.0
- return m
-def look_at(eye, target, up=(0, 1, 0)):
- eye, target, up = (np.array(v, dtype="f4") for v in (eye, target, up))
- f = target - eye; f /= np.linalg.norm(f); s = np.cross(f, up); s /= np.linalg.norm(s); u = np.cross(s, f)
- m = np.identity(4, dtype="f4"); m[0, :3], m[1, :3], m[2, :3] = s, u, -f; m[:3, 3] = -m[:3, :3] @ eye
- return m
-def rot_y(a): c, s = math.cos(a), math.sin(a); return np.array([[c, 0, s, 0], [0, 1, 0, 0], [-s, 0, c, 0], [0, 0, 0, 1]], dtype="f4")
-mvp = proj @ view @ model # then prog["u_mvp"].write(mvp.T.astype("f4").tobytes())
-# With nonuniform scale, normals use inverse transpose, never mat3(model).
-normal_matrix = np.linalg.inv(model[:3, :3]).T
-prog["u_normal_matrix"].write(normal_matrix.T.astype("f4").tobytes())
-```
-
-## Textures (procedural data, noise, LUTs)
-```python
-rng = np.random.default_rng(0)
-noise = rng.random((256, 256, 4), dtype=np.float32)
-tex = ctx.texture((256, 256), 4, noise.astype("f4").tobytes(), dtype="f4") # or uint8 data with dtype default
-tex.filter = (moderngl.LINEAR, moderngl.LINEAR); tex.repeat_x = tex.repeat_y = True
-tex.use(location=0); prog["u_noise"].value = 0
-# 3D textures: ctx.texture3d((32,32,32), 1, data.tobytes(), dtype="f4")
-```
-
-## FBOs: offscreen scene, ping-pong feedback, MRT
-```python
-color = ctx.texture((w, h), 4, dtype="f2") # f2 = half float (HDR); "f4" = float32
-depth = ctx.depth_renderbuffer((w, h))
-scene_fbo = ctx.framebuffer(color_attachments=[color], depth_attachment=depth)
-scene_fbo.use(); ctx.viewport = (0, 0, w, h); scene_fbo.clear(0.0, 0.0, 0.0, 0.0, depth=1.0)
-...draw...
-# ping-pong (feedback / simulation): two FBOs, read A write B, then swap
-pp_tex = [ctx.texture((w, h), 4, dtype="f4") for _ in range(2)]; pp_fbo = [ctx.framebuffer(color_attachments=[t]) for t in pp_tex]
-read, write = state["pp"]; pp_fbo[write].use(); pp_tex[read].use(location=0); sim_vao.render(moderngl.TRIANGLE_STRIP); state["pp"] = (write, read)
-# MRT: ctx.framebuffer(color_attachments=[albedo, normal, position], depth_attachment=depth) with
-# `layout(location = 0) out vec4 out_albedo; layout(location = 1) out vec4 out_normal; ...` in the fragment shader
-```
-ALWAYS end render() with `fbo.use(); ctx.viewport = (0, 0, width, height)` and the final draw into the harness `fbo`.
-
-## Separable Gaussian blur (bloom)
-```glsl
-#version 330 core
-uniform sampler2D u_tex; uniform vec2 u_dir; in vec2 v_uv; out vec4 fragColor;
-void main() {
- float w[5] = float[](0.227027, 0.1945946, 0.1216216, 0.054054, 0.016216);
- vec3 acc = texture(u_tex, v_uv).rgb * w[0];
- for (int i = 1; i < 5; i++) { acc += texture(u_tex, v_uv + u_dir * float(i)).rgb * w[i]; acc += texture(u_tex, v_uv - u_dir * float(i)).rgb * w[i]; }
- fragColor = vec4(acc, 1.0);
-}
-```
-Run horizontally (`u_dir = (1/w, 0)`) into FBO A, vertically (`(0, 1/h)`) into FBO B, at half resolution; composite `scene + k * blur`, tonemap `c/(1+c)`, gamma `pow(c, 1/2.2)`.
-
-## Lighting in GLSL (Blinn-Phong + rim + fog)
-This short stylized lighting model is for sketches. For a realistic material, use the GGX
-`pbrDirect` / `fresnelSchlick` functions in the GLSL cookbook's Physical surface lighting section;
-keep all light and albedo inputs linear and tonemap once at the final output. Use the Volume
-lighting helpers there for extinction and normalized phase functions in smoke/cloud raymarches.
-```glsl
-vec3 n = normalize(v_normal); vec3 l = normalize(vec3(0.5, 0.9, 0.4)); vec3 v = normalize(u_cam - v_world);
-float diff = max(dot(n, l), 0.0); float spec = pow(max(dot(n, normalize(l + v)), 0.0), 48.0);
-float rim = pow(1.0 - max(dot(n, v), 0.0), 3.0);
-vec3 col = albedo * (0.15 + 0.85 * diff) + 0.3 * spec + 0.3 * rim * albedo;
-col = mix(col, fogColor, 1.0 - exp(-0.03 * dist));
-```
-
-## Geometry generators (numpy)
-```python
-def grid_mesh(nx, nz, size): # flat plane for water / terrain (vertex shader displaces y)
- xs = np.linspace(-size, size, nx, dtype="f4"); zs = np.linspace(-size, size, nz, dtype="f4")
- X, Z = np.meshgrid(xs, zs); verts = np.stack([X, np.zeros_like(X), Z], axis=-1).reshape(-1, 3)
- idx = []
- for j in range(nz - 1):
- for i in range(nx - 1):
- a = j * nx + i; idx += [a, a + nx, a + 1, a + 1, a + nx, a + nx + 1]
- return verts.astype("f4"), np.array(idx, dtype="i4")
-def sphere_mesh(rings, sectors, r): # pos3 + normal3 interleaved
- data, idx = [], []
- for j in range(rings + 1):
- v = j / rings; phi = v * math.pi
- for i in range(sectors + 1):
- u = i / sectors; th = u * 2 * math.pi
- n = (math.sin(phi) * math.cos(th), math.cos(phi), math.sin(phi) * math.sin(th))
- data += [r * n[0], r * n[1], r * n[2], *n]
- for j in range(rings):
- for i in range(sectors):
- a = j * (sectors + 1) + i; idx += [a, a + 1, a + sectors + 1, a + 1, a + sectors + 2, a + sectors + 1]
- return np.array(data, dtype="f4"), np.array(idx, dtype="i4")
-```
-
-## GL state you may need
-```python
-ctx.enable(moderngl.DEPTH_TEST); ctx.disable(moderngl.DEPTH_TEST)
-ctx.enable(moderngl.BLEND); ctx.blend_func = moderngl.SRC_ALPHA, moderngl.ONE_MINUS_SRC_ALPHA # or ONE, ONE for additive glow
-ctx.enable(moderngl.CULL_FACE); ctx.front_face = "ccw"
-ctx.point_size = 4.0 # with mode=moderngl.POINTS (gl_PointSize in the vertex shader needs ctx.enable(moderngl.PROGRAM_POINT_SIZE))
-ctx.line_width = 1.0 # > 1 is unsupported on core profiles: draw quads for thick lines
-```
-
-## PITFALLS (each one cost a real run)
-* `KeyError: 'u_x'` — the uniform/attribute is unused in the GLSL and got optimised away; remove the assignment or guard with `in prog`.
-* Matrices: numpy is row-major, GLSL column-major → `write(m.T.astype("f4").tobytes())`; never `value = m.tolist()`.
-* Read-back rows are bottom-up (the harness flips them): draw with y up, do NOT flip in your shader.
-* Forgetting `fbo.use()` + viewport reset before the final pass → the harness frame stays black (cap 0.5).
-* `ctx.clear()` clears whatever FBO is bound; clear your own FBOs explicitly (`my_fbo.clear(...)`).
-* Depth: attach a depth renderbuffer to your offscreen FBOs or z-fighting / wrong occlusion; disable DEPTH_TEST for fullscreen passes.
-* `#version 330 core` at the very top of every shader string (no blank line before it); `out vec4 fragColor;` not gl_FragColor.
-* Attribute format strings: count+type per attribute (`"3f 3f 2f"`), `/i` for per-instance buffers; mismatched float counts silently shuffle data.
-* Big per-frame uploads (100k particles in numpy each frame) are slow; move animation into the vertex shader via `u_time`.
-* Deterministic: `np.random.default_rng(SEED)` in setup, never `random.random()` inside render without a seed.
-* Textures sampled with `texture()` need `.use(location=k)` every frame *and* `prog["u_tex"].value = k`.
-* Lines wider than 1 px and GL_QUADS do not exist in core profile; `ctx.wireframe = True` works for debugging only.
-* Half-float (`f2`) colour targets clip at ~65504 — tonemap before writing bright accumulations.
-* When replacing resources, release each owned VAO, buffer, texture, framebuffer and program;
- a framebuffer does not own its attachments. The harness tears down the context at job end
- and has no `cleanup()` callback. Do not release its supplied context or final framebuffer.
diff --git a/harness/codeverse3d/prompts/opengl_python/system.md b/harness/codeverse3d/prompts/opengl_python/system.md
index cc9b0738..9df4c085 100644
--- a/harness/codeverse3d/prompts/opengl_python/system.md
+++ b/harness/codeverse3d/prompts/opengl_python/system.md
@@ -1,8 +1,9 @@
You are a graphics programmer writing a raw moderngl program for a headless harness. You
own a program with a lifetime: `setup(ctx, width, height)` runs **once** and returns your
-state; `render(ctx, state, t, frame, fbo)` is **sampled** at unequal times, out of order,
-and must draw the frame for that `t` into the framebuffer it is handed. There is no window,
-no context creation and no clock of your own.
+state; `render(ctx, state, t, frame, fbo)` may be called for any `t`, any number of times, in
+any order (the build renders a sorted schedule; the tools re-render single times), and must
+draw the frame for that `t` into the framebuffer it is handed. There is no window, no context
+creation and no clock of your own.
{% if tools %}
The loop that decides whether your work ships:
@@ -17,35 +18,36 @@ shorter and cheaper, not longer.
{% else %}
You cannot run anything: this is a single-shot session with no tools, so the code you
return is the code that ships. Read it back before you finish as if you were the
-compiler — an undeclared name, a missing include, a term multiplied to zero. On a
-measured ten-rung ladder of shader briefs, the sessions that could compile-and-fix
-before finishing got 10 of 10 to build and the ones that could not got 5 of 10; you
-are in the second group, so spend the care up front.
-
-* **The final pass not landing** — you rendered into your own FBO and the harness read
- the one you were handed. The last thing `render` does is draw into `fbo`.
+interpreter and the GLSL compiler — an undefined Python name, an undeclared GLSL
+variable, a uniform the shader optimised away and the program then sets, a term multiplied
+to zero. On a measured ladder of graphics briefs, the sessions that could run-and-fix
+before finishing got every rung to build and the ones that could not got half; you are in
+the second group, so spend the care up front.
{% endif %}
-What the judge will name if you skip it:
+What the gate and the judge measure, and what has failed it:
* **The sampled-time trap** — you are called at t = 0, 1, 2.5, 4, 6 s, not at 60 fps. A
simulation that advances one step per call has taken five steps by the last frame. Pose
from `t`; if a state must integrate, integrate to `t` inside the call.
* **The final pass not landing** — you rendered into your own FBO and the harness read the
one you were handed. The last thing `render` does is draw into `fbo`.
-* **A hard cut between samples** — motion that is fine at 60 fps but discontinuous at the
- five sampled times. Check that your parameterisation is smooth across them.
-* **One-scale detail** — a single frequency in a texture, a displacement or a particle
- field both aliases and reads flat.
-
-Two rules that survive every brief:
-
-* Everything is a smooth function of absolute `t`, and `render` is deterministic: called
- twice with the same `t`, it must draw the same frame. No frame counters driving content,
- no per-call RNG without a `t`-derived seed, no hand-rolled `fract`/`mod` wrap of raw time.
-* **Light before colour.** Get the frame into a readable band first; hue and palette work is
- invisible on dark, low-chroma pixels. A subject in daylight sits near half the brightness
- of its own sky — a fifth is underlit, not moody.
+* **A hard cut between samples** — the gate compares consecutive sampled frames: a pair whose
+ mean |Δ| exceeds 0.35 is reported as flicker and caps the score at 0.7; frames that differ
+ by less than 0.002 everywhere read as static and cap it at 0.5.
+* **A near-flat image** — the gate measures mean edge density over the judged frames; below
+ 0.002 it reports the image as a near-flat gradient, and the judge scores visual richness on
+ the same frames.
+
+Two requirements that hold for every brief:
+
+* `render` is deterministic: called twice with the same `t`, it draws the same frame.
+ `frame` is a schedule index, not time; randomness is seeded in `setup` or derived from `t`.
+ A periodic wrap that jumps between two sampled times shows up as the flicker finding above.
+* Frames are measured for exposure: essentially black (over 97 % of pixels under luminance
+ 0.03) or blown (over 0.98) in every judged frame caps the score at 0.5. Get the frame into a
+ readable band before spending effort on hue and palette, which are invisible on dark,
+ low-chroma pixels.
A clean simpler program beats a richer one carrying a visible defect. Clear NaN, black,
blown and static before you add the next pass; deleting a pass is a legitimate fix.
diff --git a/harness/codeverse3d/prompts/sections.py b/harness/codeverse3d/prompts/sections.py
deleted file mode 100644
index f0057593..00000000
--- a/harness/codeverse3d/prompts/sections.py
+++ /dev/null
@@ -1,71 +0,0 @@
-"""Split prompt markdown into heading-delimited sections.
-
-Prompt material, so it lives with the prompts. It was in ``spatial/cookbook_tool.py``
-next to a ``read_cookbook`` MCP tool that served one chapter at a time — a tool the repo
-measured at 0 calls in 16 zone sessions (cli/skills_cmd.py:4) and 0 across every recorded
-run, and which had nothing left to do once the whole cookbook started reaching the model
-in the prompt (2026-08-28). The tool is gone; the parser stays, because naming a chapter
-is how a STAGE says which recipes it needs — scene's env/zone recipes, graphics' recipe
-seeding, repair's error-matched section.
-"""
-
-from __future__ import annotations
-
-import re
-from dataclasses import dataclass
-
-_HEADING = re.compile(r"^(#{1,3})\s+(.+?)\s*$", re.MULTILINE)
-_FENCE = re.compile(r"^(`{3,}|~{3,}).*?^\1[ \t]*$", re.MULTILINE | re.DOTALL)
-
-
-@dataclass
-class Section:
- level: int
- title: str
- body: str # heading line included
-
-
-def _heading_matches(md: str) -> list[re.Match[str]]:
- """Headings outside fenced code blocks (``# comment`` lines in snippets are not headings)."""
- out: list[re.Match[str]] = []
- fence_spans: list[tuple[int, int]] = []
- for m in _FENCE.finditer(md):
- fence_spans.append((m.start(), m.end()))
- for m in _HEADING.finditer(md):
- if not any(a <= m.start() < b for a, b in fence_spans):
- out.append(m)
- return out
-
-
-def split_sections(md: str) -> list[Section]:
- """Split markdown into heading-delimited sections (text before the first heading is 'preamble')."""
- matches = _heading_matches(md)
- if not matches:
- return [Section(0, "preamble", md)]
- out: list[Section] = []
- if matches[0].start() > 0 and md[: matches[0].start()].strip():
- out.append(Section(0, "preamble", md[: matches[0].start()]))
- for i, m in enumerate(matches):
- end = matches[i + 1].start() if i + 1 < len(matches) else len(md)
- out.append(Section(len(m.group(1)), m.group(2), md[m.start(): end]))
- return out
-
-
-def find_section(sections: list[Section], query: str) -> Section | None:
- """Case-insensitive match: exact title first, then substring, then word overlap."""
- q = query.strip().lower()
- if not q:
- return None
- for s in sections:
- if s.title.lower() == q:
- return s
- for s in sections:
- if q in s.title.lower():
- return s
- words = set(re.findall(r"[a-z0-9]+", q))
- best, best_n = None, 0
- for s in sections:
- n = len(words & set(re.findall(r"[a-z0-9]+", s.title.lower())))
- if n > best_n:
- best, best_n = s, n
- return best
diff --git a/harness/codeverse3d/prompts/system/harness_contract.md b/harness/codeverse3d/prompts/system/harness_contract.md
index 1ccdbd02..b788b327 100644
--- a/harness/codeverse3d/prompts/system/harness_contract.md
+++ b/harness/codeverse3d/prompts/system/harness_contract.md
@@ -24,47 +24,50 @@ artifacts/ harness output (object.glb, renders/, gates/, measurement.json). RE
shader files with `THREE.FileLoader` — exactly as your language contract shows. Writing files stays
forbidden everywhere.
A language contract may ALSO ship harness-owned modules inside your own `src/` and tell
- you to call them (`scene_threejs`: `src/lib/*.js`). Those are not an SDK import — they
+ you to call them (`scene_threejs`: `src/lib/*.js`; `scene_blender`: `src/lib/`). Those are not an SDK import — they
are code the harness wrote into your workspace. Call them; never rewrite them.
## 2. Code is truth
* The plan (`plan.json`) carries exact numbers: part names, bbox centre + extents in
- meters, attach_to, instances. **Use those numbers literally** in your code (as named
- constants at the top of the file). If you disagree with a number, keep the plan's value
- and note why in a comment — do not silently drift.
+ meters, attach_to, instances. They are what the gates measure against: build to them.
+ If you disagree with a number, keep the plan's value and say why in a comment — do not
+ silently drift.
* Part names are PascalCase and unique (`SeatCushion`, `LeftFrontLeg`); object / node
names in the exported artifact must equal the plan's part names exactly. URDF link
names are the snake_case of the part name (`left_front_leg`; the PascalCase spelling is
accepted too).
-* Deterministic: seed every random source (`random.seed(0)`, a hash-based `rand(i)`), no
- time-dependent geometry. Two builds of the same code must produce identical geometry.
-* Real-world scale: a chair seat is 0.45 m high, a door 2.0 m, a mug 0.09 m. Check your
- overall bbox against the plan's `overall_bbox` before you finish.
-
-## 3. Physical plausibility (what gates will reject)
-
-* **Touch or overlap, never float**: every part must share volume with (or sit flush
- against) at least one other part; seams overlap by ≥ 2 mm.
- No piece may hover. The connectivity gate hard-fails on any island with a positive gap.
-* **Weld by overlap, not by rods**: fix a floating piece by extending / embedding it
- ≥ 2 mm into its neighbour, never by adding thin connector sticks.
-* **Ground contact**: the lowest point of the object is at up = 0; footprint
- centred on the up-axis. Scenes: bounds as declared in the plan.
-* **No concealed interpenetration**: neighbours that are not welded keep ≥ 15 mm
- clearance; limbs do not sink into bodies; rings wrap cores, they do not intersect them.
-* **Hollow things are hollow** (mugs, bowls, boxes, drawers): cut the cavity; walls
- 1–6 mm for small objects, 12–20 mm for furniture.
-* **Symmetry by construction**: mirror / instance identical parts from one builder
- instead of writing the same geometry twice.
+* Deterministic: seed every random source, no time-dependent geometry. The harness rebuilds
+ your code for every measurement and render, so two builds must produce identical geometry.
+* Real-world scale, in metres: `check_contract` compares the measured overall bbox with the
+ plan's `overall_bbox`, per axis, within max(10 mm, 10 % of the extent).
+
+## 3. Physical plausibility (what the gates measure)
+
+* **Contact, never float**: `check_connectivity` counts two parts as touching when their
+ surface gap is ≤ 2 mm (flush included), and every part (over 10 mm) must be reachable
+ through such contacts from the parts on the ground — a part outside that component is a
+ floating ERROR, even when it touches another floating part.
+* **Fix a gap by moving or extending the part**, never by bridging it with thin connector
+ sticks (see §5).
+* **Interpenetration**: two parts sunk more than 2 mm into each other are a WARN, more than
+ 10 mm (with at least 2 % of one part's surface inside) an ERROR (the score is capped). A
+ flush or ≤ 2 mm seat is neither.
+* **Ground contact**: the lowest point of the object is at up = 0; footprint centred on the
+ up-axis. Scenes: the plan's bounds are the detailed area the gates measure against, not a
+ cage — the world continues past them.
+* **Stray geometry**: a disconnected piece of one part smaller than 5 % of that part's size
+ is reported as a stray island.
+* **Hollow things are hollow** when the real object is (mugs, bowls, boxes, drawers): the
+ cavity is cut, and `cross_section` shows it.
## 4. You have eyes — use them
-Before declaring done you MUST look at what you built: `build` → `render_sheet` (14 views)
-→ `check_connectivity` → fix → `isolate` a doubtful part → `cross_section` for cavities
-→ `compare_reference` if a reference image exists (each step whose tool is in your tool
-list). Read the numbers (bbox, islands, tri count) and the images. "It should be fine"
-is not evidence; a render is.
+Look at what you built before you declare done: a render is evidence, "it should be fine" is
+not. The tools in your list measure different things — `build` (errors, bbox, islands,
+triangle count), `render_sheet` / `render_views` (what the judge sees), `check_connectivity`
+(contact, islands, interpenetration), `isolate` (one part alone), `cross_section` (cavities),
+`compare_reference` (when a reference image exists). Read the numbers and the images.
On the `graphics` track there is no GLB, no part and no bbox: `render_sheet`, `check_connectivity`,
`isolate` and `cross_section` do not apply — your loop is the language contract's (`gl_probe` after every
edit, then `gl_frames`, and LOOK at the sheet).
@@ -76,33 +79,33 @@ edit, then `gl_frames`, and LOOK at the sheet).
add invisible geometry to satisfy a bbox, bridge islands with rods).
* Never print fake success, swallow exceptions, or `try/except: pass` around geometry
that fails — a loud error is cheaper than a silent wrong model. The one exception is a
- purely cosmetic fillet/chamfer that falls back to the unrounded solid (CadQuery's
- `safe_fillet`).
+ purely cosmetic fillet/chamfer that falls back to the unrounded solid when the kernel
+ refuses it.
* Do not edit `plan.json`, `spec.json` or anything under `artifacts/`.
-## 6. Efficient code
+## 6. Budgets
-* Use instancing / merged geometry for repeats.
-* No infinite loops, no per-vertex Python loops over whole meshes (use modifiers /
- `foreach_set`).
+* The build is killed at its time limit (`build_timeout_s`, 300 s by default); on the
+ `static_object` track the `detail_budget` gate also sets a triangle budget and a build-time
+ budget from the plan. The language contract states what applies to it. No infinite loops.
-## 7. Definition of done (all boxes, in order)
+## 7. Definition of done
Items 2–4 and 6's mesh checks are for GLB tracks. On the `scene` track they apply to each compiled asset
under `public/assets/`, and the scene itself is checked with `scene_probe`, `scene_views` and
-`check_placement` against the plan's declared bounds. On the `graphics` track "done" is: `gl_probe`
+`check_placement` (planned contents against the plan's bounds; scenery past them is never
+reported). On the `graphics` track "done" is: `gl_probe`
reports nothing, and the `gl_frames` sheet matches the plan's key visuals.
1. [ ] `build` succeeds with zero errors (exit 0, GLB written).
2. [ ] Every plan part exists by exact name; no extra junk objects (`Cube`, `Camera`).
-3. [ ] Measured overall bbox matches the plan's `overall_bbox` (objects) / declared bounds (scenes).
+3. [ ] Measured overall bbox matches the plan's `overall_bbox` (objects only).
4. [ ] `check_connectivity` (when in your tool list): 1 connected assembly, no floating
islands, lowest point at 0.
-5. [ ] `render_sheet` (when in your tool list) looked at: silhouette reads as the requested
- object from every view; nothing missing, nothing exploded, nothing lying on its back.
+5. [ ] The renders (when a render tool is in your list) looked at: silhouette reads as the
+ requested object from every view; nothing missing, nothing exploded, nothing lying on its back.
6. [ ] Hollow / articulated / animated behaviour verified (`cross_section`,
`joint_sweep`, `scene_probe` + `check_placement` as applicable).
7. [ ] Materials / colours assigned per plan (no grey default everywhere).
-8. [ ] Code is tidy: constants on top, one function per part, no dead code, no debug
- prints left, no forbidden imports.
+8. [ ] No forbidden imports, no debug prints left.
9. [ ] You stop editing after the last successful build (never finish on a broken build).
diff --git a/harness/codeverse3d/prompts/threejs/contract.md b/harness/codeverse3d/prompts/threejs/contract.md
index 854d9127..52d3c0a1 100644
--- a/harness/codeverse3d/prompts/threejs/contract.md
+++ b/harness/codeverse3d/prompts/threejs/contract.md
@@ -7,99 +7,135 @@ src/parts/<snake>.js export function build<Pascal>(THREE) → THREE.Group (
```
`build()` imports the part builders with relative paths (`./parts/seat_cushion.js`),
adds each returned Group to a root Group named after the object, and returns the root.
-The harness loads `src/object.js` in node, calls `build(THREE)`, and exports
-`artifacts/object.glb` with `GLTFExporter`. No renderer, scene, camera, light, DOM,
-`requestAnimationFrame`, `fetch`, texture loading or file I/O in your code.
+The harness loads `src/object.js` in node, calls `build(THREE)`, validates the Group
+(a group with no meshes, a NaN / Infinity vertex position or an empty bounding box fails
+the build and names the part), runs the optional `selfcheck`, and exports
+`artifacts/object.glb` with `GLTFExporter` **exactly as authored** — nothing re-centres,
+grounds or rescales it. The lint derives the expected export from the file stem
+(`src/parts/seat_cushion.js` → `buildSeatCushion`): a misspelt name is a WARN, no `build*`
+export at all is an ERROR, and a part file nothing imports is a WARN whose geometry is
+simply absent from the GLB. Any other relative file under `src/` (a shared helper module)
+is allowed.
## Frame, units, placement
-* **Y is up, +Z is the front, +X is the right. Meters.** `BoxGeometry(w, h, d)` is
- x-width, y-height, z-depth; `CylinderGeometry` axis is Y; `PlaneGeometry` lies in XY.
-* Each part Group is returned **at its world pose** (position set on the Group or the
- meshes — geometry in meters, root scale (1,1,1), never `root.scale.set(...)` to resize).
-* Lowest point at y = 0, footprint centred on the Y axis. Real-world dimensions.
- The harness exports the object **exactly where you put it** (no automatic drop to
- the ground or re-centring): an off-ground / off-centre build only gets a build
- warning, so place every part at its plan centre.
+* **Y is up, +Z is the front, +X is the right. Meters.**
+* three.js geometry facts: `BoxGeometry(w, h, d)` is x-width, y-height, z-depth;
+ `CylinderGeometry` / `ConeGeometry` / `LatheGeometry` axis is Y (a lathe profile is
+ `Vector2(radius, y)`, normals outward when the radius runs 0 → R → 0 bottom-up);
+ `TorusGeometry`, `PlaneGeometry`, `ShapeGeometry` and `ExtrudeGeometry` lie in the XY plane
+ (the extrusion grows along +Z); every primitive is **centred on its own origin**, so a part's
+ `position` is its centre, not its base.
+* Each part Group is returned **at its world pose** (position set on the Group or the meshes),
+ geometry in meters, root scale (1, 1, 1): `root.scale.set(...)` makes the bounds and the
+ contract gate read the geometry inconsistently.
+* The build warns when the object needs more than 10 mm of translation to stand on y = 0
+ centred on the Y axis; `check_contract` measures the same two things (below).
## Naming
-* Part Group: `g.name = "<PartName>"` — PascalCase exactly as the plan (`SeatCushion`);
- meshes inside may be unnamed or `<PartName>_<detail>`. Unique names; instances get
- their own names (`Leg_0`…`Leg_3`) even if built by one function.
-* Optional animation hook: `root.userData.tick = (dt) => { ... }` on a pivot Group
- (position + rotation only; identity scale). No other userData contract.
+* Part Group: `g.name = "<PartName>"` — PascalCase exactly as the plan (`SeatCushion`). The
+ GLB's node names are the Group / Mesh names, and the top-level node name is how every gate
+ finds the part; `new THREE.Box3().setFromObject(root)` is the box `check_contract` measures.
+ Unique names: a reused name makes the loader re-parent one of the nodes, and the gates then
+ measure the wrong object. Instances get their own names (`Leg_0`…`Leg_3`) even when one
+ function builds them. A mesh with no `.name` is a build warning (the census and the judge
+ refer to meshes by name).
+* `root.userData.tick` is not called, rendered or exported on this track (the census only
+ records whether it exists); the judged pose is the one `build` returns.
-## Imports (only these resolve)
-```js
-import * as THREE from 'three';
-import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
-import { RoundedBoxGeometry } from 'three/addons/geometries/RoundedBoxGeometry.js';
-```
-No CDN URLs, no `three/examples/js/*`, no `three/webgpu`, no `three/tsl`, no npm
-packages other than `three`, no `import ... from 'codeverse3d'` / `../runtime_js`.
+## Imports
+Imports that resolve: `three`, any `three/addons/...` module (for example
+`three/addons/utils/BufferGeometryUtils.js` for `mergeGeometries`,
+`three/addons/geometries/RoundedBoxGeometry.js`), and relative `./` files under `src/`.
+A URL, another npm package, `three/webgpu`, `three/tsl`, a path escaping `src/`, a missing
+file or a name the module does not export is a lint ERROR (`bad_import`). Names removed
+before r182 and therefore undefined: `mergeBufferGeometries` (now `mergeGeometries`),
+`three/examples/js/*`, `Geometry`, `Face3`, `sRGBEncoding`, `outputEncoding`. Copying
+three's sources into `src/` gives two copies of the library and `instanceof` failures.
+`mergeGeometries` returns `null` (logging "All geometries must have compatible attributes")
+when one input is indexed or carries an attribute another lacks (`uv`, `color`); the next call
+on that `null` fails the build.
+
+## Sandbox (what the lint reports)
+* Lint ERRORs: `document`, `window`, `navigator`, `localStorage`, `fetch`, `XMLHttpRequest`,
+ `WebSocket`, `require()`, `process.`, `eval`, `TextureLoader` / `ImageLoader` / `FileLoader`,
+ `WebGLRenderer`, `requestAnimationFrame`. Lint WARNs, ignored at export: a camera, a light
+ (exported as extras, not used by the harness lighting), a `Scene` in place of a Group.
+* Not linted: the exporter replaces `Math.random` with a seeded generator (`--seed`), so its
+ draws repeat from build to build; the clock (`Date.now()`, `performance.now()`) does not, and
+ geometry that depends on it changes between the builds the harness measures and renders.
+
+## Materials
+* `MeshStandardMaterial` / `MeshPhysicalMaterial` map to glTF PBR: colour, roughness, metalness,
+ emissive and vertex colours (`geometry.setAttribute('color', …)` + `vertexColors: true`,
+ exported as `COLOR_0`) survive the export. `ShaderMaterial`, `MeshToonMaterial` and every
+ texture do not: textures are stripped at export with a build warning, a shader material
+ exports as a plain one.
+* A hex colour is read as sRGB; `material.color.r` is the linear value, not the hex byte.
+* An `InstancedMesh` named `Posts` is exported as sibling meshes `Posts_0 … Posts_{n-1}` in
+ its place (instance matrices and colours baked), so gates see every copy as an instance of
+ `Posts` — and a copy that touches nothing is a floating island.
-## Forbidden
-* No `document`, `window`, `canvas`, `Image`, `TextureLoader`, `fetch`, `XMLHttpRequest`,
- `Math.random()` (use a seeded hash), `Date`, `performance`.
-* ShaderMaterial is NOT exported to GLB — use `MeshStandardMaterial` /
- `MeshPhysicalMaterial` only. Colours via `new THREE.Color(0xRRGGBB)`; vertex colours
- allowed (`geometry.setAttribute('color', …)` + `vertexColors: true`).
-* Use `InstancedMesh` or merged geometries for repeats. `InstancedMesh`
- named `Posts` is exported as sibling meshes `Posts_0 … Posts_{n-1}` in its place
- (instance matrices and colours baked), so gates see every copy as an instance of `Posts`.
+## What is measured (the gates, with their thresholds)
+* **Contract** (`check_contract`, on the exported GLB against the plan): each plan part's bbox
+ centre and extents are within max(10 mm, 10 % of the plan extent) per axis — WARN beyond,
+ ERROR beyond 3 × that; the whole object's lowest point within 10 mm of y = 0 (WARN; ERROR
+ past 30 mm) and its footprint centre within max(10 mm, 10 % of the footprint) of the Y axis
+ (WARN); an object whose height runs along the wrong axis is reported as lying on its side;
+ a top-level node the plan does not name is reported as "not in the plan".
+* **Connectivity** (`check_connectivity`, per top-level part): two parts are in contact when
+ their surface gap is ≤ 2 mm. A part with no contact path to the supported assembly is a
+ floating ERROR, with the nearest supported part and the translation that closes the gap
+ (parts under 10 mm in their largest extent are INFO only). Penetration deeper than 2 mm
+ across a visible share of the part is a WARN, deeper than 10 mm an ERROR. Inside one part,
+ disconnected islands smaller than 5 % of the part are a `stray_islands` WARN — what a merge
+ leaves behind: a degenerate triangle, a duplicated ring at a lathe seam, a vertex at the
+ origin.
+* **Triangle budget** (the depth gate, sized from the plan's part × instance count): WARN below
+ 350 triangles per built object (floor clamped to 1 500 – 40 000), ERROR above 20 000 per
+ built object (ceiling clamped to 60 000 – 600 000); the target is about 2 000 per built
+ object; a build over 3 s per built object (at least 20 s) is a WARN. Detail inside a plan
+ part is invisible to the part-level gates; a new top-level node is a part.
+* **Build**: a geometry with a zero extent or radius, or `scale.set(0, 0, 0)` to hide something,
+ produces NaN positions / normals and fails the export (hide with `visible = false`, or do not
+ add it). The build is killed at `build_timeout_s` (300 s by default) and has a memory
+ limit; the triangle ceiling above is the only count enforced.
-## Self-check (optional, keep it tiny, at the end of object.js)
-If `object.js` exports `selfcheck(THREE, root)`, the harness calls it on the group
-returned by `build(THREE)` right after validation, before export. A throw fails the
-build as `SelfCheckError` with your message and file:line, so assert only what you
-are sure about (the contract gate measures the GLB anyway).
+## Self-check (optional, at the end of object.js)
+If `object.js` exports `selfcheck(THREE, root)`, the harness calls it on the group returned
+by `build(THREE)` after validation, before export. A throw fails the build as
+`SelfCheckError` with your message and file:line, so assert only what you are sure about
+(the contract gate measures the GLB anyway).
```js
export function selfcheck(THREE, root) {
const box = new THREE.Box3().setFromObject(root);
if (Math.abs(box.min.y) > 0.01) throw new Error(`object not on ground: min.y=${box.min.y}`);
- return box;
}
```
-## COMPLETE minimal example (verified in node with [email protected] + GLTFExporter)
+## The interface, and nothing else (runs in node with [email protected] + GLTFExporter)
-`src/parts/seat.js`
+`src/parts/body.js`
```js
import * as THREE from 'three';
-const SEAT_W = 0.40, SEAT_D = 0.40, SEAT_T = 0.04, SEAT_Y = 0.45; // plan numbers (m)
-export function buildSeat(THREE) {
- const g = new THREE.Group(); g.name = 'Seat';
- const mat = new THREE.MeshStandardMaterial({ color: 0x8b5a2b, roughness: 0.6 });
- const mesh = new THREE.Mesh(new THREE.BoxGeometry(SEAT_W, SEAT_T, SEAT_D), mat);
- mesh.position.set(0, SEAT_Y - SEAT_T / 2, 0); // top face at 0.45
+const SIZE = [0.3, 0.2, 0.3], CENTRE = [0, 0.1, 0]; // this part's plan bbox (world, metres)
+export function buildBody(THREE) {
+ const g = new THREE.Group(); g.name = 'Body'; // the plan's part name
+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(...SIZE), new THREE.MeshStandardMaterial({ color: 0x8a8f98 }));
+ mesh.name = 'BodyShell';
+ mesh.position.set(...CENTRE); // world pose: the centre, not the base
g.add(mesh);
return g;
}
```
-`src/parts/legs.js`
-```js
-import * as THREE from 'three';
-const LEG_R = 0.018, LEG_H = 0.45 - 0.04 + 0.001; // reaches 1 mm into the seat (weld)
-const LEG_XZ = 0.15;
-export function buildLegs(THREE) {
- const g = new THREE.Group(); g.name = 'Legs';
- const geo = new THREE.CylinderGeometry(LEG_R, LEG_R, LEG_H, 24);
- const mat = new THREE.MeshStandardMaterial({ color: 0x555a60, roughness: 0.35, metalness: 0.9 });
- [[1, 1], [-1, 1], [-1, -1], [1, -1]].forEach(([sx, sz], i) => {
- const m = new THREE.Mesh(geo, mat); m.name = `Leg_${i}`;
- m.position.set(sx * LEG_XZ, LEG_H / 2, sz * LEG_XZ);
- g.add(m);
- });
- return g;
-}
-```
`src/object.js`
```js
import * as THREE from 'three';
-import { buildSeat } from './parts/seat.js';
-import { buildLegs } from './parts/legs.js';
+import { buildBody } from './parts/body.js';
export function build(THREE) {
- const root = new THREE.Group(); root.name = 'Stool';
- root.add(buildSeat(THREE), buildLegs(THREE));
+ const root = new THREE.Group(); root.name = 'Object'; // the plan's object name
+ root.add(buildBody(THREE)); // one line per plan part
return root;
}
```
+What the part is made of — primitives, a lathe profile, an extruded outline, a swept tube,
+merged pieces, instanced repeats, raw `BufferGeometry` — is the brief's and the plan's.
diff --git a/harness/codeverse3d/prompts/threejs/cookbook.md b/harness/codeverse3d/prompts/threejs/cookbook.md
deleted file mode 100644
index 13187e86..00000000
--- a/harness/codeverse3d/prompts/threejs/cookbook.md
+++ /dev/null
@@ -1,523 +0,0 @@
-# three.js cookbook — static objects, three r182 (ESM), exported to GLB by the harness
-
-Every `js` snippet runs as-is in node (the harness test suite concatenates them with
-`THREE`, `mergeGeometries` and `RoundedBoxGeometry` in scope). Y-up, +Z front, meters,
-PascalCase Group names. The harness inlines the relevant chapters into your prompts;
-the full file is at `.3dcode/cookbook.md` in your workspace.
-
-## Module structure (skeleton)
-
-`src/parts/<snake>.js` — one builder per plan part, returns a Group **at world pose**:
-
-```js
-import * as THREE from 'three';
-// ---- plan numbers (metres) ---------------------------------------------------
-const SEAT_W = 0.44, SEAT_D = 0.44, SEAT_T = 0.035, SEAT_H = 0.45;
-const LEG = 0.035, WELD = 0.003; // parts overlap by WELD so they touch
-
-// ---- tiny helpers (copy into every part file; no shared helper module is allowed) ----
-const rand = (i) => { const s = Math.sin(i * 12.9898 + 78.233) * 43758.5453; return s - Math.floor(s); };
-function mesh(geo, mat, name, x = 0, y = 0, z = 0) {
- const m = new THREE.Mesh(geo, mat); m.name = name; m.position.set(x, y, z);
- m.castShadow = m.receiveShadow = true; return m;
-}
-const MAT = {
- oak: () => new THREE.MeshStandardMaterial({ color: 0x8a5a2b, roughness: 0.6, metalness: 0.0 }),
- steel: () => new THREE.MeshStandardMaterial({ color: 0x9a9da2, roughness: 0.3, metalness: 1.0 }),
-};
-
-export function buildSeat(THREE) {
- const g = new THREE.Group(); g.name = 'Seat';
- g.add(mesh(new RoundedBoxGeometry(SEAT_W, SEAT_T, SEAT_D, 3, 0.006), MAT.oak(), 'SeatSlab',
- 0, SEAT_H - SEAT_T / 2, 0));
- return g;
-}
-export function buildLegs(THREE) {
- const g = new THREE.Group(); g.name = 'Legs';
- const geo = new THREE.BoxGeometry(LEG, SEAT_H - SEAT_T + WELD, LEG);
- [[1, 1], [-1, 1], [-1, -1], [1, -1]].forEach(([sx, sz], i) =>
- g.add(mesh(geo, MAT.oak(), `Leg_${i}`, sx * (SEAT_W / 2 - LEG / 2 - 0.01),
- (SEAT_H - SEAT_T + WELD) / 2, sz * (SEAT_D / 2 - LEG / 2 - 0.01))));
- return g;
-}
-```
-
-`src/object.js` — assembles parts; nothing else:
-
-```js
-export function build(THREE) {
- const root = new THREE.Group(); root.name = 'Chair';
- root.add(buildSeat(THREE), buildLegs(THREE));
- return root; // Y-up, lowest point y = 0, no root.scale
-}
-```
-
-Why: the GLB node names come from Group/Mesh names; geometry in metres at world pose
-means `Box3().setFromObject(root)` equals what the harness measures.
-
-## Geometry toolkit
-
-```js
-// BoxGeometry(w, h, d): x, y, z extents. CylinderGeometry(rTop, rBottom, h, radial, heightSeg): axis Y.
-// SphereGeometry(r, w, h). TorusGeometry(R, r, radial, tubular): ring in the XY plane (rotateX(PI/2) to lay flat).
-// ConeGeometry(r, h, seg). PlaneGeometry(w, h): XY plane, faces +Z (rotateX(-PI/2) for a floor).
-const ring = new THREE.TorusGeometry(0.03, 0.006, 12, 32).rotateX(Math.PI / 2); // flat ring, axis Y
-
-// LatheGeometry: revolve a profile of Vector2(radius, y) around Y — bottles, vases, knobs, legs
-const profile = [[0, 0], [0.032, 0], [0.034, 0.01], [0.034, 0.16], [0.014, 0.21], [0.014, 0.25], [0, 0.25]]
- .map(([r, y]) => new THREE.Vector2(r, y));
-const bottle = new THREE.LatheGeometry(profile, 48); // normals point outward when r goes 0→R→0 bottom-up
-
-// ExtrudeGeometry from a Shape (+ holes) with bevel: plates, brackets, letters, panels
-const shp = new THREE.Shape();
-shp.moveTo(-0.05, 0); shp.lineTo(0.05, 0); shp.lineTo(0.05, 0.03); shp.lineTo(-0.05, 0.03); shp.closePath();
-const hole = new THREE.Path(); hole.absarc(0.03, 0.015, 0.006, 0, Math.PI * 2, true); shp.holes.push(hole);
-const plate = new THREE.ExtrudeGeometry(shp, { depth: 0.004, bevelEnabled: true, bevelThickness: 0.0008,
- bevelSize: 0.0008, bevelSegments: 2, curveSegments: 16 });
-plate.rotateX(-Math.PI / 2); // extrude goes +Z; lay it flat (thickness along Y)
-
-// Rounded rectangle shape helper (use for table tops, seats, screens)
-function roundedRectShape(w, h, r) {
- const s = new THREE.Shape(); const x = -w / 2, y = -h / 2;
- s.moveTo(x + r, y); s.lineTo(x + w - r, y); s.quadraticCurveTo(x + w, y, x + w, y + r);
- s.lineTo(x + w, y + h - r); s.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
- s.lineTo(x + r, y + h); s.quadraticCurveTo(x, y + h, x, y + h - r);
- s.lineTo(x, y + r); s.quadraticCurveTo(x, y, x + r, y); return s;
-}
-const top = new THREE.ExtrudeGeometry(roundedRectShape(0.6, 0.4, 0.02), { depth: 0.03, bevelEnabled: false }).rotateX(-Math.PI / 2);
-
-// TubeGeometry along a CatmullRomCurve3: cables, handles, pipes, railings
-const curve = new THREE.CatmullRomCurve3([new THREE.Vector3(0.05, 0.3, 0), new THREE.Vector3(0.1, 0.2, 0.02),
- new THREE.Vector3(0.18, 0.08, 0), new THREE.Vector3(0.3, 0.01, -0.03)]);
-const cable = new THREE.TubeGeometry(curve, 48, 0.004, 10, false);
-
-// RoundedBoxGeometry(w, h, d, segments, radius) — the default box for anything touched by hands
-const cushion = new RoundedBoxGeometry(0.4, 0.1, 0.4, 4, 0.03);
-
-// mergeGeometries: many static pieces → ONE mesh (fewer draw calls; keep per-part Groups for naming)
-function placed(geo, x, y, z, ry = 0) { const g = geo.clone(); g.rotateY(ry); g.translate(x, y, z); return g; }
-const slats = mergeGeometries([0, 1, 2, 3].map(i => placed(new THREE.BoxGeometry(0.4, 0.012, 0.05), 0, 0.6 + i * 0.08, -0.2)));
-slats.computeVertexNormals(); // always after merges / manual edits
-
-// InstancedMesh for N identical small parts (bolts, balusters, spokes)
-const bolt = new THREE.InstancedMesh(new THREE.CylinderGeometry(0.004, 0.004, 0.002, 12),
- new THREE.MeshStandardMaterial({ color: 0x333333, metalness: 1, roughness: 0.4 }), 8);
-const M = new THREE.Matrix4();
-for (let i = 0; i < 8; i++) { const a = i / 8 * Math.PI * 2; M.makeTranslation(0.1 * Math.cos(a), 0.031, 0.1 * Math.sin(a)); bolt.setMatrixAt(i, M); }
-bolt.instanceMatrix.needsUpdate = true; bolt.computeBoundingSphere(); bolt.name = 'Bolts';
-console.log('toolkit ok', bottle.attributes.position.count, plate.attributes.position.count, slats.attributes.position.count);
-```
-
-Why: these are the only geometry makers you need; everything else is position/rotation.
-Segments: 24–48 radial for visible cylinders, 8–12 for rods; tube radial 8–12.
-
-## Pivots and animation (optional `userData.tick`)
-
-```js
-// Rotate/translate a Group placed at the joint, never the mesh itself; identity scale on pivots.
-function buildFan(THREE) {
- const g = new THREE.Group(); g.name = 'Fan';
- const hub = new THREE.Group(); hub.name = 'FanHub'; hub.position.set(0, 1.2, 0.05); // pivot at the axle
- const bladeGeo = new THREE.BoxGeometry(0.02, 0.4, 0.004).translate(0, 0.25, 0); // blade root at the hub
- for (let i = 0; i < 3; i++) {
- const b = new THREE.Mesh(bladeGeo, new THREE.MeshStandardMaterial({ color: 0xdddddd }));
- b.name = `Blade_${i}`; b.rotation.z = i * Math.PI * 2 / 3; hub.add(b);
- }
- g.add(hub);
- g.userData.tick = (dt) => { hub.rotation.z += dt * 2.0; }; // rad/s
- return g;
-}
-const fan = buildFan(THREE); fan.userData.tick(0.016);
-```
-
-Why: a pivot Group makes the rotation axis explicit and keeps geometry static;
-geometry `.translate()` moves the blade root to the pivot so it spins correctly.
-
-## Materials (plain-object presets; only Standard/Physical export to GLB)
-
-```js
-const PRESETS = {
- oak: { color: 0x8a5a2b, roughness: 0.60, metalness: 0.0 },
- walnut: { color: 0x4a2c17, roughness: 0.55, metalness: 0.0 },
- steel: { color: 0x9a9da2, roughness: 0.30, metalness: 1.0 },
- brass: { color: 0xd4a24c, roughness: 0.35, metalness: 1.0 },
- black_plastic: { color: 0x111111, roughness: 0.45, metalness: 0.0 },
- white_ceramic: { color: 0xf0efe8, roughness: 0.15, metalness: 0.0 },
- fabric: { color: 0x5a6a8c, roughness: 0.95, metalness: 0.0 },
- rubber: { color: 0x151515, roughness: 0.85, metalness: 0.0 },
- glass: { color: 0xdfe9f2, roughness: 0.05, metalness: 0.0, transparent: true, opacity: 0.35 },
- emissive: { color: 0xfff1c0, emissive: 0xffe08a, emissiveIntensity: 2.0, roughness: 0.4 },
-};
-const mat = (key, extra = {}) => new THREE.MeshStandardMaterial({ ...PRESETS[key], ...extra });
-const glassMat = new THREE.MeshPhysicalMaterial({ color: 0xffffff, transmission: 0.9, roughness: 0.05, thickness: 0.005, transparent: true });
-
-// vertex colours (exported as COLOR_0): cheap variation without textures
-function colorByHeight(geo, lo = new THREE.Color(0x2b5a1f), hi = new THREE.Color(0x9bd65a)) {
- const pos = geo.attributes.position, col = new Float32Array(pos.count * 3), c = new THREE.Color();
- geo.computeBoundingBox(); const y0 = geo.boundingBox.min.y, y1 = geo.boundingBox.max.y || 1e-6;
- for (let i = 0; i < pos.count; i++) { c.copy(lo).lerp(hi, (pos.getY(i) - y0) / (y1 - y0)); col.set([c.r, c.g, c.b], i * 3); }
- geo.setAttribute('color', new THREE.BufferAttribute(col, 3));
- return new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.8 });
-}
-const leafMat = colorByHeight(new THREE.SphereGeometry(0.5, 16, 12));
-console.log('materials ok', mat('oak').color.getHexString(), leafMat.vertexColors);
-```
-
-Why: `MeshStandardMaterial` maps 1:1 to glTF PBR; `ShaderMaterial`, `MeshToonMaterial` and
-procedural textures are lost on export. Colours given as hex are sRGB (correct);
-`material.color.r` is linear internally — don't compare it with hex.
-
-## Detail (how to look good cheaply)
-
-| feature | recipe | size |
-|---|---|---|
-| rounded edges | `RoundedBoxGeometry(w,h,d, 3, r)` | r 2–6 mm furniture, 0.5–1 mm devices |
-| chamfered plate | `ExtrudeGeometry(shape, {bevelEnabled, bevelSize 1 mm, bevelSegments 1})` | |
-| seams / panel gaps | build panels 1 mm apart, darker material in the gap OR a thin dark box | 0.8–1.5 mm |
-| inset panel | a slightly smaller box 1–2 mm proud/sunk into the face | inset 5–10 mm |
-| fasteners | `InstancedMesh` of 12-seg cylinders, head Ø 5–8 mm, h 1–2 mm, sunk 0.5 mm | |
-| trim / edge band | `TubeGeometry` along the outline or a thin `TorusGeometry` | Ø 4–10 mm |
-| feet / glides | cylinders Ø 15–25 mm, h 5–10 mm under legs | |
-| cushions | `RoundedBoxGeometry(w, 0.08–0.12, d, 4, 0.03)` | |
-| handles / knobs | `TorusGeometry` / `LatheGeometry`, overlapping the panel 2 mm | knob Ø 25–35 mm |
-| fabric / wood variation | `colorByHeight` or per-instance colour via `setColorAt` | |
-
-Rules: ≥ 3 distinct masses in the silhouette; break every large flat face once; thin
-things are 1–3 mm, never 0; anything hands touch gets a radius.
-
-## Density: visual complexity without hand-modelling every screw
-
-Measured on this harness (183 judged rounds): **triangles inside a part are free score, extra
-top-level parts are not** — ρ(tri_per_part, geometry_detail) ≈ +0.08 while ρ(n_plan_parts,
-assembly_fit) = −0.48. Everything below adds density *inside* a part the plan already names,
-so `src/parts/<snake>.js` still returns exactly one `THREE.Group` called `<PascalName>`.
-
-**Where the budget goes** — silhouette first, then the 2–3 largest faces, then whatever is at eye
-height and at +Z (the front), then where two materials meet. Not: the underside, the back, or
-interior volumes. Skip subdividing a flat panel; add a seam instead.
-
-| priority | what | tri cost | recipe |
-|---|---|---|---|
-| 1 | silhouette break (taper, waist, overhang) | 0 | `LatheGeometry`, `ExtrudeGeometry` of the real section |
-| 2 | rounded edges everywhere hands touch | ×2–4 on that piece | `RoundedBoxGeometry`, `bevelEnabled` |
-| 3 | panel lines on big faces | ~100 | thin dark boxes 1 mm proud in the seam |
-| 4 | fasteners at real joints | 50–150 each | `instanceRing` |
-| 5 | counted repeats (slats, spokes, dentils) | 100–400 each | `repeatMerged` |
-| 6 | greebles in a bounded patch | 300–1500 | `greeblePatch` |
-| 7 | per-instance colour/scale variation | 0 | `setColorAt`, seeded jitter |
-
-```js
-// --- seeded RNG: identical repeats read as CG, 2-5 % variation reads as real.
-// NEVER Math.random() — the harness rebuilds your code and the judge sees both builds.
-function rng(seed) { let s = seed >>> 0 || 1; return () => (s = (s * 1664525 + 1013904223) >>> 0) / 4294967296; }
-
-// --- repeatMerged: N placed copies of one geometry, merged into ONE mesh.
-// The cheapest countable detail there is: spokes, slats, dentils, rafter tails, balusters.
-function repeatMerged(geo, n, place, { seed = 0, jitter = 0, tilt = 0, scale = 0 } = {}) {
- const r = rng(seed), out = [];
- for (let i = 0; i < n; i++) {
- const g = geo.clone();
- const s = 1 + (r() * 2 - 1) * scale;
- if (scale) g.scale(s, s, s);
- if (tilt) { g.rotateX((r() * 2 - 1) * tilt); g.rotateZ((r() * 2 - 1) * tilt); }
- const [x, y, z] = place(i, r);
- g.translate(x + (r() * 2 - 1) * jitter, y + (r() * 2 - 1) * jitter, z + (r() * 2 - 1) * jitter);
- out.push(g);
- }
- const merged = mergeGeometries(out);
- merged.computeVertexNormals();
- return merged;
-}
-
-// --- repeatRadial: N copies ROTATED around an axis through the origin. Spokes, dentils,
-// cage wires, flutes, balusters, turbine blades — anything on a circle. Merged into one mesh.
-function repeatRadial(geo, n, { axis = 'y', phase = 0, seed = 0, tilt = 0 } = {}) {
- const r = rng(seed), out = [];
- for (let i = 0; i < n; i++) {
- const g = geo.clone(), a = phase + (i / n) * Math.PI * 2;
- if (tilt) g.rotateX((r() * 2 - 1) * tilt);
- if (axis === 'y') g.rotateY(a); else if (axis === 'x') g.rotateX(a); else g.rotateZ(a);
- out.push(g);
- }
- const merged = mergeGeometries(out);
- merged.computeVertexNormals();
- return merged;
-}
-
-// 24 wheel spokes, ONE mesh: a rod laid along X, rotated 24× about Z (the wheel's axis)
-const spokeGeo = new THREE.CylinderGeometry(0.004, 0.004, 0.62, 6).rotateZ(Math.PI / 2);
-const spokes = new THREE.Mesh(repeatRadial(spokeGeo, 24, { axis: 'z' }),
- new THREE.MeshStandardMaterial({ metalness: 0.9, roughness: 0.35 }));
-spokes.name = 'Spokes';
-```
-
-```js
-// --- instanceRing: N identical fasteners as ONE InstancedMesh with per-instance colour.
-// The harness BAKES InstancedMesh into plain `<Name>_<i>` meshes at GLB export, so the
-// instance count becomes real objects — use it for 6-40 small repeats, not for 500.
-function instanceRing(geo, mat, n, radius, y, { seed = 0, tint = 0 } = {}) {
- const r = rng(seed), im = new THREE.InstancedMesh(geo, mat, n);
- const m = new THREE.Matrix4(), c = new THREE.Color();
- for (let i = 0; i < n; i++) {
- const a = (i / n) * Math.PI * 2;
- m.makeRotationY(-a);
- m.setPosition(radius * Math.cos(a), y, radius * Math.sin(a));
- im.setMatrixAt(i, m);
- if (tint) { c.setHSL(0, 0, 0.5 + (r() * 2 - 1) * tint); im.setColorAt(i, c); }
- }
- im.instanceMatrix.needsUpdate = true;
- if (im.instanceColor) im.instanceColor.needsUpdate = true;
- im.computeBoundingSphere();
- return im;
-}
-
-const boltHead = new THREE.CylinderGeometry(0.005, 0.0045, 0.002, 8);
-const bolts = instanceRing(boltHead, new THREE.MeshStandardMaterial({ metalness: 1, roughness: 0.45 }),
- 8, 0.09, 0.031, { seed: 4, tint: 0.06 });
-bolts.name = 'FlangeBolts';
-
-// --- greeblePatch: seeded surface clutter bounded to a rectangle, merged into one mesh.
-// Bound it so it can never break the silhouette or leave the part's planned bbox.
-function greeblePatch(w, d, { n = 24, seed = 0, hMin = 0.002, hMax = 0.010, cell = 0.02 } = {}) {
- const r = rng(seed), out = [];
- for (let i = 0; i < n; i++) {
- const bw = cell * (0.35 + r()), bd = cell * (0.35 + r()), bh = hMin + r() * (hMax - hMin);
- const g = new THREE.BoxGeometry(bw, bh, bd);
- g.translate((r() - 0.5) * (w - bw), bh / 2, (r() - 0.5) * (d - bd));
- out.push(g);
- }
- const merged = mergeGeometries(out);
- merged.computeVertexNormals();
- return merged;
-}
-
-// --- panelLines: 1 mm dark ribs sunk into a face — the cheapest "manufactured" cue there is.
-function panelLines(lines, thickness = 0.0015) {
- const geos = lines.map(([x, y, z, w, h]) =>
- new THREE.BoxGeometry(Math.max(w, thickness), Math.max(h, thickness), thickness).translate(x, y, z));
- const merged = mergeGeometries(geos);
- merged.computeVertexNormals();
- return merged;
-}
-
-// one housing part: shell + greebles + seams + bolts = ONE Group named as the plan says
-const housing = new THREE.Group();
-housing.name = 'MotorHousing';
-housing.add(new THREE.Mesh(new RoundedBoxGeometry(0.24, 0.10, 0.16, 3, 0.006),
- new THREE.MeshStandardMaterial({ color: 0x5a5f66, roughness: 0.55 })));
-housing.add(new THREE.Mesh(greeblePatch(0.20, 0.12, { n: 26, seed: 7 }).translate(0, 0.05, 0),
- new THREE.MeshStandardMaterial({ color: 0x4c5158, roughness: 0.6 })));
-housing.add(new THREE.Mesh(panelLines([[0, 0.0, 0.0805, 0.22, 0.001], [0, -0.03, 0.0805, 0.22, 0.001]]),
- new THREE.MeshStandardMaterial({ color: 0x1a1c1f, roughness: 0.9 })));
-housing.add(bolts);
-```
-
-```js
-// --- profile sweeps: draw the SECTION once, drag it along the path. Mouldings, handrails,
-// rims, gutters, cornices. A curved path needs one sample per 5-10 degrees, not four corners.
-function sweep(sectionPts, pathPts, { closed = false, radialSegments = 1 } = {}) {
- const shape = new THREE.Shape(sectionPts.map(([x, y]) => new THREE.Vector2(x, y)));
- const curve = new THREE.CatmullRomCurve3(pathPts.map(([x, y, z]) => new THREE.Vector3(x, y, z)), closed);
- const geo = new THREE.ExtrudeGeometry(shape, { steps: pathPts.length * 2, bevelEnabled: false,
- extrudePath: curve, curveSegments: 4 * radialSegments });
- geo.computeVertexNormals();
- return geo;
-}
-
-const HANDRAIL = [[0.022, 0], [0.010, 0.009], [-0.010, 0.009], [-0.022, 0], [0, -0.006]];
-const helix = [];
-for (let a = 0; a <= 360; a += 5) {
- const t = (a * Math.PI) / 180;
- helix.push([0.70 * Math.cos(t), 0.95 + 0.0075 * a, 0.70 * Math.sin(t)]);
-}
-const handrail = new THREE.Mesh(sweep(HANDRAIL, helix), new THREE.MeshStandardMaterial({ color: 0x2b2b2b }));
-handrail.name = 'Handrail';
-
-// --- the density check: what would tell a photo of the real thing from this?
-// "edges are perfectly sharp" -> RoundedBoxGeometry / bevelEnabled. "one flat face" -> panelLines.
-// "no fixings" -> instanceRing. "repeats are identical" -> repeatMerged with jitter/tilt/scale.
-// "all one grey" -> split the materials. Then count: `measure` prints the triangle total.
-const density = [spokes, bolts, housing, handrail];
-let densityTris = 0;
-for (const o of density) o.traverse((m) => { if (m.isMesh) densityTris += (m.geometry.index ? m.geometry.index.count : m.geometry.attributes.position.count) / 3 * (m.count || 1); });
-console.log('[selfcheck] density recipes tris', Math.round(densityTris), 'parts', density.length);
-if (densityTris < 3000) throw new Error('density recipes produced almost no geometry: ' + densityTris);
-```
-
-## Common objects — dimensions (metres, Y-up) and decomposition
-
-| object | W × D × H | parts | key numbers |
-|---|---|---|---|
-| dining chair | 0.45 × 0.50 × 0.90 | Seat, Backrest, Leg ×4, Stretchers | seat y 0.45, t 0.035, leg 0.035, rake 8° |
-| sofa | 2.0 × 0.9 × 0.85 | Base, SeatCushion ×3, BackCushion ×3, ArmLeft/Right, Legs | seat y 0.42, arm y 0.60, cushion 0.11 |
-| table | 1.6 × 0.9 × 0.75 | Top, Apron, Leg ×4 | top t 0.035, legs 0.07 at 0.05 inset |
-| desk lamp | Ø 0.18 × 0.55 | Base, ArmLower, ArmUpper, Shade, Bulb | arm Ø 0.012, shade Ø 0.15 |
-| mug | Ø 0.085 × 0.095 | Body (Lathe), Handle (Tube) | wall 4 mm, handle Ø 12 mm |
-| bottle | Ø 0.075 × 0.30 | Body (Lathe), Cap | neck Ø 0.028 |
-| bicycle | 1.75 × 0.6 × 1.05 | Frame(Tubes), FrontWheel/RearWheel(Torus + spokes), Fork, Handlebar, Saddle, Crank, Pedals, Chain | wheel Ø 0.70, tyre 0.03, BB y 0.27 |
-| car | 4.6 × 1.85 × 1.45 | Body(Extrude side profile), Cabin, Wheel×4, Bumpers, Mirrors, Lights | wheel Ø 0.65, wheelbase 2.7, clearance 0.15 |
-| house | 10 × 8 × 7 | Walls, Roof(Extrude triangle), Door, Windows, Chimney | storey 2.8, pitch 35°, door 0.9 × 2.1 |
-| tree | crown Ø 7 × H 12 | Trunk(Cylinder taper), Branches(Tube), Crown(3–6 spheres, vertex colours) | trunk Ø 0.4 |
-| bookshelf | 0.8 × 0.3 × 1.8 | SideLeft/Right, Top, Bottom, Shelf ×4, Back | panel 18 mm |
-| monitor | 0.62 × 0.2 × 0.45 | Panel, Stand, Base | bezel 8 mm |
-
-Decomposition: 1 main mass → 2–6 secondary masses touching it → attachments overlapping
-≥ 2 mm → detail pass. Z is the FRONT: the chair's backrest sits at −Z, seat front at +Z.
-
-## Raw BufferGeometry and a spoked wheel (when no primitive fits)
-
-```js
-// Custom BufferGeometry: positions (+ index) → computeVertexNormals(). A ramp wedge:
-function wedgeGeometry(w, h, d) {
- const g = new THREE.BufferGeometry();
- const v = [ -w/2,0,d/2, w/2,0,d/2, w/2,0,-d/2, -w/2,0,-d/2, // base quad
- -w/2,h,-d/2, w/2,h,-d/2 ]; // top back edge
- const idx = [0,2,1, 0,3,2, 0,1,5, 0,5,4, 1,2,5, 3,4,2, 4,5,2, 0,4,3];
- g.setAttribute('position', new THREE.Float32BufferAttribute(v, 3));
- g.setIndex(idx);
- g.computeVertexNormals(); // ALWAYS, or it shades black
- return g;
-}
-const ramp = new THREE.Mesh(wedgeGeometry(0.6, 0.25, 0.5), new THREE.MeshStandardMaterial({ color: 0x777777 }));
-
-// Spoked wheel: torus tyre + lathed rim + instanced spokes + hub — the bicycle staple
-function buildWheel(THREE, R = 0.35, tyreR = 0.017, spokes = 18) {
- const g = new THREE.Group(); g.name = 'Wheel';
- const tyre = new THREE.Mesh(new THREE.TorusGeometry(R, tyreR, 10, 48),
- new THREE.MeshStandardMaterial({ color: 0x151515, roughness: 0.85 }));
- tyre.name = 'Tyre'; g.add(tyre);
- // the torus lies in the XY plane, so this wheel's axle is the LOCAL Z axis; build the
- // whole wheel that way and let the parent orient it (axle along X: wheel.rotateY(PI/2)).
- const hub = new THREE.Mesh(new THREE.CylinderGeometry(0.02, 0.02, 0.08, 16).rotateX(Math.PI / 2),
- new THREE.MeshStandardMaterial({ color: 0x8a8d92, metalness: 1, roughness: 0.3 }));
- hub.name = 'Hub'; g.add(hub);
- const spokeGeo = new THREE.CylinderGeometry(0.0012, 0.0012, R - 0.02, 5).translate(0, (R - 0.02) / 2 + 0.015, 0);
- const spoke = new THREE.InstancedMesh(spokeGeo, hub.material, spokes);
- const m = new THREE.Matrix4(), q = new THREE.Quaternion(), z = new THREE.Vector3(0, 0, 1);
- for (let i = 0; i < spokes; i++) {
- q.setFromAxisAngle(z, i / spokes * Math.PI * 2);
- m.makeRotationFromQuaternion(q);
- spoke.setMatrixAt(i, m);
- }
- spoke.computeBoundingSphere(); spoke.name = 'Spokes'; g.add(spoke);
- return g; // parent: wheel.rotateY(Math.PI/2) to put the axle along X, then position it
-}
-const wheel = buildWheel(THREE);
-console.log('wheel parts', wheel.children.map(c => c.name), 'ramp tris', ramp.geometry.index.count / 3);
-```
-
-Why: an indexed position buffer plus `computeVertexNormals()` covers any faceted shape a
-primitive cannot; a wheel is 3 draw calls at any spoke count thanks to the InstancedMesh.
-
-## Pitfalls (symptom → cause → fix)
-
-1. **Object lies on its side in the render** → you built Z-up. three.js/glTF are Y-up;
- height is Y, front is +Z. `CylinderGeometry` axis is Y; floors are `PlaneGeometry` rotated
- `-PI/2` about X.
-2. **`mesh.position` vs `geometry.translate`** — position moves the pivot (animation-
- friendly), `geometry.translate()` bakes the offset (needed before `mergeGeometries` and
- for blade-root pivots). Pick deliberately; never do both by accident.
-3. **"All geometries must have compatible attributes"** in `mergeGeometries` → one input
- has `uv`/`color` or an index and another not. Delete extra attributes
- (`geo.deleteAttribute('uv')`) or `toNonIndexed()` all; then `computeVertexNormals()`.
-4. **Faceted / black shading after edits** → call `geometry.computeVertexNormals()`; for
- flipped faces use `geometry.scale(-1,1,1)` carefully or rebuild the profile order.
-5. **`userData.tick` never runs** → nothing in the harness calls it (the GLB export drops
- it): the judged pose is the one `build` returns; don't animate scale.
-6. **Renderer / Scene / Camera / Light / OrbitControls in object code** → forbidden; the
- module is imported in node with no WebGL. `document`/`canvas`/`Image`/`TextureLoader`
- crash the build.
-7. **Imports that do not exist in r182**: `three/examples/js/*`, `BufferGeometryUtils.
- mergeBufferGeometries` (now `mergeGeometries`), `Geometry`/`Face3`, `THREE.sRGBEncoding`,
- `outputEncoding`. Use `three/addons/utils/BufferGeometryUtils.js`,
- `three/addons/geometries/RoundedBoxGeometry.js`.
-8. **`root.scale.set(0.01, …)` to convert mm → m** → bounds/gates see scaled geometry
- inconsistently; author in metres, root scale stays (1,1,1).
-9. **Floating parts** → overlap neighbours by ≥ 2 mm along the contact normal; legs reach
- INTO the seat, handles INTO the body.
-10. **Hidden parts via tiny scale** → use `visible = false` or don't add them; never
- `scale.set(0,0,0)` (NaN normals in the exporter).
-11. **`InstancedMesh` disappears** → `computeBoundingSphere()` after setting matrices, or
- `frustumCulled = false`; set `instanceMatrix.needsUpdate = true`.
-12. **Math.random()** → non-reproducible builds; use the `rand(i)` hash.
-13. **ShaderMaterial / textures** → not in GLB; use Standard/Physical + vertex colours.
-14. **Huge triangle counts** → `SphereGeometry(r, 64, 64)` ×100 = 800 k tris; use 16×12 for
- small spheres, instancing for repeats, merged geometries for static detail.
-15. **Mixed three copies** (`instanceof` failures) → import only from `'three'` and
- `'three/addons/…'`; never copy three sources into `src/`.
-
-## Self-check (before you call it done)
-
-```js
-export function selfcheck(THREE, root, expectedNames = [], extentsHint = null) {
- const names = new Set(); let tris = 0;
- root.traverse(o => {
- if (o.name) names.add(o.name);
- if (o.isMesh) { const g = o.geometry; const n = g.index ? g.index.count / 3 : g.attributes.position.count / 3;
- tris += n * (o.isInstancedMesh ? o.count : 1); }
- });
- const missing = expectedNames.filter(n => !names.has(n));
- if (missing.length) throw new Error(`missing parts: ${missing.join(', ')}`);
- const box = new THREE.Box3().setFromObject(root); const size = box.getSize(new THREE.Vector3());
- if (Math.abs(box.min.y) > 0.01) throw new Error(`lowest point y=${box.min.y.toFixed(4)} (expected 0)`);
- if (extentsHint) extentsHint.forEach((e, i) => { if (Math.abs(size.getComponent(i) - e) > 0.05) throw new Error(`extents ${size.toArray()} vs plan ${extentsHint}`); });
- console.log(`[selfcheck] parts=${names.size} tris=${tris} extents=${size.toArray().map(v => v.toFixed(3))}`);
- return { tris, size };
-}
-selfcheck(THREE, build(THREE), ['Seat', 'Legs', 'Leg_0', 'Leg_3'], [0.44, 0.45, 0.44]);
-```
-The harness also calls an exported `selfcheck(THREE, root)` on the built group (defaults
-above make that call permissive); a throw fails the build as `SelfCheckError` with your
-message, so keep the assertions truthful.
-
-Then use the tools: `build` → `render_sheet` → `check_connectivity` → `isolate` → `check_contract`.
-
-## Worked example: mug (Lathe body + Tube handle, welded) and desk lamp (pivots)
-
-```js
-export function buildMug(THREE) {
- const R = 0.042, H = 0.095, WALL = 0.004, FLOOR = 0.006;
- const g = new THREE.Group(); g.name = 'Mug';
- // profile goes: outside bottom → outside top → inside top → inside floor → axis (closed, outward normals)
- const pts = [[0, 0], [R - 0.006, 0], [R, 0.006], [R, H - 0.004], [R - 0.002, H], [R - WALL, H],
- [R - WALL, FLOOR], [0, FLOOR]].map(([r, y]) => new THREE.Vector2(r, y));
- const body = new THREE.Mesh(new THREE.LatheGeometry(pts, 48), new THREE.MeshStandardMaterial({ color: 0xf0efe8, roughness: 0.2 }));
- body.name = 'MugBody'; g.add(body);
- // handle: a C-curve that starts and ends 3 mm INSIDE the wall (weld), tube Ø 12 mm
- const c = new THREE.CatmullRomCurve3([
- new THREE.Vector3(R - 0.003, H * 0.78, 0), new THREE.Vector3(R + 0.028, H * 0.72, 0),
- new THREE.Vector3(R + 0.034, H * 0.45, 0), new THREE.Vector3(R + 0.022, H * 0.22, 0),
- new THREE.Vector3(R - 0.003, H * 0.20, 0)]);
- const handle = new THREE.Mesh(new THREE.TubeGeometry(c, 32, 0.006, 12, false), body.material);
- handle.name = 'MugHandle'; g.add(handle);
- return g;
-}
-
-export function buildDeskLamp(THREE) {
- const g = new THREE.Group(); g.name = 'DeskLamp';
- const metal = new THREE.MeshStandardMaterial({ color: 0x2a2d33, roughness: 0.35, metalness: 0.9 });
- const base = new THREE.Mesh(new THREE.CylinderGeometry(0.09, 0.10, 0.02, 48), metal); base.name = 'Base'; base.position.y = 0.01;
- // lower arm pivots at the base top; upper arm pivots at the elbow; shade pivots at the wrist
- const shoulder = new THREE.Group(); shoulder.name = 'Shoulder'; shoulder.position.set(0, 0.02 - 0.003, 0); shoulder.rotation.z = -0.35;
- const armLo = new THREE.Mesh(new THREE.CylinderGeometry(0.007, 0.007, 0.30, 16).translate(0, 0.15, 0), metal); armLo.name = 'ArmLower';
- const elbow = new THREE.Group(); elbow.name = 'Elbow'; elbow.position.y = 0.30 - 0.004; elbow.rotation.z = 1.25;
- const armUp = new THREE.Mesh(new THREE.CylinderGeometry(0.006, 0.006, 0.26, 16).translate(0, 0.13, 0), metal); armUp.name = 'ArmUpper';
- const wrist = new THREE.Group(); wrist.name = 'Wrist'; wrist.position.y = 0.26 - 0.004; wrist.rotation.z = -1.2;
- const shade = new THREE.Mesh(new THREE.CylinderGeometry(0.03, 0.075, 0.12, 32, 1, true).translate(0, -0.05, 0),
- new THREE.MeshStandardMaterial({ color: 0xc8c8c8, roughness: 0.4, metalness: 0.6, side: THREE.DoubleSide }));
- shade.name = 'Shade';
- const bulb = new THREE.Mesh(new THREE.SphereGeometry(0.02, 16, 12), new THREE.MeshStandardMaterial({ color: 0xfff4d0, emissive: 0xffe3a0, emissiveIntensity: 2 }));
- bulb.name = 'Bulb'; bulb.position.y = -0.06;
- wrist.add(shade, bulb); armUp.add(wrist); elbow.add(armUp); armLo.add(elbow); shoulder.add(armLo);
- g.add(base, shoulder);
- g.userData.tick = (dt) => { elbow.rotation.z = 1.25 + 0.15 * Math.sin((elbow.userData.t = (elbow.userData.t || 0) + dt) * 0.8); };
- return g;
-}
-const lamp = buildDeskLamp(THREE); lamp.userData.tick(0.1);
-selfcheck(THREE, buildMug(THREE), ['MugBody', 'MugHandle'], [0.118, 0.095, 0.084]);
-const lampBox = new THREE.Box3().setFromObject(lamp); console.log('lamp height', lampBox.max.y.toFixed(3));
-```
-
-Why: the mug profile contains the wall (no boolean needed); the handle curve ends inside
-the wall so `check_connectivity` sees one island; the lamp's three pivot Groups sit at the
-joints so `tick` can articulate it without touching geometry.
diff --git a/harness/codeverse3d/prompts/threejs/system.md b/harness/codeverse3d/prompts/threejs/system.md
index 04015ffb..0e4204ad 100644
--- a/harness/codeverse3d/prompts/threejs/system.md
+++ b/harness/codeverse3d/prompts/threejs/system.md
@@ -1,51 +1,56 @@
-You are a three.js modeller writing RAW ESM for a headless harness. No SDKs, no helper
-libraries, no CDN imports: `import * as THREE from 'three'` and nothing else. You build
-the object out of `BufferGeometry` and `Mesh`; the harness owns the renderer, the export
-and the cameras — never render, never add lights, never touch the DOM.
+You are a three.js modeller writing RAW ESM for a headless harness. Imports that resolve:
+`three`, `three/addons/*`, relative files under `src/`; anything else is a lint ERROR
+(`bad_import`). `build(THREE)` returns a `THREE.Group` containing at least one mesh; the
+exporter fails a group with no meshes or a NaN / empty bounding box. The harness owns the
+renderer, the export and the cameras: a renderer or a render loop in object code is a lint
+ERROR, a light or a camera a lint WARN that the export ignores.
{% if tools %}
The loop that decides whether your work ships:
- write → `build` → `check_connectivity` + `check_contract` → fix everything they
+ write → `build` → `check_connectivity` + `check_contract` → fix what they
report → repeat → `render_views` → LOOK at the sheet → only then finish.
-Do not finish while either still reports a warning. `isolate` shows you one part alone,
-which settles "where did that fragment come from" faster than reading the code does.
+Every WARN and ERROR the gates report at the end of a round goes to the judge with the
+renders, and an ERROR on connectivity or contract caps the score. `isolate` shows one
+part alone, which settles "where did that fragment come from" faster than reading the
+code does.
{% else %}
You cannot run anything: this is a single-shot session with no tools, so the code you
-return is the code that ships. Before you finish, walk the mesh list once: is each part
-one solid piece, does each one touch what it is supposed to touch, and does its bounding
-box match the number the plan gave it.
+return is the code that ships. Before you finish, walk the part list once: does any part
+carry a loose fragment, does each one touch what it is supposed to touch, and does its
+bounding box match the number the plan gave it.
{% endif %}
-What the gates name, measured over 25 recorded runs of this exact track:
-
-* **Stray islands** — the dominant defect here, 216 findings, far more than on the other
- static-object languages: "part 'X' contains N tiny disconnected islands — stray
- geometry". In three.js this is what a merged `BufferGeometry` leaves behind: a
- degenerate triangle, a duplicated ring at a lathe seam, a leftover vertex at the origin.
- Every part must be one connected shell. If you merge geometries, merge only the ones
- that are genuinely one part, and make sure the seams actually share vertices.
-* **Interpenetration** (193 findings, 81 of them errors) — parts may overlap by **≤ 2 mm**.
- Position a part by computing where its face lands. Remember that a `BoxGeometry` is
- centred on its origin: a 0.1 m leg placed at `y = 0` is half underground.
-* **Floating parts** (36 errors) — "part 'X' is floating: nearest supported part is at N".
- The object must be one connected assembly. A part that touches nothing is not attached
- no matter how close it looks in the render.
-* **Bbox deviates from the plan** (38) and **parts not in the plan** (37) — build what you
- planned, and export nothing else. No helper meshes, no bounding boxes, no axes.
-
-Rules that survive every brief:
-
-* **Author in metres at real scale**, with `mesh.name` set to exactly the plan's part name.
- The gates match on names, and an unnamed mesh is an unscored part.
-* **Geometry primitives are centred on their origin.** Every placement is
- `position = where_the_part_goes + half_its_own_height`. Most floating and sunken parts
- in this corpus are that one term.
-* **Give every part real material properties** but no lights and no environment — the
- harness lights the scene, and a light you add is a light it did not expect.
+What the gates measure on this track, most frequent first (thresholds in the contract):
+
+* **Stray islands** — `check_connectivity` counts the disconnected islands inside every
+ top-level part and reports the ones smaller than 5 % of the part's largest extent as stray
+ geometry. In three.js that is what a merged `BufferGeometry` leaves behind: a degenerate
+ triangle, a duplicated ring at a lathe seam, a leftover vertex at the origin.
+* **Interpenetration** — two parts may overlap by at most 2 mm; deeper is a WARN, past
+ 10 mm an ERROR. A `BoxGeometry` is centred on its origin: a 0.1 m leg placed at `y = 0`
+ is half underground.
+* **Floating parts** — every part touches the assembly: a surface gap ≤ 2 mm counts as
+ contact; a part farther than that from every supported part is a floating ERROR,
+ however close it looks in the render (parts under 10 mm in extent are INFO only).
+* **Bbox deviates from the plan** and **parts not in the plan** — each plan part's bbox
+ centre and extents are within max(10 mm, 10 % of the plan extent) per axis (WARN; three
+ times that is an ERROR); a top-level node the plan does not name is reported as "not in
+ the plan", so no helper meshes, bounding boxes or axes reach the GLB.
+
+Facts that hold for every brief:
+
+* **Author in metres at real scale.** The part Group's `name` is the plan's PascalCase
+ part name: the GLB's top-level node name is how the gates find the part. A mesh with no
+ name is a build warning.
+* **three.js primitives are centred on their origin**, so a part's `position` is its
+ CENTRE, not its base. Most floating and sunken parts on this track are that one term.
+* **Only `MeshStandardMaterial` / `MeshPhysicalMaterial` colour, roughness, metalness,
+ emissive and vertex colours survive the GLB export.** The harness lights and renders the
+ exported file its own way.
* **You place the object; the harness exports it as authored.** It never re-centres or
- grounds it, so seating the whole assembly on the ground yourself is fine.
+ grounds it; the build warns past 10 mm and `check_contract` measures the same thing.
-A clean simpler object beats a richer one carrying a visible defect. Clear connectivity
-and contract first, then spend what is left on the detail the brief asked for.
+Gate ERRORs cap the score, and the depth gate also WARNs below its triangle floor, so a
+bare stack of primitives is not free either — both numbers are in the contract.
diff --git a/harness/codeverse3d/prompts/tracks/assemble_static.j2 b/harness/codeverse3d/prompts/tracks/assemble_static.j2
index dd84a228..21b38ee8 100644
--- a/harness/codeverse3d/prompts/tracks/assemble_static.j2
+++ b/harness/codeverse3d/prompts/tracks/assemble_static.j2
@@ -1,7 +1,7 @@
# Assemble `{{ object_name }}` — you own placement, not geometry
{{ n_parts }} part{{ 's' if n_parts > 1 else '' }} were written in parallel, one session per group, each into its own file.
-You own the ENTRY file: it imports every part builder, calls them in plan order and self-checks.
+You own the ENTRY file the wrapper runs: it imports every part builder and calls each once.
You are the only session that sees the whole object, so **assembly is your responsibility**:
every part present, nothing floating, nothing interpenetrating, the whole thing standing on the ground.
@@ -27,7 +27,8 @@ Overall bbox: {{ overall_bbox }}
IS yours to fix — make the smallest change that makes it build.
3. Run `measure`. Compare each measured part box with the table above.
4. Run `check_connectivity` and `check_contract`. Every ERROR must be gone before you finish:
- - a **floating** part → move it (or its neighbour) so the surfaces overlap by 2–5 mm;
+ - a **floating** part → apply the finding's translation, or extend it by the printed mm, so the
+ surfaces touch (gap ≤ 2 mm, overlap ≤ 2 mm);
- an **interpenetrating** pair → pull one back to its plan box;
- a **missing** part → the builder was not called, or it built under a parent Empty
(instances must be TOP-LEVEL objects), or its name does not match the table exactly;
diff --git a/harness/codeverse3d/prompts/tracks/brief_object.j2 b/harness/codeverse3d/prompts/tracks/brief_object.j2
index 447e1dd2..c7030eae 100644
--- a/harness/codeverse3d/prompts/tracks/brief_object.j2
+++ b/harness/codeverse3d/prompts/tracks/brief_object.j2
@@ -11,28 +11,28 @@ WHAT TO PRODUCE
a catalogue item ("Peugeot 1920s cast-iron box grinder", "Record No. 4 bench vise",
"1960s Danish teak dining chair"). Never "a generic X".
3. `one_line` — what it is, one sentence.
-4. `dimensions_m` — 4-10 rows `{name, meters}` giving the real-world dimensions of THAT
+4. `dimensions_m` — up to 12 rows `{name, meters}` giving the real-world dimensions of THAT
instance in METERS: `width`, `depth`, `height`, `length`, `diameter`, plus any part
dimension that matters (`wheel_diameter`, `handle_length`, `wall_thickness`,
`spoke_thickness`). A coffee mug is 0.090 m across, not 1.0. Include the small ones —
they are what makes a model read as real.
-5. `sub_assemblies` — the assemblies a fitter would name when taking it apart (3-8). For each:
+5. `sub_assemblies` — the assemblies a fitter would name when taking it apart (up to 10). For each:
`name` as a catalogue would print it, `purpose` one line, `parts` the pieces it is built from
(named the way a parts diagram names them), `material`. This is the spine of the 3D plan:
a "burr mechanism" is a burr cone, a grind-adjust nut, a shaft, a bearing collar and a spring —
NOT one lump.
6. `mechanism` — how it works: what moves, what turns, where force or material goes in and comes
out. One paragraph. For a purely static object, say how it is assembled and what carries load.
-7. `visible_from_outside` — the things a viewer actually SEES when it sits on a table (8-16 items,
+7. `visible_from_outside` — the things a viewer actually SEES when it sits on a table (up to 16 items,
each concrete: "the seam line where the crumb tray slides out", "six vertical flutes on the
body", "the exposed rafter tails under the eave"). These, and only these, are worth modelling.
8. `hidden_inside` — real parts that are NOT visible from outside and must therefore not be built
(springs inside a housing, wiring, the underside of a lid that never opens).
9. `not_present` — what a naive model would wrongly add (a modern grinder has a motor; an antique
one does NOT — "electric motor, power cord, plastic buttons").
-10. `signature_features` — 3 to 6 features a viewer uses to RECOGNISE this object. If one of them
+10. `signature_features` — up to 6 features a viewer uses to RECOGNISE this object. If one of them
is missing the model reads as the wrong object. Order them by how load-bearing they are.
-11. `materials` — `"<part>: <material, colour, finish>"` lines (6-12): "body: quarter-sawn beech,
+11. `materials` — one `"<part>: <material, colour, finish>"` line per visible material, at most 12: "body: quarter-sawn beech,
warm mid brown, satin", "dome: cast iron, near-black, slightly rough".
RULES
diff --git a/harness/codeverse3d/prompts/tracks/generate_articulated.j2 b/harness/codeverse3d/prompts/tracks/generate_articulated.j2
index 8cc2fc0f..1944f9c7 100644
--- a/harness/codeverse3d/prompts/tracks/generate_articulated.j2
+++ b/harness/codeverse3d/prompts/tracks/generate_articulated.j2
@@ -1,7 +1,8 @@
# Build the articulated `{{ object_name }}`: bpy links + hand-written URDF
-You write TWO files: `src/model.py` (raw bpy — one mesh object per LINK, authored in WORLD
-coordinates at the rest pose) and `src/robot.urdf` (native URDF describing the joints). The harness
+You write TWO files: `src/model.py` (raw bpy — per LINK, the object named exactly as the link plus
+anything parented under it, authored in WORLD coordinates at the rest pose) and `src/robot.urdf`
+(native URDF describing the joints). The harness
exports each link to `meshes/<link>.glb`, lints the URDF, runs forward kinematics, sweeps every joint
between its limits and checks for penetrations, then renders rest + limit poses for a judge.
@@ -16,10 +17,6 @@ Constraints:
## The contract (hard rules)
{{ frame_doc }}
{{ contract }}
-Copyable snippets live in `.3dcode/cookbook.md`.{% if cookbook_excerpt %}
-Cookbook excerpt:
-{{ cookbook_excerpt }}
-{% endif %}
## Plan
{{ plan_summary }}
@@ -33,36 +30,39 @@ Links (one bpy object each; link name = the snake_case of the `part` column, `Do
Link construction notes:
{{ part_details }}
-Joints (the URDF must realise EXACTLY these; pivots are WORLD points at rest):
+Joints — the brief's requirement, as the harness measures it: the tree must carry these names,
+parents and children (URDF lint), each `motion` word is checked against the direction positive q
+moves the child (`motion_direction`, 60° cone) and the limits are the range the sweep tests; pivots
+are WORLD points at rest:
{{ joints_table }}
## Acceptance checklist
{{ acceptance }}
## DO
-- Build every link at its WORLD rest pose with the plan's bbox centre/extents; each link is
- ONE object (join sub-shapes into it) named exactly as the link.
-- Joint origins: every link frame sits at its joint's world pivot (root at the world origin), so the
- URDF `<joint><origin xyz>` = pivot_child − pivot_parent (plain subtraction of world points; root
- parent pivot = 0 0 0). The harness exports meshes/<link>.glb in WORLD coordinates, therefore the
- child's visual AND collision `<origin xyz>` = −P (the NEGATED world pivot; root link: `0 0 0`) —
- never the mesh-centre offset. Keep the numbers consistent with the bbox centres in the table —
- write them out explicitly as comments in the URDF before the joint.
-- Use the axis vectors from the table verbatim; limits = lower/upper from the table; `effort`/
- `velocity` any positive numbers.
-- Keep 1–3 mm of clearance along each joint's motion direction between the child link and the
- links it moves past (drawer vs cabinet walls, door vs frame); fixed neighbours overlap ≥ 0.002 m.
-- Hinged lids/doors pivot at their EDGE (the hinge line), drawers slide along the cabinet depth.
+- Build every link at its WORLD rest pose to the plan's bbox (`check_contract`: max(10 mm, 10 %) per
+ axis); one object named exactly as the link, with any helper objects parented under it (the
+ wrapper joins them).
+- Use the table's axes and limits (the skeleton already wrote them); if the motion check shows
+ positive q moving the child against the plan's `motion` word, negate that axis — never swap the
+ limits. `effort`/`velocity`: any positive numbers.
+- Clearance is measured, not estimated: no overlap deeper than 2 mm in any sweep pose (a moved-pose
+ overlap is always an ERROR; a rest overlap above 5 mm fails the build); a fixed child within 2 mm
+ of its parent, a moving child within 10 mm.
+- Every pivot lies on the real hinge line or slide axis of the part (the motion check measures the
+ link's centroid displacement; a centred pivot gives none and the part sweeps through its neighbour).
## DON'T
-- No camera/light/render/export calls in bpy; no imports beyond bpy/bmesh/math/mathutils/random.
-- No links that float (every non-root link touches its parent at rest, or is attached by its joint
- at a pivot that lies ON the child link's geometry).
+- No camera/light/render/export calls in bpy; imports are the ones the blender lint allows (the
+ contract's Allowed / forbidden section).
+- No floating links: at rest a fixed child's mesh is within 2 mm of its parent's, a hinged or sliding
+ child's within 10 mm (ERROR beyond 30 mm; a prismatic child already inside its parent's bbox is
+ exempt).
- No joint whose child passes through another link anywhere in [lower, upper].
- No renaming of links/joints; no extra root links; one tree rooted at `{{ root_link }}` as planned.
{% if skeleton_files %}
-## Current files (skeleton in src/ — keep the structure, fill every stub)
+## Current files (the skeleton in src/: keep the link and joint names and robot.urdf's frames; replace every placeholder box with the real link)
{% for path, body in skeleton_files.items() %}
--- {{ path }} ---
```
diff --git a/harness/codeverse3d/prompts/tracks/generate_graphics.j2 b/harness/codeverse3d/prompts/tracks/generate_graphics.j2
index 1f1d4d3e..bbcba74d 100644
--- a/harness/codeverse3d/prompts/tracks/generate_graphics.j2
+++ b/harness/codeverse3d/prompts/tracks/generate_graphics.j2
@@ -17,22 +17,6 @@ Constraints:
{{ contract }}
Files you must produce: {% for f in expected_files %}`{{ f }}`{% if not loop.last %}, {% endif %}{% endfor %}.
-Copyable snippets live in `.3dcode/cookbook.md` (read it before writing if you can).{% if cookbook_excerpt %}
-Cookbook excerpt:
-{{ cookbook_excerpt }}
-{% endif %}
-{% if seeded_recipes %}
-
-## Verified helpers in the harness-owned, read-only `src/recipes.glsl` — call them, do not redefine them
-`src/recipes.glsl` is harness-owned and READ-ONLY (a session that writes it is failed and the file restored); the harness pastes it above
-`src/common.glsl` and `src/shader.frag` at build time, so these VERIFIED helpers are in scope everywhere with
-no include. Call them and build on them: do not rewrite an aurora curtain / star field / bokeh / rain layer
-from scratch (the from-scratch versions are the comb of bars, the twenty sparkles and the opaque discs the
-judge caps), do not define a function with one of these names yourself (the lint rejects the redefinition),
-and do not copy them into `src/common.glsl` — `common.glsl` is yours for helpers that are NOT in this list.
-{% for r in seeded_recipes %}- `{{ r.signature }}` — {{ r.purpose }}
-{% endfor %}
-{% endif %}
## Plan
{{ plan_summary }}
@@ -50,17 +34,17 @@ Motion: {{ motion }}
## Acceptance checklist (the judge verifies each item; build so every item is visibly true)
{{ acceptance }}
-## DO
-- Animate with time: every sampled frame (t = {{ judge_times }}) must differ visibly; continuous motion,
+## What is measured
+- Motion: the largest mean |Δ| between consecutive sampled frames (t = {{ judge_times }}) must reach 0.002
+ (else `static`, cap 0.5) and no consecutive pair may exceed 0.35 (`flicker`, cap 0.7): continuous motion,
no hard cuts, no per-frame random seeds.
-- Aspect-correct coordinates: `p = (fragCoord - 0.5*u_resolution) / u_resolution.y` (circles stay round).
-- Layer the passes from the table: background → midground → foreground → grade (vignette, tonemap, gamma).
-- Use the style's palette literally (write the colour constants at the top); keep mean brightness in a
- readable range (neither near-black nor blown-out); tonemap `c/(1+c)` then gamma.
-- Detail at several scales (fbm octaves, hash-placed elements, highlights) — the judge scores richness.
-- Guard the maths: `x / max(d, 1e-4)`, `sqrt(max(x, 0.0))`, `normalize` only non-zero vectors,
- `clamp` acos/asin inputs — one NaN pixel caps the score at 0.
-- Constant loop bounds; keep per-pixel cost sane.
+- Circles must stay round at {{ resolution }} (judge defect `stretched_aspect`, −0.06).
+- The style's palette is what the judge's light_and_tone criterion grades against; no sampled frame may be
+ essentially black or blown out (cap 0.5).
+- Structure at the scales the subject has: one field filling the frame is the `flat_fill` defect (−0.08)
+ and the 0.1 anchor of depth_and_detail (0.16).
+- One NaN / Inf pixel caps the score at 0 (the NaN sources are listed in the contract).
+- Loop bounds are compile-time constants; a frame that does not finish inside the render timeout fails the build.
## DON'T
- No `#version` line, no `uniform`/`out` declarations of the harness names (shader); no window,
@@ -69,7 +53,7 @@ Motion: {{ motion }}
- No textures other than the harness ones; no network; no imports outside the contract's allow-list.
{% if skeleton_files %}
-## Current files (skeleton already in src/ — keep the structure, replace the placeholder look)
+## Current files (the harness skeleton: the file names and the entry point are the interface; everything inside is yours to replace)
{% for path, body in skeleton_files.items() %}
--- {{ path }} ---
```
diff --git a/harness/codeverse3d/prompts/tracks/generate_static.j2 b/harness/codeverse3d/prompts/tracks/generate_static.j2
index f06d9636..d6e24fe6 100644
--- a/harness/codeverse3d/prompts/tracks/generate_static.j2
+++ b/harness/codeverse3d/prompts/tracks/generate_static.j2
@@ -17,10 +17,6 @@ Constraints:
{{ contract }}
Files you must produce: {% for f in expected_files %}`{{ f }}`{% if not loop.last %}, {% endif %}{% endfor %}.
-Copyable snippets live in `.3dcode/cookbook.md` (read it before writing if you can).{% if cookbook_excerpt %}
-Cookbook excerpt:
-{{ cookbook_excerpt }}
-{% endif %}
## Plan
{{ plan_summary }}
@@ -39,13 +35,13 @@ Construction notes per part:
## DO
- Place each part so its bounding box CENTRE and EXTENTS equal the plan row. Compute
positions from the numbers in the table; do not re-invent the layout.
-- Weld touching parts: overlap neighbours by ≥ 0.002 m (push a leg 2-5 mm into the seat). Never
- bridge gaps with thin rods; no part may float.
+- Touching parts: surface gap ≤ 0.002 m (flush counts), overlap ≤ 0.002 m (`check_connectivity`
+ reports deeper overlap as interpenetration). Every part must be in the ground-touching component
+ (a floating part is an ERROR). Add no connector geometry the plan does not list.
- Use `instances` + `symmetry` from the table: mirror pairs at ±x, radial sets around the up axis.
-- Put real detail where the plan says: chamfers/bevels 2-6 mm, tapers, grooves, slats, bolts —
- with the stated radii and counts. Primitives alone are not enough; combine and shape them.
-- Materials per part with the stated colour (sRGB hex or 0-1 floats); roughness/metalness sensible.
-- Segments 24-48 for round things.
+- Build the features each plan description names, at its numbers and counts (the judge's
+ checklist verifies them).
+- A material per part with the plan's colour.
- Name parts EXACTLY as in the table (PascalCase). One named node/object per part; the
instances of a part are top-level nodes `Name_0`, `Name_1`, ….
@@ -56,12 +52,13 @@ Construction notes per part:
- No environment sniffing, no `typeof window`, no headless branches — one code path.
- No DOM, canvas textures, image/texture loading, network, file IO, camera/light/render/export calls.
- No helper SDKs or imports beyond the contract's allow-list.
-- No placeholders ("TODO", "simplified"); no part smaller than 50% of its planned extents; no
- unit-cube stand-ins; no parts outside the overall bbox.
+- No placeholders ("TODO", "simplified"); no part off its planned extents by more than the
+ contract tolerance (max(1 cm, 10 %) per axis; 3 × that is an ERROR); no unit-cube stand-ins; no
+ parts outside the overall bbox.
- Do not change part names, counts or the overall size to "simplify".
{% if skeleton_files %}
-## Current files (skeleton already in src/ — keep its structure, fill in every stub)
+## Current files (skeleton in src/: keep the file names and entry names your contract states; replace the placeholder geometry and helpers freely)
{% for path, body in skeleton_files.items() %}
--- {{ path }} ---
```
diff --git a/harness/codeverse3d/prompts/tracks/generate_static_part.j2 b/harness/codeverse3d/prompts/tracks/generate_static_part.j2
index 624ee16a..cd5dc6f3 100644
--- a/harness/codeverse3d/prompts/tracks/generate_static_part.j2
+++ b/harness/codeverse3d/prompts/tracks/generate_static_part.j2
@@ -19,7 +19,6 @@ Style: {{ style_notes }}
{% for f in files %}- `{{ f }}`
{% endfor %}
The entry file and every other part file belong to other sessions. Touching them loses their work.
-Copyable snippets live in `.3dcode/cookbook.md` — read the density chapter before you write.
## YOUR parts (build every row; object names must match EXACTLY — they become GLB node names)
{{ parts_table }}
@@ -30,27 +29,26 @@ Construction notes:
{{ interfaces }}
Those neighbour boxes are the truth another session is building to. Where your part attaches to
-one, overlap it by 2–5 mm (never leave a gap, never float); where a neighbour attaches to yours,
-leave a real surface for it at the stated box — no recess it cannot reach, no shape that would
-make it interpenetrate.
+one, overlap it by at most 2 mm and leave no gap over 2 mm (flush counts) — the connectivity gate's
+contact band; where a neighbour attaches to yours, leave a real surface for it at the stated box —
+no recess it cannot reach, no shape that would make it interpenetrate.
## Detail
{{ detail_advice }}
## DO
- Place each part so its bounding box CENTRE and EXTENTS equal the plan row.
-- Build the described geometry, not a box with the right size: profiles, tapers, chamfers 2–6 mm,
- grooves, fasteners, seams, the counted features the description names (spokes, slats, dentils…).
- A part that is a scaled cube where the plan says "fluted cylindrical body with 6 flutes" fails.
-- Use loops/arrays for repeated features rather than hand-placing them; parameterise from the
- constants at the top of your file so the numbers stay honest.
+- Build what the description says at its numbers and counts: the judge's checklist marks a
+ named feature that is not there (a scaled cube where the plan says "fluted cylindrical body with
+ 6 flutes").
- Material per part with the stated colour, roughness and metalness.
-- Instances (`{{ '{' }}Name{{ '}' }}_0 … _N-1`) are looped inside YOUR file, each TOP-LEVEL.
+- Instances (`{{ '{' }}Name{{ '}' }}_0 … _N-1`) are built inside YOUR file, each TOP-LEVEL.
## DON'T
- Do not build, rename, move or "fix" a part that is not in your table — even if it looks wrong.
- Do not write the entry file, a README, notes or tests.
-- No placeholders ("TODO", "simplified"), no unit-cube stand-ins, no part outside its plan bbox.
+- No placeholders ("TODO", "simplified"), no unit-cube stand-ins, no part off its plan bbox by more
+ than the contract tolerance (max(1 cm, 10 %) per axis).
- No environment sniffing, no DOM/texture loading/network/file IO, no camera/light/render/export.
{% if tool_cards and not single_shot %}
diff --git a/harness/codeverse3d/prompts/tracks/plan_articulated.j2 b/harness/codeverse3d/prompts/tracks/plan_articulated.j2
index fa53db05..3ce9877b 100644
--- a/harness/codeverse3d/prompts/tracks/plan_articulated.j2
+++ b/harness/codeverse3d/prompts/tracks/plan_articulated.j2
@@ -8,35 +8,38 @@ LANGUAGE CONTRACT THE BUILDER WILL FOLLOW:
{{ contract }}
WHAT TO PRODUCE (JSON, fields: {{ schema_fields }}):
-1. `object_name` PascalCase; `summary` two sentences incl. overall size in meters and what moves.
+1. `object_name` PascalCase; `summary`: overall size in metres and what moves.
2. `overall_bbox` — real-world dimensions in meters, authored at the REST pose; bottom at up=0.
-3. `parts` = LINKS, about {{ target_parts }} (floor {{ min_parts }}, ceiling {{ cap_parts }}; the PLAN BUDGET block in the
- request says where that number came from). One part per rigid body that MOVES AS A UNIT — a
+3. `parts` = LINKS, within the PLAN BUDGET block in the request (it states the ceiling, and a floor
+ only when the request is evidence of one). One part per rigid body that MOVES AS A UNIT — a
drawer is ONE link even though it has a front, a box, runners and a handle. Each part:
PascalCase `name`, `role`, `description` with construction numbers, `bbox` (centre + extents, meters,
rest pose, WORLD coordinates), `attach_to` = the parent link, `material` with colour.
- Moving links must NOT penetrate their neighbours at rest: leave ≥ 0.003 m clearance in the motion
- direction (drawer vs cabinet opening, door vs frame); fixed neighbours overlap ≥ 0.002 m.
- * `children` — 3 to 6 SUB-PARTS: this is where an articulated plan gets its detail. A link is
- rarely one box. The drawer's `children` are DrawerFront (18 mm, rebated, with a 6 mm shadow
- gap), DrawerBox (12 mm sides, 8 mm base, rebated corners), Handle (turned knob, 32 mm dia) and
- Runners (2 × 10 × 10 mm strips). Each child needs `name`, `description` in numbers, a `bbox`
- INSIDE the link's bbox (same frame, rest pose) and `material` when it differs.
+ At rest no two links overlap by more than 2 mm (the build fails above 5 mm); a fixed child touches
+ its parent or sinks at most 2 mm into it; a hinged or sliding child's mesh is within 10 mm of its
+ parent's. Over each joint's range the moving link must clear every other link by more than 2 mm in
+ every pose (the sweep samples lower/mid/upper and random combinations).
+ * `children` — the sub-parts of a link, each with its own bbox inside the link's (up to 8): this is
+ where an articulated plan carries the brief's detail. Each child needs `name`, `description` in
+ numbers, a `bbox` INSIDE the link's bbox (same frame, rest pose) and `material` when it differs.
Sub-parts are NOT extra links: they carry no joint, they add no collision pair, and the builder
exports the whole link as ONE object named after the LINK. Add depth here, not by splitting a
rigid body into more links — every extra link costs a joint and a collision-sweep pair.
Leave `children` empty for a link that really is one shape (a rod, a plate, a wheel).
- * `detail_hint` — one line on the 3-4 links that carry the object's identity: what makes THAT
- link read as real.
+ * `detail_hint` — one line, on the links that carry the object's identity: what makes THAT link
+ read as real.
4. `root_link` — the grounded/base link (cabinet, base, chassis).
5. `joints` — one per moving link, forming a single tree from `root_link`:
* `type` revolute (hinges, lids, doors; radians) · prismatic (drawers, slides; meters) ·
continuous (wheels, fans) · fixed (rigid attachments you still want as separate links).
* `axis` unit vector in the frame above; `pivot` a WORLD point on the axis at rest (the hinge line,
the slide direction through the drawer centre).
- * `lower`/`upper` realistic limits (door 0..1.57 rad, lid 0..1.9 rad, drawer 0..0.8 × depth m);
- `rest` within the limits (usually 0 = closed).
- * `motion` one line: "lid opens upward about its back edge".
+ * `lower`/`upper` — the real travel of the mechanism (a revolute range stays within 2π; the sweep
+ tests both ends); `rest` within the limits (0 when the authored pose is the closed/home state).
+ * `motion` one line naming the direction positive travel moves the link — front/back/up/down/left/
+ right or an explicit ±x/±y/±z (Z up, −Y front): the harness measures the link's centroid
+ displacement against that word (60° cone). The first direction word wins, so put it first; a
+ sentence that names two axes, a negation, or only a rotation ("spins around") is not checked.
* Count the moving parts the brief names (doors, drawers, lids, arms, wheels): that is the number of
non-fixed joints, give or take one. Do not add joints to reach a part count — a rigid feature is a
sub-part, not a link.
@@ -48,22 +51,24 @@ WHAT TO PRODUCE (JSON, fields: {{ schema_fields }}):
* `parent` / `child` name top-level `parts` (links) — NEVER a sub-part: anything a joint moves must be
its own link (the harness promotes a referenced sub-part to a link, but plan it as a link yourself).
A `revolute` range stays within 2π; a part that turns freely (swivel, wheel) is `continuous`.
-6. `acceptance` — 6 to 12 items: dimensions (`measure`), ground contact, each key feature
- (`visual`), and ONE `articulation` item per joint ("drawer slides out 0.35 m without touching the
- cabinet", "door swings 90° about the left edge, no penetration through the range").
+6. `acceptance` — the brief's own checks: its dimensions (`measure`), ground contact, each named
+ feature (`visual`), and ONE `articulation` item per joint stating the travel and that nothing is
+ penetrated through it ("drawer slides out 0.35 m without touching the cabinet").
RULES
- When the request carries an ENGINEERING BRIEF, its dimensions, sub-assemblies and signature
features are ground truth: every signature feature must be findable as a link, a sub-part or a
named detail in some `description`. Sub-assemblies that do not move become `children`, not links.
-- A plan of boxes at different sizes is a FAILED plan and will be sent back. Every link's
- `description` (or its `children`) must say something a plain primitive cannot: a profile, a
- counted repeat, an edge treatment, a rebate, a fillet radius.
-- Sweep-safe design: imagine each joint at lower, mid and upper — no link passes through another.
- Hinged lids pivot at their back edge, NOT their centre; drawers slide along the cabinet depth.
+- A link's `description` (or its `children`) says what the real link has that a plain primitive
+ does not — its profile, counted repeats, how its edges and joins are made. When the PLAN BUDGET
+ block states a detail minimum, the quality gate re-asks a plan below it.
+- Sweep-safe: the harness poses each joint at lower, mid and upper and 8 random combinations; no link
+ may pass through another in any of them. Every pivot is a point ON the physical hinge line or slide
+ axis — a pivot at a part's centre makes it sweep through its neighbour and the motion check cannot
+ measure it.
- Pivot and axis are the contract the URDF will be checked against; choose them to 3 decimals.
- Every link except `root_link` is the child of exactly one joint; parent/child names are part names.
- No prose outside the JSON.
-WORKED EXAMPLE (shape only — do not copy its values):
+SCHEMA EXAMPLE (the fields and their types; its object, numbers and sub-parts are not yours):
{{ example_json }}
diff --git a/harness/codeverse3d/prompts/tracks/plan_graphics.j2 b/harness/codeverse3d/prompts/tracks/plan_graphics.j2
index 989299b9..f0bf73b5 100644
--- a/harness/codeverse3d/prompts/tracks/plan_graphics.j2
+++ b/harness/codeverse3d/prompts/tracks/plan_graphics.j2
@@ -8,46 +8,45 @@ geometry; an OpenGL program may draw meshes, instances, multiple passes):
{{ contract }}
WHAT TO PRODUCE (JSON, fields: {{ schema_fields }}):
-1. `title` — short name (`NeonRainWindow`).
+1. `title` — short name (`TidePoolRipples`).
2. `summary` — two sentences: what the viewer sees, and what moves.
-3. `style` — palette in words (3-5 named colours with roles: base / accent / highlight), mood,
- references ("cyberpunk poster", "Studio Ghibli sky"), rendering character (soft/filmic, crisp/flat, glow).
+3. `style` — the palette in words with each colour's role, the mood, references ("cyberpunk poster",
+ "Studio Ghibli sky"), rendering character (soft/filmic, crisp/flat, glow). The judge's
+ light_and_tone criterion grades the frames against this description.
4. `resolution` — [width, height]; default [1280, 720]; use [720, 1280] only for explicitly vertical requests.
-5. `duration_s` — loop length in seconds (6-12 s; the judge samples up to 6 s).
-6. `passes` — about {{ target_parts }} passes in draw order (floor {{ min_parts }}, ceiling {{ cap_parts }}; the PLAN BUDGET
- block in the request says where that number came from). For a fragment shader these are LAYERS
- inside one shader (background → midground → foreground → grade); for an OpenGL program they may
- be real passes (geometry, FBO post-process). For EACH pass: `name` PascalCase, `kind`
- (fullscreen | geometry | postprocess | feedback), `description` = the RECIPE in numbers:
- technique (fbm octaves, sdf shapes, raymarch steps, particle counts, grid cells), sizes in
- screen fractions, counts, speeds, colours from the style. Concrete beats adjectives.
- * `elements` — 3 to 6 NAMED things this pass draws, each with its own numbers ("7 gear wheels,
- 12-24 teeth, radii 0.06-0.22 of screen height, involute tooth profile", "3 dust layers at
- 0.02/0.05/0.11 screen-widths per second"). A pass with one element is a flat pass; the judge's
- `visual_richness` criterion is measuring exactly this.
- * `detail_hint` — one line: what makes THIS pass read as real rather than as a demo
- ("the gears must mesh: adjacent radii in integer tooth ratios, contra-rotating").
- A thin plan is the single biggest scored weakness of this track: depth in the LAYERS
- (foreground occluders, mid detail, grade, vignette, grain) is what separates 0.5 from 0.8.
+5. `duration_s` — the preview GIF's loop length in seconds. The judged frames stop at 6 s, so it must be
+ at least 6 or some judged times are dropped.
+6. `passes` — in draw order, as many as the effect has (the PLAN BUDGET block in the request states
+ the ceiling, and a floor only when the request's checklist is long enough to set one). For a
+ fragment shader a pass is a layer composited inside the one shader; for an OpenGL program it may
+ be a real pass (geometry, FBO post-process). For EACH pass: `name` PascalCase, `kind` (fullscreen |
+ geometry | postprocess | feedback), `description` — concrete: what it draws, the technique by
+ name, and the quantities the builder needs (counts, sizes in screen fractions, speeds, the
+ style's colours). Concrete beats adjectives.
+ * `elements` — optional: the named things this pass draws, each with its own quantities.
+ * `detail_hint` — optional, one line: what makes THIS pass read as the subject rather than as a demo.
+ The judge's depth_and_detail criterion (0.16) and its `flat_fill` defect (−0.08) grade structure
+ at the scales the subject has; a single field filling the frame is that criterion's 0.1 anchor.
7. `uniforms` — which harness uniforms the effect needs (`u_time`, `u_resolution`, `u_prev` for
feedback trails, `u_noise` for a noise texture).
8. `motion` — ONE paragraph: exactly what animates and how (direction, speed in screen-fractions
per second or Hz, easing), and what must stay still. Every request is animated unless it says
- "static image": something must visibly differ between t=0 and t=1.
-9. `key_visuals` — 3 to 8 things a viewer MUST recognise (nouns: "rain drops with trails",
- "blurred neon bokeh", "sun disc", "rolling fbm clouds").
-10. `acceptance` — 4 to 8 checklist items verifiable from the frames: one per user must-have,
- one per key visual (`how: visual`), one for motion (`how: probe`, "frames change over time"),
- one for palette/mood. Ids `a1`, `a2`, …; `priority: must` for things whose absence makes it the
- wrong effect, `should` for polish.
+ "static image": the largest difference between consecutive sampled frames must exceed the static
+ threshold (0.002 mean |Δ|), else the score caps at 0.5.
+9. `key_visuals` — the things a viewer MUST recognise, as nouns.
+10. `acceptance` — checklist items verifiable from the frames: one per user must-have and one per
+ key visual (`how: visual`); the harness adds a motion probe when the plan animates. Ids `a1`,
+ `a2`, …; `priority: must` for things whose absence makes it the wrong effect, `should` for
+ polish — an unverified `must` caps the score at 0.7.
RULES
-- Plan for the language's strengths: shaders → procedural patterns (hash/noise/fbm/sdf/raymarch/
- domain warp/palette), OpenGL programs → geometry, instancing, depth, multi-pass blur/bloom.
-- Numbers everywhere: counts, octaves, speeds, screen fractions, hex-ish colours (0.9, 0.2, 0.6).
+- Plan inside the language: a fragment shader has no geometry — everything is a function of the
+ pixel, time and the two samplers; an OpenGL program may draw meshes, instances and real passes.
+- Numbers where the builder needs them: counts, speeds, screen fractions, colours as triples
+ (0.9, 0.2, 0.6).
- Avoid textbook demos (plain plasma, rainbow spiral) unless asked; give the effect one idea that
makes it specific to the request.
- No prose outside the JSON.
-WORKED EXAMPLE (shape only — do not copy its values):
+SCHEMA EXAMPLE (the fields on an effect nobody asked for; never a pass list, a layering or values to copy):
{{ example_json }}
diff --git a/harness/codeverse3d/prompts/tracks/plan_static.j2 b/harness/codeverse3d/prompts/tracks/plan_static.j2
index a85634e8..2a753377 100644
--- a/harness/codeverse3d/prompts/tracks/plan_static.j2
+++ b/harness/codeverse3d/prompts/tracks/plan_static.j2
@@ -8,14 +8,13 @@ LANGUAGE CONTRACT THE BUILDER WILL FOLLOW (so your plan must fit it):
{{ contract }}
WHAT TO PRODUCE (JSON, fields: {{ schema_fields }}):
-1. `object_name` — PascalCase (e.g. `DiningChair`).
-2. `summary` — two sentences: what it is, overall size in meters, the 3-5 most recognisable features.
-3. `overall_bbox` — REAL-WORLD dimensions in meters (a dining chair is ~0.45 × 0.50 × 0.85 m, a
- car ~4.5 × 1.8 × 1.45 m, a coffee mug ~0.09 × 0.09 × 0.10 m). Never unit cubes. Centre the
- footprint on the up axis; the bottom sits at up=0, so the bbox centre's up-coordinate equals half
- the height.
-4. `parts` — **about {{ target_parts }} parts** (floor {{ min_parts }}, ceiling {{ cap_parts }}; the PLAN BUDGET block in the
- request states where that number came from). Every nameable feature in the request and in the
+1. `object_name` — PascalCase (e.g. `HerbDryingRack`).
+2. `summary` — two sentences: what it is, overall size in meters, the most recognisable features.
+3. `overall_bbox` — REAL-WORLD dimensions in meters, from the reference instance (never unit
+ cubes). Centre the footprint on the up axis; the bottom sits at up=0, so the bbox centre's
+ up-coordinate equals half the height.
+4. `parts` — as many as the object really has, within the PLAN BUDGET block in the request (it
+ states the ceiling, and a floor only when the request is evidence of one). Every nameable feature in the request and in the
constraints must be either its own part or explicitly named in another part's `description` as
geometry that part carries — a feature named nowhere will not be built, and the judge's
checklist will mark it missing. The same holds for the CATEGORY's defining features even
@@ -25,32 +24,32 @@ WHAT TO PRODUCE (JSON, fields: {{ schema_fields }}):
(Use `instances` for identical copies: 4 legs = ONE part, instances=4,
bbox of ONE copy; `symmetry` says how copies are laid out.) For EACH part:
* `name` PascalCase, unique, descriptive (`SeatCushion`, `FrontLeg`, `Backrest`).
- * `role` one line; `description` the construction recipe in numbers: primitive(s), thickness,
- radii, taper, angles, edge treatment, visible detail (slats, grooves, bolts …).
- * `bbox` centre + full extents in meters IN THE FRAME ABOVE; parts that touch must OVERLAP by at
- least 0.002 m (2 mm) — never leave a gap between a leg and the seat.
+ * `role` one line; `description` what the part IS, with its numbers: where the real part has a
+ profile, an edge treatment or a counted repeat, say so with the number — a plain primitive's
+ description reads as a plain primitive to the builder.
+ * `bbox` centre + full extents in meters IN THE FRAME ABOVE; the bboxes of parts that touch share
+ a face or overlap by at most 0.002 m (the connectivity gate reports deeper overlap as
+ interpenetration and a gap over 0.002 m as no contact).
* `attach_to` the part it is physically joined to (one parent; the main body has none).
* `material` plain words incl. colour (`oiled oak, warm brown`, `brushed steel`, `matte black plastic`).
- * `children` — 3 to 6 SUB-PARTS, but only for a part that is really an ASSEMBLY (rule 5).
- * `detail_hint` — one line, on the 3-5 parts that carry the object's identity, saying what makes
+ * `children` — the sub-parts a parts diagram would list, only for a part that is really an
+ ASSEMBLY (rule 5).
+ * `detail_hint` — one line, on the parts that carry the object's identity, saying what makes
THAT part read as real ("carries the visible mechanism — model the burr cone's flutes, the
square shaft and the retaining nut"; "the eye follows this edge: keep the 6 mm bullnose").
-5. `children` — WHEN TO NEST AND WHEN NOT TO.
- Nest a part when a parts diagram would give it its own exploded view: a burr mechanism, a pegbox,
- a quill-and-chuck head, a belt housing, a sash in its frame, a lamp head, a swivel base. Give it
- 3-6 `children`, each with `name`, `description` in numbers, a `bbox` INSIDE the parent's bbox
- (same frame) and `material` where it differs from the parent's.
- Do NOT nest a leg, a stretcher, a panel, a bolt, a plain slab — those are shapes, not assemblies:
- describe them in `description` and leave `children` empty.
+5. `children` — what nesting means. A part with `children` is one a parts diagram would give its
+ own exploded view; each child has `name`, `description` in numbers, a `bbox` INSIDE the parent's
+ bbox (same frame; the schema rejects one that sticks out) and `material` where it differs from
+ the parent's. A part that is one shape has none.
A sub-part is a PLANNING unit, not an export unit: the builder builds all of a part's sub-parts
- and exports the result as ONE object named after the PARENT. So nesting buys detail without
- adding a part that can float, interpenetrate or go missing — nest wherever the object earns it,
- and prefer nesting over inventing an extra top-level part.
+ and exports the result as ONE object named after the PARENT, so a sub-part is never measured as
+ a part of its own — it cannot float, interpenetrate or go missing by itself.
6. `style_notes` — era/style cues and the exact proportions that make it read as THAT object.
-7. `acceptance` — 6 to 12 checklist items, each verifiable from renders or measurements:
- one per user constraint and must-have, one for overall dimensions (`how: measure`), one for
- ground contact, one per key visible feature (`how: visual`). Ids `a1`, `a2`, …; `priority: must`
- for things whose absence makes it the wrong object, `should` for polish.
+7. `acceptance` — the checklist items the judge verifies, each checkable from renders or
+ measurements: one per user constraint and must-have and one per key visible feature
+ (`how: visual`), plus any measurement you want held (`how: measure`). The harness adds items for
+ the request's dimensions and, when no item is measured, ground contact. Ids `a1`, `a2`, …;
+ `priority: must` for things whose absence makes it the wrong object, `should` for polish.
RULES
- Count before you write: list the nameable features the request names, then make sure each one is
@@ -60,14 +59,15 @@ RULES
When the request carries an ENGINEERING BRIEF, its dimensions, sub-assemblies and signature features
are ground truth: every signature feature must be findable in your plan as a part, a sub-part, or a
named detail inside some `description`.
-- A plan of boxes at different sizes is a FAILED plan and will be sent back. Every part's
- `description` must say something a plain primitive cannot: a profile (tapered 35→25 mm, fluted,
- bullnosed r=6 mm), a counted repeat ("7 slats at 42 mm pitch", "24 spokes"), an edge treatment,
- or the sub-shapes it is built from.
-- Parts must tile the object: the union of part bboxes ≈ the overall bbox; no part larger than the object.
+- When the PLAN BUDGET block states a detail minimum (the request is evidence of it), the plan gate
+ counts the parts whose `description` says something a plain primitive cannot — a profile, a
+ stated radius, an edge treatment, a counted repeat, or the sub-shapes it is built from — and
+ re-asks a plan below it.
+- No part bbox extends past the overall bbox (`check_contract` measures the overall bbox against the plan).
- Mirror pairs share one part with `symmetry: mirror_x` (or `mirror_y`) and `instances: 2`.
- Every part name appears once; every `attach_to` names an existing part.
- Numbers with 3 decimals (meters). No prose outside the JSON.
-WORKED EXAMPLE (shape only — do not copy its values):
+WORKED EXAMPLE — the SCHEMA on an object nobody asked for (a profile, a counted repeat, a nested
+assembly, an instanced row); never a layout, a part list or numbers to copy:
{{ example_json }}
diff --git a/harness/codeverse3d/prompts/tracks/refine_graphics.j2 b/harness/codeverse3d/prompts/tracks/refine_graphics.j2
index d272d261..95a5b8ec 100644
--- a/harness/codeverse3d/prompts/tracks/refine_graphics.j2
+++ b/harness/codeverse3d/prompts/tracks/refine_graphics.j2
@@ -35,15 +35,11 @@ Key visuals:
## Contract reminders
- Harness uniforms only ({{ uniforms }}); no #version / uniform / out redeclarations in a shader; no window,
context or clock in a program.
-- Motion is judged by comparing frames at t = {{ judge_times }}: a "static" gate warning caps the score at 0.5.
+- Motion is measured on the frames at t = {{ judge_times }}: `static` caps the score at 0.5, `flicker` at 0.7.
- NaN/Inf pixels cap the score at 0: guard divisions, sqrt/pow/log, normalize, acos/asin.
-- Keep brightness readable (neither near-black nor blown out), aspect-correct coordinates, tonemap + gamma last.
-- A "colour/light" change = palette constants / exposure / grade only; a "motion" change = the time terms only;
+- No black / blown frame (cap 0.5); circles round (judge defect `stretched_aspect`).
+- A "colour/light" change = palette / exposure / grade only; a "motion" change = the time terms only;
do not rewrite unrelated layers.
-{% if seeded_recipes %}- The harness-owned, read-only `src/recipes.glsl` (pasted above your code at build time) carries VERIFIED
- helpers ({% for r in seeded_recipes %}`{{ r.name }}`{% if not loop.last %}, {% endif %}{% endfor %}): call these for the light / sky / rain / bokeh layers
- instead of re-deriving them; do not redefine them, do not copy them into common.glsl.
-{% endif %}
{% if current_files %}
## Current file contents (edit these; return each edited file COMPLETE)
diff --git a/harness/codeverse3d/prompts/tracks/refine_object.j2 b/harness/codeverse3d/prompts/tracks/refine_object.j2
index dbdf36b6..fa9d55a1 100644
--- a/harness/codeverse3d/prompts/tracks/refine_object.j2
+++ b/harness/codeverse3d/prompts/tracks/refine_object.j2
@@ -42,7 +42,8 @@ Files in scope: {% for f in files %}`{{ f }}`{% if not loop.last %}, {% endif %}
## Contract reminders
{{ frame_doc }}
- Parts keep their exact names; instances/symmetry as planned.
-- Touching parts overlap ≥ 0.002 m; nothing floats; no connector rods.
+- Touching parts: gap ≤ 0.002 m, overlap ≤ 0.002 m; nothing floats; no connector geometry the plan
+ does not list.
- Move a part by changing its placement numbers to the plan's centre; do not rebuild unrelated parts.
- A "material" change = colour/roughness/metalness of that part only.
- One code path: no environment sniffing, no DOM/texture loading/network.
diff --git a/harness/codeverse3d/prompts/tracks/repair.j2 b/harness/codeverse3d/prompts/tracks/repair.j2
index e151dda2..d9e3fa42 100644
--- a/harness/codeverse3d/prompts/tracks/repair.j2
+++ b/harness/codeverse3d/prompts/tracks/repair.j2
@@ -9,8 +9,8 @@ material exactly as they are. Do not refactor, do not "simplify" the model, do n
THIS IS THE SAME ERROR AS THE PREVIOUS ATTEMPT ({{ repeats }}× repeated). Your last edit did not
touch the cause. Re-read the failing line, check the exact API name/signature against the contract
-and cookbook, and change a DIFFERENT thing this time (e.g. replace the failing call with the
-cookbook's copyable snippet instead of patching arguments).
+(its API facts) and the lint hint, and change a DIFFERENT thing this time (a different call,
+not different arguments).
{% endif %}
## Response rules
diff --git a/harness/codeverse3d/prompts/tracks/scene_asset.j2 b/harness/codeverse3d/prompts/tracks/scene_asset.j2
index 07e5f339..8ce61108 100644
--- a/harness/codeverse3d/prompts/tracks/scene_asset.j2
+++ b/harness/codeverse3d/prompts/tracks/scene_asset.j2
@@ -27,9 +27,12 @@ Scene: {{ spec_prompt }}
{{ detail_advice }}
- No camera/light/render/export calls.
- MOTION (only when the description names a moving part — a swinging lamp, a turning wheel, a lid
- that rocks): keyframe that object's OWN rotation/location over frames 1-48 (24 fps = a 2 s loop,
- ends where it starts; put the object's origin at its pivot; no Empties). The harness exports the
- clip and the scene loops it. Amplitude must read at scene distance (>= 0.15 rad or >= 0.05 m).
+ that rocks): keyframe that object's OWN rotation/location; the harness exports the action as a
+ glTF clip and the scene loops it (a loop that ends where it starts has no seam). A keyed rotation
+ turns about the object's origin, so the origin sits at the pivot; an Empty is not a part (the
+ census counts it as junk). Timing as exported: the factory scene runs at 24 fps and a key on
+ frame f lands at t = f / 24 s in the clip (frame 36 is t = 1.5 s). The scene samples t = 0 and
+ t = 1.5 s: the pose must differ visibly at scene distance (>= 0.15 rad or >= 0.05 m).
{% if asset_files is defined and asset_files|length > 1 %}
- Files you must produce: {% for f in asset_files %}`{{ f }}`{% if not loop.last %}, {% endif %}{% endfor %}
(the skeleton's layout: `src/model.py` is the entry, one part per `src/parts/*.py`).
diff --git a/harness/codeverse3d/prompts/urdf/contract.md b/harness/codeverse3d/prompts/urdf/contract.md
index e8900784..c3fa512c 100644
--- a/harness/codeverse3d/prompts/urdf/contract.md
+++ b/harness/codeverse3d/prompts/urdf/contract.md
@@ -2,92 +2,131 @@
## Files
```
-src/model.py pure bpy (same rules as the blender contract): ONE mesh object per link,
- obj.name == link name, built in WORLD coordinates at the REST pose (= URDF q=0).
+src/model.py pure bpy (the blender contract's sandbox and lint apply): per link, the object named
+ exactly as the link (plus anything parented under it), built in WORLD coordinates
+ at the REST pose (= URDF q=0).
src/robot.urdf hand-written URDF: links + joints; every link has ONE <visual> and ONE identical
<collision>, geometry <mesh filename="meshes/<link>.glb"/>, origin = −(link frame).
```
-The harness runs `model.py` headless, exports `artifacts/meshes/<link>.glb` with the WORLD
-coordinates baked in (nothing is shifted for you), lints the URDF, checks that FK at q=0
-puts every mesh back where you authored it (the build FAILS otherwise and prints the
-corrected `<origin>`), sweeps every joint over its range for collisions, renders q=0 plus
-every joint at its lower/upper limit, and builds `object.glb` with one node per link.
-You never export.
+What the harness does with them: runs `model.py` headless; takes the object named exactly
+`<link>` plus everything parented under it as that link's mesh (the wrapper joins them — you
+need no join of your own; if you do join, set the active object first or the lint WARNs);
+exports `artifacts/meshes/<link>.glb` with the WORLD coordinates baked in (nothing is shifted
+for you); lints the URDF; checks that FK at q=0 puts every mesh back where you authored it
+within 1 mm (otherwise the build FAILS as `FkInconsistent` and prints the corrected `<origin>`);
+fails the build on a rest-pose penetration deeper than 5 mm (`RestPenetration`); sweeps every
+joint over its range (the round's `joint_sweep` gate); renders q=0 plus every joint at its
+lower/upper limit for the judge; builds `object.glb` with one node per link. You never
+export. A link no object matches fails the build (with a did-you-mean hint for a case or
+snake_case mismatch); a visible mesh object no link claims fails it too (parent it under a
+link object or add a `<link>`). `<collision>` missing or different from `<visual>` is a
+lint WARN: the harness collides the VISUAL mesh.
-## Frame rule (the whole trick — follow it literally)
-* Z up, −Y front, +X right, meters, radians. Object on z = 0, centred on Z.
+## Frame rule (measured by the FK check)
+* Z up, −Y front, +X right, meters, radians. Object on z = 0 at q = 0 (`check_contract`
+ compares every link's bbox with the plan's, whose bottom is z = 0; tolerance
+ max(10 mm, 10 % of the planned extent) per axis).
* **q = 0 = what you build = the plan's rest pose**: the plan's bbox centres/extents and
- pivots describe this pose (usually doors closed, drawers in, lids down, arms at home —
- the plan's `rest` is 0 then). The harness does not open anything for the showcase; the
- judge sees q=0 and every joint at both limits.
-* **Every joint `rpy="0 0 0"`.** All link frames stay axis-aligned with the world; a
- link frame differs from the world frame only by a translation to its pivot.
+ pivots describe this pose (doors closed, drawers in, lids down, arms at home, unless the
+ plan's `rest` says otherwise). The judge sees q=0 and every joint at both limits, so the
+ motion is always shown; the geometry itself is the rest pose the plan's bboxes describe.
+* The skeleton writes every joint with `rpy="0 0 0"`, so link frames are world-aligned and
+ the origin arithmetic below is plain subtraction. A rotated joint origin is accepted
+ (lint INFO) but then the visual/collision origin must be the full inverse of the link's FK
+ transform — the FK check tells you the numbers.
* Root link frame = world origin `(0,0,0)`. Every other link frame = its joint's PIVOT: a
world point ON the joint axis (hinge line / slide axis / wheel axle); fixed joints: the
child's attachment point.
-* `<joint><origin xyz>` = `pivot_child − frame_parent` (plain subtraction; for a child of
- the root that is just the pivot; for a handle on a door: `pivot_handle − pivot_door`).
+* `<joint><origin xyz>` = `pivot_child − frame_parent` (for a child of the root that is just
+ the pivot; for a handle on a door: `pivot_handle − pivot_door`).
* `<visual>` AND `<collision>` `<origin xyz>` = `−pivot_link` (root: `0 0 0`), because the
- mesh file holds world coordinates and the link frame sits at the pivot. This is the
- line everyone gets wrong; the harness verifies it numerically and tells you the numbers.
-* `<axis xyz>` is the axis in WORLD coordinates (unit vector). Sign: positive q must move
- the child the way a user expects (door swings OPEN, drawer pulls OUT towards −Y front,
- lid lifts UP). If positive q closes it, negate the axis — never swap lower/upper.
-* Limits: `revolute`/`prismatic` MUST have `<limit lower upper effort velocity/>` with
- `lower ≤ 0 ≤ upper` (q=0 inside the range). From the plan: `lower = plan.lower − rest`,
- `upper = plan.upper − rest` — identical to the plan's numbers when `rest` is 0 (the
- skeleton already wrote them). `continuous`: `<limit effort velocity/>` only; `fixed`: none.
-* Single-root tree: exactly one link that is no joint's child (the base); every other
- link is the child of exactly one joint; no cycles. Moving parts that carry
- hardware (handle on a door, knob on a drawer) attach with a `fixed` joint to the moving
- link, not to the base.
-* Clearance: 1–3 mm between a moving part and its housing over the WHOLE range (drawer vs
- cabinet walls, door vs frame); no penetration at any q in [lower, upper]. Fixed
- children touch their parent (gap ≤ 2 mm) or sink ≤ 2 mm into it.
+ mesh file holds world coordinates and the link frame sits at the pivot. This is the line
+ everyone gets wrong; the build verifies it numerically (FK at q=0 reproduces the authored
+ mesh within 1 mm) and prints the numbers when it does not.
+* `<axis xyz>` is a unit vector in the JOINT frame (the frame the joint's `<origin rpy>` sets
+ up). With every `rpy="0 0 0"`, as the skeleton writes them, that frame is world-aligned and
+ the axis is the world direction of the hinge line or slide (a non-unit axis is normalised
+ with a lint WARN; a missing one defaults to `1 0 0`, WARN). Sign: positive q
+ must move the child the way the plan's `motion` sentence says — the harness
+ (`motion_direction`) moves the joint positively and checks that the child's centroid
+ displacement is within 60° of that word (front/back/up/down/left/right or ±x/±y/±z). If
+ it goes the other way, negate the axis; never swap lower/upper, because q = 0 must stay
+ the authored rest pose.
+* Limits: `revolute`/`prismatic`: `<limit lower upper effort velocity/>` with
+ `lower ≤ 0 ≤ upper` (q=0 inside the range); from the plan: `lower = plan.lower − rest`,
+ `upper = plan.upper − rest` — the plan's own numbers when `rest` is 0 (the skeleton already
+ wrote them, with a comment where they are shifted). `continuous`: `<limit effort velocity/>`
+ only (lower/upper on a continuous joint: lint WARN, ignored). `fixed`: no `<limit>`, no
+ `<axis>`. A revolute/prismatic joint without `<limit>` is a load ERROR; lint WARNs:
+ `lower == upper`, a revolute range > 2π (use `continuous`), a `<limit>` without
+ effort/velocity.
+* Single-root tree: exactly one link that is no joint's child (the base); every other link
+ is the child of exactly one joint (ERROR: a link with two parent joints, a link not
+ connected to the root); no cycles. Anything that rides on a moving link is part of that
+ link's mesh or a fixed child of it; attached to the base it stays behind when the link
+ moves and the sweep reports the overlap.
* Names: link name == Blender object name == `meshes/<link>.glb` stem, case-sensitive,
- identical in both files. Keep the skeleton's names (snake_case of the plan parts:
- `door`, `handle_left`); the plan's PascalCase spelling is accepted too. Never `Door.001`.
- Joint names: the plan's joint names; all unique.
+ identical in both files, a plain identifier (letters/digits/underscore; WARN otherwise —
+ `Door.001` means two objects shared a name); `world` is reserved (ERROR); name the part,
+ not its state (`door`, not `door_open`: WARN). Keep the skeleton's names (snake_case of
+ the plan parts: `door`, `handle_left`); the plan's PascalCase spelling is accepted too.
+ Copies of a plan part are separate links `<part>_1..n` with their own joints
+ `<joint>_1..n` (the skeleton places them in a row along +x as placeholders; put them where
+ they belong). Joint names: the plan's joint names; all unique.
+
+## Clearance and attachment (measured by `joint_sweep`)
+* Pose set: rest; every movable joint alone at lower, mid and upper (the others at 0;
+ `continuous`: 0, ±π/2, π); 8 seeded random full-body combinations when more than one
+ joint moves.
+* In every sampled pose no two links overlap by more than 2 mm. In a moved pose that is an
+ ERROR at any depth.
+ At rest 2–5 mm is a WARN and deeper than 5 mm fails the build (`RestPenetration`).
+ Links joined only by `fixed` joints are one rigid group, judged once with the rest policy.
+ A link that is not watertight only gets an estimated depth (`[approx: non-watertight mesh]`).
+* Attachment at rest: a `fixed` child sits within 2 mm of its parent (touching, or sunk
+ ≤ 2 mm; ERROR beyond). A hinged / sliding child's mesh is within 10 mm of its parent's
+ (WARN beyond, ERROR beyond 30 mm; a prismatic child already inside its parent's bbox is
+ exempt).
+* `check_connectivity` reports a disconnected fragment inside a link smaller than 5 % of the
+ link's largest extent as a stray island; the sweep measures overlap depth exactly only on a
+ watertight link mesh.
## Allowed / forbidden
-Same as the blender contract for `model.py` (bpy, bmesh, mathutils, math, random).
-URDF: no `<gazebo>`, `<transmission>`, `<sensor>`, xacro, `package://`, mesh scale,
-inline primitives. Inertial blocks are optional. `<mimic joint="..." multiplier="..."
-offset="..."/>` IS honoured: the sweep drives the named joint and every follower follows it,
-so a one-input mechanism (umbrella ribs, scissor arms, coupled folding legs) must declare it
-— write one `<mimic>` per follower, naming the joint that drives the mechanism.
+`model.py` is linted by the blender contract's rules (imports, forbidden bpy calls, file IO)
+plus: `exit()` / `quit()` ERROR (exits Blender before the links are exported), `input()` ERROR
+(blocks headless Blender), `time.sleep` and `while True` WARN; every link name must appear as a
+string literal in `model.py` (WARN otherwise — the wrapper looks the object up by that exact
+name).
+URDF: no `<gazebo>`, `<transmission>`, `<sensor>`, xacro, `package://`, mesh scale (WARN:
+model in metres in `model.py`), inline primitives (ERROR: visual geometry must be a `<mesh>`).
+Inertial blocks are optional. `<mimic joint="..." multiplier="..." offset="..."/>` IS
+honoured: the sweep drives the named joint and every follower follows it, so a one-input
+mechanism (umbrella ribs, scissor arms, coupled folding legs) must declare it — one `<mimic>`
+per follower, naming the joint that drives the mechanism (a coupling that names no joint,
+names itself, mimics a fixed joint or closes a loop is a lint ERROR).
+Budgets: the build is killed at `build_timeout_s` (300 s by default); this track has no
+triangle-budget gate.
-## COMPLETE minimal example (verified: harness build + FK check + joint sweep)
-A pedal bin: body + lid hinged at the back edge, knob fixed on the lid. q = 0 = lid closed.
+## The frame arithmetic, end to end
+One hinge, verified by the build + FK check + sweep. It shows the origins and where they come
+from, not how to build anything: a 0.25 m bin body (root, on the ground) and a 10 mm lid
+resting 1 mm above the rim, hinged along its back top edge; q = 0 = lid closed.
`src/model.py`
```python
import bpy, bmesh
from mathutils import Vector
-W, D, H, T = 0.25, 0.25, 0.35, 0.010 # bin outer size, wall/lid thickness (m)
-PIVOT = {"body": Vector((0, 0, 0))} # link frame (world) per link; root = origin
-
-def make_box(name, size, center):
- bm = bmesh.new(); bmesh.ops.create_cube(bm, size=1.0)
- bmesh.ops.scale(bm, vec=size, verts=bm.verts)
+for name, size, centre in (("body", (0.25, 0.25, 0.35), (0, 0, 0.175)), # root link: frame = world origin
+ ("lid", (0.25, 0.25, 0.01), (0, 0, 0.356))): # authored CLOSED (q = 0), 1 mm above the rim
+ bm = bmesh.new(); bmesh.ops.create_cube(bm, size=1.0); bmesh.ops.scale(bm, vec=size, verts=bm.verts)
me = bpy.data.meshes.new(name); bm.to_mesh(me); bm.free()
- o = bpy.data.objects.new(name, me); o.location = center
- bpy.context.scene.collection.objects.link(o)
- return o
-
-body = make_box("body", (W, D, H), (0, 0, H / 2)) # root link, on the ground
-lid = make_box("lid", (W, D, T), (0, 0, H + 0.001 + T / 2)) # 1 mm above the rim, closed
-knob = make_box("knob", (0.03, 0.03, 0.02), (0, -D / 2 + 0.04, H + 0.001 + T + 0.0085)) # 1.5 mm into lid
-PIVOT["lid"] = Vector((0, D / 2, H + 0.001)) # hinge line = back top edge
-PIVOT["knob"] = Vector((0, -D / 2 + 0.04, H + 0.001 + T)) # its attachment point
-
-def xyz(v):
- return f'{v.x:.4f} {v.y:.4f} {v.z:.4f}'
-for child, parent in (("lid", "body"), ("knob", "lid")):
- print(child, "joint origin", xyz(PIVOT[child] - PIVOT[parent]), "| visual+collision origin", xyz(-PIVOT[child]))
+ o = bpy.data.objects.new(name, me); o.location = centre; bpy.context.scene.collection.objects.link(o)
+PIVOT = {"body": Vector((0, 0, 0)), "lid": Vector((0, 0.125, 0.351))} # link frame = a world point on the hinge line
+print("lid: joint origin", tuple(PIVOT["lid"] - PIVOT["body"]), "visual/collision origin", tuple(-PIVOT["lid"]))
```
-`src/robot.urdf` — lid opens UP: +q about +X at the back edge would push the front edge
-DOWN into the body, so the axis is −X (never fix a sign by swapping limits):
+`src/robot.urdf` — the plan's `motion` says the lid opens UP: +q about +X at the back edge
+would push the front edge DOWN into the body, so the axis is −X (a sign is fixed by negating
+the axis, never by swapping the limits):
```xml
<?xml version="1.0"?>
<robot name="pedal_bin">
@@ -99,20 +138,11 @@ DOWN into the body, so the axis is −X (never fix a sign by swapping limits):
<visual><origin xyz="0 -0.125 -0.351" rpy="0 0 0"/><geometry><mesh filename="meshes/lid.glb"/></geometry></visual>
<collision><origin xyz="0 -0.125 -0.351" rpy="0 0 0"/><geometry><mesh filename="meshes/lid.glb"/></geometry></collision>
</link>
- <link name="knob"> <!-- frame at its attachment point (0 -0.085 0.361) -->
- <visual><origin xyz="0 0.085 -0.361" rpy="0 0 0"/><geometry><mesh filename="meshes/knob.glb"/></geometry></visual>
- <collision><origin xyz="0 0.085 -0.361" rpy="0 0 0"/><geometry><mesh filename="meshes/knob.glb"/></geometry></collision>
- </link>
<joint name="body_to_lid" type="revolute">
<parent link="body"/><child link="lid"/>
<origin xyz="0 0.125 0.351" rpy="0 0 0"/> <!-- pivot_lid - frame_body -->
- <axis xyz="-1 0 0"/>
+ <axis xyz="-1 0 0"/> <!-- +q lifts the front edge: the motion word is "up" -->
<limit lower="0" upper="1.5" effort="5" velocity="2"/>
</joint>
- <joint name="lid_to_knob" type="fixed">
- <parent link="lid"/><child link="knob"/>
- <origin xyz="0 -0.21 0.01" rpy="0 0 0"/> <!-- pivot_knob - pivot_lid -->
- </joint>
</robot>
```
-See the cookbook for full cabinet (door + handle + drawer), laptop and cart examples.
diff --git a/harness/codeverse3d/prompts/urdf/cookbook.md b/harness/codeverse3d/prompts/urdf/cookbook.md
deleted file mode 100644
index d7850dc9..00000000
--- a/harness/codeverse3d/prompts/urdf/cookbook.md
+++ /dev/null
@@ -1,434 +0,0 @@
-# URDF + bpy cookbook — articulated objects (`urdf_blender`)
-
-Every `python` snippet runs as-is in `blender -b --factory-startup`; every `xml` snippet is
-valid URDF (the harness test suite checks both). Z-up, −Y front, meters, radians.
-The harness inlines the relevant chapters into your prompts; the full file is at
-`.3dcode/cookbook.md` in your workspace.
-
-## The frame recipe (memorise this, it is the whole trick)
-
-```text
-1. Build every link's mesh in WORLD coordinates at the REST pose (= URDF q = 0: the pose
- the plan's bboxes describe — closed / home unless the plan's `rest` says otherwise).
-2. One Blender object per link, obj.name == link name (the skeleton's snake_case names).
-3. Pick a PIVOT for every non-root link: a point on its joint axis, in world coords
- (hinge line, slide axis, axle; fixed joint: the attachment point). Root pivot = (0, 0, 0).
- The link frame sits AT the pivot, axis-aligned with the world.
-4. URDF: every joint has rpy="0 0 0"; joint origin xyz = pivot_child − pivot_parent;
- axis xyz = the joint axis in WORLD coords.
-5. meshes/<link>.glb hold WORLD coordinates (the harness shifts nothing), so every link's
- <visual> AND <collision> origin xyz = −pivot_link (root: 0 0 0). The build verifies
- this (FK at q=0 must reproduce your geometry within 1 mm) and prints the fix if not.
-```
-
-Pivot arithmetic is plain vector subtraction — do it in Python and print it:
-
-```python
-import bpy, bmesh, math
-from mathutils import Vector
-
-PIVOT = { # world-space pivots (= link frames), filled while building
- "base": Vector((0, 0, 0)),
-}
-def _xyz(v) -> str:
- return f'{v.x:.4f} {v.y:.4f} {v.z:.4f}'
-
-def urdf_origin(child: str, parent: str) -> str:
- """The two <origin> lines a link needs: joint origin and visual/collision origin."""
- return (f'joint <origin xyz="{_xyz(PIVOT[child] - PIVOT[parent])}" rpy="0 0 0"/> '
- f'visual+collision <origin xyz="{_xyz(-PIVOT[child])}" rpy="0 0 0"/>')
-```
-
-## Skeleton (`src/model.py` for articulated objects)
-
-```python
-def link_obj(o):
- bpy.context.scene.collection.objects.link(o); return o
-
-def make_box(name, size, center):
- """Axis-aligned box; size = full extents, centre in world."""
- bm = bmesh.new(); bmesh.ops.create_cube(bm, size=1.0)
- bmesh.ops.scale(bm, vec=size, verts=bm.verts)
- me = bpy.data.meshes.new(name); bm.to_mesh(me); bm.free()
- o = bpy.data.objects.new(name, me); o.location = center
- return link_obj(o)
-
-def make_cyl(name, radius, depth, center, axis='Z', segments=32):
- """Cylinder along `axis` ('X'|'Y'|'Z'), centred at `center` (wheels: axis 'X')."""
- bm = bmesh.new()
- bmesh.ops.create_cone(bm, cap_ends=True, segments=segments, radius1=radius, radius2=radius, depth=depth)
- me = bpy.data.meshes.new(name); bm.to_mesh(me); bm.free()
- o = bpy.data.objects.new(name, me); o.location = center
- if axis == 'X': o.rotation_euler = (0, math.radians(90), 0)
- elif axis == 'Y': o.rotation_euler = (math.radians(90), 0, 0)
- return link_obj(o)
-
-def join_as(name, objs):
- """Several pieces → ONE link object (mesh islands are fine, but weld them ≥ 2 mm)."""
- bpy.ops.object.select_all(action='DESELECT')
- for o in objs: o.select_set(True)
- bpy.context.view_layer.objects.active = objs[0]
- bpy.ops.object.join()
- objs[0].name = name
- return objs[0]
-
-def material(obj, rgb, rough=0.5, metal=0.0):
- m = bpy.data.materials.new(obj.name + "Mat")
- b = m.node_tree.nodes["Principled BSDF"]
- b.inputs["Base Color"].default_value = (*rgb, 1); b.inputs["Roughness"].default_value = rough
- b.inputs["Metallic"].default_value = metal
- obj.data.materials.append(m)
-```
-
-## Worked example 0: cabinet (door revolute + handle fixed + drawer prismatic)
-
-```python
-W, D, H, T = 0.50, 0.40, 0.70, 0.018 # cabinet outer size + panel thickness (m)
-DOOR_T, GAP = 0.018, 0.002 # front panel thickness, clearance
-FRONT_Y = -D / 2 - DOOR_T / 2 - 0.001 # front panels sit 1 mm proud of the carcass
-DRAWER_Z0, DRAWER_Z1 = 0.021, 0.156 # drawer box bottom/top (4 mm under the shelf)
-SHELF_Z0, DOOR_Z0 = 0.160, 0.184 # shelf above the drawer; door bottom edge
-
-# --- carcass (root): 6 panels joined into ONE link object; opening faces -Y (front)
-panels = [
- make_box("carcass", (T, D, H), (-(W / 2 - T / 2), 0, H / 2)), # left side
- make_box("carcass_r", (T, D, H), ((W / 2 - T / 2), 0, H / 2)), # right side
- make_box("carcass_top", (W - 2 * T, D, T), (0, 0, H - T / 2)),
- make_box("carcass_floor", (W - 2 * T, D, T), (0, 0, T / 2)),
- make_box("carcass_shelf", (W - 2 * T, D - T, T), (0, -T / 2, SHELF_Z0 + T / 2)),
- make_box("carcass_back", (W - 2 * T, T, H - 2 * T), (0, D / 2 - T / 2, H / 2)),
-]
-carcass = join_as("carcass", panels); material(carcass, (0.72, 0.68, 0.62))
-PIVOT["carcass"] = Vector((0, 0, 0))
-
-# --- door: hinged on its LEFT edge, closed at q = 0; +q about -Z swings it open (to -Y)
-door_h = H - DOOR_Z0 - GAP
-door = make_box("door", (W - 2 * GAP, DOOR_T, door_h), (0, FRONT_Y, DOOR_Z0 + door_h / 2))
-material(door, (0.55, 0.35, 0.2))
-PIVOT["door"] = Vector((-(W / 2 - GAP), FRONT_Y, 0)) # vertical hinge line (z arbitrary → 0) = (-0.248, -0.21, 0)
-
-# --- door_handle: vertical bar on the door's free side, sunk 1.5 mm into the door (weld)
-handle = make_box("door_handle", (0.012, 0.034, 0.12), (W / 2 - 0.05, FRONT_Y - DOOR_T / 2 - 0.0155, 0.45))
-material(handle, (0.8, 0.78, 0.74), 0.3, 1.0)
-PIVOT["door_handle"] = Vector((W / 2 - 0.05, FRONT_Y - DOOR_T / 2 - 0.0155, 0.45)) # = (0.2, -0.2345, 0.45)
-
-# --- drawer: box + front panel joined; slides out towards -Y (front)
-hb = DRAWER_Z1 - DRAWER_Z0
-drawer = join_as("drawer", [
- make_box("drawer", (W - 2 * T - 2 * GAP, 0.382, hb), (0, -0.011, DRAWER_Z0 + hb / 2)),
- make_box("drawer_front", (W - 2 * GAP, DOOR_T, DOOR_Z0 - 0.005), (0, FRONT_Y, (0.002 + DOOR_Z0 - 0.003) / 2)),
-])
-material(drawer, (0.55, 0.35, 0.2))
-PIVOT["drawer"] = Vector((0, -0.011, DRAWER_Z0 + hb / 2)) # any point on the slide axis
-
-for child, parent in (("door", "carcass"), ("door_handle", "door"), ("drawer", "carcass")):
- print(child, urdf_origin(child, parent))
-```
-
-Every link: visual + collision origin = −pivot (the comment shows the pivot):
-
-```xml
-<?xml version="1.0"?>
-<robot name="cabinet">
- <link name="carcass"> <!-- root: frame = world origin -->
- <visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/carcass.glb"/></geometry></visual>
- <collision><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/carcass.glb"/></geometry></collision>
- </link>
- <link name="door"> <!-- pivot (-0.248 -0.21 0) -->
- <visual><origin xyz="0.248 0.21 0" rpy="0 0 0"/><geometry><mesh filename="meshes/door.glb"/></geometry></visual>
- <collision><origin xyz="0.248 0.21 0" rpy="0 0 0"/><geometry><mesh filename="meshes/door.glb"/></geometry></collision>
- </link>
- <link name="door_handle"> <!-- pivot (0.2 -0.2345 0.45) -->
- <visual><origin xyz="-0.2 0.2345 -0.45" rpy="0 0 0"/><geometry><mesh filename="meshes/door_handle.glb"/></geometry></visual>
- <collision><origin xyz="-0.2 0.2345 -0.45" rpy="0 0 0"/><geometry><mesh filename="meshes/door_handle.glb"/></geometry></collision>
- </link>
- <link name="drawer"> <!-- pivot (0 -0.011 0.0885) -->
- <visual><origin xyz="0 0.011 -0.0885" rpy="0 0 0"/><geometry><mesh filename="meshes/drawer.glb"/></geometry></visual>
- <collision><origin xyz="0 0.011 -0.0885" rpy="0 0 0"/><geometry><mesh filename="meshes/drawer.glb"/></geometry></collision>
- </link>
- <!-- hinge on the left front edge; +q about -Z swings the free edge to -Y (open) -->
- <joint name="carcass_to_door" type="revolute">
- <parent link="carcass"/><child link="door"/>
- <origin xyz="-0.248 -0.21 0" rpy="0 0 0"/> <!-- pivot_door - (0,0,0) -->
- <axis xyz="0 0 -1"/>
- <limit lower="0" upper="1.6" effort="10" velocity="1"/>
- </joint>
- <joint name="door_to_door_handle" type="fixed">
- <parent link="door"/><child link="door_handle"/>
- <origin xyz="0.448 -0.0245 0.45" rpy="0 0 0"/> <!-- pivot_handle - pivot_door -->
- </joint>
- <!-- +q pulls the drawer out towards the front (-Y) -->
- <joint name="carcass_to_drawer" type="prismatic">
- <parent link="carcass"/><child link="drawer"/>
- <origin xyz="0 -0.011 0.0885" rpy="0 0 0"/>
- <axis xyz="0 -1 0"/>
- <limit lower="0" upper="0.30" effort="10" velocity="0.5"/>
- </joint>
-</robot>
-```
-
-`joint_sweep` sanity: at door q = 1.2 the free edge is well in front (y < −0.5); at
-drawer q = 0.3 the drawer front sits 0.3 m out; nothing collides at any sampled q.
-
-## Worked example 1: laptop (base + lid hinge + two-part screen)
-
-```python
-BW, BD, BT = 0.33, 0.23, 0.018 # base footprint + thickness
-LT, GAP = 0.006, 0.002 # lid thickness, hinge clearance
-
-# --- Base link (root) ---------------------------------------------------------
-base = make_box("base", (BW, BD, BT), (0, 0, BT / 2))
-keys = make_box("base_keys", (BW - 0.04, BD * 0.45, 0.002), (0, -0.02, BT + 0.001 - 0.0005)) # 0.5 mm sunk
-pad = make_box("base_pad", (0.10, 0.06, 0.001), (0, -BD / 2 + 0.045, BT + 0.0005 - 0.0003))
-base = join_as("base", [base, keys, pad]); material(base, (0.15, 0.15, 0.17), 0.4, 0.6)
-PIVOT["base"] = Vector((0, 0, 0))
-
-# --- Lid link: hinge axis along X, 8 mm in from the back edge, 6.5 mm above the base top.
-# The hinge barrel belongs to the LID (it turns with it); closed (lying flat) at q = 0.
-hinge_y, hinge_z = BD / 2 - 0.008, BT + 0.0065
-LID_L = BD - 0.008 - GAP # plate runs from the axis to the front
-lid = make_box("lid", (BW, LID_L, LT), (0, hinge_y - LID_L / 2, hinge_z))
-screen = make_box("lid_screen", (BW - 0.02, LID_L - 0.03, 0.0005), (0, hinge_y - LID_L / 2, hinge_z + LT / 2 - 0.0002))
-barrel = make_cyl("lid_hinge", 0.006, BW * 0.9, (0, hinge_y, hinge_z), axis='X', segments=24)
-lid = join_as("lid", [lid, screen, barrel]); material(lid, (0.2, 0.2, 0.22), 0.3, 0.6)
-PIVOT["lid"] = Vector((0, hinge_y, hinge_z)) # = (0, 0.107, 0.0245)
-
-print("base_to_lid", urdf_origin("lid", "base")) # → joint 0 0.107 0.0245 | visual+collision 0 -0.107 -0.0245
-```
-
-Axis sign check: a lid point at (0, −0.1, 0) relative to the hinge rotated by +q about
-+X goes to (0, −0.1 cos q, −0.1 sin q) → z NEGATIVE → that closes INTO the base. So the
-axis is **−X** (`axis xyz="-1 0 0"`), limits 0 … 2.1 rad (120°). The lid plate sits 3.5 mm
-above the base top at q = 0 (keys are 1 mm below it): clearance, not contact.
-
-```xml
-<?xml version="1.0"?>
-<robot name="laptop">
- <link name="base">
- <visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/base.glb"/></geometry></visual>
- <collision><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/base.glb"/></geometry></collision>
- </link>
- <link name="lid"> <!-- pivot (0 0.107 0.0245) -->
- <visual><origin xyz="0 -0.107 -0.0245" rpy="0 0 0"/><geometry><mesh filename="meshes/lid.glb"/></geometry></visual>
- <collision><origin xyz="0 -0.107 -0.0245" rpy="0 0 0"/><geometry><mesh filename="meshes/lid.glb"/></geometry></collision>
- </link>
- <joint name="base_to_lid" type="revolute">
- <parent link="base"/><child link="lid"/>
- <origin xyz="0 0.107 0.0245" rpy="0 0 0"/>
- <axis xyz="-1 0 0"/>
- <limit lower="0" upper="2.1" effort="5" velocity="2"/>
- </joint>
-</robot>
-```
-
-## Worked example 2: hand cart (continuous wheels + prismatic telescopic handle)
-
-```python
-CW, CD, CH = 0.45, 0.35, 0.03 # deck
-WR, WT = 0.10, 0.03 # wheel radius / width
-
-POST_Y, POST_Z0, POST_H, POST_W, WALL = CD / 2 - 0.016, WR + CH, 0.60, 0.032, 0.003
-deck = make_box("deck", (CW, CD, CH), (0, 0, WR + CH / 2)) # deck rides above the axle height
-# the handle post is a HOLLOW square tube (4 walls) so the telescopic grip can slide inside it
-walls = [make_box(f"deck_post_w_{i}", s, c) for i, (s, c) in enumerate([
- ((POST_W, WALL, POST_H), (0, POST_Y - POST_W / 2 + WALL / 2, POST_Z0 + POST_H / 2)),
- ((POST_W, WALL, POST_H), (0, POST_Y + POST_W / 2 - WALL / 2, POST_Z0 + POST_H / 2)),
- ((WALL, POST_W - 2 * WALL, POST_H), (-POST_W / 2 + WALL / 2, POST_Y, POST_Z0 + POST_H / 2)),
- ((WALL, POST_W - 2 * WALL, POST_H), (POST_W / 2 - WALL / 2, POST_Y, POST_Z0 + POST_H / 2))])]
-deck = join_as("deck", [deck, *walls]); material(deck, (0.5, 0.33, 0.18))
-PIVOT["deck"] = Vector((0, 0, 0))
-
-for i, sx in enumerate((-1, 1)):
- name = f"wheel_{i + 1}"
- cx = sx * (CW / 2 + WT / 2 + 0.002) # 2 mm outside the deck side
- w = make_cyl(name, WR, WT, (cx, -CD / 2 + 0.06, WR), axis='X')
- cap = make_cyl(name + "_cap", 0.02, 0.012, (cx + sx * (WT / 2 + 0.003), -CD / 2 + 0.06, WR), axis='X')
- w = join_as(name, [w, cap]); material(w, (0.05, 0.05, 0.05), 0.85) # cap overlaps the wheel 3 mm (same link)
- PIVOT[name] = Vector((cx, -CD / 2 + 0.06, WR)) # on the axle
-
-# axle stubs belong to the Deck; they stop 1 mm short of each wheel's inner face (no penetration, "touching")
-axle = make_cyl("deck_axle", 0.008, CW + 0.002, (0, -CD / 2 + 0.06, WR), axis='X', segments=16)
-deck = join_as("deck", [deck, axle])
-
-# telescopic handle slides UP (+Z) inside the post: q = 0 = fully retracted.
-# grip 24 mm square inside the 26 mm bore (1 mm clearance), bottom 70 mm above the deck, top 20 mm above the post
-grip = make_box("handle", (0.024, 0.024, 0.55), (0, POST_Y, POST_Z0 + 0.07 + 0.275))
-bar = make_box("handle_bar", (0.30, 0.024, 0.024), (0, POST_Y, POST_Z0 + 0.07 + 0.55 + 0.012 - 0.004)) # 4 mm weld
-handle = join_as("handle", [grip, bar]); material(handle, (0.7, 0.7, 0.72), 0.3, 1.0)
-PIVOT["handle"] = Vector((0, POST_Y, POST_Z0 + POST_H / 2)) # any point on the slide axis = (0, 0.159, 0.43)
-
-for child, parent in (("wheel_1", "deck"), ("wheel_2", "deck"), ("handle", "deck")):
- print(child, urdf_origin(child, parent))
-```
-
-```xml
-<?xml version="1.0"?>
-<robot name="hand_cart">
- <link name="deck">
- <visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/deck.glb"/></geometry></visual>
- <collision><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/deck.glb"/></geometry></collision>
- </link>
- <link name="wheel_1"> <!-- pivot (-0.242 -0.115 0.1) -->
- <visual><origin xyz="0.242 0.115 -0.1" rpy="0 0 0"/><geometry><mesh filename="meshes/wheel_1.glb"/></geometry></visual>
- <collision><origin xyz="0.242 0.115 -0.1" rpy="0 0 0"/><geometry><mesh filename="meshes/wheel_1.glb"/></geometry></collision>
- </link>
- <link name="wheel_2"> <!-- pivot (0.242 -0.115 0.1) -->
- <visual><origin xyz="-0.242 0.115 -0.1" rpy="0 0 0"/><geometry><mesh filename="meshes/wheel_2.glb"/></geometry></visual>
- <collision><origin xyz="-0.242 0.115 -0.1" rpy="0 0 0"/><geometry><mesh filename="meshes/wheel_2.glb"/></geometry></collision>
- </link>
- <link name="handle"> <!-- pivot (0 0.159 0.43) -->
- <visual><origin xyz="0 -0.159 -0.43" rpy="0 0 0"/><geometry><mesh filename="meshes/handle.glb"/></geometry></visual>
- <collision><origin xyz="0 -0.159 -0.43" rpy="0 0 0"/><geometry><mesh filename="meshes/handle.glb"/></geometry></collision>
- </link>
- <joint name="deck_to_wheel_1" type="continuous">
- <parent link="deck"/><child link="wheel_1"/>
- <origin xyz="-0.242 -0.115 0.1" rpy="0 0 0"/><axis xyz="1 0 0"/>
- <limit effort="1" velocity="20"/>
- </joint>
- <joint name="deck_to_wheel_2" type="continuous">
- <parent link="deck"/><child link="wheel_2"/>
- <origin xyz="0.242 -0.115 0.1" rpy="0 0 0"/><axis xyz="1 0 0"/>
- <limit effort="1" velocity="20"/>
- </joint>
- <joint name="deck_to_handle" type="prismatic">
- <parent link="deck"/><child link="handle"/>
- <origin xyz="0 0.159 0.43" rpy="0 0 0"/><axis xyz="0 0 1"/>
- <limit lower="0" upper="0.35" effort="10" velocity="0.5"/>
- </joint>
-</robot>
-```
-
-Why: wheels are cylinders along X (`axis='X'`), their pivot is the axle point; the
-telescopic handle's q = 0 is retracted (inside the post), +q pulls it up.
-
-## Joint types, axes, limits (what to write)
-
-| joint | use | `<axis>` sign rule | `<limit>` |
-|---|---|---|---|
-| `revolute` | doors, lids, hinges, levers, knobs with stops | +q = opens / lifts / the "interact" direction | `lower upper effort velocity` all required |
-| `prismatic` | drawers, slides, telescopes, pistons, buttons | +q = pulls OUT / extends | `lower="0" upper=<travel>` |
-| `continuous` | wheels, fans, spinners, casters' roll | right-hand about axis | `effort velocity` only (NO lower/upper) |
-| `fixed` | handles, knobs, feet, labels on a moving link | — | none |
-
-Plausible ranges (SI):
-
-| mechanism | type | lower | upper | notes |
-|---|---|---|---|---|
-| cabinet / room door | revolute | 0 | 1.6–1.9 rad | axis vertical through the hinge edge |
-| laptop / lid / chest lid | revolute | 0 | 1.6–2.1 rad | axis along the back edge |
-| toilet seat / piano fallboard | revolute | 0 | 1.5 rad | |
-| oven / dishwasher door | revolute | 0 | 1.57 rad | axis along the bottom edge |
-| drawer | prismatic | 0 | 0.35–0.45 m (≈ 0.8 × depth) | axis −Y (front) |
-| keyboard tray / telescopic | prismatic | 0 | 0.2–0.4 m | |
-| button / key | prismatic | 0 | 0.002–0.01 m | axis into the body |
-| wheel / caster roll | continuous | — | — | axis = axle (usually X) |
-| caster swivel | continuous | — | — | vertical axis above the wheel |
-| knob / dial | revolute or continuous | −2.6 | 2.6 rad | |
-| lever / switch | revolute | 0 | 0.5–0.9 rad | |
-| faucet handle | revolute | 0 | 1.57 rad | |
-| scissor / tongs | revolute | 0 | 0.6–1.0 rad | one joint; the other leg is the root |
-| robot arm joint | revolute | −2.9 | 2.9 rad | |
-| gripper finger | prismatic | 0 | 0.04 m | |
-
-The harness renders q = 0 plus every joint at its lower and upper limit (the judge sees
-all three), so articulation is always visible — never bake an ajar pose into geometry to
-"show" it. URDF limits from the plan: `lower − rest` … `upper − rest` (the plan's values
-verbatim when `rest` = 0, the usual case; the skeleton already has them).
-
-## Clearances, rest pose, hardware
-
-* Moving part vs housing: 1–3 mm all round over the WHOLE range (drawer box inside the
- cabinet: 2 mm each side, 4 mm above; door leaf vs frame: 2 mm). Test mentally at
- `upper`: does the door corner sweep through the side panel? Put the hinge ON the edge.
-* q = 0 must not self-intersect: a closed door touches the carcass face (flush, 0–1 mm),
- never sinks into it.
-* Handles / knobs / pulls: `fixed` joint to the MOVING link, touching it or sunk ≤ 2 mm
- into it, pivot = the attachment point (handle centre is fine). Hinge barrels and drawer runners belong to the housing link (or to the
- moving link) — they are geometry, not joints.
-* One mechanism per joint. Doubles (two doors, four wheels) = separate links with their
- own pivots; identical meshes are fine.
-* Runners/rails for drawers: two thin boxes on the cabinet sides + two on the drawer box;
- drawer box bottom 3 mm above the rail.
-
-## URDF skeleton (copy, then fill)
-
-```xml
-<?xml version="1.0"?>
-<robot name="object_name">
- <!-- one <link> per Blender object, names identical; visual + collision origin = -pivot -->
- <link name="base"> <!-- root: frame = world origin -->
- <visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/base.glb"/></geometry></visual>
- <collision><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/base.glb"/></geometry></collision>
- <!-- optional: <inertial><mass value="5"/><inertia ixx="0.1" iyy="0.1" izz="0.1" ixy="0" ixz="0" iyz="0"/></inertial> -->
- </link>
- <link name="child"> <!-- frame at pivot (PX PY PZ) -->
- <visual><origin xyz="-PX -PY -PZ" rpy="0 0 0"/><geometry><mesh filename="meshes/child.glb"/></geometry></visual>
- <collision><origin xyz="-PX -PY -PZ" rpy="0 0 0"/><geometry><mesh filename="meshes/child.glb"/></geometry></collision>
- </link>
- <joint name="base_to_child" type="revolute">
- <parent link="base"/><child link="child"/>
- <origin xyz="PX PY PZ" rpy="0 0 0"/> <!-- pivot_child - pivot_parent (root pivot = 0 0 0) -->
- <axis xyz="0 0 1"/> <!-- unit, WORLD direction, +q = open -->
- <limit lower="0" upper="1.6" effort="10" velocity="1"/>
- </joint>
-</robot>
-```
-
-## Pitfalls (symptom → cause → fix)
-
-1. **Door swings into the cabinet** → axis sign. Flip the axis (`0 0 1` ↔ `0 0 -1`);
- never make `lower` negative to compensate.
-2. **Child jumps when q changes / orbits around the wrong point** → pivot not on the
- hinge line: the pivot must be a point ON the axis (edge of the door, the axle), not
- the part's centre.
-3. **Build fails `FkInconsistent` / "URDF frames do not reproduce the authored geometry"**
- → a link's visual/collision `<origin>` is not `−pivot` (most often left at `0 0 0`), or a
- joint has `rpy ≠ 0`. Meshes are world coordinates; the link frame sits at the pivot, so
- the origin must undo it. Copy the corrected numbers from the message into BOTH tags.
-4. **"link X has two parent joints" / "not connected to root"** → every non-root link is
- the child of exactly one joint; handles attach to the door, not to the base AND door.
-5. **Penetration at upper limit** (`joint_sweep` says `Drawer` hits `Base` at q = 0.4) →
- travel too long or clearance zero. Shorten `upper` to 0.8 × depth, add 2 mm gaps.
-6. **Parts float** (`check_connectivity`): hinge barrels, runners, knobs not overlapping.
- Weld 2 mm.
-7. **`continuous` with `<limit lower upper>`** or `revolute` without limits → lint error.
-8. **Blender object names ≠ link names** (`door.001`, `Door` vs `door`) → mesh not found.
- Identical spelling in both files, unique, no `.001` suffix; join sub-pieces with `join_as`.
-9. **Object not on the ground** → wheels' bottom / feet at z = 0 at q = 0.
-10. **Mesh scale in URDF** (`scale="0.001 …"`) → forbidden; author in metres.
-11. **Non-unit axis** (`0 0 2`) → lint error; also avoid `0.7 0.7 0` unless intended.
-12. **q = 0 is the open pose** (but the plan says rest 0 = closed) → the rest render looks
- odd and the sweep at `lower` collides; build the pose the plan's bboxes describe and let
- the limit poses show the motion.
-13. **Limits copied verbatim although the plan's `rest` ≠ 0** → the joint over-opens by
- `rest` and never closes. Write `lower − rest` … `upper − rest` (the skeleton did).
-14. **Handles built in world but parented to the wrong link** → their joint origin must be
- subtracted from the DOOR pivot (`urdf_origin("door_handle", "door")`), not from the base;
- their visual/collision origin is still `−pivot_handle`.
-15. **`<collision>` missing or ≠ `<visual>`** → lint warning; give every link one identical
- collision block (same mesh, same origin) — the sweep collides those.
-
-## Self-check (before you call it done)
-
-```python
-def urdf_selfcheck(expected_links):
- names = sorted(o.name for o in bpy.data.objects if o.type == 'MESH')
- missing = [n for n in expected_links if n not in names]
- extra = [n for n in names if n not in expected_links]
- assert not missing and not extra, f"links mismatch: missing={missing} extra={extra}"
- assert all("." not in n for n in names), f"auto-suffixed: {[n for n in names if '.' in n]}"
- for n in expected_links:
- assert n in PIVOT, f"no pivot recorded for {n}"
- bpy.context.view_layer.update()
- zmin = min((o.matrix_world @ Vector(c)).z for o in bpy.data.objects if o.type == 'MESH' for c in o.bound_box)
- assert abs(zmin) < 0.01, f"lowest point z={zmin:.4f}"
- print("[selfcheck] links", names, "pivots ok")
-
-urdf_selfcheck(["carcass", "door", "door_handle", "drawer", "base", "lid",
- "deck", "wheel_1", "wheel_2", "handle"])
-```
-
-Then: `build` (it runs the FK check and the collision sweep and tells you the numbers) →
-`render_sheet` → `check_connectivity` → `joint_sweep` on EVERY joint (look at q = lower /
-mid / upper renders: does the right part move, the right way, without penetration?) →
-`check_contract`.
diff --git a/harness/codeverse3d/prompts/urdf/system.md b/harness/codeverse3d/prompts/urdf/system.md
index 35d5ba48..4397544b 100644
--- a/harness/codeverse3d/prompts/urdf/system.md
+++ b/harness/codeverse3d/prompts/urdf/system.md
@@ -1,53 +1,58 @@
You are a Blender `bpy` + URDF author writing RAW python and RAW URDF for a headless
harness. No SDKs, no helper libraries. Links are bpy objects named exactly as the URDF
-links; joints are native URDF with origins and axes stated in the **parent** link frame.
+links; joints are native URDF: the origin in the **parent** link frame, the axis in the
+joint frame that origin sets up.
The harness owns the export and the pose sweep — never save, never render.
You are not modelling a shape. You are modelling a **mechanism**, and it is judged while
it moves.
{% if tools %}
-The loop that decides whether your work ships:
-
- write → `build` → `check_contract` + `check_connectivity` → fix →
- **`joint_sweep`** → fix every pose collision → repeat → `render_views` → LOOK
- → only then finish.
-
-`joint_sweep` is the one that fails you, and it is the one agents skip. Do not finish
-while it reports an error. An assembly that is clean at rest and jams at 40° of travel is
-the normal failure of this track, not an unlucky one.
+The round's gates: `build` (lint, the FK check at q=0, rest-pose penetration),
+`joint_sweep` (every joint at lower/mid/upper plus 8 random combinations; an overlap deeper
+than 2 mm in a moved pose is an ERROR), `check_connectivity` and `check_contract`. A round
+with a sweep ERROR is not accepted. Run them in whatever order finds your errors soonest;
+`render_views` shows you what the judge will see. The sweep is the one agents skip: an
+assembly that is clean at rest and jams at 40° of travel is the normal failure of this
+track, not an unlucky one.
{% else %}
You cannot run anything: this is a single-shot session with no tools, so the code you
-return is the code that ships. Before you finish, take each joint in turn and walk it
-mentally to **both** of its limits with every other joint at both of theirs. The question
+return is the code that ships. The sweep will pose every joint at lower, mid and upper
+(the others at 0) and 8 random full-body combinations; nothing may overlap by more than
+2 mm in any of them. Check those poses yourself before you return the code: the question
is not "does this fit" but "does this still fit at the end of its travel".
{% endif %}
-What the gates name, measured over 64 recorded runs of this exact track:
-
-* **Links overlapping at a pose** — the dominant defect, and it is logged as an **error**,
- not a warning: 500+ findings of the form "links 'A' and 'B' overlap by N at pose
- `joint=…,joint=…`". Only 68 of those were at the rest pose. **Everything else only
- appeared once the joint moved.** Give each moving link the clearance its full range
- needs: measure the swept volume, not the parked one. Where two links must pass close,
- make the travel limits honest rather than letting them intersect.
-* **Stray islands** (232 findings) — a link that contains tiny disconnected fragments.
- Every link is one connected shell. A mirror or boolean that left debris fails here.
-* **Bbox deviates from the plan** (126 findings) — the link you built is not the size you
- planned. Change the plan if the number was wrong; do not silently build something else.
+What the gates measure on this track, in order of how often they fire:
+
+* **Links overlapping at a pose** — any overlap deeper than 2 mm in a moved pose is an
+ ERROR whatever its depth (`joint_sweep`); at rest 2–5 mm is a WARN and more than 5 mm
+ fails the build. Almost all findings appear only once a joint moves, so give each moving
+ link the clearance its whole range needs: measure the swept volume, not the parked one.
+ Where two links must pass close, make the travel limits honest rather than letting them
+ intersect.
+* **Stray islands** — `check_connectivity` reports disconnected fragments inside a link, and
+ the sweep can only estimate depth on a non-watertight link (`[approx: non-watertight
+ mesh]`). A fragment smaller than 5 % of the link's largest extent is a stray island; a
+ mirror or boolean that left debris fails here.
+* **Bbox deviates from the plan** — `check_contract` compares every link's bbox with the
+ plan's (tolerance max(10 mm, 10 % of the planned extent) per axis). Build the planned
+ size; if a number is wrong for the object, keep it and say why in a comment.
Rules that survive every brief:
-* **Joint origins and axes are in the parent frame.** This is where most URDF goes wrong.
- State the origin as the offset from the parent's frame to the joint, and the axis as a
- unit vector in that same frame. Verify by asking what happens at angle zero.
+* **Joint origins are in the parent link frame; the axis is in the joint frame.** This is
+ where most URDF goes wrong. State the origin as the offset from the parent's frame to the
+ joint and the axis as a unit vector; with every `rpy` at 0 both frames are world-aligned
+ (the contract's frame rule). Verify by asking what happens at angle zero.
* **Every joint needs real limits.** `lower`/`upper` that describe the mechanism, not
- `-3.14`/`3.14` placeholders. A hinge that can rotate through its own housing is a
- modelling error the sweep will find.
+ `-3.14`/`3.14` placeholders (`lower == upper` is a lint WARN; the sweep tests both ends).
+ A hinge that can rotate through its own housing is a modelling error the sweep will find.
* **The kinematic tree is a tree.** One root, every other link reachable through exactly
- one parent. No cycles, no orphans, no link named in a joint that does not exist.
+ one parent (lint ERROR otherwise). No cycles, no orphans, no link named in a joint that
+ does not exist.
* **Author in metres at real scale.** The harness exports the assembly as authored and
never re-centres or grounds it, so seating it on the ground yourself is fine.
-A mechanism that moves cleanly through its whole range beats a more detailed one that
-jams. Clear `joint_sweep` first; spend what is left on the geometry.
+A sweep ERROR blocks the round whatever the geometry looks like; detail only counts on a
+mechanism that clears it.
diff --git a/harness/codeverse3d/record/telemetry.py b/harness/codeverse3d/record/telemetry.py
index 5e07718d..921469e8 100644
--- a/harness/codeverse3d/record/telemetry.py
+++ b/harness/codeverse3d/record/telemetry.py
@@ -6,7 +6,7 @@ docs/RUN_LAYOUT.md):
* ``settings.json`` — how the run was configured: model id per role, thinking
level / temperature / judge samples, rounds + budget, rubric and its content
- hash, prompt & cookbook hashes, tool versions, harness git sha, key-pool size,
+ hash, prompt and skill hashes, tool versions, harness git sha, key-pool size,
price-table hash, render + limit settings.
* ``cost.json`` — the run-layout summary of the ledger rows: totals, per stage, per
role, per model, per round, the run's minutes against ``max_minutes``.
diff --git a/harness/codeverse3d/skills/__init__.py b/harness/codeverse3d/skills/__init__.py
index a9e914e2..7d913a74 100644
--- a/harness/codeverse3d/skills/__init__.py
+++ b/harness/codeverse3d/skills/__init__.py
@@ -1,13 +1,14 @@
"""The 3dcode skill library: task-scoped rule sheets, routed automatically, read-measured.
-A *skill* is not a renamed cookbook chapter — the two sit on opposite sides of the split
-in ``prompts/catalog.py``. The cookbook is PROMPT material: the reference manual of
-copyable code, resolved through that catalog, inlined into the generate templates and
-materialised at ``.3dcode/cookbook.md`` for the agent to re-read (the ``read_cookbook`` MCP
-tool that once served it a chapter at a time was deleted — 0 calls in 16 zone sessions).
-A skill is AGENT-READ material the harness only materialises: <=350 lines of rules and
-numbers for one recurring failure class, attached to a session only when the track /
-language / kind / plan / **previous round's gate findings** say it applies.
+A *skill* is not a recipe library — the two sides of the split in ``prompts/catalog.py``:
+PROMPT material (``contract.md`` / ``system.md``: interface, sandbox, measured requirements)
+is what the harness puts in a message; a skill is AGENT-READ material the harness only
+materialises: <=350 lines of measured requirements and a few short optional practices for
+one recurring failure class (library / API names, fences of ~12 lines at most, numbers only
+where a gate or the judge measures them — D107), attached to a session only when the track /
+language / kind / plan / **previous round's gate findings** say it applies. (The cookbooks
+that preceded the library were deleted track by track, D106 / D107; the ``read_cookbook`` MCP
+tool that served them a chapter at a time was measured at 0 calls in 16 zone sessions.)
Why the library lives inside the package: every backend reads it from a materialised
workspace copy, but the source of truth ships in the wheel, so it must be package data
diff --git a/harness/codeverse3d/skills/_claims/c3d-glsl-craft.toml b/harness/codeverse3d/skills/_claims/c3d-glsl-craft.toml
index 1e875238..e214194d 100644
--- a/harness/codeverse3d/skills/_claims/c3d-glsl-craft.toml
+++ b/harness/codeverse3d/skills/_claims/c3d-glsl-craft.toml
@@ -1,4 +1,4 @@
-# The judged frame times this bundle quotes, pinned to the tuple the graphics track renders.
+# The judged frame times and the gl_frames thresholds this bundle quotes, pinned to the live constants.
[[claim]]
key = "judge_times"
@@ -6,3 +6,27 @@ text = "0, 1, 2.5, 4, 6"
python = "codeverse3d.languages._gl_common:JUDGE_TIMES"
sep = ", "
context = "renders five frames"
+
+[[claim]]
+key = "static_diff"
+text = "0.002"
+python = "codeverse3d.spatial.frame_stats:STATIC_DIFF"
+context = "static"
+
+[[claim]]
+key = "flicker_diff"
+text = "0.35"
+python = "codeverse3d.spatial.frame_stats:FLICKER_DIFF"
+context = "flicker"
+
+[[claim]]
+key = "black_lum"
+text = "0.03"
+python = "codeverse3d.spatial.frame_stats:BLACK_LUM"
+context = "blown"
+
+[[claim]]
+key = "blown_lum"
+text = "0.98"
+python = "codeverse3d.spatial.frame_stats:BLOWN_LUM"
+context = "blown"
diff --git a/harness/codeverse3d/skills/c3d-bbox-contract/SKILL.md b/harness/codeverse3d/skills/c3d-bbox-contract/SKILL.md
index d661029c..91350318 100644
--- a/harness/codeverse3d/skills/c3d-bbox-contract/SKILL.md
+++ b/harness/codeverse3d/skills/c3d-bbox-contract/SKILL.md
@@ -4,7 +4,7 @@ description: "Use when a session owns part sizes, placement or ground contact, o
license: Apache-2.0
metadata:
evidence: measured
- verified: "2026-08-25"
+ verified: "2026-10-15"
corpus: bench/out, 142 graded records with gate artefacts, recomputed 2026-08-25
target_metric: "contract_findings"
target_direction: "down"
@@ -50,27 +50,23 @@ ERROR, not a rounding difference.
## Rules
-1. **Type every plan number once.** Each dimension becomes one named constant at the top of
- the file; everything else is derived from those constants. A number typed twice is a
- number that will disagree with itself.
-2. **Derive a spanning dimension from its neighbours' bounds, never re-type it.** A shelf
- that spans two uprights is `inner_span = pitch - upright_thickness + 2 * weld`, computed
- from the constants the uprights already used. Re-typing "0.58" is how the 1.47x median
- miss is made.
-3. **Budget for what the modifiers do to the bounding box.** The gate measures the built
+1. **Derive, do not retype** (a strong option, not a layout rule). A dimension computed from
+ the plan numbers it depends on — a neighbour's bounds included — lives in one place; a
+ number typed twice will disagree with itself, which is how the 1.47x median miss is made.
+2. **Budget for what the modifiers do to the bounding box.** The gate measures the built
AABB, after everything. A bevel, chamfer or fillet *shrinks* the silhouette; a solidify,
skin or subdivision surface pulls a cage *inward*; an outline offset grows it. If the
plan says 88 mm and your bevel eats 9 mm, you shipped 79 mm and the gate says so.
-4. **Instanced parts are measured on extents only.** For a part with `instances > 1` the
+3. **Instanced parts are measured on extents only.** For a part with `instances > 1` the
gate reads the plan box two ways — as the size of ONE copy, and as the union of all
copies — and keeps whichever fits better, so building either reading is accepted. It
does **not** check the centre of an instanced part (it cannot know which copy is which).
A wrong *count* is a separate WARN: name the copies `Name_0 .. Name_N-1`.
-5. **Sit on the ground and centre the footprint.** Lowest point at zero: a gap beyond 1 cm
+4. **Sit on the ground and centre the footprint.** Lowest point at zero: a gap beyond 1 cm
is a WARN and beyond 3 cm an ERROR, with the exact translation in the hint. The
footprint centre must be within `max(1 cm, 10 % of the larger horizontal extent)` of the
up axis — that one is always a WARN and always fixable by one translate.
-6. **Names are the join key.** Parts match by their snake-cased name; the exact name is
+5. **Names are the join key.** Parts match by their snake-cased name; the exact name is
claimed first and `Name_0..Name_N` afterwards. A plan part with no matching node is an
ERROR ("missing from the GLB"); an extra node the plan never mentioned is only INFO. So
a spare helper node is cheap and a misspelt part name is expensive.
@@ -86,4 +82,9 @@ know which finding is the ERROR.
`isolate <PartName>` renders one part alone with its measurement row when a delta does not
make sense.
+**Measure like the gate** when you check a size in your own script (bpy): the gate reads the
+world-space AABB, so take `obj.matrix_world @ Vector(c)` over `obj.bound_box` after
+`bpy.context.view_layer.update()`; `obj.dimensions` ignores rotation and `bound_box` is
+object-space, so either one disagrees with the gate on a rotated part.
+
Worked example of turning a real fix hint into an edit: `references/reading-a-fix-hint.md`.
diff --git a/harness/codeverse3d/skills/c3d-bbox-contract/references/reading-a-fix-hint.md b/harness/codeverse3d/skills/c3d-bbox-contract/references/reading-a-fix-hint.md
index 35f74e52..bd7e1ddd 100644
--- a/harness/codeverse3d/skills/c3d-bbox-contract/references/reading-a-fix-hint.md
+++ b/harness/codeverse3d/skills/c3d-bbox-contract/references/reading-a-fix-hint.md
@@ -61,14 +61,15 @@ translate everything by (-0.019, +0.006, +0.000) m to centre the footprint
object floats 130.0 mm above the ground
```
-Both hints hand you the vector. Apply it to the top-level container, once, at the end of
-construction — not per part, or the parts drift relative to each other and the contact
-graph changes.
+Both hints hand you the vector. Apply the same vector to every part — three.js: the root
+Group; cadquery: each child's `loc`; blender: every top-level object (there is no container,
+a parent Empty would merge the parts) — so the parts keep their places relative to each
+other and the contact graph does not change.
## Order of work on a repair round
1. `check_contract`, and sort the findings by the "worst Nx tolerance" number in the message.
2. Fix ERRORs (ratio above 3x) first; they are the only ones that fail the gate.
-3. Change constants, never the built geometry, wherever a constant exists.
+3. Where a constant drives the dimension, changing the constant fixes every place that uses it.
4. `build` -> `check_contract` again. A fix that moves a second part into failure means the
two shared a derived number and one of them was re-typed.
diff --git a/harness/codeverse3d/skills/c3d-blender-forms/SKILL.md b/harness/codeverse3d/skills/c3d-blender-forms/SKILL.md
index 7760bdf5..876c9f96 100644
--- a/harness/codeverse3d/skills/c3d-blender-forms/SKILL.md
+++ b/harness/codeverse3d/skills/c3d-blender-forms/SKILL.md
@@ -2,10 +2,10 @@
name: c3d-blender-forms
description: "Use when writing Blender bpy code (language blender or urdf_blender): turn a described shape into the right bpy technique. Avoids the five bpy traps this harness's lint and exporter actually catch: join without an active object, a part file model.py never imports, no PascalCase names, modifier_apply out of context, and primitive_cube_add scale doubling the extents. Covers building, detailing, refining and repairing geometry."
license: Apache-2.0
-compatibility: Blender 5.0.1 headless, run by codeverse3d/languages/wrappers/run_bpy.py. bpy, bmesh, mathutils, math, random, numpy only.
+compatibility: Blender 5.2.2 LTS headless, run by codeverse3d/languages/wrappers/run_bpy.py; imports per the contract's allow-list.
metadata:
evidence: measured
- verified: "2026-08-25"
+ verified: "2026-10-15"
corpus: "102 graded blender runs + 23 urdf_blender runs with gate artefacts, mined 2026-08-25"
target_metric: "blender_lint_findings"
target_direction: "down"
@@ -18,7 +18,9 @@ metadata:
**Read this if** you are about to write `bpy` code. It is two things: a form-to-technique
table so you do not build everything out of boxes, and the five traps that a static lint
-already caught in this corpus, with how often.
+already caught in this corpus, with how often. Every row and practice is an option under its
+real API name — the brief and the plan say what the object is; nothing here says how it must
+be built.
blender is the biggest language here (102 of 142 graded runs with gate artefacts) and its
two weakest judge criteria are `assembly_fit` (0.60) and `geometry_detail` (0.67), means
@@ -28,26 +30,25 @@ defers to rather than restating.
## Form to technique
-Name the form first — say the shape in words before you type a call — then pick the row. Never
-start from "what primitive is nearest".
+Say the form in words, then pick the technique; the table is a menu, not an order.
| form | technique | notes |
|---|---|---|
-| revolved profile (bottle, knob, vase, wheel hub) | `bmesh.ops.spin` on a profile, or a SCREW modifier | a lathe is one line and reads instantly better than a stack of cylinders |
+| revolved profile (bottle, knob, vase, wheel hub) | `bmesh.ops.spin` on a profile, or a SCREW modifier | one `(radius, z)` list is the whole shape; spin needs EDGES in `geom`, and `remove_doubles` welds the seam and the axis points |
| thread, coil, spring | SCREW modifier with `screw_offset` and `iterations` | not a stack of tori |
-| swept tube (rail, cable, handle, hose) | curve with a non-zero `bevel_depth`; evaluate it to a mesh when a later step needs real geometry | `bevel_depth = 0` is a path with no surface: the node exports with no faces and the part is reported **missing** |
+| swept tube (rail, cable, handle, hose) | curve with a non-zero `bevel_depth`; evaluate it to a mesh when a later step needs real geometry | `bevel_depth = 0` is a path with no surface: it exports no node and the part is reported **missing** (contract.md) |
+| moulding, rim, handrail, cornice | a 2-D profile curve as the `bevel_object` of a 3-D path curve (`bevel_mode = 'OBJECT'`), evaluated to a mesh | a curved path needs sampled points, not four corners |
| extruded outline with softened edges | `bmesh.ops.extrude_face_region` then BEVEL modifier | `width` must be under half the thinnest wall or the bevel eats the part |
-| shell / sheet metal / panel with wall thickness | build the surface, add SOLIDIFY | `offset=-1` grows inward, so the outer surface stays on the plan bbox |
+| shell / sheet metal / panel with wall thickness | build the surface, add SOLIDIFY, then any bevel | `offset=-1` grows inward, so the outer surface stays on the plan bbox; zero-thickness faces have no volume for the gate's inside test and break booleans |
| cavity, slot, groove, hole | BOOLEAN DIFFERENCE, solver EXACT or MANIFOLD | cutter must overshoot the pierced face and never be coplanar with it |
| small detail welded onto a body | BOOLEAN UNION, or build it into the same `bmesh` | overlapping is not merging: see `c3d-part-contact` |
| N identical features on one part | ARRAY or MIRROR modifier, or one python loop into one `bmesh` | array/mirror/screw results are ONE object, which is what you want for in-part detail |
| N identical *parts* | a loop that creates N top-level objects named `Name_0 .. Name_N-1` | never a parent Empty; see `c3d-repeats-and-mirrors` |
-| taper, bend, twist | `bmesh` vertex maths, or SIMPLE_DEFORM | cheap and it reads |
-| smooth organic body with sharp seams | SUBSURF plus edge creases | subsurf shrinks the part: measured on Blender 5.0.1 a subsurfed cube loses **16%** of every extent, a 32-segment cylinder 4-6%. The exporter applies it, so the contract gate sees the shrunk size |
-| beam between two points | build along one axis, then place from the endpoints | do **not** rotate a cylinder with Euler angles; see `references/form-recipes.md` |
+| taper, bend, twist | `bmesh` vertex maths, or SIMPLE_DEFORM | pivots on the object origin; needs rings along the length |
+| smooth organic body with sharp seams | SUBSURF plus edge creases (`crease_edge` attribute) | subsurf shrinks the part: measured on Blender 5.2.2 a level-2 subsurfed cube loses **16%** of every extent. The exporter applies it, so the contract gate sees the shrunk size |
+| beam between two points | build along one axis, then place from the endpoints | a quaternion from the endpoint direction (`Vector.rotation_difference`) avoids Euler-order mistakes; see `references/form-recipes.md` |
-Code for every row: the cookbook section "Modifiers", and "Screw and lathe",
-"Curves", "Deformation", "Boolean detailing", "Parametric repetition".
+Short practices for each row are in `references/form-recipes.md`.
## The five traps, with counts
@@ -75,7 +76,7 @@ finding, emitted before the build even runs.
loop — and then wrap it: `with bpy.context.temp_override(object=obj, active_object=obj,
selected_objects=[obj]):`.
5. **`primitive_cube_add(scale=...)` without `size=1` — the extents come out doubled.**
- Verified on Blender 5.0.1: `primitive_cube_add(scale=(0.3, 0.2, 0.1))` gives dimensions
+ Re-measured on Blender 5.2.2: `primitive_cube_add(scale=(0.3, 0.2, 0.1))` gives dimensions
0.6 x 0.4 x 0.2; adding `size=1` gives exactly 0.3 x 0.2 x 0.1. Pass `size=1` and the
scale vector **is** the plan's extents, so you can paste the plan numbers in. Then bake
it: `transform_apply(location=False, rotation=False, scale=True)` — all three keywords,
@@ -85,21 +86,37 @@ Two more from the same lint that cost a whole run when they fire: indexing
`bm.verts[i]` without `ensure_lookup_table()` is an ERROR (IndexError at build time), and
`bsdf.inputs["Specular"]` is an ERROR (renamed to `"Specular IOR Level"` in 4.x/5.x).
-## Rules that are not in the lint but should be in your head
+## Strong options (not in the lint)
-* **Never rotate a cylinder into place.** Build a beam from its two world endpoints —
- direction, length, and a quaternion from `(0,0,1)` to that direction. Euler order will
- betray you on the second axis. Recipe in `references/form-recipes.md`.
-* **Derive spanning dimensions from the neighbour's plan bbox**, not from a typed literal.
- A cross-brace's length is `right.bbox.min.x - left.bbox.max.x + 2 * weld`.
+* **Struts.** Build along +Z and place with a quaternion from the two world endpoints
+ (`references/form-recipes.md` §1); Euler order betrays you on the second axis.
+* **Spans computed from the neighbours' plan bboxes** follow the neighbours when they move;
+ a typed literal does not.
* **Keep `obj.scale` at 1 by export time.** A scaled object bevels unevenly and exports its
- scale baked; `apply_transforms` before any bevel or boolean.
+ scale baked; apply the transform before any bevel or boolean.
* **`bpy.context.selected_objects` and `bpy.context.object` are unreliable headless.** Keep
your own references to everything you create. (1 run lost time to this.)
* **The exporter takes every *visible* mesh.** A leftover cutter, a construction guide or a
duplicate ships as a part. Delete it or set `hide_render`/`hide_viewport`.
-* **Detail over triangle count.** A bevel and a chamfer on the right edges read as more
- refinement than a dense subsurf.
+* **Fewer booleans.** Cutters of one kind can share one mesh and one cut: every boolean is
+ another evaluation and another chance of a non-manifold sliver, which the island gate
+ reports. A cutter coplanar with the face it cuts, or not closed (`cap_ends=True`), fails
+ silently.
+* **Flipped normals** after `bmesh.ops.scale` with a negative factor or after mirroring read
+ as dark, inside-out faces in every render (no gate measures them):
+ `bmesh.ops.recalc_face_normals(bm, faces=bm.faces)` before `to_mesh`.
+* **Bend / taper.** SIMPLE_DEFORM pivots on the object origin and needs rings along the
+ length (`bmesh.ops.subdivide_edges` on the side edges): an origin at one end gives an arc,
+ a centred one a C.
+* **Two-tone parts.** A second colour on one part is a second material slot and
+ `face.material_index` on the faces you choose; `bmesh.ops.create_*` return only `verts`,
+ so diff `set(bm.faces)` before and after the op to find the new faces, or set
+ `polygon.material_index` on `obj.data.polygons` afterwards. The census warns when a slot
+ is never used (contract.md, Materials).
+* **Where detail is seen.** The judge's montage shows the silhouette and the largest faces
+ from the rig's views; the underside and interiors the camera cannot enter are never
+ rendered. Bevels and chamfers add shading breaks for few triangles; the triangle budget
+ gate states a number only when you exceed it.
## Before you finish
@@ -107,6 +124,5 @@ Two more from the same lint that cost a whole run when they fire: indexing
`lint:blender` findings in the build report first: they are free, static, and every one of
the five above was reported *before* the model was wrong.
-Worked code — the beam helper, the lathe, the sweep, the solidify shell, the boolean with
-its cutter cleaned up, and the multi-file wiring skeleton — is in
-`references/form-recipes.md`.
+Short options — the beam, the lathe, the swept tube, the solidify shell, the boolean with
+its cutter cleaned up, and the multi-file wiring — are in `references/form-recipes.md`.
diff --git a/harness/codeverse3d/skills/c3d-blender-forms/references/form-recipes.md b/harness/codeverse3d/skills/c3d-blender-forms/references/form-recipes.md
index 4f2b4226..a2faa7d0 100644
--- a/harness/codeverse3d/skills/c3d-blender-forms/references/form-recipes.md
+++ b/harness/codeverse3d/skills/c3d-blender-forms/references/form-recipes.md
@@ -1,154 +1,65 @@
-# bpy form recipes
+# bpy form options
-Companion to `c3d-blender-forms`. Every snippet was written against the harness's own
-runtime (Blender 5.0.1, `blender -b --factory-startup`, no operator context you did not
-create yourself) and uses only the allowed imports. Longer copyable code lives in the
-cookbook section "Modifiers" and friends.
+Companion to `c3d-blender-forms`. Written against Blender 5.2.2 LTS, `blender -b
+--factory-startup`, no operator context you did not create yourself, the contract's
+allowed imports only. Each paragraph names a form under its real API and the trap that
+bites it — an option, not the way.
-## 1. A beam between two world points (instead of rotating a cylinder)
+## 1. A beam between two world points
-Euler order is the single most reliable way to place a strut wrong. Build along +Z and
-rotate once, with a quaternion derived from the endpoints:
-
-```python
-import bpy, bmesh
-from mathutils import Vector, Matrix
-
-def beam(name, p0, p1, radius, segments=16):
- """A capsule-less cylinder from p0 to p1, correct for any direction."""
- a, b = Vector(p0), Vector(p1)
- d = b - a
- length = d.length
- bm = bmesh.new()
- bmesh.ops.create_cone(bm, cap_ends=True, segments=segments,
- radius1=radius, radius2=radius, depth=length)
- me = bpy.data.meshes.new(name); bm.to_mesh(me); bm.free()
- obj = bpy.data.objects.new(name, me)
- obj.matrix_world = (Matrix.Translation((a + b) / 2.0)
- @ Vector((0.0, 0.0, 1.0)).rotation_difference(d.normalized()).to_matrix().to_4x4())
- bpy.context.scene.collection.objects.link(obj)
- return obj
-```
-
-The length is the distance between the two points, so it cannot disagree with them, and the
-endpoints are where you say they are. Compute `p0`/`p1` from the neighbours' plan bboxes
-plus the 1 mm weld from `c3d-part-contact`.
+Build the shape along +Z (`bmesh.ops.create_cone` with equal radii and `depth` = the endpoint
+distance), then set `obj.matrix_world` from the midpoint translation times
+`Vector((0, 0, 1)).rotation_difference(direction).to_matrix().to_4x4()`. The length then
+cannot disagree with the endpoints, and no Euler order is involved — two chained Euler
+rotations are the most reliable way to place a strut wrong.
## 2. Revolved profile (lathe)
-```python
-def lathe(name, profile_xy, segments=48, axis=(0, 0, 1)):
- """profile_xy: [(radius, z)] from bottom to top, in metres, from the plan."""
- bm = bmesh.new()
- verts = [bm.verts.new((r, 0.0, z)) for r, z in profile_xy]
- for v0, v1 in zip(verts, verts[1:]):
- bm.edges.new((v0, v1))
- bmesh.ops.spin(bm, geom=bm.verts[:] + bm.edges[:], axis=axis, cent=(0, 0, 0),
- dvec=(0, 0, 0), angle=6.283185, steps=segments, use_merge=True)
- bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
- me = bpy.data.meshes.new(name); bm.to_mesh(me); bm.free()
- obj = bpy.data.objects.new(name, me)
- bpy.context.scene.collection.objects.link(obj)
- return obj
-```
-
-A profile of six or eight `(radius, z)` pairs is what turns "a jug" from a cylinder into a
-jug. That is the `geometry_detail` criterion in one function.
-
-## 3. Swept tube along a path — and the real export trap
+`bmesh.ops.spin(bm, geom=verts + edges, axis=(0, 0, 1), cent=(0, 0, 0), angle=2π, steps=n,
+use_merge=True)` on a `(radius, 0, z)` profile. Traps: spin needs the EDGES in `geom` (verts
+alone give a point cloud); `bmesh.ops.remove_doubles` afterwards welds the seam and the axis
+points, and `bmesh.ops.recalc_face_normals` fixes a profile drawn top-down.
-Verified on Blender 5.0.1 against the harness's own export call: a curve object with a
-`bevel_depth` **does** export (the glTF writer evaluates it), so the old advice "always
-convert or it exports nothing" is not the failure. The failure is a curve with
-`bevel_depth = 0` — a zero-thickness path has no surface, the node exports with no faces,
-`spatial/measure.py::solid_parts` drops it, and the contract gate reports the part missing.
+## 3. Swept tube along a path
-Give every curve a bevel, and convert to a mesh whenever a later step needs real geometry
-(a boolean, a vertex loop, a measurement). Convert without operators — `bpy.ops.object.convert`
-needs the object to be a *selected editable* object in the view layer and fails silently in
-background mode with "No editable objects to convert":
-
-```python
-def curve_to_mesh(obj):
- """Ops-free CURVE -> MESH: evaluate the bevel and swap the data. Keeps the name."""
- dg = bpy.context.evaluated_depsgraph_get()
- me = bpy.data.meshes.new_from_object(obj.evaluated_get(dg))
- name = obj.name
- bpy.data.objects.remove(obj, do_unlink=True)
- new = bpy.data.objects.new(name, me)
- bpy.context.scene.collection.objects.link(new)
- return new
-
-def tube(name, points, radius, resolution=6):
- cu = bpy.data.curves.new(name + "Data", 'CURVE'); cu.dimensions = '3D'
- cu.bevel_depth = radius # never 0: that is the part-goes-missing bug
- cu.bevel_resolution = resolution; cu.use_fill_caps = True
- sp = cu.splines.new('POLY'); sp.points.add(len(points) - 1)
- for i, (x, y, z) in enumerate(points):
- sp.points[i].co = (x, y, z, 1.0)
- obj = bpy.data.objects.new(name, cu)
- bpy.context.scene.collection.objects.link(obj)
- return curve_to_mesh(obj)
-```
+A curve (`bpy.data.curves.new(name, 'CURVE')`, `dimensions = '3D'`, a `POLY` spline whose
+`points[i].co = (x, y, z, 1.0)`) with `bevel_depth > 0` and `use_fill_caps = True` exports as a
+mesh; with `bevel_depth = 0` it exports no node and the part is reported missing (measured on
+5.2.2, contract.md). When a later step needs real geometry, convert without operators —
+`bpy.data.meshes.new_from_object(obj.evaluated_get(depsgraph))`, then a new object under the
+same name — because `bpy.ops.object.convert` needs a selected editable object and fails headless
+with "No editable objects to convert". A bevelled strip can come back as one island per
+segment; `remove_doubles` on the converted mesh welds it.
## 4. Shell with a wall thickness
-```python
-sol = obj.modifiers.new("Solidify", 'SOLIDIFY')
-sol.thickness = 0.003 # 3 mm wall
-sol.offset = -1 # grow INWARD: the outer surface stays on the plan bbox
-sol.use_even_offset = True
-```
-
-Leave it unapplied. The exporter evaluates modifiers (`export_apply=True`), so the gate
-measures the solidified result without you touching operator context.
+A SOLIDIFY modifier with `offset = -1` grows inward, so the outer surface stays where the plan
+bbox puts it; `use_even_offset = True` keeps the wall even on curves. Left unapplied, the
+exporter evaluates it (`export_apply=True`). A bevel on a shell goes after the solidify in the
+stack, or it bevels a zero-thickness surface.
## 5. Cavity, and cleaning up after it
-```python
-def cut(obj, cutter, solver='MANIFOLD'):
- m = obj.modifiers.new("Cut", 'BOOLEAN'); m.operation = 'DIFFERENCE'; m.object = cutter
- if solver not in m.bl_rna.properties["solver"].enum_items.keys():
- solver = 'EXACT'
- m.solver = solver
- with bpy.context.temp_override(object=obj, active_object=obj, selected_objects=[obj]):
- bpy.ops.object.modifier_apply(modifier=m.name)
- bpy.data.objects.remove(cutter, do_unlink=True) # or it exports as its own part
-```
-
-The cutter must overshoot the face it pierces and must never be coplanar with it. If you
-leave the modifier for the exporter instead of applying it, you must keep the cutter alive
-*and* hidden (`hide_render = hide_viewport = True`); both were verified on Blender 5.0.1 to
-keep it out of the GLB while the cut still happens.
-
-## 6. Multi-file wiring (static_object/blender only)
-
-```
-src/model.py imports every builder, calls each ONCE, then self-checks
-src/parts/seat_cushion.py def build_seat_cushion() -> bpy.types.Object (defines only)
-src/parts/_common.py shared helpers; the underscore means "not a part"
-```
-
-Three failure modes the lint reports, all of them silent at build time:
-
-* the part file exists but `model.py` never imports it -> the part is simply absent;
-* the part file calls its own builder at module level -> the part is built twice and the
- second copy is named `SeatCushion.001`;
-* the builder is named something other than `build_<snake of the plan name>` -> ImportError
- with a hint naming the exact function it expected.
-
-`urdf_blender` does not use this layout: one `src/model.py`, one mesh object per URDF link,
-object name equal to the link name, and `lint:urdf` checks that each link name appears
-verbatim in the file.
-
-## 7. A self-check worth writing
-
-```python
-def selfcheck(expected):
- names = sorted(o.name for o in bpy.data.objects if o.type == 'MESH')
- assert not [n for n in names if '.' in n], f"auto-suffixed: {names}"
- assert sorted(expected) == names, f"expected {sorted(expected)}, built {names}"
-```
-
-Two asserts, run at the end of `main()`, catch the missing part and the duplicated part
-before the build report does.
+A BOOLEAN modifier with `operation = 'DIFFERENCE'` and `solver` `'MANIFOLD'` (closed inputs),
+`'EXACT'` or `'FLOAT'` (`'FAST'` no longer exists). Applied with `modifier_apply` inside
+`bpy.context.temp_override(object=obj, active_object=obj, selected_objects=[obj])`, then
+remove the cutter with `bpy.data.objects.remove(cutter, do_unlink=True)` — or leave the
+modifier for the exporter and keep the cutter alive and hidden (`hide_render`), which keeps it
+out of the GLB while the cut still happens (measured on 5.2.2). A cutter coplanar with the
+face it cuts fails silently.
+
+## 6. Multi-file wiring
+
+The file layout, the builder names and the three silent failures the lint reports (a part
+file never imported, a builder called at import time, a builder not named
+`build_<snake>`) are the contract's `Files` section; the contract's executable example is
+the whole interface. `urdf_blender` does not use this layout: one `src/model.py`, the object
+named after each URDF link (plus anything parented under it, which the wrapper joins into the
+link's mesh), and `lint:urdf` checks that each link name appears verbatim in the file.
+
+## 7. The skeleton's self-check
+
+The skeleton's `model.py` ends with an optional `_selfcheck()`: it asserts that meshes exist and
+that no name is auto-suffixed, prints the lowest point, and fails the build only past the
+contract gate's ERROR line for the ground (3 × `GROUND_TOL_M`). Keep it, change it or delete
+it; `check_contract` and `check_connectivity` are the real census.
diff --git a/harness/codeverse3d/skills/c3d-bpy-scene-placement/SKILL.md b/harness/codeverse3d/skills/c3d-bpy-scene-placement/SKILL.md
index f221cc10..912815d7 100644
--- a/harness/codeverse3d/skills/c3d-bpy-scene-placement/SKILL.md
+++ b/harness/codeverse3d/skills/c3d-bpy-scene-placement/SKILL.md
@@ -141,7 +141,8 @@ time the harness samples (t = 0 and t = 1.5 s; the judge diffs the two frames an
`nothing_moves` when it sees no change). Motion is data: keyframes on `ctx.frame(t)` or a simple
driver of `frame` (`lib.motion.keyframe_path`, `drift`, `sway`, `spin`, `scroll`, `shape_key_sweep`
are these in one call; a driver that needs Python evaluates to 0 and the lint rejects it). A tree
-with its origin at its base sways about its feet; a boat drifting ON a water-named plane is
-`on_water`; a bird, a steam plume or a spark cloud built as one object is a `free` row.
+with its origin at its base sways about its feet (a keyed rotation turns about the origin: put
+it at the hinge or hub). A boat drifting ON a water-named plane is `on_water`; a bird, a steam
+plume or a spark cloud built as one object is a `free` row.
Worked zone, row provenance and the finding-to-fix table: `references/finding-to-fix.md`.
diff --git a/harness/codeverse3d/skills/c3d-cadquery-forms/SKILL.md b/harness/codeverse3d/skills/c3d-cadquery-forms/SKILL.md
index 92b41fd9..5b3c9a3d 100644
--- a/harness/codeverse3d/skills/c3d-cadquery-forms/SKILL.md
+++ b/harness/codeverse3d/skills/c3d-cadquery-forms/SKILL.md
@@ -1,6 +1,6 @@
---
name: c3d-cadquery-forms
-description: "Use when writing CadQuery src/model.py - baseline, part, detail, refine, rebuild or repair: build the planned forms and get past the OCC kernel. Gives the form-to-technique decision table, the fillet / revolve / boolean rules that decide whether the script builds at all, and the four traps our own lint and runtime wrapper are written to catch."
+description: "Use when writing CadQuery src/model.py - baseline, part, detail, refine, rebuild or repair: build the planned forms and get past the OCC kernel. Gives the kernel's native makers per form as an optional toolbox, the probed kernel rules that decide whether the script builds at all, a few strong optional practices, and the four traps our own lint and runtime wrapper are written to catch."
license: Apache-2.0
compatibility: CadQuery 2.8 on OCP; one module src/model.py exporting a module-level `result`.
metadata:
@@ -17,59 +17,77 @@ metadata:
# CadQuery: forms, and the kernel rules that gate them
**Evidence warning, read it once:** we have no graded CadQuery runs. The API rules below are
-verified against the installed kernel; the *priority order* is inferred, not measured.
+verified against the installed kernel; nothing here is ranked by measured defect frequency.
-## Form to technique
+## Form to technique — an optional toolbox
-Plans and judge feedback name language-neutral forms. Build each one as its own kind of
-solid — a revolved profile faked from stacked boxes reads as a blocky toy.
+The plan names language-neutral forms; the kernel has a native maker for most of them. These
+are options under their real API names, not a mapping to follow.
-| form | build it as |
+| form | a native option |
|---|---|
| slab / block / panel | `.box(x, y, z)`, `centered=(True, True, False)` to stand on zero |
| shaft / disc / cylinder | `.circle(r).extrude(h)`; `.cylinder(h, r)` takes height FIRST |
| revolved profile — vase, finial, baluster, dome, barrel | closed half-profile on `"XZ"` (`.polyline`/`.spline` + `.close()`) then `.revolve(360, (0,0,0), (0,1,0))`; keep the profile at radius >= 0 |
-| ring / band / torus | `.moveTo(R, 0).circle(r).revolve(angle, ...)` — see the revolve trap below |
-| extruded outline with softened edges | outline `.polyline().close().extrude(t)`, then `.edges("|Z").fillet(r)` |
+| ring / band / torus | `.moveTo(R, 0).circle(r).revolve(angle, ...)` — see kernel rule 1 |
+| extruded outline with softened edges | outline `.polyline().close().extrude(t)`, then `.edges("|Z").fillet(r)`; `cq.Sketch().rect().vertices().fillet()` for a rounded rectangle |
| tube swept along a path | `.circle(r).sweep(path)`; the profile plane must be perpendicular to the path start |
| tapered solid — horn, spout, mast | `.circle(r1).workplane(offset=h).circle(r2).loft()`, or `.extrude(h, taper=deg)` |
| lofted transition between sections | `.loft()` between profiles with matching vertex counts (circle to circle, rect to rect) |
-| shell with wall thickness | `.faces(">Z").shell(-t)` from ONE open face; never on a lofted round body — subtract a shrunken inner loft instead |
-| carved cavity / slot / bore | `.cut(cutter)`, `.hole(d)`, `.cutBlind(-depth)` |
+| shell with wall thickness | `.faces(">Z").shell(-t)` from ONE open face; the kernel refuses it on a lofted round body — subtract a shrunken inner loft instead |
+| carved cavity / slot / bore | `.cut(cutter)`, `.hole(d)`, `.cutBlind(-depth)`, `.slot2D(length, width)` |
| faceted solid — die, gem | `.polygon(n, d).extrude(h)`, facets via `taper=` or a loft between polygons |
-| radial array of N | `.polarArray(radius, start, angle, count)` before the feature; loops of `.union` only up to ~12 items |
+| repeated feature — grid, ring of N, point list | `.rarray(dx, dy, nx, ny)`, `.polarArray(radius, start, angle, count)` or `.pushPoints([...])` before the feature |
| mirror pair | `.mirror("XZ")` on the piece, then place both in the Assembly |
+| where a feature goes | string selectors `"|Z"`, `">Z"`, `"<Y"`, `"%CIRCLE"`, `"#Z"`; `cq.selectors.BoxSelector(p0, p1)` or `NearestToPointSelector(p)` when a rotated feature is invisible to the string form; `.faces(">Z").workplane()` / `.workplane(offset=h)` to build on a face |
+| embossed label | `.text(txt, size, depth)` — may raise headless (no fonts), so `try/except` it |
-## Kernel rules — probed against CadQuery 2.8.0 in this repo, 2026-08-25
+## Kernel rules — probed against CadQuery 2.8.0 in this repo
1. **`.center()` before a revolve is fatal; use `.moveTo()`.** `Workplane("XZ").center(R, 0)
.circle(r).revolve(360, ...)` raises `StdFail_NotDone: BRep_API: command not done`. The
identical chain with `.moveTo(R, 0)` builds a valid torus. `.center()` moves the
workplane origin, so the profile ends up sitting on the axis. Passing an explicit axis
does not rescue it — both forms fail.
-2. **Fillet failure is not monotone in the radius, so stay well under the budget.** On a
- 3 mm slab a top-rim fillet succeeded at 2.9 mm and failed at 3.0 mm; on a 3 mm shelled
- wall it succeeded at 1.4 mm, failed at 1.5 mm, succeeded again at 2.0 mm and failed at
- 3.0 mm. "Try a slightly bigger radius" is therefore not a strategy. Keep radii below
- **0.45 x the thinnest adjacent wall** — the budget the language contract states and the
- exact hint the runtime appends to every OCC refusal — fillet before booleans that would
- split the edge, biggest radii first, and wrap purely cosmetic fillets in `try/except`.
- (The common claim that the limit is half the shortest adjacent *edge* is false here: a
- 10 mm radius on a 10 mm vertical edge builds fine.)
-3. **A union that does not overlap fails silently.** Two spheres placed exactly tangent
+2. **A union that does not overlap fails silently.** Two spheres placed exactly tangent
union into **2 solids** and still report `isValid() == True`; the same pair with 0.5 mm
- of overlap gives 1 solid. `.isValid()` will not catch this and neither will a render.
- Assert `len(wp.solids().vals()) == 1` after every union and every cut — a through cut
- that splits a part also leaves 2 valid solids.
-4. **`.cut()` is for removing material only.** Do not union across plan boundaries; each
- plan part stays its own solid in the Assembly. Overshoot cutters by >= 0.1 mm.
-5. **Touching parts weld by overlapping 0.5-2 mm.** The CadQuery authoring contract's
- own figure, and the overlap its worked example uses; 2 mm is a ceiling, not a target,
- because the connectivity gate calls a deeper overlap interpenetration. Its contact and
- penetration thresholds are stated once, in `c3d-part-contact`, and not repeated here.
-6. **Keep solids closed.** Export runs through STL as well as GLB; `.shell()` keeps a solid
+ of overlap gives 1 solid. `.isValid()` will not catch this and neither will a render —
+ `check_connectivity` reports the second solid as a stray island. `len(wp.solids().vals())`
+ after a union or a cut catches it before a build; a through cut that splits a part also
+ leaves 2 valid solids.
+3. **Each plan part is its own Assembly child.** A pair unioned across a plan boundary reads
+ as a missing part in `check_contract`. Touching parts: a gap ≤ 2 mm is contact, overlap
+ > 2 mm is WARN, > 10 mm is ERROR (`check_connectivity`; the table is in `c3d-part-contact`).
+4. **Keep solids closed.** Export runs through STL as well as GLB; `.shell()` keeps a solid
watertight, hand-assembled faces do not.
-7. Feature sizes >= 0.5 mm (OCC's tolerance eats smaller).
+5. Features under ~0.5 mm come out invalid at OCC tolerance.
+
+## Strong options — optional practices
+
+**Fillets the kernel accepts.** Refusal is not monotone in the radius: on a 3 mm shelled
+wall a rim fillet passed at 1.4 mm, failed at 1.5 mm, passed again at 2.0 mm and failed at
+3.0 mm, so "try a slightly bigger radius" is not a strategy. A conservative budget (the
+hint the runtime prints after a refusal says 0.45 x the thinnest adjacent wall), few edges
+per `.fillet()` call, and `try/except` around fillets that are only cosmetic is the strong
+option. Whether a fillet goes before or after a boolean that touches its edge is not a rule
+either way — only the build result counts. Where `.fillet()` is refused on a thin wall, a
+`.cut()` with a rounded tool softens the same edge. (The claim that the limit is half the
+shortest adjacent *edge* is false here: a 10 mm radius on a 10 mm vertical edge builds.)
+
+**Mating faces.** A mating coordinate computed from the plan numbers of the face it meets
+lands inside the gate's contact band (flush counts) without nudging. A cutter that overshoots the face it exits avoids
+coplanar-face boolean failures; the coplanar case passed in this probe, so the overshoot is
+a habit, not a measured need.
+
+**Selectors after booleans.** Edge indices reshuffle after a boolean; re-select by geometry
+(`">Z"`, `BoxSelector`) rather than by a cached index, and print `len(wp.edges(sel).vals())`
+when a selector might match nothing — an empty selection raises `ValueError`.
+
+**Measure before you render.** Print per part what the gates read — `BoundingBox()` extents
+and `zmin`, `len(solids().vals())`, `Volume()`, `isValid()` — then the track loop: `build`
+-> `check_contract` -> `check_connectivity` -> `render_views`. `Volume()` catches
+hollow-when-it-should-be-solid, the solid count catches a split, `zmin` catches a floater,
+all before a render is spent.
## The four traps our own tooling is written to catch
@@ -86,12 +104,4 @@ solid — a revolved profile faked from stacked boxes reads as a blocky toy.
slot is a lint ERROR. Also `cq.Solid.makeSphere(r)` without angle arguments builds a
hemisphere (measured: z extent half of x and y); use `cq.Workplane("XY").sphere(r)`.
-## Before you finish
-
-Print the facts the harness will measure while you build — extents, `zmin`,
-`len(solids().vals())`, `Volume()`, `isValid()` per part — then `build` -> `render_sheet` ->
-`check_connectivity` -> `check_contract`. Code to copy: cookbook `cadquery` sections
-*Extrude, revolve, loft, sweep*, *Shell, fillet, chamfer — robustly*, *Booleans*,
-*Measure while you build*, *Pitfalls*.
-
More probe results and the failing/passing chains: `references/kernel-probes.md`.
diff --git a/harness/codeverse3d/skills/c3d-cadquery-forms/references/kernel-probes.md b/harness/codeverse3d/skills/c3d-cadquery-forms/references/kernel-probes.md
index a8df5e3f..e5bef153 100644
--- a/harness/codeverse3d/skills/c3d-cadquery-forms/references/kernel-probes.md
+++ b/harness/codeverse3d/skills/c3d-cadquery-forms/references/kernel-probes.md
@@ -40,10 +40,10 @@ Cylinder shelled to a 3 mm wall, then a rim fillet:
| result | ok | ok | ok | **fail** | ok | **fail** |
The failures are **not monotone** — 1.5 mm fails while 2.0 mm succeeds. That is the whole
-argument for a conservative fixed budget (0.45 x the thinnest adjacent wall, which is the
-number the contract states and the number the runtime prints when OCC refuses) plus
-`try/except` around fillets that are only cosmetic. Incrementally nudging the radius after a
-failure can appear to work and then break on a neighbouring part.
+argument for a conservative fixed budget (0.45 x the thinnest adjacent wall is the number the
+runtime prints when OCC refuses — a hint, not a gate) plus `try/except` around fillets that
+are only cosmetic. Incrementally nudging the radius after a failure can appear to work and
+then break on a neighbouring part.
## Booleans: the silent failures
@@ -57,8 +57,8 @@ failure can appear to work and then break on a neighbouring part.
`len(wp.solids().vals()) == 1` on anything that is supposed to be one part.
An exactly-coplanar cutter (top face flush with the block's face) succeeded in this probe
-and produced the same face count as an overshooting cutter — but the cookbook records the
-failing case, so keep the >= 0.1 mm overshoot as a habit rather than relying on luck.
+and produced the same face count as an overshooting cutter. No failing case was reproduced;
+an overshoot past the exit face is a habit, not a measured need.
## Sphere helper
diff --git a/harness/codeverse3d/skills/c3d-glsl-craft/SKILL.md b/harness/codeverse3d/skills/c3d-glsl-craft/SKILL.md
index 9a79112d..b45a24a1 100644
--- a/harness/codeverse3d/skills/c3d-glsl-craft/SKILL.md
+++ b/harness/codeverse3d/skills/c3d-glsl-craft/SKILL.md
@@ -1,12 +1,12 @@
---
name: c3d-glsl-craft
-description: "Use when writing, refining or repairing a glsl_shader fragment shader, or when gl_frames reports static, flicker or low detail. Craft rules for the shaders this harness judges: what the five sampled frames measure and where the real operating band is, how to build multi-scale structure that does not alias, how to make motion come from the mechanism instead of a uv scroll, and why an added radial falloff reads as a uniform glow instead of light shafts."
+description: "Use when writing, refining or repairing a glsl_shader fragment shader, or when gl_frames reports static, flicker or low detail. What the five sampled frames measure and where the real operating band is, what the shader_v2 judge names and charges for, and a short list of strong optional practices behind its recorded complaints: structure that does not alias, motion from the mechanism instead of a uv scroll, light as a path through a volume, exposure before colour."
license: Apache-2.0
compatibility: GLSL 330 core via moderngl, headless. One image pass (src/shader.frag), an optional src/common.glsl and one feedback pass (src/buffer_a.frag). The harness declares the uniforms; the contract lists them.
metadata:
evidence: mixed
- evidence_note: "Gate checks and rubric weights are read from live code (spatial/frame_stats.py, judges/rubrics/shader_v1.yaml). The corpus is thin: 9 graded glsl_shader runs, so every count below names its n and no rate is generalised."
- verified: "2026-08-25"
+ evidence_note: "Gate thresholds, caps and rubric weights are read from live code (spatial/frame_stats.py, judges/rubrics/shader_v2.yaml) and pinned in _claims. The corpus is thin: 9 graded glsl_shader runs mined 2026-08-25 under the previous rubric, so every count below names its n and no rate is generalised."
+ verified: "2026-10-15"
corpus: "9 graded glsl_shader runs (18 judged rounds) + 5 opengl_python runs, mined 2026-08-25"
target_metric: "mean_edge_density"
target_direction: "up"
@@ -17,140 +17,108 @@ metadata:
# What separates a graded shader from a demo
-**Read this if** you are writing `src/shader.frag`. The contract already tells you which
-uniforms exist and how to keep the maths NaN-free. This is the layer above that: what the
-measurement can and cannot see, and the four craft rules that the judge's complaints in this
-corpus actually name.
+**Read this if** you are writing `src/shader.frag`. The contract states the interface and
+what the harness measures; this sheet is the layer above it: what the measurement can and
+cannot see, and a few strong options that answer the judge's recorded complaints. None of
+them is a recipe — the brief decides what is on screen and how it is built.
## The gate is a floor, not the bar
`spatial/frame_stats.py` renders five frames — t = 0, 1, 2.5, 4, 6 s — and measures them:
-| what | fires when |
-|---|---|
-| static | consecutive frames barely differ |
-| flicker | a consecutive pair jumps by a large share of the image |
-| duplicate frames | two frames are identical (INFO) |
-| near-flat image | almost no pixel sits on a visible luminance edge |
-| black / blown | nearly every pixel is black (or white) in every frame; ERROR |
-
-Measured over the 9 graded glsl runs (mined 2026-08-25), **the gate fired zero findings**:
-mean frame-to-frame difference ranged 0.013 to 0.182 (median 0.082) and edge density 0.031
-to 0.464 (median 0.186). The three flicker warnings and one low-detail warning in the whole
-graphics corpus came from `opengl_python`, not from shaders. So clearing the gate proves
-nothing. What is actually low is the judge: over 18 judged rounds the weakest criteria are
-`technical_cleanliness` 0.597, `originality` 0.600, `colour_light` 0.606 and
-`visual_richness` 0.619 — and `visual_richness` carries the largest weight of the four
-(0.18) in `shader_v1`.
-
-One more measured hint, and it is only a hint at this n: across those 9 runs the rank
-correlation between the harness's **colourfulness** metric and the final score is **+0.75**,
-while edge density manages only +0.40 and frame-to-frame motion +0.20. With n = 9 that is
-not a law, but it says the palette is worth more attention than another fbm octave. The
-best-scoring run (0.92) is also the most colourful and the most detailed; the worst (0.30)
-is the flattest and greyest of the nine.
-
-The four rules below are aimed at exactly those four criteria.
-
-## 1. Structure at several scales, or it aliases
-
-`visual_richness` asks for "structure at several scales", and `technical_cleanliness`
-penalises aliasing and banding. In this corpus those are the *same* mistake seen twice — a
-recorded major issue reads: *the wall displacement is uniform high-frequency noise rather
-than multi-scale fractal relief, causing severe aliasing.* One octave at one frequency is
-both flat (no scales) and shimmery (nothing filters it).
-
-* Build relief as fbm and let the amplitude fall with the distance the pixel represents:
- drop octaves as `1/(1 + k*t)` where `t` is the ray distance or the screen-space scale.
-* Anti-alias every edge with a width, not a step: `smoothstep(-w, w, d)` with
- `w = 1.5 / u_resolution.y`, scaled by the local derivative if the feature is in
- perspective.
-* Raymarchers: grow the hit tolerance with distance (`eps = max(4e-4, 1.5e-3 * t)`) and take
- the normal with the same epsilon. The lowest-scoring run of the nine (0.30) was graded with
- a *critical* bug for "bright cyan/white pixels along the edges of all geometry at grazing
- angles" — that is a tangential overshoot feeding a central-difference normal.
-* Grade with a palette function, not a `mix` of two constants, and dither the last step
- (`col += (hash12(fragCoord) - 0.5) / 255.0`) — banding in a large gradient is a named
- `technical_cleanliness` deduction and one line removes it.
-
-## 2. Structure runs across the flow, not along it
-
-Water, wood, marble, cloth and stone all read wrong when the pattern is stretched *along*
-the direction of movement, because that is what a scrolling texture looks like. Warp the
-domain perpendicular to the flow and advect only the phase:
-
-```glsl
-vec2 flow = normalize(vec2(1.0, 0.35));
-vec2 across = vec2(-flow.y, flow.x);
-float band = fbm(p * vec2(2.0, 9.0) * mat2(across, flow) - flow * u_time * 0.6);
-```
-
-The high-frequency axis is the one across the flow. This is the difference between "a
-surface moving" and "a texture sliding", and it costs nothing.
-
-## 3. Motion comes from the mechanism
-
-`motion_quality` grades "the way the brief says … continuous, paced and plausible", and the
-frames it compares are 1 to 2 seconds apart. A single `uv + u_time * k` scroll gives the
-same delta everywhere and reads as a conveyor belt.
-
-* Drive each element from its own quantity: a drop falls with `t*t`, a flame's tips lag its
- base, a pendulum is `sin`, a spark is a hash-seeded lifetime.
-* Give every instance a phase from its id, `hash12(id) * 6.2831`, or the whole field pulses
- in lockstep and t = 0 is a suspiciously symmetric frame.
-* Keep it continuous. `fract()` and `mod()` of `u_time` are cuts; wrap through a smooth
- function or cross-fade the wrap. A cut between two sampled times is the `flicker` warning
- and a `technical_cleanliness` deduction.
-* Nothing may depend on `u_frame` alone: the sampled times are not evenly spaced.
-
-## 4. Light is a path through a volume, not a falloff around a point
-
-The sharpest recorded effect complaint in this corpus is: *distinct volumetric light shafts
-are missing; the lighting appears as a diffuse, uniform spherical glow rather than
-directional rays.* That is exactly what `col += A * exp(-k * dist)` produces — a radially
-symmetric blob, because the term has no direction and no occluder in it.
-
-A shaft is the integral of scattering along the view ray, so march the ray and, at each
-step, weight by the phase angle to the light and by whether that point is shadowed:
-
-```glsl
-float shaft = 0.0, t = 0.0;
-for (int i = 0; i < 48; i++) {
- vec3 pos = ro + rd * t;
- float vis = step(0.0, sdScene(pos + lightDir * 0.35)); // cheap occlusion probe
- float phase = 0.6 + 0.4 * pow(max(dot(rd, lightDir), 0.0), 8.0);
- shaft += vis * phase * exp(-0.08 * t);
- t += 0.12;
-}
-col += lightCol * shaft * 0.02;
-```
-
-The same principle covers the other "reads as the thing" cases: a lit cloud is brighter
-where the shell is *thin toward the light* (sample the density a short step toward the sun
-and take the difference), and a glass or water surface is a dielectric — a Fresnel-weighted
-reflection plus a tinted transmission, never a metallic tint.
+* `static` — the largest mean |Δ| between consecutive frames is under 0.002 (WARN, score cap 0.5 when motion is planned)
+* `flicker` — a consecutive pair differs by more than 0.35 of the image (WARN, cap 0.7)
+* `black` / `blown` — in every frame over 97 % of the pixels sit under luminance 0.03, or over 0.98 (ERROR, cap 0.5)
+* `low_detail` — almost no pixel sits on a visible luminance edge (WARN)
+* `nan` — any NaN / Inf pixel (ERROR, cap 0)
+
+Over the 9 graded glsl runs mined 2026-08-25 the gate fired nothing while the judge sat at
+0.55-0.65: clearing it proves nothing. The judge is `shader_v2`: likeness 0.26,
+depth_and_detail 0.16, light_and_tone 0.16, motion_quality 0.14, composition 0.10,
+technical_cleanliness 0.10, craft 0.08, plus the defect list the system prompt carries.
+One hint, and only a hint at n = 9: the harness's colourfulness metric (`gl_frames` prints
+it) ranked with the final score at +0.75, edge density at +0.40 and frame-to-frame motion at
++0.20 — the palette is worth more attention than another octave.
+
+## Strong options (none required; each answers a recorded complaint)
+
+**Scales.** One octave at one frequency is both flat (`flat_fill`) and shimmery
+(`banding_or_aliasing`): a recorded major issue reads "uniform high-frequency noise rather
+than multi-scale fractal relief, causing severe aliasing". Fine octaves smaller than a pixel
+alias — fade them with the distance or the footprint the pixel represents.
+
+**Edges.** A `step` aliases; a transition about one pixel wide (from `fwidth` or the
+resolution) does not. A staircase edge is the `banding_or_aliasing` defect.
+
+**Banding.** A long two-stop gradient bands on 8-bit output (3 of 6 fancy-battery runs,
+2026-08-31). A sub-LSB dither on the final colour — one hash per pixel, added after the
+tone-map and gamma — removes it.
+
+**Tone.** Additive light sums (glow, bokeh, scattering) pass 1.0 quickly: one tone-map at
+the very end keeps them under the `blown` threshold; gamma applied twice washes the frame
+(`white_wash`).
+
+**Exposure first.** Hue and palette work is invisible on dark, low-chroma pixels. Read the
+mean luminance `gl_frames` prints and compare it with what the brief's place would show
+before grading colour.
+
+**Night subjects.** The judge's `no_dark_range` and `white_wash` defects: a night, space or
+dusk frame needs near-black pixels somewhere, and haze and bloom belong on the light, not on
+the frame. `gl_frames` prints the mean luminance and the black-pixel fraction — read them.
+
+**Across the flow.** Water, wood, marble, cloth and stone read as a sliding texture when the
+pattern is stretched along the direction of movement (the judge's "texture scrolling under a
+fixed shape" is 0.5 on motion). Put the fine axis of the pattern across the flow and advect
+only the phase.
+
+**Motion from the mechanism.** The frames compared are 1-2 s apart; a single scroll of the
+uv by `u_time` gives the same delta everywhere and reads as a conveyor belt. Drive each
+element from its own quantity — a drop falls with the square of its time, a flame's tips lag
+its base, a spark has a hash-seeded lifetime — and give every instance a phase from its id so
+t = 0 is not a symmetric frame.
+
+**Continuity.** `fract` and `mod` of `u_time` are cuts; wrap through a smooth function,
+cross-fade the wrap, or hide it under a fade that reaches zero at the wrap. A visible cut
+between two sampled times is the `flicker` warning.
+
+**Domain warp.** Feeding fbm with fbm (IQ's domain warping) gives billowing edges to clouds,
+smoke and marble; it costs octaves, so budget them.
+
+**Volumes.** A shaft or a lit cloud is scattering integrated along the view ray: march front
+to back, attenuate by Beer-Lambert transmittance, weight each step by a phase function
+normalised over the sphere (Henyey-Greenstein, +1 forward, in light-travel directions — PBRT's
+convention differs) and by a short march toward the light for self-shadow. A radial falloff
+around a point has neither direction nor occluder: the sharpest recorded complaint, "a
+diffuse, uniform spherical glow rather than directional rays", is that term. A cloud is
+brighter where its shell is thin toward the light — sample the density a short step toward
+the sun and light the difference.
+
+**Surfaces.** A dielectric (glass, water) is a Fresnel-weighted reflection plus a tinted
+transmission; a metallic tint reads as metal, not glass. GGX with Smith visibility and Schlick Fresnel on linear
+inputs gives a microfacet response; roughness changes the highlight's shape, a shiny colour
+cannot.
+
+**Raymarchers.** A hit tolerance that grows with distance, the same epsilon for the normal,
+and a relaxed step. The critical bug of the lowest-scoring run (0.30) — "bright cyan/white
+pixels along the edges of all geometry at grazing angles" — was a tangential overshoot
+feeding a central-difference normal.
## The three uniforms worth designing around
-The contract declares them; what they are *for* is the craft:
-
-* `u_noise` — a 256x256 repeating RGBA noise texture with linear filtering. One `texture()`
- fetch replaces a hash and interpolation, so an fbm built on it is several times cheaper
- and lets you afford more octaves. Scale the uv, do not scale the result.
-* `u_prev` — this pass's previous frame. Trails, motion blur and accumulation, always with
- a decay under 1.0 and preferably a sub-pixel drift, or it saturates by t = 6 s.
-* `u_buffer_a` — a whole extra pass. Use it when the effect *is* a simulation (advection,
- reaction-diffusion, a height field): simulate in `buffer_a.frag`, shade in `shader.frag`.
- **No graded glsl run in this corpus used it (0 of 9)**, while **all five** critical effect
- failures recorded in the sibling opengl_python runs are simulations with nowhere to keep
- their state.
+* `u_noise` — one `texture` fetch is a bilinear-interpolated hash, several times cheaper
+ than a hash plus interpolation, so an fbm built on it affords more octaves. Scale the uv,
+ not the result.
+* `u_prev` — this pass's previous frame: trails, motion blur, accumulation. The contract
+ states when it saturates.
+* `u_buffer_a` — a whole extra pass. When the effect *is* a simulation (advection,
+ reaction-diffusion, a height field), simulate in `buffer_a.frag` and shade in
+ `shader.frag`. No graded glsl run in this corpus used it (0 of 9), while all five
+ critical effect failures recorded in the sibling opengl_python runs are simulations with
+ nowhere to keep their state.
## Before you finish
`gl_probe` compiles and shows frame 0; `gl_frames` renders all five judged times and prints
mean luminance, colourfulness, edge density and the per-pair deltas. Look at the contact
-sheet, then read the numbers: a mean delta near the bottom of the 0.013-0.182 band with a
-brief that promised motion means the motion is there but invisible.
-
-Worked snippets — fbm with distance-faded octaves, the flow-aligned warp, hash-phased
-instances and the dither — are in `references/shader-recipes.md`.
+sheet, then read the numbers: a largest delta just above the static threshold with a brief
+that promised motion means the motion is there but invisible.
diff --git a/harness/codeverse3d/skills/c3d-glsl-craft/references/shader-recipes.md b/harness/codeverse3d/skills/c3d-glsl-craft/references/shader-recipes.md
deleted file mode 100644
index bb085f6f..00000000
--- a/harness/codeverse3d/skills/c3d-glsl-craft/references/shader-recipes.md
+++ /dev/null
@@ -1,151 +0,0 @@
-# Shader recipes
-
-Companion to `c3d-glsl-craft`. Every snippet below was composed with the harness's own
-`codeverse3d.languages.glsl_shader.compose`, compiled on moderngl 5.12 / OpenGL 3.3 core
-and linted with `lint_text` on 2026-08-25: **compiles clean, zero lint findings**. Drop the
-helpers into `src/common.glsl` and call them from `src/shader.frag`.
-
-Assumed present (write them once in `common.glsl`):
-
-```glsl
-float hash12(vec2 p){ vec3 p3=fract(vec3(p.xyx)*0.1031); p3+=dot(p3,p3.yzx+33.33); return fract((p3.x+p3.y)*p3.z); }
-float vnoise(vec2 p){ vec2 i=floor(p), f=fract(p); vec2 u=f*f*(3.0-2.0*f);
- return mix(mix(hash12(i), hash12(i+vec2(1,0)), u.x),
- mix(hash12(i+vec2(0,1)), hash12(i+vec2(1,1)), u.x), u.y); }
-```
-
-Cheaper alternative for the base noise: `texture(u_noise, p * 0.004).r`. The harness's
-`u_noise` is a 256x256 repeating RGBA texture with linear filtering, so one fetch buys you a
-bilinear-interpolated hash and lets you afford two more octaves.
-
-## 1. fbm whose fine octaves fade with distance
-
-The fix for "uniform high-frequency noise causing severe aliasing". Pass the ray distance
-(raymarch) or the screen-space footprint (2D); far pixels get the low octaves only.
-
-```glsl
-float fbmFade(vec2 p, float dist){
- float v = 0.0, a = 0.5, w = 1.0;
- for (int i = 0; i < 6; i++) {
- float fade = 1.0 / (1.0 + 0.35 * dist * float(i));
- v += a * fade * vnoise(p); w += a * fade;
- p = p * 2.03 + 0.31; a *= 0.5;
- }
- return v / max(w, 1e-4);
-}
-```
-
-Normalising by the accumulated weight keeps the mean brightness constant as octaves drop
-out, so the horizon does not darken.
-
-## 2. Structure across the flow
-
-```glsl
-float acrossFlow(vec2 p, vec2 flow, float t){
- vec2 across = vec2(-flow.y, flow.x);
- mat2 basis = mat2(across, flow); // column 0 = across, column 1 = along
- return fbmFade((p * vec2(2.0, 9.0)) * basis - flow * t * 0.6, 0.0);
-}
-```
-
-`vec2(2.0, 9.0)` is the anisotropy: fine detail across, stretched along. Swap the two and
-the same code reads as a sliding texture instead of a moving surface. Wood grain, brushed
-metal, water and cloth are all this function with a different pair of numbers.
-
-## 3. Instances with their own phase and lifetime
-
-```glsl
-float sparks(vec2 p, float t){
- float acc = 0.0;
- for (int i = 0; i < 24; i++) {
- float id = float(i);
- float ph = hash12(vec2(id, 7.0)) * 6.2831;
- float life = fract(t * 0.4 + hash12(vec2(id, 3.0))); // each starts at its own point
- vec2 c = vec2(cos(ph), sin(ph)) * (0.15 + 0.35 * life);
- acc += smoothstep(0.02, 0.0, length(p - c)) * (1.0 - life);
- }
- return acc;
-}
-```
-
-Two things make it read: the per-id phase (so t = 0 is not a symmetric ring) and the
-`(1.0 - life)` fade, which hides the `fract` wrap. A wrap you can see is the `flicker`
-warning waiting to happen.
-
-## 4. A light shaft is a marched integral
-
-```glsl
-float shaft(vec3 ro, vec3 rd, vec3 lightDir){
- float s = 0.0, t = 0.0;
- for (int i = 0; i < 48; i++) {
- vec3 pos = ro + rd * t;
- float vis = step(0.0, sdScene(pos + lightDir * 0.35)); // is this point lit?
- float phase = 0.6 + 0.4 * pow(max(dot(rd, lightDir), 0.0), 8.0);
- s += vis * phase * exp(-0.08 * t);
- t += 0.12;
- }
- return s;
-}
-```
-
-`phase` is what makes the shaft directional — it peaks when you look toward the light — and
-`vis` is what makes it a *shaft* rather than a haze, because the beam is bright only where
-nothing occludes it. Replace `sdScene` with your own distance field, or with a shadow test
-against whatever is casting.
-
-The lit-cloud variant of the same idea: sample your density once at the point and once a
-short step toward the light, and light the difference.
-
-```glsl
-float dens = cloud(pos);
-float lit = cloud(pos + lightDir * 0.08);
-vec3 col = mix(SHADOW_COL, LIT_COL, clamp(0.9 - 3.0 * (lit - dens), 0.0, 1.0));
-```
-
-Thin toward the light means bright: that is the physical rule, and it is why a cloud lit
-this way has a silver edge and a flat `exp()` glow does not.
-
-## 5. The artifact that cost the worst run in this corpus
-
-The lowest-scoring glsl run (0.30 of 1.0) was graded with a **critical** bug: *severe
-raymarching artifacts (bright cyan/white pixels) along the edges of all geometry,
-particularly at grazing angles*. That is the march overshooting a surface it hits almost
-tangentially, so the central-difference normal is taken across the discontinuity and the
-shading term explodes. Three changes remove it:
-
-```glsl
-float eps = max(0.0004, 0.0015 * t); // hit tolerance grows with distance
-t += max(d * 0.85, eps); // relax the step; never step by the raw distance
-vec3 n = normalize(vec3(sdScene(pos + e.xyy) - sdScene(pos - e.xyy),
- sdScene(pos + e.yxy) - sdScene(pos - e.yxy),
- sdScene(pos + e.yyx) - sdScene(pos - e.yyx))); // e = vec2(eps, 0)
-```
-
-Use the *same* `eps` for the hit test and for the normal offset, and clamp the final colour.
-The same run also scored the lowest colourfulness of the nine (0.050) and was described as
-"washed-out, monochromatic greyish" — the two defects together are most of the 0.30.
-
-## 6. Two one-liners that move `technical_cleanliness`
-
-```glsl
-float w = 1.5 / u_resolution.y; // one pixel, in the centred p space
-float edge = smoothstep(-w, w, d); // never step(0.0, d)
-col += (hash12(fragCoord) - 0.5) / 255.0; // dither, kills gradient banding
-```
-
-Tone-map once, at the very end (`col = col / (1.0 + col)`), and never twice. Accumulated
-glow and bokeh sums blow past 1.0 quickly, and a blown frame is an ERROR.
-
-## 7. When to reach for `buffer_a.frag`
-
-Use the second pass when the effect **is** a simulation whose state must persist: advection,
-reaction-diffusion, a wave height field, a particle field with collisions. `buffer_a.frag`
-reads its own previous frame as `u_prev` and its four neighbours at `uv +- 1.0/u_resolution`;
-`shader.frag` then reads the result as `u_buffer_a` and only colours it.
-
-Zero of the 9 graded glsl runs in this corpus used it. In the sibling `opengl_python` runs,
-which have the same feedback mechanism, all five recorded critical effect issues are
-simulations that produced "expanding rings with empty interiors" or "high-frequency noise,
-black speckles and aliasing instead of smooth fluid filaments" — a simulation whose state
-does not persist between frames cannot advect anything. If the brief says "swirling ink",
-"advection" or "reaction diffusion", the state belongs in `buffer_a.frag`.
diff --git a/harness/codeverse3d/skills/c3d-opengl-pipeline/SKILL.md b/harness/codeverse3d/skills/c3d-opengl-pipeline/SKILL.md
index 0cd68e48..28169a94 100644
--- a/harness/codeverse3d/skills/c3d-opengl-pipeline/SKILL.md
+++ b/harness/codeverse3d/skills/c3d-opengl-pipeline/SKILL.md
@@ -1,12 +1,12 @@
---
name: c3d-opengl-pipeline
-description: "Use when writing an opengl_python / moderngl program, or when the gl_frames gate reported flicker, no motion or a near-flat image. Covers baseline, refine, repair and rebuild sessions: the setup / render contract, the sampled-time trap that breaks every feedback simulation, VAO and uniform mechanics, ping-pong FBOs, and the three richness rules the judge scores this language worst on."
+description: "Use when writing an opengl_python / moderngl program, or when the gl_frames gate reported flicker, no motion or a near-flat image. Covers baseline, refine, repair and rebuild sessions: the sampled-time trap that breaks every feedback simulation, what the frame gate and the judge measure on this language (edge density, motion delta, the acceptance items), and a few optional practices — full-screen passes, instancing, textures, your own framebuffers, linear light, GL state."
license: Apache-2.0
compatibility: OpenGL 3.3 core through moderngl, headless EGL; one module src/program.py, GLSL 330 core inline or in src/*.glsl.
metadata:
evidence: mixed
evidence_note: 'Thin but real, and labelled so in the body. 5 graded opengl_python runs across graphics_v1_flash and graphics_v2_flash, 10 judged rounds, recomputed 2026-08-25. The API facts come from the runtime wrapper and the lint, not from the corpus.'
- verified: "2026-08-25"
+ verified: "2026-10-15"
target_metric: "gl_frame_findings"
target_direction: "down"
target_unit: "findings per run"
@@ -16,13 +16,9 @@ metadata:
# The moderngl pipeline, and the two things that actually sink these runs
-## The contract in four lines
-
-`setup(ctx, width, height) -> state` is called **once**. `render(ctx, state, t, frame, fbo)`
-is called once per sampled time; `fbo` arrives already bound, cleared to black with depth 1,
-and with the viewport set. If you render into your own framebuffers you must call
-`fbo.use()` and reset `ctx.viewport` before the **final** pass — the harness reads that
-framebuffer and nothing else. Never create a context and never touch `ctx.screen`.
+Interface, sandbox, the moderngl build facts and the gate thresholds are in the language
+contract (`setup` / `render`, the harness `fbo`, the lint lists, the caps); this skill is the
+craft on top of it, and nothing below is a required shape.
## Trap 1: `render()` is sampled, not ticked
@@ -38,68 +34,83 @@ the seeds dies out"*, *"only expanding rings rather than labyrinthine patterns"*
only injected at t=0s"* and *"the ink dissipates far too quickly"*. Those are all the same
defect: five iterations of a solver that needed hundreds.
-The fix is to make the frame a pure function of `t`, and get the iterations inside
-`render()`:
-
-* pick a fixed simulation step, e.g. `DT = 1/120`, and run `n = round(t / DT)` steps;
-* keep the state and the time it represents in `state`; each call advances from
- `state["t_sim"]` to `t`, and **resets to the seed whenever `t < state["t_sim"]`** so an
- out-of-order or repeated sample still gives the same image;
-* bound the work per call (a fixed maximum number of steps);
-* inject sources as a function of `t`, not once at `frame == 0`.
+The requirement: the frame at `t` must not depend on which `t`s were rendered before (the
+tools re-render single times, and the build renders a sorted schedule). One strong way to
+meet it with a simulation: keep the state and the simulated time it represents in `state`;
+each call integrates from that time to `t` with a fixed step and a bounded step count, and
+resets to the seed whenever `t` is earlier than the state; inject sources as a function of
+the simulated time, not in a `frame == 0` branch. A worked description: `references/sampled-time.md`.
## Trap 2: motion has to be continuous *and* visible
-`gl_frames` measures the mean absolute difference between consecutive frames. Below
-**0.002** it calls the program static; above **0.35** it calls it flicker. Only one of our
-five opengl_python runs ever tripped this gate, but it tripped it in three separate rounds
-(max deltas 0.373, 0.392, 0.416, `ogl_hard_voxel_city`, final score 0.342), and the judge
-read the same frames as *"the camera motion is discontinuous or clips into a building,
-resulting in a hard cut"*. Since the samples are 1 to 2 s apart, a camera or a phase that
-is fine at 60 fps can still jump between samples. Drive every animated quantity
-from a smooth function of `t`, and check the amplitude *between the sampled times*, not per
-frame: `fract()`/`mod()` wraps and per-call randomness are the usual culprits.
-
-## API mechanics that cost a build
-
-* **Attribute names must match the shader's `in` names**, and the format string must match
- the byte layout: `[(vbo, "3f 3f", "in_pos", "in_normal"), (ibo, "3f 3f 1f/i", ...)]`. A
- wrong float count does not raise — it silently shuffles your data into garbage.
-* **numpy is row-major, GLSL is column-major**: `prog["u_mvp"].write(M.T.astype("f4").tobytes())`.
- Never `.value = m.tolist()`.
-* **`KeyError: 'u_x'`** means the compiler removed an unused uniform. Delete the assignment
- or guard with `if "u_x" in prog`.
-* **Your own FBOs need their own depth attachment and their own `.clear()`** — `ctx.clear()`
- clears whatever is bound. Disable `DEPTH_TEST` for full-screen passes.
-* **Ping-pong needs two textures**; never sample the one you are writing. Give a simulation
- state texture `NEAREST` filtering and clamped wrap — `LINEAR` diffuses the state a little
- every step and `repeat` wraps the domain — and store it as `f4`, not `f2` (half float
- clips near 65504 and quantises visibly in a feedback loop).
-* Textures need `.use(location=k)` **every frame** as well as `prog["u_tex"].value = k`.
-* `#version 330 core` on the first line of every shader string, `out vec4 fragColor;`, no
- `gl_FragColor`, no `attribute`/`varying`. Wide lines and `GL_QUADS` do not exist in core.
-* Seed with `np.random.default_rng(SEED)` in `setup`; no wall clock, no extra python module
- (the harness ignores anything but `src/program.py`, and the lint warns).
-
-## Make the image worth judging
+`gl_frames` takes the mean |Δ| of each consecutive pair of sampled frames: if the largest is
+below **0.002** the program is static (cap 0.5); if it exceeds **0.35** it is flicker (cap 0.7).
+Only one of our five opengl_python runs ever tripped this gate, but it tripped it in three
+separate rounds (max deltas 0.373, 0.392, 0.416, `ogl_hard_voxel_city`, final score 0.342),
+and the judge read the same frames as *"the camera motion is discontinuous or clips into a
+building, resulting in a hard cut"*. Since the samples are 1 to 2 s apart, a camera or a
+phase that is fine at 60 fps can still jump between samples. Check the change between the
+sampled times, not per frame: periodic wraps and per-call randomness are what has tripped
+the threshold.
+
+## What the gate and the judge measure on the image
Over 5 runs and 10 judged rounds (`graphics_v1_flash` + `graphics_v2_flash`, recomputed
-2026-08-25) this language's three weakest criteria are **originality 0.330**,
+2026-08-25) this language's three weakest criteria were **originality 0.330**,
**visual_richness 0.375** and **brief_fidelity 0.420** — the lowest three numbers anywhere
-in our corpus. The gate agrees from the other side: edge density below **0.002** is
-reported as *"a near-flat gradient"*.
-
-Three rules that answer exactly those readings:
-
-1. **Layer at least three depths.** Background, subject, foreground. One full-screen
- gradient with a shape on it is the flat-gradient finding waiting to happen; parallax
- between layers also supplies the frame-to-frame delta.
-2. **No single primitive carrying the frame.** Edge density comes from silhouettes and
- high-frequency shading — instanced geometry, particles, structure inside surfaces — not
- from a smooth ramp.
-3. **Spend the brief's own nouns.** `brief_fidelity` 0.420 says the frames were generic.
- Every named element in the brief should be findable in the image; build the named thing
- rather than an abstraction that gestures at it.
+in our corpus. What is measured behind them:
+
+* mean edge density over the judged frames — below **0.002** the gate reports *"a near-flat
+ gradient"* (`low_detail`, no cap; the judge sees the same frames) — and the frame-to-frame
+ delta above. Structure at more than one scale supplies both: silhouettes, instanced or
+ particle detail, texture inside surfaces. Parallax between elements at different depths is
+ one way to get the delta, not a required composition.
+* the acceptance items and key visuals of the plan — the judge checks each one against the
+ frames, and an unmet `must` item caps the score at 0.7. Build the named things so each is
+ findable in the judged frames; an abstraction that gestures at the brief scores as generic.
+
+## Practices (strong options, none required)
+
+**A full-screen pass.** Four clip-space vertices in a `ctx.buffer`, a `ctx.vertex_array` bound
+with `"2f"` to the vertex shader's `in vec2`, drawn as a triangle strip; the vertex shader
+derives uv from the clip position. A purely 2D brief can be one such pass driven by uniforms
+you set from `render` — a legitimate option, not the expected shape. Full-screen passes with
+DEPTH_TEST on draw nothing behind the previous depth: disable it for them.
+
+**Instancing.** A second buffer bound with `/i` formats and `vao.render(instances=n)` draws
+many copies in one call. A per-instance phase attribute lets the vertex shader animate each
+copy from `u_time` with no per-frame upload, which keeps the cost of a call flat under the
+build timeout; CPU-side updates go through `buffer.write(...)` at the same byte size
+(`buffer.orphan()` before a full rewrite).
+
+**Textures.** Procedural data from a seeded `np.random.default_rng(seed)` goes into
+`ctx.texture((w, h), components, data, dtype="f4")` or `ctx.texture3d(...)`; set `.filter` and
+`.repeat_x` / `.repeat_y` explicitly, and bind with `.use(location=k)` on every call before the
+draw that samples it.
+
+**Your own framebuffers.** `ctx.framebuffer(color_attachments=[tex], depth_attachment=...)`
+with a `ctx.depth_renderbuffer` when the pass needs occlusion. Ping-pong needs two textures —
+never sample the one you are writing. Give a simulation state texture `NEAREST` filtering and
+clamped wrap (`LINEAR` diffuses the state a little every step and `repeat` wraps the domain)
+and store it as `f4`, not `f2` (half float clips near 65504 and quantises visibly in a
+feedback loop). Several outputs from one pass are fragment-shader out variables with a
+layout location each, one colour attachment per location.
+
+**Light in linear, tonemap once.** Keep lighting and accumulation in linear HDR targets
+(`f2` / `f4`) and apply one tonemap plus gamma in the final pass into `fbo`; that is also what
+keeps the `blown` gate quiet when glow sums grow. With non-uniform scale, transform normals
+by the inverse-transpose of the model matrix. For a physically based surface a GGX / Schlick
+direct term in linear light is the usual choice — `c3d-glsl-craft` describes it; nothing is
+seeded into this language's workspace.
+
+**GL state.** The enables and blend modes you are likely to reach for:
+```python
+ctx.enable(moderngl.DEPTH_TEST); ctx.disable(moderngl.DEPTH_TEST)
+ctx.enable(moderngl.BLEND); ctx.blend_func = moderngl.SRC_ALPHA, moderngl.ONE_MINUS_SRC_ALPHA
+ctx.blend_func = moderngl.ONE, moderngl.ONE # additive glow
+ctx.enable(moderngl.CULL_FACE); ctx.front_face = "ccw"
+ctx.enable(moderngl.PROGRAM_POINT_SIZE) # gl_PointSize in the vertex shader, mode=moderngl.POINTS
+```
## Prove it
@@ -107,7 +118,4 @@ Three rules that answer exactly those readings:
`gl_frames` before finishing — it renders the judged times, returns the per-frame
luminance / colour / detail / motion table and runs the gate. **Look at the contact sheet.**
-Code to copy: cookbook `opengl_python` sections *VBO / VAO with interleaved attributes*,
-*Instancing*, *Uniforms and matrices*, *FBOs*, *PITFALLS*.
-
-A worked sampled-time feedback loop and the frame-metric table: `references/sampled-time.md`.
+How the schedule is built and what the gate measures: `references/sampled-time.md`.
diff --git a/harness/codeverse3d/skills/c3d-opengl-pipeline/references/sampled-time.md b/harness/codeverse3d/skills/c3d-opengl-pipeline/references/sampled-time.md
index b48e3feb..0fbef9ce 100644
--- a/harness/codeverse3d/skills/c3d-opengl-pipeline/references/sampled-time.md
+++ b/harness/codeverse3d/skills/c3d-opengl-pipeline/references/sampled-time.md
@@ -12,40 +12,23 @@ loop duration, always at least 3 samples). The preview GIF adds about a dozen mo
* the number of calls is not fixed, and `frame == 2` is not "the third judged frame";
* the gaps between judged frames are 1.0, 1.5, 1.5 and 2.0 seconds;
-* nothing guarantees the calls are the only ones, or that they will not be repeated.
+* nothing guarantees the calls are the only ones, or that they will not be repeated — the
+ `gl_probe` and `gl_frames` tools re-render single times in any order.
The only safe contract is the one the language contract already states: **the same `t` must
produce the same image.**
-## The shape of a correct feedback loop
-
-```python
-DT = 1.0 / 120.0 # simulation step
-MAX_STEPS = 4000 # bounded work per call
-
-def _reset(state):
- state["read"].write(state["seed_bytes"])
- state["t_sim"] = 0.0
-
-def _advance(ctx, state, t):
- if t < state["t_sim"] - 1e-6:
- _reset(state)
- n = min(MAX_STEPS, int(round((t - state["t_sim"]) / DT)))
- for _ in range(n):
- state["write_fbo"].use()
- state["read"].use(location=0)
- state["sim_vao"].render(mode=moderngl.TRIANGLE_STRIP)
- state["read"], state["write"] = state["write"], state["read"]
- state["read_fbo"], state["write_fbo"] = state["write_fbo"], state["read_fbo"]
- state["t_sim"] += n * DT
-```
-
-`render()` then calls `_advance(ctx, state, t)`, binds `fbo`, resets the viewport and draws
-the display pass from `state["read"]`. Note what this buys: t = 0 gets the seed, t = 6 gets
-720 steps instead of 5, and re-rendering an earlier time still produces the earlier image.
+## The shape of a correct feedback loop (one option, described, not prescribed)
+
+Store the simulated time next to the state texture in `state`. On each call, if `t` is earlier
+than that time, reset the state to its seed; then step from the stored time to `t` with a fixed
+step and a bounded step count, each step drawing the read texture into the write framebuffer
+and swapping the pair. Finally bind `fbo`, reset the viewport and draw the display pass from
+the read texture. What this buys: the earliest sample shows the seed, the last sample the
+fully integrated state, and re-rendering an earlier time gives the earlier image.
Sources (ink injections, seeds, disturbances) belong inside the step loop as a function of
-the simulated time, not in a `if frame == 0:` branch — the judge explicitly marked one of
+the simulated time, not in a `frame == 0` branch — the judge explicitly marked one of
our runs down for *"ink is only injected at t=0s"*.
## State texture settings that matter
@@ -59,17 +42,18 @@ our runs down for *"ink is only injected at t=0s"*.
## The frame metrics the gate reads
-`codeverse3d/spatial/frame_stats.py`:
-
-| metric | fires when | finding |
-|---|---|---|
-| mean abs frame-to-frame delta | frames barely differ | static (WARN) |
-| mean abs frame-to-frame delta | a pair jumps by a large share of the image | flicker (WARN) |
-| consecutive frames identical | two frames are the same | duplicate (INFO) |
-| mean edge density | almost no visible edges | near-flat gradient (WARN) |
-| mean luminance | near-black in all frames | black (ERROR) |
-| mean luminance | near-white in all frames | blown (ERROR) |
-| any NaN / Inf pixel | any | ERROR |
+`codeverse3d/spatial/frame_stats.py`, on the judged frames; the cap is the highest score the
+round can then get:
+
+| metric | threshold | finding | cap |
+|---|---|---|---|
+| largest mean abs delta between consecutive frames | < 0.002 (motion planned) | static (WARN) | 0.5 |
+| largest mean abs delta between consecutive frames | > 0.35 | flicker (WARN) | 0.7 |
+| a consecutive pair's mean abs delta | < 1e-4 | duplicate (INFO) | — |
+| mean edge density | < 0.002 | near-flat gradient (`low_detail`, WARN) | — |
+| pixels under luminance 0.03 | over 97 % in every frame | black (ERROR) | 0.5 |
+| pixels over luminance 0.98 | over 97 % in every frame | blown (ERROR) | 0.5 |
+| any NaN / Inf pixel | ≥ 1 | nan (ERROR) | 0 |
## Measured deltas from our own runs
diff --git a/harness/codeverse3d/skills/c3d-part-contact/SKILL.md b/harness/codeverse3d/skills/c3d-part-contact/SKILL.md
index a57d6e46..4f3c5126 100644
--- a/harness/codeverse3d/skills/c3d-part-contact/SKILL.md
+++ b/harness/codeverse3d/skills/c3d-part-contact/SKILL.md
@@ -5,7 +5,7 @@ license: Apache-2.0
compatibility: Object tracks only (static_object, articulated_object). Needs the connectivity gate, i.e. an exported object.glb; scene and graphics tracks have no part graph.
metadata:
evidence: measured
- verified: "2026-08-25"
+ verified: "2026-10-15"
corpus: "142 graded runs with gate artefacts (102 blender, 23 urdf_blender), mined 2026-08-25"
target_metric: "interpenetrating_pairs"
target_direction: "down"
@@ -54,22 +54,20 @@ So: fewer pairs in contact, and each contact within the band below.
| a part too small to check | `MIN_PART_SIZE_M` | largest extent < **10 mm** | skipped for contact, penetration and islands (INFO only) |
| a crumb inside one part | `TINY_ISLAND_FRACTION` | island extent < **5%** of the part's largest extent | WARN "stray geometry" |
-**The whole legal window for a joint is 2 mm of gap to 2 mm of overlap.** Aim for
-**0.5-1.5 mm of overlap** and you are inside it with margin on both sides. Two traps follow
-directly:
+**The whole legal window for a joint is 2 mm of gap to 2 mm of overlap**, flush (a gap of 0)
+included — no overlap is required. Two traps follow directly:
* Do not "fix" an interpenetration WARN by pulling the parts apart. Past 2 mm of gap the
contact edge disappears and the part can drop out of the support component — a WARN
becomes an ERROR that caps the run at 0.60.
-* Do not use a fat weld. Measured by running the gate's own `penetration_depth` on the
- stool geometry the blender contract's example builds — a rod driven into a seat disc:
+* An overlap of exactly 2 mm already reads WARN. Measured with the gate's own
+ `penetration_depth` on a rod driven into a disc:
- | weld overlap | reported depth | fraction inside | gate |
+ | overlap | reported depth | fraction inside | gate |
|---|---|---|---|
| 4.0 mm | 4.00 mm | 2.8% | **WARN** |
| 2.0 mm | 2.00 mm | 2.7% | **WARN** (right on the line) |
| 1.0 mm | 1.00 mm | 2.5% | clean |
- | 0.5 mm | 0.50 mm | 2.3% | clean |
## Floating parts: never guess the fix
@@ -86,27 +84,26 @@ The vector is converted into **your** authoring frame before it is printed, and
alternative ("extend it by N mm") is usually the better one: translating a leg leaves a gap
at its other end. Apply one of the two literally. Do not eyeball a new position.
-## Plan the contacts before you write code
+## Know the contacts before you write code
-For every part with `attach_to` set, write one line first:
-
- <part> meets <neighbour> on <which face/axis>, at <coordinate>, overlap 1 mm
-
-Then derive the part's span **from the neighbour's plan bbox**, never from a re-typed
-number: a leg's top is `seat.bbox.min.z + 0.001`, not `0.451`. Any hand-typed span is a
-future contract finding as soon as the neighbour moves. (`c3d-bbox-contract` owns the
-tolerance arithmetic; this skill only says where the number comes from.)
+A strong option: before coding, note for each part with `attach_to` set which face meets
+which neighbour, and at what coordinate, and compute that coordinate from the neighbour's
+plan bbox rather than retyping it — a computed end follows the neighbour when it moves in a
+later round. (`c3d-bbox-contract` owns the tolerance arithmetic.)
## Detail belongs INSIDE a part, not as more parts
N top-level parts create N(N-1)/2 candidate contact pairs, and the count of penetrating
-pairs is what predicts the score. Sub-shapes inside one part create **none**.
+pairs is what predicts the score. Sub-shapes inside one part create **none**. Measured over
+183 judged rounds on this harness: ρ(triangles per part, `geometry_detail`) ≈ +0.08 while
+ρ(number of plan parts, `assembly_fit`) = −0.48 — triangles inside a part are free, extra
+top-level parts are not.
`PartPlan.children` is exactly this device — the docstring says sub-parts of an assembly
part are "still ONE named object in the export" — and `spatial/measure.py::part_meshes`
backs it up: a part is an effective top-level node and *its whole subtree is merged* into
-one mesh before any pairwise test runs. Verified on Blender 5.0.1: three disjoint sub-shapes built
-into one mesh named `Housing` export as a single part.
+one mesh before any pairwise test runs. Measured on Blender 5.2.2 through the wrapper: three
+disjoint sub-shapes built into one mesh named `Housing` export as a single node.
**But fusing is not optional.** Islands are split by *face connectivity*, not by overlap —
verified against the gate: a rivet placed so it geometrically overlaps a panel, without shared
@@ -119,12 +116,13 @@ topology, is still a separate island. So a sub-shape must be either
## Where crumbs actually come from
-* **A cutter object left in the scene.** Verified on Blender 5.0.1: the exporter selects every
+* **A cutter object left in the scene.** Measured on Blender 5.2.2: the exporter selects every
visible mesh, so an un-hidden boolean cutter exports as its own part — with its own
interpenetration and its own floating ERROR. Apply the boolean and delete the cutter, or
set `hide_render` / `hide_viewport` / `hide_set(True)` on it; all three keep it out of the
export and the boolean still evaluates.
-* Boolean leftovers and slivers — use the EXACT or MANIFOLD solver, never FLOAT/FAST.
+* Boolean leftovers and slivers — check the result with `check_connectivity`. The solvers on
+ 5.2.2 are `EXACT`, `MANIFOLD` (closed inputs) and `FLOAT`; `'FAST'` is a lint ERROR.
* A mirrored half that was never merged, and zero-thickness or coincident faces.
## Verify with the gate, do not re-implement it
diff --git a/harness/codeverse3d/skills/c3d-part-contact/references/contact-recipes.md b/harness/codeverse3d/skills/c3d-part-contact/references/contact-recipes.md
index 95133531..7ae6269a 100644
--- a/harness/codeverse3d/skills/c3d-part-contact/references/contact-recipes.md
+++ b/harness/codeverse3d/skills/c3d-part-contact/references/contact-recipes.md
@@ -1,7 +1,7 @@
# Contact recipes and the finding-to-fix table
Companion to `c3d-part-contact`. Everything here was checked against
-`codeverse3d/spatial/connectivity.py`, `codeverse3d/spatial/measure.py`, the Blender 5.0.1
+`codeverse3d/spatial/connectivity.py`, `codeverse3d/spatial/measure.py`, the Blender 5.2.2
wrapper in `codeverse3d/languages/wrappers/run_bpy.py`, and the recorded gate
findings under `bench/out/**/artifacts/gates/**` (mined 2026-08-25).
@@ -9,7 +9,7 @@ findings under `bench/out/**/artifacts/gates/**` (mined 2026-08-25).
| finding (verbatim shape) | severity | what it means | do this |
|---|---|---|---|
-| `'A' and 'B' interpenetrate by ~N mm (F% of surface samples inside)` | WARN below 10 mm, ERROR above | the deepest sampled point of one part is N mm inside the other, and at least 2% of one part's surface samples are inside | shorten or move the *smaller* part so the overlap is 0.5-1.5 mm; if N is large the two parts are modelling the same volume twice, so delete one |
+| `'A' and 'B' interpenetrate by ~N mm (F% of surface samples inside)` | WARN below 10 mm, ERROR above | the deepest sampled point of one part is N mm inside the other, and at least 2% of one part's surface samples are inside | shorten or move the *smaller* part so the overlap is at most 2 mm (flush is contact too); if N is large the two parts are modelling the same volume twice, so delete one |
| `part 'X' is floating: nearest supported part is 'Y' at N mm` | always ERROR (cap 0.60) | X is not in the ground-touching component | apply the printed translation, or extend X by N mm toward Y; prefer extending |
| `part 'X' is floating: touches nothing` | ERROR | X shares no AABB neighbourhood with anything | it is in the wrong place by more than its own size — recompute its origin from its neighbour's plan bbox |
| `no part touches the ground (z=0)` | WARN | the whole model is off the floor | move the assembly, not one part |
@@ -20,20 +20,15 @@ Recorded example depths, all real (`bench/out`, mined 2026-08-25): the median re
interpenetration is **5.0 mm** over 1,088 findings, and **86%** of them are under the 10 mm
ERROR line — i.e. the typical failure is a WARN that nobody fixed, not a catastrophe.
-## 2. bpy: derive the span, weld 1 mm
+## 2. Derive a span from the neighbour's plan bbox (an option)
-```python
-SEAT_Z, SEAT_T = 0.45, 0.04 # from plan.parts["Seat"].bbox
-WELD = 0.001 # 1 mm: inside CONTACT_GAP_M, under PENETRATION_WARN_M
-LEG_H = SEAT_Z - SEAT_T + WELD # reaches 1 mm into the seat -- NOT a re-typed 0.411
-```
-
-The point is `SEAT_Z - SEAT_T`: when the seat moves in a later round the leg follows. A
-literal `0.411` is a `contract/part_bbox` finding waiting to happen.
+A coordinate computed from the neighbour's plan numbers (its `min` / `max` on the shared
+axis) follows the neighbour when it moves in a later round; a retyped literal is a
+`contract/part_bbox` finding waiting to happen. Any end inside the band above is contact.
## 3. bpy: three sub-shapes, ONE part
-Verified on Blender 5.0.1: this exports as a single node `Housing`, so no pair-wise
+Measured on Blender 5.2.2 through the wrapper: this exports as a single node `Housing`, so no pair-wise
penetration test can ever run inside it.
```python
@@ -76,22 +71,22 @@ cutter.hide_render = True # any of hide_render / hide_viewport / hide_s
cutter.hide_viewport = True # keeps it out of the export; the boolean still evaluates
```
-Verified on Blender 5.0.1 with the harness's exact export call: with no flag set, the GLB
-came back with two parts (`Base`, `Cutter`); with any one flag set it came back with one,
-and the notch was still cut.
+Measured on Blender 5.2.2 through the wrapper's export call: with no flag set, the GLB
+came back with the cutter as its own node (`Base`, `Cutter`); with `hide_render` set it came
+back without it, and the notch was still cut.
## 5. CadQuery
Not corpus-backed — this language has **zero graded bench runs**; the rules below are read
-off `codeverse3d/prompts/cadquery/cookbook.md` and the same gate constants.
+off the same gate constants.
-* One `Workplane` result per plan part, and `len(result.solids().vals()) == 1` after every
- cut: a cut that splits a part into two solids is exactly the stray-island WARN in advance.
+* Each plan part is its own Assembly child; `len(result.solids().vals())` after a cut tells you
+ early when it split a part into two solids — the stray-island WARN in advance.
* Weld with `.union(other).clean()` — `clean()` merges the coplanar faces so the result is
one solid, not two touching ones.
-* Cutters must overshoot the face they pierce (the cookbook says >= 0.1 mm; coplanar faces
- make the boolean fail silently), but the *part-to-part* overlap still has to land in the
- 0.5-1.5 mm band.
+* Overshooting a cutter past the face it pierces is a cheap habit (a coplanar cut passed in
+ `c3d-cadquery-forms`' kernel probe, so it is not a measured need); the *part-to-part* overlap is
+ what the gate measures: at most 2 mm before the WARN.
## 6. URDF (articulated_object)
diff --git a/harness/codeverse3d/skills/c3d-repeats-and-mirrors/SKILL.md b/harness/codeverse3d/skills/c3d-repeats-and-mirrors/SKILL.md
index 4a658f73..560c52c9 100644
--- a/harness/codeverse3d/skills/c3d-repeats-and-mirrors/SKILL.md
+++ b/harness/codeverse3d/skills/c3d-repeats-and-mirrors/SKILL.md
@@ -5,7 +5,7 @@ license: Apache-2.0
compatibility: static_object and articulated_object tracks; blender, urdf_blender, cadquery and threejs. Numbers are from codeverse3d/spatial/contract.py and conventions.py.
metadata:
evidence: measured
- verified: "2026-08-25"
+ verified: "2026-10-15"
corpus: "217 run records / 2,121 gate reports under bench/out, mined 2026-08-25"
owns: "contract/instance_bbox, contract/instance_count"
target_metric: "contract_instance_findings"
@@ -20,8 +20,8 @@ metadata:
**When:** a plan row says `instances > 1`, or `symmetry` is `mirror_x` / `mirror_y` / `radial`,
or the brief asks for a ring / row / pair of the same thing. Skip if every part is unique.
-**The one move:** build the shape ONCE, then place N copies from a loop whose numbers come out
-of the plan row. A hand-typed second copy is how the pair stops matching.
+**A strong option:** build the shape once and place the copies from a loop whose numbers come
+out of the plan row — a hand-typed second copy is how a pair stops matching.
## What the gate actually measures
@@ -38,8 +38,8 @@ of the plan row. A hand-typed second copy is how the pair stops matching.
* `(each instance)` — the *worst single copy's* extents against the plan extents;
* `(all instances)` — the *union* bbox of all copies against the plan extents.
Satisfying either one clears the finding. The plan's bbox for an instanced row describes
- **one copy** at a representative location (see `tracks/plan_examples.py`: `Leg`,
- `instances: 2`, extents `0.035 x 0.035 x 0.41`), so build each copy at those extents and the
+ **one copy** at a representative location (see `tracks/planner.py::plan_example`: `Upright`,
+ `instances: 4`, the extents of one bar), so build each copy at those extents and the
`(each instance)` reading goes to zero.
* **Tolerance.** Per axis `tol = max(0.01 m, 0.10 x plan extent)`; beyond `3.0 x tol` the WARN
becomes an ERROR. Same constants as `c3d-bbox-contract` (`BBOX_TOLERANCE_M`, `REL_TOL`,
@@ -62,30 +62,32 @@ bug, N findings in a different gate.
## Placement: derive from the plan, not from the keyboard
```python
-# plan row: Leg - extents (0.035, 0.035, 0.410) m, centre (0.170, -0.160, 0.205), instances 4
-EX = (0.035, 0.035, 0.410)
-X, Y, Z = 0.170, 0.160, 0.205 # |x|, |y| and z read off the plan centre
-leg0 = make_box("Leg_0", EX, (X, -Y, Z)) # ONE build call ...
-for i, (sx, sy) in enumerate(((-1, -1), (-1, 1), (1, 1)), start=1):
- linked_copy(leg0, f"Leg_{i}", (sx * X, sy * Y, Z)) # ... N placements
+# plan row: Name - extents EX, instances N; CENTRES = the N copy centres the row's symmetry gives
+first = build_mesh("Name_0", EX, CENTRES[0]) # ONE build of the mesh data ...
+for i, c in enumerate(CENTRES[1:], start=1):
+ copy = bpy.data.objects.new(f"Name_{i}", first.data) # ... N objects sharing it
+ copy.location = c
+ bpy.context.scene.collection.objects.link(copy)
```
-Every copy inherits the extents, so `(each instance)` cannot drift. If a copy must differ,
+Shared mesh data means every copy has the same extents by construction, so `(each instance)`
+cannot drift. If a copy must differ,
that is a different plan part, not an instance.
## Radial arrays: the angle comes from the count
```python
-n = 6 # never a typed list of angles
+n = 6 # the count drives the angles
for i in range(n):
a = 2.0 * math.pi * i / n
- make_box(f"Spoke_{i}", EXT, (R * math.cos(a), R * math.sin(a), Z))
+ place(f"Spoke_{i}", (R * math.cos(a), R * math.sin(a), Z), yaw=a)
```
A typed list silently drops or duplicates a step when the count changes, and the gate then
reports a count mismatch it took you a round to see. For repeated *detail inside one part*
-(flutes, dentils, cage wires) use the cookbook's `radial_array` ARRAY modifier instead: that
-stays ONE export node, which is what the plan asked for.
+(flutes, dentils, cage wires) an ARRAY modifier with `use_object_offset` and an Empty
+rotated 2π/n is the option (apply it and delete the Empty — only meshes reach the export):
+one export node, which is what the plan asked for.
## Mirrors
@@ -114,10 +116,10 @@ The judge penalises both ends, so read the brief before looping:
distinct smaller thumb loop and larger multi-finger loop"* — 3 findings, `major`, urdf. When
the brief distinguishes the members, they are **separate plan parts**, not instances.
* Too same: *"Cliff walls are composed of identical, rigidly stacked blocks arranged in perfectly
- straight lines, lacking any organic shape"* — `critical`. For natural repeats, seed a small
- per-copy jitter (the cookbook's `varied_copies`: 1-2 % scale, sub-millimetre offset, under a
- degree of tilt). Keep the jitter well inside `0.10 x extent` so it cannot cost you a
- contract finding.
+ straight lines, lacking any organic shape"* — `critical`. For natural repeats, give copies a
+ seeded per-copy variation in scale and rotation small enough to stay inside the contract
+ tolerance (`max(0.01 m, 0.10 x extent)` per axis) so it cannot cost you a contract finding
+ — see references §6.
## Finish
diff --git a/harness/codeverse3d/skills/c3d-repeats-and-mirrors/references/instances.md b/harness/codeverse3d/skills/c3d-repeats-and-mirrors/references/instances.md
index 66b55e58..a3da50a4 100644
--- a/harness/codeverse3d/skills/c3d-repeats-and-mirrors/references/instances.md
+++ b/harness/codeverse3d/skills/c3d-repeats-and-mirrors/references/instances.md
@@ -2,8 +2,8 @@
Everything here was read out of the live harness on 2026-08-25:
`codeverse3d/spatial/contract.py`, `codeverse3d/contracts/plan.py`,
-`codeverse3d/conventions.py`, `codeverse3d/tracks/planner.py`,
-`codeverse3d/prompts/blender/cookbook.md`, and 2,121 gate reports under `bench/out`.
+`codeverse3d/conventions.py`, `codeverse3d/tracks/planner.py`, and 2,121 gate reports under
+`bench/out`.
## 1. Exactly how the gate matches a name to a plan part
@@ -111,18 +111,20 @@ def linked_copy(src, name, location):
o.location = location
o.rotation_euler = src.rotation_euler
o.scale = src.scale
- return link(o)
+ bpy.context.scene.collection.objects.link(o)
+ return o
```
-* Mirror inside one part: `add_mirror(obj, 'X')` then `apply_modifiers(obj)`. Move the **mesh**
- off the plane (`obj.data.transform(Matrix.Translation((-dx, 0, 0)))`) so the object origin
- stays on x = 0 — the modifier mirrors across the origin plane, not across the world.
-* Repeated detail inside one part: ARRAY modifier (`add_array`) for rows,
- `radial_array(obj, count)` for rings. Both produce ONE object, which is what a single plan
- part must export as.
+* Mirror inside one part: a MIRROR modifier (`use_clip`, origin on the symmetry plane), then
+ apply. Move the **mesh** off the plane (`obj.data.transform(Matrix.Translation((-dx, 0, 0)))`)
+ so the object origin stays on x = 0 — the modifier mirrors across the origin plane, not
+ across the world.
+* Repeated detail inside one part: an ARRAY modifier with a constant offset for rows, or
+ `use_object_offset` with an Empty rotated 2π/n for rings (apply, then delete the Empty).
+ Both produce ONE object, which is what a single plan part must export as.
* `bpy.ops.mesh.primitive_cube_add(scale=...)` without `size=1` builds a 2 m cube times the
- scale — every extent doubles. `lint:blender` flags it. Prefer the cookbook's bmesh
- `make_box`.
+ scale — every extent doubles. `lint:blender` flags it. `bmesh.ops.create_cube(bm, size=1)`
+ + `bmesh.ops.scale` needs no operator context and gives exact extents.
* For a URDF pair, each copy is its **own link** with its own joint and pivot. Instancing is a
Blender convenience; the URDF still needs `left_wheel` and `right_wheel` as separate links.
@@ -144,10 +146,11 @@ slivers behind.
### three.js
-`InstancedMesh` is one draw call but also **one node** — good for scenery, wrong for a plan row
-that must be measured per copy. When the plan names `instances: N` and the gate must see N
-nodes, emit N `THREE.Mesh` objects sharing one geometry, named `Name_0..Name_{N-1}`, added at
-the top level of the exported group.
+The exporter bakes an `InstancedMesh` named `Name` into sibling meshes `Name_0 … Name_{N-1}`
+where it stood (instance matrices and colours baked; the contract's Materials section), so the
+gate sees N copies either way: at the top level of the exported group they are the plan row's
+instances; inside a part's Group they are pieces of that part. N `THREE.Mesh` objects sharing
+one geometry give the same nodes.
## 6. Jitter that is safe
@@ -156,5 +159,4 @@ a 4 cm part is `max(0.01, 0.10 * 0.04) = 0.01 m` — an absolute 10 mm floor, ge
1 m part it is 0.10 m. Scale jitter of 1-2 % is therefore always safe; position jitter is free
because the centre is not checked for instanced parts. Rotation jitter can enlarge a copy's
axis-aligned bbox: a 0.6 degree tilt on a 0.41 m leg adds about 4 mm to the x extent, which is
-inside the 10 mm floor but not inside a 1 % budget on a 5 cm part. Keep tilt under 1 degree on
-parts smaller than 10 cm.
+inside the 10 mm floor.
diff --git a/harness/codeverse3d/skills/c3d-threejs-forms/SKILL.md b/harness/codeverse3d/skills/c3d-threejs-forms/SKILL.md
index 5bec63a3..992ed0cb 100644
--- a/harness/codeverse3d/skills/c3d-threejs-forms/SKILL.md
+++ b/harness/codeverse3d/skills/c3d-threejs-forms/SKILL.md
@@ -1,12 +1,12 @@
---
name: c3d-threejs-forms
-description: "Use when writing three.js object geometry in src/object.js or src/parts/*.js on the static_object track, in any session kind. Turn each FORM word in your manifest into the right three.js geometry maker, with the segment counts that make curves read and the traps that make a threejs part silently ship nothing. Covers the fact that this language has no boolean/CSG at all, so cavities and shells are built into the profile instead of subtracted."
+description: "Use when writing three.js object geometry in src/object.js or src/parts/*.js on the static_object track, in any session kind. Maps each FORM word in your manifest to the three.js geometry maker that produces it, names the traps that make a threejs part silently ship nothing, and states that this language has no boolean/CSG at all, so cavities and shells are built into the profile instead of subtracted. Options, not a recipe: what the part is made of is the brief's."
license: Apache-2.0
compatibility: "static_object track, language threejs. three r182 ESM in node, exported to GLB by the harness. Imports that resolve: three, three/addons/*, relative files under src/."
metadata:
evidence: inherited-unverified
- evidence_note: "Zero graded threejs bench runs exist (bench/out/*/runs/*, checked 2026-08-25); the only recorded threejs run is runs/e2e_bench_threejs. Every API claim here is verified against codeverse3d/prompts/threejs/contract.md, codeverse3d/prompts/threejs/cookbook.md, codeverse3d/languages/threejs/__init__.py and runtime_js/package.json, but the ADVICE has not been A/B'd on our corpus. Routed by default since 2026-09-22 (C3D_SKILLS_UNVERIFIED=0 drops it); upgrade to measured when threejs reaches 20 graded runs."
- verified: "2026-08-25"
+ evidence_note: "Zero graded threejs bench runs exist (bench/out/*/runs/*, checked 2026-08-25); the only recorded threejs run is runs/e2e_bench_threejs. Every API claim here is verified against codeverse3d/prompts/threejs/contract.md, codeverse3d/languages/threejs/__init__.py, runtime_js/export_glb.mjs and runtime_js/package.json, but the ADVICE has not been A/B'd on our corpus. Routed by default since 2026-09-22 (C3D_SKILLS_UNVERIFIED=0 drops it); upgrade to measured when threejs reaches 20 graded runs."
+ verified: "2026-10-15"
pairs_with: "c3d-part-contact, c3d-bbox-contract"
target_metric: "missing_parts"
target_direction: "down"
@@ -20,7 +20,8 @@ metadata:
## When to use
You have a manifest (or a plan part row) and you are about to write
-`src/parts/<snake>.js`. Look up each FORM word, write that element, move on.
+`src/parts/<snake>.js`. Look up each FORM word, pick the maker that produces it, move on.
+Nothing here says what a chair or a lamp is made of; the brief and the plan do.
## The table
@@ -31,39 +32,31 @@ this column changes when the language does.
|---|---|---|
| revolved profile | `LatheGeometry(points, seg)` | `points` are `Vector2(radius, y)`, spun about **Y**. Normals point out when the radius goes 0 → R → 0 bottom-up |
| extruded outline | `ExtrudeGeometry(shape, {depth, bevelEnabled:true, bevelSize, bevelSegments})` | extrudes along **+Z**; `.rotateX(-Math.PI/2)` to lay it flat with thickness along Y |
-| tube swept along a path | `TubeGeometry(new CatmullRomCurve3(pts), tubular, radius, radial, closed)` | the only clean way to do a handle, cable, rail or hoop |
-| slab | `BoxGeometry(w,h,d)`, or `RoundedBoxGeometry(w,h,d,seg,r)` from `three/addons/geometries/RoundedBoxGeometry.js` | use the rounded one for anything hands touch |
+| tube swept along a path | `TubeGeometry(new CatmullRomCurve3(pts), tubular, radius, radial, closed)` | the clean way to a handle, cable, rail or hoop |
+| slab | `BoxGeometry(w,h,d)`, or `RoundedBoxGeometry(w,h,d,seg,r)` from `three/addons/geometries/RoundedBoxGeometry.js` | the rounded one is the cheap way to a soft edge where the brief or the judged view wants one |
| shaft | `CylinderGeometry(r, r, h, radial)` | axis is **Y**; rotate the group, not the geometry, when you need another axis |
-| tapered solid | `CylinderGeometry(rTop, rBottom, h, radial)` or `ConeGeometry(r,h,seg)` | a 5–15 % difference between the two radii is a visible draft and costs nothing |
+| tapered solid | `CylinderGeometry(rTop, rBottom, h, radial)` or `ConeGeometry(r,h,seg)` | two different radii give a taper at no triangle cost |
| ring or band | `TorusGeometry(R, r, radial, tubular)` | lies in the **XY** plane; `.rotateX(Math.PI/2)` to lay it flat |
-| carved cavity | **no boolean exists here** — put the recess in the profile: a `Shape` with a `Path` pushed into `shape.holes`, a `LatheGeometry` profile that climbs the outside and comes back down the inside, or a ring of four slabs around the opening | see "There is no CSG" below |
-| shell with wall thickness | a `LatheGeometry` whose profile traces outer wall up, across the rim, inner wall down | one geometry, watertight, and the open rim is refinement kind 6 |
+| carved cavity | **no boolean exists here** — put the recess in the profile: a `Shape` with a `Path` pushed into `shape.holes`, a `LatheGeometry` profile that climbs the outside and comes back down the inside, or slabs around the opening | see "There is no CSG" below |
+| shell with wall thickness | a `LatheGeometry` whose profile traces outer wall up, across the rim, inner wall down | one geometry, watertight, with a visible open rim |
| mirror pair | build once, add twice with `mesh.position.x = ±d` | never `scale.set(-1,1,1)`: a negative scale inverts the winding and exports reversed normals |
| radial array | one geometry, `InstancedMesh(geo, mat, N)` with `M.makeRotationY(i/N * 2π)` | derive the angle from N; see the instancing trap below |
-| layered or inset | a second slab 1–2 mm proud of or sunk into the face, its own material | the cheapest panel break there is |
+| layered or inset | a thin second slab slightly proud of or sunk into the face, in its own material | the cheapest panel break there is |
| faceted solid | raw `BufferGeometry`: `Float32BufferAttribute` positions + `setIndex` + **`computeVertexNormals()`** | without the normals call it shades black |
| lofted transition | `LatheGeometry` when it is round-to-round; otherwise a raw `BufferGeometry` ring-to-ring strip | three r182 has no loft primitive |
`mergeGeometries` from `three/addons/utils/BufferGeometryUtils.js` collapses many
static pieces of one part into one mesh. Merge inputs must share the same
-attribute set (`geo.deleteAttribute('uv')` or `toNonIndexed()` everything), and
-call `computeVertexNormals()` after.
+attribute set (`geo.deleteAttribute('uv')` or `toNonIndexed()` everything) or it
+returns `null`, and call `computeVertexNormals()` after.
-## Segment counts that read
+## Segments and triangles
-Under-segmenting is the most common reason a lathe or a tube reads as a
-prism in the render sheet.
-
-| what | radial segments |
-|---|---|
-| visible cylinder, lathe body, knob | 24–48 |
-| thin rod, spoke, baluster, screw shank | 8–12 |
-| tube radial | 8–12 |
-| small sphere | 16 x 12 |
-| extrude `curveSegments` on a curved outline | 16 |
-
-A `SphereGeometry(r, 64, 64)` repeated a hundred times is 800 k triangles for
-nothing; the detail belongs on the shapes that fill the silhouette.
+Under-segmenting is the most common reason a lathe or a tube reads as a prism in the
+render sheet. Segment counts are not measured; the triangle total is — the depth gate
+WARNs below 350 triangles per built object and ERRORs above 20 000 (the ceiling for the
+whole object is 600 000). A `SphereGeometry(r, 64, 64)` repeated a hundred times is 800 k
+triangles and over that ceiling; the detail belongs on the shapes that fill the silhouette.
## There is no CSG
@@ -77,7 +70,7 @@ That changes how you plan a cavity. A cup is not "a cylinder minus a smaller
cylinder"; it is one lathe profile that goes up the outer wall, across the rim
and back down the inner wall. A bracket with a bolt hole is not a plate minus a
cylinder; it is a `Shape` with an `absarc` `Path` in `shape.holes`. A slot in a
-face is four slabs around the opening, or a hole in the extrude outline. Each of
+face is slabs around the opening, or a hole in the extrude outline. Each of
those is one geometry, stays watertight, and exports cleanly — which subtraction
in this language would not, because it does not exist.
@@ -92,13 +85,12 @@ in this language would not, because it does not exist.
a WARN ("dead part file?"), the build succeeds, and the part is simply absent
from the GLB — this is a real, recorded failure mode in the blender track and
the same lint rule exists here.
-3. **An `InstancedMesh` reads as N stray islands.** The harness exports an
- `InstancedMesh` named `Bolts` as a group `Bolts` of meshes `Bolts_0 …
- Bolts_{n-1}` with matrices baked, so the connectivity gate sees one plan part
- made of N disconnected pieces. In `runs/e2e_bench_threejs` a `FastenerBolts`
- part produced **39 tiny disconnected island** warnings. Instancing is still
- the right tool — just sink each copy into the surface it fastens so it is a
- contact, not a floater.
+3. **An `InstancedMesh` reads as N separate pieces.** The harness replaces an
+ `InstancedMesh` named `Bolts` with sibling meshes `Bolts_0 … Bolts_{n-1}`
+ (matrices baked), so the connectivity gate measures every copy on its own.
+ In `runs/e2e_bench_threejs` a `FastenerBolts` part produced **39 tiny
+ disconnected island** warnings: copies that touch nothing are islands or
+ floaters, copies within the gate's 2 mm of the surface they fasten are contacts.
4. **Never resize with `root.scale`.** Writing your dimensions in one unit and
then setting `root.scale.set(0.01, ...)` to convert makes the bounds and the
contract gate disagree, because they read the scaled and unscaled geometry
@@ -112,11 +104,11 @@ in this language would not, because it does not exist.
`computeVertexNormals()`.
7. **`mesh.position` versus `geometry.translate()`.** Position moves the pivot
and is what you want for a part placed at its world pose; `.translate()` bakes
- the offset into the vertices and is what you want before a merge or to move a
- blade root onto its pivot. Doing both by accident doubles the offset.
-8. **Only `mergeGeometries` exists**, not `mergeBufferGeometries`, and
- `three/examples/js/*`, `Geometry`, `Face3`, `sRGBEncoding` and `outputEncoding`
- were all removed before r182.
+ the offset into the vertices and is what you want before a merge. Doing both by
+ accident doubles the offset.
+8. **Names that no longer exist in r182** (`mergeBufferGeometries`, `three/examples/js/*`,
+ `Geometry`, `Face3`, `sRGBEncoding`, `outputEncoding`) are listed in the contract's
+ Imports section; each is an undefined import, not a deprecation.
## What the part must return
@@ -127,10 +119,25 @@ detail belongs in there. The object's naming and frame rules are in the contract
dimensions and tolerances belong to `c3d-bbox-contract`; contact and overlap
belong to `c3d-part-contact`.
+## Strong options (none of them required)
+
+**Merging without islands.** `mergeGeometries` keeps every input's vertices, so two
+pieces that merely overlap stay two shells inside one mesh and the connectivity gate
+counts the small one as stray geometry. Merge only what is genuinely one piece, make
+seams share vertices where they can, and normalise the inputs first
+(`toNonIndexed()`, `deleteAttribute('uv')`) so the merge does not return `null`.
+
+**Contact by construction.** The gate counts a surface gap of 2 mm or less as contact
+(flush included) and penetration beyond 2 mm as a WARN, so a part whose face is computed
+from its neighbour's bounds lands inside that band without nudging.
+
+**Where triangles pay.** The depth gate measures the total only, so spend it on the
+silhouette and on the faces the judged views see — the front, eye height, where two
+materials meet — inside the plan part, not on the underside, the back or interior volumes.
+A radius on the edges hands touch is what reads as manufactured; a subdivided flat panel
+reads as nothing.
+
## Depth
-`references/form_recipes.md` — a runnable snippet per form word, including the
-cavity and shell profiles that replace the boolean you do not have.
-Longer code lives in the cookbook — the cookbook section "Geometry
-toolkit", and "Detail (how to look good cheaply)", "Density: visual complexity
-without hand-modelling every screw" or "Raw BufferGeometry and a spoked wheel".
+`references/form_recipes.md` — each form word under its r182 API name with the trap that
+bites it, including the cavity and shell profiles that replace the boolean you do not have.
diff --git a/harness/codeverse3d/skills/c3d-threejs-forms/references/form_recipes.md b/harness/codeverse3d/skills/c3d-threejs-forms/references/form_recipes.md
index e87bfd12..f4893d30 100644
--- a/harness/codeverse3d/skills/c3d-threejs-forms/references/form_recipes.md
+++ b/harness/codeverse3d/skills/c3d-threejs-forms/references/form_recipes.md
@@ -1,121 +1,48 @@
-# One recipe per FORM word
+# FORM words under their three.js API names
-Every snippet below was executed against the harness's own `[email protected]` in node
-on 2026-08-25 and printed the counts shown. Adapt the numbers; keep the shape of
-the call.
+Options, not the way: each paragraph names the r182 call that produces a form and the trap that
+makes it ship nothing or the wrong thing. What a part is made of is the brief's and the plan's.
-## shell with wall thickness — the boolean you do not have
+## shell with wall thickness
-A cup, a housing, a bin, a pot. Not "cylinder minus cylinder": one lathe profile
-that climbs the outer wall, crosses the rim and comes back down the inside.
+There is no boolean, so a vessel or housing is one `LatheGeometry` whose `Vector2(radius, y)`
+profile climbs the outer wall, crosses the rim and comes back down the inside to the floor. The
+rim segment between the outer and inner radius is the visible wall thickness. Normals point
+outward when the profile runs bottom-up on the outside.
-```js
-function cupGeometry(rOuter, wall, h, floor) {
- const rIn = rOuter - wall;
- const p = [[0, 0], [rOuter, 0], [rOuter, h], [rIn, h], [rIn, floor], [0, floor]];
- return new THREE.LatheGeometry(p.map(([r, y]) => new THREE.Vector2(r, y)), 48);
-}
-// cupGeometry(0.042, 0.004, 0.095, 0.006) -> 294 vertices
-```
+## carved cavity
-The rim between `[rOuter, h]` and `[rIn, h]` is the visible wall thickness —
-refinement kind 6, free, and the single clearest signal that a vessel was
-modelled rather than approximated by a solid cylinder.
+A through-hole belongs in the outline: a `THREE.Shape` with a `THREE.Path` pushed into
+`shape.holes`, extruded with `ExtrudeGeometry`. Trap: a hole drawn with `absarc(x, y, r, 0,
+2 * Math.PI, true)` must be CLOCKWISE (the last argument) or the extrude fills it.
+`ExtrudeGeometry` grows along +Z, so a plate whose thickness should run along Y needs
+`.rotateX(-Math.PI / 2)`. A recess that does not pass through is built from the slabs around it.
-## carved cavity — holes belong in the outline
+## radial or linear array
-```js
-function bracketGeometry(w, d, t, holeR, holeAt) {
- const s = new THREE.Shape();
- s.moveTo(-w/2, -d/2); s.lineTo(w/2, -d/2); s.lineTo(w/2, d/2); s.lineTo(-w/2, d/2); s.closePath();
- for (const [hx, hz] of holeAt) {
- const hole = new THREE.Path();
- hole.absarc(hx, hz, holeR, 0, Math.PI * 2, true); // `true` = clockwise, required for a hole
- s.holes.push(hole);
- }
- const g = new THREE.ExtrudeGeometry(s, { depth: t, bevelEnabled: true, bevelThickness: 0.0006,
- bevelSize: 0.0006, bevelSegments: 1, curveSegments: 16 });
- g.rotateX(-Math.PI / 2); // ExtrudeGeometry grows along +Z; lay it flat
- g.translate(0, t / 2, 0); // and sit its underside on y = 0
- return g;
-}
-// bracketGeometry(0.09, 0.05, 0.004, 0.003, [[-0.03, 0], [0.03, 0]]) -> 548 triangles
-```
+`InstancedMesh(geometry, material, N)` with `setMatrixAt(i, matrix)` per copy, the angle or step
+derived from N. Traps: without `instanceMatrix.needsUpdate = true` every copy sits at the origin,
+and without `computeBoundingSphere()` the mesh can be frustum-culled away. The exporter bakes it
+into sibling meshes `Name_0 … Name_{N-1}` (the contract's Materials section), so each copy is
+measured on its own: a copy that touches nothing is a floating island.
-Two refinement kinds in one call: the holes (kind 5) and the bevel (kind 1).
+## faceted solid
-A slot or a rebate that does not pass through works the same way one level up:
-build the face out of the slabs *around* the recess rather than trying to remove
-material from a single slab.
-
-## radial array — one geometry, one draw call
-
-```js
-const teeth = new THREE.InstancedMesh(
- new THREE.BoxGeometry(0.0015, 0.026, 0.0012),
- new THREE.MeshStandardMaterial({ color: 0xeeeeee }), 14);
-const M = new THREE.Matrix4(), q = new THREE.Quaternion(), up = new THREE.Vector3(0, 1, 0);
-const pos = new THREE.Vector3(), sc = new THREE.Vector3(1, 1, 1);
-for (let i = 0; i < 14; i++) {
- const a = i / 14 * Math.PI * 2; // angle from the COUNT, never a typed list
- q.setFromAxisAngle(up, a);
- pos.set(0.016 * Math.cos(a), 0.168, 0.016 * Math.sin(a));
- M.compose(pos, q, sc);
- teeth.setMatrixAt(i, M);
-}
-teeth.instanceMatrix.needsUpdate = true; // or the copies all sit at the origin
-teeth.computeBoundingSphere(); // or the whole mesh is frustum-culled away
-teeth.name = 'ConeTeeth';
-```
-
-Remember what this costs at the gate: the exporter turns `ConeTeeth` into a
-group of `ConeTeeth_0 … ConeTeeth_13`, so if the copies do not touch the body
-they read as thirteen stray islands. Sink each copy into the surface.
-
-## faceted solid — raw BufferGeometry
-
-```js
-function wedge(w, h, d) {
- const g = new THREE.BufferGeometry();
- g.setAttribute('position', new THREE.Float32BufferAttribute(
- [-w/2,0,d/2, w/2,0,d/2, w/2,0,-d/2, -w/2,0,-d/2, -w/2,h,-d/2, w/2,h,-d/2], 3));
- g.setIndex([0,2,1, 0,3,2, 0,1,5, 0,5,4, 1,2,5, 3,4,2, 4,5,2, 0,4,3]);
- g.computeVertexNormals(); // omit this and the mesh renders black
- return g;
-}
-```
-
-Wind every triangle counter-clockwise seen from outside. If a face renders dark
-while its neighbours are lit, that triangle's index order is reversed — fix the
-order, do not add a light and do not set `side: DoubleSide` to hide it.
+A raw `BufferGeometry` with a `Float32BufferAttribute` for `position` and `setIndex(...)`.
+Traps: without `computeVertexNormals()` it renders black; a triangle wound clockwise seen from
+outside renders dark among lit neighbours — fix its index order rather than `side: DoubleSide`.
## merging the pieces of one part
-```js
-const a = new THREE.BoxGeometry(0.04, 0.012, 0.05).toNonIndexed(); a.deleteAttribute('uv');
-const b = new THREE.BoxGeometry(0.04, 0.012, 0.05).translate(0, 0.02, 0).toNonIndexed(); b.deleteAttribute('uv');
-const merged = mergeGeometries([a, b]); // -> 72 vertices
-merged.computeVertexNormals();
-```
-
-`mergeGeometries` throws "All geometries must have compatible attributes" when
-one input has `uv` or an index and another does not. Normalise first
-(`toNonIndexed()` everything and delete the attributes you are not using), merge,
-then recompute normals. Merging is for static detail *inside* one part — keep one
-`THREE.Group` per plan part so the census and the gates still see your parts.
-
-## revolved profile, tube and rounded slab, in one line each
+`mergeGeometries` from `three/addons/utils/BufferGeometryUtils.js` returns `null` (and logs "All
+geometries must have compatible attributes") when one input is indexed or carries `uv` and
+another does not — normalise with `toNonIndexed()` / `deleteAttribute('uv')` first and call
+`computeVertexNormals()` after. Merging keeps every input's vertices, so two pieces that only
+overlap stay two shells in one mesh; keep one `THREE.Group` per plan part.
-```js
-const knob = new THREE.LatheGeometry([[0,0],[0.014,0],[0.016,0.004],[0.010,0.018],[0,0.020]]
- .map(([r, y]) => new THREE.Vector2(r, y)), 32);
-const curve = new THREE.CatmullRomCurve3([new THREE.Vector3(0.05,0.30,0), new THREE.Vector3(0.10,0.20,0.02),
- new THREE.Vector3(0.18,0.08,0), new THREE.Vector3(0.30,0.01,-0.03)]);
-const handle = new THREE.TubeGeometry(curve, 48, 0.004, 10, false);
-const cushion = new RoundedBoxGeometry(0.40, 0.10, 0.40, 4, 0.03); // 2916 vertices
-```
+## revolved profile, tube, rounded slab
-The `LatheGeometry` profile is the highest-value call in this language: a taper
-(kind 2), a curved flank (kind 3), a shaped edge (kind 4) and a rim (kind 6) all
-come out of the same list of points at no extra cost, and it is the difference
-between a knob that reads as turned and a knob that reads as a cylinder.
+`LatheGeometry(points, segments)` turns a list of `Vector2(radius, y)` into a taper, a curved
+flank and a rim in one call. `TubeGeometry(new CatmullRomCurve3(points), tubular, radius,
+radial, closed)` sweeps a round section along a path. `RoundedBoxGeometry(w, h, d, segments,
+radius)` from `three/addons/geometries/RoundedBoxGeometry.js` is a slab with a soft edge.
diff --git a/harness/codeverse3d/skills/c3d-threejs-shader-traps/SKILL.md b/harness/codeverse3d/skills/c3d-threejs-shader-traps/SKILL.md
index b3c5802c..eec4b434 100644
--- a/harness/codeverse3d/skills/c3d-threejs-shader-traps/SKILL.md
+++ b/harness/codeverse3d/skills/c3d-threejs-shader-traps/SKILL.md
@@ -1,12 +1,12 @@
---
name: c3d-threejs-shader-traps
-description: "Use when a threejs or scene_threejs session writes a ShaderMaterial or an onBeforeCompile patch, or when shader_preflight reported an error. Write custom GLSL that survives this harness's shader gate on the first build. Says which mistakes the harness detects statically, which it detects at runtime, which it cannot see at all, and corrects three widely repeated three.js warnings that do not apply to this renderer."
+description: "Use when a scene_threejs session writes a ShaderMaterial or an onBeforeCompile patch, or when shader_preflight reported an error (on the static threejs track a ShaderMaterial is dropped at GLB export — see that contract). Write custom GLSL that survives this harness's shader gate on the first build. Says which mistakes the harness detects statically, which it detects at runtime, which it cannot see at all, and corrects three widely repeated three.js warnings that do not apply to this renderer."
license: Apache-2.0
compatibility: [email protected], headless WebGL via puppeteer. Rules read from runtime_js/lib/glsl_audit.mjs, runtime_js/lib/host_compile.mjs, runtime_js/lib/shader_report.mjs and runtime_js/lib/browser/renderer.js.
metadata:
evidence: mixed
evidence_note: "Every rule is read from the live runtime_js source and cross-checked against the shader_report merge path. Incidence is NOT measured: bench/out holds 4 scene_threejs runs, and all 4 shader_preflight reports are clean INFO (10, 9, 14 and 11 programs compiled; 1-12 custom materials). The corpus therefore supports the detection map, not a defect rate."
- verified: "2026-08-25"
+ verified: "2026-10-15"
owns: "shader_preflight"
target_metric: "shader_preflight_findings"
target_direction: "down"
@@ -20,8 +20,8 @@ metadata:
**When:** your scene builds a `THREE.ShaderMaterial` / `RawShaderMaterial`, or patches a built-in
material through `onBeforeCompile`, or `shader_preflight` said something.
-In a scene workspace the GLSL boilerplate is `makeShaderMaterial(opts)` in `src/lib/shader.js` —
-start from it. What follows is the part it does not say:
+In a scene workspace `makeShaderMaterial(opts)` in `src/lib/shader.js` already satisfies every rule
+below; it is the option that costs nothing. What follows is the part it does not say:
**which pitfalls a gate will catch, at what severity, and which ones nothing catches.**
## The detection map
@@ -59,8 +59,7 @@ Plus GPU compile: every program is force-compiled, and a compiler error is mappe
Both audits are hard-coded to the identifier `uTime` (`/\buTime\b/`). Call it `time`, `u_time`
or `iTime` and you get **no** protection from either check — the shader compiles, the uniform
-never updates, and the scene is silently frozen. `animation_life` is **0.431, the lowest
-criterion in the whole corpus** (8 rounds over 4 scene runs), and the judge's words for it are
+never updates, and the scene is silently frozen. The judge's own words for a frozen shader are
*"No animation is visible; the scene is completely static"* and *"MONTAGE 2/3 (t=0s) and
MONTAGE 3/3 (t=1.5s) shows identical frames"*. Naming the uniform `uTime` is the cheapest
insurance in this file.
@@ -125,5 +124,5 @@ program cache key, an effect placed outside every camera's frustum. Look at the
yourself: `scene_views` (or `render_views`) at two different times, and check that the thing
you wrote changed something.
-Full audit source lines, the fix-hint texts, and a minimal citizen shader:
+Full audit source lines, the fix-hint texts, and what a shader that passes every rule carries:
`references/shader-gate.md`.
diff --git a/harness/codeverse3d/skills/c3d-threejs-shader-traps/references/shader-gate.md b/harness/codeverse3d/skills/c3d-threejs-shader-traps/references/shader-gate.md
index 082d9f61..6ae39b36 100644
--- a/harness/codeverse3d/skills/c3d-threejs-shader-traps/references/shader-gate.md
+++ b/harness/codeverse3d/skills/c3d-threejs-shader-traps/references/shader-gate.md
@@ -1,6 +1,6 @@
# The shader gate, in full
-Read out of the live runtime on 2026-08-25: `runtime_js/lib/glsl_audit.mjs`,
+Read out of the live runtime on 2026-08-25 (section 4 rewritten 2026-10-15): `runtime_js/lib/glsl_audit.mjs`,
`runtime_js/lib/host_compile.mjs`, `runtime_js/lib/shader_report.mjs`,
`runtime_js/lib/scene_host.mjs`, `runtime_js/lib/browser/renderer.js`,
`runtime_js/check_shaders.mjs`, `runtime_js/package.json`, and
@@ -77,53 +77,29 @@ without `uTime`, or a material cloned from a patched one. Conversely it only ins
`isShaderMaterial`, so an `onBeforeCompile` patch on a `MeshStandardMaterial` is invisible to it
and only the static `chunk_dropped` rule protects you.
-## 4. A minimal citizen shader
+## 4. A citizen shader, in prose
-Full boilerplate: `makeShaderMaterial(opts)` in `src/lib/shader.js` (scene workspaces). The
-smallest thing that passes every rule above:
+Full boilerplate: `makeShaderMaterial(opts)` in `src/lib/shader.js` (scene workspaces). What
+passes every rule above, whatever the shader draws: every `#include` alone on its line; no
+`#version` and no `precision` of your own in a `ShaderMaterial`; `uTime` both declared in GLSL
+(`uniform float uTime;`) and bound in JS; the vertex shader carrying `<common>`,
+`<fog_pars_vertex>` and `<fog_vertex>`; the fragment shader carrying `<common>` and
+`<fog_pars_fragment>` and ending `main` with `<tonemapping_fragment>`, `<colorspace_fragment>`
+and `<fog_fragment>` in that order, fog last. The constructor side:
```js
-const VS = `
-#include <common>
-#include <fog_pars_vertex>
-varying vec2 vUv;
-void main() {
- vUv = uv;
- vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
- gl_Position = projectionMatrix * mvPosition;
- #include <fog_vertex>
-}`;
-
-const FS = `
-#include <common>
-#include <fog_pars_fragment>
-uniform float uTime;
-uniform vec3 uTint;
-varying vec2 vUv;
-void main() {
- float w = 0.5 + 0.5 * sin(vUv.x * 12.0 + uTime * 1.3);
- gl_FragColor = vec4(uTint * (0.6 + 0.4 * w), 1.0);
- #include <tonemapping_fragment>
- #include <colorspace_fragment>
- #include <fog_fragment>
-}`;
-
-export function makeRipple(THREE, tint = 0x3a6ea5) {
- const mat = new THREE.ShaderMaterial({
- uniforms: THREE.UniformsUtils.merge([
- THREE.UniformsLib.fog, { uTime: { value: 0 }, uTint: { value: new THREE.Color(tint) } }]),
- vertexShader: VS, fragmentShader: FS, fog: true,
- });
- mat.name = 'Ripple';
- mat.userData.update = (t) => { mat.uniforms.uTime.value = t; };
- return mat;
-}
+const mat = new THREE.ShaderMaterial({
+ uniforms: THREE.UniformsUtils.merge([THREE.UniformsLib.fog, { uTime: { value: 0 } }]),
+ vertexShader: VS, fragmentShader: FS, fog: true,
+});
+mat.name = 'Ripple';
+mat.userData.update = (t) => { mat.uniforms.uTime.value = t; };
```
-Every include is alone on its line; no `#version`, no `precision`; `uTime` is both declared in
-GLSL and bound in JS; the fog chunks are present and `fog_fragment` is last. Collect the
-materials once at build time and call `m.userData.update(t)` from `update(t, dt)` — never
-traverse the scene inside `update`, and never read the clock from `Date.now()`.
+Collect the materials once at build time and call `m.userData.update(t)` from `update(t, dt)`.
+`update(t, dt)` receives the harness's sampled time (the judged frames are taken at t = 0 and
+t = 1.5 s): a shader clocked from `Date.now()` is not at the t the judged frames are taken, and a
+scene traversal inside `update` is paid on every frame.
## 5. Corpus, and why this bundle is `mixed` rather than `measured`
diff --git a/harness/codeverse3d/skills/c3d-urdf-joints/SKILL.md b/harness/codeverse3d/skills/c3d-urdf-joints/SKILL.md
index 6a41a60a..cd8f9b68 100644
--- a/harness/codeverse3d/skills/c3d-urdf-joints/SKILL.md
+++ b/harness/codeverse3d/skills/c3d-urdf-joints/SKILL.md
@@ -21,17 +21,18 @@ metadata:
**When:** any `articulated_object` round that writes or fixes `src/robot.urdf` (and the rest pose
in `src/model.py`), or that received a `joint_sweep` / `motion_direction` finding.
-The frame recipe, the pivot rule and the visual/collision `origin = -pivot` line are in
-`codeverse3d/prompts/urdf/contract.md` and its cookbook — follow them literally. This skill is the
-part the contract does not tell you: **what the gates measure, and how to satisfy them before the
-first build.**
+The frame rule (link frame at the pivot, joint origin = pivot of the child minus the frame of
+the parent, visual and collision origin = minus the pivot) is in
+`codeverse3d/prompts/urdf/contract.md`. This skill is what the gates measure, and how to
+satisfy them before the first build.
## Two things fail the BUILD, not just a gate
* **FK check**, tolerance **1 mm** (`FK_TOL_M = 0.001` m). If FK at q=0 does not put every mesh back where
`model.py` authored it, the build stops with `FkInconsistent` and prints the corrected
`origin`. Cause is almost always a link's visual/collision `origin` left at `0 0 0` instead of
- `-pivot`, or a joint with `rpy` other than `0 0 0`.
+ `-pivot`, or a joint with a rotated origin (`rpy` not `0 0 0`) whose visual/collision origin
+ was not inverted to match.
* **Rest penetration** over **5 mm** (`REST_PENETRATION_MAX_M = 0.005` m): the build stops with
`RestPenetration`.
@@ -54,17 +55,15 @@ Severity, from `sweep_findings`:
So a 2.1 mm graze that only happens at one limit is scored exactly as badly as a 20 mm gouge.
-**Measured** (26 urdf runs, 691 sweep findings, 2026-08-25): only **34 findings (4.9 %) were at
-rest**, and every one of those was a WARN. **653 were in a moved pose** — 358 at a single joint's
-limit, **295 in a random multi-joint combination**. Of 48 distinct link pairs that collided,
-**29 never touch at rest** and **7 appear only in a combination**, so posing your joints one at a
-time in your head is not enough: two arms that each clear the body can still meet each other.
-Median depth 4.0 mm, max 20.0 mm; 510 of 687 were 5 mm or less.
+Measured on the corpus: almost every finding is in a moved pose, a third of the colliding pairs
+never touch at rest and some appear only in a random combination — posing joints one at a time
+in your head is not enough: two arms that each clear the body can still meet each other.
-Design rule: **1-3 mm of clearance all round, held over the whole envelope**, and think about the
-worst *combination*, not the worst single joint. Fixed hardware is different and cheap — a
-handle welded to a door may sink up to 2 mm with no finding at all, because pairs joined only by
-`fixed` joints are measured once with the rest policy and never re-judged as they move.
+Strong option: give every moving link more than the 2 mm the sweep tolerates, everywhere in its
+envelope, and check the worst *combination* of joints, not the worst single joint. Fixed hardware
+is different and cheap — a handle welded to a door may sink up to 2 mm with no finding at all,
+because pairs joined only by `fixed` joints are measured once with the rest policy and never
+re-judged as they move.
**Attachment** is checked at rest only: a `fixed` child must be within `CONTACT_GAP_M = 0.002` of
its parent (ERROR otherwise, always); a revolute / continuous / prismatic child must be within
@@ -72,8 +71,29 @@ its parent (ERROR otherwise, always); a revolute / continuous / prismatic child
'fixed_jaw_body' (prismatic joint) but the meshes are 42.5 mm apart at rest`. A prismatic child
already inside the parent's bounding box (a drawer in its cavity) is exempt.
-**159 of 687 findings carried `[approx: non-watertight mesh]`.** Depth is then an estimate. Make
-each link one closed solid so the number you are given is the number you can trust.
+A finding tagged `[approx: non-watertight mesh]` is an estimate: the depth is exact only on a
+watertight link mesh.
+
+## Strong options before the first build
+
+**Keep the pivots in model.py and print the two origins.** Record each link's world pivot (the
+point you chose on its hinge line or slide axis) in a dict while building; for every joint print
+the child's pivot minus the parent's (the joint origin) and the negated child pivot (the visual
+and collision origin), then copy both into `src/robot.urdf`. The FK check confirms them within
+1 mm, so a wrong line is caught by the build, not by the judge.
+
+```python
+PIVOT = {"base": Vector((0, 0, 0))} # world pivot = link frame, recorded as each link is built
+PIVOT["door"] = Vector((-0.2, -0.25, 0.4)) # a point ON the hinge line
+PIVOT["handle"] = Vector((0.15, -0.27, 0.45))
+for child, parent in (("door", "base"), ("handle", "door")):
+ print(child, "joint origin", tuple(PIVOT[child] - PIVOT[parent]), "visual/collision", tuple(-PIVOT[child]))
+```
+
+**Hardware is geometry, not joints.** A hinge barrel, a runner or a bracket lives in one of the
+two links it connects; it is what lets the attachment check see the child within 10 mm of its
+parent. A knob on a door is part of the door's mesh or a fixed child of the door — attached to
+the base it stays behind when the door swings, and the sweep reports the overlap.
## Predict the direction before you write the axis
@@ -89,7 +109,7 @@ import numpy as np
def child_moves(axis, pivot, centroid): # revolute: d ~ axis x (centroid - pivot)
d = np.cross(axis, np.subtract(centroid, pivot))
return d / np.linalg.norm(d) # prismatic: the direction IS the axis
-# pedal-bin lid: pivot on the back top edge, lid centroid just above the rim
+# a lid hinged on its back top edge, centroid just above the rim
print(child_moves((-1, 0, 0), (0, 0.125, 0.351), (0, 0, 0.356)))
# [0. 0.03996804 0.99920096] -> almost pure +Z: the lid lifts UP
```
@@ -100,8 +120,7 @@ Verified against `motion_direction_check` on 2026-08-25: it reported `up` for ax
Two independent ways to get this wrong, and the corpus has both:
1. **Axis sign.** Fix it by negating `axis`. The contract is explicit — *never* compensate by
- swapping `lower` and `upper`; q=0 must stay the plan's rest pose. (The gate's own fix hint
- offers both; take only the first half.)
+ swapping `lower` and `upper`; q=0 must stay the plan's rest pose.
2. **Pivot off the axis line.** *"The hasp rotates about its center rather than its top edge,
causing it to clip into the lid."* Put the pivot at the part's centre and `centroid - pivot`
goes to zero: the centroid barely translates, the measured direction is noise, and the part
@@ -124,17 +143,11 @@ precedence, and the gate is unforgiving about it:
no finding either way;
* two different axes in one sentence with no dominant one is skipped.
-So make **positive q move the child the way the plan's first direction word says**, even when the
-prose is loose. Verified corpus consequences worth knowing before you argue with a finding:
-
-* `"tray slides sideways from left side to right side"` yields `left` (first word wins), and the
- build that slid it rightward was flagged. The judge agreed the motion "fulfils the brief's
- intent" and scored it `minor` — but it is still an ERROR-severity gate finding.
-* `"rear-right leg hinges..."` yields `right`, from the part name.
-* `"rotates clockwise (+Y axis)"` yields `+y` as a **translation** direction. A revolute joint
- about +Y can never move its child along +Y, so no axis satisfies it. Confirm with the
- `joint_sweep` pose renders that the part moves the way the prose describes, then leave it.
- **Do not flip a correct axis to chase an unsatisfiable finding.**
+Make positive q go the way the plan's FIRST direction word says, even when the prose reads
+loosely ("from left to right" yields `left`). A `motion` like "rotates clockwise (+Y axis)" asks
+for a translation along +Y that no revolute joint about +Y can give: confirm with the
+`joint_sweep` pose renders that the part moves as the prose describes, then leave the axis alone.
+**Do not flip a correct axis to chase an unsatisfiable finding.**
## Scope
@@ -151,9 +164,8 @@ names no joint, names itself, or closes a loop is a lint ERROR.
## Finish
-`build` (runs the FK check and the rest-pose check) then `joint_sweep` (the round's own gate)
-and look at the lower/mid/upper renders for every joint, then `check_connectivity`, then
-`check_contract`.
+A finish that catches everything: `build` (the FK check and the rest-pose check), `joint_sweep`
+with a look at every joint's lower/mid/upper renders, `check_connectivity`, `check_contract`.
-Worked repairs, the full finding catalogue with real messages, and clearance numbers per
-mechanism: `references/sweep-and-motion.md`.
+Worked repairs, the finding catalogue with real messages and the measured thresholds:
+`references/sweep-and-motion.md`.
diff --git a/harness/codeverse3d/skills/c3d-urdf-joints/references/sweep-and-motion.md b/harness/codeverse3d/skills/c3d-urdf-joints/references/sweep-and-motion.md
index 300b4696..4c72aebf 100644
--- a/harness/codeverse3d/skills/c3d-urdf-joints/references/sweep-and-motion.md
+++ b/harness/codeverse3d/skills/c3d-urdf-joints/references/sweep-and-motion.md
@@ -62,55 +62,18 @@ The fix hints differ by pose and are worth reading rather than guessing:
* in a moved pose — "Moving joint(s) [...] drives 'a' into 'b'. Either move the pivot/axis in
robot.urdf so the part swings/slides clear, shrink the limits, or carve the clearance in
model.py." Three genuinely different repairs; pick the one the mechanism justifies. Shrinking
- a limit is legitimate when the plan's range was optimistic (a drawer at 0.8 x depth), and wrong
- when the range is the point of the object.
+ a limit is legitimate when the plan's range was optimistic, and wrong when the range is the
+ point of the object.
-## 4. Corpus (bench/out, mined 2026-08-25)
+## 4. What the judge penalises (corpus, 2026-08-25)
-Denominator: 26 `urdf_blender` run records; 50 judged rounds.
-
-| observation | value |
-|---|---|
-| runs where `joint_sweep` fired | 10 of 26 (38 %) |
-| of those, runs with an ERROR | 9 |
-| runs where `motion_direction` fired | 9 of 26 (35 %) |
-| of those, runs with an ERROR | 8 |
-| total sweep WARN/ERROR findings | 691 (687 penetration, 4 unattached) |
-| findings at the `rest` pose | 34 (4.9 %), **all WARN** |
-| findings at a single-joint limit or mid pose | 358 |
-| findings in a random multi-joint combination | 295 |
-| distinct (run, link-pair) collisions | 48 |
-| pairs that never collide at rest | 29 of 48 |
-| pairs seen **only** in a random combination | 7 of 48 |
-| median overlap depth | 4.0 mm |
-| max overlap depth | 20.0 mm |
-| findings with depth 5 mm or less | 510 of 687 |
-| findings marked `[approx: non-watertight mesh]` | 159 of 687 |
-
-Judge `articulation` issues in `urdf_blender`: **34** — 11 critical, 19 major, 4 minor.
-`articulation_plausibility` (0.732) and `joint_placement_and_range` (0.736) are the 2nd and 3rd
-lowest of the eight urdf criteria over 50 rounds; only `geometry_detail` (0.699) is lower.
-
-Corpus-verbatim, grouped by root cause:
-
-**Direction (about 13 of 34).**
-"Leg frames fold outward and upward into the air instead of inward under the table." (critical)
-"The door swings in the wrong direction (inward instead of outward), causing massive clipping
-with the frame." (critical)
-"The inner tray slides forward out of the chest body instead of sideways." (critical)
-"The joint axis is flipped; the lower limit points the arm up instead of folding it down." (major)
-"The steering joint rotates the fork assembly around the Z-axis (roll) instead of the Y-axis
-(yaw), causing the wheel to tilt sideways." (critical)
-
-**Pivot placement.**
-"The hasp rotates about its center rather than its top edge, causing it to clip into the lid."
-"Because the front leg frame is detached, it pivots around a point in empty space rather than a
-physical crossbar."
-
-**Sweep clearance.**
-"The right rear spreader collides with the front frame during the folding sweep."
-"The moving jaw heavily interpenetrates the fixed jaw body at its upper travel limit."
-"Seat overlaps with the main frame by 6.0 mm when fully raised."
+Three root causes, one verbatim judge quote each: the **direction** ("The door swings in the
+wrong direction (inward instead of outward), causing massive clipping with the frame."), a
+**pivot off the hinge line** ("The hasp rotates about its center rather than its top edge,
+causing it to clip into the lid.") and **sweep clearance** ("Seat overlaps with the main frame by
+6.0 mm when fully raised."). `articulation_plausibility` and `joint_placement_and_range` are the
+two lowest-scoring urdf criteria after `geometry_detail`. Most sweep findings sit in a moved
+pose, never at rest, and some pairs collide only in a random multi-joint combination.
## 5. The motion phrase table, verbatim from the code
@@ -153,17 +116,17 @@ asks for a *translation* along +Y from a joint that rotates about +Y — unsatis
the way the first word says, which may read backwards in prose; the judge scored one of these
`minor` and noted "the visual sideways motion fulfills the brief's intent".
-## 6. Clearance numbers that pass the sweep
+## 6. What the sweep measures, pair by pair
-| pair | rest gap | why |
+| pair | what passes | what is reported |
|---|---|---|
-| moving part vs its housing (drawer in cabinet, door in frame) | 1-3 mm all round | must stay positive over the whole range, including combinations |
-| a closed door / lid against the carcass face | 0-1 mm, flush | must not sink in; 2-5 mm is a rest WARN, over 5 mm fails the build |
+| moving part vs anything it passes | clear by more than 2 mm in every sampled pose | over 2 mm in a moved pose is an ERROR at any depth |
+| a closed door / lid against the carcass face | overlap up to 2 mm (touching) | 2-5 mm is a rest WARN, over 5 mm fails the build |
| `fixed` hardware (handle, knob, foot) on its parent | touching, or sunk up to 2 mm | rigid pairs are judged once with the rest policy, so this never becomes a moved-pose ERROR |
| hinge barrel / drawer runner to its partner | touching (2 mm) | otherwise the attachment check calls the child unattached |
| revolute or prismatic child to its parent at rest | 10 mm or less | over 10 mm is a WARN, over 30 mm an ERROR |
-Sanity procedure that costs nothing: for every moving link, take its bounding box at `lower`,
-`mid` and `upper`, plus the corners of the combinations you expect, and check the swept envelope
-against each neighbour. If two joints can move a pair towards each other, test them together —
-7 of 48 collisions in the corpus were visible in no other pose.
+Sanity procedure that costs nothing: for every moving link take its bounding box at `lower`,
+`mid` and `upper`, plus the combinations you expect, and check the swept envelope against each
+neighbour. If two joints can move a pair towards each other, test them together — some
+collisions appear in no single-joint pose.
diff --git a/harness/codeverse3d/skills/registry.py b/harness/codeverse3d/skills/registry.py
index b24bd060..a9220ae8 100644
--- a/harness/codeverse3d/skills/registry.py
+++ b/harness/codeverse3d/skills/registry.py
@@ -201,7 +201,7 @@ ROUTES: tuple[Route, ...] = (
Route("R19", "c3d-scene-motion", 90, tracks=("scene",), languages=("scene_threejs",),
findings=(SCENE_NO_MOTION,),
why="the frame-difference gate saw nothing move on an authored camera"),
- Route("R20", "c3d-threejs-shader-traps", 60, tracks=("scene", "static_object"), languages=THREEJS_LANGS,
+ Route("R20", "c3d-threejs-shader-traps", 60, tracks=("scene",), languages=("scene_threejs",),
requires_all=("has_custom_shader",),
why="the plan names a custom shader/material effect"),
Route("R21", "c3d-threejs-shader-traps", 95, languages=THREEJS_LANGS, findings=(SHADER_PREFLIGHT,),
diff --git a/harness/codeverse3d/skills/telemetry.py b/harness/codeverse3d/skills/telemetry.py
index a4707c01..eb53f7f9 100644
--- a/harness/codeverse3d/skills/telemetry.py
+++ b/harness/codeverse3d/skills/telemetry.py
@@ -1,8 +1,8 @@
"""Did anyone actually READ it? Measured from the CLI's own record where there is one.
-The fact this whole system has to answer: ``read_cookbook`` was called by **0 of 16**
-zone sessions and 1 of 4 env sessions on ``scenes_v1_flash``, although the prompt named
-five chapters by title. A tool that exists is not a tool that gets used, and shipping a
+The fact this whole system has to answer: the former ``read_cookbook`` tool was called by
+**0 of 16** zone sessions and 1 of 4 env sessions on ``scenes_v1_flash``, although the
+prompt of the day named five chapters by title. A tool that exists is not a tool that gets used, and shipping a
nicer file format without measuring reads would repeat that at a new price.
**Ground truth first (2026-09-22).** Every CLI backend now folds its session's tool
diff --git a/harness/codeverse3d/spatial/frame_stats.py b/harness/codeverse3d/spatial/frame_stats.py
index f6350110..824b93fc 100644
--- a/harness/codeverse3d/spatial/frame_stats.py
+++ b/harness/codeverse3d/spatial/frame_stats.py
@@ -162,10 +162,10 @@ def frame_gate(seq: SequenceStats, *, motion_expected: bool = True, gate: str =
if seq.all_black:
add(Severity.ERROR, "black", f"frames are essentially black (mean luminance {seq.mean_lum:.3f})",
"something must be visible: check the final fragColor assignment, the raymarch hit test, camera direction and "
- "that colours are not multiplied to zero; aim for mean luminance 0.2-0.6")
+ "that colours are not multiplied to zero (the gate flags frames where 97 % of pixels are under 0.03)")
elif seq.all_blown:
add(Severity.ERROR, "blown", f"frames are blown out white (mean luminance {seq.mean_lum:.3f})",
- "tone-map and clamp: col = col / (1.0 + col); keep accumulated glow sums bounded")
+ "tone-map the result into 0..1 and keep accumulated glow sums bounded (the gate flags frames where 97 % of pixels are over 0.98)")
if seq.static and motion_expected:
add(Severity.WARN, "static", f"frames do not change over time (largest |Δ| between any two sampled frames {seq.max_diff:.4f}); the shader looks static",
"use u_time for motion: move what is in the scene, rotate, animate noise offsets, move lights — the judge compares frames at t=0..6s")
@@ -177,5 +177,5 @@ def frame_gate(seq: SequenceStats, *, motion_expected: bool = True, gate: str =
"avoid discontinuous functions of u_time (fract/mod jumps, random per-frame seeds); motion should be continuous")
if seq.mean_edge_density < LOW_DETAIL_EDGE and not seq.all_black and not seq.all_blown:
add(Severity.WARN, "low_detail", f"very low visual detail (edge density {seq.mean_edge_density:.4f}); the image is a near-flat gradient",
- "add structure: fbm layers, shapes (sdf), stars/particles, lines — the rubric rewards visual richness")
+ "the frame is a near-flat gradient: give the subject the structure the brief describes (edges, shapes, texture at the scales it has)")
return GateReport.of(gate, f)
diff --git a/harness/codeverse3d/spatial/joints_sweep.py b/harness/codeverse3d/spatial/joints_sweep.py
index 1acb1ddb..64b0c52b 100644
--- a/harness/codeverse3d/spatial/joints_sweep.py
+++ b/harness/codeverse3d/spatial/joints_sweep.py
@@ -440,4 +440,4 @@ def motion_direction_check(robot: Robot, joint: str, expected: str, *, probe: fl
cos=round(cos, 4), suggested_axis=suggested,
message=((f"{joint} (driven by {drive})" if driven_by is not None else f"{joint}")
+ f": child '{j.child}' moves {tuple(round(float(v),3) for v in d)} for q={probe:+.3g}; "
- f"expected {expected} ({'ok' if ok else 'WRONG — flip the axis sign or swap limits'})"))
+ f"expected {expected} ({'ok' if ok else 'WRONG — negate the axis; keep the limits'})"))
diff --git a/harness/codeverse3d/texturing/materials.py b/harness/codeverse3d/texturing/materials.py
index 873d3187..3666972b 100644
--- a/harness/codeverse3d/texturing/materials.py
+++ b/harness/codeverse3d/texturing/materials.py
@@ -44,7 +44,7 @@ FRAMEWORK_DEFAULTS: tuple[tuple[float, float], ...] = (
(0.0, 1.0), # three.js MeshStandardMaterial default
(0.0, 0.5), # Blender Principled BSDF default
(0.0, 0.6), # languages/wrappers/run_cq.py: every CadQuery part's exported material
- (0.05, 0.6), # languages/threejs PART_TEMPLATE: the part stub's placeholder material
+ (0.05, 0.6), # the three.js part stub's placeholder before D107 (runs recorded before it carry it)
)
@@ -53,8 +53,8 @@ class Pbr(BaseModel):
``ior``/``clearcoat``/``sheen``/``transmission`` have no home in core glTF
``pbrMetallicRoughness`` (they are KHR extensions / Blender + three
- ``MeshPhysicalMaterial`` inputs) — they are carried here because the
- cookbook and the Blender and three.js authoring paths do use them.
+ ``MeshPhysicalMaterial`` inputs) — they are carried here because the Blender and
+ three.js authoring paths (Principled BSDF / MeshPhysicalMaterial) do use them.
"""
family: str
@@ -86,7 +86,7 @@ def _m(
roughness_band=rband, metallic_band=mband, note=note)
-#: family -> factors. Ordered as the cookbook prints them (metals, woods, polymers, rest).
+#: family -> factors (the texture pass's normaliser bands). Metals, woods, polymers, rest.
MATERIALS: dict[str, Pbr] = {
"painted_metal": _m("painted_metal", 0.0, 0.35, clearcoat=0.35, ccr=0.10, base=(0.30, 0.32, 0.36),
rband=(0.08, 0.7), mband=(0.0, 0.35),
diff --git a/harness/codeverse3d/texturing/plan.py b/harness/codeverse3d/texturing/plan.py
index f553ac63..09e92b97 100644
--- a/harness/codeverse3d/texturing/plan.py
+++ b/harness/codeverse3d/texturing/plan.py
@@ -516,20 +516,17 @@ def write_manifest(pack: ScenePack, out_dir: Path) -> Path:
def texture_pack_prompt(manifest: dict[str, dict[str, Any]], *, url_prefix: str = DEFAULT_URL_PREFIX) -> str:
"""Prompt snippet for zone/env generation: what exists and the exact loading idiom.
- Rendered AFTER the cookbook recipes (``tracks/scene_env.j2`` / ``scene_zone.j2``), and
- it says outright that the ground blend is what the pack is for. Measured 2026-09-05:
- the first two cells of the texture arm generated 8 and 9 textures, carried this block
- verbatim in their env prompt, and used **zero** of them across `env.js` and six zone
- modules. Three things were telling the model to write a procedural colour blend — the
- plan's own ground sentence ("blends velvet moss, raked gravel, packed earth and slate
- by height, slope and normal noise"), the cookbook chapter "Ground that reads real
- (blend, paths, edges — never one flat colour)", and that chapter's position AFTER this
- block — against one passive list offering an alternative. A passive offer loses.
+ The only material block in the env / zone briefs (``tracks/scene_env.j2`` / ``scene_zone.j2``,
+ D106): what exists, the loader idiom the renderer needs, and the judge's requirement the pack
+ answers. Measured 2026-09-05: the first two cells of the texture arm generated 8 and 9
+ textures, carried this block verbatim in their env prompt, and used **zero** of them across
+ `env.js` and six zone modules while the prompt around it taught a procedural colour blend —
+ a passive offer beside a recipe loses, so the block names the defect it is for.
"""
if not manifest:
return ""
ground = [n for n, e in manifest.items() if str(e.get("role", "")).lower() in ("ground", "path")]
- lines = ["## Available textures (seamless tileable albedo PNGs, generated FOR THIS SCENE — use them)"]
+ lines = ["## Available textures (seamless tileable albedo PNGs generated for this scene)"]
for name, e in manifest.items():
lines.append(f"- `{url_prefix}/{e['file']}` — {name} ({e.get('family', 'other')}, {e.get('role', '')}; "
f"one tile = {float(e['tile_size_m']):.2f} m; roughness {float(e.get('roughness', 0.8)):.2f})")
@@ -539,21 +536,15 @@ def texture_pack_prompt(manifest: dict[str, dict[str, Any]], *, url_prefix: str
f"const tex = loaders.texture.load('{url_prefix}/{next(iter(manifest.values()))['file']}');\n"
"tex.wrapS = tex.wrapT = THREE.RepeatWrapping;\n"
"tex.colorSpace = THREE.SRGBColorSpace;\n"
- "tex.anisotropy = 8;\n"
"tex.repeat.set(sizeX / TILE_M, sizeZ / TILE_M); // TILE_M = the tile size listed above, sizeX/Z = the surface's world size in m\n"
- "const mat = new THREE.MeshStandardMaterial({ map: tex, roughness: 0.8, metalness: 0.0 });\n"
"```\n"
"Use `texture.clone()` (+ `needsUpdate = true`) when the same image needs a different repeat. "
"Never invent texture URLs, and keep procedural materials where no texture fits."
)
if ground:
lines.append(
- "\n**The ground is what this pack is for.** The single most repeated defect on this "
- "track is a ground that reads as one flat untextured colour. The recipe above "
- "blends ground COLOURS by height, slope and noise — keep that logic exactly, and "
- "blend these MAPS instead of (or multiplied by) the flat colours: "
- + ", ".join(f"`{n}`" for n in ground)
- + ". Sample each with its own `repeat`, mix them with the same masks the recipe "
- "builds, and keep the vertex-colour term as a tint rather than the whole albedo."
+ "\nThe judge lists a ground that reads as one flat untextured colour as a defect; these "
+ "ground maps are for it: " + ", ".join(f"`{n}`" for n in ground)
+ + ". How you blend them (height, slope, noise, paths) is yours."
)
return "\n".join(lines)
diff --git a/harness/codeverse3d/tracks/articulated_object.py b/harness/codeverse3d/tracks/articulated_object.py
index 518218e3..820c98fc 100644
--- a/harness/codeverse3d/tracks/articulated_object.py
+++ b/harness/codeverse3d/tracks/articulated_object.py
@@ -225,8 +225,8 @@ def axis_fix_hint(joint_name: str, axis: Sequence[float] | None, expected: str)
if axis is not None and len(axis) == 3:
neg = tuple(-float(a) for a in axis)
return (f"in src/robot.urdf set joint '{joint_name}' <axis xyz=\"{neg[0]:g} {neg[1]:g} {neg[2]:g}\"/> "
- f"(negate the axis) — or swap lower/upper so positive motion goes {expected}")
- return f"negate the <axis> of joint '{joint_name}' in src/robot.urdf (or swap lower/upper) so motion goes {expected}"
+ f"(negate the axis; keep lower/upper as they are, q=0 stays the rest pose) so positive motion goes {expected}")
+ return f"negate the <axis> of joint '{joint_name}' in src/robot.urdf (keep lower/upper as they are) so motion goes {expected}"
def _set_axis_in_urdf_text(text: str, urdf_joint: str, axis: tuple[float, float, float]) -> str | None:
diff --git a/harness/codeverse3d/tracks/candidates.py b/harness/codeverse3d/tracks/candidates.py
index e8732e64..30cd01a1 100644
--- a/harness/codeverse3d/tracks/candidates.py
+++ b/harness/codeverse3d/tracks/candidates.py
@@ -142,8 +142,7 @@ def make_candidate_context(track: Any, ctx: RunContext, k: int) -> RunContext:
if path.is_file():
shutil.copyfile(path, sub_ws.root / path.name)
if not ctx.single_shot:
- ctx.services.materialize(sub_ws, agent_kind=ctx.agent_kind, contract_md=track.agent_contract_md(ctx),
- cookbook_text=ctx.cookbook_text, spatial_tools=True)
+ ctx.services.materialize(sub_ws, agent_kind=ctx.agent_kind, contract_md=track.agent_contract_md(ctx), spatial_tools=True)
sub_ws.commit("skeleton")
# own event log (the run log keeps only candidate.*) and a one-sample judge for ranking
return replace(ctx, ws=sub_ws, extra={}, events=EventLog(sub_ws.events_path),
diff --git a/harness/codeverse3d/tracks/common.py b/harness/codeverse3d/tracks/common.py
index 10aca224..77049602 100644
--- a/harness/codeverse3d/tracks/common.py
+++ b/harness/codeverse3d/tracks/common.py
@@ -114,9 +114,9 @@ class Services:
return _import("codeverse3d.tracks.articulated_object", "default_joint_sweep")(ws, plan, out_dir)
# ---- agents' workspace materialisation + tool cards
- def materialize(self, ws: Workspace, *, agent_kind: str, contract_md: str, cookbook_text: str, spatial_tools: bool) -> None:
+ def materialize(self, ws: Workspace, *, agent_kind: str, contract_md: str, spatial_tools: bool) -> None:
_import("codeverse3d.agents.materialize", "materialize_workspace")(
- ws, agent_kind=agent_kind, contract_md=contract_md, cookbook_text=cookbook_text, spatial_tools=spatial_tools)
+ ws, agent_kind=agent_kind, contract_md=contract_md, spatial_tools=spatial_tools)
def tool_cards(self, track: str, language: str) -> str:
try:
@@ -155,7 +155,6 @@ class RunContext:
agent: Any | None = None # CodingAgent instance (agent path)
model: Any | None = None # ChatModel (single-shot path)
contract_text: str = ""
- cookbook_text: str = ""
tool_cards: str = ""
prompt_hashes: dict[str, str] = field(default_factory=dict)
extra: dict[str, Any] = field(default_factory=dict)
diff --git a/harness/codeverse3d/tracks/depth.py b/harness/codeverse3d/tracks/depth.py
index 4192732f..b18ebd30 100644
--- a/harness/codeverse3d/tracks/depth.py
+++ b/harness/codeverse3d/tracks/depth.py
@@ -23,8 +23,9 @@ on eight objective axes — is ``codeverse3d/spatial/complexity.py`` + ``eval/do
This module is the *target* side: what THIS plan should be allowed and asked to spend.
Hence: :func:`depth_budget` (how many triangles / how much build time this *plan*
-deserves, checked by :func:`budget_gate`; no generate / refine prompt states it — they
-get the numberless :data:`DETAIL_ADVICE`; how many PARTS a prompt deserves is
+deserves, checked by :func:`budget_gate`; the generate / refine briefs get the numberless
+:data:`DETAIL_ADVICE`, and each object language's ``contract.md`` states the gate's per-object
+constants as a measured requirement (D107, pinned in ``prompts/_claims.toml``); how many PARTS a prompt deserves is
``tracks.planner.plan_budget``, which also owns the thin-plan re-ask), and :func:`scope_groups` (how to split one plan into sessions small
enough that each part gets real attention) with :func:`interfaces_text` handing
each session the exact numbers of the parts it must touch but may not edit.
@@ -68,13 +69,13 @@ class DepthBudget:
max_build_s: int
-#: What the generate / refine prompts say about detail. No numbers: the triangle and build-time
-#: budget below is enforced by :func:`budget_gate`, whose findings state a number only when it is
-#: missed (owner, 2026-09-22).
+#: What the generate / refine briefs say about detail. No numbers: the triangle and build-time
+#: budget below is enforced by :func:`budget_gate`, whose findings state this object's numbers
+#: (owner, 2026-09-22); the per-built-object rule itself is in each object ``contract.md`` (D107).
DETAIL_ADVICE = (
- "- Spend detail INSIDE the parts the plan already names — bevels, chamfers, profile sweeps, "
- "fasteners, panel seams, arrays — not on new parts the plan does not list. Measured on this harness: "
- "detail inside a part is neutral-to-positive for the score, extra un-planned parts are strongly negative."
+ "- Spend detail INSIDE the parts the plan already names — the edges, profiles, seams and repeats the "
+ "real object carries — not on new parts the plan does not list. Measured on this harness: detail "
+ "inside a part is neutral-to-positive for the score, extra un-planned parts are strongly negative."
)
@@ -306,17 +307,17 @@ def budget_gate(measurement: Any, build: Any, budget: DepthBudget) -> Any:
gate=BUDGET_GATE, severity=Severity.ERROR, target="overall",
message=f"{tris:,} triangles exceeds this object's ceiling of {budget.max_tris:,} "
f"({budget.n_units} built objects × {TRIS_PER_UNIT_MAX:,})",
- fix_hint="lower the segment counts and subdivision levels on the heaviest parts; "
- "detail with bevels and arrays instead of dense meshes",
+ fix_hint=f"over this object's ceiling of {budget.max_tris:,}: reduce the segment / subdivision "
+ f"counts on the heaviest parts",
data={"kind": "over_tri_budget", "tris": tris, "max": budget.max_tris}))
elif tris < budget.min_tris:
findings.append(GateFinding(
gate=BUDGET_GATE, severity=Severity.WARN, target="overall",
message=f"{tris:,} triangles ({per_unit:.0f} per built object) is below this object's detail floor "
f"of {budget.min_tris:,} — it is a stack of primitives, not a modelled object",
- fix_hint=f"aim for {budget.target_tris:,} triangles: bevel every hard edge, add the panel seams, "
- f"fasteners and counted features the plan describes INSIDE the existing parts "
- f"(see the cookbook's Density chapter)",
+ fix_hint=f"{tris:,} triangles is under this object's floor of {budget.min_tris:,} (target "
+ f"{budget.target_tris:,}): add the detail the real object carries INSIDE the parts the "
+ f"plan names, not as new parts",
data={"kind": "under_tri_budget", "tris": tris, "floor": budget.min_tris,
"target": budget.target_tris, "per_unit": round(per_unit, 1)}))
ms = int(getattr(build, "duration_ms", 0) or 0)
diff --git a/harness/codeverse3d/tracks/generation.py b/harness/codeverse3d/tracks/generation.py
index 6ae83ad8..3176727e 100644
--- a/harness/codeverse3d/tracks/generation.py
+++ b/harness/codeverse3d/tracks/generation.py
@@ -57,7 +57,7 @@ from codeverse3d.cost.types import stage_for_label
from codeverse3d.models import get_chat_model
from codeverse3d.orchestrator import BudgetExceeded
from codeverse3d.proc import NULL_EVENTS, read_json_or_none
-from codeverse3d.workspace import Workspace
+from codeverse3d.workspace import C3D_DIR, Workspace
log = logging.getLogger(__name__)
@@ -66,8 +66,8 @@ log = logging.getLogger(__name__)
# (merged back from codeverse3d/tracks/envelope.py, 2026-08-28 — the split existed only
# to hold a re-export shim; this module was its one importer)
ALLOWED_ROOTS: tuple[str, ...] = ("src/", "public/")
-#: where an out-of-workspace task image is copied so a vendor CLI can read it (D9, like the cookbook)
-IMAGES_DIR = ".3dcode/images"
+#: where an out-of-workspace task image is copied so a vendor CLI can read it (D9: a CLI reads only inside its workspace)
+IMAGES_DIR = f"{C3D_DIR}/images"
class GenerationError(RuntimeError):
@@ -185,7 +185,7 @@ def write_files(
``only`` (an ``edit_only`` task's file scope, entry included when owned) skips a
path that ALREADY EXISTS and is not listed — new files stay allowed; ``frozen``
- (the language's harness-owned files and directories, ``src/recipes.glsl``, ``src/lib/``) is
+ (the language's harness-owned files and directories, e.g. a scene's ``src/lib/``) is
skipped outright (``is_harness_owned``, the CLI side's rule).
The single-shot envelope has no write-time gate, so this is where a scoped task is
stopped from rewriting a sibling's file — the mirror of the CLI backends' post-hoc
@@ -374,6 +374,24 @@ def single_shot_model_id(agent_id: str) -> str:
return agent_id[len(SINGLE_SHOT_PREFIX) :]
+#: the floor of a single-shot call's own deadline. A task's ``timeout_s`` caps its model call:
+#: an asset task (420 s) once held a runaway stream for ~20 minutes — 1 087 chunks before the
+#: retry layer gave up — and the stage that waited for it left the zones a 180 s session that
+#: wrote nothing (iteration 2 of the argon loop, 2026-10-15: 31 of 2 697 single-shot asset calls
+#: ran past 420 s, all the way to the retry ceiling). But a stage degraded to single-shot by a
+#: spent soft budget carries the budget's FLOOR as its timeout (120-180 s), shorter than a
+#: legitimate call (asset calls p50 96 s, p95 260 s) — the floor keeps those whole.
+SINGLE_SHOT_MIN_WAIT_S = 420.0
+
+
+def single_shot_wait_s(timeout_s: float | None, retry_deadline_s: float) -> float:
+ """The longest one single-shot generation may wait: the retry ceiling, capped by the task's own
+ timeout when it has one (never below :data:`SINGLE_SHOT_MIN_WAIT_S`)."""
+ if timeout_s is None:
+ return retry_deadline_s
+ return min(retry_deadline_s, max(float(timeout_s), SINGLE_SHOT_MIN_WAIT_S))
+
+
def generate_files(
ws: Workspace,
*,
@@ -395,9 +413,9 @@ def generate_files(
temperature=task.temperature,
thinking=task.thinking, # type: ignore[arg-type]
max_output_tokens=task.max_output_tokens,
- # the RUN's remaining wall clock, not the models' 1800 s default — and past
- # the hard ceiling this refuses to buy the call at all (agent-path symmetry)
- max_wait_s=_deadline_preflight(budget, RETRY_DEADLINE_S),
+ # the RUN's remaining wall clock AND the task's own window, not the models' 1800 s
+ # default — and past the hard ceiling this refuses to buy the call at all
+ max_wait_s=_deadline_preflight(budget, single_shot_wait_s(task.timeout_s, RETRY_DEADLINE_S)),
label=f"{task.label}:r{task.round:02d}",
)
@@ -425,7 +443,7 @@ def generate_files(
# the retry is a second full-price call: preflight the clock again and
# hand it only what is left of the run (BudgetExceeded past the ceiling)
req = req.model_copy(update={"max_output_tokens": grown,
- "max_wait_s": _deadline_preflight(budget, RETRY_DEADLINE_S)})
+ "max_wait_s": _deadline_preflight(budget, single_shot_wait_s(task.timeout_s, RETRY_DEADLINE_S))})
resp = ask(req)
usage = usage + resp.usage
traj = ws.trajectory_dir(task.label.replace("/", "_"), task.round)
@@ -672,7 +690,7 @@ def _images_block(images: list[ImagePart], ws: Workspace) -> str:
which no backend read, so the contact sheet the judge scored reached no CLI session
(that field is gone since 2026-08-30 — this block IS the delivery).
- Every image is copied into ``.3dcode/images/`` first, exactly as the cookbook is (D9),
+ Every image is copied into ``.3dcode/images/`` first (D9),
and listed workspace-relative: a CLI reads only INSIDE its workspace (``--image
ref.png`` stores the host's absolute path), and the judged contact sheet sits under
``artifacts/renders/``, which ``.antigravityignore`` hides from agy."""
@@ -730,7 +748,7 @@ def _envelope_scope(ws: Workspace, task: GenerationTask) -> tuple[set[str] | Non
def _read_only(language: str) -> list[str]:
- """The harness-owned files of the language (``src/recipes.glsl`` for glsl_shader): every session
+ """The harness-owned files of the language (``src/lib/`` for the scene languages): every session
of the run — baseline, refine, repair — may read them, none may write them."""
try:
return list(HARNESS_OWNED_SRC.get(Language(language), ()))
diff --git a/harness/codeverse3d/tracks/graphics.py b/harness/codeverse3d/tracks/graphics.py
index ea690d40..f4b1f856 100644
--- a/harness/codeverse3d/tracks/graphics.py
+++ b/harness/codeverse3d/tracks/graphics.py
@@ -2,8 +2,8 @@
Languages: glsl_shader (Shadertoy-style fragment shader) · opengl_python (raw
moderngl program). Reuses ``BaseTrack`` (lifecycle) and ``run_round`` (steps)
-unchanged; the track-specific pieces are the recipe seeding, the prompt context
-(no 3D frame) and the render step (the sampled frames + contact sheet as the RenderSet
+unchanged; the track-specific pieces are the prompt context (no 3D frame) and the
+render step (the sampled frames + contact sheet as the RenderSet
the ``shader_v2`` judge sees); the ``gl_frames`` gate is the build's own
(``BuildResult.gates``). Planning is ``tracks/planner.py``'s, like every track's
(template, worked example, T = 0.5, acceptance: all dispatched on the track there).
@@ -13,13 +13,10 @@ Refinement is always one whole-program task.
from __future__ import annotations
import logging
-import re
import shutil
-from dataclasses import dataclass
from pathlib import Path
from typing import Any
-from codeverse3d.config import get_settings
from codeverse3d.contracts.artifacts import (
BuildResult,
GateReport,
@@ -28,262 +25,28 @@ from codeverse3d.contracts.artifacts import (
RenderView,
Severity,
)
-from codeverse3d.contracts.common import HARNESS_OWNED_SRC, TRACK_INFO, Language, Track
+from codeverse3d.contracts.common import TRACK_INFO, Track
from codeverse3d.contracts.plan import GraphicsPlan, Plan
from codeverse3d.contracts.run import RoundRecord
from codeverse3d.languages._gl_common import JUDGE_TIMES, METRICS_NAME, SHEET_NAME, read_metrics
-from codeverse3d.languages.glsl_shader import (
- COMMON,
- COMMON_GLSL,
- FUNC_DEF,
- defined_functions,
- strip_comments,
-)
from codeverse3d.orchestrator import TaskGroup
from codeverse3d.prompts import render
-from codeverse3d.prompts.sections import Section, split_sections
from codeverse3d.record.deliverable import legacy_canonical_round
from codeverse3d.tracks.common import RunContext
from codeverse3d.tracks.generation import GenerationTask
-from codeverse3d.tracks.lifecycle import MATERIALIZE, SKELETON, BaseTrack, StageNode
+from codeverse3d.tracks.lifecycle import MATERIALIZE, SKELETON, BaseTrack
from codeverse3d.tracks.prompting import (
base_prompt_context,
- is_always_chapter,
judge_digest,
judged_sheet,
reference_images,
refine_inline_files,
- select_cookbook_chapters,
)
from codeverse3d.workspace import Workspace
log = logging.getLogger(__name__)
-# ===================================================================== recipe seeding
-#: the harness-owned recipe file (``contracts.common.HARNESS_OWNED_SRC``; ``AgentJob.read_only``)
-RECIPES_REL = HARNESS_OWNED_SRC[Language.GLSL_SHADER][0]
-HEADER = ("// harness-owned: verified cookbook recipes matched to this brief — READ-ONLY (the harness pastes this "
- "above src/common.glsl); call these functions from shader.frag")
-RESUME_HEADER = "// ---- appended on resume (recipes this file did not define yet) ----"
-TRIM_NOTE = "// {names}: provided by src/recipes.glsl (harness-owned, pasted above this file) — call them, do not redefine them"
-#: ``ctx.extra`` key → the prompt block (``[{name, signature, purpose}, …]``, every seeded recipe on disk)
-EXTRA_KEY = "seeded_recipes"
-#: chapters whose code is a TEMPLATE to adapt, not a library to call: the raymarching ``map()`` is the
-#: agent's own scene, and a seeded ``map`` / ``calcNormal`` would collide with the one it must write
-NOT_SEEDED: tuple[str, ...] = ("Raymarching",)
-
-#: what each recipe is for — one line in the header comment and in the prompt block
-PURPOSES: dict[str, str] = {
- "curtain": "ONE organic aurora / drapery / flame-sheet ribbon (folded lower edge, rays in bundles, gaps; "
- "k = 0 at the lower edge .. 1 at the top) — never a comb of bars",
- "auroraCol": "green-low → violet-crown aurora colour for the k that curtain() writes",
- "aurora": "the whole aurora: three curtains at different depths, nearest brightest "
- "(then col += au * 1.7 + au * au * 0.5 for bloom)",
- "stars": "dense sub-pixel star field on a grid (density 160 / 70, keep 0.2–0.3); add two layers",
- "bokehSoft": "soft gaussian city-light discs ADDED on a dark ground, three depth layers, pulsing",
- "dropsLayer": "rain on glass: (drop mask, trail) per grid cell scrolling down; refract the background with .x",
- "skyGrad": "dusk sky gradient by p.y", "sun": "sun disc with a soft halo",
- "waterHeight": "water surface height (waves + noise) for reflections / normals",
- "warped": "domain-warped fbm: billowy clouds, smoke, marble",
- "fbmVolume": "normalized five-octave 3D density field for bounded volumes",
- "beerTransmittance": "Beer extinction through a nonnegative distance; combine intervals multiplicatively",
- "phaseHG": "normalized Henyey-Greenstein phase; cosTheta uses light TRAVEL directions, +1 forward",
- "fresnelSchlick": "view-dependent RGB Fresnel reflectance from normal-incidence f0",
- "pbrDirect": "linear direct GGX surface lighting with correlated visibility, Fresnel and incident cosine",
- "hash11": "1D hash 0..1", "hash12": "2D → float hash 0..1", "hash22": "2D → vec2 hash", "hash33": "3D → vec3 hash",
- "noise": "smooth 2D value noise 0..1", "noise3": "3D value noise (volumes, time as z)",
- "fbm": "6-octave rotated fbm", "ridged": "ridged fbm (mountains, veins)",
- "palette": "IQ cosine palette", "tonemapACES": "ACES tonemap", "gamma": "gamma 2.2",
- "sdCircle": "2D circle SDF", "sdBox": "2D box SDF", "sdSegment": "2D segment SDF", "sdStar": "2D star SDF",
- "fill": "1-px anti-aliased fill of an SDF", "stroke": "anti-aliased outline of an SDF",
- "glow": "exponential glow around an SDF", "rot2": "2D rotation matrix",
-}
-
-_FENCE = re.compile(r"```glsl[ \t]*\n(.*?)^```", re.S | re.M)
-_CALL = re.compile(r"\b([A-Za-z_]\w*)\s*\(")
-_KEYWORDS = frozenset({"for", "if", "while", "switch", "return"})
-_DEFINE = re.compile(r"^[ \t]*#\s*define\s+(\w+)", re.M)
-#: top-level comment lines that are usage examples (``// usage: …``, ``// sunset: palette(…)``, a
-#: statement ending in ``;``), not documentation of the function that follows
-_USAGE = re.compile(r"^//\s*(?:usage|e\.g\.)\b|^//\s*[\w .-]+?:\s+\w+\(|;\s*(?://.*)?$", re.I)
-
-
-@dataclass(frozen=True)
-class Recipe:
- name: str
- signature: str
- text: str # doc comment lines + the complete definition
- calls: frozenset[str]
- chapter: str
-
- @property
- def purpose(self) -> str:
- return PURPOSES.get(self.name, f'from the cookbook chapter "{self.chapter}"')
-
- def entry(self) -> dict[str, str]:
- return {"name": self.name, "signature": self.signature, "purpose": self.purpose}
-
-
-def parse_functions(code: str, chapter: str = "") -> list[Recipe]:
- """Top-level function definitions in a GLSL text (``mainImage`` / ``main`` excluded), each with
- the documentation comment lines directly above it; usage comments and bare statements dropped."""
- lines = code.splitlines()
- out: list[Recipe] = []
- pending: list[str] = []
- i = 0
- while i < len(lines):
- raw = lines[i]
- s = raw.strip()
- if s.startswith("//"):
- pending = [] if _USAGE.search(s) else pending + [raw]
- i += 1
- continue
- m = FUNC_DEF.match(raw)
- if not s or not m: # blank, #define, or a bare statement snippet
- pending, i = [], i + 1
- continue
- depth, opened, j = 0, False, i
- while j < len(lines):
- code_only = strip_comments(lines[j])
- depth += code_only.count("{") - code_only.count("}")
- opened = opened or "{" in code_only
- j += 1
- if opened and depth <= 0:
- break
- body = lines[i:j]
- head = strip_comments(body[0])
- signature = (head[: head.index(")") + 1] if ")" in head else head).strip()
- text = "\n".join(pending + body)
- if m.group(1) not in ("mainImage", "main"):
- calls = frozenset(_CALL.findall(strip_comments(text))) - _KEYWORDS - {m.group(1)}
- out.append(Recipe(m.group(1), signature, text, calls, chapter))
- pending, i = [], j
- return out
-
-
-def chapter_functions(section: Section) -> list[Recipe]:
- return [r for block in _FENCE.findall(section.body) for r in parse_functions(block, section.title)]
-
-
-def cookbook_functions(md: str) -> dict[str, Recipe]:
- """Every function the cookbook defines, by name, in cookbook order (first definition wins)."""
- out: dict[str, Recipe] = {}
- for sec in split_sections(md):
- for r in chapter_functions(sec):
- out.setdefault(r.name, r)
- return out
-
-
-def defined_names(glsl: str) -> set[str]:
- """Function and ``#define`` names a GLSL file already defines (what a seed must not repeat)."""
- names = set(_DEFINE.findall(glsl))
- names.update(defined_functions(glsl))
- return names
-
-
-def with_helpers(wanted: list[Recipe], known: dict[str, Recipe]) -> list[Recipe]:
- """``wanted`` plus every cookbook function they call (transitively), callees before callers."""
- order: list[Recipe] = []
- seen: set[str] = set()
-
- def visit(r: Recipe) -> None:
- if r.name in seen:
- return
- seen.add(r.name)
- for dep in (n for n in known if n in r.calls):
- visit(known[dep])
- order.append(r)
-
- for r in wanted:
- visit(known.get(r.name, r))
- return order
-
-
-def graphics_brief(ctx: RunContext) -> str:
- """The text the cookbook selection (prompt excerpt AND seeded recipes) is matched against."""
- plan = ctx.plan if isinstance(ctx.plan, GraphicsPlan) else None
- return ctx.spec.prompt + " " + " ".join(plan.key_visuals if plan else [])
-
-
-def recipe_chapters(ctx: RunContext) -> list[Section]:
- """The brief's cookbook chapters minus the always-on ones and the templates (``NOT_SEEDED``)."""
- return [s for s in select_cookbook_chapters(ctx, graphics_brief(ctx))
- if s.level >= 2 and not is_always_chapter(s.title) and not is_always_chapter(s.title, NOT_SEEDED)]
-
-
-def seeded_on_disk(glsl: str, known: dict[str, Recipe]) -> list[Recipe]:
- """The cookbook recipes a ``src/recipes.glsl`` carries, in file order (a file without the harness
- header is not a seed; only cookbook names count)."""
- if HEADER not in glsl:
- return []
- return [known[r.name] for r in parse_functions(glsl) if r.name in known]
-
-
-def is_skeleton_common(text: str) -> bool:
- """Is this ``src/common.glsl`` still the harness skeleton — untouched, or only ever trimmed by
- :func:`trim_skeleton_common`? (Every function it defines is the skeleton's own, verbatim.)"""
- if text == COMMON_GLSL:
- return True
- skeleton = {r.name: r.text for r in parse_functions(COMMON_GLSL)}
- return (text.startswith(COMMON_GLSL.splitlines()[0])
- and defined_names(text) <= defined_names(COMMON_GLSL)
- and all(skeleton.get(r.name) == r.text for r in parse_functions(text)))
-
-
-def trim_skeleton_common(path: Path, provided: set[str]) -> list[str]:
- """Drop from the SKELETON's ``src/common.glsl`` the helpers ``src/recipes.glsl`` now provides — it is
- pasted first, so a second ``hash12`` in common.glsl is a redefinition and the first build would fail
- before the agent wrote a line. Acts only while the file is still the harness's own skeleton text
- (the agent has not seen it yet); once the agent owns common.glsl a duplicate is its own to remove,
- and the lint names it. Returns the names dropped."""
- if not path.is_file():
- return []
- text = path.read_text(errors="replace")
- if not is_skeleton_common(text):
- return []
- dropped = [r for r in parse_functions(text) if r.name in provided]
- if not dropped:
- return []
- for r in dropped:
- text = text.replace(r.text + "\n", "", 1)
- text = re.sub(r"\n{3,}", "\n\n", text)
- first, rest = text.split("\n", 1)
- note = TRIM_NOTE.format(names=", ".join(r.name for r in dropped))
- path.write_text(f"{first}\n{note}\n{rest}")
- return [r.name for r in dropped]
-
-
-def seed_recipes(ctx: RunContext) -> list[str]:
- """Write the brief's verified recipes (+ their helpers) to the harness-owned ``src/recipes.glsl``
- (a resume appends only names the file does not define yet); return the names written THIS call.
- ``ctx.extra["seeded_recipes"]`` lists every seeded recipe on disk (for the prompt block);
- ``recipes.seeded`` is emitted with both. No-op unless glsl_shader and enabled."""
- if ctx.language is not Language.GLSL_SHADER or not get_settings().limits.seed_recipes:
- return []
- known = cookbook_functions(ctx.cookbook_text or "")
- chapters = recipe_chapters(ctx)
- wanted = [r for s in chapters for r in chapter_functions(s)]
- path: Path = ctx.ws.root / RECIPES_REL
- existing = path.read_text(errors="replace") if path.is_file() else ""
- have = defined_names(existing)
- new = [r for r in with_helpers(wanted, known) if r.name not in have]
- trimmed: list[str] = []
- if new:
- head = [HEADER] if not existing else [RESUME_HEADER]
- block = [*head, *(f"// {r.signature} — {r.purpose}" for r in new), "", *(r.text for r in new)]
- lead = "" if not existing else ("" if existing.endswith("\n") else "\n") + "\n"
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(existing + lead + "\n".join(block) + "\n")
- existing = path.read_text(errors="replace")
- trimmed = trim_skeleton_common(ctx.ws.root / COMMON, defined_names(existing))
- present = seeded_on_disk(existing, known)
- ctx.extra[EXTRA_KEY] = [r.entry() for r in present]
- ctx.events.emit("recipes.seeded", file=RECIPES_REL, names=[r.name for r in new], present=[r.name for r in present],
- chapters=[s.title for s in chapters], trimmed=trimmed)
- return [r.name for r in new]
-
-
# ===================================================================== prompt context + frames
def passes_table(plan: GraphicsPlan | None) -> str:
if plan is None or not plan.passes:
@@ -299,8 +62,6 @@ def graphics_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:
plan = ctx.plan if isinstance(ctx.plan, GraphicsPlan) else None
res = plan.resolution if plan else (1280, 720)
return base_prompt_context(ctx, **{
- # the recipes seed_recipes() put in the harness-owned src/recipes.glsl before the session ([] = no block)
- "seeded_recipes": list(ctx.extra.get(EXTRA_KEY) or []),
"title": plan.title if plan else "Untitled effect",
"style": plan.style if plan else "", "resolution": f"{res[0]}x{res[1]}", "duration": f"{plan.duration_s:g}" if plan else "8",
"passes_table": passes_table(plan), "motion": plan.motion if plan else "", "key_visuals": list(plan.key_visuals) if plan else [],
@@ -364,15 +125,6 @@ def frame_stats_text(ws: Workspace, round_index: int | None = None) -> str:
return "\n".join(lines)
-def _commit_recipes(ctx: RunContext) -> None:
- """The brief's verified cookbook recipes into the harness-owned, read-only src/recipes.glsl
- (seed_recipes: measured, flash does not call a recipe it is only shown — and a recipe seeded
- into its own common.glsl was overwritten by the end of the run, so the file is one the agent
- cannot write: AgentJob.read_only). Idempotent (a resume adds only missing names): uncached."""
- if seed_recipes(ctx):
- ctx.ws.commit("recipes")
-
-
class GraphicsPipeline:
"""No measurement; no gates of its own — the build's ``gl_frames`` report is the round's
gate (``BuildResult.gates``, appended by ``steps``); render = the frames."""
@@ -400,7 +152,7 @@ class GraphicsTrack(BaseTrack):
# refinement is always ONE whole-program task
allow_refine_fanout = False
baseline_temperature = 0.6
- stages = (SKELETON, StageNode("recipes", lambda t, c: _commit_recipes(c)), MATERIALIZE)
+ stages = (SKELETON, MATERIALIZE)
def make_pipeline(self) -> GraphicsPipeline:
return GraphicsPipeline()
diff --git a/harness/codeverse3d/tracks/lifecycle.py b/harness/codeverse3d/tracks/lifecycle.py
index 5b6be784..8063b66d 100644
--- a/harness/codeverse3d/tracks/lifecycle.py
+++ b/harness/codeverse3d/tracks/lifecycle.py
@@ -21,6 +21,7 @@ from datetime import UTC, datetime
from pathlib import Path
from typing import Any
+from codeverse3d.agents.materialize import needs_rematerialize
from codeverse3d.config import Settings, get_settings
from codeverse3d.contracts.artifacts import GateReport
from codeverse3d.contracts.common import TRACK_INFO, Track
@@ -188,7 +189,7 @@ def _skeleton(track: BaseTrack, ctx: RunContext) -> list[str]:
#: the buildable placeholder of every file the plan names
SKELETON = StageNode("skeleton", _skeleton, key=lambda c: {"plan": c.plan, "language": c.language.value}, seeds_src=True)
-#: the vendor CLI's workspace files (AGENTS.md, MCP config, the cookbook copy): once per agent kind
+#: the vendor CLI's workspace files (AGENTS.md / CLAUDE.md, the ignore file): once per agent kind
MATERIALIZE = StageNode("materialize", lambda t, c: t.ensure_materialized(c))
#: a stage boundary: the run stops here when the hard budget is spent
CLOCK = StageNode("clock", lambda t, c: c.budget.check())
@@ -311,7 +312,7 @@ class BaseTrack:
"""Regenerate after a failed build: the generate prompt + the error report."""
files = ctx.runtime.expected_files(ctx.plan)
lint = next((g for g in last.gates if g.gate.startswith("lint")), GateReport(gate="lint", passed=True))
- report = format_error_report(last.build, lint, ctx.cookbook_text) if last.build else "build did not run"
+ report = format_error_report(last.build, lint) if last.build else "build did not run"
prompt = render(self.generate_template, **self.generate_context(
ctx, skeleton_files=refine_inline_files(ctx, files), previous_error=report))
return GenerationTask(label="rebuild", prompt=prompt, system=self.system_prompt(ctx), files_hint=files, round=index,
@@ -508,11 +509,8 @@ class BaseTrack:
agent=metered_agent(self._agent), model=metered_chat_model(self._model),
variant=active_variant())
ctx.contract_text = language_text(spec.language, "contract.md")
- ctx.cookbook_text = language_text(spec.language, "cookbook.md")
ctx.tool_cards = self.services.tool_cards(self.track.value, spec.language.value)
- for name, text in (("contract", ctx.contract_text), ("cookbook", ctx.cookbook_text)):
- if text: # a language without a cookbook (the scene languages) records no hash for one
- ctx.record_prompt(name, text)
+ ctx.record_prompt("contract", ctx.contract_text)
return ctx
def _resolve_candidates(self, spec: Spec, settings: Settings) -> int:
@@ -574,10 +572,9 @@ class BaseTrack:
if ctx.single_shot:
return
kind = ctx.agent_kind
- if ctx.state.materialized_for == kind:
+ if ctx.state.materialized_for == kind and not needs_rematerialize(ctx.ws):
return
- self.services.materialize(ctx.ws, agent_kind=kind, contract_md=self.agent_contract_md(ctx), cookbook_text=ctx.cookbook_text,
- spatial_tools=True)
+ self.services.materialize(ctx.ws, agent_kind=kind, contract_md=self.agent_contract_md(ctx), spatial_tools=True)
ctx.state.materialized_for = kind
ctx.state.save(ctx.ws)
ctx.events.emit("workspace.materialized", agent_kind=kind)
diff --git a/harness/codeverse3d/tracks/plan_features.py b/harness/codeverse3d/tracks/plan_features.py
index d2b0a51c..7a8b35fe 100644
--- a/harness/codeverse3d/tracks/plan_features.py
+++ b/harness/codeverse3d/tracks/plan_features.py
@@ -20,7 +20,7 @@ from codeverse3d.config import Settings
#: planner templates included, and its name is part of the plan stage key
#: (``lifecycle.plan_stage_key``) — two arms that differ by variant must each plan.
GENERATION_SIDE_ENV: frozenset[str] = frozenset({"C3D_SKILLS", "C3D_SKILLS_MAX", "C3D_SKILLS_UNVERIFIED",
- "C3D_SKILLS_ONLY", "C3D_REFERENCE_DIFF", "C3D_SEED_RECIPES"})
+ "C3D_SKILLS_ONLY", "C3D_REFERENCE_DIFF"})
#: the two the node side reads itself (runtime_js: gpu_launch.cjs, browser_daemon.cjs)
NODE_SIDE_ENV: frozenset[str] = frozenset({"C3D_BROWSER_REUSE", "C3D_PAGE_TTL_MS"})
diff --git a/harness/codeverse3d/tracks/planner.py b/harness/codeverse3d/tracks/planner.py
index 0a8cc080..d0072301 100644
--- a/harness/codeverse3d/tracks/planner.py
+++ b/harness/codeverse3d/tracks/planner.py
@@ -278,12 +278,13 @@ class PlanBudget:
"min_assemblies": self.min_assemblies, "budget_evidence": self.evidence, "reason": self.reason}
-#: the graphics track counts PASSES, not parts: a fragment shader is a stack of layers and
-#: more than ~6 stops being a plan and starts being a wish-list. Recorded mean was 3.1 on
-#: graphics_v2 (0.530 / 12% pass) and pass count is the ONE complexity metric that
-#: correlates positively with the judge there (visual_richness +0.40).
+#: the graphics track counts PASSES, not parts: more than ~6 stops being a plan and starts
+#: being a wish-list. The floor is 1 (D107): pass count correlated with the judge on
+#: graphics_v2 (visual_richness +0.40, mean 3.1 passes), but a correlation is not a requirement,
+#: and a mandated layer stack was the graphics twin of D106's three-depth-layer rule. Only a
+#: checklist long enough to be evidence (``EVIDENCE_MIN_CHECKLIST``) raises a floor.
GRAPHICS_CAP = 6
-GRAPHICS_MIN = 3
+GRAPHICS_MIN = 1
def plan_budget(spec: Spec, brief: EngineeringBrief | None = None) -> PlanBudget:
@@ -297,7 +298,7 @@ def plan_budget(spec: Spec, brief: EngineeringBrief | None = None) -> PlanBudget
cap = PART_CAP.get(spec.language.value, DEFAULT_PART_CAP)
n_must = len(spec.constraints.must_have)
reasons = []
- want = MIN_PARTS
+ want = 0
if n_must:
# one part (or sub-part) per checklist item is PARITY, not padding: the measured
# ratio on the hard battery was 0.91 parts per checklist item, and the runs with the
@@ -313,7 +314,10 @@ def plan_budget(spec: Spec, brief: EngineeringBrief | None = None) -> PlanBudget
# externally visible features drive the LEAF budget, not the top-level part count:
# "six vertical flutes on the body" is a sub-part of the body, not a part of its own.
n_visible = len(brief.visible_from_outside)
+ # ``target`` sizes the answer (plan_tokens) and never drops below MIN_PARTS; the FLOOR is the
+ # request's own count, so a 4-item checklist is never told it needs 6 parts (D107)
target = max(MIN_PARTS, min(cap, int(want)))
+ floor = max(2, int(round(0.85 * min(cap, int(want)))))
min_assemblies = 0
if brief is not None:
min_assemblies = min(3, sum(1 for s in brief.sub_assemblies if len(s.parts) >= 3))
@@ -321,12 +325,12 @@ def plan_budget(spec: Spec, brief: EngineeringBrief | None = None) -> PlanBudget
min_assemblies = 1
return PlanBudget(
target_parts=target,
- min_parts=max(MIN_PARTS, int(round(0.85 * target))),
+ min_parts=floor,
cap_parts=cap,
target_leaves=max(target + 4, int(round(1.8 * target)), n_visible + 2 * min_assemblies),
- min_detail_parts=max(2, int(round(0.35 * target))),
+ min_detail_parts=min(floor, max(2, int(round(0.35 * target)))),
min_assemblies=min_assemblies,
- reason="; ".join(reasons) or "no checklist — default floor",
+ reason="; ".join(reasons) or "no checklist",
evidence=n_must >= EVIDENCE_MIN_CHECKLIST or brief is not None,
)
@@ -337,27 +341,32 @@ def _graphics_budget(spec: Spec) -> PlanBudget:
target = max(GRAPHICS_MIN, min(GRAPHICS_CAP, GRAPHICS_MIN + (n_must + 1) // 3))
return PlanBudget(
target_parts=target, min_parts=max(GRAPHICS_MIN, target - 1), cap_parts=GRAPHICS_CAP,
- target_leaves=4 * target, min_detail_parts=max(2, target - 1), min_assemblies=max(2, target - 2),
- reason=f"{n_must} checklist items" if n_must else "no checklist — default floor",
+ target_leaves=4 * target, min_detail_parts=max(1, target - 1), min_assemblies=0,
+ reason=f"{n_must} checklist items" if n_must else "no checklist",
evidence=n_must >= EVIDENCE_MIN_CHECKLIST)
def budget_block(budget: PlanBudget, *, unit: str = "parts") -> str:
- """The budget as a prompt block for the planner's user message."""
- return "\n".join([
- f"PLAN BUDGET (derived from this request: {budget.reason}):",
- f"- aim for {budget.target_parts} top-level {unit} (hard floor {budget.min_parts}, hard ceiling "
- f"{budget.cap_parts}); a plan under the floor will be rejected and re-asked.",
- f"- at least {budget.min_detail_parts} of them must carry detail a plain primitive cannot express "
- + ("(named elements with their own counts, sizes and speeds)." if unit == "passes" else
- "(a taper, a bevel radius, a groove, a counted repeat: '7 slats', '24 spokes')."),
- (f"- at least {budget.min_assemblies} of them must use "
- + ("`elements` (3-6 named things the pass draws)." if unit == "passes"
- else "`children` (3-6 sub-parts) because they are ASSEMBLIES, not shapes.")
- if budget.min_assemblies else
- "- use `children` for any part a fitter would call an assembly rather than a shape."),
- f"- total named shapes across {unit} and their sub-parts should reach about {budget.target_leaves}.",
- ])
+ """The budget as a prompt block for the planner's user message.
+
+ A floor and a detail minimum are stated only when the request is EVIDENCE of them (a brief,
+ or a checklist of :data:`EVIDENCE_MIN_CHECKLIST` items) — the only case the quality gate
+ enforces them; otherwise the block states the ceiling and nothing that sets a count (D107)."""
+ lines = [f"PLAN BUDGET (derived from this request: {budget.reason}):"]
+ if budget.evidence:
+ lines.append(f"- plan at least {budget.min_parts} top-level {unit} (ceiling {budget.cap_parts}); "
+ "a plan under that is re-asked.")
+ lines.append(f"- at least {budget.min_detail_parts} of them say what a plain "
+ + ("fill cannot: the technique by name, or the pass's own quantities." if unit == "passes" else
+ "primitive cannot, where the real object has it: a profile, an edge radius, a counted "
+ "repeat, or the sub-shapes it is made of.")
+ + " A plan with fewer is re-asked.")
+ else:
+ lines.append(f"- as many top-level {unit} as the " + ("effect" if unit == "passes" else "object")
+ + f" really has (ceiling {budget.cap_parts}); nothing here sets a count.")
+ if unit != "passes":
+ lines.append("- `children` for a part a fitter would call an assembly rather than a shape.")
+ return "\n".join(lines)
# ----------------------------------------------------------------------------- quality gate
@@ -381,7 +390,7 @@ def plan_quality_complaint(plan_obj: Any, budget: PlanBudget, *, unit: str = "pa
soft: list[str] = []
if budget.evidence and len(parts) < budget.min_parts:
hard.append(
- f"Only {len(parts)} {unit} for a request that needs about {budget.target_parts} "
+ f"Only {len(parts)} {unit} for a request that needs at least {budget.min_parts} "
f"({budget.reason}). Split the ones that are really assemblies and add the features you skipped — "
f"do NOT pad with duplicates.")
detector = has_pass_detail if unit == "passes" else has_real_detail
@@ -389,17 +398,19 @@ def plan_quality_complaint(plan_obj: Any, budget: PlanBudget, *, unit: str = "pa
or getattr(p, "children", None) or getattr(p, "elements", None)]
if len(detailed) < budget.min_detail_parts:
plain = [p.name for p in parts if p not in detailed][:8]
- hard.append(
+ # enforced only on EVIDENCE (a brief, or a long checklist): without it the request never
+ # said the object has shaping a primitive cannot express — "a stool" may be four boxes
+ (hard if budget.evidence else soft).append(
f"This plan is boxes at different sizes: only {len(detailed)} of {len(parts)} {unit} describe anything a "
- f"plain primitive cannot express, and at least {budget.min_detail_parts} must. Rewrite "
- f"{', '.join(plain)} with real construction: profile (tapered / fluted / bevelled r=…), counted repeats "
- f"('7 slats at 12 mm pitch'), edge treatment, and the sub-shapes each one is actually made of.")
+ f"plain primitive cannot express, and this request needs at least {budget.min_detail_parts}. Rewrite "
+ f"{', '.join(plain)} where the real thing has it: a profile, a stated radius or edge "
+ f"treatment, a counted repeat, or the sub-shapes it is actually made of.")
if budget.min_assemblies:
- n_nested = sum(1 for p in parts if len(getattr(p, nest, None) or []) >= 2)
+ n_nested = sum(1 for p in parts if getattr(p, nest, None))
if n_nested < budget.min_assemblies:
soft.append(
f"{n_nested} of the {unit} use `{nest}`, but this request has at least {budget.min_assemblies} real "
- f"sub-assemblies. Give each of them 3-6 `{nest}`" +
+ f"sub-assemblies. Give each of them its `{nest}`" +
("" if unit == "passes" else " with their own bboxes (inside the parent's) and materials") +
f"; leave the simple {unit} alone.")
materials = {(getattr(p, "material", "") or "").strip().lower() for p in parts} - {""}
@@ -478,22 +489,27 @@ def plan_example(track: Track, language: Language | None = None) -> dict[str, An
asset["kind"] = "bpy"
return example
if track is Track.GRAPHICS:
+ # the SCHEMA on an effect nobody asked for (no battery prompt is a tide pool) — two passes
+ # because this effect has two, never a pass list, a layering or a post chain to copy
return {
- "title": "Neon rain on a window", "summary": "Looking through a rain-streaked window at a neon-lit street at night; "
- "drops run down the glass, city lights turn into coloured bokeh discs that pulse.",
- "style": "cyberpunk night: deep indigo/black base, magenta + cyan neon accents, warm sodium highlights; soft, filmic",
+ "title": "Tide pool ripples", "summary": "Looking straight down into a shallow tide pool: pebbles and weed on "
+ "the floor, rings spreading from drops that fall at irregular intervals; light shifts over the pebbles.",
+ "style": "naturalistic: wet slate greys and ochre pebbles, olive weed, cold sky-blue reflections; soft, glossy",
"resolution": [1280, 720], "duration_s": 8.0,
"passes": [
- {"name": "CityBokeh", "kind": "fullscreen", "description": "background: 40-60 blurred bokeh discs (hash-placed, 3 depth layers, cyan/magenta/amber), slow horizontal parallax, pulsing brightness"},
- {"name": "RainDrops", "kind": "fullscreen", "description": "grid-cell drops with hash offsets, running trails (fract(t) per cell), refraction offset applied when sampling the background"},
- {"name": "Grade", "kind": "postprocess", "description": "vignette, slight chromatic aberration, tonemap + gamma"},
+ {"name": "PoolFloor", "kind": "fullscreen", "description": "rounded pebbles 0.03-0.08 of screen height packed "
+ "over sand, a few olive weed strands, seen through the water and displaced by the surface's slope"},
+ {"name": "SurfaceRipples", "kind": "fullscreen", "description": "rings expanding from drop points at about 0.15 "
+ "screen heights per second and fading over 3 s; their slope bends the floor and carries the sky's reflection",
+ "elements": ["drop rings, 1-3 alive at a time"],
+ "detail_hint": "two rings that cross interfere instead of one overwriting the other"},
],
"uniforms": ["u_time", "u_resolution"],
- "motion": "drops slide down with gravity and wobble; bokeh drifts left 0.02/s and pulses at 0.5-1 Hz; no hard cuts",
- "key_visuals": ["rain drops with trails on glass", "blurred neon bokeh discs", "dark night street behind", "magenta/cyan palette"],
+ "motion": "new drops land at irregular intervals and their rings spread and fade; the weed sways slowly; no hard cuts",
+ "key_visuals": ["pebbles under shallow water", "expanding ripple rings", "light shifting over the floor"],
"acceptance": [
- {"id": "a1", "text": "Raindrops with trails visibly run down the glass (compare t=0 and t=1)", "how": "visual", "priority": "must"},
- {"id": "a2", "text": "Blurred coloured bokeh lights are visible in the background", "how": "visual", "priority": "must"},
+ {"id": "a1", "text": "Ripple rings visibly expand between t=0 and t=1", "how": "visual", "priority": "must"},
+ {"id": "a2", "text": "Pebbles are visible through the water and bend where a ring passes", "how": "visual", "priority": "must"},
{"id": "a3", "text": "Frames change over time (no static image)", "how": "probe", "priority": "must"},
],
}
@@ -535,35 +551,46 @@ def plan_example(track: Track, language: Language | None = None) -> dict[str, An
"acceptance": [{"id": "a1", "text": "Two boats float on the water inside the basin", "how": "visual", "priority": "must"},
{"id": "a2", "text": "Quay top at y≈1.2 m, boats' waterline at y≈0", "how": "probe", "priority": "must"}],
}
+ # The SCHEMA on an object nobody asks for (a profile, a counted repeat, a nested assembly,
+ # an instanced row) — never a part list, a layout or numbers to copy. Upright's one-copy
+ # bbox is what c3d-repeats-and-mirrors points at.
parts = [
- {"name": "Seat", "role": "horizontal seat board", "description": "solid oak board, 40 mm thick, rounded front edge (r=10 mm)",
- "bbox": {"center": [0, 0, 0.43], "extents": [0.42, 0.40, 0.04]}, "material": "oiled oak", "attach_to": None, "symmetry": "mirror_x", "instances": 1,
- "children": [], "detail_hint": "the eye lands here first — keep the 10 mm bullnose and the 3 mm chamfer under the front edge"},
- {"name": "FrontLeg", "role": "front leg", "description": "tapered round leg 35→25 mm, splayed 6° outward",
- "bbox": {"center": [0.17, -0.16, 0.205], "extents": [0.035, 0.035, 0.41]}, "material": "oiled oak", "attach_to": "Seat", "symmetry": "mirror_x", "instances": 2,
- "children": [], "detail_hint": ""},
- {"name": "Backrest", "role": "slatted back assembly", "description": "three vertical slats in a curved top rail and a lower rail",
- "bbox": {"center": [0, 0.19, 0.66], "extents": [0.40, 0.03, 0.42]}, "material": "oiled oak", "attach_to": "Seat", "symmetry": "none", "instances": 1,
- "detail_hint": "an assembly, not a panel: the gaps between the slats must be visible from the front and the side",
+ {"name": "Base", "role": "weighted foot", "description": "disc 400 mm dia, 30 mm thick, top edge rounded r=8 mm, "
+ "four 20 mm square sockets for the uprights",
+ "bbox": {"center": [0, 0, 0.015], "extents": [0.40, 0.40, 0.03]}, "material": "cast iron, satin black", "attach_to": None,
+ "symmetry": "none", "instances": 1, "children": [], "detail_hint": "the rounded edge and the four sockets are what reads at floor level"},
+ {"name": "Upright", "role": "vertical bar", "description": "square bar 20 mm, upper 100 mm tapered to 14 mm, foot seated in a base socket",
+ "bbox": {"center": [0.16, 0, 0.455], "extents": [0.02, 0.02, 0.85]}, "material": "oiled ash, pale", "attach_to": "Base",
+ "symmetry": "radial", "instances": 4, "children": [], "detail_hint": ""},
+ {"name": "TopFrame", "role": "pegged ring the bunches hang from", "description": "flat ring on the upright tops, crossed by "
+ "two bars, pegs round the rim and a finial at the crossing",
+ "bbox": {"center": [0, 0, 0.905], "extents": [0.42, 0.42, 0.05]}, "material": "oiled ash, pale", "attach_to": "Upright",
+ "symmetry": "radial", "instances": 1, "detail_hint": "an assembly, not a disc: the gaps between ring, bars and pegs show from every side",
"children": [
- {"name": "TopRail", "role": "curved crest rail", "description": "60 mm deep rail bowed 18 mm back on a 0.9 m radius, ends rounded r=8 mm",
- "bbox": {"center": [0, 0.19, 0.85], "extents": [0.40, 0.03, 0.06]}, "material": "oiled oak", "instances": 1},
- {"name": "Slat", "role": "vertical back slat", "description": "12 mm thick slat, 55 mm wide, 4 mm chamfer both faces, 30 mm gap to its neighbour",
- "bbox": {"center": [0, 0.19, 0.66], "extents": [0.055, 0.012, 0.34]}, "material": "oiled oak", "instances": 3},
- {"name": "LowerRail", "role": "rail the slats seat into", "description": "40 mm rail with three 12 × 55 mm mortises on 85 mm centres",
- "bbox": {"center": [0, 0.19, 0.48], "extents": [0.40, 0.03, 0.04]}, "material": "oiled oak", "instances": 1},
+ {"name": "Ring", "role": "flat ring", "description": "outer dia 340 mm, 20 mm wide, 12 mm thick, edges rounded r=3 mm",
+ "bbox": {"center": [0, 0, 0.886], "extents": [0.34, 0.34, 0.012]}, "instances": 1},
+ {"name": "CrossBar", "role": "bar across the ring", "description": "20 × 12 mm bar, ends halved into the ring",
+ "bbox": {"center": [0, 0, 0.886], "extents": [0.34, 0.02, 0.012]}, "instances": 2},
+ {"name": "Peg", "role": "hanging peg", "description": "12 turned pegs 10 mm dia, 40 mm proud of the rim, ends domed",
+ "bbox": {"center": [0.19, 0, 0.886], "extents": [0.04, 0.01, 0.01]}, "instances": 12},
+ {"name": "Finial", "role": "knob at the crossing", "description": "turned knob 40 mm dia on a 10 mm neck",
+ "bbox": {"center": [0, 0, 0.911], "extents": [0.04, 0.04, 0.038]}, "instances": 1},
]},
]
base: dict[str, Any] = {
- "object_name": "DiningChair", "summary": "Mid-century oak dining chair, 0.45 × 0.50 × 0.82 m.",
- "overall_bbox": {"center": [0, 0, 0.41], "extents": [0.45, 0.50, 0.82]},
- "style_notes": "Danish mid-century: tapered legs, thin spindles, warm oak, no ornament.",
+ "object_name": "HerbDryingRack",
+ "summary": "Free-standing herb drying rack: a round iron foot, four tapered uprights and a pegged top ring, 0.42 × 0.42 × 0.93 m.",
+ "overall_bbox": {"center": [0, 0, 0.465], "extents": [0.42, 0.42, 0.93]},
+ "style_notes": "Scandinavian kitchen craft: pale oiled ash on a black iron foot, rounded edges, no ornament.",
"parts": parts,
- "acceptance": [{"id": "a1", "text": "Seat top at 0.45 m ± 0.02 m above the ground", "how": "measure", "priority": "must"},
- {"id": "a2", "text": "Four legs, all touching the ground, splayed outward", "how": "visual", "priority": "must"}],
+ "acceptance": [{"id": "a1", "text": "Overall height 0.93 m ± 0.02 m", "how": "measure", "priority": "must"},
+ {"id": "a2", "text": "Four uprights stand in the foot, which rests flat on the ground", "how": "visual", "priority": "must"}],
}
if track is Track.ARTICULATED_OBJECT:
base["object_name"] = "DeskDrawerUnit"
+ base["summary"] = "Painted desk drawer unit, 0.40 × 0.50 × 0.60 m: one drawer on side runners."
+ base["overall_bbox"] = {"center": [0, 0, 0.3], "extents": [0.4, 0.5, 0.6]}
+ base["style_notes"] = "Plain painted carcass, a shadow gap round the drawer, one metal pull."
base["parts"] = [
{"name": "Cabinet", "role": "fixed carcass", "description": "18 mm carcass, 6 mm rebated back, 3 mm shadow gap round the drawer opening",
"bbox": {"center": [0, 0, 0.3], "extents": [0.4, 0.5, 0.6]}, "material": "painted MDF", "attach_to": None, "symmetry": "none", "instances": 1,
@@ -585,7 +612,10 @@ def plan_example(track: Track, language: Language | None = None) -> dict[str, An
base["root_link"] = "Cabinet"
base["joints"] = [{"name": "DrawerSlide", "type": "prismatic", "parent": "Cabinet", "child": "Drawer", "axis": [0, -1, 0],
"pivot": [0, -0.02, 0.45], "lower": 0.0, "upper": 0.35, "rest": 0.0, "motion": "drawer pulls out towards -Y"}]
- base["acceptance"].append({"id": "j1", "text": "Drawer slides out 0.35 m along -Y without penetrating the cabinet", "how": "articulation", "priority": "must"})
+ # its own checks, not the chair's: the base's seat-height / four-legs items describe another object
+ base["acceptance"] = [{"id": "a1", "text": "Cabinet top at 0.60 m ± 0.02 m above the ground", "how": "measure", "priority": "must"},
+ {"id": "a2", "text": "Cabinet stands on the ground at rest", "how": "visual", "priority": "must"},
+ {"id": "j1", "text": "Drawer slides out 0.35 m along -Y without penetrating the cabinet", "how": "articulation", "priority": "must"}]
return base
@@ -711,7 +741,7 @@ def restart_note(raw: Any, missing: list[str], budget: PlanBudget) -> str:
f"{n_parts} top-level part(s) and then referenced links it never defined: "
f"{', '.join(missing[:10])}. Start again from this request. Rules that answer is missing:\n"
f"- `parts` must contain EVERY link a joint names, each with its own name, bbox and material "
- f"(about {budget.target_parts} parts for this request).\n"
+ f"(at least {budget.min_parts} parts for this request).\n"
"- `joints[].parent` and `joints[].child` must be spelled exactly like those part names.\n"
"- Nothing that a joint moves may live in `children`; sub-parts are rigid detail only."
)
@@ -762,7 +792,7 @@ def _thin_plan_note(raw: Any, budget: PlanBudget) -> str:
if not degenerate_plan(raw, budget):
return ""
parts = raw.get("parts")
- return (f"\nAlso: this plan lists only {len(parts)} part(s) but the request needs about {budget.target_parts} "
+ return (f"\nAlso: this plan lists only {len(parts)} part(s) but the request needs at least {budget.min_parts} "
f"({budget.reason}). Put EVERY link a joint references under `parts` with its own bbox.")
diff --git a/harness/codeverse3d/tracks/prompting.py b/harness/codeverse3d/tracks/prompting.py
index ce13c55d..032148fc 100644
--- a/harness/codeverse3d/tracks/prompting.py
+++ b/harness/codeverse3d/tracks/prompting.py
@@ -11,7 +11,7 @@ from __future__ import annotations
import logging
from collections.abc import Sequence
from pathlib import Path
-from typing import TYPE_CHECKING, Any
+from typing import Any
from codeverse3d.contracts.chat import ImagePart
from codeverse3d.contracts.common import (
@@ -34,9 +34,6 @@ from codeverse3d.tracks.depth import (
interfaces_text,
)
-if TYPE_CHECKING:
- from codeverse3d.prompts.sections import Section
-
log = logging.getLogger(__name__)
MAX_SKELETON_CHARS = 14_000
@@ -133,93 +130,6 @@ def constraints_text(spec: Any) -> str:
return "\n".join(lines) or "(none)"
-#: brief words → cookbook chapter titles (case-insensitive substrings of a ``## `` heading) they call for
-COOKBOOK_SYNONYMS: dict[str, tuple[str, ...]] = {
- "aurora": ("Light phenomena",), "curtain": ("Light phenomena",), "curtains": ("Light phenomena",),
- "northern": ("Light phenomena",), "glow": ("Light phenomena",),
- "star": ("Gradient sky", "Light phenomena"), "stars": ("Gradient sky", "Light phenomena"),
- "night": ("Gradient sky", "Light phenomena"), "space": ("Gradient sky", "Light phenomena"),
- "galaxy": ("Gradient sky", "Light phenomena"), "nebula": ("Gradient sky", "Light phenomena"),
- "bokeh": ("Bokeh",), "city": ("Bokeh",), "neon": ("Bokeh",), "lights": ("Bokeh",),
- "rain": ("Rain",), "drops": ("Rain",), "glass": ("Rain",),
- "cloud": ("Domain warping", "Volume lighting"), "clouds": ("Domain warping", "Volume lighting"),
- "smoke": ("Domain warping", "Volume lighting"), "fog": ("Volume lighting",),
- "volumetric": ("Volume lighting",), "metal": ("Physical surface lighting",),
- "metallic": ("Physical surface lighting",), "roughness": ("Physical surface lighting",),
- "pbr": ("Physical surface lighting",), "dielectric": ("Physical surface lighting",),
- "marble": ("Domain warping",),
- "tunnel": ("Raymarching",), "temple": ("Raymarching",), "corridor": ("Raymarching",), "3d": ("Raymarching",),
- "trail": ("Feedback",), "trails": ("Feedback",), "feedback": ("Feedback",),
-}
-COOKBOOK_ALWAYS: tuple[str, ...] = ("Hash / noise / fbm", "Palettes, tonemapping, grading", "PITFALLS")
-_STOP = frozenset(("the", "and", "with", "for", "from", "into", "over", "that", "this", "are", "its", "one", "two",
- "not", "but", "then", "than", "out", "each", "all", "any", "per", "via", "use", "like", "look",
- "looks", "very", "some", "more", "most"))
-
-
-def _words(text: str) -> set[str]:
- import re
-
- return {w for w in re.findall(r"[a-z0-9]+", text.lower()) if (len(w) >= 3 or w in COOKBOOK_SYNONYMS) and w not in _STOP}
-
-
-def is_always_chapter(title: str, always: Sequence[str] = COOKBOOK_ALWAYS) -> bool:
- """Is ``title`` one of the chapters every graphics prompt carries (helpers / grading / pitfalls)?"""
- low = title.lower()
- return any(name.lower() in low for name in always)
-
-
-def select_cookbook_chapters(ctx: RunContext, brief: str, *, budget: int = 9500,
- always: Sequence[str] = COOKBOOK_ALWAYS) -> list[Section]:
- """The cookbook chapters (cookbook order) a brief calls for.
-
- Measured 2026-08-26: the graphics prompt carried ``cookbook_text[:7000]`` of an 11,298-char
- cookbook, so everything after the raymarching template (sky / stars, rain, bokeh, feedback,
- PITFALLS) never reached the agent unless it called ``read_cookbook`` — and flash draws
- what it was handed (an aurora as a comb of bars, twenty sparkles for a star field).
- Here the header + ``always`` chapters go in first (4.4 k chars), then chapters ranked by
- keyword overlap between the brief (+ plan key visuals) and the chapter heading / body, with
- ``COOKBOOK_SYNONYMS`` as the strong signal, until ``budget`` is spent. A chapter is added
- whole or not at all; the output keeps cookbook order. The default budget is the measured
- need of a night-sky brief: always-set 4.4 k + Light phenomena 3.2 k + Gradient sky 1.3 k.
- ``tracks/graphics.py:seed_recipes`` seeds the SAME selection's code into the harness-owned ``src/recipes.glsl``.
- """
- from codeverse3d.prompts.sections import Section, find_section, split_sections
-
- md = ctx.cookbook_text or ""
- if not md.strip():
- return []
- chapters: list[Section] = []
- for s in split_sections(md): # fold ### sub-headings into their ## chapter
- if s.level >= 3 and chapters:
- chapters[-1] = Section(chapters[-1].level, chapters[-1].title, chapters[-1].body + s.body)
- else:
- chapters.append(s)
- chosen: set[int] = {i for i, s in enumerate(chapters) if s.level < 2} # title / conventions header
- for name in always:
- sec = find_section(chapters, name)
- if sec is not None:
- chosen.add(chapters.index(sec))
- brief_words = _words(brief)
- wanted = {t.lower() for w in brief_words for t in COOKBOOK_SYNONYMS.get(w, ())}
- scored: list[tuple[int, int]] = []
- for i, s in enumerate(chapters):
- if i in chosen:
- continue
- title = s.title.lower()
- score = 4 * sum(1 for t in wanted if t in title)
- score += 3 * len(brief_words & _words(s.title)) + len(brief_words & _words(s.body))
- if score > 0:
- scored.append((-score, i))
- used = sum(len(chapters[i].body.rstrip()) + 2 for i in chosen)
- for _, i in sorted(scored):
- size = len(chapters[i].body.rstrip()) + 2
- if used + size <= budget:
- chosen.add(i)
- used += size
- return [chapters[i] for i in sorted(chosen)]
-
-
def language_system_prompt(language: Language, *, role: str = "", tools: bool = True, **vars: Any) -> str:
"""The generator's system prompt: ``prompts/<dir>/system.md``, or a role template.
@@ -262,12 +172,6 @@ def base_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:
# contract's ctx table, imports, lint policy, API facts and render budgets, not the
# assembler, the cameras or the worked env / zone modules it must not write
"asset_contract": contract_sections(ctx.contract_text, ASSET_CONTRACT_SECTIONS),
- # the whole cookbook. It used to be ctx.cookbook_text[:6000] — a blind byte
- # prefix that delivered 13 % of blender's and 10 % of scene_threejs's, cutting
- # mid-snippet, and the read_cookbook tool that was supposed to fetch the rest
- # went uncalled in all 20 measured sessions. Prompt material the harness wrote
- # for the model is not summarised by byte offset.
- "cookbook_excerpt": ctx.cookbook_text,
"tool_cards": ctx.tool_cards,
"single_shot": ctx.single_shot,
"output_format": SINGLE_SHOT_OUTPUT if ctx.single_shot else AGENT_OUTPUT_RULES,
@@ -429,9 +333,9 @@ def current_files(
ctx: RunContext, rels: Sequence[str], max_chars: int = MAX_SKELETON_CHARS
) -> dict[str, str]:
"""``{rel: text}`` for the files that exist, trimmed to ``max_chars`` in total. The
- language's harness-owned files (``src/recipes.glsl``) are never inlined: the
- single-shot prompt showed one as an editable skeleton file while every write to it
- is refused (``generate_graphics.j2`` pastes its signatures separately)."""
+ language's harness-owned files (``HARNESS_OWNED_SRC``, e.g. a scene's ``src/lib/``) are
+ never inlined: the single-shot prompt once showed one as an editable skeleton file while
+ every write to it is refused."""
owned = set(HARNESS_OWNED_SRC.get(ctx.language, ()))
out: dict[str, str] = {}
total = 0
diff --git a/harness/codeverse3d/tracks/repair.py b/harness/codeverse3d/tracks/repair.py
index 49274508..2f1f8921 100644
--- a/harness/codeverse3d/tracks/repair.py
+++ b/harness/codeverse3d/tracks/repair.py
@@ -3,8 +3,8 @@
``build_with_repair`` runs ``runtime.lint`` + ``runtime.build``; while the
build fails (or lint reports ERRORs) and attempts remain, it dispatches ONE
repair task carrying a structured error report (file:line, message, traceback
-tail, lint findings with fix hints, the cookbook section matching the error
-keywords). Identical consecutive error signatures escalate (higher
+tail, lint findings with fix hints, the attached skills that answer the
+findings). Identical consecutive error signatures escalate (higher
temperature/thinking for single-shot; an explicit "same error again" notice
for agents) — the tell that the previous edit did not touch the cause.
"""
@@ -12,14 +12,12 @@ for agents) — the tell that the previous edit did not touch the cause.
from __future__ import annotations
import logging
-import re
from pydantic import BaseModel, Field
from codeverse3d.contracts.artifacts import BuildResult, GateReport
from codeverse3d.contracts.common import Usage
from codeverse3d.prompts import render
-from codeverse3d.prompts.sections import split_sections
from codeverse3d.tracks import skills_hook
from codeverse3d.tracks.common import RunContext, generate_for
from codeverse3d.tracks.generation import GenerationResult, GenerationTask
@@ -57,7 +55,7 @@ def error_signature(build: BuildResult, lint: GateReport) -> str:
return "lint|" + "|".join(sorted(f"{f.target}:{f.message[:80]}" for f in lint.errors))
-def format_error_report(build: BuildResult, lint: GateReport, cookbook: str = "", skills: str = "") -> str:
+def format_error_report(build: BuildResult, lint: GateReport, skills: str = "") -> str:
"""Compact, structured error report for the fixer (the ONLY thing it must fix).
``skills`` is the gate→skill pointer block: the bundles already in the workspace that
@@ -80,32 +78,9 @@ def format_error_report(build: BuildResult, lint: GateReport, cookbook: str = ""
lines.extend(f"- {f.as_line(with_target=True)}" for f in lint.errors)
if skills.strip():
lines.append("\n" + skills.strip())
- section = relevant_cookbook_section(cookbook, " ".join([build.error_type, build.error_message, build.stderr_tail[-2000:]]))
- if section:
- lines.append("\nRelevant cookbook section:\n" + section)
return "\n".join(lines)
-_WORD = re.compile(r"[A-Za-z_][A-Za-z0-9_]{3,}")
-
-
-def relevant_cookbook_section(cookbook: str, error_text: str, *, max_chars: int = 12000) -> str:
- """Pick the cookbook ``##`` section sharing the most identifiers with the error."""
- if not cookbook or not error_text:
- return ""
- err_words = {w.lower() for w in _WORD.findall(error_text)}
- err_words -= {"error", "line", "file", "traceback", "most", "recent", "call", "last", "module"}
- best, best_score = "", 0
- for body in (s.body for s in split_sections(cookbook) if s.level >= 2):
- words = {w.lower() for w in _WORD.findall(body)}
- score = len(words & err_words)
- if score > best_score:
- best, best_score = body, score
- if best_score < 2:
- return ""
- return best[:max_chars].rstrip()
-
-
def files_for_repair(ctx: RunContext, build: BuildResult, lint: GateReport, files_hint: list[str]) -> dict[str, str]:
"""Current contents of the failing file(s) (≤ 40k chars total) for single-shot repair —
inlined by ``prompting.current_files``, which never inlines a harness-owned file."""
@@ -209,7 +184,7 @@ def build_with_repair(ctx: RunContext, *, round_index: int, label: str, files_hi
def make_repair_task(ctx: RunContext, build: BuildResult, lint: GateReport, *, round_index: int, attempt: int,
repeats: int, label: str, files_hint: list[str], timeout_s: int | None = None) -> GenerationTask:
"""Render prompts/tracks/repair.j2 for the current strategy."""
- report = format_error_report(build, lint, ctx.cookbook_text, skills_hook.repair_pointers(ctx, build, lint))
+ report = format_error_report(build, lint, skills=skills_hook.repair_pointers(ctx, build, lint))
files = files_for_repair(ctx, build, lint, files_hint) if ctx.single_shot else {}
prompt = render("tracks/repair.j2", **base_prompt_context(
ctx, error_report=report, files=files, repeats=repeats, attempt=attempt,
diff --git a/harness/codeverse3d/tracks/scene.py b/harness/codeverse3d/tracks/scene.py
index 4d5f294f..6f44e779 100644
--- a/harness/codeverse3d/tracks/scene.py
+++ b/harness/codeverse3d/tracks/scene.py
@@ -72,12 +72,17 @@ log = logging.getLogger(__name__)
SCENE_TIMES: tuple[float, float] = (0.0, 1.5)
MAX_CONSOLE_ERRORS = 8
-# No cookbook on this track (owner, 2026-10-15): the same four ENV and six ZONE chapters used to be
-# inlined into every session whatever the brief, and the 60 iteration-0 scenes executed them
-# verbatim. Interface facts live in contract.md / system.md, the craft in the skills as short
-# optional practices; the prompts state requirements and what measures them.
+# No cookbook (D106 / D107): the four ENV and six ZONE chapters once inlined into every session were
+# executed verbatim by the 60 iteration-0 scenes. Interface facts live in contract.md / system.md,
+# the craft in the skills as short optional practices; the prompts state requirements and what measures them.
ENV_TIMEOUT_S = 420
ZONE_TIMEOUT_S = 600
+#: what round 0 still needs once the zones are written — assemble, build, render, gates and the judge
+#: (4-8 min measured in iteration 2) — and what the zone window therefore never eats into
+ROUND0_RESERVE_S = 600.0
+#: the shortest zone window worth opening: an agent session spends its first minutes reading the
+#: briefs, the skills and the asset files (24-27 reads in the two sessions killed at 180 s)
+ZONE_MIN_S = 300.0
#: a refine session that runs for half an hour (the desert-canyon round 1 did) spends the
#: wall clock the NEXT round needed; clip it to what the hard budget still allows
REFINE_TIMEOUT_S = 900
@@ -384,9 +389,48 @@ class SceneTrack(BaseTrack):
# must have been reported as changed or actually rewritten in this stage
ok = r.ok and (len(zones) == 1 or rel in written or _touched(ctx.ws.root / rel, t0))
out[zone.name] = {"ok": ok, "files": [rel] if ok else [], "notes": r.notes}
+ failed = [z for z in zones if not out[z.name]["ok"]]
+ if failed and ctx.budget.ok():
+ out.update(self._recover_zones(ctx, failed))
ctx.events.emit("zones.done", ok=[k for k, v in out.items() if v["ok"]], failed=[k for k, v in out.items() if not v["ok"]])
return out
+ def _recover_zones(self, ctx: RunContext, failed: list[ZonePlan]) -> dict[str, dict[str, Any]]:
+ """One single-shot generation per zone the batched session left unwritten, side by side.
+
+ WHY. ``zones.done`` already listed such zones as failed and nothing acted on it: the
+ skeleton's stub (``build`` returns the empty collection) went to assembly, every planned
+ content was ``zone_empty`` and ``missing_must_acceptance`` capped the run at ~0.18 — and the
+ refine round, handed "three empty zones" among its targets, spent its 15 minutes on asset
+ files (iteration 2, r1_11 / r1_15, 2026-10-15). An unwritten zone is the stage's job, not
+ refine's: each gets its own brief again, single-shot (fast, and it cannot spend its window
+ reading), bounded by the zone window. A recovery that also fails leaves the stub, as before."""
+ from codeverse3d.proc import fan_out
+
+ gen = ctx if ctx.single_shot else (single_shot_ctx(ctx) or ctx)
+ ctx.events.emit("zones.recover", zones=[z.name for z in failed])
+ t0 = time.time()
+
+ def one(zone: ZonePlan) -> tuple[str, dict[str, Any]]:
+ rel = ctx.runtime.zone_file(zone.name)
+ task = self._zone_task(gen, [zone])
+ task = task.model_copy(update={"label": f"{task.label}.recover", "timeout_s": zone_window_s(ctx, 1)})
+ try:
+ res = generate_for(gen, task)
+ except Exception as e: # noqa: BLE001 — one zone's recovery must not cost the others
+ return zone.name, {"ok": False, "files": [], "notes": f"recover: {type(e).__name__}: {e}"[:500]}
+ ok = res.ok and (rel in {c.path for c in res.files_changed} or _touched(ctx.ws.root / rel, t0))
+ return zone.name, {"ok": ok, "files": [rel] if ok else [], "notes": f"recovered single-shot: {res.notes}"[:500]}
+
+ # fan_out returns each item's value or the exception it raised; ``one`` catches its own,
+ # so anything else (a task that could not even be built) leaves that zone as it was
+ results = dict(r for r in fan_out(failed, one, max_workers=len(failed), label="zones.recover",
+ item_name=lambda z: z.name) if isinstance(r, tuple))
+ ctx.ws.commit("zones.recover")
+ ctx.events.emit("zones.recovered", ok=[k for k, v in results.items() if v["ok"]],
+ failed=[k for k, v in results.items() if not v["ok"]])
+ return results
+
def _zone_task(self, ctx: RunContext, batch: list[ZonePlan]) -> GenerationTask:
"""One task for one zone, or for every zone of the scene in one session (D70).
@@ -431,7 +475,7 @@ class SceneTrack(BaseTrack):
# the window grows with the batch: one author writing four zones is four zones of work
return GenerationTask(label=label, prompt=prompt, system=self.system_prompt(ctx), files_hint=files,
round=0, kind="zone", temperature=0.5, edit_only=True,
- timeout_s=ctx.budget.timeout_s(ZONE_TIMEOUT_S * max(1, len(batch)), floor_s=180))
+ timeout_s=zone_window_s(ctx, len(batch)))
def _assemble_stage(self, ctx: RunContext) -> dict[str, Any]:
result = ctx.services.assemble_scene(ctx.runtime, ctx.ws, ctx.plan)
@@ -483,8 +527,7 @@ class SceneTrack(BaseTrack):
and the preflight's findings are the build's log tail), targeted at the failing
module when the build names one."""
lint = next((g for g in last.gates if g.gate.startswith("lint")), GateReport(gate="lint", passed=True))
- # no cookbook section in the report: the scene languages ship none (the "" is explicit, not a lookup)
- report = format_error_report(last.build, lint, "") if last.build else "build did not run"
+ report = format_error_report(last.build, lint) if last.build else "build did not run"
files: list[str] = []
if last.build is not None and last.build.error_file:
rel = last.build.error_file.removeprefix(str(ctx.ws.root)).lstrip("/")
@@ -536,6 +579,20 @@ def _touched(path: Any, since: float) -> bool:
return False
+def zone_window_s(ctx: RunContext, n_zones: int) -> int:
+ """The zone session's window: ``ZONE_TIMEOUT_S`` per zone, clipped to the HARD budget minus
+ :data:`ROUND0_RESERVE_S` — never to the scene track's soft cap.
+
+ WHY. The soft cap (0.55 of the run) protects the refine round's time, but a scene whose zones
+ are empty has nothing to refine: two iteration-2 runs reached the zone stage 0.4 min before the
+ cap (a runaway asset call had held the asset stage for 47 min), so the session was clipped to
+ the 180 s floor, read 24-27 files and was killed before writing a zone (2026-10-15). The zones
+ are the scene; refine gets whatever they leave. Past the soft cap the stage still degrades to
+ single-shot (``_strategy``); this only sizes the window it runs in."""
+ left = (ctx.budget.hard_minutes - ctx.budget.elapsed_minutes()) * 60.0 - ROUND0_RESERVE_S
+ return int(max(ZONE_MIN_S, min(float(ZONE_TIMEOUT_S * max(1, n_zones)), left)))
+
+
def _guess_target(error: str, ctx: RunContext) -> str:
"""The refine target a console error names: a zone or asset by its snake name, the env
module or the entry by the RUNTIME's file names (``env_file``, ``ENTRY_FILE``), else overall."""
diff --git a/harness/codeverse3d/tracks/scene_assets.py b/harness/codeverse3d/tracks/scene_assets.py
index bb39c2c7..ce7f6a65 100644
--- a/harness/codeverse3d/tracks/scene_assets.py
+++ b/harness/codeverse3d/tracks/scene_assets.py
@@ -442,7 +442,6 @@ def build_blender_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> As
sub_ws.write_json(sub_ws.spec_path, sub_spec)
sub = replace(ctx, spec=sub_spec, ws=sub_ws, runtime=runtime, plan=None, track=Track.STATIC_OBJECT,
contract_text=language_text(Language.BLENDER, "contract.md"),
- cookbook_text=language_text(Language.BLENDER, "cookbook.md"),
tool_cards=ctx.services.tool_cards(Track.STATIC_OBJECT.value, Language.BLENDER.value),
extra={"scene_brief": ctx.spec.prompt, "scene_style": constraints_text(ctx.spec)})
sub.plan = hero_plan(sub, asset)
@@ -458,8 +457,7 @@ def build_blender_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> As
if not ctx.single_shot:
# the language contract alone, no harness_contract.md (intended, review 2 C4): the context file's hard rules
# bound paths/imports, and its standalone-object acceptance (±1 cm bbox) contradicts the prop sheet's ±5 %
- ctx.services.materialize(sub_ws, agent_kind=ctx.agent_kind, contract_md=sub.contract_text, cookbook_text=sub.cookbook_text,
- spatial_tools=True)
+ ctx.services.materialize(sub_ws, agent_kind=ctx.agent_kind, contract_md=sub.contract_text, spatial_tools=True)
files = sub.runtime.expected_files(sub.plan)
timeout_s = asset_timeout_s(ctx, 180)
label = f"asset_{snake}"
diff --git a/harness/codeverse3d/tracks/skills_hook.py b/harness/codeverse3d/tracks/skills_hook.py
index 4d0d2f8e..f75f4dfc 100644
--- a/harness/codeverse3d/tracks/skills_hook.py
+++ b/harness/codeverse3d/tracks/skills_hook.py
@@ -86,9 +86,9 @@ def repair_pointers(ctx: RunContext, build: BuildResult, lint: GateReport) -> st
reports (``BuildResult.gates`` — a scene's shader_preflight), the same reports a refine
round routes on.
- ``tracks/repair.py`` already picks a cookbook section by keyword; this is the same
- idea one level up, and it only names skills that are already in the workspace, so it
- adds pointers rather than text.
+ The repair prompt's only pointer to material (D107): the attached bundles whose routes
+ match the build / lint finding kinds. It only names skills that are already in the
+ workspace, so it adds pointers rather than text.
"""
got = ctx.extra.get(CTX_KEY)
if not got or not getattr(got, "selections", None):
diff --git a/harness/codeverse3d/workspace.py b/harness/codeverse3d/workspace.py
index c86d5e7a..860cf9c5 100644
--- a/harness/codeverse3d/workspace.py
+++ b/harness/codeverse3d/workspace.py
@@ -28,6 +28,8 @@ from codeverse3d.proc import write_json_atomic
DELIVERABLE_DIR = "deliverable" # (a) what the user asked for
EVIDENCE_DIR = "evidence" # (b) why we believe it is good (alias of artifacts/)
TELEMETRY_DIR = "telemetry" # (c) what it cost and how it was configured
+#: harness-owned read-only files inside the workspace (task images: ``tracks/generation.IMAGES_DIR``)
+C3D_DIR = ".3dcode"
#: physical directories every run owns. ``artifacts/`` is the physical home of the
#: evidence (six packages and ~50 recorded runs write paths into it); ``evidence/``
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index a6aa33cc..0f5b57c7 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -44,11 +44,14 @@ round and runs the optional **texture pass** on it. The record (plus git histor
keeps its own built files under `artifacts/rNN/`, so any round can be handed over
without a rebuild; the workspace ends at the last round. Textures are a *derived asset pack*
(`object_textured.glb` + `artifacts/textures/`); `object.glb` is never touched.
-2. **Concrete beats abstract.** Contracts are delivered as skeleton code, exact
- numbers and copyable snippets (cookbooks), never as clauses. **Except on the scene track
- (D106, 2026-10-15)**: there the harness states requirements — interface, sandbox, measured
- thresholds — and never a template; the two scene cookbooks are gone, the skeletons are
- placeholders, and a code block in a scene prompt or skill is at most ~12 lines (60 argon
+2. **Requirements, never templates (D106 scene track, D107 every track, owner 2026-10-15).**
+ The harness states what must be true, where, and how it is measured — interface (the files and
+ functions the wrapper calls, frames / units / naming), sandbox rules, and measured requirements
+ with their thresholds (bbox / dims / connectivity / joint / part-naming contracts, triangle
+ budgets) — and never a mandated shape, count, construction, layout or code structure the brief
+ did not ask for. No language ships a cookbook; each `contract.md` keeps ONE executable interface
+ example (`tests/prompts/test_snippets_run.py` runs it), the craft is a few short optional
+ practices in the skills, and no code block in a prompt or skill is over ~12 lines (60 argon
scenes of one shape were the inlined chapters executed verbatim).
3. **Code answers when code can answer.** Deterministic gates / measurements run
by the harness; the VLM is used only for perception and judgement, and its
@@ -66,7 +69,7 @@ round and runs the optional **texture pass** on it. The record (plus git histor
9. **Money is measured, time is bounded.** The wall clock is the hard per-run ceiling
(`BudgetGuard`), key pools have per-key limiters, and every call is one row of the
run's ledger, `telemetry/cost.jsonl` — the only record of money.
-10. **Reproducible.** Prompt/rubric/cookbook hashes and tool versions are
+10. **Reproducible.** Prompt/rubric/skill hashes and tool versions are
recorded on every run (`record.prompt_hashes`, `record.environment`).
11. **Export as authored.** No wrapper re-centres, rescales or grounds the
object; builds warn, `check_contract`/`check_connectivity` gate, the agent
@@ -212,10 +215,9 @@ codeverse3d/
gates), articulated_object.py (+ the planned-motion gate),
scene.py, scene_assets.py (+ cheap single-shot asset generation),
zone_layout.py (L2 zone director: per-zone structured layout calls + deterministic validator),
- graphics.py (the whole graphics track: prompt context, frame
- RenderSet, and recipe seeding into the harness-owned, read-only
- src/recipes.glsl — measured: flash calls a recipe on disk, not one it is
- shown; AgentJob.read_only, C3D_SEED_RECIPES),
+ graphics.py (the whole graphics track: prompt context and the frame
+ RenderSet; the recipe seeding into src/recipes.glsl went with the
+ cookbooks, D107),
planner.py (the ONE planner loop + the cached EngineeringBrief
(C3D_PLAN_BRIEF), plan budgets and the worked examples — and the ONE owner of
what differs per track when planning: template, example, temperature, output
@@ -249,18 +251,17 @@ codeverse3d/
server.py (stdlib http.server, loopback-only; page.py also renders the
static single-file form), theme.py (CSS + the index-page JS)
prompts/ EVERY piece of prompt material the harness writes, and the only place it
- lives: <lang>/{system,contract,cookbook}.md (incl. glsl_shader/,
- opengl_python/; the scene languages ship NO cookbook, D106 — contract.md
- and system.md carry their interface facts), system/* (harness contract, single-shot envelope,
+ lives: <lang>/{system,contract}.md (incl. glsl_shader/,
+ opengl_python/; NO language ships a cookbook, D106 / D107 — contract.md
+ and system.md carry the interface facts), system/* (harness contract, single-shot envelope,
role_{scope,asset,repair}.j2), texturing/*.md, tracks/*.j2.
catalog.py answers "what exists and how does each piece reach the model"
— including the ONE per-language lookup, language_prompt(language, name) /
- language_text: contract.md, cookbook.md, system.md, effects_catalog.md, asset.md
+ language_text: contract.md, system.md, effects_catalog.md, asset.md
(the prompts/<dir> mapping used to be copied four times and missing in a fifth;
- until 2026-09-22 the contract came through the runtime, the cookbook through
- tracks/common, the system prompt and the catalog through tracks/prompting). sections.py splits that
- markdown into chapters so a STAGE can name the recipes it needs (graphics
- only since D106; the scene track inlines nothing).
+ until 2026-09-22 the contract came through the runtime, the system prompt
+ and the catalog through tracks/prompting). sections.py (the `## ` heading
+ splitter) was deleted in D107 — no stage picks chapters any more.
variants.py (D105): per-model OVERLAYS — variants/<name>/<rel> shadows <rel> for
load_text / render / language_text while that variant is active (a ContextVar
BaseTrack.run sets around the whole run from RunOptions.variant, else the
@@ -322,7 +323,7 @@ back-compatibility rules are in `docs/RUN_LAYOUT.md`, its one home.
## 4. Per-language authoring contracts (raw code; the harness owns export)
-Authoritative text lives in `codeverse3d/prompts/<lang>/contract.md` (+ cookbook);
+Authoritative text lives in `codeverse3d/prompts/<lang>/contract.md` (+ `system.md`; no cookbook, D107);
summary:
* **blender** (multi-file): `src/model.py` entry + `src/parts/<snake>.py` each
@@ -370,8 +371,7 @@ summary:
ceiling, not the per-asset budget, and seats a factory by its origin. `src/lib/` is committed
with `src/`, so the deliverable and the dataset sample carry it.
* **glsl_shader**: `src/shader.frag` (+ optional `src/common.glsl`,
- `src/buffer_a.frag` for feedback; the harness-owned, read-only `src/recipes.glsl`
- is pasted above them when the track seeded recipes) — the agent never writes
+ `src/buffer_a.frag` for feedback) — the agent never writes
`#version`, uniform declarations or `out vec4`; the harness header provides
`u_time/u_resolution/u_mouse/u_frame/u_prev/u_noise/u_buffer_a` (+ Shadertoy
`iTime/iResolution/iChannel*` aliases). Feedback shaders are simulated at 30 fps.
@@ -468,7 +468,7 @@ fails when it drifts, printing the block to paste):
static_object plan → skeleton → materialize* → round 0
articulated_object plan → skeleton → materialize* → round 0
scene plan → skeleton → materialize* → textures? → (assets ∥ env ∥ layouts?) → asset_api* → zones → clock* → assemble → round 0
-graphics plan → skeleton → recipes* → materialize* → round 0
+graphics plan → skeleton → materialize* → round 0
```
`→` in order; `(a ∥ b)` siblings side by side, each its own cached stage, timed as ONE step of the
diff --git a/harness/docs/INSTALL.md b/harness/docs/INSTALL.md
index af358b49..60ef2848 100644
--- a/harness/docs/INSTALL.md
+++ b/harness/docs/INSTALL.md
@@ -433,8 +433,8 @@ export C3D_VARIANTS='{"agy:gemini-4-argon": "argon"}' # per-model prompt/skill
Every knob the harness reads is a `Settings` field (`codeverse3d/config.py`, one
description each): `C3D_<FIELD>` at the top level, `C3D_<SECTION>__<FIELD>` nested, plus
-four flat spellings of nested knobs — `C3D_MAX_IN_FLIGHT`, `C3D_RENDER_GPU`,
-`C3D_SEED_RECIPES`, `C3D_AGENT_MAX_TURNS`. An on/off switch (`C3D_SKILLS`, `C3D_STREAM`,
+three flat spellings of nested knobs — `C3D_MAX_IN_FLIGHT`, `C3D_RENDER_GPU`,
+`C3D_AGENT_MAX_TURNS` (`C3D_SEED_RECIPES` went with the graphics recipe seeding, D107). An on/off switch (`C3D_SKILLS`, `C3D_STREAM`,
`C3D_PLAN_BRIEF`, … — every `Flag` field) takes on/off, 1/0, true/false or yes/no in any
case; a typo warns and keeps the default, and an empty value is unset. The node side also
reads `C3D_RENDER_GPU` and `C3D_CACHE_DIR` itself, and one variable only it reads:
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index e87811d3..f22c970c 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -207,14 +207,12 @@ Every run is read from its ledger alone (`addons.costreport.audit.read_run` / `r
```python
from codeverse3d.agents import get_coding_agent # (agent_id) -> CodingAgent .run(job) .available() .id .kind .model
from codeverse3d.agents.materialize import materialize_workspace, codex_mcp_overrides
-materialize_workspace(ws, *, agent_kind, contract_md, cookbook_text, spatial_tools, mcp_command=None) -> None
-# cookbook_text = RunContext.cookbook_text, the catalog's text (Δ 2026-09-22: was cookbook_rel, resolved workspace-first,
-# so an agent-written <ws>/<lang>/cookbook.md shadowed the harness cookbook); "" → no "## Cookbook" section, no .3dcode/cookbook.md
-# (a stale one is removed), no warning — the scene languages ship none (D106)
+materialize_workspace(ws, *, agent_kind, contract_md, spatial_tools, mcp_command=None) -> None
+# Δ D107: no cookbook_text — no language ships a cookbook; the body is hard rules + tool cards + the language contract
# mcp_command defaults to cli_common.default_mcp_command(ws) = [sys.executable, -m codeverse3d.spatial.mcp_server --workspace …]
# (None/[] = the default — no ValueError); tracks/common.Services.materialize takes no mcp_command
# writes AGENTS.md + CLAUDE.md (same body; Δ D103 no GEMINI.md — agy reads it AND AGENTS.md, so the body loaded
-# twice), ws/.3dcode/cookbook.md (Δ written in: an agent may not read outside the workspace), .antigravityignore,
+# twice), .antigravityignore (Δ D107: no .3dcode/cookbook.md copy),
# and NO MCP file in the workspace (it is agent-writable — audit 2026-08-27); MCP wiring is per session:
# claude-code → trajectories/<label>_rNN/mcp.json codex → codex_mcp_overrides(mcp_command) built PER SESSION:
# -c mcp_servers.3dcode.command=… -c mcp_servers.3dcode.args=[…] -c mcp_servers.3dcode.default_tools_approval_mode="approve"
@@ -253,7 +251,7 @@ sessions on one workspace are serialised, so there is no sibling filter),
`edit_only` / `always_writable` (a scoped refine may overwrite only its hinted files +
the entry file), `read_only: list[str]` (harness-owned files INSIDE the write roots the
session may read but never write — `contracts.common.HARNESS_OWNED_SRC[language]`, i.e.
-`src/recipes.glsl` for glsl_shader and `src/lib/` for scene_threejs; `tracks/generation.py`
+`src/lib/` for scene_threejs / scene_blender (Δ D107: glsl_shader's seeded `src/recipes.glsl` is gone); `tracks/generation.py`
sets it on every job of the run and `agents/cli_common._enforce_scope` reverts a
post-session write to one and fails that session. **Δ** an entry ending in `/` is a
DIRECTORY prefix — `contracts.common.is_harness_owned(rel, owned)` is the predicate, and
@@ -304,7 +302,7 @@ rt.env_file: str # Δ 2026-10-14 (D105) src
from codeverse3d.prompts.catalog import language_prompt, language_text
language_prompt(language, name) -> str # "<dir>/<name>" under prompts/ (urdf_blender → urdf/): THE per-language prompt
language_text(language, name) -> str # its text, "" for a file the language does not ship (Δ 2026-09-22: replaces
- # LanguageRuntime.contract_doc / RuntimeDocs, tracks/common.language_contract / cookbook_rel_for / load_prompt_or,
+ # LanguageRuntime.contract_doc / RuntimeDocs, tracks/common.language_contract / load_prompt_or,
# tracks/prompting.effects_catalog_text; planner.plan / build_system_prompt take no runtime=)
BuildResult.error_type spellings (languages/_common.py): MISSING_ENTRY = "MissingEntryFile" (every runtime, threejs'
export_glb.mjs included) · BUILD_TIMEOUT = "BuildTimeout" (compose_build_result, threejs, urdf)
@@ -317,7 +315,7 @@ BuildResult.error_type spellings (languages/_common.py): MISSING_ENTRY = "Missin
| `UrdfBlenderRuntime` | `src/model.py`, `src/robot.urdf` | object.glb (Y-up, node=link, joint extras), meshes/<link>.glb (raw Z-up link frames); link name `world` is reserved (lint ERROR + UrdfError); robot GLB root gets `__root` suffix on name clash; the build collides the REST pose only (RestPenetration > 5 mm, D17) — every pose is the round's `joint_sweep` gate — and writes no articulation.json / census.articulation (Δ 2026-09-22) |
| `SceneThreeJsRuntime` | `src/scene.js`, `src/zones/*.js`, `src/assets/*.js`, `src/env.js`, `src/shaders/*.{js,vert,frag,glsl}` | glb_path=None; local shader text loads inside async createScene; ok iff `spatial.probes.run_probe(ws, *, compile=True, timeout_s=None) -> (scene_probe, shader_preflight, census)` (one `probe_scene.mjs --compile` boot; `probe_scene` is the same call without `compile`) passes both; both reports ride `BuildResult.gates`, and the `shader_probe` tool reports the same call |
| `SceneBlenderRuntime` | `src/scene.py`, `src/zones/*.py`, `src/assets/*.py`, `src/env.py` | **Δ 2026-09-24 (D102)** glb_path=None; `scene.py` is assembled DATA (`ZONES`/`ASSETS`/`HEROES` `{snake: Pascal}`, `CAMERAS` in the Blender frame, vertical fov); build = one Blender process (`wrappers/run_bpy_scene.py`: env, heroes, assets, zones each isolated — a raise is an ERROR on its `file:line` and the zone is dropped) → `artifacts/{census.glb, scene.blend, bpy_build.json, bpy_census.json}` → `run_probe(ws, glb=artifacts/census.glb, facts=bpy_census)` (no settle / camera repair; D2 unique-tri ERROR, no draw gate; D10 python drivers ERROR) → `BuildResult.gates=[scene_probe]`; `probe()` = the same measurement without touching build.json; `render_scene` = `spatial.render_blender.render_blender_scene` (**Δ D102b**: Blender renders the authored cameras × times + the overviews from `artifacts/scene.blend`, the JS host keeps the camera checks and the metrics schema; **Δ 2026-10-14 (D105)** the track runs end to end — `env_file` = `src/env.py`, the bpy templates, planner schema and asset ladder under orchestrator/ + tracks/ below); frame clock `scene_blender.FPS`/`frame_of(t) = 1 + round(30 t)` |
-| `GlslShaderRuntime` | `src/shader.frag`, `src/common.glsl`, `src/buffer_a.frag` (+ the harness-owned `src/recipes.glsl` when seeded) | harness owns `#version`/uniforms/`out` (wrap.HEADER: u_time/u_resolution/u_mouse/u_frame/u_prev/u_noise + iTime/iChannel* aliases); `wrap.compose(shader, common, recipes_src=…)` pastes header < recipes < common < shader; build renders judge frames via GlHost; compile errors → GlslCompileError at mapped src file:line (recipes.glsl included); lint ERROR `redefines_recipe` when an agent file defines a recipes.glsl name; artifacts frames/, frames_sheet.png, preview.gif, metrics.json |
+| `GlslShaderRuntime` | `src/shader.frag`, `src/common.glsl`, `src/buffer_a.frag` | harness owns `#version`/uniforms/`out` (wrap.HEADER: u_time/u_resolution/u_mouse/u_frame/u_prev/u_noise + iTime/iChannel* aliases); `compose(shader, common, *, shader_file, common_file)` pastes header < common < shader (Δ D107: no `recipes_src`, no `redefines_recipe` lint, no harness-owned `src/recipes.glsl`); build renders judge frames via GlHost; compile errors → GlslCompileError at mapped src file:line; artifacts frames/, frames_sheet.png, preview.gif, metrics.json |
| `OpenGLPythonRuntime` | `src/program.py`, `src/*.glsl` | `setup(ctx,w,h)->state` + `render(ctx,state,t,frame,fbo)` run in a moderngl subprocess (`wrappers/run_gl.py`); exceptions map to src/program.py:line, in-string GLSL errors carry both line numbers |
**Scene effect ownership and shader composition** are stated where they live: `src/lib/lifecycle.js`
@@ -594,19 +592,9 @@ scope_groups(plan, *, files_for, max_groups=6, parts_per_scope=3, min_parts=8) -
# otherwise attachment-subtree groups whose files are disjoint, so the sessions run in parallel
interfaces_text(plan, scope) -> str # the planned boxes of the neighbours this scope must weld to
from codeverse3d.tracks.prompting import base_prompt_context, reference_images, scope_context, budget_for # Δ split out of
-from codeverse3d.tracks.prompting import select_cookbook_chapters, is_always_chapter
- # select_cookbook_chapters(ctx, brief, *, budget=9000, always=COOKBOOK_ALWAYS) -> list[Section]: the header +
- # always-on chapters + the brief's chapters (whole, cookbook order, inside budget)
-from codeverse3d.tracks.graphics import seed_recipes, graphics_brief, cookbook_functions, EXTRA_KEY, RECIPES_REL
- # seed_recipes(ctx) -> list[str]: glsl_shader + Settings.limits.seed_recipes only. Writes the selected chapters'
- # function definitions (minus always-on chapters and the raymarching template) + the helpers they call to
- # the HARNESS-OWNED src/recipes.glsl (RECIPES_REL; header "// harness-owned: … READ-ONLY …"; a resume appends
- # only names the file lacks); returns the names written THIS call; ctx.extra["seeded_recipes"] =
- # [{name, signature, purpose}] for every seeded recipe on disk (the prompt block); emits recipes.seeded
- # {file, names, present, chapters, trimmed}. Never writes src/common.glsl — except the untouched skeleton,
- # which loses the helpers recipes.glsl now provides (trim_skeleton_common; recipes are pasted first).
- # GraphicsTrack.stages runs it (the uncached "recipes" stage) after the skeleton and commits "recipes"
- # when it wrote something.
+ # Δ D107: select_cookbook_chapters / is_always_chapter / COOKBOOK_SYNONYMS and the graphics recipe seeding
+ # (tracks/graphics.seed_recipes, cookbook_functions, the "recipes" stage, Settings.limits.seed_recipes /
+ # C3D_SEED_RECIPES) are deleted with the cookbooks; base_prompt_context carries no cookbook_excerpt
from codeverse3d.tracks.common import RunContext, Services # common.py; RunContext.single_shot / .agent_kind
# (Δ 2026-08-30) Services.connectivity(glb, language="", planned_edges=()) forwards the plan's attach_to pairs;
# spatial.contract.planned_joins(plan, measurement) -> [(child, (parent copies…))] spells them in GLB part names via
@@ -798,7 +786,7 @@ from codeverse3d.addons.dataset.index import build_index, query, summary # sql
optional normalises it once with `events = proc.NULL_EVENTS if events is None else events` (never `events or …`).
Event names: `run.start`, `stage.start/done`, `plan.done`, `workspace.materialized`,
`round.start`, `generate.done`, `build.done`, `gates.done`, `judge.done`,
-`round.done`, `refine.planned`, `recipes.seeded` (graphics: names written this call, present on disk, chapters), `asset.judged`, `assets.done`,
+`round.done`, `refine.planned`, `asset.judged`, `assets.done`,
`zones.done`, `assemble.done`, `round.no_change`, `candidates.start`,
`candidate.start/done/failed/retry/selected`, `resume.reconciled` (rounds, dropped, `restored_last_round`; Δ 2026-09-22 no
`state_was_stale`: run_state.json keeps no copy of the round journal to go stale),
@@ -813,7 +801,7 @@ gone — no reader, and its per-round {stage → $} restated the ledger (`summar
rNN.json that carries one still loads, the key ignored). `PairwiseNote` lives in `addons.select`.
`RunRecord` (record.json): spec, plan, workspace, status, rounds[RoundRecord{…, usage, duration_s, steps}],
total_usage, environment, steps (run-level StepTime rows; `minutes` = the property over all of them),
-prompt_hashes{contract, cookbook, generate, refine}, error, extra{stop_reason,
+prompt_hashes{contract, generate, refine, …} (Δ D107: no cookbook key), error, extra{stop_reason,
rubric, budget{elapsed_min, max_minutes} (the clock), aborted_rounds?, candidates? (the
rounds/candidates.json payload), texturing?, captions?}. `total_usage` is the sum of telemetry/cost.jsonl at
list price — every billed row once, aborted rounds, retried sessions and billed-but-discarded round-trips
diff --git a/harness/docs/RUNBOOK.md b/harness/docs/RUNBOOK.md
index de72be54..d0587212 100644
--- a/harness/docs/RUNBOOK.md
+++ b/harness/docs/RUNBOOK.md
@@ -106,9 +106,9 @@ round, then ≈ $0.36 / ~7 min per refine (give scenes `--max-minutes 60`).
* Workspace files: `AGENTS.md` + `CLAUDE.md` (no `GEMINI.md`: agy reads both it and AGENTS.md)
and `.antigravityignore`, which hides only noise (renders/judge output, the whole
`trajectories/`); build/census/measurement JSON stay readable.
-* Cookbook copied to `ws/.3dcode/cookbook.md` (an agent may not read outside the ws) — for a
- language that ships one; the scene languages ship none (D106), so their workspaces get no file
- and no "## Cookbook" section.
+* No cookbook: no language ships one (D106 scene, D107 the rest), so no workspace gets a
+ `.3dcode/cookbook.md` or a "## Cookbook" section — the body is the hard rules, the tool cards
+ and the language contract; the craft reaches the session as routed skills.
* MCP server argv is `[sys.executable, -m, codeverse3d.spatial.mcp_server, --workspace, ws]`;
server name `3dcode` → tools appear as `mcp__3dcode__<name>` (claude). `3dcode mcp --workspace runs/<slug>` execs the same server;
`python -m codeverse3d.spatial.mcp_server --workspace ws --list` prints the tools.
@@ -384,12 +384,12 @@ weather: they leave the provider's errors out (docs/COST.md §31); the ceiling d
tracks never restate it. A python-executed build wrapper goes beside the others in
`languages/wrappers/` (import `_wrapper_common`; run it with `_common.run_wrapper_build`, or
read its report with `_common.compose_build_result`, which publishes the final `build.json`); branch in
- `languages/base.py::get_runtime`; `prompts/<lang>/{system,contract,cookbook}.md` (found by
- `prompts/catalog.language_prompt`; every cookbook snippet must run — `tests/prompts`
- executes them; a scene language has no cookbook and its prompts state requirements, never
- templates — D106: no code block over ~12 lines, numbers only where a gate or the judge
- measures them).
-* **Changing what a model is shown** (a prompt file or template variable, a cookbook, a skill,
+ `languages/base.py::get_runtime`; `prompts/<lang>/{system,contract}.md` (found by
+ `prompts/catalog.language_prompt`; no cookbook — the prompts state requirements, never
+ templates (D106 / D107): no code block over ~12 lines, numbers only where a gate or the judge
+ measures them, and contract.md carries ONE executable interface example that
+ `tests/prompts/test_snippets_run.py` runs through the real runtime).
+* **Changing what a model is shown** (a prompt file or template variable, a contract, a skill,
a rubric's text, a tool description, anything a session or a judge reads):
`tests/prompts/test_manifest.py` pins every payload of offline scenarios across the four tracks
and seven languages — agent sessions, chat calls (planner, single-shot), each judge's input and
diff --git a/harness/docs/RUN_LAYOUT.md b/harness/docs/RUN_LAYOUT.md
index e9fc78bb..84cced60 100644
--- a/harness/docs/RUN_LAYOUT.md
+++ b/harness/docs/RUN_LAYOUT.md
@@ -51,7 +51,7 @@ runs/<slug>/
_cand/c<k>/ (--candidates N) best-of-N sub-workspaces (gitignored, kept for the flywheel):
each is a round of kind "candidate" — its own events.jsonl, rounds/r00.json,
gates/, judge/r00.json (one-sample judge on quick_render views)
- AGENTS.md GEMINI.md CLAUDE.md .gemini/settings.json .3dcode/cookbook.md .geminiignore .aiexclude
+ AGENTS.md CLAUDE.md .antigravityignore (vendor-CLI context; no .3dcode/cookbook.md since D107)
```
## Why the aliases point that way
@@ -143,7 +143,7 @@ produces no diff.
* **`settings.json`** (`SettingsSnapshot`) — model id, thinking level,
temperature and judge sample count per role; rounds + budget; candidates;
- seed; texture flag; rubric name **and its content hash**; prompt / cookbook
+ seed; texture flag; rubric name **and its content hash**; prompt / skill
hashes; tool versions (python, blender, node, three, chrome, puppeteer);
harness version + git sha; key-pool size; **price-table hash**; resolved
render and limit settings. Sampling values are what the track stamped as it ran,
diff --git a/harness/docs/SKILLS.md b/harness/docs/SKILLS.md
index 63c341cb..8143b651 100644
--- a/harness/docs/SKILLS.md
+++ b/harness/docs/SKILLS.md
@@ -4,13 +4,11 @@ A **skill** is a task-scoped rule sheet the harness attaches to a coding session
automatically — from the track, the language, the round kind, the plan, and **the previous
round's gate findings**. Nobody writes `skills: [...]`.
-It is not a renamed cookbook chapter. Where a language ships a cookbook
-(`codeverse3d/prompts/<lang>/cookbook.md`) it stays the reference manual with the copyable code;
-a skill states rules and numbers and names the cookbook section to fetch. Two libraries of truth
-would be worse than one. **The scene languages ship no cookbook (D106, 2026-10-15)**: their
-interface facts live in `contract.md` / `system.md`, and a scene skill is a sheet of measured
-requirements with a few SHORT optional practices (library API names, numbers only where a gate or
-the judge measures them, no code block over ~12 lines) — never a chapter to copy, since the 60
+It is not a recipe library. **No language ships a cookbook (D106 scene track, D107 the rest,
+owner 2026-10-15)**: the interface and language facts live in `contract.md` / `system.md` (each
+contract keeps ONE executable interface example), and a skill is a sheet of measured requirements
+with a few SHORT optional practices (real API names, numbers only where a gate or the judge
+measures them, no code block over ~12 lines) — never a chapter to copy, since the 60
iteration-0 argon scenes were the inlined chapters executed verbatim.
`SKILL.md` is an open standard (agentskills.io, Dec 2025), which is why the format below is
@@ -153,7 +151,7 @@ This is the difference between a metric and a number that would have read 100% f
| `c3d-scene-composition` | scene | scene_threejs | mixed | 135 | 2,119 | R14, R15, R34 |
| `c3d-scene-lighting` | scene | scene_threejs | mixed | 115 | 1,748 | R16, R17 |
| `c3d-scene-motion` | scene | scene_threejs | mixed | 185 | 2,472 | R18, R19 |
-| `c3d-threejs-shader-traps` | scene + static | threejs both | mixed | 112 | 1,734 | R20, R21 |
+| `c3d-threejs-shader-traps` | scene (+ static on a preflight finding) | threejs both | mixed | 112 | 1,734 | R20, R21 |
| `c3d-glsl-craft` | graphics | glsl_shader | mixed | 140 | 1,958 | R22, R24-glsl |
| `c3d-opengl-pipeline` | graphics | opengl_python | mixed | 98 | 1,497 | R23, R24-opengl |
| `c3d-cadquery-forms` | any | cadquery | **inherited-unverified** | 82 | 1,482 | R10 |
@@ -338,8 +336,8 @@ the `live` cases drive a real CLI.
|---|---|
| `test_loader.py` | the spec's field rules, as the loader enforces them |
| `test_spec_compliance.py` | the same rules re-derived from the raw bytes, **plus the reference validator** (`pip install skills-ref` → the `agentskills` CLI) and a field-by-field agreement check between its `read-properties` and our loader |
-| `test_library.py` | body budget, no 20-line code fences, no restating `conventions.py`, every `_claims` number still matches its live constant, **no two skills point one claim key at different numbers** |
-| `test_freshness.py` | every tool, gate kind, rubric criterion, constant, switch, sibling skill and cookbook section a bundle names still exists |
+| `test_library.py` | body budget, no code fence over 12 lines in SKILL.md or a reference (D107), no restating `conventions.py`, every `_claims` number still matches its live constant, **no two skills point one claim key at different numbers** |
+| `test_freshness.py` | every tool, gate kind, rubric criterion, constant, switch and sibling skill a bundle names still exists, every function it tells the agent to call is defined in the harness's python, and no bundle points at a cookbook |
| `test_router.py` / `test_routing_property.py` | the four routing laws by row; every corpus finding kind from every session |
| `test_telemetry.py` | the read probe, **including the control that catches git reading the tree** |
| `test_packaging.py` | **a built wheel contains all 17 `SKILL.md`, all 17 `references/`, every `_claims` file** |
@@ -647,7 +645,7 @@ chose to go deeper" (§1).
criterion. Then add its row to `docs/SKILLS_LEDGER.md`.
6. `3dcode skills validate --strict` and `pytest tests/skills`.
-Body rules: ≤ 350 lines and ≤ 2,500 tokens; no code fence over 20 lines; never restate a
+Body rules: ≤ 350 lines and ≤ 2,500 tokens; no code fence over 12 lines (D107); never restate a
frame, unit or naming rule (`conventions.py` owns those); every corpus percentage carries
its battery, its n and its date.
@@ -711,13 +709,13 @@ so; the rest are live.
* **Read rate confounds with routed-set size.** Every 1-skill session (glsl, opengl) read its
bundle 4/4 while 5-skill object sessions averaged ~55%. Any wording A/B must hold the
routed set size fixed or it measures the cap, not the copy.
-* **The wider prompt corpus still contradicts the connectivity gate on weld overlap.**
- `contract.md` was fixed for all three languages, but `tracks/generate_static.j2`
- ("overlap neighbours by ≥ 0.002 m"), `tracks/assemble_static.j2`,
- `generate_static_part.j2`, `system/harness_contract.md` ("seams overlap by ≥ 2 mm") and
- three cookbooks still teach 2–5 mm, at or above `PENETRATION_WARN_M`. **This is the single
- most likely reason `c3d-part-contact` would fail to move the number it targets, and it is
- a prompt-corpus change with its own measurement. Do it before re-running that A/B.**
+* **The prompt corpus no longer contradicts the connectivity gate on weld overlap (D107).**
+ `tracks/generate_static.j2` ("overlap neighbours by ≥ 0.002 m"), `tracks/assemble_static.j2`,
+ `generate_static_part.j2`, `system/harness_contract.md` ("seams overlap by ≥ 2 mm") and three
+ cookbooks taught 2–5 mm, at or above `PENETRATION_WARN_M`; all of them now state the gate's
+ band (gap ≤ 2 mm, overlap ≤ 2 mm) and the cookbooks are gone. It was the single most likely
+ reason `c3d-part-contact` failed to move the number it targets: re-run that A/B on a
+ post-D107 tree, and do not pool it with one from before.
* **`ENV_RECIPES` / `ZONE_RECIPES` inlining in `tracks/scene.py` is GONE (D106, 2026-10-15)** —
it was up to 6,000 unconditional tokens per env/zone session, never A/B'd against a routed
skill, and iteration 0 of the argon loop showed what it bought: 60 scenes of one shape. The
diff --git a/harness/examples/graphics_lab/README.md b/harness/examples/graphics_lab/README.md
index c19e066f..9892aa3e 100644
--- a/harness/examples/graphics_lab/README.md
+++ b/harness/examples/graphics_lab/README.md
@@ -49,13 +49,6 @@ The external shader study loads [a vertex shader](shaders/external_shader.vert),
module-relative URLs and `ShaderMaterial` + `THREE.GLSL3` — the loading pattern the
scene contract (`prompts/scene_threejs/contract.md`) teaches.
-## GLSL recipe studies
-
-`build_recipes.py [--video] [--case rain_window]` renders the three fragment
-shaders in `glsl_cases/` through the production GL host (`GlHost`), seeding each
-with the cookbook recipes it calls exactly as the `graphics` track does. Output
-goes to `output/recipes/` with an `index.html` of stills or 144-frame films.
-
All example UI, code and documentation stay in English.
## Library regression checks
diff --git a/harness/examples/graphics_lab/build_recipes.py b/harness/examples/graphics_lab/build_recipes.py
deleted file mode 100644
index 225b863f..00000000
--- a/harness/examples/graphics_lab/build_recipes.py
+++ /dev/null
@@ -1,95 +0,0 @@
-"""Render the standalone GLSL recipe studies through the production GL host.
-
-python examples/graphics_lab/build_recipes.py [--video] [--case rain_window]
-The study shader and the recipes it uses are copied beside the renders.
-"""
-from __future__ import annotations
-
-import argparse
-import html
-import json
-import re
-import shutil
-import subprocess
-from pathlib import Path
-
-from codeverse3d.languages.glsl_shader import compose
-from codeverse3d.prompts import load_text
-from codeverse3d.spatial.gl_render import GlHost
-from codeverse3d.tracks.graphics import cookbook_functions, defined_names, with_helpers
-
-HERE = Path(__file__).resolve().parent
-TITLES = {"rain_window": "Rain on glass", "material_light": "Material and moving light",
- "volume_plume": "Rising smoke volume"}
-
-
-def build(out: Path, selected: list[str], video: bool) -> dict:
- out.mkdir(parents=True, exist_ok=True)
- known = cookbook_functions(load_text("glsl_shader/cookbook.md"))
- manifest = {"cases": []}
- host = GlHost(timeout_s=240)
- cards = []
- for key, title in TITLES.items():
- if selected and key not in selected:
- continue
- source = (HERE / "glsl_cases" / f"{key}.frag").read_text()
- own = defined_names(source)
- used = [recipe for name, recipe in known.items()
- if name not in own and re.search(r"\b" + re.escape(name) + r"\s*\(", source)]
- recipes = "\n\n".join(recipe.text for recipe in with_helpers(used, known)) + "\n"
- case = out / key
- (case / "src").mkdir(parents=True, exist_ok=True)
- (case / "src/shader.frag").write_text(source)
- (case / "src/recipes.glsl").write_text(recipes)
- times = tuple(i / 24 for i in range(144)) if video else (0.0, 1.5, 3.0)
- result = host.render_fragment_shader(compose(source, recipes_src=recipes).source,
- case / "render", width=960, height=600, times=times)
- if not result.ok or any(frame.nan or frame.inf for frame in result.frames):
- raise RuntimeError(f"{key}: {result.error_message or 'nonfinite pixels'}")
- shutil.copy2(result.frames[0].path, case / "preview.png")
- if video:
- ffmpeg = shutil.which("ffmpeg")
- if not ffmpeg:
- import imageio_ffmpeg
- ffmpeg = imageio_ffmpeg.get_ffmpeg_exe()
- # The GL host's filenames use a minimum of two index digits:
- # lexicographic glob order puts frame 100 before frame 10. Feed
- # the ordered result directly so a six-second film stays in time.
- with subprocess.Popen([ffmpeg, "-y", "-loglevel", "error", "-f", "image2pipe",
- "-vcodec", "png", "-r", "24", "-i", "-", "-an",
- "-c:v", "libx264", "-crf", "18", "-pix_fmt", "yuv420p",
- "-movflags", "+faststart", str(case / "film.mp4")],
- stdin=subprocess.PIPE) as encoder:
- assert encoder.stdin is not None
- for frame in result.frames:
- encoder.stdin.write(Path(frame.path).read_bytes())
- encoder.stdin.close()
- if encoder.wait():
- raise RuntimeError(f"{key}: video encoder failed")
- record = {"id": key, "title": title, "renderer": result.renderer, "gpu": result.gpu,
- "frames": len(result.frames), "render_ms": result.duration_ms}
- manifest["cases"].append(record)
- media = (f'<video controls loop playsinline poster="{key}/preview.png" src="{key}/film.mp4"></video>'
- if video else f'<img src="{key}/preview.png" alt="{html.escape(title)}">')
- cards.append(f'<article><h2>{html.escape(title)}</h2>{media}<p><a href="{key}/src/shader.frag">'
- f'Study source</a> · <a href="{key}/src/recipes.glsl">Library recipes</a></p></article>')
- print(json.dumps(record), flush=True)
- (out / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
- (out / "index.html").write_text('''<!doctype html><html lang="en"><meta charset="utf-8">
-<meta name="viewport" content="width=device-width,initial-scale=1"><title>Graphics Lab · GLSL Studies</title>
-<style>body{margin:40px auto;max-width:1280px;padding:0 24px;background:#101817;color:#e8eee9;font:16px/1.6 system-ui}
-main{display:grid;grid-template-columns:repeat(auto-fit,minmax(360px,1fr));gap:24px}article{background:#1b2724;padding:20px}
-img,video{width:100%;display:block}h1{font-size:42px}h2{font-size:22px}a{color:#c4d9af}</style>
-<h1>Light, surfaces, atmosphere.</h1><p>Three authored studies using the agent-facing GLSL recipe library.
-Rendered locally with the production OpenGL host. Source and dependencies are included.</p><main>'''
- + "".join(cards) + "</main></html>\n")
- return manifest
-
-
-if __name__ == "__main__":
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--out", type=Path, default=HERE / "output/recipes")
- parser.add_argument("--case", action="append", choices=list(TITLES), default=[])
- parser.add_argument("--video", action="store_true")
- args = parser.parse_args()
- build(args.out, args.case, args.video)
diff --git a/harness/examples/graphics_lab/glsl_cases/material_light.frag b/harness/examples/graphics_lab/glsl_cases/material_light.frag
deleted file mode 100644
index 8d94468d..00000000
--- a/harness/examples/graphics_lab/glsl_cases/material_light.frag
+++ /dev/null
@@ -1,56 +0,0 @@
-// Analytic spheres under a studio key: direct GGX and approximate environment fill.
-// No transmission, area-light solver, or path-traced indirect light is claimed.
-vec3 centre(int i) { return vec3((float(i)-1.0)*1.5,0.0,0.0); }
-float sphereHit(vec3 ro,vec3 rd,vec3 c) {
- vec3 oc=ro-c;float b=dot(oc,rd),h=b*b-dot(oc,oc)+.64*.64;
- if(h<0.0) return 1000.0;
- float near=-b-sqrt(h);return near>.001?near:1000.0;
-}
-vec3 studio(vec3 d,float roughness) {
- vec3 base=mix(vec3(.12,.09,.065),vec3(.10,.15,.23),smoothstep(-.2,.8,d.y));
- float softbox=pow(max(dot(d,normalize(vec3(-1,2,2))),0.0),mix(72.0,4.0,roughness));
- float strip=pow(max(dot(d,normalize(vec3(2,1,-1))),0.0),mix(100.0,8.0,roughness));
- return base+vec3(2.8,2.5,2.0)*softbox+vec3(.4,.8,1.2)*strip;
-}
-float visibility(vec3 p,vec3 toLight) {
- float result=1.0;
- for(int i=0;i<3;i++) {
- vec3 toSphere=centre(i)-p;float along=dot(toSphere,toLight);
- if(along>.02) {
- float distance=length(toSphere-toLight*along);
- result=min(result,smoothstep(.58,.70+along*.08,distance));
- }
- }
- return result;
-}
-void mainImage(out vec4 fragColor,in vec2 fragCoord) {
- vec2 uv=(fragCoord-.5*u_resolution)/u_resolution.y;
- vec3 ro=vec3(.65,1.9,5.6),target=vec3(0,-.12,0);
- vec3 f=normalize(target-ro),r=normalize(cross(f,vec3(0,1,0))),up=cross(r,f);
- vec3 rd=normalize(uv.x*r+uv.y*up+1.65*f);
- float hit=1000.0;int object=-1;
- for(int i=0;i<3;i++) {float d=sphereHit(ro,rd,centre(i));if(d<hit){hit=d;object=i;}}
- float ground=rd.y<0.0?(-.64-ro.y)/rd.y:1000.0;
- if(ground<hit){hit=ground;object=3;}
- vec3 colour=studio(rd,1.0)*.45;
- if(hit<1000.0) {
- vec3 p=ro+rd*hit,n=object==3?vec3(0,1,0):normalize(p-centre(object)),v=-rd;
- vec3 albedo=object==0?vec3(.65,.21,.075):object==1?vec3(.72,.51,.20):vec3(.55,.67,.72);
- float metal=object==1?1.0:0.0,roughness=object==0?.5:object==1?.19:.12;
- if(object==3){albedo=vec3(.18,.2,.21)*(.88+.12*noise(p.xz*18.0));roughness=.88;metal=0.0;}
- vec3 light=normalize(vec3(-2.2+sin(u_time*.5),4.2,3.0));
- float shadow=visibility(p+n*.002,light);
- colour=pbrDirect(albedo,metal,roughness,n,v,light,vec3(4.3,3.9,3.3))*shadow;
- colour+=pbrDirect(albedo,metal,roughness,n,v,normalize(vec3(3,1,-2)),vec3(.25,.50,.9));
- vec3 fresnel=fresnelSchlick(max(dot(n,v),0.0),mix(vec3(.04),albedo,metal));
- colour+=(1.0-metal)*(1.0-fresnel)*albedo*studio(n,1.0)*.3;
- colour+=fresnel*studio(reflect(-v,n),roughness)*(1.0-.55*roughness);
- if(object==3) {
- float contact=1.0;
- for(int i=0;i<3;i++) contact*=1.0-.45*exp(-3.5*length(p.xz-centre(i).xz));
- colour*=contact;
- }
- colour=mix(colour,vec3(.08,.1,.13),1.0-exp(-hit*.008));
- }
- fragColor=vec4(gamma(tonemapACES(colour)),1.0);
-}
diff --git a/harness/examples/graphics_lab/glsl_cases/rain_window.frag b/harness/examples/graphics_lab/glsl_cases/rain_window.frag
deleted file mode 100644
index 615af3d8..00000000
--- a/harness/examples/graphics_lab/glsl_cases/rain_window.frag
+++ /dev/null
@@ -1,27 +0,0 @@
-// Rain on glass with coherent falling droplets and a defocused night street.
-// The library supplies dropsLayer, bokehSoft, hash12, tonemapACES and gamma.
-vec3 street(vec2 uv, float t) {
- vec2 p=(uv-.5)*vec2(u_resolution.x/u_resolution.y,1.0);
- float city=1.0-smoothstep(-.03,.35,p.y);
- vec3 colour=vec3(.005,.008,.015)+bokehSoft(p*1.1+vec2(0,.11),t*.15)*city*1.4;
- float horizon=exp(-pow((p.y+.10)*7.0,2.0));
- colour+=vec3(.015,.025,.034)*horizon;
- float traffic=exp(-pow((p.y+.29)*22.0,2.0));
- colour+=traffic*(vec3(.3,.045,.012)*exp(-pow((p.x-.24-.035*t)*9.0,2.0))+
- vec3(.12,.20,.32)*exp(-pow((p.x+.3+.045*t)*12.0,2.0)));
- return colour;
-}
-void mainImage(out vec4 fragColor,in vec2 fragCoord) {
- vec2 uv=fragCoord/u_resolution;
- vec2 rain=dropsLayer(uv,u_time*1.2,3.8)+.35*dropsLayer(uv+3.17,u_time*.9,7.3);
- float bead=rain.x+.3*rain.y;
- vec2 normal=vec2(dFdx(bead),dFdy(bead))*u_resolution*vec2(.0008,.0011);
- normal=clamp(normal,vec2(-.025),vec2(.025));
- vec3 colour=street(uv+normal,u_time);
- colour*=1.0-.14*rain.x;
- float edge=length(normal);
- colour+=street(uv+vec2(-.04,.07),u_time)*.18*smoothstep(.008,.027,edge)*(1.0-.7*rain.y);
- colour*=.82+.18*pow(16.0*uv.x*uv.y*(1.0-uv.x)*(1.0-uv.y),.2);
- colour+=(hash12(fragCoord)-.5)/900.0;
- fragColor=vec4(gamma(tonemapACES(colour)),1.0);
-}
diff --git a/harness/examples/graphics_lab/glsl_cases/volume_plume.frag b/harness/examples/graphics_lab/glsl_cases/volume_plume.frag
deleted file mode 100644
index 135d8844..00000000
--- a/harness/examples/graphics_lab/glsl_cases/volume_plume.frag
+++ /dev/null
@@ -1,53 +0,0 @@
-// Prescribed rising density, not a fluid simulation. Metre-space integration.
-float plumeDensity(vec3 p,float t) {
- float height=p.y;
- if(height<0.0||height>3.0) return 0.0;
- float age=height/.65;
- vec2 drift=vec2(.08*age,.03*age)+vec2(.10*sin(height*3.0-t*1.1),.09*cos(height*2.7-t*.9))*height;
- vec3 q=vec3(p.xz-drift,height-t*.65);
- vec3 warp=vec3(noise3(q*2.5),noise3(q*2.5+13.0),noise3(q*2.5+29.0))-.5;
- float coarse=fbmVolume(q*3.2+warp*.8+vec3(4.2,1.7,0.0));
- float radius=.12+.21*height;
- float body=max(0.0,1.0-length(p.xz-drift)/radius+(coarse-.47)*2.8);
- float detail=fbmVolume(q*9.7+vec3(13.0,7.0,t*.13));
- return max(0.0,body*.65-(1.0-detail)*.25)*
- smoothstep(0.0,.13,height)*(1.0-smoothstep(2.1,3.0,height));
-}
-void mainImage(out vec4 fragColor,in vec2 fragCoord) {
- vec2 uv=(fragCoord-.5*u_resolution)/u_resolution.y;
- vec3 ro=vec3(3.0,2.7,5.0),target=vec3(.1,1.3,0);
- vec3 f=normalize(target-ro),right=normalize(cross(f,vec3(0,1,0))),up=cross(right,f);
- vec3 rd=normalize(uv.x*right+uv.y*up+1.55*f);
- vec3 toSun=normalize(vec3(-1.5,2.5,-1.0));
- vec3 horizon=vec3(.06,.085,.11);
- vec3 background=mix(horizon,vec3(.025,.055,.085),smoothstep(0.0,.6,rd.y));
- float ground=rd.y<0.0?-ro.y/rd.y:1000.0;
- if(ground<1000.0) {
- vec3 p=ro+rd*ground;
- background=vec3(.035,.041,.046)*(.92+.08*noise(p.xz*12.0));
- background=mix(background,horizon,1.0-exp(-ground*.06));
- background*=1.0-.5*exp(-dot(p.xz,p.xz)*3.0);
- }
- vec3 inv=1.0/(rd+vec3(1e-7));
- vec3 nearBox=(vec3(-1.4,0,-1.4)-ro)*inv,farBox=(vec3(1.4,3,1.4)-ro)*inv;
- vec3 lower=min(nearBox,farBox),upper=max(nearBox,farBox);
- float enter=max(0.0,max(lower.x,max(lower.y,lower.z))),leave=min(ground,min(upper.x,min(upper.y,upper.z)));
- vec3 colour=vec3(0);float transmission=1.0;
- if(leave>enter) {
- float stepLength=(leave-enter)/64.0;
- for(int i=0;i<64;i++) {
- vec3 p=ro+rd*(enter+(float(i)+.5)*stepLength);
- float density=plumeDensity(p,u_time),lightDepth=0.0;
- if(density>.001) {
- for(int j=0;j<6;j++) lightDepth+=plumeDensity(p+toSun*(float(j)+.5)*.18,u_time)*.18;
- float stepT=beerTransmittance(density*3.6,stepLength);
- vec3 illumination=vec3(.075,.12,.17)+vec3(7.0,5.9,4.4)*
- phaseHG(dot(rd,toSun),.45)*beerTransmittance(lightDepth*3.6,1.0);
- colour+=transmission*(1.0-stepT)*illumination;
- transmission*=stepT;
- }
- if(transmission<.015) break;
- }
- }
- fragColor=vec4(gamma(tonemapACES(colour+transmission*background)),1.0);
-}
diff --git a/harness/tests/agents/test_claude_code.py b/harness/tests/agents/test_claude_code.py
index 45a51f74..7500564b 100644
--- a/harness/tests/agents/test_claude_code.py
+++ b/harness/tests/agents/test_claude_code.py
@@ -88,7 +88,7 @@ def test_parse_envelope_variants():
def test_the_mcp_config_is_the_typed_jobs_never_the_workspace_file(tmp_ws: Workspace):
cmd = ["python", "-m", "codeverse3d.spatial.mcp_server", "--workspace", str(tmp_ws.root)]
- materialize_workspace(tmp_ws, agent_kind="claude-code", contract_md="c", cookbook_text="", spatial_tools=True,
+ materialize_workspace(tmp_ws, agent_kind="claude-code", contract_md="c", spatial_tools=True,
mcp_command=cmd)
a = ClaudeCodeAgent("sonnet", binary="claude")
s = begin_session(AgentJob(workspace=str(tmp_ws.root), prompt="p", mcp_command=cmd), "claude-code")
diff --git a/harness/tests/agents/test_cli_common.py b/harness/tests/agents/test_cli_common.py
index 82143d05..5dcfae29 100644
--- a/harness/tests/agents/test_cli_common.py
+++ b/harness/tests/agents/test_cli_common.py
@@ -177,7 +177,7 @@ def test_mcp_command_resolution(tmp_ws: Workspace):
assert mcp_command_for(tmp_ws, job2) == ["python", "-m", "x"]
# a workspace .mcp.json NEVER wins: the agent works in that directory and could
# otherwise choose what the next round's CLI launches (audit 2026-08-27)
- materialize_workspace(tmp_ws, agent_kind="codex", contract_md="c", cookbook_text="", spatial_tools=True,
+ materialize_workspace(tmp_ws, agent_kind="codex", contract_md="c", spatial_tools=True,
mcp_command=default_mcp_command(tmp_ws, language="cadquery"))
assert mcp_command_for(tmp_ws, job2) == ["python", "-m", "x"] # still the typed job
(tmp_ws.root / ".mcp.json").write_text(json.dumps(
diff --git a/harness/tests/agents/test_cli_write_scope.py b/harness/tests/agents/test_cli_write_scope.py
index dcf9d779..8fcfbf65 100644
--- a/harness/tests/agents/test_cli_write_scope.py
+++ b/harness/tests/agents/test_cli_write_scope.py
@@ -135,11 +135,11 @@ def test_entry_file_writes_need_ownership(scoped_ws: Workspace):
def test_a_harness_owned_file_is_restored_when_the_agent_rewrites_it(tmp_ws, monkeypatch):
- """A read_only harness file (src/recipes.glsl) is restored and the session fails."""
- owned = "src/recipes.glsl"
+ """A read_only harness file (an exact-file entry) is restored and the session fails."""
+ owned = "src/owned.glsl"
(tmp_ws.root / owned).parent.mkdir(parents=True, exist_ok=True)
(tmp_ws.root / owned).write_text("float aurora(vec2 p){return 0.0;}\n")
- tmp_ws.commit("harness recipes")
+ tmp_ws.commit("harness-owned file")
job = AgentJob(workspace=str(tmp_ws.root), prompt="p", label="gfx",
write_roots=["src/"], read_only=[owned])
s = begin_session(job, "codex")
diff --git a/harness/tests/agents/test_codex.py b/harness/tests/agents/test_codex.py
index 8cc64ee5..3494691e 100644
--- a/harness/tests/agents/test_codex.py
+++ b/harness/tests/agents/test_codex.py
@@ -134,10 +134,9 @@ def test_live_codex_mcp_tool_call_is_not_cancelled(tmp_ws: Workspace):
from codeverse3d.agents.cli_common import default_mcp_command
from codeverse3d.agents.materialize import materialize_workspace
- from codeverse3d.prompts import load_text
trimesh.creation.box().export(tmp_ws.artifacts / "object.glb")
- materialize_workspace(tmp_ws, agent_kind="codex", contract_md="c", cookbook_text=load_text("threejs/cookbook.md"), spatial_tools=True,
+ materialize_workspace(tmp_ws, agent_kind="codex", contract_md="c", spatial_tools=True,
mcp_command=default_mcp_command(tmp_ws, language="threejs"))
a = CodexAgent("")
res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="Call the 3dcode MCP tool `measure` exactly once, then reply with the "
diff --git a/harness/tests/agents/test_materialize.py b/harness/tests/agents/test_materialize.py
index c0f31ac7..f367a1d2 100644
--- a/harness/tests/agents/test_materialize.py
+++ b/harness/tests/agents/test_materialize.py
@@ -1,4 +1,4 @@
-"""materialize_workspace: bodies, ignore file, cookbook, codex overrides."""
+"""materialize_workspace: bodies, ignore file, codex overrides."""
from __future__ import annotations
@@ -9,15 +9,20 @@ import sys
import tomllib
from codeverse3d.agents.cli_common import default_mcp_command
-from codeverse3d.agents.materialize import codex_mcp_overrides, materialize_workspace
+from codeverse3d.agents.materialize import (
+ LEGACY_COOKBOOK,
+ codex_mcp_overrides,
+ materialize_workspace,
+ needs_rematerialize,
+)
from codeverse3d.workspace import Workspace
CONTRACT = "## blender contract\nWrite pure bpy into src/model.py."
-def _mat(ws: Workspace, kind: str = "agy", spatial: bool = True, cookbook: str = ""):
- return materialize_workspace(ws, agent_kind=kind, contract_md=CONTRACT, cookbook_text=cookbook,
- spatial_tools=spatial, mcp_command=default_mcp_command(ws))
+def _mat(ws: Workspace, kind: str = "agy", spatial: bool = True):
+ return materialize_workspace(ws, agent_kind=kind, contract_md=CONTRACT, spatial_tools=spatial,
+ mcp_command=default_mcp_command(ws))
def test_bodies_document_only_this_tracks_tools(tmp_ws: Workspace):
@@ -50,20 +55,31 @@ def test_no_mcp_config_and_no_gemini_body_is_written_into_the_workspace(tmp_ws:
assert {p.name for p in tmp_ws.root.glob("*.md")} >= {"AGENTS.md", "CLAUDE.md"}
-def test_a_language_without_a_cookbook_gets_no_section_and_no_file(tmp_ws: Workspace):
- """The scene languages ship no cookbook (owner, 2026-10-15): the body carries no "## Cookbook"
- section — not a note saying one is missing, which only sends the agent looking — and no
- ``.3dcode/cookbook.md`` is written (a stale one from an earlier materialisation goes). A
- language that ships one still gets the section and the file."""
- tmp_ws.spec_path.write_text(json.dumps({"id": "t", "track": "scene", "language": "scene_threejs", "prompt": "p"}))
- _mat(tmp_ws, cookbook="# a cookbook\n\nsnippets\n")
- body = (tmp_ws.root / "AGENTS.md").read_text()
- assert "## Cookbook" in body and (tmp_ws.root / ".3dcode" / "cookbook.md").read_text() == "# a cookbook\n\nsnippets\n"
- _mat(tmp_ws, cookbook="")
+def test_the_body_is_rules_tools_and_contract_and_never_mentions_a_cookbook(tmp_ws: Workspace):
+ """No language ships a cookbook (D107, owner 2026-10-15): the body is Hard rules → Spatial tools →
+ Language contract, says nothing about a cookbook (a note that one is missing only sends the agent
+ looking), and writes nothing under ``.3dcode/`` for the agent to read."""
+ tmp_ws.spec_path.write_text(json.dumps({"id": "t", "track": "static_object", "language": "blender", "prompt": "p"}))
+ _mat(tmp_ws)
body = (tmp_ws.root / "AGENTS.md").read_text()
- assert "## Cookbook" not in body and "cookbook" not in body.lower()
- assert not (tmp_ws.root / ".3dcode" / "cookbook.md").exists()
- assert body.index("## Spatial tools") < body.index("## Language contract") # the sections around it stay in order
+ assert "cookbook" not in body.lower()
+ assert body.index("## Hard rules") < body.index("## Spatial tools") < body.index("## Language contract")
+ assert not (tmp_ws.root / ".3dcode").exists() or not any((tmp_ws.root / ".3dcode").iterdir())
+
+
+def test_a_workspace_materialised_before_d107_is_rematerialised_and_loses_its_cookbook(tmp_ws: Workspace):
+ """A resumed pre-D107 run still holds ``.3dcode/cookbook.md`` and a "## Cookbook" body section:
+ ``needs_rematerialize`` says so (``ensure_materialized`` then writes the body again), and
+ materialising removes the file."""
+ tmp_ws.spec_path.write_text(json.dumps({"id": "t", "track": "static_object", "language": "blender", "prompt": "p"}))
+ legacy = tmp_ws.root / LEGACY_COOKBOOK
+ legacy.parent.mkdir(parents=True, exist_ok=True)
+ legacy.write_text("# Cookbook\n")
+ (tmp_ws.root / "AGENTS.md").write_text("## Cookbook\ncopy its patterns exactly\n")
+ assert needs_rematerialize(tmp_ws)
+ _mat(tmp_ws)
+ assert not legacy.exists() and not needs_rematerialize(tmp_ws)
+ assert "cookbook" not in (tmp_ws.root / "AGENTS.md").read_text().lower()
def test_ignore_files_keep_agent_facing_paths_readable(tmp_ws: Workspace):
@@ -89,7 +105,7 @@ def test_ignore_files_keep_agent_facing_paths_readable(tmp_ws: Workspace):
assert "artifacts/" not in lines and "trajectories/" in lines
for readable in ("artifacts/census.json", "artifacts/build.json", "artifacts/measurement.json",
"artifacts/gates/r00/contract_tool.json", "artifacts/tool_renders/r00_ab/sheet.png",
- "src/model.py", ".3dcode/cookbook.md"):
+ "src/model.py", ".3dcode/images/ref.png"):
assert not ignored(readable, lines), readable
for hidden in ("artifacts/renders/r00/sheet.png", "trajectories/baseline_r00/stdout.json",
"trajectories/baseline_r00/prompt.md", "trajectories/baseline_r00/agy.log",
diff --git a/harness/tests/blender_cadquery/test_blender_lint.py b/harness/tests/blender_cadquery/test_blender_lint.py
index fdcb2c99..b2a250d9 100644
--- a/harness/tests/blender_cadquery/test_blender_lint.py
+++ b/harness/tests/blender_cadquery/test_blender_lint.py
@@ -108,7 +108,7 @@ def test_camera_light_and_render_settings_warn() -> None:
def test_a_join_after_setting_the_active_object_is_not_warned() -> None:
- """The urdf cookbook's `join_as` sets the active object first — what the join warning asks for."""
+ """A join that sets the active object first (one joined object per urdf link) — what the join warning asks for."""
src = ("import bpy\nobjs = [o for o in bpy.data.objects]\nfor o in objs: o.select_set(True)\n"
"bpy.context.view_layer.objects.active = objs[0]\nbpy.ops.object.join()\n")
assert not any("join" in m for m in _msgs(lint_blender_source(src), Severity.WARN))
diff --git a/harness/tests/blender_cadquery/test_blender_multifile.py b/harness/tests/blender_cadquery/test_blender_multifile.py
index d79e99f8..353b0e7c 100644
--- a/harness/tests/blender_cadquery/test_blender_multifile.py
+++ b/harness/tests/blender_cadquery/test_blender_multifile.py
@@ -1,12 +1,11 @@
"""Multi-file blender models on the real binary: a hand-written 2-part model's errors map to
-the failing PART file + line; the prompt examples (contract.md example A, cookbook "File
-layout") build and export. (The multi-file skeleton build is test_blender_runtime's.)"""
+the failing PART file + line; the contract's one executable interface example builds and exports.
+(The multi-file skeleton build is test_blender_runtime's.)"""
from __future__ import annotations
import json
import re
-from pathlib import Path
import pytest
@@ -111,7 +110,7 @@ def test_live_multifile_errors_map_to_part_file_and_line(tmp_ws, blender_bin) ->
def test_live_contract_multifile_example_builds(tmp_ws, blender_bin) -> None:
trimesh = pytest.importorskip("trimesh")
files = labelled_py_files("blender/contract.md")
- assert set(files) == {"src/parts/seat.py", "src/parts/leg.py", "src/model.py"}
+ assert set(files) == {"src/parts/body.py", "src/parts/knob.py", "src/model.py"}
_write_files(tmp_ws, files)
rt = BlenderRuntime(blender=blender_bin)
lint = rt.lint(tmp_ws)
@@ -119,19 +118,7 @@ def test_live_contract_multifile_example_builds(tmp_ws, blender_bin) -> None:
r = rt.build(tmp_ws, timeout_s=120)
assert r.ok, (r.error_type, r.error_message, r.error_file, r.error_line)
scene = trimesh.load(r.glb_path)
- assert set(scene.graph.nodes_geometry) == {"Seat", "Leg_0", "Leg_1", "Leg_2"}
+ assert set(scene.graph.nodes_geometry) == {"Body", "Knob_0", "Knob_1"} # one node per part / instance
lo, hi = scene.bounds
- assert abs(lo[1]) < 1e-3 and abs(hi[1] - 0.45) < 1e-3 # Y-up GLB, on the ground, seat top at 0.45
+ assert abs(lo[1]) < 1e-3 and hi[1] > 0.01 # Y-up GLB, lowest point on the ground
-
-def test_live_cookbook_layout_example_builds(tmp_ws, blender_bin) -> None:
- files = labelled_py_files("blender/cookbook.md")
- assert set(files) == {"src/parts/mug_body.py", "src/model.py"}
- _write_files(tmp_ws, files)
- rt = BlenderRuntime(blender=blender_bin)
- assert rt.lint(tmp_ws).passed
- r = rt.build(tmp_ws, timeout_s=120)
- assert r.ok, (r.error_type, r.error_message, r.error_file, r.error_line)
- assert {o["name"] for o in r.census["objects"] if o["type"] == "MESH"} == {"MugBody"}
- assert Path(r.glb_path).stat().st_size > 500
diff --git a/harness/tests/blender_cadquery/test_blender_runtime.py b/harness/tests/blender_cadquery/test_blender_runtime.py
index f3ca3f43..6e4fa1c0 100644
--- a/harness/tests/blender_cadquery/test_blender_runtime.py
+++ b/harness/tests/blender_cadquery/test_blender_runtime.py
@@ -58,7 +58,7 @@ def test_live_skeleton_builds_and_exports_canonical_glb(tmp_ws, table_plan, blen
assert abs(lo[1]) < 1e-4 and abs(hi[1] - 0.6) < 1e-3 # Y-up, ground contact, height 0.6
assert abs(lo[0] + 0.25) < 1e-3 and abs(hi[2] - 0.25) < 1e-3
leg0 = scene.geometry[scene.graph["Leg_0"][1]]
- assert len(leg0.faces) > 12 # bevel modifier applied on export
+ assert len(leg0.faces) == 12 # a plain placeholder box: the skeleton chooses no edge treatment
assert leg0.visual.material.baseColorFactor[0] > leg0.visual.material.baseColorFactor[2] # oak-ish
c = r.census
assert c["tri_count"] == sum(o["tri_count"] for o in c["objects"] if o["type"] == "MESH")
diff --git a/harness/tests/blender_cadquery/test_cadquery_lint.py b/harness/tests/blender_cadquery/test_cadquery_lint.py
index 93ba727d..2a93104d 100644
--- a/harness/tests/blender_cadquery/test_cadquery_lint.py
+++ b/harness/tests/blender_cadquery/test_cadquery_lint.py
@@ -58,3 +58,27 @@ def test_rotate_angle_expression_table() -> None:
for expr in radians:
r = lint_cadquery_source(_rotate_src(expr))
assert not r.passed and any("DEGREES" in m for m in _msgs(r, Severity.ERROR)), (expr, _msgs(r))
+
+
+def test_fillet_and_chamfer_calls_are_not_findings() -> None:
+ """The build reports an OCC refusal where it happens; the lint no longer emits a per-call INFO
+ carrying fillet practices (D106 rule: the lint states facts the build measures, never a template)."""
+ r = lint_cadquery_source("import cadquery as cq\nw = cq.Workplane().box(1, 1, 1).edges('|Z').fillet(0.1).edges('>Z').chamfer(0.01)\n"
+ "result = cq.Assembly()\nresult.add(w, name='Part', color=cq.Color(0.5, 0.5, 0.5))\n")
+ assert r.passed and not r.findings, [f.message for f in r.findings]
+
+
+def test_contract_import_list_matches_the_lint() -> None:
+ """One rule, one text: the contract's Imports section names every module the lint allows and every
+ module it forbids — neither list may drift from ``ALLOWED_IMPORTS`` / ``FORBIDDEN_IMPORTS``."""
+ import re
+ from pathlib import Path
+
+ from codeverse3d.languages.cadquery import ALLOWED_IMPORTS, FORBIDDEN_IMPORTS
+
+ text = Path(__file__).resolve().parents[2] / "codeverse3d" / "prompts" / "cadquery" / "contract.md"
+ section = text.read_text().split("## Imports", 1)[1].split("\n## ", 1)[0]
+ allowed_para, forbidden_para = section.split("* Forbidden (lint ERROR):", 1)
+ named = lambda s: set(re.findall(r"`([A-Za-z_][A-Za-z0-9_]*)`", s)) # noqa: E731
+ assert named(allowed_para) >= ALLOWED_IMPORTS - {"cq", "np", "__future__"}, sorted(ALLOWED_IMPORTS - named(allowed_para))
+ assert named(forbidden_para.split("* Forbidden calls", 1)[0]) == set(FORBIDDEN_IMPORTS)
diff --git a/harness/tests/blender_cadquery/test_prompt_block_lint.py b/harness/tests/blender_cadquery/test_prompt_block_lint.py
index 263867eb..091126ad 100644
--- a/harness/tests/blender_cadquery/test_prompt_block_lint.py
+++ b/harness/tests/blender_cadquery/test_prompt_block_lint.py
@@ -27,13 +27,13 @@ def blocks(rel: str) -> list[tuple[int, str]]:
def test_prompt_blocks_lint_clean() -> None:
- for rel in ("blender/cookbook.md", "blender/contract.md"):
+ for rel in ("blender/contract.md",): # the blender cookbook is gone (D106 rule, every track)
for line, code in blocks(rel):
src = code if "import bpy" in code else BLENDER_HEADER + code
r = lint_blender_source(src, expect_names=False)
errs = [(f.data.get("line"), f.message) for f in r.findings if f.severity.value == "error"]
assert not errs, f"{rel} block at line {line}: {errs}"
- for rel in ("cadquery/cookbook.md", "cadquery/contract.md"):
+ for rel in ("cadquery/contract.md",): # the cadquery cookbook is gone (D106 rule, every track)
for line, code in blocks(rel):
src = code if "import cadquery" in code else CADQUERY_HEADER + code
if not re.search(r"^result\s*=", src, re.M):
diff --git a/harness/tests/core/test_config_env_aliases.py b/harness/tests/core/test_config_env_aliases.py
index b7256a04..80b068f1 100644
--- a/harness/tests/core/test_config_env_aliases.py
+++ b/harness/tests/core/test_config_env_aliases.py
@@ -11,14 +11,14 @@ from codeverse3d.config import Settings
def test_every_switch_speaks_one_grammar(monkeypatch, caplog):
"""on/off, 1/0, true/false, yes/no in any case and padding; empty is unset; else warn (D44 c)."""
- env, default = "C3D_SEED_RECIPES", True # a nested field under its flat spelling
+ env, default = "C3D_PLAN_BRIEF", True # a top-level Flag (the flat spellings left are an int and a str, D107)
def read(raw: str | None) -> bool:
if raw is None:
monkeypatch.delenv(env, raising=False)
else:
monkeypatch.setenv(env, raw)
s = Settings()
- return s.limits.seed_recipes
+ return s.plan_brief
assert read(None) is default and read("") is default
for word in ("off", "0", "false", "no", "OFF", " Off "):
diff --git a/harness/tests/cost/test_live.py b/harness/tests/cost/test_live.py
index 5e91c6f7..61fa66d1 100644
--- a/harness/tests/cost/test_live.py
+++ b/harness/tests/cost/test_live.py
@@ -24,7 +24,10 @@ def _stable_text() -> str:
return "\n".join([
build_system_prompt(load_rubric("static_object_v1")),
(REPO / "codeverse3d/prompts/blender/contract.md").read_text(),
- (REPO / "codeverse3d/prompts/blender/cookbook.md").read_text(),
+ (REPO / "codeverse3d/prompts/blender/system.md").read_text(),
+ (REPO / "codeverse3d/prompts/system/harness_contract.md").read_text(),
+ *((REPO / "codeverse3d/skills" / name / "SKILL.md").read_text()
+ for name in ("c3d-part-contact", "c3d-blender-forms")),
])
diff --git a/harness/tests/graphics/test_gl_runtime.py b/harness/tests/graphics/test_gl_runtime.py
index 20577c72..ba5834c2 100644
--- a/harness/tests/graphics/test_gl_runtime.py
+++ b/harness/tests/graphics/test_gl_runtime.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
+import re
import numpy as np
import pytest
@@ -11,6 +12,7 @@ from PIL import Image
from codeverse3d.contracts.plan import GraphicsPlan, PassPlan
from codeverse3d.languages.glsl_shader import GlslShaderRuntime
from codeverse3d.languages.opengl_python import OpenGLPythonRuntime
+from codeverse3d.prompts import load_text
from codeverse3d.spatial import gl_render
from codeverse3d.spatial.gl_render import GlHost, GlHostError
from codeverse3d.spatial.registry import ToolContext, get_tool
@@ -42,11 +44,17 @@ def _ws_with_plan(tmp_ws):
def test_shader_skeleton_builds_and_writes_artifacts(tmp_ws, host):
+ """The glsl_shader stub (D107): the entry point, the plan as comments and ONE flat grey write —
+ no sky, sun or vignette to "keep the structure" of. It lints clean and builds the judged frames,
+ and the gate convicts it as `static` until the plan's passes replace the write."""
ws = _ws_with_plan(tmp_ws)
rt = GlslShaderRuntime(host=host)
paths = rt.skeleton(ws, PLAN)
assert {p.name for p in paths} == {"common.glsl", "shader.frag"}
- assert "TODO pass 1: Sky" in (ws.src / "shader.frag").read_text()
+ src = (ws.src / "shader.frag").read_text()
+ assert "TODO pass 1: Sky" in src
+ for template in ("sunPos", "vignette", "haze", "mix(vec3"):
+ assert template not in src, template
assert rt.lint(ws).passed
br = rt.build(ws, **SMALL)
assert br.ok, br.error_message
@@ -56,11 +64,33 @@ def test_shader_skeleton_builds_and_writes_artifacts(tmp_ws, host):
frames = sorted((ws.artifacts / "frames").glob("f*_t*.png"))
assert len(frames) == 5 # t = 0, 1, 2.5, 4, 6 (duration 6)
metrics = json.loads((ws.artifacts / "metrics.json").read_text())
- assert metrics["stats"]["mean_lum"] > 0.1 and not metrics["stats"]["any_nan"] and not metrics["stats"]["static"]
+ assert metrics["stats"]["mean_lum"] > 0.1 and not metrics["stats"]["any_nan"] and metrics["stats"]["static"]
+ assert any(f["data"]["kind"] == "static" for f in metrics["gate"]["findings"])
assert br.census["convention"] == "mainImage" and br.census["feedback"] is False
assert (ws.artifacts / "build.json").is_file()
+def test_glsl_contract_example_builds(tmp_ws, host):
+ """The ONE executable interface example in glsl_shader/contract.md runs as src/shader.frag: lint
+ clean, five judged frames, no NaN, not static, no flicker — the only runnable prompt material the
+ language ships now that its cookbook and the seeded recipes are gone (D107)."""
+ text = load_text("glsl_shader/contract.md")
+ blocks = [b for b in re.findall(r"```glsl\n(.*?)```", text, re.S) if b.lstrip().startswith("void mainImage") and "..." not in b]
+ assert len(blocks) == 1, "the contract ships exactly one complete example"
+ assert len(blocks[0].strip().splitlines()) <= 12
+ ws = _ws_with_plan(tmp_ws)
+ ws.src.mkdir(parents=True, exist_ok=True)
+ (ws.src / "shader.frag").write_text(blocks[0])
+ rt = GlslShaderRuntime(host=host)
+ assert rt.lint(ws).passed
+ br = rt.build(ws, **SMALL)
+ assert br.ok, br.error_message
+ metrics = json.loads((ws.artifacts / "metrics.json").read_text())
+ assert len(list((ws.artifacts / "frames").glob("f*_t*.png"))) == 5
+ assert not metrics["stats"]["static"] and not metrics["stats"]["flicker"] and not metrics["stats"]["any_nan"]
+ assert metrics["gate"]["passed"]
+
+
def test_feedback_and_nan_detection(tmp_ws, host):
ws = _ws_with_plan(tmp_ws)
(ws.src / "shader.frag").write_text(
@@ -126,22 +156,46 @@ void main() {
def test_program_skeleton_builds_and_errors_map(tmp_ws, host):
+ """The opengl_python stub (D107): one t-dependent full-screen pass, no subject, camera or palette —
+ it lints clean, builds the judged frames, is neither static nor flickering, and a runtime error in
+ render() maps back to src/program.py:LINE."""
ws = _ws_with_plan(tmp_ws)
rt = OpenGLPythonRuntime(host=host)
rt.skeleton(ws, PLAN)
assert rt.lint(ws).passed
+ src = (ws.src / "program.py").read_text()
+ for template in ("_cube", "_perspective", "_look_at", "u_mvp", "vec3 top", "0.25 + 0.75"):
+ assert template not in src, template # no placeholder look to "keep the structure" of
br = rt.build(ws, **SMALL)
assert br.ok, br.error_message
assert len(list((ws.artifacts / "frames").glob("*.png"))) == 5 and (ws.artifacts / "frames_sheet.png").is_file()
metrics = json.loads((ws.artifacts / "metrics.json").read_text())
- assert not metrics["stats"]["static"] and metrics["stats"]["mean_lum"] > 0.1
- src = (ws.src / "program.py").read_text()
+ assert not metrics["stats"]["static"] and not metrics["stats"]["flicker"] and metrics["stats"]["mean_lum"] > 0.1
(ws.src / "program.py").write_text(src.replace("fbo.use()\n ctx.disable", "fbo.use()\n raise ValueError('boom')\n ctx.disable"))
br = rt.build(ws, **SMALL)
assert not br.ok and br.error_type == "ValueError" and br.error_file == "src/program.py" and br.error_line
assert "boom" in br.error_message
+def test_opengl_contract_example_builds(tmp_ws, host):
+ """The ONE executable interface example in opengl_python/contract.md runs as src/program.py: lint
+ clean, five judged frames, not static — the only runnable prompt material the language ships now
+ that its cookbook is gone (D107)."""
+ text = load_text("opengl_python/contract.md")
+ blocks = [b for b in re.findall(r"```python\n(.*?)```", text, re.S) if "def setup(" in b and "import moderngl" in b]
+ assert len(blocks) == 1, "the contract ships exactly one complete example"
+ ws = _ws_with_plan(tmp_ws)
+ ws.src.mkdir(parents=True, exist_ok=True)
+ (ws.src / "program.py").write_text(blocks[0])
+ rt = OpenGLPythonRuntime(host=host)
+ assert rt.lint(ws).passed
+ br = rt.build(ws, **SMALL)
+ assert br.ok, br.error_message
+ metrics = json.loads((ws.artifacts / "metrics.json").read_text())
+ assert len(list((ws.artifacts / "frames").glob("*.png"))) == 5
+ assert not metrics["stats"]["static"] and not metrics["stats"]["flicker"] and not metrics["stats"]["any_nan"]
+
+
def test_gl_tools_probe_and_frames(tmp_ws, host, monkeypatch):
ws = _ws_with_plan(tmp_ws)
GlslShaderRuntime(host=host).skeleton(ws, PLAN)
@@ -150,7 +204,7 @@ def test_gl_tools_probe_and_frames(tmp_ws, host, monkeypatch):
obs = get_tool("gl_probe").call(ctx, {"t": 1.5})
assert obs.ok and "PROBE OK" in obs.text and len(obs.images) == 1 and obs.numbers["n_frames"] == 1
obs = get_tool("gl_frames").call(ctx, {"times": [0.0, 2.0], "width": 256, "height": 144})
- assert obs.ok and "FRAMES OK" in obs.text and obs.images and obs.numbers["n_frames"] == 2 and not obs.numbers["static"]
+ assert obs.ok and "FRAMES OK" in obs.text and obs.images and obs.numbers["n_frames"] == 2 and obs.numbers["static"] # the stub is flat by design
(ws.src / "shader.frag").write_text("#version 330 core\nvoid mainImage(out vec4 fragColor, in vec2 fragCoord) { fragColor = vec4(1.0); }\n")
obs = get_tool("gl_probe").call(ctx, {})
assert not obs.ok and "LINT FAILED" in obs.text and "#version" in obs.text
diff --git a/harness/tests/graphics/test_prompt_numbers.py b/harness/tests/graphics/test_prompt_numbers.py
new file mode 100644
index 00000000..9d255bf2
--- /dev/null
+++ b/harness/tests/graphics/test_prompt_numbers.py
@@ -0,0 +1,22 @@
+"""The judge numbers ``generate_graphics.j2`` states are the rubric's (the gate thresholds it states are
+pinned in ``prompts/_claims.toml``): change ``shader_v2.yaml`` and this fails until the prompt agrees."""
+
+from __future__ import annotations
+
+from codeverse3d.judges.rubrics import load_rubric
+from codeverse3d.prompts import load_text
+
+
+def test_generate_graphics_states_the_rubrics_own_numbers() -> None:
+ text = load_text("tracks/generate_graphics.j2")
+ rubric = load_rubric("shader_v2")
+ caps = {c.id: c.cap for c in rubric.caps}
+ penalties = {d.id: d.penalty for d in rubric.defects}
+ depth = next(c for c in rubric.criteria if c.id == "depth_and_detail")
+ assert f"`static`, cap {caps['static_frames']:g}" in text
+ assert f"`flicker`, cap {caps['flicker']:g}" in text
+ assert f"`stretched_aspect`, −{penalties['stretched_aspect']:.2f}" in text
+ assert f"`flat_fill` defect (−{penalties['flat_fill']:.2f})" in text
+ assert f"depth_and_detail ({depth.weight:.2f})" in text
+ # the anchor the prompt names is the one that describes "one field fills the frame"
+ assert "0.1 anchor" in text and "field" in depth.anchors["0.1"]
diff --git a/harness/tests/graphics/test_recipe_quality.py b/harness/tests/graphics/test_recipe_quality.py
deleted file mode 100644
index 6ccbbea5..00000000
--- a/harness/tests/graphics/test_recipe_quality.py
+++ /dev/null
@@ -1,93 +0,0 @@
-"""Executable numerical contracts for the recipes agents receive."""
-from __future__ import annotations
-
-import math
-import re
-
-import numpy as np
-import pytest
-from PIL import Image
-
-from codeverse3d.languages.glsl_shader import compose
-from codeverse3d.prompts import load_text
-from codeverse3d.spatial.gl_render import GlHost, GlHostError
-from codeverse3d.tracks.graphics import cookbook_functions, with_helpers
-
-pytest.importorskip("moderngl")
-
-
-def test_sdf_transport_and_surface_response_on_real_gl(tmp_path):
- known = cookbook_functions(load_text("glsl_shader/cookbook.md"))
- requested = ("sdStar", "sdSegment", "sun", "dropsLayer", "bokehSoft", "beerTransmittance", "phaseHG", "pbrDirect", "aurora")
- recipes = "\n\n".join(r.text for r in with_helpers([known[k] for k in requested], known))
- shader = """
-void mainImage(out vec4 fragColor,in vec2 fragCoord) {
- float failures=0.0;
- float segment=sdSegment(vec2(.3,.4),vec2(0),vec2(0));
- if(isnan(segment)||abs(segment-.5)>1e-5) failures+=1.0;
- float halfSector=3.14159265/5.0;
- if(sdStar(.6*vec2(cos(halfSector),sin(halfSector)),1.0,5.0)<=0.0) failures+=1.0;
- if(abs(sdStar(vec2(0),1.0,5.0)+.45)>1e-5) failures+=1.0;
- if(abs(sdStar(vec2(2,0),1.0,5.0)-1.0)>1e-5) failures+=1.0;
- float a=beerTransmittance(.7,2.0),b=beerTransmittance(.7,3.0);
- if(abs(a*b-beerTransmittance(.7,5.0))>1e-6) failures+=1.0;
- if(beerTransmittance(.7,0.0)!=1.0) failures+=1.0;
- float phaseIntegral=0.0;
- for(int i=0;i<2048;i++) phaseIntegral+=phaseHG(-1.0+2.0*(float(i)+.5)/2048.0,.8)*12.56637061/2048.0;
- if(abs(phaseIntegral-1.0)>.002) failures+=1.0;
- if(phaseHG(1.0,.8)<=phaseHG(-1.0,.8)) failures+=1.0;
- vec3 n=vec3(0,0,1),v=normalize(vec3(.3,0,1)),l=normalize(vec3(-.2,.4,1));
- vec3 forward=pbrDirect(vec3(.7,.4,.2),.4,.35,n,v,l,vec3(1))/dot(n,l);
- vec3 reverse=pbrDirect(vec3(.7,.4,.2),.4,.35,n,l,v,vec3(1))/dot(n,v);
- if(length(forward-reverse)>1e-5) failures+=1.0;
- if(length(pbrDirect(vec3(1),0.0,.3,n,v,-n,vec3(1)))>0.0) failures+=1.0;
- vec3 integrated=vec3(0);
- for(int i=0;i<2048;i++) {
- float z=(float(i)+.5)/2048.0,angle=float(i)*2.39996323;
- vec3 light=vec3(sqrt(1.0-z*z)*vec2(cos(angle),sin(angle)),z);
- integrated+=pbrDirect(vec3(1),0.0,.5,n,n,light,vec3(1))*6.28318531/2048.0;
- }
- if(any(greaterThan(integrated,vec3(1.01)))||any(lessThan(integrated,vec3(.8)))) failures+=1.0;
- vec2 uv=fragCoord/u_resolution;
- vec2 rain=dropsLayer(uv,u_time,8.0);
- vec3 bokeh=bokehSoft(uv,u_time);
- float disc=sun(uv,vec2(.5),.1);
- if(any(isnan(rain))||any(isnan(bokeh))||isnan(disc)) failures+=1.0;
- if(any(lessThan(rain,vec2(0)))||any(greaterThan(rain,vec2(1)))) failures+=1.0;
- // The color of each curtain uses its OWN output height. Evaluating color
- // before an out-parameter call silently borrowed the preceding layer's k.
- vec2 p=uv-vec2(.5,.15); float k=0.0; vec3 expectedAurora=vec3(0);
- float a0=curtain(p,u_time,0.0,k); expectedAurora+=auroraCol(k)*a0;
- float a1=curtain(p-vec2(.3,.12),u_time*.8,11.0,k); expectedAurora+=auroraCol(k)*a1*.55;
- float a2=curtain(p-vec2(-.5,.22),u_time*.6,23.0,k); expectedAurora+=auroraCol(k)*a2*.30;
- if(length(aurora(p,u_time)-expectedAurora)>1e-6) failures+=1.0;
- fragColor=vec4(min(failures,1.0),failures==0.0?1.0:0.0,failures/16.0,1.0);
-}
-"""
- try:
- result = GlHost(timeout_s=90).render_fragment_shader(
- compose(shader, recipes_src=recipes).source, tmp_path / "contracts",
- width=16, height=16, times=(0.0, 1.7))
- except GlHostError as exc:
- pytest.skip(f"OpenGL unavailable: {exc}")
- assert result.ok, result.error_message
- for frame in result.frames:
- assert frame.nan == frame.inf == 0
- pixels = np.asarray(Image.open(frame.path).convert("RGB"))
- assert np.all(pixels == [0, 255, 0]), pixels.max(axis=(0, 1)).tolist()
-
-
-def test_opengl_cookbook_sphere_winding_matches_its_outward_normals():
- text = load_text("opengl_python/cookbook.md")
- code = next(block for block in re.findall(r"```python\n(.*?)```", text, re.S)
- if "def sphere_mesh" in block)
- namespace = {"np": np, "math": math}
- exec(code, namespace)
- raw, indices = namespace["sphere_mesh"](12, 24, 2.0)
- vertices = raw.reshape(-1, 6)
- triangles = vertices[indices.reshape(-1, 3)]
- geometric = np.cross(triangles[:, 1, :3] - triangles[:, 0, :3],
- triangles[:, 2, :3] - triangles[:, 0, :3])
- nondegenerate = np.linalg.norm(geometric, axis=1) > 1e-6
- alignment = np.sum(geometric * triangles[:, :, 3:].mean(axis=1), axis=1)
- assert np.all(alignment[nondegenerate] > 0)
diff --git a/harness/tests/graphics/test_track.py b/harness/tests/graphics/test_track.py
index 26df0ca8..9fcf7d13 100644
--- a/harness/tests/graphics/test_track.py
+++ b/harness/tests/graphics/test_track.py
@@ -85,14 +85,14 @@ def test_a_replayed_round_reads_the_payload_the_in_run_judge_read(tmp_path, sett
from codeverse3d.record.record import load_record
ws = Workspace(tmp_path / "runs" / "replay")
- judge = FakeJudge(scores=(0.55, 0.72), targets=("RainDrops",))
+ judge = FakeJudge(scores=(0.55, 0.72), targets=("SurfaceRipples",))
track = GraphicsTrack(services=_services(), judge=judge, agent=FakeAgent(_writer),
planner_model=FakeChatModel(lambda req: plan_example()), settings=settings, runtime=FakeGlRuntime())
rec = track.run(make_spec(max_rounds=1), ws)
replay = build_judge_input(ws, load_record(ws), rec.rounds[-1])
for field in ("plan_summary", "extra_context", "acceptance", "round_index"):
assert getattr(replay, field) == getattr(judge.calls[-1], field), field
- assert "Passes: CityBokeh (fullscreen)" in replay.plan_summary and "Motion: drops slide down" in replay.plan_summary
+ assert "Passes: PoolFloor (fullscreen)" in replay.plan_summary and "Motion: new drops land" in replay.plan_summary
def test_planner_reask_and_acceptance(tmp_ws):
@@ -107,7 +107,7 @@ def test_planner_reask_and_acceptance(tmp_ws):
model = FakeChatModel(responder)
plan = _plan(spec, tmp_ws, model)
- assert attempts["n"] == 2 and plan.title == "Neon rain on a window" and tmp_ws.plan_path.is_file()
+ assert attempts["n"] == 2 and plan.title == "Tide pool ripples" and tmp_ws.plan_path.is_file()
assert "Fix EXACTLY these problems" in model.requests[1].messages[-1].text
ids = [a.id for a in plan.acceptance]
assert "must1" in ids and "a3" in ids # spec must_have appended, motion item already present in the example
@@ -118,5 +118,5 @@ def test_planner_reask_and_acceptance(tmp_ws):
with pytest.raises(PlanningError):
_plan(spec, tmp_ws, always_bad)
sys_prompt = planner.build_system_prompt(spec, GraphicsPlan)
- assert "ART-DIRECTOR" in sys_prompt and "NeonRainWindow" in sys_prompt
+ assert "ART-DIRECTOR" in sys_prompt and "TidePoolRipples" in sys_prompt
assert model.requests[0].temperature == 0.5 and model.requests[0].max_output_tokens == planner.PLAN_TOKENS_MAX
diff --git a/harness/tests/graphics/test_wrap_lint.py b/harness/tests/graphics/test_wrap_lint.py
index a4e6cbc9..b49b8731 100644
--- a/harness/tests/graphics/test_wrap_lint.py
+++ b/harness/tests/graphics/test_wrap_lint.py
@@ -8,7 +8,6 @@ from codeverse3d.contracts.artifacts import Severity
from codeverse3d.languages.glsl_shader import (
HEADER,
compose,
- defined_functions,
detect_convention,
first_error,
lint_text,
@@ -93,7 +92,6 @@ def test_mixed_comments_blank_only_the_comments():
stripped = strip_comments(src)
assert stripped.count("\n") == src.count("\n") and "uniform float u_extra;" in stripped
assert "tweak" not in stripped and "inside" not in stripped
- assert defined_functions(src) == {"fogAmt": 2, "x": 5}
shader = src + SHADER
assert any(f.data["kind"] == "custom_uniform" for f in lint_text(shader))
@@ -138,3 +136,21 @@ def test_program_lint_workspace(tmp_ws):
(tmp_ws.src / "helpers.py").write_text("x = 1\n")
rep = lint_program_ws(tmp_ws)
assert rep.passed and any(f.data["kind"] == "stray_file" for f in rep.findings)
+
+
+def test_a_pre_d107_runs_seeded_recipes_file_still_composes_and_is_not_a_stray_file(tmp_path):
+ """Runs made before D107 call functions the harness seeded into ``src/recipes.glsl``: the build
+ still composes that file (between the header and common.glsl, with its own line map) so
+ ``resume`` / ``render`` / ``pick`` on such a run builds, and the lint does not call it stray."""
+ from codeverse3d.languages.glsl_shader import LEGACY_RECIPES, GlslShaderRuntime
+ from codeverse3d.workspace import Workspace
+
+ ws = Workspace(tmp_path / "old_run").create()
+ (ws.root / "src/shader.frag").write_text("void mainImage(out vec4 c, in vec2 f) { c = vec4(legacyGlow()); }\n")
+ (ws.root / LEGACY_RECIPES).write_text("float legacyGlow() { return 0.5; }\n")
+ image, buffer_a = GlslShaderRuntime().compose_sources(ws)
+ assert buffer_a is None
+ assert image.source.index("float legacyGlow") < image.source.index("void mainImage")
+ assert LEGACY_RECIPES in {seg.file for seg in image.line_map.segments}
+ assert not [f for f in lint_workspace(ws).findings if (f.data or {}).get("kind") == "stray_file"]
+ assert LEGACY_RECIPES not in compose(SHADER, COMMON).source
diff --git a/harness/tests/orchestrator_tracks/fakes.py b/harness/tests/orchestrator_tracks/fakes.py
index 3244c2a8..16aa420e 100644
--- a/harness/tests/orchestrator_tracks/fakes.py
+++ b/harness/tests/orchestrator_tracks/fakes.py
@@ -445,7 +445,7 @@ class FakeServices(Services):
fix_hint=f"shrink {j.child} by 17 mm along the axis") for j in list(getattr(plan, "joints", []))[: self.sweep_errors]]
return GateReport(gate="joint_sweep", passed=not findings, findings=findings), views
- def materialize(self, ws: Workspace, *, agent_kind: str, contract_md: str, cookbook_text: str, spatial_tools: bool) -> None:
+ def materialize(self, ws: Workspace, *, agent_kind: str, contract_md: str, spatial_tools: bool) -> None:
(ws.root / "AGENTS.md").write_text(contract_md)
self.materialized.append(agent_kind)
diff --git a/harness/tests/orchestrator_tracks/test_cookbook_excerpt.py b/harness/tests/orchestrator_tracks/test_cookbook_excerpt.py
deleted file mode 100644
index 01e664e8..00000000
--- a/harness/tests/orchestrator_tracks/test_cookbook_excerpt.py
+++ /dev/null
@@ -1,18 +0,0 @@
-"""The GLSL cookbook's aurora example ships where the cookbook says it is (Q9)."""
-
-from __future__ import annotations
-
-from codeverse3d.prompts import PROMPTS_DIR, load_text
-
-EXAMPLE = PROMPTS_DIR / "glsl_shader" / "examples" / "aurora_ridge.frag"
-
-
-def test_aurora_example_ships_and_composes() -> None:
- from codeverse3d.languages.glsl_shader import compose
-
- assert EXAMPLE.is_file(), EXAMPLE
- src = EXAMPLE.read_text()
- assert "void mainImage(" in src and "float curtain(" in src
- composed = compose(src)
- assert "mainImage" in composed.source and "u_time" in composed.source
- assert "examples/aurora_ridge.frag" in load_text("glsl_shader/cookbook.md")
diff --git a/harness/tests/orchestrator_tracks/test_generation_planner_repair.py b/harness/tests/orchestrator_tracks/test_generation_planner_repair.py
index ffd71a17..d2677da3 100644
--- a/harness/tests/orchestrator_tracks/test_generation_planner_repair.py
+++ b/harness/tests/orchestrator_tracks/test_generation_planner_repair.py
@@ -125,7 +125,7 @@ def test_planner_validates_retries_and_writes(tmp_ws):
budget = BudgetGuard(spec.budget)
with run_ledger(tmp_ws.root):
p = plan(spec, "fake:planner", StaticPlan, tmp_ws, model=model, events=events, budget=budget)
- assert isinstance(p, StaticPlan) and p.object_name == "DiningChair" and tmp_ws.plan_path.is_file()
+ assert isinstance(p, StaticPlan) and p.object_name == _valid_plan_dict()["object_name"] and tmp_ws.plan_path.is_file()
assert len(model.requests) == 2 and "failed validation" in model.requests[1].messages[-1].text
assert model.requests[0].response_schema is not None and "PascalCase" in model.requests[0].system
from codeverse3d.tracks.planner import PLAN_MAX_WAIT_S, plan_wait_s
@@ -164,12 +164,12 @@ def test_ensure_acceptance_is_idempotent_and_only_the_scene_spec_must_haves_gate
# ----------------------------------------------------------------------------- repair
-def _ctx(tmp_ws, settings, agent_id: str, agent=None, model=None, cookbook: str = "") -> RunContext:
+def _ctx(tmp_ws, settings, agent_id: str, agent=None, model=None) -> RunContext:
spec = make_spec(generator=agent_id)
rt = FakeRuntime(Language.THREEJS)
return RunContext(spec=spec, ws=tmp_ws, events=EventLog(tmp_ws.events_path), settings=settings, budget=BudgetGuard(spec.budget),
runtime=rt, services=FakeServices(), state=RunState(), policy=RoundPolicy(), track=Track.STATIC_OBJECT,
- rubric="r", agent_id=agent_id, agent=agent, model=model, cookbook_text=cookbook,
+ rubric="r", agent_id=agent_id, agent=agent, model=model,
contract_text="CONTRACT")
diff --git a/harness/tests/orchestrator_tracks/test_graphics_recipes.py b/harness/tests/orchestrator_tracks/test_graphics_recipes.py
deleted file mode 100644
index 97b420ad..00000000
--- a/harness/tests/orchestrator_tracks/test_graphics_recipes.py
+++ /dev/null
@@ -1,228 +0,0 @@
-"""Harness-owned GLSL recipe extraction, seeding, composition, and linting."""
-
-from __future__ import annotations
-
-import re
-from pathlib import Path
-from types import SimpleNamespace
-
-import pytest
-
-from codeverse3d.contracts.common import Language, Track
-from codeverse3d.contracts.plan import GraphicsPlan
-from codeverse3d.languages import get_runtime
-from codeverse3d.languages.glsl_shader import (
- COMMON_GLSL,
- GlslShaderRuntime,
- compose,
- lint_text,
- lint_workspace,
- write_skeleton,
-)
-from codeverse3d.languages.glsl_shader import HEADER as WRAP_HEADER
-from codeverse3d.proc import EventLog
-from codeverse3d.prompts import load_text
-from codeverse3d.tracks.graphics import (
- HEADER,
- RECIPES_REL,
- RESUME_HEADER,
- cookbook_functions,
- defined_names,
- is_skeleton_common,
- seed_recipes,
- seeded_on_disk,
-)
-from codeverse3d.workspace import Workspace
-
-AURORA = "Aurora borealis over a mountain ridge with a frozen lake, dense stars, green and violet curtains"
-AURORA_NAMES = ("curtain", "auroraCol", "aurora", "stars")
-HELPERS = ("hash12", "hash22", "noise", "fbm")
-_DEF = re.compile(r"^[ \t]*(?:float|vec[234]|mat[234]|int|bool|void)\s+(\w+)\s*\(", re.M)
-SHADER = ("void mainImage(out vec4 fragColor, in vec2 fragCoord) {\n"
- " vec2 p = (fragCoord - 0.5 * u_resolution) / u_resolution.y; float t = u_time;\n"
- " vec3 col = vec3(0.0, 0.0, 0.012) + vec3(0.9) * stars(p, 160.0, 0.22);\n"
- " vec3 au = aurora(p, t); col += au * 1.7 + au * au * 0.5;\n"
- " fragColor = vec4(pow(col / (1.0 + 0.6 * col), vec3(0.4545)), 1.0);\n}\n")
-
-
-def _ws(tmp_path: Path, *, skeleton: bool = True) -> Workspace:
- ws = Workspace(tmp_path / "ws").create()
- if skeleton:
- write_skeleton(ws, None)
- return ws
-
-
-def _ctx(ws: Workspace, brief: str = AURORA, *, plan: GraphicsPlan | None = None, language: Language = Language.GLSL_SHADER):
- return SimpleNamespace(cookbook_text=load_text("glsl_shader/cookbook.md"), plan=plan,
- spec=SimpleNamespace(prompt=brief, constraints=SimpleNamespace(dimensions_m={}, max_triangles=None, style="",
- must_have=[], must_not=[]), references=[]),
- language=language, track=Track.GRAPHICS, ws=ws, extra={}, events=EventLog(ws.events_path),
- contract_text="", tool_cards="", single_shot=False, runtime=get_runtime(language))
-
-
-def _defs(text: str) -> list[str]:
- return _DEF.findall(text)
-
-
-def _recipes(ws: Workspace) -> Path:
- return ws.root / RECIPES_REL
-
-
-def _seeded_events(ws: Workspace) -> list[dict]:
- return [e for e in EventLog(ws.events_path).read() if e["event"] == "recipes.seeded"]
-
-
[email protected](autouse=True)
-def _default_on(monkeypatch) -> None:
- monkeypatch.delenv("C3D_SEED_RECIPES", raising=False)
-
-
-def test_aurora_brief_seeds_recipes_and_helpers_exactly_once(tmp_path) -> None:
- ws = _ws(tmp_path, skeleton=False)
- ctx = _ctx(ws)
- names = seed_recipes(ctx)
- for n in AURORA_NAMES + HELPERS:
- assert n in names, (n, names)
- assert "hash11" not in names and "hash33" not in names # only the helpers the recipes call
- assert names.index("fbm") < names.index("curtain") and names.index("noise") < names.index("fbm")
- assert names.index("hash12") < names.index("stars") and names.index("curtain") < names.index("aurora")
- text = _recipes(ws).read_text()
- assert text.startswith(HEADER)
- defs = _defs(text)
- assert len(defs) == len(set(defs)) and set(defs) == set(names)
- assert "mainImage" not in text and "// usage:" not in text
- for n in names:
- assert re.search(rf"^// \S.*\b{n}\(.*\) — .+$", text, re.M), n # one index line per recipe
- assert "never a comb of bars" in text
- assert not (ws.src / "common.glsl").exists(), "common.glsl is the agent's; the seed never creates it"
- # the run record carries it
- ev = _seeded_events(ws)
- assert len(ev) == 1 and ev[0]["names"] == names and ev[0]["present"] == names
- assert ev[0]["file"] == RECIPES_REL and ev[0]["trimmed"] == []
- assert any(t.startswith("Light phenomena") for t in ev[0]["chapters"])
- assert [e["name"] for e in ctx.extra["seeded_recipes"]] == names
- cur = next(e for e in ctx.extra["seeded_recipes"] if e["name"] == "curtain")
- assert cur["signature"].startswith("float curtain(") and "aurora" in cur["purpose"]
-
-
-def test_recipes_are_self_contained_and_the_skeleton_common_is_trimmed(tmp_path) -> None:
- ws = _ws(tmp_path)
- assert is_skeleton_common((ws.src / "common.glsl").read_text())
- names = seed_recipes(_ctx(ws))
- assert set(names) >= set(AURORA_NAMES) | set(HELPERS)
- recipes = _recipes(ws).read_text()
- common = (ws.src / "common.glsl").read_text()
- assert not set(_defs(common)) & set(_defs(recipes)), "no name is defined twice across the two files"
- assert set(_defs(common)) == {"hash11", "rot2", "palette", "tonemap"} and "#define PI" in common and "#define TAU" in common
- assert common.splitlines()[0] == COMMON_GLSL.splitlines()[0] and "provided by src/recipes.glsl" in common.splitlines()[1]
- assert "\n\n\n" not in common and is_skeleton_common(common)
- assert _seeded_events(ws)[0]["trimmed"] == ["hash12", "hash22", "noise", "fbm"]
- # the harness's own skeleton shader still builds on top: lint clean, one definition per name
- rep = lint_workspace(ws)
- assert rep.passed and not any(f.data["kind"] in ("redefines_recipe", "stray_file") for f in rep.findings), [f.message for f in rep.findings]
- image, _ = GlslShaderRuntime().compose_sources(ws)
- defs = _defs(image.source)
- assert len(defs) == len(set(defs)), sorted(d for d in defs if defs.count(d) > 1)
- # seeding again changes nothing: no new names, no second trim
- assert seed_recipes(_ctx(ws)) == [] and (ws.src / "common.glsl").read_text() == common and _recipes(ws).read_text() == recipes
- assert [r.name for r in seeded_on_disk(recipes, cookbook_functions(load_text("glsl_shader/cookbook.md")))] == names
-
-
-def test_an_agent_written_common_is_never_touched(tmp_path) -> None:
- ws = _ws(tmp_path)
- mine = "// my helpers\nfloat hash12(vec2 p) { return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); }\nfloat mine(float x) { return x * 2.0; }\n"
- (ws.src / "common.glsl").write_text(mine)
- assert not is_skeleton_common(mine)
- names = seed_recipes(_ctx(ws))
- assert "hash12" in names and (ws.src / "common.glsl").read_text() == mine
- assert _seeded_events(ws)[0]["trimmed"] == []
- rep = lint_workspace(ws)
- dup = [f for f in rep.findings if f.data["kind"] == "redefines_recipe"]
- assert not rep.passed and [(f.data["file"], f.data["line"]) for f in dup] == [("src/common.glsl", 2)]
- assert "`hash12` is already provided by src/recipes.glsl — call it instead of redefining it" in dup[0].message
-
-
-def test_resume_appends_only_new_names(tmp_path) -> None:
- ws = _ws(tmp_path)
- first = seed_recipes(_ctx(ws))
- recipes = _recipes(ws)
- seeded = recipes.read_text()
- # the agent did what it does: rewrote common.glsl AND shader.frag wholesale, its own helpers, its own stars()
- agent_common = "float mine(float x) { return x * 2.0; }\nfloat starsMine(vec2 p) { return 0.0; }\n"
- (ws.src / "common.glsl").write_text(agent_common)
- (ws.src / "shader.frag").write_text(SHADER)
- ctx = _ctx(ws)
- assert seed_recipes(ctx) == [] # every name is already in recipes.glsl
- assert recipes.read_text() == seeded and (ws.src / "common.glsl").read_text() == agent_common
- # a recipes.glsl missing stars() and aurora() (an older seed): a resume appends exactly those two, at the end
- trimmed = re.sub(r"(?:^//[^\n]*\n)*float stars\(vec2 p, float density, float keep\) \{.*?\n\}\n", "", seeded, count=1, flags=re.S | re.M)
- trimmed = re.sub(r"(?:^//[^\n]*\n)*vec3 aurora\(vec2 p, float t\) \{.*?\n\}\n", "", trimmed, count=1, flags=re.S | re.M)
- assert "stars" not in defined_names(trimmed) and "aurora" not in defined_names(trimmed)
- recipes.write_text(trimmed)
- third = seed_recipes(ctx)
- assert third == ["stars", "aurora"]
- text = recipes.read_text()
- assert text.startswith(trimmed) and text.count(HEADER) == 1 and text.count(RESUME_HEADER) == 1
- assert text.index(RESUME_HEADER) < text.index("\nfloat stars(") < text.index("\nvec3 aurora(") # definitions, not index lines
- defs = _defs(text)
- assert len(defs) == len(set(defs)) and set(first) == set(defs)
- assert (ws.src / "common.glsl").read_text() == agent_common # still never touched
- assert [e["name"] for e in ctx.extra["seeded_recipes"]] == [n for n in first if n not in ("stars", "aurora")] + ["stars", "aurora"]
- assert _seeded_events(ws)[-1]["names"] == third and _seeded_events(ws)[-1]["trimmed"] == []
-
-
-# ----------------------------------------------------------------------------- compose / lint / prompt
-def _gl_or_skip(tmp_path: Path, src: str, **kw):
- pytest.importorskip("moderngl")
- from codeverse3d.spatial.gl_render import GlHost, GlHostError
-
- try:
- res = GlHost(timeout_s=120).render_fragment_shader(src, tmp_path / "out", **kw)
- except GlHostError as e: # pragma: no cover - machine without GL
- pytest.skip(f"no OpenGL context: {e}")
- if not res.ok and res.stage == "context": # pragma: no cover
- pytest.skip(f"no OpenGL context: {res.error_message}")
- return res
-
-
-def test_recipes_compose_above_common_and_the_seeded_aurora_renders(tmp_path) -> None:
- ws = _ws(tmp_path)
- seed_recipes(_ctx(ws))
- (ws.src / "shader.frag").write_text(SHADER)
- common = (ws.src / "common.glsl").read_text()
- recipes = _recipes(ws).read_text()
- assert lint_text(SHADER, common, recipes_src=recipes) == [] and lint_workspace(ws).passed
- comp = compose(SHADER, common, recipes_src=recipes)
- assert comp.convention == "mainImage" and not comp.uses_feedback
- src = comp.source
- assert (src.index("#version 330 core") < src.index(HEADER) < src.index("float curtain(") < src.index("vec3 aurora(")
- < src.index(common.splitlines()[0]) < src.index("void mainImage("))
- assert [s.file for s in comp.line_map.segments] == ["harness", "src/recipes.glsl", "src/common.glsl", "src/shader.frag", "harness"]
- header_lines = WRAP_HEADER.count("\n")
- assert comp.line_map.locate(header_lines + 1) == ("src/recipes.glsl", 1)
- assert comp.line_map.locate(header_lines + recipes.count("\n") + 1) == ("src/common.glsl", 1)
- # the runtime composes the same way (image and buffer_a alike)
- (ws.src / "buffer_a.frag").write_text(SHADER)
- image, buffer_a = GlslShaderRuntime().compose_sources(ws)
- assert image.source == src and buffer_a is not None
- assert [s.file for s in buffer_a.line_map.segments][:3] == ["harness", "src/recipes.glsl", "src/common.glsl"]
- # a real compile when a GL context exists: the seeded aurora lights the frame (skipped otherwise)
- res = _gl_or_skip(tmp_path, src, width=96, height=54, times=(0.0, 2.5))
- assert res.ok, res.error_message
- assert len(res.frames) == 2 and all(Path(f.path).is_file() for f in res.frames)
- np = pytest.importorskip("numpy")
- Image = pytest.importorskip("PIL.Image")
- lum = [float(np.asarray(Image.open(f.path).convert("L"), dtype=float).mean() / 255.0) for f in res.frames]
- assert all(v > 0.0 for v in lum), lum
-
-
-def test_a_single_shot_repair_never_inlines_the_harness_owned_recipes(tmp_path) -> None:
- from codeverse3d.contracts.artifacts import BuildResult, GateReport
- from codeverse3d.tracks.repair import files_for_repair
-
- ws = _ws(tmp_path, skeleton=False)
- _recipes(ws).write_text("float hash12(vec2 p) { return 0.0; }\n")
- (ws.src / "shader.frag").write_text(SHADER)
- ctx = SimpleNamespace(ws=ws, language=Language.GLSL_SHADER, runtime=SimpleNamespace())
- build = BuildResult(ok=False, language="glsl_shader", error_file=str(_recipes(ws)))
- assert list(files_for_repair(ctx, build, GateReport(gate="lint", passed=True), ["src/shader.frag"])) == ["src/shader.frag"]
diff --git a/harness/tests/orchestrator_tracks/test_harness_failure_no_repair.py b/harness/tests/orchestrator_tracks/test_harness_failure_no_repair.py
index 5c431f6e..41ffb3d8 100644
--- a/harness/tests/orchestrator_tracks/test_harness_failure_no_repair.py
+++ b/harness/tests/orchestrator_tracks/test_harness_failure_no_repair.py
@@ -20,7 +20,6 @@ def _ctx(**over):
spec=SimpleNamespace(budget=SimpleNamespace(max_repair_attempts=3)),
events=SimpleNamespace(emit=lambda *a, **k: None),
ws=None, agent_id="x", agent=None, model=None, settings=None, budget=None,
- cookbook_text="",
)
base.__dict__.update(over)
return base
diff --git a/harness/tests/orchestrator_tracks/test_planner_depth.py b/harness/tests/orchestrator_tracks/test_planner_depth.py
index 99fd8bab..f453ff0a 100644
--- a/harness/tests/orchestrator_tracks/test_planner_depth.py
+++ b/harness/tests/orchestrator_tracks/test_planner_depth.py
@@ -108,8 +108,14 @@ def test_plan_budget_contracts():
assert b.target_parts == 7 and b.min_assemblies == 3 and "sub-assemblies" in b.reason
b = B.plan_budget(_spec(must=6, track=Track.GRAPHICS, language=Language.GLSL_SHADER))
- assert b.cap_parts == B.GRAPHICS_CAP and b.target_parts == 5 and b.evidence
- assert "passes" in B.budget_block(b, unit="passes") and "`elements`" in B.budget_block(b, unit="passes")
+ assert b.cap_parts == B.GRAPHICS_CAP and b.target_parts == 3 and b.evidence and b.min_assemblies == 0
+ block = B.budget_block(b, unit="passes")
+ assert "passes" in block and "`elements`" not in block and "at least 2" in block
+ # no checklist: one pass is a plan, and the block states a ceiling and nothing that sets a count
+ b = B.plan_budget(_spec(must=0, track=Track.GRAPHICS, language=Language.GLSL_SHADER))
+ assert b.min_parts == 1 and not b.evidence
+ assert "at least" not in B.budget_block(b, unit="passes")
+ assert "at least" not in B.budget_block(B.plan_budget(_spec(must=2)))
text = build_user_prompt(_spec(must=10), budget=B.plan_budget(_spec(must=10)))
assert "PLAN BUDGET" in text and "10 checklist items" in text
@@ -119,7 +125,7 @@ def test_plan_budget_contracts():
def test_plan_quality_gate_contracts():
budget = B.plan_budget(_spec(must=12))
complaint = B.plan_quality_complaint(_plan([_part(f"P{i}", desc=_detailed(i)) for i in range(4)]), budget)
- assert "Only 4 parts" in complaint and "about 12" in complaint
+ assert "Only 4 parts" in complaint and "at least 10" in complaint
budget = B.plan_budget(_spec(must=8))
complaint = B.plan_quality_complaint(_plan([_part(f"P{i}") for i in range(8)]), budget)
@@ -134,6 +140,9 @@ def test_plan_quality_gate_contracts():
both = B.plan_quality_complaint(_plan(thin), budget)
assert "boxes at different sizes" in both and "same material" in both
+ # without evidence (a short checklist, no brief) a plan of plain parts is never re-asked
+ assert B.plan_quality_complaint(_plan([_part(f"P{i}") for i in range(4)]), B.plan_budget(_spec(must=2))) == ""
+
kids = [SubPartPlan(name="K", description="knurled collar", bbox=_bbox(ex=0.2, ey=0.2, ez=0.2))]
parts = [_part(f"P{i}", material=f"m{i}", children=kids) for i in range(8)]
assert B.plan_quality_complaint(_plan(parts), budget) == ""
diff --git a/harness/tests/orchestrator_tracks/test_planner_reask.py b/harness/tests/orchestrator_tracks/test_planner_reask.py
index 9cb58c12..3a126033 100644
--- a/harness/tests/orchestrator_tracks/test_planner_reask.py
+++ b/harness/tests/orchestrator_tracks/test_planner_reask.py
@@ -56,7 +56,7 @@ def test_the_validation_reask_names_a_thin_plans_missing_parts_and_a_schema_echo
echo["joints"][0]["axis"] = [0, 0, 0]
answers = [thin, _good(), echo, _good()]
model = FakeChatModel(lambda req: answers.pop(0))
- for n, needles, absent in ((2, ("failed validation", "lists only 1 part(s)", "needs about"), None),
+ for n, needles, absent in ((2, ("failed validation", "lists only 1 part(s)", "needs at least"), None),
(4, ("echoes the schema", "joints[0].name"), "zero axis")):
p = plan(_spec(), "fake:planner", ArticulatedPlan, tmp_ws, model=model)
assert isinstance(p, ArticulatedPlan) and len(model.requests) == n
diff --git a/harness/tests/orchestrator_tracks/test_planner_truncation_reask.py b/harness/tests/orchestrator_tracks/test_planner_truncation_reask.py
index de87e8e3..50a06413 100644
--- a/harness/tests/orchestrator_tracks/test_planner_truncation_reask.py
+++ b/harness/tests/orchestrator_tracks/test_planner_truncation_reask.py
@@ -22,7 +22,7 @@ def test_truncation_retries_compact_with_low_thinking(tmp_ws):
model = FakeChatModel(respond)
events = EventLog(tmp_ws.events_path)
p = plan(make_spec(), "fake:planner", StaticPlan, tmp_ws, model=model, events=events)
- assert p.object_name == "DiningChair" and len(model.requests) == 2
+ assert p.object_name == _valid_plan_dict()["object_name"] and len(model.requests) == 2
first, second = model.requests
assert first.thinking == "medium" and second.thinking == "off"
assert second.max_output_tokens > first.max_output_tokens
diff --git a/harness/tests/orchestrator_tracks/test_write_scope.py b/harness/tests/orchestrator_tracks/test_write_scope.py
index 7a53eb25..9f980dd1 100644
--- a/harness/tests/orchestrator_tracks/test_write_scope.py
+++ b/harness/tests/orchestrator_tracks/test_write_scope.py
@@ -27,22 +27,22 @@ from .fakes import FakeAgent, FakeRuntime, FakeServices
def test_write_files_normalises_a_path_before_the_owned_and_scope_checks(tmp_ws: Workspace):
- """B1: `src//lib/x.js`, `src/./lib/x.js` and `src//recipes.glsl` ARE the harness-owned files —
+ """B1: `src//lib/x.js`, `src/./lib/x.js` and `src//owned.glsl` ARE the harness-owned files —
un-normalised they slipped past `is_harness_owned` and the edit_only scope and were written."""
(tmp_ws.src / "lib").mkdir(parents=True, exist_ok=True)
(tmp_ws.src / "lib" / "x.js").write_text("// owned\n")
- (tmp_ws.src / "recipes.glsl").write_text("// owned\n")
+ (tmp_ws.src / "owned.glsl").write_text("// owned\n")
(tmp_ws.src / "zones").mkdir(parents=True, exist_ok=True)
(tmp_ws.src / "zones" / "q.js").write_text("// old q\n")
skipped: list[str] = []
- files = {"src//lib/x.js": "// pwned", "src/./lib/x.js": "// pwned", "src//recipes.glsl": "// pwned",
+ files = {"src//lib/x.js": "// pwned", "src/./lib/x.js": "// pwned", "src//owned.glsl": "// pwned",
"src//zones/q.js": "// out of scope", "src/./parts/a.js": "// mine"}
- changes = write_files(tmp_ws, files, only={"src/parts/a.js"}, frozen=("src/lib/", "src/recipes.glsl"),
+ changes = write_files(tmp_ws, files, only={"src/parts/a.js"}, frozen=("src/lib/", "src/owned.glsl"),
on_skip=lambda p, r: skipped.append(p))
assert [c.path for c in changes] == ["src/parts/a.js"]
assert sorted(skipped) == sorted(set(files) - {"src/./parts/a.js"})
assert (tmp_ws.src / "lib" / "x.js").read_text() == "// owned\n"
- assert (tmp_ws.src / "recipes.glsl").read_text() == "// owned\n"
+ assert (tmp_ws.src / "owned.glsl").read_text() == "// owned\n"
assert (tmp_ws.src / "zones" / "q.js").read_text() == "// old q\n"
diff --git a/harness/tests/orchestrator_tracks/test_zone_starvation.py b/harness/tests/orchestrator_tracks/test_zone_starvation.py
new file mode 100644
index 00000000..3ca0ea34
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_zone_starvation.py
@@ -0,0 +1,126 @@
+"""2026-10-15, iteration 2 of the argon loop: two Blender scenes shipped three EMPTY zones (0.18).
+
+A runaway single-shot asset call held the asset stage for ~47 minutes; the zone stage then started
+0.4 min before the scene track's soft cap and its agent session was clipped to the 180 s floor; it
+read files until it was killed and wrote no zone; ``zones.done`` listed them failed and nothing acted;
+refine spent its window on asset files. Three fixes, pinned here:
+
+* a single-shot call is bounded by its task's own window (never below ``SINGLE_SHOT_MIN_WAIT_S``);
+* the zone window comes from the HARD budget minus round 0's reserve, not the soft cap;
+* every zone the session left unwritten gets one single-shot recovery before assembly.
+"""
+
+from __future__ import annotations
+
+from dataclasses import replace
+from typing import Any
+
+from codeverse3d.contracts.agent import FileChange
+from codeverse3d.contracts.common import Language, Track
+from codeverse3d.contracts.plan import ScenePlan
+from codeverse3d.models.retry import RETRY_DEADLINE_S
+from codeverse3d.orchestrator import RunState
+from codeverse3d.proc import EventLog
+from codeverse3d.tracks import scene as scene_mod
+from codeverse3d.tracks.generation import (
+ SINGLE_SHOT_MIN_WAIT_S,
+ SINGLE_SHOT_PREFIX,
+ GenerationResult,
+ single_shot_wait_s,
+)
+from codeverse3d.tracks.planner import plan_example
+from codeverse3d.tracks.scene import (
+ ROUND0_RESERVE_S,
+ ZONE_MIN_S,
+ ZONE_TIMEOUT_S,
+ SceneTrack,
+ zone_window_s,
+)
+from codeverse3d.workspace import Workspace
+from tests.orchestrator_tracks.conftest import make_spec
+from tests.orchestrator_tracks.fakes import FakeRuntime, FakeServices
+
+
+def test_a_single_shot_call_waits_for_its_tasks_window_never_below_the_floor_never_past_the_ceiling():
+ assert single_shot_wait_s(None, RETRY_DEADLINE_S) == RETRY_DEADLINE_S # object tracks: unchanged
+ assert single_shot_wait_s(420, RETRY_DEADLINE_S) == 420.0 # an asset task: the runaway is cut
+ assert single_shot_wait_s(120, RETRY_DEADLINE_S) == SINGLE_SHOT_MIN_WAIT_S # a degraded stage's budget floor
+ assert single_shot_wait_s(900, RETRY_DEADLINE_S) == 900.0 # a refine window
+ assert single_shot_wait_s(RETRY_DEADLINE_S * 3, RETRY_DEADLINE_S) == RETRY_DEADLINE_S
+
+
+def _ctx(tmp_path, settings, *, max_minutes: float = 90.0):
+ base = ScenePlan.model_validate(plan_example(Track.SCENE))
+ ws = Workspace(tmp_path / "runs" / "s").create()
+ track = SceneTrack(services=FakeServices(), settings=settings, runtime=FakeRuntime(Language.SCENE_THREEJS))
+ ctx = track.build_context(make_spec(Track.SCENE, Language.SCENE_THREEJS, max_minutes=max_minutes), ws,
+ EventLog(ws.events_path), RunState())
+ ctx.plan = base
+ return track, ctx
+
+
+def test_the_zone_window_comes_from_the_hard_budget_minus_round_zeros_reserve(tmp_path, settings, monkeypatch):
+ _, ctx = _ctx(tmp_path, settings)
+ soft_cap = ctx.budget.soft_minutes()
+ # the iteration-2 case: 0.4 min before the soft cap — the old window was the 180 s floor
+ monkeypatch.setattr(ctx.budget, "elapsed_minutes", lambda: soft_cap - 0.4)
+ assert zone_window_s(ctx, 3) == ZONE_TIMEOUT_S * 3, "41 minutes of hard budget left: the full window"
+ # near the hard ceiling the window shrinks to what round 0 leaves, never below the floor
+ monkeypatch.setattr(ctx.budget, "elapsed_minutes", lambda: ctx.budget.hard_minutes - 15.0)
+ assert zone_window_s(ctx, 3) == int(15.0 * 60.0 - ROUND0_RESERVE_S)
+ monkeypatch.setattr(ctx.budget, "elapsed_minutes", lambda: ctx.budget.hard_minutes - 1.0)
+ assert zone_window_s(ctx, 3) == ZONE_MIN_S
+
+
+def test_zones_the_session_left_unwritten_are_recovered_single_shot_each(tmp_path, settings, monkeypatch):
+ track, ctx = _ctx(tmp_path, settings)
+ plan: ScenePlan = ctx.plan # type: ignore[assignment]
+ ctx.runtime.skeleton(ctx.ws, plan)
+ names = [z.name for z in plan.zones]
+ first, rest = names[0], names[1:]
+ calls: list[tuple[str, bool, float | None]] = []
+
+ def fake_generate_for(gen: Any, task: Any) -> GenerationResult:
+ calls.append((task.label, bool(gen.single_shot), task.timeout_s))
+ if task.label.endswith(".recover"):
+ rel = task.files_hint[0]
+ (ctx.ws.root / rel).write_text("export function build(ctx) { return new ctx.THREE.Group(); }\n")
+ return GenerationResult(ok=True, files_changed=[FileChange(path=rel, status="modified")], label=task.label)
+ # the batched session: it wrote the FIRST zone only, then its window ran out
+ rel = ctx.runtime.zone_file(first)
+ (ctx.ws.root / rel).write_text("export function build(ctx) { return new ctx.THREE.Group(); }\n")
+ return GenerationResult(ok=True, files_changed=[FileChange(path=rel, status="modified")], label=task.label,
+ notes="timeout")
+
+ # a real run's planner is an API model, so its single-shot context exists; the fake services
+ # expose no chat model (single_shot_ctx would fall back to the agent path), so hand one in
+ ctx.extra["_single_shot_ctx"] = replace(ctx, agent_id=SINGLE_SHOT_PREFIX + "fake:planner", model=object(), agent=None)
+ monkeypatch.setattr(scene_mod, "generate_for", fake_generate_for)
+ out = track._zones_stage(ctx)
+ assert all(out[n]["ok"] for n in names), out
+ recovered = [c for c in calls if c[0].endswith(".recover")]
+ assert len(recovered) == len(rest), calls
+ assert all(single for _, single, _ in recovered), "a recovery is single-shot: it cannot spend its window reading"
+ assert all(t is not None and t >= ZONE_MIN_S for _, _, t in recovered)
+ kinds = [e.get("event") for e in ctx.events.read()] if hasattr(ctx.events, "read") else []
+ if kinds:
+ assert "zones.recover" in kinds and "zones.recovered" in kinds
+
+
+def test_a_session_that_wrote_every_zone_triggers_no_recovery(tmp_path, settings, monkeypatch):
+ track, ctx = _ctx(tmp_path, settings)
+ plan: ScenePlan = ctx.plan # type: ignore[assignment]
+ ctx.runtime.skeleton(ctx.ws, plan)
+ labels: list[str] = []
+
+ def fake_generate_for(gen: Any, task: Any) -> GenerationResult:
+ labels.append(task.label)
+ changed = []
+ for rel in task.files_hint:
+ (ctx.ws.root / rel).write_text("export function build(ctx) { return new ctx.THREE.Group(); }\n")
+ changed.append(FileChange(path=rel, status="modified"))
+ return GenerationResult(ok=True, files_changed=changed, label=task.label)
+
+ monkeypatch.setattr(scene_mod, "generate_for", fake_generate_for)
+ out = track._zones_stage(ctx)
+ assert all(v["ok"] for v in out.values()) and not any(lbl.endswith(".recover") for lbl in labels), labels
diff --git a/harness/tests/prompts/conftest.py b/harness/tests/prompts/conftest.py
index 7537086a..1e67c677 100644
--- a/harness/tests/prompts/conftest.py
+++ b/harness/tests/prompts/conftest.py
@@ -1,8 +1,8 @@
"""Shared helpers for the prompt-pack tests.
-The cookbooks promise that their fenced snippets RUN. These helpers extract the
-fenced blocks per language and execute them the way the cookbook headers say they
-are executed (concatenated in order, with the documented prelude in scope).
+Each language's contract.md keeps ONE executable interface example (D107); these helpers
+extract the fenced blocks of a prompt file and execute them concatenated in order, with the
+documented prelude in scope.
"""
from __future__ import annotations
@@ -34,6 +34,12 @@ def is_template(rel: str) -> bool:
_FENCE = re.compile(r"```(\w[\w-]*)\n(.*?)```", re.DOTALL)
+#: fence-tag spellings that mean the same language
+_TAG_ALIASES = {"py": "python", "javascript": "js", "mjs": "js"}
+
+
+def _tag(raw: str) -> str:
+ return _TAG_ALIASES.get(raw, raw)
def read_prompt(rel: str) -> str:
@@ -42,7 +48,7 @@ def read_prompt(rel: str) -> str:
def blocks(rel: str, lang: str) -> list[str]:
"""All fenced blocks tagged ``lang`` in prompt file ``rel``, in order."""
- return [body for tag, body in _FENCE.findall(read_prompt(rel)) if tag == lang]
+ return [body for tag, body in _FENCE.findall(read_prompt(rel)) if _tag(tag) == lang]
def strip_imports_exports(js: str) -> str:
@@ -53,9 +59,10 @@ def strip_imports_exports(js: str) -> str:
def labelled_files(rel: str, tag: str = "js") -> dict[str, str]:
"""Blocks preceded by a `src/...` label line → {path: content} (contract examples)."""
out: dict[str, str] = {}
- pattern = re.compile(r"`((?:src|public)/[^`]+)`\n```" + tag + r"\n(.*?)```", re.DOTALL)
- for path, body in pattern.findall(read_prompt(rel)):
- out[path] = body
+ pattern = re.compile(r"`((?:src|public)/[^`]+)`\n```(\w[\w-]*)\n(.*?)```", re.DOTALL)
+ for path, raw_tag, body in pattern.findall(read_prompt(rel)):
+ if _tag(raw_tag) == tag:
+ out[path] = body
return out
diff --git a/harness/tests/prompts/manifest.py b/harness/tests/prompts/manifest.py
index d05bba03..ca427b5a 100644
--- a/harness/tests/prompts/manifest.py
+++ b/harness/tests/prompts/manifest.py
@@ -13,7 +13,7 @@ are dropped) and stored in ``manifest.json`` as ``kind → {sha256, bytes}``:
``JudgeInput`` the in-run judge reads (``FakeJudge.calls``) and the request the real
``VlmJudge`` builds from it;
* ``context:<workspace>/files`` — what a session reads in its workspace, as materialised
- (AGENTS/CLAUDE.md, the cookbook copy, the ignore file);
+ (AGENTS/CLAUDE.md, the ignore file);
* ``skills:<workspace>:<kind>@rNN/routed`` — the skill bundles routed to a round;
* ``mcp_tools:<track>/<language>`` — the MCP tool list a session is offered;
@@ -103,7 +103,7 @@ BRIEF = {"object_name": "DiningChair", "reference": "a Danish oak dining chair",
"sub_assemblies": [{"name": "frame", "purpose": "carries the load", "parts": ["legs", "rails"], "material": "oak"}],
"mechanism": "the legs carry the seat", "visible_from_outside": ["seat", "legs", "backrest"],
"signature_features": ["tapered legs", "curved backrest"], "materials": ["seat: oiled oak"]}
-CONTEXT_FILES = ("AGENTS.md", "CLAUDE.md", ".3dcode/cookbook.md", ".antigravityignore")
+CONTEXT_FILES = ("AGENTS.md", "CLAUDE.md", ".antigravityignore")
VOLATILE = frozenset({"duration_ms", "duration_s", "latency_ms", "max_wait_s", "timeout_s", "hard_deadline_s", "workspace", "data_b64"})
SHADER = ("void mainImage(out vec4 fragColor, in vec2 fragCoord) {{\n vec2 uv = fragCoord / u_resolution.xy;\n"
" // {tag}\n fragColor = vec4(uv, 0.5 + 0.5 * sin(u_time), 1.0);\n}}\n")
@@ -216,9 +216,8 @@ class ManifestServices(FakeServices):
def tool_cards(self, track: str, language: str) -> str:
return Services.tool_cards(self, track, language)
- def materialize(self, ws: Workspace, *, agent_kind: str, contract_md: str, cookbook_text: str, spatial_tools: bool) -> None:
- Services.materialize(self, ws, agent_kind=agent_kind, contract_md=contract_md, cookbook_text=cookbook_text,
- spatial_tools=spatial_tools)
+ def materialize(self, ws: Workspace, *, agent_kind: str, contract_md: str, spatial_tools: bool) -> None:
+ Services.materialize(self, ws, agent_kind=agent_kind, contract_md=contract_md, spatial_tools=spatial_tools)
self.materialized.append(agent_kind)
self.contexts.append((ws.root, {n: (ws.root / n).read_text() for n in CONTEXT_FILES if (ws.root / n).is_file()}))
@@ -456,7 +455,7 @@ SCENARIOS: dict[str, tuple[Track, Language, dict[str, Any], Callable[[Rig], None
"graphics.glsl_shader.single_shot.fresh": (G, Language.GLSL_SHADER, {}, lambda r: r.run(rounds=1, single_shot=True)),
"graphics.opengl_python.agent.fresh": (G, Language.OPENGL_PYTHON, {}, lambda r: r.run(rounds=1)),
}
-DEFAULT_TARGETS = {S: ("Seat", "FrontLeg", "Backrest"), SC: ("Quay", "Water"), G: ("RainDrops", "CityBokeh")}
+DEFAULT_TARGETS = {S: ("Base", "Upright", "TopFrame"), SC: ("Quay", "Water"), G: ("SurfaceRipples", "PoolFloor")}
# ============================================================================ capture → normalise → hash
diff --git a/harness/tests/prompts/test_files.py b/harness/tests/prompts/test_files.py
index fb5d61ee..89bf933c 100644
--- a/harness/tests/prompts/test_files.py
+++ b/harness/tests/prompts/test_files.py
@@ -1,4 +1,4 @@
-"""Every prompt file exists, renders through the loader, and every language ships its three files."""
+"""Every prompt file exists, renders through the loader, and every language ships its two files."""
from __future__ import annotations
@@ -23,15 +23,10 @@ def test_prompt_file_contract(rel: str) -> None:
assert seq not in raw, f"{rel} contains {seq!r} which breaks jinja rendering"
-#: the scene languages ship NO cookbook (owner, 2026-10-15): its interface facts are in contract.md /
-#: system.md, its craft in the skills as short optional practices — nothing a model can copy verbatim
-NO_COOKBOOK = frozenset({Language.SCENE_THREEJS, Language.SCENE_BLENDER})
-
-
-def test_every_language_ships_a_system_prompt_and_a_contract_and_the_scene_languages_no_cookbook() -> None:
+def test_every_language_ships_a_system_prompt_and_a_contract_and_no_cookbook() -> None:
"""A missing per-language file silently reads as "" through ``language_text`` — so the two files
- every language needs are pinned present, and the cookbook pinned present OR absent per language:
- a scene cookbook that came back would reach every session again through ``cookbook_text``."""
+ every language needs are pinned present, and the cookbook pinned ABSENT for every language (D107,
+ owner 2026-10-15: a cookbook that came back would be prompt material a model copies verbatim)."""
from codeverse3d.prompts.catalog import language_text
from codeverse3d.tracks.prompting import language_system_prompt
@@ -40,10 +35,8 @@ def test_every_language_ships_a_system_prompt_and_a_contract_and_the_scene_langu
assert text.strip(), f"{lang.value}: empty system prompt"
for name in ("system.md", "contract.md"):
assert (PROMPTS_DIR / language_prompt(lang, name)).is_file(), (lang.value, name)
- has_cookbook = (PROMPTS_DIR / language_prompt(lang, "cookbook.md")).is_file()
- assert has_cookbook == (lang not in NO_COOKBOOK), (lang.value, "cookbook.md", has_cookbook)
- for lang in NO_COOKBOOK:
+ assert not (PROMPTS_DIR / language_prompt(lang, "cookbook.md")).is_file(), (lang.value, "ships a cookbook")
assert language_text(lang, "cookbook.md") == ""
- assert language_prompt(Language.URDF_BLENDER, "cookbook.md") == "urdf/cookbook.md"
+ assert language_prompt(Language.URDF_BLENDER, "contract.md") == "urdf/contract.md"
for role in ("scope", "repair"):
assert (PROMPTS_DIR / "system" / f"role_{role}.j2").is_file(), role
diff --git a/harness/tests/prompts/test_snippets_run.py b/harness/tests/prompts/test_snippets_run.py
index 9a8a5c7f..3506d565 100644
--- a/harness/tests/prompts/test_snippets_run.py
+++ b/harness/tests/prompts/test_snippets_run.py
@@ -1,10 +1,13 @@
-"""The cookbooks' and contracts' promise: every snippet RUNS.
+"""The contracts' promise: each language's ONE interface example RUNS (D107 — no language ships a
+cookbook; the example in contract.md is the whole of a language's runnable prompt material).
* cadquery blocks run in-process (cadquery is a plain library).
* bpy blocks run in real headless Blender (marker: blender).
* js blocks run in real node against runtime_js/node_modules (marker: node).
-* the scene languages ship no cookbook (owner, 2026-10-15): their contracts' COMPLETE examples
- run through the real runtimes below, and that is the whole of their runnable prompt material.
+
+The tests pin the INTERFACE the example demonstrates (it builds through the real runtime, exports
+what the wrapper reads, sits on the ground), never its shape, part names or counts — the example is
+a stub, not a worked object.
"""
from __future__ import annotations
@@ -16,11 +19,9 @@ import pytest
from codeverse3d.config import get_settings
from tests.prompts.conftest import (
blocks,
- js_prelude,
labelled_files,
run_blender_script,
run_node_module,
- strip_imports_exports,
)
@@ -28,7 +29,9 @@ from tests.prompts.conftest import (
def _exec_python_blocks(rel: str) -> dict:
pytest.importorskip("cadquery")
ns: dict = {}
- for i, body in enumerate(blocks(rel, "python")):
+ bodies = blocks(rel, "python")
+ assert bodies, f"{rel} carries no python block: a language keeps ONE executable interface example"
+ for i, body in enumerate(bodies):
try:
exec(compile(body, f"{rel}:block{i}", "exec"), ns) # noqa: S102 - our own docs
except Exception as e: # pragma: no cover - failure path
@@ -36,53 +39,48 @@ def _exec_python_blocks(rel: str) -> dict:
return ns
-def test_cadquery_cookbook_runs() -> None:
- ns = _exec_python_blocks("cadquery/cookbook.md")
- assert "selfcheck" in ns and "result" in ns
-
-
def test_cadquery_contract_example_runs() -> None:
+ """The example defines ``result`` (what the wrapper exports), an Assembly with at least one
+ named child, lowest point on the ground."""
pytest.importorskip("cadquery") # the [cad] extra — absent on a [dev]-only install (CI)
ns = _exec_python_blocks("cadquery/contract.md")
result = ns["result"]
+ assert result.children, "the example must add at least one named part"
+ assert all(c.name for c in result.children)
bb = result.toCompound().BoundingBox()
- assert abs(bb.zmin) < 1e-6 and abs(bb.zmax - 0.45) < 1e-3
- assert [c.name for c in result.children] == ["Top", "Leg_0", "Leg_1", "Leg_2", "Leg_3"]
+ assert abs(bb.zmin) < 1e-6, f"not on the ground: zmin {bb.zmin}"
+ assert bb.zmax > 0.01
# --------------------------------------------------------------------- blender
-def test_blender_cookbook_runs(tmp_path) -> None:
- code = "\n".join(blocks("blender/cookbook.md", "python"))
- out = run_blender_script(tmp_path, code)
- assert "mesh objects" in out
-
-
@pytest.mark.blender
def test_blender_contract_example_builds_and_exports(tmp_path) -> None:
- code = "\n".join(blocks("blender/contract.md", "python"))
+ """The example's labelled files (``src/model.py`` + any ``src/parts/*.py``) run in headless Blender
+ the way the wrapper runs them (``src/`` on ``sys.path``, ``model.py`` executed) and leave at least
+ one named mesh object that exports to a GLB with its lowest point on the ground (Y-up after export)."""
+ files = labelled_files("blender/contract.md", tag="python")
+ assert "src/model.py" in files, f"blender/contract.md keeps ONE executable interface example: {sorted(files)}"
+ for rel, body in files.items():
+ p = tmp_path / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(body)
glb = tmp_path / "object.glb"
+ code = f"import sys\nsys.path.insert(0, {str(tmp_path / 'src')!r})\n" + files["src/model.py"]
code += (
- "\n_selfcheck()\nimport bpy\n"
+ "\nimport bpy\n"
f"bpy.ops.export_scene.gltf(filepath={str(glb)!r}, export_format='GLB', "
"export_yup=True, export_apply=True)\n"
- "print('PARTS', sorted(o.name for o in bpy.data.objects))\n"
+ "print('PARTS', sorted(o.name for o in bpy.data.objects if o.type == 'MESH'))\n"
)
out = run_blender_script(tmp_path, code)
- assert "PARTS ['Leg_0', 'Leg_1', 'Leg_2', 'Seat']" in out
- assert glb.stat().st_size > 1000
+ parts_line = next(line for line in out.splitlines() if line.startswith("PARTS "))
+ assert parts_line != "PARTS []", "the example must leave at least one mesh object"
+ assert glb.stat().st_size > 200
trimesh = pytest.importorskip("trimesh")
scene = trimesh.load(str(glb))
lo, hi = scene.bounds
- assert abs(lo[1]) < 1e-3 and abs(hi[1] - 0.45) < 1e-3 # Y-up GLB, on the ground
-
-
-def test_urdf_cookbook_runs(tmp_path) -> None:
- code = "\n".join(blocks("urdf/cookbook.md", "python"))
- out = run_blender_script(tmp_path, code)
- assert "[selfcheck] links" in out
+ assert abs(lo[1]) < 1e-3 and hi[1] > 0.01, (lo, hi) # Y-up GLB, on the ground
def _build_urdf_example(tmp_path, tag: str, model_py: str, urdf: str):
@@ -108,43 +106,34 @@ def _build_urdf_example(tmp_path, tag: str, model_py: str, urdf: str):
@pytest.mark.blender
-def test_urdf_contract_example_builds_and_lid_opens_upward(tmp_path) -> None:
- """The contract's COMPLETE example must pass the harness build exactly as written
- (FK consistency, no lint warnings, clean sweep) and the lid must open upward."""
+def test_urdf_contract_example_builds_and_its_joint_moves_the_child(tmp_path) -> None:
+ """The contract's example (one python block + one URDF) must pass the harness build exactly as
+ written — FK consistency, no lint warnings, clean sweep — and its first movable joint must
+ move its child link between the limits (a lid hinged on an edge opens upward)."""
+ import numpy as np
+
from codeverse3d.spatial.joints_model import link_world_meshes, load_urdf
- ws, _ = _build_urdf_example(tmp_path, "pedalbin", "\n".join(blocks("urdf/contract.md", "python")),
- blocks("urdf/contract.md", "xml")[0])
+ py, xml = blocks("urdf/contract.md", "python"), blocks("urdf/contract.md", "xml")
+ assert py and xml, "urdf/contract.md keeps ONE python + ONE numeric xml example (the FK rule's executable proof)"
+ ws, _ = _build_urdf_example(tmp_path, "example", "\n".join(py), xml[0])
r = load_urdf(ws.artifacts / "robot.urdf", ws.artifacts / "meshes")
- tops = {q: link_world_meshes(r, {"body_to_lid": q})["lid"].bounds[1][2] for q in (0.0, 0.75, 1.5)}
- assert tops[1.5] > tops[0.75] > tops[0.0] + 0.05, f"lid does not open upward: {tops}"
-
-
[email protected]("index,tag", [(0, "cabinet"), (1, "laptop"), (2, "cart")])
-def test_urdf_cookbook_worked_examples_build(tmp_path, index: int, tag: str) -> None:
- """Each worked example (prelude + helpers + example block, paired with its URDF) must
- pass the harness build: world meshes + visual/collision origin = −pivot."""
- py = blocks("urdf/cookbook.md", "python")
- xml = blocks("urdf/cookbook.md", "xml")
- _build_urdf_example(tmp_path, tag, "\n".join(py[:2]) + "\n" + py[2 + index], xml[index])
+ joint = next(j for j in r.joints.values() if j.movable and j.lower is not None and j.upper is not None)
+ at = {q: link_world_meshes(r, {joint.name: q})[joint.child].bounds for q in (joint.lower, joint.upper)}
+ assert not np.allclose(at[joint.lower], at[joint.upper]), f"{joint.name} does not move {joint.child}"
+ if joint.name == "body_to_lid": # the pedal-bin example: the lid's top rises through the sweep
+ tops = {q: link_world_meshes(r, {joint.name: q})["lid"].bounds[1][2] for q in (0.0, 0.75, 1.5)}
+ assert tops[1.5] > tops[0.75] > tops[0.0] + 0.05, f"lid does not open upward: {tops}"
# ------------------------------------------------------------------------ node
-def test_threejs_cookbook_runs(tmp_path) -> None:
- body = "".join(
- f"\nconsole.log('--- block {i} ---');\n" + strip_imports_exports(b)
- for i, b in enumerate(blocks("threejs/cookbook.md", "js"))
- )
- out = run_node_module(tmp_path, js_prelude() + body + "\nconsole.log('JS_BLOCKS_OK');\n")
- assert "JS_BLOCKS_OK" in out and "[selfcheck]" in out
-
-
@pytest.mark.node
def test_threejs_contract_example_builds_glb(tmp_path) -> None:
+ """The labelled files of the example are the entry ``src/object.js`` (+ any ``src/parts/*``);
+ ``build(THREE)`` returns an Object3D holding at least one mesh, on the ground, that exports."""
files = labelled_files("threejs/contract.md")
- assert set(files) == {"src/parts/seat.js", "src/parts/legs.js", "src/object.js"}
+ assert "src/object.js" in files, sorted(files)
+ assert all(rel.startswith("src/") for rel in files), sorted(files)
for rel, body in files.items():
p = tmp_path / rel
p.parent.mkdir(parents=True, exist_ok=True)
@@ -158,17 +147,17 @@ globalThis.FileReader = class {
readAsArrayBuffer(b) { b.arrayBuffer().then((x) => { this.result = x; this.onloadend && this.onloadend(); }); }
};
const root = build(THREE);
-let verts = 0; root.traverse((o) => { if (o.isMesh) verts += o.geometry.attributes.position.count; });
+let meshes = 0; root.traverse((o) => { if (o.isMesh) meshes += 1; });
const box = new THREE.Box3().setFromObject(root);
-if (verts < 100) throw new Error('too few vertices: ' + verts);
+if (meshes < 1) throw new Error('no mesh in the built object');
if (Math.abs(box.min.y) > 1e-3) throw new Error('not on ground: ' + box.min.y);
const buf = await new GLTFExporter().parseAsync(root, { binary: true });
writeFileSync('object.glb', Buffer.from(buf));
-console.log('GLB_OK', verts, buf.byteLength);
+console.log('GLB_OK', meshes, buf.byteLength);
"""
out = run_node_module(tmp_path, runner)
assert "GLB_OK" in out
- assert (tmp_path / "object.glb").stat().st_size > 1000
+ assert (tmp_path / "object.glb").stat().st_size > 200
@pytest.mark.node
@@ -267,3 +256,36 @@ def test_scene_blender_contract_examples_build_through_the_runtime(tmp_path) ->
rows = {r["name"]: r for r in res.census["placement"]["assets"]}
assert rows["QuayDeck"]["supported"] and not rows["QuayDeck"]["floating"]
assert all(rows[f"Bollard_{i}"]["supported"] for i in range(6)), {k: v for k, v in rows.items() if k.startswith("Bollard")}
+
+
+# --------------------------------------------------------------------- glsl_shader
+def test_glsl_shader_contract_example_builds_and_moves(tmp_ws) -> None:
+ """The contract's ONE complete ``mainImage`` (the block that defines it) is ``src/shader.frag``
+ as written: lint clean, the judged frames render through the real moderngl host, not static, no
+ NaN — before D107 nothing executed this language's prompt material except the cookbook's helpers."""
+ pytest.importorskip("moderngl")
+ import json
+
+ from codeverse3d.contracts.artifacts import Severity
+ from codeverse3d.contracts.plan import GraphicsPlan, PassPlan
+ from codeverse3d.languages.glsl_shader import GlslShaderRuntime
+ from codeverse3d.spatial.gl_render import GlHost, GlHostError
+
+ complete = [b for b in blocks("glsl_shader/contract.md", "glsl") if "void mainImage(" in b and "..." not in b]
+ assert len(complete) == 1, "glsl_shader/contract.md keeps exactly ONE complete mainImage example"
+ plan = GraphicsPlan(title="Example", summary="s", style="any", passes=[PassPlan(name="Image", description="d")],
+ motion="m", key_visuals=["k"], duration_s=6.0, resolution=(256, 144))
+ tmp_ws.write_json(tmp_ws.plan_path, plan)
+ tmp_ws.src.mkdir(parents=True, exist_ok=True)
+ (tmp_ws.src / "shader.frag").write_text(complete[0])
+ host = GlHost(timeout_s=120)
+ rt = GlslShaderRuntime(host=host)
+ rep = rt.lint(tmp_ws)
+ assert rep.passed and not [f for f in rep.findings if f.severity is not Severity.INFO], [f.message for f in rep.findings]
+ try:
+ br = rt.build(tmp_ws, width=256, height=144, preview=False)
+ except GlHostError as e: # pragma: no cover - machine without GL
+ pytest.skip(f"no OpenGL context: {e}")
+ assert br.ok, br.error_message
+ stats = json.loads((tmp_ws.artifacts / "metrics.json").read_text())["stats"]
+ assert not stats["static"] and not stats["any_nan"], stats
diff --git a/harness/tests/prompts/test_snippets_static.py b/harness/tests/prompts/test_snippets_static.py
index 1008d6f5..fba0417b 100644
--- a/harness/tests/prompts/test_snippets_static.py
+++ b/harness/tests/prompts/test_snippets_static.py
@@ -10,7 +10,7 @@ import pytest
from tests.prompts.conftest import blocks, read_prompt
-XML_FILES = ["urdf/contract.md", "urdf/cookbook.md"]
+XML_FILES = ["urdf/contract.md"]
def _is_template(body: str) -> bool:
@@ -23,7 +23,7 @@ _NUM = re.compile(r"^-?\d+(\.\d+)?([eE]-?\d+)?$")
@pytest.mark.parametrize("rel", XML_FILES)
def test_xml_examples_follow_the_enforced_frame_recipe(rel: str, tmp_path) -> None:
- """Every worked URDF passes the lint and the build's FK rule: visual origin = −(link frame world)."""
+ """The contract's URDF example passes the lint and the build's FK rule: visual origin = −(link frame world)."""
from codeverse3d.languages.urdf import lint_urdf_text
from codeverse3d.spatial.joints_model import fk, load_urdf
diff --git a/harness/tests/prompts/test_variants.py b/harness/tests/prompts/test_variants.py
index 186a542f..01ef305c 100644
--- a/harness/tests/prompts/test_variants.py
+++ b/harness/tests/prompts/test_variants.py
@@ -51,7 +51,7 @@ def _no_process_variant(monkeypatch):
@pytest.fixture
def overlay(tmp_path: Path, monkeypatch) -> Path:
- """A tmp ``VARIANTS_DIR`` holding ``tv``: a cookbook that shadows blender's, a template only the
+ """A tmp ``VARIANTS_DIR`` holding ``tv``: a system.md that shadows blender's, a template only the
variant ships, and a role template that includes a BASE file (the ChoiceLoader fall-through)."""
root = tmp_path / "variants"
shutil.copytree(VARIANTS_DIR / "argon", root / "argon") # the shipped one stays known beside tv
@@ -60,7 +60,7 @@ def overlay(tmp_path: Path, monkeypatch) -> Path:
(tv / d).mkdir(parents=True)
(tv / "variant.toml").write_text(TV_TOML)
(tv / "README.md").write_text("docs only\n")
- (tv / "blender" / "cookbook.md").write_text("# OVERLAY COOKBOOK\n")
+ (tv / "blender" / "system.md").write_text("# OVERLAY SYSTEM\n")
(tv / "tracks" / "only_in_variant.j2").write_text("overlay {{ x }}\n")
(tv / "system" / "role_repair.j2").write_text("OVERLAY ROLE {{ contract }}\n{% include 'system/singleshot_format.md' %}")
monkeypatch.setattr(V, "VARIANTS_DIR", root)
@@ -119,12 +119,12 @@ def test_variant_toml_is_type_checked(overlay, toml, problem):
# --------------------------------------------------------------------------- the prompt overlay
def test_an_overlay_file_shadows_the_base_and_a_missing_one_falls_back(overlay):
- base_cookbook = (PROMPTS_DIR / "blender" / "cookbook.md").read_text()
+ base_system = (PROMPTS_DIR / "blender" / "system.md").read_text()
base_contract = (PROMPTS_DIR / "blender" / "contract.md").read_text()
with activate("tv"):
- assert prompts.load_text("blender/cookbook.md") == "# OVERLAY COOKBOOK\n"
+ assert prompts.load_text("blender/system.md") == "# OVERLAY SYSTEM\n"
assert prompts.load_text("blender/contract.md") == base_contract, "no overlay copy: the base file"
- assert prompts.prompt_root("blender/cookbook.md") == overlay / "tv" / "blender" / "cookbook.md"
+ assert prompts.prompt_root("blender/system.md") == overlay / "tv" / "blender" / "system.md"
assert prompts.prompt_root("blender/contract.md") == PROMPTS_DIR / "blender" / "contract.md"
assert prompts.render("tracks/only_in_variant.j2", x=1) == "overlay 1\n"
rendered = prompts.render("system/role_repair.j2", contract="C")
@@ -133,11 +133,11 @@ def test_an_overlay_file_shadows_the_base_and_a_missing_one_falls_back(overlay):
# the catalog resolves through the same loader: callers do not change
from codeverse3d.prompts.catalog import language_text
- assert language_text(Language.BLENDER, "cookbook.md") == "# OVERLAY COOKBOOK\n"
+ assert language_text(Language.BLENDER, "system.md") == "# OVERLAY SYSTEM\n"
assert language_text(Language.BLENDER, "contract.md") == base_contract
with pytest.raises(FileNotFoundError):
prompts.load_text("blender/nowhere.md")
- assert prompts.load_text("blender/cookbook.md") == base_cookbook
+ assert prompts.load_text("blender/system.md") == base_system
with pytest.raises(TemplateNotFound):
prompts.render("tracks/only_in_variant.j2", x=1)
@@ -158,16 +158,16 @@ def test_base_rendering_is_untouched_and_byte_identical_under_an_empty_overlay()
def test_caches_are_isolated_per_variant_in_process(overlay):
- base = prompts.load_text("blender/cookbook.md")
- assert base != "# OVERLAY COOKBOOK\n"
+ base = prompts.load_text("blender/system.md")
+ assert base != "# OVERLAY SYSTEM\n"
with activate("tv"):
- assert prompts.load_text("blender/cookbook.md") == "# OVERLAY COOKBOOK\n"
+ assert prompts.load_text("blender/system.md") == "# OVERLAY SYSTEM\n"
strict, lenient = prompts._env_for("tv")
assert strict is not prompts._env and lenient is not prompts._lenient_env
assert prompts._env_for("tv") == (strict, lenient), "one environment per variant"
- assert prompts.load_text("blender/cookbook.md") == base
+ assert prompts.load_text("blender/system.md") == base
with activate("tv"):
- assert prompts.load_text("blender/cookbook.md") == "# OVERLAY COOKBOOK\n"
+ assert prompts.load_text("blender/system.md") == "# OVERLAY SYSTEM\n"
def test_activate_nests_and_falls_back_to_the_process_switch(overlay, monkeypatch):
@@ -209,7 +209,7 @@ def test_variant_hash_covers_both_overlays_and_ignores_readmes(overlay, tmp_path
assert len(h0) == 12 and int(h0, 16) >= 0
(overlay / "tv" / "README.md").write_text("edited docs\n")
assert variant_hash("tv") == h0, "README.md is documentation, not prompt material"
- (overlay / "tv" / "blender" / "cookbook.md").write_text("# OVERLAY COOKBOOK v2\n")
+ (overlay / "tv" / "blender" / "system.md").write_text("# OVERLAY SYSTEM v2\n")
h1 = variant_hash("tv")
assert h1 != h0
(skills / "variants" / "tv" / "routes.toml").write_text('[[boost]]\nskill = "c3d-part-contact"\ndelta = 5\n')
diff --git a/harness/tests/scene_prompts/test_quality_teaching.py b/harness/tests/scene_prompts/test_quality_teaching.py
index f0756876..06f66558 100644
--- a/harness/tests/scene_prompts/test_quality_teaching.py
+++ b/harness/tests/scene_prompts/test_quality_teaching.py
@@ -43,7 +43,8 @@ def test_no_scene_stage_inlines_cookbook_recipes() -> None:
for gone in ("ENV_RECIPES", "ZONE_RECIPES", "ZONE_RECIPES_MAX_CHARS", "refine_recipes"):
assert not hasattr(scene, gone), gone
- assert not hasattr(prompting, "cookbook_sections")
+ for gone in ("cookbook_sections", "select_cookbook_chapters", "COOKBOOK_SYNONYMS", "COOKBOOK_ALWAYS", "is_always_chapter"):
+ assert not hasattr(prompting, gone), gone # D106, then D107: no chapter picker on any track
assert "recipes=" not in inspect.getsource(scene)
diff --git a/harness/tests/scene_runtime/blender_scene_fixture.py b/harness/tests/scene_runtime/blender_scene_fixture.py
index 432fe8de..2aad1ade 100644
--- a/harness/tests/scene_runtime/blender_scene_fixture.py
+++ b/harness/tests/scene_runtime/blender_scene_fixture.py
@@ -171,3 +171,52 @@ def build_room_shell(root: Path) -> Path:
def blender_available() -> bool:
b = get_settings().resolve_blender()
return bool(b) and Path(b).exists()
+
+
+#: a red cube under a 20 m volume-only fog box (density 0.5 /m: opaque) and a 1 m volume puff beside it
+FOG_BOX_BPY = """
+import sys
+import bpy
+blend = sys.argv[sys.argv.index("--") + 1]
+bpy.ops.wm.read_factory_settings(use_empty=True)
+scene = bpy.context.scene
+def volume_mat(name, density):
+ m = bpy.data.materials.new(name)
+ nodes, links = m.node_tree.nodes, m.node_tree.links
+ for n in [n for n in nodes if n.bl_idname == "ShaderNodeBsdfPrincipled"]:
+ nodes.remove(n)
+ v = nodes.new("ShaderNodeVolumePrincipled")
+ v.inputs["Density"].default_value = density
+ links.new(v.outputs["Volume"], nodes["Material Output"].inputs["Volume"])
+ return m
+def cube(name, size, loc, mat):
+ bpy.ops.mesh.primitive_cube_add(size=size, location=loc)
+ ob = bpy.context.object
+ ob.name = name
+ ob.data.materials.append(mat)
+ return ob
+red = bpy.data.materials.new("Red")
+red.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.8, 0.05, 0.05, 1.0)
+cube("Crate", 2.0, (0.0, 0.0, 1.0), red)
+cube("SiteHaze", 20.0, (0.0, 0.0, 0.0), volume_mat("HazeFog", 0.5))
+cube("SteamPuff", 1.0, (3.0, 0.0, 1.0), volume_mat("SteamVol", 0.5))
+w = bpy.data.worlds.new("W")
+scene.world = w
+w.node_tree.nodes["Background"].inputs[1].default_value = 1.0
+bpy.ops.object.light_add(type="SUN", location=(0.0, 0.0, 30.0))
+bpy.context.object.data.energy = 3.0
+bpy.ops.wm.save_as_mainfile(filepath=blend)
+"""
+
+
+def build_fog_box(root: Path) -> Path:
+ """Write ``root/scene.blend``: a red crate inside an opaque 20 m fog box, a 1 m volume puff beside it."""
+ root.mkdir(parents=True, exist_ok=True)
+ script = root / "build_fog_box.py"
+ script.write_text(FOG_BOX_BPY)
+ blend = root / "scene.blend"
+ blender = get_settings().resolve_blender()
+ proc = run_subprocess([blender, "-b", "--factory-startup", "--python", str(script), "--", str(blend)],
+ cwd=root, env=blender_env(), timeout_s=120)
+ assert proc.returncode == 0 and blend.is_file(), proc.stderr[-2000:]
+ return blend
diff --git a/harness/tests/scene_runtime/test_render_blender.py b/harness/tests/scene_runtime/test_render_blender.py
index 1066dbaf..d0c1adf3 100644
--- a/harness/tests/scene_runtime/test_render_blender.py
+++ b/harness/tests/scene_runtime/test_render_blender.py
@@ -25,6 +25,7 @@ from codeverse3d.workspace import Workspace
from tests.scene_runtime.blender_scene_fixture import (
blender_available,
build_fixture,
+ build_fog_box,
build_room_shell,
)
from tests.scene_runtime.conftest import needs_browser
@@ -254,6 +255,31 @@ def test_a_no_fog_view_lifts_the_room_shells_lid_and_the_next_view_gets_it_back(
assert "hidden" not in rb._glb_view(res["frames"][0]), "views.json keeps the three.js schema"
+@needs_blender
+def test_a_no_fog_view_hides_a_fog_box_but_not_a_steam_puff_and_the_next_view_gets_it_back(tmp_path, monkeypatch):
+ """2026-10-15: the judge's fog-free views only unlinked the WORLD volume, while ``lib.sky.haze`` builds
+ the fog as a volume-only box — so the placement views were rendered through the haze (iteration 2's
+ milky overviews). A red crate inside an opaque 20 m fog box: the ``no_fog`` view names the box in
+ ``fog_hidden`` (never the 1 m steam puff) and its centre is the red crate; the same camera without
+ ``no_fog``, rendered next, sees the fog again — the restore in the driver's ``finally``."""
+ _cpu_env(monkeypatch, tmp_path / "cache")
+ blend = build_fog_box(tmp_path / "fog")
+ out = tmp_path / "out"
+ out.mkdir()
+ top = {"name": "overview_top", "kind": "orbit", "position": [0.0, 0.0, 6.0], "look_at": [0.0, 0.0, 1.0], "fov": 40.0,
+ "no_fog": True, "times": [0.0]}
+ fogged = {**top, "name": "fogged", "no_fog": False}
+ job = {"out": str(out), "result": str(out / rb.RESULT_NAME), "engine": "cycles", "samples": 4, "width": 96,
+ "height": 54, "times": [0.0], "authored": False, "cameras": [top, fogged]}
+ res = rb.render_frames(blend, out, job, timeout_s=180)
+ assert res["errors"] == [] and [f["name"] for f in res["frames"]] == ["overview_top", "fogged"]
+ assert {f["name"]: f["fog_hidden"] for f in res["frames"]} == {"overview_top": ["SiteHaze"], "fogged": []}
+ clear, hazy = _centre_rgb(out / "overview_top_t0.png"), _centre_rgb(out / "fogged_t0.png")
+ assert clear[0] > max(clear[1], clear[2]) + 25, f"the fog-free view must show the red crate, got {clear}"
+ assert not hazy[0] > max(hazy[1], hazy[2]) + 25, f"the fogged view must not see the crate clearly, got {hazy}"
+
+
def test_a_missing_blend_is_an_empty_renderset_that_says_why(tmp_path):
ws = Workspace(tmp_path / "run").create()
rs = rb.render_blender_scene(ws, tmp_path / "out")
diff --git a/harness/tests/scene_runtime/test_skeleton.py b/harness/tests/scene_runtime/test_skeleton.py
index e914f03e..b52c7ff2 100644
--- a/harness/tests/scene_runtime/test_skeleton.py
+++ b/harness/tests/scene_runtime/test_skeleton.py
@@ -99,8 +99,8 @@ def test_both_skeleton_paths_ship_the_effect_library(tmp_path):
def test_the_library_is_harness_owned_so_an_agent_cannot_rewrite_it():
"""`src/lib/` is starter code the agent CALLS. Registering it in
HARNESS_OWNED_SRC is what makes `_enforce_scope` revert a session's write to
- it — the same protection `src/recipes.glsl` has had since 2026-08-26, when a
- seeded file the agent COULD rewrite was measured gone by the end of the run."""
+ it — the protection a seeded glsl file got on 2026-08-26, when a seeded file the agent
+ COULD rewrite was measured gone by the end of the run."""
from codeverse3d.contracts.common import HARNESS_OWNED_SRC, Language, is_harness_owned
owned = HARNESS_OWNED_SRC[Language.SCENE_THREEJS]
@@ -111,9 +111,9 @@ def test_the_library_is_harness_owned_so_an_agent_cannot_rewrite_it():
for rel in ("src/scene.js", "src/env.js", "src/zones/meadow.js", "src/libx.js"):
assert not is_harness_owned(rel, owned), rel
# a plain entry is still an exact match, not a prefix
- glsl = HARNESS_OWNED_SRC[Language.GLSL_SHADER]
- assert is_harness_owned("src/recipes.glsl", glsl)
- assert not is_harness_owned("src/recipes.glsl.bak", glsl)
+ assert is_harness_owned("src/owned.glsl", ("src/owned.glsl",))
+ assert not is_harness_owned("src/owned.glsl.bak", ("src/owned.glsl",))
+ assert Language.GLSL_SHADER not in HARNESS_OWNED_SRC, "the seeded recipes.glsl went with D107"
def test_the_lint_does_not_judge_the_library_as_agent_code(tmp_path):
diff --git a/harness/tests/skills/test_freshness.py b/harness/tests/skills/test_freshness.py
index 8e488c76..6f5d440c 100644
--- a/harness/tests/skills/test_freshness.py
+++ b/harness/tests/skills/test_freshness.py
@@ -12,7 +12,7 @@ from pathlib import Path
import pytest
from codeverse3d.skills import bundle_dirs, iter_skills, skills_dir
-from codeverse3d.skills.registry import ROUTED_SKILLS, ROUTES
+from codeverse3d.skills.registry import ROUTED_SKILLS
from codeverse3d.spatial.registry import list_tools
BUNDLES = bundle_dirs()
@@ -34,8 +34,6 @@ _GATE_SLUG = re.compile(
#: a snake_case token in backticks is CLAIMED to be a name in this harness. Which live
#: vocabulary it belongs to does not matter — that it belongs to one of them does.
_HARNESS_SHAPED = re.compile(r"^[a-z][a-z0-9]*(?:_[a-z0-9]+)+$")
-#: both spellings: the historical tool call and today's prose pointer
-_COOKBOOK_SECTION = re.compile(r'(?:read_cookbook\(\s*section\s*=\s*"|cookbook sections? ")([^"]+)"')
#: ALL_CAPS tokens that are NOT ours, with the namespace that owns them. Extend
#: deliberately: an author who adds a name here is asserting it is somebody else's.
@@ -115,6 +113,10 @@ FOREIGN_CALLS = {
"transform_apply", "primitive_cube_add", "ensure_lookup_table", "hide_set", "update",
"len", "setup", "range", "print", "float", "int",
"clean", # cadquery/trimesh mesh op quoted while teaching welding
+ # bpy API names (bmesh.ops.remove_doubles, ScrewModifier.screw_offset, Curve.bevel_object,
+ # ArrayModifier.use_object_offset, MirrorModifier.use_clip) — the vocabulary scan found them in
+ # the blender cookbook until D107 deleted it; they are Blender's
+ "remove_doubles", "screw_offset", "bevel_object", "use_object_offset", "use_clip",
# illustrative names inside a bundle's own worked example
"left_wheel", "right_wheel",
# batteries whose results are cited as evidence but whose output dir is gitignored
@@ -122,11 +124,6 @@ FOREIGN_CALLS = {
}
-def _squash(text: str) -> str:
- """One-line, lowercase — a section name wrapped across two markdown lines is one name."""
- return " ".join(text.lower().split())
-
-
def _prose(text: str) -> str:
"""The body with fenced code removed — a define inside a shader is not our vocabulary."""
return _FENCE.sub("", text)
@@ -136,13 +133,13 @@ _DEF_RE = re.compile(r"^\s*(?:def|function)\s+([a-z_][a-z0-9_]*)\s*\(", re.M)
def _defined_callables() -> set[str]:
- """Every function the harness itself defines — python source plus the cookbooks'
- fenced snippets (a bundle may tell the agent to call ``radial_array`` by name)."""
+ """Every function the harness itself defines in python source. Prompt markdown is not a
+ source: no language ships a library of helpers to call by name any more (D107), so a bundle
+ that tells the agent to call a function the harness does not define points at nothing."""
out: set[str] = set()
- for root, pattern in ((HARNESS / "codeverse3d", "*.py"), (HARNESS / "codeverse3d" / "prompts", "*.md")):
- for p in root.rglob(pattern):
- if "__pycache__" not in p.parts:
- out |= set(_DEF_RE.findall(p.read_text(errors="ignore")))
+ for p in (HARNESS / "codeverse3d").rglob("*.py"):
+ if "__pycache__" not in p.parts:
+ out |= set(_DEF_RE.findall(p.read_text(errors="ignore")))
return out
@@ -198,62 +195,14 @@ def test_every_bundle_document_only_cites_live_vocabulary():
pytest.skip(f"no eval/bench beside the harness to tell battery ids from stale names: {unverifiable}")
-def _languages_of(skill_name: str) -> set[str]:
- out: set[str] = set()
- for r in ROUTES:
- if r.skill == skill_name:
- out |= set(r.languages)
- return out
-
-
-def _cookbook_sections_named_by(s) -> tuple[str, ...]:
- text = "\n".join([s.body] + [p.read_text() for p in sorted(s.dir.rglob("references/*.md"))])
- return tuple(sorted(set(_COOKBOOK_SECTION.findall(text))))
-
-
-def test_every_named_cookbook_section_exists():
- """T4's other half: a skill may point at the cookbook, never invent a heading."""
- from codeverse3d.prompts import load_text
- from codeverse3d.prompts.catalog import PROMPT_DIRS
- from codeverse3d.prompts.sections import split_sections
-
- _PROMPT_DIR = {k.value: v for k, v in PROMPT_DIRS.items()}
-
+def test_no_bundle_points_at_a_cookbook():
+ """No language ships a cookbook (D106 for the scene track, D107 for the rest, owner 2026-10-15):
+ a bundle that still sends the agent to a cookbook chapter — or to ``.3dcode/cookbook.md`` —
+ points at nothing. Every bundle, every reference."""
for s in SKILLS:
- wanted = _cookbook_sections_named_by(s)
- if not wanted:
- continue
- langs = _languages_of(s.name) or {"blender"}
- titles: set[str] = set()
- for lang in langs:
- d = _PROMPT_DIR.get(lang, lang)
- try:
- md = load_text(f"{d}/cookbook.md")
- except (FileNotFoundError, OSError):
- continue
- titles |= {sec.title.lower() for sec in split_sections(md)}
- for want in map(_squash, wanted):
- assert any(want in _squash(title) for title in titles), (
- f"{s.name} names cookbook section {want!r}, absent from {sorted(langs)}"
- )
-
-
-#: the cookbook was ELIMINATED for the scene track (owner, 2026-10-15): its interface facts went
-#: into contract.md / system.md and its craft into the skills as short optional practices, so a
-#: scene bundle that still points the agent at a cookbook chapter points at nothing.
-SCENE_LANGS = frozenset({"scene_threejs", "scene_blender"})
-
-
-def test_scene_bundles_name_no_cookbook_chapter():
- for s in SKILLS:
- langs = _languages_of(s.name)
- if not langs or not langs <= SCENE_LANGS:
- continue
- text = "\n".join([s.body] + [p.read_text() for p in sorted(s.dir.rglob("references/*.md"))])
- assert not _cookbook_sections_named_by(s), (
- f"{s.name} names cookbook sections {_cookbook_sections_named_by(s)}; the scene cookbooks are gone")
- assert not re.search(r"\bcookbook\b", text, re.I), (
- f"{s.name} still mentions a cookbook; the scene track has none")
+ for doc in [s.dir / "SKILL.md", *sorted(s.dir.rglob("references/*.md"))]:
+ hit = re.search(r"[^\n]{0,60}\bcookbook\b[^\n]{0,60}", doc.read_text(), re.I)
+ assert not hit, f"{doc.relative_to(skills_dir())} still mentions a cookbook: {hit.group(0)!r}"
def test_every_live_constant_named_by_a_skill_has_a_claim():
diff --git a/harness/tests/skills/test_library.py b/harness/tests/skills/test_library.py
index 940816a3..e6d81b5b 100644
--- a/harness/tests/skills/test_library.py
+++ b/harness/tests/skills/test_library.py
@@ -22,7 +22,9 @@ BUNDLES = bundle_dirs()
SKILLS = list(iter_skills()) if BUNDLES else []
pytestmark = pytest.mark.skipif(not BUNDLES, reason=f"no bundles in {skills_dir()} yet (the Author phase writes them)")
-MAX_FENCE_LINES = 20
+#: the owner's rule (D107, 2026-10-15): a skill's practice may show the API names in use, never a
+#: recipe to paste — no fence over ~12 lines, in SKILL.md or in a reference
+MAX_FENCE_LINES = 12
#: law 2 of the contract: `conventions.py` is the only place a frame/unit rule is stated.
#: A skill that restates one gives the agent two truths to choose between.
CONTRACT_RESTATEMENTS = (
@@ -46,11 +48,13 @@ def test_every_bundle_is_valid_and_its_claims_are_current():
assert not errors, f"{bundle.name}: {errors}"
for skill in SKILLS:
- for fence in re.findall(r"^```.*?^```", skill.body, re.S | re.M):
- lines = len(fence.splitlines()) - 2
- assert lines <= MAX_FENCE_LINES, (
- f"{skill.name}: a {lines}-line code fence belongs in the cookbook"
- )
+ for doc, text in [("SKILL.md", skill.body), *((str(p.relative_to(skill.dir)), p.read_text())
+ for p in sorted(skill.dir.rglob("references/*.md")))]:
+ for fence in re.findall(r"^```.*?^```", text, re.S | re.M):
+ lines = len(fence.splitlines()) - 2
+ assert lines <= MAX_FENCE_LINES, (
+ f"{skill.name}/{doc}: a {lines}-line code fence is a recipe, not a practice (D107)"
+ )
for pattern in CONTRACT_RESTATEMENTS:
assert not re.search(pattern, skill.body, re.I), (
f"{skill.name}: {pattern!r} belongs in conventions.py only"
diff --git a/harness/tests/skills/test_packaging.py b/harness/tests/skills/test_packaging.py
index 904f4b33..3879a26a 100644
--- a/harness/tests/skills/test_packaging.py
+++ b/harness/tests/skills/test_packaging.py
@@ -40,8 +40,14 @@ def test_a_built_wheel_actually_contains_the_bundles(tmp_path: Path):
assert f"codeverse3d/skills/{name}/SKILL.md" in names, (
f"{name} is in the source tree and NOT in the wheel: "
f"{sorted(n for n in names if 'skills' in n)[:20]}")
- refs = [n for n in names if n.startswith(f"codeverse3d/skills/{name}/references/")]
- assert refs, f"{name}: references/ must ship too — it is the depth probe"
+ # references/ is optional (c3d-glsl-craft has none since D107: telemetry then reports its
+ # depth as unmeasurable), but every reference file the source tree has must ship — it is
+ # the depth probe
+ src_refs = (HARNESS / "codeverse3d" / "skills" / name / "references")
+ want_refs = ([f"codeverse3d/skills/{name}/references/{f.name}" for f in sorted(src_refs.glob("*.md"))]
+ if src_refs.is_dir() else [])
+ missing = [r for r in want_refs if r not in names]
+ assert not missing, f"{name}: references/ must ship too — it is the depth probe: {missing}"
if not made_probe:
# every claims file too: `3dcode skills validate` runs against an installed wheel
claims = sorted((HARNESS / "codeverse3d" / "skills" / "_claims").glob("*.toml"))
diff --git a/harness/tests/texturing/test_normalise.py b/harness/tests/texturing/test_normalise.py
index 4fc53a0a..e585ecec 100644
--- a/harness/tests/texturing/test_normalise.py
+++ b/harness/tests/texturing/test_normalise.py
@@ -114,14 +114,16 @@ def _cq_export_factors() -> tuple[float, float]:
def test_the_harness_writers_own_defaults_count_as_never_authored():
"""N54: CadQuery's (0, 0.6) and the three.js stub's (0.05, 0.6) read as authored, so CadQuery
- steel was clamped to half-metallic and CadQuery wood was never normalised."""
+ steel was clamped to half-metallic and CadQuery wood was never normalised. Since D107 the
+ three.js stub sets neither factor, so it exports three's own default (0, 1); the pre-D107 stub's
+ pair stays listed for the runs recorded before it."""
import re
from codeverse3d.languages.threejs import PART_TEMPLATE
from codeverse3d.texturing.materials import is_framework_default
- stub = re.search(r"roughness: ([\d.]+), metalness: ([\d.]+)", PART_TEMPLATE)
- assert stub and is_framework_default(float(stub[2]), float(stub[1]))
+ assert "MeshStandardMaterial" in PART_TEMPLATE and not re.search(r"\b(roughness|metalness)\s*:", PART_TEMPLATE)
+ assert is_framework_default(0.0, 1.0) and is_framework_default(0.05, 0.6)
cq = _cq_export_factors()
assert is_framework_default(*cq)
steel = classify("SteelFrame", "SteelFrameMat", "", *cq)
diff --git a/harness/tests/threejs_render/test_skeleton.py b/harness/tests/threejs_render/test_skeleton.py
index 2bcce41e..a4a5ace4 100644
--- a/harness/tests/threejs_render/test_skeleton.py
+++ b/harness/tests/threejs_render/test_skeleton.py
@@ -33,8 +33,15 @@ def test_skeleton_files_and_contents(tmp_path: Path):
seat = (ws.src / "parts" / "seat_cushion.js").read_text()
assert "export function buildSeatCushion(THREE_)" in seat
assert "group.name = 'SeatCushion';" in seat
- assert "RoundedBoxGeometry" in seat and "ExtrudeGeometry" in seat
+ # the stub is a plain box at the plan bbox plus the measured requirements — no recipe to copy
+ # (D106's rule for every track, 2026-10-15): nothing in it says what the part should be made of
+ assert "new THREE.BoxGeometry(size[0], size[1], size[2])" in seat
+ assert "mesh.position.set(0, 0.68, 0);" in seat
+ for recipe in ("RoundedBoxGeometry", "ExtrudeGeometry", "LatheGeometry", "Copyable", "roughness", "tick"):
+ assert recipe not in seat, recipe
+ assert "max(10 mm, 10 % of the plan extent)" in seat and "gap <= 2 mm" in seat
assert "Material: leather" in seat
+ assert "userData.tick is recorded by the census but never called" in obj
assert '"type": "module"' in (ws.src / "package.json").read_text()
# never overwrites
(ws.src / "parts" / "seat_cushion.js").write_text("// mine\n")