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): let the Content Agent write a draft from Start (#1307)
Cihanda8969977c88
diff --git a/server/src/lib/content-agent.js b/server/src/lib/content-agent.jsindex 936f1fbad..503d6054b 100644--- a/server/src/lib/content-agent.js+++ b/server/src/lib/content-agent.js@@ -55,7 +55,7 @@ export const fixRulesInput = z.object({locked: z.array(z.string().max(5000)).max(500).default([]),});-const suggestionsSchema = z.object({+export const suggestionsSchema = z.object({suggestions: z.array(z.object({diff --git a/server/src/lib/content-writer.js b/server/src/lib/content-writer.jsnew file mode 100644index 000000000..c54d328b3--- /dev/null+++ b/server/src/lib/content-writer.js@@ -0,0 +1,470 @@+import { randomUUID } from 'crypto';+import { generateObject } from 'ai';+import { z } from 'zod';+import supabaseAdmin from '../config/supabase.js';+import { resolveModel } from './ai-provider.js';+import {+ MAX_AGENT_SUGGESTIONS,+ draftPassages,+ hasOpenSuggestions,+ keepSuggestions,+ passageKey,+ promptPassages,+ suggestionsSchema,+} from './content-agent.js';+import { contentBriefModelId, rebuildSources, recordUsage } from './content-brief.js';+import { getLanguageName } from './languages.js';+import { logger } from './logger.js';+import { enforceImproveQuota } from './plan-guard.js';++/**+ * "Agent" in the Content Editor's Start (CE-015, spec §5): the Content Agent+ * does the page, and a person reviews it in Library › In review. A new page+ * is written whole, from its brief, prompts, the AI searches behind them and+ * its rules. An existing page is the person's live text: the agent leaves+ * suggestions on it (content_draft_suggestions, 00217), as Fix open rules+ * does, and never changes a passage AI answers quote today.+ *+ * Start doesn't wait for it. The draft says where the agent is+ * (content_drafts.agent_state, 00219): 'writing' while it runs here in the+ * background, then In review, or 'failed'. It is metered from the+ * organization's AI usage, as the brief and the agent's fixes are, and one+ * draft of an organization is written at a time: the budget is checked+ * before a run, so runs started together could all pass it.+ */++/** How long the model may take: nobody waits on the request. */+const CALL_TIMEOUT_MS = 180_000;++/** A 'writing' this old was left by a server that stopped: it can start again. */+export const WRITING_STALE_MS = 10 * 60_000;++/** What the person's dashboard sends: the sources kept, the page's rules, its locked passages. */+export const writeDraftInput = z.object({+ sources: rebuildSources,+ rules: z+ .array(+ z.object({+ key: z.string().trim().min(1).max(60),+ name: z.string().trim().min(1).max(200),+ /** What the rule asks: "aim 3,000 characters". */+ detail: z.string().trim().max(500).default(''),+ }),+ )+ .max(60)+ .default([]),+ textRules: z.array(z.string().trim().min(1).max(300)).max(50).default([]),+ /** The passages AI answers quote today, by passageKey (an existing page's). */+ locked: z.array(z.string().max(5000)).max(500).default([]),+});++export const pageSchema = z.object({+ title: z.string().describe('The page title, its H1.'),+ intro: z+ .array(z.string())+ .min(1)+ .max(3)+ .describe('The opening paragraphs, the direct answer first.'),+ sections: z+ .array(+ z.object({+ heading: z.string().describe('The H2.'),+ paragraphs: z.array(z.string()).max(6),+ bullets: z.array(z.string()).max(10).describe('A list after the paragraphs, or none.'),+ }),+ )+ .min(2)+ .max(12),+ faqHeading: z.string().describe('The FAQ section heading, in the page language, or "".'),+ faq: z.array(z.object({ question: z.string(), answer: z.string() })).max(8),+});++const WRITE_SYSTEM_PROMPT = `You are the Content Agent for Answer Engine Optimization (AEO). You write one web page so AI assistants (ChatGPT, Perplexity, Gemini, Copilot, Google's AI Overviews) understand it, trust it and cite it. A person reviews it before it is published.++How to write:+- Answer first: the opening paragraphs answer the page's main question directly.+- Follow the outline when there is one; each H2 answers one of the questions or AI searches given.+- Short paragraphs and plain sentences. Lists where a reader compares or follows steps.+- Follow every rule listed, and the writer's own rules.+- Use only facts from the brand and the brief. Never invent numbers, prices, dates, names, customers, sources or quotes. When the page needs a fact you don't have, write a placeholder in square brackets, e.g. [price], [figure, source, year].+- Plain text in every field: no HTML, no Markdown.+- Write in the language asked for.`;++const SUGGEST_SYSTEM_PROMPT = `You are the Content Agent for Answer Engine Optimization (AEO). You improve one existing web page so AI assistants cite it, by suggesting changes that a person reviews.++Rules for your suggestions:+- Make the page answer the questions and AI searches listed, follow the brief when there is one, and meet the rules listed.+- A replace changes words inside one passage: copy "before" exactly as that passage has it (a phrase or a sentence), and write "after" as plain text that fits in its place.+- An insert adds new blocks after a passage, as simple HTML (h2, h3, p, ul, ol, li, strong, em): a missing section, a direct answer, an FAQ.+- Never change a passage marked LOCKED: AI assistants quote its wording today. You may insert after it.+- Put the keys of the rules a change meets in "rules" (none when it meets none).+- Use only facts from the page and the brand. Never invent numbers, prices, dates, names, sources or quotes; write a placeholder in square brackets instead, e.g. [figure, source, year].+- Keep the page's voice. The most useful changes first, at most ${MAX_AGENT_SUGGESTIONS}.+- "reason" says in a few words what the change does, e.g. "answer the search 'x' (fan-out)".+- Write in the language asked for.`;++const ENTITIES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };+const escapeText = (value) => String(value).replace(/[&<>"']/g, (c) => ENTITIES[c]);+const clean = (value) => String(value ?? '').trim();++/**+ * The written page as the editor's HTML: an H1, the opening paragraphs, an+ * H2 per section with its paragraphs and list, and the FAQ as H3 questions.+ * Every text is escaped: the model writes text, never markup.+ */+export function renderPage(page) {+ const p = (text) => (clean(text) ? `<p>${escapeText(clean(text))}</p>` : '');+ const parts = [`<h1>${escapeText(clean(page.title))}</h1>`, ...page.intro.map(p)];+ for (const section of page.sections) {+ if (!clean(section.heading)) continue;+ parts.push(`<h2>${escapeText(clean(section.heading))}</h2>`, ...section.paragraphs.map(p));+ const bullets = section.bullets.filter((b) => clean(b));+ if (bullets.length) {+ parts.push(`<ul>${bullets.map((b) => `<li>${p(b)}</li>`).join('')}</ul>`);+ }+ }+ const faq = page.faq.filter((item) => clean(item.question) && clean(item.answer));+ if (faq.length && clean(page.faqHeading)) {+ parts.push(`<h2>${escapeText(clean(page.faqHeading))}</h2>`);+ for (const item of faq) {+ parts.push(`<h3>${escapeText(clean(item.question))}</h3>`, p(item.answer));+ }+ }+ return parts.filter(Boolean).join('');+}++const list = (items) => (items.length ? items.map((item) => `- ${item}`).join('\n') : '- none');++/** The brief as the model reads it: the draft's own, else its opportunity's. */+export function briefText(draftBrief, opportunityBrief) {+ if (draftBrief?.outline?.length || draftBrief?.goal) {+ const sections = draftBrief.outline.map(+ (s) =>+ `${s.heading}${s.keyPoints?.length ? `: ${s.keyPoints.join('; ')}` : ''}${s.fanout ? ` (answers the AI search "${s.fanout}")` : ''}`,+ );+ return `Goal: ${draftBrief.goal || '—'}+Audience: ${draftBrief.audience || '—'}+Outline:+${list(sections)}+Keywords: ${(draftBrief.keywords ?? []).join(', ') || '—'}`;+ }+ if (opportunityBrief?.outline?.length) {+ const sections = opportunityBrief.outline.map(+ (s) => `${s.heading}${s.keyPoints?.length ? `: ${s.keyPoints.join('; ')}` : ''}`,+ );+ return `Suggested title: ${opportunityBrief.suggestedTitle || '—'}+Outline:+${list(sections)}+Keywords: ${(opportunityBrief.targetKeywords ?? []).join(', ') || '—'}+Call to action: ${opportunityBrief.callToAction || '—'}`;+ }+ return 'No brief: plan the sections from the questions and AI searches below.';+}++/** What the model is told, for a new page or an existing one. */+export function buildWritePrompt({+ brand,+ draft,+ prompts,+ brief,+ input,+ passages,+ more = false,+ lockedKeys,+}) {+ const { sources } = input;+ const rules = input.rules.map((r) => `${r.key}: ${r.name}${r.detail ? ` — ${r.detail}` : ''}`);+ const own = input.textRules.map((text) => `- ${text}`);+ const page = passages+ ? `The page, passage by passage:\n${passages+ .map((p, i) => {+ const locked = lockedKeys.has(passageKey(p.text)) ? ', LOCKED' : '';+ return `[${i + 1}] (${p.tag}${locked}) ${p.text}`;+ })+ .join(+ '\n',+ )}${more ? '\n(The page goes on; suggest changes only to the passages above.)' : ''}`+ : `Write a new page titled about: ${draft.title || 'the questions below'}.`;+ return `Brand: ${brand?.name || 'Unknown'}+Industry: ${brand?.industry || 'Not specified'}+Description: ${brand?.description || 'N/A'}++Page type: ${draft.page_type || 'not set'}+Length: about ${sources.length} characters.++Brief:+${brief}++Questions the page must answer (tracked prompts):+${list(prompts)}++AI searches (fan-outs) run while answering them, the most searched first:+${list(sources.fanouts.map((f) => `"${f.query}"`))}++Google searches people use (Search Console):+${list(sources.queries)}++Pages AI cites for these questions today (answer better than them, never copy them):+${list(sources.pages.map((p) => p.url))}++Rules (key: rule — what it asks):+${list(rules)}+${own.length ? `\nThe writer's own rules:\n${own.join('\n')}\n` : ''}+${page}++Write in ${getLanguageName(brand?.language)}.`;+}++/**+ * Whether the agent is writing another of the organization's drafts now (a+ * 'writing' left by a stopped server doesn't count).+ */+async function organizationWriting(organizationId, draftId, staleBefore) {+ const { data, error } = await supabaseAdmin+ .from('content_drafts')+ .select('id, brands!inner(organization_id)')+ .eq('brands.organization_id', organizationId)+ .eq('agent_state', 'writing')+ .gt('agent_state_at', staleBefore)+ .neq('id', draftId)+ .limit(1);+ if (error) throw error;+ return (data ?? []).length > 0;+}++/**+ * Starts the agent on a draft: checks it is the brand's and still a draft,+ * that the agent isn't already on it or on another of the organization's+ * drafts, the AI usage budget and the model; marks it 'writing' and runs the+ * model in the background. Throws with `.status` 404 for a draft outside the+ * brand, 409 (code 'not_draft', 'writing' or 'org_writing'), PlanLimitError+ * once the budget is spent, and the provider's error when the model isn't+ * set up — all before anything runs.+ */+export async function startDraftWriting({ draftId, brandId, input }) {+ const { data: draft, error: draftError } = await supabaseAdmin+ .from('content_drafts')+ .select(+ 'id, brand_id, title, page_type, method, source_url, body_html, status, agent_state, agent_state_at, opportunity_id, brief, action_id',+ )+ .eq('id', draftId)+ .maybeSingle();+ if (draftError) throw draftError;+ if (!draft || draft.brand_id !== brandId) {+ throw Object.assign(new Error('Draft not found'), { status: 404 });+ }+ if (draft.status !== 'draft') {+ throw Object.assign(new Error('Only a draft can be written'), {+ status: 409,+ code: 'not_draft',+ });+ }+ const staleBefore = new Date(Date.now() - WRITING_STALE_MS).toISOString();+ if (+ draft.agent_state === 'writing' &&+ new Date(draft.agent_state_at).getTime() > Date.now() - WRITING_STALE_MS+ ) {+ throw Object.assign(new Error('The agent is already writing it'), {+ status: 409,+ code: 'writing',+ });+ }+ // An existing page's run leaves a new batch, which would hide the open+ // one (the editor shows the latest), as Fix open rules and the API refuse.+ if (draft.method === 'optimize' && (await hasOpenSuggestions(draftId))) {+ throw Object.assign(new Error('Decide the open suggestions first'), {+ status: 409,+ code: 'open_suggestions',+ });+ }++ const { data: brand, error: brandError } = await supabaseAdmin+ .from('brands')+ .select('name, industry, description, organization_id, language')+ .eq('id', brandId)+ .single();+ if (brandError) throw brandError;+ const modelId = contentBriefModelId();+ await enforceImproveQuota(brand.organization_id, modelId);+ if (await organizationWriting(brand.organization_id, draftId, staleBefore)) {+ throw Object.assign(new Error('The agent is writing another draft'), {+ status: 409,+ code: 'org_writing',+ });+ }+ // A provider that isn't set up fails here, before anything is claimed.+ const model = resolveModel(modelId);++ // Claimed once: a second start meanwhile finds it writing.+ const { data: claimed, error: claimError } = await supabaseAdmin+ .from('content_drafts')+ .update({ agent_state: 'writing', agent_state_at: new Date().toISOString() })+ .eq('id', draftId)+ .eq('status', 'draft')+ .or(`agent_state.is.null,agent_state.eq.failed,agent_state_at.lt."${staleBefore}"`)+ .select('id')+ .maybeSingle();+ if (claimError) throw claimError;+ if (!claimed) {+ throw Object.assign(new Error('The agent is already writing it'), {+ status: 409,+ code: 'writing',+ });+ }++ runDraftWriting({ draft, brand, model, modelId, input }).catch((err) =>+ logger.error({ err, draftId }, '[content-writer] run failed'),+ );+ return { started: true };+}++/**+ * The agent's state as it ends, only while it is still the run's to end;+ * with `draftOnly`, only while the draft is still a draft (not marked ready+ * meanwhile). Answers whether it ended it.+ */+async function finish(draftId, values, { draftOnly = false } = {}) {+ let query = supabaseAdmin+ .from('content_drafts')+ .update({ ...values, agent_state_at: new Date().toISOString() })+ .eq('id', draftId)+ .eq('agent_state', 'writing');+ if (draftOnly) query = query.eq('status', 'draft');+ const { data, error } = await query.select('id').maybeSingle();+ if (error) throw error;+ return !!data;+}++/** A draft that left Draft during the run keeps its page; the agent lets go of it. */+async function letGo(draftId) {+ await finish(draftId, { agent_state: null });+ logger.info({ draftId }, '[content-writer] the draft left Draft during the run');+ return { skipped: true };+}++/**+ * The run itself: the page written, or the suggestions left, and the draft+ * In review; 'failed' when the model fails or leaves nothing to review.+ */+export async function runDraftWriting({ draft, brand, model, modelId, input }) {+ try {+ const [promptsRes, opportunityRes] = await Promise.all([+ input.sources.promptIds.length+ ? supabaseAdmin+ // Through the prompt's set, not its topic: a prompt may have no topic.+ .from('prompts')+ .select('id, text, prompt_sets!inner(brand_id)')+ .in('id', input.sources.promptIds)+ .eq('prompt_sets.brand_id', draft.brand_id)+ : Promise.resolve({ data: [], error: null }),+ draft.opportunity_id && !draft.brief+ ? supabaseAdmin+ .from('content_opportunities')+ .select('brief')+ .eq('id', draft.opportunity_id)+ .eq('brand_id', draft.brand_id)+ .maybeSingle()+ : Promise.resolve({ data: null, error: null }),+ ]);+ if (promptsRes.error) throw promptsRes.error;+ if (opportunityRes.error) throw opportunityRes.error;+ const prompts = (promptsRes.data ?? []).map((p) => p.text);+ const brief = briefText(draft.brief, opportunityRes.data?.brief);++ if (draft.method === 'create') {+ const { object, usage } = await generateObject({+ model,+ schema: pageSchema,+ system: WRITE_SYSTEM_PROMPT,+ prompt: buildWritePrompt({ brand, draft, prompts, brief, input }),+ abortSignal: AbortSignal.timeout(CALL_TIMEOUT_MS),+ });+ await recordUsage({+ organizationId: brand.organization_id,+ draftId: draft.id,+ modelId,+ usage,+ });+ const title = clean(object.title).slice(0, 300) || draft.title;+ // Try again over a page the person has written in: History keeps it+ // first. Their saves wait while the agent writes (saveContentDraft).+ if (draftPassages(draft.body_html).some((p) => p.tag !== 'h1')) {+ const { error: keepError } = await supabaseAdmin.rpc('content_draft_snapshot', {+ p_draft_id: draft.id,+ p_origin: 'agent_before',+ });+ if (keepError) throw keepError;+ }+ const written = await finish(+ draft.id,+ {+ title,+ body_html: renderPage({ ...object, title }),+ status: 'in_review',+ author: 'agent',+ agent_state: null,+ },+ { draftOnly: true },+ );+ // Awaited here, so a failure to let go is caught below.+ return written ? { written: true } : await letGo(draft.id);+ }++ const { passages, more } = promptPassages(draftPassages(draft.body_html));+ if (!passages.length) throw new Error('The page has no text to improve');+ const lockedKeys = new Set(input.locked.map(passageKey));+ const { object, usage } = await generateObject({+ model,+ schema: suggestionsSchema,+ system: SUGGEST_SYSTEM_PROMPT,+ prompt: buildWritePrompt({ brand, draft, prompts, brief, input, passages, more, lockedKeys }),+ abortSignal: AbortSignal.timeout(CALL_TIMEOUT_MS),+ });+ await recordUsage({ organizationId: brand.organization_id, draftId: draft.id, modelId, usage });+ const rows = keepSuggestions(+ object.suggestions,+ passages,+ lockedKeys,+ new Set(input.rules.map((r) => r.key)),+ );+ if (!rows.length) throw new Error('The agent left no suggestion it could place');+ // A batch that landed during the run (Fix open rules, the API) stays the+ // one to decide: this one isn't added over it.+ if (await hasOpenSuggestions(draft.id)) {+ logger.info(+ { draftId: draft.id },+ '[content-writer] open suggestions came in during the run',+ );+ return await letGo(draft.id);+ }+ const batchId = randomUUID();+ const { error: insertError } = await supabaseAdmin.from('content_draft_suggestions').insert(+ rows.map((row, position) => ({+ ...row,+ draft_id: draft.id,+ batch_id: batchId,+ action_id: draft.action_id ?? null,+ position,+ })),+ );+ if (insertError) throw insertError;+ if (+ !(await finish(draft.id, { status: 'in_review', agent_state: null }, { draftOnly: true }))+ ) {+ // Nobody reviews suggestions on a page already marked ready.+ const { error: dropError } = await supabaseAdmin+ .from('content_draft_suggestions')+ .delete()+ .eq('batch_id', batchId);+ if (dropError) throw dropError;+ return await letGo(draft.id);+ }+ return { suggestions: rows.length };+ } catch (err) {+ logger.error({ err, draftId: draft.id }, '[content-writer] the agent could not finish');+ await finish(draft.id, { agent_state: 'failed' }).catch((finishErr) =>+ logger.error({ err: finishErr, draftId: draft.id }, '[content-writer] state not saved'),+ );+ return { failed: true };+ }+}diff --git a/server/src/lib/content-writer.test.js b/server/src/lib/content-writer.test.jsnew file mode 100644index 000000000..284422370--- /dev/null+++ b/server/src/lib/content-writer.test.js@@ -0,0 +1,419 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * Start's Agent (Content Editor CE-015): the Content Agent writes a new page+ * whole, or leaves suggestions on an existing one, in the background, and+ * the draft goes to In review — or says it failed.+ */++const BRAND = '33333333-3333-3333-3333-333333333333';+const DRAFT = '77777777-7777-7777-7777-777777777777';++let rows;+let writes;+let claimed;+let finished;+let rpcCalls;+let reads;+const generateObject = vi.fn();+const enforceImproveQuota = vi.fn();++vi.mock('../config/supabase.js', () => ({+ default: {+ rpc: async (name, args) => (rpcCalls.push([name, args]), { data: 'v1', error: null }),+ from: (table) => {+ const op = { table, kind: 'select', filters: [] };+ const result = () => {+ if (op.kind === 'select') {+ reads.push(op);+ // The organization's other drafts being written.+ if (op.filters.some(([col]) => col === 'brands.organization_id')) {+ return { data: rows.writingInOrg ?? [], error: null };+ }+ return { data: rows[table] ?? null, error: null };+ }+ writes.push(op);+ // The claim and the finish read back their row, when they matched one.+ const claim = op.kind === 'update' && op.value.agent_state === 'writing';+ return { data: claim ? claimed : op.kind === 'update' ? finished : null, error: null };+ };+ const chain = {+ select: () => chain,+ eq: (col, v) => (op.filters.push([col, v]), chain),+ neq: (col, v) => (op.filters.push([`${col}<>`, v]), chain),+ gt: (col, v) => (op.filters.push([`${col}>`, v]), chain),+ in: (col, v) => (op.filters.push([col, v]), chain),+ or: (v) => (op.filters.push(['or', v]), chain),+ limit: () => chain,+ update: (value) => ((op.kind = 'update'), (op.value = value), chain),+ insert: (value) => ((op.kind = 'insert'), (op.value = value), chain),+ delete: () => ((op.kind = 'delete'), chain),+ maybeSingle: async () => result(),+ single: async () => result(),+ then: (resolve, reject) => Promise.resolve(result()).then(resolve, reject),+ };+ return chain;+ },+ },+}));+vi.mock('ai', () => ({ generateObject: (...args) => generateObject(...args) }));+const resolveModel = vi.hoisted(() => vi.fn((id) => `model:${id}`));+vi.mock('./ai-provider.js', () => ({ resolveModel }));+vi.mock('./plan-guard.js', async (importOriginal) => ({+ ...(await importOriginal()),+ enforceImproveQuota: (...args) => enforceImproveQuota(...args),+}));+vi.mock('./logger.js', () => ({ logger: { error: vi.fn(), info: vi.fn() } }));+const hasOpenSuggestions = vi.hoisted(() => vi.fn());+vi.mock('./content-agent.js', async (importOriginal) => ({+ ...(await importOriginal()),+ hasOpenSuggestions: (...args) => hasOpenSuggestions(...args),+}));++const { briefText, renderPage, runDraftWriting, startDraftWriting } =+ await import('./content-writer.js');+const { passageKey } = await import('./content-agent.js');+const { PlanLimitError } = await import('./plan-guard.js');++const input = (over = {}) => ({+ sources: {+ promptIds: ['p1'],+ fanouts: [{ query: 'pour over ratio', platforms: ['copilot-web'] }],+ pages: [],+ queries: [],+ headings: [],+ length: 3000,+ },+ rules: [{ key: 'faq', name: 'FAQ with 5 questions', detail: 'aim: 5' }],+ textRules: [],+ locked: [],+ ...over,+});++const draftRow = (over = {}) => ({+ id: DRAFT,+ brand_id: BRAND,+ title: 'How to brew pour-over coffee',+ page_type: 'guide',+ method: 'create',+ source_url: null,+ body_html: '<h1>How to brew pour-over coffee</h1>',+ status: 'draft',+ agent_state: null,+ agent_state_at: null,+ opportunity_id: null,+ brief: null,+ action_id: null,+ ...over,+});+const brand = {+ name: 'Acme Coffee',+ industry: 'Coffee',+ description: 'Beans',+ organization_id: 'org-1',+ language: 'en',+};++const page = {+ title: 'How to brew pour-over coffee',+ intro: ['Use 15 g of coffee for 250 g of water.'],+ sections: [+ { heading: 'What you need', paragraphs: ['A dripper & a filter.'], bullets: ['Kettle', ''] },+ { heading: 'Step by step', paragraphs: ['Rinse, bloom, pour.'], bullets: [] },+ ],+ faqHeading: 'FAQ',+ faq: [{ question: 'How long?', answer: '[time] minutes.' }],+};++beforeEach(() => {+ writes = [];+ rpcCalls = [];+ reads = [];+ claimed = { id: DRAFT };+ finished = { id: DRAFT };+ rows = { content_drafts: draftRow(), brands: brand, prompts: [{ id: 'p1', text: 'ratio?' }] };+ generateObject.mockReset().mockResolvedValue({+ object: page,+ usage: { inputTokens: 10, outputTokens: 20 },+ });+ enforceImproveQuota.mockReset().mockResolvedValue(undefined);+ hasOpenSuggestions.mockReset().mockResolvedValue(false);+});++const draftUpdates = () =>+ writes.filter((w) => w.table === 'content_drafts' && w.kind === 'update').map((w) => w.value);++describe('renderPage', () => {+ it('writes the editor’s HTML from text, escaped', () => {+ expect(renderPage({ ...page, title: 'Pour-over <b>101</b>' })).toBe(+ '<h1>Pour-over <b>101</b></h1>' ++ '<p>Use 15 g of coffee for 250 g of water.</p>' ++ '<h2>What you need</h2><p>A dripper & a filter.</p><ul><li><p>Kettle</p></li></ul>' ++ '<h2>Step by step</h2><p>Rinse, bloom, pour.</p>' ++ '<h2>FAQ</h2><h3>How long?</h3><p>[time] minutes.</p>',+ );+ });+});++describe('briefText', () => {+ it('reads the draft’s brief, else its opportunity’s', () => {+ const own = briefText(+ {+ goal: 'Sell beans',+ audience: 'Home brewers',+ outline: [{ heading: 'Ratio', keyPoints: ['15:250'], fanout: 'pour over ratio' }],+ keywords: ['pour over'],+ },+ { outline: [{ heading: 'Ignored' }] },+ );+ expect(own).toContain('Goal: Sell beans');+ expect(own).toContain('- Ratio: 15:250 (answers the AI search "pour over ratio")');+ expect(own).not.toContain('Ignored');++ expect(+ briefText(null, {+ suggestedTitle: 'Pour-over guide',+ outline: [{ heading: 'Gear', keyPoints: [] }],+ targetKeywords: [],+ callToAction: 'Shop',+ }),+ ).toContain('- Gear');+ expect(briefText(null, null)).toMatch(/^No brief/);+ });+});++describe('startDraftWriting', () => {+ it('claims the draft, answers at once, and writes the new page for review', async () => {+ await expect(+ startDraftWriting({ draftId: DRAFT, brandId: BRAND, input: input() }),+ ).resolves.toEqual({ started: true });+ expect(enforceImproveQuota).toHaveBeenCalledWith('org-1', expect.any(String));+ expect(draftUpdates()[0]).toMatchObject({ agent_state: 'writing' });++ await vi.waitFor(() => expect(draftUpdates()).toHaveLength(2));+ expect(draftUpdates()[1]).toMatchObject({+ title: 'How to brew pour-over coffee',+ status: 'in_review',+ author: 'agent',+ agent_state: null,+ });+ expect(draftUpdates()[1].body_html).toMatch(+ /^<h1>How to brew pour-over coffee<\/h1><p>Use 15 g/,+ );+ const finish = writes.filter((w) => w.table === 'content_drafts')[1];+ expect(finish.filters).toContainEqual(['agent_state', 'writing']);+ // Only while it is still a draft: one marked ready meanwhile keeps its page.+ expect(finish.filters).toContainEqual(['status', 'draft']);+ // A new page holds only its H1: nothing of the person's to keep first.+ expect(rpcCalls).toEqual([]);+ expect(writes.some((w) => w.table === 'prompt_improve_usage')).toBe(true);+ const { prompt } = generateObject.mock.calls[0][0];+ expect(prompt).toContain('- ratio?');+ expect(prompt).toContain('- "pour over ratio"');+ expect(prompt).toContain('- faq: FAQ with 5 questions — aim: 5');+ });++ it('refuses another brand’s draft, one past Draft, or one the agent is on — before charging', async () => {+ const start = () => startDraftWriting({ draftId: DRAFT, brandId: BRAND, input: input() });+ rows.content_drafts = draftRow({ brand_id: 'other' });+ await expect(start()).rejects.toMatchObject({ status: 404 });+ rows.content_drafts = draftRow({ status: 'in_review' });+ await expect(start()).rejects.toMatchObject({ status: 409, code: 'not_draft' });+ rows.content_drafts = draftRow({+ agent_state: 'writing',+ agent_state_at: new Date().toISOString(),+ });+ await expect(start()).rejects.toMatchObject({ status: 409, code: 'writing' });+ expect(enforceImproveQuota).not.toHaveBeenCalled();+ expect(writes).toEqual([]);++ // A 'writing' left long ago can start again; a start that lost the claim can't.+ rows.content_drafts = draftRow({+ agent_state: 'writing',+ agent_state_at: '2026-01-01T00:00:00Z',+ });+ claimed = null;+ await expect(start()).rejects.toMatchObject({ status: 409, code: 'writing' });+ expect(generateObject).not.toHaveBeenCalled();+ });++ it('waits on an existing page while its suggestions are open, before charging', async () => {+ rows.content_drafts = draftRow({ method: 'optimize', source_url: 'https://acme.example/x' });+ hasOpenSuggestions.mockResolvedValue(true);+ await expect(+ startDraftWriting({ draftId: DRAFT, brandId: BRAND, input: input() }),+ ).rejects.toMatchObject({ status: 409, code: 'open_suggestions' });+ expect(hasOpenSuggestions).toHaveBeenCalledWith(DRAFT);+ expect(enforceImproveQuota).not.toHaveBeenCalled();+ expect(writes).toEqual([]);++ // A new page is written whole: its run adds no batch.+ rows.content_drafts = draftRow();+ hasOpenSuggestions.mockClear();+ await expect(+ startDraftWriting({ draftId: DRAFT, brandId: BRAND, input: input() }),+ ).resolves.toEqual({ started: true });+ expect(hasOpenSuggestions).not.toHaveBeenCalled();+ });++ it('writes one of the organization’s drafts at a time', async () => {+ rows.writingInOrg = [{ id: 'other-draft' }];+ await expect(+ startDraftWriting({ draftId: DRAFT, brandId: BRAND, input: input() }),+ ).rejects.toMatchObject({ status: 409, code: 'org_writing' });+ expect(writes).toEqual([]);+ expect(generateObject).not.toHaveBeenCalled();+ });++ it('fails at once when the model isn’t set up, claiming nothing', async () => {+ resolveModel.mockImplementationOnce(() => {+ throw new Error('Provider "google" is not configured');+ });+ await expect(+ startDraftWriting({ draftId: DRAFT, brandId: BRAND, input: input() }),+ ).rejects.toThrow('not configured');+ expect(writes).toEqual([]);+ });++ it('stops at the budget', async () => {+ enforceImproveQuota.mockRejectedValue(new PlanLimitError('used up', 429));+ await expect(+ startDraftWriting({ draftId: DRAFT, brandId: BRAND, input: input() }),+ ).rejects.toBeInstanceOf(PlanLimitError);+ expect(writes).toEqual([]);+ });+});++describe('runDraftWriting on a new page', () => {+ const run = (draft) =>+ runDraftWriting({ draft, brand, model: 'model:m', modelId: 'm', input: input() });++ it('keeps the person’s text in History before writing over it, and reads prompts by their set', async () => {+ const tried = draftRow({+ agent_state: 'failed',+ body_html: '<h1>How to brew pour-over coffee</h1><p>My own notes.</p>',+ });+ await expect(run(tried)).resolves.toEqual({ written: true });+ expect(rpcCalls).toEqual([+ ['content_draft_snapshot', { p_draft_id: DRAFT, p_origin: 'agent_before' }],+ ]);+ // A prompt without a topic is the brand's too.+ expect(reads.find((r) => r.table === 'prompts').filters).toContainEqual([+ 'prompt_sets.brand_id',+ BRAND,+ ]);+ });++ it('leaves a draft marked ready during the run as it is', async () => {+ finished = null;+ await expect(run(draftRow())).resolves.toEqual({ skipped: true });+ // The page wasn't written; the agent let go of the draft.+ expect(draftUpdates().at(-1)).toEqual({+ agent_state: null,+ agent_state_at: expect.any(String),+ });+ });+});++describe('runDraftWriting on an existing page', () => {+ const QUOTED = 'Pour-over coffee tastes cleaner than a French press.';+ const existing = draftRow({+ method: 'optimize',+ source_url: 'https://acme.example/pour-over',+ body_html: `<h1>Pour-over</h1><p>${QUOTED}</p><p>Use good coffee.</p>`,+ action_id: 'act-1',+ });+ const run = (over = {}) =>+ runDraftWriting({+ draft: existing,+ brand,+ model: 'model:m',+ modelId: 'm',+ input: input({ locked: [passageKey(QUOTED)], ...over }),+ });++ it('leaves its suggestions for review, never on a locked passage', async () => {+ generateObject.mockResolvedValue({+ object: {+ suggestions: [+ {+ kind: 'replace',+ passage: 2,+ before: 'cleaner',+ after: 'brighter',+ reason: 'x',+ rules: [],+ },+ {+ kind: 'replace',+ passage: 3,+ before: 'good coffee',+ after: '15 g of coffee',+ reason: 'answer the ratio search',+ rules: ['faq'],+ },+ ],+ },+ usage: {},+ });+ await expect(run()).resolves.toEqual({ suggestions: 1 });+ const batch = writes.find((w) => w.table === 'content_draft_suggestions').value;+ expect(batch).toEqual([+ expect.objectContaining({+ draft_id: DRAFT,+ action_id: 'act-1',+ block_text: 'Use good coffee.',+ before_text: 'good coffee',+ position: 0,+ }),+ ]);+ expect(generateObject.mock.calls[0][0].prompt).toContain(`[2] (p, LOCKED) ${QUOTED}`);+ expect(draftUpdates()).toEqual([+ { status: 'in_review', agent_state: null, agent_state_at: expect.any(String) },+ ]);+ });++ it('adds no batch over one that came in during the run', async () => {+ generateObject.mockResolvedValue({+ object: {+ suggestions: [+ { kind: 'replace', passage: 3, before: 'good', after: 'fresh', reason: 'x', rules: [] },+ ],+ },+ usage: {},+ });+ hasOpenSuggestions.mockResolvedValue(true);+ await expect(run()).resolves.toEqual({ skipped: true });+ expect(writes.some((w) => w.table === 'content_draft_suggestions')).toBe(false);+ expect(draftUpdates()).toEqual([{ agent_state: null, agent_state_at: expect.any(String) }]);+ });++ it('drops its suggestions when the draft was marked ready during the run', async () => {+ generateObject.mockResolvedValue({+ object: {+ suggestions: [+ { kind: 'replace', passage: 3, before: 'good', after: 'fresh', reason: 'x', rules: [] },+ ],+ },+ usage: {},+ });+ finished = null;+ await expect(run()).resolves.toEqual({ skipped: true });+ const batch = writes.find(+ (w) => w.table === 'content_draft_suggestions' && w.kind === 'insert',+ );+ const drop = writes.find((w) => w.table === 'content_draft_suggestions' && w.kind === 'delete');+ expect(drop.filters).toEqual([['batch_id', batch.value[0].batch_id]]);+ });++ it('says it failed when the model fails or leaves nothing to place', async () => {+ generateObject.mockResolvedValue({ object: { suggestions: [] }, usage: {} });+ await expect(run()).resolves.toEqual({ failed: true });+ generateObject.mockRejectedValue(new Error('timeout'));+ await expect(run()).resolves.toEqual({ failed: true });+ expect(draftUpdates()).toEqual([+ { agent_state: 'failed', agent_state_at: expect.any(String) },+ { agent_state: 'failed', agent_state_at: expect.any(String) },+ ]);+ });+});diff --git a/server/src/routes/content-drafts.js b/server/src/routes/content-drafts.jsindex e3275c690..555b26976 100644--- a/server/src/routes/content-drafts.js+++ b/server/src/routes/content-drafts.js@@ -3,13 +3,14 @@ import { z } from 'zod';import { assertBrandAccess } from '../lib/access.js';import { fixDraftRules, fixRulesInput } from '../lib/content-agent.js';import { rebuildDraftBrief, rebuildSources } from '../lib/content-brief.js';+import { startDraftWriting, writeDraftInput } from '../lib/content-writer.js';import { PlanLimitError } from '../lib/plan-guard.js';/*** Content Editor drafts: Rebuild outline in the editor's Brief tab writes* the draft's brief from the sources the person kept (CE-007); Fix open* rules with agent leaves the Content Agent's suggestions for review- * (CE-018).+ * (CE-018); Start's Agent has the Content Agent do the page (CE-015).*/const router = Router();@@ -90,4 +91,42 @@ router.post('/:draftId/suggestions', async (req, res) => {}});+const writeBody = writeDraftInput.extend({ brandId: z.guid() });++/**+ * POST /api/content-drafts/:draftId/write+ * Body: { brandId, sources, rules, textRules, locked }+ * Answers 202 { started: true } at once: the agent runs in the background+ * and the draft shows where it is (agent_state). 409 when the draft isn't a+ * draft any more (code not_draft), the agent is on it (code writing) or on+ * another of the organization's drafts (code org_writing), or an existing+ * page's suggestions are still open (code open_suggestions).+ */+router.post('/:draftId/write', async (req, res) => {+ const draftId = z.guid().safeParse(req.params.draftId);+ const parsed = writeBody.safeParse(req.body ?? {});+ if (!draftId.success || !parsed.success) {+ return res.status(400).json({ error: 'Invalid request', code: 'invalid' });+ }+ const { brandId, ...input } = parsed.data;+ try {+ await assertBrandAccess(brandId, req.user.id);+ const result = await startDraftWriting({ draftId: draftId.data, brandId, input });+ return res.status(202).json(result);+ } 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 agent write error');+ return res.status(502).json({ error: 'The agent could not start', code: 'failed' });+ }+});+export default router;diff --git a/server/src/routes/content-drafts.test.js b/server/src/routes/content-drafts.test.jsindex d35e0badc..a4dcec371 100644--- a/server/src/routes/content-drafts.test.js+++ b/server/src/routes/content-drafts.test.js@@ -3,13 +3,15 @@ import express from 'express';/*** POST /api/content-drafts/:draftId/brief (CE-007): Rebuild outline;- * POST /api/content-drafts/:draftId/suggestions (CE-018): Fix open rules with agent.+ * POST /api/content-drafts/:draftId/suggestions (CE-018): Fix open rules with agent; and+ * POST /api/content-drafts/:draftId/write (CE-015): Start's Agent.*/const BRAND = '33333333-3333-3333-3333-333333333333';const DRAFT = '77777777-7777-7777-7777-777777777777';const rebuildDraftBrief = vi.fn();+const startDraftWriting = vi.fn();const fixDraftRules = vi.fn();const assertBrandAccess = vi.fn();@@ -19,6 +21,10 @@ vi.mock('../lib/content-brief.js', async (importOriginal) => ({...(await importOriginal()),rebuildDraftBrief: (...args) => rebuildDraftBrief(...args),}));+vi.mock('../lib/content-writer.js', async (importOriginal) => ({+ ...(await importOriginal()),+ startDraftWriting: (...args) => startDraftWriting(...args),+}));vi.mock('../lib/content-agent.js', async (importOriginal) => ({...(await importOriginal()),fixDraftRules: (...args) => fixDraftRules(...args),@@ -33,6 +39,7 @@ let baseUrl;beforeEach(async () => {rebuildDraftBrief.mockReset().mockResolvedValue({ goal: 'g', outline: [] });+ startDraftWriting.mockReset().mockResolvedValue({ started: true });fixDraftRules.mockReset().mockResolvedValue({ count: 2, batchId: 'b1' });assertBrandAccess.mockReset().mockResolvedValue({});const app = express();@@ -118,6 +125,51 @@ describe('POST /api/content-drafts/:draftId/brief', () => {});});+describe('POST /api/content-drafts/:draftId/write', () => {+ const write = (body, draftId = DRAFT) =>+ fetch(`${baseUrl}/${draftId}/write`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });+ const rules = [{ key: 'faq', name: 'FAQ with 5 questions', detail: 'aim: 5' }];++ it('starts the agent and answers at once', async () => {+ const res = await write({ brandId: BRAND, sources, rules, textRules: ['Say we'] });+ expect(res.status).toBe(202);+ await expect(res.json()).resolves.toEqual({ started: true });+ expect(assertBrandAccess).toHaveBeenCalledWith(BRAND, 'u1');+ expect(startDraftWriting).toHaveBeenCalledWith({+ draftId: DRAFT,+ brandId: BRAND,+ input: { sources, rules, textRules: ['Say we'], locked: [] },+ });+ });++ it('refuses a malformed request, and says why it didn’t start', async () => {+ // A length out of range is brought into it (rebuildSources); a malformed prompt id isn't.+ let res = await write({ brandId: BRAND, sources: { ...sources, promptIds: ['p1'] } });+ expect(res.status).toBe(400);+ expect(startDraftWriting).not.toHaveBeenCalled();++ startDraftWriting.mockRejectedValueOnce(+ Object.assign(new Error('busy'), { status: 409, code: 'writing' }),+ );+ res = await write({ brandId: BRAND, sources });+ expect(res.status).toBe(409);+ await expect(res.json()).resolves.toMatchObject({ code: 'writing' });++ startDraftWriting.mockRejectedValueOnce(new PlanLimitError('used up', 429));+ res = await write({ brandId: BRAND, sources });+ expect(res.status).toBe(429);+ await expect(res.json()).resolves.toMatchObject({ code: 'ai_budget' });++ startDraftWriting.mockRejectedValueOnce(new Error('db down'));+ res = await write({ brandId: BRAND, sources });+ expect(res.status).toBe(502);+ });+});+const fix = (body) =>fetch(`${baseUrl}/${DRAFT}/suggestions`, {method: 'POST',diff --git a/supabase/migrations/00219_content_draft_agent_state.sql b/supabase/migrations/00219_content_draft_agent_state.sqlnew file mode 100644index 000000000..67ee96a51--- /dev/null+++ b/supabase/migrations/00219_content_draft_agent_state.sql@@ -0,0 +1,72 @@+-- ============================================================================+-- 00219: the Content Agent writing a draft (Content Editor, CE-015)+-- ============================================================================+-- "Agent" in Start (spec v2 §5): the Content Agent writes the page, and the+-- person reviews it in Library › In review. The writing runs on the server+-- after Start closes, so the draft says where it is:+--+-- * content_drafts.agent_state: 'writing' while the agent works on it,+-- 'failed' when it couldn't finish (the person writes it, or tries+-- again), null otherwise. A 'writing' left by a server that stopped+-- reads as failed after a while (the app's WRITING_STALE_MS);+-- * content_drafts.agent_state_at: when it last changed.+--+-- Like the draft's author and action, they are the server's to write:+-- guard_content_draft_server_columns (00208) is redefined to keep members+-- from setting or changing them.++alter table public.content_drafts+ add column if not exists agent_state text,+ add column if not exists agent_state_at timestamptz;++alter table public.content_drafts+ drop constraint if exists content_drafts_agent_state_check;+alter table public.content_drafts+ add constraint content_drafts_agent_state_check+ check (agent_state is null or agent_state in ('writing', 'failed'));++comment on column public.content_drafts.agent_state is+ 'Content Editor (CE-015): writing while the Content Agent writes the draft, failed when it could not finish, else null. Server-set.';+comment on column public.content_drafts.agent_state_at is+ 'Content Editor (CE-015): when agent_state last changed. Server-set.';++create or replace function public.guard_content_draft_server_columns()+returns trigger+language plpgsql+set search_path = ''+as $$+begin+ -- A role that bypasses RLS is server-side (service role, migrations).+ if (select rolbypassrls from pg_catalog.pg_roles where rolname = current_user) then+ return new;+ end if;++ if tg_op = 'INSERT' then+ if new.score_before is not null or new.score_after is not null then+ raise exception 'content draft scores are set server-side'+ using errcode = '42501';+ end if;+ if new.action_id is not null then+ raise exception 'content draft action is set server-side'+ using errcode = '42501';+ end if;+ if new.agent_state is not null or new.agent_state_at is not null then+ raise exception 'content draft agent state is set server-side'+ using errcode = '42501';+ end if;+ elsif new.brand_id is distinct from old.brand_id+ or new.author is distinct from old.author+ or new.created_by is distinct from old.created_by+ or new.created_at is distinct from old.created_at+ or new.score_before is distinct from old.score_before+ or new.score_after is distinct from old.score_after+ or new.action_id is distinct from old.action_id+ or new.agent_state is distinct from old.agent_state+ or new.agent_state_at is distinct from old.agent_state_at+ then+ raise exception 'content draft column is managed server-side'+ using errcode = '42501';+ end if;+ return new;+end;+$$;diff --git a/supabase/schema.sql b/supabase/schema.sqlindex d7beb91f4..28d945bf4 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -30442,3 +30442,79 @@ create unique index if not exists content_drafts_action_work_keycomment on index public.content_drafts_action_work_key is'Content Editor (CE-022): one draft per action, method and page.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00219_content_draft_agent_state.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00219: the Content Agent writing a draft (Content Editor, CE-015)+-- ============================================================================+-- "Agent" in Start (spec v2 §5): the Content Agent writes the page, and the+-- person reviews it in Library › In review. The writing runs on the server+-- after Start closes, so the draft says where it is:+--+-- * content_drafts.agent_state: 'writing' while the agent works on it,+-- 'failed' when it couldn't finish (the person writes it, or tries+-- again), null otherwise. A 'writing' left by a server that stopped+-- reads as failed after a while (the app's WRITING_STALE_MS);+-- * content_drafts.agent_state_at: when it last changed.+--+-- Like the draft's author and action, they are the server's to write:+-- guard_content_draft_server_columns (00208) is redefined to keep members+-- from setting or changing them.++alter table public.content_drafts+ add column if not exists agent_state text,+ add column if not exists agent_state_at timestamptz;++alter table public.content_drafts+ drop constraint if exists content_drafts_agent_state_check;+alter table public.content_drafts+ add constraint content_drafts_agent_state_check+ check (agent_state is null or agent_state in ('writing', 'failed'));++comment on column public.content_drafts.agent_state is+ 'Content Editor (CE-015): writing while the Content Agent writes the draft, failed when it could not finish, else null. Server-set.';+comment on column public.content_drafts.agent_state_at is+ 'Content Editor (CE-015): when agent_state last changed. Server-set.';++create or replace function public.guard_content_draft_server_columns()+returns trigger+language plpgsql+set search_path = ''+as $$+begin+ -- A role that bypasses RLS is server-side (service role, migrations).+ if (select rolbypassrls from pg_catalog.pg_roles where rolname = current_user) then+ return new;+ end if;++ if tg_op = 'INSERT' then+ if new.score_before is not null or new.score_after is not null then+ raise exception 'content draft scores are set server-side'+ using errcode = '42501';+ end if;+ if new.action_id is not null then+ raise exception 'content draft action is set server-side'+ using errcode = '42501';+ end if;+ if new.agent_state is not null or new.agent_state_at is not null then+ raise exception 'content draft agent state is set server-side'+ using errcode = '42501';+ end if;+ elsif new.brand_id is distinct from old.brand_id+ or new.author is distinct from old.author+ or new.created_by is distinct from old.created_by+ or new.created_at is distinct from old.created_at+ or new.score_before is distinct from old.score_before+ or new.score_after is distinct from old.score_after+ or new.action_id is distinct from old.action_id+ or new.agent_state is distinct from old.agent_state+ or new.agent_state_at is distinct from old.agent_state_at+ then+ raise exception 'content draft column is managed server-side'+ using errcode = '42501';+ end if;+ return new;+end;+$$;+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 6e3745381..8b58e6a73 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3091,6 +3091,10 @@"openDetails": "Open topic details"},"contentEditor": {+ "agentState": {+ "writing": "Agent writing…",+ "failed": "Agent failed"+ },"library": {"title": "Library","description": "Everything you and the agents wrote or changed.",@@ -3222,7 +3226,19 @@"sentDescription": "Action #{number}: the draft waits in the Library for whoever writes it.","openAction": "Open","sendFailed": "The draft is in the Library, but it couldn't be sent to the Action Center.",- "openDraft": "Open draft"+ "openDraft": "Open draft",+ "startAgent": "Start the agent",+ "agentStarted": "Content Agent is drafting",+ "agentStartedDescription": "You'll review it in Library › In review.",+ "agentErrors": {+ "ai_budget": "This month's AI usage is spent, so the agent didn't start. The draft is in the Library for you to write.",+ "no_subscription": "The agent needs an active subscription, so it didn't start. The draft is in the Library for you to write.",+ "writing": "The agent is already working on this draft.",+ "org_writing": "The agent is writing another of your team's drafts, so it didn't start. The draft is in the Library for you to write.",+ "open_suggestions": "This page has suggestions waiting for review, so the agent didn't start. Accept or reject them in the editor first.",+ "not_draft": "This draft is no longer a draft, so the agent didn't start.",+ "failed": "The agent couldn't start. The draft is in the Library for you to write."+ }},"who": {"label": "Who does it",@@ -3232,8 +3248,7 @@},"agent": {"title": "Agent",- "hint": "Drafts, I review",- "soon": "Comes with the Content Agent"+ "hint": "Drafts, I review"},"team": {"title": "Team",@@ -3360,6 +3375,24 @@},"markedReady": "Marked ready. Publish it on your site when you're ready.","markedReadyAction": "Marked ready, and {count, plural, one {its task} other {its # tasks}} in Action AC-{no} {count, plural, one {is} other {are}} done. Publish it on your site when you're ready.",+ "agentWriting": {+ "title": "Content Agent is writing this page",+ "body": "It opens here for your review when it's done, usually within a minute or two. You can leave this page meanwhile; it waits in Library › In review."+ },+ "agentFailed": {+ "text": "The Content Agent couldn't finish this page. Write it yourself, or try again.",+ "retry": "Try again",+ "dismiss": "Close",+ "errors": {+ "ai_budget": "This month's AI usage is spent, so the agent didn't start.",+ "no_subscription": "The agent needs an active subscription. Choose a plan in Settings › Billing.",+ "writing": "The agent is already working on this draft.",+ "org_writing": "The agent is writing another of your team's drafts. Try again in a minute or two.",+ "open_suggestions": "Accept or reject the open suggestions first, then try again.",+ "not_draft": "This draft is no longer a draft, so the agent didn't start.",+ "failed": "The agent couldn't start. Try again in a moment."+ }+ },"actionBar": "This draft is the work of <link>Action AC-{no}</link>. Mark ready completes its task there.","actionBarDone": "This draft is the work of <link>Action AC-{no}</link>.","suggestions": {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 b117fc6e8..cb91255e3 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@@ -9,7 +9,7 @@ import StarterKit from '@tiptap/starter-kit';import { TableKit } from '@tiptap/extension-table';import Image from '@tiptap/extension-image';import { CharacterCount, Placeholder } from '@tiptap/extensions';-import { ArrowLeft, Check, Copy, Loader2, PanelRight, Target } from 'lucide-react';+import { ArrowLeft, Bot, Check, Copy, Loader2, PanelRight, Target, X } from 'lucide-react';import { Link } from '@/i18n/navigation';import { Button } from '@/components/ui/button';import { buttonVariants } from '@/components/ui/button-variants';@@ -32,7 +32,9 @@ import {markContentDraftReady,restoreDraftVersion,setContentDraftPageType,+ startAgentWriting,} from '@/lib/actions/content-drafts';+import { agentWriteRequest, useRuleDescriber } from '@/lib/content/agent-write';import { CONTENT_LIBRARY_PATH, type ContentDraft, type PageType } from '@/lib/content/drafts';import { CITED_DAYS, MAX_PASSAGES, type CitedPassage } from '@/lib/content/cited-passages';import type { DraftVersion } from '@/lib/content/history';@@ -121,7 +123,14 @@ const DOCUMENT_CLASS = cn(* reject, with the agent bar over it, and Fix open rules with agent asks the* Content Agent for a new batch (CE-018).*/-export function DraftEditor({ draft }: { draft: ContentDraft }) {+export function DraftEditor({+ draft,+ onAgentStarted,+}: {+ draft: ContentDraft;+ /** The Content Agent took the draft again (Try again): the page waits for it. */+ onAgentStarted?: () => void;+}) {const t = useTranslations('contentEditor.editor');const autosave = useDraftAutosave(draft.id, draft);const [title, setTitle] = useState(draft.title);@@ -131,6 +140,10 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {useEffect(() => () => clearTimeout(pageReadTimer.current), []);const [status, setStatus] = useState(draft.status);const [marking, setMarking] = useState(false);+ // The Content Agent couldn't finish the page Start gave it (CE-015).+ const [agentFailed, setAgentFailed] = useState(draft.agentState === 'failed');+ const [retrying, setRetrying] = useState(false);+ const describeRule = useRuleDescriber();const [restoring, setRestoring] = useState(false);const format = useFormatter();// A change to a locked passage, waiting for the person (CE-018).@@ -626,6 +639,46 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {);};+ /**+ * Try again: the agent takes the page as saved now, with the rules in+ * effect here, and the page waits for it.+ */+ const retryAgent = async () => {+ if (!editor) return;+ setRetrying(true);+ try {+ await autosave.settle();+ const request = await agentWriteRequest(+ {+ id: draft.id,+ brandId: draft.brandId,+ title,+ pageType,+ method: draft.method,+ sourceUrl: draft.sourceUrl,+ bodyHtml: editor.getHTML(),+ rules: draft.rules,+ },+ describeRule,+ {+ rules: rules.rules.filter(({ rule }) => rule.on).map(({ rule }) => rule),+ textRules: rules.textRules.filter(({ rule }) => rule.on).map(({ rule }) => rule.text),+ },+ );+ const result = await startAgentWriting(draft.id, draft.brandId, request);+ if ('error' in result) {+ toast.error(t(`agentFailed.errors.${result.error}`));+ return;+ }+ onAgentStarted?.();+ } catch (err) {+ console.error('Failed to start the Content Agent again:', err);+ toast.error(t('agentFailed.errors.failed'));+ } finally {+ setRetrying(false);+ }+ };+const canMarkReady = status === 'draft' || status === 'in_review';const markReady = async () => {setMarking(true);@@ -823,6 +876,36 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {<div className="flex min-h-0 flex-1"><div className="flex min-w-0 flex-1 flex-col">+ {agentFailed && status === 'draft' && (+ <div+ role="alert"+ className="flex flex-wrap items-center gap-x-3 gap-y-1.5 border-b border-amber-200 bg-amber-50 px-4 py-1.5 text-[13px] text-amber-800 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-300"+ >+ <Bot aria-hidden className="h-3.5 w-3.5 shrink-0" />+ <span className="min-w-0 flex-1">{t('agentFailed.text')}</span>+ <span className="flex shrink-0 items-center gap-1">+ <Button+ variant="outline"+ size="sm"+ className="h-7"+ disabled={retrying || !editor}+ onClick={() => void retryAgent()}+ >+ {retrying && <Loader2 className="h-3.5 w-3.5 animate-spin" />}+ {t('agentFailed.retry')}+ </Button>+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label={t('agentFailed.dismiss')}+ title={t('agentFailed.dismiss')}+ onClick={() => setAgentFailed(false)}+ >+ <X className="h-3.5 w-3.5" />+ </Button>+ </span>+ </div>+ )}{/* The action this draft is the work of (CE-022): under the header,which has no room left at 1024px, and Mark ready completes its task. */}{draft.action && (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 07ec99a59..5694e3fbb 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@@ -29,8 +29,10 @@ const getDraftSuggestions = vi.fn();const decideDraftSuggestions = vi.fn();const keepAgentBeforeVersion = vi.fn();const fixDraftRules = vi.fn();+const startAgentWriting = vi.fn();vi.mock('@/lib/actions/content-drafts', () => ({fixDraftRules: (...args: unknown[]) => fixDraftRules(...args),+ startAgentWriting: (...args: unknown[]) => startAgentWriting(...args),getDraftSuggestions: (...args: unknown[]) => getDraftSuggestions(...args),decideDraftSuggestions: (...args: unknown[]) => decideDraftSuggestions(...args),keepAgentBeforeVersion: (...args: unknown[]) => keepAgentBeforeVersion(...args),@@ -140,6 +142,7 @@ const draft = (over: Partial<ContentDraft> = {}): ContentDraft => ({author: 'agent',rules: { set: null, source: null, overrides: {}, textRules: [] },action: null,+ agentState: null,updatedAt: '2026-10-20T10:00:00Z',...over,});@@ -191,6 +194,7 @@ beforeEach(() => {decideDraftSuggestions.mockReset().mockResolvedValue(1);keepAgentBeforeVersion.mockReset().mockResolvedValue(undefined);fixDraftRules.mockReset().mockResolvedValue({ count: 0 });+ startAgentWriting.mockReset().mockResolvedValue({ started: true });localStorage.clear();brandState.activeBrandId = 'b1';brandState.setActiveBrand.mockReset();@@ -363,6 +367,76 @@ describe('the content editor', () => {});});+ describe('the Content Agent writing it (CE-015)', () => {+ it('waits while the agent writes, then opens on what it wrote', async () => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ try {+ getContentDraft.mockResolvedValue(+ draft({+ status: 'draft',+ agentState: 'writing',+ bodyHtml: '<h1>Pipeline forecasting</h1>',+ }),+ );+ await renderPage();+ expect(container.querySelector('[role="status"]')!.textContent).toContain(+ 'Content Agent is writing this page',+ );+ expect(container.querySelector('.ProseMirror')).toBeNull();++ getContentDraft.mockResolvedValue(+ draft({+ status: 'in_review',+ author: 'agent',+ bodyHtml: '<h1>Pipeline</h1><p>Written.</p>',+ }),+ );+ await act(async () => void (await vi.advanceTimersByTimeAsync(5_000)));+ await act(async () => {});+ expect(getContentDraft).toHaveBeenCalledTimes(2);+ expect(container.querySelector('.ProseMirror')!.textContent).toContain('Written.');+ expect(container.querySelector('header')!.textContent).toContain('In review');+ } finally {+ vi.useRealTimers();+ }+ });++ it('says the agent couldn’t finish, and tries again with the page and rules in effect', async () => {+ getContentDraft.mockResolvedValue(draft({ status: 'draft', agentState: 'failed' }));+ await renderPage();+ const alert = container.querySelector('[role="alert"]')!;+ expect(alert.textContent).toContain("The Content Agent couldn't finish this page.");++ await act(async () => button('Try again')!.click());+ await act(async () => {});+ expect(startAgentWriting).toHaveBeenCalledWith(+ 'd1',+ 'b1',+ expect.objectContaining({ textRules: [], locked: [] }),+ );+ const [, , request] = startAgentWriting.mock.calls[0];+ expect(request.rules.length).toBeGreaterThan(0);+ // The page now waits for the agent.+ expect(container.querySelector('[role="status"]')!.textContent).toContain(+ 'Content Agent is writing this page',+ );+ });++ it('keeps the page when the agent can’t start again', async () => {+ startAgentWriting.mockResolvedValue({ error: 'ai_budget' });+ getContentDraft.mockResolvedValue(draft({ status: 'draft', agentState: 'failed' }));+ await renderPage();+ await act(async () => button('Try again')!.click());+ await act(async () => {});+ expect(toast.error).toHaveBeenCalledWith(+ "This month's AI usage is spent, so the agent didn't start.",+ );+ expect(container.querySelector('.ProseMirror')).not.toBeNull();+ await act(async () => button('Close')!.click());+ expect(container.querySelector('[role="alert"]')).toBeNull();+ });+ });+it('marks the draft ready once', async () => {getContentDraft.mockResolvedValue(draft());markContentDraftReady.mockResolvedValue({ status: 'ready', tasksDone: 0 });diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.tsxindex dffb899df..46aabdc2e 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.tsx@@ -3,12 +3,12 @@import { useEffect, useState } from 'react';import { useParams } from 'next/navigation';import { useTranslations } from 'next-intl';-import { Loader2 } from 'lucide-react';+import { ArrowLeft, Bot, Loader2 } from 'lucide-react';import { Link } from '@/i18n/navigation';import { Button } from '@/components/ui/button';import { buttonVariants } from '@/components/ui/button-variants';import { getContentDraft } from '@/lib/actions/content-drafts';-import { CONTENT_LIBRARY_PATH, type ContentDraft } from '@/lib/content/drafts';+import { AGENT_POLL_MS, CONTENT_LIBRARY_PATH, type ContentDraft } from '@/lib/content/drafts';import { useBrandStore } from '@/stores/use-brand-store';import { DraftEditor } from './_draft-editor';@@ -58,14 +58,45 @@ export default function ContentEditorPage() {const current = read?.id === draftId ? read : null;+ // While the Content Agent writes the draft (CE-015), the page waits and+ // looks again; the editor opens on what it wrote.+ const writing = current?.draft?.agentState === 'writing';+ useEffect(() => {+ if (!writing) return;+ let cancelled = false;+ const timer = setTimeout(() => {+ getContentDraft(draftId).then(+ (draft) => {+ if (!cancelled && draft) setRead({ id: draftId, draft });+ },+ // A failed look leaves the page waiting; the next one tries again.+ () => !cancelled && setRead((prev) => (prev ? { ...prev } : prev)),+ );+ }, AGENT_POLL_MS);+ return () => {+ cancelled = true;+ clearTimeout(timer);+ };+ }, [draftId, writing, read]);+return (<div className="-m-6 flex h-[calc(100vh-4rem)] flex-col md:h-screen">{!current ? (<div className="flex flex-1 items-center justify-center" aria-busy="true"><Loader2 className="h-5 w-5 animate-spin text-muted-foreground" /></div>+ ) : current.draft && writing ? (+ <AgentWriting title={current.draft.title} />) : current.draft ? (- <DraftEditor key={current.draft.id} draft={current.draft} />+ <DraftEditor+ key={current.draft.id}+ draft={current.draft}+ onAgentStarted={() =>+ setRead((prev) =>+ prev?.draft ? { id: prev.id, draft: { ...prev.draft, agentState: 'writing' } } : prev,+ )+ }+ />) : (<div className="flex flex-1 flex-col items-center justify-center gap-3 px-6 text-center"><p className="text-sm text-muted-foreground">@@ -96,3 +127,37 @@ export default function ContentEditorPage() {</div>);}++/** The draft while the Content Agent writes it: nothing to edit yet. */+function AgentWriting({ title }: { title: string }) {+ const t = useTranslations('contentEditor.editor');+ return (+ <>+ <header className="flex items-center gap-2.5 border-b px-4 py-2.5">+ <Link+ href={CONTENT_LIBRARY_PATH}+ aria-label={t('back')}+ title={t('back')}+ className={buttonVariants({ variant: 'ghost', size: 'icon-sm' })}+ >+ <ArrowLeft className="h-4 w-4" />+ </Link>+ <h1 className="min-w-0 truncate text-sm font-medium">{title.trim() || t('untitled')}</h1>+ </header>+ <div+ role="status"+ className="flex flex-1 flex-col items-center justify-center gap-3 px-6 text-center"+ >+ <span className="relative">+ <Bot aria-hidden className="h-6 w-6 text-muted-foreground" />+ <Loader2+ aria-hidden+ className="absolute -right-2 -bottom-2 h-3.5 w-3.5 animate-spin text-muted-foreground"+ />+ </span>+ <p className="text-sm font-medium">{t('agentWriting.title')}</p>+ <p className="max-w-sm text-sm text-muted-foreground">{t('agentWriting.body')}</p>+ </div>+ </>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsxindex 7b1a09a09..4f504f55c 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/_library-table.tsx@@ -13,7 +13,11 @@ import {TableHeader,TableRow,} from '@/components/ui/table';-import { DraftMethodBadge, DraftStatusBadge } from '@/components/content/draft-badges';+import {+ AgentStateBadge,+ DraftMethodBadge,+ DraftStatusBadge,+} from '@/components/content/draft-badges';import { assigneeLabel, labelInitials } from '@/lib/action-center/display';import {aeoScoreText,@@ -88,7 +92,13 @@ export function LibraryTable({ drafts, tab }: { drafts: ContentDraftListItem[];<DraftAuthorCell draft={draft} /></TableCell><TableCell>- <DraftStatusBadge status={draft.status} />+ {/* The agent works on drafts only: its state says more than "Draft".+ One marked ready by hand since reads Ready. */}+ {draft.agentState && draft.status === 'draft' ? (+ <AgentStateBadge state={draft.agentState} />+ ) : (+ <DraftStatusBadge status={draft.status} />+ )}</TableCell><TableCell className="pr-6 text-right tabular-nums">{score ?? <span className="text-muted-foreground">—</span>}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsxindex 996e0ace2..542d6d3f2 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.test.tsx@@ -49,6 +49,7 @@ const row = (over: Partial<ContentDraftListItem>): ContentDraftListItem => ({isMine: true,scoreBefore: 62,scoreAfter: 78,+ agentState: null,updatedAt: '2026-10-20T10:00:00Z',...over,});@@ -168,6 +169,33 @@ describe('the Content Library', () => {expect(container.textContent).toContain('Nothing marked ready.');});+ it('shows where the Content Agent is, and reads the list again while it writes', async () => {+ vi.useFakeTimers();+ try {+ getContentDrafts.mockResolvedValue([+ row({ status: 'draft', author: 'agent', agentState: 'writing' }),+ row({ id: 'd2', status: 'draft', agentState: 'failed' }),+ // Written by hand after the agent failed, and marked ready.+ row({ id: 'd3', status: 'ready', agentState: 'failed' }),+ ]);+ await renderPage();+ const status = [...container.querySelectorAll('tbody tr')].map(+ (tr) => tr.querySelectorAll('td')[4].textContent,+ );+ expect(status).toEqual(['Agent writing…', 'Agent failed', 'Ready']);+ expect(getContentDrafts).toHaveBeenCalledTimes(1);++ getContentDrafts.mockResolvedValue([row({ status: 'in_review', author: 'agent' })]);+ await act(async () => void (await vi.advanceTimersByTimeAsync(5_000)));+ expect(getContentDrafts).toHaveBeenCalledTimes(2);+ expect(container.querySelector('tbody tr td:nth-child(5)')!.textContent).toBe('In review');+ await act(async () => void (await vi.advanceTimersByTimeAsync(10_000)));+ expect(getContentDrafts).toHaveBeenCalledTimes(2);+ } finally {+ vi.useRealTimers();+ }+ });+it('opens the tab the URL names', async () => {window.history.replaceState(null, '', '/dashboard/content/library?tab=in_review');getContentDrafts.mockResolvedValue([row({}), row({ id: 'd2', status: 'draft' })]);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsxindex 850fff4c8..56321b0e5 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/library/page.tsx@@ -9,6 +9,7 @@ import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';import { NewContentDialog } from '@/components/content/new-content-dialog';import { getContentDrafts } from '@/lib/actions/content-drafts';import {+ AGENT_POLL_MS,LIBRARY_TABS,draftsInTab,libraryTabCounts,@@ -63,6 +64,15 @@ export default function ContentLibraryPage() {};}, [activeBrandId, attempt]);+ // While the Content Agent writes a draft (CE-015), the list is read again+ // now and then, so it moves to In review without a reload.+ const agentWriting = !!read?.drafts?.some((draft) => draft.agentState === 'writing');+ useEffect(() => {+ if (!agentWriting) return;+ const timer = setTimeout(() => setAttempt((n) => n + 1), AGENT_POLL_MS);+ return () => clearTimeout(timer);+ }, [agentWriting, read]);+const changeTab = (next: LibraryTab) => {setTab(next);writeUrlParams({ tab: next }, { tab: 'all' });diff --git a/web/src/components/content/draft-badges.tsx b/web/src/components/content/draft-badges.tsxindex 4a40f5bd9..c2a39b349 100644--- a/web/src/components/content/draft-badges.tsx+++ b/web/src/components/content/draft-badges.tsx@@ -1,9 +1,10 @@'use client';import { useTranslations } from 'next-intl';+import { Loader2 } from 'lucide-react';import { Badge } from '@/components/ui/badge';import { cn } from '@/lib/utils';-import type { DraftMethod, DraftStatus } from '@/lib/content/drafts';+import type { AgentState, DraftMethod, DraftStatus } from '@/lib/content/drafts';/*** A draft's status and method, as the Library and the editor show them@@ -47,3 +48,21 @@ export function DraftMethodBadge({</Badge>);}++/** Where the Content Agent is on a draft Start gave it (CE-015): writing, or couldn't finish. */+export function AgentStateBadge({ state }: { state: Exclude<AgentState, null> }) {+ const t = useTranslations('contentEditor.agentState');+ return (+ <Badge+ variant="outline"+ className={+ state === 'writing'+ ? 'border-border bg-muted/50 text-muted-foreground'+ : 'border-red-500/30 bg-red-500/10 text-red-600 dark:text-red-400'+ }+ >+ {state === 'writing' && <Loader2 aria-hidden className="h-3 w-3 animate-spin" />}+ {t(state)}+ </Badge>+ );+}diff --git a/web/src/components/content/new-content-dialog.test.tsx b/web/src/components/content/new-content-dialog.test.tsxindex e298a8810..4fe3d4f7d 100644--- a/web/src/components/content/new-content-dialog.test.tsx+++ b/web/src/components/content/new-content-dialog.test.tsx@@ -11,13 +11,22 @@ const createContentDraft = vi.fn();const getContentOverlap = vi.fn();const importContentPage = vi.fn();const sendContentDraftToActionCenter = vi.fn();+const startAgentWriting = vi.fn();vi.mock('@/lib/actions/content-drafts', () => ({sendContentDraftToActionCenter: (...args: unknown[]) => sendContentDraftToActionCenter(...args),+ startAgentWriting: (...args: unknown[]) => startAgentWriting(...args),importContentPage: (...args: unknown[]) => importContentPage(...args),getContentStartOptions: (...args: unknown[]) => getContentStartOptions(...args),createContentDraft: (...args: unknown[]) => createContentDraft(...args),getContentOverlap: (...args: unknown[]) => getContentOverlap(...args),}));+// What the agent is given is agent-write.test.ts's; here, that Start hands it over.+const agentWriteRequest = vi.fn();+const describeRule = vi.fn();+vi.mock('@/lib/content/agent-write', () => ({+ agentWriteRequest: (...args: unknown[]) => agentWriteRequest(...args),+ useRuleDescriber: () => describeRule,+}));const push = vi.fn();const onSent = vi.fn();vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push }) }));@@ -107,10 +116,13 @@ beforeEach(() => {getContentOverlap.mockReset().mockResolvedValue({ totalPrompts: 2, pages: [] });importContentPage.mockReset().mockResolvedValue({ error: 'failed' });sendContentDraftToActionCenter.mockReset();+ startAgentWriting.mockReset();+ agentWriteRequest.mockReset().mockResolvedValue({ sources: 'kept', rules: [] });onSent.mockReset();toast.warning.mockReset();push.mockReset();toast.error.mockReset();+ toast.success.mockReset();});afterEach(() => {@@ -461,15 +473,59 @@ describe('New content', () => {...document.querySelectorAll<HTMLElement>('[aria-labelledby="start-who"] [role="radio"]'),].find((r) => r.textContent?.startsWith(name))!;- it('opens the editor for me, and offers the agent only once it exists', async () => {+ it('opens the editor for me by default', async () => {await startNewPage();expect(whoOption('Me').getAttribute('aria-checked')).toBe('true');- const agent = whoOption('Agent') as HTMLButtonElement;- expect(agent.disabled).toBe(true);- expect(agent.textContent).toContain('Comes with the Content Agent');+ expect(whoOption('Agent').textContent).toBe('AgentDrafts, I review');expect(button('Open editor')).toBeDefined();});+ it('hands the draft to the Content Agent, which drafts it for review in the Library', async () => {+ startAgentWriting.mockResolvedValue({ started: true });+ await startNewPage();+ await click(whoOption('Agent'));+ await click(button('Start the agent'));++ expect(agentWriteRequest).toHaveBeenCalledWith(+ expect.objectContaining({+ id: 'd9',+ brandId: 'b1',+ method: 'create',+ rules: { set: null, source: null, overrides: {}, textRules: [] },+ }),+ describeRule,+ );+ expect(startAgentWriting).toHaveBeenCalledWith('d9', 'b1', { sources: 'kept', rules: [] });+ expect(push).not.toHaveBeenCalled();+ expect(onSent).toHaveBeenCalled();+ const [message, options] = toast.success.mock.calls[0];+ expect(message).toBe('Content Agent is drafting');+ expect(options.description).toBe("You'll review it in Library › In review.");+ options.action.onClick();+ expect(push).toHaveBeenCalledWith('/dashboard/content/editor/d9');+ });++ it('keeps the draft for me when the agent can’t start', async () => {+ startAgentWriting.mockResolvedValue({ error: 'ai_budget' });+ await startNewPage();+ await click(whoOption('Agent'));+ await click(button('Start the agent'));+ expect(toast.error.mock.calls[0][0]).toBe(+ "This month's AI usage is spent, so the agent didn't start. The draft is in the Library for you to write.",+ );+ expect(onSent).toHaveBeenCalled();+ });++ it('says the draft is the person’s to write when the agent is busy with another', async () => {+ startAgentWriting.mockResolvedValue({ error: 'org_writing' });+ await startNewPage();+ await click(whoOption('Agent'));+ await click(button('Start the agent'));+ expect(toast.error.mock.calls[0][0]).toBe(+ "The agent is writing another of your team's drafts, so it didn't start. The draft is in the Library for you to write.",+ );+ });+it('sends the draft to the Action Center for the team, and keeps it in the Library', async () => {sendContentDraftToActionCenter.mockResolvedValue({actionId: 'a1',diff --git a/web/src/components/content/new-content-dialog.tsx b/web/src/components/content/new-content-dialog.tsxindex e9ac84ddf..47f78bcac 100644--- a/web/src/components/content/new-content-dialog.tsx+++ b/web/src/components/content/new-content-dialog.tsx@@ -35,9 +35,12 @@ import {getContentStartOptions,importContentPage,sendContentDraftToActionCenter,+ startAgentWriting,} from '@/lib/actions/content-drafts';+import { agentWriteRequest, useRuleDescriber } from '@/lib/content/agent-write';import { MAX_ATTACHMENT_BYTES, textToHtml } from '@/lib/content/attachments';import { cleanHtml } from '@/lib/content/clean-html';+import { NO_DRAFT_RULES } from '@/lib/content/rules';import {contentEditorPath,type ContentOverlap,@@ -143,6 +146,7 @@ export function NewContentDialog({const t = useTranslations('contentEditor.newContent');const tTypes = useTranslations('contentEditor.pageTypes');const router = useRouter();+ const describeRule = useRuleDescriber();const [options, setOptions] = useState<DraftStartOptions | null>(null);const [optionsFailed, setOptionsFailed] = useState(false);@@ -392,6 +396,10 @@ export function NewContentDialog({await sendToTeam(id);return;}+ if (who === 'agent') {+ await sendToAgent(id, bodyHtml);+ return;+ }router.push(contentEditorPath(id));} catch (err) {console.error('Failed to start a draft:', err);@@ -400,6 +408,49 @@ export function NewContentDialog({}};+ /**+ * Agent: the Content Agent does the page in the background — a new page+ * written, an existing one's suggestions left — and the draft waits in+ * Library › In review. It stays in the Library as a draft if it can't start.+ */+ const sendToAgent = async (id: string, bodyHtml: string | undefined) => {+ const openDraft = {+ label: t('start.openDraft'),+ onClick: () => router.push(contentEditorPath(id)),+ };+ let started: Awaited<ReturnType<typeof startAgentWriting>>;+ try {+ const request = await agentWriteRequest(+ {+ id,+ brandId,+ title: startTitle,+ pageType: start?.pageType ?? null,+ method: startMethod,+ sourceUrl: existing?.url ?? start?.sourceUrl ?? null,+ bodyHtml: bodyHtml ?? '',+ rules: NO_DRAFT_RULES,+ },+ describeRule,+ );+ started = await startAgentWriting(id, brandId, request);+ } catch (err) {+ console.error('Failed to hand the draft to the Content Agent:', err);+ started = { error: 'failed' };+ }+ changeOpen(false);+ onSent?.();+ if ('error' in started) {+ toast.error(t(`start.agentErrors.${started.error}`), { action: openDraft });+ return;+ }+ toast.success(t('start.agentStarted'), {+ description: t('start.agentStartedDescription'),+ duration: 10_000,+ action: openDraft,+ });+ };+/*** Team: the draft goes to the Action Center as an action for someone to* write; it stays in the Library either way.@@ -495,39 +546,32 @@ export function NewContentDialog({aria-labelledby="start-who"className="grid grid-cols-3 gap-1.5">- {WHO.map((value) => {- // The Content Agent comes in its own update (CE-018/022).- const soon = value === 'agent';- return (- <button- key={value}- type="button"- role="radio"- aria-checked={who === value}- aria-disabled={soon || undefined}- disabled={soon}- title={soon ? t('who.agent.soon') : undefined}- onClick={() => setWho(value)}+ {WHO.map((value) => (+ <button+ key={value}+ type="button"+ role="radio"+ aria-checked={who === value}+ onClick={() => setWho(value)}+ className={cn(+ 'flex items-start gap-2 rounded-xl border px-3 py-2.5 text-left transition-colors hover:bg-muted/50',+ who === value && 'border-foreground ring-1 ring-inset ring-foreground',+ )}+ >+ <spanclassName={cn(- 'flex items-start gap-2 rounded-xl border px-3 py-2.5 text-left transition-colors hover:bg-muted/50 disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent',- who === value && 'border-foreground ring-1 ring-inset ring-foreground',+ 'mt-0.5 h-4 w-4 shrink-0 rounded-full border-[1.5px] border-muted-foreground/50',+ who === value && 'border-[5px] border-foreground',)}- >- <span- className={cn(- 'mt-0.5 h-4 w-4 shrink-0 rounded-full border-[1.5px] border-muted-foreground/50',- who === value && 'border-[5px] border-foreground',- )}- />- <span className="min-w-0">- <span className="block text-sm font-medium">{t(`who.${value}.title`)}</span>- <span className="block text-xs text-muted-foreground">- {soon ? t('who.agent.soon') : t(`who.${value}.hint`)}- </span>+ />+ <span className="min-w-0">+ <span className="block text-sm font-medium">{t(`who.${value}.title`)}</span>+ <span className="block text-xs text-muted-foreground">+ {t(`who.${value}.hint`)}</span>- </button>- );- })}+ </span>+ </button>+ ))}</div></div><DialogFooter>@@ -537,7 +581,13 @@ export function NewContentDialog({</Button><Button onClick={() => void openEditor()} disabled={opening}>{opening && <Loader2 className="h-4 w-4 animate-spin" />}- {t(who === 'team' ? 'start.sendToTeam' : 'start.openEditor')}+ {t(+ who === 'team'+ ? 'start.sendToTeam'+ : who === 'agent'+ ? 'start.startAgent'+ : 'start.openEditor',+ )}</Button></DialogFooter></>diff --git a/web/src/lib/actions/content-drafts-start.test.ts b/web/src/lib/actions/content-drafts-start.test.tsindex 5ac7be575..2ac20adbe 100644--- a/web/src/lib/actions/content-drafts-start.test.ts+++ b/web/src/lib/actions/content-drafts-start.test.ts@@ -87,6 +87,7 @@ const {getContentStartOptions,importContentPage,sendContentDraftToActionCenter,+ startAgentWriting,startDraftFromAction,} = await import('./content-drafts');@@ -680,3 +681,47 @@ describe('startDraftFromAction', () => {});});});++describe('startAgentWriting', () => {+ const request = {+ sources: { promptIds: [], fanouts: [], pages: [], queries: [], headings: [], length: 3000 },+ rules: [],+ textRules: [],+ locked: [],+ };++ it('starts the API’s Content Agent with the member’s session', async () => {+ const fetchMock = vi.fn(async () => new Response('{"started":true}', { status: 202 }));+ vi.stubGlobal('fetch', fetchMock);+ await expect(startAgentWriting(OPPORTUNITY, BRAND, request)).resolves.toEqual({+ started: true,+ });+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];+ expect(url).toMatch(new RegExp(`/api/content-drafts/${OPPORTUNITY}/write$`));+ expect(init.headers).toMatchObject({ Authorization: 'Bearer jwt' });+ expect(JSON.parse(init.body as string)).toEqual({ brandId: BRAND, ...request });+ vi.unstubAllGlobals();+ });++ it('says why it didn’t start, and sends nothing for a malformed id', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => new Response('{"code":"ai_budget"}', { status: 429 })),+ );+ await expect(startAgentWriting(OPPORTUNITY, BRAND, request)).resolves.toEqual({+ error: 'ai_budget',+ });+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => new Response('{"code":"something_new"}', { status: 500 })),+ );+ await expect(startAgentWriting(OPPORTUNITY, BRAND, request)).resolves.toEqual({+ error: 'failed',+ });+ const fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+ await expect(startAgentWriting('nope', BRAND, request)).resolves.toEqual({ error: 'failed' });+ expect(fetchMock).not.toHaveBeenCalled();+ vi.unstubAllGlobals();+ });+});diff --git a/web/src/lib/actions/content-drafts.test.ts b/web/src/lib/actions/content-drafts.test.tsindex 2933a2179..20016d2a5 100644--- a/web/src/lib/actions/content-drafts.test.ts+++ b/web/src/lib/actions/content-drafts.test.ts@@ -52,6 +52,7 @@ vi.mock('@/lib/supabase/server', () => ({eq: (col: string, v: unknown) => (call.filters.push(['eq', col, v]), chain),in: (col: string, v: unknown) => (call.filters.push(['in', col, v]), chain),gte: (col: string, v: unknown) => (call.filters.push(['gte', col, v]), chain),+ or: (v: string) => (call.filters.push(['or', v, null]), chain),order: () => chain,limit: async () => ({ data: list, error: null }),update: (value: unknown) => ((call.op = 'update'), (call.value = value), chain),@@ -117,6 +118,8 @@ describe('saveContentDraft', () => {filters: [['eq', 'id', DRAFT],['eq', 'updated_at', '2026-10-20T14:00:00Z'],+ // Not while the Content Agent writes it.+ ['or', expect.stringMatching(/^agent_state\.is\.null,agent_state\.neq\.writing,/), null],],});});@@ -155,6 +158,19 @@ describe('saveContentDraft', () => {expect(calls.map((c) => c.op)).toEqual(['update', 'select']);});+ it('waits while the Content Agent writes the page, the page being the same', async () => {+ row = {+ updated_at: '2026-10-20T14:30:00Z',+ body_html: LOADED,+ agent_state: 'writing',+ agent_state_at: new Date().toISOString(),+ };+ await expect(+ saveContentDraft(DRAFT, { title: 'Mine', bodyHtml: '<h1>Mine</h1>', base: await base() }),+ ).resolves.toEqual({ ok: false, reason: 'conflict' });+ expect(calls.map((c) => c.op)).toEqual(['update', 'select']);+ });+it('says so when the draft is gone or not the member’s, rather than reporting it saved', async () => {await expect(saveContentDraft(DRAFT, { title: '', bodyHtml: '', base: await base() }),diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex a59c94ca3..9dbded141 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -7,6 +7,8 @@ import { readAssignees } from '@/lib/action-center/assignees';import {DRAFT_STATUSES,PAGE_TYPES,+ WRITING_STALE_MS,+ agentStateOf,type ContentDraft,type ContentDraftListItem,type ContentOverlap,@@ -64,6 +66,7 @@ import {type RestoredDraft,type VersionOrigin,} from '@/lib/content/history';+import type { AgentWriteRequest } from '@/lib/content/agent-write';import {actionPages,completeDraftTasks,@@ -98,7 +101,7 @@ export async function getContentDrafts(brandId: string): Promise<ContentDraftLissupabase.from('content_drafts').select(- 'id, title, page_type, method, status, author, created_by, score_before, score_after, updated_at',+ 'id, title, page_type, method, status, author, created_by, score_before, score_after, agent_state, agent_state_at, updated_at',).eq('brand_id', brandId).order('updated_at', { ascending: false })@@ -127,6 +130,7 @@ export async function getContentDrafts(brandId: string): Promise<ContentDraftLisisMine: me !== null && row.created_by === me,scoreBefore: row.score_before,scoreAfter: row.score_after,+ agentState: agentStateOf(row.agent_state, row.agent_state_at),updatedAt: row.updated_at,}));}@@ -161,7 +165,7 @@ export async function getContentDraft(id: string): Promise<ContentDraft | null>const { data, error } = await supabase.from('content_drafts').select(- `id, brand_id, title, page_type, page_type_source, method, status, body_html, author, source_url, rules, action_id, updated_at, ${BRAND_SITE}, actions(action_no)`,+ `id, brand_id, title, page_type, page_type_source, method, status, body_html, author, source_url, rules, action_id, agent_state, agent_state_at, updated_at, ${BRAND_SITE}, actions(action_no)`,).eq('id', id).maybeSingle();@@ -184,6 +188,7 @@ export async function getContentDraft(id: string): Promise<ContentDraft | null>data.action_id && data.actions? { id: data.action_id, number: data.actions.action_no }: null,+ agentState: agentStateOf(data.agent_state, data.agent_state_at),updatedAt: data.updated_at,};}@@ -802,12 +807,17 @@ export async function saveContentDraft(const bodyHtml = sanitizeDraftHtml(parsed.data.bodyHtml);const supabase = await createClient();let expected = base.updatedAt;+ // While the Content Agent writes the page (CE-015), a tab left open waits:+ // the agent's page would go over its save. A 'writing' left by a stopped+ // server doesn't hold it.+ const writingSince = new Date(Date.now() - WRITING_STALE_MS).toISOString();for (let attempt = 0; attempt < SAVE_ATTEMPTS; attempt++) {const { data, error } = await supabase.from('content_drafts').update({ title, body_html: bodyHtml }).eq('id', id).eq('updated_at', expected)+ .or(`agent_state.is.null,agent_state.neq.writing,agent_state_at.lt."${writingSince}"`).select(`updated_at, page_type, page_type_source, ${BRAND_SITE}`).maybeSingle();if (error) throw new Error(error.message);@@ -837,11 +847,15 @@ export async function saveContentDraft(const { data: current, error: readError } = await supabase.from('content_drafts')- .select('updated_at, body_html')+ .select('updated_at, body_html, agent_state, agent_state_at').eq('id', id).maybeSingle();if (readError) throw new Error(readError.message);if (!current) return { ok: false, reason: 'not_found' };+ // The page is changing elsewhere: Reload opens it as the agent leaves it.+ if (agentStateOf(current.agent_state, current.agent_state_at) === 'writing') {+ return { ok: false, reason: 'conflict' };+ }if ((await bodyHash(current.body_html)) !== base.bodyHash) {return { ok: false, reason: 'conflict' };}@@ -1383,6 +1397,56 @@ export async function fixDraftRules(}}+const AGENT_WRITE_ERRORS = [+ 'ai_budget',+ 'no_subscription',+ 'writing',+ 'org_writing',+ 'open_suggestions',+ 'not_draft',+ 'failed',+] as const;+export type AgentWriteError = (typeof AGENT_WRITE_ERRORS)[number];++/**+ * Start's Agent (CE-015): the API's Content Agent does the draft in the+ * background (content-writer.js) — a new page written whole, an existing+ * page's suggestions left — and the draft goes to In review. Returns once it+ * has started. Returned, not thrown: production hides a server action's+ * errors.+ */+export async function startAgentWriting(+ id: string,+ brandId: string,+ request: AgentWriteRequest,+): Promise<{ started: true } | { error: AgentWriteError }> {+ 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}/write`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${session.access_token}`,+ },+ body: JSON.stringify({ brandId, ...request }),+ });+ if (res.ok) return { started: true };+ const body = (await res.json().catch(() => ({}))) as { code?: string };+ const code = body.code as AgentWriteError;+ return { error: AGENT_WRITE_ERRORS.includes(code) ? code : 'failed' };+ } catch (err) {+ console.error('Failed to start the Content Agent:', err);+ return { error: 'failed' };+ }+}+/*** The Rules tab (CE-009): a rule turned on or off, or given a value, for* this draft ("Rule updated for this draft"). Throws 'not_found' when nodiff --git a/web/src/lib/content/agent-write.test.ts b/web/src/lib/content/agent-write.test.tsnew file mode 100644index 000000000..5e60f79e7--- /dev/null+++ b/web/src/lib/content/agent-write.test.ts@@ -0,0 +1,124 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { DraftSourcesData } from './sources';+import { NO_DRAFT_RULES, activeRules, ruleSet, type ActiveRule } from './rules';++/**+ * What Start's Agent gives the Content Agent (CE-015): the sources kept, the+ * rules in effect (the workspace's My rules included, feed rules left out),+ * the person's own rules, and on an existing page the passages AI quotes.+ */++const getDraftSources = vi.fn();+const getMyRuleSets = vi.fn();+const getCitedPassages = vi.fn();+vi.mock('@/lib/actions/content-drafts', () => ({+ getDraftSources: (...args: unknown[]) => getDraftSources(...args),+ getMyRuleSets: (...args: unknown[]) => getMyRuleSets(...args),+ getCitedPassages: (...args: unknown[]) => getCitedPassages(...args),+}));++const { agentWriteRequest } = await import('./agent-write');++const data: DraftSourcesData = {+ prompts: [+ { id: 'p1', text: 'Best grinder?', inDraft: true, citesPage: false, answers: 4, mentioned: 1 },+ ],+ fanouts: [{ query: 'burr grinder under 200', platforms: ['copilot-web'], searched: 3 }],+ citedPages: [],+ gscQueries: [],+ brandDomains: ['acme.example'],+ competitorDomains: [],+};+const describe_ = (rule: ActiveRule) => ({ name: `name:${rule.key}`, detail: rule.current });+const draft = (over = {}) => ({+ id: 'd1',+ brandId: 'b1',+ title: 'Burr grinders',+ pageType: 'product_page',+ method: 'create' as const,+ sourceUrl: null,+ bodyHtml: '<h1>Burr grinders</h1>',+ rules: NO_DRAFT_RULES,+ ...over,+});++beforeEach(() => {+ getDraftSources.mockReset().mockResolvedValue({ data, choices: [] });+ getMyRuleSets.mockReset().mockResolvedValue({});+ getCitedPassages.mockReset().mockResolvedValue([]);+});++describe('agentWriteRequest', () => {+ it('sends the sources kept and the type’s rules, with the workspace’s My rules', async () => {+ getMyRuleSets.mockResolvedValue({+ product_page: {+ overrides: { faq: { on: false }, length: { value: '2000' } },+ textRules: [+ { id: 't1', text: 'Say “we” for the brand', on: true },+ { id: 't2', text: 'Old rule', on: false },+ ],+ },+ });+ const request = await agentWriteRequest(draft(), describe_);++ expect(request.sources).toMatchObject({+ promptIds: ['p1'],+ fanouts: [{ query: 'burr grinder under 200', platforms: ['copilot-web'] }],+ headings: [],+ length: 2000,+ });+ const keys = request.rules.map((rule) => rule.key);+ expect(keys).not.toContain('faq');+ expect(keys).not.toContain('feedMatch');+ expect(keys).toContain('aiTraces');+ expect(request.rules.find((rule) => rule.key === 'length')).toEqual({+ key: 'length',+ name: 'name:length',+ detail: '2000',+ });+ expect(request.textRules).toEqual(['Say “we” for the brand']);+ // A new page has nothing AI quotes yet.+ expect(getCitedPassages).not.toHaveBeenCalled();+ expect(request.locked).toEqual([]);+ });++ it('locks what AI quotes on an existing page, and takes the editor’s rules as given', async () => {+ getCitedPassages.mockResolvedValue([{ key: 'burrs grind evenly', platforms: [] }]);+ const rules = activeRules(ruleSet('product_page'), NO_DRAFT_RULES).filter((rule) =>+ ['summary', 'feedMatch'].includes(rule.key),+ );+ const request = await agentWriteRequest(+ draft({+ method: 'optimize',+ sourceUrl: 'https://acme.example/grinders',+ bodyHtml: '<h1>Grinders</h1><p>Burrs grind evenly.</p><ul><li><p>Steel</p></li></ul>',+ }),+ describe_,+ { rules, textRules: ['Short sentences'] },+ );++ expect(getCitedPassages).toHaveBeenCalledWith('d1', [+ 'Grinders',+ 'Burrs grind evenly.',+ 'Steel',+ ]);+ expect(request.locked).toEqual(['burrs grind evenly']);+ expect(getMyRuleSets).not.toHaveBeenCalled();+ expect(request.rules.map((rule) => rule.key)).toEqual(['summary']);+ expect(request.textRules).toEqual(['Short sentences']);+ });++ it('still sends the rules when the sources can’t be read', async () => {+ getDraftSources.mockResolvedValue(null);+ const request = await agentWriteRequest(draft({ pageType: null }), describe_);+ expect(request.sources).toEqual({+ promptIds: [],+ fanouts: [],+ pages: [],+ queries: [],+ headings: [],+ length: expect.any(Number),+ });+ expect(request.rules.length).toBeGreaterThan(0);+ });+});diff --git a/web/src/lib/content/agent-write.ts b/web/src/lib/content/agent-write.tsnew file mode 100644index 000000000..20eaffdf9--- /dev/null+++ b/web/src/lib/content/agent-write.ts@@ -0,0 +1,110 @@+import { useCallback } from 'react';+import { useTranslations } from 'next-intl';+import { getCitedPassages, getDraftSources, getMyRuleSets } from '@/lib/actions/content-drafts';+import { rebuildSources, type RebuildSources } from './brief';+import { MAX_PASSAGES } from './cited-passages';+import { isPageType, type DraftMethod } from './drafts';+import {+ activeRules,+ effectiveRules,+ ruleLength,+ ruleSet,+ type ActiveRule,+ type DraftRules,+} from './rules';++/**+ * What the Content Agent is given when Start hands it a draft (CE-015), as+ * the API's content-writer.js reads it: the sources the Sources tab keeps+ * (as Rebuild outline sends them), the page type's rules in effect, the+ * person's own rules, and the passages AI answers quote today on an existing+ * page, which it never changes. Read in the browser: the sources and the+ * page are read with DOMParser.+ */+export interface AgentWriteRequest {+ sources: RebuildSources;+ rules: { key: string; name: string; detail: string }[];+ textRules: string[];+ locked: string[];+}++/** The server's limit on rules (content-writer.js writeDraftInput). */+const MAX_AGENT_RULES = 60;++/** A rule as the agent reads it: its name, and what it asks. */+export type RuleDescriber = (rule: ActiveRule) => { name: string; detail: string };++/** Rules in the reader's words, as Fix open rules sends them. */+export function useRuleDescriber(): RuleDescriber {+ const t = useTranslations('contentEditor.editor.rules');+ return useCallback(+ (rule: ActiveRule) => ({+ name: t(`names.${rule.key}`),+ detail: rule.current+ ? `${t('agent.aim')}: ${rule.current}${rule.unit ? ` ${t(`units.${rule.unit}`)}` : ''}`+ : '',+ }),+ [t],+ );+}++/** The page's headings and paragraphs, as the editor's passages. */+function pagePassages(html: string): string[] {+ const doc = new DOMParser().parseFromString(html, 'text/html');+ return [...doc.querySelectorAll('h1, h2, h3, h4, h5, h6, p')]+ .map((el) => (el.textContent ?? '').trim().slice(0, 5_000))+ .filter(Boolean)+ .slice(0, MAX_PASSAGES);+}++/**+ * The request for a draft. The rules in effect are read for it (the page+ * type's set with the workspace's My rules), unless the editor, which has+ * them, passes its own.+ */+export async function agentWriteRequest(+ draft: {+ id: string;+ brandId: string;+ title: string;+ pageType: string | null;+ method: DraftMethod;+ sourceUrl: string | null;+ bodyHtml: string;+ rules: DraftRules;+ },+ describe: RuleDescriber,+ inEffect?: { rules: ActiveRule[]; textRules: string[] },+): Promise<AgentWriteRequest> {+ const setType = draft.rules.set ?? (isPageType(draft.pageType) ? draft.pageType : null);+ const [read, mine, cited] = await Promise.all([+ getDraftSources(draft.id),+ // Without the workspace's rules, the page type's defaults still apply.+ inEffect+ ? null+ : getMyRuleSets(draft.brandId).catch((): Awaited<ReturnType<typeof getMyRuleSets>> => ({})),+ draft.method === 'optimize' && draft.sourceUrl+ ? getCitedPassages(draft.id, pagePassages(draft.bodyHtml))+ : Promise.resolve(null),+ ]);+ const effective = effectiveRules(draft.rules, setType ? mine?.[setType] : undefined);+ const rules = (+ inEffect?.rules ?? activeRules(ruleSet(setType), effective).filter((rule) => rule.on)+ ).filter((rule) => rule.check !== 'feed');+ const textRules =+ inEffect?.textRules ?? effective.textRules.filter((rule) => rule.on).map((rule) => rule.text);+ const length = ruleLength(rules, setType);+ return {+ sources: read+ ? rebuildSources(read.data, read.choices, {+ title: draft.title,+ sourceUrl: draft.sourceUrl,+ html: draft.bodyHtml,+ length,+ })+ : { promptIds: [], fanouts: [], pages: [], queries: [], headings: [], length },+ rules: rules.slice(0, MAX_AGENT_RULES).map((rule) => ({ key: rule.key, ...describe(rule) })),+ textRules,+ locked: (cited ?? []).map((passage) => passage.key),+ };+}diff --git a/web/src/lib/content/drafts.test.ts b/web/src/lib/content/drafts.test.tsindex 0b8be2f22..bb9a358f8 100644--- a/web/src/lib/content/drafts.test.ts+++ b/web/src/lib/content/drafts.test.ts@@ -3,7 +3,9 @@ import messages from '../../../messages/en.json';import {DRAFT_STATUSES,PAGE_TYPES,+ WRITING_STALE_MS,aeoScoreText,+ agentStateOf,contentEditorPath,draftsInTab,isPageType,@@ -23,6 +25,7 @@ const draft = (id: string, status: DraftStatus): ContentDraftListItem => ({isMine: true,scoreBefore: null,scoreAfter: null,+ agentState: null,updatedAt: '2026-10-20T10:00:00Z',});@@ -86,3 +89,16 @@ describe('page types and labels', () => {expect(contentEditorPath('d1')).toBe('/dashboard/content/editor/d1');});});++describe('agentStateOf', () => {+ const now = Date.parse('2026-10-21T12:00:00Z');+ it('reads the agent writing, failed, or done — a writing left long ago as failed', () => {+ expect(agentStateOf(null, null, now)).toBeNull();+ expect(agentStateOf('failed', '2026-10-21T11:59:00Z', now)).toBe('failed');+ expect(agentStateOf('writing', '2026-10-21T11:58:00Z', now)).toBe('writing');+ expect(agentStateOf('writing', new Date(now - WRITING_STALE_MS - 1).toISOString(), now)).toBe(+ 'failed',+ );+ expect(agentStateOf('writing', null, now)).toBe('failed');+ });+});diff --git a/web/src/lib/content/drafts.ts b/web/src/lib/content/drafts.tsindex d946f3973..006f51de7 100644--- a/web/src/lib/content/drafts.ts+++ b/web/src/lib/content/drafts.ts@@ -14,6 +14,29 @@ export type DraftStatus = (typeof DRAFT_STATUSES)[number];/** A new page, or an existing one improved. */export type DraftMethod = 'create' | 'optimize';+/**+ * Where the Content Agent is on a draft Start gave it (CE-015,+ * content_drafts.agent_state, 00219): writing it, or couldn't finish.+ */+export type AgentState = 'writing' | 'failed' | null;++/** A 'writing' this old was left by a server that stopped (content-writer.js). */+export const WRITING_STALE_MS = 10 * 60_000;++/** How often the Library and the editor look again while the agent writes. */+export const AGENT_POLL_MS = 5_000;++/** The agent's state as the app shows it: a 'writing' gone stale reads as failed. */+export function agentStateOf(+ state: string | null,+ at: string | null,+ now: number = Date.now(),+): AgentState {+ if (state === 'failed') return 'failed';+ if (state !== 'writing') return null;+ return at && now - new Date(at).getTime() < WRITING_STALE_MS ? 'writing' : 'failed';+}+/*** The page types a draft can be, across brand types (B2B, e-commerce, B2C;* SITE_PAGE_TYPES says which). Stored as these keys (content_drafts.page_type);@@ -76,6 +99,8 @@ export interface ContentDraftListItem {isMine: boolean;scoreBefore: number | null;scoreAfter: number | null;+ /** Where the Content Agent is on it (CE-015). */+ agentState: AgentState;updatedAt: string;}@@ -104,6 +129,8 @@ export interface ContentDraft {rules: DraftRules;/** The Action Center action the draft is the work of (CE-022), shown as "from Action AC-214". */action: { id: string; number: number } | null;+ /** Where the Content Agent is on it (CE-015): the editor waits while it writes. */+ agentState: AgentState;updatedAt: string;}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 9d5abd632..485585220 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -855,6 +855,8 @@ export type Database = {content_drafts: {Row: {action_id: string | null+ agent_state: string | null+ agent_state_at: string | nullauthor: stringbody_html: stringbrief: Json | null@@ -877,6 +879,8 @@ export type Database = {}Insert: {action_id?: string | null+ agent_state?: string | null+ agent_state_at?: string | nullauthor?: stringbody_html?: stringbrief?: Json | null@@ -899,6 +903,8 @@ export type Database = {}Update: {action_id?: string | null+ agent_state?: string | null+ agent_state_at?: string | nullauthor?: stringbody_html?: stringbrief?: Json | null