Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(content): plan the page in the editor's Brief tab and rebuild it from the sources kept (#1293)
Cihan450e4a1565bd
diff --git a/server/src/lib/content-brief.js b/server/src/lib/content-brief.jsnew file mode 100644index 000000000..db15b8533--- /dev/null+++ b/server/src/lib/content-brief.js@@ -0,0 +1,288 @@+import { NoObjectGeneratedError, generateObject } from 'ai';+import { z } from 'zod';+import supabaseAdmin from '../config/supabase.js';+import { resolveModel } from './ai-provider.js';+import { generationCostUsd } from './improve-cost.js';+import { getLanguageName } from './languages.js';+import { logger } from './logger.js';+import { enforceImproveQuota } from './plan-guard.js';++/**+ * The Content Editor's brief (CE-007, spec §10): Rebuild outline writes a+ * draft's goal, audience and outline from the sources the person kept in the+ * Sources tab (CE-008), each H2 answering one of the searches AI engines ran+ * (a fan-out) on a platform. It is metered from the organization's AI usage,+ * the monthly budget the Improve tab and the task writer draw from — not the+ * content brief quota, which stays with Opportunities' Generate Brief+ * (spec §3).+ */++/** The model, as the Improve tab's. */+export function contentBriefModelId() {+ return (+ process.env.IMPROVE_SUGGESTION_MODEL ||+ process.env.DEFAULT_SUGGESTION_MODEL ||+ 'google/gemini-3-flash-preview'+ );+}++/** How long the model may take: the dashboard waits for it. */+const CALL_TIMEOUT_MS = 60_000;++/** A string cut to `max` characters after trimming: a long one is shortened, not refused. */+const cut = (max) =>+ z+ .string()+ .max(10_000)+ .transform((s) => s.trim().slice(0, max));++/** A list of strings, each cut to `max`; the ones left empty are dropped. */+const cutList = (max, count) =>+ z+ .array(cut(max))+ .max(count)+ .transform((items) => items.filter(Boolean));++/** The length a rebuild asks for, in characters. */+export const BRIEF_LENGTH_MIN = 100;+export const BRIEF_LENGTH_MAX = 50_000;++/**+ * What the Sources tab keeps, as the web sends it. Text is cut to fit, and+ * the length is brought into range, rather than refusing the whole rebuild+ * over one long heading or a Length rule out of range.+ */+export const rebuildSources = z.object({+ promptIds: z.array(z.guid()).max(100),+ fanouts: z+ .array(z.object({ query: cut(300), platforms: cutList(60, 12) }))+ .max(40)+ .transform((items) => items.filter((f) => f.query)),+ pages: z.array(z.object({ url: cut(2048), kind: cut(30) })).max(30),+ queries: cutList(300, 20),+ /** The page's headings as written now, for a draft optimizing a page. */+ headings: cutList(300, 30),+ /** The length the page type's rules ask for, in characters. */+ length: z+ .number()+ .int()+ .transform((n) => Math.min(BRIEF_LENGTH_MAX, Math.max(BRIEF_LENGTH_MIN, n))),+});++/**+ * The limits the web reads a brief with (web/src/lib/content/brief.ts+ * draftBriefSchema): the model's output is cut to them, so a brief saved and+ * charged for is one the editor can show.+ */+export const BRIEF_LIMITS = {+ goal: 500,+ audience: 500,+ sections: 12,+ heading: 300,+ keyPoints: 8,+ keyPoint: 500,+ keywords: 15,+ keyword: 80,+};++// No counts or lengths enforced on the model: a miss would fail the whole+// call (charged all the same). They are asked for here and cut afterwards.+const outlineSchema = z.object({+ goal: z.string().describe('What the page must achieve for the brand, in one sentence.'),+ audience: z.string().describe('Who the page is for, in one sentence.'),+ outline: z+ .array(+ z.object({+ heading: z.string().describe('The H2, worded as the answer a reader looks for.'),+ keyPoints: z.array(z.string()).describe('What the section must cover: up to 5 points.'),+ fanout: z+ .string()+ .nullable()+ .describe('The AI search this H2 answers, copied exactly from the list, or null.'),+ platform: z+ .string()+ .nullable()+ .describe('The platform key that ran that search, from its list, or null.'),+ }),+ )+ .describe('3 to 10 sections.'),+ keywords: z.array(z.string()).describe('Up to 10 keywords.'),+});++const SYSTEM_PROMPT = `You are a senior content strategist for Answer Engine Optimization (AEO). You plan one web page so AI assistants (ChatGPT, Perplexity, Gemini, Copilot, Google's AI Overviews) cite it.++Rules:+- Plan an outline of H2 sections. Each H2 should answer one of the AI searches (fan-outs) listed, the most searched first, and name it exactly in "fanout" with one of its platform keys in "platform". An H2 that answers none has null for both.+- Cover the prompts listed: they are the questions the page must answer.+- Use only the facts given. Never invent numbers, prices, dates, names or claims; a key point that needs a fact says what to find out.+- When the page exists, keep its useful headings and improve them rather than starting over.+- Cited pages show what AI quotes today; plan to answer better than them, never to copy them.+- Write every field in the language asked for.`;++const norm = (text) => text.trim().replace(/\s+/g, ' ').toLowerCase();++/**+ * Builds the brief: reads the draft and its brand, keeps the prompts that are+ * the brand's, charges the AI usage budget, asks the model, and saves the+ * brief on the draft. Throws with `.status` 404 for a draft outside the+ * brand, 422 with no sources to build from, PlanLimitError once the budget+ * is spent.+ */+export async function rebuildDraftBrief({ draftId, brandId, sources }) {+ const { data: draft, error: draftError } = await supabaseAdmin+ .from('content_drafts')+ .select('id, brand_id, title, page_type, method, source_url')+ .eq('id', draftId)+ .maybeSingle();+ if (draftError) throw draftError;+ if (!draft || draft.brand_id !== brandId) {+ throw Object.assign(new Error('Draft not found'), { status: 404 });+ }++ const [brandRes, promptsRes] = await Promise.all([+ supabaseAdmin+ .from('brands')+ .select('name, industry, description, organization_id, language')+ .eq('id', brandId)+ .single(),+ sources.promptIds.length+ ? supabaseAdmin+ .from('prompts')+ .select('id, text, prompt_sets!inner(brand_id)')+ .in('id', sources.promptIds)+ .eq('prompt_sets.brand_id', brandId)+ : Promise.resolve({ data: [], error: null }),+ ]);+ if (brandRes.error) throw brandRes.error;+ if (promptsRes.error) throw promptsRes.error;+ const brand = brandRes.data;+ const prompts = (promptsRes.data ?? []).map((p) => p.text);++ if (!prompts.length && !sources.fanouts.length && !sources.queries.length) {+ throw Object.assign(new Error('No prompts, fan-outs or queries to build from'), {+ status: 422,+ code: 'no_sources',+ });+ }++ const modelId = contentBriefModelId();+ await enforceImproveQuota(brand.organization_id, modelId);++ let generated;+ try {+ generated = await generateObject({+ model: resolveModel(modelId),+ schema: outlineSchema,+ system: SYSTEM_PROMPT,+ prompt: buildBriefPrompt({ brand, draft, prompts, sources }),+ abortSignal: AbortSignal.timeout(CALL_TIMEOUT_MS),+ });+ } catch (err) {+ // An answer that didn't fit the schema was still paid for: charged as+ // Improve charges it, so retries don't run free.+ if (NoObjectGeneratedError.isInstance(err) && err.usage) {+ await recordUsage({+ organizationId: brand.organization_id,+ draftId,+ modelId,+ usage: err.usage,+ });+ }+ throw err;+ }+ const { object, usage } = generated;+ await recordUsage({ organizationId: brand.organization_id, draftId, modelId, usage });++ const brief = {+ goal: object.goal.trim().slice(0, BRIEF_LIMITS.goal),+ audience: object.audience.trim().slice(0, BRIEF_LIMITS.audience),+ outline: mapOutline(object.outline, sources.fanouts),+ keywords: [+ ...new Set(+ object.keywords.map((k) => k.trim().slice(0, BRIEF_LIMITS.keyword)).filter(Boolean),+ ),+ ].slice(0, BRIEF_LIMITS.keywords),+ origin: 'rebuild',+ builtAt: new Date().toISOString(),+ builtFrom: {+ prompts: prompts.length,+ fanouts: sources.fanouts.length,+ pages: sources.pages.length,+ queries: sources.queries.length,+ },+ };+ const { error: saveError } = await supabaseAdmin+ .from('content_drafts')+ .update({ brief })+ .eq('id', draftId);+ if (saveError) throw saveError;+ return brief;+}++/**+ * Keeps an H2's fan-out only when it is one the person kept, written as+ * listed, and its platform only when that search ran there. Cut to the+ * limits the web reads a brief with (BRIEF_LIMITS): a heading or key point+ * left empty goes, long text is shortened, and the lists are capped.+ */+export function mapOutline(outline, fanouts) {+ const byQuery = new Map(fanouts.map((f) => [norm(f.query), f]));+ return outline+ .map((section) => {+ const fanout = section.fanout ? byQuery.get(norm(section.fanout)) : undefined;+ const platform =+ fanout && fanout.platforms.includes(section.platform)+ ? section.platform+ : (fanout?.platforms[0] ?? null);+ return {+ heading: (section.heading ?? '').trim().slice(0, BRIEF_LIMITS.heading),+ keyPoints: (section.keyPoints ?? [])+ .map((p) => p.trim().slice(0, BRIEF_LIMITS.keyPoint))+ .filter(Boolean)+ .slice(0, BRIEF_LIMITS.keyPoints),+ fanout: fanout?.query ?? null,+ platform: fanout ? platform : null,+ };+ })+ .filter((section) => section.heading)+ .slice(0, BRIEF_LIMITS.sections);+}++/** What the model is told: the brand, the page, and the sources kept. */+export function buildBriefPrompt({ brand, draft, prompts, sources }) {+ const list = (items) => (items.length ? items.map((item) => `- ${item}`).join('\n') : '- none');+ return `Brand: ${brand?.name || 'Unknown'}+Industry: ${brand?.industry || 'Not specified'}+Description: ${brand?.description || 'N/A'}++Page: ${draft.title || 'Untitled'}+Page type: ${draft.page_type || 'not set'}+${draft.method === 'optimize' && draft.source_url ? `Existing page to improve: ${draft.source_url}` : 'A new page.'}+Length: about ${sources.length} characters.++Prompts the page must answer:+${list(prompts)}++AI searches (fan-outs) run while answering them, with the platform keys that ran each and the most searched first:+${list(sources.fanouts.map((f) => `"${f.query}" (${f.platforms.join(', ') || 'unknown'})`))}++Google searches people use (Search Console):+${list(sources.queries)}++Pages AI cites for these prompts today:+${list(sources.pages.map((p) => `${p.url} (${p.kind})`))}++${sources.headings.length ? `The page's headings now:\n${list(sources.headings)}\n\n` : ''}Write the brief in ${getLanguageName(brand?.language)}.`;+}++async function recordUsage({ organizationId, draftId, modelId, usage }) {+ const { error } = await supabaseAdmin.from('prompt_improve_usage').insert({+ organization_id: organizationId,+ content_draft_id: draftId,+ model: modelId,+ input_tokens: usage?.inputTokens ?? null,+ output_tokens: usage?.outputTokens ?? null,+ cost_usd: generationCostUsd(modelId, usage),+ });+ if (error) logger.error({ err: error, draftId }, '[content-brief] usage insert failed');+}diff --git a/server/src/lib/content-brief.test.js b/server/src/lib/content-brief.test.jsnew file mode 100644index 000000000..619a6e4b0--- /dev/null+++ b/server/src/lib/content-brief.test.js@@ -0,0 +1,329 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * Rebuild outline (Content Editor CE-007): the brief written from the+ * sources the person kept, metered from the AI usage budget.+ */++const BRAND = '33333333-3333-3333-3333-333333333333';+const DRAFT = '77777777-7777-7777-7777-777777777777';+const PROMPT = '55555555-5555-5555-5555-555555555555';++let rows;+let writes;+let filters;+const generateObject = vi.fn();+const enforceImproveQuota = vi.fn();++vi.mock('../config/supabase.js', () => ({+ default: {+ from: (table) => {+ const call = { table, filters: [] };+ filters.push(call);+ const result = () => ({ data: rows[table] ?? null, error: null });+ const chain = {+ select: () => chain,+ eq: (col, v) => (call.filters.push(['eq', col, v]), chain),+ in: (col, v) => (call.filters.push(['in', col, v]), chain),+ insert: async (value) => (writes.push({ table, op: 'insert', value }), { error: null }),+ update: (value) => (writes.push({ table, op: 'update', value }), chain),+ maybeSingle: async () => result(),+ single: async () => result(),+ then: (resolve) => resolve(result()),+ };+ return chain;+ },+ },+}));+class NoObjectGeneratedError extends Error {+ static isInstance(err) {+ return err instanceof NoObjectGeneratedError;+ }+}+vi.mock('ai', () => ({+ generateObject: (...args) => generateObject(...args),+ NoObjectGeneratedError,+}));+vi.mock('./ai-provider.js', () => ({ resolveModel: vi.fn((id) => `model:${id}`) }));+vi.mock('./plan-guard.js', async (importOriginal) => ({+ ...(await importOriginal()),+ enforceImproveQuota: (...args) => enforceImproveQuota(...args),+}));+vi.mock('./logger.js', () => ({ logger: { error: vi.fn() } }));++const { buildBriefPrompt, mapOutline, rebuildDraftBrief, rebuildSources } =+ await import('./content-brief.js');+const { PlanLimitError } = await import('./plan-guard.js');++const sources = (over = {}) => ({+ promptIds: [PROMPT],+ fanouts: [+ { query: 'Best espresso machine under 500', platforms: ['perplexity-web', 'copilot-web'] },+ { query: 'home espresso grinder', platforms: ['copilot-web'] },+ ],+ pages: [{ url: 'https://www.reddit.com/r/espresso/x', kind: 'forum' }],+ queries: ['espresso machine under 500'],+ headings: ['Choosing a machine'],+ length: 3000,+ ...over,+});++const outline = [+ {+ heading: 'The best espresso machines under $500',+ keyPoints: ['Price bands', ' '],+ fanout: 'best espresso machine UNDER 500',+ platform: 'copilot-web',+ },+ {+ heading: 'Grinders',+ keyPoints: ['Burr vs blade'],+ fanout: 'home espresso grinder',+ platform: 'chatgpt',+ },+ { heading: 'Care', keyPoints: [], fanout: 'made up search', platform: 'copilot-web' },+];++beforeEach(() => {+ writes = [];+ filters = [];+ rows = {+ content_drafts: {+ id: DRAFT,+ brand_id: BRAND,+ title: 'The home espresso guide',+ page_type: 'buying_guide',+ method: 'optimize',+ source_url: 'https://acme.example/guides/espresso',+ },+ brands: {+ name: 'Acme Coffee',+ industry: 'Food & Beverage',+ description: null,+ organization_id: 'o1',+ language: 'tr',+ },+ prompts: [{ id: PROMPT, text: 'Best espresso machines under $500?' }],+ };+ generateObject.mockReset().mockResolvedValue({+ object: {+ goal: ' Help buyers pick ',+ audience: 'Home baristas',+ outline,+ keywords: ['espresso', 'espresso', ' grinder '],+ },+ usage: { inputTokens: 1000, outputTokens: 500 },+ });+ enforceImproveQuota.mockReset().mockResolvedValue({ unlimited: true });+});++describe('rebuildDraftBrief', () => {+ it('writes the brief from the kept sources, charges AI usage, and saves it on the draft', async () => {+ const brief = await rebuildDraftBrief({ draftId: DRAFT, brandId: BRAND, sources: sources() });++ expect(enforceImproveQuota).toHaveBeenCalledWith('o1', 'google/gemini-3-flash-preview');+ const call = generateObject.mock.calls[0][0];+ expect(call.model).toBe('model:google/gemini-3-flash-preview');+ expect(call.prompt).toContain('- Best espresso machines under $500?');+ expect(call.prompt).toContain(+ '"Best espresso machine under 500" (perplexity-web, copilot-web)',+ );+ expect(call.prompt).toContain('Existing page to improve: https://acme.example/guides/espresso');+ expect(call.prompt).toContain('- Choosing a machine');+ expect(call.prompt).toContain('Write the brief in Turkish.');++ expect(brief).toMatchObject({+ goal: 'Help buyers pick',+ audience: 'Home baristas',+ keywords: ['espresso', 'grinder'],+ origin: 'rebuild',+ builtFrom: { prompts: 1, fanouts: 2, pages: 1, queries: 1 },+ });+ expect(brief.outline).toEqual([+ {+ heading: 'The best espresso machines under $500',+ keyPoints: ['Price bands'],+ fanout: 'Best espresso machine under 500',+ platform: 'copilot-web',+ },+ // A platform that didn't run the search: the one that did.+ {+ heading: 'Grinders',+ keyPoints: ['Burr vs blade'],+ fanout: 'home espresso grinder',+ platform: 'copilot-web',+ },+ // A search the person didn't keep: none.+ { heading: 'Care', keyPoints: [], fanout: null, platform: null },+ ]);++ expect(writes).toEqual([+ {+ table: 'prompt_improve_usage',+ op: 'insert',+ value: expect.objectContaining({+ organization_id: 'o1',+ content_draft_id: DRAFT,+ input_tokens: 1000,+ }),+ },+ { table: 'content_drafts', op: 'update', value: { brief } },+ ]);+ // Only the brand's prompts are read.+ expect(filters.find((f) => f.table === 'prompts').filters).toEqual([+ ['in', 'id', [PROMPT]],+ ['eq', 'prompt_sets.brand_id', BRAND],+ ]);+ });++ it('refuses a draft of another brand before any model call', async () => {+ rows.content_drafts = {+ ...rows.content_drafts,+ brand_id: '44444444-4444-4444-4444-444444444444',+ };+ await expect(+ rebuildDraftBrief({ draftId: DRAFT, brandId: BRAND, sources: sources() }),+ ).rejects.toMatchObject({+ status: 404,+ });+ rows.content_drafts = null;+ await expect(+ rebuildDraftBrief({ draftId: DRAFT, brandId: BRAND, sources: sources() }),+ ).rejects.toMatchObject({+ status: 404,+ });+ expect(generateObject).not.toHaveBeenCalled();+ });++ it('needs a prompt, a fan-out or a query to build from', async () => {+ rows.prompts = [];+ await expect(+ rebuildDraftBrief({+ draftId: DRAFT,+ brandId: BRAND,+ sources: sources({ fanouts: [], queries: [] }),+ }),+ ).rejects.toMatchObject({ status: 422, code: 'no_sources' });+ expect(enforceImproveQuota).not.toHaveBeenCalled();+ expect(generateObject).not.toHaveBeenCalled();+ });++ it('reads the prompts through their prompt set, so a prompt with no topic counts', async () => {+ await rebuildDraftBrief({ draftId: DRAFT, brandId: BRAND, sources: sources() });+ expect(filters.find((call) => call.table === 'prompts').filters).toContainEqual([+ 'eq',+ 'prompt_sets.brand_id',+ BRAND,+ ]);+ });++ it('cuts the model’s answer to the limits the editor reads a brief with', async () => {+ generateObject.mockResolvedValue({+ object: {+ goal: 'g'.repeat(600),+ audience: 'Home baristas',+ outline: [+ { heading: ' ', keyPoints: ['Lost'], fanout: null, platform: null },+ {+ heading: 'h'.repeat(400),+ keyPoints: Array.from({ length: 10 }, (_, i) => `${i}`.repeat(600)),+ fanout: null,+ platform: null,+ },+ ...Array.from({ length: 14 }, (_, i) => ({+ heading: `Section ${i}`,+ keyPoints: [],+ fanout: null,+ platform: null,+ })),+ ],+ keywords: Array.from({ length: 20 }, (_, i) => `${i} ${'k'.repeat(90)}`),+ },+ usage: { inputTokens: 1000, outputTokens: 500 },+ });+ const brief = await rebuildDraftBrief({ draftId: DRAFT, brandId: BRAND, sources: sources() });+ expect(brief.goal).toHaveLength(500);+ // The empty heading went; the rest is capped at 12 sections.+ expect(brief.outline).toHaveLength(12);+ expect(brief.outline[0].heading).toHaveLength(300);+ expect(brief.outline[0].keyPoints).toHaveLength(8);+ expect(brief.outline[0].keyPoints.every((p) => p.length === 500)).toBe(true);+ expect(brief.keywords).toHaveLength(15);+ expect(brief.keywords.every((k) => k.length <= 80)).toBe(true);+ });++ it('charges a call whose answer didn’t fit, then fails', async () => {+ generateObject.mockRejectedValue(+ Object.assign(new NoObjectGeneratedError('no object'), {+ usage: { inputTokens: 900, outputTokens: 300 },+ }),+ );+ await expect(+ rebuildDraftBrief({ draftId: DRAFT, brandId: BRAND, sources: sources() }),+ ).rejects.toBeInstanceOf(NoObjectGeneratedError);+ expect(writes).toEqual([+ expect.objectContaining({+ table: 'prompt_improve_usage',+ op: 'insert',+ value: expect.objectContaining({ input_tokens: 900, output_tokens: 300 }),+ }),+ ]);+ });++ it('stops when the AI usage budget is spent', async () => {+ enforceImproveQuota.mockRejectedValue(new PlanLimitError('used up', 429));+ await expect(+ rebuildDraftBrief({ draftId: DRAFT, brandId: BRAND, sources: sources() }),+ ).rejects.toBeInstanceOf(PlanLimitError);+ expect(generateObject).not.toHaveBeenCalled();+ expect(writes).toEqual([]);+ });+});++describe('rebuildSources', () => {+ it('cuts long text and drops empty items rather than refusing the rebuild', () => {+ const parsed = rebuildSources.parse(+ sources({+ headings: ['x'.repeat(400), ' ', 'Care'],+ queries: [' espresso ', ''],+ fanouts: [{ query: 'q'.repeat(350), platforms: ['p'.repeat(70)] }],+ }),+ );+ expect(parsed.headings).toEqual(['x'.repeat(300), 'Care']);+ expect(parsed.queries).toEqual(['espresso']);+ expect(parsed.fanouts[0].query).toHaveLength(300);+ expect(parsed.fanouts[0].platforms[0]).toHaveLength(60);+ });++ it('brings the length into the range a rebuild takes', () => {+ expect(rebuildSources.parse(sources({ length: 50 })).length).toBe(100);+ expect(rebuildSources.parse(sources({ length: 60_000 })).length).toBe(50_000);+ });+});++describe('the brief prompt', () => {+ it('says a new page is new, and lists none where a source is empty', () => {+ const prompt = buildBriefPrompt({+ brand: { name: 'Acme', language: 'en' },+ draft: { title: 'Grinders', page_type: null, method: 'create', source_url: null },+ prompts: [],+ sources: sources({ fanouts: [], pages: [], queries: ['burr grinder'], headings: [] }),+ });+ expect(prompt).toContain('A new page.');+ expect(prompt).toContain('Prompts the page must answer:\n- none');+ expect(prompt).toContain('- burr grinder');+ expect(prompt).not.toContain('headings now');+ expect(prompt).toContain('Write the brief in English.');+ });++ it('maps an outline with no fan-outs kept to none', () => {+ expect(mapOutline(outline.slice(0, 1), [])).toEqual([+ {+ heading: 'The best espresso machines under $500',+ keyPoints: ['Price bands'],+ fanout: null,+ platform: null,+ },+ ]);+ });+});diff --git a/server/src/routes/content-drafts.js b/server/src/routes/content-drafts.jsnew file mode 100644index 000000000..6d98f98a4--- /dev/null+++ b/server/src/routes/content-drafts.js@@ -0,0 +1,54 @@+import { Router } from 'express';+import { z } from 'zod';+import { assertBrandAccess } from '../lib/access.js';+import { rebuildDraftBrief, rebuildSources } from '../lib/content-brief.js';+import { PlanLimitError } from '../lib/plan-guard.js';++/**+ * Content Editor drafts (CE-007): Rebuild outline in the editor's Brief tab+ * writes the draft's brief from the sources the person kept.+ */++const router = Router();++/** The person-facing reason, by status, when the error names none. */+const ERROR_CODES = { 403: 'forbidden', 404: 'not_found', 422: 'invalid' };++const rebuildBody = z.object({+ // guid, not uuid: brand ids aren't all RFC 4122 versions (seeded ones).+ brandId: z.guid(),+ sources: rebuildSources,+});++/**+ * POST /api/content-drafts/:draftId/brief+ * Body: { brandId, sources: { promptIds, fanouts, pages, queries, headings, length } }+ */+router.post('/:draftId/brief', async (req, res) => {+ const draftId = z.guid().safeParse(req.params.draftId);+ const parsed = rebuildBody.safeParse(req.body ?? {});+ if (!draftId.success || !parsed.success) {+ return res.status(400).json({ error: 'Invalid request', code: 'invalid' });+ }+ const { brandId, sources } = parsed.data;+ try {+ await assertBrandAccess(brandId, req.user.id);+ const brief = await rebuildDraftBrief({ draftId: draftId.data, brandId, sources });+ return res.json({ brief });+ } catch (err) {+ if (err instanceof PlanLimitError) {+ // 402: no active subscription, not a spent budget.+ const code = err.statusCode === 402 ? 'no_subscription' : 'ai_budget';+ return res.status(err.statusCode).json({ error: err.message, code });+ }+ if (ERROR_CODES[err?.status]) {+ return res+ .status(err.status)+ .json({ error: err.message, code: err.code ?? ERROR_CODES[err.status] });+ }+ req.log.error({ err }, 'content draft brief rebuild error');+ return res.status(502).json({ error: 'The brief could not be written', code: 'failed' });+ }+});++export default router;diff --git a/server/src/routes/content-drafts.test.js b/server/src/routes/content-drafts.test.jsnew file mode 100644index 000000000..f74391d4c--- /dev/null+++ b/server/src/routes/content-drafts.test.js@@ -0,0 +1,110 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/** POST /api/content-drafts/:draftId/brief (CE-007): Rebuild outline. */++const BRAND = '33333333-3333-3333-3333-333333333333';+const DRAFT = '77777777-7777-7777-7777-777777777777';++const rebuildDraftBrief = vi.fn();+const assertBrandAccess = vi.fn();++// The route's modules read the Supabase client; CI has no credentials for it.+vi.mock('../config/supabase.js', () => ({ default: {} }));+vi.mock('../lib/content-brief.js', async (importOriginal) => ({+ ...(await importOriginal()),+ rebuildDraftBrief: (...args) => rebuildDraftBrief(...args),+}));+vi.mock('../lib/access.js', () => ({ assertBrandAccess: (...args) => assertBrandAccess(...args) }));++const { default: router } = await import('./content-drafts.js');+const { PlanLimitError } = await import('../lib/plan-guard.js');++let server;+let baseUrl;++beforeEach(async () => {+ rebuildDraftBrief.mockReset().mockResolvedValue({ goal: 'g', outline: [] });+ assertBrandAccess.mockReset().mockResolvedValue({});+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => {+ req.user = { id: 'u1' };+ req.log = { error: vi.fn() };+ next();+ });+ app.use('/api/content-drafts', router);+ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ baseUrl = `http://127.0.0.1:${server.address().port}/api/content-drafts`;+});++afterEach(() => new Promise((resolve) => server.close(resolve)));++const sources = {+ promptIds: [],+ fanouts: [{ query: 'espresso', platforms: ['copilot-web'] }],+ pages: [],+ queries: [],+ headings: [],+ length: 3000,+};++const rebuild = (body, draftId = DRAFT) =>+ fetch(`${baseUrl}/${draftId}/brief`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });++describe('POST /api/content-drafts/:draftId/brief', () => {+ it('rebuilds the brief for a member of the brand', async () => {+ const res = await rebuild({ brandId: BRAND, sources });+ expect(res.status).toBe(200);+ await expect(res.json()).resolves.toEqual({ brief: { goal: 'g', outline: [] } });+ expect(assertBrandAccess).toHaveBeenCalledWith(BRAND, 'u1');+ expect(rebuildDraftBrief).toHaveBeenCalledWith({ draftId: DRAFT, brandId: BRAND, sources });+ });++ it('refuses a malformed draft, brand or source list', async () => {+ for (const [body, draftId] of [+ [{ brandId: BRAND, sources }, 'd1'],+ [{ brandId: 'b1', sources }, DRAFT],+ [{ brandId: BRAND, sources: { ...sources, promptIds: ['p1'] } }, DRAFT],+ ]) {+ const res = await rebuild(body, draftId);+ expect(res.status).toBe(400);+ }+ expect(rebuildDraftBrief).not.toHaveBeenCalled();+ });++ it('says why it didn’t rebuild', async () => {+ assertBrandAccess.mockRejectedValueOnce(Object.assign(new Error('Forbidden'), { status: 403 }));+ let res = await rebuild({ brandId: BRAND, sources });+ expect(res.status).toBe(403);++ rebuildDraftBrief.mockRejectedValueOnce(new PlanLimitError('used up', 429));+ res = await rebuild({ brandId: BRAND, sources });+ expect(res.status).toBe(429);+ await expect(res.json()).resolves.toMatchObject({ code: 'ai_budget' });++ // No active subscription is its own case, not a spent budget.+ rebuildDraftBrief.mockRejectedValueOnce(new PlanLimitError('no subscription', 402));+ res = await rebuild({ brandId: BRAND, sources });+ expect(res.status).toBe(402);+ await expect(res.json()).resolves.toMatchObject({ code: 'no_subscription' });++ rebuildDraftBrief.mockRejectedValueOnce(+ Object.assign(new Error('none'), { status: 422, code: 'no_sources' }),+ );+ res = await rebuild({ brandId: BRAND, sources });+ expect(res.status).toBe(422);+ await expect(res.json()).resolves.toMatchObject({ code: 'no_sources' });++ rebuildDraftBrief.mockRejectedValueOnce(new Error('model down'));+ res = await rebuild({ brandId: BRAND, sources });+ expect(res.status).toBe(502);+ await expect(res.json()).resolves.toMatchObject({ code: 'failed' });+ });+});diff --git a/server/src/routes/index.js b/server/src/routes/index.jsindex 835f1d22b..36a0eb696 100644--- a/server/src/routes/index.js+++ b/server/src/routes/index.js@@ -4,6 +4,7 @@ import trackingRoutes from './tracking.js';import volumeRoutes from './volumes.js';import contentRoutes from './content.js';import contentPageRoutes from './content-pages.js';+import contentDraftRoutes from './content-drafts.js';import competitorRoutes from './competitors.js';import topicRoutes from './topics.js';import auditRoutes from './audits.js';@@ -21,6 +22,7 @@ router.use('/tracking', trackingRoutes);router.use('/volumes', volumeRoutes);router.use('/content', contentRoutes);router.use('/content-pages', contentPageRoutes);+router.use('/content-drafts', contentDraftRoutes);router.use('/competitors', competitorRoutes);router.use('/topics', topicRoutes);router.use('/audits', auditRoutes);diff --git a/supabase/migrations/00212_content_draft_brief.sql b/supabase/migrations/00212_content_draft_brief.sqlnew file mode 100644index 000000000..aab39f5e0--- /dev/null+++ b/supabase/migrations/00212_content_draft_brief.sql@@ -0,0 +1,32 @@+-- ============================================================================+-- 00212: a draft's brief, for the editor's Brief tab (Content Editor, CE-007)+-- ============================================================================+-- The Brief tab (Content Editor spec v2 §10) shows what the page should do:+-- the page type and target address, then its goal, audience and length, and+-- an outline whose H2s each answer one of the searches AI engines ran+-- (a fan-out) on a platform. Rebuild outline writes it from the draft's+-- sources (the Sources tab, 00211); Edit brief changes it by hand.+--+-- * content_drafts.brief: the brief as jsonb — {goal, audience, outline:+-- [{heading, keyPoints, fanout, platform}], keywords, origin, builtAt,+-- builtFrom}. Null until one is built; the tab then offers the brief of+-- the opportunity the draft started from, if it has one. A member edits+-- it like the body, so it isn't a server column.+-- * prompt_improve_usage.content_draft_id: a rebuild is metered from the+-- organization's AI usage, the monthly budget the Improve tab and the+-- Action Center's task writer draw from (00120, 00150), not the content+-- brief quota, which stays with Opportunities' Generate Brief (spec §3).+-- The row names the draft it wrote the brief for.++alter table public.content_drafts+ add column if not exists brief jsonb+ check (brief is null or (jsonb_typeof(brief) = 'object' and octet_length(brief::text) <= 65536));++comment on column public.content_drafts.brief is+ 'The draft''s brief (CE-007): goal, audience, outline (each H2 with the fan-out and platform it answers), keywords, and how it was made (origin, builtAt, builtFrom). Null until built.';++alter table public.prompt_improve_usage+ add column if not exists content_draft_id uuid references public.content_drafts(id) on delete set null;++comment on column public.prompt_improve_usage.content_draft_id is+ 'The Content Editor draft whose brief this generation rebuilt (CE-007). Null for an Improve tab or task-writer generation.';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 3b0c39823..49a11539d 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -29827,3 +29827,39 @@ grant execute on function public.content_draft_sources(uuid, integer) to authentcomment on function public.content_draft_sources(uuid, integer) is'Content Editor (CE-008): a draft''s sources over the last N days — its prompts and those citing its page, their AI fan-out searches, the pages their answers cited, the brand''s Search Console queries, and the brand and competitor domains. Security definer with an organization check through the draft''s brand.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00212_content_draft_brief.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00212: a draft's brief, for the editor's Brief tab (Content Editor, CE-007)+-- ============================================================================+-- The Brief tab (Content Editor spec v2 §10) shows what the page should do:+-- the page type and target address, then its goal, audience and length, and+-- an outline whose H2s each answer one of the searches AI engines ran+-- (a fan-out) on a platform. Rebuild outline writes it from the draft's+-- sources (the Sources tab, 00211); Edit brief changes it by hand.+--+-- * content_drafts.brief: the brief as jsonb — {goal, audience, outline:+-- [{heading, keyPoints, fanout, platform}], keywords, origin, builtAt,+-- builtFrom}. Null until one is built; the tab then offers the brief of+-- the opportunity the draft started from, if it has one. A member edits+-- it like the body, so it isn't a server column.+-- * prompt_improve_usage.content_draft_id: a rebuild is metered from the+-- organization's AI usage, the monthly budget the Improve tab and the+-- Action Center's task writer draw from (00120, 00150), not the content+-- brief quota, which stays with Opportunities' Generate Brief (spec §3).+-- The row names the draft it wrote the brief for.++alter table public.content_drafts+ add column if not exists brief jsonb+ check (brief is null or (jsonb_typeof(brief) = 'object' and octet_length(brief::text) <= 65536));++comment on column public.content_drafts.brief is+ 'The draft''s brief (CE-007): goal, audience, outline (each H2 with the fan-out and platform it answers), keywords, and how it was made (origin, builtAt, builtFrom). Null until built.';++alter table public.prompt_improve_usage+ add column if not exists content_draft_id uuid references public.content_drafts(id) on delete set null;++comment on column public.prompt_improve_usage.content_draft_id is+ 'The Content Editor draft whose brief this generation rebuilt (CE-007). Null for an Improve tab or task-writer generation.';+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 2f59d8893..929410a95 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3417,6 +3417,7 @@"hide": "Hide side panel","tabs": {"impact": "Impact",+ "brief": "Brief","sources": "Sources"}},@@ -3451,7 +3452,8 @@"cited": "Cited {count}×","lostBadge": "Lost","wasCitedOn": "Was cited on {platforms}",- "seeInCitations": "See in Citations"+ "seeInCitations": "See in Citations",+ "useLost": "{count, plural, one {Use the lost prompt in this draft} other {Use the # lost prompts in this draft}}"},"results": {"title": "Results from AI visits",@@ -3489,7 +3491,7 @@"retry": "Retry","summary": "{count, plural, one {Built from # source} other {Built from # sources}}","summaryParts": "{prompts, plural, one {# prompt} other {# prompts}} · {fanouts, plural, one {# fan-out} other {# fan-outs}} · {pages, plural, one {# cited page} other {# cited pages}} · {queries, plural, one {# Search Console query} other {# Search Console queries}}",- "hint": "Each source shows where the draft uses it. Uncheck one to leave it out of the brief and the agent's work.",+ "hint": "Each source shows where the draft uses it. Uncheck one to leave it out, then rebuild the brief.","empty": "No sources yet. Add a prompt, a page or a Search Console query.","toggleFailed": "Couldn't change the source. Try again.","include": "Use {name}",@@ -3558,6 +3560,52 @@"submit": "Add","added": "Source added","failed": "Couldn't add the source. Try again."+ },+ "rebuild": "Rebuild with selection"+ },+ "brief": {+ "loadError": "Couldn't load the brief.",+ "retry": "Retry",+ "pageType": "Page type",+ "targetUrl": "Target URL",+ "newPage": "A new page",+ "notSet": "Not set",+ "goal": "Goal",+ "audience": "Audience",+ "length": "Length",+ "lengthValue": "{count} characters · from the page type",+ "outline": "Outline",+ "answers": "Answers “{fanout}”",+ "keywords": "Keywords",+ "empty": "No outline yet. Rebuild outline writes one from the sources you keep, each H2 answering a search AI ran.",+ "fromOpportunity": "From the opportunity's brief. Rebuild outline maps each H2 to a fan-out.",+ "edited": "Edited by you.",+ "builtFrom": "{count, plural, one {Built from # source} other {Built from # sources}} · {date}",+ "rebuild": "Rebuild outline",+ "build": "Build brief",+ "edit": "Edit brief",+ "usage": "Rebuilding uses your workspace's AI usage.",+ "rebuilt": "{count, plural, one {Brief rebuilt from # source} other {Brief rebuilt from # sources}}",+ "rebuildErrors": {+ "ai_budget": "This month's AI usage is used up. It resets when your subscription renews.",+ "no_subscription": "Rebuilding needs an active subscription. Choose a plan in Settings › Billing.",+ "no_sources": "Keep at least one prompt, fan-out or Search Console query to build from.",+ "failed": "Couldn't rebuild the brief. Try again."+ },+ "editor": {+ "goal": "Goal",+ "audience": "Audience",+ "outline": "Outline",+ "heading": "Section {index} heading",+ "remove": "Remove section {index}",+ "points": "Section {index} key points",+ "pointsPlaceholder": "One key point per line",+ "addSection": "Add section",+ "keywords": "Keywords, separated by commas",+ "save": "Save brief",+ "cancel": "Cancel",+ "saved": "Brief saved",+ "failed": "Couldn't save the brief. Try again."}}},diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.test.tsxnew file mode 100644index 000000000..03dcc7d5a--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.test.tsx@@ -0,0 +1,204 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../../../messages/en.json';+import type { DraftBrief } from '@/lib/content/brief';+import { BriefTab, type BriefState } from './_brief-tab';++const saveDraftBrief = vi.fn();+vi.mock('@/lib/actions/content-drafts', () => ({+ saveDraftBrief: (...args: unknown[]) => saveDraftBrief(...args),+}));+const toast = vi.hoisted(() => Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }));+vi.mock('sonner', () => ({ toast }));++(+ globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT: boolean;+ }+).IS_REACT_ACT_ENVIRONMENT = true;++const brief: DraftBrief = {+ goal: 'Help home baristas pick a machine',+ audience: 'First-time espresso buyers',+ outline: [+ {+ heading: 'The best espresso machines under $500',+ keyPoints: ['Price bands', 'What to skip'],+ fanout: 'best espresso machine under 500',+ platform: 'perplexity-web',+ },+ { heading: 'Care and cleaning', keyPoints: [], fanout: null, platform: null },+ ],+ keywords: ['espresso machine', 'grinder'],+ origin: 'rebuild',+ builtAt: '2026-10-21T10:00:00Z',+ builtFrom: { prompts: 2, fanouts: 3, pages: 1, queries: 1 },+};++const onRebuild = vi.fn();+const onRetry = vi.fn();+const onSaved = vi.fn();++let container: HTMLDivElement;+let root: Root;++async function render(+ state: BriefState,+ extra: { pageType?: string | null; sourceUrl?: string | null } = {},+) {+ await act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <BriefTab+ draftId="d1"+ state={state}+ pageType={extra.pageType === undefined ? 'buying_guide' : extra.pageType}+ sourceUrl={+ extra.sourceUrl === undefined ? 'https://acme.example/guides/espresso' : extra.sourceUrl+ }+ rebuilding={false}+ onRebuild={onRebuild}+ onRetry={onRetry}+ onSaved={onSaved}+ />+ </NextIntlClientProvider>,+ );+ });+}++const button = (name: string) =>+ [...container.querySelectorAll('button')].find(+ (b) => b.textContent === name || b.getAttribute('aria-label') === name,+ )!;+const fields = () =>+ Object.fromEntries(+ [...container.querySelectorAll('dt')].map((dt) => [+ dt.textContent,+ dt.nextElementSibling?.textContent,+ ]),+ );++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ saveDraftBrief.mockReset();+ onRebuild.mockReset();+ onRetry.mockReset();+ onSaved.mockReset();+ toast.success.mockReset();+ toast.error.mockReset();+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++describe('the Brief tab', () => {+ it('shows the page, the brief and each H2 with the fan-out it answers', async () => {+ await render({ status: 'ready', brief });+ expect(fields()).toEqual({+ 'Page type': 'Buying guide',+ 'Target URL': '/guides/espresso',+ Goal: 'Help home baristas pick a machine',+ Audience: 'First-time espresso buyers',+ Length: '3,000 characters · from the page type',+ });+ const sections = [...container.querySelectorAll('ol > li')].map((li) => li.textContent);+ expect(sections).toEqual([+ 'H2The best espresso machines under $500Price bandsWhat to skipAnswers “best espresso machine under 500”· Perplexity',+ 'H2Care and cleaning',+ ]);+ expect(container.textContent).toContain('espresso machinegrinder');+ expect(container.textContent).toContain('Built from 7 sources');++ await act(async () => button('Rebuild outline').click());+ expect(onRebuild).toHaveBeenCalled();+ });++ it('offers to build a brief for a new page without one', async () => {+ await render({ status: 'ready', brief: null }, { pageType: 'product_page', sourceUrl: null });+ expect(fields()).toMatchObject({+ 'Page type': 'Product page',+ 'Target URL': 'A new page',+ Goal: '—',+ Length: '1,200 characters · from the page type',+ });+ expect(container.textContent).toContain('No outline yet.');+ expect(button('Edit brief')).toBeUndefined();+ await act(async () => button('Build brief').click());+ expect(onRebuild).toHaveBeenCalled();+ });++ it('says where an opportunity’s brief comes from', async () => {+ await render({+ status: 'ready',+ brief: { ...brief, origin: 'opportunity', builtAt: null, builtFrom: null },+ });+ expect(container.textContent).toContain("From the opportunity's brief.");+ });++ it('edits the brief by hand', async () => {+ saveDraftBrief.mockImplementation(async (_id, next: DraftBrief) => ({+ ...next,+ origin: 'edit',+ }));+ await render({ status: 'ready', brief });+ await act(async () => button('Edit brief').click());++ const setValue = (el: HTMLInputElement | HTMLTextAreaElement, value: string) => {+ const proto =+ el instanceof HTMLTextAreaElement+ ? HTMLTextAreaElement.prototype+ : HTMLInputElement.prototype;+ Object.getOwnPropertyDescriptor(proto, 'value')!.set!.call(el, value);+ el.dispatchEvent(new Event('input', { bubbles: true }));+ };+ const heading = container.querySelector<HTMLInputElement>(+ 'input[aria-label="Section 1 heading"]',+ )!;+ const points = container.querySelector<HTMLTextAreaElement>(+ 'textarea[aria-label="Section 1 key points"]',+ )!;+ await act(async () => {+ setValue(heading, 'Espresso machines under $500');+ setValue(points, 'Price bands\n\n Warranty ');+ });+ await act(async () => button('Remove section 2').click());+ await act(async () => button('Save brief').click());++ expect(saveDraftBrief).toHaveBeenCalledWith('d1', {+ ...brief,+ outline: [+ {+ heading: 'Espresso machines under $500',+ keyPoints: ['Price bands', 'Warranty'],+ fanout: 'best espresso machine under 500',+ platform: 'perplexity-web',+ },+ ],+ });+ expect(onSaved).toHaveBeenCalledWith(expect.objectContaining({ origin: 'edit' }));+ expect(toast.success).toHaveBeenCalledWith('Brief saved');+ });++ it('keeps the edit open when saving fails', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ saveDraftBrief.mockRejectedValue(new Error('boom'));+ await render({ status: 'ready', brief });+ await act(async () => button('Edit brief').click());+ await act(async () => button('Save brief').click());+ expect(toast.error).toHaveBeenCalledWith("Couldn't save the brief. Try again.");+ expect(button('Save brief')).toBeDefined();+ expect(onSaved).not.toHaveBeenCalled();+ });++ it('offers to retry when the brief can’t be read', async () => {+ await render({ status: 'failed' });+ await act(async () => button('Retry').click());+ expect(onRetry).toHaveBeenCalled();+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsxnew file mode 100644index 000000000..e289efaeb--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx@@ -0,0 +1,328 @@+'use client';++import { useState } from 'react';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { Loader2, Pencil, Plus, RefreshCw, Trash2 } from 'lucide-react';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Textarea } from '@/components/ui/textarea';+import { saveDraftBrief } from '@/lib/actions/content-drafts';+import { MAX_BRIEF_SECTIONS, builtFromCount, type DraftBrief } from '@/lib/content/brief';+import { lengthTarget } from '@/lib/content/editor';+import { platformNames } from '@/lib/content/impact';+import { pagePath } from '@/lib/content/overlap';+import { formatDateTime, formatNumber } from '@/lib/format';++/** The brief as the panel holds it: read once the tab opens. */+export type BriefState =+ | { status: 'loading' }+ | { status: 'failed' }+ | { status: 'ready'; brief: DraftBrief | null };++/**+ * The Brief tab (Content Editor CE-007, spec §10): the page type and target+ * address at the top, then the goal, audience and length, and the outline+ * with each H2's fan-out and platform. Rebuild outline writes it from the+ * sources kept; Edit brief changes it by hand. Until the draft has a brief,+ * the opportunity's brief it started from is shown.+ */+export function BriefTab({+ draftId,+ state,+ pageType,+ sourceUrl,+ rebuilding,+ onRebuild,+ onRetry,+ onSaved,+}: {+ draftId: string;+ state: BriefState;+ pageType: string | null;+ sourceUrl: string | null;+ rebuilding: boolean;+ onRebuild: () => void;+ onRetry: () => void;+ onSaved: (brief: DraftBrief) => void;+}) {+ const t = useTranslations('contentEditor.editor.brief');+ const tTypes = useTranslations('contentEditor.pageTypes');+ const [editing, setEditing] = useState(false);++ if (state.status === 'loading') {+ return (+ <div className="flex justify-center py-8" aria-busy="true">+ <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />+ </div>+ );+ }+ if (state.status === 'failed') {+ return (+ <p className="flex items-center gap-2 text-xs text-muted-foreground">+ {t('loadError')}+ <button type="button" className="font-medium underline" onClick={onRetry}>+ {t('retry')}+ </button>+ </p>+ );+ }++ const brief = state.brief;+ if (editing && brief) {+ return (+ <BriefEditor+ draftId={draftId}+ brief={brief}+ onCancel={() => setEditing(false)}+ onSaved={(saved) => {+ setEditing(false);+ onSaved(saved);+ }}+ />+ );+ }++ const typeLabel = pageType && (tTypes.has(pageType) ? tTypes(pageType) : pageType);++ return (+ <div className="space-y-4 text-sm">+ <dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1.5 text-xs">+ <dt className="text-muted-foreground">{t('pageType')}</dt>+ <dd>{typeLabel || t('notSet')}</dd>+ <dt className="text-muted-foreground">{t('targetUrl')}</dt>+ <dd className="min-w-0 truncate" title={sourceUrl ?? undefined}>+ {sourceUrl ? pagePath(sourceUrl) : t('newPage')}+ </dd>+ <dt className="text-muted-foreground">{t('goal')}</dt>+ <dd>{brief?.goal || '—'}</dd>+ <dt className="text-muted-foreground">{t('audience')}</dt>+ <dd>{brief?.audience || '—'}</dd>+ <dt className="text-muted-foreground">{t('length')}</dt>+ <dd>{t('lengthValue', { count: formatNumber(lengthTarget(pageType)) })}</dd>+ </dl>++ {brief && brief.outline.length > 0 ? (+ <section className="space-y-1.5">+ <h4 className="text-xs font-medium text-muted-foreground">+ {t('outline')}{' '}+ <span className="font-normal">· {formatNumber(brief.outline.length)}</span>+ </h4>+ <ol className="space-y-1.5">+ {brief.outline.map((section, i) => (+ <li key={i} className="rounded-lg border px-3 py-2">+ <p className="text-xs font-medium">+ <span className="mr-1.5 text-muted-foreground">H2</span>+ {section.heading}+ </p>+ {section.keyPoints.length > 0 && (+ <ul className="mt-1 list-disc space-y-0.5 pl-4 text-xs text-muted-foreground">+ {section.keyPoints.map((point, j) => (+ <li key={j}>{point}</li>+ ))}+ </ul>+ )}+ {section.fanout && (+ <p className="mt-1.5 inline-flex max-w-full items-center gap-1 rounded-md bg-muted px-1.5 py-0.5 text-[11px]">+ <span className="truncate" title={section.fanout}>+ {t('answers', { fanout: section.fanout })}+ </span>+ {section.platform && (+ <span className="shrink-0 text-muted-foreground">+ · {platformNames([section.platform])[0]}+ </span>+ )}+ </p>+ )}+ </li>+ ))}+ </ol>+ </section>+ ) : (+ <p className="rounded-lg border border-dashed px-3 py-2 text-xs text-muted-foreground">+ {t('empty')}+ </p>+ )}++ {brief && brief.keywords.length > 0 && (+ <section className="space-y-1.5">+ <h4 className="text-xs font-medium text-muted-foreground">{t('keywords')}</h4>+ <div className="flex flex-wrap gap-1">+ {brief.keywords.map((keyword) => (+ <span key={keyword} className="rounded-md border px-1.5 py-0.5 text-[11px]">+ {keyword}+ </span>+ ))}+ </div>+ </section>+ )}++ {brief && (+ <p className="text-[11px] text-muted-foreground">+ {brief.origin === 'opportunity'+ ? t('fromOpportunity')+ : brief.origin === 'edit'+ ? t('edited')+ : t('builtFrom', {+ count: builtFromCount(brief),+ date: brief.builtAt ? formatDateTime(brief.builtAt) : '',+ })}+ </p>+ )}++ <div className="flex flex-wrap gap-2">+ <Button size="sm" variant="outline" disabled={rebuilding} onClick={onRebuild}>+ {rebuilding ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <RefreshCw className="h-3.5 w-3.5" />+ )}+ {brief ? t('rebuild') : t('build')}+ </Button>+ {brief && (+ <Button size="sm" variant="ghost" disabled={rebuilding} onClick={() => setEditing(true)}>+ <Pencil className="h-3.5 w-3.5" />+ {t('edit')}+ </Button>+ )}+ </div>+ <p className="text-[11px] text-muted-foreground">{t('usage')}</p>+ </div>+ );+}++/** Edit brief: goal, audience, the outline's sections and key points, keywords. */+function BriefEditor({+ draftId,+ brief,+ onCancel,+ onSaved,+}: {+ draftId: string;+ brief: DraftBrief;+ onCancel: () => void;+ onSaved: (brief: DraftBrief) => void;+}) {+ const t = useTranslations('contentEditor.editor.brief.editor');+ const [goal, setGoal] = useState(brief.goal);+ const [audience, setAudience] = useState(brief.audience);+ const [sections, setSections] = useState(+ brief.outline.map((s) => ({ ...s, points: s.keyPoints.join('\n') })),+ );+ const [keywords, setKeywords] = useState(brief.keywords.join(', '));+ const [saving, setSaving] = useState(false);++ const update = (index: number, change: Partial<(typeof sections)[number]>) =>+ setSections((prev) => prev.map((s, i) => (i === index ? { ...s, ...change } : s)));++ const save = async () => {+ setSaving(true);+ try {+ const saved = await saveDraftBrief(draftId, {+ ...brief,+ goal: goal.trim(),+ audience: audience.trim(),+ outline: sections+ .filter((s) => s.heading.trim())+ .map((s) => ({+ heading: s.heading.trim(),+ keyPoints: s.points+ .split('\n')+ .map((p) => p.trim())+ .filter(Boolean),+ fanout: s.fanout,+ platform: s.platform,+ })),+ keywords: [+ ...new Set(+ keywords+ .split(',')+ .map((k) => k.trim())+ .filter(Boolean),+ ),+ ],+ });+ toast.success(t('saved'));+ onSaved(saved);+ } catch (err) {+ console.error('Failed to save the brief:', err);+ toast.error(t('failed'));+ } finally {+ setSaving(false);+ }+ };++ return (+ <div className="space-y-3 text-sm">+ <label className="block space-y-1">+ <span className="text-xs text-muted-foreground">{t('goal')}</span>+ <Textarea value={goal} onChange={(e) => setGoal(e.target.value)} rows={2} maxLength={500} />+ </label>+ <label className="block space-y-1">+ <span className="text-xs text-muted-foreground">{t('audience')}</span>+ <Input value={audience} onChange={(e) => setAudience(e.target.value)} maxLength={500} />+ </label>+ <div className="space-y-2">+ <span className="text-xs text-muted-foreground">{t('outline')}</span>+ {sections.map((section, i) => (+ <div key={i} className="space-y-1.5 rounded-lg border p-2">+ <div className="flex items-center gap-1.5">+ <span className="text-xs text-muted-foreground">H2</span>+ <Input+ value={section.heading}+ onChange={(e) => update(i, { heading: e.target.value })}+ aria-label={t('heading', { index: i + 1 })}+ maxLength={300}+ className="h-8"+ />+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label={t('remove', { index: i + 1 })}+ onClick={() => setSections((prev) => prev.filter((_, j) => j !== i))}+ >+ <Trash2 className="h-3.5 w-3.5" />+ </Button>+ </div>+ <Textarea+ value={section.points}+ onChange={(e) => update(i, { points: e.target.value })}+ aria-label={t('points', { index: i + 1 })}+ placeholder={t('pointsPlaceholder')}+ rows={2}+ className="text-xs"+ />+ </div>+ ))}+ {sections.length < MAX_BRIEF_SECTIONS && (+ <Button+ variant="ghost"+ size="sm"+ onClick={() =>+ setSections((prev) => [+ ...prev,+ { heading: '', keyPoints: [], points: '', fanout: null, platform: null },+ ])+ }+ >+ <Plus className="h-3.5 w-3.5" />+ {t('addSection')}+ </Button>+ )}+ </div>+ <label className="block space-y-1">+ <span className="text-xs text-muted-foreground">{t('keywords')}</span>+ <Input value={keywords} onChange={(e) => setKeywords(e.target.value)} />+ </label>+ <div className="flex gap-2">+ <Button size="sm" disabled={saving} onClick={() => void save()}>+ {saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}+ {t('save')}+ </Button>+ <Button size="sm" variant="outline" disabled={saving} onClick={onCancel}>+ {t('cancel')}+ </Button>+ </div>+ </div>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsxindex 7d7f43c74..f4827306b 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx@@ -409,7 +409,9 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {</div>{attachments.ui}</div>- {panelOpen && <EditorSidePanel draft={draft} title={title} bodyHtml={pageHtml} />}+ {panelOpen && (+ <EditorSidePanel draft={draft} title={title} bodyHtml={pageHtml} pageType={pageType} />+ )}</div></div>);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.test.tsxindex a3b9059f6..44e7a12dc 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.test.tsx@@ -81,11 +81,17 @@ const results = (over: Partial<ContentResults> = {}): ContentResults => ({let container: HTMLDivElement;let root: Root;-async function render(pageUrl: string | null = PAGE) {+const onUseLostPrompts = vi.fn();++async function render(pageUrl: string | null = PAGE, withLostPrompts = true) {await act(async () => {root.render(<NextIntlClientProvider locale="en" messages={messages}>- <ImpactTab brandId="b1" pageUrl={pageUrl} />+ <ImpactTab+ brandId="b1"+ pageUrl={pageUrl}+ onUseLostPrompts={withLostPrompts ? onUseLostPrompts : undefined}+ /></NextIntlClientProvider>,);});@@ -143,6 +149,21 @@ describe('the Impact tab', () => {).toBe(`/dashboard/citations/url?u=${encodeURIComponent(PAGE)}`);});+ it('uses the lost prompts in the draft', async () => {+ onUseLostPrompts.mockReset();+ getContentImpact.mockResolvedValue(impact());+ await render();+ await act(async () => periodButton('Use the lost prompt in this draft').click());+ expect(onUseLostPrompts).toHaveBeenCalledWith(['p2']);++ // Nothing lost, or nowhere to use them: no button.+ getContentImpact.mockResolvedValue(impact({ prompts: impact().prompts.slice(0, 1) }));+ await act(async () => periodButton('7d').click());+ expect(container.textContent).not.toContain('lost prompt');+ await render(PAGE, false);+ expect(container.textContent).not.toContain('in this draft');+ });+it('counts the prompts over all of them, not the list it shows', async () => {// The list is cut at 100 (lost prompts last); the counts come whole.getContentImpact.mockResolvedValue(impact({ promptCounts: { cur: 140, prev: 150, lost: 12 } }));diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.tsxindex db18b9ada..c3c22c4a5 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_impact-tab.tsx@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react';import { useTranslations } from 'next-intl';import { Check, ExternalLink, Loader2 } from 'lucide-react';import { Link } from '@/i18n/navigation';+import { Button } from '@/components/ui/button';import { getContentImpact, getContentResults } from '@/lib/actions/content-drafts';import {DEFAULT_IMPACT_PERIOD,@@ -40,7 +41,18 @@ interface ImpactRead {* from AI visits, per AI source; the brand's other pages cited for the same* prompts; and where the numbers come from.*/-export function ImpactTab({ brandId, pageUrl }: { brandId: string; pageUrl: string | null }) {+export function ImpactTab({+ brandId,+ pageUrl,+ rebuilding = false,+ onUseLostPrompts,+}: {+ brandId: string;+ pageUrl: string | null;+ /** Use lost prompts in this draft: they join its sources and the brief is rebuilt. */+ rebuilding?: boolean;+ onUseLostPrompts?: (promptIds: string[]) => void;+}) {const t = useTranslations('contentEditor.editor.impact');const [period, setPeriod] = useState<ImpactPeriod>(DEFAULT_IMPACT_PERIOD);const [read, setRead] = useState<ImpactRead | null>(null);@@ -118,7 +130,14 @@ export function ImpactTab({ brandId, pageUrl }: { brandId: string; pageUrl: stri</button></p>) : (- <ImpactBody impact={impact} results={current.results} period={period} pageUrl={pageUrl} />+ <ImpactBody+ impact={impact}+ results={current.results}+ period={period}+ pageUrl={pageUrl}+ rebuilding={rebuilding}+ onUseLostPrompts={onUseLostPrompts}+ />)}</div>);@@ -129,16 +148,22 @@ function ImpactBody({results,period,pageUrl,+ rebuilding,+ onUseLostPrompts,}: {impact: ContentImpact;results: ContentResults | null;period: ImpactPeriod;pageUrl: string;+ rebuilding: boolean;+ onUseLostPrompts?: (promptIds: string[]) => void;}) {const t = useTranslations('contentEditor.editor.impact');const coverage = gscCoverage(impact.gscSince, period);const cited = impact.promptCounts;const lost = impact.promptCounts.lost;+ // The lost prompts listed, to use in the draft (the list is capped at 100).+ const lostPrompts = impact.prompts.filter(isLost);const promptDelta = cited.cur - cited.prev;return (@@ -239,13 +264,26 @@ function ImpactBody({})}</ul>)}- <Link- href={`/dashboard/citations/url?u=${encodeURIComponent(pageUrl)}`}- className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"- >- {t('prompts.seeInCitations')}- <ExternalLink className="h-3 w-3" />- </Link>+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2">+ <Link+ href={`/dashboard/citations/url?u=${encodeURIComponent(pageUrl)}`}+ className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"+ >+ {t('prompts.seeInCitations')}+ <ExternalLink className="h-3 w-3" />+ </Link>+ {lostPrompts.length > 0 && onUseLostPrompts && (+ <Button+ size="sm"+ variant="outline"+ disabled={rebuilding}+ onClick={() => onUseLostPrompts(lostPrompts.map((p) => p.id))}+ >+ {rebuilding && <Loader2 className="h-3.5 w-3.5 animate-spin" />}+ {t('prompts.useLost', { count: lostPrompts.length })}+ </Button>+ )}+ </div></section>{results && <ImpactResults results={results} />}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsxindex 1e37c8ec0..e76c9af37 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx@@ -1,11 +1,14 @@'use client';-import { useState } from 'react';+import { useEffect, useRef, useState } from 'react';import { useTranslations } from 'next-intl';import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';import type { ContentDraft } from '@/lib/content/drafts';+import { getDraftBrief } from '@/lib/actions/content-drafts';+import { BriefTab, type BriefState } from './_brief-tab';import { ImpactTab } from './_impact-tab';import { SourcesTab } from './_sources-tab';+import { useBriefRebuild, type PageNow } from './_use-brief-rebuild';/** Remembers whether the panel is open, across drafts and visits. */const PANEL_OPEN_KEY = 'aeo:content-editor-panel';@@ -39,38 +42,81 @@ export function useSidePanelOpen(): [boolean, () => void] {return [open, toggle];}-const PANEL_TABS = ['impact', 'sources'] as const;+const PANEL_TABS = ['impact', 'brief', 'sources'] as const;type PanelTab = (typeof PANEL_TABS)[number];/*** The editor's right panel (Content Editor spec v2 §6), 400px beside the page.* The spec's tabs are Impact · Chat · Brief · Sources · Rules; each joins the- * panel with the update that makes it work: Impact (CE-016), then Sources- * (CE-008). A tab opened once stays mounted, so switching back keeps it as- * it was.+ * panel with the update that makes it work: Impact (CE-016), Brief (CE-007)+ * and Sources (CE-008). A tab opened once stays mounted, so switching back+ * keeps it as it was. The brief is held here: Sources' "Rebuild with+ * selection" and Impact's "Use lost prompts" rebuild it too, and open it.*/export function EditorSidePanel({draft,title,bodyHtml,+ pageType,}: {draft: ContentDraft;- /** The draft's title and page as written now: Sources says where each source is used. */+ /** The draft's title, page and type as written now: Sources and Brief read them. */title: string;bodyHtml: string;+ pageType: string | null;}) {const t = useTranslations('contentEditor.editor.panel');const [tab, setTab] = useState<PanelTab>('impact');const [opened, setOpened] = useState<Set<PanelTab>>(() => new Set(['impact']));+ const [brief, setBrief] = useState<BriefState>({ status: 'loading' });+ const [briefAttempt, setBriefAttempt] = useState(0);+ // Read afresh after prompts join the draft.+ const [sourcesVersion, setSourcesVersion] = useState(0);+ const page = useRef<PageNow>({ title, html: bodyHtml, pageType });+ const briefNow = useRef(brief);+ useEffect(() => {+ page.current = { title, html: bodyHtml, pageType };+ briefNow.current = brief;+ });++ const open = (next: PanelTab) => {+ setTab(next);+ setOpened((prev) => (prev.has(next) ? prev : new Set([...prev, next])));+ };++ const briefOpened = opened.has('brief');+ useEffect(() => {+ // A brief already in hand (a rebuild from Sources or Impact) isn't read again.+ if (!briefOpened || briefNow.current.status !== 'loading') return;+ let cancelled = false;+ getDraftBrief(draft.id)+ .then((result) => {+ if (!cancelled)+ setBrief(result ? { status: 'ready', brief: result.brief } : { status: 'failed' });+ })+ .catch((err) => {+ console.error('Failed to read the brief:', err);+ if (!cancelled) setBrief({ status: 'failed' });+ });+ return () => {+ cancelled = true;+ };+ }, [draft.id, briefOpened, briefAttempt]);++ const { rebuilding, rebuild } = useBriefRebuild({+ draft,+ pageNow: () => page.current,+ onRebuilt: (next) => {+ setBrief({ status: 'ready', brief: next });+ open('brief');+ },+ });+return (<aside aria-label={t('label')} className="flex w-[400px] shrink-0 flex-col border-l bg-card"><Tabsvalue={tab}- onValueChange={(value) => {- const next = value as PanelTab;- setTab(next);- setOpened((prev) => (prev.has(next) ? prev : new Set([...prev, next])));- }}+ onValueChange={(value) => open(value as PanelTab)}className="border-b px-3 pt-1.5"><TabsList variant="line">@@ -83,16 +129,43 @@ export function EditorSidePanel({</Tabs><div className="min-h-0 flex-1 overflow-y-auto px-4 py-4"><div hidden={tab !== 'impact'}>- <ImpactTab brandId={draft.brandId} pageUrl={draft.sourceUrl} />+ <ImpactTab+ brandId={draft.brandId}+ pageUrl={draft.sourceUrl}+ rebuilding={rebuilding}+ onUseLostPrompts={(promptIds) =>+ void rebuild({ addPrompts: promptIds }).then(() => setSourcesVersion((n) => n + 1))+ }+ /></div>+ {briefOpened && (+ <div hidden={tab !== 'brief'}>+ <BriefTab+ draftId={draft.id}+ state={brief}+ pageType={pageType}+ sourceUrl={draft.sourceUrl}+ rebuilding={rebuilding}+ onRebuild={() => void rebuild()}+ onRetry={() => {+ setBrief({ status: 'loading' });+ setBriefAttempt((n) => n + 1);+ }}+ onSaved={(saved) => setBrief({ status: 'ready', brief: saved })}+ />+ </div>+ )}{opened.has('sources') && (<div hidden={tab !== 'sources'}><SourcesTab+ key={sourcesVersion}draftId={draft.id}brandId={draft.brandId}title={title}sourceUrl={draft.sourceUrl}bodyHtml={bodyHtml}+ rebuilding={rebuilding}+ onRebuild={(sources) => void rebuild({ sources })}/></div>)}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.test.tsxindex 1bf5944fc..bf2fafa8e 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.test.tsx@@ -16,6 +16,7 @@ vi.mock('@/lib/actions/content-drafts', () => ({addDraftSource: (...args: unknown[]) => addDraftSource(...args),getContentStartOptions: (...args: unknown[]) => getContentStartOptions(...args),}));+const onRebuild = vi.fn();const toast = vi.hoisted(() => Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn() }));vi.mock('sonner', () => ({ toast }));@@ -79,6 +80,8 @@ function Tab({ bodyHtml }: { bodyHtml: string }) {title="The home espresso guide"sourceUrl={PAGE}bodyHtml={bodyHtml}+ rebuilding={false}+ onRebuild={onRebuild}/></NextIntlClientProvider>);@@ -102,6 +105,7 @@ beforeEach(() => {getContentStartOptions.mockReset().mockResolvedValue({ opportunities: [], prompts: [], topics: [] });+ onRebuild.mockReset();toast.mockReset();toast.success.mockReset();toast.error.mockReset();@@ -168,6 +172,19 @@ describe('the Sources tab', () => {expect(toast.error).toHaveBeenCalledWith("Couldn't change the source. Try again.");});+ it('rebuilds the brief from the sources as checked here', async () => {+ await render();+ await act(async () => checkbox('home espresso grinder').click());+ const rebuild = [...container.querySelectorAll('button')].find(+ (b) => b.textContent === 'Rebuild with selection',+ )!;+ await act(async () => rebuild.click());+ expect(onRebuild).toHaveBeenCalledWith({+ data: data(),+ choices: [{ kind: 'fanout', ref: 'home espresso grinder', included: false, added: false }],+ });+ });+it('changes each row on its own, and puts back only the one that failed', async () => {await render();vi.spyOn(console, 'error').mockImplementation(() => {});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsxindex f4a2a9292..24b7371d1 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx@@ -3,7 +3,7 @@import { useDeferredValue, useEffect, useMemo, useState } from 'react';import { useTranslations } from 'next-intl';import { toast } from 'sonner';-import { Loader2, Plus } from 'lucide-react';+import { Loader2, Plus, RefreshCw } from 'lucide-react';import { Button } from '@/components/ui/button';import { Checkbox } from '@/components/ui/checkbox';import { getDraftSources, setDraftSourceIncluded } from '@/lib/actions/content-drafts';@@ -39,12 +39,17 @@ export function SourcesTab({title,sourceUrl,bodyHtml,+ rebuilding,+ onRebuild,}: {draftId: string;brandId: string;title: string;sourceUrl: string | null;bodyHtml: string;+ /** Rebuild with selection: the brief from the sources as checked here. */+ rebuilding: boolean;+ onRebuild: (sources: { data: DraftSourcesData; choices: DraftSourceChoice[] }) => void;}) {const t = useTranslations('contentEditor.editor.sources');const [read, setRead] = useState<SourcesRead | null>(null);@@ -172,10 +177,24 @@ export function SourcesTab({))}- <Button variant="outline" size="sm" onClick={() => setAdding(true)}>- <Plus className="h-3.5 w-3.5" />- {t('add.button')}- </Button>+ <div className="flex flex-wrap gap-2">+ <Button+ size="sm"+ disabled={rebuilding || total === 0}+ onClick={() => onRebuild({ data: read.data, choices: read.choices })}+ >+ {rebuilding ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <RefreshCw className="h-3.5 w-3.5" />+ )}+ {t('rebuild')}+ </Button>+ <Button variant="outline" size="sm" onClick={() => setAdding(true)}>+ <Plus className="h-3.5 w-3.5" />+ {t('add.button')}+ </Button>+ </div><AddSourceDialogopen={adding}onOpenChange={setAdding}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.tsnew file mode 100644index 000000000..fb915e4da--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.ts@@ -0,0 +1,75 @@+'use client';++import { useState } from 'react';+import { useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { addDraftPrompts, getDraftSources, rebuildDraftBrief } from '@/lib/actions/content-drafts';+import { builtFromCount, rebuildSources, type DraftBrief } from '@/lib/content/brief';+import type { ContentDraft } from '@/lib/content/drafts';+import type { DraftSourceChoice, DraftSourcesData } from '@/lib/content/sources';++/** The page as written now: a rebuild reads its headings and length. */+export interface PageNow {+ title: string;+ html: string;+ pageType: string | null;+}++/**+ * Rebuild outline (CE-007), from the Brief tab, Sources' "Rebuild with+ * selection" or Impact's "Use lost prompts": the sources kept (as the+ * Sources tab has them, or read afresh), the page as written now, and the+ * brief the server writes from them, metered from the AI usage budget.+ */+export function useBriefRebuild({+ draft,+ pageNow,+ onRebuilt,+}: {+ draft: ContentDraft;+ pageNow: () => PageNow;+ onRebuilt: (brief: DraftBrief) => void;+}) {+ const t = useTranslations('contentEditor.editor.brief');+ const [rebuilding, setRebuilding] = useState(false);++ const rebuild = async (+ options: {+ sources?: { data: DraftSourcesData; choices: DraftSourceChoice[] };+ addPrompts?: string[];+ } = {},+ ): Promise<boolean> => {+ setRebuilding(true);+ try {+ if (options.addPrompts?.length) await addDraftPrompts(draft.id, options.addPrompts);+ const read = options.sources ?? (await getDraftSources(draft.id));+ if (!read) throw new Error('not_found');+ const page = pageNow();+ const result = await rebuildDraftBrief(+ draft.id,+ draft.brandId,+ rebuildSources(read.data, read.choices, {+ title: page.title,+ sourceUrl: draft.sourceUrl,+ html: page.html,+ pageType: page.pageType,+ }),+ );+ if ('error' in result) {+ toast.error(t(`rebuildErrors.${result.error}`));+ return false;+ }+ toast.success(t('rebuilt', { count: builtFromCount(result.brief) }));+ onRebuilt(result.brief);+ return true;+ } catch (err) {+ console.error('Failed to rebuild the brief:', err);+ toast.error(t('rebuildErrors.failed'));+ return false;+ } finally {+ setRebuilding(false);+ }+ };++ return { rebuilding, rebuild };+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsxindex 087b663c7..ddb678953 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx@@ -13,8 +13,12 @@ const setContentDraftPageType = vi.fn();const getContentImpact = vi.fn();const getContentResults = vi.fn();const getDraftSources = vi.fn();+const getDraftBrief = vi.fn();+const rebuildDraftBrief = vi.fn();vi.mock('@/lib/actions/content-drafts', () => ({getDraftSources: (...args: unknown[]) => getDraftSources(...args),+ getDraftBrief: (...args: unknown[]) => getDraftBrief(...args),+ rebuildDraftBrief: (...args: unknown[]) => rebuildDraftBrief(...args),getContentImpact: (...args: unknown[]) => getContentImpact(...args),getContentResults: (...args: unknown[]) => getContentResults(...args),getContentDraft: (...args: unknown[]) => getContentDraft(...args),@@ -145,6 +149,8 @@ beforeEach(() => {getContentImpact.mockReset().mockResolvedValue(null);getContentResults.mockReset().mockResolvedValue(null);getDraftSources.mockReset().mockResolvedValue(null);+ getDraftBrief.mockReset().mockResolvedValue({ brief: null });+ rebuildDraftBrief.mockReset();localStorage.clear();brandState.activeBrandId = 'b1';brandState.setActiveBrand.mockReset();@@ -623,6 +629,72 @@ describe('the side panel', () => {expect(getContentImpact).toHaveBeenCalledTimes(1);});+ it('rebuilds the brief from Sources and opens it', async () => {+ getDraftSources.mockResolvedValue({+ data: {+ prompts: [],+ fanouts: [{ query: 'pipeline forecasting', platforms: ['copilot-web'], searched: 2 }],+ citedPages: [],+ gscQueries: [],+ brandDomains: [],+ competitorDomains: [],+ },+ choices: [],+ });+ rebuildDraftBrief.mockResolvedValue({+ brief: {+ goal: 'Win forecasting searches',+ audience: 'Sales leaders',+ outline: [+ {+ heading: 'How pipeline forecasting works',+ keyPoints: [],+ fanout: 'pipeline forecasting',+ platform: 'copilot-web',+ },+ ],+ keywords: [],+ origin: 'rebuild',+ builtAt: '2026-10-21T10:00:00Z',+ builtFrom: { prompts: 0, fanouts: 1, pages: 0, queries: 0 },+ },+ });+ getContentDraft.mockResolvedValue(draft({ sourceUrl: 'https://acme.example.com/pricing' }));+ window.innerWidth = 1440;+ await renderPage();++ const pick = async (name: string) => {+ const tab = [...panel()!.querySelectorAll<HTMLElement>('[role="tab"]')].find(+ (el) => el.textContent === name,+ )!;+ await act(async () => {+ tab.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));+ tab.click();+ });+ };+ expect([...panel()!.querySelectorAll('[role="tab"]')].map((el) => el.textContent)).toEqual([+ 'Impact',+ 'Brief',+ 'Sources',+ ]);+ await pick('Sources');+ await act(async () => button('Rebuild with selection')!.click());++ expect(rebuildDraftBrief).toHaveBeenCalledWith('d1', 'b1', {+ promptIds: [],+ fanouts: [{ query: 'pipeline forecasting', platforms: ['copilot-web'] }],+ pages: [],+ queries: [],+ headings: [],+ length: 3000,+ });+ expect(toast.success).toHaveBeenCalledWith('Brief rebuilt from 1 source');+ const selected = panel()!.querySelector('[role="tab"][aria-selected="true"]');+ expect(selected?.textContent).toBe('Brief');+ expect(panel()!.textContent).toContain('How pipeline forecasting works');+ expect(panel()!.textContent).toContain('Win forecasting searches');+ });+it('starts open on a wide window, and remembers it closed', async () => {getContentDraft.mockResolvedValue(draft({ method: 'create' }));window.innerWidth = 1440;diff --git a/web/src/lib/actions/content-drafts-brief.test.ts b/web/src/lib/actions/content-drafts-brief.test.tsnew file mode 100644index 000000000..490958d31--- /dev/null+++ b/web/src/lib/actions/content-drafts-brief.test.ts@@ -0,0 +1,185 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { DraftBrief, RebuildSources } from '@/lib/content/brief';++/** The Brief tab (CE-007): read, edit and rebuild a draft's brief. */++const DRAFT = '77777777-7777-7777-7777-777777777777';+const BRAND = '33333333-3333-3333-3333-333333333333';+const PROMPT = '55555555-5555-5555-5555-555555555555';++interface Call {+ table: string;+ op: string;+ value?: unknown;+ filters: [string, unknown][];+}+let calls: Call[];+let reads: Record<string, unknown>;+let session: { access_token: string } | null;++vi.mock('@/lib/action-center/assignees', () => ({ readAssignees: vi.fn(async () => new Map()) }));+vi.mock('@/lib/supabase/server', () => ({+ createClient: vi.fn(async () => ({+ auth: { getSession: async () => ({ data: { session } }) },+ from: (table: string) => {+ const call: Call = { table, op: 'select', filters: [] };+ calls.push(call);+ const result = () =>+ call.op === 'update' && call.filters.length && reads[`${table}:update`] !== undefined+ ? { data: reads[`${table}:update`], error: null }+ : { data: call.op === 'select' ? (reads[table] ?? null) : null, error: null };+ const chain: Record<string, unknown> = {+ select: () => chain,+ eq: (col: string, v: unknown) => (call.filters.push([col, v]), chain),+ in: (col: string, v: unknown) => (call.filters.push([col, v]), chain),+ update: (value: unknown) => ((call.op = 'update'), (call.value = value), chain),+ maybeSingle: async () => result(),+ then: (resolve: (r: unknown) => void) => resolve(result()),+ };+ return chain;+ },+ })),+}));++const { addDraftPrompts, getDraftBrief, rebuildDraftBrief, saveDraftBrief } =+ await import('./content-drafts');++const brief: DraftBrief = {+ goal: 'Help buyers pick',+ audience: 'Home baristas',+ outline: [+ { heading: 'Machines', keyPoints: ['Price'], fanout: 'espresso', platform: 'copilot-web' },+ ],+ keywords: ['espresso'],+ origin: 'rebuild',+ builtAt: '2026-10-21T10:00:00Z',+ builtFrom: { prompts: 1, fanouts: 1, pages: 0, queries: 0 },+};++const sources: RebuildSources = {+ promptIds: [PROMPT],+ fanouts: [{ query: 'espresso', platforms: ['copilot-web'] }],+ pages: [],+ queries: [],+ headings: [],+ length: 3000,+};++const fetchMock = vi.fn();++beforeEach(() => {+ calls = [];+ reads = {};+ session = { access_token: 'jwt' };+ fetchMock.mockReset();+ vi.stubGlobal('fetch', fetchMock);+});++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('getDraftBrief', () => {+ it('reads the draft’s brief', async () => {+ reads.content_drafts = { brief, opportunity_id: 'o1' };+ expect(await getDraftBrief(DRAFT)).toEqual({ brief });+ expect(calls.map((c) => c.table)).toEqual(['content_drafts']);+ });++ it('falls back to the opportunity’s brief, or none', async () => {+ reads.content_drafts = { brief: null, opportunity_id: 'o1' };+ reads.content_opportunities = {+ brief: {+ outline: [{ heading: 'Why', keyPoints: [] }],+ targetKeywords: [],+ callToAction: 'Try it',+ },+ };+ expect(await getDraftBrief(DRAFT)).toMatchObject({+ brief: { origin: 'opportunity', goal: 'Try it', outline: [{ heading: 'Why', fanout: null }] },+ });++ reads.content_opportunities = { brief: null };+ expect(await getDraftBrief(DRAFT)).toEqual({ brief: null });+ reads.content_drafts = { brief: null, opportunity_id: null };+ expect(await getDraftBrief(DRAFT)).toEqual({ brief: null });+ reads.content_drafts = null;+ expect(await getDraftBrief(DRAFT)).toBeNull();+ });+});++describe('saveDraftBrief', () => {+ it('saves the brief as edited by the person', async () => {+ reads['content_drafts:update'] = { id: DRAFT };+ const saved = await saveDraftBrief(DRAFT, brief);+ expect(saved.origin).toBe('edit');+ expect(calls[0]).toMatchObject({+ table: 'content_drafts',+ op: 'update',+ value: { brief: { ...brief, origin: 'edit' } },+ filters: [['id', DRAFT]],+ });+ });++ it('refuses a brief over its limits, and says when the draft isn’t found', async () => {+ await expect(saveDraftBrief(DRAFT, { ...brief, goal: 'x'.repeat(501) })).rejects.toThrow(+ 'invalid',+ );+ await expect(saveDraftBrief(DRAFT, brief)).rejects.toThrow('not_found');+ });+});++describe('rebuildDraftBrief', () => {+ it('asks the API to rebuild with the member’s session', async () => {+ fetchMock.mockResolvedValue({ ok: true, json: async () => ({ brief }) });+ expect(await rebuildDraftBrief(DRAFT, BRAND, sources)).toEqual({ brief });+ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toMatch(new RegExp(`/api/content-drafts/${DRAFT}/brief$`));+ expect(init.headers.Authorization).toBe('Bearer jwt');+ expect(JSON.parse(init.body)).toEqual({ brandId: BRAND, sources });+ });++ it('names why it didn’t, and anything unexpected as failed', async () => {+ for (const [body, ok, error] of [+ [{ code: 'ai_budget' }, false, 'ai_budget'],+ [{ code: 'no_subscription' }, false, 'no_subscription'],+ [{ code: 'no_sources' }, false, 'no_sources'],+ [{ code: 'forbidden' }, false, 'failed'],+ [{ brief: { goal: 1 } }, true, 'failed'],+ ] as const) {+ fetchMock.mockResolvedValueOnce({ ok, json: async () => body });+ expect(await rebuildDraftBrief(DRAFT, BRAND, sources)).toEqual({ error });+ }+ session = null;+ expect(await rebuildDraftBrief(DRAFT, BRAND, sources)).toEqual({ error: 'failed' });+ expect(await rebuildDraftBrief('d1', BRAND, sources)).toEqual({ error: 'failed' });+ });+});++describe('addDraftPrompts', () => {+ it('adds the prompts the draft hasn’t, and brings left-out ones back', async () => {+ reads.content_drafts = { prompt_ids: [PROMPT] };+ const other = '66666666-6666-6666-6666-666666666666';+ await addDraftPrompts(DRAFT, [PROMPT, other]);+ const writes = calls.filter((c) => c.op === 'update');+ expect(writes[0]).toMatchObject({+ table: 'content_drafts',+ value: { prompt_ids: [PROMPT, other] },+ });+ expect(writes[1]).toMatchObject({+ table: 'content_draft_sources',+ value: expect.objectContaining({ included: true }),+ filters: [+ ['draft_id', DRAFT],+ ['kind', 'prompt'],+ ['ref', [PROMPT, other]],+ ],+ });+ });++ it('refuses no prompts or a malformed one', async () => {+ await expect(addDraftPrompts(DRAFT, [])).rejects.toThrow('invalid');+ await expect(addDraftPrompts(DRAFT, ['p1'])).rejects.toThrow('invalid');+ expect(calls).toEqual([]);+ });+});diff --git a/web/src/lib/actions/content-drafts-sources.test.ts b/web/src/lib/actions/content-drafts-sources.test.tsindex db49c46be..a6c0bd805 100644--- a/web/src/lib/actions/content-drafts-sources.test.ts+++ b/web/src/lib/actions/content-drafts-sources.test.ts@@ -35,6 +35,7 @@ vi.mock('@/lib/supabase/server', () => ({const chain: Record<string, unknown> = {select: () => chain,eq: (col: string, v: unknown) => (call.filters.push([col, v]), chain),+ in: (col: string, v: unknown) => (call.filters.push([col, v]), chain),update: (value: unknown) => ((call.op = 'update'), (call.value = value), chain),upsert: (value: unknown, options: unknown) => ((call.op = 'upsert'),@@ -147,7 +148,7 @@ describe('addDraftSource', () => {filters: [['draft_id', DRAFT],['kind', 'prompt'],- ['ref', PROMPT],+ ['ref', [PROMPT]],],}),]);diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex 1884b83e2..9592d0cdb 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -29,6 +29,13 @@ import {} from '@/lib/content/editor';import { detectPageType, siteTypeOf, type SiteType } from '@/lib/content/page-types';import { sanitizeDraftHtml } from '@/lib/content/sanitize-draft-html';+import {+ briefFromOpportunity,+ draftBriefSchema,+ type DraftBrief,+ type RebuildSources,+} from '@/lib/content/brief';+import type { ContentBrief } from '@/types';import {DRAFT_SOURCE_KINDS,SOURCES_DAYS,@@ -725,31 +732,7 @@ export async function addDraftSource(id: string, source: AddedDraftSource): Promconst now = new Date().toISOString();if (parsed.data.kind === 'prompt') {- const { promptId } = parsed.data;- const { data: draft, error } = await supabase- .from('content_drafts')- .select('prompt_ids')- .eq('id', id)- .maybeSingle();- if (error) throw new Error(error.message);- if (!draft) throw new Error('not_found');- const promptIds: string[] = draft.prompt_ids ?? [];- if (!promptIds.includes(promptId)) {- // check_content_draft_links (00206) refuses a prompt of another brand.- const { error: updateError } = await supabase- .from('content_drafts')- .update({ prompt_ids: [...promptIds, promptId] })- .eq('id', id);- if (updateError) throw new Error(updateError.message);- }- // A prompt left out before is back in.- const { error: choiceError } = await supabase- .from('content_draft_sources')- .update({ included: true, updated_at: now })- .eq('draft_id', id)- .eq('kind', 'prompt')- .eq('ref', promptId);- if (choiceError) throw new Error(choiceError.message);+ await addDraftPrompts(id, [parsed.data.promptId]);return;}@@ -763,3 +746,128 @@ export async function addDraftSource(id: string, source: AddedDraftSource): Prom);if (error) throw new Error(error.message);}++const promptIdList = z.array(z.guid()).min(1).max(100);++/**+ * Prompts join the draft's prompts (Sources' + Add source, Impact's "Use+ * lost prompts"); one left out of the sources before is back in. Throws+ * 'not_found' when the draft isn't the member's.+ */+export async function addDraftPrompts(id: string, promptIds: string[]): Promise<void> {+ const parsed = promptIdList.safeParse(promptIds);+ if (!draftId.safeParse(id).success || !parsed.success) throw new Error('invalid');+ const supabase = await createClient();+ const { data: draft, error } = await supabase+ .from('content_drafts')+ .select('prompt_ids')+ .eq('id', id)+ .maybeSingle();+ if (error) throw new Error(error.message);+ if (!draft) throw new Error('not_found');+ const current: string[] = draft.prompt_ids ?? [];+ const added = parsed.data.filter((promptId) => !current.includes(promptId));+ if (added.length) {+ // check_content_draft_links (00206) refuses a prompt of another brand.+ const { error: updateError } = await supabase+ .from('content_drafts')+ .update({ prompt_ids: [...current, ...added] })+ .eq('id', id);+ if (updateError) throw new Error(updateError.message);+ }+ const { error: choiceError } = await supabase+ .from('content_draft_sources')+ .update({ included: true, updated_at: new Date().toISOString() })+ .eq('draft_id', id)+ .eq('kind', 'prompt')+ .in('ref', parsed.data);+ if (choiceError) throw new Error(choiceError.message);+}++/**+ * The Brief tab (CE-007): the draft's brief, or, until it has one, the brief+ * of the opportunity it started from. Null when the member can't read the+ * draft.+ */+export async function getDraftBrief(id: string): Promise<{ brief: DraftBrief | null } | null> {+ if (!draftId.safeParse(id).success) throw new Error('invalid');+ const supabase = await createClient();+ const { data: draft, error } = await supabase+ .from('content_drafts')+ .select('brief, opportunity_id')+ .eq('id', id)+ .maybeSingle();+ if (error) throw new Error(error.message);+ if (!draft) return null;+ const own = draftBriefSchema.safeParse(draft.brief);+ if (own.success) return { brief: own.data };+ if (!draft.opportunity_id) return { brief: null };+ const { data: opportunity, error: oppError } = await supabase+ .from('content_opportunities')+ .select('brief')+ .eq('id', draft.opportunity_id)+ .maybeSingle();+ if (oppError) throw new Error(oppError.message);+ const brief = opportunity?.brief as ContentBrief | null | undefined;+ return { brief: brief?.outline ? briefFromOpportunity(brief) : null };+}++/** Edit brief (CE-007): the brief as the person wrote it. Throws 'not_found' when no row changed. */+export async function saveDraftBrief(id: string, brief: DraftBrief): Promise<DraftBrief> {+ const parsed = draftBriefSchema.safeParse({ ...brief, origin: 'edit' });+ if (!draftId.safeParse(id).success || !parsed.success) throw new Error('invalid');+ const supabase = await createClient();+ const { data, error } = await supabase+ .from('content_drafts')+ .update({ brief: parsed.data })+ .eq('id', id)+ .select('id')+ .maybeSingle();+ if (error) throw new Error(error.message);+ if (!data) throw new Error('not_found');+ return parsed.data;+}++const BRIEF_REBUILD_ERRORS = ['ai_budget', 'no_subscription', 'no_sources', 'failed'] as const;+export type BriefRebuildError = (typeof BRIEF_REBUILD_ERRORS)[number];++/**+ * Rebuild outline (CE-007): the server writes the brief from the sources+ * kept, metered from the organization's AI usage (content-brief.js).+ */+export async function rebuildDraftBrief(+ id: string,+ brandId: string,+ sources: RebuildSources,+): Promise<{ brief: DraftBrief } | { error: BriefRebuildError }> {+ if (!draftId.safeParse(id).success || !draftId.safeParse(brandId).success) {+ return { error: 'failed' };+ }+ const supabase = await createClient();+ const {+ data: { session },+ } = await supabase.auth.getSession();+ if (!session) return { error: 'failed' };+ try {+ const res = await fetch(`${API_BASE_URL}/api/content-drafts/${id}/brief`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${session.access_token}`,+ },+ body: JSON.stringify({ brandId, sources }),+ });+ const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;+ if (!res.ok) {+ const code = body.code as BriefRebuildError;+ return {+ error: (BRIEF_REBUILD_ERRORS as readonly string[]).includes(code) ? code : 'failed',+ };+ }+ const brief = draftBriefSchema.safeParse(body.brief);+ return brief.success ? { brief: brief.data } : { error: 'failed' };+ } catch (err) {+ console.error('Failed to rebuild the brief:', err);+ return { error: 'failed' };+ }+}diff --git a/web/src/lib/content/brief.test.ts b/web/src/lib/content/brief.test.tsnew file mode 100644index 000000000..0b1005a4b--- /dev/null+++ b/web/src/lib/content/brief.test.ts@@ -0,0 +1,129 @@+import { describe, expect, it } from 'vitest';+import {+ briefFromOpportunity,+ builtFromCount,+ draftBriefSchema,+ rebuildSources,+ type DraftBrief,+} from './brief';+import type { DraftSourcesData } from './sources';++const data: DraftSourcesData = {+ prompts: [+ {+ id: 'p1',+ text: 'Best espresso machines under $500?',+ inDraft: true,+ citesPage: false,+ answers: 21,+ mentioned: 4,+ },+ {+ id: 'p2',+ text: 'Manual vs automatic espresso',+ inDraft: false,+ citesPage: true,+ answers: 3,+ mentioned: 0,+ },+ ],+ fanouts: [+ { query: 'best espresso machine under 500', platforms: ['perplexity-web'], searched: 5 },+ { query: 'home espresso grinder', platforms: ['copilot-web'], searched: 2 },+ ],+ citedPages: [+ {+ url: 'https://www.reddit.com/r/espresso/x',+ title: null,+ domain: 'reddit.com',+ citations: 12,+ answers: 9,+ },+ ],+ gscQueries: [{ query: 'espresso machine under 500', clicks: 40, impressions: 900 }],+ brandDomains: ['acme.example'],+ competitorDomains: [],+};++const draft = {+ title: 'The home espresso guide',+ sourceUrl: 'https://acme.example/guides/espresso',+ html: '<h1>The home espresso guide</h1><h2>Choosing a machine</h2><p>x</p><h3>Grinders</h3><h2></h2>',+ pageType: 'product_page',+};++describe('rebuildSources', () => {+ it('sends the sources kept, the page’s H2s and H3s, and the length its type asks for', () => {+ expect(+ rebuildSources(+ data,+ [+ { kind: 'prompt', ref: 'p2', included: false, added: false },+ { kind: 'fanout', ref: 'home espresso grinder', included: false, added: false },+ { kind: 'cited_page', ref: 'https://example.org/study', included: true, added: true },+ ],+ draft,+ ),+ ).toEqual({+ promptIds: ['p1'],+ fanouts: [{ query: 'best espresso machine under 500', platforms: ['perplexity-web'] }],+ pages: [+ { url: 'https://www.reddit.com/r/espresso/x', kind: 'forum' },+ { url: 'https://example.org/study', kind: 'other' },+ ],+ queries: ['espresso machine under 500'],+ headings: ['Choosing a machine', 'Grinders'],+ length: 1200,+ });+ });+});++describe('the brief', () => {+ const brief: DraftBrief = {+ goal: 'Help buyers pick',+ audience: 'Home baristas',+ outline: [+ { heading: 'Machines', keyPoints: ['Price'], fanout: 'espresso', platform: 'copilot-web' },+ ],+ keywords: ['espresso'],+ origin: 'rebuild',+ builtAt: '2026-10-21T10:00:00Z',+ builtFrom: { prompts: 1, fanouts: 2, pages: 1, queries: 1 },+ };++ it('counts the sources it was built from', () => {+ expect(builtFromCount(brief)).toBe(5);+ expect(builtFromCount({ ...brief, builtFrom: null })).toBe(0);+ });++ it('keeps to its limits', () => {+ expect(draftBriefSchema.safeParse(brief).success).toBe(true);+ expect(+ draftBriefSchema.safeParse({ ...brief, outline: [{ ...brief.outline[0], heading: ' ' }] })+ .success,+ ).toBe(false);+ expect(draftBriefSchema.safeParse({ ...brief, origin: 'agent' }).success).toBe(false);+ });++ it('reads an opportunity’s brief until the draft has its own', () => {+ expect(+ briefFromOpportunity({+ suggestedTitle: 'x',+ contentType: 'guide',+ targetWordCount: 1500,+ outline: [{ heading: 'Why', keyPoints: ['a'] }],+ targetKeywords: ['espresso'],+ competitorInsights: '',+ callToAction: 'Start a trial',+ }),+ ).toEqual({+ goal: 'Start a trial',+ audience: '',+ outline: [{ heading: 'Why', keyPoints: ['a'], fanout: null, platform: null }],+ keywords: ['espresso'],+ origin: 'opportunity',+ builtAt: null,+ builtFrom: null,+ });+ });+});diff --git a/web/src/lib/content/brief.ts b/web/src/lib/content/brief.tsnew file mode 100644index 000000000..cd117a07e--- /dev/null+++ b/web/src/lib/content/brief.ts@@ -0,0 +1,141 @@+import { z } from 'zod';+import type { ContentBrief } from '@/types';+import { lengthTarget } from '@/lib/content/editor';+import {+ buildSourceGroups,+ readDraftDoc,+ type DraftSourceChoice,+ type DraftSourcesData,+} from '@/lib/content/sources';++/**+ * The editor's Brief tab (Content Editor CE-007, spec §10): what the page+ * should do — its goal, audience and length, and an outline whose H2s each+ * answer a search AI engines ran (a fan-out) on a platform. Rebuild outline+ * writes it from the sources kept in the Sources tab (server+ * content-brief.js); Edit brief changes it by hand. Stored in+ * content_drafts.brief (00212).+ */++export const BRIEF_ORIGINS = ['rebuild', 'edit', 'opportunity'] as const;+export type BriefOrigin = (typeof BRIEF_ORIGINS)[number];++export interface BriefSection {+ heading: string;+ keyPoints: string[];+ /** The fan-out the H2 answers, as the Sources tab lists it; null for none. */+ fanout: string | null;+ /** The platform key that ran it (perplexity-web, copilot-web…). */+ platform: string | null;+}++export interface DraftBrief {+ goal: string;+ audience: string;+ outline: BriefSection[];+ keywords: string[];+ origin: BriefOrigin;+ /** When Rebuild outline last wrote it. */+ builtAt: string | null;+ /** The sources it was built from, by group. */+ builtFrom: { prompts: number; fanouts: number; pages: number; queries: number } | null;+}++/** Limits a brief keeps to, the server's (content-brief.js) and the column's (00212). */+export const MAX_BRIEF_SECTIONS = 12;+const text = (max: number) => z.string().trim().max(max);++export const draftBriefSchema = z.object({+ goal: text(500),+ audience: text(500),+ outline: z+ .array(+ z.object({+ heading: text(300).min(1),+ keyPoints: z.array(text(500).min(1)).max(8),+ fanout: text(300).nullable(),+ platform: text(60).nullable(),+ }),+ )+ .max(MAX_BRIEF_SECTIONS),+ keywords: z.array(text(80).min(1)).max(15),+ origin: z.enum(BRIEF_ORIGINS),+ builtAt: z.string().max(40).nullable(),+ builtFrom: z+ .object({+ prompts: z.number().int().min(0),+ fanouts: z.number().int().min(0),+ pages: z.number().int().min(0),+ queries: z.number().int().min(0),+ })+ .nullable(),+});++/** The brief of the opportunity a draft started from, until the draft has its own. */+export function briefFromOpportunity(brief: ContentBrief): DraftBrief {+ return {+ goal: brief.callToAction ?? '',+ audience: '',+ outline: (brief.outline ?? []).map((section) => ({+ heading: section.heading,+ keyPoints: section.keyPoints ?? [],+ fanout: null,+ platform: null,+ })),+ keywords: brief.targetKeywords ?? [],+ origin: 'opportunity',+ builtAt: null,+ builtFrom: null,+ };+}++/** What Rebuild outline sends the server: the sources kept, the page as written, its length. */+export interface RebuildSources {+ promptIds: string[];+ fanouts: { query: string; platforms: string[] }[];+ pages: { url: string; kind: string }[];+ queries: string[];+ headings: string[];+ length: number;+}++/**+ * The sources a rebuild uses: the ones checked in the Sources tab, as it+ * lists them; the page's H2s and H3s as written now; and the length the page+ * type asks for.+ */+export function rebuildSources(+ data: DraftSourcesData,+ choices: DraftSourceChoice[],+ draft: { title: string; sourceUrl: string | null; html: string; pageType: string | null },+): RebuildSources {+ const groups = buildSourceGroups(data, choices, draft);+ const kept = (kind: string) =>+ groups.find((g) => g.kind === kind)?.rows.filter((r) => r.included) ?? [];+ // The server's limits (content-brief.js rebuildSources).+ return {+ promptIds: kept('prompt')+ .map((r) => r.ref)+ .slice(0, 100),+ fanouts: kept('fanout')+ .flatMap((r) => (r.kind === 'fanout' ? [{ query: r.name, platforms: r.platforms }] : []))+ .slice(0, 40),+ pages: kept('cited_page')+ .flatMap((r) => (r.kind === 'cited_page' ? [{ url: r.name, kind: r.category }] : []))+ .slice(0, 30),+ queries: kept('gsc_query')+ .map((r) => r.name)+ .slice(0, 20),+ headings: readDraftDoc(draft.html)+ .headings.filter((h) => h.level > 1 && h.text)+ .map((h) => h.text)+ .slice(0, 30),+ length: lengthTarget(draft.pageType),+ };+}++/** The sources a brief was built from, counted together. */+export function builtFromCount(brief: DraftBrief): number {+ const from = brief.builtFrom;+ return from ? from.prompts + from.fanouts + from.pages + from.queries : 0;+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex f416719e5..1b230b686 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -830,6 +830,7 @@ export type Database = {action_id: string | nullauthor: stringbody_html: string+ brief: Json | nullbrand_id: stringcreated_at: stringcreated_by: string | null@@ -850,6 +851,7 @@ export type Database = {action_id?: string | nullauthor?: stringbody_html?: string+ brief?: Json | nullbrand_id: stringcreated_at?: stringcreated_by?: string | null@@ -870,6 +872,7 @@ export type Database = {action_id?: string | nullauthor?: stringbody_html?: string+ brief?: Json | nullbrand_id?: stringcreated_at?: stringcreated_by?: string | null