Skip to content

Official Codebase of 3DCodeVerse

Python

graphics: seeded recipes are harness-owned — src/recipes.glsl, read-only, pasted above common.glsl

gaoypengf774b3bfedb0
diff --git a/harness/codeverse/agents/api_agent.py b/harness/codeverse/agents/api_agent.py
index 74a8ec45..23325beb 100644
--- a/harness/codeverse/agents/api_agent.py
+++ b/harness/codeverse/agents/api_agent.py
@@ -111,6 +111,7 @@ class _Loop:
allow_shell=job.api.allow_shell,
edit_only=job.files_hint if job.edit_only else None,
always_writable=job.always_writable,
+ read_only=job.read_only,
language=job.language,
)
self.spatial: SpatialTools | None = None
diff --git a/harness/codeverse/agents/api_tools.py b/harness/codeverse/agents/api_tools.py
index 9ffadd53..f2349bbc 100644
--- a/harness/codeverse/agents/api_tools.py
+++ b/harness/codeverse/agents/api_tools.py
@@ -101,6 +101,7 @@ class FileTools:
allow_shell: bool = True,
edit_only: Collection[str] | None = None,
always_writable: Collection[str] = (),
+ read_only: Collection[str] = (),
language: str = "",
):
self.ws = ws
@@ -122,7 +123,13 @@ class FileTools:
frozenset((ws.root / f).resolve() for f in edit_only) if edit_only is not None else None
)
self.always_writable = frozenset((ws.root / f).resolve() for f in always_writable)
+ #: harness-owned files inside the write roots (``src/recipes.glsl``): readable, never
+ #: writable — measured 2026-08-26 (bench/out/seed_v1), recipes seeded into the agent's own
+ #: common.glsl were overwritten by the end of the run; a file the agent can rewrite is not
+ #: a place to keep verified code.
+ self.read_only = frozenset((ws.root / f).resolve() for f in read_only)
self.scope_denials: list[str] = []
+ self.read_only_denials: list[str] = []
self.allow_shell = allow_shell
self.writes: list[str] = [] # workspace-relative paths written/edited, in order
@@ -243,6 +250,14 @@ class FileTools:
if write and not any(p == r or r in p.parents for r in self.write_roots):
roots = ", ".join(os.path.relpath(r, root) + "/" for r in self.write_roots)
raise PathDenied(f"writes are only allowed under {roots} (got {path})")
+ if write and p in self.read_only:
+ rel = os.path.relpath(p, root)
+ self.read_only_denials.append(rel)
+ raise PathDenied(
+ f"{rel} is harness-owned and read-only: the harness wrote it and pastes it above your "
+ f"code at build time, so its functions are already in scope — call them from your own "
+ f"files instead of editing, redefining or copying them (read_file on it still works)."
+ )
if (
write
and self.edit_only is not None
diff --git a/harness/codeverse/config.py b/harness/codeverse/config.py
index f5337a30..26bca3d7 100644
--- a/harness/codeverse/config.py
+++ b/harness/codeverse/config.py
@@ -101,11 +101,13 @@ class Limits(BaseModel):
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 src/common.glsl BEFORE the baseline session (tracks/graphics_recipes.py). "
+ "they use) into the harness-owned, read-only src/recipes.glsl BEFORE the baseline session "
+ "(tracks/graphics_recipes.py; 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). `CV3D_SEED_RECIPES=0` "
- "(read at call time by `seed_recipes_enabled`) is the control arm.",
+ "times — round 0 was again a comb of bars (comb_artefact, 0.33); and (bench/out/seed_v1) "
+ "recipes seeded into the agent's own common.glsl were overwritten before the end of the run. "
+ "`CV3D_SEED_RECIPES=0` (read at call time by `seed_recipes_enabled`) is the control arm.",
)
diff --git a/harness/codeverse/contracts/agent.py b/harness/codeverse/contracts/agent.py
index 979e0ca5..da548d3b 100644
--- a/harness/codeverse/contracts/agent.py
+++ b/harness/codeverse/contracts/agent.py
@@ -76,6 +76,12 @@ class AgentJob(BaseModel):
default_factory=list,
description="files exempt from edit_only (the entry file: adding a part means importing it there)",
)
+ 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); a write_file / "
+ "edit_file on one is refused with 'harness-owned — call its functions instead'",
+ )
mcp_command: list[str] | None = Field(
default=None, description="override for the 3dcv MCP server command"
)
diff --git a/harness/codeverse/contracts/common.py b/harness/codeverse/contracts/common.py
index 2074703c..c4ffb9a3 100644
--- a/harness/codeverse/contracts/common.py
+++ b/harness/codeverse/contracts/common.py
@@ -73,6 +73,15 @@ ENTRY_FILE: dict[Language, str] = {
Language.OPENGL_PYTHON: "src/program.py",
}
+#: source files the HARNESS writes under ``src/`` and owns: the agent reads them and calls what
+#: they define, never writes them (``AgentJob.read_only`` → ``FileTools`` refuses the write).
+#: Measured 2026-08-26 (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.
+HARNESS_OWNED_SRC: dict[Language, tuple[str, ...]] = {
+ Language.GLSL_SHADER: ("src/recipes.glsl",),
+}
+
#: human label per language (galleries, captions, reports)
LANGUAGE_LABEL: dict[Language, str] = {
Language.BLENDER: "Blender Python",
diff --git a/harness/codeverse/languages/file_lint.py b/harness/codeverse/languages/file_lint.py
index e4284c3a..c8b3a48b 100644
--- a/harness/codeverse/languages/file_lint.py
+++ b/harness/codeverse/languages/file_lint.py
@@ -93,11 +93,14 @@ def _js(path: Path, max_errors: int) -> FileVerdict:
errors=[(f"line {problem.line}: " if problem.line else "") + problem.message][:max_errors])
-def _glsl(rel: str, text: str, max_errors: int) -> FileVerdict:
+def _glsl(rel: str, text: str, path: Path, max_errors: int) -> FileVerdict:
from codeverse.languages.glsl_shader import lint as gl
role = {gl.SHADER: "shader", gl.COMMON: "common", gl.BUFFER_A: "buffer_a"}.get(rel, "shader")
- return _errors(gl._check_file(rel, text, role=role), max_errors)
+ # the harness-owned recipe file beside it reserves its names (redefines_recipe)
+ recipes = path.parent / Path(gl.RECIPES).name
+ reserved = frozenset(gl.defined_functions(recipes.read_text(errors="replace"))) if recipes.is_file() else frozenset()
+ return _errors(gl._check_file(rel, text, role=role, recipe_names=reserved), max_errors)
def _urdf(rel: str, text: str, max_errors: int) -> FileVerdict:
@@ -127,7 +130,7 @@ def lint_one_file(language: str, rel: str, text: str, path: Path, *, max_errors:
if suffix in (".js", ".mjs") and lang in (Language.THREEJS, Language.SCENE_THREEJS):
return _js(path, max_errors)
if suffix in (".frag", ".glsl") and lang is Language.GLSL_SHADER:
- return _glsl(rel, text, max_errors)
+ return _glsl(rel, text, path, max_errors)
if suffix == ".urdf" and lang is Language.URDF_BLENDER:
return _urdf(rel, text, max_errors)
except Exception as e: # noqa: BLE001 — a lint crash is not the agent's problem
diff --git a/harness/codeverse/languages/glsl_shader/lint.py b/harness/codeverse/languages/glsl_shader/lint.py
index c5d17801..ec2b5dbd 100644
--- a/harness/codeverse/languages/glsl_shader/lint.py
+++ b/harness/codeverse/languages/glsl_shader/lint.py
@@ -4,13 +4,18 @@ Catches what the compiler reports confusingly (or too late): a ``#version`` line
(the harness prepends one), redeclared harness uniforms / outputs, Shadertoy
inputs that do not exist here (``iChannel2``, ``iDate`` …), ``texture()`` on
undeclared samplers, GLSL 1.x syntax (``gl_FragColor`` / ``varying`` /
-``texture2D``), ``%`` on floats, a missing ``mainImage``/``main``.
-Gate name ``lint:glsl_shader``; ``data["kind"]`` names the rule.
+``texture2D``), ``%`` on floats, a missing ``mainImage``/``main``, and a function
+the harness-owned ``src/recipes.glsl`` already provides defined again in an agent
+file (``redefines_recipe`` — the compiler would say "redefinition" at the second
+copy; this says which file owns the first). ``src/recipes.glsl`` itself is
+harness-verified and is not linted. Gate name ``lint:glsl_shader``;
+``data["kind"]`` names the rule.
"""
from __future__ import annotations
import re
+from collections.abc import Collection
from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
from codeverse.languages.glsl_shader.wrap import (
@@ -25,6 +30,10 @@ GATE = "lint:glsl_shader"
SHADER = "src/shader.frag"
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*\(")
SAMPLERS = {"u_prev", "u_noise", "u_buffer_a", "iChannel0", "iChannel1"}
MAX_CHARS = 60_000
@@ -46,7 +55,16 @@ def _line_of(text: str, pos: int) -> int:
return text.count("\n", 0, pos) + 1
-def _check_file(rel: str, text: str, *, role: str) -> list[GateFinding]:
+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]:
out: list[GateFinding] = []
raw_len = len(text)
text = strip_comments(text)
@@ -91,6 +109,10 @@ def _check_file(rel: str, text: str, *, role: str) -> list[GateFinding]:
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",
@@ -110,21 +132,28 @@ def _check_file(rel: str, text: str, *, role: str) -> list[GateFinding]:
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"))
+ findings.extend(_check_file(SHADER, shader.read_text(errors="replace"), role="shader", recipe_names=reserved))
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))
+ findings.extend(_check_file(rel, p.read_text(errors="replace"), role=role, recipe_names=reserved))
stray = [str(p.relative_to(ws.root)) for p in ws.src.rglob("*") if p.is_file()
- and str(p.relative_to(ws.root)) not in (SHADER, COMMON, BUFFER_A) and p.suffix in (".frag", ".glsl", ".vert", ".py", ".js")]
+ and str(p.relative_to(ws.root)) not in (SHADER, COMMON, BUFFER_A, 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}))
@@ -132,14 +161,18 @@ def lint_workspace(ws: Workspace) -> GateReport:
return GateReport(gate=GATE, passed=passed, findings=findings)
-def lint_text(shader_src: str, common_src: str | None = None, buffer_a_src: str | None = None) -> list[GateFinding]:
- """Lint in-memory sources (tools / tests)."""
- out = _check_file(SHADER, shader_src, role="shader")
+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 (tools / tests); ``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)
if common_src is not None:
- out += _check_file(COMMON, common_src, role="common")
+ out += _check_file(COMMON, common_src, role="common", recipe_names=reserved)
if buffer_a_src is not None:
- out += _check_file(BUFFER_A, buffer_a_src, role="buffer_a")
+ out += _check_file(BUFFER_A, buffer_a_src, role="buffer_a", recipe_names=reserved)
return out
-__all__ = ["GATE", "SHADER", "COMMON", "BUFFER_A", "lint_workspace", "lint_text", "strip_comments"]
+__all__ = ["GATE", "SHADER", "COMMON", "BUFFER_A", "RECIPES", "FUNC_DEF", "defined_functions", "recipe_names",
+ "lint_workspace", "lint_text", "strip_comments"]
diff --git a/harness/codeverse/languages/glsl_shader/runtime.py b/harness/codeverse/languages/glsl_shader/runtime.py
index ddb13104..3a6bab4a 100644
--- a/harness/codeverse/languages/glsl_shader/runtime.py
+++ b/harness/codeverse/languages/glsl_shader/runtime.py
@@ -1,10 +1,11 @@
"""GlslShaderRuntime: skeleton → lint → build (moderngl frames) for Shadertoy-style shaders.
-``src/shader.frag`` (+ optional ``src/common.glsl``, ``src/buffer_a.frag``) is
-wrapped by :mod:`wrap` (header with the uniform contract + main trampoline),
-compiled and rendered in a subprocess by :class:`GlHost` at the plan's
-resolution for t ∈ {0, 1, 2.5, 4, 6}s (+ preview frames for the GIF).
-Compile errors come back mapped to ``src/shader.frag:LINE``.
+``src/shader.frag`` (+ optional ``src/common.glsl``, ``src/buffer_a.frag``, and the
+harness-owned ``src/recipes.glsl`` when the track seeded recipes) is wrapped by
+:mod:`wrap` (header with the uniform contract + main trampoline; recipes pasted
+above common), compiled and rendered in a subprocess by :class:`GlHost` at the
+plan's resolution for t ∈ {0, 1, 2.5, 4, 6}s (+ preview frames for the GIF).
+Compile errors come back mapped to ``src/shader.frag:LINE`` (or common / recipes).
"""
from __future__ import annotations
@@ -23,7 +24,7 @@ from codeverse.languages._gl_common import (
preview_times,
resolution_for,
)
-from codeverse.languages.glsl_shader.lint import BUFFER_A, COMMON, SHADER, lint_workspace
+from codeverse.languages.glsl_shader.lint import BUFFER_A, COMMON, RECIPES, SHADER, lint_workspace
from codeverse.languages.glsl_shader.skeleton import write_skeleton
from codeverse.languages.glsl_shader.wrap import Composed, compose, first_error
from codeverse.prompts import PROMPTS_DIR, load_text
@@ -68,9 +69,12 @@ class GlslShaderRuntime:
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
- image = compose(shader, common)
+ 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)
buf_p = ws.root / BUFFER_A
- buffer_a = compose(buf_p.read_text(errors="replace"), common, shader_file=BUFFER_A) if buf_p.is_file() else None
+ buffer_a = (compose(buf_p.read_text(errors="replace"), common, recipes_src=recipes, shader_file=BUFFER_A)
+ if buf_p.is_file() else None)
return image, buffer_a
def build(self, ws: Workspace, *, timeout_s: int | None = None, times: list[float] | None = None,
@@ -92,7 +96,7 @@ class GlslShaderRuntime:
extra_times=preview_times(duration) if preview else (),
)
census = {"convention": image.convention, "has_common": (ws.root / COMMON).is_file(), "has_buffer_a": buffer_a is not None,
- "resolution": [w, h]}
+ "has_recipes": (ws.root / RECIPES).is_file(), "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/codeverse/languages/glsl_shader/wrap.py b/harness/codeverse/languages/glsl_shader/wrap.py
index cbe93a37..f2a27f11 100644
--- a/harness/codeverse/languages/glsl_shader/wrap.py
+++ b/harness/codeverse/languages/glsl_shader/wrap.py
@@ -3,9 +3,11 @@
The harness owns the ``#version`` line, the uniform block and the ``main``
trampoline; the agent writes only the body (``mainImage(out vec4 fragColor,
in vec2 fragCoord)`` or a plain ``main()`` writing the harness-declared ``fragColor``).
-``compose`` returns the full source plus a :class:`LineMap` so compiler
-messages (``0:LINE(COL)`` / ``0(LINE)`` / ``ERROR: 0:LINE:`` variants) map back
-to ``src/shader.frag`` / ``src/common.glsl`` line numbers.
+``compose`` pastes harness header < ``src/recipes.glsl`` (harness-owned seeded
+recipes, when present) < ``src/common.glsl`` < ``src/shader.frag`` (+ trailer) and
+returns the full source plus a :class:`LineMap` so compiler messages
+(``0:LINE(COL)`` / ``0(LINE)`` / ``ERROR: 0:LINE:`` variants) map back to
+``src/shader.frag`` / ``src/common.glsl`` / ``src/recipes.glsl`` line numbers.
"""
from __future__ import annotations
@@ -82,16 +84,22 @@ def _count(text: str) -> int:
return text.count("\n") + (0 if text.endswith("\n") else 1)
-def compose(shader_src: str, common_src: str | None = None, *, shader_file: str = "src/shader.frag",
- common_file: str = "src/common.glsl") -> Composed:
- """Header + common + shader (+ trailer) with a line map back to the agent files."""
+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,
+ 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."""
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 common_src and common_src.strip():
- body = common_src if common_src.endswith("\n") else common_src + "\n"
- pieces.append((common_file, body))
- body = shader_src if shader_src.endswith("\n") else shader_src + "\n"
- pieces.append((shader_file, body))
+ pieces.append((common_file, _piece(common_src)))
+ pieces.append((shader_file, _piece(shader_src)))
if convention == "mainImage":
pieces.append(("harness", MAIN_IMAGE_TRAILER))
segments: list[Segment] = []
@@ -103,7 +111,7 @@ def compose(shader_src: str, common_src: str | None = None, *, shader_file: str
cursor += n
out.append(text)
src = "".join(out)
- code = strip_comments(shader_src) + "\n" + strip_comments(common_src or "")
+ code = strip_comments(shader_src) + "\n" + strip_comments(common_src or "") + "\n" + strip_comments(recipes_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)
diff --git a/harness/codeverse/prompts/glsl_shader/contract.md b/harness/codeverse/prompts/glsl_shader/contract.md
index 6780a53b..3e6ac145 100644
--- a/harness/codeverse/prompts/glsl_shader/contract.md
+++ b/harness/codeverse/prompts/glsl_shader/contract.md
@@ -9,6 +9,8 @@ measures / judges the frames. The code is the deliverable.
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/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 to it is refused)
```
Nothing else is read. No textures, no files, no includes.
diff --git a/harness/codeverse/prompts/tracks/generate_graphics.j2 b/harness/codeverse/prompts/tracks/generate_graphics.j2
index 6a3d9f97..f7097b4e 100644
--- a/harness/codeverse/prompts/tracks/generate_graphics.j2
+++ b/harness/codeverse/prompts/tracks/generate_graphics.j2
@@ -24,13 +24,13 @@ Cookbook excerpt:
{% endif %}
{% if seeded_recipes %}
-## Verified helpers ALREADY in `src/common.glsl` — call them, do not rewrite them
-`src/common.glsl` already contains these VERIFIED helpers; the harness pastes that file above your shader,
-so they are in scope in `src/shader.frag` 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), and do not define a function with one of these
-names yourself (a redefinition fails the compile). When you write `src/common.glsl`, keep the seeded block
-under `// ---- harness-seeded verified recipes` intact and add your own helpers below it.
+## 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 write to it is refused); 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 %}
diff --git a/harness/codeverse/prompts/tracks/refine_graphics.j2 b/harness/codeverse/prompts/tracks/refine_graphics.j2
index d3074afb..9b77ad5b 100644
--- a/harness/codeverse/prompts/tracks/refine_graphics.j2
+++ b/harness/codeverse/prompts/tracks/refine_graphics.j2
@@ -40,8 +40,9 @@ Key visuals:
- Keep brightness readable (mean luminance ~0.2-0.6), aspect-correct coordinates, tonemap + gamma last.
- A "colour/light" change = palette constants / exposure / grade only; a "motion" change = the time terms only;
do not rewrite unrelated layers.
-{% if seeded_recipes %}- `src/common.glsl` carries harness-seeded VERIFIED helpers ({% for r in seeded_recipes %}`{{ r.name }}`{% if not loop.last %}, {% endif %}{% endfor %}):
- call them for the light / sky / rain / bokeh layers instead of re-deriving them, and keep that block intact.
+{% 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 %}
diff --git a/harness/codeverse/tracks/generation.py b/harness/codeverse/tracks/generation.py
index 7975cf87..8b198856 100644
--- a/harness/codeverse/tracks/generation.py
+++ b/harness/codeverse/tracks/generation.py
@@ -430,6 +430,7 @@ def run_agent_task(
extra=extra,
edit_only=task.edit_only,
always_writable=_always_writable(language),
+ read_only=_read_only(language),
images=list(task.images),
**({"max_turns": turns_cap} if turns_cap > 0 else {}),
)
@@ -601,6 +602,17 @@ def _always_writable(language: str) -> list[str]:
return []
+def _read_only(language: str) -> list[str]:
+ """The harness-owned files of the language (``src/recipes.glsl`` for glsl_shader): every session
+ of the run — baseline, refine, repair — may read them, none may write them."""
+ from codeverse.contracts.common import HARNESS_OWNED_SRC, Language
+
+ try:
+ return list(HARNESS_OWNED_SRC.get(Language(language), ()))
+ except ValueError:
+ return []
+
+
def _attributed_fallback(ws: Workspace, task: GenerationTask, before: str) -> list[FileChange]:
"""Change detection when the agent did not report its own ``files_changed``.
diff --git a/harness/codeverse/tracks/graphics.py b/harness/codeverse/tracks/graphics.py
index 24c5500f..e5fa5845 100644
--- a/harness/codeverse/tracks/graphics.py
+++ b/harness/codeverse/tracks/graphics.py
@@ -107,8 +107,10 @@ class GraphicsTrack(BaseTrack):
# ------------------------------------------------------------------ prepare
def prepare(self, ctx: RunContext, runner: StageRunner) -> None:
- """Skeleton, then the brief's verified cookbook recipes into src/common.glsl (graphics_recipes:
- measured, flash does not call a recipe it is only shown; it does call one that is on disk)."""
+ """Skeleton, then the brief's verified cookbook recipes into the harness-owned, read-only
+ src/recipes.glsl (graphics_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)."""
super().prepare(ctx, runner)
if seed_recipes(ctx):
ctx.ws.commit("recipes")
diff --git a/harness/codeverse/tracks/graphics_recipes.py b/harness/codeverse/tracks/graphics_recipes.py
index 4fc71315..4102f769 100644
--- a/harness/codeverse/tracks/graphics_recipes.py
+++ b/harness/codeverse/tracks/graphics_recipes.py
@@ -1,18 +1,34 @@
-"""Seed the cookbook's verified GLSL recipes into ``src/common.glsl`` BEFORE the session.
-
-Measured 2026-08-26 (refs_v2_graphics, aurora brief, gemini-3.7-flash api-agent, shader_v2
-judge): the baseline prompt carried the cookbook's "Light phenomena" chapter — five mentions of
-``curtain(`` in ``trajectories/baseline_r00/prompt.md`` — and the agent called none of them
-(``grep -c "curtain(" src/shader.frag`` = 0 in both finished runs): round 0 was again a comb
-of bars (``comb_artefact``, 0.33), a later round a washed-out blur (0.12). Showing flash a
-recipe is not the same as flash using it, so the generator-side lever is to put the matched
-recipes ON DISK: the chapters :func:`select_cookbook_chapters` picks for the brief (minus the
-always-on helper / grading / pitfalls chapters), their ``glsl`` code blocks reduced to function
-definitions (no usage comments, no ``mainImage``), plus exactly the helpers those functions call
-(``hash12`` / ``noise`` / ``fbm`` …), appended to ``src/common.glsl`` under a header the prompt
-names. A resume appends only the names the file does not define yet. Gate:
-``Settings.limits.seed_recipes`` / ``CV3D_SEED_RECIPES`` (:func:`seed_recipes_enabled`).
-glsl_shader only — ``opengl_python`` programs own their shader strings, nothing is seeded there.
+"""Seed the cookbook's verified GLSL recipes into the HARNESS-OWNED ``src/recipes.glsl`` BEFORE the session.
+
+Measured 2026-08-26 (refs_v2_graphics, aurora brief, gemini-3.7-flash api-agent, shader_v2 judge): the
+baseline prompt carried the cookbook's "Light phenomena" chapter — five mentions of ``curtain(`` in
+``trajectories/baseline_r00/prompt.md`` — and the agent called none of them (``grep -c "curtain("
+src/shader.frag`` = 0 in both finished runs): round 0 was again a comb of bars (``comb_artefact``, 0.33).
+Showing flash a recipe is not the same as flash using it, so the recipes go ON DISK.
+
+Measured again 2026-08-26 (bench/out/seed_v1, same brief / model, seeding ON into ``src/common.glsl``):
+``recipes.seeded`` fired, and the finished run's ``src/common.glsl`` carried NO seeded block and no
+``curtain(`` — the agent overwrote common.glsl with its own helpers — and ``src/shader.frag`` called
+neither ``aurora(`` nor ``curtain(`` nor ``stars(``. Seeding into a file the agent owns is not sticky.
+So the file is now ``src/recipes.glsl`` (:data:`RECIPES_REL`), which the harness owns:
+
+* the agent cannot write it — ``AgentJob.read_only`` → ``FileTools`` refuses ``write_file`` /
+ ``edit_file`` (``read_file`` still works); the prompt says "call these, do not redefine them";
+* ``wrap.compose`` pastes it ABOVE ``src/common.glsl`` (harness header < recipes < common < shader),
+ so it is self-contained: every ``hash12`` / ``noise`` / ``fbm`` helper a recipe calls is IN the
+ file and nothing the agent does to common.glsl can break a recipe;
+* a name it defines is reserved: defining it again in shader.frag / common.glsl / buffer_a.frag is
+ the ``lint:glsl_shader`` ERROR ``redefines_recipe`` ("… is already provided by src/recipes.glsl");
+* the skeleton's ``src/common.glsl`` is the only file this module ever edits, and only while it is
+ still the untouched harness skeleton: the helpers recipes.glsl now provides are dropped from it
+ (:func:`trim_skeleton_common`), otherwise the very first build would fail on ``hash12`` twice.
+
+What is seeded: the chapters :func:`select_cookbook_chapters` picks for the brief (minus the always-on
+helper / grading / pitfalls chapters and the raymarching template), their ``glsl`` code blocks reduced to
+function definitions (no usage comments, no ``mainImage``), plus exactly the helpers those functions
+call. A resume appends only the names recipes.glsl does not define yet. Gate:
+``Settings.limits.seed_recipes`` / ``CV3D_SEED_RECIPES`` (:func:`seed_recipes_enabled`). glsl_shader
+only — ``opengl_python`` programs own their shader strings, nothing is seeded there.
"""
from __future__ import annotations
@@ -22,15 +38,23 @@ from dataclasses import dataclass
from pathlib import Path
from codeverse.config import seed_recipes_enabled
-from codeverse.contracts.common import Language
+from codeverse.contracts.common import HARNESS_OWNED_SRC, Language
from codeverse.contracts.plan import GraphicsPlan
+from codeverse.languages.glsl_shader.lint import FUNC_DEF
+from codeverse.languages.glsl_shader.skeleton import COMMON_GLSL
from codeverse.languages.glsl_shader.wrap import strip_comments
from codeverse.spatial.cookbook_tool import Section, split_sections
from codeverse.tracks.common import RunContext
from codeverse.tracks.prompting import is_always_chapter, select_cookbook_chapters
+#: the harness-owned recipe file (``contracts.common.HARNESS_OWNED_SRC``; ``AgentJob.read_only``)
+RECIPES_REL = HARNESS_OWNED_SRC[Language.GLSL_SHADER][0]
+#: the agent's helper file — never written by this module, except :func:`trim_skeleton_common`
COMMON_REL = "src/common.glsl"
-HEADER = "// ---- harness-seeded verified recipes (from the GLSL cookbook; call them, do not rewrite them) ----"
+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
@@ -60,7 +84,6 @@ PURPOSES: dict[str, str] = {
}
_FENCE = re.compile(r"```glsl[ \t]*\n(.*?)^```", re.S | re.M)
-_FUNC = re.compile(r"^[ \t]*(?:float|int|bool|void|[bi]?vec[234]|mat[234])\s+(\w+)\s*\(")
_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)
@@ -99,7 +122,7 @@ def parse_functions(code: str, chapter: str = "") -> list[Recipe]:
pending = [] if _USAGE.search(s) else pending + [raw]
i += 1
continue
- m = _FUNC.match(raw)
+ m = FUNC_DEF.match(raw)
if not s or not m: # blank, #define, or a bare statement snippet
pending, i = [], i + 1
continue
@@ -138,7 +161,7 @@ def cookbook_functions(md: str) -> dict[str, Recipe]:
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(m.group(1) for line in strip_comments(glsl).splitlines() if (m := _FUNC.match(line)))
+ names.update(m.group(1) for line in strip_comments(glsl).splitlines() if (m := FUNC_DEF.match(line)))
return names
@@ -173,34 +196,72 @@ def recipe_chapters(ctx: RunContext) -> list[Section]:
def seeded_on_disk(glsl: str, known: dict[str, Recipe]) -> list[Recipe]:
- """The cookbook recipes a ``common.glsl`` carries under the harness header, in file order (the
- agent's own helpers below the header are not "seeded", so only cookbook names count)."""
+ """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.split(HEADER, 1)[1]) if r.name in known]
+ 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]:
- """Append the brief's verified recipes (+ their helpers) to ``src/common.glsl``; 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."""
+ """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 seed_recipes_enabled():
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 / COMMON_REL
+ 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:
- block = [HEADER, *(f"// {r.signature} — {r.purpose}" for r in new), "", *(r.text for r in 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_REL, defined_names(existing))
present = seeded_on_disk(existing, known)
ctx.extra[EXTRA_KEY] = [r.entry() for r in present]
- ctx.events.emit("recipes.seeded", names=[r.name for r in new], present=[r.name for r in present],
- chapters=[s.title for s in chapters])
+ 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]
diff --git a/harness/codeverse/tracks/graphics_steps.py b/harness/codeverse/tracks/graphics_steps.py
index 01483f16..5dc5ad33 100644
--- a/harness/codeverse/tracks/graphics_steps.py
+++ b/harness/codeverse/tracks/graphics_steps.py
@@ -122,7 +122,7 @@ def graphics_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:
d: dict[str, Any] = {
"track": ctx.track.value, "language": ctx.language.value, "contract": ctx.contract_text,
"cookbook_rel": ctx.cookbook_rel, "cookbook_excerpt": select_cookbook_excerpt(ctx, graphics_brief(ctx)), "tool_cards": ctx.tool_cards,
- # the recipes tracks/graphics_recipes.py put in src/common.glsl before the session ([] = no prompt block)
+ # the recipes tracks/graphics_recipes.py put in the harness-owned src/recipes.glsl before the session ([] = no block)
"seeded_recipes": list((getattr(ctx, "extra", None) or {}).get(SEEDED_KEY) or []),
"single_shot": ctx.single_shot, "output_format": SINGLE_SHOT_FORMAT if ctx.single_shot else AGENT_OUTPUT_RULES,
"spec_prompt": ctx.spec.prompt, "constraints": constraints_text(ctx.spec),
diff --git a/harness/codeverse/tracks/prompting.py b/harness/codeverse/tracks/prompting.py
index 6c7fcc58..2075c8a7 100644
--- a/harness/codeverse/tracks/prompting.py
+++ b/harness/codeverse/tracks/prompting.py
@@ -227,7 +227,7 @@ def select_cookbook_chapters(ctx: RunContext, brief: str, *, budget: int = 9000,
``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_recipes.py`` seeds the SAME selection's code into ``src/common.glsl``.
+ ``tracks/graphics_recipes.py`` seeds the SAME selection's code into the harness-owned ``src/recipes.glsl``.
"""
from codeverse.spatial.cookbook_tool import Section, find_section, split_sections
diff --git a/harness/tests/agents/test_read_only.py b/harness/tests/agents/test_read_only.py
new file mode 100644
index 00000000..16702c62
--- /dev/null
+++ b/harness/tests/agents/test_read_only.py
@@ -0,0 +1,83 @@
+"""``AgentJob.read_only`` / ``FileTools(read_only=…)``: a harness-owned file inside the write roots is
+readable, never writable.
+
+Measured 2026-08-26 (bench/out/seed_v1, aurora brief, gemini-3.7-flash api-agent, seeding ON): the
+``recipes.seeded`` event fired and the finished run's ``src/common.glsl`` carried no seeded block and
+no ``curtain(`` — the agent overwrote the file with its own helpers. Verified code the agent can
+rewrite is not verified for long; ``src/recipes.glsl`` is therefore a file it can only call into.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from codeverse.agents.api_tools import FileTools, PathDenied
+from codeverse.contracts.agent import AgentJob, AgentResult
+from codeverse.contracts.common import HARNESS_OWNED_SRC, Language
+from codeverse.tracks.generation import GenerationTask, run_agent_task
+from codeverse.workspace import Workspace
+
+RECIPES = "src/recipes.glsl"
+SEEDED = "// harness-owned\nfloat curtain(vec2 p) { return 0.0; }\n"
+
+
+def _ws(tmp_path):
+ ws = Workspace(tmp_path / "run").create()
+ ws.src.mkdir(parents=True, exist_ok=True)
+ (ws.src / "recipes.glsl").write_text(SEEDED)
+ (ws.src / "shader.frag").write_text("void mainImage(out vec4 fragColor, in vec2 fragCoord) { fragColor = vec4(1.0); }\n")
+ return ws
+
+
+def test_a_read_only_file_can_be_read_but_not_written_or_edited(tmp_path):
+ ws = _ws(tmp_path)
+ ft = FileTools(ws, ["src", "public"], read_only=[RECIPES])
+ assert ft.read_file(RECIPES).text == SEEDED and not ft.read_file(RECIPES).is_error
+ with pytest.raises(PathDenied) as ei:
+ ft.write_file(RECIPES, "float curtain(vec2 p) { return 1.0; }\n")
+ assert "harness-owned" in str(ei.value) and "call them" in str(ei.value) and RECIPES in str(ei.value)
+ with pytest.raises(PathDenied, match="harness-owned"):
+ ft.edit_file(RECIPES, "0.0", "1.0")
+ assert (ws.src / "recipes.glsl").read_text() == SEEDED, "nothing was written"
+ assert ft.read_only_denials == [RECIPES, RECIPES] and ft.scope_denials == []
+ # the agent loop sees a tool error, not an exception; the other files stay writable
+ out = ft.call("write_file", {"path": RECIPES, "content": "x"})
+ assert out.is_error and "harness-owned" in out.text
+ assert not ft.write_file("src/shader.frag", "void mainImage(out vec4 f, in vec2 c) { f = vec4(0.5); }\n").is_error
+ assert not ft.write_file("src/common.glsl", "float mine(float x) { return x; }\n").is_error
+
+
+def test_read_only_holds_under_edit_only_too(tmp_path):
+ """A refine session scoped to the recipe file still cannot write it: read_only beats edit_only."""
+ ws = _ws(tmp_path)
+ ft = FileTools(ws, ["src", "public"], edit_only=[RECIPES], always_writable=[RECIPES], read_only=[RECIPES])
+ with pytest.raises(PathDenied, match="harness-owned"):
+ ft.write_file(RECIPES, "x")
+ assert FileTools(ws, ["src"]).read_only == frozenset() and not FileTools(ws, ["src"]).write_file(RECIPES, SEEDED).is_error
+
+
+class _CaptureAgent:
+ kind = "fake"
+ model = "fake"
+ id = "fake:fake"
+
+ def __init__(self):
+ self.jobs: list[AgentJob] = []
+
+ def available(self):
+ return True, "ok"
+
+ def run(self, job: AgentJob) -> AgentResult:
+ self.jobs.append(job)
+ return AgentResult(ok=False, exit_reason="completed")
+
+
[email protected](("language", "expected"), [("glsl_shader", [RECIPES]), ("blender", []), ("opengl_python", []), ("", [])])
+def test_the_job_carries_the_languages_harness_owned_files(tmp_path, language, expected):
+ ws = _ws(tmp_path)
+ if language:
+ ws.write_json(ws.spec_path, {"prompt": "aurora", "track": "graphics" if language != "blender" else "static_object", "language": language})
+ agent = _CaptureAgent()
+ run_agent_task(ws, agent=agent, task=GenerationTask(label="baseline", prompt="p", round=0, kind="baseline"), retry_silent_bail=False)
+ assert agent.jobs[-1].read_only == expected
+ assert AgentJob(workspace="w", prompt="p").read_only == [] and HARNESS_OWNED_SRC == {Language.GLSL_SHADER: (RECIPES,)}
diff --git a/harness/tests/graphics/test_track.py b/harness/tests/graphics/test_track.py
index 3daba436..c1bc4816 100644
--- a/harness/tests/graphics/test_track.py
+++ b/harness/tests/graphics/test_track.py
@@ -136,11 +136,18 @@ def test_graphics_track_end_to_end(tmp_path, settings):
# prompts: baseline is concrete (passes table, key visuals, contract, tools), refine carries judge + metrics
p0 = agent.jobs[0].prompt
assert "| RainDrops |" in p0 and "rain drops with trails" in p0 and "glsl_shader authoring contract" in p0 and "gl_frames" in p0
- # the brief's recipes were seeded into src/common.glsl before the session and the prompt names them
+ # the brief's recipes were seeded into the harness-owned src/recipes.glsl before the session (measured
+ # 2026-08-26, seed_v1: seeded into common.glsl they were overwritten), the prompt names them, every
+ # session's job carries the file as read-only, and common.glsl stays the agent's (skeleton, minus the
+ # helpers recipes.glsl now provides)
+ recipes = (ws.src / "recipes.glsl").read_text()
+ assert recipes.startswith("// harness-owned:") and "vec3 bokehSoft(vec2 p, float t)" in recipes and "vec2 dropsLayer(" in recipes
common = (ws.src / "common.glsl").read_text()
- assert "harness-seeded verified recipes" in common and "vec3 bokehSoft(vec2 p, float t)" in common and "vec2 dropsLayer(" in common
- assert "Verified helpers ALREADY in `src/common.glsl`" in p0 and "`vec3 bokehSoft(vec2 p, float t)`" in p0
- assert "harness-seeded VERIFIED helpers" in agent.jobs[1].prompt and "`bokehSoft`" in agent.jobs[1].prompt
+ assert "// harness-owned:" not in common and "bokehSoft" not in common and common.startswith("// src/common.glsl")
+ assert "provided by src/recipes.glsl" in common.splitlines()[1] # the skeleton's own hash/noise/fbm were trimmed
+ assert all(j.read_only == ["src/recipes.glsl"] for j in agent.jobs) and all(j.edit_only is False for j in agent.jobs[:1])
+ assert "Verified helpers in the harness-owned, read-only `src/recipes.glsl`" in p0 and "`vec3 bokehSoft(vec2 p, float t)`" in p0
+ assert "harness-owned, read-only `src/recipes.glsl`" in agent.jobs[1].prompt and "`bokehSoft`" in agent.jobs[1].prompt
p1 = agent.jobs[1].prompt
assert "Refine" in p1 and "Frame metrics" in p1 and "Previous score 0.55" in p1
assert rec.rounds[1].instructions and all("[judge/" in i or "[gate/" in i for i in rec.rounds[1].instructions)
diff --git a/harness/tests/orchestrator_tracks/test_graphics_recipes.py b/harness/tests/orchestrator_tracks/test_graphics_recipes.py
index fb060dd8..98f9db9c 100644
--- a/harness/tests/orchestrator_tracks/test_graphics_recipes.py
+++ b/harness/tests/orchestrator_tracks/test_graphics_recipes.py
@@ -1,9 +1,12 @@
-"""``tracks/graphics_recipes.py``: the brief's verified cookbook recipes land in ``src/common.glsl`` BEFORE the session.
+"""``tracks/graphics_recipes.py``: the brief's verified cookbook recipes land in the HARNESS-OWNED ``src/recipes.glsl``.
Measured 2026-08-26 (refs_v2_graphics, aurora brief, gemini-3.7-flash, shader_v2): the baseline prompt
carried ``curtain()`` five times and ``src/shader.frag`` called it zero times in both finished runs —
-round 0 a comb of bars (0.33), a later round a wash (0.12). Showing flash a recipe is not flash using
-it; these tests pin the on-disk seed, its helpers, the resume behaviour, the compose/lint path and the
+showing flash a recipe is not flash using it. Measured again the same day (bench/out/seed_v1, seeding
+ON into ``src/common.glsl``): ``recipes.seeded`` fired and the finished run's common.glsl had NO seeded
+block and no ``curtain(`` — the agent overwrote the file with its own helpers. Seeding into a file the
+agent owns is not sticky; these tests pin the harness-owned file, its self-contained helpers, the
+skeleton trim, the resume behaviour, the compose order + line map, the redefinition lint and the
prompt block that names what was seeded.
"""
@@ -16,19 +19,25 @@ from types import SimpleNamespace
import pytest
from codeverse.config import Settings, seed_recipes_enabled
-from codeverse.contracts.common import Language, Track
+from codeverse.contracts.common import HARNESS_OWNED_SRC, Language, Track
from codeverse.contracts.plan import GraphicsPlan
from codeverse.events import EventLog
-from codeverse.languages.glsl_shader.lint import lint_text
+from codeverse.languages.file_lint import lint_one_file
+from codeverse.languages.glsl_shader.lint import lint_text, lint_workspace
+from codeverse.languages.glsl_shader.runtime import GlslShaderRuntime
from codeverse.languages.glsl_shader.skeleton import COMMON_GLSL, write_skeleton
-from codeverse.languages.glsl_shader.wrap import compose
+from codeverse.languages.glsl_shader.wrap import HEADER as WRAP_HEADER
+from codeverse.languages.glsl_shader.wrap import compose, first_error, parse_glsl_log
from codeverse.prompts import load_text, render
from codeverse.tracks import graphics_recipes as gr
from codeverse.tracks.graphics_recipes import (
HEADER,
NOT_SEEDED,
+ RECIPES_REL,
+ RESUME_HEADER,
cookbook_functions,
defined_names,
+ is_skeleton_common,
parse_functions,
recipe_chapters,
seed_recipes,
@@ -44,6 +53,11 @@ UNMATCHED = "xyzzy plugh"
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:
@@ -65,6 +79,14 @@ 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"]
+
+
@pytest.fixture(autouse=True)
def _default_on(monkeypatch) -> None:
monkeypatch.delenv("CV3D_SEED_RECIPES", raising=False)
@@ -106,8 +128,13 @@ def test_chapter_selection_excludes_always_on_and_templates(tmp_path) -> None:
# ----------------------------------------------------------------------------- seeding
+def test_the_file_is_the_harness_owned_recipes_glsl() -> None:
+ assert RECIPES_REL == "src/recipes.glsl" and HARNESS_OWNED_SRC[Language.GLSL_SHADER] == (RECIPES_REL,)
+ assert HEADER.startswith("// harness-owned:") and "READ-ONLY" in HEADER and "above src/common.glsl" in HEADER
+
+
def test_aurora_brief_seeds_recipes_and_helpers_exactly_once(tmp_path) -> None:
- ws = _ws(tmp_path, skeleton=False) # no skeleton: helpers must come along
+ ws = _ws(tmp_path, skeleton=False)
ctx = _ctx(ws)
names = seed_recipes(ctx)
for n in AURORA_NAMES + HELPERS:
@@ -115,7 +142,7 @@ def test_aurora_brief_seeds_recipes_and_helpers_exactly_once(tmp_path) -> None:
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 = (ws.src / "common.glsl").read_text()
+ text = _recipes(ws).read_text()
assert text.startswith(HEADER)
defs = _defs(text)
assert len(defs) == len(set(defs)) and set(defs) == set(names)
@@ -123,32 +150,63 @@ def test_aurora_brief_seeds_recipes_and_helpers_exactly_once(tmp_path) -> None:
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 = [e for e in EventLog(ws.events_path).read() if e["event"] == "recipes.seeded"]
+ 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_skeleton_helpers_are_not_duplicated(tmp_path) -> None:
- ws = _ws(tmp_path) # the skeleton already defines hash/noise/fbm
- before = (ws.src / "common.glsl").read_text()
+def test_recipes_are_self_contained_and_the_skeleton_common_is_trimmed(tmp_path) -> None:
+ """recipes.glsl is pasted ABOVE common.glsl, so it must carry its own hash/noise/fbm — and the
+ skeleton's copies (the only common.glsl the harness ever edits: the agent has not seen it yet) go."""
+ 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) and not set(names) & set(HELPERS)
- text = (ws.src / "common.glsl").read_text()
- assert text.startswith(before) and HEADER in text
- defs = _defs(text)
+ 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)
- assert [r.name for r in seeded_on_disk(text, cookbook_functions(load_text("glsl_shader/cookbook.md")))] == names
+ # 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:
+ """Once the agent owns common.glsl (measured: it rewrites the whole file), the seed leaves it
+ alone — a duplicate is the agent's to remove, and the lint names it."""
+ 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_rain_brief_seeds_drops_and_bokeh(tmp_path) -> None:
ws = _ws(tmp_path)
names = seed_recipes(_ctx(ws, RAIN))
assert "dropsLayer" in names and "bokehSoft" in names and "curtain" not in names and "stars" not in names
- text = (ws.src / "common.glsl").read_text()
+ text = _recipes(ws).read_text()
assert "vec2 dropsLayer(vec2 uv, float t, float scale)" in text and "vec3 bokehSoft(vec2 p, float t)" in text
@@ -164,58 +222,58 @@ def test_plan_key_visuals_join_the_brief(tmp_path) -> None:
assert "curtain" in names2 and "bokehSoft" not in names2
-def test_nothing_matches_nothing_seeded_no_block(tmp_path) -> None:
+def test_nothing_matches_nothing_seeded_no_file_no_block(tmp_path) -> None:
ws = _ws(tmp_path)
- before = (ws.src / "common.glsl").read_text()
ctx = _ctx(ws, NOTHING)
assert seed_recipes(ctx) == []
- assert (ws.src / "common.glsl").read_text() == before and HEADER not in before
+ assert not _recipes(ws).exists() and (ws.src / "common.glsl").read_text() == COMMON_GLSL
assert ctx.extra["seeded_recipes"] == []
d = graphics_prompt_context(ctx, skeleton_files={}, previous_error="")
assert d["seeded_recipes"] == []
gen = render("tracks/generate_graphics.j2", **d)
- assert "Verified helpers ALREADY" not in gen and "harness-seeded" not in gen
- # a brief that matches nothing and NO common.glsl at all: no file is created
+ assert "Verified helpers in the harness-owned" not in gen and "recipes.glsl" not in gen
ws2 = _ws(tmp_path / "b", skeleton=False)
- assert seed_recipes(_ctx(ws2, NOTHING)) == [] and not (ws2.src / "common.glsl").exists()
- assert seed_recipes(_ctx(ws2, UNMATCHED)) == [] and not (ws2.src / "common.glsl").exists()
+ assert seed_recipes(_ctx(ws2, NOTHING)) == [] and not _recipes(ws2).exists() and not (ws2.src / "common.glsl").exists()
+ assert seed_recipes(_ctx(ws2, UNMATCHED)) == [] and not _recipes(ws2).exists()
def test_resume_appends_only_new_names(tmp_path) -> None:
ws = _ws(tmp_path)
first = seed_recipes(_ctx(ws))
- # the agent rewrote common.glsl: kept the seeded block, added its own helper, defined its own stars()
- p = ws.src / "common.glsl"
- agent = p.read_text().replace("float stars(vec2 p, float density, float keep)", "float starsOld(vec2 p, float density, float keep)")
- agent += "\nfloat mine(float x) { return x * 2.0; }\nfloat stars(vec2 p, float density, float keep) { return 0.0; }\n"
- p.write_text(agent)
+ 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)
- again = seed_recipes(ctx)
- assert again == [], again # every name is defined (stars by the agent)
- assert p.read_text() == agent
- # drop the agent's stars() and the seeded aurora(): a resume re-seeds exactly those two, after the agent's code
- trimmed = agent.replace("float stars(vec2 p, float density, float keep) { return 0.0; }\n", "")
- trimmed = re.sub(r"vec3 aurora\(vec2 p, float t\) \{.*?\n\}\n", "", trimmed, flags=re.S)
- p.write_text(trimmed)
+ 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 = p.read_text()
- assert text.startswith(trimmed) and text.count(HEADER) == 2 and "float mine(float x)" in text
+ 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) - {"stars", "aurora"} <= set(defs)
- # the prompt block lists the cookbook recipes on disk, not the agent's own helpers under the header
+ 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"] == []
def test_gate_and_language(tmp_path, monkeypatch) -> None:
ws = _ws(tmp_path)
- before = (ws.src / "common.glsl").read_text()
assert Settings().limits.seed_recipes is True and seed_recipes_enabled() is True
monkeypatch.setenv("CV3D_SEED_RECIPES", "0")
assert seed_recipes_enabled() is False
ctx = _ctx(ws)
- assert seed_recipes(ctx) == [] and (ws.src / "common.glsl").read_text() == before and "seeded_recipes" not in ctx.extra
- assert not [e for e in EventLog(ws.events_path).read() if e["event"] == "recipes.seeded"]
+ assert seed_recipes(ctx) == [] and not _recipes(ws).exists() and "seeded_recipes" not in ctx.extra
+ assert (ws.src / "common.glsl").read_text() == COMMON_GLSL and not _seeded_events(ws)
monkeypatch.setenv("CV3D_SEED_RECIPES", "garbage")
assert seed_recipes_enabled() is False # a typo is a control run, not a crash
monkeypatch.setenv("CV3D_SEED_RECIPES", "on")
@@ -223,39 +281,100 @@ def test_gate_and_language(tmp_path, monkeypatch) -> None:
monkeypatch.delenv("CV3D_SEED_RECIPES")
monkeypatch.setattr(gr, "seed_recipes_enabled", lambda: True)
assert seed_recipes(_ctx(ws, language=Language.OPENGL_PYTHON)) == [] # opengl_python: nothing seeded
- assert (ws.src / "common.glsl").read_text() == before
+ assert not _recipes(ws).exists() and (ws.src / "common.glsl").read_text() == COMMON_GLSL
monkeypatch.setenv("CV3D_SEED_RECIPES", "off")
assert Settings().limits.seed_recipes is False # the flat alias reaches Settings too
# ----------------------------------------------------------------------------- compose / lint / prompt
-def test_seeded_common_composes_and_lints_clean(tmp_path) -> None:
- ws = _ws(tmp_path)
- seed_recipes(_ctx(ws))
- common = (ws.src / "common.glsl").read_text()
- 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")
- assert lint_text(shader, common) == []
- comp = compose(shader, common)
- 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("void mainImage(")
- assert comp.line_map.segments[1].file == "src/common.glsl"
- # a real compile when a GL context exists (the harness's own host; skipped otherwise)
+def _gl_or_skip(tmp_path: Path, src: str, **kw):
pytest.importorskip("moderngl")
from codeverse.spatial.gl_render import GlHost, GlHostError
try:
- res = GlHost(timeout_s=120).render_fragment_shader(src, tmp_path / "out", width=96, height=54, times=(0.0, 2.5))
+ 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_compile_error_inside_recipes_is_reported_at_its_recipes_line(tmp_path) -> None:
+ recipes = "// harness-owned: verified cookbook recipes ...\nfloat ok(float x) { return x; }\n\nfloat bad(float x) { return x + ; }\n"
+ common = "float mine(float x) { return x; }\n"
+ comp = compose(SHADER, common, recipes_src=recipes)
+ header_lines = WRAP_HEADER.count("\n")
+ composed_line = header_lines + 4 # `bad` is recipes.glsl line 4
+ assert comp.source.splitlines()[composed_line - 1].startswith("float bad(")
+ for log in (f"0:{composed_line}(32): error: syntax error, unexpected ';'", # Mesa
+ f"0({composed_line}) : error C0000: syntax error, unexpected ';'", # NVIDIA
+ f"ERROR: 0:{composed_line}: ';' : syntax error"): # ANGLE / ES
+ first = first_error(parse_glsl_log(log, comp.line_map))
+ assert first is not None and (first.file, first.file_line) == ("src/recipes.glsl", 4), log
+ assert first.text().startswith("src/recipes.glsl:4: error:")
+ # and common.glsl / shader.frag lines still map to themselves, shifted by the recipes block
+ assert comp.line_map.locate(header_lines + 5) == ("src/common.glsl", 1)
+ assert comp.line_map.locate(header_lines + 6) == ("src/shader.frag", 1)
+ # the real compiler, when there is one: the build names src/recipes.glsl:4
+ res = _gl_or_skip(tmp_path, comp.source, width=32, height=18, times=(0.0,))
+ assert not res.ok and res.stage == "compile"
+ first = first_error(parse_glsl_log(res.error_message, comp.line_map))
+ assert first is not None and (first.file, first.file_line) == ("src/recipes.glsl", 4), res.error_message
+
+
+def test_lint_flags_a_redefinition_of_a_seeded_recipe(tmp_path) -> None:
+ recipes = "float curtain(vec2 p, float t, float seed, out float k) { k = 0.0; return 0.0; }\nvec3 aurora(vec2 p, float t) { return vec3(0.0); }\n"
+ shader = "// mine\nfloat curtain(vec2 p, float t, float seed, out float k) { k = 1.0; return 1.0; }\n" + SHADER
+ common = "float hash12(vec2 p) { return 0.0; }\n\nvec3 aurora(vec2 p, float t) { return vec3(1.0); }\n"
+ found = [f for f in lint_text(shader, common, recipes_src=recipes) if f.data["kind"] == "redefines_recipe"]
+ assert [(f.data["file"], f.data["line"]) for f in found] == [("src/shader.frag", 2), ("src/common.glsl", 3)]
+ assert found[0].message == "src/shader.frag:2: `curtain` is already provided by src/recipes.glsl — call it instead of redefining it"
+ assert found[1].message.endswith("`aurora` is already provided by src/recipes.glsl — call it instead of redefining it")
+ assert all(f.severity.value == "error" for f in found) and "harness-owned" in found[0].fix_hint
+ assert not [f for f in lint_text(shader, common) if f.data["kind"] == "redefines_recipe"] # no recipes: no rule
+ # the workspace lint reads recipes.glsl itself (and does not call it a stray file); buffer_a is checked too
+ ws = _ws(tmp_path, skeleton=False)
+ (ws.src / "shader.frag").write_text(SHADER)
+ (ws.src / "buffer_a.frag").write_text("vec3 aurora(vec2 p, float t) { return vec3(0.0); }\n" + SHADER)
+ _recipes(ws).write_text(recipes)
+ rep = lint_workspace(ws)
+ assert not rep.passed and [f.data["file"] for f in rep.findings if f.data["kind"] == "redefines_recipe"] == ["src/buffer_a.frag"]
+ assert not any(f.data["kind"] == "stray_file" for f in rep.findings)
+ # the per-file verdict a write_file hands back says it too
+ verdict = lint_one_file("glsl_shader", "src/common.glsl", common, ws.src / "common.glsl")
+ assert verdict.checked and any("`aurora` is already provided by src/recipes.glsl" in e for e in verdict.errors)
def test_prompt_block_lists_the_seeded_names(tmp_path) -> None:
@@ -265,15 +384,17 @@ def test_prompt_block_lists_the_seeded_names(tmp_path) -> None:
d = graphics_prompt_context(ctx, skeleton_files={}, previous_error="")
assert [r["name"] for r in d["seeded_recipes"]] == names
gen = render("tracks/generate_graphics.j2", **d)
- assert "Verified helpers ALREADY in `src/common.glsl`" in gen and "do not rewrite" in gen
+ assert "Verified helpers in the harness-owned, read-only `src/recipes.glsl`" in gen and "do not redefine them" in gen
+ assert "do not copy them into `src/common.glsl`" in gen and "pastes it above" in gen and "ALREADY in `src/common.glsl`" not in gen
for n in names:
assert re.search(rf"^- `[^`]*\b{n}\([^`]*\)` — .+$", gen, re.M), n
assert "float curtain(vec2 p, float t, float seed, out float k)" in gen and "never a comb of bars" in gen
- assert gen.index("Cookbook excerpt:") < gen.index("Verified helpers ALREADY") < gen.index("## Plan")
+ assert gen.index("Cookbook excerpt:") < gen.index("Verified helpers in the harness-owned") < gen.index("## Plan")
ref = render("tracks/refine_graphics.j2", **graphics_prompt_context(
ctx, round_index=1, tasks=["[judge/likeness] overall: no curtain"], targets=["overall"], files=["src/shader.frag"],
judge_summary="Previous score 0.3", frame_notes="(no frame metrics)", current_files={}))
- assert "harness-seeded VERIFIED helpers" in ref and all(f"`{n}`" in ref for n in names)
+ assert "harness-owned, read-only `src/recipes.glsl`" in ref and "do not copy them into common.glsl" in ref
+ assert all(f"`{n}`" in ref for n in names)
# the sibling prompt-context test builds ctx without .extra: the key still resolves to []
bare = SimpleNamespace(**{k: v for k, v in vars(ctx).items() if k != "extra"})
assert graphics_prompt_context(bare, skeleton_files={}, previous_error="")["seeded_recipes"] == []