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): rewrite the page to its rules from the Rules tab, and compare it (#1394)
Cihan7aecdcd3a755
diff --git a/web/messages/en.json b/web/messages/en.jsonindex fa154f63d..3e3b6602a 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3564,6 +3564,7 @@"usual": "Usually a minute or two.","slow": "Taking longer than usual. If it can't finish within a few minutes, this page says so and you can try again.","leave": "You can leave this page meanwhile: the draft waits in Library › In review.",+ "leaveRewrite": "You can leave this page meanwhile: the rewrite waits here for you to compare.","steps": {"create": {"read": "Read the sources and the brief",@@ -3576,11 +3577,18 @@"rules": "Set aside the passages AI answers quote","write": "Suggesting changes","review": "Opens here with the suggestions to review"+ },+ "rewrite": {+ "read": "Read the page and its rules",+ "rules": "Set aside the passages AI answers quote, tables and images",+ "write": "Rewriting the page",+ "review": "Opens here beside your page to compare"}}},"agentFailed": {"text": "The Content Agent couldn't finish this page. Write it yourself, or try again.",+ "rewriteText": "The Content Agent couldn't rewrite this page. Edit it yourself, or try again.","retry": "Try again","dismiss": "Close","errors": {@@ -3590,9 +3598,32 @@"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.",+ "empty": "The page has no text to rewrite yet.",+ "too_long": "The page is too long to rewrite whole. Use Apply rules with Agent, or shorten it first.","failed": "The agent couldn't start. Try again in a moment."}},+ "rewrite": {+ "bar": "Rewritten page",+ "ready": "Content Agent rewrote the page to its rules",+ "characters": "{before, number} → {after, number} characters",+ "accepted": "Rewrite accepted",+ "rejected": "Rewrite rejected",+ "rulesOpen": "{count, plural, one {# rule still open} other {# rules still open}}",+ "compare": "Compare",+ "compareTitle": "Your page and the rewrite",+ "before": "Your page · {count, number} characters",+ "after": "Rewrite · {count, number} characters",+ "accept": "Accept",+ "reject": "Reject",+ "undo": "Undo",+ "close": "Close",+ "changed": "The page changed after the agent read it. Reject this rewrite and run it again on the page as it is now.",+ "changedAfter": "The page changed after the rewrite was put in. To go back, open History.",+ "acceptedToast": "Rewrite put in place. History keeps your page as it was.",+ "rejectedToast": "Rewrite rejected. Your page stays as it is.",+ "undoneToast": "Your page is back, and the rewrite is open to decide again."+ },"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": {@@ -3631,12 +3662,14 @@"notForAgent": "Content Agent doesn't change heading levels: make the extra H1s H2s in the toolbar.","decideFirst": "Accept or reject the open suggestions first.","citedLoading": "Reading which passages AI quotes, so the agent leaves them as they are…",+ "agentBusy": "Content Agent is already working on this page. Wait for it to finish.","fixErrors": {"ai_budget": "This month's AI usage is spent. Upgrade for more, or try again next month.","no_subscription": "Content Agent needs an active subscription. Choose a plan in Settings › Billing.","empty": "Write something first: the agent improves the page you have.","open_suggestions": "This page has open suggestions, maybe from another tab. They're shown now: accept or reject them first.","published": "This page is published. Content Agent suggests changes to drafts only.",+ "writing": "Content Agent is already writing this page, maybe from another tab. Try again once it has finished.","failed": "Content Agent couldn't run. Try again."}},@@ -4091,6 +4124,14 @@"agentFix": "Apply rules with Agent","agentFixing": "Content Agent is working…","agentFixHint": "Content Agent suggests changes for the rules not met yet, for you to review in the page",+ "rewrite": "Rewrite the page to these rules",+ "rewriting": "Content Agent is rewriting…",+ "rewriteHint": "Content Agent rewrites the whole page in one go and shows it beside yours to accept or reject. Passages AI quotes, tables and images stay as they are.",+ "agentsHint": "Apply rules makes small edits, up to {max} a run. Rewrite does the whole page as one change to compare.",+ "rewriteAdvice": {+ "length": "Recommended: the page is {count, number} characters for a Length of {target, number} ({percent, number}% off). A rewrite gets there in one go.",+ "open": "Recommended: {count, number} rules are open. A rewrite meets them together."+ },"lengthConflict": "The fan-out H2s, FAQ questions and summary these rules still ask for take about {need, number} characters, more than Length allows (up to {max, number}). Raise Length, or ask for fewer.","fixTrace": "Fix","fixTraceHint": "Content Agent rewrites only these phrases, for you to review",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-writing.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-writing.tsxindex 7e0f0ddb1..ef420102a 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-writing.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_agent-writing.tsx@@ -47,11 +47,14 @@ export function AgentWriting({title,method,since,+ rewrite = false,}: {title: string;method: DraftMethod;/** When the agent started (content_drafts.agent_state_at). */since: string | null;+ /** Rewrite the page to these rules, as this tab started it. */+ rewrite?: boolean;}) {const t = useTranslations('contentEditor.editor');const seconds = elapsedSeconds(since, useNow({ updateInterval: 1000 }));@@ -96,7 +99,9 @@ export function AgentWriting({) : (<Circle aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground/60" />)}- <span className="min-w-0 flex-1">{t(`agentWriting.steps.${method}.${step}`)}</span>+ <span className="min-w-0 flex-1">+ {t(`agentWriting.steps.${rewrite ? 'rewrite' : method}.${step}`)}+ </span>{/* Hidden from screen readers: a status that reads out every second. */}{i === WRITING && seconds !== null && (<span aria-hidden className="shrink-0 text-xs text-muted-foreground tabular-nums">@@ -112,7 +117,7 @@ export function AgentWriting({) : (t('agentWriting.usual'))}{' '}- {t('agentWriting.leave')}+ {rewrite ? t('agentWriting.leaveRewrite') : t('agentWriting.leave')}</p></div></div>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsxindex af1aec277..c98ebff65 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@@ -33,6 +33,7 @@ import {restoreDraftVersion,setContentDraftPageType,startAgentWriting,+ startPageRewrite,} from '@/lib/actions/content-drafts';import { agentWriteRequest, useRuleDescriber } from '@/lib/content/agent-write';import {@@ -82,7 +83,8 @@ import { HtmlBlock, copyToClipboard } from './_html-block';import { OwnCopies, ownCopyHtml } from './_own-copies';import { PageTypeMenu } from './_page-type-menu';import type { AgentRewrite } from './_brief-tab';-import { ruleStatusDetail, type AgentFix } from './_rules-tab';+import { ruleStatusDetail, type AgentFix, type PageRewrite } from './_rules-tab';+import { PageRewriteBar, pageChangedSince } from './_page-rewrite';import { EditorPanelRail, EditorSidePanel, useSidePanelOpen, type PanelTab } from './_side-panel';import {AgentSuggestions,@@ -170,8 +172,11 @@ export function DraftEditor({onAgentStarted,}: {draft: ContentDraft;- /** The Content Agent took the draft again (Try again): the page waits for it. */- onAgentStarted?: () => void;+ /**+ * The Content Agent took the draft again (Try again, Rewrite from brief, or+ * Rewrite the page to these rules): the page waits for it.+ */+ onAgentStarted?: (run: 'write' | 'rewrite') => void;}) {const t = useTranslations('contentEditor.editor');const autosave = useDraftAutosave(draft.id, draft);@@ -184,7 +189,10 @@ export function DraftEditor({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');+ // That run was a rewrite (agent_run, on every device): Try again rewrites again.+ const failedRewrite = draft.agentState === 'failed' && draft.agentRun === 'rewrite';const [starting, setStarting] = useState(false);+ const [rewriting, setRewriting] = useState(false);const describeRule = useRuleDescriber();const [restoring, setRestoring] = useState(false);const format = useFormatter();@@ -456,8 +464,10 @@ export function DraftEditor({useEffect(() => {suggestionsNow.current = suggestions;if (!editor || editor.isDestroyed) return;+ // A whole page (Rewrite the page to these rules) has its own bar, not a card.+ const cards = suggestions.filter((s) => s.kind !== 'page');editor.view.dispatch(- editor.state.tr.setMeta(suggestionsKey, { suggestions, labels: suggestionLabels }),+ editor.state.tr.setMeta(suggestionsKey, { suggestions: cards, labels: suggestionLabels }),);}, [editor, suggestions, suggestionLabels]);@@ -561,6 +571,63 @@ export function DraftEditor({}};const openSuggestions = suggestions.filter((s) => s.status === 'open').length;+ const pageSuggestion = suggestions.find((s) => s.kind === 'page') ?? null;++ /**+ * A whole page rewritten (Rewrite the page to these rules): Accept puts it+ * in place of the page the agent read (History keeps that first), Reject+ * leaves the page, and Undo puts the page back. A page changed since+ * isn't written over: the person runs the rewrite again.+ */+ const decidePage = async (s: DraftSuggestion, to: SuggestionStatus) => {+ if (!editor || deciding) return;+ const undo = to === 'open' && s.status === 'accepted';+ // What the page must still read as for the change to go in.+ const expected = to === 'accepted' ? (s.beforeHtml ?? '') : undo ? s.afterText : null;+ const changed = () => expected !== null && pageChangedSince(editor.getHTML(), expected);+ const refuse = () =>+ toast(to === 'accepted' ? t('rewrite.changed') : t('rewrite.changedAfter'));+ if (changed()) {+ refuse();+ return;+ }+ setDeciding(true);+ // Held still from here: nothing typed while History and the decision are+ // saved can be written over.+ const editable = editor.isEditable;+ editor.setEditable(false, false);+ try {+ if (to === 'accepted' && !agentBeforeKept.current) {+ await autosave.settle();+ await keepAgentBeforeVersion(draft.id);+ agentBeforeKept.current = true;+ }+ if (changed()) {+ refuse();+ return;+ }+ await decideDraftSuggestions([s.id], to);+ if (expected !== null) {+ editor+ .chain()+ .setMeta(CITED_EDIT_ALLOWED, true)+ // The page as it was, two H1s and all, on Undo.+ .setMeta(ONE_H1_AS_IS, true)+ .setContent(to === 'accepted' ? s.afterText : (s.beforeHtml ?? ''))+ .run();+ }+ setSuggestions((prev) => prev.map((x) => (x.id === s.id ? { ...x, status: to } : x)));+ if (to === 'accepted') toast.success(t('rewrite.acceptedToast'));+ else if (to === 'rejected') toast(t('rewrite.rejectedToast'));+ else toast(t('rewrite.undoneToast'));+ } catch (err) {+ console.error('Failed to decide the rewritten page:', err);+ toast.error(t('suggestions.saveFailed'));+ } finally {+ if (editable) editor.setEditable(true, false);+ setDeciding(false);+ }+ };// A full batch: the run stopped at its most, so it says to run it again.const fixedMessage = (count: number) =>@@ -661,6 +728,8 @@ export function DraftEditor({setFixing(false);}};+ // One agent run at a time from this page: the others wait for it.+ const agentBusy = fixing || starting || rewriting;const agentFix: AgentFix = {run: (only) => void fixRules(only),running: fixing,@@ -669,7 +738,9 @@ export function DraftEditor({? t('suggestions.decideFirst'): !citedRead? t('suggestions.citedLoading')- : null,+ : agentBusy && !fixing+ ? t('suggestions.agentBusy')+ : null,};// A drag with files over the page shows where they go; one dropped beside@@ -797,7 +868,7 @@ export function DraftEditor({toast.error(t(`agentFailed.errors.${result.error}`));return;}- onAgentStarted?.();+ onAgentStarted?.('write');} catch (err) {console.error('Failed to start the Content Agent again:', err);toast.error(t('agentFailed.errors.failed'));@@ -813,7 +884,82 @@ export function DraftEditor({? {run: () => void startAgent(),running: starting,- blocked: openSuggestions > 0 ? t('suggestions.decideFirst') : null,+ blocked:+ openSuggestions > 0+ ? t('suggestions.decideFirst')+ : agentBusy && !starting+ ? t('suggestions.agentBusy')+ : null,+ }+ : undefined;++ /**+ * Rewrite the page to these rules: the page as saved now, the rules in+ * effect here (with how the page reads against each), the person's own+ * rules and the passages still locked go to the Content Agent, which+ * rewrites the whole page in the background; the page waits for it, then+ * opens with the rewrite to compare.+ */+ const rewritePage = async () => {+ // Never before the locked passages are read: the rewrite would be told none are.+ if (!editor || agentBusy || !citedRead) return;+ setRewriting(true);+ try {+ await autosave.settle();+ const inEffect = rules.rules.filter(({ rule }) => rule.on);+ const locks = citedLocks(editor.state);+ 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: inEffect.map(({ rule }) => rule),+ textRules: rules.textRules.filter(({ rule }) => rule.on).map(({ rule }) => rule.text),+ },+ // The passages still locked here, the ones the person didn't unlock.+ [...locks.labels.keys()].filter((key) => !locks.unlocked.has(key)),+ );+ // Each rule says how the page reads now, as Apply rules with Agent's do.+ const statusOf = new Map(inEffect.map(({ rule, status }) => [rule.key, status]));+ request.rules = request.rules.map((rule) => {+ const status = statusOf.get(rule.key);+ if (!status || status.state !== 'bad') return rule;+ const now = `${tRules('agent.now')}: ${ruleStatusDetail(tStatus, status)}`;+ return { ...rule, detail: [rule.detail, now].filter(Boolean).join(' · ').slice(0, 500) };+ });+ const result = await startPageRewrite(draft.id, draft.brandId, request);+ if ('error' in result) {+ toast.error(t(`agentFailed.errors.${result.error}`));+ return;+ }+ onAgentStarted?.('rewrite');+ } catch (err) {+ console.error('Failed to start the page rewrite:', err);+ toast.error(t('agentFailed.errors.failed'));+ } finally {+ setRewriting(false);+ }+ };+ const pageRewrite: PageRewrite | undefined = canMarkReady+ ? {+ run: () => void rewritePage(),+ running: rewriting,+ blocked:+ openSuggestions > 0+ ? t('suggestions.decideFirst')+ : !citedRead+ ? t('suggestions.citedLoading')+ : agentBusy && !rewriting+ ? t('suggestions.agentBusy')+ : null,}: undefined;const markReady = async () => {@@ -1012,16 +1158,18 @@ export function DraftEditor({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="min-w-0 flex-1">+ {failedRewrite ? t('agentFailed.rewriteText') : t('agentFailed.text')}+ </span><span className="flex shrink-0 items-center gap-1"><Buttonvariant="outline"size="sm"className="h-7"- disabled={starting || !editor}- onClick={() => void startAgent()}+ disabled={agentBusy || !editor || (failedRewrite && !citedRead)}+ onClick={() => void (failedRewrite ? rewritePage() : startAgent())}>- {starting && <Loader2 className="h-3.5 w-3.5 animate-spin" />}+ {(starting || rewriting) && <Loader2 className="h-3.5 w-3.5 animate-spin" />}{t('agentFailed.retry')}</Button><Button@@ -1056,7 +1204,17 @@ export function DraftEditor({</span></p>)}- {suggestions.length > 0 && !(barClosed && openSuggestions === 0) && (+ {pageSuggestion && !(barClosed && openSuggestions === 0) && (+ <PageRewriteBar+ suggestion={pageSuggestion}+ rulesOpen={Math.max(0, rules.total - rules.met)}+ // Not while the HTML view holds the page: it would write over it.+ busy={deciding || htmlSource !== null}+ onDecide={(to) => void decidePage(pageSuggestion, to)}+ onClose={() => setBarClosed(true)}+ />+ )}+ {!pageSuggestion && suggestions.length > 0 && !(barClosed && openSuggestions === 0) && (<AgentBarsuggestions={suggestions}rulesOpen={Math.max(0, rules.total - rules.met)}@@ -1144,6 +1302,7 @@ export function DraftEditor({reads={reads}tabRequest={tabRequest}agentFix={agentFix}+ pageRewrite={pageRewrite}agentRewrite={agentRewrite}/>) : (diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-rewrite.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-rewrite.test.tsnew file mode 100644index 000000000..e4172c9b0--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-rewrite.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest';+import { pageChangedSince } from './_page-rewrite';++/** Rewrite the page to these rules: whether the page still reads as the agent read it. */+describe('pageChangedSince', () => {+ it('reads the editor’s HTML and stored HTML alike, line breaks and lists included', () => {+ const editor =+ '<h2>Pricing</h2><p>Plans start at $49.</p><ul><li><p>A</p></li><li><p>B</p></li></ul>';+ const stored =+ '<h2>Pricing</h2>\n<p>Plans start at $49.</p>\n<ul>\n<li>A</li>\n<li>B</li>\n</ul>';+ expect(pageChangedSince(editor, stored)).toBe(false);+ // Structured data isn't the page's words.+ expect(+ pageChangedSince(editor, `${stored}<script type="application/ld+json">{"a":1}</script>`),+ ).toBe(false);+ });++ it('says a page with other words changed', () => {+ expect(pageChangedSince('<p>Plans start at $49.</p>', '<p>Plans start at $59.</p>')).toBe(true);+ expect(pageChangedSince('<p>AB</p>', '<p>A</p><p>B</p>')).toBe(true);+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-rewrite.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-rewrite.tsxnew file mode 100644index 000000000..1018ad9b5--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_page-rewrite.tsx@@ -0,0 +1,212 @@+'use client';++import { useMemo, useState } from 'react';+import { useTranslations } from 'next-intl';+import { FileText, X } from 'lucide-react';+import { Button } from '@/components/ui/button';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import { passageKey } from '@/lib/content/cited-passages';+import { cleanHtml } from '@/lib/content/clean-html';+import { pageTextLength } from '@/lib/content/rules';+import type { DraftSuggestion, SuggestionStatus } from '@/lib/content/suggestions';+import { cn } from '@/lib/utils';++/**+ * Rewrite the page to these rules: the Content Agent's whole page, one+ * suggestion (kind 'page', 00247). The bar over the page says what it did,+ * Compare shows it beside the page as the agent read it, and Accept puts it+ * in place (History keeps the page first); Undo puts the page back.+ */++/** Blocks whose words a line break or a missing space must not run together. */+const BLOCKS = 'p, h1, h2, h3, h4, h5, h6, li, td, th, blockquote, div, br';++/**+ * The page's words, one space apart: formatting, markup and the space+ * between blocks don't count, so the editor's HTML (no space between+ * blocks) and stored HTML (line breaks between them) read the same.+ */+function wordsOf(html: string): string {+ const doc = new DOMParser().parseFromString(html, 'text/html');+ doc.querySelectorAll('script, style').forEach((el) => el.remove());+ doc.querySelectorAll(BLOCKS).forEach((el) => el.append(' '));+ return passageKey(doc.body.textContent ?? '');+}++/** Whether the page's words changed since the agent read it (or since it was put in place). */+export function pageChangedSince(currentHtml: string, readHtml: string): boolean {+ return wordsOf(currentHtml) !== wordsOf(readHtml);+}++/** The page as it reads, for Compare: the editor's prose, smaller. */+const PAGE_CLASS = cn(+ 'prose prose-sm prose-neutral max-w-none dark:prose-invert',+ 'prose-a:font-normal prose-a:text-blue-600 prose-a:underline dark:prose-a:text-blue-400',+ '[&_table]:w-full [&_td]:border [&_td]:px-2 [&_td]:py-1 [&_th]:border [&_th]:px-2 [&_th]:py-1',+ '[&_td>p]:my-0 [&_th>p]:my-0 [&_li>p]:my-0',+ // A page to read side by side: its links don't leave the editor.+ '[&_a]:pointer-events-none',+);++function PageColumn({ label, html }: { label: string; html: string }) {+ // Cleaned as a paste is: what the page holds, never a script that runs.+ // Its links read as links but go nowhere, by mouse or by keyboard.+ const clean = useMemo(() => {+ const doc = new DOMParser().parseFromString(+ cleanHtml(html, { keepImages: true }).html,+ 'text/html',+ );+ for (const link of doc.querySelectorAll('a[href]')) link.removeAttribute('href');+ return doc.body.innerHTML;+ }, [html]);+ return (+ <section aria-label={label} className="flex min-h-0 min-w-0 flex-col gap-1.5">+ <h3 className="text-xs font-medium text-muted-foreground">{label}</h3>+ <div+ className={cn(PAGE_CLASS, 'min-h-0 flex-1 overflow-y-auto rounded-lg border bg-card p-4')}+ dangerouslySetInnerHTML={{ __html: clean }}+ />+ </section>+ );+}++export function PageRewriteBar({+ suggestion,+ rulesOpen,+ busy,+ onDecide,+ onClose,+}: {+ suggestion: DraftSuggestion;+ rulesOpen: number;+ busy: boolean;+ /** accepted, rejected, or open again (Undo). */+ onDecide: (status: SuggestionStatus) => void;+ onClose: () => void;+}) {+ const t = useTranslations('contentEditor.editor.rewrite');+ const [comparing, setComparing] = useState(false);+ const before = pageTextLength(suggestion.beforeHtml ?? '');+ const after = pageTextLength(suggestion.afterText);+ const open = suggestion.status === 'open';+ const decide = (status: SuggestionStatus) => {+ setComparing(false);+ onDecide(status);+ };++ return (+ <div+ role="region"+ aria-label={t('bar')}+ className="flex flex-wrap items-center gap-x-3 gap-y-1.5 border-b bg-muted/40 px-4 py-1.5 text-[13px]"+ >+ <FileText aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />+ {/* Room for a line of text first: on a narrow page the buttons go under it. */}+ <span className="min-w-0 flex-1 basis-64">+ {open ? (+ <>+ <span className="font-medium">{t('ready')}</span>+ {' · '}+ {t('characters', { before, after })}+ <span className="text-muted-foreground">+ {' · '}+ {suggestion.reason}+ </span>+ </>+ ) : (+ <>+ <span className="font-medium">+ {suggestion.status === 'accepted' ? t('accepted') : t('rejected')}+ </span>+ {suggestion.status === 'accepted' && rulesOpen > 0 && (+ <span className="text-muted-foreground">+ {' · '}+ {t('rulesOpen', { count: rulesOpen })}+ </span>+ )}+ </>+ )}+ </span>+ <span className="ml-auto flex shrink-0 items-center gap-1.5">+ <Button+ variant="ghost"+ size="sm"+ className="h-7"+ disabled={busy}+ onClick={() => setComparing(true)}+ >+ {t('compare')}+ </Button>+ {open ? (+ <>+ <Button+ variant="outline"+ size="sm"+ className="h-7"+ disabled={busy}+ onClick={() => decide('rejected')}+ >+ {t('reject')}+ </Button>+ <Button size="sm" className="h-7" disabled={busy} onClick={() => decide('accepted')}>+ {t('accept')}+ </Button>+ </>+ ) : (+ <>+ <Button+ variant="outline"+ size="sm"+ className="h-7"+ disabled={busy}+ onClick={() => decide('open')}+ >+ {t('undo')}+ </Button>+ <Button+ variant="ghost"+ size="icon-sm"+ aria-label={t('close')}+ title={t('close')}+ onClick={onClose}+ >+ <X className="h-3.5 w-3.5" />+ </Button>+ </>+ )}+ </span>++ <Dialog open={comparing} onOpenChange={setComparing}>+ <DialogContent className="flex max-h-[90vh] flex-col sm:max-w-6xl">+ <DialogHeader>+ <DialogTitle>{t('compareTitle')}</DialogTitle>+ <DialogDescription>+ {t('characters', { before, after })} · {suggestion.reason}+ </DialogDescription>+ </DialogHeader>+ <div className="grid min-h-0 flex-1 grid-cols-1 gap-3 overflow-y-auto md:grid-cols-2 md:overflow-hidden">+ <PageColumn label={t('before', { count: before })} html={suggestion.beforeHtml ?? ''} />+ <PageColumn label={t('after', { count: after })} html={suggestion.afterText} />+ </div>+ {open && (+ <DialogFooter>+ <Button variant="outline" disabled={busy} onClick={() => decide('rejected')}>+ {t('reject')}+ </Button>+ <Button disabled={busy} onClick={() => decide('accepted')}>+ {t('accept')}+ </Button>+ </DialogFooter>+ )}+ </DialogContent>+ </Dialog>+ </div>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.test.tsxindex 27777effb..32924141c 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.test.tsx@@ -98,6 +98,43 @@ afterEach(() => {});describe('the Rules tab', () => {+ it('puts the agent’s two ways first, and recommends a rewrite far from Length', async () => {+ const fix = { run: vi.fn(), running: false, blocked: null };+ const rewrite = { run: vi.fn(), running: false, blocked: null };+ const show = async (props: Partial<Parameters<typeof RulesTab>[0]>) =>+ act(async () => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <RoleProvider role="admin">+ <RulesTab state={state()} siteType="b2b" draftPageType="feature_page" {...props} />+ </RoleProvider>+ </NextIntlClientProvider>,+ );+ });+ await show({ agentFix: fix, pageRewrite: rewrite });+ const labels = [...container.querySelectorAll('button')].map((b) => b.textContent);+ expect(labels.slice(0, 2)).toEqual([+ 'Apply rules with Agent',+ 'Rewrite the page to these rules',+ ]);+ const rewriteButton = () =>+ [...container.querySelectorAll('button')].find(+ (b) => b.textContent === 'Rewrite the page to these rules',+ )!;+ // 15,921 characters for a 3,000 Length.+ expect(container.querySelector('[role="note"]')!.textContent).toBe(+ 'Recommended: the page is 15,921 characters for a Length of 3,000 (431% off). A rewrite gets there in one go.',+ );+ await act(async () => rewriteButton().click());+ expect(rewrite.run).toHaveBeenCalled();++ // Suggestions still open: it says why it can't run.+ await show({ agentFix: fix, pageRewrite: { ...rewrite, blocked: 'Decide first' } });+ const blocked = rewriteButton();+ expect(blocked.disabled).toBe(true);+ expect(blocked.title).toBe('Decide first');+ });+it('lists the page type’s rules, then the shared groups, each with its status', async () => {const s = state();await render(s);diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsxindex 290f11bdf..6bc75c95f 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx@@ -2,7 +2,7 @@import { useState } from 'react';import { useTranslations } from 'next-intl';-import { Bot, Loader2 } from 'lucide-react';+import { Bot, FileText, Loader2, Sparkles } from 'lucide-react';import { Button } from '@/components/ui/button';import {Dialog,@@ -25,12 +25,14 @@ import { SITE_PAGE_TYPES, type SiteType } from '@/lib/content/page-types';import {MAX_TEXT_RULE_LENGTH,RULE_GROUPS,+ rewriteAdvice,splitRules,type ActiveRule,type RuleStatus,type TextRule,} from '@/lib/content/rules';import { formatNumber } from '@/lib/format';+import { AGENT_RUN_MAX } from '@/lib/content/suggestions';import { cn } from '@/lib/utils';import { useUserRole } from '@/hooks/use-user-role';import type { DraftRulesState } from './_use-draft-rules';@@ -68,17 +70,27 @@ export interface AgentFix {blocked: string | null;}+/** Rewrite the page to these rules, as the editor runs it: the whole page, one suggestion. */+export interface PageRewrite {+ run: () => void;+ running: boolean;+ /** Why it can't run now (suggestions still open), or null. */+ blocked: string | null;+}+export function RulesTab({state,siteType,draftPageType,agentFix,+ pageRewrite,onOpenSources,}: {state: DraftRulesState;siteType: SiteType;draftPageType: PageType | null;agentFix?: AgentFix;+ pageRewrite?: PageRewrite;/*** Opens the Sources tab, where a draft with no prompts (so no fan-outs)* gets them; none while the sources are read, or when the draft has prompts.@@ -104,6 +116,10 @@ export function RulesTab({})),];+ // Rewrite the page whole when small edits can't get there.+ const advice = pageRewrite ? rewriteAdvice(state.rules) : null;+ const agents = (agentFix || pageRewrite) && state.met < state.total;+// A draft on My rules for a type the workspace has none for (its type// changed, or My rules couldn't be read) shows Ansvisor's set for it.const source =@@ -118,6 +134,66 @@ export function RulesTab({aria-busy={!state.ready}className="m-0 min-w-0 space-y-4 border-0 p-0 text-sm">+ {/* The agent's two ways to meet the rules, first: a few edits a run,+ or the whole page rewritten as one change to compare. */}+ {agents && (+ <div className="space-y-1.5">+ {agentFix && (+ <Button+ size="sm"+ variant="outline"+ className="w-full"+ disabled={agentFix.running || agentFix.blocked !== null}+ title={agentFix.blocked ?? t('agentFixHint')}+ onClick={() => agentFix.run()}+ >+ {agentFix.running ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Bot className="h-3.5 w-3.5" />+ )}+ {agentFix.running ? t('agentFixing') : t('agentFix')}+ </Button>+ )}+ {pageRewrite && (+ <Button+ size="sm"+ variant={advice ? 'default' : 'outline'}+ className="w-full"+ disabled={pageRewrite.running || pageRewrite.blocked !== null}+ title={pageRewrite.blocked ?? t('rewriteHint')}+ onClick={() => pageRewrite.run()}+ >+ {pageRewrite.running ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <FileText className="h-3.5 w-3.5" />+ )}+ {pageRewrite.running ? t('rewriting') : t('rewrite')}+ </Button>+ )}+ {pageRewrite &&+ (advice ? (+ <p className="flex gap-1.5 text-xs" role="note">+ <Sparkles aria-hidden className="mt-0.5 h-3 w-3 shrink-0 text-muted-foreground" />+ <span>+ {advice.reason === 'length'+ ? t('rewriteAdvice.length', {+ count: advice.count,+ target: advice.target,+ percent: advice.percent,+ })+ : t('rewriteAdvice.open', { count: advice.count })}+ </span>+ </p>+ ) : (+ <p className="text-xs text-muted-foreground">+ {t('agentsHint', { max: AGENT_RUN_MAX })}+ </p>+ ))}+ </div>+ )}+<div className="space-y-1.5"><span className="text-xs text-muted-foreground">{t('set')}</span><Select@@ -143,23 +219,6 @@ export function RulesTab({<p className="text-xs text-muted-foreground" role="status">{t('met', { met: state.met, total: state.total })}</p>- {agentFix && state.met < state.total && (- <Button- size="sm"- variant="outline"- className="w-full"- disabled={agentFix.running || agentFix.blocked !== null}- title={agentFix.blocked ?? t('agentFixHint')}- onClick={() => agentFix.run()}- >- {agentFix.running ? (- <Loader2 className="h-3.5 w-3.5 animate-spin" />- ) : (- <Bot className="h-3.5 w-3.5" />- )}- {agentFix.running ? t('agentFixing') : t('agentFix')}- </Button>- )}</div>{RULE_GROUPS.map((group) => {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsxindex c9fe2a4e1..df77e73c2 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx@@ -6,7 +6,7 @@ import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';import { isPageType, type ContentDraft } from '@/lib/content/drafts';import { BriefTab, type AgentRewrite } from './_brief-tab';import { ImpactTab } from './_impact-tab';-import { RulesTab, type AgentFix } from './_rules-tab';+import { RulesTab, type AgentFix, type PageRewrite } from './_rules-tab';import { SourcesTab } from './_sources-tab';import { useBriefRebuild, type PageNow } from './_use-brief-rebuild';import type { DraftReads } from './_use-draft-reads';@@ -95,6 +95,7 @@ export function EditorSidePanel({reads,tabRequest,agentFix,+ pageRewrite,agentRewrite,}: {draft: ContentDraft;@@ -110,6 +111,8 @@ export function EditorSidePanel({tabRequest: { tab: PanelTab; n: number } | null;/** Fix open rules with agent, for the Rules tab (CE-018). */agentFix?: AgentFix;+ /** Rewrite the page to these rules, for the Rules tab; absent once the page is ready or published. */+ pageRewrite?: PageRewrite;/** Rewrite from brief, for the Brief tab; absent once the page is ready or published. */agentRewrite?: AgentRewrite;}) {@@ -201,6 +204,7 @@ export function EditorSidePanel({<div hidden={tab !== 'rules'}><RulesTabagentFix={agentFix}+ pageRewrite={pageRewrite}// Only a draft with no prompts gets no fan-outs for want of them.onOpenSources={reads.sources && !reads.sources.failed && reads.sources.data.prompts.length === 0diff --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 d518cb480..9bf49b5f4 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@@ -31,9 +31,11 @@ const decideDraftSuggestions = vi.fn();const keepAgentBeforeVersion = vi.fn();const fixDraftRules = vi.fn();const startAgentWriting = vi.fn();+const startPageRewrite = vi.fn();vi.mock('@/lib/actions/content-drafts', () => ({fixDraftRules: (...args: unknown[]) => fixDraftRules(...args),startAgentWriting: (...args: unknown[]) => startAgentWriting(...args),+ startPageRewrite: (...args: unknown[]) => startPageRewrite(...args),getDraftSuggestions: (...args: unknown[]) => getDraftSuggestions(...args),decideDraftSuggestions: (...args: unknown[]) => decideDraftSuggestions(...args),keepAgentBeforeVersion: (...args: unknown[]) => keepAgentBeforeVersion(...args),@@ -147,6 +149,7 @@ const draft = (over: Partial<ContentDraft> = {}): ContentDraft => ({action: null,agentState: null,agentSince: null,+ agentRun: null,updatedAt: '2026-10-20T10:00:00Z',...over,});@@ -211,6 +214,7 @@ beforeEach(() => {keepAgentBeforeVersion.mockReset().mockResolvedValue(undefined);fixDraftRules.mockReset().mockResolvedValue({ count: 0 });startAgentWriting.mockReset().mockResolvedValue({ started: true });+ startPageRewrite.mockReset().mockResolvedValue({ started: true });localStorage.clear();brandState.activeBrandId = 'b1';brandState.setActiveBrand.mockReset();@@ -2134,6 +2138,165 @@ describe('the side panel', () => {});});+ describe('Rewrite the page to these rules', () => {+ const long = draft({+ pageType: 'blog_post',+ bodyHtml: '<h1>Pipeline forecasting</h1><p>We delve into how teams forecast.</p>',+ });+ const rewritten = {+ id: 'p1',+ batchId: 'b3',+ actionId: null,+ actionNo: null,+ kind: 'page' as const,+ blockText: 'Pipeline forecasting',+ beforeText: '',+ beforeHtml: '<h1>Pipeline forecasting</h1><p>We delve into how teams forecast.</p>',+ afterText: '<h1>Pipeline forecasting</h1><p>Teams forecast from their pipeline.</p>',+ reason: 'cut to the Length and answered the heading first',+ ruleKeys: ['length', 'aiTraces'],+ status: 'open' as const,+ };+ async function openRules() {+ window.innerWidth = 1024;+ await renderPage();+ const chip = container.querySelector<HTMLButtonElement>(+ 'header button[aria-label^="Rules "]',+ )!;+ await act(async () => chip.click());+ }+ const button = (scope: ParentNode, label: string) =>+ [...scope.querySelectorAll<HTMLButtonElement>('button')].find(+ (b) => b.textContent === label,+ )!;+ const bar = () =>+ container.querySelector('[role="region"][aria-label="Rewritten page"]') as HTMLElement | null;+ const page = () => container.querySelector('.ProseMirror')!.textContent;++ it('sends the rules in effect, how the page reads against each, and the page waits', async () => {+ getContentDraft.mockResolvedValue(long);+ await openRules();++ await act(async () => button(panel()!, 'Rewrite the page to these rules').click());+ await act(async () => {});++ const [id, brandId, request] = startPageRewrite.mock.calls[0];+ expect([id, brandId]).toEqual(['d1', 'b1']);+ // An open rule says how the page reads now; locked passages come from the page.+ expect(request.rules).toContainEqual(+ expect.objectContaining({+ key: 'aiTraces',+ detail: expect.stringContaining('now: 1 found'),+ }),+ );+ expect(request.locked).toEqual([]);+ expect(fixDraftRules).not.toHaveBeenCalled();+ // The page waits for it, with the rewrite's own steps.+ expect(container.textContent).toContain('Rewriting the page');+ expect(container.querySelector('.ProseMirror')).toBeNull();+ });++ it('shows the rewrite to compare, puts it in place on Accept, and puts the page back on Undo', async () => {+ getContentDraft.mockResolvedValue(long);+ getDraftSuggestions.mockResolvedValue([rewritten]);+ await renderPage();+ await act(async () => {});++ expect(bar()!.textContent).toContain('Content Agent rewrote the page to its rules');+ // A whole page is never a card in the page.+ expect(container.querySelector('[data-suggestion]')).toBeNull();+ await act(async () => button(bar()!, 'Compare').click());+ const dialog = document.querySelector<HTMLElement>('[role="dialog"]')!;+ expect(dialog.textContent).toContain('Teams forecast from their pipeline.');+ expect(dialog.textContent).toContain('We delve into how teams forecast.');++ await act(async () => button(dialog, 'Accept').click());+ await act(async () => {});+ expect(keepAgentBeforeVersion).toHaveBeenCalledWith('d1');+ expect(decideDraftSuggestions).toHaveBeenCalledWith(['p1'], 'accepted');+ expect(page()).toContain('Teams forecast from their pipeline.');+ expect(bar()!.textContent).toContain('Rewrite accepted');++ await act(async () => button(bar()!, 'Undo').click());+ await act(async () => {});+ expect(decideDraftSuggestions).toHaveBeenLastCalledWith(['p1'], 'open');+ expect(page()).toContain('We delve into how teams forecast.');+ });++ it('reads the page by its words: stored line breaks and lists are no change', async () => {+ getContentDraft.mockResolvedValue(long);+ getDraftSuggestions.mockResolvedValue([+ {+ ...rewritten,+ beforeHtml: '<h1>Pipeline forecasting</h1>\n<p>We delve into how teams forecast.</p>\n',+ afterText:+ '<h1>Pipeline forecasting</h1>\n<ul>\n<li>Teams forecast</li>\n<li>from their pipeline</li>\n</ul>',+ },+ ]);+ await renderPage();+ await act(async () => {});++ await act(async () => button(bar()!, 'Accept').click());+ await act(async () => {});+ expect(decideDraftSuggestions).toHaveBeenCalledWith(['p1'], 'accepted');+ await act(async () => button(bar()!, 'Undo').click());+ await act(async () => {});+ expect(decideDraftSuggestions).toHaveBeenLastCalledWith(['p1'], 'open');+ expect(page()).toContain('We delve into how teams forecast.');+ });++ it('doesn’t undo a rewrite edited since it went in', async () => {+ getContentDraft.mockResolvedValue(long);+ getDraftSuggestions.mockResolvedValue([{ ...rewritten, status: 'accepted' as const }]);+ await renderPage();+ await act(async () => {});+ // The page as accepted, then a word of the person's own.+ const editor = (container.querySelector('.ProseMirror') as HTMLElement & { editor: Editor })+ .editor;+ await act(async () => {+ editor.commands.setContent(rewritten.afterText);+ editor.commands.insertContentAt(editor.state.doc.content.size - 1, ' Mine.');+ });++ await act(async () => button(bar()!, 'Undo').click());+ expect(toast).toHaveBeenCalledWith(+ 'The page changed after the rewrite was put in. To go back, open History.',+ );+ expect(decideDraftSuggestions).not.toHaveBeenCalled();+ });++ it('rewrites again from Try again after a rewrite failed, on any device', async () => {+ // The draft says which run failed (agent_run), not this browser's storage.+ getContentDraft.mockResolvedValue({ ...long, agentState: 'failed', agentRun: 'rewrite' });+ await renderPage();+ await act(async () => {});++ expect(container.textContent).toContain(+ "The Content Agent couldn't rewrite this page. Edit it yourself, or try again.",+ );+ await act(async () => button(container, 'Try again').click());+ await act(async () => {});+ expect(startPageRewrite).toHaveBeenCalled();+ expect(startAgentWriting).not.toHaveBeenCalled();+ });++ it('doesn’t put a rewrite over a page that changed since the agent read it', async () => {+ getContentDraft.mockResolvedValue(long);+ getDraftSuggestions.mockResolvedValue([+ { ...rewritten, beforeHtml: '<h1>Pipeline forecasting</h1><p>An older page.</p>' },+ ]);+ await renderPage();+ await act(async () => {});++ await act(async () => button(bar()!, 'Accept').click());+ expect(toast).toHaveBeenCalledWith(+ 'The page changed after the agent read it. Reject this rewrite and run it again on the page as it is now.',+ );+ expect(decideDraftSuggestions).not.toHaveBeenCalled();+ expect(page()).toContain('We delve into how teams forecast.');+ });+ });+it('starts a draft from the workspace’s My rules, and saves a draft’s set as them', async () => {getMyRuleSets.mockResolvedValue({blog_post: {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 c10e519a3..80012a8ad 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@@ -91,12 +91,13 @@ export default function ContentEditorPage() {title={current.draft.title}method={current.draft.method}since={current.draft.agentSince}+ rewrite={current.draft.agentRun === 'rewrite'}/>) : current.draft ? (<DraftEditorkey={current.draft.id}draft={current.draft}- onAgentStarted={() =>+ onAgentStarted={(run) =>setRead((prev) =>prev?.draft? {@@ -105,6 +106,7 @@ export default function ContentEditorPage() {...prev.draft,agentState: 'writing',agentSince: new Date().toISOString(),+ agentRun: run,},}: prev,diff --git a/web/src/lib/actions/content-drafts.test.ts b/web/src/lib/actions/content-drafts.test.tsindex 8d118fffc..5c1c11256 100644--- a/web/src/lib/actions/content-drafts.test.ts+++ b/web/src/lib/actions/content-drafts.test.ts@@ -55,7 +55,17 @@ vi.mock('@/lib/supabase/server', () => ({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 }),+ // The list, by its batch when one is asked for; the first row alone+ // when the read is for one (the latest batch).+ limit: () => {+ const batch = call.filters.find(([op, col]) => op === 'eq' && col === 'batch_id');+ const rows = batch+ ? list.filter((r) => (r as { batch_id?: unknown }).batch_id === batch[2])+ : list;+ return Object.assign(Promise.resolve({ data: rows, error: null }), {+ maybeSingle: async () => ({ data: rows[0] ?? null, error: null }),+ });+ },update: (value: unknown) => ((call.op = 'update'), (call.value = value), chain),insert: (value: unknown) => ((call.op = 'insert'), (call.value = value), chain),maybeSingle: async () => result(),@@ -573,11 +583,39 @@ describe('agent suggestions', () => {beforeText: 'very accurate',afterText: 'shown per team',afterLinks: null,+ beforeHtml: null,reason: 'answer a fan-out',ruleKeys: ['dated'],status: 'open',});expect(calls[0].filters).toContainEqual(['eq', 'draft_id', DRAFT]);+ // The latest batch is found first; only its rows are read whole.+ expect(calls[1].filters).toContainEqual(['eq', 'batch_id', 'new']);+ });++ it('reads none for a draft the agent never suggested on', async () => {+ list = [];+ await expect(getDraftSuggestions(DRAFT)).resolves.toEqual([]);+ expect(calls).toHaveLength(1);+ });++ it('reads a whole page rewritten, with the page the agent read (00247)', async () => {+ list = [+ row({+ kind: 'page',+ before_text: '',+ before_html: '<h1>Old</h1><p>Old page.</p>',+ after_text: '<h1>New</h1><p>New page.</p>',+ after_links: [{ start: 0, end: 3, href: 'https://acme.example' }],+ }),+ ];+ const [read] = await getDraftSuggestions(DRAFT);+ expect(read).toMatchObject({+ kind: 'page',+ beforeHtml: '<h1>Old</h1><p>Old page.</p>',+ afterText: '<h1>New</h1><p>New page.</p>',+ afterLinks: null,+ });});it('reads a replace’s links, keeping only safe ones inside its words (00240)', async () => {diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex 0f74f004e..f0859288f 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -10,6 +10,7 @@ import {LIBRARY_TABS,PAGE_TYPES,WRITING_STALE_MS,+ agentRunOf,agentStateOf,libraryTabCounts,type ContentDraft,@@ -216,7 +217,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, agent_state, agent_state_at, 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, agent_run, updated_at, ${BRAND_SITE}, actions(action_no)`,).eq('id', id).maybeSingle();@@ -241,6 +242,7 @@ export async function getContentDraft(id: string): Promise<ContentDraft | null>: null,agentState: agentStateOf(data.agent_state, data.agent_state_at),agentSince: data.agent_state_at,+ agentRun: agentRunOf(data.agent_run),updatedAt: data.updated_at,};}@@ -1374,20 +1376,29 @@ export async function keepAgentBeforeVersion(id: string): Promise<void> {export async function getDraftSuggestions(id: string): Promise<DraftSuggestion[]> {if (!draftId.safeParse(id).success) throw new Error('invalid');const supabase = await createClient();+ // The latest batch first, one row and no text: a past rewrite's two whole+ // pages are never read again (this runs on every open, and while Fix waits).+ const { data: latest, error: latestError } = await supabase+ .from('content_draft_suggestions')+ .select('batch_id')+ .eq('draft_id', id)+ .order('created_at', { ascending: false })+ .limit(1)+ .maybeSingle();+ if (latestError) throw new Error(latestError.message);+ if (!latest) return [];const { data, error } = await supabase.from('content_draft_suggestions').select(- 'id, batch_id, action_id, kind, block_text, before_text, after_text, after_links, reason, rule_keys, position, status, created_at, actions(action_no)',+ 'id, batch_id, action_id, kind, block_text, before_text, before_html, after_text, after_links, reason, rule_keys, position, status, created_at, actions(action_no)',).eq('draft_id', id)- .order('created_at', { ascending: false })+ .eq('batch_id', latest.batch_id).limit(MAX_DECIDE);if (error) throw new Error(error.message);- const rows = data ?? [];- const batch = rows[0]?.batch_id;const statuses: readonly string[] = SUGGESTION_STATUSES;- return rows- .filter((row) => row.batch_id === batch && statuses.includes(row.status))+ return (data ?? [])+ .filter((row) => statuses.includes(row.status)).sort((a, b) => a.position - b.position).map((row) => {const action = (Array.isArray(row.actions) ? row.actions[0] : row.actions) as {@@ -1398,11 +1409,13 @@ export async function getDraftSuggestions(id: string): Promise<DraftSuggestion[]batchId: row.batch_id,actionId: row.action_id,actionNo: action?.action_no ?? null,- kind: row.kind === 'insert' ? 'insert' : 'replace',+ kind: row.kind === 'insert' || row.kind === 'page' ? row.kind : 'replace',blockText: row.block_text,beforeText: row.before_text,afterText: row.after_text,- afterLinks: row.kind === 'insert' ? null : suggestionLinks(row.after_links, row.after_text),+ afterLinks:+ row.kind === 'replace' ? suggestionLinks(row.after_links, row.after_text) : null,+ beforeHtml: row.kind === 'page' ? row.before_html : null,reason: row.reason,ruleKeys: row.rule_keys ?? [],status: row.status as SuggestionStatus,@@ -1698,6 +1711,8 @@ const AGENT_FIX_ERRORS = ['empty','open_suggestions','published',+ /** Start or a rewrite holds the draft (another tab, another member). */+ 'writing','failed',/** No answer from the API (a timeout on the way): the agent may still finish. */'unconfirmed',@@ -1771,6 +1786,9 @@ const AGENT_WRITE_ERRORS = ['org_writing','open_suggestions','not_draft',+ // Rewrite the page to these rules: a page with no text, or one too long to send whole.+ 'empty',+ 'too_long','failed',] as const;export type AgentWriteError = (typeof AGENT_WRITE_ERRORS)[number];@@ -1786,6 +1804,29 @@ export async function startAgentWriting(id: string,brandId: string,request: AgentWriteRequest,+): Promise<{ started: true } | { error: AgentWriteError }> {+ return startAgentRun('write', id, brandId, request);+}++/**+ * Rewrite the page to these rules: the API's Content Agent rewrites the whole+ * page in the background (content-writer.js, rewrite) and leaves it as ONE+ * suggestion to compare and accept or reject. Returns once it has started;+ * 'empty' for a page with no text, 'too_long' for one too long to send whole.+ */+export async function startPageRewrite(+ id: string,+ brandId: string,+ request: AgentWriteRequest,+): Promise<{ started: true } | { error: AgentWriteError }> {+ return startAgentRun('rewrite', id, brandId, request);+}++async function startAgentRun(+ path: 'write' | 'rewrite',+ id: string,+ brandId: string,+ request: AgentWriteRequest,): Promise<{ started: true } | { error: AgentWriteError }> {if (!draftId.safeParse(id).success || !draftId.safeParse(brandId).success) {return { error: 'failed' };@@ -1796,7 +1837,7 @@ export async function startAgentWriting(} = await supabase.auth.getSession();if (!session) return { error: 'failed' };try {- const res = await fetch(`${API_BASE_URL}/api/content-drafts/${id}/write`, {+ const res = await fetch(`${API_BASE_URL}/api/content-drafts/${id}/${path}`, {method: 'POST',headers: {'Content-Type': 'application/json',@@ -1809,7 +1850,7 @@ export async function startAgentWriting(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);+ console.error(`Failed to start the Content Agent (${path}):`, err);return { error: 'failed' };}}diff --git a/web/src/lib/content/agent-write.ts b/web/src/lib/content/agent-write.tsindex de3f2591d..a519dd752 100644--- a/web/src/lib/content/agent-write.ts+++ b/web/src/lib/content/agent-write.ts@@ -99,6 +99,8 @@ export async function agentWriteRequest(},describe: RuleDescriber,inEffect?: { rules: ActiveRule[]; textRules: string[] },+ /** The locked passages' keys, as the editor holds them; read from the server otherwise. */+ locked?: string[],): Promise<AgentWriteRequest> {const setType = draft.rules.set ?? (isPageType(draft.pageType) ? draft.pageType : null);const [read, mine, cited] = await Promise.all([@@ -107,7 +109,7 @@ export async function agentWriteRequest(inEffect? null: getMyRuleSets(draft.brandId).catch((): Awaited<ReturnType<typeof getMyRuleSets>> => ({})),- draft.method === 'optimize' && draft.sourceUrl+ !locked && draft.method === 'optimize' && draft.sourceUrl? getCitedPassages(draft.id, pagePassages(draft.bodyHtml)): Promise.resolve(null),]);@@ -147,6 +149,6 @@ export async function agentWriteRequest(...describe(rule, FANOUT_RULES.has(rule.key) ? checkRule(rule, page, ctx) : undefined),})),textRules,- locked: (cited ?? []).map((passage) => passage.key),+ locked: locked ?? (cited ?? []).map((passage) => passage.key),};}diff --git a/web/src/lib/content/drafts.test.ts b/web/src/lib/content/drafts.test.tsindex f3d050d41..6981302ae 100644--- a/web/src/lib/content/drafts.test.ts+++ b/web/src/lib/content/drafts.test.ts@@ -4,6 +4,7 @@ import {DRAFT_STATUSES,PAGE_TYPES,WRITING_STALE_MS,+ agentRunOf,agentStateOf,contentEditorPath,draftsCreatedIn,@@ -119,3 +120,12 @@ describe('agentStateOf', () => {expect(agentStateOf('writing', null, now)).toBe('failed');});});++describe('agentRunOf', () => {+ it('reads the run that holds the draft, and nothing else', () => {+ expect(agentRunOf('write')).toBe('write');+ expect(agentRunOf('rewrite')).toBe('rewrite');+ expect(agentRunOf(null)).toBeNull();+ expect(agentRunOf('brief')).toBeNull();+ });+});diff --git a/web/src/lib/content/drafts.ts b/web/src/lib/content/drafts.tsindex 7d9fb20f3..63551cf74 100644--- a/web/src/lib/content/drafts.ts+++ b/web/src/lib/content/drafts.ts@@ -20,6 +20,17 @@ export type DraftMethod = 'create' | 'optimize';*/export type AgentState = 'writing' | 'failed' | null;+/**+ * Which run holds the draft, or last held it (content_drafts.agent_run,+ * 00247): Start with Agent, or Rewrite the page to these rules.+ */+export type AgentRun = 'write' | 'rewrite' | null;++/** A stored run, or null for anything else. */+export function agentRunOf(value: string | null | undefined): AgentRun {+ return value === 'write' || value === 'rewrite' ? value : null;+}+/** A 'writing' this old was left by a server that stopped (content-writer.js). */export const WRITING_STALE_MS = 10 * 60_000;@@ -149,6 +160,8 @@ export interface ContentDraft {agentState: AgentState;/** When the agent's state last changed: while it writes, when it started. */agentSince: string | null;+ /** Which run that is, for every device: a failed rewrite is tried again as one. */+ agentRun: AgentRun;updatedAt: string;}diff --git a/web/src/lib/content/rules.test.ts b/web/src/lib/content/rules.test.tsindex fa3269707..ebd354278 100644--- a/web/src/lib/content/rules.test.ts+++ b/web/src/lib/content/rules.test.ts@@ -27,6 +27,9 @@ import {startingRules,RULE_LENGTH_MIN,RULE_LENGTH_MAX,+ lengthBand,+ rewriteAdvice,+ type RuleStatus,} from './rules';const ctx: RuleContext = {@@ -648,6 +651,65 @@ describe('lengthConflict', () => {});});+describe('rewriteAdvice', () => {+ const statuses = (+ length: number | null,+ open: string[] = [],+ lengthValue = '8000',+ ): { rule: ActiveRule; status: RuleStatus }[] =>+ activeRules(ruleSet('blog_post'), { overrides: { length: { value: lengthValue } } }).map(+ (rule) => {+ if (rule.key === 'length' && length !== null) {+ const band = lengthBand(Number(rule.current));+ const ok = length >= band.min && length <= band.max;+ return {+ rule,+ status: ok+ ? { state: 'ok' as const }+ : {+ state: 'bad' as const,+ code: length > band.max ? ('long' as const) : ('short' as const),+ count: length,+ min: band.min,+ max: band.max,+ },+ };+ }+ return {+ rule,+ status: open.includes(rule.key)+ ? { state: 'bad' as const, code: 'missing' as const }+ : { state: 'ok' as const },+ };+ },+ );++ it('recommends a rewrite for a page more than 30% off its Length', () => {+ // The user's page: 19,203 characters for 8,000.+ expect(rewriteAdvice(statuses(19_203))).toEqual({+ reason: 'length',+ count: 19_203,+ target: 8_000,+ percent: 140,+ });+ // 30% off, no more, is for small edits.+ expect(rewriteAdvice(statuses(10_400))).toBeNull();+ // An empty page has nothing to rewrite; one past 60,000 can't be sent whole.+ expect(rewriteAdvice(statuses(0, ['faq', 'summary', 'h2Answer', 'keywords']))).toBeNull();+ expect(rewriteAdvice(statuses(60_001))).toBeNull();+ });++ it('recommends it for 4 rules or more the agent can fix', () => {+ expect(rewriteAdvice(statuses(null, ['faq', 'summary', 'h2Answer']))).toBeNull();+ expect(rewriteAdvice(statuses(null, ['faq', 'summary', 'h2Answer', 'keywords']))).toEqual({+ reason: 'open',+ count: 4,+ });+ // A rule it can't fix doesn't count.+ expect(rewriteAdvice(statuses(null, ['faq', 'summary', 'h2Answer', 'oneH1']))).toBeNull();+ });+});+describe('My rules and text rules', () => {const mine = {overrides: { sentence: { value: '120' } },diff --git a/web/src/lib/content/rules.ts b/web/src/lib/content/rules.tsindex 5746d30ec..0a07ca2c5 100644--- a/web/src/lib/content/rules.ts+++ b/web/src/lib/content/rules.ts@@ -755,6 +755,48 @@ export function openRulesForAgent<T extends { rule: ActiveRule; status: RuleStat};}+/** How far off its Length a page may be before Rewrite the page to these rules is recommended. */+export const REWRITE_LENGTH_OFF = 0.3;+/** How many rules the agent can fix may be open before it is. */+export const REWRITE_OPEN_RULES = 4;+/** The most text a page sent whole may hold (content-rewrite.js MAX_REWRITE_CHARS). */+export const REWRITE_MAX_CHARS = 60_000;++/** Why the Rules tab recommends rewriting the page whole. */+export type RewriteAdvice =+ | { reason: 'length'; count: number; target: number; percent: number }+ | { reason: 'open'; count: number };++/**+ * Whether the Rules tab recommends Rewrite the page to these rules over+ * Apply rules with Agent's few edits a run: the page more than 30% off its+ * Length, or 4 rules or more open that the agent can fix. Null otherwise.+ */+export function rewriteAdvice<T extends { rule: ActiveRule; status: RuleStatus }>(+ rules: T[],+): RewriteAdvice | null {+ const length = rules.find(({ rule }) => rule.key === 'length' && rule.on);+ const target = Number(length?.rule.current);+ const status = length?.status;+ // An empty page has nothing to rewrite, and one too long can't be sent whole.+ if (status && 'count' in status && (status.count === 0 || status.count > REWRITE_MAX_CHARS)) {+ return null;+ }+ if (+ status?.state === 'bad' &&+ (status.code === 'short' || status.code === 'long') &&+ Number.isFinite(target) &&+ target > 0+ ) {+ const off = Math.abs(status.count - target) / target;+ if (off > REWRITE_LENGTH_OFF) {+ return { reason: 'length', count: status.count, target, percent: Math.round(off * 100) };+ }+ }+ const open = openRulesForAgent(rules).forAgent.length;+ return open >= REWRITE_OPEN_RULES ? { reason: 'open', count: open } : null;+}+/** Checks one rule against the page as written. */export function checkRule(rule: ActiveRule, page: PageRead, ctx: RuleContext): RuleStatus {if (rule.check === 'feed') return { state: 'info', code: 'needsFeed' };diff --git a/web/src/lib/content/suggestions.ts b/web/src/lib/content/suggestions.tsindex c15c29da8..8a227c215 100644--- a/web/src/lib/content/suggestions.ts+++ b/web/src/lib/content/suggestions.ts@@ -5,7 +5,9 @@** A replace changes words in a passage (before → after, plain text); an* insert adds blocks (HTML) after a passage. Both find their passage by its- * text, as the agent read it.+ * text, as the agent read it. A page suggestion (00247, Rewrite the page to+ * these rules) is the whole page rewritten, alone in its batch: accepting it+ * puts its page in place of the one the agent read.*/import { safeLinkHref } from './editor';@@ -19,13 +21,15 @@ export interface DraftSuggestion {/** The Action Center action the run came from, with its number ("AC-214"). */actionId: string | null;actionNo: number | null;- kind: 'replace' | 'insert';+ kind: 'replace' | 'insert' | 'page';/** The passage's text when the agent read it. */blockText: string;/** replace: the words replaced; insert: empty. */beforeText: string;- /** replace: the new words; insert: the blocks added, as HTML. */+ /** replace: the new words; insert: the blocks added, as HTML; page: the whole page. */afterText: string;+ /** page: the page as the agent read it, put back on Undo. */+ beforeHtml?: string | null;/** replace: the links on the new words (00240); an insert's are in its HTML. */afterLinks?: SuggestionLink[] | null;/** Why, as the agent says it: "add a dated data point (rule)". */diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 81fc16598..480ac32cc 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -973,6 +973,7 @@ export type Database = {content_drafts: {Row: {action_id: string | null+ agent_run: string | nullagent_state: string | nullagent_state_at: string | nullarchived_at: string | null@@ -999,6 +1000,7 @@ export type Database = {}Insert: {action_id?: string | null+ agent_run?: string | nullagent_state?: string | nullagent_state_at?: string | nullarchived_at?: string | null@@ -1025,6 +1027,7 @@ export type Database = {}Update: {action_id?: string | null+ agent_run?: string | nullagent_state?: string | nullagent_state_at?: string | nullarchived_at?: string | null@@ -1125,6 +1128,7 @@ export type Database = {after_text: stringagent: stringbatch_id: string+ before_html: string | nullbefore_text: stringblock_text: stringcreated_at: string@@ -1144,6 +1148,7 @@ export type Database = {after_text: stringagent?: stringbatch_id: string+ before_html?: string | nullbefore_text?: stringblock_text: stringcreated_at?: string@@ -1163,6 +1168,7 @@ export type Database = {after_text?: stringagent?: stringbatch_id?: string+ before_html?: string | nullbefore_text?: stringblock_text?: stringcreated_at?: string