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(v0.32.4): deterministic design correctness — enforced plans, duplicate detection, wrap-up audits, run ledger (#92)
Ashiq Hussain Mir4d5fa3a42ca5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 17962f9..3c2fac9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,31 @@All notable changes to Canvix will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).+### Added — v0.32.4: deterministic design correctness++- **Hard plan validation:** plan_layout REJECTS invalid geometry+ (gaps < 40px computed for real — the old 24px overlap slack is+ gone; bands beyond the page; negative y) with the exact numbers;+ safe-area intrusion stays a warning. Validated bands ride the+ plan action.+- **Duplicate detection in the quality audit:** near-twin texts+ (same normalized text + overlapping boxes / centers < 80px) and+ layered twin shapes (same type/size/fill + centers < 24px) are+ reported with both ids; intentional repetition (3-card rows,+ distant repeats) passes; nothing is auto-deleted.+- **Plan adherence:** an empty planned section is a finding.+- **Wrap-up audits too:** guard exits with applied changes run the+ audit once and disclose the residue — the live coffee run's+ duplicate survived precisely because the wrap-up path skipped it.+- **Per-design run ledger** (`DesignAgentRun`, migration 0015):+ compact rows of what each run did, fed into the next run's system+ prompt; best-effort, never blocks a run.+- **list_fonts is real:** the sanitizer has pointed at it since+ v0.29 but the tool never existed. Read tool over the 369-family+ catalog (query + cap); the prompt's font sample shows the total.+- **Margin advisory:** text deep in the 6% margin (>40px) is+ disclosed; full-bleed shapes are a design choice, not a finding.+### Added — v0.32.3: plan-first, geometry ground truth, conversation memory- **Conversation history reaches the loop:** `LoopDeps.history`diff --git a/ROADMAP.md b/ROADMAP.mdindex 48c7051..b2262a2 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -1,3 +1,4 @@+- v0.32.4 — deterministic design correctness: hard plan validation (real ≥40px gaps, bounds), duplicate-text/shape detection, plan adherence, wrap-up audit disclosure, per-design run ledger (0015), the phantom list_fonts tool made real.# Canvix Roadmap — where we are, what's next> **Status date:** 2026-11-25 · **Changelog state:** v0.31.0 · `package.json` 0.31.0 · **latest published GitHub release:** v0.31.0 · **Test posture:** 1,693 unit tests across 127 test files (verified full run, 25 Nov, the v0.31.0 release run) · 39 e2e spec files + the plugins & stock-video gated suites · CI gates every PR (`lint-unit` incl. production build + `e2e` running all three suites) · `npm audit` **0 vulnerabilities**.diff --git a/docs/UNIFIED-AI-MILESTONE.md b/docs/UNIFIED-AI-MILESTONE.mdindex 32dce60..1fd4738 100644--- a/docs/UNIFIED-AI-MILESTONE.md+++ b/docs/UNIFIED-AI-MILESTONE.md@@ -378,3 +378,98 @@ compaction-keeps-the-head, the geometry block's computed numbers, theplan-first bounce + redirect, planned-runs-never-bounced,edit-runs-exempt). 14 scripted create-run tests updated to encodeplan-first (their models now plan before building).++---++# v0.32.4 — deterministic design correctness++**The ask (external review of v0.32.3):** telling the model to follow+a plan is not enforcing a geometrically valid plan; the live run+still left a duplicated subline that a human follow-up had to+remove. The next milestone must enforce correctness in the+orchestration and validation layers, not add prompt instructions.++All five review findings were verified in source before coding:++| Finding | Verdict |+| --- | --- |+| plan validator permitted 24px overlap + never rejected | CONFIRMED — `sorted[i].y < prev.y + prev.h - 24`, problems were warnings with `ok: true` |+| no duplicate-element detection in the audit | CONFIRMED — the live coffee run's residue could not be caught |+| plan-first advisory after one bounce | CONFIRMED by design (anti-deadlock); now backed by a HARD validator |+| memory = 12 chat turns, no execution ledger | CONFIRMED — added a per-design run ledger |+| knowledge scoped (40-font sample) | CONFIRMED — and the sanitizer pointed at a **`list_fonts` tool that never existed** (a phantom tool) |++## 1. Hard plan validation (`tools.ts`)++`plan_layout` now REJECTS invalid geometry with the exact numbers:+gaps computed as `current.y - (prev.y + prev.h)` must be ≥ 40px+(39px is rejected, 40 accepted — boundary tested), bands must lie+inside `0..H` (the `H × 1.02` slack is gone), negative y rejected.+Safe-area intrusion stays a WARNING (content may sit inside a band+that starts high; the audit flags text that actually hugs the edge).+Sanitize errors are retryable, not strikes — the model fixes the+bands and resends. The validated plan's structured bands now ride+the `__planLayout` action.++## 2. Duplicate detection (`audit.ts`)++- **Duplicate texts**: identical normalized text (case/whitespace+ insensitive) with overlapping boxes or centers within 80px — the+ near-twin the live run left. Distant repeats (page furniture,+ symmetric CTAs) are NOT flagged.+- **Duplicate shapes**: same type + size (±2px) + fill + centers+ within 24px — layered twins (re-add artifacts). Repeated cards at+ different x pass (intentional repetition, tested).+- Findings name both element ids; nothing is auto-deleted — the+ model decides, and deletion still needs user approval.+- **Text deep in the 6% margin** (>40px intrusion) is disclosed as+ advisory; shallow bleed and full-bleed shapes are not flagged.++## 3. Plan adherence++The quality audit receives the run's validated bands and reports+any planned section that holds no element ("build it, or the canvas+no longer matches the plan").++## 4. The wrap-up hole (found during verification)++The live duplicate survived because the cycle-guard WRAP-UP path+skipped the audit that the done path runs. `guardExit` now audits+too: a guard exit with applied changes runs the audit once and+DISCLOSES the residue in the summary + verification ("disclosed,+unfixed") — no fix round (the run is ending), but the next message+gets named, targetable findings.++## 5. Per-design run ledger (Prisma `DesignAgentRun`, migration 0015)++One compact row per run (mode, request, action count, summary,+disclosed findings). The route reads the last 3 rows into the next+run's system prompt as "YOUR RECENT RUNS IN THIS DESIGN" — grounded+execution memory of what the agent itself did, distinct from the+chat history (what the user said). The canvas state stays the+authority. Ledger I/O is best-effort: a ledger failure can never+break a run. Migration 0015 was verified statement-exact against+`prisma migrate diff`.++## 6. The phantom `list_fonts` tool (now real)++The sanitizer's font errors have said "Full list via list_fonts"+since v0.29 — the tool never existed; the model was being directed+at a phantom. `list_fonts` is now a read tool over the 369-family+catalog (substring query, capped listing), and the system prompt's+font sample carries the real total + the discovery pointer.++## Verification-then-stop (unchanged chain, stronger checks)++brief contract → quality audit (now with duplicates, margins, plan+adherence) → grounded vision critique → honest INCOMPLETE framing —+plus the wrap-up disclosure above.++## Evidence++1,733/1,733 unit (9 new regressions: twin texts flagged, 3-card row+and distant repeats not flagged, layered twin shapes flagged,+margin advisory with shallow-bleed tolerance, empty-section+adherence, wrap-up residue disclosure, list_fonts search/cap/no-+match, ledger rendering + absence, hard validator boundaries incl.+the 39/40px edge and beyond-page rejection). Live re-test below.diff --git a/prisma/migrations/0015_design_agent_runs/migration.sql b/prisma/migrations/0015_design_agent_runs/migration.sqlnew file mode 100644index 0000000..60bcdd4--- /dev/null+++ b/prisma/migrations/0015_design_agent_runs/migration.sql@@ -0,0 +1,22 @@+-- v0.32.4: per-design agent run ledger — compact records of what each+-- Canvix AI run did on a design, fed back into the next run's context.++-- CreateTable+CREATE TABLE "DesignAgentRun" (+ "id" TEXT NOT NULL,+ "designId" TEXT NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "mode" TEXT NOT NULL,+ "request" VARCHAR(240) NOT NULL,+ "summary" VARCHAR(600) NOT NULL,+ "toolCalls" INTEGER NOT NULL DEFAULT 0,+ "findings" VARCHAR(1200),++ CONSTRAINT "DesignAgentRun_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE INDEX "DesignAgentRun_designId_createdAt_idx" ON "DesignAgentRun"("designId", "createdAt");++-- AddForeignKey+ALTER TABLE "DesignAgentRun" ADD CONSTRAINT "DesignAgentRun_designId_fkey" FOREIGN KEY ("designId") REFERENCES "Design"("id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 31159b8..9d9f008 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -32,18 +32,18 @@ datasource db {// no OAuth, no external provider) so self-hosting stays free forever.// Passwords are scrypt hashes from node:crypto (see src/lib/auth/passwords.ts).model User {- id String @id @default(cuid())+ id String @id @default(cuid())// lowercase, 3–32 chars, [a-z0-9_-] (enforced in src/lib/auth/validate.ts)- username String @unique+ username String @uniquepasswordHash String// v0.16 (A1): admin console access. "user" | "admin". Effective admin ALSO// honours the CANVIX_ADMIN_USERS env bootstrap (src/lib/admin/guard.ts) so// the first admin exists without CLI surgery; this column is what the// console manages afterwards.- role String @default("user")- createdAt DateTime @default(now())- designs Design[] @relation("DesignOwner")- folders Folder[] @relation("FolderOwner")+ role String @default("user")+ createdAt DateTime @default(now())+ designs Design[] @relation("DesignOwner")+ folders Folder[] @relation("FolderOwner")sessions Session[]aiProviders UserAIProvider[]apiKeys ApiKey[]@@ -98,15 +98,15 @@ model Session {// delete, so the 401 reason can say "revoked" and the audit trail// (lastUsedAt) survives.model ApiKey {- id String @id // sha256(token) hex- userId String- user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ id String @id // sha256(token) hex+ userId String+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)label String// CSV of API_KEY_SCOPES, or 'all' (sugar for every current scope)- scopes String @default("designs:read")- createdAt DateTime @default(now())+ scopes String @default("designs:read")+ createdAt DateTime @default(now())lastUsedAt DateTime?- expiresAt DateTime?+ expiresAt DateTime?revokedAt DateTime?@@index([userId])@@ -114,18 +114,18 @@ model ApiKey {// A user design / project — the core artifact of Canvix.model Design {- id String @id @default(cuid())- name String @default("Untitled design")- width Int @default(1080)- height Int @default(1080)+ id String @id @default(cuid())+ name String @default("Untitled design")+ width Int @default(1080)+ height Int @default(1080)// Structured document: { pages: PageData[], ... } — stored as native jsonb- pages Json @default("[]")- thumbnail String? // small dataURL preview- source String @default("blank") // blank | template:<id> | duplicate:<id> | resize:<id>+ pages Json @default("[]")+ thumbnail String? // small dataURL preview+ source String @default("blank") // blank | template:<id> | duplicate:<id> | resize:<id>// v0.9: owning account. null = link-accessible design (pre-accounts// behaviour — anonymous editing keeps working for legacy + shared links).ownerId String?- owner User? @relation("DesignOwner", fields: [ownerId], references: [id], onDelete: SetNull)+ owner User? @relation("DesignOwner", fields: [ownerId], references: [id], onDelete: SetNull)// v0.9.1: anonymous attribution — sha256 of the canvix_anon cookie that// was set when an anonymous browser created this design. adopt-all only// claims rows whose anonKey matches the caller's cookie, so one account@@ -137,18 +137,23 @@ model Design {// filed under. null = "All designs" (the root; unchanged pre-v0.14// behaviour). Deleting a folder unfiles its designs (SetNull) — a// folder delete never destroys work.- folderId String?- folder Folder? @relation("DesignFolder", fields: [folderId], references: [id], onDelete: SetNull)+ folderId String?+ folder Folder? @relation("DesignFolder", fields: [folderId], references: [id], onDelete: SetNull)// soft delete (dashboard Trash) — null = live design- deletedAt DateTime?+ deletedAt DateTime?versions DesignVersion[]// v0.32 (Unified Canvix AI): the brief contract an autonomous// generation was verified against, persisted on the applied design —// chat-agent refinements of the SAME design merge it into their run// brief so verified requirements survive refinement- provenance DesignProvenance? @relation("DesignProvenance")- createdAt DateTime @default(now())- updatedAt DateTime @updatedAt+ provenance DesignProvenance? @relation("DesignProvenance")+ // v0.32.4: per-design agent run ledger — compact records of what+ // each Canvix AI run did (mode, request, actions, outcome), fed+ // back into the next run's context. The canvas state stays the+ // authority; this explains how it got there.+ agentRuns DesignAgentRun[] @relation("DesignAgentRuns")+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt@@index([ownerId])@@index([anonKey])@@ -263,12 +268,12 @@ model DesignEvent {// exclusive to one design: every heartbeat for a second design failed with// P2002 (production incident 2026-10-29).model Presence {- id String // = participant id- designId String- name String- color String- cursor Json? // { page: number, x: number, y: number, selection?: string[] }- lastSeen DateTime @default(now()) @updatedAt+ id String // = participant id+ designId String+ name String+ color String+ cursor Json? // { page: number, x: number, y: number, selection?: string[] }+ lastSeen DateTime @default(now()) @updatedAt@@id([designId, id])@@index([designId, lastSeen])@@ -276,7 +281,7 @@ model Presence {// Canvas-anchored comment threads (author identity is the local participant).model Comment {- id String @id @default(cuid())+ id String @id @default(cuid())designId StringpageId Stringx Float // anchor in page coordinates (fraction of page size, 0..1)@@ -287,9 +292,9 @@ model Comment {authorColor Stringbody StringparentId String? // reply threading- resolved Boolean @default(false)- createdAt DateTime @default(now())- updatedAt DateTime @updatedAt+ resolved Boolean @default(false)+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt@@index([designId, createdAt])@@index([designId, resolved])@@ -368,9 +373,9 @@ model PluginInstall {}model PluginAsset {- id String @id @default(cuid())+ id String @id @default(cuid())installId String- install PluginInstall @relation(fields: [installId], references: [id], onDelete: Cascade)+ install PluginInstall @relation(fields: [installId], references: [id], onDelete: Cascade)path Stringmime Stringbytes Bytes@@ -399,12 +404,12 @@ model AppConfig {// table × days × status codes. Rows older than 90 days are swept lazily.// CANVIX_TRAFFIC=0 opts an instance out entirely.model TrafficStat {- id BigInt @id @default(autoincrement())- day DateTime // UTC midnight- route String // logical route name, e.g. "GET /api/designs"- method String- status Int- hits Int @default(0)+ id BigInt @id @default(autoincrement())+ day DateTime // UTC midnight+ route String // logical route name, e.g. "GET /api/designs"+ method String+ status Int+ hits Int @default(0)@@unique([day, route, method, status])@@index([day])@@ -416,9 +421,9 @@ model TrafficStat {// the two surfaces that mean "someone used Canvix today" (design list /// editor open), so it adds no extra auth resolution anywhere.model DailyActive {- id BigInt @id @default(autoincrement())+ id BigInt @id @default(autoincrement())day DateTime- actor String+ actor String@@unique([day, actor])}@@ -465,3 +470,25 @@ model BrandKitRecord {@@index([ownerId])@@index([anonKey])}++// ── v0.32.4: per-design agent run ledger ──────────────────────+// One row per Canvix AI run on a design (create/edit/improve/+// review). Compact by design: mode + request + action count + the+// run's own summary (trimmed). The route reads the last few rows+// into the next run's system prompt as "YOUR RECENT RUNS IN THIS+// DESIGN" — grounded memory of what the agent itself did, distinct+// from the chat history (what the user said). findings keeps the+// disclosed audit/vision residue so a follow-up can target it.+model DesignAgentRun {+ id String @id @default(cuid())+ designId String+ design Design @relation("DesignAgentRuns", fields: [designId], references: [id], onDelete: Cascade)+ createdAt DateTime @default(now())+ mode String // create | edit | improve | review | plan+ request String @db.VarChar(240)+ summary String @db.VarChar(600)+ toolCalls Int @default(0)+ findings String? @db.VarChar(1200)++ @@index([designId, createdAt])+}diff --git a/src/app/api/ai/agent/route.ts b/src/app/api/ai/agent/route.tsindex f4261a0..b5ae534 100644--- a/src/app/api/ai/agent/route.ts+++ b/src/app/api/ai/agent/route.ts@@ -19,6 +19,7 @@ import { critiqueWithVision } from '@/lib/agent/vision'import { getClientForSlotForUser } from '@/lib/ai/provider'import { getSessionUser } from '@/lib/auth/session'import { getDesignProvenance } from '@/lib/design-provenance'+import { db } from '@/lib/db'export const runtime = 'nodejs'export const maxDuration = 800@@ -366,8 +367,30 @@ async function __canvix_post(req: NextRequest) {// find this bridge (protocol detail: rides an observation)emit({ v: AGENT_PROTOCOL_VERSION, type: 'observation', stepIndex: 0, message: `__runId:${runId}` })+ // v0.32.4: per-design run ledger — the last few runs in+ // THIS design (mode, request, actions, outcome) enter the+ // system prompt. Best-effort: a ledger failure must never+ // break the run itself.+ let ledgerLines: string[] = []+ if (design.designId) {+ try {+ const rows = await db.designAgentRun.findMany({+ where: { designId: design.designId },+ orderBy: { createdAt: 'desc' },+ take: 3,+ })+ ledgerLines = rows.map(+ (r) =>+ `${r.mode} "${r.request.slice(0, 80)}" → ${r.toolCalls} action(s): ${r.summary.slice(0, 160)}${r.findings ? ` [residue to fix: ${r.findings.slice(0, 140)}]` : ''}`,+ )+ } catch {+ /* best-effort — run without the ledger */+ }+ }++ let loopResult: Awaited<ReturnType<typeof runAgentLoop>> | null = nulltry {- await runAgentLoop({+ loopResult = await runAgentLoop({chat,design,mode,@@ -378,6 +401,9 @@ async function __canvix_post(req: NextRequest) {// v0.32.3: the conversation this request arrives in —// the loop's model sees the prior turns verbatimhistory,+ // v0.32.4: what the agent's recent runs did to THIS+ // design — grounded execution memory+ ledger: ledgerLines,brief,skills,emit,@@ -437,7 +463,12 @@ async function __canvix_post(req: NextRequest) {refreshedContext: () => bridge.latestDesign,// v0.29: audit the freshest design snapshot the panel acked// (v0.29.3: the brief rides along for strip detection)- auditDesign: () => runDesignAudit(bridge.latestDesign ?? design, brief),+ // v0.29: audit the freshest design snapshot the panel acked+ // (v0.29.3: the brief rides along for strip detection;+ // v0.32.4: so do the run's validated plan bands — the+ // audit checks duplicate elements, margins and that no+ // planned section was left empty)+ auditDesign: (bands) => runDesignAudit(bridge.latestDesign ?? design, brief, bands),validateBriefOnClient: async () => {// consume an early answer first, then wait for a live oneif (bridge.pendingBriefResult) {@@ -461,6 +492,31 @@ async function __canvix_post(req: NextRequest) {})} finally {bridges.delete(runId)+ // v0.32.4: persist the run ledger row — what THIS run did,+ // so the next run in this design starts with grounded+ // execution memory. Best-effort: the run's outcome is+ // already streamed; a ledger write failure never+ // surfaces as an agent error.+ if (design.designId) {+ try {+ await db.designAgentRun.create({+ data: {+ designId: design.designId,+ mode,+ request: message.slice(0, 240),+ summary: String(loopResult?.summary ?? '').slice(0, 600),+ toolCalls: loopResult?.toolCalls ?? 0,+ findings:+ (loopResult?.findings ?? [])+ .map((f) => `${f.severity} ${f.issue}`)+ .join(' | ')+ .slice(0, 1200) || null,+ },+ })+ } catch {+ /* best-effort ledger */+ }+ }}} catch (err) {emit({diff --git a/src/lib/agent/audit.ts b/src/lib/agent/audit.tsindex 3f148a7..6c7d65c 100644--- a/src/lib/agent/audit.ts+++ b/src/lib/agent/audit.ts@@ -100,9 +100,16 @@ function effectiveBackdrop(text: AgentElementCtx, els: AgentElementCtx[], pageBg}/** Worst N issues, human-readable and FIXABLE (the model acts on these). */+export interface PlanBand {+ name: string+ y: number+ h: number+}+export function auditDesign(d: AgentDesignCtx,brief?: { requiredColors?: { hex: string; tier?: string }[] } | null,+ planBands?: PlanBand[],): string[] {const issues: string[] = []const els = d.elements ?? []@@ -233,6 +240,107 @@ export function auditDesign(}}+ // 8. DUPLICATE TEXT (v0.32.4): the same normalized text twice with+ // boxes that overlap or centers within 80px — the near-twin the+ // live coffee run left behind (a human had to remove it).+ // Distant repeats (page furniture, repeated distant labels) are+ // intentional and NOT flagged — proximity is the discriminator.+ const norm = (t: string | undefined) => String(t ?? '').trim().toLowerCase().replace(/\s+/g, ' ')+ let dupTextHits = 0+ for (let i = 0; i < texts.length; i++) {+ for (let j = i + 1; j < texts.length; j++) {+ const a = texts[i]+ const b = texts[j]+ const na = norm(a.text)+ if (!na || na !== norm(b.text)) continue+ const ba = box(a)+ const bb = box(b)+ const cx = (e: { x: number; y: number; w: number; h: number }) => ({ x: e.x + e.w / 2, y: e.y + e.h / 2 })+ const ca = cx(ba)+ const cb = cx(bb)+ const near = Math.hypot(ca.x - cb.x, ca.y - cb.y) < 80+ const overlapped = coverage(a, b) > 0.2 || coverage(b, a) > 0.2+ if (!near && !overlapped) continue+ dupTextHits += 1+ if (dupTextHits <= 3) {+ issues.push(+ `Duplicate text: "${na.slice(0, 30)}" exists twice (text#${a.id} at (${Math.round(ba.x)},${Math.round(ba.y)}) and text#${b.id} at (${Math.round(bb.x)},${Math.round(bb.y)})) — delete one (delete_elements) or move the other where it belongs.`,+ )+ }+ }+ }+ if (dupTextHits > 3) issues.push(`…and ${dupTextHits - 3} more duplicate text pairs.`)++ // 9. DUPLICATE SHAPES (v0.32.4): same type + same size (±2px) ++ // same fill + centers within 24px — a layered twin, almost+ // always a re-add artifact. Repeated cards at different x are+ // intentional and pass (their centers are far apart).+ const shapes = els.filter((e) => e && e.type !== 'text')+ let dupShapeHits = 0+ for (let i = 0; i < shapes.length; i++) {+ for (let j = i + 1; j < shapes.length; j++) {+ const a = shapes[i]+ const b = shapes[j]+ if (a.type !== b.type) continue+ const fa = a.fill ?? ''+ const fb = b.fill ?? ''+ if (fa !== fb) continue+ const ba = box(a)+ const bb = box(b)+ if (Math.abs(ba.w - bb.w) > 2 || Math.abs(ba.h - bb.h) > 2) continue+ if (Math.hypot(ba.x - bb.x, ba.y - bb.y) > 24) continue+ dupShapeHits += 1+ if (dupShapeHits <= 2) {+ issues.push(+ `Duplicate shape: ${a.type}#${a.id} and ${b.type}#${b.id} are stacked at the same position with the same size and fill — delete one (delete_elements; approval will be asked).`,+ )+ }+ }+ }++ // 10. TEXT IN THE MARGIN (v0.32.4, advisory): text hugging a page+ // edge by >40px inside the 6% margin zone — a readability+ // risk, not a hard failure (shapes may full-bleed by design).+ if (d.width && d.height) {+ const mx = d.width * 0.06+ const my = d.height * 0.06+ let marginHits = 0+ for (const t of texts) {+ const b = box(t)+ const intrusions: string[] = []+ if (b.x < mx - 40) intrusions.push(`left (x=${Math.round(b.x)}, safe ≥ ${Math.round(mx)})`)+ if (b.y < my - 40) intrusions.push(`top (y=${Math.round(b.y)}, safe ≥ ${Math.round(my)})`)+ if (b.x + b.w > d.width! - mx + 40) intrusions.push(`right (ends ${Math.round(b.x + b.w)}, safe ≤ ${Math.round(d.width! - mx)})`)+ if (b.y + b.h > d.height! - my + 40) intrusions.push(`bottom (ends ${Math.round(b.y + b.h)}, safe ≤ ${Math.round(d.height! - my)})`)+ if (intrusions.length) {+ marginHits += 1+ if (marginHits <= 2) {+ issues.push(`Text "${String(t.text ?? '').slice(0, 24)}" sits deep inside the page margin: ${intrusions.join(', ')} — move it into the safe area.`)+ }+ }+ }+ }++ // 11. PLAN ADHERENCE (v0.32.4): every planned section band should+ // hold at least one element — an empty band means the build+ // diverged from the validated plan (missing section).+ if (planBands?.length) {+ let emptyBands = 0+ for (const band of planBands) {+ const has = els.some((e) => {+ const b = box(e)+ const iy = Math.max(0, Math.min(b.y + b.h, band.y + band.h) - Math.max(b.y, band.y))+ return iy > 0+ })+ if (!has) {+ emptyBands += 1+ if (emptyBands <= 3) {+ issues.push(`Planned section "${band.name}" (y ${Math.round(band.y)}..${Math.round(band.y + band.h)}) is empty — build it, or the canvas no longer matches the plan.`)+ }+ }+ }+ }+return issues.slice(0, 12)}diff --git a/src/lib/agent/harness.test.ts b/src/lib/agent/harness.test.tsindex e814723..3ebca10 100644--- a/src/lib/agent/harness.test.ts+++ b/src/lib/agent/harness.test.ts@@ -106,7 +106,7 @@ describe('harness · tool matrix', () => {'duplicate_elements', 'group_elements', 'ungroup_elements', 'reorder_layers','animate_elements', 'set_page_transition', 'delete_page', 'set_brand_kit', 'resize_design','mask_image', 'adjust_image', 'measure_text', 'set_text_spans', 'export_design',- 'add_stock_video', 'validate_brief', 'plan_layout',+ 'add_stock_video', 'validate_brief', 'plan_layout', 'list_fonts',]for (const t of AGENT_TOOLS) expect(covered, `add harness cases for new tool "${t.name}"`).toContain(t.name)expect(covered).toHaveLength(AGENT_TOOLS.length)@@ -264,7 +264,7 @@ describe('harness · tool matrix', () => {})it('read tools are exactly the state/measure/validate/plan set', () => {const reads = AGENT_TOOLS.filter((t) => t.risk === 'read').map((t) => t.name)- expect(reads.sort()).toEqual(['get_page_state', 'goto_page', 'measure_text', 'plan_layout', 'validate_brief'])+ expect(reads.sort()).toEqual(['get_page_state', 'goto_page', 'list_fonts', 'measure_text', 'plan_layout', 'validate_brief'])})it('CASE G: quality audit — one self-critique fix round before done is accepted', async () => {@@ -1107,7 +1107,7 @@ describe('audit heuristics (v0.29)', () => {elements: [{ id: 'b1', type: 'text', text: 'Dark', fill: '#111122', fontSize: 48, x: 0, y: 0, width: 600, height: 90 }],})expect(flagged.join('\n')).toContain('Low contrast')- expect(auditDesign({ width: 1080, height: 1080, background: '#FFFFFF', elements: [{ id: 'c1', type: 'text', text: 'OK', fill: '#111111', fontSize: 32, x: 0, y: 0, width: 300, height: 60 }] })).toEqual([])+ expect(auditDesign({ width: 1080, height: 1080, background: '#FFFFFF', elements: [{ id: 'c1', type: 'text', text: 'OK', fill: '#111111', fontSize: 32, x: 100, y: 100, width: 300, height: 60 }] })).toEqual([])})})@@ -1439,7 +1439,7 @@ describe('v0.29.3 · loop: planning + fail-closed acks', () => {background: '#090B1A',sections: [{ name: 'headline', y: 60, height: 140, contains: 'CANVIX' },- { name: 'tagline', y: 220, height: 80, contains: 'Design Beyond Limits.' },+ { name: 'tagline', y: 240, height: 80, contains: 'Design Beyond Limits.' },],}),turn('set_background', { kind: 'solid', from: '#090B1A' }),@@ -1452,7 +1452,7 @@ describe('v0.29.3 · loop: planning + fail-closed acks', () => {expect(result.steps).toBe(2) // plan_layout + set_background each count as a step})- it('plan_layout rejects stacked bands with actionable guidance', () => {+ it('plan_layout rejects stacked bands with actionable guidance (v0.32.4: hard reject, not a warning)', () => {const tool = AGENT_TOOL_MAP.get('plan_layout')expect(tool).toBeTruthy()const res = tool!.sanitize(@@ -1464,8 +1464,50 @@ describe('v0.29.3 · loop: planning + fail-closed acks', () => {},ctx,)- expect(res.ok).toBe(true)- expect(String((res as { observation?: string }).observation)).toContain('PLAN WARNINGS')+ // the 24px overlap slack is gone: gap = 250 - 300 = -50 → REJECTED+ expect(res.ok).toBe(false)+ expect(String((res as { error?: string }).error)).toContain('≥40px gap')+ expect(String((res as { error?: string }).error)).toContain('"a" and "b"')+ // 39px gap: still rejected — the boundary is 40, sharp on both sides+ const res39 = tool!.sanitize(+ {+ sections: [+ { name: 'a', y: 100, height: 200, contains: 'x' },+ { name: 'b', y: 339, height: 100, contains: 'y' },+ ],+ },+ ctx,+ )+ expect(res39.ok).toBe(false)+ // 40px gap: accepted+ const res40 = tool!.sanitize(+ {+ sections: [+ { name: 'a', y: 100, height: 200, contains: 'x' },+ { name: 'b', y: 340, height: 100, contains: 'y' },+ ],+ },+ ctx,+ )+ expect(res40.ok).toBe(true)+ // a band beyond the page: rejected with the exact numbers+ const resBeyond = tool!.sanitize(+ {+ sections: [+ { name: 'a', y: 100, height: 200, contains: 'x' },+ { name: 'b', y: 340, height: 2000, contains: 'y' },+ ],+ },+ ctx,+ )+ expect(resBeyond.ok).toBe(false)+ expect(String((resBeyond as { error?: string }).error)).toContain('beyond the')+ // the structured bands ride the action for the plan-adherence audit+ const actions = (res40 as { actions?: { bands?: { name: string; y: number; h: number }[] }[] }).actions+ expect(actions?.[0]?.bands).toEqual([+ { name: 'a', y: 100, h: 200 },+ { name: 'b', y: 340, h: 100 },+ ])})it('a failed (timed-out) apply ack tells the model the action was NOT applied — fail closed', async () => {@@ -1943,3 +1985,183 @@ describe('v0.32.3 · plan-first gate (create runs)', () => {expect(result.summary).not.toContain('INCOMPLETE')})})++// ═════════════════════════════════════════════════════════════+// v0.32.4 · deterministic design correctness: hard plan validation,+// duplicate detection, plan adherence, wrap-up audit, list_fonts,+// run ledger rendering+// ═════════════════════════════════════════════════════════════++describe('v0.32.4 · duplicate detection (the live coffee-run residue, now caught)', () => {+ const base = { width: 1080, height: 1920, background: '#090B1A' }++ it('near-twin texts (same text, overlapping boxes) are flagged with both ids', () => {+ const issues = auditDesign({+ ...base,+ elements: [+ { id: 'a', type: 'text', text: 'Experience the perfect balance', fill: '#FFFFFF', fontSize: 32, x: 90, y: 186, width: 700, height: 120 },+ { id: 'b', type: 'text', text: 'experience the\nperfect balance', fill: '#FFFFFF', fontSize: 32, x: 90, y: 164, width: 700, height: 120 },+ ],+ })+ const hit = issues.find((i) => i.startsWith('Duplicate text'))+ expect(hit).toBeTruthy()+ expect(hit).toContain('#a')+ expect(hit).toContain('#b')+ })++ it('the 3-card row (same size + fill, different x) is NOT flagged — intentional repetition', () => {+ const card = (x: number, id: string) => ({ id, type: 'rect', x, y: 300, width: 280, height: 360, fill: 'rgba(255,255,255,0.08)' })+ const label = (x: number, id: string, text: string) => ({ id, type: 'text', text, fill: '#FFFFFF', fontSize: 24, x, y: 430, width: 240, height: 60 })+ const issues = auditDesign({+ ...base,+ elements: [+ card(90, 'c1'), card(400, 'c2'), card(710, 'c3'),+ label(110, 't1', 'Freshly Roasted'), label(420, 't2', 'Single Origin'), label(730, 't3', 'Smooth Crema'),+ ],+ })+ expect(issues.filter((i) => i.startsWith('Duplicate'))).toEqual([])+ })++ it('distant identical texts (page furniture) are NOT flagged', () => {+ const issues = auditDesign({+ ...base,+ elements: [+ { id: 'a', type: 'text', text: 'Shop Now', fill: '#FFFFFF', fontSize: 28, x: 100, y: 800, width: 200, height: 60 },+ { id: 'b', type: 'text', text: 'Shop Now', fill: '#FFFFFF', fontSize: 28, x: 780, y: 800, width: 200, height: 60 },+ ],+ })+ expect(issues.filter((i) => i.startsWith('Duplicate text'))).toEqual([])+ })++ it('a layered twin shape (same size + fill + position) is flagged', () => {+ const twin = (id: string, y: number) => ({ id, type: 'rect', x: 100, y, width: 280, height: 200, fill: '#8B5CF6' })+ const issues = auditDesign({+ ...base,+ elements: [twin('r1', 300), twin('r2', 296)],+ })+ const hit = issues.find((i) => i.startsWith('Duplicate shape'))+ expect(hit).toBeTruthy()+ expect(hit).toContain('#r1')+ expect(hit).toContain('#r2')+ })++ it('text deep in the page margin is disclosed (advisory), shallow bleed is not', () => {+ const issues = auditDesign({+ ...base,+ elements: [+ { id: 'deep', type: 'text', text: 'Edge hugger', fill: '#FFFFFF', fontSize: 40, x: 20, y: 54, width: 400, height: 90 },+ ],+ })+ expect(issues.some((i) => i.includes('inside the page margin') && i.includes('top') && i.includes('left'))).toBe(true)+ const shallow = auditDesign({+ ...base,+ elements: [+ { id: 'sh', type: 'text', text: 'Fine', fill: '#FFFFFF', fontSize: 40, x: 95, y: 100, width: 400, height: 90 },+ ],+ })+ expect(shallow.filter((i) => i.includes('page margin'))).toEqual([])+ })+})++describe('v0.32.4 · plan adherence (the build must fill the plan)', () => {+ const base = { width: 1080, height: 1920, background: '#090B1A' }++ it('an empty planned section is reported; filled sections pass', () => {+ const els = [+ { id: 'h', type: 'text', text: 'COFFEE', fill: '#FFFFFF', fontSize: 96, x: 90, y: 100, width: 800, height: 200 },+ { id: 'f', type: 'text', text: 'Shop Now', fill: '#FFD166', fontSize: 28, x: 90, y: 800, width: 300, height: 60 },+ ]+ const withPlan = auditDesign({ ...base, elements: els }, null, [+ { name: 'headline', y: 100, h: 200 },+ { name: 'features', y: 350, h: 400 },+ { name: 'cta', y: 800, h: 200 },+ ])+ expect(withPlan.some((i) => i.includes('Planned section "features"') && i.includes('empty'))).toBe(true)+ expect(withPlan.some((i) => i.includes('"headline"'))).toBe(false)+ // no plan → no adherence check at all+ expect(auditDesign({ ...base, elements: els }).some((i) => i.startsWith('Planned section'))).toBe(false)+ })+})++describe('v0.32.4 · guard exits audit their residue (the wrap-up hole)', () => {+ const emptyDesign: AgentDesignCtx = {+ name: 'Untitled', width: 1080, height: 1920, pageCount: 1,+ currentPageIndex: 0, elements: [], colorsInUse: [], otherPages: [],+ }++ it('a cycle-guard wrap-up runs the audit and DISCLOSES fixable residue', async () => {+ const events: AgentEvent[] = []+ // model: plan → build a duplicate text → repeat the identical call+ // 3× → the cycle guard wraps the run up+ const { chat } = scriptedChat([+ turn('plan_layout', { background: '#090B1A', sections: [{ name: 'hero', y: 130, height: 200, contains: 'Hero' }] }),+ turn('add_text', { text: 'Twin', fontSize: 64, y: 150, color: '#FFFFFF', x: 100 }),+ turn('add_text', { text: 'Twin', fontSize: 64, y: 150, color: '#FFFFFF', x: 100 }),+ turn('add_text', { text: 'Twin', fontSize: 64, y: 150, color: '#FFFFFF', x: 100 }),+ turn('add_text', { text: 'Twin', fontSize: 64, y: 150, color: '#FFFFFF', x: 100 }),+ ])+ let auditedDesign: AgentDesignCtx | null = null+ const result = await runAgentLoop({+ chat, design: emptyDesign, mode: 'create',+ request: 'Design a poster',+ emit: (e) => events.push(e),+ awaitApply: async () => ({ ok: true }),+ refreshedContext: () => auditedDesign ?? emptyDesign,+ auditDesign: (bands) => {+ // the audit sees what the run actually built: the twin pair+ auditedDesign = {+ ...emptyDesign,+ elements: [+ { id: 't1', type: 'text', text: 'Twin', x: 100, y: 150, width: 300, height: 90, fontSize: 64, fill: '#FFFFFF' },+ { id: 't2', type: 'text', text: 'Twin', x: 100, y: 150, width: 300, height: 90, fontSize: 64, fill: '#FFFFFF' },+ ],+ }+ return auditDesign(auditedDesign, null, bands?.length ? bands : undefined)+ },+ })+ expect(result.summary).toContain('wrapped up')+ expect(result.summary).toContain('Quality audit at wrap-up')+ expect(result.summary).toContain('Duplicate text')+ expect(result.verification).toContain('disclosed, unfixed')+ })+})++describe('v0.32.4 · list_fonts (the phantom tool, now real)', () => {+ it('lists and filters the 369-family catalog with a cap', () => {+ const tool = AGENT_TOOL_MAP.get('list_fonts')+ expect(tool).toBeTruthy()+ const all = tool!.sanitize({ limit: 10 }, ctx)+ expect(all.ok).toBe(true)+ expect(String((all as { observation?: string }).observation)).toContain('Font families')+ expect(String((all as { observation?: string }).observation)).toContain('of 369')+ const query = tool!.sanitize({ query: 'mono', limit: 20 }, ctx)+ expect(query.ok).toBe(true)+ const obs = String((query as { observation?: string }).observation)+ expect(obs).toContain('matching "mono"')+ expect(obs.toLowerCase()).toContain('mono')+ const none = tool!.sanitize({ query: 'zzzznope' }, ctx)+ expect(none.ok).toBe(true)+ expect(String((none as { observation?: string }).observation)).toContain('No font family matches')+ })+})++describe('v0.32.4 · run ledger renders into the system prompt', () => {+ it('recent runs appear as grounded history; absent ledger stays silent', () => {+ const withLedger = loopSystemPrompt({+ design, ctx, mode: 'create',+ ledger: [+ 'create "Design a bold Instagram post for a coffee launch" → 24 action(s): Coffee-launch Instagram post built (brief validated).',+ 'edit "Remove the duplicates" → 2 action(s): Duplicate subline and card removed.',+ ],+ })+ expect(withLedger).toContain('YOUR RECENT RUNS IN THIS DESIGN')+ expect(withLedger).toContain('coffee launch')+ expect(withLedger).toContain('Duplicate subline')+ expect(withLedger).toContain('the state above is still the authority')+ const without = loopSystemPrompt({ design, ctx, mode: 'create' })+ expect(without).not.toContain('YOUR RECENT RUNS IN THIS DESIGN')+ // the font sample now carries the real catalog size + discovery pointer+ expect(without).toContain('369 total')+ expect(without).toContain('list_fonts')+ })+})diff --git a/src/lib/agent/loop.ts b/src/lib/agent/loop.tsindex 7454c1a..760f509 100644--- a/src/lib/agent/loop.ts+++ b/src/lib/agent/loop.ts@@ -59,12 +59,19 @@ export interface LoopDeps {* meaning). Compaction never drops this head, only the long* tool-observation middle. */history?: { role: 'user' | 'assistant'; content: string }[]+ /** v0.32.4: per-design run ledger lines (route-fetched, compact) —+ * what the agent's recent runs in THIS design did. Rendered into+ * the system prompt after the design context; the canvas state+ * stays the authority, the ledger explains how it got there. */+ ledger?: string[]/** the run's brief contract (extracted by the route) */brief?: DesignBrief | null/** v0.29: local quality audit of the latest design snapshot* (contrast/overlap/overflow heuristics). The loop runs ONE- * auto-fix round on its findings before accepting done. */- auditDesign?: () => string[] | Promise<string[]>+ * auto-fix round on its findings before accepting done.+ * v0.32.4: receives the run's validated plan bands so the audit+ * can also check plan adherence (empty planned sections). */+ auditDesign?: (bands?: { name: string; y: number; h: number }[]) => string[] | Promise<string[]>/** v0.29.3: ask the CLIENT to screenshot the live canvas (the real* render) — resolved with a dataURL, or null on timeout/absence* (fail-closed: visual verification is then DISCLOSED as@@ -123,8 +130,14 @@ export function loopSystemPrompt(deps: {mode: AgentModebrief?: DesignBrief | nullskills?: DesignSkill[]+ /** v0.32.4: compact per-design run ledger — what THIS design's+ * agent runs did recently (mode, request, actions, outcome). The+ * canvas state stays the authority; the ledger explains how it+ * got there, so follow-ups build on prior work instead of+ * re-deriving it. */+ ledger?: string[]}): string {- const { design, ctx, mode, brief, skills } = deps+ const { design, ctx, mode, brief, skills, ledger } = depsconst W = design.width ?? 1080const H = design.height ?? 1080const margin = 0.06@@ -152,7 +165,10 @@ export function loopSystemPrompt(deps: {'TOOLS (risk: read | write | destructive):',toolsPromptSectionFor(mode),'',- `Fonts available (use EXACT names): ${fontFamilies().slice(0, 40).join(', ')}…`,+ // v0.32.4: 369 families exist — a 40-name sample hid the rest.+ // Show 60 + the total and point at the (now real) list_fonts+ // tool for search: progressive discovery, not a bloated prompt.+ `Fonts available (use EXACT names; ${fontFamilies().length} total — list_fonts {query} searches the rest): ${fontFamilies().slice(0, 60).join(', ')}…`,'',]@@ -165,7 +181,7 @@ export function loopSystemPrompt(deps: {lines.push('LAYOUT PLANNING (required first step):','· Call plan_layout FIRST with your composition: page background, sections with y-ranges, what each contains (headline band, tagline, feature cards row, mockup, CTA, footer).',- '· Reserve a vertical band per section with ≥40px gaps so nothing stacks or crowds; the brief texts each get their section.',+ '· Reserve a vertical band per section with ≥40px gaps so nothing stacks or crowds; the brief texts each get their section. Invalid plans (gaps under 40px, bands beyond the page) are REJECTED with the exact numbers — fix the bands and resend.','· Set the page background EARLY with set_background (a required background color belongs there, not in strips).','· Build section by section after the plan. NEVER add bare decorative bars/strips just to include a required color — use colors as the page background, text fills, or real panel/card fills.','· A realistic editor mockup = a large native panel (rounded rect, glass fill, border) CONTAINING inner native elements (toolbar bar, sidebar, canvas area, buttons) — not one empty rectangle.',@@ -174,6 +190,16 @@ export function loopSystemPrompt(deps: {)}+ // v0.32.4: the per-design run ledger — what the agent did in THIS+ // design recently. The canvas state above stays the authority; the+ // ledger explains how it got there (so "another one like the last+ // run" or "finish what you started" has grounded history).+ if (ledger?.length) {+ lines.push('YOUR RECENT RUNS IN THIS DESIGN (most recent first — the state above is still the authority):')+ for (const entry of ledger.slice(0, 4)) lines.push(`· ${entry}`)+ lines.push('')+ }+const skillSection = skillsPromptSection(skills ?? [])if (skillSection) lines.push(skillSection, '')@@ -285,6 +311,10 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {/** v0.32.3: has plan_layout run in this run? Once it has, writes* proceed freely — the gate never fires again. */let planHasRun = false+ /** v0.32.4: the validated plan's structured bands (from the+ * __planLayout action) — passed to the quality audit so it can+ * check plan adherence (empty planned sections). */+ const planBands: { name: string; y: number; h: number }[] = []const toolCtx: ToolContext = {validIds: contextValidIds(design),@@ -294,7 +324,7 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {}const messages: { role: 'system' | 'user' | 'assistant'; content: string }[] = [- { role: 'system', content: loopSystemPrompt({ design, ctx: toolCtx, mode, brief, skills }) },+ { role: 'system', content: loopSystemPrompt({ design, ctx: toolCtx, mode, brief, skills, ledger: deps.ledger }) },// v0.32.3: the conversation this request arrives in — prior// user/assistant turns, verbatim (route-sanitized). The model// knows what it already did in this chat.@@ -323,14 +353,39 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {/** v0.32.2 (progress requirement): guard exits must be HONEST about* what actually happened — a create/improve run that changed- * nothing is INCOMPLETE, never a wrapped-up success. */- const guardExit = (base: string): { summary: string; verification: string | undefined } =>- (mode === 'create' || mode === 'improve') && designChanges === 0- ? {- summary: `INCOMPLETE — no design changes were made. ${base}`,- verification: 'NOT completed — the run ended without applying any design change; nothing was created.',+ * nothing is INCOMPLETE, never a wrapped-up success.+ * v0.32.4: a guard exit that ends a run WITH applied changes now+ * also runs the quality audit once and DISCLOSES the residue in+ * the summary — the live coffee run left a duplicate subline+ * precisely because the wrap-up path skipped the audit that the+ * done path runs. No fix round here (the run is ending); the+ * findings are named so the next message can target them. */+ const guardExit = async (base: string): Promise<{ summary: string; verification: string | undefined }> => {+ if ((mode === 'create' || mode === 'improve') && designChanges === 0) {+ return {+ summary: `INCOMPLETE — no design changes were made. ${base}`,+ verification: 'NOT completed — the run ended without applying any design change; nothing was created.',+ }+ }+ if ((mode === 'create' || mode === 'improve') && deps.auditDesign) {+ try {+ const issues = (await deps.auditDesign(planBands.length ? planBands : undefined)) ?? []+ if (issues.length) {+ const residue = issues.slice(0, 4).map((i) => `· ${i}`).join('\n')+ const withResidue = `${base}\nQuality audit at wrap-up (fixable residue):\n${residue}`+ return {+ summary: withResidue,+ verification: verification+ ? `${verification} Quality audit at wrap-up reports ${issues.length} issue(s) — disclosed, unfixed.`+ : `Quality audit at wrap-up reports ${issues.length} issue(s) — disclosed, unfixed.`,+ }}- : { summary: base, verification }+ } catch {+ /* best-effort — the guard exit must never hang on the audit */+ }+ }+ return { summary: base, verification }+ }while (true) {// ── task-driven stops ───────────────────────────────────@@ -356,11 +411,11 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {message: `Stopped after ${AGENT_GUARDS.strikes} consecutive invalid tool calls — the error under each step explains what to fix; try rephrasing the request.`,code: 'STRIKES',})- const exit = guardExit(summary || 'Stopped after repeated invalid calls.')+ const exit = await guardExit(summary || 'Stopped after repeated invalid calls.')return { summary: exit.summary, steps, toolCalls, verification: exit.verification }}if (Date.now() - lastProgressAt > AGENT_GUARDS.idleMs) {- const exit = guardExit('The run stopped making progress and was wrapped up. Everything applied so far is kept — send a follow-up message to continue.')+ const exit = await guardExit('The run stopped making progress and was wrapped up. Everything applied so far is kept — send a follow-up message to continue.')emit({v: AGENT_PROTOCOL_VERSION,type: 'done',@@ -393,7 +448,7 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {message: `The AI provider failed: ${err instanceof Error ? err.message.slice(0, 200) : 'unknown error'}. Applied work is kept — retry to continue.`,code: 'PROVIDER',})- const exit = guardExit(summary)+ const exit = await guardExit(summary)return { summary: exit.summary, steps, toolCalls, verification: exit.verification }}@@ -471,7 +526,7 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {if ((mode === 'create' || mode === 'improve') && deps.auditDesign) {let issues: string[] = []try {- issues = (await deps.auditDesign()) ?? []+ issues = (await deps.auditDesign(planBands.length ? planBands : undefined)) ?? []} catch {/* audit is best-effort — never block completion on it */}@@ -630,8 +685,12 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {// an observation. No apply/ack round trip: a plan changes nothing.if (toolName === 'plan_layout' && result.ok) {planHasRun = true- const planLines = (result.actions as { type: string; lines?: string[] }[])- .flatMap((a) => (a && a.type === '__planLayout' && Array.isArray(a.lines) ? a.lines : []))+ const planActions = (result.actions as { type: string; lines?: string[]; bands?: { name: string; y: number; h: number }[] }[])+ const planLines = planActions.flatMap((a) => (a && a.type === '__planLayout' && Array.isArray(a.lines) ? a.lines : []))+ // v0.32.4: keep the structured bands for the quality audit's+ // plan-adherence check (empty planned sections)+ planBands.length = 0+ planBands.push(...planActions.flatMap((a) => (a && a.type === '__planLayout' && Array.isArray(a.bands) ? a.bands : [])))const lines = planLines.length ? planLines : ['(model emitted an empty plan)']emit({ v: AGENT_PROTOCOL_VERSION, type: 'plan', steps: lines })emit({ v: AGENT_PROTOCOL_VERSION, type: 'observation', stepIndex: steps, message: result.observation })@@ -686,7 +745,7 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {if (hash === lastCallHash) {cycleCount += 1if (cycleCount >= AGENT_GUARDS.cycleRepeat - 1) {- const exit = guardExit('The run repeated the same operation without effect and was wrapped up. Applied work is kept — describe the next change to continue.')+ const exit = await guardExit('The run repeated the same operation without effect and was wrapped up. Applied work is kept — describe the next change to continue.')emit({v: AGENT_PROTOCOL_VERSION,type: 'done',diff --git a/src/lib/agent/tools.ts b/src/lib/agent/tools.tsindex 84f3046..ac99043 100644--- a/src/lib/agent/tools.ts+++ b/src/lib/agent/tools.ts@@ -129,6 +129,36 @@ export const AGENT_TOOLS: AgentTool[] = [observation: 'Fresh page state attached as the next observation.',}),},+ {+ // v0.32.4: the sanitizer's font errors have pointed at+ // "list_fonts" since v0.29 — but the tool never existed, so the+ // model was directed at a phantom. The catalog holds 369+ // families; the system prompt shows a sample, this tool streams+ // the rest (searchable, capped) — progressive capability+ // discovery without bloating every turn.+ name: 'list_fonts',+ description: `List available font families (${FONTS.length} in the catalog). Optional {query} filters by substring (case-insensitive); {limit} caps the count (default 60, max 120). Use EXACT names in add_text/set_text_style.`,+ risk: 'read',+ argsSpec: '{query?: string, limit?: 1-120}',+ sanitize: (args, _ctx) => {+ const query = typeof args.query === 'string' ? args.query.trim().toLowerCase() : ''+ const limitRaw = num(args, 'limit')+ const limit = limitRaw === null ? 60 : Math.max(1, Math.min(120, Math.round(limitRaw)))+ let families = FONTS.map((f) => f.family)+ if (query) families = families.filter((f) => f.toLowerCase().includes(query))+ const slice = families.slice(0, limit)+ const head = query+ ? `Fonts matching "${query}" (${slice.length}${families.length > slice.length ? ` of ${families.length}` : ''}):`+ : `Font families (${slice.length}${families.length > slice.length ? ` of ${families.length} — refine with {query}` : ''}):`+ return {+ ok: true,+ actions: [],+ observation: families.length+ ? `${head} ${slice.join(', ')}.`+ : `No font family matches "${query}". Try the system prompt's sample, or query a shorter substring.`,+ }+ },+ },{// v0.29.3: brief-to-layout planning. The model reserves the// composition BEFORE building — the failed production runs@@ -164,25 +194,51 @@ export const AGENT_TOOLS: AgentTool[] = [if (bg) lines.unshift(`page background ${bg}`)const notes = typeof args.notes === 'string' ? args.notes.trim().slice(0, 200) : ''if (notes) lines.push(`notes: ${notes}`)- // sanity: sections inside the page, in order, not stacked- const sorted = [...sectionsRaw]+ // v0.32.4: HARD geometry validation — the plan protocol+ // promises ≥40px gaps and bands inside the page; the plan is+ // now REJECTED when it violates either (the model retries+ // with a corrected plan; sanitize errors are retryable, not+ // strikes). Safe-area intrusion stays a WARNING (content can+ // sit inside bands that start slightly high; the audit flags+ // actual text that hugs the edge). This closes the old `- 24`+ // slack that let sections overlap by up to 24px.+ const bands = sectionsRaw+ .filter((s) => s && typeof s === 'object').map((s) => s as Record<string, unknown>)- .map((s) => ({ y: num(s, 'y') ?? 0, h: num(s, 'height') ?? 0 }))- .sort((a, b) => a.y - b.y)+ .map((s) => ({+ name: typeof s.name === 'string' ? s.name.trim().slice(0, 40) : '',+ y: num(s, 'y') ?? 0,+ h: num(s, 'height') ?? 0,+ }))+ .filter((b) => b.h > 0)+ const sorted = [...bands].sort((a, b) => a.y - b.y)const problems: string[] = []+ const warnings: string[] = []if (sorted.length) {+ if (sorted[0].y < 0) problems.push(`section 1 starts at y=${Math.round(sorted[0].y)} — negative y`)const last = sorted[sorted.length - 1]- if (last.y + last.h > H * 1.02) problems.push(`the last section ends at y=${Math.round(last.y + last.h)} — beyond the ${H}px page`)+ if (last.y + last.h > H) problems.push(`the last section ends at y=${Math.round(last.y + last.h)} — beyond the ${H}px page`)for (let i = 1; i < sorted.length; i++) {- if (sorted[i].y < sorted[i - 1].y + sorted[i - 1].h - 24) {- problems.push(`sections ${i} and ${i + 1} overlap or have <24px gap at y=${Math.round(sorted[i].y)}`)+ const gap = sorted[i].y - (sorted[i - 1].y + sorted[i - 1].h)+ if (gap < 40) {+ problems.push(`sections "${sorted[i - 1].name}" and "${sorted[i].name}" need ≥40px gap; found ${Math.round(gap)}px at y=${Math.round(sorted[i].y)}`)}}+ const safeTop = Math.round(H * 0.06)+ const safeBottom = Math.round(H * 0.94)+ if (sorted[0].y < safeTop) warnings.push(`the first band starts at y=${Math.round(sorted[0].y)}, inside the 6% top margin (${safeTop}px) — prefer starting at y=${safeTop}`)+ if (last.y + last.h > safeBottom) warnings.push(`the last band ends at y=${Math.round(last.y + last.h)}, inside the 6% bottom margin (ends ${safeBottom}px) — prefer ending by y=${safeBottom}`)+ }+ if (problems.length) {+ return {+ ok: false,+ error: `Invalid plan: ${problems.join('; ')}. Revise plan_layout so the bands tile the page top-to-bottom, each fully inside 0..${H} with ≥40px gaps between sections.`,+ }}- const observation = `PLAN RECORDED (${lines.length} lines):\n${lines.join('\n')}${problems.length ? `\nPLAN WARNINGS: ${problems.join('; ')} — revise the bands before building.` : '\nBands verified non-overlapping.'}`+ const observation = `PLAN RECORDED (${lines.length} lines):\n${lines.join('\n')}${warnings.length ? `\nPLAN WARNINGS: ${warnings.join('; ')} — revise the bands before building.` : '\nBands verified: non-overlapping, ≥40px gaps, inside the page.'}`return {ok: true,- actions: [{ type: '__planLayout', lines }],+ actions: [{ type: '__planLayout', lines, bands }],observation,}},