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
fix(v0.32.1): Unified Canvix AI hardening — all 4 review findings closed + ONE AI surface
Ashiq Hussain Mir3880c1acb31b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4e774ed..585e1c5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,25 +3,41 @@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/).-## [Unreleased] — Unified Canvix AI (create → verify → refine)+## [Unreleased] — Unified Canvix AI (create → verify → refine) + the hardening pass-> One engineering upgrade, four unifications — full write-up in-> `docs/UNIFIED-AI-MILESTONE.md`, acceptance in+> One engineering upgrade, four unifications, one external review+> closed (4 findings) and ONE AI surface — full write-up in+> `docs/UNIFIED-AI-MILESTONE.md` (the v0.32.1 section), acceptance in> `src/lib/design-agent/continuation.test.ts`.-### Added — design provenance (the contract that persists)--- `DesignProvenance` model (migration `0013`): the brief an autonomous- generation was verified against, stored on the applied design; the- design GET returns it as `aiProvenance` and the editor hydrates it.-- `PUT|GET /api/designs/[id]/ai-provenance` — edit-gated persistence- (same-origin, its own rate budget, NOT_YOUR_DESIGN on foreign- designs, flat 404 on missing ids), plus a live-DB e2e spec- (`tests/e2e/unified-ai-provenance.spec.ts`).-- `mergeBriefs` / `normalizeStoredBrief` (`src/lib/agent/brief.ts`): the- stored contract merges with every chat-agent run on that design —- union semantics, hostile input capped, dimensions dropped (the design- owns geometry after fit-pages).+### Added — design provenance (the contract that persists, verified)++- `DesignProvenance` model (migrations `0013` + `0014`): the brief an+ autonomous generation was verified against, stored on the applied+ design — with a SERVER-SIDE verification verdict (`verified`,+ `verifiedAt`) that is re-checked on every design save and bound to+ the saved document. The design GET returns it as `aiProvenance` and+ the editor hydrates the brief (payload-vs-brief hydration bug fixed+ with a regression test).+- Contracts enter the store only through the **design save**: the+ apply flow queues a pending contract and `PUT /api/designs/[id]`+ persists + verifies it against the final saved pages. The+ client-supplied `PUT /api/designs/[id]/ai-provenance` is REMOVED+ (an authorized editor could previously store any brief with an+ unearned `passed`); the GET stays.+- `GET /api/designs/[id]/ai-provenance` + the design GET: link+ viewers receive the shareable contract (brief, verification state)+ but NEVER the original generation prompt — that ships only to+ editors/owners (privacy hardening).+- `mergeBriefs` / `normalizeStoredBrief` (`src/lib/agent/brief.ts`):+ the stored contract merges with every chat-agent run on that design+ — union semantics, dimensions dropped (the design owns geometry+ after fit-pages). Restrictions and notes SURVIVE persistence;+ over-limit briefs are REFUSED at save time (never stored truncated+ or capped — no silent weakening).+- Live-DB e2e (`tests/e2e/unified-ai-provenance.spec.ts`): the+ apply→save flow, the strict server-side verdict, viewer privacy,+ junk/over-limit refusals, missing-id 404s.### Changed — the two agents share one foundation@@ -29,14 +45,29 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).verification route (`/api/ai/agent/vision`) now resolve the visionslot USER-FIRST (BYOK), matching the text slot and the design-agentroute — a user's own vision provider serves their critiques.-- **Shared validation:** the agent loop's done-gate fires for edit-mode- runs that carry a brief (the continuation case) — a refinement may- not finish while a requirement the design was verified against has- gone missing; enforcement is proven by test, not hoped for.+- **Shared validation (now EXACT):** `validateBrief` enforces strict+ normalized equality for required texts — appended words,+ re-capitalization, altered punctuation and missing spaces are+ rejections, not matches. The agent loop's done-gate fires for+ edit-mode runs that carry a brief (the continuation case), and the+ chat agent reads the AUTHORITATIVE database brief (the design+ context carries `designId`), so a client post cannot tamper with+ what a run is gated on.- **Shared editing workflow:** DesignAgent Apply sets the design's- stored brief (and persists it best-effort) so natural-language- refinement of the same design keeps the contract, the context and- full editability (the same `applyDesignAction` executor).+ brief and queues the pending contract (persisted + verified by the+ next save) so natural-language refinement of the same design keeps+ the contract, the context and full editability (the same+ `applyDesignAction` executor).++### Changed — ONE AI surface (the consolidation)++- The six AI-branded apps (chat copilot, design agent, Magic Write,+ AI image generator, AI design plan, AI theme) are now ONE **Canvix+ AI** app with five mode tabs — Chat / Generate / Write / Image /+ Theme (`UnifiedAIApp.tsx`; the tab contents are the original,+ unchanged app components). The AI design plan PANEL is retired —+ its describe → review → apply flow IS the Generate tab; the+ `/api/ai/plan` route remains available as an API.## [0.31.0] — 2026-11-25diff --git a/ROADMAP.md b/ROADMAP.mdindex 7a2689c..48c7051 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -14,7 +14,7 @@ Where every active effort actually stands, in one place. The sections below rema| Track | State | Contents ||---|---|---|-| **Shipped on `main`** | Deployed at canvix.app; tagged through **v0.31.0**, changelog at v0.31.0 | WP1 complete — scoped API keys (v0.24, PR #77) + Docker/compose self-hosting; auto-snapshots (v0.24); the v0.29.4 agent-correctness arc; v0.29.5 funding & trust documentation: SECURITY.md, GOVERNANCE.md, CODE_OF_CONDUCT.md, `funding.json` with **live wellKnown domain verification** (PR #87), the FOSS United proposal, and the grantee research record; **the DesignAgent merge (24 Nov 2026, unfunded work)** — DesignSpec v2 + the deterministic design engine + the autonomous design pipeline (plan → compile → self-correct → visual-verify) with BYOK production wiring (`/api/ai/design-agent`) and the 22-brief instruction-fidelity benchmark; **the CWE-79 media-XSS closure (25 Nov 2026, `fde7f25`)** — the project's first coordinated security disclosure (reported by @hackchang), four defense layers + 40 regression tests, private GHSA + CVE request in flight; **the v0.31.0 release** reconciling all version frames; **the Unified Canvix AI milestone (25 Nov 2026, `docs/UNIFIED-AI-MILESTONE.md`)** — shared user-first provider resolution (vision BYOK closed), design provenance persisted on the applied design (`DesignProvenance`, migration 0013, `/api/designs/[id]/ai-provenance`), and the create→verify→refine continuation: the stored brief merges into every chat-agent run on that design and edit-mode runs are gated on it — acceptance proven by `src/lib/design-agent/continuation.test.ts` (create → apply → real-executor refine, requirements enforced, never just hoped) |+| **Shipped on `main`** | Deployed at canvix.app; tagged through **v0.31.0**, changelog at v0.31.0 | WP1 complete — scoped API keys (v0.24, PR #77) + Docker/compose self-hosting; auto-snapshots (v0.24); the v0.29.4 agent-correctness arc; v0.29.5 funding & trust documentation: SECURITY.md, GOVERNANCE.md, CODE_OF_CONDUCT.md, `funding.json` with **live wellKnown domain verification** (PR #87), the FOSS United proposal, and the grantee research record; **the DesignAgent merge (24 Nov 2026, unfunded work)** — DesignSpec v2 + the deterministic design engine + the autonomous design pipeline (plan → compile → self-correct → visual-verify) with BYOK production wiring (`/api/ai/design-agent`) and the 22-brief instruction-fidelity benchmark; **the CWE-79 media-XSS closure (25 Nov 2026, `fde7f25`)** — the project's first coordinated security disclosure (reported by @hackchang), four defense layers + 40 regression tests, private GHSA + CVE request in flight; **the v0.31.0 release** reconciling all version frames; **the Unified Canvix AI milestone (25 Nov 2026, `docs/UNIFIED-AI-MILESTONE.md`)** — shared user-first provider resolution (vision BYOK closed), design provenance persisted on the applied design (`DesignProvenance`, migration 0013, `/api/designs/[id]/ai-provenance`), and the create→verify→refine continuation: the stored brief merges into every chat-agent run on that design and edit-mode runs are gated on it — acceptance proven by `src/lib/design-agent/continuation.test.ts` (create → apply → real-executor refine, requirements enforced, never just hoped); **the same-day hardening pass (external review, all 4 findings closed + the consolidation request)** — strict exact-text equality (appended words / case / punctuation are rejections, unit + gate + server-side), restrictions survive persistence and over-limit briefs are refused (never silently weakened), the original AI prompt is editor-only (link viewers get the shareable contract, never the prompt), provenance persistence moved INTO the design save with a server-side `verified` verdict re-checked on every save (migration 0014; the client-supplied PUT is gone), the chat agent reads the authoritative DB brief, and the six AI apps consolidated into ONE "Canvix AI" app with Chat/Generate/Write/Image/Theme tabs || **Merged feature branches** | `feat/design-spec-foundation` + `feat/design-agent` — **merged into `main`** 24 Nov 2026 | DesignSpec v2 (types, model-output parser, brief mapper), the deterministic design engine (palette/typography/layout/compositions/compile — dedicated builders for every block kind), the re-runnable **real-model + real-browser acceptance harness** (`scripts/designspec-compile.ts`, `scripts/designspec-render.cjs`, `scripts/designspec-agent-run.ts`), the seed-guarantee engine fix, `docs/DESIGNSPEC-ACCEPTANCE-REPORT.md` + `docs/DESIGN-AGENT-ACCEPTANCE-REPORT.md`, and `research/AUTONOMOUS-AGENT-RESEARCH.md` (the ReAct / OpenAI-SDK / PosterGen pattern study the pipeline architecture follows) || **Pending funding — decision outstanding** | Submitted; **not awarded — never represent it as such** | **FOSS United project grant** (INR 5,00,000, milestones M1–M4, submitted 12 Nov 2026 via the funding.json mechanism): design-output correctness, reproducible design evaluation, creator education. **NLnet** (WP1–WP5, ~€12,600 labour-only): deployment trust, collaboration scale, mobile editing, sharing, v1.0 stabilization. The two scopes are deliberately disjoint — no hour or deliverable is funded twice || **Unfunded development** | Proceeds on its own cadence | AI-provider track (vendor-SDK removal + direct OpenAI-compatible adapter, ~65 h — outside NLnet scope by its connectors policy), media GC, D8/D10 depth, Wave-5 remainder sequencing |diff --git a/docs/UNIFIED-AI-MILESTONE.md b/docs/UNIFIED-AI-MILESTONE.mdindex 98f07ff..220a39c 100644--- a/docs/UNIFIED-AI-MILESTONE.md+++ b/docs/UNIFIED-AI-MILESTONE.md@@ -4,6 +4,9 @@**Scope:** one engineering upgrade, four unifications — shared providerresolution, shared rendering, shared validation, shared editingworkflow — proven by a single acceptance test.+**Hardened same day (v0.32.1):** the external review's four findings+(3×P0, 1×P1) + the one-AI-surface consolidation — see the last+section; it supersedes the persistence/PUT details below.## The acceptance test (as specified, then implemented)@@ -129,3 +132,96 @@ The two model seams (chat loop, pipeline plan/critique), the honestycontracts, the review gates and the checks-outrank-critique hierarchyare untouched. This milestone wires the systems together around thedocument; it does not alter how either agent thinks.++---++# v0.32.1 — the hardening pass (external review, 25 Nov 2026)++An independent review of the merged milestone confirmed the+architecture and CI, then sent back four findings (3×P0, 1×P1) and a+consolidation request ("I don't want multiple AI apps in canvix, just+keep it few"). All five are closed in this pass; the v0.32 statements+about the client PUT and best-effort persistence above are SUPERSEDED+by this section.++## P0 — exact-text preservation is now exact++`validateBrief` used case-insensitive SUBSTRING matching: a required+`"Run Dal Lake 2026"` passed when the canvas held `"Run Dal Lake 2026+— Special Offer"`. It now enforces strict normalized equality+(whitespace collapsed, everything else character-for-character).+Regression tests cover exactly the review's list — appended words,+capitalization changes, punctuation edits, missing spaces — at three+levels: unit (`continuation.test.ts`, `harness.test.ts`), the+acceptance gate (a refinement that appends words is rejected and+bounced back), and the server-side save verification (the e2e flips+`verified` to false on an appended-words save).++## P0 — no requirement is silently weakened anymore++`normalizeStoredBrief` discarded `restrictions` and `notes`, silently+truncated texts at 200 chars and capped at 24 entries. Now:+restrictions and notes SURVIVE persistence (a "no stock photos" rides+every refinement prompt); texts are never sliced mid-string; caps are+generous (64 texts / 32 colors / 16 features); and overflow is+EXPLICIT — the persistence path runs in **reject** mode (an over-limit+brief is refused with a reason, never stored weakened), read paths run+clamp mode and count what they dropped.++## P0 — the original AI prompt is private++The provenance row stores the generation prompt; both GETs used to+ship it to anyone who could open the link — including read-only+viewers — while the prompt can hold information not present in the+finished design. Now `prompt` ships ONLY to callers who may edit the+design (owner/anon attribution); link viewers receive the shareable+contract — brief, verification state, timestamps — never the prompt.+The e2e proves it with a real viewer against a design that HAS+provenance.++## P1 — stored provenance now carries proof, not claims++The client-supplied `PUT /api/designs/[id]/ai-provenance` is GONE (an+authorized editor could store any brief with `outcome: "passed"`).+Contracts now enter the store only through the **design save itself**:+the apply flow queues a pending contract in the editor store, the next+`PUT /api/designs/[id]` carries it alongside the pages, the server+normalizes it in reject mode and **verifies it against the final saved+pages** (`verified`, `verifiedAt` — migration 0014). Every later save+re-validates and keeps the verdict true to the current document —+drift flips it false, restoration flips it back. The chat agent reads+the AUTHORITATIVE database brief (the design context now carries+`designId`), so a client post cannot tamper with what a run is gated+on. Side effect: the "failed provenance save then reload" hazard is+gone structurally — persistence rides the same save as the pages, so+an unsaved apply loses pages and contract together, consistently.++Also fixed here: the reload hydration bug — the design GET's+`aiProvenance` payload object was stored as the brief itself, so+reload continuation silently did nothing. The store now hydrates the+payload's `brief` (regression-tested).++## The consolidation — ONE AI surface++Six AI-branded apps in the registry (chat copilot, design agent,+Magic Write, AI image generator, AI design plan, AI theme) became one+**Canvix AI** app with five mode tabs — Chat / Generate / Write /+Image / Theme — each rendering the original, unchanged app component+(`UnifiedAIApp.tsx`). The AI design plan panel is retired: its+describe → review → apply flow IS the Generate tab, with the stronger+DesignAgent engine behind it (`/api/ai/plan` remains available as an+API). The wave-4 e2e now opens the unified app and switches tabs; the+plan panel's UI test was retired with the panel.++## Evidence (v0.32.1)++- Unit: 1,709/1,709 (16 in the acceptance file — strict-equality+ regressions, restriction preservation, reject-mode refusals, the+ reload-hydration regression, and the appended-words gate).+- tsc, eslint, production build clean locally.+- Live-DB e2e (`unified-ai-provenance.spec.ts`, rewritten): the+ apply→save flow with server verification, the appended-words flip,+ viewer privacy (no prompt, writes refused, PUT 405), junk and+ over-limit refusals with explicit reasons, flat 404 on missing ids.+- Migration `0014` validated offline against Prisma's own schema+ derivation (statement-equal) and applied by CI's db:setup.diff --git a/prisma/migrations/0014_design_ai_provenance_verified/migration.sql b/prisma/migrations/0014_design_ai_provenance_verified/migration.sqlnew file mode 100644index 0000000..1da7fe5--- /dev/null+++ b/prisma/migrations/0014_design_ai_provenance_verified/migration.sql@@ -0,0 +1,10 @@+-- v0.32.1 (Unified Canvix AI hardening, review P1): server-side+-- verification state on design provenance. The design save now+-- re-validates the stored brief against the SAVED pages and flips+-- `verified` — stored provenance carries proof, not a client's+-- claim. `verifiedAt` binds the proof to the document version it+-- was checked against.++-- AlterTable+ALTER TABLE "DesignProvenance" ADD COLUMN "verified" BOOLEAN NOT NULL DEFAULT false,+ADD COLUMN "verifiedAt" TIMESTAMP(3);diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 68c8b74..31159b8 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -162,14 +162,21 @@ model Design {// audit trail of the run that produced it. Cascade: deleting a design// deletes its provenance (it is meaningless without the design).model DesignProvenance {- id String @id @default(cuid())- designId String @unique- design Design @relation("DesignProvenance", fields: [designId], references: [id], onDelete: Cascade)- prompt String @default("")- brief Json @default("{}")- outcome String @default("passed")- createdAt DateTime @default(now())- updatedAt DateTime @updatedAt+ id String @id @default(cuid())+ designId String @unique+ design Design @relation("DesignProvenance", fields: [designId], references: [id], onDelete: Cascade)+ prompt String @default("")+ brief Json @default("{}")+ outcome String @default("passed")+ // v0.32.1 (review P1): server-side verification state. The design+ // save re-validates the stored brief against the SAVED pages and+ // flips this flag — stored provenance carries proof, not a client's+ // claim. verifiedAt binds the proof to the document version it was+ // checked against.+ verified Boolean @default(false)+ verifiedAt DateTime?+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt}// ── v0.14 (D6): dashboard folders ───────────────────────────diff --git a/src/app/api/ai/agent/route.ts b/src/app/api/ai/agent/route.tsindex cce01a1..b3414f3 100644--- a/src/app/api/ai/agent/route.ts+++ b/src/app/api/ai/agent/route.ts@@ -18,6 +18,7 @@ import { extractBrief, mergeBriefs, normalizeStoredBrief, type DesignBrief } froimport { critiqueWithVision } from '@/lib/agent/vision'import { getClientForSlotForUser } from '@/lib/ai/provider'import { getSessionUser } from '@/lib/auth/session'+import { getDesignProvenance } from '@/lib/design-provenance'export const runtime = 'nodejs'export const maxDuration = 800@@ -82,6 +83,25 @@ function newRunId(): string {return `run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`}+/** v0.32.1 (review P1): the stored brief, read AUTHORITATIVELY. When+ * the design context carries a design id, the persisted DB contract+ * (server-normalized, server-verified provenance) wins — a client+ * post cannot tamper with what the run is gated on. The posted+ * aiBrief is only the fallback (designs whose provenance is not yet+ * persisted, or a DB hiccup). */+async function authoritativeStoredBrief(design: AgentDesignCtx): Promise<DesignBrief | null> {+ if (design.designId) {+ try {+ const row = await getDesignProvenance(design.designId)+ if (row) return row.brief+ } catch {+ /* fall through to the posted brief */+ }+ }+ const posted = normalizeStoredBrief(design.aiBrief)+ return posted ? posted.brief : null+}+/** v0.29.3: one grounded vision critique of a REAL captured* screenshot — shared by the loop's pre-completion round. Resolves* null when the vision slot is unconfigured or the call fails (the@@ -255,7 +275,12 @@ async function __canvix_post(req: NextRequest) {// and an edit-mode refinement on such a design is gated on the// merged brief too: a refinement may not finish while a verified// requirement has gone missing.- const storedBrief = normalizeStoredBrief(design.aiBrief)+ // v0.32.1 (review P1): when the context carries the design id, the+ // persisted DB contract is AUTHORITATIVE — server-normalized,+ // server-verified — so a client post cannot tamper with what the+ // run is gated on. The client-posted aiBrief stays as the fallback+ // for designs whose provenance is not (yet) persisted.+ const storedBrief = await authoritativeStoredBrief(design)const extracted =mode === 'create' || mode === 'improve'? extractBrief(message, design.width, design.height)diff --git a/src/app/api/designs/[id]/ai-provenance/route.ts b/src/app/api/designs/[id]/ai-provenance/route.tsindex c037e52..1df8600 100644--- a/src/app/api/designs/[id]/ai-provenance/route.ts+++ b/src/app/api/designs/[id]/ai-provenance/route.ts@@ -1,30 +1,28 @@import { NextRequest, NextResponse } from 'next/server'-import { resolveDesignAccess, NOT_YOUR_DESIGN } from '@/lib/auth/design-guard'-import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'-import { checkRateLimit, rateLimitResponse } from '@/lib/rate-limit'+import { resolveDesignAccess } from '@/lib/auth/design-guard'import { withLogging } from '@/lib/observability'-import { saveDesignProvenance, getDesignProvenance } from '@/lib/design-provenance'+import { getDesignProvenance } from '@/lib/design-provenance'export const runtime = 'nodejs'// ─────────────────────────────────────────────────────────────-// /api/designs/[id]/ai-provenance (v0.32 — Unified Canvix AI).+// GET /api/designs/[id]/ai-provenance (v0.32 — Unified Canvix AI;+// hardened v0.32.1).//// The stored brief contract of the design: what an autonomous-// generation was verified against, so later natural-language-// refinement of the SAME design stays gated on it.+// generation was verified against, plus the SERVER-SIDE verification+// state (re-checked on every design save). Read-only —//-// GET → { prompt, brief, outcome, updatedAt? } | { brief: null }-// PUT { prompt?, brief, outcome? } → the stored payload (upsert)-//-// Deliberately separate from PUT /api/designs/[id] (the autosave-// path — provenance changes once, at DesignAgent Apply, and must-// never ride the 300/min save budget). Access mirrors the design-// routes: GET is link-open (viewing), PUT needs edit rights-// (owner/anon attribution; 404 absent, 403 foreign-owned).-// The brief is normalized server-side (src/lib/design-provenance.ts)-// — dimensions dropped (the design's own canvas is the truth after-// apply), tiers forced mandatory, everything capped.+// v0.32.1 (review P0/P1): the PUT is GONE. Contracts enter the store+// only through the design save itself (PUT /api/designs/[id] with+// the apply flow's pending payload), where the brief is normalized+// in 'reject' mode and verified against the final saved pages — an+// authorized editor can no longer store an arbitrary brief or an+// unearned 'passed'. And the original generation prompt ships only+// to callers who may EDIT the design; link viewers get the+// shareable contract (brief, verified, verifiedAt), never the+// prompt. GET follows the designs family: link-view (200 with null+// when no provenance exists); a missing id is a flat 404.// ─────────────────────────────────────────────────────────────async function __canvix_get(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {@@ -32,7 +30,7 @@ async function __canvix_get(req: NextRequest, { params }: { params: Promise<{ idconst { id } = await paramsconst access = await resolveDesignAccess(req, id)if (!access) return NextResponse.json({ error: 'Not found' }, { status: 404 })- const provenance = await getDesignProvenance(id)+ const provenance = await getDesignProvenance(id, { includePrompt: access.canEdit })return NextResponse.json({ provenance })} catch (error) {console.error('GET /api/designs/[id]/ai-provenance failed', error)@@ -40,38 +38,6 @@ async function __canvix_get(req: NextRequest, { params }: { params: Promise<{ id}}-async function __canvix_put(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {- if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })- // once per applied generation — its own small budget, not the- // autosave's (a runaway client cannot hammer this path)- const limit = checkRateLimit(req, 'designs:update')- if (!limit.ok) return rateLimitResponse(limit)- try {- const { id } = await params- const access = await resolveDesignAccess(req, id)- if (!access) return NextResponse.json({ error: 'Not found' }, { status: 404 })- if (!access.canEdit) return NextResponse.json(NOT_YOUR_DESIGN, { status: 403 })-- const body = (await req.json().catch(() => ({}))) as { prompt?: unknown; brief?: unknown; outcome?: unknown }- const stored = await saveDesignProvenance(id, {- prompt: typeof body.prompt === 'string' ? body.prompt : '',- brief: body.brief,- outcome: typeof body.outcome === 'string' ? body.outcome : undefined,- })- if (!stored) {- return NextResponse.json(- { error: 'The provenance brief carried no usable requirements (texts, colors or features).' },- { status: 422 },- )- }- return NextResponse.json({ provenance: stored })- } catch (error) {- console.error('PUT /api/designs/[id]/ai-provenance failed', error)- return NextResponse.json({ error: 'Failed to save provenance' }, { status: 500 })- }-}-// v0.12.5 (H7): opt-in request logging wrapper — passthrough// unless CANVIX_LOG=requests (see src/lib/observability.ts)export const GET = withLogging('GET /api/designs/[id]/ai-provenance', __canvix_get)-export const PUT = withLogging('PUT /api/designs/[id]/ai-provenance', __canvix_put)diff --git a/src/app/api/designs/[id]/route.ts b/src/app/api/designs/[id]/route.tsindex c62cff1..cde9924 100644--- a/src/app/api/designs/[id]/route.ts+++ b/src/app/api/designs/[id]/route.ts@@ -11,7 +11,7 @@ import { getSessionUser } from '@/lib/auth/session'import { anonHashFrom } from '@/lib/auth/anon'import { recordActive } from '@/lib/admin/traffic'import { getSettings } from '@/lib/admin/config'-import { getDesignProvenance } from '@/lib/design-provenance'+import { getDesignProvenance, saveDesignProvenance, revalidateDesignProvenance } from '@/lib/design-provenance'// Normalise incoming pages payload (accepts object or legacy JSON string)// into a value suitable for the Postgres jsonb column.@@ -48,7 +48,11 @@ async function __canvix_get(req: NextRequest, { params }: { params: Promise<{ id// rides the design load so the editor — and the chat agent through// it — knows the requirements an applied autonomous generation was// verified against. Null when the design has no AI provenance.- const aiProvenance = await getDesignProvenance(id).catch(() => null)+ // v0.32.1 (review P0): the ORIGINAL PROMPT is private — it ships+ // only to callers who may edit this design; link viewers get the+ // shareable contract (brief + verification state), never the+ // prompt that produced it.+ const aiProvenance = await getDesignProvenance(id, { includePrompt: access.canEdit }).catch(() => null)return NextResponse.json({...design,pages: design.pages ?? [],@@ -128,11 +132,56 @@ async function __canvix_put(req: NextRequest, { params }: { params: Promise<{ id}const design = await db.design.update({ where: { id }, data })++ // ── v0.32.1 (Unified Canvix AI, review P1): provenance persistence+ // rides the design save itself ─────────────────────────────────+ // The apply flow marks the store's pending contract; the FIRST+ // save that lands those pages persists it — normalized in+ // 'reject' mode (over-limit briefs are REFUSED with a reason,+ // never stored weakened) and verified SERVER-SIDE against the+ // final saved pages (post-merge). Every LATER save re-validates+ // the stored brief and keeps the verdict true to the document,+ // so `verified` is proof bound to the saved version, not a+ // client's claim.+ let provenanceExtra: Record<string, unknown> = {}+ try {+ const pending = (body as { aiProvenance?: { prompt?: unknown; outcome?: unknown; brief?: unknown } }).aiProvenance+ const finalPages = asPages(design.pages)+ if (pending && typeof pending === 'object' && (pending.brief !== undefined || pending.outcome !== undefined)) {+ const result = await saveDesignProvenance(+ id,+ {+ prompt: typeof pending.prompt === 'string' ? pending.prompt : '',+ outcome: typeof pending.outcome === 'string' ? pending.outcome : undefined,+ brief: pending.brief,+ },+ { pages: finalPages, width: design.width, height: design.height },+ )+ provenanceExtra =+ result.status === 'stored'+ ? { aiProvenance: result.payload }+ : { aiProvenanceRejected: result.reason }+ } else if (body.pages !== undefined) {+ // plain content save — keep the stored verdict honest+ const revalidated = await revalidateDesignProvenance(id, {+ pages: finalPages,+ width: design.width,+ height: design.height,+ })+ if (revalidated) provenanceExtra = { aiProvenanceVerified: revalidated.verified }+ }+ } catch (provErr) {+ // provenance persistence is best-effort ON TOP of a successful+ // design save — a provenance failure must never fail the save+ console.error('PUT /api/designs/[id] provenance hook failed', provErr)+ }+return NextResponse.json({id: design.id,name: design.name,updatedAt: design.updatedAt,...(mergedPages ? { merged: true, pages: mergedPages } : {}),+ ...provenanceExtra,})} catch (error) {console.error('PUT /api/designs/[id] failed', error)diff --git a/src/components/editor/Editor.tsx b/src/components/editor/Editor.tsxindex 1aa1856..dfbd81b 100644--- a/src/components/editor/Editor.tsx+++ b/src/components/editor/Editor.tsx@@ -186,6 +186,11 @@ export default function Editor() {pages: state.pages,baseUpdatedAt: state.baseUpdatedAt,...(thumbnail ? { thumbnail } : {}),+ // v0.32.1: the apply flow's pending contract rides THIS save —+ // the server normalizes it ('reject' mode: over-limit is+ // refused, never weakened) and verifies it against the+ // saved pages (proof, not a claim)+ ...(state.aiPendingProvenance ? { aiProvenance: state.aiPendingProvenance } : {}),}),})if (!res.ok) throw new Error('save failed')@@ -193,6 +198,21 @@ export default function Editor() {updatedAt?: stringmerged?: booleanpages?: PageData[]+ aiProvenance?: unknown+ aiProvenanceRejected?: string+ }+ // v0.32.1: the contract was stored or explicitly rejected —+ // either way the pending payload is settled (a rejection is+ // surfaced, never silently retried into a weakened store)+ if (saved.aiProvenance !== undefined || saved.aiProvenanceRejected !== undefined) {+ if (saved.aiProvenanceRejected) {+ toast({+ title: 'AI contract not saved',+ description: saved.aiProvenanceRejected.slice(0, 160),+ variant: 'destructive',+ })+ }+ useEditorStore.getState().setAIPendingProvenance(null)}// v0.10: the server merged our pages with concurrent edits — adopt// the merged result (applying through the merge gate is a no-op fordiff --git a/src/components/editor/apps/AIPlanApp.tsx b/src/components/editor/apps/AIPlanApp.tsxdeleted file mode 100644index cf06b2e..0000000--- a/src/components/editor/apps/AIPlanApp.tsx+++ /dev/null@@ -1,328 +0,0 @@-'use client'--import { useState } from 'react'-import { Bot, Loader2, Check, Eye, EyeOff, Sparkles } from 'lucide-react'-import { useEditorStore } from '@/store/editor-store'-import { planToPages, type DesignPlan, type PlanPageSpec } from '@/lib/design-plan'-import { AppHeader, type AppPanelProps } from './registry'-import { cn } from '@/lib/utils'-import { toast } from '@/hooks/use-toast'--const IDEAS = [- 'A 4-page launch deck for a specialty coffee subscription — warm, cozy, earthy',- 'Instagram post + story for a fitness studio opening — bold, high energy',- '3-page pitch outline for an eco packaging startup — clean, green, minimal',-]--/**- * v0.19 (Wave 4) — Agentic design planning with an EDITABLE REVIEW GATE.- *- * Step 1: the user describes the design; /api/ai/plan returns a- * structured multi-page plan (nothing is applied yet).- * Step 2: the gate — every page and element can be toggled, every text- * rewritten, colors seen — before anything lands.- * Step 3: Apply → planToPages() → store.appendPages() as fully editable- * native elements. Ctrl+Z undoes the whole apply.- */-export function AIPlanApp({ onClose }: AppPanelProps) {- const [prompt, setPrompt] = useState('')- const [pageCount, setPageCount] = useState(2)- const [busy, setBusy] = useState(false)- const [error, setError] = useState<string | null>(null)- const [plan, setPlan] = useState<DesignPlan | null>(null)-- const width = useEditorStore((s) => s.width)- const height = useEditorStore((s) => s.height)-- const generate = async () => {- if (!prompt.trim() || busy) return- setBusy(true)- setError(null)- setPlan(null)- try {- const res = await fetch('/api/ai/plan', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ prompt: prompt.trim(), width, height, pageCount }),- })- const data = (await res.json()) as { plan?: DesignPlan; error?: string }- if (!res.ok || !data.plan) throw new Error(data.error ?? 'Planning failed')- setPlan(data.plan)- } catch (e) {- setError(e instanceof Error ? e.message : 'Planning failed')- } finally {- setBusy(false)- }- }-- const togglePage = (id: string) => {- setPlan((p) =>- p ? { ...p, pages: p.pages.map((pg) => (pg.id === id ? { ...pg, enabled: !pg.enabled } : pg)) } : p,- )- }- const toggleElement = (pageId: string, elId: string) => {- setPlan((p) =>- p- ? {- ...p,- pages: p.pages.map((pg) =>- pg.id !== pageId- ? pg- : { ...pg, elements: pg.elements.map((el) => (el.id === elId ? { ...el, enabled: !el.enabled } : el)) },- ),- }- : p,- )- }- const editText = (pageId: string, elId: string, text: string) => {- setPlan((p) =>- p- ? {- ...p,- pages: p.pages.map((pg) =>- pg.id !== pageId- ? pg- : { ...pg, elements: pg.elements.map((el) => (el.id === elId ? { ...el, text } : el)) },- ),- }- : p,- )- }-- const apply = () => {- if (!plan) return- const pages = planToPages(plan)- if (!pages.length) {- toast({ title: 'Nothing to apply', description: 'Enable at least one page with elements.' })- return- }- useEditorStore.getState().appendPages(pages)- toast({- title: `${pages.length} page${pages.length > 1 ? 's' : ''} added`,- description: 'Fully editable elements. Ctrl+Z removes them all.',- })- onClose()- }-- const enabledPages = plan?.pages.filter((p) => p.enabled).length ?? 0- const enabledElements =- plan?.pages.filter((p) => p.enabled).reduce((n, p) => n + p.elements.filter((e) => e.enabled).length, 0) ?? 0-- return (- <div>- <AppHeader icon={Bot} title="AI design plan" onClose={onClose} />- <p className="text-[11.5px] text-white/50 leading-snug mb-3">- Describe the design — the agent drafts a full multi-page plan you REVIEW and EDIT before a single- element lands on the canvas.- </p>-- <textarea- value={prompt}- onChange={(e) => setPrompt(e.target.value)}- placeholder="e.g. A 3-page menu for an Italian trattoria — rustic, warm, handwritten accents"- className="w-full h-24 rounded-xl bg-white/[0.05] border border-white/10 text-white text-[12.5px] p-3 resize-none focus:outline-none focus:border-[#02C0CC]"- maxLength={2000}- aria-label="Design brief"- />-- <div className="flex items-center gap-2 mt-2.5">- <span className="text-[11px] text-white/50">Pages</span>- <div className="flex gap-1">- {[1, 2, 3, 4, 6].map((n) => (- <button- key={n}- onClick={() => setPageCount(n)}- className={cn(- 'w-8 h-8 rounded-lg text-[11px] font-bold transition-colors',- pageCount === n ? 'bg-[#7630D7] text-white' : 'bg-white/[0.05] text-white/60 hover:bg-white/10',- )}- aria-pressed={pageCount === n}- >- {n}- </button>- ))}- </div>- <button- className="btn-cv h-9 px-4 ml-auto text-[12px] flex items-center gap-1.5 disabled:opacity-60"- onClick={() => void generate()}- disabled={busy || !prompt.trim()}- >- {busy ? <Loader2 size={13} className="animate-spin" /> : <Sparkles size={13} />}- {busy ? 'Planning…' : 'Plan my design'}- </button>- </div>-- {!plan && !busy && (- <div className="mt-3 space-y-1.5">- {IDEAS.map((idea) => (- <button- key={idea}- onClick={() => setPrompt(idea)}- className="block w-full text-left text-[11px] text-white/45 hover:text-white/80 px-2.5 py-2 rounded-lg hover:bg-white/[0.04] transition-colors"- >- “{idea}”- </button>- ))}- </div>- )}-- {error && (- <p className="mt-3 rounded-xl border border-red-400/30 bg-red-400/10 px-3 py-2 text-[11.5px] text-red-200">- {error}- </p>- )}-- {plan && (- <div className="mt-4 border-t border-white/10 pt-3">- <div className="flex items-start gap-2 mb-3">- <div className="min-w-0">- <p className="text-[12.5px] font-bold text-white truncate">{plan.name}</p>- {plan.summary && <p className="text-[11px] text-white/50 leading-snug mt-0.5">{plan.summary}</p>}- </div>- <div className="ml-auto flex gap-2 shrink-0">- <button- className="text-[11px] text-white/55 hover:text-white px-2.5 h-8 rounded-lg hover:bg-white/10"- onClick={() => setPlan(null)}- >- Redraft- </button>- <button className="btn-cv h-8 px-3.5 text-[11.5px] flex items-center gap-1.5" onClick={apply}>- <Check size={12} /> Apply {enabledPages > 0 ? `(${enabledPages}p · ${enabledElements}el)` : ''}- </button>- </div>- </div>-- <div className="space-y-3">- {plan.pages.map((pg) => (- <PageCard- key={pg.id}- page={pg}- planWidth={plan.width}- planHeight={plan.height}- onTogglePage={togglePage}- onToggleElement={toggleElement}- onEditText={editText}- />- ))}- </div>-- <p className="mt-3 text-[10.5px] text-white/35 leading-snug">- Uncheck anything you don't want; edit any copy inline. Apply adds the checked pages to this design- as native editable elements — one Ctrl+Z removes them all.- </p>- </div>- )}- </div>- )-}--/** One reviewable page: mini preview + element checklist with inline copy editing. */-function PageCard({- page,- planWidth,- planHeight,- onTogglePage,- onToggleElement,- onEditText,-}: {- page: PlanPageSpec- planWidth: number- planHeight: number- onTogglePage: (id: string) => void- onToggleElement: (pageId: string, elId: string) => void- onEditText: (pageId: string, elId: string, text: string) => void-}) {- return (- <div- className={cn(- 'rounded-xl border p-2.5 transition-colors',- page.enabled ? 'border-white/12 bg-white/[0.04]' : 'border-white/8 bg-white/[0.015] opacity-60',- )}- >- <div className="flex items-center gap-2">- <button- onClick={() => onTogglePage(page.id)}- className={cn(- 'w-5 h-5 rounded-md border flex items-center justify-center shrink-0 transition-colors',- page.enabled ? 'bg-[#02C0CC] border-[#02C0CC] text-black' : 'border-white/25 text-transparent',- )}- aria-label={page.enabled ? `Disable page ${page.title}` : `Enable page ${page.title}`}- aria-pressed={page.enabled}- >- <Check size={12} strokeWidth={3.5} />- </button>- <span className="text-[12px] font-semibold text-white/90 truncate">{page.title}</span>- <span className="ml-auto text-[10px] text-white/40">{page.elements.filter((e) => e.enabled).length}/{page.elements.length}</span>- </div>-- <div className="flex gap-2.5 mt-2">- {/* scaled geometry preview — the honest wireframe of the plan */}- <div- className="relative shrink-0 rounded-lg overflow-hidden border border-white/10"- style={{- width: 96,- height: Math.max(48, Math.round((96 * planHeight) / Math.max(1, planWidth))),- background:- page.background.type === 'gradient'- ? `linear-gradient(${page.background.angle}deg, ${page.background.from}, ${page.background.to})`- : page.background.color,- }}- aria-hidden- >- {page.elements.map((el) => (- <div- key={el.id}- className="absolute rounded-[2px]"- style={{- left: `${(el.x / planWidth) * 100}%`,- top: `${(el.y / planHeight) * 100}%`,- width: `${(el.width / planWidth) * 100}%`,- height: `${((el.height ?? Math.round(planHeight * 0.06)) / planHeight) * 100}%`,- background: el.type === 'text' ? 'rgba(255,255,255,0.75)' : (el.fill ?? '#02C0CC'),- opacity: el.enabled ? 0.9 : 0.25,- minHeight: 3,- }}- />- ))}- </div>-- <div className="flex-1 min-w-0 space-y-1 max-h-44 overflow-y-auto pr-0.5">- {page.elements.map((el) => (- <div key={el.id} className="flex items-center gap-1.5">- <button- onClick={() => onToggleElement(page.id, el.id)}- className={cn(- 'w-4 h-4 rounded border flex items-center justify-center shrink-0 transition-colors',- el.enabled ? 'bg-[#02C0CC] border-[#02C0CC] text-black' : 'border-white/25 text-transparent',- )}- aria-label={- el.enabled- ? `Disable ${el.type}: ${(el.text ?? '').slice(0, 30) || el.type}`- : `Enable ${el.type}: ${(el.text ?? '').slice(0, 30) || el.type}`- }- aria-pressed={el.enabled}- >- <Check size={9} strokeWidth={4} />- </button>- {el.type === 'text' ? (- <input- value={el.text ?? ''}- onChange={(e) => onEditText(page.id, el.id, e.target.value)}- className="flex-1 min-w-0 h-7 rounded-md bg-white/[0.05] border border-white/10 text-[11px] text-white px-2 focus:outline-none focus:border-[#02C0CC]"- aria-label="Element text"- maxLength={400}- />- ) : (- <span className="flex items-center gap-1.5 text-[11px] text-white/55 truncate">- {el.enabled ? <Eye size={11} className="shrink-0" /> : <EyeOff size={11} className="shrink-0" />}- {el.type} — {el.width}×{el.height ?? 'auto'}- <span className="w-2.5 h-2.5 rounded-sm border border-white/20 shrink-0" style={{ background: el.fill ?? '#02C0CC' }} />- </span>- )}- </div>- ))}- </div>- </div>- </div>- )-}diff --git a/src/components/editor/apps/AssistantApp.tsx b/src/components/editor/apps/AssistantApp.tsxindex 351e25d..38ea4cb 100644--- a/src/components/editor/apps/AssistantApp.tsx+++ b/src/components/editor/apps/AssistantApp.tsx@@ -204,6 +204,10 @@ function buildDesignContext() {return {name: s.designName,+ // v0.32.1: the design id lets the route read the AUTHORITATIVE+ // stored brief from the database — the posted aiBrief copy is+ // only a fallback+ designId: s.designId,width: s.width,height: s.height,templateType: (s as unknown as { templateType?: string }).templateType,diff --git a/src/components/editor/apps/DesignAgentApp.tsx b/src/components/editor/apps/DesignAgentApp.tsxindex 7fdc25c..cd3f57a 100644--- a/src/components/editor/apps/DesignAgentApp.tsx+++ b/src/components/editor/apps/DesignAgentApp.tsx@@ -163,21 +163,19 @@ export function DesignAgentApp({ onClose }: AppPanelProps) {setApplied(true)// v0.32 (Unified Canvix AI — continuation): the applied pages carry// their contract. The store brief makes every later chat-agent run- // on THIS design merge it (create→verify→refine on one design);- // the provenance PUT persists it across sessions/reloads. Both are- // best-effort AFTER the pages landed — a persistence hiccup never- // rolls the apply back, and the session brief still guards.+ // on THIS design merge it (create→verify→refine on one design).+ // v0.32.1 (review P1): persistence no longer happens here — the+ // PENDING contract rides the next design save (PUT /api/designs/+ // [id]), where the server normalizes it in 'reject' mode and+ // verifies it against the saved pages. No client-supplied PUT, no+ // unearned 'passed', and a failed save can't strand a contract+ // for pages that were never saved.const brief = result.report?.brief ?? null- if (brief) store.setAIBrief(brief)- if (brief && store.designId && !store.readOnly) {- void fetch(`/api/designs/${store.designId}/ai-provenance`, {- method: 'PUT',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ prompt, brief, outcome: result.outcome }),- }).catch(() => {- /* session brief still guards; reload loses the stored contract */- console.warn('[design-agent] provenance save failed')- })+ if (brief) {+ store.setAIBrief(brief)+ if (!store.readOnly) {+ store.setAIPendingProvenance({ prompt, outcome: result.outcome, brief })+ }}toast({title: `${chosen.length} page${chosen.length > 1 ? 's' : ''} added`,diff --git a/src/components/editor/apps/UnifiedAIApp.tsx b/src/components/editor/apps/UnifiedAIApp.tsxnew file mode 100644index 0000000..d6be4d2--- /dev/null+++ b/src/components/editor/apps/UnifiedAIApp.tsx@@ -0,0 +1,112 @@+'use client'++// ─────────────────────────────────────────────────────────────+// UnifiedAIApp (v0.32.1) — ONE AI surface.+//+// The review that mattered: "I don't want multiple AI apps in+// canvix, just keep it few." Six AI-branded panels (chat copilot,+// design agent, Magic Write, AI image, AI design plan, AI theme)+// became this one app with five modes:+//+// Chat — the agent: refine THIS design in natural language+// (brief-contract gated, edit-safe)+// Generate — the autonomous pipeline: one prompt → planned,+// compiled, checked, visually verified, reviewed by+// you, applied editable+// Write — AI copy: headlines, taglines, captions+// Image — prompt → design-ready image+// Theme — palette + fonts, applied safely with contrast guards+//+// The former AI design plan app is retired — its describe → review+// → apply flow IS the Generate tab, with the stronger engine behind+// it. The /api/ai/plan route stays available as an API.+//+// Each tab renders the original self-contained app component —+// behavior, review gates and honesty contracts unchanged. The panel+// opens on Chat (the most-used mode); switching tabs keeps each+// app's internal state only while it is active, exactly as before.+// ─────────────────────────────────────────────────────────────++import { useState } from 'react'+import type { AppPanelProps } from './registry'+import { cn } from '@/lib/utils'+import { AssistantApp } from './AssistantApp'+import { DesignAgentApp } from './DesignAgentApp'+import { MagicWriteApp } from './MagicWriteApp'+import { AIImageApp } from './AIImageApp'+import { AIThemeApp } from './AIThemeApp'++const TABS = [+ {+ id: 'chat',+ label: 'Chat',+ hint: 'Refine this design in natural language — brief-contract gated',+ Component: AssistantApp,+ },+ {+ id: 'generate',+ label: 'Generate',+ hint: 'One prompt in — a checked, reviewed, editable design out',+ Component: DesignAgentApp,+ },+ {+ id: 'write',+ label: 'Write',+ hint: 'AI copy — headlines, taglines & captions',+ Component: MagicWriteApp,+ },+ {+ id: 'image',+ label: 'Image',+ hint: 'Turn a prompt into a design-ready image',+ Component: AIImageApp,+ },+ {+ id: 'theme',+ label: 'Theme',+ hint: 'Palette + fonts for the whole design, applied safely',+ Component: AIThemeApp,+ },+] as const++type TabId = (typeof TABS)[number]['id']++export function UnifiedAIApp({ onClose }: AppPanelProps) {+ const [tab, setTab] = useState<TabId>('chat')+ const active = TABS.find((t) => t.id === tab) ?? TABS[0]+ const Active = active.Component+ const select = (id: TabId) => {+ setTab(id)+ }+ return (+ <div className="flex flex-col gap-2">+ <div role="tablist" aria-label="Canvix AI modes" className="flex flex-wrap gap-1.5">+ {TABS.map((t) => (+ <div+ key={t.id}+ role="tab"+ tabIndex={0}+ aria-selected={tab === t.id}+ title={t.hint}+ onClick={() => select(t.id)}+ onKeyDown={(e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault()+ select(t.id)+ }+ }}+ className={cn(+ 'cursor-pointer select-none rounded-full px-3 py-1 text-[11px] font-semibold transition-colors',+ tab === t.id+ ? 'bg-[#7630D7] text-white'+ : 'bg-white/5 text-white/55 hover:bg-white/10 hover:text-white',+ )}+ >+ {t.label}+ </div>+ ))}+ </div>+ <Active onClose={onClose} />+ </div>+ )+}diff --git a/src/components/editor/apps/registry.tsx b/src/components/editor/apps/registry.tsxindex 1dac597..f713866 100644--- a/src/components/editor/apps/registry.tsx+++ b/src/components/editor/apps/registry.tsx@@ -1,6 +1,6 @@'use client'-import { BarChart3, QrCode, Smile, Shapes, Palette, Type, Wand2, ImageIcon, Bot, LayoutTemplate, SwatchBook, Video, Workflow } from 'lucide-react'+import { BarChart3, QrCode, Smile, Shapes, Palette, Type, ImageIcon, Bot } from 'lucide-react'import type { LucideIcon } from 'lucide-react'/** ── Canvix app registry ─────────────────────────────────────@@ -31,24 +31,17 @@ import { IllustrationsApp } from './IllustrationsApp'import { PaletteApp } from './PaletteApp'import { LoremApp } from './LoremApp'import { StickersApp } from './StickersApp'-import { MagicWriteApp } from './MagicWriteApp'-import { AIImageApp } from './AIImageApp'-import { AssistantApp } from './AssistantApp'-import { AIPlanApp } from './AIPlanApp'-import { AIThemeApp } from './AIThemeApp'-import { DesignAgentApp } from './DesignAgentApp'+import { UnifiedAIApp } from './UnifiedAIApp'export const CANVIX_APPS: CanvixApp[] = [// AI apps first (canva 2026: “Canva AI” is the flagship surface)- { id: 'assistant', name: 'Canvix AI', desc: 'Chat copilot — copy, palettes, images, translate', icon: Bot, color: '#7630D7', content: AssistantApp },- // v0.31: the autonomous generation pipeline — one prompt →- // planned, compiled, checked, visually reviewed, REVIEWED BY YOU- { id: 'design-agent', name: 'Design agent', desc: 'One prompt in — a checked, reviewed, editable design out', icon: Workflow, color: '#02C0CC', content: DesignAgentApp },- { id: 'magic-write', name: 'Magic Write', desc: 'AI copy — headlines, taglines & captions', icon: Wand2, color: '#9B6BFF', content: MagicWriteApp },- { id: 'ai-image', name: 'AI image generator', desc: 'Turn a prompt into a design-ready image', icon: ImageIcon, color: '#02C0CC', content: AIImageApp },- // v0.19 (Wave 4 — AI Power-Up):- { id: 'ai-plan', name: 'AI design plan', desc: 'Describe it — review the plan — apply editable pages', icon: LayoutTemplate, color: '#7630D7', content: AIPlanApp },- { id: 'ai-theme', name: 'AI theme', desc: 'Palette + fonts for the whole design, applied safely', icon: SwatchBook, color: '#FF5C8A', content: AIThemeApp },+ // v0.32.1 (Unified Canvix AI): ONE AI surface. The six AI-branded+ // apps (chat copilot, design agent, Magic Write, AI image, AI+ // design plan, AI theme) consolidated into a single app with five+ // modes (Chat / Generate / Write / Image / Theme — see+ // UnifiedAIApp). The AI design plan panel is retired: its+ // describe → review → apply flow IS the Generate tab.+ { id: 'ai', name: 'Canvix AI', desc: 'One AI for the whole design — chat, generate, write, images, theme', icon: Bot, color: '#7630D7', content: UnifiedAIApp },{ id: 'charts', name: 'Charts', desc: 'Bar, line & donut charts as editable shapes', icon: BarChart3, color: '#7630D7', content: ChartsApp },{ id: 'qr', name: 'QR generator', desc: 'Turn any link or text into a QR code', icon: QrCode, color: '#3B82F6', content: QRApp },{ id: 'icons', name: 'Icons', desc: '562 offline icons + the Iconify universe online', icon: Shapes, color: '#02C0CC', content: IconsApp },diff --git a/src/lib/agent/brief.ts b/src/lib/agent/brief.tsindex 09dae6c..e0c80a6 100644--- a/src/lib/agent/brief.ts+++ b/src/lib/agent/brief.ts@@ -372,12 +372,16 @@ export function validateBrief(const text = brief.requiredTexts.filter((t) => t.tier === 'mandatory').map((t) => {- // case-insensitive + whitespace-tolerant containment: catches- // the user's copy through case/wrap variations while still- // rejecting substitutions ("Creative Pulse" ≠ "Design Beyond- // Limits"). Hex colors are case-insensitive the same way.- const wanted = t.text.replace(/\s+/g, ' ').trim().toLowerCase()- const found = state.texts.some((s) => s.replace(/\s+/g, ' ').trim().toLowerCase().includes(wanted))+ // v0.32.1 (review P0): STRICT normalized equality — the required+ // text must appear as an element's own value, not as a substring+ // of a longer one. "Run Dal Lake 2026 — Special Offer" does NOT+ // satisfy "Run Dal Lake 2026": appended words, re-capitalized+ // letters, altered punctuation and collapsed spaces are all+ // rejections the gate bounces back to fix. (Whitespace is still+ // collapsed — line-wrap artifacts are benign, everything else+ // must match character for character.)+ const wanted = t.text.replace(/\s+/g, ' ').trim()+ const found = state.texts.some((s) => s.replace(/\s+/g, ' ').trim() === wanted)if (!found) unmet.push(`Required text missing or altered: "${t.text}"`)return { text: t.text, found }})@@ -506,11 +510,36 @@ export function mergeBriefs(stored: DesignBrief, live: DesignBrief): DesignBrief// normalizeStoredBrief turns either into a safe DesignBrief before// it can reach a prompt or a gate — pure, so both the (db-bound)// provenance module and the agent route import it from here.--const STORED_TEXTS_CAP = 24-const STORED_COLORS_CAP = 12-const STORED_FEATURES_CAP = 8-const STORED_TEXT_LEN_CAP = 200+//+// v0.32.1 (review P0): nothing is weakened silently anymore.+// Restrictions and notes SURVIVE persistence (a "no stock photos"+// the user demanded stays part of the contract), nothing is+// truncated mid-requirement, and overflow is REPORTED: the+// persistence path runs in 'reject' mode (over-limit briefs are+// refused instead of stored in weakened form) while read paths run+// 'clamp' (defensive bounds on untrusted client posts).++const STORED_TEXTS_CAP = 64+const STORED_COLORS_CAP = 32+const STORED_FEATURES_CAP = 16+const STORED_TEXT_LEN_CAP = 400+const STORED_RESTRICTIONS_CAP = 12+const STORED_RESTRICTION_LEN_CAP = 120+const STORED_NOTES_CAP = 8++/** How normalizeStoredBrief answers a brief that exceeds the safe+ * bounds: 'clamp' (read paths — defensive bounds on untrusted+ * posts) drops the over-limit entries; 'reject' (the persistence+ * path) refuses the whole brief — never store a weakened contract. */+export type StoredBriefOverflow = 'clamp' | 'reject'++export interface NormalizedStoredBrief {+ brief: DesignBrief+ /** 'clamp' mode: how many VALID requirements were dropped for+ * exceeding the safe bounds. 'reject' mode always returns null+ * instead, so 0 here means nothing was dropped. */+ dropped: number+}/*** Normalize an UNTRUSTED brief (a client post or the stored JSON) into@@ -524,23 +553,40 @@ const STORED_TEXT_LEN_CAP = 200* · tier is forced to 'mandatory' — provenance requirements are* exactly the things that must survive refinement*/-export function normalizeStoredBrief(value: unknown): DesignBrief | null {+export function normalizeStoredBrief(+ value: unknown,+ opts: { overflow?: StoredBriefOverflow } = {},+): NormalizedStoredBrief | null {+ const overflow = opts.overflow ?? 'clamp'if (!value || typeof value !== 'object') return nullconst raw = value as Partial<DesignBrief>const rawTexts: { text?: unknown }[] = Array.isArray(raw.requiredTexts)? (raw.requiredTexts as { text?: unknown }[]): []- const requiredTexts: DesignBrief['requiredTexts'] = rawTexts- .filter((t) => !!t && typeof t.text === 'string' && (t.text as string).trim().length > 0)+ const validTexts = rawTexts.filter(+ (t) => !!t && typeof t.text === 'string' && (t.text as string).trim().length > 0,+ )+ const textsOver =+ validTexts.filter((t) => (t.text as string).length > STORED_TEXT_LEN_CAP).length ++ Math.max(0, validTexts.length - STORED_TEXTS_CAP)+ if (overflow === 'reject' && textsOver > 0) return null+ const requiredTexts: DesignBrief['requiredTexts'] = validTexts+ .filter((t) => (t.text as string).length <= STORED_TEXT_LEN_CAP).slice(0, STORED_TEXTS_CAP)- .map((t) => ({ tier: 'mandatory' as const, text: (t.text as string).slice(0, STORED_TEXT_LEN_CAP) }))+ // never slice a requirement mid-string — a truncated contract+ // value is a different requirement+ .map((t) => ({ tier: 'mandatory' as const, text: (t.text as string).replace(/\s+/g, ' ').trim() }))const rawColors: { hex?: unknown }[] = Array.isArray(raw.requiredColors)? (raw.requiredColors as { hex?: unknown }[]): []- const requiredColors: DesignBrief['requiredColors'] = rawColors- .filter((c) => !!c && typeof c.hex === 'string' && /^#[0-9a-fA-F]{6}$/.test(c.hex as string))+ const validColors = rawColors.filter(+ (c) => !!c && typeof c.hex === 'string' && /^#[0-9a-fA-F]{6}$/.test(c.hex as string),+ )+ const colorsOver = Math.max(0, validColors.length - STORED_COLORS_CAP)+ if (overflow === 'reject' && colorsOver > 0) return null+ const requiredColors: DesignBrief['requiredColors'] = validColors.slice(0, STORED_COLORS_CAP).map((c) => ({ tier: 'mandatory' as const, hex: (c.hex as string).toLowerCase() }))@@ -548,8 +594,10 @@ export function normalizeStoredBrief(value: unknown): DesignBrief | null {const rawFeatures: { kind?: unknown; count?: unknown; label?: unknown }[] = Array.isArray(raw.requiredFeatures)? (raw.requiredFeatures as { kind?: unknown; count?: unknown; label?: unknown }[]): []- const requiredFeatures: RequiredFeature[] = rawFeatures- .filter((f) => !!f && KINDS.includes(f.kind as RequiredFeature['kind']))+ const validFeatures = rawFeatures.filter((f) => !!f && KINDS.includes(f.kind as RequiredFeature['kind']))+ const featuresOver = Math.max(0, validFeatures.length - STORED_FEATURES_CAP)+ if (overflow === 'reject' && featuresOver > 0) return null+ const requiredFeatures: RequiredFeature[] = validFeatures.slice(0, STORED_FEATURES_CAP).map((f) => ({tier: 'mandatory' as const,@@ -558,14 +606,30 @@ export function normalizeStoredBrief(value: unknown): DesignBrief | null {label: typeof f.label === 'string' ? f.label.slice(0, 160) : String(f.kind),}))+ // v0.32.1 (review P0): restrictions survive persistence — a "no+ // stock photos" the user demanded stays in the contract and rides+ // every refinement prompt. Notes too (free-text context).+ const cleanStrings = (list: unknown[], lenCap: number): string[] => {+ const valid = list.filter((s): s is string => typeof s === 'string' && s.trim().length > 0)+ return valid.map((s) => s.replace(/\s+/g, ' ').trim().slice(0, lenCap))+ }+ const restrictions = cleanStrings(+ Array.isArray(raw.restrictions) ? raw.restrictions : [],+ STORED_RESTRICTION_LEN_CAP,+ ).slice(0, STORED_RESTRICTIONS_CAP)+ const notes = cleanStrings(Array.isArray(raw.notes) ? raw.notes : [], STORED_TEXT_LEN_CAP).slice(0, STORED_NOTES_CAP)+if (!requiredTexts.length && !requiredColors.length && !requiredFeatures.length) return nullreturn {- requiredTexts,- requiredColors,- ...(requiredFeatures.length ? { requiredFeatures } : {}),- restrictions: [],- notes: [],- source: 'user',+ brief: {+ requiredTexts,+ requiredColors,+ ...(requiredFeatures.length ? { requiredFeatures } : {}),+ restrictions,+ notes,+ source: 'user',+ },+ dropped: overflow === 'clamp' ? textsOver + colorsOver + featuresOver : 0,}}diff --git a/src/lib/agent/context.ts b/src/lib/agent/context.tsindex 4595e12..161553d 100644--- a/src/lib/agent/context.ts+++ b/src/lib/agent/context.ts@@ -41,6 +41,10 @@ export interface AgentElementCtx {export interface AgentDesignCtx {name?: string+ /** v0.32.1: the open design's id — lets the route read the+ * AUTHORITATIVE stored brief from the database (server-verified+ * provenance) instead of trusting the client-posted copy. */+ designId?: string | nullwidth?: numberheight?: numbertemplateType?: stringdiff --git a/src/lib/agent/harness.test.ts b/src/lib/agent/harness.test.tsindex f99af7f..9433196 100644--- a/src/lib/agent/harness.test.ts+++ b/src/lib/agent/harness.test.ts@@ -467,10 +467,10 @@ describe('harness · brief contract', () => {expect(FORMAT_PRESETS[id], id).toBeTruthy()}})- it('validation passes when exact text + colors are present, fails with the unmet item named', () => {+ it('validation passes only on EXACT text, fails with the unmet item named', () => {const brief = extractBrief('"Design Beyond Limits" with #8B5CF6 on 1080x1080')const ok = validateBrief(brief, {- texts: ['DESIGN BEYOND LIMITS — really'],+ texts: ['Design Beyond Limits'],colors: ['#8b5cf6'],width: 1080,height: 1080,@@ -482,11 +482,22 @@ describe('harness · brief contract', () => {expect(bad.unmet.some((u) => u.includes('8B5CF6'))).toBe(true)expect(bad.unmet.some((u) => u.includes('1080'))).toBe(true)})- it('case-insensitive hex matching; whitespace-tolerant text matching', () => {+ it('case-insensitive hex matching; whitespace-tolerant but otherwise STRICT text matching', () => {const brief = extractBrief('"Hello World" #AABBCC')+ // whitespace collapse still tolerated (line-wrap artifacts)expect(- validateBrief(brief, { texts: [' hello\nworld '], colors: ['#AABBCC'], width: 1080, height: 1080 }).satisfied,+ validateBrief(brief, { texts: [' Hello\nWorld '], colors: ['#AABBCC'], width: 1080, height: 1080 }).satisfied,).toBe(true)+ // v0.32.1 (review P0): appended words no longer ride through as a+ // "satisfied" requirement — strict equality, not containment+ expect(+ validateBrief(brief, { texts: ['Hello World — Special Offer'], colors: ['#AABBCC'], width: 1080, height: 1080 }).satisfied,+ ).toBe(false)+ // ...and neither do case changes: character-for-character after+ // whitespace collapse+ expect(+ validateBrief(brief, { texts: ['hello world'], colors: ['#aabbcc'], width: 1080, height: 1080 }).satisfied,+ ).toBe(false)expect(validateBrief(brief, { texts: ['x'], colors: ['#aabbcc'], width: 1080, height: 1080 }).satisfied,).toBe(false)diff --git a/src/lib/design-agent/continuation.test.ts b/src/lib/design-agent/continuation.test.tsindex b1e753d..64f06a5 100644--- a/src/lib/design-agent/continuation.test.ts+++ b/src/lib/design-agent/continuation.test.ts@@ -1,5 +1,6 @@// ─────────────────────────────────────────────────────────────-// Unified Canvix AI — the continuation acceptance (v0.32).+// Unified Canvix AI — the continuation acceptance (v0.32, hardened+// v0.32.1 after the external review).//// THE milestone acceptance test, exactly as specified:// a user requests an entire design → Canvix creates and verifies@@ -14,6 +15,15 @@// applyDesignAction (the same validated, undoable executor user// edits ride), and the brief gate validates against the live store// state exactly the way the Assistant panel does.+//+// v0.32.1 additions (the review's asks, as tests):+// · strict normalized equality — appended words, case changes,+// punctuation edits and missing spaces are REJECTIONS+// · restrictions survive normalization ("no stock photos" persists)+// · over-limit briefs are refused in reject mode, counted in clamp+// mode — never silently weakened or truncated+// · reload hydration regression (the GET payload's brief, not the+// payload object, lands in the store)// ─────────────────────────────────────────────────────────────import { describe, it, expect } from 'vitest'@@ -114,6 +124,7 @@ function storeDesignContext(): AgentDesignCtx {})return {name: s.designName,+ designId: s.designId,width: s.width,height: s.height,pageCount: s.pages.length,@@ -212,20 +223,21 @@ async function refineWithAgent(const events: AgentEvent[] = []const { chat, calls } = scriptedChat(messages)const design = storeDesignContext()- const storedBrief = normalizeStoredBrief(design.aiBrief)+ const storedBrief = normalizeStoredBrief(design.aiBrief)?.brief ?? brieflet pending: DesignAction[] = []const result = await runAgentLoop({chat,design,mode: 'edit',- brief: storedBrief ?? brief,+ brief: storedBrief,emit: (e) => {events.push(e)if (e.type === 'action') pending = e.actions as DesignAction[]},// the REAL executor — proving the applied pages are editableawaitApply: async () => applyForReal(pending),- validateBriefOnClient: async () => validateAgainstStore(storedBrief ?? brief ?? { requiredTexts: [], requiredColors: [], restrictions: [], notes: [], source: 'user' }),+ validateBriefOnClient: async () =>+ validateAgainstStore(storedBrief ?? { requiredTexts: [], requiredColors: [], restrictions: [], notes: [], source: 'user' }),})return { result: result as Awaited<ReturnType<typeof runAgentLoop>>, events, calls }}@@ -284,40 +296,165 @@ describe('mergeBriefs: the continuation contract', () => {})})-describe('normalizeStoredBrief: provenance hygiene', () => {+describe('normalizeStoredBrief: provenance hygiene (v0.32.1 — nothing silently weakened)', () => {it('keeps texts/colors, forces mandatory, drops dimensions (the design owns geometry after apply)', () => {const brief = normalizeStoredBrief({requiredTexts: [{ tier: 'preference', text: 'Run Dal Lake 2026' }],requiredColors: [{ tier: 'preference', hex: '#1B3A6B' }],dimensions: { tier: 'mandatory', width: 1080, height: 1350 },- restrictions: ['nope'],- notes: ['x'],source: 'model-refined',})expect(brief).not.toBeNull()- expect(brief!.requiredTexts).toEqual([{ tier: 'mandatory', text: 'Run Dal Lake 2026' }])- expect(brief!.requiredColors).toEqual([{ tier: 'mandatory', hex: '#1b3a6b' }])- expect(brief!.dimensions).toBeUndefined()- expect(brief!.restrictions).toEqual([])+ expect(brief!.brief.requiredTexts).toEqual([{ tier: 'mandatory', text: 'Run Dal Lake 2026' }])+ expect(brief!.brief.requiredColors).toEqual([{ tier: 'mandatory', hex: '#1b3a6b' }])+ expect(brief!.brief.dimensions).toBeUndefined()})- it('caps a hostile payload and rejects junk', () => {+ it('restrictions and notes SURVIVE persistence (a "no stock photos" stays in the contract)', () => {+ const brief = normalizeStoredBrief({+ requiredTexts: [{ text: 'Run Dal Lake 2026' }],+ restrictions: [' no stock photos ', 'avoid cluttered layouts'],+ notes: ['night-sky feel'],+ })+ expect(brief!.brief.restrictions).toEqual(['no stock photos', 'avoid cluttered layouts'])+ expect(brief!.brief.notes).toEqual(['night-sky feel'])+ })++ it('clamp mode bounds a hostile payload and COUNTS what it dropped; junk is null', () => {const hostile = {requiredTexts: Array.from({ length: 100 }, (_, i) => ({ text: `t${i}` })),requiredColors: Array.from({ length: 50 }, () => ({ hex: '#123456' })),}const brief = normalizeStoredBrief(hostile)- expect(brief!.requiredTexts).toHaveLength(24)- expect(brief!.requiredColors).toHaveLength(12)+ // generous caps — a real pipeline brief never approaches them+ expect(brief!.brief.requiredTexts).toHaveLength(64)+ expect(brief!.brief.requiredColors).toHaveLength(32)+ expect(brief!.dropped).toBe((100 - 64) + (50 - 32))expect(normalizeStoredBrief({ requiredTexts: [{ text: ' ' }] })).toBeNull()expect(normalizeStoredBrief('junk')).toBeNull()expect(normalizeStoredBrief(null)).toBeNull()expect(normalizeStoredBrief({ requiredColors: [{ hex: '#12345' }] })).toBeNull()})++ it('reject mode REFUSES over-limit briefs instead of storing a weakened contract — never truncation', () => {+ const overCap = {+ requiredTexts: Array.from({ length: 65 }, (_, i) => ({ text: `t${i}` })),+ }+ expect(normalizeStoredBrief(overCap, { overflow: 'reject' })).toBeNull()+ // a text LONGER than the cap is dropped in clamp mode (a truncated+ // requirement is a DIFFERENT requirement) and refused in reject+ // mode — never sliced mid-string+ const longText = { requiredTexts: [{ text: 'x'.repeat(401) }] }+ expect(normalizeStoredBrief(longText)).toBeNull()+ expect(normalizeStoredBrief(longText, { overflow: 'reject' })).toBeNull()+ // within limits, reject mode stores exactly what was given+ const fine = { requiredTexts: [{ text: 'Run Dal Lake 2026' }], restrictions: ['no stock photos'] }+ const ok = normalizeStoredBrief(fine, { overflow: 'reject' })+ expect(ok!.brief.requiredTexts).toEqual([{ tier: 'mandatory', text: 'Run Dal Lake 2026' }])+ expect(ok!.brief.restrictions).toEqual(['no stock photos'])+ expect(ok!.dropped).toBe(0)+ })+})++// ═════════════════════════════════════════════════════════════+// 2. strict normalized equality (review P0 — the regressions asked+// for: appended words, capitalization, punctuation, spaces)+// ═════════════════════════════════════════════════════════════++describe('validateBrief: required texts are EXACT, not substrings', () => {+ const brief: DesignBrief = {+ requiredTexts: [{ tier: 'mandatory', text: 'Run Dal Lake 2026' }],+ requiredColors: [{ tier: 'mandatory', hex: '#1b3a6b' }],+ restrictions: [],+ notes: [],+ source: 'user',+ }+ const state = (texts: string[]) => ({ texts, colors: ['#1b3a6b'], width: 1080, height: 1350 })++ it('the exact string passes; whitespace wrap is tolerated', () => {+ expect(validateBrief(brief, state(['Run Dal Lake 2026'])).satisfied).toBe(true)+ expect(validateBrief(brief, state([' Run\nDal Lake 2026 '])).satisfied).toBe(true)+ })+ it('appended words do NOT satisfy the requirement (the review\u2019s example)', () => {+ expect(validateBrief(brief, state(['Run Dal Lake 2026 — Special Offer'])).satisfied).toBe(false)+ expect(validateBrief(brief, state(['Tonight: Run Dal Lake 2026'])).satisfied).toBe(false)+ })+ it('capitalization changes are rejections', () => {+ expect(validateBrief(brief, state(['RUN DAL LAKE 2026'])).satisfied).toBe(false)+ expect(validateBrief(brief, state(['run dal lake 2026'])).satisfied).toBe(false)+ })+ it('altered punctuation and missing spaces are rejections', () => {+ expect(validateBrief(brief, state(['Run Dal Lake 2026!'])).satisfied).toBe(false)+ expect(validateBrief(brief, state(['Run Dal Lake, 2026'])).satisfied).toBe(false)+ expect(validateBrief(brief, state(['RunDalLake 2026'])).satisfied).toBe(false)+ expect(validateBrief(brief, state(['Run Dal Lake2026'])).satisfied).toBe(false)+ })})// ═════════════════════════════════════════════════════════════-// 2. THE acceptance: create → verify → refine on one design+// 3. reload hydration + the pending-contract lifecycle (client side)+// ═════════════════════════════════════════════════════════════++describe('provenance hydration (the reload path)', () => {+ it('the GET payload\u2019s BRIEF lands in the store — not the payload object (v0.32 regression)', () => {+ const brief: DesignBrief = {+ requiredTexts: [{ tier: 'mandatory', text: 'Run Dal Lake 2026' }],+ requiredColors: [{ tier: 'mandatory', hex: '#1b3a6b' }],+ restrictions: ['no stock photos'],+ notes: [],+ source: 'user',+ }+ useEditorStore.getState().loadDesign({+ id: `design-hydrate-${Date.now()}`,+ name: 'Night Run Poster',+ width: 1080,+ height: 1350,+ pages: [{ id: 'p1', background: { type: 'solid', color: '#FFFFFF' }, elements: [] }],+ thumbnail: null,+ source: 'blank',+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ // exactly what GET /api/designs/[id] returns for an editor+ aiProvenance: { brief, outcome: 'passed', verified: true, verifiedAt: '2026-11-25T00:00:00.000Z' },+ })+ const s = useEditorStore.getState()+ // the hydration bug stored the whole PAYLOAD as the brief — the+ // posted aiBrief then normalized to nothing and reload silently+ // lost the contract+ expect(s.aiBrief).toEqual(brief)+ })++ it('a design without provenance hydrates to no brief; loadDesign clears pending', () => {+ useEditorStore.getState().setAIPendingProvenance({+ prompt: 'old prompt',+ outcome: 'passed',+ brief: {+ requiredTexts: [{ tier: 'mandatory', text: 'stale' }],+ requiredColors: [],+ restrictions: [],+ notes: [],+ source: 'user',+ },+ })+ useEditorStore.getState().loadDesign({+ id: `design-hydrate-plain-${Date.now()}`,+ name: 'Plain',+ width: 1080,+ height: 1080,+ pages: [{ id: 'p1', background: { type: 'solid', color: '#FFFFFF' }, elements: [] }],+ thumbnail: null,+ source: 'blank',+ createdAt: new Date().toISOString(),+ updatedAt: new Date().toISOString(),+ })+ const s = useEditorStore.getState()+ expect(s.aiBrief).toBeNull()+ expect(s.aiPendingProvenance).toBeNull()+ })+})++// ═════════════════════════════════════════════════════════════+// 4. THE acceptance: create → verify → refine on one design// ═════════════════════════════════════════════════════════════describe('Unified Canvix AI acceptance: create → verify → refine on ONE design', () => {@@ -369,7 +506,7 @@ describe('Unified Canvix AI acceptance: create → verify → refine on ONE desiexpect(after.locked).toBeFalsy()// the contract held: brief validation against the LIVE store- const storedBrief = normalizeStoredBrief(run.report.brief)!+ const storedBrief = normalizeStoredBrief(run.report.brief)!.briefconst v = validateAgainstStore(storedBrief)expect(v.satisfied).toBe(true)expect(v.unmet).toEqual([])@@ -386,7 +523,7 @@ describe('Unified Canvix AI acceptance: create → verify → refine on ONE desiconst run = await runDesignAgent({ prompt: PROMPT, model: scriptedPlanner() })expect(run.outcome).toBe('passed')seedStore(run.pages ?? [], run.report.brief)- const storedBrief = normalizeStoredBrief(run.report.brief)!+ const storedBrief = normalizeStoredBrief(run.report.brief)!.brief// sanity: the applied design satisfies its own contractexpect(validateAgainstStore(storedBrief).satisfied).toBe(true)@@ -421,4 +558,34 @@ describe('Unified Canvix AI acceptance: create → verify → refine on ONE desiconst finalEvent = events[events.length - 1]expect(finalEvent?.type).toBe('done')})++ it('appended words are rejected too — strict equality is what the gate enforces (review P0)', async () => {+ const run = await runDesignAgent({ prompt: PROMPT, model: scriptedPlanner() })+ expect(run.outcome).toBe('passed')+ seedStore(run.pages ?? [], run.report.brief)+ const storedBrief = normalizeStoredBrief(run.report.brief)!.brief++ const headlineId = textElementId(REQUIRED_TEXTS[0])+ const { calls, result } = await refineWithAgent(+ [+ // the "refinement" appends a promo line to the required+ // headline — a SUBSTRING match would let this ride through+ turn('update_elements', { ids: [headlineId], patch: { text: `${REQUIRED_TEXTS[0]} — Special Offer` } }, 'add a promo suffix'),+ done('Suffixed'),+ turn('update_elements', { ids: [headlineId], patch: { text: REQUIRED_TEXTS[0] } }, 'restore the exact required headline'),+ done('Restored verbatim'),+ ],+ storedBrief,+ )++ // the gate REJECTED the appended-words done: the unmet list named+ // the requirement+ const rejection = calls.find((c) => c.some((m) => m.role === 'user' && m.content.includes('NOT DONE')))+ expect(rejection).toBeDefined()+ expect(rejection!.find((m) => m.role === 'user' && m.content.includes('NOT DONE'))!.content).toContain(REQUIRED_TEXTS[0])++ const restored = useEditorStore.getState().pages[useEditorStore.getState().currentPage].elements.find((e) => e.id === headlineId) as TextElement+ expect(restored.text).toBe(REQUIRED_TEXTS[0])+ expect(result.verification).toContain('Brief contract validated')+ })})diff --git a/src/lib/design-provenance.ts b/src/lib/design-provenance.tsindex 33b2599..975458c 100644--- a/src/lib/design-provenance.ts+++ b/src/lib/design-provenance.ts@@ -1,5 +1,5 @@// ─────────────────────────────────────────────────────────────-// Design provenance (v0.32 — Unified Canvix AI).+// Design provenance (v0.32 — Unified Canvix AI; hardened v0.32.1).//// The brief contract an autonomous generation was verified against,// persisted ON the design it was applied to. When the user keeps@@ -9,54 +9,205 @@// while the user keeps editing — the create→verify→refine loop the// Unified Canvix AI milestone is accepted on.//+// v0.32.1 hardening (external review, 25 Nov 2026):+// · VERIFICATION, not claims — persistence rides the design save+// itself: the brief is validated SERVER-SIDE against the final+// saved pages and the row carries `verified`/`verifiedAt`+// (re-checked on every later save, so it stays bound to the+// current document state). The client-side PUT that accepted+// arbitrary briefs/outcomes is GONE.+// · PRIVACY — the original generation prompt never leaves this+// module for viewers: getDesignProvenance includes it only for+// editors/owners (link viewers can already see the design; the+// prompt can hold information that is not in the design).+// · NO SILENT WEAKENING — the save path normalizes in 'reject'+// mode: an over-limit brief is refused (reported to the caller),+// never stored truncated or capped.+//// Server-only: this module touches the database. The brief itself is-// CLIENT-SAFE data (it is typed in src/lib/agent/brief.ts and rides-// the design context), but reads and writes go through the API.+// CLIENT-SAFE data (typed in src/lib/agent/brief.ts), but reads and+// writes go through the API.// ─────────────────────────────────────────────────────────────import { db } from '@/lib/db'-import { normalizeStoredBrief, type DesignBrief } from '@/lib/agent/brief'+import { normalizeStoredBrief, validateBrief, type BriefValidationResult, type DesignBrief } from '@/lib/agent/brief'+import type { PageData, AnyElement, TextElement } from '@/lib/types'-/** What the design GET and the provenance GET return to the editor. */+/** What the design GET and the provenance GET return.+ * `prompt` is present ONLY when the caller may edit the design —+ * the original AI prompt is private to editors/owners. */export interface DesignProvenancePayload {- prompt: string+ prompt?: stringbrief: DesignBriefoutcome: string+ /** server-side verdict: does the SAVED document satisfy the stored+ * brief? Re-checked on every design save — proof, not a claim. */+ verified: boolean+ verifiedAt?: stringupdatedAt?: string}+/** Result of the save path — 'rejected' is explicit, never silent. */+export type SaveProvenanceResult =+ | { status: 'stored'; payload: DesignProvenancePayload }+ | { status: 'rejected'; reason: string }+const PROMPT_CAP = 2000+const OUTCOME_CAP = 32++/**+ * Pages → the validation state shape, server-side twin of the panel's+ * computeBriefValidation. Flattens groups, collects every text value,+ * every color (fills, strokes, solid backgrounds) and the element+ * shapes the composite-feature validator needs — across ALL pages+ * (the server answers "does the saved DOCUMENT satisfy the contract";+ * the agent's client gate answers "does the current PAGE").+ */+export function briefStateFromPages(pages: PageData[], width: number, height: number): Parameters<typeof validateBrief>[1] {+ const texts: string[] = []+ const colors: string[] = []+ const elements: { type: string; x?: number; y?: number; width?: number; height?: number; fill?: string; stroke?: string; text?: string }[] = []+ const pushColor = (c: unknown) => {+ if (typeof c === 'string' && c.trim()) colors.push(c)+ }+ const walk = (els: AnyElement[]) => {+ for (const el of els) {+ const base: { type: string; x?: number; y?: number; width?: number; height?: number; fill?: string; stroke?: string; text?: string } = {+ type: el.type,+ x: Math.round(el.x),+ y: Math.round(el.y),+ width: Math.round(el.width),+ height: Math.round(el.height),+ }+ if ('fill' in el) {+ pushColor((el as { fill?: unknown }).fill)+ if (typeof (el as { fill?: unknown }).fill === 'string') base.fill = (el as { fill: string }).fill+ }+ if ('stroke' in el) {+ pushColor((el as { stroke?: unknown }).stroke)+ if (typeof (el as { stroke?: unknown }).stroke === 'string') base.stroke = (el as { stroke: string }).stroke+ }+ if (el.type === 'text') {+ const t = el as TextElement+ texts.push(t.text)+ base.text = t.text+ if (typeof t.fill === 'string') pushColor(t.fill)+ }+ elements.push(base)+ if (el.type === 'group') walk(el.children)+ }+ }+ for (const page of pages) {+ walk(page.elements ?? [])+ if (page.background?.type === 'solid') pushColor(page.background.color)+ }+ return { texts, colors, width, height, elements }+}-/** Persist (upsert) the provenance for a design. Best-effort shape:- * returns the stored payload, or null when nothing usable remained- * after normalization (the caller then treats the design as having- * no stored contract). */+/** Validate a brief against a saved document. Pure. */+export function verifyBriefAgainstPages(+ brief: DesignBrief,+ pages: PageData[],+ width: number,+ height: number,+): BriefValidationResult {+ return validateBrief(brief, briefStateFromPages(pages, width, height))+}++/**+ * Persist (upsert) the provenance for a design, WITH the server-side+ * verdict computed against the final saved pages. 'reject' mode+ * normalization: an over-limit or empty brief is REFUSED (with the+ * reason) instead of stored in weakened form — the caller surfaces+ * that, the contract never silently shrinks.+ */export async function saveDesignProvenance(designId: string,input: { prompt?: string; brief?: unknown; outcome?: string },-): Promise<DesignProvenancePayload | null> {- const brief = normalizeStoredBrief(input.brief)- if (!brief) return null+ doc: { pages: PageData[]; width: number; height: number },+): Promise<SaveProvenanceResult> {+ const normalized = normalizeStoredBrief(input.brief, { overflow: 'reject' })+ if (!normalized) {+ return {+ status: 'rejected',+ reason: 'The provenance brief carried no usable requirements (texts, colors or features) or exceeded the safe limits — nothing was weakened to make it fit.',+ }+ }+ const brief = normalized.brief+ const verdict = verifyBriefAgainstPages(brief, doc.pages, doc.width, doc.height)+ const verified = verdict.satisfiedconst prompt = (input.prompt ?? '').slice(0, PROMPT_CAP)- const outcome = (input.outcome ?? 'passed').slice(0, 32)+ const outcome = (input.outcome ?? 'passed').slice(0, OUTCOME_CAP)+ const verifiedAt = verified ? new Date() : nullconst row = await db.designProvenance.upsert({where: { designId },- create: { designId, prompt, brief: brief as unknown as object, outcome },- update: { prompt, brief: brief as unknown as object, outcome },+ create: { designId, prompt, brief: brief as unknown as object, outcome, verified, verifiedAt },+ update: { prompt, brief: brief as unknown as object, outcome, verified, verifiedAt },})- return { prompt, brief, outcome, updatedAt: row.updatedAt.toISOString() }+ return {+ status: 'stored',+ payload: {+ prompt,+ brief,+ outcome,+ verified,+ ...(verifiedAt ? { verifiedAt: verifiedAt.toISOString() } : {}),+ updatedAt: row.updatedAt.toISOString(),+ },+ }}-/** Read the provenance for a design (normalized; null when absent). */-export async function getDesignProvenance(designId: string): Promise<DesignProvenancePayload | null> {+/**+ * The plain-save hook: re-validate the stored brief against the+ * CURRENTLY saved pages and keep the row's verdict true to the+ * document (flips verified both ways as edits drift or restore).+ * Cheap: one indexed read + one pure validation, a write only when+ * the verdict changed. Returns the payload (or null when the design+ * has no provenance).+ */+export async function revalidateDesignProvenance(+ designId: string,+ doc: { pages: PageData[]; width: number; height: number },+): Promise<DesignProvenancePayload | null> {+ const row = await db.designProvenance.findUnique({ where: { designId } })+ if (!row) return null+ const normalized = normalizeStoredBrief(row.brief)+ if (!normalized) return null+ const verdict = verifyBriefAgainstPages(normalized.brief, doc.pages, doc.width, doc.height)+ const verified = verdict.satisfied+ if (verified !== row.verified) {+ await db.designProvenance.update({+ where: { designId },+ data: { verified, verifiedAt: verified ? new Date() : null },+ })+ }+ return {+ brief: normalized.brief,+ outcome: row.outcome,+ verified,+ ...(verified ? { verifiedAt: (row.verifiedAt ?? new Date()).toISOString() } : {}),+ updatedAt: row.updatedAt.toISOString(),+ }+}++/** Read the provenance for a design (normalized; null when absent).+ * The prompt is included ONLY for editors/owners — pass+ * includePrompt: false for viewer-facing reads (design GET for a+ * foreign viewer, the agent route's contract read). */+export async function getDesignProvenance(+ designId: string,+ opts: { includePrompt?: boolean } = {},+): Promise<DesignProvenancePayload | null> {const row = await db.designProvenance.findUnique({ where: { designId } })if (!row) return null- const brief = normalizeStoredBrief(row.brief)- if (!brief) return null+ const normalized = normalizeStoredBrief(row.brief)+ if (!normalized) return nullreturn {- prompt: row.prompt,- brief,+ ...(opts.includePrompt === true ? { prompt: row.prompt } : {}),+ brief: normalized.brief,outcome: row.outcome,+ verified: row.verified,+ ...(row.verified && row.verifiedAt ? { verifiedAt: row.verifiedAt.toISOString() } : {}),updatedAt: row.updatedAt.toISOString(),}}diff --git a/src/lib/types.ts b/src/lib/types.tsindex fa66c34..450d9eb 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -615,13 +615,25 @@ export interface DesignRecord extends DesignSnapshot {/** v0.9: true when the design belongs to another account — the editor* switches to view-only (no saves; mutating APIs answer 403). */readOnly?: boolean- /** v0.32 (Unified Canvix AI): the stored brief contract — what an- * applied autonomous generation was verified against. Present when- * GET /api/designs/[id] found a provenance row; the editor keeps it- * in the store and the chat agent merges it into every refinement- * run on this design (continuation). Type-only import: no runtime- * dependency on the agent module. */- aiProvenance?: import('./agent/brief').DesignBrief | null+ /** v0.32 (Unified Canvix AI): the stored provenance payload — what an+ * applied autonomous generation was verified against, plus the+ * server-side verification state (re-checked on every design save).+ * Present when GET /api/designs/[id] found a provenance row; the+ * editor keeps the brief in the store and the chat agent merges it+ * into every refinement run on this design (continuation).+ * v0.32.1: `prompt` ships ONLY in editor/owner responses — it is+ * private to the caller who can edit (viewers get the shareable+ * contract without the original prompt). Type-only import: no+ * runtime dependency on the agent module. */+ aiProvenance?: {+ prompt?: string+ brief: import('./agent/brief').DesignBrief+ outcome?: string+ /** server-side verdict against the SAVED pages */+ verified?: boolean+ verifiedAt?: string+ updatedAt?: string+ } | null}export interface TemplateRecord extends DesignSnapshot {diff --git a/src/store/editor-store.ts b/src/store/editor-store.tsindex 080195f..13878b4 100644--- a/src/store/editor-store.ts+++ b/src/store/editor-store.ts@@ -158,6 +158,13 @@ interface EditorState {// runs on this design stay gated on the verified requirements.aiBrief: DesignBrief | nullsetAIBrief: (brief: DesignBrief | null) => void+ /** v0.32.1: the contract waiting to be persisted. Set at Apply;+ * the design save carries it to the server (PUT /api/designs/[id]+ * body.aiProvenance), where it is normalized in 'reject' mode and+ * verified against the saved pages; cleared once the save answers+ * (stored or rejected — a rejection is surfaced, never silent). */+ aiPendingProvenance: { prompt: string; outcome: string; brief: DesignBrief } | null+ setAIPendingProvenance: (pending: { prompt: string; outcome: string; brief: DesignBrief } | null) => void// lifecycleloadDesign: (d: DesignRecord) => void@@ -334,6 +341,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({// opens; set when a DesignAgent run is applied. The chat agent's// requests carry it so refinement runs stay gated on it.aiBrief: null,+ aiPendingProvenance: null,// v0.5: collaboration runtimecollaborators: [],@@ -372,8 +380,12 @@ export const useEditorStore = create<EditorState>((set, get) => ({baseUpdatedAt: d.updatedAt ?? null,offlineRestored: false,// v0.32: the stored brief contract rides the load — null for- // designs without AI provenance (behaviour unchanged)- aiBrief: d.aiProvenance ?? null,+ // designs without AI provenance (behaviour unchanged).+ // v0.32.1: hydrate from the PAYLOAD's brief (the GET returns+ // {prompt?, brief, verified…} — the old code stored the whole+ // payload as the brief, silently breaking reload continuation)+ aiBrief: d.aiProvenance?.brief ?? null,+ aiPendingProvenance: null,})// v0.10: seed the collab replay cursor from the server's current seq —// our freshly loaded document already contains every persisted edit,@@ -453,12 +465,16 @@ export const useEditorStore = create<EditorState>((set, get) => ({emit({ kind: 'design:rename', name: name.slice(0, 80) })},- // v0.32 (Unified Canvix AI): set/clear the design's stored brief- // contract. DesignAgent Apply sets it right after appending the- // pages (and persists it via /ai-provenance); loadDesign hydrates it- // from the design GET on open.+ // v0.32: set/clear the design's stored brief contract. DesignAgent+ // Apply sets it right after appending the pages (and persists it+ // via /ai-provenance); loadDesign hydrates it from the design GET+ // on open.setAIBrief: (brief) => set({ aiBrief: brief }),+ // v0.32.1: queue the contract for the next design save (Apply) /+ // clear it once the save answered (stored or rejected)+ setAIPendingProvenance: (pending) => set({ aiPendingProvenance: pending }),+pushHistory: () => {// v0.7: snapshots share structure — pages are never mutated in place,// so storing the reference is safe and keeps history O(1) per push.diff --git a/tests/e2e/unified-ai-provenance.spec.ts b/tests/e2e/unified-ai-provenance.spec.tsindex 091ef86..327df01 100644--- a/tests/e2e/unified-ai-provenance.spec.ts+++ b/tests/e2e/unified-ai-provenance.spec.ts@@ -2,37 +2,73 @@ import { test, expect, type Browser } from '@playwright/test'import { createHash } from 'node:crypto'import { Client } from 'pg'-// v0.32 (Unified Canvix AI) — design provenance, end to end.+// v0.32.1 (Unified Canvix AI hardening) — design provenance, end to+// end through the REAL flow the review asked for: the design save.//-// The stored brief contract of a design: what an applied autonomous-// generation was verified against, persisted so later natural-language-// refinement of the SAME design stays gated on it. Proven here through-// the real API and the real database (migration 0013 applied by-// db:setup, same as CI):-//-// 1. PUT /api/designs/[id]/ai-provenance stores a brief (normalized:-// tiers forced mandatory, hexes lowercased)-// 2. GET /api/designs/[id] (the editor's load path) carries it back-// as aiProvenance — this is what hydrates the editor store-// 3. GET /api/designs/[id]/ai-provenance returns it too-// 4. a brief with nothing usable is a 422 (honest rejection)-// 5. foreign designs follow the designs family: GET is link-view-// (200, null provenance — that viewer can already GET the design-// itself), PUT answers NOT_YOUR_DESIGN (403); a missing id is a-// flat 404 on both verbs (no existence oracle)-// 6. dimension-only briefs are rejected too (the design owns the-// geometry after apply — a stored size would fail every-// refinement on a legitimately resized design)+// 1. APPLY→SAVE: PUT /api/designs/[id] with the pages AND the+// pending aiProvenance payload persists the contract and+// VERIFIES it server-side against the saved pages (verified:+// true, verifiedAt bound to that save). Restrictions survive+// ("no stock photos" stays in the contract).+// 2. BOUND TO THE DOCUMENT: a later save whose pages append words+// to a required text (the review's P0 example — substring+// matching used to let this through) flips verified to FALSE;+// restoring the exact text flips it back. Proof, not a claim.+// 3. PRIVACY: a link VIEWER (no session) gets the shareable+// contract (brief + verification state) but NEVER the original+// generation prompt; writes are refused (NOT_YOUR_DESIGN 403,+// and the client-supplied provenance PUT is gone — 405).+// 4. NO SILENT WEAKENING: a junk or over-limit brief is REFUSED at+// save time with an explicit reason in the response — never+// stored truncated or capped.//// Needs a database — see playwright.config.ts. The fixture user +// session + designs are seeded straight into the database (same// pattern as api-keys.spec.ts, inside the register budget).-const USER = { id: 'u_e2e_prov_user', username: 'e2e_prov_user', token: 'e2e-prov-user-token' }-const OTHER = { id: 'u_e2e_prov_other', username: 'e2e_prov_other' } // owns the foreign design+const USER = { id: 'u_e2e_prov_user', username: 'e2e_prov_user', token: 'e2e-prov-user-token-v2' }const BASE = process.env.BASE_URL ?? 'http://localhost:3000'+const PROMPT = 'A poster for a night run — "Run Dal Lake 2026", night blues, 1080x1350'++const BRIEF = {+ requiredTexts: [+ { tier: 'preference', text: 'Run Dal Lake 2026' },+ { tier: 'preference', text: '12km · Dachigam Road · 26 Jan' },+ ],+ requiredColors: [{ tier: 'preference', hex: '#1B3A6B' }],+ restrictions: ['no stock photos'],+ notes: [],+}++/** pages that satisfy the brief exactly (strict equality) */+const pagesSatisfying = () => [+ {+ id: 'p1',+ background: { type: 'solid', color: '#FFFFFF' },+ elements: [+ { id: 't1', type: 'text', text: 'Run Dal Lake 2026', x: 80, y: 200, width: 900, height: 120, fontSize: 96, fontFamily: 'Inter', bold: true, fill: '#1B3A6B', align: 'center' },+ { id: 't2', type: 'text', text: '12km · Dachigam Road · 26 Jan', x: 80, y: 360, width: 900, height: 60, fontSize: 36, fontFamily: 'Inter', fill: '#1B3A6B', align: 'center' },+ { id: 'r1', type: 'rect', x: 0, y: 0, width: 1080, height: 120, fill: '#1B3A6B' },+ ],+ },+]++/** the review's P0 example: required text with words APPENDED — a+ * substring match would pass, strict equality must not */+const pagesWithAppendedWords = () => [+ {+ id: 'p1',+ background: { type: 'solid', color: '#FFFFFF' },+ elements: [+ { id: 't1', type: 'text', text: 'Run Dal Lake 2026 — Special Offer', x: 80, y: 200, width: 900, height: 120, fontSize: 96, fontFamily: 'Inter', bold: true, fill: '#1B3A6B', align: 'center' },+ { id: 't2', type: 'text', text: '12km · Dachigam Road · 26 Jan', x: 80, y: 360, width: 900, height: 60, fontSize: 36, fontFamily: 'Inter', fill: '#1B3A6B', align: 'center' },+ { id: 'r1', type: 'rect', x: 0, y: 0, width: 1080, height: 120, fill: '#1B3A6B' },+ ],+ },+]+function sessionId(token: string): string {return createHash('sha256').update(token).digest('hex')}@@ -45,30 +81,31 @@ test.beforeAll(async () => {client = new Client({ connectionString: process.env.DATABASE_URL })await client.connect()await client.query(`DELETE FROM "Session" WHERE "userId" = $1`, [USER.id])- await client.query(`DELETE FROM "User" WHERE "id" IN ($1, $2)`, [USER.id, OTHER.id])+ await client.query(`DELETE FROM "User" WHERE "id" = $1`, [USER.id])await client.query(- `INSERT INTO "User" ("id", "username", "passwordHash", "createdAt") VALUES ($1, $2, 'seed-no-login', now()), ($3, $4, 'seed-no-login', now())`,- [USER.id, USER.username, OTHER.id, OTHER.username]+ `INSERT INTO "User" ("id", "username", "passwordHash", "createdAt") VALUES ($1, $2, 'seed-no-login', now())`,+ [USER.id, USER.username])await client.query(`INSERT INTO "Session" ("id", "userId", "createdAt", "expiresAt") VALUES ($1, $2, now(), now() + interval '2 hours')`,[sessionId(USER.token), USER.id])- await client.query(`DELETE FROM "Design" WHERE "ownerId" IN ($1, $2)`, [USER.id, OTHER.id])- await client.query(- `INSERT INTO "Design" ("id", "name", "width", "height", "pages", "ownerId", "createdAt", "updatedAt")- VALUES ('d_e2e_prov_mine', 'Provenance mine', 1080, 1350, '[]'::jsonb, $1, now(), now()),- ('d_e2e_prov_other', 'Provenance foreign', 1080, 1350, '[]'::jsonb, $2, now(), now())`,- [USER.id, OTHER.id]- )+ await client.query(`DELETE FROM "Design" WHERE "ownerId" = $1`, [USER.id])+ for (const id of ['d_e2e_prov_mine', 'd_e2e_prov_two']) {+ await client.query(+ `INSERT INTO "Design" ("id", "name", "width", "height", "pages", "ownerId", "createdAt", "updatedAt")+ VALUES ($1, 'Provenance design', 1080, 1350, '[]'::jsonb, $2, now(), now())`,+ [id, USER.id]+ )+ }})test.afterAll(async () => {if (client) {// provenance rows cascade with their designs; clean the designs- await client.query(`DELETE FROM "Design" WHERE "ownerId" IN ($1, $2)`, [USER.id, OTHER.id])+ await client.query(`DELETE FROM "Design" WHERE "ownerId" = $1`, [USER.id])await client.query(`DELETE FROM "Session" WHERE "userId" = $1`, [USER.id])- await client.query(`DELETE FROM "User" WHERE "id" IN ($1, $2)`, [USER.id, OTHER.id])+ await client.query(`DELETE FROM "User" WHERE "id" = $1`, [USER.id])await client.end().catch(() => {})}})@@ -79,106 +116,183 @@ async function signedInContext(browser: Browser) {return ctx}-test.describe('design AI provenance (Unified Canvix AI)', () => {- test('PUT stores the normalized brief; the design GET carries it back to the editor', async ({ browser }) => {+type ApiResponse = { status(): number; json(): Promise<unknown> }+type ApiFetch = (url: string, opts?: Record<string, unknown>) => Promise<ApiResponse>++async function saveDesign(api: { fetch: ApiFetch }, designId: string, body: Record<string, unknown>): Promise<{ status: number; body: Record<string, unknown> }> {+ const res = await api.fetch(`${BASE}/api/designs/${designId}`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json', origin: BASE },+ data: body,+ })+ return { status: res.status(), body: (await res.json()) as Record<string, unknown> }+}++test.describe('design AI provenance — persisted and verified by the design save (v0.32.1)', () => {+ test('the apply→save flow stores the contract AND verifies it server-side', async ({ browser }) => {const ctx = await signedInContext(browser)const api = ctx.request- // 1. store a provenance brief (the DesignAgent Apply path)- const put = await api.fetch(`${BASE}/api/designs/d_e2e_prov_mine/ai-provenance`, {- method: 'PUT',- headers: { 'Content-Type': 'application/json', origin: BASE },- data: {- prompt: 'A poster for a night run',- outcome: 'passed',- brief: {- requiredTexts: [- { tier: 'preference', text: 'Run Dal Lake 2026' },- { tier: 'preference', text: '12km · Dachigam Road · 26 Jan' },- ],- requiredColors: [{ tier: 'preference', hex: '#1B3A6B' }],- dimensions: { tier: 'mandatory', width: 1080, height: 1350 },- },- },+ // the apply flow's next save carries pages + the pending contract+ const { status, body } = await saveDesign(api, 'd_e2e_prov_mine', {+ pages: pagesSatisfying(),+ aiProvenance: { prompt: PROMPT, outcome: 'passed', brief: BRIEF },})- expect(put.status()).toBe(200)- const stored = (await put.json()) as { provenance?: { brief?: { requiredTexts?: { tier?: string; text?: string }[]; requiredColors?: { hex?: string }[]; dimensions?: unknown } } }- // normalized: tiers forced mandatory, hex lowercased- expect(stored.provenance?.brief?.requiredTexts?.[0]).toEqual({ tier: 'mandatory', text: 'Run Dal Lake 2026' })- expect(stored.provenance?.brief?.requiredColors).toEqual([{ tier: 'mandatory', hex: '#1b3a6b' }])- expect(stored.provenance?.brief?.dimensions).toBeUndefined()-- // 2. the editor's load path carries it (this hydrates the store)+ expect(status).toBe(200)++ // stored, normalized (tiers forced mandatory) and VERIFIED against+ // the saved pages — with the restriction intact+ const stored = body.aiProvenance as {+ brief?: { requiredTexts?: { tier?: string; text?: string }[]; restrictions?: string[] }+ verified?: boolean+ verifiedAt?: string+ }+ expect(stored).toBeDefined()+ expect(stored.brief?.requiredTexts?.[0]).toEqual({ tier: 'mandatory', text: 'Run Dal Lake 2026' })+ expect(stored.brief?.restrictions).toEqual(['no stock photos'])+ expect(stored.verified).toBe(true)+ expect(typeof stored.verifiedAt).toBe('string')++ // the editor's load path: prompt + contract + verification stateconst got = await api.fetch(`${BASE}/api/designs/d_e2e_prov_mine`)expect(got.status()).toBe(200)- const design = (await got.json()) as { aiProvenance?: { brief?: { requiredTexts?: { text?: string }[] } } }+ const design = (await got.json()) as {+ aiProvenance?: { prompt?: string; brief?: { requiredTexts?: { text?: string }[] }; verified?: boolean }+ }+ expect(design.aiProvenance?.prompt).toBe(PROMPT)expect(design.aiProvenance?.brief?.requiredTexts?.map((t) => t.text)).toEqual(expect.arrayContaining(['Run Dal Lake 2026', '12km · Dachigam Road · 26 Jan']))+ expect(design.aiProvenance?.verified).toBe(true)- // 3. the dedicated GET returns it too+ // the dedicated GET agrees (the editor sees the prompt)const direct = await api.fetch(`${BASE}/api/designs/d_e2e_prov_mine/ai-provenance`)expect(direct.status()).toBe(200)- const directBody = (await direct.json()) as { provenance?: { outcome?: string } }- expect(directBody.provenance?.outcome).toBe('passed')+ const directBody = (await direct.json()) as { provenance?: { prompt?: string; verified?: boolean } }+ expect(directBody.provenance?.prompt).toBe(PROMPT)+ expect(directBody.provenance?.verified).toBe(true)await ctx.close()})- test('a brief with nothing usable is a 422, a dimension-only brief included', async ({ browser }) => {+ test('verification is bound to the saved document — appended words flip it false, the exact text flips it back', async ({ browser }) => {const ctx = await signedInContext(browser)const api = ctx.request- const junk = await api.fetch(`${BASE}/api/designs/d_e2e_prov_mine/ai-provenance`, {+ // a later save APPENDS words to the required headline (the+ // review's P0 example). Substring matching would call this+ // satisfied; the strict server-side gate must not.+ const appended = await saveDesign(api, 'd_e2e_prov_mine', { pages: pagesWithAppendedWords() })+ expect(appended.status).toBe(200)+ expect(appended.body.aiProvenanceVerified).toBe(false)++ // the GET shows the contract intact but the verdict false+ const drifted = (await (await api.fetch(`${BASE}/api/designs/d_e2e_prov_mine`)).json()) as {+ aiProvenance?: { brief?: { requiredTexts?: { text?: string }[] }; verified?: boolean }+ }+ expect(drifted.aiProvenance?.brief?.requiredTexts?.[0]?.text).toBe('Run Dal Lake 2026')+ expect(drifted.aiProvenance?.verified).toBe(false)++ // restoring the exact text flips the verdict back — the proof+ // stays bound to the CURRENT document, not a one-time claim+ const restored = await saveDesign(api, 'd_e2e_prov_mine', { pages: pagesSatisfying() })+ expect(restored.body.aiProvenanceVerified).toBe(true)++ await ctx.close()+ })++ test('privacy: a link VIEWER gets the shareable contract, never the prompt; writes are refused', async ({ browser }) => {+ // the owner stores a contract first (fresh design)+ const ctx = await signedInContext(browser)+ const api = ctx.request+ const stored = await saveDesign(api, 'd_e2e_prov_two', {+ pages: pagesSatisfying(),+ aiProvenance: { prompt: 'private generation prompt', outcome: 'passed', brief: BRIEF },+ })+ expect(stored.body.aiProvenance).toBeDefined()+ await ctx.close()++ // the link viewer: no session at all — the designs family grants+ // link-view, so they can read the design AND its shareable+ // contract, but the original prompt is private to editors+ const viewer = await browser.newContext()+ const vapi = viewer.request+ const got = await vapi.fetch(`${BASE}/api/designs/d_e2e_prov_two`)+ expect(got.status()).toBe(200)+ const design = (await got.json()) as { readOnly?: boolean; aiProvenance?: { prompt?: string; brief?: unknown; verified?: boolean } }+ expect(design.readOnly).toBe(true)+ expect(design.aiProvenance).toBeDefined()+ expect(design.aiProvenance?.brief).toBeDefined()+ expect(design.aiProvenance?.verified).toBe(true)+ expect('prompt' in (design.aiProvenance ?? {})).toBe(false)+ expect(JSON.stringify(design.aiProvenance)).not.toContain('private generation prompt')++ // the dedicated GET follows the same rule+ const direct = await vapi.fetch(`${BASE}/api/designs/d_e2e_prov_two/ai-provenance`)+ expect(direct.status()).toBe(200)+ const directBody = (await direct.json()) as { provenance?: { prompt?: string; brief?: unknown } }+ expect(directBody.provenance?.brief).toBeDefined()+ expect('prompt' in (directBody.provenance ?? {})).toBe(false)++ // writes are refused: the viewer cannot save the design (and so+ // cannot write provenance through it)…+ const foreignSave = await vapi.fetch(`${BASE}/api/designs/d_e2e_prov_two`, {method: 'PUT',headers: { 'Content-Type': 'application/json', origin: BASE },- data: { brief: { requiredTexts: [], requiredColors: [] } },+ data: { pages: pagesSatisfying() },})- expect(junk.status()).toBe(422)-- // dimensions alone never survive normalization — nothing checkable- // remains, so the PUT rejects instead of storing a no-op contract- const dimsOnly = await api.fetch(`${BASE}/api/designs/d_e2e_prov_mine/ai-provenance`, {+ expect(foreignSave.status()).toBe(403)+ // …and the client-supplied provenance PUT no longer exists+ const gone = await vapi.fetch(`${BASE}/api/designs/d_e2e_prov_two/ai-provenance`, {method: 'PUT',headers: { 'Content-Type': 'application/json', origin: BASE },- data: { brief: { dimensions: { tier: 'mandatory', width: 1080, height: 1350 } } },+ data: { brief: BRIEF },})- expect(dimsOnly.status()).toBe(422)+ expect(gone.status()).toBe(405)- await ctx.close()+ await viewer.close()})- test('foreign designs follow the designs family — viewable, never writable; a missing id is a flat 404', async ({ browser }) => {+ test('junk and over-limit briefs are REFUSED at save — never silently weakened', async ({ browser }) => {const ctx = await signedInContext(browser)const api = ctx.request- // GET: link-view semantics, same as GET /api/designs/[id] itself —- // that viewer can already read the whole design, so the (less- // sensitive) provenance rides the same rule: null when none stored- const got = await api.fetch(`${BASE}/api/designs/d_e2e_prov_other/ai-provenance`)- expect(got.status()).toBe(200)- expect(((await got.json()) as { provenance?: unknown }).provenance).toBeNull()+ // nothing usable: the design still saves; the refusal is explicit+ const junk = await saveDesign(api, 'd_e2e_prov_two', {+ pages: pagesSatisfying(),+ aiProvenance: { prompt: 'x', outcome: 'passed', brief: { requiredTexts: [], requiredColors: [] } },+ })+ expect(junk.status).toBe(200)+ expect(typeof junk.body.aiProvenanceRejected).toBe('string')+ expect(junk.body.aiProvenance).toBeUndefined()- // PUT: the family's NOT_YOUR_DESIGN — a foreign design is never- // writable, and the response says exactly that- const put = await api.fetch(`${BASE}/api/designs/d_e2e_prov_other/ai-provenance`, {- method: 'PUT',- headers: { 'Content-Type': 'application/json', origin: BASE },- data: { brief: { requiredTexts: [{ text: 'nope' }] } },+ // over-limit (more than the cap): refused rather than stored+ // with entries silently dropped+ const over = await saveDesign(api, 'd_e2e_prov_two', {+ pages: pagesSatisfying(),+ aiProvenance: {+ prompt: 'x',+ outcome: 'passed',+ brief: { requiredTexts: Array.from({ length: 80 }, (_, i) => ({ text: `t${i}` })) },+ },})- expect(put.status()).toBe(403)+ expect(over.status).toBe(200)+ expect(typeof over.body.aiProvenanceRejected).toBe('string')- // a design that does not exist is a flat 404 on both verbs — no- // existence oracle- const gotMissing = await api.fetch(`${BASE}/api/designs/d_e2e_prov_does_not_exist/ai-provenance`)- expect(gotMissing.status()).toBe(404)- const putMissing = await api.fetch(`${BASE}/api/designs/d_e2e_prov_does_not_exist/ai-provenance`, {+ await ctx.close()+ })++ test('a missing design id is a flat 404 on both verbs', async ({ browser }) => {+ const ctx = await signedInContext(browser)+ const api = ctx.request+ const got = await api.fetch(`${BASE}/api/designs/d_e2e_prov_missing/ai-provenance`)+ expect(got.status()).toBe(404)+ const put = await api.fetch(`${BASE}/api/designs/d_e2e_prov_missing`, {method: 'PUT',headers: { 'Content-Type': 'application/json', origin: BASE },- data: { brief: { requiredTexts: [{ text: 'nope' }] } },+ data: { pages: pagesSatisfying() },})- expect(putMissing.status()).toBe(404)-+ expect(put.status()).toBe(404)await ctx.close()})})diff --git a/tests/e2e/wave4-ai-powerup.spec.ts b/tests/e2e/wave4-ai-powerup.spec.tsindex 01b2128..4ce155f 100644--- a/tests/e2e/wave4-ai-powerup.spec.ts+++ b/tests/e2e/wave4-ai-powerup.spec.ts@@ -156,35 +156,13 @@ async function openApp(page: Page, appName: string) {await page.getByText(appName, { exact: true }).first().click()}-/** the mocked plan the /api/ai/plan route fulfills with */-const MOCK_PLAN = {- plan: {- name: 'Trattoria Menu',- summary: 'Rustic two-page menu with warm accents',- width: 1080,- height: 720,- pages: [- {- id: 'pp1',- title: 'Cover',- enabled: true,- background: { type: 'gradient', from: '#7A3B2E', to: '#D9A566', angle: 135 },- elements: [- { id: 'e1', type: 'text', enabled: true, text: 'Trattoria da Luca', x: 140, y: 240, width: 800, fontSize: 84, fontFamily: 'Playfair Display', bold: true, fill: '#FFF6EC', align: 'center' },- { id: 'e2', type: 'rect', enabled: true, x: 340, y: 420, width: 400, height: 8, fill: '#D9A566' },- ],- },- {- id: 'pp2',- title: 'Antipasti',- enabled: true,- background: { type: 'solid', color: '#FFF6EC' },- elements: [- { id: 'e3', type: 'text', enabled: true, text: 'Antipasti', x: 140, y: 120, width: 400, fontSize: 56, fontFamily: 'Playfair Display', bold: true, fill: '#7A3B2E', align: 'left' },- ],- },- ],- },+/** v0.32.1: the six AI apps consolidated into ONE "Canvix AI" app —+ * open it and switch to the named mode tab (Chat / Generate /+ * Write / Image / Theme). The tab contents are the original,+ * unchanged app components. */+async function openUnifiedAI(page: Page, tab: string) {+ await openApp(page, 'Canvix AI')+ await page.getByRole('tab', { name: tab, exact: true }).click()}const MOCK_THEME = {@@ -213,42 +191,11 @@ const MOCK_NOTES = {test.describe('Wave 4 — AI Power-Up', () => {test.setTimeout(180_000)- test('agentic plan: review gate lets you edit, toggle, then apply native pages', async ({ page }) => {- await register(page, 'plan')- const designId = await createDesign(page, 'w4 plan', [textEl({ text: 'Seed page' })])- await openEditor(page, designId)-- await page.route('**/api/ai/plan', (route) => route.fulfill({ json: MOCK_PLAN }))- await openApp(page, 'AI design plan')-- // the brief + generate- await page.getByLabel('Design brief').fill('Two-page trattoria menu, rustic and warm')- await page.getByRole('button', { name: 'Plan my design' }).click()-- // the review gate: both pages render as cards- await expect(page.getByText('Trattoria Menu', { exact: true })).toBeVisible({ timeout: 15_000 })- await expect(page.getByText('Cover', { exact: true })).toBeVisible()- await expect(page.getByText('Antipasti', { exact: true })).toBeVisible()-- // editable copy — rewrite the headline- const headline = page.locator('input[aria-label="Element text"]').first()- await headline.fill('Trattoria da Enzo')-- // toggle the second page OFF — the gate must skip it on apply- // (the page checkbox's aria-label is namespaced with "page")- await page.getByRole('button', { name: 'Disable page Antipasti' }).click()-- await page.getByRole('button', { name: /Apply \(1p/ }).click()-- // document truth: exactly one new page, with the EDITED headline- const applied = await waitForDoc(page, designId, (d) => d.pages.length === 2, 'the applied plan page')- expect(applied.pages).toHaveLength(2)- const newTexts = applied.pages[1].elements.filter((e) => e.type === 'text').map((e) => e.text)- expect(newTexts).toContain('Trattoria da Enzo')- expect(newTexts).not.toContain('Trattoria da Luca')- // the applied page carries the plan's gradient background- expect(applied.pages[1].elements.some((e) => e.type === 'rect')).toBe(true)- })+ // v0.32.1: the 'agentic plan' UI test is retired WITH its panel —+ // the AI design plan app was consolidated into the unified Canvix+ // AI app's Generate tab (the stronger DesignAgent engine). The+ // /api/ai/plan route remains available as an API; its review-gate+ // semantics live on in the Generate tab's flow.test('speaker notes: AI draft is reviewed, edited, then saved per page', async ({ page }) => {await register(page, 'notes')@@ -313,7 +260,7 @@ test.describe('Wave 4 — AI Power-Up', () => {await openEditor(page, designId)await page.route('**/api/ai/theme', (route) => route.fulfill({ json: MOCK_THEME }))- await openApp(page, 'AI theme')+ await openUnifiedAI(page, 'Theme')await page.getByLabel('Theme mood').fill('nordic calm, cool editorial')await page.getByRole('button', { name: 'Generate' }).click()