Skip to content

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.

feat(v0.32): Unified Canvix AI — create → verify → refine on one design

Ashiq Hussain Mirf42541676614
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3784ba2..0934b83 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,40 @@
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)
+
+> One engineering upgrade, four unifications — full write-up in
+> `docs/UNIFIED-AI-MILESTONE.md`, 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, flat 404 on foreign designs), 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).
+
+### Changed — the two agents share one foundation
+
+- **Shared provider resolution:** the agent vision path and the shared
+ verification route (`/api/ai/agent/vision`) now resolve the vision
+ slot USER-FIRST (BYOK), matching the text slot and the design-agent
+ route — 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 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).
+
## [0.31.0] — 2026-11-25
> **Version reconciliation, stated not papered over:** this is the first
diff --git a/ROADMAP.md b/ROADMAP.md
index 0c161df..7a2689c 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 |
+| **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) |
| **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.md
new file mode 100644
index 0000000..912acb3
--- /dev/null
+++ b/docs/UNIFIED-AI-MILESTONE.md
@@ -0,0 +1,129 @@
+# Unified Canvix AI — the create → verify → refine milestone (v0.32)
+
+**Date:** 25 November 2026 · **Base:** v0.31.0 (`5f39489`)
+**Scope:** one engineering upgrade, four unifications — shared provider
+resolution, shared rendering, shared validation, shared editing
+workflow — proven by a single acceptance test.
+
+## The acceptance test (as specified, then implemented)
+
+> A user requests an entire design. Canvix creates and verifies it.
+> The user continues refining that same design through natural-language
+> instructions — without losing required text, colors, editability or
+> context.
+
+Implemented as `src/lib/design-agent/continuation.test.ts` (7 tests, no
+network, deterministic): the autonomous pipeline runs with a scripted
+model seam, its compiled pages are applied to the REAL editor store
+(`appendPages`), and the refinement runs through the REAL chat agent
+loop whose `awaitApply` executes through `applyDesignAction` — the same
+validated, undoable executor user edits ride. The gate behavior is
+asserted both ways:
+
+- **happy path** — "make the headline bigger": the system prompt
+ carries the stored brief's exact requirements (context), the
+ executor really changes the applied element (editability), and
+ every required text and color is still present, validated against
+ the live store (no loss);
+- **enforcement** — a "refinement" that rewrites a required headline is
+ REJECTED by the done-gate in edit mode ("NOT DONE — brief validation
+ against the real canvas found unmet requirements"), bounces back with
+ the unmet list, and the run only finishes once the exact string is
+ restored. The contract is enforced, not hoped for.
+
+## What shipped
+
+### 1. Shared provider resolution (the BYOK vision asymmetry, closed)
+
+`getClientForSlotForUser` existed for the MCP rail but the two agent
+vision paths resolved the instance-only `getClientForSlot`. Both call
+sites — `/api/ai/agent/vision` (the shared verification endpoint both
+panels' post-apply critique lands on) and the agent route's in-run
+`critiqueRoute` — now resolve the session user first, matching how the
+text slot and the design-agent route already resolved. A signed-in user
+with their own vision provider critiques with their keys on every AI
+surface; anonymous requests are unchanged.
+
+### 2. Shared validation (the brief contract flows across systems)
+
+- `mergeBriefs` (`src/lib/agent/brief.ts`): the design's stored brief
+ and the freshly extracted one merge by UNION — requirements survive
+ refinement, new explicit requirements join the contract, the live
+ message's explicit dimensions win, same-kind composite features take
+ the newest count. A merge can only add or sharpen, never drop.
+- `normalizeStoredBrief` (same module, pure): every stored brief — from
+ the provenance JSON column or the client's context post — is
+ normalized before it can reach a prompt or a gate: tiers forced
+ mandatory, hexes lowercased, arrays capped (24 texts / 12 colors /
+ 8 features), dimensions dropped (the design owns its geometry after
+ fit-pages; a stored size would fail every legitimately resized
+ refinement).
+- The agent loop's done-gate now fires for **edit runs that carry a
+ brief** in addition to create/improve — that is precisely the
+ continuation case. The audit and vision rounds stay scoped to
+ create/improve (full builds); the brief gate is what protects
+ refinement.
+
+### 3. Design provenance (the context that persists)
+
+- `DesignProvenance` Prisma model (migration `0013_design_ai_provenance`,
+ unique per design, cascade delete): `brief` JSON, `prompt`,
+ `outcome`, timestamps.
+- `src/lib/design-provenance.ts` — `saveDesignProvenance` /
+ `getDesignProvenance` (server-only; normalization shared with the
+ agent route through the pure module).
+- `PUT|GET /api/designs/[id]/ai-provenance` — PUT needs edit rights
+ (404 absent, 403 foreign, same-origin, its own rate budget — never
+ the autosave path's); GET is link-open like the design itself.
+- `GET /api/designs/[id]` (the editor's load path) now returns
+ `aiProvenance`, which `loadDesign` hydrates into the editor store
+ (`aiBrief`). DesignAgentApp Apply sets the store brief AND persists
+ it (best-effort after the pages landed — a persistence hiccup never
+ rolls the apply back; the session brief still guards).
+
+### 4. Shared editing workflow (one document, two agents)
+
+After Apply, the design is ordinary editable state: the chat agent's
+tools, the `applyDesignAction` executor, undo, collaboration and
+autosave all operate on the same elements the pipeline compiled — and
+now the CONTRACT travels with them. The chat panel posts the stored
+brief in its design context (`AgentDesignCtx.aiBrief`); the route
+merges it into the run's brief; the client's `validate_brief` answers
+(the panel already validates whatever brief the run event carries, so
+the enforcement needed no new client-side gate code).
+
+## Evidence
+
+- Unit: 1,700 / 1,700 pass (1,693 prior + 7 new; no regressions).
+ New: `continuation.test.ts` (the acceptance, mergeBriefs,
+ normalizeStoredBrief). `tsc --noEmit` clean, eslint clean.
+- Live-DB e2e: `tests/e2e/unified-ai-provenance.spec.ts` — the
+ provenance PUT/GET round trip through the real API against real
+ Postgres, normalization asserted, junk/dimension-only briefs 422,
+ foreign designs a flat 404 (no existence oracle), the design GET
+ carrying `aiProvenance` back (the hydration path).
+
+## Decisions and disclosed limits
+
+- **Edit-mode gates:** the brief gate fires in edit mode when a brief
+ exists; the quality-audit and vision rounds do not (they are
+ full-build machinery; a per-keystroke refine should not pay for a
+ canvas re-critique). The `validate_brief` tool remains available to
+ the model in every mode.
+- **Provenance is one row per design:** a new applied generation
+ overwrites it — the contract describes the design's CURRENT
+ verified requirements, not its history (versions already keep
+ history).
+- **Unsaved designs:** a design without an id keeps the session brief
+ (the store) but skips persistence; saving later does not retro-store
+ it. The next applied generation on a saved design persists.
+- **Dimensions in provenance are dropped by design** — after
+ fit-pages the design's own canvas is the truth; resize is a
+ legitimate refinement, not a contract violation.
+
+## What this does NOT change
+
+The two model seams (chat loop, pipeline plan/critique), the honesty
+contracts, the review gates and the checks-outrank-critique hierarchy
+are untouched. This milestone wires the systems together around the
+document; it does not alter how either agent thinks.
diff --git a/prisma/migrations/0013_design_ai_provenance/migration.sql b/prisma/migrations/0013_design_ai_provenance/migration.sql
new file mode 100644
index 0000000..649b7b0
--- /dev/null
+++ b/prisma/migrations/0013_design_ai_provenance/migration.sql
@@ -0,0 +1,24 @@
+-- v0.32 (Unified Canvix AI): design provenance — the brief contract an
+-- autonomous generation was verified against, persisted ON the design
+-- it was applied to. Chat-agent refinements of the SAME design merge
+-- the stored brief into every run's contract (mergeBriefs), so
+-- required texts/colors cannot silently vanish during refinement.
+
+-- CreateTable
+CREATE TABLE "DesignProvenance" (
+ "id" TEXT NOT NULL,
+ "designId" TEXT NOT NULL,
+ "prompt" TEXT NOT NULL DEFAULT '',
+ "brief" JSONB NOT NULL DEFAULT '{}',
+ "outcome" TEXT NOT NULL DEFAULT 'passed',
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "DesignProvenance_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "DesignProvenance_designId_key" ON "DesignProvenance"("designId");
+
+-- AddForeignKey
+ALTER TABLE "DesignProvenance" ADD CONSTRAINT "DesignProvenance_designId_fkey" FOREIGN KEY ("designId") REFERENCES "Design"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index e2f39b7..68c8b74 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -142,14 +142,36 @@ model Design {
// soft delete (dashboard Trash) — null = live design
deletedAt DateTime?
versions DesignVersion[]
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ // v0.32 (Unified Canvix AI): the brief contract an autonomous
+ // generation was verified against, persisted on the applied design —
+ // chat-agent refinements of the SAME design merge it into their run
+ // brief so verified requirements survive refinement
+ provenance DesignProvenance? @relation("DesignProvenance")
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
@@index([ownerId])
@@index([anonKey])
@@index([folderId])
}
+// ── v0.32 (Unified Canvix AI): design provenance ─────────────
+// One row per design (unique). `brief` is the normalized DesignBrief
+// JSON (src/lib/agent/brief.ts) — the exact texts/colors/features the
+// autonomous run was verified against; `prompt` and `outcome` keep the
+// 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
+}
+
// ── v0.14 (D6): dashboard folders ───────────────────────────
// A named group of the caller's designs. Attribution mirrors Design/
// Media exactly: signed-in → ownerId, anonymous → anonKey (the
diff --git a/src/app/api/ai/agent/route.ts b/src/app/api/ai/agent/route.ts
index 253f233..cce01a1 100644
--- a/src/app/api/ai/agent/route.ts
+++ b/src/app/api/ai/agent/route.ts
@@ -14,9 +14,10 @@ import { heuristicMode, parseMode, ROUTER_SYSTEM, modeAllowsWrites, MODE_TOOL_RI
import { runAgentLoop, toolsForMode } from '@/lib/agent/loop'
import { auditDesign as runDesignAudit } from '@/lib/agent/audit'
import { selectSkills } from '@/lib/agent/skills'
-import { extractBrief, type DesignBrief } from '@/lib/agent/brief'
+import { extractBrief, mergeBriefs, normalizeStoredBrief, type DesignBrief } from '@/lib/agent/brief'
import { critiqueWithVision } from '@/lib/agent/vision'
-import { getClientForSlot } from '@/lib/ai/provider'
+import { getClientForSlotForUser } from '@/lib/ai/provider'
+import { getSessionUser } from '@/lib/auth/session'
export const runtime = 'nodejs'
export const maxDuration = 800
@@ -84,14 +85,20 @@ function newRunId(): string {
/** 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
- * caller then discloses, never pretends). */
+ * caller then discloses, never pretends).
+ * v0.32 (Unified Canvix AI): the vision slot resolves USER-FIRST
+ * (BYOK) — the same chain the text slot and the design-agent route
+ * use. A signed-in user with their own vision provider critiques
+ * with THEIR keys; anonymous requests resolve the instance chain
+ * exactly as before. */
async function critiqueRoute(
image: string,
brief: DesignBrief | null,
design: AgentDesignCtx,
+ userId: string | null,
): Promise<{ findings: { severity: 'P0' | 'P1' | 'P2' | 'P3'; issue: string; fix?: string }[]; note: string } | null> {
if (!image.startsWith('data:image/')) return null
- const vision = await getClientForSlot('vision')
+ const vision = await getClientForSlotForUser('vision', userId)
if (!vision) return null
// same structural cast the route's chat fn uses — the SDK's typed
// create() accepts our body shape at runtime
@@ -167,6 +174,15 @@ async function __canvix_post(req: NextRequest) {
// up; the body streams through untouched.
const wrapped = await withProvider('assistant', req, { limit: 20, windowSec: 60 }, async (ctx) => {
const design: AgentDesignCtx = body.design ?? {}
+ // v0.32: the session user for the user-first vision resolution
+ // (the text slot already resolves BYOK-first inside withProvider —
+ // the vision seam now matches it, see critiqueRoute)
+ let userId: string | null = null
+ try {
+ userId = (await getSessionUser(req))?.id ?? null
+ } catch {
+ /* session hiccup — the instance chain answers */
+ }
const history = (body.history ?? [])
.slice(-12)
.filter((m) => m && (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string')
@@ -232,10 +248,22 @@ async function __canvix_post(req: NextRequest) {
}
// ── 2. extract the brief contract + pre-select skills ─────
- const brief =
+ // v0.32 (Unified Canvix AI — continuation): a design with stored
+ // AI provenance (an applied autonomous generation) contributes its
+ // brief to EVERY run on that design. The stored contract merges
+ // with the freshly extracted one (union — requirements survive),
+ // 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)
+ const extracted =
mode === 'create' || mode === 'improve'
? extractBrief(message, design.width, design.height)
: null
+ const brief =
+ storedBrief && extracted
+ ? mergeBriefs(storedBrief, extracted)
+ : (storedBrief ?? extracted)
const skills = selectSkills(
message,
mode,
@@ -371,8 +399,9 @@ async function __canvix_post(req: NextRequest) {
}),
// v0.29.3: the grounded vision critique, BEFORE completion.
// Unconfigured vision slot → null → the loop discloses.
+ // v0.32: user-first BYOK resolution (see critiqueRoute).
critique: (image) =>
- critiqueRoute(image, brief, bridge.latestDesign ?? design).then((r) => r ?? null),
+ critiqueRoute(image, brief, bridge.latestDesign ?? design, userId).then((r) => r ?? null),
refreshedContext: () => bridge.latestDesign,
// v0.29: audit the freshest design snapshot the panel acked
// (v0.29.3: the brief rides along for strip detection)
diff --git a/src/app/api/ai/agent/vision/route.ts b/src/app/api/ai/agent/vision/route.ts
index 01af7d0..adde03c 100644
--- a/src/app/api/ai/agent/vision/route.ts
+++ b/src/app/api/ai/agent/vision/route.ts
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from 'next/server'
-import { getClientForSlot } from '@/lib/ai/provider'
+import { getClientForSlotForUser } from '@/lib/ai/provider'
import { withLogging } from '@/lib/observability'
+import { getSessionUser } from '@/lib/auth/session'
import { critiqueWithVision } from '@/lib/agent/vision'
export const runtime = 'nodejs'
@@ -43,7 +44,20 @@ async function __canvix_post(req: NextRequest) {
// the vision slot is a SEPARATE capability — resolve it directly
// (withProvider resolves the text slot). When unconfigured, answer
// honestly instead of falling back to a text model.
- const vision = await getClientForSlot('vision')
+ // v0.32 (Unified Canvix AI): the resolution is user-first BYOK — the
+ // SAME chain every other AI capability rides. A signed-in user with
+ // their own vision provider now critiques with THEIR keys (matching
+ // how the design-agent route resolves its vision seam); anonymous
+ // requests resolve the instance chain exactly as before. This route
+ // is the shared verification path for BOTH agents' post-apply
+ // critique (the chat panel and the DesignAgent panel both land here).
+ let vision: Awaited<ReturnType<typeof getClientForSlotForUser>> = null
+ try {
+ const user = await getSessionUser(req)
+ vision = await getClientForSlotForUser('vision', user?.id ?? null)
+ } catch {
+ vision = null
+ }
if (!vision) {
return NextResponse.json(
{
diff --git a/src/app/api/designs/[id]/ai-provenance/route.ts b/src/app/api/designs/[id]/ai-provenance/route.ts
new file mode 100644
index 0000000..c037e52
--- /dev/null
+++ b/src/app/api/designs/[id]/ai-provenance/route.ts
@@ -0,0 +1,77 @@
+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 { withLogging } from '@/lib/observability'
+import { saveDesignProvenance, getDesignProvenance } from '@/lib/design-provenance'
+
+export const runtime = 'nodejs'
+
+// ─────────────────────────────────────────────────────────────
+// /api/designs/[id]/ai-provenance (v0.32 — Unified Canvix AI).
+//
+// 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.
+//
+// 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.
+// ─────────────────────────────────────────────────────────────
+
+async function __canvix_get(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+ try {
+ const { id } = await params
+ const access = await resolveDesignAccess(req, id)
+ if (!access) return NextResponse.json({ error: 'Not found' }, { status: 404 })
+ const provenance = await getDesignProvenance(id)
+ return NextResponse.json({ provenance })
+ } catch (error) {
+ console.error('GET /api/designs/[id]/ai-provenance failed', error)
+ return NextResponse.json({ error: 'Failed to get provenance' }, { status: 500 })
+ }
+}
+
+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.ts
index 197e3c8..c62cff1 100644
--- a/src/app/api/designs/[id]/route.ts
+++ b/src/app/api/designs/[id]/route.ts
@@ -11,6 +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'
// Normalise incoming pages payload (accepts object or legacy JSON string)
// into a value suitable for the Postgres jsonb column.
@@ -43,11 +44,17 @@ async function __canvix_get(req: NextRequest, { params }: { params: Promise<{ id
const maxEvent = await db.designEvent
.aggregate({ where: { designId: id }, _max: { id: true } })
.catch(() => null)
+ // v0.32 (Unified Canvix AI): the stored brief contract (provenance)
+ // 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)
return NextResponse.json({
...design,
pages: design.pages ?? [],
readOnly: !access.canEdit,
seq: maxEvent ? Number(maxEvent._max.id ?? 0) : 0,
+ aiProvenance,
})
} catch (error) {
console.error('GET /api/designs/[id] failed', error)
diff --git a/src/components/editor/apps/AssistantApp.tsx b/src/components/editor/apps/AssistantApp.tsx
index 65e7b8f..351e25d 100644
--- a/src/components/editor/apps/AssistantApp.tsx
+++ b/src/components/editor/apps/AssistantApp.tsx
@@ -211,6 +211,11 @@ function buildDesignContext() {
currentPageIndex: s.currentPage,
selectedIds: s.selectedIds.slice(0, 20),
elements,
+ // v0.32 (Unified Canvix AI): the design's STORED brief contract —
+ // an applied autonomous generation's verified requirements. The
+ // route merges it into the run's brief so refinement of the SAME
+ // design cannot silently drop a required text or color.
+ aiBrief: s.aiBrief ?? null,
colorsInUse: [
...new Set(
texts
diff --git a/src/components/editor/apps/DesignAgentApp.tsx b/src/components/editor/apps/DesignAgentApp.tsx
index 7c97a8d..7fdc25c 100644
--- a/src/components/editor/apps/DesignAgentApp.tsx
+++ b/src/components/editor/apps/DesignAgentApp.tsx
@@ -158,14 +158,35 @@ export function DesignAgentApp({ onClose }: AppPanelProps) {
}
const from = result.format ?? { width, height }
const fit = fitPagesToCanvas(chosen, from, { width, height })
- useEditorStore.getState().appendPages(fit.pages)
+ const store = useEditorStore.getState()
+ store.appendPages(fit.pages)
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.
+ 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')
+ })
+ }
toast({
title: `${chosen.length} page${chosen.length > 1 ? 's' : ''} added`,
description:
- fit.scale !== 1
- ? `Rescaled from ${from.width}×${from.height} to fit the ${width}×${height} canvas — fully editable. Ctrl+Z removes them all.`
- : 'Fully editable elements. Ctrl+Z removes them all.',
+ (fit.scale !== 1
+ ? `Rescaled from ${from.width}×${from.height} to fit the ${width}×${height} canvas — fully editable. `
+ : 'Fully editable elements. ') +
+ (brief ? 'The brief now guards chat-agent refinements of this design. ' : '') +
+ 'Ctrl+Z removes them all.',
})
}
diff --git a/src/lib/agent/brief.ts b/src/lib/agent/brief.ts
index 73bb378..09dae6c 100644
--- a/src/lib/agent/brief.ts
+++ b/src/lib/agent/brief.ts
@@ -430,3 +430,142 @@ export function briefPromptSection(brief: DesignBrief): string {
parts.push('You are not done until validate_brief passes or every mandatory item is verifiably present.')
return parts.join('\n')
}
+
+// ── v0.32 (Unified Canvix AI): the continuation merge ────────
+// A design generated by the DesignAgent carries its brief as
+// PROVENANCE (persisted on the design record). When the user keeps
+// refining that same design through the chat agent, the stored brief
+// and the freshly extracted one merge into the run's contract, so a
+// refinement can never silently drop a requirement the original run
+// was verified against.
+
+/** Union key for a required text (case/whitespace-insensitive). */
+function briefTextKey(text: string): string {
+ return text.replace(/\s+/g, ' ').trim().toLowerCase()
+}
+
+/**
+ * Merge the design's STORED brief (provenance) with the LIVE-extracted
+ * one (this message). Pure and deterministic:
+ * · required texts/colors UNION — the stored contract survives
+ * refinement, and new explicit requirements join it
+ * · for composite features the LIVE entry of the same kind replaces
+ * the stored one — it carries the user's newest count/intent
+ * · the LIVE message's explicitly stated dimensions win (the user may
+ * be resizing on purpose); otherwise the stored dimensions carry
+ * The Phase 5 immutability rule holds: a merge can only ADD (or
+ * sharpen) requirements, never drop one.
+ */
+export function mergeBriefs(stored: DesignBrief, live: DesignBrief): DesignBrief {
+ const texts = [...stored.requiredTexts]
+ const seenText = new Set(texts.map((t) => briefTextKey(t.text)))
+ for (const t of live.requiredTexts) {
+ if (!seenText.has(briefTextKey(t.text))) {
+ seenText.add(briefTextKey(t.text))
+ texts.push(t)
+ }
+ }
+ const colors = [...stored.requiredColors]
+ const seenHex = new Set(colors.map((c) => c.hex.toLowerCase()))
+ for (const c of live.requiredColors) {
+ if (!seenHex.has(c.hex.toLowerCase())) {
+ seenHex.add(c.hex.toLowerCase())
+ colors.push(c)
+ }
+ }
+ const features = [...(stored.requiredFeatures ?? [])]
+ for (const f of live.requiredFeatures ?? []) {
+ const idx = features.findIndex((x) => x.kind === f.kind)
+ if (idx === -1) features.push(f)
+ else features[idx] = f
+ }
+ // the LIVE message's explicit dimensions outrank the stored ones —
+ // the user may legitimately resize during refinement; without an
+ // explicit size the stored contract keeps the canvas it was
+ // verified against
+ const dimensions =
+ live.dimensions && live.dimensions.tier === 'mandatory'
+ ? live.dimensions
+ : (stored.dimensions ?? live.dimensions)
+ return {
+ requiredTexts: texts,
+ requiredColors: colors,
+ ...(features.length ? { requiredFeatures: features } : {}),
+ dimensions,
+ format: live.format ?? stored.format,
+ designType: live.designType ?? stored.designType,
+ restrictions: [...new Set([...stored.restrictions, ...live.restrictions])],
+ notes: [...stored.notes, ...live.notes].slice(0, 12),
+ source: 'user',
+ }
+}
+
+// ── v0.32: stored-brief input hygiene ────────────────────────
+// The stored brief arrives from TWO untrusted directions: the
+// provenance JSON column and the client's design context post.
+// 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
+
+/**
+ * Normalize an UNTRUSTED brief (a client post or the stored JSON) into
+ * a safe DesignBrief, or null when it carries nothing usable.
+ *
+ * Deliberate omissions:
+ * · dimensions are DROPPED — fit-pages may have rescaled the applied
+ * design onto a different canvas, so the design's own geometry is
+ * the truth now; a stored canvas size would fail every refinement
+ * on a legitimately resized design
+ * · tier is forced to 'mandatory' — provenance requirements are
+ * exactly the things that must survive refinement
+ */
+export function normalizeStoredBrief(value: unknown): DesignBrief | null {
+ if (!value || typeof value !== 'object') return null
+ const 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)
+ .slice(0, STORED_TEXTS_CAP)
+ .map((t) => ({ tier: 'mandatory' as const, text: (t.text as string).slice(0, STORED_TEXT_LEN_CAP) }))
+
+ 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))
+ .slice(0, STORED_COLORS_CAP)
+ .map((c) => ({ tier: 'mandatory' as const, hex: (c.hex as string).toLowerCase() }))
+
+ const KINDS: RequiredFeature['kind'][] = ['editor-mockup', 'feature-cards', 'glassmorphism']
+ 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']))
+ .slice(0, STORED_FEATURES_CAP)
+ .map((f) => ({
+ tier: 'mandatory' as const,
+ kind: f.kind as RequiredFeature['kind'],
+ ...(typeof f.count === 'number' && f.count >= 1 ? { count: Math.min(Math.round(f.count), 8) } : {}),
+ label: typeof f.label === 'string' ? f.label.slice(0, 160) : String(f.kind),
+ }))
+
+ if (!requiredTexts.length && !requiredColors.length && !requiredFeatures.length) return null
+
+ return {
+ requiredTexts,
+ requiredColors,
+ ...(requiredFeatures.length ? { requiredFeatures } : {}),
+ restrictions: [],
+ notes: [],
+ source: 'user',
+ }
+}
diff --git a/src/lib/agent/context.ts b/src/lib/agent/context.ts
index 380cc99..4595e12 100644
--- a/src/lib/agent/context.ts
+++ b/src/lib/agent/context.ts
@@ -14,6 +14,8 @@
// server treats them as opaque-but-typed data.
// ─────────────────────────────────────────────────────────────
+import type { DesignBrief } from './brief'
+
export interface AgentElementCtx {
id: string
type: string
@@ -61,6 +63,13 @@ export interface AgentDesignCtx {
* omit it and the audit falls back to per-text backdrops only.
* v0.29.3: NEVER guessed — the audit uses only this real field. */
background?: string
+ /** v0.32 (Unified Canvix AI): the design's STORED brief contract —
+ * provenance persisted when an autonomous generation was applied to
+ * this design. The client sends it with every request so a
+ * refinement run (even in edit mode) is gated on the requirements
+ * the original run was verified against. Optional: designs without
+ * AI provenance behave exactly as before. */
+ aiBrief?: DesignBrief | null
}
/** Element summary line — compact but geometry-complete. */
diff --git a/src/lib/agent/loop.ts b/src/lib/agent/loop.ts
index f04aad2..068218d 100644
--- a/src/lib/agent/loop.ts
+++ b/src/lib/agent/loop.ts
@@ -159,7 +159,7 @@ export function loopSystemPrompt(deps: {
'3. Destructive tools (delete_elements, clear_page, delete_page on non-empty pages) need user confirmation — the system pauses and asks; do not repeat the call in the same turn.',
'4. Keep 6% margins from page edges. Use measure_text for real text widths before finalizing headings — never rely on the 0.6×fontSize estimate for tight fits. Avoid overlaps; fix_overlaps resolves accidental ones.',
'5. Prefer the BRAND KIT colors/fonts when one is given; the BRIEF always outranks it.',
- '6. When the goal is achieved, verify via get_page_state (once) and validate_brief (create/improve runs), then emit {"done":true,"summary":"…"}. Never claim work you did not do; never claim completion while validate_brief reports unmet items.',
+ '6. When the goal is achieved, verify via get_page_state (once) and validate_brief (create/improve runs, and edit runs whose design carries a stored brief), then emit {"done":true,"summary":"…"}. Never claim work you did not do; never claim completion while validate_brief reports unmet items.',
'7. Args must match each tool spec exactly. On an error observation, fix the args and retry — the error message tells you what to change.',
'8. Tools edit the CURRENT page only. To work on another page: goto_page {page: N}, then get_page_state — ids change with the page. add_page appends the LAST page.',
'9. In review/explain mode, ground every claim in the state you read. Report missing items as missing — never describe them as present.',
@@ -346,8 +346,12 @@ export async function runAgentLoop(deps: LoopDeps): Promise<LoopResult> {
if (turn.done) {
summary = String(turn.summary ?? '').slice(0, 800) || 'Done.'
// BRIEF GATE (Phase 5): create/improve runs must validate
- // against real client state before completion is accepted
- if ((mode === 'create' || mode === 'improve') && brief && deps.validateBriefOnClient && !briefValidated) {
+ // against real client state before completion is accepted.
+ // v0.32 (Unified Canvix AI): an EDIT run that carries a brief
+ // (the design's stored provenance merged with this message) is
+ // gated too — a refinement may not finish while a requirement
+ // the design was verified against has gone missing.
+ if ((mode === 'create' || mode === 'improve' || (mode === 'edit' && brief)) && brief && deps.validateBriefOnClient && !briefValidated) {
const v = await deps.validateBriefOnClient()
if (v && !v.satisfied) {
doneRejections += 1
diff --git a/src/lib/design-agent/continuation.test.ts b/src/lib/design-agent/continuation.test.ts
new file mode 100644
index 0000000..b1e753d
--- /dev/null
+++ b/src/lib/design-agent/continuation.test.ts
@@ -0,0 +1,424 @@
+// ─────────────────────────────────────────────────────────────
+// Unified Canvix AI — the continuation acceptance (v0.32).
+//
+// THE milestone acceptance test, exactly as specified:
+// a user requests an entire design → Canvix creates and verifies
+// it → the user continues refining that SAME design through
+// natural-language instructions — without losing required text,
+// colors, editability or context.
+//
+// All model seams are SCRIPTED (deterministic, no network, same
+// style as pipeline.test.ts and harness.test.ts), but the document
+// is REAL: the compiled pages are applied to the real editor store
+// (appendPages), refinements execute through the REAL
+// 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.
+// ─────────────────────────────────────────────────────────────
+
+import { describe, it, expect } from 'vitest'
+import { runDesignAgent, type DesignAgentRun } from './pipeline'
+import type { DesignAgentModel } from './model'
+import { runAgentLoop } from '@/lib/agent/loop'
+import { mergeBriefs, normalizeStoredBrief, validateBrief, type DesignBrief } from '@/lib/agent/brief'
+import { type AgentDesignCtx, type AgentElementCtx } from '@/lib/agent/context'
+import type { AgentEvent } from '@/lib/agent/protocol'
+import { applyDesignAction, type DesignAction } from '@/lib/design-actions'
+import { useEditorStore } from '@/store/editor-store'
+import type { PageData, TextElement, AnyElement } from '@/lib/types'
+
+// ── the prompt: an entire design, exact requirements ──────────
+
+const PROMPT = [
+ 'Create a poster for a night run.',
+ 'The poster must show these exact lines:',
+ '"Run Dal Lake 2026",',
+ '"12km · Dachigam Road · 26 Jan",',
+ '"Register at runwallah.example".',
+ 'Use the colors #1B3A6B and #E2604F somewhere.',
+ 'Size 1080x1350. Bold, energetic, night-sky feel.',
+].join(' ')
+
+const REQUIRED_TEXTS = ['Run Dal Lake 2026', '12km · Dachigam Road · 26 Jan', 'Register at runwallah.example']
+const REQUIRED_COLORS = ['#1b3a6b', '#e2604f']
+
+function specJson(): string {
+ return JSON.stringify({
+ version: 'v2',
+ name: 'scripted night-run poster',
+ format: { width: 1080, height: 1350 },
+ palette: { seeds: ['#1B3A6B', '#E2604F'], mood: 'bold' },
+ typography: { scale: 1.25 },
+ blocks: [
+ {
+ kind: 'hero',
+ weight: 4,
+ content: [
+ { role: 'headline', source: 'user-required', text: REQUIRED_TEXTS[0] },
+ { role: 'subline', source: 'user-required', text: REQUIRED_TEXTS[1] },
+ { role: 'cta', source: 'user-required', text: REQUIRED_TEXTS[2] },
+ ],
+ overlap: 'none',
+ },
+ ],
+ })
+}
+
+/** the scripted planner: one call, the passing spec. */
+const scriptedPlanner = (): DesignAgentModel => ({
+ plan: async () => specJson(),
+})
+
+// ── store helpers (mirror what the panels do) ─────────────────
+
+function seedStore(pages: PageData[], aiBrief: DesignBrief | null) {
+ useEditorStore.getState().loadDesign({
+ id: `design-continuation-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
+ name: 'Night Run Poster',
+ width: 1080,
+ height: 1350,
+ // one blank page — the agent's page is APPENDED (the panel flow)
+ pages: [{ id: 'page-blank', background: { type: 'solid', color: '#FFFFFF' }, elements: [] }],
+ thumbnail: null,
+ source: 'blank',
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ })
+ useEditorStore.getState().appendPages(pages)
+ if (aiBrief) useEditorStore.getState().setAIBrief(aiBrief)
+}
+
+/** the design context the Assistant panel would post for this store
+ * state (tiered, with the stored brief riding along). */
+function storeDesignContext(): AgentDesignCtx {
+ const s = useEditorStore.getState()
+ const page = s.pages[s.currentPage]
+ const elements: AgentElementCtx[] = (page?.elements ?? []).map((el: AnyElement): AgentElementCtx => {
+ const base: AgentElementCtx = {
+ id: el.id,
+ type: el.type,
+ x: Math.round(el.x),
+ y: Math.round(el.y),
+ width: Math.round(el.width),
+ height: Math.round(el.height),
+ }
+ if (el.type === 'text') {
+ const t = el as TextElement
+ base.text = t.text.slice(0, 80)
+ base.fill = t.fill
+ base.fontSize = Math.round(t.fontSize)
+ } else if ('fill' in el && typeof (el as { fill?: unknown }).fill === 'string') {
+ base.fill = (el as { fill: string }).fill
+ }
+ return base
+ })
+ return {
+ name: s.designName,
+ width: s.width,
+ height: s.height,
+ pageCount: s.pages.length,
+ currentPageIndex: s.currentPage,
+ elements,
+ aiBrief: s.aiBrief ?? null,
+ }
+}
+
+/** brief validation against the LIVE store — what the Assistant
+ * panel's computeBriefValidation does (flat elements included so
+ * composite features would validate too). */
+function validateAgainstStore(brief: DesignBrief): { satisfied: boolean; unmet: string[] } {
+ const s = useEditorStore.getState()
+ const page = s.pages[s.currentPage]
+ const els: AnyElement[] = []
+ const flatten = (list: AnyElement[]) => {
+ for (const el of list) {
+ els.push(el)
+ if (el.type === 'group') flatten(el.children)
+ }
+ }
+ flatten(page?.elements ?? [])
+ const texts = els.filter((e) => e.type === 'text').map((e) => (e as TextElement).text)
+ const colors = new Set<string>()
+ for (const el of els) {
+ if ('fill' in el && typeof (el as { fill?: unknown }).fill === 'string') {
+ colors.add(((el as { fill: string }).fill).toLowerCase())
+ }
+ if ('stroke' in el && typeof (el as { stroke?: unknown }).stroke === 'string') {
+ colors.add(((el as { stroke: string }).stroke).toLowerCase())
+ }
+ }
+ if (page?.background?.type === 'solid') colors.add(page.background.color.toLowerCase())
+ const result = validateBrief(brief, {
+ texts,
+ colors: [...colors],
+ width: s.width,
+ height: s.height,
+ elements: els.slice(0, 120).map((e) => ({
+ type: e.type,
+ x: Math.round(e.x),
+ y: Math.round(e.y),
+ width: Math.round(e.width),
+ height: Math.round(e.height),
+ ...('fill' in e && typeof (e as { fill?: unknown }).fill === 'string' ? { fill: (e as { fill: string }).fill } : {}),
+ ...('stroke' in e && typeof (e as { stroke?: unknown }).stroke === 'string' ? { stroke: (e as { stroke: string }).stroke } : {}),
+ ...(e.type === 'text' ? { text: (e as TextElement).text } : {}),
+ })),
+ })
+ return { satisfied: result.satisfied, unmet: result.unmet }
+}
+
+/** find a text element's id by its exact text (on the current page). */
+function textElementId(text: string): string {
+ const page = useEditorStore.getState().pages[useEditorStore.getState().currentPage]
+ const el = (page?.elements ?? []).find((e) => e.type === 'text' && (e as TextElement).text === text)
+ if (!el) throw new Error(`no text element with "${text}" on the applied page`)
+ return el.id
+}
+
+/** the panel's applyActions: run the emitted action batch through the
+ * REAL executor (same validated, undoable path user edits ride). */
+async function applyForReal(actions: DesignAction[]): Promise<{ ok: boolean; message?: string }> {
+ try {
+ for (const a of actions) {
+ if (a.type === '__validateBrief') continue
+ await applyDesignAction(a, undefined)
+ }
+ return { ok: true }
+ } catch (e) {
+ return { ok: false, message: e instanceof Error ? e.message : 'action failed' }
+ }
+}
+
+/** scripted chat: pops replies in order; records every request. */
+function scriptedChat(replies: string[]) {
+ const calls: { role: string; content: string }[][] = []
+ const chat = async (messages: { role: 'system' | 'user' | 'assistant'; content: string }[]) => {
+ calls.push(messages.map((m) => ({ role: m.role, content: m.content })))
+ return replies.shift() ?? JSON.stringify({ done: true, summary: '(script exhausted)' })
+ }
+ return { chat, calls }
+}
+const turn = (tool: string, args: Record<string, unknown> = {}, thought = 'step') =>
+ JSON.stringify({ thought, tool, args })
+const done = (summary: string) => JSON.stringify({ done: true, summary })
+
+/** run the refine loop exactly the route does it: the stored brief is
+ * normalized from the context, edit mode still gates on it, and the
+ * apply path executes for real. */
+async function refineWithAgent(
+ messages: string[],
+ brief: DesignBrief | null,
+): Promise<{ result: Awaited<ReturnType<typeof runAgentLoop>>; events: AgentEvent[]; calls: { role: string; content: string }[][] }> {
+ const events: AgentEvent[] = []
+ const { chat, calls } = scriptedChat(messages)
+ const design = storeDesignContext()
+ const storedBrief = normalizeStoredBrief(design.aiBrief)
+ let pending: DesignAction[] = []
+ const result = await runAgentLoop({
+ chat,
+ design,
+ mode: 'edit',
+ brief: storedBrief ?? brief,
+ emit: (e) => {
+ events.push(e)
+ if (e.type === 'action') pending = e.actions as DesignAction[]
+ },
+ // the REAL executor — proving the applied pages are editable
+ awaitApply: async () => applyForReal(pending),
+ validateBriefOnClient: async () => validateAgainstStore(storedBrief ?? brief ?? { requiredTexts: [], requiredColors: [], restrictions: [], notes: [], source: 'user' }),
+ })
+ return { result: result as Awaited<ReturnType<typeof runAgentLoop>>, events, calls }
+}
+
+// ═════════════════════════════════════════════════════════════
+// 1. the merge + hygiene units
+// ═════════════════════════════════════════════════════════════
+
+describe('mergeBriefs: the continuation contract', () => {
+ const stored: DesignBrief = {
+ requiredTexts: [
+ { tier: 'mandatory', text: 'Run Dal Lake 2026' },
+ { tier: 'mandatory', text: '12km · Dachigam Road · 26 Jan' },
+ ],
+ requiredColors: [{ tier: 'mandatory', hex: '#1b3a6b' }],
+ restrictions: ['no stock photos'],
+ notes: [],
+ source: 'user',
+ }
+ const live: DesignBrief = {
+ requiredTexts: [{ tier: 'mandatory', text: 'run dal lake 2026 ' }],
+ requiredColors: [{ tier: 'mandatory', hex: '#E2604F' }],
+ dimensions: { tier: 'mandatory', width: 1080, height: 1080 },
+ restrictions: [],
+ notes: [],
+ source: 'user',
+ }
+
+ it('unions requirements — the stored contract survives refinement, deduped', () => {
+ const merged = mergeBriefs(stored, live)
+ expect(merged.requiredTexts.map((t) => t.text)).toEqual([
+ 'Run Dal Lake 2026',
+ '12km · Dachigam Road · 26 Jan',
+ ])
+ expect(merged.requiredColors.map((c) => c.hex.toLowerCase())).toEqual(['#1b3a6b', '#e2604f'])
+ expect(merged.restrictions).toEqual(['no stock photos'])
+ })
+
+ it("the live message's explicit dimensions win; without them the stored ones carry", () => {
+ expect(mergeBriefs(stored, live).dimensions).toEqual({ tier: 'mandatory', width: 1080, height: 1080 })
+ expect(
+ mergeBriefs({ ...stored, dimensions: { tier: 'mandatory', width: 1080, height: 1350 } }, { ...live, dimensions: undefined }).dimensions,
+ ).toEqual({ tier: 'mandatory', width: 1080, height: 1350 })
+ })
+
+ it('a same-kind composite feature is replaced by the live entry (newest count/intent)', () => {
+ const withCards: DesignBrief = {
+ ...stored,
+ requiredFeatures: [{ tier: 'mandatory', kind: 'feature-cards', count: 3, label: '3 feature cards' }],
+ }
+ const merged = mergeBriefs(withCards, {
+ ...live,
+ requiredFeatures: [{ tier: 'mandatory', kind: 'feature-cards', count: 5, label: '5 feature cards' }],
+ })
+ expect(merged.requiredFeatures).toEqual([{ tier: 'mandatory', kind: 'feature-cards', count: 5, label: '5 feature cards' }])
+ })
+})
+
+describe('normalizeStoredBrief: provenance hygiene', () => {
+ 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([])
+ })
+
+ it('caps a hostile payload and rejects junk', () => {
+ 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)
+ expect(normalizeStoredBrief({ requiredTexts: [{ text: ' ' }] })).toBeNull()
+ expect(normalizeStoredBrief('junk')).toBeNull()
+ expect(normalizeStoredBrief(null)).toBeNull()
+ expect(normalizeStoredBrief({ requiredColors: [{ hex: '#12345' }] })).toBeNull()
+ })
+})
+
+// ═════════════════════════════════════════════════════════════
+// 2. THE acceptance: create → verify → refine on one design
+// ═════════════════════════════════════════════════════════════
+
+describe('Unified Canvix AI acceptance: create → verify → refine on ONE design', () => {
+ it('the full loop — no lost text, colors, editability or context', async () => {
+ // ── CREATE: one prompt in, the autonomous pipeline runs ────
+ const run: DesignAgentRun = await runDesignAgent({ prompt: PROMPT, model: scriptedPlanner() })
+
+ // ── VERIFY: the pipeline's own deterministic verdict ───────
+ expect(run.outcome).toBe('passed')
+ expect(run.checks?.passed).toBe(true)
+ expect(run.briefConformance).toEqual([])
+ expect(run.pages?.length).toBeGreaterThan(0)
+ const appliedTexts = (run.pages?.[0].elements ?? []).filter((e) => e.type === 'text').map((e) => (e as TextElement).text)
+ for (const t of REQUIRED_TEXTS) expect(appliedTexts).toContain(t)
+ expect(run.report.brief.requiredTexts.map((t) => t.text)).toEqual(expect.arrayContaining(REQUIRED_TEXTS))
+
+ // ── APPLY: the panel flow on the REAL store ───────────────
+ seedStore(run.pages ?? [], run.report.brief)
+ const s0 = useEditorStore.getState()
+ expect(s0.aiBrief).not.toBeNull()
+ // the applied page is current and carries every requirement
+ expect(s0.pages[s0.currentPage].elements.length).toBeGreaterThan(0)
+
+ // ── REFINE (happy path): natural-language restyling through
+ // the chat agent — the REAL executor applies the patch ─────
+ const headlineId = textElementId(REQUIRED_TEXTS[0])
+ const before = useEditorStore.getState().pages[useEditorStore.getState().currentPage].elements.find((e) => e.id === headlineId) as TextElement
+ const { result, events, calls } = await refineWithAgent(
+ [
+ turn('update_elements', { ids: [headlineId], patch: { fontSize: 96 } }, 'make the headline bigger'),
+ done('Headline enlarged, everything else kept'),
+ ],
+ null,
+ )
+
+ // context: the system prompt carried the stored brief's exact
+ // requirements — the refinement knew what it must not lose
+ const systemPrompt = calls[0]?.[0]?.content ?? ''
+ expect(systemPrompt).toContain('DESIGN BRIEF CONTRACT')
+ for (const t of REQUIRED_TEXTS) expect(systemPrompt).toContain(`"${t}"`)
+ expect(systemPrompt).toContain('#1B3A6B')
+
+ // editability: the SAME executor user edits ride actually changed
+ // the applied element (and it stayed a real, unlocked text element)
+ const after = useEditorStore.getState().pages[useEditorStore.getState().currentPage].elements.find((e) => e.id === headlineId) as TextElement
+ expect(after.fontSize).toBe(96)
+ expect(after.fontSize).not.toBe(before.fontSize)
+ expect(after.type).toBe('text')
+ expect(after.locked).toBeFalsy()
+
+ // the contract held: brief validation against the LIVE store
+ const storedBrief = normalizeStoredBrief(run.report.brief)!
+ const v = validateAgainstStore(storedBrief)
+ expect(v.satisfied).toBe(true)
+ expect(v.unmet).toEqual([])
+
+ // the loop's done-gate ran in EDIT mode (continuation) and the
+ // run reported the validated contract
+ expect(result.toolCalls).toBe(1)
+ expect(result.verification).toContain('Brief contract validated')
+ const finalEvent = events[events.length - 1]
+ expect(finalEvent?.type).toBe('done')
+ })
+
+ it('the edit-mode brief gate REJECTS a refinement that loses a required text (enforced, not hoped)', 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)!
+
+ // sanity: the applied design satisfies its own contract
+ expect(validateAgainstStore(storedBrief).satisfied).toBe(true)
+
+ const headlineId = textElementId(REQUIRED_TEXTS[0])
+ const { result, events, calls } = await refineWithAgent(
+ [
+ // the "refinement" rewrites the headline — losing the
+ // required text
+ turn('update_elements', { ids: [headlineId], patch: { text: 'Totally Different Headline' } }, 'retitle'),
+ done('Retitled'),
+ // the gate bounces it back with the unmet list; the model
+ // restores the exact required string
+ turn('update_elements', { ids: [headlineId], patch: { text: REQUIRED_TEXTS[0] } }, 'restore the required headline'),
+ done('Restored the required headline verbatim'),
+ ],
+ storedBrief,
+ )
+
+ // the done-gate fired in edit mode and REJECTED the first done
+ 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])
+
+ // the store ends with the requirement intact
+ const restored = useEditorStore.getState().pages[useEditorStore.getState().currentPage].elements.find((e) => e.id === headlineId) as TextElement
+ expect(restored.text).toBe(REQUIRED_TEXTS[0])
+ expect(validateAgainstStore(storedBrief).satisfied).toBe(true)
+
+ // and the run finished with the validated contract
+ expect(result.verification).toContain('Brief contract validated')
+ const finalEvent = events[events.length - 1]
+ expect(finalEvent?.type).toBe('done')
+ })
+})
diff --git a/src/lib/design-provenance.ts b/src/lib/design-provenance.ts
new file mode 100644
index 0000000..33b2599
--- /dev/null
+++ b/src/lib/design-provenance.ts
@@ -0,0 +1,62 @@
+// ─────────────────────────────────────────────────────────────
+// Design provenance (v0.32 — Unified Canvix AI).
+//
+// The brief contract an autonomous generation was verified against,
+// persisted ON the design it was applied to. When the user keeps
+// refining that same design through the chat agent, the stored brief
+// merges into every refinement run's contract (src/lib/agent/brief.ts
+// mergeBriefs), so required texts and colors cannot silently vanish
+// while the user keeps editing — the create→verify→refine loop the
+// Unified Canvix AI milestone is accepted on.
+//
+// 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.
+// ─────────────────────────────────────────────────────────────
+
+import { db } from '@/lib/db'
+import { normalizeStoredBrief, type DesignBrief } from '@/lib/agent/brief'
+
+/** What the design GET and the provenance GET return to the editor. */
+export interface DesignProvenancePayload {
+ prompt: string
+ brief: DesignBrief
+ outcome: string
+ updatedAt?: string
+}
+
+const PROMPT_CAP = 2000
+
+/** 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). */
+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
+ const prompt = (input.prompt ?? '').slice(0, PROMPT_CAP)
+ const outcome = (input.outcome ?? 'passed').slice(0, 32)
+ const 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 },
+ })
+ return { prompt, brief, outcome, updatedAt: row.updatedAt.toISOString() }
+}
+
+/** Read the provenance for a design (normalized; null when absent). */
+export async function getDesignProvenance(designId: string): Promise<DesignProvenancePayload | null> {
+ const row = await db.designProvenance.findUnique({ where: { designId } })
+ if (!row) return null
+ const brief = normalizeStoredBrief(row.brief)
+ if (!brief) return null
+ return {
+ prompt: row.prompt,
+ brief,
+ outcome: row.outcome,
+ updatedAt: row.updatedAt.toISOString(),
+ }
+}
diff --git a/src/lib/types.ts b/src/lib/types.ts
index c9eda62..fa66c34 100644
--- a/src/lib/types.ts
+++ b/src/lib/types.ts
@@ -613,8 +613,15 @@ export interface DesignRecord extends DesignSnapshot {
createdAt: string
updatedAt: string
/** v0.9: true when the design belongs to another account — the editor
- * switches to view-only (no saves; mutating APIs answer 403). */
+ * 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
}
export interface TemplateRecord extends DesignSnapshot {
diff --git a/src/store/editor-store.ts b/src/store/editor-store.ts
index 27dacba..080195f 100644
--- a/src/store/editor-store.ts
+++ b/src/store/editor-store.ts
@@ -14,6 +14,7 @@ import {
type PageData,
} from '@/lib/types'
import type { TemplateDef } from '@/lib/templates'
+import type { DesignBrief } from '@/lib/agent/brief'
import { magicRelayoutPages } from '@/lib/magic'
import {
clearPageAnimations,
@@ -151,6 +152,13 @@ interface EditorState {
// autosave is disabled and the editor shows a view-only banner
readOnly: boolean
+ // v0.32 (Unified Canvix AI): the design's stored brief contract (AI
+ // provenance) — hydrates from the design GET, set at DesignAgent
+ // Apply. Carried by the chat agent's design context so refinement
+ // runs on this design stay gated on the verified requirements.
+ aiBrief: DesignBrief | null
+ setAIBrief: (brief: DesignBrief | null) => void
+
// lifecycle
loadDesign: (d: DesignRecord) => void
rename: (name: string) => void
@@ -321,6 +329,12 @@ export const useEditorStore = create<EditorState>((set, get) => ({
drawSize: 6,
brand: DEFAULT_BRAND,
+ // v0.32 (Unified Canvix AI): the design's stored brief contract
+ // (AI provenance). Hydrated from the design GET when the editor
+ // opens; set when a DesignAgent run is applied. The chat agent's
+ // requests carry it so refinement runs stay gated on it.
+ aiBrief: null,
+
// v0.5: collaboration runtime
collaborators: [],
collabStatus: 'offline',
@@ -357,6 +371,9 @@ export const useEditorStore = create<EditorState>((set, get) => ({
readOnly: d.readOnly === true,
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,
})
// v0.10: seed the collab replay cursor from the server's current seq —
// our freshly loaded document already contains every persisted edit,
@@ -436,6 +453,12 @@ 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.
+ setAIBrief: (brief) => set({ aiBrief: brief }),
+
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.ts
new file mode 100644
index 0000000..2150239
--- /dev/null
+++ b/tests/e2e/unified-ai-provenance.spec.ts
@@ -0,0 +1,164 @@
+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.
+//
+// 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. a foreign design is a flat 404 on both GET and PUT — 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)
+//
+// 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 BASE = process.env.BASE_URL ?? 'http://localhost:3000'
+
+function sessionId(token: string): string {
+ return createHash('sha256').update(token).digest('hex')
+}
+
+let client: InstanceType<typeof Client>
+
+test.setTimeout(120_000)
+
+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(
+ `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]
+ )
+ 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]
+ )
+})
+
+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 "Session" WHERE "userId" = $1`, [USER.id])
+ await client.query(`DELETE FROM "User" WHERE "id" IN ($1, $2)`, [USER.id, OTHER.id])
+ await client.end().catch(() => {})
+ }
+})
+
+async function signedInContext(browser: Browser) {
+ const ctx = await browser.newContext()
+ await ctx.addCookies([{ name: 'canvix_session', value: USER.token, url: BASE }])
+ 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 }) => {
+ 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 },
+ },
+ },
+ })
+ 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)
+ const 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 }[] } } }
+ expect(design.aiProvenance?.brief?.requiredTexts?.map((t) => t.text)).toEqual(
+ expect.arrayContaining(['Run Dal Lake 2026', '12km · Dachigam Road · 26 Jan'])
+ )
+
+ // 3. the dedicated GET returns it too
+ 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')
+
+ await ctx.close()
+ })
+
+ test('a brief with nothing usable is a 422, a dimension-only brief included', 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`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', origin: BASE },
+ data: { brief: { requiredTexts: [], requiredColors: [] } },
+ })
+ 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`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', origin: BASE },
+ data: { brief: { dimensions: { tier: 'mandatory', width: 1080, height: 1350 } } },
+ })
+ expect(dimsOnly.status()).toBe(422)
+
+ await ctx.close()
+ })
+
+ test('a foreign design is a flat 404 on both GET and PUT — no existence oracle', async ({ browser }) => {
+ const ctx = await signedInContext(browser)
+ const api = ctx.request
+
+ const got = await api.fetch(`${BASE}/api/designs/d_e2e_prov_other/ai-provenance`)
+ expect(got.status()).toBe(404)
+ 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' }] } },
+ })
+ expect(put.status()).toBe(404)
+
+ await ctx.close()
+ })
+})