Skip to content

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.

feat(content): check the page against its rules in the editor's Rules tab (#1294)

Cihan89a91bb1e6de
diff --git a/supabase/migrations/00213_content_draft_rules.sql b/supabase/migrations/00213_content_draft_rules.sql
new file mode 100644
index 000000000..01c1ef3d3
--- /dev/null
+++ b/supabase/migrations/00213_content_draft_rules.sql
@@ -0,0 +1,22 @@
+-- ============================================================================
+-- 00213: a draft's rules, for the editor's Rules tab (Content Editor, CE-009)
+-- ============================================================================
+-- The Rules tab (Content Editor spec v2 §10) lists the rules a page of its
+-- type is written to — the type's own, then the shared groups (length and
+-- structure, fan-outs and keywords, links and sources, style) — and reads
+-- each one's status from the page as written. The rules themselves are the
+-- app's (web/src/lib/content/rules.ts); a draft keeps only what the person
+-- changed for it.
+--
+-- * content_drafts.rules: {set, overrides} — the page type whose set
+-- applies (null follows the draft's type) and, per rule, whether it is
+-- on and the value the draft uses ("Rule updated for this draft"). Null
+-- until something changes. A member edits it like the body, so it isn't
+-- a server column.
+
+alter table public.content_drafts
+ add column if not exists rules jsonb
+ check (rules is null or (jsonb_typeof(rules) = 'object' and octet_length(rules::text) <= 32768));
+
+comment on column public.content_drafts.rules is
+ 'The draft''s rule choices (CE-009): the page type whose rule set applies (null = the draft''s type) and per-rule overrides {on, value}. Null until changed.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 49a11539d..6afacf640 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -29863,3 +29863,29 @@ alter table public.prompt_improve_usage
comment on column public.prompt_improve_usage.content_draft_id is
'The Content Editor draft whose brief this generation rebuilt (CE-007). Null for an Improve tab or task-writer generation.';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00213_content_draft_rules.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00213: a draft's rules, for the editor's Rules tab (Content Editor, CE-009)
+-- ============================================================================
+-- The Rules tab (Content Editor spec v2 §10) lists the rules a page of its
+-- type is written to — the type's own, then the shared groups (length and
+-- structure, fan-outs and keywords, links and sources, style) — and reads
+-- each one's status from the page as written. The rules themselves are the
+-- app's (web/src/lib/content/rules.ts); a draft keeps only what the person
+-- changed for it.
+--
+-- * content_drafts.rules: {set, overrides} — the page type whose set
+-- applies (null follows the draft's type) and, per rule, whether it is
+-- on and the value the draft uses ("Rule updated for this draft"). Null
+-- until something changes. A member edits it like the body, so it isn't
+-- a server column.
+
+alter table public.content_drafts
+ add column if not exists rules jsonb
+ check (rules is null or (jsonb_typeof(rules) = 'object' and octet_length(rules::text) <= 32768));
+
+comment on column public.content_drafts.rules is
+ 'The draft''s rule choices (CE-009): the page type whose rule set applies (null = the draft''s type) and per-rule overrides {on, value}. Null until changed.';
+
diff --git a/web/messages/en.json b/web/messages/en.json
index 929410a95..5af4e79b1 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3418,7 +3418,8 @@
"tabs": {
"impact": "Impact",
"brief": "Brief",
- "sources": "Sources"
+ "sources": "Sources",
+ "rules": "Rules"
}
},
"impact": {
@@ -3573,7 +3574,7 @@
"goal": "Goal",
"audience": "Audience",
"length": "Length",
- "lengthValue": "{count} characters · from the page type",
+ "lengthValue": "{count} characters · from the rules",
"outline": "Outline",
"answers": "Answers “{fanout}”",
"keywords": "Keywords",
@@ -3607,6 +3608,97 @@
"saved": "Brief saved",
"failed": "Couldn't save the brief. Try again."
}
+ },
+ "rulesChip": "Rules {met}/{total}",
+ "rulesChipShort": "{met}/{total}",
+ "rulesChipHint": "Rules this page meets now. Open the Rules tab.",
+ "rules": {
+ "set": "Rule set",
+ "setName": "{type} · Ansvisor default",
+ "pickSet": "Pick a page type",
+ "met": "{met} of {total} rules met",
+ "typeGroup": "{type} rules",
+ "groups": {
+ "type": "Page type rules",
+ "structure": "Length and structure",
+ "fanouts": "Fan-outs and keywords",
+ "links": "Links and sources",
+ "style": "Style"
+ },
+ "names": {
+ "sentence": "Max sentence length",
+ "length": "Length",
+ "summary": "AI Overview summary at the top",
+ "h2Answer": "Direct answer under each H2",
+ "fanoutH2": "Use top fan-outs as H2s",
+ "faq": "FAQ block",
+ "fanoutFaq": "Use fan-outs in FAQ questions",
+ "keywords": "Keywords to include",
+ "internalLinks": "Internal links (anchor text)",
+ "outboundLinks": "Outbound links to trusted sources (anchor text)",
+ "datedPoint": "Dated data point in the first 100 words",
+ "citeInline": "Cite sources inline",
+ "aiTraces": "Remove AI traces (humanize)",
+ "bannedWords": "Banned words",
+ "tone": "Tone",
+ "language": "Language",
+ "comparisonTable": "Comparison table vs alternatives",
+ "whoFor": "Who it's for, in one sentence",
+ "proofPerSection": "Proof: customer number or quote",
+ "industryNamed": "Name the industry in H1 and summary",
+ "useCaseSteps": "Use case steps",
+ "sideBySide": "Side-by-side table",
+ "fairness": "Fair: name where the competitor wins",
+ "specsTable": "Specs table",
+ "feedMatch": "Price, GTIN and stock match the feed",
+ "fitQuestions": "Answer fit and sizing questions",
+ "first40Words": "Type + key attributes in the first 40 words",
+ "introText": "Intro text above products",
+ "buyingFaq": "Buying tips + FAQ",
+ "currentPrices": "Prices and dates are current",
+ "bestTime": "Best time to visit in the summary"
+ },
+ "hints": {
+ "summary": "A short summary under the H1 that answer engines can quote.",
+ "fanoutH2": "Takes the top fan-outs you keep in Sources, the most searched first, not every one.",
+ "internalLinks": "Links with descriptive anchor text to your own pages.",
+ "outboundLinks": "Descriptive anchor text to an authoritative source: research, a standards body, government or a well-known publication. Never a competitor. Opens in a new tab.",
+ "aiTraces": "Finds phrases that read as machine-written (delve, in today's fast-paced world, not only… but also). Fixing them comes with the Content Agent.",
+ "whoFor": "Who the page is for, in one sentence, e.g. \"Sales leaders at 20–200 person B2B teams\".",
+ "first40Words": "ChatGPT reads about the first 50 tokens (~40 words) of a product description. The rest is ignored.",
+ "feedMatch": "Checked against the product feed once it's connected."
+ },
+ "units": {
+ "characters": "characters",
+ "wordsMax": "words max",
+ "wordsMin": "words min",
+ "fanouts": "fan-outs",
+ "questions": "questions",
+ "links": "links",
+ "perSection": "per section",
+ "steps": "steps"
+ },
+ "toggle": "{name}: on or off",
+ "value": "{name}: value",
+ "whoForPlaceholder": "e.g. Sales leaders at 20–200 person B2B teams",
+ "note": "Values you change apply to this draft only. Rules marked AI check are judged by the Content Agent and aren't counted yet.",
+ "updated": "Rule updated for this draft",
+ "saveFailed": "Couldn't update the rule. Try again.",
+ "status": {
+ "off": "Off",
+ "over": "{count} over",
+ "found": "{count} found",
+ "partOf": "{count} of {of}",
+ "words": "{count} words",
+ "missing": "Missing",
+ "noH2": "No H2 yet",
+ "needsFaq": "Needs FAQ",
+ "notSet": "Not set",
+ "aiCheck": "AI check",
+ "needsFeed": "Needs feed",
+ "noFanouts": "No fan-outs",
+ "addKeywords": "Add keywords"
+ }
}
},
"status": {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.test.tsx
index 03dcc7d5a..736f7c4c7 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.test.tsx
@@ -46,7 +46,7 @@ let root: Root;
async function render(
state: BriefState,
- extra: { pageType?: string | null; sourceUrl?: string | null } = {},
+ extra: { pageType?: string | null; sourceUrl?: string | null; length?: number } = {},
) {
await act(async () => {
root.render(
@@ -55,6 +55,7 @@ async function render(
draftId="d1"
state={state}
pageType={extra.pageType === undefined ? 'buying_guide' : extra.pageType}
+ length={extra.length ?? 3000}
sourceUrl={
extra.sourceUrl === undefined ? 'https://acme.example/guides/espresso' : extra.sourceUrl
}
@@ -105,7 +106,7 @@ describe('the Brief tab', () => {
'Target URL': '/guides/espresso',
Goal: 'Help home baristas pick a machine',
Audience: 'First-time espresso buyers',
- Length: '3,000 characters · from the page type',
+ Length: '3,000 characters · from the rules',
});
const sections = [...container.querySelectorAll('ol > li')].map((li) => li.textContent);
expect(sections).toEqual([
@@ -120,12 +121,15 @@ describe('the Brief tab', () => {
});
it('offers to build a brief for a new page without one', async () => {
- await render({ status: 'ready', brief: null }, { pageType: 'product_page', sourceUrl: null });
+ await render(
+ { status: 'ready', brief: null },
+ { pageType: 'product_page', sourceUrl: null, length: 1200 },
+ );
expect(fields()).toMatchObject({
'Page type': 'Product page',
'Target URL': 'A new page',
Goal: '—',
- Length: '1,200 characters · from the page type',
+ Length: '1,200 characters · from the rules',
});
expect(container.textContent).toContain('No outline yet.');
expect(button('Edit brief')).toBeUndefined();
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx
index e289efaeb..045d3ddb1 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_brief-tab.tsx
@@ -9,7 +9,6 @@ import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { saveDraftBrief } from '@/lib/actions/content-drafts';
import { MAX_BRIEF_SECTIONS, builtFromCount, type DraftBrief } from '@/lib/content/brief';
-import { lengthTarget } from '@/lib/content/editor';
import { platformNames } from '@/lib/content/impact';
import { pagePath } from '@/lib/content/overlap';
import { formatDateTime, formatNumber } from '@/lib/format';
@@ -31,6 +30,7 @@ export function BriefTab({
draftId,
state,
pageType,
+ length,
sourceUrl,
rebuilding,
onRebuild,
@@ -40,6 +40,8 @@ export function BriefTab({
draftId: string;
state: BriefState;
pageType: string | null;
+ /** The length the rules ask for (CE-009). */
+ length: number;
sourceUrl: string | null;
rebuilding: boolean;
onRebuild: () => void;
@@ -99,7 +101,7 @@ export function BriefTab({
<dt className="text-muted-foreground">{t('audience')}</dt>
<dd>{brief?.audience || '—'}</dd>
<dt className="text-muted-foreground">{t('length')}</dt>
- <dd>{t('lengthValue', { count: formatNumber(lengthTarget(pageType)) })}</dd>
+ <dd>{t('lengthValue', { count: formatNumber(length) })}</dd>
</dl>
{brief && brief.outline.length > 0 ? (
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.tsx
index f4827306b..e9f908b99 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
@@ -22,12 +22,7 @@ import {
htmlFromSource,
publishableHtml,
} from '@/lib/content/clean-html';
-import {
- PAGE_READ_DELAY_MS,
- draftTitleFromDoc,
- lengthTarget,
- safeLinkHref,
-} from '@/lib/content/editor';
+import { PAGE_READ_DELAY_MS, draftTitleFromDoc, safeLinkHref } from '@/lib/content/editor';
import { JsonLd } from '@/lib/content/json-ld-node';
import { detectPageType } from '@/lib/content/page-types';
import { cn } from '@/lib/utils';
@@ -35,6 +30,8 @@ import { DropOverlay, useAttachments } from './_attach';
import { HtmlBlock, copyToClipboard } from './_html-block';
import { PageTypeMenu } from './_page-type-menu';
import { EditorSidePanel, useSidePanelOpen } from './_side-panel';
+import { useDraftReads } from './_use-draft-reads';
+import { useDraftRules } from './_use-draft-rules';
import { EditorToolbar } from './_toolbar';
import { useDraftAutosave, type SaveState } from './_use-autosave';
@@ -68,7 +65,9 @@ const DOCUMENT_CLASS = cn(
* whole page, or one block, on the clipboard. The page type follows the page
* as it is written until the person picks one (CE-023). The side panel, open
* beside the page or closed from the header, shows what the page earns
- * (Impact, CE-016) and the sources it draws on (Sources, CE-008).
+ * (Impact, CE-016), its brief and the sources it draws on (CE-007, CE-008)
+ * and the rules it is written to (CE-009); the header's chip says how many
+ * of those rules the page meets now.
*/
export function DraftEditor({ draft }: { draft: ContentDraft }) {
const t = useTranslations('contentEditor.editor');
@@ -94,6 +93,8 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
const [dragging, setDragging] = useState(false);
const dragDepth = useRef(0);
const [panelOpen, togglePanel] = useSidePanelOpen();
+ // The header's rules chip opens the panel on Rules.
+ const [tabRequest, setTabRequest] = useState<{ tab: 'rules'; n: number } | null>(null);
const editor = useEditor({
extensions: [
@@ -177,6 +178,16 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
});
const attachments = useAttachments(editor);
+ // The rules the page is written to, checked as it reads now (CE-009).
+ // The brief and sources, read once: the rules check against them, the panel shows them.
+ const reads = useDraftReads(draft.id);
+ const rules = useDraftRules({
+ draft,
+ html: pageHtml,
+ characters: (editor?.storage.characterCount.characters() as number | undefined) ?? 0,
+ pageType,
+ reads,
+ });
useEffect(() => {
attachRef.current = (files) => void attachments.attach(files);
});
@@ -320,11 +331,41 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
<span className="shrink-0">
<DraftStatusBadge status={status} />
</span>
+ <button
+ type="button"
+ onClick={() => {
+ if (!panelOpen) togglePanel();
+ setTabRequest((prev) => ({ tab: 'rules', n: (prev?.n ?? 0) + 1 }));
+ }}
+ title={t('rulesChipHint')}
+ aria-label={t('rulesChip', { met: rules.met, total: rules.total })}
+ className={cn(
+ 'inline-flex shrink-0 items-center gap-1.5 rounded-full border px-2 py-0.5 text-xs font-medium',
+ rules.total > 0 && rules.met === rules.total
+ ? 'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-900 dark:bg-emerald-950 dark:text-emerald-300'
+ : 'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-300',
+ )}
+ >
+ <span aria-hidden className="h-1.5 w-1.5 rounded-full bg-current" />
+ {/* Short on a narrow window, so the header stays one line. */}
+ <span aria-hidden className="hidden xl:inline">
+ {t('rulesChip', { met: rules.met, total: rules.total })}
+ </span>
+ <span aria-hidden className="xl:hidden">
+ {t('rulesChipShort', { met: rules.met, total: rules.total })}
+ </span>
+ </button>
<div className="ml-auto flex shrink-0 items-center gap-3">
<SaveIndicator state={autosave.state} onRetry={() => void autosave.retry()} />
- <Button variant="outline" size="sm" onClick={copyPageHtml} title={t('copyHtmlHint')}>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={copyPageHtml}
+ title={t('copyHtmlHint')}
+ aria-label={t('copyHtml')}
+ >
<Copy className="h-3.5 w-3.5" />
- {t('copyHtml')}
+ <span className="hidden xl:inline">{t('copyHtml')}</span>
</Button>
<Button
size="sm"
@@ -363,7 +404,7 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
{editor && (
<EditorToolbar
editor={editor}
- target={lengthTarget(pageType)}
+ target={rules.length}
htmlView={htmlSource !== null}
onToggleHtml={htmlSource === null ? openHtmlView : applyHtmlView}
onAttach={attachments.open}
@@ -410,7 +451,15 @@ export function DraftEditor({ draft }: { draft: ContentDraft }) {
{attachments.ui}
</div>
{panelOpen && (
- <EditorSidePanel draft={draft} title={title} bodyHtml={pageHtml} pageType={pageType} />
+ <EditorSidePanel
+ draft={draft}
+ title={title}
+ bodyHtml={pageHtml}
+ pageType={pageType}
+ rules={rules}
+ reads={reads}
+ tabRequest={tabRequest}
+ />
)}
</div>
</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.tsx
new file mode 100644
index 000000000..5aef79ebd
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.test.tsx
@@ -0,0 +1,139 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../../../../../../messages/en.json';
+import {
+ activeRules,
+ checkRule,
+ readPage,
+ ruleSet,
+ rulesMet,
+ type DraftRules,
+} from '@/lib/content/rules';
+import { RulesTab } from './_rules-tab';
+import type { DraftRulesState } from './_use-draft-rules';
+
+(
+ globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT: boolean;
+ }
+).IS_REACT_ACT_ENVIRONMENT = true;
+
+const change = vi.fn();
+const pickSet = vi.fn();
+
+function state(choices: DraftRules = { set: null, overrides: {} }): DraftRulesState {
+ const rules = activeRules(ruleSet('feature_page'), choices);
+ const page = readPage(
+ '<h1>Pipeline forecasting</h1><p>A seamless way to forecast in 2026.</p><table><tr><td>x</td></tr></table>',
+ 2610,
+ );
+ const checked = rules.map((rule) => ({
+ rule,
+ status: checkRule(rule, page, { brandDomains: [], competitorDomains: [], fanouts: [] }),
+ }));
+ return {
+ setType: 'feature_page',
+ rules: checked,
+ ...rulesMet(checked),
+ length: 3000,
+ change,
+ pickSet,
+ };
+}
+
+let container: HTMLDivElement;
+let root: Root;
+
+async function render(s: DraftRulesState) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <RulesTab state={s} siteType="b2b" draftPageType="feature_page" />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+const row = (name: string) =>
+ [...container.querySelectorAll('li')].find((li) => li.textContent?.includes(name))!;
+const setValue = (input: HTMLInputElement, value: string) => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+};
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ change.mockReset();
+ pickSet.mockReset();
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+describe('the Rules tab', () => {
+ it('lists the page type’s rules, then the shared groups, each with its status', async () => {
+ const s = state();
+ await render(s);
+ expect([...container.querySelectorAll('h4')].map((h) => h.textContent)).toEqual([
+ 'Feature page rules',
+ 'Length and structure',
+ 'Fan-outs and keywords',
+ 'Links and sources',
+ 'Style',
+ ]);
+ expect(container.textContent).toContain(`${s.met} of ${s.total} rules met`);
+ expect(row('Comparison table vs alternatives').textContent).toContain('✓');
+ expect(row("Who it's for").textContent).toContain('Not set');
+ expect(row('Length').textContent).toContain('2,610');
+ expect(row('Banned words').textContent).toContain('1 found');
+ expect(row('Tone').textContent).toContain('AI check');
+ expect(row('Use top fan-outs as H2s').textContent).toContain('No fan-outs');
+ });
+
+ it('changes a value for this draft when the field is left', async () => {
+ await render(state());
+ const input = row('Max sentence length').querySelector('input')!;
+ await act(async () => {
+ input.focus();
+ setValue(input, '120');
+ });
+ await act(async () => input.blur());
+ expect(change).toHaveBeenCalledWith('sentence', { value: '120' });
+
+ // A number rule keeps a number.
+ change.mockReset();
+ await act(async () => {
+ input.focus();
+ setValue(input, 'many');
+ });
+ await act(async () => input.blur());
+ expect(change).not.toHaveBeenCalled();
+
+ const who = row("Who it's for").querySelector('input')!;
+ await act(async () => {
+ who.focus();
+ setValue(who, 'Sales leaders at B2B teams');
+ });
+ await act(async () => who.blur());
+ expect(change).toHaveBeenCalledWith('whoFor', { value: 'Sales leaders at B2B teams' });
+ });
+
+ it('turns a rule off, and shows it off', async () => {
+ await render(state());
+ await act(async () =>
+ row('Cite sources inline').querySelector<HTMLElement>('[role="switch"]')!.click(),
+ );
+ expect(change).toHaveBeenCalledWith('citeInline', { on: false });
+
+ await render(state({ set: null, overrides: { citeInline: { on: false } } }));
+ const off = row('Cite sources inline');
+ expect(off.querySelector('[role="switch"]')!.getAttribute('aria-checked')).toBe('false');
+ expect(off.textContent).toContain('Off');
+ });
+});
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.tsx
new file mode 100644
index 000000000..d5461be12
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx
@@ -0,0 +1,248 @@
+'use client';
+
+import { useState } from 'react';
+import { useTranslations } from 'next-intl';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { isPageType, type PageType } from '@/lib/content/drafts';
+import { SITE_PAGE_TYPES, type SiteType } from '@/lib/content/page-types';
+import { RULE_GROUPS, type ActiveRule, type RuleStatus } from '@/lib/content/rules';
+import { formatNumber } from '@/lib/format';
+import { cn } from '@/lib/utils';
+import type { DraftRulesState } from './_use-draft-rules';
+
+/** Rules with an explanation on hover (spec §10). */
+const HINTED = new Set([
+ 'summary',
+ 'fanoutH2',
+ 'internalLinks',
+ 'outboundLinks',
+ 'aiTraces',
+ 'whoFor',
+ 'first40Words',
+ 'feedMatch',
+]);
+
+/**
+ * The Rules tab (Content Editor CE-009, spec §10): the rule set for the
+ * page's type — its own rules, then length and structure, fan-outs and
+ * keywords, links and sources, style — each with an on/off switch, a value
+ * the person can change for this draft, and its status as the page reads
+ * now. "N of M rules met" counts the rules on that the page can say; the
+ * header's chip shows the same.
+ */
+export function RulesTab({
+ state,
+ siteType,
+ draftPageType,
+}: {
+ state: DraftRulesState;
+ siteType: SiteType;
+ draftPageType: PageType | null;
+}) {
+ const t = useTranslations('contentEditor.editor.rules');
+ const tTypes = useTranslations('contentEditor.pageTypes');
+ const types = [...SITE_PAGE_TYPES[siteType]];
+ for (const type of [draftPageType, state.setType]) {
+ if (type && !types.includes(type)) types.push(type);
+ }
+ const items = types.map((type) => ({ value: type, label: t('setName', { type: tTypes(type) }) }));
+
+ return (
+ <div className="space-y-4 text-sm">
+ <div className="space-y-1.5">
+ <span className="text-xs text-muted-foreground">{t('set')}</span>
+ <Select
+ items={items}
+ value={state.setType ?? ''}
+ onValueChange={(value) => {
+ if (!isPageType(value)) return;
+ state.pickSet(value === draftPageType ? null : value);
+ }}
+ >
+ <SelectTrigger aria-label={t('set')} className="w-full">
+ <SelectValue placeholder={t('pickSet')} />
+ </SelectTrigger>
+ <SelectContent>
+ {items.map((item) => (
+ <SelectItem key={item.value} value={item.value}>
+ {item.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <p className="text-xs text-muted-foreground" role="status">
+ {t('met', { met: state.met, total: state.total })}
+ </p>
+ </div>
+
+ {RULE_GROUPS.map((group) => {
+ const rows = state.rules.filter((r) => r.rule.group === group);
+ if (!rows.length) return null;
+ return (
+ <section key={group} className="space-y-1.5">
+ <h4 className="text-xs font-medium text-muted-foreground">
+ {group === 'type' && state.setType
+ ? t('typeGroup', { type: tTypes(state.setType) })
+ : t(`groups.${group}`)}
+ </h4>
+ <ul className="divide-y rounded-lg border">
+ {rows.map(({ rule, status }) => (
+ <RuleRow
+ key={rule.key}
+ rule={rule}
+ status={status}
+ onChange={(change) => state.change(rule.key, change)}
+ />
+ ))}
+ </ul>
+ </section>
+ );
+ })}
+
+ <p className="text-[11px] text-muted-foreground">{t('note')}</p>
+ </div>
+ );
+}
+
+function RuleRow({
+ rule,
+ status,
+ onChange,
+}: {
+ rule: ActiveRule;
+ status: RuleStatus;
+ onChange: (change: { on?: boolean; value?: string }) => void;
+}) {
+ const t = useTranslations('contentEditor.editor.rules');
+ const name = t(`names.${rule.key}`);
+ return (
+ <li className={cn('px-3 py-2', !rule.on && 'opacity-60')}>
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ role="switch"
+ aria-checked={rule.on}
+ aria-label={t('toggle', { name })}
+ onClick={() => onChange({ on: !rule.on })}
+ className={cn(
+ 'relative h-4 w-7 shrink-0 rounded-full transition-colors',
+ rule.on ? 'bg-primary' : 'bg-muted-foreground/30',
+ )}
+ >
+ <span
+ className={cn(
+ 'absolute top-0.5 h-3 w-3 rounded-full bg-background transition-all',
+ rule.on ? 'left-3.5' : 'left-0.5',
+ )}
+ />
+ </button>
+ <span
+ className="min-w-0 flex-1 text-xs"
+ title={HINTED.has(rule.key) ? t(`hints.${rule.key}`) : undefined}
+ >
+ {name}
+ </span>
+ <StatusBadge on={rule.on} status={status} />
+ </div>
+ {rule.kind !== 'switch' && (
+ <div className="mt-1 flex items-center gap-1 pl-9">
+ <RuleValue rule={rule} name={name} onCommit={(value) => onChange({ value })} />
+ </div>
+ )}
+ </li>
+ );
+}
+
+/** A rule's value: changed for this draft when the field is left or Enter is pressed. */
+function RuleValue({
+ rule,
+ name,
+ onCommit,
+}: {
+ rule: ActiveRule;
+ name: string;
+ onCommit: (value: string) => void;
+}) {
+ const t = useTranslations('contentEditor.editor.rules');
+ const [text, setText] = useState(rule.current);
+ const [editing, setEditing] = useState(false);
+ const shown = editing ? text : rule.current;
+
+ const commit = () => {
+ setEditing(false);
+ const value = text.trim();
+ if (value === rule.current) return;
+ if (rule.kind === 'number' && !/^\d{1,6}$/.test(value)) return;
+ onCommit(value);
+ };
+
+ const wide = rule.kind !== 'number';
+ return (
+ <span className={cn('flex items-center gap-1', wide ? 'min-w-0 flex-1' : 'shrink-0')}>
+ <input
+ value={shown}
+ inputMode={rule.kind === 'number' ? 'numeric' : undefined}
+ aria-label={t('value', { name })}
+ placeholder={rule.key === 'whoFor' ? t('whoForPlaceholder') : undefined}
+ maxLength={500}
+ onFocus={() => {
+ setText(rule.current);
+ setEditing(true);
+ }}
+ onChange={(e) => setText(e.target.value)}
+ onBlur={commit}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') e.currentTarget.blur();
+ if (e.key === 'Escape') {
+ setText(rule.current);
+ setEditing(false);
+ }
+ }}
+ className={cn(
+ 'h-6 rounded-md border bg-background px-1.5 text-xs tabular-nums outline-none focus-visible:ring-2 focus-visible:ring-ring/50',
+ wide ? 'min-w-0 flex-1' : 'w-14 text-right',
+ rule.changed && 'border-primary/50',
+ )}
+ />
+ {rule.unit && (
+ <span className="text-[11px] whitespace-nowrap text-muted-foreground">
+ {t(`units.${rule.unit}`)}
+ </span>
+ )}
+ </span>
+ );
+}
+
+function StatusBadge({ on, status }: { on: boolean; status: RuleStatus }) {
+ const t = useTranslations('contentEditor.editor.rules.status');
+ if (!on) {
+ return (
+ <span className="w-20 shrink-0 text-right text-[11px] text-muted-foreground">{t('off')}</span>
+ );
+ }
+ let text: string;
+ if (status.state === 'ok') text = '✓';
+ else if (status.code === 'partOf') text = t('partOf', { count: status.count, of: status.of });
+ else if (status.code === 'current') text = formatNumber(status.count);
+ else if ('count' in status) text = t(status.code, { count: status.count });
+ else text = t(status.code);
+ return (
+ <span
+ className={cn(
+ 'w-20 shrink-0 truncate text-right text-[11px] font-medium',
+ status.state === 'ok' && 'text-emerald-600 dark:text-emerald-400',
+ status.state === 'bad' && 'text-amber-600 dark:text-amber-400',
+ status.state === 'info' && 'font-normal text-muted-foreground',
+ )}
+ title={text}
+ >
+ {text}
+ </span>
+ );
+}
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.tsx
index e76c9af37..db499bf72 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
@@ -3,12 +3,14 @@
import { useEffect, useRef, useState } from 'react';
import { useTranslations } from 'next-intl';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
-import type { ContentDraft } from '@/lib/content/drafts';
-import { getDraftBrief } from '@/lib/actions/content-drafts';
-import { BriefTab, type BriefState } from './_brief-tab';
+import { isPageType, type ContentDraft } from '@/lib/content/drafts';
+import { BriefTab } from './_brief-tab';
import { ImpactTab } from './_impact-tab';
+import { RulesTab } from './_rules-tab';
import { SourcesTab } from './_sources-tab';
import { useBriefRebuild, type PageNow } from './_use-brief-rebuild';
+import type { DraftReads } from './_use-draft-reads';
+import type { DraftRulesState } from './_use-draft-rules';
/** Remembers whether the panel is open, across drafts and visits. */
const PANEL_OPEN_KEY = 'aeo:content-editor-panel';
@@ -42,41 +44,47 @@ export function useSidePanelOpen(): [boolean, () => void] {
return [open, toggle];
}
-const PANEL_TABS = ['impact', 'brief', 'sources'] as const;
-type PanelTab = (typeof PANEL_TABS)[number];
+const PANEL_TABS = ['impact', 'brief', 'sources', 'rules'] as const;
+export type PanelTab = (typeof PANEL_TABS)[number];
/**
* The editor's right panel (Content Editor spec v2 §6), 400px beside the page.
* The spec's tabs are Impact · Chat · Brief · Sources · Rules; each joins the
- * panel with the update that makes it work: Impact (CE-016), Brief (CE-007)
- * and Sources (CE-008). A tab opened once stays mounted, so switching back
- * keeps it as it was. The brief is held here: Sources' "Rebuild with
- * selection" and Impact's "Use lost prompts" rebuild it too, and open it.
+ * panel with the update that makes it work: Impact (CE-016), Brief (CE-007),
+ * Sources (CE-008) and Rules (CE-009). A tab opened once stays mounted, so switching back
+ * keeps it as it was. The brief and the sources are the editor's one read
+ * (useDraftReads), which the rules check against too: Sources' "Rebuild with
+ * selection" and Impact's "Use lost prompts" rebuild the brief, and open it.
*/
export function EditorSidePanel({
draft,
title,
bodyHtml,
pageType,
+ rules,
+ reads,
+ tabRequest,
}: {
draft: ContentDraft;
/** The draft's title, page and type as written now: Sources and Brief read them. */
title: string;
bodyHtml: string;
pageType: string | null;
+ /** The rules, as the editor checks them (the header's chip shows the same). */
+ rules: DraftRulesState;
+ /** The draft's brief and sources, read once for the editor. */
+ reads: DraftReads;
+ /** A tab to open, from outside the panel (the header's rules chip). */
+ tabRequest: { tab: PanelTab; n: number } | null;
}) {
const t = useTranslations('contentEditor.editor.panel');
const [tab, setTab] = useState<PanelTab>('impact');
const [opened, setOpened] = useState<Set<PanelTab>>(() => new Set(['impact']));
- const [brief, setBrief] = useState<BriefState>({ status: 'loading' });
- const [briefAttempt, setBriefAttempt] = useState(0);
- // Read afresh after prompts join the draft.
- const [sourcesVersion, setSourcesVersion] = useState(0);
- const page = useRef<PageNow>({ title, html: bodyHtml, pageType });
- const briefNow = useRef(brief);
+ const page = useRef<PageNow>({ title, html: bodyHtml, length: rules.length });
+ const sourcesNow = useRef(reads.sources);
useEffect(() => {
- page.current = { title, html: bodyHtml, pageType };
- briefNow.current = brief;
+ page.current = { title, html: bodyHtml, length: rules.length };
+ sourcesNow.current = reads.sources;
});
const open = (next: PanelTab) => {
@@ -84,30 +92,21 @@ export function EditorSidePanel({
setOpened((prev) => (prev.has(next) ? prev : new Set([...prev, next])));
};
- const briefOpened = opened.has('brief');
+ const requested = tabRequest?.n;
useEffect(() => {
- // A brief already in hand (a rebuild from Sources or Impact) isn't read again.
- if (!briefOpened || briefNow.current.status !== 'loading') return;
- let cancelled = false;
- getDraftBrief(draft.id)
- .then((result) => {
- if (!cancelled)
- setBrief(result ? { status: 'ready', brief: result.brief } : { status: 'failed' });
- })
- .catch((err) => {
- console.error('Failed to read the brief:', err);
- if (!cancelled) setBrief({ status: 'failed' });
- });
- return () => {
- cancelled = true;
- };
- }, [draft.id, briefOpened, briefAttempt]);
+ if (tabRequest) open(tabRequest.tab);
+ // Only a new request opens a tab.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [requested]);
+
+ const briefOpened = opened.has('brief');
const { rebuilding, rebuild } = useBriefRebuild({
draft,
pageNow: () => page.current,
+ sourcesNow: () => sourcesNow.current,
onRebuilt: (next) => {
- setBrief({ status: 'ready', brief: next });
+ reads.setBrief(next);
open('brief');
},
});
@@ -134,7 +133,7 @@ export function EditorSidePanel({
pageUrl={draft.sourceUrl}
rebuilding={rebuilding}
onUseLostPrompts={(promptIds) =>
- void rebuild({ addPrompts: promptIds }).then(() => setSourcesVersion((n) => n + 1))
+ void rebuild({ addPrompts: promptIds }).then(() => reads.reloadSources())
}
/>
</div>
@@ -142,23 +141,23 @@ export function EditorSidePanel({
<div hidden={tab !== 'brief'}>
<BriefTab
draftId={draft.id}
- state={brief}
+ state={reads.brief}
pageType={pageType}
+ length={rules.length}
sourceUrl={draft.sourceUrl}
rebuilding={rebuilding}
onRebuild={() => void rebuild()}
- onRetry={() => {
- setBrief({ status: 'loading' });
- setBriefAttempt((n) => n + 1);
- }}
- onSaved={(saved) => setBrief({ status: 'ready', brief: saved })}
+ onRetry={reads.reloadBrief}
+ onSaved={(saved) => reads.setBrief(saved)}
/>
</div>
)}
{opened.has('sources') && (
<div hidden={tab !== 'sources'}>
<SourcesTab
- key={sourcesVersion}
+ read={reads.sources}
+ setRead={reads.setSources}
+ onReload={reads.reloadSources}
draftId={draft.id}
brandId={draft.brandId}
title={title}
@@ -169,6 +168,15 @@ export function EditorSidePanel({
/>
</div>
)}
+ {opened.has('rules') && (
+ <div hidden={tab !== 'rules'}>
+ <RulesTab
+ state={rules}
+ siteType={draft.siteType}
+ draftPageType={isPageType(pageType) ? pageType : null}
+ />
+ </div>
+ )}
</div>
</aside>
);
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.test.tsx
index bf2fafa8e..a1e4fe4e4 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.test.tsx
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import messages from '../../../../../../../../messages/en.json';
import type { DraftSourceChoice, DraftSourcesData } from '@/lib/content/sources';
import { SourcesTab } from './_sources-tab';
+import { useDraftReads } from './_use-draft-reads';
const getDraftSources = vi.fn();
const setDraftSourceIncluded = vi.fn();
@@ -12,6 +13,7 @@ const addDraftSource = vi.fn();
const getContentStartOptions = vi.fn();
vi.mock('@/lib/actions/content-drafts', () => ({
getDraftSources: (...args: unknown[]) => getDraftSources(...args),
+ getDraftBrief: async () => null,
setDraftSourceIncluded: (...args: unknown[]) => setDraftSourceIncluded(...args),
addDraftSource: (...args: unknown[]) => addDraftSource(...args),
getContentStartOptions: (...args: unknown[]) => getContentStartOptions(...args),
@@ -71,10 +73,15 @@ async function render(
});
}
+/** The tab as the editor gives it its sources: one read, shared (useDraftReads). */
function Tab({ bodyHtml }: { bodyHtml: string }) {
+ const reads = useDraftReads('d1');
return (
<NextIntlClientProvider locale="en" messages={messages}>
<SourcesTab
+ read={reads.sources}
+ setRead={reads.setSources}
+ onReload={reads.reloadSources}
draftId="d1"
brandId="b1"
title="The home espresso guide"
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx
index 24b7371d1..6be3a0e64 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_sources-tab.tsx
@@ -1,12 +1,12 @@
'use client';
-import { useDeferredValue, useEffect, useMemo, useState } from 'react';
+import { useDeferredValue, useMemo, useState, type Dispatch, type SetStateAction } from 'react';
import { useTranslations } from 'next-intl';
import { toast } from 'sonner';
import { Loader2, Plus, RefreshCw } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
-import { getDraftSources, setDraftSourceIncluded } from '@/lib/actions/content-drafts';
+import { setDraftSourceIncluded } from '@/lib/actions/content-drafts';
import { platformNames } from '@/lib/content/impact';
import {
buildSourceGroups,
@@ -21,10 +21,7 @@ import {
import { formatNumber } from '@/lib/format';
import { cn } from '@/lib/utils';
import { AddSourceDialog } from './_add-source-dialog';
-
-type SourcesRead =
- | { data: DraftSourcesData; choices: DraftSourceChoice[]; failed: false }
- | { data: null; choices: []; failed: true };
+import type { SourcesRead } from './_use-draft-reads';
/**
* The Sources tab (Content Editor CE-008, spec §10): every source the draft
@@ -32,8 +29,13 @@ type SourcesRead =
* pages their answers cite, and the brand's Search Console queries — each
* with its numbers and where the draft uses it as written now. A person
* unchecks a source to leave it out, or adds a prompt, a page or a query.
+ * The sources are the editor's read (useDraftReads), which the rules check
+ * against too.
*/
export function SourcesTab({
+ read,
+ setRead,
+ onReload,
draftId,
brandId,
title,
@@ -42,6 +44,11 @@ export function SourcesTab({
rebuilding,
onRebuild,
}: {
+ /** The sources as the editor read them; null while reading. */
+ read: SourcesRead | null;
+ setRead: Dispatch<SetStateAction<SourcesRead | null>>;
+ /** Reads them again: after a failure, or once a source was added. */
+ onReload: () => void;
draftId: string;
brandId: string;
title: string;
@@ -52,30 +59,8 @@ export function SourcesTab({
onRebuild: (sources: { data: DraftSourcesData; choices: DraftSourceChoice[] }) => void;
}) {
const t = useTranslations('contentEditor.editor.sources');
- const [read, setRead] = useState<SourcesRead | null>(null);
- const [attempt, setAttempt] = useState(0);
const [adding, setAdding] = useState(false);
- useEffect(() => {
- let cancelled = false;
- getDraftSources(draftId)
- .then((result) => {
- if (cancelled) return;
- setRead(
- result
- ? { data: result.data, choices: result.choices, failed: false }
- : { data: null, choices: [], failed: true },
- );
- })
- .catch((err) => {
- console.error('Failed to read the draft sources:', err);
- if (!cancelled) setRead({ data: null, choices: [], failed: true });
- });
- return () => {
- cancelled = true;
- };
- }, [draftId, attempt]);
-
// Where each source is used follows the page as it is written, a beat behind typing.
const html = useDeferredValue(bodyHtml);
const doc = useMemo(() => readDraftDoc(html), [html]);
@@ -95,14 +80,7 @@ export function SourcesTab({
return (
<p className="flex items-center gap-2 text-xs text-muted-foreground">
{t('loadError')}
- <button
- type="button"
- className="font-medium underline"
- onClick={() => {
- setRead(null);
- setAttempt((n) => n + 1);
- }}
- >
+ <button type="button" className="font-medium underline" onClick={onReload}>
{t('retry')}
</button>
</p>
@@ -202,7 +180,7 @@ export function SourcesTab({
brandId={brandId}
gscQueries={read.data.gscQueries}
listed={groups.flatMap((g) => g.rows.map((r) => `${r.kind}:${r.ref}`))}
- onAdded={() => setAttempt((n) => n + 1)}
+ onAdded={onReload}
/>
</div>
);
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.ts
index fb915e4da..a0a6421a1 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brief-rebuild.ts
@@ -7,27 +7,33 @@ import { addDraftPrompts, getDraftSources, rebuildDraftBrief } from '@/lib/actio
import { builtFromCount, rebuildSources, type DraftBrief } from '@/lib/content/brief';
import type { ContentDraft } from '@/lib/content/drafts';
import type { DraftSourceChoice, DraftSourcesData } from '@/lib/content/sources';
+import type { SourcesRead } from './_use-draft-reads';
/** The page as written now: a rebuild reads its headings and length. */
export interface PageNow {
title: string;
html: string;
- pageType: string | null;
+ /** The length the rules ask for. */
+ length: number;
}
/**
* Rebuild outline (CE-007), from the Brief tab, Sources' "Rebuild with
* selection" or Impact's "Use lost prompts": the sources kept (as the
- * Sources tab has them, or read afresh), the page as written now, and the
- * brief the server writes from them, metered from the AI usage budget.
+ * editor has them, or read afresh once prompts were added), the page as
+ * written now, and the brief the server writes from them, metered from the
+ * AI usage budget.
*/
export function useBriefRebuild({
draft,
pageNow,
+ sourcesNow,
onRebuilt,
}: {
draft: ContentDraft;
pageNow: () => PageNow;
+ /** The sources as the editor has them; null until read. */
+ sourcesNow: () => SourcesRead | null;
onRebuilt: (brief: DraftBrief) => void;
}) {
const t = useTranslations('contentEditor.editor.brief');
@@ -41,8 +47,12 @@ export function useBriefRebuild({
): Promise<boolean> => {
setRebuilding(true);
try {
- if (options.addPrompts?.length) await addDraftPrompts(draft.id, options.addPrompts);
- const read = options.sources ?? (await getDraftSources(draft.id));
+ const added = !!options.addPrompts?.length;
+ if (added) await addDraftPrompts(draft.id, options.addPrompts!);
+ // Prompts just added aren't in the sources in hand: those are read afresh.
+ const inHand = added ? null : sourcesNow();
+ const read =
+ options.sources ?? (inHand && !inHand.failed ? inHand : await getDraftSources(draft.id));
if (!read) throw new Error('not_found');
const page = pageNow();
const result = await rebuildDraftBrief(
@@ -52,7 +62,7 @@ export function useBriefRebuild({
title: page.title,
sourceUrl: draft.sourceUrl,
html: page.html,
- pageType: page.pageType,
+ length: page.length,
}),
);
if ('error' in result) {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-reads.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-reads.ts
new file mode 100644
index 000000000..2a4892eb5
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-reads.ts
@@ -0,0 +1,90 @@
+'use client';
+
+import { useCallback, useEffect, useState, type Dispatch, type SetStateAction } from 'react';
+import { getDraftBrief, getDraftSources } from '@/lib/actions/content-drafts';
+import type { DraftBrief } from '@/lib/content/brief';
+import type { DraftSourceChoice, DraftSourcesData } from '@/lib/content/sources';
+import type { BriefState } from './_brief-tab';
+
+export type SourcesRead =
+ | { data: DraftSourcesData; choices: DraftSourceChoice[]; failed: false }
+ | { data: null; choices: []; failed: true };
+
+export interface DraftReads {
+ brief: BriefState;
+ /** Null while the sources are read. */
+ sources: SourcesRead | null;
+ /** The brief as a rebuild or an edit left it. */
+ setBrief: (brief: DraftBrief | null) => void;
+ /** The sources as the Sources tab changed them (a source left out or kept). */
+ setSources: Dispatch<SetStateAction<SourcesRead | null>>;
+ reloadBrief: () => void;
+ /** Reads the sources again: prompts, a page or a query joined the draft. */
+ reloadSources: () => void;
+}
+
+/**
+ * A draft's brief and sources (CE-007, CE-008), read once when the editor
+ * opens and shared: the rules check against them (CE-009), the side panel's
+ * Brief and Sources tabs show them, and Rebuild outline builds from them. A
+ * rebuild, an edit or a source checked changes them here, so the rules never
+ * check against a brief or sources the person no longer sees.
+ */
+export function useDraftReads(draftId: string): DraftReads {
+ const [brief, setBriefState] = useState<BriefState>({ status: 'loading' });
+ const [sources, setSources] = useState<SourcesRead | null>(null);
+ const [briefAttempt, setBriefAttempt] = useState(0);
+ const [sourcesAttempt, setSourcesAttempt] = useState(0);
+
+ useEffect(() => {
+ let cancelled = false;
+ getDraftBrief(draftId)
+ .then((result) => {
+ if (!cancelled) {
+ setBriefState(result ? { status: 'ready', brief: result.brief } : { status: 'failed' });
+ }
+ })
+ .catch((err) => {
+ console.error('Failed to read the brief:', err);
+ if (!cancelled) setBriefState({ status: 'failed' });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [draftId, briefAttempt]);
+
+ useEffect(() => {
+ let cancelled = false;
+ getDraftSources(draftId)
+ .then((result) => {
+ if (cancelled) return;
+ setSources(
+ result
+ ? { data: result.data, choices: result.choices, failed: false }
+ : { data: null, choices: [], failed: true },
+ );
+ })
+ .catch((err) => {
+ console.error('Failed to read the draft sources:', err);
+ if (!cancelled) setSources({ data: null, choices: [], failed: true });
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [draftId, sourcesAttempt]);
+
+ const setBrief = useCallback(
+ (next: DraftBrief | null) => setBriefState({ status: 'ready', brief: next }),
+ [],
+ );
+ const reloadBrief = useCallback(() => {
+ setBriefState({ status: 'loading' });
+ setBriefAttempt((n) => n + 1);
+ }, []);
+ const reloadSources = useCallback(() => {
+ setSources(null);
+ setSourcesAttempt((n) => n + 1);
+ }, []);
+
+ return { brief, sources, setBrief, setSources, reloadBrief, reloadSources };
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.ts
new file mode 100644
index 000000000..afbf3ce95
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.ts
@@ -0,0 +1,127 @@
+'use client';
+
+import { useDeferredValue, useMemo, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { saveDraftRules } from '@/lib/actions/content-drafts';
+import { isPageType, type ContentDraft, type PageType } from '@/lib/content/drafts';
+import {
+ activeRules,
+ checkRule,
+ readPage,
+ ruleLength,
+ ruleSet,
+ rulesMet,
+ type ActiveRule,
+ type DraftRules,
+ type RuleContext,
+ type RuleStatus,
+} from '@/lib/content/rules';
+import { buildSourceGroups } from '@/lib/content/sources';
+import type { DraftReads } from './_use-draft-reads';
+
+export interface DraftRulesState {
+ /** The page type whose set applies. */
+ setType: PageType | null;
+ rules: { rule: ActiveRule; status: RuleStatus }[];
+ met: number;
+ total: number;
+ /** The page length the rules ask for. */
+ length: number;
+ /** Turns a rule on or off, or gives it a value, for this draft. */
+ change: (key: string, change: { on?: boolean; value?: string }) => void;
+ /** Applies another page type's set, or the draft's own (null). */
+ pickSet: (type: PageType | null) => void;
+}
+
+/**
+ * The draft's rules (CE-009) as the editor reads them: the set for its page
+ * type with the person's changes, each checked against the page as written —
+ * the header's chip and the Rules tab show the same. The brand's domains,
+ * the fan-outs kept and the brief's keywords come from the editor's one read
+ * of the sources and the brief (useDraftReads), so a rebuild, an edit or a
+ * source checked shows in the rules at once.
+ */
+export function useDraftRules({
+ draft,
+ html,
+ characters,
+ pageType,
+ reads,
+}: {
+ draft: ContentDraft;
+ html: string;
+ characters: number;
+ pageType: string | null;
+ reads: Pick<DraftReads, 'brief' | 'sources'>;
+}): DraftRulesState {
+ const t = useTranslations('contentEditor.editor.rules');
+ const [choices, setChoices] = useState<DraftRules>(draft.rules);
+
+ const sources = reads.sources;
+ const ctx = useMemo<RuleContext>(() => {
+ if (!sources || sources.failed) return { brandDomains: [], competitorDomains: [], fanouts: [] };
+ const fanouts = buildSourceGroups(sources.data, sources.choices, {
+ title: draft.title,
+ sourceUrl: draft.sourceUrl,
+ })
+ .find((g) => g.kind === 'fanout')
+ ?.rows.filter((r) => r.included)
+ .map((r) => r.name);
+ return {
+ brandDomains: sources.data.brandDomains,
+ competitorDomains: sources.data.competitorDomains,
+ fanouts: fanouts ?? [],
+ };
+ }, [sources, draft.title, draft.sourceUrl]);
+ const brief = reads.brief;
+ const keywords = useMemo(
+ () => (brief.status === 'ready' ? (brief.brief?.keywords ?? []) : []),
+ [brief],
+ );
+
+ const draftType = isPageType(pageType) ? pageType : null;
+ const setType = choices.set ?? draftType;
+ const rules = useMemo(
+ () => activeRules(ruleSet(setType, { keywords }), choices),
+ [setType, keywords, choices],
+ );
+ // The checks follow the page a beat behind typing.
+ const deferredHtml = useDeferredValue(html);
+ const deferredCharacters = useDeferredValue(characters);
+ const page = useMemo(
+ () => readPage(deferredHtml, deferredCharacters),
+ [deferredHtml, deferredCharacters],
+ );
+ const checked = useMemo(
+ () => rules.map((rule) => ({ rule, status: checkRule(rule, page, ctx) })),
+ [rules, page, ctx],
+ );
+ const { met, total } = rulesMet(checked);
+
+ const save = (next: DraftRules) => {
+ const before = choices;
+ setChoices(next);
+ saveDraftRules(draft.id, next)
+ .then(() => toast(t('updated')))
+ .catch((err) => {
+ console.error('Failed to save the rules:', err);
+ setChoices(before);
+ toast.error(t('saveFailed'));
+ });
+ };
+
+ return {
+ setType,
+ rules: checked,
+ met,
+ total,
+ length: ruleLength(rules, setType),
+ change: (key, change) =>
+ save({
+ ...choices,
+ overrides: { ...choices.overrides, [key]: { ...choices.overrides[key], ...change } },
+ }),
+ pickSet: (type) => save({ ...choices, set: type }),
+ };
+}
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.tsx
index ddb678953..8dad1bff7 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
@@ -15,7 +15,9 @@ const getContentResults = vi.fn();
const getDraftSources = vi.fn();
const getDraftBrief = vi.fn();
const rebuildDraftBrief = vi.fn();
+const saveDraftRules = vi.fn();
vi.mock('@/lib/actions/content-drafts', () => ({
+ saveDraftRules: (...args: unknown[]) => saveDraftRules(...args),
getDraftSources: (...args: unknown[]) => getDraftSources(...args),
getDraftBrief: (...args: unknown[]) => getDraftBrief(...args),
rebuildDraftBrief: (...args: unknown[]) => rebuildDraftBrief(...args),
@@ -114,6 +116,7 @@ const draft = (over: Partial<ContentDraft> = {}): ContentDraft => ({
status: 'in_review',
bodyHtml: '<h1>Pipeline forecasting</h1><p>Teams trust it.</p>',
author: 'agent',
+ rules: { set: null, overrides: {} },
updatedAt: '2026-10-20T10:00:00Z',
...over,
});
@@ -151,6 +154,7 @@ beforeEach(() => {
getDraftSources.mockReset().mockResolvedValue(null);
getDraftBrief.mockReset().mockResolvedValue({ brief: null });
rebuildDraftBrief.mockReset();
+ saveDraftRules.mockReset().mockResolvedValue(undefined);
localStorage.clear();
brandState.activeBrandId = 'b1';
brandState.setActiveBrand.mockReset();
@@ -613,7 +617,9 @@ describe('the side panel', () => {
getContentDraft.mockResolvedValue(draft({ sourceUrl: 'https://acme.example.com/pricing' }));
window.innerWidth = 1440;
await renderPage();
- expect(getDraftSources).not.toHaveBeenCalled();
+ // The editor reads the sources once on opening; the tab itself isn't there yet.
+ expect(getDraftSources).toHaveBeenCalledTimes(1);
+ expect(panel()!.textContent).not.toContain('pipeline forecasting');
const tab = [...panel()!.querySelectorAll<HTMLElement>('[role="tab"]')].find(
(el) => el.textContent === 'Sources',
@@ -622,7 +628,8 @@ describe('the side panel', () => {
tab.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
tab.click();
});
- expect(getDraftSources).toHaveBeenCalledWith('d1');
+ // The tab shows the editor's one read: nothing is read again.
+ expect(getDraftSources).toHaveBeenCalledTimes(1);
// The draft's H1 carries the fan-out's words.
expect(panel()!.textContent).toContain('pipeline forecasting');
expect(panel()!.textContent).toContain('H1');
@@ -653,7 +660,7 @@ describe('the side panel', () => {
platform: 'copilot-web',
},
],
- keywords: [],
+ keywords: ['forecast accuracy', 'pipeline'],
origin: 'rebuild',
builtAt: '2026-10-21T10:00:00Z',
builtFrom: { prompts: 0, fanouts: 1, pages: 0, queries: 0 },
@@ -676,6 +683,7 @@ describe('the side panel', () => {
'Impact',
'Brief',
'Sources',
+ 'Rules',
]);
await pick('Sources');
await act(async () => button('Rebuild with selection')!.click());
@@ -693,6 +701,49 @@ describe('the side panel', () => {
expect(selected?.textContent).toBe('Brief');
expect(panel()!.textContent).toContain('How pipeline forecasting works');
expect(panel()!.textContent).toContain('Win forecasting searches');
+
+ // The rules check against the brief just rebuilt, without a reload.
+ await pick('Rules');
+ expect(
+ [...panel()!.querySelectorAll<HTMLInputElement>('input')].map((input) => input.value),
+ ).toContain('forecast accuracy, pipeline');
+ });
+
+ it('shows how many rules the page meets, and opens them from the header', async () => {
+ getContentDraft.mockResolvedValue(
+ draft({
+ pageType: 'blog_post',
+ bodyHtml: '<h1>Pipeline forecasting</h1><p>Teams trust it in 2026.</p>',
+ }),
+ );
+ window.innerWidth = 1024;
+ await renderPage();
+ expect(panel()).toBeNull();
+
+ const chip = container.querySelector<HTMLButtonElement>('header button[aria-label^="Rules "]')!;
+ const [met, total] = chip
+ .getAttribute('aria-label')!
+ .replace('Rules ', '')
+ .split('/')
+ .map(Number);
+ expect(total).toBeGreaterThan(met);
+
+ await act(async () => chip.click());
+ const selected = panel()!.querySelector('[role="tab"][aria-selected="true"]');
+ expect(selected?.textContent).toBe('Rules');
+ expect(panel()!.textContent).toContain(`${met} of ${total} rules met`);
+
+ // Turning a rule off for this draft saves it and takes it out of the count.
+ const sentence = panel()!.querySelector<HTMLElement>(
+ '[role="switch"][aria-label="Max sentence length: on or off"]',
+ )!;
+ await act(async () => sentence.click());
+ expect(saveDraftRules).toHaveBeenCalledWith('d1', {
+ set: null,
+ overrides: { sentence: { on: false } },
+ });
+ expect(chip.getAttribute('aria-label')).toBe(`Rules ${met - 1}/${total - 1}`);
+ expect(toast).toHaveBeenCalledWith('Rule updated for this draft');
});
it('starts open on a wide window, and remembers it closed', async () => {
diff --git a/web/src/lib/actions/content-drafts-rules.test.ts b/web/src/lib/actions/content-drafts-rules.test.ts
new file mode 100644
index 000000000..c78ec6b16
--- /dev/null
+++ b/web/src/lib/actions/content-drafts-rules.test.ts
@@ -0,0 +1,86 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/** The Rules tab (CE-009): a draft's rule choices, read with it and saved. */
+
+const DRAFT = '77777777-7777-7777-7777-777777777777';
+
+let updates: { value: unknown; filters: [string, unknown][] }[];
+let row: Record<string, unknown> | null;
+let updated: { id: string } | null;
+
+vi.mock('@/lib/action-center/assignees', () => ({ readAssignees: vi.fn(async () => new Map()) }));
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(async () => ({
+ from: () => {
+ const call = {
+ op: 'select',
+ value: undefined as unknown,
+ filters: [] as [string, unknown][],
+ };
+ const chain: Record<string, unknown> = {
+ select: () => chain,
+ eq: (col: string, v: unknown) => (call.filters.push([col, v]), chain),
+ update: (value: unknown) => {
+ call.op = 'update';
+ call.value = value;
+ updates.push(call);
+ return chain;
+ },
+ maybeSingle: async () => ({ data: call.op === 'update' ? updated : row, error: null }),
+ };
+ return chain;
+ },
+ })),
+}));
+
+const { getContentDraft, saveDraftRules } = await import('./content-drafts');
+
+const base = {
+ id: DRAFT,
+ brand_id: 'b1',
+ title: 'T',
+ page_type: 'blog_post',
+ page_type_source: 'user',
+ method: 'create',
+ status: 'draft',
+ body_html: '',
+ author: 'user',
+ source_url: null,
+ updated_at: '2026-10-21T10:00:00Z',
+ brands: { site_type: null, industry: null, shopping_mode_enabled: false },
+};
+
+beforeEach(() => {
+ updates = [];
+ row = null;
+ updated = { id: DRAFT };
+});
+
+describe('the draft’s rules', () => {
+ it('are read with the draft, and none when they aren’t valid', async () => {
+ row = { ...base, rules: { set: 'guide', overrides: { faq: { on: false } } } };
+ expect((await getContentDraft(DRAFT))?.rules).toEqual({
+ set: 'guide',
+ overrides: { faq: { on: false } },
+ });
+ row = { ...base, rules: null };
+ expect((await getContentDraft(DRAFT))?.rules).toEqual({ set: null, overrides: {} });
+ row = { ...base, rules: { set: 'nope', overrides: {} } };
+ expect((await getContentDraft(DRAFT))?.rules).toEqual({ set: null, overrides: {} });
+ });
+
+ it('are saved for this draft', async () => {
+ const rules = { set: null, overrides: { sentence: { value: '120' } } };
+ await saveDraftRules(DRAFT, rules);
+ expect(updates).toEqual([{ op: 'update', value: { rules }, filters: [['id', DRAFT]] }]);
+ });
+
+ it('refuses rules out of shape, and says when the draft isn’t found', async () => {
+ await expect(
+ saveDraftRules(DRAFT, { set: null, overrides: { tone: { value: 'x'.repeat(501) } } }),
+ ).rejects.toThrow('invalid');
+ await expect(saveDraftRules('d1', { set: null, overrides: {} })).rejects.toThrow('invalid');
+ updated = null;
+ await expect(saveDraftRules(DRAFT, { set: null, overrides: {} })).rejects.toThrow('not_found');
+ });
+});
diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.ts
index 9592d0cdb..35107ba32 100644
--- a/web/src/lib/actions/content-drafts.ts
+++ b/web/src/lib/actions/content-drafts.ts
@@ -29,6 +29,7 @@ import {
} from '@/lib/content/editor';
import { detectPageType, siteTypeOf, type SiteType } from '@/lib/content/page-types';
import { sanitizeDraftHtml } from '@/lib/content/sanitize-draft-html';
+import { NO_DRAFT_RULES, draftRulesSchema, type DraftRules } from '@/lib/content/rules';
import {
briefFromOpportunity,
draftBriefSchema,
@@ -124,7 +125,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, updated_at, ${BRAND_SITE}`,
+ `id, brand_id, title, page_type, page_type_source, method, status, body_html, author, source_url, rules, updated_at, ${BRAND_SITE}`,
)
.eq('id', id)
.maybeSingle();
@@ -142,6 +143,7 @@ export async function getContentDraft(id: string): Promise<ContentDraft | null>
status: draftStatus(data.status),
bodyHtml: data.body_html,
author: data.author === 'agent' ? 'agent' : 'user',
+ rules: draftRulesSchema.safeParse(data.rules).data ?? NO_DRAFT_RULES,
updatedAt: data.updated_at,
};
}
@@ -871,3 +873,22 @@ export async function rebuildDraftBrief(
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 no
+ * row changed.
+ */
+export async function saveDraftRules(id: string, rules: DraftRules): Promise<void> {
+ const parsed = draftRulesSchema.safeParse(rules);
+ if (!draftId.safeParse(id).success || !parsed.success) throw new Error('invalid');
+ const supabase = await createClient();
+ const { data, error } = await supabase
+ .from('content_drafts')
+ .update({ rules: parsed.data })
+ .eq('id', id)
+ .select('id')
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!data) throw new Error('not_found');
+}
diff --git a/web/src/lib/content/brief.test.ts b/web/src/lib/content/brief.test.ts
index 0b1005a4b..ba94adb1f 100644
--- a/web/src/lib/content/brief.test.ts
+++ b/web/src/lib/content/brief.test.ts
@@ -49,7 +49,7 @@ const draft = {
title: 'The home espresso guide',
sourceUrl: 'https://acme.example/guides/espresso',
html: '<h1>The home espresso guide</h1><h2>Choosing a machine</h2><p>x</p><h3>Grinders</h3><h2></h2>',
- pageType: 'product_page',
+ length: 1200,
};
describe('rebuildSources', () => {
diff --git a/web/src/lib/content/brief.ts b/web/src/lib/content/brief.ts
index cd117a07e..4859d6948 100644
--- a/web/src/lib/content/brief.ts
+++ b/web/src/lib/content/brief.ts
@@ -1,6 +1,5 @@
import { z } from 'zod';
import type { ContentBrief } from '@/types';
-import { lengthTarget } from '@/lib/content/editor';
import {
buildSourceGroups,
readDraftDoc,
@@ -101,13 +100,13 @@ export interface RebuildSources {
/**
* The sources a rebuild uses: the ones checked in the Sources tab, as it
- * lists them; the page's H2s and H3s as written now; and the length the page
- * type asks for.
+ * lists them; the page's H2s and H3s as written now; and the length the
+ * rules ask for.
*/
export function rebuildSources(
data: DraftSourcesData,
choices: DraftSourceChoice[],
- draft: { title: string; sourceUrl: string | null; html: string; pageType: string | null },
+ draft: { title: string; sourceUrl: string | null; html: string; length: number },
): RebuildSources {
const groups = buildSourceGroups(data, choices, draft);
const kept = (kind: string) =>
@@ -130,7 +129,7 @@ export function rebuildSources(
.headings.filter((h) => h.level > 1 && h.text)
.map((h) => h.text)
.slice(0, 30),
- length: lengthTarget(draft.pageType),
+ length: draft.length,
};
}
diff --git a/web/src/lib/content/drafts.ts b/web/src/lib/content/drafts.ts
index c45f4eb53..d24b513a7 100644
--- a/web/src/lib/content/drafts.ts
+++ b/web/src/lib/content/drafts.ts
@@ -5,6 +5,7 @@
*/
import type { SiteType } from './page-types';
+import type { DraftRules } from '@/lib/content/rules';
/** Draft → In review (an agent's draft waiting for a person) → Ready → Published. */
export const DRAFT_STATUSES = ['draft', 'in_review', 'ready', 'published'] as const;
@@ -99,6 +100,8 @@ export interface ContentDraft {
status: DraftStatus;
bodyHtml: string;
author: 'user' | 'agent';
+ /** What the person changed on the page's rules for this draft (CE-009). */
+ rules: DraftRules;
updatedAt: string;
}
diff --git a/web/src/lib/content/rules.test.ts b/web/src/lib/content/rules.test.ts
new file mode 100644
index 000000000..e0e8d0cdb
--- /dev/null
+++ b/web/src/lib/content/rules.test.ts
@@ -0,0 +1,320 @@
+import { describe, expect, it } from 'vitest';
+import {
+ NO_DRAFT_RULES,
+ activeRules,
+ checkRule,
+ draftRulesSchema,
+ readPage,
+ ruleLength,
+ ruleSet,
+ rulesMet,
+ type ActiveRule,
+ type RuleContext,
+} from './rules';
+
+const ctx: RuleContext = {
+ brandDomains: ['acme.example'],
+ competitorDomains: ['crema.example'],
+ fanouts: [
+ 'best espresso machine under 500',
+ 'home espresso grinder',
+ 'espresso machine reviews 2026',
+ ],
+};
+
+const rule = (
+ key: string,
+ pageType: Parameters<typeof ruleSet>[0] = 'feature_page',
+ value?: string,
+): ActiveRule => {
+ const rules = activeRules(
+ ruleSet(pageType),
+ value === undefined ? NO_DRAFT_RULES : { set: null, overrides: { [key]: { value } } },
+ );
+ const found = rules.find((r) => r.key === key);
+ if (!found) throw new Error(`no rule ${key}`);
+ return found;
+};
+
+const page = (html: string, characters = 0) => readPage(html, characters);
+const check = (
+ key: string,
+ html: string,
+ value?: string,
+ pageType?: Parameters<typeof ruleSet>[0],
+) => checkRule(rule(key, pageType ?? 'feature_page', value), page(html), ctx);
+
+describe('rule sets', () => {
+ it('puts the page type’s own rules above the shared groups, with its length', () => {
+ expect(
+ ruleSet('feature_page')
+ .map((r) => r.key)
+ .slice(0, 4),
+ ).toEqual(['comparisonTable', 'whoFor', 'proofPerSection', 'sentence']);
+ expect(ruleSet('blog_post')[0].key).toBe('sentence');
+ expect(ruleSet('product_page').find((r) => r.key === 'length')?.value).toBe('1200');
+ expect(ruleSet(null).find((r) => r.key === 'length')?.value).toBe('3000');
+ expect(
+ ruleSet('guide', { keywords: ['espresso', 'grinder'] }).find((r) => r.key === 'keywords')
+ ?.value,
+ ).toBe('espresso, grinder');
+ });
+
+ it('applies the draft’s choices', () => {
+ const rules = activeRules(ruleSet('category_page'), {
+ set: null,
+ overrides: { length: { value: '1000' }, faq: { on: false } },
+ });
+ expect(rules.find((r) => r.key === 'length')).toMatchObject({
+ current: '1000',
+ changed: true,
+ on: true,
+ });
+ expect(rules.find((r) => r.key === 'faq')).toMatchObject({ on: false, changed: true });
+ expect(rules.find((r) => r.key === 'sentence')).toMatchObject({ changed: false });
+ expect(ruleLength(rules, 'category_page')).toBe(1000);
+ const off = activeRules(ruleSet('category_page'), {
+ set: null,
+ overrides: { length: { on: false } },
+ });
+ expect(ruleLength(off, 'category_page')).toBe(800);
+ // Kept within what Rebuild outline builds for.
+ const tiny = activeRules(ruleSet('category_page'), {
+ set: null,
+ overrides: { length: { value: '50' } },
+ });
+ expect(ruleLength(tiny, 'category_page')).toBe(100);
+ const huge = activeRules(ruleSet('category_page'), {
+ set: null,
+ overrides: { length: { value: '600000' } },
+ });
+ expect(ruleLength(huge, 'category_page')).toBe(50_000);
+ });
+
+ it('keeps the draft’s choices to their limits', () => {
+ expect(
+ draftRulesSchema.safeParse({ set: 'blog_post', overrides: { faq: { on: false } } }).success,
+ ).toBe(true);
+ expect(draftRulesSchema.safeParse({ set: 'nope', overrides: {} }).success).toBe(false);
+ expect(
+ draftRulesSchema.safeParse({ set: null, overrides: { tone: { value: 'x'.repeat(501) } } })
+ .success,
+ ).toBe(false);
+ });
+});
+
+describe('length and structure', () => {
+ it('counts sentences over the limit', () => {
+ expect(check('sentence', `<p>Short one. ${'Long '.repeat(40)}sentence.</p>`)).toEqual({
+ state: 'bad',
+ code: 'over',
+ count: 1,
+ });
+ expect(check('sentence', '<p>Short. Also short!</p>')).toEqual({ state: 'ok' });
+ });
+
+ it('reads the length from the editor’s count', () => {
+ expect(checkRule(rule('length'), page('', 2610), ctx)).toEqual({
+ state: 'bad',
+ code: 'current',
+ count: 2610,
+ });
+ expect(checkRule(rule('length'), page('', 3000), ctx)).toEqual({ state: 'ok' });
+ });
+
+ it('wants a short summary under the H1, and a short answer under each H2', () => {
+ expect(check('summary', '<h1>T</h1><h2>A</h2>')).toEqual({ state: 'bad', code: 'missing' });
+ expect(check('summary', `<h1>T</h1><p>${'word '.repeat(60)}</p>`)).toEqual({
+ state: 'bad',
+ code: 'words',
+ count: 60,
+ });
+ expect(check('summary', '<h1>T</h1><p>A short answer.</p><h2>A</h2>')).toEqual({ state: 'ok' });
+
+ expect(check('h2Answer', '<h1>T</h1><p>x</p>')).toEqual({ state: 'bad', code: 'noH2' });
+ expect(
+ check('h2Answer', `<h2>A</h2><p>Short.</p><h2>B</h2><table><tr><td>x</td></tr></table>`),
+ ).toEqual({
+ state: 'bad',
+ code: 'partOf',
+ count: 1,
+ of: 2,
+ });
+ });
+});
+
+describe('fan-outs and keywords', () => {
+ it('counts the top fan-outs used as H2s', () => {
+ expect(
+ check(
+ 'fanoutH2',
+ '<h2>Best espresso machines under $500</h2><h2>Home espresso grinders</h2>',
+ '2',
+ ),
+ ).toEqual({ state: 'ok' });
+ expect(check('fanoutH2', '<h2>Best espresso machines under $500</h2>')).toEqual({
+ state: 'bad',
+ code: 'partOf',
+ count: 1,
+ of: 3,
+ });
+ expect(checkRule(rule('fanoutH2'), page('<h2>x</h2>'), { ...ctx, fanouts: [] })).toEqual({
+ state: 'info',
+ code: 'noFanouts',
+ });
+ });
+
+ it('finds the FAQ and its questions, and the fan-outs they use', () => {
+ const faq =
+ '<h2>FAQ</h2><h3>Which home espresso grinder should I buy?</h3><p>The Baratza.</p>' +
+ '<h3>Is it loud?</h3><p>A bit.</p><h2>Next</h2><p>Is this counted?</p>';
+ expect(check('faq', faq)).toEqual({ state: 'bad', code: 'partOf', count: 2, of: 5 });
+ expect(check('faq', faq, '2')).toEqual({ state: 'ok' });
+ expect(check('faq', '<h2>Questions</h2>')).toEqual({ state: 'bad', code: 'missing' });
+ expect(check('fanoutFaq', faq)).toEqual({ state: 'bad', code: 'partOf', count: 1, of: 3 });
+ expect(check('fanoutFaq', '<p>x</p>')).toEqual({ state: 'bad', code: 'needsFaq' });
+ });
+
+ it('counts the keywords on the page', () => {
+ expect(check('keywords', '<p>A pipeline forecast.</p>', 'pipeline forecast, accuracy')).toEqual(
+ {
+ state: 'bad',
+ code: 'partOf',
+ count: 1,
+ of: 2,
+ },
+ );
+ expect(check('keywords', '<p>x</p>')).toEqual({ state: 'info', code: 'addKeywords' });
+ });
+});
+
+describe('links and sources', () => {
+ const html =
+ '<p>See <a href="/guides/milk">milk</a>, <a href="https://www.acme.example/beans">beans</a> and ' +
+ '<a href="#top">top</a>.</p>' +
+ '<p>Per <a href="https://www.nist.gov/coffee">NIST</a> and <a href="https://crema.example/x">Crema</a>.</p>';
+
+ it('counts internal links, and outbound ones that aren’t a competitor’s', () => {
+ expect(check('internalLinks', html, '2')).toEqual({ state: 'ok' });
+ expect(check('outboundLinks', html)).toEqual({ state: 'bad', code: 'partOf', count: 1, of: 2 });
+ expect(check('citeInline', html)).toEqual({ state: 'ok' });
+ expect(check('citeInline', '<p><a href="https://crema.example/x">x</a></p>')).toEqual({
+ state: 'bad',
+ code: 'missing',
+ });
+ });
+
+ it('wants a dated data point in the first 100 words', () => {
+ expect(check('datedPoint', '<p>In 2026, 62% of buyers asked AI first.</p>')).toEqual({
+ state: 'ok',
+ });
+ expect(check('datedPoint', `<p>${'word '.repeat(120)}In 2026.</p>`)).toEqual({
+ state: 'bad',
+ code: 'missing',
+ });
+ });
+});
+
+describe('style', () => {
+ it('finds AI traces and banned words', () => {
+ expect(check('aiTraces', '<p>Let’s delve in. It is important to note this.</p>')).toEqual({
+ state: 'bad',
+ code: 'found',
+ count: 2,
+ });
+ expect(check('aiTraces', '<p>Plain words.</p>')).toEqual({ state: 'ok' });
+ expect(check('bannedWords', '<p>A seamless, robust tool. Leverage it.</p>')).toEqual({
+ state: 'bad',
+ code: 'found',
+ count: 3,
+ });
+ expect(check('bannedWords', '<p>Seamlessly done.</p>')).toEqual({ state: 'ok' });
+ });
+
+ it('leaves tone and language to AI', () => {
+ expect(check('tone', '<p>x</p>')).toEqual({ state: 'info', code: 'aiCheck' });
+ expect(check('language', '<p>x</p>')).toEqual({ state: 'info', code: 'aiCheck' });
+ });
+});
+
+describe('page type rules', () => {
+ it('checks a feature page', () => {
+ expect(check('comparisonTable', '<table><tr><td>x</td></tr></table>')).toEqual({ state: 'ok' });
+ expect(check('comparisonTable', '<p>x</p>')).toEqual({ state: 'bad', code: 'missing' });
+ expect(check('whoFor', '<p>x</p>')).toEqual({ state: 'bad', code: 'notSet' });
+ expect(check('whoFor', '<p>x</p>', 'Sales leaders')).toEqual({
+ state: 'info',
+ code: 'aiCheck',
+ });
+ expect(
+ check(
+ 'proofPerSection',
+ '<h2>A</h2><p>Used by 400 teams.</p><h2>B</h2><blockquote><p>Love it</p></blockquote><h2>C</h2><p>x</p>',
+ ),
+ ).toEqual({ state: 'bad', code: 'partOf', count: 2, of: 3 });
+ });
+
+ it('checks a solution page’s steps', () => {
+ expect(
+ check('useCaseSteps', '<ol><li>a</li><li>b</li><li>c</li></ol>', undefined, 'solution_page'),
+ ).toEqual({
+ state: 'ok',
+ });
+ expect(check('useCaseSteps', '<ol><li>a</li></ol>', undefined, 'solution_page')).toEqual({
+ state: 'bad',
+ code: 'partOf',
+ count: 1,
+ of: 3,
+ });
+ });
+
+ it('checks a product and a category page', () => {
+ expect(check('feedMatch', '<p>x</p>', undefined, 'product_page')).toEqual({
+ state: 'info',
+ code: 'needsFeed',
+ });
+ expect(
+ check(
+ 'fitQuestions',
+ '<h3>Does it fit wide feet?</h3><p>Which size should I order?</p>',
+ '2',
+ 'product_page',
+ ),
+ ).toEqual({ state: 'ok' });
+ expect(
+ check(
+ 'introText',
+ `<h1>Shoes</h1><p>${'word '.repeat(40)}</p><h2>All</h2>`,
+ undefined,
+ 'category_page',
+ ),
+ ).toEqual({ state: 'bad', code: 'current', count: 40 });
+ });
+
+ it('checks a destination page’s summary', () => {
+ expect(
+ check(
+ 'bestTime',
+ '<h1>Lisbon</h1><p>The best time to visit is May.</p>',
+ undefined,
+ 'destination_page',
+ ),
+ ).toEqual({ state: 'ok' });
+ });
+});
+
+describe('rulesMet', () => {
+ it('counts the rules on that the page can say', () => {
+ const rules = activeRules(ruleSet('blog_post'), {
+ set: null,
+ overrides: { sentence: { on: false } },
+ });
+ const p = page('<h1>T</h1><p>Short summary.</p>', 10);
+ const statuses = rules.map((r) => ({ rule: r, status: checkRule(r, p, ctx) }));
+ const { met, total } = rulesMet(statuses);
+ // 16 shared rules: sentence off; tone, language and keywords (none set) can't say.
+ expect(total).toBe(12);
+ expect(met).toBeGreaterThan(0);
+ expect(met).toBeLessThan(total);
+ });
+});
diff --git a/web/src/lib/content/rules.ts b/web/src/lib/content/rules.ts
new file mode 100644
index 000000000..0aa46255e
--- /dev/null
+++ b/web/src/lib/content/rules.ts
@@ -0,0 +1,544 @@
+import { z } from 'zod';
+import { classifyDomain, normalizeDomain } from '@/lib/citations/classify';
+import { PAGE_TYPES, type PageType } from '@/lib/content/drafts';
+import { lengthTarget } from '@/lib/content/editor';
+import { wordsOf } from '@/lib/content/sources';
+
+/**
+ * The editor's Rules tab (Content Editor CE-009, spec §10): the rules a page
+ * of its type is written to — the type's own, then the shared groups — each
+ * on or off, with a value the person can change for the draft, and its
+ * status read from the page as written. Rules only AI can judge (tone,
+ * fairness…) say so and don't count; the agent (CE-018) checks them.
+ */
+
+export const RULE_GROUPS = ['type', 'structure', 'fanouts', 'links', 'style'] as const;
+export type RuleGroup = (typeof RULE_GROUPS)[number];
+
+export type RuleKind = 'number' | 'text' | 'list' | 'switch';
+export type RuleUnit =
+ | 'characters'
+ | 'wordsMax'
+ | 'wordsMin'
+ | 'fanouts'
+ | 'questions'
+ | 'links'
+ | 'perSection'
+ | 'steps';
+
+export interface RuleDef {
+ key: string;
+ group: RuleGroup;
+ kind: RuleKind;
+ /** The default: a number, a text, a comma list; '' for a switch. */
+ value: string;
+ unit?: RuleUnit;
+ /** How it is checked: from the page as written, by AI, or against the product feed. */
+ check: 'page' | 'ai' | 'feed';
+}
+
+const SHARED_RULES: RuleDef[] = [
+ {
+ key: 'sentence',
+ group: 'structure',
+ kind: 'number',
+ value: '150',
+ unit: 'characters',
+ check: 'page',
+ },
+ {
+ key: 'length',
+ group: 'structure',
+ kind: 'number',
+ value: '',
+ unit: 'characters',
+ check: 'page',
+ },
+ {
+ key: 'summary',
+ group: 'structure',
+ kind: 'number',
+ value: '50',
+ unit: 'wordsMax',
+ check: 'page',
+ },
+ {
+ key: 'h2Answer',
+ group: 'structure',
+ kind: 'number',
+ value: '60',
+ unit: 'wordsMax',
+ check: 'page',
+ },
+ { key: 'fanoutH2', group: 'fanouts', kind: 'number', value: '4', unit: 'fanouts', check: 'page' },
+ { key: 'faq', group: 'fanouts', kind: 'number', value: '5', unit: 'questions', check: 'page' },
+ {
+ key: 'fanoutFaq',
+ group: 'fanouts',
+ kind: 'number',
+ value: '3',
+ unit: 'questions',
+ check: 'page',
+ },
+ { key: 'keywords', group: 'fanouts', kind: 'list', value: '', check: 'page' },
+ {
+ key: 'internalLinks',
+ group: 'links',
+ kind: 'number',
+ value: '3',
+ unit: 'links',
+ check: 'page',
+ },
+ {
+ key: 'outboundLinks',
+ group: 'links',
+ kind: 'number',
+ value: '2',
+ unit: 'links',
+ check: 'page',
+ },
+ { key: 'datedPoint', group: 'links', kind: 'switch', value: '', check: 'page' },
+ { key: 'citeInline', group: 'links', kind: 'switch', value: '', check: 'page' },
+ { key: 'aiTraces', group: 'style', kind: 'switch', value: '', check: 'page' },
+ {
+ key: 'bannedWords',
+ group: 'style',
+ kind: 'list',
+ value: 'seamless, leverage, robust',
+ check: 'page',
+ },
+ { key: 'tone', group: 'style', kind: 'text', value: 'Clear, confident, no hype', check: 'ai' },
+ { key: 'language', group: 'style', kind: 'text', value: 'English (US)', check: 'ai' },
+];
+
+/** Each page type's own rules, above the shared ones (spec §10); a blog post has none. */
+const TYPE_RULES: Partial<Record<PageType, RuleDef[]>> = {
+ feature_page: [
+ { key: 'comparisonTable', group: 'type', kind: 'switch', value: '', check: 'page' },
+ { key: 'whoFor', group: 'type', kind: 'text', value: '', check: 'ai' },
+ {
+ key: 'proofPerSection',
+ group: 'type',
+ kind: 'number',
+ value: '1',
+ unit: 'perSection',
+ check: 'page',
+ },
+ ],
+ solution_page: [
+ { key: 'industryNamed', group: 'type', kind: 'switch', value: '', check: 'ai' },
+ {
+ key: 'useCaseSteps',
+ group: 'type',
+ kind: 'number',
+ value: '3',
+ unit: 'steps',
+ check: 'page',
+ },
+ ],
+ comparison: [
+ { key: 'sideBySide', group: 'type', kind: 'switch', value: '', check: 'page' },
+ { key: 'fairness', group: 'type', kind: 'switch', value: '', check: 'ai' },
+ ],
+ product_page: [
+ { key: 'specsTable', group: 'type', kind: 'switch', value: '', check: 'page' },
+ { key: 'feedMatch', group: 'type', kind: 'switch', value: '', check: 'feed' },
+ {
+ key: 'fitQuestions',
+ group: 'type',
+ kind: 'number',
+ value: '3',
+ unit: 'questions',
+ check: 'page',
+ },
+ { key: 'first40Words', group: 'type', kind: 'switch', value: '', check: 'ai' },
+ ],
+ category_page: [
+ {
+ key: 'introText',
+ group: 'type',
+ kind: 'number',
+ value: '120',
+ unit: 'wordsMin',
+ check: 'page',
+ },
+ {
+ key: 'buyingFaq',
+ group: 'type',
+ kind: 'number',
+ value: '3',
+ unit: 'questions',
+ check: 'page',
+ },
+ ],
+ destination_page: [
+ { key: 'currentPrices', group: 'type', kind: 'switch', value: '', check: 'ai' },
+ { key: 'bestTime', group: 'type', kind: 'switch', value: '', check: 'page' },
+ ],
+};
+
+/** The rules of a set: the type's own, then the shared groups, with the type's length. */
+export function ruleSet(
+ pageType: PageType | null,
+ defaults: { keywords?: string[] } = {},
+): RuleDef[] {
+ const own = (pageType && TYPE_RULES[pageType]) || [];
+ return [
+ ...own,
+ ...SHARED_RULES.map((rule) => {
+ if (rule.key === 'length') return { ...rule, value: String(lengthTarget(pageType)) };
+ if (rule.key === 'keywords' && defaults.keywords?.length) {
+ return { ...rule, value: defaults.keywords.join(', ') };
+ }
+ return rule;
+ }),
+ ];
+}
+
+/** The draft's choices on its rules (content_drafts.rules, 00213). */
+export const draftRulesSchema = z.object({
+ /** The page type whose set applies; null follows the draft's type. */
+ set: z.enum(PAGE_TYPES).nullable(),
+ overrides: z
+ .record(
+ z.string().max(40),
+ z.object({ on: z.boolean().optional(), value: z.string().max(500).optional() }),
+ )
+ .refine((o) => Object.keys(o).length <= 60),
+});
+export type DraftRules = z.infer<typeof draftRulesSchema>;
+export const NO_DRAFT_RULES: DraftRules = { set: null, overrides: {} };
+
+export interface ActiveRule extends RuleDef {
+ on: boolean;
+ /** The value in effect: the draft's, else the set's. */
+ current: string;
+ changed: boolean;
+}
+
+export function activeRules(defs: RuleDef[], rules: DraftRules): ActiveRule[] {
+ return defs.map((def) => {
+ const override = rules.overrides[def.key];
+ const current = override?.value ?? def.value;
+ return {
+ ...def,
+ on: override?.on ?? true,
+ current,
+ changed: (override?.on !== undefined && override.on !== true) || current !== def.value,
+ };
+ });
+}
+
+/** The lengths a brief is built for (content-brief.js BRIEF_LENGTH_MIN/MAX), in characters. */
+export const RULE_LENGTH_MIN = 100;
+export const RULE_LENGTH_MAX = 50_000;
+
+/**
+ * The page length the rules ask for: the Length rule's value while it is on,
+ * within the range Rebuild outline builds for.
+ */
+export function ruleLength(rules: ActiveRule[], pageType: PageType | null): number {
+ const rule = rules.find((r) => r.key === 'length');
+ const value = rule?.on ? Number(rule.current) : NaN;
+ if (!Number.isFinite(value) || value <= 0) return lengthTarget(pageType);
+ return Math.min(RULE_LENGTH_MAX, Math.max(RULE_LENGTH_MIN, value));
+}
+
+// ─── The page as written ────────────────────────────────────────────────────
+
+export interface PageBlock {
+ tag: string;
+ text: string;
+ words: number;
+ /** Links in the block, as written. */
+ links: string[];
+}
+
+export interface PageRead {
+ blocks: PageBlock[];
+ text: string;
+ /** The editor's character count, as the toolbar shows it. */
+ characters: number;
+}
+
+const BLOCK_TAGS = 'h1, h2, h3, p, li, table, ol, ul, blockquote';
+
+/** Reads the page's blocks in order, each list item and table once. */
+export function readPage(html: string, characters: number): PageRead {
+ const doc = new DOMParser().parseFromString(html, 'text/html');
+ const blocks: PageBlock[] = [];
+ for (const el of doc.body.querySelectorAll(BLOCK_TAGS)) {
+ const tag = el.tagName.toLowerCase();
+ // A paragraph inside a list item or a cell is part of that block.
+ if (tag === 'p' && el.closest('li, td, th, blockquote')) continue;
+ if ((tag === 'ol' || tag === 'ul') && el.closest('li')) continue;
+ const text = (el.textContent ?? '').replace(/\s+/g, ' ').trim();
+ blocks.push({
+ tag:
+ tag === 'ol' || tag === 'ul' ? `${tag}:${el.querySelectorAll(':scope > li').length}` : tag,
+ text,
+ words: countWords(text),
+ links: [...el.querySelectorAll('a[href]')].map((a) => a.getAttribute('href') ?? ''),
+ });
+ }
+ return {
+ blocks,
+ text: blocks
+ .filter((b) => !b.tag.startsWith('ol') && !b.tag.startsWith('ul'))
+ .map((b) => b.text)
+ .join(' '),
+ characters,
+ };
+}
+
+function countWords(text: string): number {
+ return text.match(/[\p{L}\p{N}][\p{L}\p{N}'’-]*/gu)?.length ?? 0;
+}
+
+const isHeading = (b: PageBlock) => b.tag === 'h1' || b.tag === 'h2' || b.tag === 'h3';
+const isText = (b: PageBlock) => b.tag === 'p' || b.tag === 'li';
+const isQuestion = (b: PageBlock) => b.text.trim().endsWith('?');
+
+// ─── Checks ─────────────────────────────────────────────────────────────────
+
+/** A rule's status: met, not met (with what's missing), or one the page can't say. */
+export type RuleStatus =
+ | { state: 'ok' }
+ | { state: 'bad'; code: 'over' | 'found'; count: number }
+ | { state: 'bad'; code: 'partOf'; count: number; of: number }
+ | { state: 'bad'; code: 'current'; count: number }
+ | { state: 'bad'; code: 'words'; count: number }
+ | { state: 'bad'; code: 'missing' | 'noH2' | 'needsFaq' | 'notSet' }
+ | { state: 'info'; code: 'aiCheck' | 'needsFeed' | 'noFanouts' | 'addKeywords' };
+
+export interface RuleContext {
+ brandDomains: string[];
+ competitorDomains: string[];
+ /** The fan-outs the draft keeps, the most searched first. */
+ fanouts: string[];
+}
+
+/** Phrases that read as machine-written (spec §10, "Remove AI traces"). */
+export const AI_TRACES = [
+ 'delve',
+ "in today's fast-paced world",
+ 'in today’s fast-paced world',
+ 'it is important to note',
+ "it's important to note",
+ 'navigate the complexities',
+ 'unlock the power',
+ 'a testament to',
+ 'in the ever-evolving',
+ 'game-changer',
+ 'not only',
+];
+
+const list = (value: string) =>
+ value
+ .split(',')
+ .map((v) => v.trim())
+ .filter(Boolean);
+
+function count(text: string, phrase: string): number {
+ const escaped = phrase.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ return (
+ text.toLowerCase().match(new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, 'gu'))
+ ?.length ?? 0
+ );
+}
+
+/** A link's host, or null for one on the page's own site (a path or an anchor). */
+function linkHost(href: string): string | null {
+ if (!/^https?:\/\//i.test(href)) return null;
+ return normalizeDomain(href) || null;
+}
+
+/** Whether a fan-out's words are carried by a text, as the Sources tab reads it. */
+function carries(fanout: string, text: string): boolean {
+ const words = [...new Set(wordsOf(fanout))];
+ if (!words.length) return false;
+ const have = new Set(wordsOf(text));
+ return words.filter((w) => have.has(w)).length / words.length >= 0.75;
+}
+
+/** The FAQ's questions: the blocks after an "FAQ" heading, up to the next H2, that ask one. */
+function faqQuestions(blocks: PageBlock[]): string[] | null {
+ const start = blocks.findIndex(
+ (b) => (b.tag === 'h2' || b.tag === 'h3') && /\b(faq|faqs|frequently asked)\b/i.test(b.text),
+ );
+ if (start < 0) return null;
+ const level = blocks[start].tag;
+ const questions: string[] = [];
+ for (const block of blocks.slice(start + 1)) {
+ if (block.tag === 'h2' || (level === 'h3' && block.tag === 'h3' && !isQuestion(block))) break;
+ if ((block.tag === 'h3' || isText(block)) && isQuestion(block)) questions.push(block.text);
+ }
+ return questions;
+}
+
+const atLeast = (have: number, want: number): RuleStatus =>
+ have >= want ? { state: 'ok' } : { state: 'bad', code: 'partOf', count: have, of: want };
+
+/** 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' };
+ if (rule.key === 'whoFor' && !rule.current.trim()) return { state: 'bad', code: 'notSet' };
+ if (rule.check === 'ai') return { state: 'info', code: 'aiCheck' };
+
+ const n = Math.max(0, Math.floor(Number(rule.current) || 0));
+ const { blocks } = page;
+ const h1 = blocks.findIndex((b) => b.tag === 'h1');
+ const firstH2 = blocks.findIndex((b) => b.tag === 'h2');
+ const summary = blocks
+ .slice(h1 + 1, firstH2 < 0 ? undefined : firstH2)
+ .find((b) => b.tag === 'p');
+ const own = ctx.brandDomains.map(normalizeDomain);
+ const competitors = ctx.competitorDomains.map(normalizeDomain);
+ const links = blocks.flatMap((b) => (isText(b) ? b.links : []));
+ const outbound = (href: string) => {
+ const host = linkHost(href);
+ if (!host) return false;
+ const kind = classifyDomain(host, { brandDomains: own, competitorDomains: competitors });
+ return kind !== 'you' && kind !== 'competitor';
+ };
+
+ switch (rule.key) {
+ case 'sentence': {
+ const over = blocks
+ .filter(isText)
+ .flatMap((b) => b.text.split(/(?<=[.!?])\s+/))
+ .filter((s) => s.length > n).length;
+ return over ? { state: 'bad', code: 'over', count: over } : { state: 'ok' };
+ }
+ case 'length':
+ return page.characters >= n
+ ? { state: 'ok' }
+ : { state: 'bad', code: 'current', count: page.characters };
+ case 'summary':
+ if (!summary || !summary.words) return { state: 'bad', code: 'missing' };
+ return summary.words <= n
+ ? { state: 'ok' }
+ : { state: 'bad', code: 'words', count: summary.words };
+ case 'h2Answer': {
+ const h2s = blocks.flatMap((b, i) => (b.tag === 'h2' ? [i] : []));
+ if (!h2s.length) return { state: 'bad', code: 'noH2' };
+ const answered = h2s.filter((i) => {
+ const next = blocks[i + 1];
+ return next?.tag === 'p' && next.words > 0 && next.words <= n;
+ }).length;
+ return atLeast(answered, h2s.length);
+ }
+ case 'fanoutH2': {
+ const top = ctx.fanouts.slice(0, n);
+ if (!top.length) return { state: 'info', code: 'noFanouts' };
+ const h2s = blocks.filter((b) => b.tag === 'h2');
+ return atLeast(top.filter((f) => h2s.some((h) => carries(f, h.text))).length, top.length);
+ }
+ case 'faq':
+ case 'buyingFaq': {
+ const questions = faqQuestions(blocks);
+ if (!questions) return { state: 'bad', code: 'missing' };
+ return atLeast(questions.length, n);
+ }
+ case 'fanoutFaq': {
+ const questions = faqQuestions(blocks);
+ if (!questions) return { state: 'bad', code: 'needsFaq' };
+ if (!ctx.fanouts.length) return { state: 'info', code: 'noFanouts' };
+ const used = questions.filter((q) => ctx.fanouts.some((f) => carries(f, q))).length;
+ return atLeast(used, n);
+ }
+ case 'keywords': {
+ const wanted = list(rule.current);
+ if (!wanted.length) return { state: 'info', code: 'addKeywords' };
+ return atLeast(wanted.filter((k) => count(page.text, k) > 0).length, wanted.length);
+ }
+ case 'internalLinks':
+ return atLeast(
+ links.filter((href) => {
+ const host = linkHost(href);
+ return host
+ ? classifyDomain(host, { brandDomains: own, competitorDomains: [] }) === 'you'
+ : !href.startsWith('#') && !/^[a-z]+:/i.test(href);
+ }).length,
+ n,
+ );
+ case 'outboundLinks':
+ return atLeast(links.filter(outbound).length, n);
+ case 'datedPoint': {
+ const first100 = page.text.split(/\s+/).slice(0, 100).join(' ');
+ return /\b(19|20)\d{2}\b/.test(first100)
+ ? { state: 'ok' }
+ : { state: 'bad', code: 'missing' };
+ }
+ case 'citeInline':
+ return links.some(outbound) ? { state: 'ok' } : { state: 'bad', code: 'missing' };
+ case 'aiTraces': {
+ const found = AI_TRACES.reduce((sum, phrase) => sum + count(page.text, phrase), 0);
+ return found ? { state: 'bad', code: 'found', count: found } : { state: 'ok' };
+ }
+ case 'bannedWords': {
+ const found = list(rule.current).reduce((sum, word) => sum + count(page.text, word), 0);
+ return found ? { state: 'bad', code: 'found', count: found } : { state: 'ok' };
+ }
+ case 'comparisonTable':
+ case 'sideBySide':
+ case 'specsTable':
+ return blocks.some((b) => b.tag === 'table')
+ ? { state: 'ok' }
+ : { state: 'bad', code: 'missing' };
+ case 'proofPerSection': {
+ const sections = splitSections(blocks);
+ if (!sections.length) return { state: 'bad', code: 'noH2' };
+ const proven = sections.filter(
+ (s) =>
+ s.filter((b) => b.tag === 'blockquote' || (isText(b) && /\d/.test(b.text))).length >= n,
+ ).length;
+ return atLeast(proven, sections.length);
+ }
+ case 'useCaseSteps': {
+ const most = Math.max(
+ 0,
+ ...blocks.filter((b) => b.tag.startsWith('ol:')).map((b) => Number(b.tag.slice(3))),
+ );
+ return most ? atLeast(most, n) : { state: 'bad', code: 'missing' };
+ }
+ case 'fitQuestions':
+ return atLeast(
+ blocks.filter((b) => isQuestion(b) && /\b(fit|fits|size|sizes|sizing)\b/i.test(b.text))
+ .length,
+ n,
+ );
+ case 'introText': {
+ const words = blocks
+ .slice(h1 + 1, firstH2 < 0 ? undefined : firstH2)
+ .filter(isText)
+ .reduce((sum, b) => sum + b.words, 0);
+ return words >= n ? { state: 'ok' } : { state: 'bad', code: 'current', count: words };
+ }
+ case 'bestTime':
+ return summary && /\bbest time\b/i.test(summary.text)
+ ? { state: 'ok' }
+ : { state: 'bad', code: 'missing' };
+ default:
+ return { state: 'info', code: 'aiCheck' };
+ }
+}
+
+/** The blocks under each H2, up to the next. */
+function splitSections(blocks: PageBlock[]): PageBlock[][] {
+ const sections: PageBlock[][] = [];
+ for (const block of blocks) {
+ if (block.tag === 'h2') sections.push([]);
+ else if (sections.length && !isHeading(block)) sections[sections.length - 1].push(block);
+ }
+ return sections;
+}
+
+/** How many of the rules in effect are met: off rules and ones the page can't say don't count. */
+export function rulesMet(statuses: { rule: ActiveRule; status: RuleStatus }[]): {
+ met: number;
+ total: number;
+} {
+ const counted = statuses.filter((s) => s.rule.on && s.status.state !== 'info');
+ return { met: counted.filter((s) => s.status.state === 'ok').length, total: counted.length };
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 1b230b686..779f97d55 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -840,6 +840,7 @@ export type Database = {
page_type: string | null
page_type_source: string
prompt_ids: string[]
+ rules: Json | null
source_url: string | null
score_after: number | null
score_before: number | null
@@ -861,6 +862,7 @@ export type Database = {
page_type?: string | null
page_type_source?: string
prompt_ids?: string[]
+ rules?: Json | null
source_url?: string | null
score_after?: number | null
score_before?: number | null
@@ -882,6 +884,7 @@ export type Database = {
page_type?: string | null
page_type_source?: string
prompt_ids?: string[]
+ rules?: Json | null
source_url?: string | null
score_after?: number | null
score_before?: number | null