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 design pipeline — research-grounded, self-correcting, honestly bounded
Ashiq Hussain Mir8c8742ea076d
diff --git a/docs/DESIGN-AGENT-ACCEPTANCE-REPORT.md b/docs/DESIGN-AGENT-ACCEPTANCE-REPORT.mdnew file mode 100644index 0000000..c49bb0d--- /dev/null+++ b/docs/DESIGN-AGENT-ACCEPTANCE-REPORT.md@@ -0,0 +1,106 @@+# DesignAgent — autonomous design pipeline acceptance report (24 Nov 2026)++**Branch:** `feat/design-agent` · **Research:** `research/AUTONOMOUS-AGENT-RESEARCH.md`+**What this is:** the Phase B design agent — a code-orchestrated autonomous+pipeline over the DesignSpec engine, built from the patterns that production+agent systems actually use (ReAct tool-registry discipline, the OpenAI Agents+SDK "code orchestration + evaluator loop" guidance, and PosterGen's staged+specialists with embedded design principles). The model plans and critiques;+deterministic code runs everything else and judges the result.++## The run (real planner model, real VLM, real renderer)++Brief: a 1080×1350 race poster — three verbatim lines (one with middle dots),+two required hexes (#0D47A1, #FF6F00), a stats band and a framed photo area.++```+extract-brief (deterministic) PASS — 3 required texts, 2 required colors+plan (GLM via z-ai chat) round 1 → brief-conformance FAIL: the model dropped+ "12km · Dachigam Road · 26 Jan" (the+ engine's own checks were GREEN — this+ failure is only visible at the agent+ layer, which is why it exists)+feedback → revise round 2 → still imperfect+feedback → revise round 3 → every required text/color/dimension carried;+ compile checks all PASS+render (exportPageToSVG in Chromium) all texts + both fills verified in the+ RENDERED SVG; balance 82% coverage+VLM critique (z-ai vision on the PNG) P1s and P2s listed below — advisory,+ never overriding the checks+```++3 model calls · 2 revision rounds · 15 s wall · outcome **passed**, honestly.++## What the evaluator loop caught++The round-1 spec **passed every engine check** — the compiler validates+spec→page fidelity, and the spec's own slots were internally consistent. What+was wrong was brief→spec fidelity: the model had dropped a user-required line.+The pipeline's `briefConformance()` check (required texts verbatim in slots,+required hexes in seeds, exact dimensions) is the evaluator the engine cannot+be, and the revision loop fixed it in one feedback round. This is the exact+Reflexion/evaluator-loop pattern from the research, with real stakes.++## What the VLM critique caught (and what it changed)++The first critique found, among other issues: *"Stat row baseline+misalignment: 'Dachigam Road' wraps to two lines and its underline/label sit+visibly lower than '12km'"* — a genuine **engine defect**. Fixed the same hour+(`buildStatRow` now places every cell on a uniform value block: shared+baseline for underlines and captions). Recompiled the SAME spec (deterministic,+zero model calls), re-rendered, re-critiqued: the issue drops out of the P1+class. The critique is advisory — it can drive engine and prompt improvements,+but it can never mark a run passed; only the deterministic checks can.++**Still open from the critique (the honest next-round list):** band rhythm+(~200px dead zones between blocks — stackInRect gap tuning), inkSoft at the+WCAG floor reads dim on saturated backgrounds (raise the contrast bar above+4.5 for poster distance), footer/stat duplication (planner prompt rule),+typographic pairing beyond the mood default, and a margins/frame system.++## The toolbox (every function the agent can use)++`extract-brief`, `parse-spec`, `compile-spec` (the engine: palette expansion,+type scale, band/grid layout, wrap-aware text, seed-guarantee colors,+contrast), `wrap-estimate`, `balance-report` — a typed registry+(`src/lib/design-agent/tools.ts`) that doubles as the planner's capability+catalog. The model seams (`plan`, `revise`, `critique`) run through the+`DesignAgentModel` interface — the same seam a BYOK production adapter or the+CLI adapter in `scripts/designspec-agent-run.ts` implements. The engine's+composition vocabulary grew to match: `stat-row` (big numbers + captions,+uniform baselines, accent underlines) and `mockup` (4:3 visual frame with+accent border) now have dedicated deterministic builders; `timeline`,+`gallery`, `footer` still compile via the generic stack with a pending-builder+warning.++## Guards and honesty (tested, not claimed)++- **bounded revisions** (default 3) — then the run fails honestly with all+ failures visible+- **cycle guard** — a model repeating its spec verbatim stops the loop+- **parse failures** are recoverable against the prior spec, or fail honestly+- 8 pipeline tests with a scripted model prove all of this deterministically+ (self-correction, recovery, guards, toolbox, critique parsing fail-closed)+- **1,639/1,639** branch suite · tsc clean · eslint clean++## Not exercised (no claims beyond it)++- No production BYOK provider adapter yet (the seam is built and the CLI+ adapter proves it end-to-end; wiring it into the app's agent route is the+ next integration step, alongside the chat loop that already exists).+- No auto-revision on critique findings (critique output is advisory and+ reported; feeding P1/P2 items back into one more revision round is+ designed-for but not yet automatic).+- Multi-script (Devanagari) corpus, human study — M-scope per the proposal.++## Reproduce++```+bun scripts/designspec-agent-run.ts run <promptFile> <outDir>+node scripts/designspec-render.cjs <outDir> "agent-run"+bun scripts/designspec-agent-run.ts critique <outDir>+```++Artifacts in `download/designspec-agent/`: the rendered poster (PNG/SVG), the+final spec, compile + render checks, and the full run report (stages, model+calls, revisions, elapsed, VLM critique).diff --git a/research/AUTONOMOUS-AGENT-RESEARCH.md b/research/AUTONOMOUS-AGENT-RESEARCH.mdnew file mode 100644index 0000000..b6d4f0a--- /dev/null+++ b/research/AUTONOMOUS-AGENT-RESEARCH.md@@ -0,0 +1,140 @@+# 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. This turn extends that vocabulary (stat-row, mockup builders) so+"professional" components exist to compose.++### 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) 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 adds the+same stage for generation: render → screenshot → VLM critique → optional+revision. The acceptance run in this sandbox exercises it with a real VLM+(z-ai `vision`); production runs BYOK. Critique output is advisory — it can+trigger one more revision round but can never override the deterministic+checks.++### 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.+- **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 (deterministic engine: palette, type, layout, checks)+ ─► [checks.failed → feedback → revise-spec (MODEL seam 2)] × ≤3, cycle-guarded+ ─► render (exportPageToSVG) → VLM critique (MODEL seam 3, optional,+ advisory) → optional final revision+ ─► run report: stages, model calls, revisions, 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..4b90cfd--- /dev/null+++ b/scripts/designspec-agent-run.ts@@ -0,0 +1,131 @@+// ─────────────────────────────────────────────────────────────+// DesignAgent real-model acceptance run (Phase B, 24 Nov 2026).+//+// Drives the autonomous pipeline end-to-end with a REAL planner+// model (z-ai CLI → GLM) at the model seam, exactly as the sandbox+// acceptance harness does for the compiler path:+//+// phase "run": prompt → extract-brief → plan (model) →+// parse → brief-conformance + compile+check →+// [feedback → revise (model)] × ≤3 → report+// writes spec/pages/checks/agent-report JSON+// phase "critique": after scripts/designspec-render.cjs produced+// rendered.png, a REAL VLM (z-ai vision) reviews+// the render — advisory only, never overriding+// the deterministic checks — and the result is+// merged into agent-report.json.+//+// Usage:+// bun scripts/designspec-agent-run.ts run <prompt> <outDir>+// node scripts/designspec-render.cjs <outDir> "agent-run"+// bun scripts/designspec-agent-run.ts critique <outDir>+//+// The pipeline itself is src/lib/design-agent/pipeline.ts; the CLI+// model adapter below implements the same DesignAgentModel seam a+// BYOK production adapter would.+// ─────────────────────────────────────────────────────────────++import { execFileSync } from 'node:child_process'+import { mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs'+import path from 'node:path'+import { runDesignAgent } from '@/lib/design-agent/pipeline'+import { parseCritiqueResponse, type DesignAgentModel } 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'++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,+ ),+}++const phase = process.argv[2]+const arg = process.argv[3]+const outDirArg = process.argv[4]++if (phase !== 'run' && phase !== 'critique' && phase !== 'recompile') {+ console.error('usage: bun scripts/designspec-agent-run.ts run <promptFile> <outDir> | 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 started = Date.now()+ const run = await runDesignAgent({ prompt, model: cliModel })+ const elapsedMs = Date.now() - started++ // 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(`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 ')}`)+ process.exit(run.outcome === 'passed' ? 0 : 1)+}++if (phase === 'critique') {+ 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) ══`)+ 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..84d48f5--- /dev/null+++ b/src/lib/design-agent/model.ts@@ -0,0 +1,106 @@+// ─────────────────────────────────────────────────────────────+// 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+}++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..dc75667--- /dev/null+++ b/src/lib/design-agent/pipeline.test.ts@@ -0,0 +1,236 @@+import { describe, expect, it } from 'vitest'+import { runDesignAgent } from './pipeline'+import { runDesignTool } from './tools'+import { parseCritiqueResponse, type DesignAgentModel } 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 and guards 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[]) {+ const planInputs: { feedback?: { failures: string[]; priorSpec: unknown } }[] = []+ const model: DesignAgentModel = {+ plan: async (req) => {+ planInputs.push({ feedback: req.feedback ? { failures: req.feedback.failures, priorSpec: req.feedback.priorSpec } : undefined })+ return replies[Math.min(planInputs.length - 1, replies.length - 1)]+ },+ }+ return { model, planInputs }+}++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)+ })+})++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('stat-row and mockup compile through the agent toolbox', () => {+ const spec = JSON.stringify({+ version: 'v2',+ name: 'stats + mockup',+ 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: 'mockup',+ weight: 3,+ content: [{ role: 'label', source: 'model', text: 'Last year at the finish line' }],+ },+ ],+ })++ it('dedicated builders emit the stats and the visual frame with all checks green', () => {+ const r = runDesignTool('compile-spec', { spec: JSON.parse(spec) })+ expect(r.ok).toBe(true)+ 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 ['12k+', '42', '5', 'runners finished', 'villages on the route', 'years running', 'Last year at the finish line']) {+ expect(texts).toContain(t)+ }+ // stat underline: slim accent rects (height 4) per stat cell+ const underlines = result.pages[0].elements.filter(+ (el) => el.type === 'rect' && (el as { height?: number }).height === 4,+ )+ expect(underlines.length).toBeGreaterThanOrEqual(3)+ // mockup frame: a surface card large enough to be a real frame+ const frame = result.pages[0].elements.find(+ (el) => el.type === 'rect' && (el as { width?: number }).width !== undefined && ((el as { width: number }).width > 300) && (el as { fill?: string }).fill === result.palette.roles.surface,+ )+ expect(frame).toBeTruthy()+ })+})diff --git a/src/lib/design-agent/pipeline.ts b/src/lib/design-agent/pipeline.tsnew file mode 100644index 0000000..9497865--- /dev/null+++ b/src/lib/design-agent/pipeline.ts@@ -0,0 +1,249 @@+// ─────────────────────────────────────────────────────────────+// 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 (optionally) 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+// required text).+//+// Guards (machine protection, not product caps — the repo's+// protocol.ts philosophy):+// · maxRevisions (default 3) — bounded self-correction rounds+// · cycle guard — a model that repeats its previous spec verbatim+// is looping, not progressing: stop, disclose+// · 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 } from './model'+import { runDesignTool, toolboxPromptSection } from './tools'+import { PLANNER_SYSTEM, planUserPrompt, revisionUserPrompt } from './prompts'++export interface DesignAgentLimits {+ /** bounded self-correction rounds (guard, not a product cap) */+ maxRevisions: number+}++export const DEFAULT_LIMITS: DesignAgentLimits = { maxRevisions: 3 }++export type AgentOutcome = 'passed' | 'failed-honestly' | 'guard-cycled'++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 AgentRunReport {+ stages: AgentStageRecord[]+ modelCalls: number+ revisionRounds: number+ cycleGuard: boolean+ brief: DesignBrief+ spec?: DesignSpec+ limits: DesignAgentLimits+}++export interface DesignAgentRun {+ outcome: AgentOutcome+ /** the last 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) failures.push(`required text missing from the spec — add it as a user-required slot with this EXACT text: "${t.text}"`)+ }+ 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). */+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+}++/**+ * The autonomous design run:+ * extract-brief → plan (model) → parse → compile+check →+ * [failures → revise (model)] × ≤ maxRevisions → report.+ */+export async function runDesignAgent(opts: {+ prompt: string+ model: DesignAgentModel+ limits?: Partial<DesignAgentLimits>+}): Promise<DesignAgentRun> {+ const limits = { ...DEFAULT_LIMITS, ...opts.limits }+ const stages: AgentStageRecord[] = []+ let modelCalls = 0++ // ── 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 },+ }+ }+ 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++ while (true) {+ // 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 },+ }+ }+ revisionRounds += 1+ feedback = { round: revisionRounds, failures: [parsed.error], warnings: [], priorSpec: lastSpec }+ 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 },+ }+ }+ 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 })+ const balance = runDesignTool('balance-report', { pages: compiled.pages, width: spec.format.width, height: 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 })+ return {+ outcome: 'passed',+ pages: compiled.pages,+ checks: compiled.checks,+ briefConformance: [],+ warnings: [...compiled.warnings, ...balance.notes],+ report: { stages, modelCalls, revisionRounds, cycleGuard: false, brief, spec, limits },+ }+ }++ // 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 },+ }+ }+ revisionRounds += 1+ feedback = { round: revisionRounds, failures: allFailures, warnings: compiled.warnings, priorSpec: spec }+ }+}++/** 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+}++export { extractJsonObject }diff --git a/src/lib/design-agent/prompts.ts b/src/lib/design-agent/prompts.tsnew file mode 100644index 0000000..166e8a7--- /dev/null+++ b/src/lib/design-agent/prompts.ts@@ -0,0 +1,90 @@+// ─────────────────────────────────────────────────────────────+// 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.+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, gallery, footer (compiled via the generic stack today).+4. stat-row 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.++${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[] = []+ 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..c55e7b8--- /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), 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..e793908 100644--- a/src/lib/design-engine/compositions.ts+++ b/src/lib/design-engine/compositions.ts@@ -268,11 +268,187 @@ 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. Each value carries a small accent underline — the+ * emphasis device the seed-guarantee machinery prefers. */+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 })+ })++ // uniform value block across the row (found by the VLM critique of+ // the acceptance run: a wrapping value shifted its underline below+ // the one-line values' — every cell now reserves the max line+ // count, so underlines and captions share one baseline)+ 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 }+}++/** Mockup: a centered rounded 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). A thin accent frame sits+ * behind a surface card, and an optional caption slot renders under+ * the frame. The frame keeps a 4:3 aspect within the band. */+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 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)+ const frameX = Math.round(band.x + (band.width - frameW) / 2)+ const frameY = Math.round(band.y + (band.height - captionH - frameH) / 2)+ if (frameW < 180 || frameH < 120) warnings.push('mockup band too small for a 4:3 frame — consider more weight')++ // thin accent frame behind, surface card in front (two-rect border)+ backdrops.push(+ createShapeElement('rect', {+ x: frameX - 6,+ y: frameY - 6,+ width: frameW + 12,+ height: frameH + 12,+ fill: palette.roles.accentSoft,+ cornerRadius: 26,+ opacity: 0.6,+ }),+ )+ backdrops.push(+ createShapeElement('rect', {+ x: frameX,+ y: frameY,+ width: frameW,+ height: frameH,+ 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(frameX + frameW * 0.44),+ y: Math.round(frameY + frameH / 2 - 14),+ width: Math.round(frameW * 0.12),+ height: 28,+ fill: palette.roles.accentSoft,+ cornerRadius: 4,+ }),+ )++ if (captionSlot && captionH > 0) {+ const cap = wrapFontSize(captionSlot.text, frameW, 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: frameX,+ y: Math.round(frameY + frameH + 12),+ width: frameW,+ height: h,+ fontSize: cap.size,+ fontFamily: type.families.body,+ fill: palette.roles.inkSoft,+ align: 'center',+ }),+ )+ }++ return { backdrops, content, warnings }+}++/** Dispatch: hero, feature-cards, stat-row and mockup have dedicated+ * builders; other kinds compile through the generic hero stack with a+ * warning (Phase C gives each kind its own builder). */export function buildBlock(block: BlockNode, ctx: BuildContext): ComposedElements {if (block.kind === 'feature-cards') return buildFeatureCards(block, ctx)+ if (block.kind === 'stat-row') return buildStatRow(block, ctx)+ if (block.kind === 'mockup') return buildMockup(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`] }