Skip to content

Official Codebase of 3DCodeVerse

Python

graphics: hand the agent the cookbook chapters its brief calls for, not the first 7000 chars

gaoypeng9c79df0b4160
diff --git a/harness/codeverse/tracks/graphics_steps.py b/harness/codeverse/tracks/graphics_steps.py
index b434fdc4..666e004f 100644
--- a/harness/codeverse/tracks/graphics_steps.py
+++ b/harness/codeverse/tracks/graphics_steps.py
@@ -28,6 +28,7 @@ from codeverse.tracks.prompting import (
acceptance_lines,
constraints_text,
reference_note,
+ select_cookbook_excerpt,
)
from codeverse.workspace import Workspace
@@ -116,9 +117,10 @@ 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": ctx.cookbook_text[:7000], "tool_cards": ctx.tool_cards,
+ "cookbook_rel": ctx.cookbook_rel, "cookbook_excerpt": select_cookbook_excerpt(ctx, brief), "tool_cards": ctx.tool_cards,
"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 da1912cc..acb2edae 100644
--- a/harness/codeverse/tracks/prompting.py
+++ b/harness/codeverse/tracks/prompting.py
@@ -171,6 +171,82 @@ def cookbook_sections(ctx: RunContext, names: Sequence[str], *, max_chars: int =
return text
+#: brief words → cookbook chapter titles (case-insensitive substrings of a ``## `` heading) they call for
+COOKBOOK_SYNONYMS: dict[str, tuple[str, ...]] = {
+ "aurora": ("Light phenomena",), "curtain": ("Light phenomena",), "curtains": ("Light phenomena",),
+ "northern": ("Light phenomena",), "glow": ("Light phenomena",),
+ "star": ("Gradient sky", "Light phenomena"), "stars": ("Gradient sky", "Light phenomena"),
+ "night": ("Gradient sky", "Light phenomena"), "space": ("Gradient sky", "Light phenomena"),
+ "galaxy": ("Gradient sky", "Light phenomena"), "nebula": ("Gradient sky", "Light phenomena"),
+ "bokeh": ("Bokeh",), "city": ("Bokeh",), "neon": ("Bokeh",), "lights": ("Bokeh",),
+ "rain": ("Rain",), "drops": ("Rain",), "glass": ("Rain",),
+ "cloud": ("Domain warping",), "clouds": ("Domain warping",), "smoke": ("Domain warping",),
+ "marble": ("Domain warping",),
+ "tunnel": ("Raymarching",), "temple": ("Raymarching",), "corridor": ("Raymarching",), "3d": ("Raymarching",),
+ "trail": ("Feedback",), "trails": ("Feedback",), "feedback": ("Feedback",),
+}
+COOKBOOK_ALWAYS: tuple[str, ...] = ("Hash / noise / fbm", "Palettes, tonemapping, grading", "PITFALLS")
+_STOP = frozenset(("the", "and", "with", "for", "from", "into", "over", "that", "this", "are", "its", "one", "two",
+ "not", "but", "then", "than", "out", "each", "all", "any", "per", "via", "use", "like", "look",
+ "looks", "very", "some", "more", "most"))
+
+
+def _words(text: str) -> set[str]:
+ import re
+
+ return {w for w in re.findall(r"[a-z0-9]+", text.lower()) if (len(w) >= 3 or w in COOKBOOK_SYNONYMS) and w not in _STOP}
+
+
+def 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.
+
+ Measured 2026-08-26: the graphics prompt carried ``cookbook_text[:7000]`` of an 11,298-char
+ cookbook, so everything after the raymarching template (sky / stars, rain, bokeh, feedback,
+ PITFALLS) never reached the agent unless it called ``read_cookbook`` — and flash draws
+ what it was handed (an aurora as a comb of bars, twenty sparkles for a star field).
+ Here the header + ``always`` chapters go in first (4.4 k chars), then chapters ranked by
+ keyword overlap between the brief (+ plan key visuals) and the chapter heading / body, with
+ ``COOKBOOK_SYNONYMS`` as the strong signal, until ``budget`` is spent. A chapter is added
+ whole or not at all; the output keeps cookbook order. The default budget is the measured
+ need of a night-sky brief: always-set 4.4 k + Light phenomena 3.2 k + Gradient sky 1.3 k.
+ """
+ from codeverse.spatial.cookbook_tool import Section, find_section, split_sections
+
+ md = ctx.cookbook_text or ""
+ if not md.strip():
+ return ""
+ chapters: list[Section] = []
+ for s in split_sections(md): # fold ### sub-headings into their ## chapter
+ if s.level >= 3 and chapters:
+ chapters[-1] = Section(chapters[-1].level, chapters[-1].title, chapters[-1].body + s.body)
+ else:
+ chapters.append(s)
+ chosen: set[int] = {i for i, s in enumerate(chapters) if s.level < 2} # title / conventions header
+ for name in always:
+ sec = find_section(chapters, name)
+ if sec is not None:
+ chosen.add(chapters.index(sec))
+ brief_words = _words(brief)
+ wanted = {t.lower() for w in brief_words for t in COOKBOOK_SYNONYMS.get(w, ())}
+ scored: list[tuple[int, int]] = []
+ for i, s in enumerate(chapters):
+ if i in chosen:
+ continue
+ title = s.title.lower()
+ score = 4 * sum(1 for t in wanted if t in title)
+ score += 3 * len(brief_words & _words(s.title)) + len(brief_words & _words(s.body))
+ if score > 0:
+ scored.append((-score, i))
+ used = sum(len(chapters[i].body.rstrip()) + 2 for i in chosen)
+ for _, i in sorted(scored):
+ size = len(chapters[i].body.rstrip()) + 2
+ if used + size <= budget:
+ chosen.add(i)
+ used += size
+ return "\n\n".join(chapters[i].body.rstrip() for i in sorted(chosen))
+
+
def base_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:
"""Variables every tracks/*.j2 template may use (StrictUndefined → all present)."""
plan = ctx.plan
diff --git a/harness/tests/orchestrator_tracks/test_cookbook_excerpt.py b/harness/tests/orchestrator_tracks/test_cookbook_excerpt.py
new file mode 100644
index 00000000..28f885c7
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_cookbook_excerpt.py
@@ -0,0 +1,124 @@
+"""``select_cookbook_excerpt``: the graphics prompt carries the cookbook chapters its brief calls for.
+
+Measured 2026-08-26: ``cookbook_text[:7000]`` of an 11,298-char cookbook cut everything after
+the raymarching template (sky / stars, rain, bokeh, feedback, PITFALLS) out of every graphics
+prompt, and flash drew what it was handed — an aurora as a comb of bars, a star field of twenty
+sparkles. The selector hands over whole chapters, ranked by the brief, inside a budget.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+from codeverse.contracts.common import Language, Track
+from codeverse.prompts import PROMPTS_DIR, load_text
+from codeverse.spatial.cookbook_tool import split_sections
+from codeverse.tracks.prompting import COOKBOOK_ALWAYS, select_cookbook_excerpt
+
+AURORA = "Aurora borealis over a mountain ridge with a frozen lake, dense stars, green and violet curtains"
+RAIN = "rain drops running down a window at night, blurred city lights behind the glass"
+EXAMPLE = PROMPTS_DIR / "glsl_shader" / "examples" / "aurora_ridge.frag"
+
+
+def _ctx() -> SimpleNamespace:
+ return SimpleNamespace(cookbook_text=load_text("glsl_shader/cookbook.md"))
+
+
+def _titles(text: str) -> list[str]:
+ return [s.title for s in split_sections(text) if s.level == 2]
+
+
+def _chapter_bodies(md: str) -> dict[str, str]:
+ return {s.title: s.body.rstrip() for s in split_sections(md)}
+
+
+def test_real_cookbook_parses_into_chapters() -> None:
+ secs = [s for s in split_sections(load_text("glsl_shader/cookbook.md")) if s.level == 2]
+ assert len(secs) >= 10
+ titles = [s.title for s in secs]
+ assert any(t.startswith("Light phenomena") for t in titles)
+ assert any(t.startswith("Gradient sky") for t in titles)
+ assert any(t.startswith("PITFALLS") for t in titles)
+
+
+def test_aurora_brief_selects_light_and_sky_within_budget() -> None:
+ ctx = _ctx()
+ text = select_cookbook_excerpt(ctx, AURORA)
+ titles = _titles(text)
+ assert any(t.startswith("Light phenomena") for t in titles), titles
+ assert any(t.startswith("Gradient sky") for t in titles), titles
+ assert len(text) <= 9000
+ assert "float curtain(vec2 p, float t, float seed, out float k)" in text
+ assert "float stars(vec2 p, float density, float keep)" in text
+ # never split: every chapter in the excerpt is the whole chapter from the cookbook
+ whole = _chapter_bodies(ctx.cookbook_text)
+ for s in split_sections(text):
+ assert s.body.rstrip() == whole[s.title], s.title
+ # deterministic, cookbook order
+ assert text == select_cookbook_excerpt(ctx, AURORA)
+ order = [t for t in whole if t in titles]
+ assert titles == order
+
+
+def test_rain_brief_selects_rain() -> None:
+ text = select_cookbook_excerpt(_ctx(), RAIN)
+ titles = _titles(text)
+ assert any(t.startswith("Rain") for t in titles), titles
+ assert any(t.startswith("Bokeh") for t in titles), titles
+ assert len(text) <= 9000
+
+
+def test_always_chapters_present_for_any_brief() -> None:
+ ctx = _ctx()
+ for brief in ("", "xyzzy plugh", AURORA, RAIN, "a raymarched temple corridor with fog"):
+ text = select_cookbook_excerpt(ctx, brief)
+ assert text.startswith("# glsl_shader cookbook"), brief # the p / uv conventions header
+ titles = _titles(text)
+ for name in COOKBOOK_ALWAYS:
+ assert any(name.lower() in t.lower() for t in titles), (brief, name)
+ assert select_cookbook_excerpt(SimpleNamespace(cookbook_text=""), AURORA) == ""
+
+
+def test_budget_never_cuts_a_chapter() -> None:
+ ctx = _ctx()
+ small = select_cookbook_excerpt(ctx, AURORA, budget=6000)
+ whole = _chapter_bodies(ctx.cookbook_text)
+ for s in split_sections(small):
+ assert s.body.rstrip() == whole[s.title], s.title
+ assert not any(t.startswith("Light phenomena") for t in _titles(small)) # 3.2 k does not fit in 1.6 k of room
+ assert any(t.startswith("Gradient sky") for t in _titles(small)) # the 1.3 k chapter that does
+
+
+def test_graphics_prompt_context_uses_the_selector(monkeypatch) -> None:
+ from codeverse.tracks import graphics_steps
+
+ seen: dict[str, str] = {}
+
+ def fake(ctx, brief, **kw):
+ seen["brief"] = brief
+ return "EXCERPT"
+
+ monkeypatch.setattr(graphics_steps, "select_cookbook_excerpt", fake)
+ ctx = SimpleNamespace(plan=None, spec=SimpleNamespace(prompt="an aurora", constraints=None, must=[], must_not=[], dims={},
+ reference_images=[], reference_notes=""),
+ track=Track.GRAPHICS, language=Language.GLSL_SHADER,
+ contract_text="", cookbook_rel="", cookbook_text="", tool_cards="", single_shot=True,
+ runtime=SimpleNamespace(entry_globs=()))
+ monkeypatch.setattr(graphics_steps, "constraints_text", lambda spec: "")
+ monkeypatch.setattr(graphics_steps, "reference_note", lambda ctx: "")
+ monkeypatch.setattr(graphics_steps, "acceptance_lines", lambda plan: "")
+ d = graphics_steps.graphics_prompt_context(ctx)
+ assert d["cookbook_excerpt"] == "EXCERPT" and seen["brief"].startswith("an aurora")
+
+
+def test_aurora_example_ships_and_composes() -> None:
+ from codeverse.languages.glsl_shader.wrap import compose
+
+ assert EXAMPLE.is_file(), EXAMPLE
+ src = EXAMPLE.read_text()
+ assert "void mainImage(" in src and "float curtain(" in src
+ composed = compose(src)
+ assert "mainImage" in composed.source and "u_time" in composed.source
+ assert "examples/aurora_ridge.frag" in load_text("glsl_shader/cookbook.md")
+ assert Path(EXAMPLE).suffix == ".frag"