Skip to content

Official Codebase of 3DCodeVerse

Python

graphics: seed the brief's verified cookbook recipes into src/common.glsl before the session (CV3D_SEED_RECIPES)

gaoypeng2e9c17fb6716
diff --git a/harness/codeverse/config.py b/harness/codeverse/config.py
index 001dd62d..f5337a30 100644
--- a/harness/codeverse/config.py
+++ b/harness/codeverse/config.py
@@ -97,6 +97,16 @@ class Limits(BaseModel):
"reads out; `CV3D_FEWER_TURNS=1` (read at call time by `fewer_turns_enabled`) is "
"what `bench/ab_plan.py --variant-env` flips.",
)
+ seed_recipes: bool = 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 src/common.glsl BEFORE the baseline session (tracks/graphics_recipes.py). "
+ "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.",
+ )
class Rate(BaseModel):
@@ -155,6 +165,8 @@ class Judge(BaseModel):
#: differs its arms by environment alone, and a value frozen at first ``get_settings()``
#: would hand the variant the control's behaviour (the CQ-5 lesson, tracks/plan_features.py).
FEWER_TURNS_ENV = "CV3D_FEWER_TURNS"
+#: The recipe-seeding switch (Limits.seed_recipes); same call-time contract as FEWER_TURNS_ENV.
+SEED_RECIPES_ENV = "CV3D_SEED_RECIPES"
_TRUE_WORDS = frozenset({"1", "on", "true", "yes", "y"})
_FALSE_WORDS = frozenset({"0", "off", "false", "no", "n"})
@@ -168,18 +180,30 @@ def _env_flag(raw: str, env: str) -> bool:
raise ValueError(f"{env}={raw!r}: expected on/off (1/0, true/false, yes/no)")
-def fewer_turns_enabled() -> bool:
- """Is the fewer-turns bundle on for THIS call? ``$CV3D_FEWER_TURNS`` when it is set
- (garbage counts as off, with a warning — a typo in a bench command must produce a
- control run, not a crash mid-battery), else ``Settings.limits.fewer_turns``."""
- raw = os.environ.get(FEWER_TURNS_ENV)
+def _call_time_flag(env: str, fallback: bool) -> bool:
+ """``$env`` when it is set (garbage counts as off, with a warning — a typo in a bench
+ command must produce a control run, not a crash mid-battery), else ``fallback`` (the
+ cached Settings value)."""
+ raw = os.environ.get(env)
if raw is not None and raw.strip():
try:
- return _env_flag(raw, FEWER_TURNS_ENV)
+ return _env_flag(raw, env)
except ValueError as e:
logging.getLogger(__name__).warning("%s; treating it as off", e)
return False
- return get_settings().limits.fewer_turns
+ return fallback
+
+
+def fewer_turns_enabled() -> bool:
+ """Is the fewer-turns bundle on for THIS call? ``$CV3D_FEWER_TURNS`` when it is set,
+ else ``Settings.limits.fewer_turns``."""
+ return _call_time_flag(FEWER_TURNS_ENV, get_settings().limits.fewer_turns)
+
+
+def seed_recipes_enabled() -> bool:
+ """Is recipe seeding (``tracks/graphics_recipes.py``) on for THIS call? ``$CV3D_SEED_RECIPES``
+ when it is set, else ``Settings.limits.seed_recipes`` (default ON)."""
+ return _call_time_flag(SEED_RECIPES_ENV, get_settings().limits.seed_recipes)
class Settings(BaseSettings):
@@ -193,6 +217,7 @@ class Settings(BaseSettings):
_FLAT_ALIASES: ClassVar[dict[str, tuple[str, str]]] = {
"CV3D_MAX_IN_FLIGHT": ("rate", "max_in_flight"),
FEWER_TURNS_ENV: ("limits", "fewer_turns"),
+ SEED_RECIPES_ENV: ("limits", "seed_recipes"),
}
@model_validator(mode="after")
diff --git a/harness/codeverse/prompts/tracks/generate_graphics.j2 b/harness/codeverse/prompts/tracks/generate_graphics.j2
index 8ff84c7c..6a3d9f97 100644
--- a/harness/codeverse/prompts/tracks/generate_graphics.j2
+++ b/harness/codeverse/prompts/tracks/generate_graphics.j2
@@ -22,6 +22,18 @@ Files you must produce: {% for f in expected_files %}`{{ f }}`{% if not loop.las
Cookbook excerpt:
{{ 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.
+{% for r in seeded_recipes %}- `{{ r.signature }}` — {{ r.purpose }}
+{% endfor %}
+{% endif %}
## Plan
{{ plan_summary }}
diff --git a/harness/codeverse/prompts/tracks/refine_graphics.j2 b/harness/codeverse/prompts/tracks/refine_graphics.j2
index 3b5e4c10..d3074afb 100644
--- a/harness/codeverse/prompts/tracks/refine_graphics.j2
+++ b/harness/codeverse/prompts/tracks/refine_graphics.j2
@@ -40,6 +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.
+{% endif %}
{% if current_files %}
## Current file contents (edit these; return each edited file COMPLETE)
diff --git a/harness/codeverse/tracks/graphics.py b/harness/codeverse/tracks/graphics.py
index 9329576a..24c5500f 100644
--- a/harness/codeverse/tracks/graphics.py
+++ b/harness/codeverse/tracks/graphics.py
@@ -24,6 +24,7 @@ from codeverse.orchestrator.rounds import TaskGroup
from codeverse.prompts import render
from codeverse.tracks.common import RunContext
from codeverse.tracks.generation import GenerationTask
+from codeverse.tracks.graphics_recipes import seed_recipes
from codeverse.tracks.graphics_steps import (
PLAN_MAX_OUTPUT_TOKENS,
PLAN_TEMPERATURE,
@@ -36,7 +37,7 @@ from codeverse.tracks.graphics_steps import (
graphics_prompt_context,
)
from codeverse.tracks.graphics_steps import plan_example as graphics_plan_example
-from codeverse.tracks.lifecycle import BaseTrack
+from codeverse.tracks.lifecycle import BaseTrack, StageRunner
from codeverse.tracks.prompting import (
current_files,
judge_digest,
@@ -104,6 +105,14 @@ class GraphicsTrack(BaseTrack):
def plan_event_stats(self, plan_obj: Any) -> dict[str, Any]:
return graphics_event_stats(plan_obj)
+ # ------------------------------------------------------------------ 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)."""
+ super().prepare(ctx, runner)
+ if seed_recipes(ctx):
+ ctx.ws.commit("recipes")
+
# ------------------------------------------------------------------ baseline
def system_prompt(self, ctx: RunContext) -> str:
what = "GLSL fragment-shader artist (Shadertoy style)" if ctx.language is Language.GLSL_SHADER else "raw OpenGL (moderngl) graphics programmer"
diff --git a/harness/codeverse/tracks/graphics_recipes.py b/harness/codeverse/tracks/graphics_recipes.py
new file mode 100644
index 00000000..4fc71315
--- /dev/null
+++ b/harness/codeverse/tracks/graphics_recipes.py
@@ -0,0 +1,206 @@
+"""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.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from pathlib import Path
+
+from codeverse.config import seed_recipes_enabled
+from codeverse.contracts.common import Language
+from codeverse.contracts.plan import GraphicsPlan
+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
+
+COMMON_REL = "src/common.glsl"
+HEADER = "// ---- harness-seeded verified recipes (from the GLSL cookbook; call them, do not rewrite 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",
+ "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)
+_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)
+#: 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.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(m.group(1) for line in strip_comments(glsl).splitlines() if (m := _FUNC.match(line)))
+ 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 ``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)."""
+ 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]
+
+
+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."""
+ 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
+ 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]
+ if new:
+ block = [HEADER, *(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")
+ 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])
+ return [r.name for r in new]
diff --git a/harness/codeverse/tracks/graphics_steps.py b/harness/codeverse/tracks/graphics_steps.py
index 666e004f..01483f16 100644
--- a/harness/codeverse/tracks/graphics_steps.py
+++ b/harness/codeverse/tracks/graphics_steps.py
@@ -21,6 +21,8 @@ from codeverse.contracts.spec import Spec
from codeverse.languages._gl_common import SHEET_NAME, read_metrics
from codeverse.tracks.common import RunContext
from codeverse.tracks.generation import SINGLE_SHOT_FORMAT
+from codeverse.tracks.graphics_recipes import EXTRA_KEY as SEEDED_KEY
+from codeverse.tracks.graphics_recipes import graphics_brief
from codeverse.tracks.planner import add_acceptance_item, build_system_prompt
from codeverse.tracks.planner import plan as run_planner
from codeverse.tracks.prompting import (
@@ -117,10 +119,11 @@ def graphics_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:
"""Every variable the graphics templates may reference (StrictUndefined)."""
plan = ctx.plan if isinstance(ctx.plan, GraphicsPlan) else None
res = plan.resolution if plan else (1280, 720)
- brief = ctx.spec.prompt + " " + " ".join(plan.key_visuals if plan else [])
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, brief), "tool_cards": ctx.tool_cards,
+ "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)
+ "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),
"title": plan.title if plan else "Untitled effect", "plan_summary": plan.summary if plan else "",
diff --git a/harness/codeverse/tracks/prompting.py b/harness/codeverse/tracks/prompting.py
index 1b4efc0e..6c7fcc58 100644
--- a/harness/codeverse/tracks/prompting.py
+++ b/harness/codeverse/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 Any
+from typing import TYPE_CHECKING, Any
from codeverse.config import fewer_turns_enabled
from codeverse.contracts.chat import ImagePart
@@ -23,6 +23,9 @@ from codeverse.tracks.common import RunContext
from codeverse.tracks.depth import DepthBudget, PartScope, depth_budget, interfaces_text
from codeverse.tracks.generation import SINGLE_SHOT_FORMAT
+if TYPE_CHECKING:
+ from codeverse.spatial.cookbook_tool import Section
+
log = logging.getLogger(__name__)
MAX_SKELETON_CHARS = 14_000
@@ -198,9 +201,22 @@ def _words(text: str) -> set[str]:
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_excerpt(ctx: RunContext, brief: str, *, budget: int = 9000,
always: Sequence[str] = COOKBOOK_ALWAYS) -> str:
- """Whole cookbook chapters chosen for ``brief``, never a blind prefix.
+ """Whole cookbook chapters chosen for ``brief``, never a blind prefix (see
+ :func:`select_cookbook_chapters` for the selection; this joins their bodies)."""
+ return "\n\n".join(s.body.rstrip() for s in select_cookbook_chapters(ctx, brief, budget=budget, always=always))
+
+
+def select_cookbook_chapters(ctx: RunContext, brief: str, *, budget: int = 9000,
+ 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,
@@ -211,12 +227,13 @@ def select_cookbook_excerpt(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``.
"""
from codeverse.spatial.cookbook_tool import Section, find_section, split_sections
md = ctx.cookbook_text or ""
if not md.strip():
- return ""
+ return []
chapters: list[Section] = []
for s in split_sections(md): # fold ### sub-headings into their ## chapter
if s.level >= 3 and chapters:
@@ -245,7 +262,7 @@ def select_cookbook_excerpt(ctx: RunContext, brief: str, *, budget: int = 9000,
if used + size <= budget:
chosen.add(i)
used += size
- return "\n\n".join(chapters[i].body.rstrip() for i in sorted(chosen))
+ return [chapters[i] for i in sorted(chosen)]
def base_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:
diff --git a/harness/tests/graphics/test_track.py b/harness/tests/graphics/test_track.py
index 42adf8ba..3daba436 100644
--- a/harness/tests/graphics/test_track.py
+++ b/harness/tests/graphics/test_track.py
@@ -136,12 +136,19 @@ 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
+ 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
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)
kinds = [e["event"] for e in EventLog(ws.events_path).read()]
- for k in ("plan.done", "round.start", "build.done", "gates.done", "judge.done", "refine.planned", "stop", "run.done"):
+ for k in ("plan.done", "recipes.seeded", "round.start", "build.done", "gates.done", "judge.done", "refine.planned", "stop", "run.done"):
assert k in kinds, k
+ seeded = next(e for e in EventLog(ws.events_path).read() if e["event"] == "recipes.seeded")
+ assert {"dropsLayer", "bokehSoft"} <= set(seeded["names"]) and seeded["present"] == seeded["names"] # + the night-sky chapter
def test_static_frames_become_a_gate_warning_and_refine_task(tmp_path, settings):
diff --git a/harness/tests/orchestrator_tracks/test_graphics_recipes.py b/harness/tests/orchestrator_tracks/test_graphics_recipes.py
new file mode 100644
index 00000000..fb060dd8
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_graphics_recipes.py
@@ -0,0 +1,279 @@
+"""``tracks/graphics_recipes.py``: the brief's verified cookbook recipes land in ``src/common.glsl`` BEFORE the session.
+
+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
+prompt block that names what was seeded.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from codeverse.config import Settings, seed_recipes_enabled
+from codeverse.contracts.common import 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.glsl_shader.skeleton import COMMON_GLSL, write_skeleton
+from codeverse.languages.glsl_shader.wrap import compose
+from codeverse.prompts import load_text, render
+from codeverse.tracks import graphics_recipes as gr
+from codeverse.tracks.graphics_recipes import (
+ HEADER,
+ NOT_SEEDED,
+ cookbook_functions,
+ defined_names,
+ parse_functions,
+ recipe_chapters,
+ seed_recipes,
+ seeded_on_disk,
+)
+from codeverse.tracks.graphics_steps import graphics_prompt_context, plan_example
+from codeverse.workspace import Workspace
+
+AURORA = "Aurora borealis over a mountain ridge with a frozen lake, dense stars, green and violet curtains"
+RAIN = "neon rain on glass"
+NOTHING = "a rotating rainbow gear wheel" # matches the Instancing chapter, which defines no function
+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)
+
+
+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"), cookbook_rel="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=SimpleNamespace(entry_globs=()))
+
+
+def _defs(text: str) -> list[str]:
+ return _DEF.findall(text)
+
+
[email protected](autouse=True)
+def _default_on(monkeypatch) -> None:
+ monkeypatch.delenv("CV3D_SEED_RECIPES", raising=False)
+
+
+# ----------------------------------------------------------------------------- extraction
+def test_cookbook_functions_are_real_definitions_without_usage_lines() -> None:
+ known = cookbook_functions(load_text("glsl_shader/cookbook.md"))
+ for name in AURORA_NAMES + HELPERS + ("bokehSoft", "dropsLayer", "warped"):
+ assert name in known, name
+ assert "mainImage" not in known and "main" not in known
+ assert known["curtain"].signature == "float curtain(vec2 p, float t, float seed, out float k)"
+ assert {"fbm", "noise"} <= known["curtain"].calls and {"hash12", "hash22"} <= known["stars"].calls
+ assert "// ORGANIC CURTAIN" in known["curtain"].text and "Never a comb" in known["curtain"].text
+ for r in known.values():
+ assert "// usage:" not in r.text and "// e.g." not in r.text and r.text.count("{") == r.text.count("}"), r.name
+ # the stars doc comment (prose with a ';' inside) is kept, the usage line under it is not
+ assert "DENSE STARS" in known["stars"].text and "col += vec3(0.9, 0.95, 1.0)" not in known["stars"].text
+ assert "// sunset:" not in known["tonemapACES"].text and "// water colour" not in "".join(r.text for r in known.values())
+
+
+def test_parse_functions_handles_one_liners_and_nested_braces() -> None:
+ code = "// doc\nfloat a(float x) { return x; }\n// usage: a(1.0);\nvec2 b(vec2 p) {\n for (int i = 0; i < 2; i++) { p = p * 2.0; }\n return p; // }\n}\nvoid mainImage(out vec4 f, in vec2 c) { f = vec4(a(1.0)); }\n"
+ got = parse_functions(code, "ch")
+ assert [r.name for r in got] == ["a", "b"] and got[0].text == "// doc\nfloat a(float x) { return x; }"
+ assert got[1].signature == "vec2 b(vec2 p)" and got[1].text.endswith("\n}") and got[1].calls == frozenset()
+ assert got[1].purpose == 'from the cookbook chapter "ch"'
+ assert defined_names(COMMON_GLSL) >= {"hash11", "hash12", "hash22", "noise", "fbm", "rot2", "palette", "tonemap", "PI", "TAU"}
+
+
+def test_chapter_selection_excludes_always_on_and_templates(tmp_path) -> None:
+ ws = _ws(tmp_path)
+ titles = [s.title for s in recipe_chapters(_ctx(ws, AURORA))]
+ assert any(t.startswith("Light phenomena") for t in titles) and any(t.startswith("Gradient sky") for t in titles)
+ assert not any("Hash" in t or "Palettes" in t or "PITFALLS" in t for t in titles)
+ assert recipe_chapters(_ctx(ws, "a raymarched temple corridor with fog")) == [] and NOT_SEEDED == ("Raymarching",)
+ assert recipe_chapters(_ctx(ws, UNMATCHED)) == []
+ assert [s.title[:10] for s in recipe_chapters(_ctx(ws, NOTHING))] == ["Instancing"]
+
+
+# ----------------------------------------------------------------------------- seeding
+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
+ 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 = (ws.src / "common.glsl").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
+ # the run record carries it
+ ev = [e for e in EventLog(ws.events_path).read() if e["event"] == "recipes.seeded"]
+ assert len(ev) == 1 and ev[0]["names"] == names and ev[0]["present"] == names
+ 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()
+ 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 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
+
+
+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()
+ assert "vec2 dropsLayer(vec2 uv, float t, float scale)" in text and "vec3 bokehSoft(vec2 p, float t)" in text
+
+
+def test_plan_key_visuals_join_the_brief(tmp_path) -> None:
+ ws = _ws(tmp_path)
+ plan = GraphicsPlan.model_validate({**plan_example(), "key_visuals": ["an aurora curtain over the ridge"]})
+ names = seed_recipes(_ctx(ws, "a landscape", plan=plan))
+ assert "curtain" in names and "bokehSoft" not in names
+ # the seed follows the prompt's selection exactly, budget included: for "a city at night" the Light +
+ # Gradient-sky chapters fill the 9 k budget and Bokeh does not fit, so bokehSoft is NOT seeded either
+ ws2 = _ws(tmp_path / "b")
+ names2 = seed_recipes(_ctx(ws2, "a city at night", plan=plan))
+ assert "curtain" in names2 and "bokehSoft" not in names2
+
+
+def test_nothing_matches_nothing_seeded_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 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
+ 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()
+
+
+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)
+ 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)
+ 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
+ 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 [e["name"] for e in ctx.extra["seeded_recipes"]] == [n for n in first if n not in ("stars", "aurora")] + ["stars", "aurora"]
+
+
+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"]
+ 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")
+ assert seed_recipes_enabled() is True
+ 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
+ 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)
+ 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))
+ 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}")
+ assert res.ok, res.error_message
+ assert len(res.frames) == 2 and all(Path(f.path).is_file() for f in res.frames)
+
+
+def test_prompt_block_lists_the_seeded_names(tmp_path) -> None:
+ ws = _ws(tmp_path)
+ ctx = _ctx(ws, plan=GraphicsPlan.model_validate({**plan_example(), "key_visuals": ["green aurora curtains", "dense stars"]}))
+ names = seed_recipes(ctx)
+ 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
+ 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")
+ 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)
+ # 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"] == []