Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
feat(design-agent): autonomous pipeline with in-run visual verification — render → critique → guarded correction → re-verify
Ashiq Hussain Mir2b263e285a4b
diff --git a/research/AUTONOMOUS-AGENT-RESEARCH.md b/research/AUTONOMOUS-AGENT-RESEARCH.mdnew file mode 100644index 0000000..6f52685--- /dev/null+++ b/research/AUTONOMOUS-AGENT-RESEARCH.md@@ -0,0 +1,149 @@+# Autonomous agent research → Canvix DesignAgent (24 Nov 2026)++**Question:** how do production autonomous agents actually work, and which of+those mechanics should Canvix adopt so its AI can produce professional designs+by itself?++Three sources were read in full (not search-snippet level):++1. **IBM, "What is a ReAct Agent?"** — the canonical thought→action→observation loop.+2. **OpenAI Agents SDK docs, "Agent orchestration"** — production orchestration patterns (LLM-orchestrated vs code-orchestrated, agents-as-tools, handoffs, guardrails, evaluator loops).+3. **PosterGen: Aesthetic-Aware Multi-Modal Paper-to-Poster Generation (CVPR 2026, arXiv 2508.17188)** — a multi-agent LLM design pipeline scored 4.43/5 aesthetics vs human-designed 4.27, with ablations isolating what each stage contributes.++Plus secondary leads (search level only, not read in depth): Reflexion+(self-critique memory), LangGraph, tldraw's repeat-pattern cycle detection+(which this repo's `agent/protocol.ts` already credits for its cycle guard).++## The patterns that matter, and what Canvix does with each++### P1 — The agent loop (ReAct): think → act → observe → repeat++Mechanics: a tool registry (name + description + input schema), a scratchpad+the model appends to, observations fed back after every action, and hard+termination guards (iteration cap; a "no progress" stop). The loop's power is+that each action's result reshapes the next step.++**Canvix already has this** — `src/lib/agent/loop.ts` is a ReAct-style chat+loop over `AGENT_TOOLS` with resource guards (strikes / cycle-repeat / idle),+risk-tiered tools and fail-closed acks. That loop is for interactive editing.++**Adoption for design generation:** the generation pipeline keeps the loop's+*discipline* (registry, observations, guards, bounded termination) but is+CODE-orchestrated (P2) rather than free-form.++### P2 — Orchestrate in code around the LLM seams (OpenAI Agents SDK)++The SDK's own guidance: LLM-orchestrated agents (the model routes itself) are+for open-ended tasks; **code orchestration** — your code decides what runs,+in what order — is "more deterministic and predictable" on speed, cost and+performance. The two mix. The concrete code-orchestration patterns it lists:+chaining (research → outline → write → critique → refine), the **evaluator+loop** (a producer agent + an evaluator agent; stop when criteria are met),+structured-output routing, and parallel fan-out.++**Canvix adoption:** the DesignAgent pipeline is deterministic TypeScript that+calls the model only at the decision seams — plan, revise, critique. Stages,+order, retries and termination are code, not model whims. This also matches+Canvix's funding thesis (determinism and verifiability over vibes) and keeps+the exact-text/color contract enforceable at every seam.++### P3 — Specialist stages with the design principles EMBEDDED (PosterGen)++PosterGen does not ask one model to "make a poster." It runs a chain of+single-purpose agents — Parser → Curator → Layout → Color → Font — where+design principles (narrative roles, column rules, WCAG contrast, 3-tier+emphasis) are **built into each stage's logic**, then a deterministic renderer+emits the file. Its ablation is the argument: curation alone scores 3.57/5;+adding the layout stage lifts it to 4.03; adding styling to 4.53.++**Canvix adoption:** this is exactly the DesignSpec split — the model chooses+semantics (blocks, copy, seeds), the deterministic engine owns geometry, color+math and type scale. The engine's composition builders ARE the embedded+principles. The vocabulary now covers every declared kind (hero,+feature-cards, stat-row, mockup, timeline, gallery, footer) with a dedicated+deterministic builder.++### P4 — The evaluator loop / Reflexion: fail → feedback → revise, bounded++Mechanics: a deterministic evaluator produces structured failures; the+failures are fed back to the producer as observations; the producer revises;+repeat up to a bound; if still failing, report honestly instead of+hallucinating success. PosterGen's variant: the Balancer reads utilization+analysis and conservatively adjusts; pure text-to-image approaches score 2.41+(content hallucination) — the loop is what separates 2.41 from 4.4.++**Canvix adoption:** `compileSpec` checks (exact texts, colors, wrap-aware+fit, overlap, contrast) plus the pipeline's **brief-conformance** check (the+evaluator the engine cannot run: brief→spec fidelity) are the evaluator. The+pipeline feeds `failures[]` back to the planner as a revision prompt, bounded+(default 3 revisions), with cycle detection (an unchanged spec is not+progress) and an honest `failed-honestly` outcome instead of a fake pass.++### P5 — Grounded critique on the REAL render (VLM-as-judge), not the model's imagination++Mechanics: render first, screenshot, THEN have a vision model critique the+pixels; calibrate the rubric with positive examples at 4-5 and defect examples+at 1-3 (VLM judges are generous); two independent judges; strict anchors.+Humans judge ~15% harder than VLM judges — never let the VLM score be the+whole claim.++**Canvix adoption:** the shipped agent already has grounded vision critique+(the `capture` event, fail-closed when unavailable). The pipeline now runs the+same stage INSIDE the run: after the checks pass it renders, critiques the+pixels, and can trigger one more revision round from the findings. The+hierarchy is absolute: **checks outrank critique** — a critique-revision is+only accepted if it also passes every deterministic check and actually+reduces the actionable findings; otherwise the previous passing design is+kept and the outcome is disclosed. Critique with no renderer or vision seam+is reported as `unavailable`, never faked. The acceptance harness exercises+it with a real VLM (z-ai `vision`); production runs BYOK.++### P6 — Estimate-vs-renderer gap: measure, don't guess (PosterGen Alg. 1)++PosterGen binary-searches the text-box height the real renderer will not+auto-shrink — the data model and the renderer disagree, and the pipeline must+measure the boundary. **Canvix already lives this:** `textFits` is+wrap-aware at the plan-route estimate, and the acceptance harness verifies+presence against the RENDERED SVG (tspan-aware), not the model's claim.++## What Canvix deliberately does NOT adopt++- **Handoffs / multi-agent conversations for generation** — one planner seam+ with a fixed stage order is cheaper, deterministic and debuggable. The SDK+ docs themselves recommend specialists as *tools*, not as free conversational+ peers, for predictable pipelines.+- **Unbounded autonomy** — the repo's own guard philosophy (machine+ protection, not product caps) is kept: revision rounds are bounded, cycles+ are detected, failures are honest, cancellation is honored.+- **Pure text-to-image generation** — PosterGen measured it at 2.41/5 with+ garbled text; Canvix's exact-text contract exists precisely to avoid that+ failure class.++## The DesignAgent architecture that follows++```+prompt ──► extract-brief (deterministic)+ ─► plan-spec (MODEL seam 1: brief + toolbox catalog → DesignSpec JSON)+ ─► parse-spec (deterministic, honest failure object)+ ─► compile-spec + brief-conformance (deterministic evaluator)+ ─► [failures → revise-spec (MODEL seam 2)] × ≤3, cycle-guarded+ ─► visual verification (P0):+ render (DesignRenderer) → VLM critique (MODEL seam 3, advisory)+ → P1/P2 findings → one guarded revision → re-compile (must stay+ checks-green, else the previous design is kept) → re-render →+ verify → report improvement honestly+ ─► run report: stages, model calls, revisions, visual passes,+ outcome, honest gaps+```++The model can choose ANY semantic the toolbox vocabulary expresses; it cannot+choose geometry, cannot touch required copy, cannot mark itself done. Every+function the agent "has" is in the registry (`src/lib/design-agent/tools.ts`)+— the registry is the capability surface, the pipeline is the discipline.++## Source list++- https://www.ibm.com/think/topics/react-agent — ReAct pattern, loop mechanics+- https://openai.github.io/openai-agents-python/multi_agent/ — orchestration styles, evaluator loop, guardrails+- https://arxiv.org/html/2508.17188v2 — PosterGen (CVPR 2026): staged agents, embedded principles, ablations, VLM-judge calibration+- Search-level leads (not read in full): Reflexion (Shinn et al.), LangGraph docs, tldraw agent repeat-pattern writeupdiff --git a/scripts/designspec-agent-run.ts b/scripts/designspec-agent-run.tsnew file mode 100644index 0000000..2d1f2ef--- /dev/null+++ b/scripts/designspec-agent-run.ts@@ -0,0 +1,192 @@+// ─────────────────────────────────────────────────────────────+// DesignAgent real-model acceptance run (Phase B v2, 24 Nov 2026).+//+// Drives the autonomous pipeline end-to-end with REAL seams:+// · planner: z-ai chat (GLM) — the plan/revise seam+// · renderer: Chromium + the app's REAL vector export pipeline+// (exportPageToSVG) — the DesignRenderer seam+// · critic: z-ai vision (VLM) — the critique seam+//+// With --visual (default) the pipeline runs its FULL loop including+// the in-run visual verification stage: render → critique →+// (guarded) revision → re-compile → re-render → verify. Everything+// is recorded in agent-report.json.+//+// Usage:+// bun scripts/designspec-agent-run.ts run <promptFile> <outDir> [--visual|--no-visual]+// bun scripts/designspec-agent-run.ts recompile <outDir>+// bun scripts/designspec-agent-run.ts critique <outDir>+//+// Build the browser bundle first if missing:+// bun build scripts/designspec-browser-entry.ts --outfile scripts/designspec-browser-bundle.js --target browser+// ─────────────────────────────────────────────────────────────++import { execFileSync } from 'node:child_process'+import { mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs'+import path from 'node:path'+import { chromium } from 'playwright'+import { runDesignAgent, type DesignRenderer } from '@/lib/design-agent/pipeline'+import { parseCritiqueResponse, type DesignAgentModel, type CritiqueRequest } from '@/lib/design-agent/model'+import { PLANNER_SYSTEM, planUserPrompt, revisionUserPrompt, CRITIQUE_SYSTEM, critiqueUserPrompt } from '@/lib/design-agent/prompts'+import { compileSpec } from '@/lib/design-engine/compile'+import type { PageData } from '@/lib/types'+import type { DesignSpec } from '@/lib/design-spec/types'++const TMP = '/tmp/designspec-agent'++/** CLI-backed planner: z-ai chat, OpenAI-shaped output. */+function cliPlan(prompt: string, system: string): string {+ const out = `${TMP}-chat.json`+ execFileSync('z-ai', ['chat', '-p', prompt, '-s', system, '-o', out], { stdio: ['ignore', 'ignore', 'ignore'] })+ const reply = JSON.parse(readFileSync(out, 'utf-8')) as { choices?: { message?: { content?: string } }[] }+ return reply.choices?.[0]?.message?.content ?? ''+}++/** CLI-backed VLM critique: z-ai vision (no --system flag — folded+ * into the prompt). */+function cliVision(prompt: string, image: string): string {+ const out = `${TMP}-vision.json`+ execFileSync('z-ai', ['vision', '-p', prompt, '-i', image, '-o', out], { stdio: ['ignore', 'ignore', 'ignore'] })+ const reply = JSON.parse(readFileSync(out, 'utf-8')) as { choices?: { message?: { content?: string } }[] }+ return reply.choices?.[0]?.message?.content ?? ''+}++const cliModel: DesignAgentModel = {+ plan: async (req) =>+ cliPlan(+ req.feedback ? revisionUserPrompt(req.feedback) : planUserPrompt(req.brief),+ PLANNER_SYSTEM,+ ),+ critique: async (req: CritiqueRequest) =>+ cliVision(`${CRITIQUE_SYSTEM}\n\n${critiqueUserPrompt(req.brief)}`, req.image),+}++/** Browser-backed renderer: the app's REAL export pipeline+ * (exportPageToSVG) inside real Chromium, screenshotted to a PNG the+ * VLM can read. One browser for the whole run; each render call+ * re-embeds the current pages (the loop re-renders after revisions). */+async function makeRenderer(outDir: string): Promise<{ renderer: DesignRenderer; close: () => Promise<void> }> {+ const browser = await chromium.launch()+ const page = await browser.newPage({ viewport: { width: 1400, height: 1800 } })+ await page.setContent(`<!doctype html><html><head><meta charset="utf-8">+ <style>body{margin:0;background:#fff;padding:0}+ #host svg{display:block;background:#fff}</style></head>+ <body><div id="host"></div></body></html>`)+ await page.addScriptTag({ path: path.resolve(process.cwd(), 'scripts/designspec-browser-bundle.js') })+ let shot = 0+ const renderer: DesignRenderer = {+ render: async (pages: PageData[], spec: DesignSpec) => {+ try {+ shot += 1+ await page.evaluate(+ ({ pageData, width, height }) => {+ const svg = (window as unknown as { __canvixExportPageToSVG: (p: unknown, w: number, h: number) => string })+ .__canvixExportPageToSVG(pageData, width, height)+ document.getElementById('host')!.innerHTML = svg+ },+ { pageData: pages[0], width: spec.format.width, height: spec.format.height },+ )+ const host = await page.$('#host svg')+ if (!host) return null+ const png = path.join(outDir, shot === 1 ? 'rendered.png' : `rendered-r${shot}.png`)+ await host.screenshot({ path: png })+ // also keep the final SVG for the artifacts+ writeFileSync(path.join(outDir, 'rendered.svg'), await page.evaluate(() => document.getElementById('host')!.innerHTML))+ return { image: png }+ } catch {+ return null+ }+ },+ }+ return { renderer, close: () => browser.close() }+}++const phase = process.argv[2]+const arg = process.argv[3]+const outDirArg = process.argv[4]+const visualFlag = process.argv.includes('--visual')+const noVisualFlag = process.argv.includes('--no-visual')++if (phase !== 'run' && phase !== 'critique' && phase !== 'recompile') {+ console.error('usage: bun scripts/designspec-agent-run.ts run <promptFile> <outDir> [--visual|--no-visual] | recompile <outDir> | critique <outDir>')+ process.exit(2)+}++if (phase === 'recompile') {+ // deterministic: recompile a saved spec through the (possibly+ // updated) engine — no model calls, byte-level reproducibility+ const outDir = arg+ const spec = JSON.parse(readFileSync(path.join(outDir, 'spec.json'), 'utf-8'))+ const result = compileSpec(spec)+ writeFileSync(path.join(outDir, 'pages.json'), JSON.stringify(result.pages, null, 2))+ writeFileSync(path.join(outDir, 'checks.json'), JSON.stringify(result.checks, null, 2))+ console.log(`recompiled: checks ${result.checks.passed ? 'PASS' : 'FAIL'} · warnings: ${result.warnings.length}`)+ process.exit(result.checks.passed ? 0 : 1)+}++if (phase === 'run') {+ const prompt = readFileSync(arg, 'utf-8')+ const outDir = outDirArg+ mkdirSync(outDir, { recursive: true })+ const wantVisual = !noVisualFlag && existsSync(path.resolve(process.cwd(), 'scripts/designspec-browser-bundle.js'))++ const started = Date.now()+ const visual = wantVisual ? await makeRenderer(outDir) : undefined+ const run = await runDesignAgent({+ prompt,+ model: cliModel,+ renderer: visual?.renderer,+ limits: { maxRevisions: 3, maxVisualPasses: 1 },+ })+ const elapsedMs = Date.now() - started+ if (visual) await visual.close()++ // artifacts: the same contract the render script consumes+ if (run.report.spec) writeFileSync(path.join(outDir, 'spec.json'), JSON.stringify(run.report.spec, null, 2))+ if (run.pages) writeFileSync(path.join(outDir, 'pages.json'), JSON.stringify(run.pages, null, 2))+ if (run.checks) writeFileSync(path.join(outDir, 'checks.json'), JSON.stringify(run.checks, null, 2))+ writeFileSync(+ path.join(outDir, 'agent-report.json'),+ JSON.stringify({ ...run.report, outcome: run.outcome, warnings: run.warnings, briefConformance: run.briefConformance, elapsedMs }, null, 2),+ )++ console.log(`══ DesignAgent run ══`)+ console.log(`outcome: ${run.outcome}`)+ console.log(`model calls: ${run.report.modelCalls} · revisions: ${run.report.revisionRounds} · cycle guard: ${run.report.cycleGuard}`)+ console.log(`visual: ${run.report.visualVerification} (${run.report.visualPasses.map((p) => p.action).join(', ') || 'no passes'})`)+ console.log(`elapsed: ${elapsedMs} ms`)+ for (const s of run.report.stages) {+ console.log(` ${s.ok ? 'PASS' : 'FAIL'} ${s.name}${s.modelCall ? ' [model]' : ''}${s.detail ? ` — ${s.detail.slice(0, 110)}` : ''}`)+ }+ if (run.briefConformance.length) console.log(`brief failures:\n ${run.briefConformance.join('\n ')}`)+ if (run.warnings.length) console.log(`warnings:\n ${run.warnings.join('\n ')}`)+ for (const p of run.report.visualPasses) {+ if (p.issues.length) {+ console.log(`critique pass ${p.round} — ${p.action}:`)+ for (const i of p.issues) console.log(` ${i.severity} ${i.issue.slice(0, 110)}`)+ }+ }+ process.exit(run.outcome === 'passed' ? 0 : 1)+}++if (phase === 'critique') {+ // standalone post-hoc critique of an existing rendered.png,+ // merged into agent-report.json (for renders produced by+ // designspec-render.cjs rather than the in-run renderer)+ const outDir = arg+ const report = JSON.parse(readFileSync(path.join(outDir, 'agent-report.json'), 'utf-8')) as Record<string, unknown>+ const png = path.join(outDir, 'rendered.png')+ if (!existsSync(png)) {+ console.log('no rendered.png — critique skipped (fail-closed)')+ process.exit(0)+ }+ const brief = report.brief as Parameters<typeof critiqueUserPrompt>[0]+ const raw = cliVision(`${CRITIQUE_SYSTEM}\n\n${critiqueUserPrompt(brief)}`, png)+ const critique = parseCritiqueResponse(raw)+ report.vlmCritique = critique ?? { summary: 'critique reply unparseable — discarded', issues: [], advisory: true, failedClosed: true }+ report.vlmCritiqueRaw = raw+ writeFileSync(path.join(outDir, 'agent-report.json'), JSON.stringify(report, null, 2))+ console.log(`══ VLM critique (advisory, standalone) ══`)+ console.log(`summary: ${(critique?.summary ?? '(unparseable — fail-closed)').slice(0, 300)}`)+ for (const i of critique?.issues ?? []) console.log(` ${i.severity} ${i.issue.slice(0, 120)}${i.fix ? ` → ${i.fix.slice(0, 80)}` : ''}`)+}diff --git a/src/lib/design-agent/model.ts b/src/lib/design-agent/model.tsnew file mode 100644index 0000000..30c7a60--- /dev/null+++ b/src/lib/design-agent/model.ts@@ -0,0 +1,110 @@+// ─────────────────────────────────────────────────────────────+// DesignAgent · the model seam (Phase B, 24 Nov 2026).+//+// The autonomous design pipeline's ONLY model interfaces. Everything+// else is deterministic code (see tools.ts / pipeline.ts and+// research/AUTONOMOUS-AGENT-RESEARCH.md — the OpenAI Agents SDK+// "code orchestration" pattern: the model sits at decision seams,+// stages/order/termination are code, not model choice).+//+// Two seams:+// plan — brief (+ revision feedback) → DesignSpec JSON text+// critique — rendered image → advisory issues JSON text (optional+// capability; grounded visual review, fail-closed when+// unavailable)+//+// Production (BYOK provider adapters) and the sandbox acceptance+// harness (z-ai CLI) both implement this interface; unit tests use a+// scripted model. The pipeline NEVER trusts the raw text — it parses+// and validates everything deterministically.+// ─────────────────────────────────────────────────────────────++import type { DesignBrief } from '@/lib/agent/brief'+import type { DesignSpec } from '@/lib/design-spec/types'++/** Feedback for one revision round (Reflexion-style: deterministic+ * evaluator output returned to the planner as an observation). */+export interface RevisionFeedback {+ round: number+ /** compile check failures — the hard reasons the spec failed */+ failures: string[]+ /** non-fatal notes (palette defaults, density, seed placement) */+ warnings: string[]+ /** the spec that was just tried, so the model revises rather than+ * restarts from zero */+ priorSpec: DesignSpec+ /** where this round's failures came from: the deterministic+ * checks (brief conformance / compile), or the advisory vision+ * critique of the rendered page */+ origin: 'checks' | 'critique'+}++export interface PlanRequest {+ brief: DesignBrief+ /** the toolbox catalog (tools.ts) — the model's capability surface */+ toolbox: string+ feedback?: RevisionFeedback+}++export interface CritiqueIssue {+ severity: 'P1' | 'P2' | 'P3'+ issue: string+ fix?: string+}++export interface CritiqueResult {+ summary: string+ issues: CritiqueIssue[]+ /** critiques are ADVISORY: they can trigger a revision round but+ * never override the deterministic compile checks */+ advisory: true+}++export interface CritiqueRequest {+ brief: DesignBrief+ /** how the adapter receives the render (a path, URL or data URL —+ * adapter-specific; the pipeline only passes it through) */+ image: string+}++export interface DesignAgentModel {+ /** plan a DesignSpec. Returns raw model text — the pipeline owns+ * parsing/validation. Receives revision feedback on later rounds. */+ plan(req: PlanRequest): Promise<string>+ /** grounded critique of the REAL render (optional capability). */+ critique?(req: CritiqueRequest): Promise<string>+}++/** Parse a critique reply into the advisory result. Tolerant of+ * markdown fences and prose around the JSON; a reply without usable+ * JSON is a null — the caller discloses that critique failed rather+ * than inventing issues (fail-closed, same contract as the shipped+ * agent's vision path). */+export function parseCritiqueResponse(raw: string): CritiqueResult | null {+ const cleaned = raw.replace(/```(?:json)?/gi, '')+ const start = cleaned.indexOf('{')+ const end = cleaned.lastIndexOf('}')+ if (start === -1 || end <= start) return null+ let obj: Record<string, unknown> | null = null+ try {+ obj = JSON.parse(cleaned.slice(start, end + 1)) as Record<string, unknown>+ } catch {+ return null+ }+ if (!obj || typeof obj !== 'object') return null+ const issuesRaw = Array.isArray(obj.issues) ? obj.issues : []+ const issues: CritiqueIssue[] = []+ for (const i of issuesRaw) {+ if (typeof i !== 'object' || i === null) continue+ const it = i as Record<string, unknown>+ const severity = it.severity === 'P1' || it.severity === 'P2' || it.severity === 'P3' ? it.severity : 'P3'+ const issue = typeof it.issue === 'string' ? it.issue : ''+ if (!issue) continue+ issues.push({ severity, issue, fix: typeof it.fix === 'string' ? it.fix : undefined })+ }+ return {+ summary: typeof obj.summary === 'string' ? obj.summary : '',+ issues,+ advisory: true,+ }+}diff --git a/src/lib/design-agent/pipeline.test.ts b/src/lib/design-agent/pipeline.test.tsnew file mode 100644index 0000000..70b96e0--- /dev/null+++ b/src/lib/design-agent/pipeline.test.ts@@ -0,0 +1,401 @@+import { describe, expect, it } from 'vitest'+import { runDesignAgent, type DesignRenderer } from './pipeline'+import { runDesignTool } from './tools'+import { parseCritiqueResponse, type DesignAgentModel, type CritiqueResult } from './model'+import { compileSpec } from '@/lib/design-engine/compile'++/**+ * Phase B: the autonomous pipeline proven with a SCRIPTED model —+ * the loop's self-correction, honesty, guards AND the visual+ * verification stage are deterministic behavior, so they are tested+ * without any network. The real-model acceptance run+ * (scripts/designspec-agent-run.ts + z-ai CLI) exercises the same+ * seams end-to-end.+ */++const PROMPT = [+ 'Create a poster for a harvest festival.',+ 'The poster must show these exact lines:',+ '"Kashmir Apple Harvest Festival 2026",',+ '"Oct 18 · Dachigam Grounds · Srinagar",',+ '"Entry Free — 10 AM to 6 PM".',+ 'Use the colors #1B5E20 and #F9A825 somewhere.',+ 'Size 1080x1350. Warm autumn feel, bold and inviting.',+].join(' ')++function specJson(headline: string, body: string, extra: Record<string, unknown> = {}): string {+ return JSON.stringify({+ version: 'v2',+ name: 'scripted poster',+ format: { width: 1080, height: 1350 },+ palette: { seeds: ['#1B5E20', '#F9A825'], mood: 'warm' },+ typography: { scale: 1.25 },+ blocks: [+ {+ kind: 'hero',+ weight: 4,+ content: [+ { role: 'headline', source: 'user-required', text: headline },+ { role: 'subline', source: 'user-required', text: body },+ { role: 'cta', source: 'user-required', text: 'Entry Free — 10 AM to 6 PM' },+ ],+ overlap: 'none',+ },+ ],+ ...extra,+ })+}++const GOOD = specJson('Kashmir Apple Harvest Festival 2026', 'Oct 18 · Dachigam Grounds · Srinagar')+// round-1 mistake: the model paraphrased the required headline+const PARAPHRASED = specJson('Kashmir Apple Harvest Festival ’26', 'Oct 18 · Dachigam Grounds · Srinagar')++/** A scripted planner: plays back replies in order, recording what+ * it was asked (so tests can assert the feedback reached the model). */+function scriptedModel(replies: string[], critiques: string[] = []) {+ const planInputs: { feedback?: { failures: string[]; priorSpec: unknown; origin?: string } }[] = []+ const critiqueInputs: { image: string }[] = []+ let critiqueIdx = 0+ const model: DesignAgentModel = {+ plan: async (req) => {+ planInputs.push({ feedback: req.feedback ? { failures: req.feedback.failures, priorSpec: req.feedback.priorSpec, origin: req.feedback.origin } : undefined })+ return replies[Math.min(planInputs.length - 1, replies.length - 1)]+ },+ critique: async (req) => {+ critiqueInputs.push({ image: req.image })+ return critiques[Math.min(critiqueIdx++, critiques.length - 1)]+ },+ }+ return { model, planInputs, critiqueInputs }+}++/** A scripted renderer: returns a fake image ref per call. */+function scriptedRenderer(images: (string | null)[] = ['render://page-1']): DesignRenderer {+ let i = 0+ return {+ render: async () => ({ image: images[Math.min(i++, images.length - 1)] ?? null }) as { image: string } | null,+ }+}++function critiqueJson(issues: { severity: string; issue: string; fix?: string }[]): string {+ return JSON.stringify({ summary: 'scripted critique', issues })+}++describe('DesignAgent pipeline: self-correction (evaluator loop)', () => {+ it('a check failure is fed back as a revision prompt and the fixed spec passes', async () => {+ const { model, planInputs } = scriptedModel([PARAPHRASED, GOOD])+ const run = await runDesignAgent({ prompt: PROMPT, model })++ expect(run.outcome).toBe('passed')+ expect(run.report.modelCalls).toBe(2)+ expect(run.report.revisionRounds).toBe(1)+ expect(run.checks?.passed).toBe(true)+ expect(run.briefConformance).toEqual([])+ // the feedback round carried the exact failure and the prior spec+ expect(planInputs).toHaveLength(2)+ expect(planInputs[1].feedback?.failures.join(' ')).toMatch(/required text missing from the spec/)+ expect(JSON.stringify(planInputs[1].feedback?.priorSpec)).toContain('Festival ’26')+ // and the final page carries the exact required texts+ const texts = run.pages?.[0].elements.filter((el) => el.type === 'text').map((el) => (el as { text: string }).text) ?? []+ expect(texts).toContain('Kashmir Apple Harvest Festival 2026')+ // the run report records both rounds — the brief-conformance+ // stage is the one that caught the paraphrase in round 1+ expect(run.report.stages.filter((s) => s.name.startsWith('brief-conformance')).map((s) => s.ok)).toEqual([false, true])+ })++ it('a parse hiccup mid-loop is recoverable: feedback on the prior spec, not a dead end', async () => {+ const { model } = scriptedModel([PARAPHRASED, 'sorry here is your spec: {"version":"v2" (oops', GOOD])+ const run = await runDesignAgent({ prompt: PROMPT, model })++ expect(run.outcome).toBe('passed')+ expect(run.report.modelCalls).toBe(3)+ expect(run.report.revisionRounds).toBe(2)+ expect(run.report.stages.some((s) => s.detail.includes('parse failed'))).toBe(true)+ })+})++describe('DesignAgent pipeline: honesty and guards', () => {+ it('repeating the same broken spec trips the cycle guard — no silent looping', async () => {+ const { model } = scriptedModel([PARAPHRASED, PARAPHRASED])+ const run = await runDesignAgent({ prompt: PROMPT, model })++ expect(run.outcome).toBe('guard-cycled')+ expect(run.report.cycleGuard).toBe(true)+ expect(run.warnings.join(' ')).toMatch(/repeated its spec verbatim/)+ // evidence is kept: the brief failure is still reported (the+ // engine's spec→page checks can be clean while the SPEC itself+ // dropped a requirement — exactly why the agent layer runs its+ // own conformance check)+ expect(run.briefConformance.join(' ')).toMatch(/required text missing from the spec/)+ })++ it('distinct-but-never-fixed specs exhaust the revision budget and fail honestly', async () => {+ const replies = [0, 1, 2, 3, 4].map((i) => specJson(`Kashmir Attempt Number ${i}`, 'Oct 18 · Dachigam Grounds · Srinagar'))+ const { model } = scriptedModel(replies)+ const run = await runDesignAgent({ prompt: PROMPT, model })++ expect(run.outcome).toBe('failed-honestly')+ expect(run.report.revisionRounds).toBe(3) // DEFAULT_LIMITS.maxRevisions+ expect(run.report.modelCalls).toBe(4) // initial plan + 3 revisions+ expect(run.warnings.join(' ')).toMatch(/revision budget exhausted/)+ // never a fake pass, and the failed pages stay as evidence+ expect(run.briefConformance.length).toBeGreaterThan(0)+ expect(run.pages?.[0].elements.length).toBeGreaterThan(0)+ })++ it('a first reply that is not JSON at all fails honestly (nothing to revise against)', async () => {+ const { model } = scriptedModel(['I will make you a beautiful poster!'])+ const run = await runDesignAgent({ prompt: PROMPT, model })++ expect(run.outcome).toBe('failed-honestly')+ expect(run.report.modelCalls).toBe(1)+ expect(run.warnings.join(' ')).toMatch(/no JSON object|parse/i)+ })++ it('caller cancellation aborts before any further model call', async () => {+ const { model, planInputs } = scriptedModel([PARAPHRASED, GOOD])+ const signal = { aborted: true }+ const run = await runDesignAgent({ prompt: PROMPT, model, signal })++ expect(run.outcome).toBe('aborted')+ expect(run.report.modelCalls).toBe(0)+ expect(planInputs).toHaveLength(0)+ expect(run.warnings.join(' ')).toMatch(/cancelled/)+ })+})++describe('DesignAgent pipeline: visual verification (P0 stage)', () => {+ it('renders, critiques, corrects once, re-renders and reports improvement', async () => {+ // plan: paraphrase → fix. critique 1: one P2; critique 2 (verify): clean.+ const { model, planInputs } = scriptedModel(+ [PARAPHRASED, GOOD, GOOD],+ [+ critiqueJson([{ severity: 'P2', issue: 'subline crowds the CTA', fix: 'raise hero weight' }]),+ critiqueJson([]),+ ],+ )+ const run = await runDesignAgent({+ prompt: PROMPT,+ model,+ renderer: scriptedRenderer(['render://page-1', 'render://page-2']),+ })++ expect(run.outcome).toBe('passed')+ expect(run.report.visualVerification).toBe('improved')+ expect(run.report.visualPasses).toHaveLength(1)+ expect(run.report.visualPasses[0].action).toBe('revised')+ // the critique-origin revision carried the finding+ const critiqueFeedback = planInputs.find((p) => p.feedback?.origin === 'critique')+ expect(critiqueFeedback?.feedback?.failures.join(' ')).toMatch(/subline crowds the CTA/)+ // plan calls: 2 (checks rounds) + 1 (critique revision) = 3; critiques: 2+ expect(run.report.modelCalls).toBe(5)+ // the revised design still passes every deterministic check+ expect(run.checks?.passed).toBe(true)+ expect(run.briefConformance).toEqual([])+ })++ it('a clean critique marks the run verified with no extra revision', async () => {+ const { model, planInputs } = scriptedModel([PARAPHRASED, GOOD], [critiqueJson([{ severity: 'P3', issue: 'minor polish' }])])+ const run = await runDesignAgent({ prompt: PROMPT, model, renderer: scriptedRenderer() })++ expect(run.outcome).toBe('passed')+ expect(run.report.visualVerification).toBe('verified')+ expect(run.report.visualPasses[0].action).toBe('accepted-as-is')+ // P3 alone is not actionable: no extra plan call beyond the 2 check rounds+ expect(run.report.modelCalls).toBe(3)+ expect(planInputs).toHaveLength(2)+ })++ it('a critique revision that breaks the deterministic checks is REJECTED — the passing design is kept', async () => {+ // round 3 (critique revision) returns a spec that drops a required text again+ const { model } = scriptedModel(+ [PARAPHRASED, GOOD, PARAPHRASED],+ [critiqueJson([{ severity: 'P1', issue: 'huge empty middle band' }])],+ )+ const run = await runDesignAgent({ prompt: PROMPT, model, renderer: scriptedRenderer() })++ expect(run.outcome).toBe('passed')+ expect(run.report.visualPasses[0].action).toBe('rejected-by-checks')+ // the KEPT design is the one that passed the checks+ const texts = run.pages?.[0].elements.filter((el) => el.type === 'text').map((el) => (el as { text: string }).text) ?? []+ expect(texts).toContain('Kashmir Apple Harvest Festival 2026')+ expect(run.report.stages.some((s) => s.detail.includes('checks outrank critique'))).toBe(true)+ })++ it('no renderer or critique seam → disclosed as unavailable, never faked', async () => {+ const { model } = scriptedModel([PARAPHRASED, GOOD])+ const run = await runDesignAgent({ prompt: PROMPT, model })++ expect(run.outcome).toBe('passed')+ expect(run.report.visualVerification).toBe('unverified')+ expect(run.warnings.join(' ')).toMatch(/visual verification unavailable/)+ expect(run.report.stages.some((s) => s.name === 'visual-verification' && s.detail.includes('unavailable'))).toBe(true)+ })++ it('an unparseable critique is discarded fail-closed — no invented issues', async () => {+ const { model } = scriptedModel([PARAPHRASED, GOOD], ['looks lovely to me!'])+ const run = await runDesignAgent({ prompt: PROMPT, model, renderer: scriptedRenderer() })++ expect(run.outcome).toBe('passed')+ expect(run.report.visualPasses[0].action).toBe('unparseable-discarded')+ expect(run.report.visualVerification).toBe('unverified')+ })+})++describe('DesignAgent toolbox', () => {+ it('every deterministic tool runs; unknown tools fail honestly', () => {+ const brief = runDesignTool('extract-brief', { prompt: PROMPT })+ expect(brief.ok).toBe(true)++ const compiled = runDesignTool('compile-spec', { spec: JSON.parse(GOOD) })+ expect(compiled.ok).toBe(true)++ const wrap = runDesignTool('wrap-estimate', { text: 'a few words to wrap here', width: 200, fontSize: 18 })+ expect(wrap.ok).toBe(true)+ expect((wrap.value as { lines: number }).lines).toBeGreaterThan(1)++ const balance = runDesignTool('balance-report', {+ pages: (compiled.value as { pages: unknown[] }).pages,+ width: 1080,+ height: 1350,+ })+ expect(balance.ok).toBe(true)++ const unknown = runDesignTool('make-it-pretty', {})+ expect(unknown.ok).toBe(false)+ expect(unknown.notes[0]).toMatch(/unknown tool/)+ })+})++describe('critique parsing (advisory, fail-closed)', () => {+ it('parses fenced JSON with issues; garbage is a null, never invented issues', () => {+ const ok = parseCritiqueResponse('```json\n{"summary":"decent","issues":[{"severity":"P2","issue":"subline crowds the CTA","fix":"raise hero weight"}]}\n```')+ expect(ok).not.toBeNull()+ expect(ok?.issues).toHaveLength(1)+ expect(ok?.issues[0].severity).toBe('P2')+ expect(ok?.advisory).toBe(true)++ expect(parseCritiqueResponse('looks great to me!')).toBeNull()+ // a missing severity degrades to P3, a missing issue is dropped+ const lax = parseCritiqueResponse('{"summary":"","issues":[{"issue":"x"},{"severity":"P1"}]}')+ expect(lax?.issues).toHaveLength(1)+ expect(lax?.issues[0].severity).toBe('P3')+ })+})++describe('the full block vocabulary compiles through the agent toolbox', () => {+ const spec = JSON.stringify({+ version: 'v2',+ name: 'vocabulary poster',+ format: { width: 1080, height: 1350 },+ palette: { seeds: ['#1B5E20', '#F9A825'], mood: 'warm' },+ typography: {},+ blocks: [+ {+ kind: 'hero',+ weight: 3,+ content: [+ { role: 'headline', source: 'user-required', text: 'Valley Runs 2026' },+ { role: 'cta', source: 'user-required', text: 'Register Free' },+ ],+ overlap: 'none',+ },+ {+ kind: 'stat-row',+ weight: 2,+ count: 3,+ content: [+ { role: 'headline', source: 'user-required', text: '12k+' },+ { role: 'label', source: 'model', text: 'runners finished' },+ { role: 'headline', source: 'user-required', text: '42' },+ { role: 'label', source: 'model', text: 'villages on the route' },+ { role: 'headline', source: 'user-required', text: '5' },+ { role: 'label', source: 'model', text: 'years running' },+ ],+ },+ {+ kind: 'timeline',+ weight: 2,+ count: 3,+ content: [+ { role: 'headline', source: 'model', text: '7 AM' },+ { role: 'label', source: 'model', text: 'start line opens' },+ { role: 'headline', source: 'model', text: '9 AM' },+ { role: 'label', source: 'model', text: 'race begins' },+ { role: 'headline', source: 'model', text: '1 PM' },+ { role: 'label', source: 'model', text: 'awards' },+ ],+ },+ {+ kind: 'mockup',+ weight: 3,+ content: [{ role: 'label', source: 'model', text: 'Last year at the finish line' }],+ },+ {+ kind: 'gallery',+ weight: 2,+ count: 2,+ content: [+ { role: 'label', source: 'model', text: 'Route through the valley' },+ { role: 'label', source: 'model', text: 'Finish festival' },+ ],+ },+ {+ kind: 'footer',+ weight: 1,+ content: [{ role: 'label', source: 'model', text: 'Organized by the Srinagar Running Club' }],+ },+ ],+ })++ it('every kind gets its dedicated builder and all checks stay green', () => {+ const result = compileSpec(JSON.parse(spec))+ expect(result.checks.passed).toBe(true)+ const texts = result.pages[0].elements.filter((el) => el.type === 'text').map((el) => (el as { text: string }).text)+ for (const t of [+ 'Valley Runs 2026', 'Register Free',+ '12k+', '42', '5', 'runners finished', 'villages on the route', 'years running',+ '7 AM', '9 AM', '1 PM', 'race begins', 'awards',+ 'Last year at the finish line',+ 'Route through the valley', 'Finish festival',+ 'Organized by the Srinagar Running Club',+ ]) {+ expect(texts).toContain(t)+ }+ // timeline route: the stop dots are small ellipses+ const dots = result.pages[0].elements.filter((el) => el.type === 'ellipse')+ expect(dots.length).toBeGreaterThanOrEqual(3)+ // stat underline: slim accent rects (height 4, narrow — the+ // timeline route is also height 4 but spans hundreds of px)+ const statRects = result.pages[0].elements.filter((el) => el.type === 'rect' && (el as { height?: number }).height === 4 && (el as { width?: number }).width !== undefined && (el as { width: number }).width < 120)+ expect(statRects.length).toBeGreaterThanOrEqual(3)+ // stat values share one underline baseline+ const baselines = new Set(statRects.map((el) => (el as { y?: number }).y))+ expect(baselines.size).toBe(1)+ // gallery frames: 2 surface cards wide enough to be real frames+ const galleryFrames = result.pages[0].elements.filter(+ (el) => el.type === 'rect' && (el as { fill?: string }).fill === result.palette.roles.surface && (el as { width?: number }).width !== undefined && (el as { width: number }).width > 200,+ )+ expect(galleryFrames.length).toBeGreaterThanOrEqual(3) // mockup frame + 2 gallery frames+ })++ it('runs through the full pipeline (scripted model) with all vocabulary accepted', async () => {+ const briefSpec = JSON.parse(spec)+ // the model always returns this spec; its user-required texts+ // differ from PROMPT's — the run must NOT fake success (the+ // identical-reply loop trips the cycle guard, which is the same+ // honesty contract: never claim a design that misses the brief)+ const model = { plan: async () => JSON.stringify(briefSpec) } as DesignAgentModel+ const run = await runDesignAgent({ prompt: PROMPT, model })+ expect(['failed-honestly', 'guard-cycled']).toContain(run.outcome)+ expect(run.outcome).not.toBe('passed')+ expect(run.briefConformance.length).toBeGreaterThan(0)+ })+})++describe('CritiqueResult shape', () => {+ it('is advisory by construction', () => {+ const c = parseCritiqueResponse('{"summary":"s","issues":[{"severity":"P1","issue":"i"}]}')+ expect((c as CritiqueResult)?.advisory).toBe(true)+ })+})diff --git a/src/lib/design-agent/pipeline.ts b/src/lib/design-agent/pipeline.tsnew file mode 100644index 0000000..5d04033--- /dev/null+++ b/src/lib/design-agent/pipeline.ts@@ -0,0 +1,435 @@+// ─────────────────────────────────────────────────────────────+// DesignAgent · the autonomous pipeline (Phase B, 24 Nov 2026).+//+// research/AUTONOMOUS-AGENT-RESEARCH.md P2/P4: CODE orchestration+// around the model seams, with the evaluator loop (Reflexion-style+// self-correction). The pipeline is deterministic TypeScript —+// stages, order, retries and termination are code; the model only+// plans and critiques. The compile checks are the evaluator: their+// failures are fed back to the planner as a revision prompt,+// bounded and cycle-guarded, and a run that cannot pass ENDS+// HONESTLY (never a fake success, never a truncated text).+//+// Visual verification (v2, the P0 ChatGPT review item): after the+// deterministic checks pass, the pipeline RENDERS the pages and a+// vision model critiques the real pixels. P1/P2 findings can trigger+// one more revision round — but a critique-revision is only+// ACCEPTED if the new spec also passes every deterministic check+// and the critique issue count actually drops; otherwise the+// previous passing design is kept and the outcome disclosed.+// Checks outrank critique, always. No renderer or critique seam →+// "visual verification unavailable" is disclosed, never faked.+//+// Guards (machine protection, not product caps — the repo's+// protocol.ts philosophy):+// · maxRevisions (default 3) — bounded self-correction rounds,+// shared by check- and critique-origin revisions+// · cycle guard — a model that repeats its previous spec verbatim+// is looping, not progressing: stop, disclose+// · signal — caller cancellation (AbortSignal), checked before+// every model call and stage+// · every stage recorded in the run report — the "why" is public+// ─────────────────────────────────────────────────────────────++import type { DesignBrief } from '@/lib/agent/brief'+import type { DesignSpec } from '@/lib/design-spec/types'+import type { CompileChecks } from '@/lib/design-engine/compile'+import type { PageData } from '@/lib/types'+import { parseSpecResponse } from '@/lib/design-spec/parse'+import { compileSpec } from '@/lib/design-engine/compile'+import type { DesignAgentModel, RevisionFeedback, CritiqueIssue, CritiqueResult } from './model'+import { parseCritiqueResponse } from './model'+import { runDesignTool, toolboxPromptSection } from './tools'+import { PLANNER_SYSTEM, planUserPrompt, revisionUserPrompt } from './prompts'++export interface DesignAgentLimits {+ /** bounded self-correction rounds, shared by checks- and+ * critique-origin revisions (guard, not a product cap) */+ maxRevisions: number+ /** bounded visual-verification passes (render → critique) */+ maxVisualPasses: number+}++export const DEFAULT_LIMITS: DesignAgentLimits = { maxRevisions: 3, maxVisualPasses: 1 }++export type AgentOutcome = 'passed' | 'failed-honestly' | 'guard-cycled' | 'aborted'++/** How the pipeline sees its own render. Implementations: the app+ * (exportPageToSVG + captureStage), the acceptance harness (the CLI+ * render step). Returns null when rendering is unavailable — the+ * pipeline discloses it, never invents a critique. */+export interface DesignRenderer {+ render(pages: PageData[], spec: DesignSpec): Promise<{ image: string } | null>+}++export interface AgentStageRecord {+ name: string+ ok: boolean+ /** what happened, for the run report */+ detail: string+ /** true when this stage consumed a model call */+ modelCall: boolean+}++export interface VisualPassRecord {+ round: number+ issues: CritiqueIssue[]+ summary: string+ /** what the pipeline did with the findings */+ action: 'revised' | 'accepted-as-is' | 'rejected-by-checks' | 'no-improvement' | 'budget-exhausted' | 'unparseable-discarded' | 'unavailable'+}++export interface AgentRunReport {+ stages: AgentStageRecord[]+ modelCalls: number+ revisionRounds: number+ cycleGuard: boolean+ brief: DesignBrief+ spec?: DesignSpec+ limits: DesignAgentLimits+ /** the visual-verification passes (render → critique) and what+ * each one concluded */+ visualPasses: VisualPassRecord[]+ visualVerification: 'verified' | 'improved' | 'unverified' | 'unavailable' | 'aborted'+}++export interface DesignAgentRun {+ outcome: AgentOutcome+ /** the last accepted compiled pages (present when a spec parsed at+ * all — even a failed run keeps its evidence) */+ pages?: PageData[]+ checks?: CompileChecks+ /** brief→spec conformance failures (the model dropped or altered+ * something the user required). Empty on a passing run. */+ briefConformance: string[]+ warnings: string[]+ report: AgentRunReport+}++/**+ * Brief→spec conformance: the evaluator the ENGINE cannot run (it+ * validates spec→page; only the agent layer knows what the brief+ * demanded of the spec). A model that paraphrases, drops or recases+ * a user-required text, forgets a required hex, or changes the+ * requested dimensions fails HERE — deterministically, with the+ * exact requirement quoted back for the revision round.+ */+export function briefConformance(brief: DesignBrief, spec: DesignSpec): string[] {+ const failures: string[] = []+ for (const t of brief.requiredTexts) {+ const carried = spec.blocks.some((b) =>+ b.content.some((s) => s.source === 'user-required' && s.text.normalize('NFC') === t.text.normalize('NFC')),+ )+ if (!carried) {+ const pieces = spec.blocks.flatMap((b) => b.content).map((s) => s.text)+ const splitHint = pieces.includes(t.text.split(' ')[0])+ ? ' It is NOT enough to split its pieces across separate slots — the FULL string must be one slot.'+ : ''+ failures.push(`required text missing from the spec — add it as ONE user-required slot with exactly this text: "${t.text}"${splitHint}`)+ }+ }+ for (const c of brief.requiredColors) {+ const pinned = Object.values(spec.palette.pinned ?? {})+ const carried =+ spec.palette.seeds.some((s) => s.trim().toLowerCase() === c.hex.trim().toLowerCase()) ||+ pinned.some((s) => typeof s === 'string' && s.trim().toLowerCase() === c.hex.trim().toLowerCase())+ if (!carried) failures.push(`required color ${c.hex} missing from palette.seeds — add it verbatim`)+ }+ if (brief.dimensions) {+ const { width, height } = brief.dimensions+ if (spec.format.width !== width || spec.format.height !== height) {+ failures.push(`dimensions must be ${width}x${height} per the brief — spec says ${spec.format.width}x${spec.format.height}`)+ }+ }+ return failures+}++/** Extract one JSON object from a model reply (tolerant of fences+ * and prose; the same tolerance loop.ts's parseAgentTurn has). */+export function extractJsonObject(raw: string): unknown | null {+ const cleaned = raw.replace(/```(?:json)?/gi, '')+ for (let start = cleaned.indexOf('{'); start !== -1; start = cleaned.indexOf('{', start + 1)) {+ const end = cleaned.lastIndexOf('}')+ if (end > start) {+ try {+ return JSON.parse(cleaned.slice(start, end + 1))+ } catch {+ // keep scanning+ }+ }+ }+ return null+}++/** Count the findings that warrant action (P1/P2). */+function actionableIssues(critique: CritiqueResult): CritiqueIssue[] {+ return critique.issues.filter((i) => i.severity === 'P1' || i.severity === 'P2')+}++/**+ * The autonomous design run:+ * extract-brief → plan (model) → parse → brief-conformance ++ * compile+check → [failures → revise (model)] × ≤ maxRevisions →+ * visual verification: render → critique → (bounded, guarded+ * correction → re-compile → re-render → verify) → report.+ */+export async function runDesignAgent(opts: {+ prompt: string+ model: DesignAgentModel+ renderer?: DesignRenderer+ limits?: Partial<DesignAgentLimits>+ /** caller cancellation; checked before every model call and stage */+ signal?: { aborted: boolean }+}): Promise<DesignAgentRun> {+ const limits = { ...DEFAULT_LIMITS, ...opts.limits }+ const stages: AgentStageRecord[] = []+ let modelCalls = 0+ const signal = opts.signal ?? { aborted: false }+ const isAborted = () => signal.aborted++ const abortedRun = (partial: Partial<AgentRunReport> & { brief: DesignBrief }): DesignAgentRun => ({+ outcome: 'aborted',+ briefConformance: [],+ warnings: ['run cancelled by the caller before completion'],+ report: { stages, modelCalls, revisionRounds: 0, cycleGuard: false, visualPasses: [], visualVerification: 'aborted', ...partial, limits },+ })++ // ── stage 1: extract the brief (deterministic) ──+ const briefRun = runDesignTool('extract-brief', { prompt: opts.prompt })+ stages.push({ name: 'extract-brief', ok: briefRun.ok, detail: briefRun.ok ? `${(briefRun.value as DesignBrief).requiredTexts.length} required text(s), ${(briefRun.value as DesignBrief).requiredColors.length} required color(s)` : briefRun.notes.join('; '), modelCall: false })+ if (!briefRun.ok || !briefRun.value) {+ return {+ outcome: 'failed-honestly',+ briefConformance: [],+ warnings: briefRun.notes,+ report: { stages, modelCalls: 0, revisionRounds: 0, cycleGuard: false, brief: briefRun.value as DesignBrief, limits, visualPasses: [], visualVerification: 'unverified' },+ }+ }+ const brief = briefRun.value as DesignBrief+ const toolbox = toolboxPromptSection()++ // ── the plan/compile/revise loop (evaluator loop, bounded) ──+ const seenSpecs: string[] = []+ let revisionRounds = 0+ let cycleGuard = false+ let lastSpec: DesignSpec | undefined+ let lastCompile: ReturnType<typeof compileSpec> | undefined+ let feedback: RevisionFeedback | undefined++ /** the accepted (checks-green) result after the loop */+ let accepted: { spec: DesignSpec; compiled: ReturnType<typeof compileSpec>; conformance: string[] } | undefined++ while (true) {+ if (isAborted()) return abortedRun({ brief, spec: lastSpec })+ // plan seam (model)+ const raw = await opts.model.plan({ brief, toolbox, feedback })+ modelCalls += 1++ // parse (deterministic, honest failure)+ const parsed = parseSpecResponse(raw)+ if (!parsed.ok) {+ stages.push({ name: `plan+parse (round ${revisionRounds + 1})`, ok: false, detail: `parse failed: ${parsed.error}`, modelCall: true })+ // a parse failure with no prior spec: nothing to revise against+ if (!lastSpec || revisionRounds >= limits.maxRevisions) {+ return {+ outcome: 'failed-honestly',+ briefConformance: [],+ warnings: [parsed.error],+ report: { stages, modelCalls, revisionRounds, cycleGuard: false, brief, spec: lastSpec, limits, visualPasses: [], visualVerification: 'unverified' },+ }+ }+ revisionRounds += 1+ feedback = { round: revisionRounds, failures: [parsed.error], warnings: [], priorSpec: lastSpec, origin: 'checks' }+ continue+ }+ const spec = parsed.spec++ // cycle guard: the model repeated itself verbatim — no progress+ const canonical = JSON.stringify(spec)+ if (seenSpecs.includes(canonical)) {+ cycleGuard = true+ stages.push({ name: `cycle-guard (round ${revisionRounds + 1})`, ok: false, detail: 'model repeated its previous spec verbatim — looping, not progressing; run stops honestly', modelCall: false })+ return {+ outcome: 'guard-cycled',+ pages: lastCompile?.pages,+ checks: lastCompile?.checks,+ briefConformance: lastSpec ? briefConformance(brief, lastSpec) : [],+ warnings: [...(lastCompile?.warnings ?? []), 'revision loop detected: the model repeated its spec verbatim'],+ report: { stages, modelCalls, revisionRounds, cycleGuard: true, brief, spec: lastSpec ?? spec, limits, visualPasses: [], visualVerification: 'unverified' },+ }+ }+ seenSpecs.push(canonical)++ // compile + evaluate (deterministic) — engine checks spec→page,+ // brief conformance checks brief→spec: BOTH must be clean+ const compiled = compileSpec(spec)+ const briefFailures = briefConformance(brief, spec)+ const allFailures = [...briefFailures, ...compiled.checks.failures]+ lastSpec = spec+ lastCompile = compiled++ if (allFailures.length === 0 && compiled.checks.passed) {+ stages.push({ name: `brief-conformance (round ${revisionRounds + 1})`, ok: true, detail: 'spec carries every required text, color and dimension', modelCall: false })+ stages.push({ name: `compile+check (round ${revisionRounds + 1})`, ok: true, detail: 'all checks passed', modelCall: false })+ accepted = { spec, compiled, conformance: briefFailures }+ break+ }++ // failed → feedback → revise (bounded)+ stages.push({ name: `brief-conformance (round ${revisionRounds + 1})`, ok: briefFailures.length === 0, detail: briefFailures.join('; ') || 'conformant', modelCall: false })+ stages.push({ name: `compile+check (round ${revisionRounds + 1})`, ok: compiled.checks.passed, detail: compiled.checks.failures.join('; ') || 'all checks passed', modelCall: false })+ if (revisionRounds >= limits.maxRevisions) {+ return {+ outcome: 'failed-honestly',+ pages: compiled.pages,+ checks: compiled.checks,+ briefConformance: briefFailures,+ warnings: [...compiled.warnings, `revision budget exhausted (${limits.maxRevisions}) — run ends honestly with the failures visible`],+ report: { stages, modelCalls, revisionRounds, cycleGuard: false, brief, spec, limits, visualPasses: [], visualVerification: 'unverified' },+ }+ }+ revisionRounds += 1+ feedback = { round: revisionRounds, failures: allFailures, warnings: compiled.warnings, priorSpec: spec, origin: 'checks' }+ }++ // ── visual verification: render → critique → (guarded) fix ──+ const visualPasses: VisualPassRecord[] = []+ let visualVerification: AgentRunReport['visualVerification'] = 'unverified'+ const canSee = Boolean(opts.renderer && opts.model.critique)+ if (!canSee) {+ stages.push({ name: 'visual-verification', ok: false, detail: 'unavailable — no renderer or critique seam provided; disclosed, not faked', modelCall: false })+ visualVerification = 'unverified'+ } else {+ // the accepted design gets rendered and critiqued, up to+ // maxVisualPasses times; each pass may trigger ONE revision+ // round (shared budget) if actionable findings exist+ let current = accepted!+ let passes = 0+ while (passes < limits.maxVisualPasses) {+ if (isAborted()) return abortedRun({ brief, spec: current.spec })+ passes += 1+ const rendered = await opts.renderer!.render(current.compiled.pages, current.spec)+ if (!rendered) {+ stages.push({ name: `render (pass ${passes})`, ok: false, detail: 'renderer returned no image — visual verification unavailable, disclosed', modelCall: false })+ visualPasses.push({ round: passes, issues: [], summary: '', action: 'unavailable' })+ visualVerification = 'unavailable'+ break+ }+ stages.push({ name: `render (pass ${passes})`, ok: true, detail: 'rendered the real pages for visual review', modelCall: false })++ if (isAborted()) return abortedRun({ brief, spec: current.spec })+ const critiqueRaw = await opts.model.critique!({ brief, image: rendered.image })+ modelCalls += 1+ const critique = parseCritiqueResponse(critiqueRaw)+ if (!critique) {+ stages.push({ name: `critique (pass ${passes})`, ok: false, detail: 'critique reply unparseable — discarded (fail-closed; no invented issues)', modelCall: true })+ visualPasses.push({ round: passes, issues: [], summary: '', action: 'unparseable-discarded' })+ visualVerification = 'unverified'+ break+ }+ const actionable = actionableIssues(critique)+ stages.push({ name: `critique (pass ${passes})`, ok: actionable.length === 0, detail: `${critique.issues.length} issue(s), ${actionable.length} actionable (P1/P2)${critique.summary ? ` — ${critique.summary.slice(0, 90)}` : ''}`, modelCall: true })++ if (actionable.length === 0) {+ visualPasses.push({ round: passes, issues: critique.issues, summary: critique.summary, action: 'accepted-as-is' })+ visualVerification = 'verified'+ break+ }++ // actionable findings → one critique-origin revision, IF the+ // shared revision budget still allows it+ if (revisionRounds >= limits.maxRevisions) {+ visualPasses.push({ round: passes, issues: critique.issues, summary: critique.summary, action: 'budget-exhausted' })+ stages.push({ name: `visual-revision (pass ${passes})`, ok: false, detail: `revision budget exhausted — findings recorded, design kept (checks green)`, modelCall: false })+ visualVerification = 'unverified'+ break+ }+ revisionRounds += 1+ const reviseFeedback: RevisionFeedback = {+ round: revisionRounds,+ failures: actionable.map((i) => `${i.severity}: ${i.issue}${i.fix ? ` → fix: ${i.fix}` : ''}`),+ warnings: [],+ priorSpec: current.spec,+ origin: 'critique',+ }+ if (isAborted()) return abortedRun({ brief, spec: current.spec })+ const revisedRaw = await opts.model.plan({ brief, toolbox, feedback: reviseFeedback })+ modelCalls += 1+ const revisedParsed = parseSpecResponse(revisedRaw)+ if (!revisedParsed.ok) {+ stages.push({ name: `visual-revision (pass ${passes})`, ok: false, detail: `revised spec unparseable — previous passing design kept (${revisedParsed.error})`, modelCall: true })+ visualPasses.push({ round: passes, issues: critique.issues, summary: critique.summary, action: 'rejected-by-checks' })+ visualVerification = 'unverified'+ break+ }+ const revisedSpec = revisedParsed.spec+ // a critique revision is only accepted if it ALSO passes every+ // deterministic check and stays brief-conformant — the checks+ // outrank the critique+ const revisedCompiled = compileSpec(revisedSpec)+ const revisedConformance = briefConformance(brief, revisedSpec)+ if (!revisedCompiled.checks.passed || revisedConformance.length > 0) {+ stages.push({ name: `visual-revision (pass ${passes})`, ok: false, detail: 'revised spec failed deterministic checks — rejected; previous passing design kept (checks outrank critique)', modelCall: true })+ visualPasses.push({ round: passes, issues: critique.issues, summary: critique.summary, action: 'rejected-by-checks' })+ visualVerification = 'unverified'+ break+ }+ current = { spec: revisedSpec, compiled: revisedCompiled, conformance: revisedConformance }+ visualPasses.push({ round: passes, issues: critique.issues, summary: critique.summary, action: 'revised' })+ stages.push({ name: `visual-revision (pass ${passes})`, ok: true, detail: 'revised spec accepted — re-rendering to verify', modelCall: true })+ }+ accepted = current+ // final verify pass when the last action was a revision+ if (visualPasses.length > 0 && visualPasses[visualPasses.length - 1].action === 'revised') {+ if (isAborted()) return abortedRun({ brief, spec: current.spec })+ // the findings that TRIGGERED the revision, for comparison+ const triggering = actionableIssues({ summary: '', issues: visualPasses[visualPasses.length - 1].issues, advisory: true })+ const reRendered = await opts.renderer!.render(accepted.compiled.pages, accepted.spec)+ if (reRendered) {+ const reCritiqueRaw = await opts.model.critique!({ brief, image: reRendered.image })+ modelCalls += 1+ const reCritique = parseCritiqueResponse(reCritiqueRaw)+ if (reCritique) {+ const remaining = actionableIssues(reCritique)+ stages.push({ name: 'verify (post-revision)', ok: remaining.length === 0, detail: `${remaining.length} actionable issue(s) after the correction (was ${triggering.length})`, modelCall: true })+ visualVerification = remaining.length < triggering.length ? 'improved' : 'unverified'+ } else {+ stages.push({ name: 'verify (post-revision)', ok: false, detail: 'verification critique unparseable — discarded (fail-closed)', modelCall: true })+ visualVerification = 'unverified'+ }+ } else {+ stages.push({ name: 'verify (post-revision)', ok: false, detail: 'renderer unavailable for the verification pass', modelCall: false })+ visualVerification = 'unverified'+ }+ } else if (visualPasses.length > 0 && visualPasses[visualPasses.length - 1].action === 'accepted-as-is') {+ visualVerification = 'verified'+ }+ }++ // ── finish: balance diagnostics + report ──+ if (isAborted()) return abortedRun({ brief, spec: accepted!.spec })+ const balance = runDesignTool('balance-report', { pages: accepted!.compiled.pages, width: accepted!.spec.format.width, height: accepted!.spec.format.height })+ stages.push({ name: 'balance-report', ok: true, detail: `vertical coverage ${(Number((balance.value as { coverage: number }).coverage ?? 0) * 100).toFixed(0)}%`, modelCall: false })++ const warnings = [...accepted!.compiled.warnings, ...balance.notes]+ if (!canSee) warnings.push('visual verification unavailable (no renderer or critique seam) — deterministic checks passed; the render was not visually reviewed')++ return {+ outcome: 'passed',+ pages: accepted!.compiled.pages,+ checks: accepted!.compiled.checks,+ briefConformance: accepted!.conformance,+ warnings,+ report: { stages, modelCalls, revisionRounds, cycleGuard, brief, spec: accepted!.spec, limits, visualPasses, visualVerification },+ }+}++/** Extract a spec-shaped object from a raw model reply WITHOUT the+ * strict parse (used by the acceptance harness when a scripted or+ * file-based planner needs tolerant extraction). */+export function tolerantParseSpec(raw: string): DesignSpec | null {+ const obj = extractJsonObject(raw)+ if (!obj || typeof obj !== 'object') return null+ const parsed = parseSpecResponse(JSON.stringify(obj))+ return parsed.ok ? parsed.spec : null+}diff --git a/src/lib/design-agent/prompts.ts b/src/lib/design-agent/prompts.tsnew file mode 100644index 0000000..e8ee3a0--- /dev/null+++ b/src/lib/design-agent/prompts.ts@@ -0,0 +1,95 @@+// ─────────────────────────────────────────────────────────────+// DesignAgent · prompts (Phase B).+//+// The planner system prompt: the DesignSpec contract, the block+// vocabulary, the slot conventions for the dedicated builders, and+// the hard rules (verbatim copy, required hexes). Written for a+// JSON-returns model; the pipeline parses tolerantly but the prompt+// asks for clean JSON first.+// ─────────────────────────────────────────────────────────────++import type { DesignBrief } from '@/lib/agent/brief'+import type { RevisionFeedback } from './model'+import { toolboxPromptSection } from './tools'++export const PLANNER_SYSTEM = `You are the design planner of a deterministic design engine. You choose SEMANTICS only; geometry, color math, typography and quality checks are executed by the engine and cannot be negotiated.++Emit ONLY a JSON object (no prose, no markdown fences) shaped exactly:++{+ "version": "v2",+ "name": "short design name",+ "format": { "width": 1080, "height": 1350 },+ "palette": { "seeds": ["#RRGGBB"], "mood": "warm|cool|neutral|vibrant|minimal" },+ "typography": { "scale": 1.25 },+ "blocks": [+ { "kind": "hero", "weight": 3, "content": [+ { "role": "headline", "source": "user-required", "text": "..." },+ { "role": "subline", "source": "model", "text": "...", "maxWords": 12 },+ { "role": "cta", "source": "user-required", "text": "..." }+ ], "overlap": "none" }+ ]+}++RULES (violations fail deterministic checks and are sent back to you):+1. Every user-required text goes into a slot with source "user-required" and the EXACT text — character-for-character, no paraphrase, no case change, no truncation. A required text is ONE slot holding the full string: never split it across multiple slots or blocks, even when its pieces look like separate stats or dates.+2. Every required hex goes into palette.seeds. Seeds are preserved and guaranteed to appear on the page.+3. Roles: headline, subline, tagline, body, cta, label. Blocks kinds: hero (headline/subline/cta stack), feature-cards (N short card texts), stat-row (alternating value/caption pairs — value as role "headline", caption as role "label"), mockup (one label/body slot = the frame caption; the engine draws the visual frame), timeline (dates/labels as alternating value/caption pairs, rendered as a horizontal route), gallery (short captions for a 2-up image grid), footer (one short closing line) — all kinds have dedicated builders.+4. stat-row and timeline slot convention: content is value, caption, value, caption… Set count to the number of value/caption PAIRS.+5. Blocks stack top-to-bottom; weight is relative band height (hero usually 2-4, other blocks 1-2). One hero, at most one of each other kind per poster.+6. Model-authored copy (source "model") must carry maxWords (a soft budget the engine reports, never a cut).+7. Keep total slots modest (≤14): density is a warning, emptiness is not.+8. Do not duplicate the same line in two blocks — say a thing once, in the block where it belongs.++${toolboxPromptSection()}`++export function planUserPrompt(brief: DesignBrief): string {+ const lines: string[] = []+ lines.push(`Design brief (extracted deterministically from the user prompt):`)+ lines.push(`- design type: ${brief.designType ?? 'poster'}${brief.format ? ` (${brief.format})` : ''}`)+ if (brief.dimensions) lines.push(`- dimensions: ${brief.dimensions.width}x${brief.dimensions.height} px`)+ if (brief.requiredTexts.length) {+ lines.push(`- required verbatim texts (MUST appear character-for-character):`)+ for (const t of brief.requiredTexts) lines.push(` "${t.text}"`)+ }+ if (brief.requiredColors.length) {+ lines.push(`- required hex colors (MUST appear on the page): ${brief.requiredColors.map((c) => c.hex).join(', ')}`)+ }+ if (brief.restrictions.length) lines.push(`- restrictions: ${brief.restrictions.join('; ')}`)+ if (brief.notes.length) lines.push(`- notes: ${brief.notes.join('; ')}`)+ lines.push(``, `Plan the DesignSpec JSON now.`)+ return lines.join('\n')+}++export function revisionUserPrompt(feedback: RevisionFeedback): string {+ const lines: string[] = []+ if (feedback.origin === 'critique') {+ lines.push(`A vision model reviewed the RENDERED design and found concrete visual defects. Revise the spec to fix them.`)+ } else {+ lines.push(`Your previous DesignSpec FAILED the deterministic checks. Revise it.`)+ }+ lines.push(``)+ lines.push(`Failures (hard — every one must be fixed):`)+ for (const f of feedback.failures) lines.push(` ✗ ${f}`)+ if (feedback.warnings.length) {+ lines.push(``, `Warnings (advisory, fix if reasonable):`)+ for (const w of feedback.warnings) lines.push(` ⚠ ${w}`)+ }+ lines.push(``)+ lines.push(`Your previous spec (revise THIS — do not restart from zero):`)+ lines.push(JSON.stringify(feedback.priorSpec, null, 2))+ lines.push(``)+ lines.push(`Emit the FULL corrected DesignSpec JSON (same schema, no prose).`)+ return lines.join('\n')+}++export const CRITIQUE_SYSTEM = `You are an aesthetic reviewer looking at a REAL rendered design (not a plan). Score against a professional poster bar: layout balance and alignment, color hierarchy, typographic hierarchy, readable contrast, breathing room. Be strict — calibrated anchors: 4-5 means a professional human designer shipped it; 1-3 requires naming the concrete defect.++Emit ONLY JSON: { "summary": "one paragraph verdict", "issues": [ { "severity": "P1|P2|P3", "issue": "concrete defect", "fix": "actionable fix" } ] }+P1 = a defect a client would reject; P2 = clearly subprofessional; P3 = polish. No invented content — only what you can see.`++export function critiqueUserPrompt(brief: DesignBrief): string {+ const req = brief.requiredTexts.map((t) => `"${t.text}"`).join(', ')+ return `The brief required these verbatim texts (already machine-verified — do not re-check them): ${req || '(none)'}.+Review the RENDERED poster as an aesthetic expert: layout, color, typography, spacing, hierarchy. List concrete, visible defects only.`+}diff --git a/src/lib/design-agent/tools.ts b/src/lib/design-agent/tools.tsnew file mode 100644index 0000000..239e7fa--- /dev/null+++ b/src/lib/design-agent/tools.ts@@ -0,0 +1,162 @@+// ─────────────────────────────────────────────────────────────+// DesignAgent · the toolbox (Phase B, 24 Nov 2026).+//+// Every function the autonomous design agent can use, as a typed+// registry — the ReAct tool-registry discipline (name + one-line+// description + inputs) applied to a code-orchestrated pipeline.+// The registry is the CAPABILITY SURFACE: what the model may choose+// semantically (blocks, copy, seeds, kinds) and what the engine+// executes deterministically (geometry, color math, type scale,+// checks). Mirrors src/lib/agent/tools.ts (AGENT_TOOLS) in style.+//+// Design principles are EMBEDDED in the executors (the PosterGen+// lesson): the compiler carries the composition vocabulary, the+// checks carry the quality bar. The model cannot reach past either.+// ─────────────────────────────────────────────────────────────++import { extractBrief, type DesignBrief } from '@/lib/agent/brief'+import { type DesignSpec } from '@/lib/design-spec/types'+import { parseSpecResponse } from '@/lib/design-spec/parse'+import {+ compileSpec,+ type CompileResult,+ type CompileChecks,+} from '@/lib/design-engine/compile'+import { wrapLines, estimateTextWidth } from '@/lib/design-engine/compositions'+import type { PageData } from '@/lib/types'++export interface ToolRunResult {+ ok: boolean+ /** the tool's typed output (serializable for reports) */+ value: unknown+ /** non-fatal notes */+ notes: string[]+}++export interface DesignTool {+ name: string+ /** one sentence: what it does and when the pipeline uses it */+ description: string+ /** compact input schema for prompts and the run report */+ inputs: string+ run: (args: Record<string, unknown>) => ToolRunResult+}++// ── deterministic executors (pure, testable, no model I/O) ────++const extractBriefTool: DesignTool = {+ name: 'extract-brief',+ description: 'Extracts the structured brief from the user prompt: required verbatim texts, colors, dimensions, format preset.',+ inputs: '{ prompt: string }',+ run: ({ prompt }) => {+ if (typeof prompt !== 'string' || !prompt.trim()) return { ok: false, value: null, notes: ['no prompt'] }+ const brief = extractBrief(prompt)+ const notes: string[] = []+ if (brief.requiredTexts.length === 0) notes.push('no verbatim texts required — planner copy is free')+ return { ok: true, value: brief, notes }+ },+}++const parseSpecTool: DesignTool = {+ name: 'parse-spec',+ description: 'Validates model output into a DesignSpec: kind vocabulary, roles, hexes, format bounds. Honest failure object, never a silently-emptied spec.',+ inputs: '{ raw: string }',+ run: ({ raw }) => {+ const r = parseSpecResponse(typeof raw === 'string' ? raw : '')+ return r.ok+ ? { ok: true, value: r.spec, notes: [] }+ : { ok: false, value: null, notes: [r.error] }+ },+}++const compileSpecTool: DesignTool = {+ name: 'compile-spec',+ description: 'The design engine: expands the palette, assigns the type scale, lays out blocks into editable elements, runs every check (exact texts, required colors, wrap-aware fit, overlap, contrast) and guarantees required colors reach the page.',+ inputs: '{ spec: DesignSpec }',+ run: ({ spec }) => {+ if (!spec || typeof spec !== 'object') return { ok: false, value: null, notes: ['no spec'] }+ const result = compileSpec(spec as DesignSpec)+ return {+ ok: result.checks.passed,+ value: { pages: result.pages, checks: result.checks, warnings: result.warnings },+ notes: result.checks.failures,+ }+ },+}++const wrapEstimateTool: DesignTool = {+ name: 'wrap-estimate',+ description: 'Greedy word-wrap estimate for a text at a box width/font size — how many lines the renderer will need (never truncates; the estimate is conservative).',+ inputs: '{ text: string, width: number, fontSize: number }',+ run: ({ text, width, fontSize }) => {+ const t = String(text ?? '')+ const w = Number(width) || 1+ const s = Number(fontSize) || 1+ const lines = wrapLines(t, w, s)+ return {+ ok: true,+ value: { lines: lines.length, widest: Math.max(...lines.map((l) => estimateTextWidth(l, s))) },+ notes: [],+ }+ },+}++const balanceReportTool: DesignTool = {+ name: 'balance-report',+ description: 'Composition balance diagnostics (advisory, warning-level): vertical coverage of the content, the PosterGen utilization-band analog — sparse (<60%) or crowded (>98%) compositions get a note.',+ inputs: '{ pages: PageData[], width: number, height: number }',+ run: ({ pages, width, height }) => {+ const pgs = Array.isArray(pages) ? (pages as PageData[]) : []+ const W = Number(width) || 1+ const H = Number(height) || 1+ if (!pgs[0]?.elements?.length) return { ok: true, value: { coverage: 0 }, notes: ['empty page'] }+ let minY = Infinity+ let maxY = -Infinity+ for (const el of pgs[0].elements) {+ const r = el as unknown as { x: number; y: number; width: number; height: number }+ minY = Math.min(minY, r.y)+ maxY = Math.max(maxY, r.y + r.height)+ }+ const coverage = Math.max(0, Math.min(1, (maxY - minY) / H))+ const notes: string[] = []+ if (coverage < 0.6) notes.push(`composition covers ${(coverage * 100).toFixed(0)}% of the height — sparse; consider more weight on content blocks`)+ if (coverage > 0.98) notes.push(`composition covers ${(coverage * 100).toFixed(0)}% of the height — crowded; tighten weights`)+ return { ok: true, value: { coverage: Number(coverage.toFixed(3)), width: W, height: H }, notes }+ },+}++/** The registry — every function the autonomous agent can use. The+ * MODEL seams (plan / revise / critique) are listed in+ * toolboxPromptSection() but executed by the pipeline through the+ * DesignAgentModel interface, never through this registry. */+export const DESIGN_TOOLS: readonly DesignTool[] = [+ extractBriefTool,+ parseSpecTool,+ compileSpecTool,+ wrapEstimateTool,+ balanceReportTool,+] as const++export const DESIGN_TOOL_MAP: ReadonlyMap<string, DesignTool> = new Map(DESIGN_TOOLS.map((t) => [t.name, t]))++/** The prompt catalog: what the planner is told it can do. Mirrors+ * toolsPromptSection() in the shipped agent. */+export function toolboxPromptSection(): string {+ const tools = DESIGN_TOOLS.map((t) => ` · ${t.name} (${t.inputs}) — ${t.description}`).join('\n')+ return [+ 'The deterministic toolbox executing your plan (you choose semantics; the engine owns geometry, color and type):',+ tools,+ 'Model seams the pipeline drives for you: plan (this call), revise (after check failures or critique findings), critique (a vision model reviews the real render — advisory only).',+ ].join('\n')+}++/** Run a tool by name (registry discipline: unknown names fail+ * honestly, never guess). Exported for the pipeline and tests. */+export function runDesignTool(name: string, args: Record<string, unknown>): ToolRunResult {+ const tool = DESIGN_TOOL_MAP.get(name)+ if (!tool) return { ok: false, value: null, notes: [`unknown tool: ${name}`] }+ return tool.run(args)+}++// ── shared result types re-exported for the pipeline ─────────+export type { DesignBrief, DesignSpec, CompileResult, CompileChecks, PageData }diff --git a/src/lib/design-engine/compositions.ts b/src/lib/design-engine/compositions.tsindex 6d23c70..98c8184 100644--- a/src/lib/design-engine/compositions.ts+++ b/src/lib/design-engine/compositions.ts@@ -268,14 +268,403 @@ export function buildFeatureCards(block: BlockNode, ctx: BuildContext): Composedreturn { backdrops, content, warnings }}-/** Dispatch: hero + feature-cards have dedicated builders today;- * other kinds compile through the generic hero stack with a warning- * (Phase C gives each kind its own builder). */+/** Stat row: N big-number/label pairs in a grid — the numbers band+ * of a professional poster (impact metrics, dates, prices). Slots+ * arrive as alternating value/caption pairs: role 'headline' is the+ * value, role 'label' its caption; a trailing bare value is+ * tolerated. Every cell reserves the MAX wrapped-line count so the+ * accent underlines and captions share one baseline (a wrapping+ * value must never shift its column's rhythm — found by the VLM+ * critique of the acceptance run). */+export function buildStatRow(block: BlockNode, ctx: BuildContext): ComposedElements {+ const { palette, type } = ctx+ const warnings: string[] = []+ const backdrops: AnyElement[] = []+ const content: AnyElement[] = []++ const slots = block.content+ const count = Math.max(1, Math.min(6, block.count ?? Math.ceil(slots.length / 2)))+ const cells = gridInRect(ctx.rect, count, { columns: 3, gap: 24, minCellWidth: 150, minCellHeight: 96 })+ if (cells.some((c) => c.width < 150 || c.height < 96)) {+ warnings.push(`stat-row band too small for ${count} stats — minimum 150x96 not met`)+ }++ // pass 1: fit each value; pass 2 places them on a shared baseline+ const fitted: { cell: Rect; valueText: string; captionText?: string; size: number; lines: string[] }[] = []++ cells.forEach((cell, i) => {+ const value = slots[2 * i]+ const caption = slots[2 * i + 1]+ const valueText = value?.text ?? `${(i + 1) * 25}+`+ const captionText = caption?.text++ // value: big, bold, ink — wrap-aware, shrunk to fit the cell+ const { size, lines } = wrapFontSize(valueText, cell.width, cell.height * 0.6, Math.max(type.sizes.headline, 48), 24, 1.15)+ fitted.push({ cell, valueText, captionText, size, lines })+ })++ const uniformLineH = Math.max(...fitted.map((f) => Math.round(f.size * 1.15)))+ const uniformValueH = Math.max(...fitted.map((f) => f.lines.length)) * uniformLineH++ for (const { cell, valueText, captionText, size, lines } of fitted) {+ const valueY = cell.y + Math.round(cell.height * 0.12)+ const valueH = Math.min(Math.round(cell.height * 0.6), Math.round(lines.length * size * 1.15))+ content.push(+ createTextElement({+ text: valueText,+ x: Math.round(cell.x),+ y: valueY,+ width: Math.round(cell.width),+ height: valueH,+ fontSize: size,+ fontFamily: type.families.heading,+ bold: true,+ fill: palette.roles.ink,+ align: 'center',+ lineHeight: 1.15,+ }),+ )++ // accent underline under the value — at the UNIFORM baseline+ const underlineY = valueY + uniformValueH + 6+ if (underlineY + 4 <= cell.y + cell.height) {+ backdrops.push(+ createShapeElement('rect', {+ x: Math.round(cell.x + cell.width * 0.36),+ y: underlineY,+ width: Math.round(cell.width * 0.28),+ height: 4,+ fill: palette.roles.accentSoft,+ cornerRadius: 2,+ }),+ )+ }++ if (captionText) {+ const capStart = type.sizes.label ?? type.sizes.body+ const cap = wrapFontSize(captionText, cell.width, Math.round(cell.height * 0.28), capStart, 14, 1.3)+ const capH = Math.min(Math.round(cell.height * 0.28), Math.round(cap.lines.length * cap.size * 1.3))+ content.push(+ createTextElement({+ text: captionText,+ x: Math.round(cell.x),+ y: Math.round(cell.y + cell.height - capH - Math.round(cell.height * 0.06)),+ width: Math.round(cell.width),+ height: capH,+ fontSize: cap.size,+ fontFamily: type.families.body,+ fill: palette.roles.inkSoft,+ align: 'center',+ }),+ )+ }+ }++ return { backdrops, content, warnings }+}++/** A visual frame: the deterministic stand-in a real image/asset+ * fills at the app layer (image sourcing is an app-layer tool, not+ * engine math). Aspect-locked 4:3. */+function visualFrame(band: Rect, captionH: number): { frame: Rect; warns: string[] } {+ const warns: string[] = []+ const frameMaxH = band.height - captionH - Math.round(band.height * 0.08)+ const frameW = Math.min(band.width * 0.72, Math.round(frameMaxH * (4 / 3)))+ const frameH = Math.round(frameW * 0.75)+ if (frameW < 120 || frameH < 90) warns.push('visual band too small for a 4:3 frame — consider more weight')+ return {+ frame: {+ x: Math.round(band.x + (band.width - frameW) / 2),+ y: Math.round(band.y + (band.height - captionH - frameH) / 2),+ width: Math.round(frameW),+ height: frameH,+ },+ warns,+ }+}++/** Mockup: one centered visual frame with an optional caption slot+ * (role 'label' or 'body'). */+export function buildMockup(block: BlockNode, ctx: BuildContext): ComposedElements {+ const { palette, type } = ctx+ const warnings: string[] = []+ const backdrops: AnyElement[] = []+ const content: AnyElement[] = []++ const band = ctx.rect+ const captionSlot = block.content.find((s) => s.role === 'label' || s.role === 'body')+ const captionH = captionSlot ? Math.round(band.height * 0.18) : 0+ const { frame, warns } = visualFrame(band, captionH)+ warnings.push(...warns)++ // thin accent frame behind, surface card in front (two-rect border)+ backdrops.push(+ createShapeElement('rect', {+ x: frame.x - 6,+ y: frame.y - 6,+ width: frame.width + 12,+ height: frame.height + 12,+ fill: palette.roles.accentSoft,+ cornerRadius: 26,+ opacity: 0.6,+ }),+ )+ backdrops.push(+ createShapeElement('rect', {+ x: frame.x,+ y: frame.y,+ width: frame.width,+ height: frame.height,+ fill: palette.roles.surface,+ cornerRadius: 20,+ opacity: 0.95,+ }),+ )+ // the placeholder mark: a slim centered glyph bar (deterministic)+ backdrops.push(+ createShapeElement('rect', {+ x: Math.round(frame.x + frame.width * 0.44),+ y: Math.round(frame.y + frame.height / 2 - 14),+ width: Math.round(frame.width * 0.12),+ height: 28,+ fill: palette.roles.accentSoft,+ cornerRadius: 4,+ }),+ )++ if (captionSlot && captionH > 0) {+ const cap = wrapFontSize(captionSlot.text, frame.width, captionH, type.sizes.label ?? type.sizes.body, 14, 1.3)+ const h = Math.min(captionH, Math.round(cap.lines.length * cap.size * 1.3))+ content.push(+ createTextElement({+ text: captionSlot.text,+ x: frame.x,+ y: Math.round(frame.y + frame.height + 12),+ width: frame.width,+ height: h,+ fontSize: cap.size,+ fontFamily: type.families.body,+ fill: palette.roles.inkSoft,+ align: 'center',+ }),+ )+ }++ return { backdrops, content, warnings }+}++/** Timeline: a horizontal route — a baseline with N stops, each a+ * dot with a value above and a caption below. Slots arrive as+ * alternating value/caption pairs (same convention as stat-row).+ * The classic schedule/journey band of event posters. */+export function buildTimeline(block: BlockNode, ctx: BuildContext): ComposedElements {+ const { palette, type } = ctx+ const warnings: string[] = []+ const backdrops: AnyElement[] = []+ const content: AnyElement[] = []++ const slots = block.content+ const count = Math.max(2, Math.min(6, block.count ?? Math.ceil(slots.length / 2)))+ const cells = gridInRect(ctx.rect, count, { columns: count, gap: 12, minCellWidth: 120, minCellHeight: 80 })+ if (cells.length < count) warnings.push(`timeline band fits only ${cells.length} of ${count} stops`)++ const midY = ctx.rect.y + Math.round(ctx.rect.height / 2)+ const firstCx = cells.length ? cells[0].x + Math.round(cells[0].width / 2) : ctx.rect.x+ const last = cells[cells.length - 1] ?? ctx.rect+ const lastCx = last.x + Math.round(last.width / 2)++ // the route: one baseline through all stops (accent-soft)+ backdrops.push(+ createShapeElement('rect', {+ x: firstCx,+ y: midY - 2,+ width: Math.max(0, lastCx - firstCx),+ height: 4,+ fill: palette.roles.accentSoft,+ cornerRadius: 2,+ }),+ )++ cells.forEach((cell, i) => {+ const value = slots[2 * i]+ const caption = slots[2 * i + 1]+ const cx = cell.x + Math.round(cell.width / 2)+ // the stop dot, ON the baseline+ backdrops.push(+ createShapeElement('ellipse', {+ x: cx - 7,+ y: midY - 7,+ width: 14,+ height: 14,+ fill: palette.roles.accent,+ }),+ )+ if (value?.text) {+ const v = wrapFontSize(value.text, cell.width, Math.round(cell.height * 0.42), Math.max(type.sizes.subline, 20), 14, 1.2)+ const vH = Math.min(Math.round(cell.height * 0.42), Math.round(v.lines.length * v.size * 1.2))+ content.push(+ createTextElement({+ text: value.text,+ x: Math.round(cell.x),+ y: Math.round(midY - 16 - vH),+ width: Math.round(cell.width),+ height: vH,+ fontSize: v.size,+ fontFamily: type.families.heading,+ bold: true,+ fill: palette.roles.ink,+ align: 'center',+ }),+ )+ }+ if (caption?.text) {+ const c = wrapFontSize(caption.text, cell.width, Math.round(cell.height * 0.34), type.sizes.label ?? type.sizes.body, 12, 1.25)+ const cH = Math.min(Math.round(cell.height * 0.34), Math.round(c.lines.length * c.size * 1.25))+ content.push(+ createTextElement({+ text: caption.text,+ x: Math.round(cell.x),+ y: midY + 16,+ width: Math.round(cell.width),+ height: cH,+ fontSize: c.size,+ fontFamily: type.families.body,+ fill: palette.roles.inkSoft,+ align: 'center',+ }),+ )+ }+ })++ return { backdrops, content, warnings }+}++/** Gallery: a 2- or 3-up grid of visual frames with optional short+ * captions — the storyboard band (photos the app layer fills). */+export function buildGallery(block: BlockNode, ctx: BuildContext): ComposedElements {+ const { palette, type } = ctx+ const warnings: string[] = []+ const backdrops: AnyElement[] = []+ const content: AnyElement[] = []++ const slots = block.content+ const count = Math.max(2, Math.min(3, block.count ?? 2))+ const cells = gridInRect(ctx.rect, count, { columns: count, gap: 16, minCellWidth: 140, minCellHeight: 100 })+ if (cells.length < count) warnings.push(`gallery band fits only ${cells.length} of ${count} frames`)++ cells.forEach((cell, i) => {+ const caption = slots[i]?.text+ const captionH = caption ? Math.round(cell.height * 0.22) : 0+ // accent border behind, surface card front (two-rect border)+ backdrops.push(+ createShapeElement('rect', {+ x: cell.x - 4,+ y: cell.y - 4,+ width: cell.width + 8,+ height: cell.height - captionH + 8,+ fill: palette.roles.accentSoft,+ cornerRadius: 14,+ opacity: 0.55,+ }),+ )+ backdrops.push(+ createShapeElement('rect', {+ x: cell.x,+ y: cell.y,+ width: cell.width,+ height: Math.max(40, cell.height - captionH),+ fill: palette.roles.surface,+ cornerRadius: 10,+ opacity: 0.95,+ }),+ )+ if (caption) {+ const cap = wrapFontSize(caption, cell.width, captionH, type.sizes.label ?? type.sizes.body, 12, 1.25)+ const h = Math.min(captionH, Math.round(cap.lines.length * cap.size * 1.25))+ content.push(+ createTextElement({+ text: caption,+ x: Math.round(cell.x),+ y: Math.round(cell.y + cell.height - h),+ width: Math.round(cell.width),+ height: h,+ fontSize: cap.size,+ fontFamily: type.families.body,+ fill: palette.roles.inkSoft,+ align: 'center',+ }),+ )+ }+ })++ return { backdrops, content, warnings }+}++/** Footer: one short closing line (venue, credits, contact) over a+ * hairline divider — the poster's sign-off band. */+export function buildFooter(block: BlockNode, ctx: BuildContext): ComposedElements {+ const { palette, type } = ctx+ const warnings: string[] = []+ const backdrops: AnyElement[] = []+ const content: AnyElement[] = []++ const slot = block.content[0]+ const text = slot?.text+ if (!text) {+ warnings.push('footer block without content — emitted an empty band')+ return { backdrops, content, warnings }+ }++ const band = ctx.rect+ // hairline divider across the top of the band+ backdrops.push(+ createShapeElement('rect', {+ x: band.x + Math.round(band.width * 0.1),+ y: band.y,+ width: Math.round(band.width * 0.8),+ height: 2,+ fill: palette.roles.accentSoft,+ cornerRadius: 1,+ }),+ )+ const start = Math.min(type.sizes.label ?? type.sizes.body, 22)+ const f = wrapFontSize(text, Math.round(band.width * 0.9), Math.round(band.height * 0.8), start, 12, 1.3)+ const h = Math.min(Math.round(band.height * 0.8), Math.round(f.lines.length * f.size * 1.3))+ content.push(+ createTextElement({+ text,+ x: Math.round(band.x + band.width * 0.05),+ y: Math.round(band.y + (band.height - h) / 2) + 6,+ width: Math.round(band.width * 0.9),+ height: h,+ fontSize: f.size,+ fontFamily: type.families.body,+ fill: palette.roles.inkSoft,+ align: 'center',+ }),+ )++ return { backdrops, content, warnings }+}++/** Dispatch: every declared block kind has a dedicated builder —+ * the design vocabulary is engine-owned, one kind at a time. */export function buildBlock(block: BlockNode, ctx: BuildContext): ComposedElements {- if (block.kind === 'feature-cards') return buildFeatureCards(block, ctx)- if (block.kind !== 'hero') {- const composed = buildHero(block, ctx)- return { ...composed, warnings: [...composed.warnings, `kind '${block.kind}' compiled with the generic stack — dedicated builder pending Phase C`] }+ switch (block.kind) {+ case 'feature-cards':+ return buildFeatureCards(block, ctx)+ case 'stat-row':+ return buildStatRow(block, ctx)+ case 'mockup':+ return buildMockup(block, ctx)+ case 'timeline':+ return buildTimeline(block, ctx)+ case 'gallery':+ return buildGallery(block, ctx)+ case 'footer':+ return buildFooter(block, ctx)+ case 'hero':+ default:+ return buildHero(block, ctx)}- return buildHero(block, ctx)}