Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(content): let people write their own rules and keep a rule set for the workspace (#1295)
Cihan7397673739f2
diff --git a/supabase/migrations/00214_content_rule_sets.sql b/supabase/migrations/00214_content_rule_sets.sqlnew file mode 100644index 000000000..e27f5d0b4--- /dev/null+++ b/supabase/migrations/00214_content_rule_sets.sql@@ -0,0 +1,71 @@+-- ============================================================================+-- 00214: a workspace's own rules per page type (Content Editor, CE-009)+-- ============================================================================+-- The Rules tab's "Save as my rules" (Content Editor spec v2 §10) keeps a+-- draft's rule choices for the workspace, per page type: the values and+-- switches the person changed, and the rules they wrote in their own words.+-- A new draft of that type starts from them ("My rules"); Reset takes a+-- draft back to Ansvisor's default set. The rules themselves are the app's+-- (web/src/lib/content/rules.ts); a set keeps only what differs.+--+-- * content_rule_sets: one row per organization and page type, with+-- overrides {key: {on, value}} and text_rules [{id, text, on}] — the+-- same shapes as content_drafts.rules (00213). Pasted rule text is+-- writing guidance for the editor and the agent only; it changes no+-- access or safety rule (spec §10, CHAT-05).+-- * Members of the organization read them; admins and managers save them,+-- as they do the workspace's other settings (brand_domains), since every+-- new draft of the type starts from them.++create table if not exists public.content_rule_sets (+ organization_id uuid not null references public.organizations(id) on delete cascade,+ page_type text not null check (char_length(page_type) between 1 and 40),+ overrides jsonb not null default '{}'::jsonb+ check (jsonb_typeof(overrides) = 'object' and octet_length(overrides::text) <= 16384),+ text_rules jsonb not null default '[]'::jsonb+ check (jsonb_typeof(text_rules) = 'array' and jsonb_array_length(text_rules) <= 50+ and octet_length(text_rules::text) <= 32768),+ updated_by uuid references public.profiles(id) on delete set null,+ updated_at timestamptz not null default now(),+ primary key (organization_id, page_type)+);++alter table public.content_rule_sets enable row level security;++create policy "content_rule_sets: member select"+ on public.content_rule_sets+ for select+ using (organization_id in (select p.organization_id from public.profiles p where p.id = auth.uid()));++create policy "content_rule_sets: manager insert"+ on public.content_rule_sets+ for insert+ with check (+ organization_id in (+ select p.organization_id from public.profiles p+ where p.id = auth.uid() and p.role in ('admin', 'manager')+ )+ and updated_by = auth.uid()+ );++create policy "content_rule_sets: manager update"+ on public.content_rule_sets+ for update+ using (+ organization_id in (+ select p.organization_id from public.profiles p+ where p.id = auth.uid() and p.role in ('admin', 'manager')+ )+ )+ with check (+ organization_id in (+ select p.organization_id from public.profiles p+ where p.id = auth.uid() and p.role in ('admin', 'manager')+ )+ and updated_by = auth.uid()+ );++grant select, insert, update on public.content_rule_sets to authenticated;++comment on table public.content_rule_sets is+ 'Content Editor (CE-009): a workspace''s "My rules" per page type — rule overrides and text rules a new draft of the type starts from.';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 6afacf640..88ff64f7a 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -29889,3 +29889,78 @@ alter table public.content_draftscomment 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.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00214_content_rule_sets.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00214: a workspace's own rules per page type (Content Editor, CE-009)+-- ============================================================================+-- The Rules tab's "Save as my rules" (Content Editor spec v2 §10) keeps a+-- draft's rule choices for the workspace, per page type: the values and+-- switches the person changed, and the rules they wrote in their own words.+-- A new draft of that type starts from them ("My rules"); Reset takes a+-- draft back to Ansvisor's default set. The rules themselves are the app's+-- (web/src/lib/content/rules.ts); a set keeps only what differs.+--+-- * content_rule_sets: one row per organization and page type, with+-- overrides {key: {on, value}} and text_rules [{id, text, on}] — the+-- same shapes as content_drafts.rules (00213). Pasted rule text is+-- writing guidance for the editor and the agent only; it changes no+-- access or safety rule (spec §10, CHAT-05).+-- * Members of the organization read them; admins and managers save them,+-- as they do the workspace's other settings (brand_domains), since every+-- new draft of the type starts from them.++create table if not exists public.content_rule_sets (+ organization_id uuid not null references public.organizations(id) on delete cascade,+ page_type text not null check (char_length(page_type) between 1 and 40),+ overrides jsonb not null default '{}'::jsonb+ check (jsonb_typeof(overrides) = 'object' and octet_length(overrides::text) <= 16384),+ text_rules jsonb not null default '[]'::jsonb+ check (jsonb_typeof(text_rules) = 'array' and jsonb_array_length(text_rules) <= 50+ and octet_length(text_rules::text) <= 32768),+ updated_by uuid references public.profiles(id) on delete set null,+ updated_at timestamptz not null default now(),+ primary key (organization_id, page_type)+);++alter table public.content_rule_sets enable row level security;++create policy "content_rule_sets: member select"+ on public.content_rule_sets+ for select+ using (organization_id in (select p.organization_id from public.profiles p where p.id = auth.uid()));++create policy "content_rule_sets: manager insert"+ on public.content_rule_sets+ for insert+ with check (+ organization_id in (+ select p.organization_id from public.profiles p+ where p.id = auth.uid() and p.role in ('admin', 'manager')+ )+ and updated_by = auth.uid()+ );++create policy "content_rule_sets: manager update"+ on public.content_rule_sets+ for update+ using (+ organization_id in (+ select p.organization_id from public.profiles p+ where p.id = auth.uid() and p.role in ('admin', 'manager')+ )+ )+ with check (+ organization_id in (+ select p.organization_id from public.profiles p+ where p.id = auth.uid() and p.role in ('admin', 'manager')+ )+ and updated_by = auth.uid()+ );++grant select, insert, update on public.content_rule_sets to authenticated;++comment on table public.content_rule_sets is+ 'Content Editor (CE-009): a workspace''s "My rules" per page type — rule overrides and text rules a new draft of the type starts from.';+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 5af4e79b1..baf4b8704 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3681,7 +3681,7 @@"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.",+ "note": "Values you change apply to this draft only. Save as my rules keeps them for the workspace's next drafts of this type. 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": {@@ -3697,7 +3697,33 @@"aiCheck": "AI check","needsFeed": "Needs feed","noFanouts": "No fan-outs",- "addKeywords": "Add keywords"+ "addKeywords": "Add keywords",+ "numberCheck": "Number check"+ },+ "mineName": "My rules · {type}",+ "setPicked": "Rule set changed for this draft",+ "saveMine": "Save as my rules",+ "reset": "Reset",+ "savedMine": "Saved as My rules for {type}",+ "saveMineFailed": "Couldn't save My rules. Try again.",+ "resetDone": "Back to the default set",+ "text": {+ "title": "Your text rules",+ "write": "Write a rule",+ "placeholder": "Write a rule in your own words, e.g. \"Mention free shipping in the first paragraph\"",+ "help": "Numbers become checks. Other lines are checked by AI.",+ "add": "Add",+ "pasteMany": "Paste many",+ "pasteTitle": "Paste rules as text",+ "pasteDescription": "Paste your style guide or a list of rules. Each line becomes a rule you can edit or turn off. Rules guide the writing only.",+ "addMany": "{count, plural, =0 {Add rules} one {Add # rule} other {Add # rules}}",+ "cancel": "Cancel",+ "edit": "Edit rule",+ "added": "{count, plural, one {# rule added for this draft} other {# rules added for this draft}}",+ "removed": "Rule removed",+ "tooMany": "A draft keeps {max} text rules at most.",+ "numberCheckHint": "Checked as a number when the draft is scored.",+ "aiCheckHint": "Checked by AI when the draft is scored."}}},diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.test.tsxindex 5aef79ebd..30a101437 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.test.tsx@@ -11,6 +11,7 @@ import {rulesMet,type DraftRules,} from '@/lib/content/rules';+import { RoleProvider, type TeamRole } from '@/components/providers/role-provider';import { RulesTab } from './_rules-tab';import type { DraftRulesState } from './_use-draft-rules';@@ -22,8 +23,15 @@ import type { DraftRulesState } from './_use-draft-rules';const change = vi.fn();const pickSet = vi.fn();+const addTextRules = vi.fn();+const changeTextRule = vi.fn();+const saveAsMine = vi.fn();+const reset = vi.fn();-function state(choices: DraftRules = { set: null, overrides: {} }): DraftRulesState {+function state(+ choices: Pick<DraftRules, 'overrides'> = { overrides: {} },+ extra: Partial<DraftRulesState> = {},+): 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>',@@ -35,22 +43,33 @@ function state(choices: DraftRules = { set: null, overrides: {} }): DraftRulesSt}));return {setType: 'feature_page',+ source: 'default',rules: checked,+ textRules: [],+ mineTypes: [],+ ready: true,...rulesMet(checked),length: 3000,change,pickSet,+ addTextRules,+ changeTextRule,+ saveAsMine,+ reset,+ ...extra,};}let container: HTMLDivElement;let root: Root;-async function render(s: DraftRulesState) {+async function render(s: DraftRulesState, role: TeamRole = 'admin') {await act(async () => {root.render(<NextIntlClientProvider locale="en" messages={messages}>- <RulesTab state={s} siteType="b2b" draftPageType="feature_page" />+ <RoleProvider role={role}>+ <RulesTab state={s} siteType="b2b" draftPageType="feature_page" />+ </RoleProvider></NextIntlClientProvider>,);});@@ -67,8 +86,8 @@ beforeEach(() => {container = document.createElement('div');document.body.appendChild(container);root = createRoot(container);- change.mockReset();- pickSet.mockReset();+ for (const fn of [change, pickSet, addTextRules, changeTextRule, saveAsMine, reset])+ fn.mockReset();});afterEach(() => {@@ -131,9 +150,93 @@ describe('the Rules tab', () => {);expect(change).toHaveBeenCalledWith('citeInline', { on: false });- await render(state({ set: null, overrides: { citeInline: { on: false } } }));+ await render(state({ 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');});+ it('lists the rules in the person’s own words, edited in place', async () => {+ await render(+ state(undefined, {+ textRules: [+ { rule: { id: 'a', text: 'Use at least 3 images', on: true }, check: 'numberCheck' },+ { rule: { id: 'b', text: 'Mention free shipping', on: false }, check: 'aiCheck' },+ ],+ }),+ );+ expect(container.textContent).toContain('Your text rules');+ const inputs = [+ ...container.querySelectorAll<HTMLInputElement>('input[aria-label="Edit rule"]'),+ ];+ expect(inputs.map((i) => i.value)).toEqual(['Use at least 3 images', 'Mention free shipping']);+ expect(inputs[0].closest('li')!.textContent).toContain('Number check');+ expect(inputs[1].closest('li')!.textContent).toContain('Off');++ await act(async () => {+ inputs[0].focus();+ setValue(inputs[0], 'Use at least 4 images');+ });+ await act(async () => inputs[0].blur());+ expect(changeTextRule).toHaveBeenCalledWith('a', { text: 'Use at least 4 images' });++ await act(async () =>+ inputs[1].closest('li')!.querySelector<HTMLElement>('[role="switch"]')!.click(),+ );+ expect(changeTextRule).toHaveBeenCalledWith('b', { on: true });+ });++ it('adds a rule written in the box, one per line', async () => {+ await render(state());+ const box = container.querySelector<HTMLTextAreaElement>(+ 'textarea[aria-label="Write a rule"]',+ )!;+ await act(async () => {+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!.call(+ box,+ '- Mention free shipping\n2) Use 3 images',+ );+ box.dispatchEvent(new Event('input', { bubbles: true }));+ });+ const add = [...container.querySelectorAll('button')].find((b) => b.textContent === 'Add')!;+ await act(async () => add.click());+ expect(addTextRules).toHaveBeenCalledWith(['Mention free shipping', 'Use 3 images']);+ expect(box.value).toBe('');+ });++ it('saves the set as My rules, or resets it', async () => {+ await render(state());+ const button = (name: string) =>+ [...container.querySelectorAll('button')].find((b) => b.textContent === name)!;+ await act(async () => button('Save as my rules').click());+ expect(saveAsMine).toHaveBeenCalled();+ await act(async () => button('Reset').click());+ expect(reset).toHaveBeenCalled();+ });++ it('leaves saving My rules to admins and managers', async () => {+ const saveButton = () =>+ [...container.querySelectorAll('button')].find((b) => b.textContent === 'Save as my rules');+ await render(state(), 'manager');+ expect(saveButton()).toBeDefined();+ for (const role of ['analyst', 'agency_partner'] as const) {+ await render(state(), role);+ expect(saveButton()).toBeUndefined();+ // Reset is the draft's own: anyone can.+ expect(container.textContent).toContain('Reset');+ }+ });++ it('keeps every control off until My rules are read', async () => {+ await render(state(undefined, { ready: false }));+ expect(container.querySelector('fieldset')!.disabled).toBe(true);+ await render(state());+ expect(container.querySelector('fieldset')!.disabled).toBe(false);+ });++ it('shows Ansvisor’s set when a draft on My rules has none for its type', async () => {+ await render(state(undefined, { source: 'mine', mineTypes: [] }));+ const trigger = container.querySelector('[aria-label="Rule set"]')!;+ expect(trigger.textContent).toContain('Feature page · Ansvisor default');+ expect(trigger.textContent).not.toContain('mine:');+ });});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsxindex d5461be12..05280c513 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx@@ -2,6 +2,16 @@import { useState } from 'react';import { useTranslations } from 'next-intl';+import { Button } from '@/components/ui/button';+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog';+import { Textarea } from '@/components/ui/textarea';import {Select,SelectContent,@@ -11,9 +21,17 @@ import {} 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 {+ MAX_TEXT_RULE_LENGTH,+ RULE_GROUPS,+ splitRules,+ type ActiveRule,+ type RuleStatus,+ type TextRule,+} from '@/lib/content/rules';import { formatNumber } from '@/lib/format';import { cn } from '@/lib/utils';+import { useUserRole } from '@/hooks/use-user-role';import type { DraftRulesState } from './_use-draft-rules';/** Rules with an explanation on hover (spec §10). */@@ -34,7 +52,9 @@ const HINTED = new Set([* 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.+ * header's chip shows the same. Rules in the person's own words follow+ * ("Your text rules"); Save as my rules keeps the set for the workspace's+ * drafts of the type, and Reset goes back to Ansvisor's default.*/export function RulesTab({state,@@ -47,22 +67,46 @@ export function RulesTab({}) {const t = useTranslations('contentEditor.editor.rules');const tTypes = useTranslations('contentEditor.pageTypes');+ // The workspace's sets are saved by admins and managers, as its other settings are.+ const { canManage } = useUserRole();const types = [...SITE_PAGE_TYPES[siteType]];- for (const type of [draftPageType, state.setType]) {+ for (const type of [draftPageType, state.setType, ...state.mineTypes]) {if (type && !types.includes(type)) types.push(type);}- const items = types.map((type) => ({ value: type, label: t('setName', { type: tTypes(type) }) }));+ const items = [+ ...types.map((type) => ({+ value: `default:${type}`,+ label: t('setName', { type: tTypes(type) }),+ })),+ ...state.mineTypes.map((type) => ({+ value: `mine:${type}`,+ label: t('mineName', { type: tTypes(type) }),+ })),+ ];++ // A draft on My rules for a type the workspace has none for (its type+ // changed, or My rules couldn't be read) shows Ansvisor's set for it.+ const source =+ state.source === 'mine' && state.setType && state.mineTypes.includes(state.setType)+ ? 'mine'+ : 'default';return (- <div className="space-y-4 text-sm">+ // Nothing changes before My rules are read: a change would leave them out.+ <fieldset+ disabled={!state.ready}+ aria-busy={!state.ready}+ className="m-0 min-w-0 space-y-4 border-0 p-0 text-sm"+ ><div className="space-y-1.5"><span className="text-xs text-muted-foreground">{t('set')}</span><Selectitems={items}- value={state.setType ?? ''}+ value={state.setType ? `${source}:${state.setType}` : ''}onValueChange={(value) => {- if (!isPageType(value)) return;- state.pickSet(value === draftPageType ? null : value);+ const [source, type] = String(value ?? '').split(':');+ if (!isPageType(type) || (source !== 'default' && source !== 'mine')) return;+ state.pickSet(type, source);}}><SelectTrigger aria-label={t('set')} className="w-full">@@ -105,7 +149,167 @@ export function RulesTab({);})}+ {state.textRules.length > 0 && (+ <section className="space-y-1.5">+ <h4 className="text-xs font-medium text-muted-foreground">{t('text.title')}</h4>+ <ul className="divide-y rounded-lg border">+ {state.textRules.map(({ rule, check }) => (+ <TextRuleRow+ key={rule.id}+ rule={rule}+ check={check}+ onChange={(change) => state.changeTextRule(rule.id, change)}+ />+ ))}+ </ul>+ </section>+ )}++ <AddTextRules onAdd={state.addTextRules} />++ <div className="flex flex-wrap gap-2">+ {canManage && (+ <Button size="sm" disabled={!state.setType} onClick={state.saveAsMine}>+ {t('saveMine')}+ </Button>+ )}+ <Button size="sm" variant="outline" onClick={state.reset}>+ {t('reset')}+ </Button>+ </div>+<p className="text-[11px] text-muted-foreground">{t('note')}</p>+ </fieldset>+ );+}++/** A rule in the person's own words: edited in place, turned off, removed when emptied. */+function TextRuleRow({+ rule,+ check,+ onChange,+}: {+ rule: TextRule;+ check: 'numberCheck' | 'aiCheck';+ onChange: (change: { text?: string; on?: boolean }) => void;+}) {+ const t = useTranslations('contentEditor.editor.rules');+ const [text, setText] = useState(rule.text);+ const [editing, setEditing] = useState(false);+ const commit = () => {+ setEditing(false);+ if (text.trim() !== rule.text) onChange({ text });+ };+ return (+ <li className={cn('flex items-center gap-2 px-3 py-2', !rule.on && 'opacity-60')}>+ <Switch+ on={rule.on}+ label={t('toggle', { name: rule.text })}+ onToggle={() => onChange({ on: !rule.on })}+ />+ <input+ value={editing ? text : rule.text}+ title={rule.text}+ aria-label={t('text.edit')}+ maxLength={MAX_TEXT_RULE_LENGTH}+ onFocus={() => {+ setText(rule.text);+ 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.text);+ setEditing(false);+ }+ }}+ className="h-6 min-w-0 flex-1 rounded-md border border-transparent bg-transparent px-1 text-xs outline-none hover:border-border focus-visible:border-border focus-visible:ring-2 focus-visible:ring-ring/50"+ />+ <span+ className="w-20 shrink-0 text-right text-[11px] text-muted-foreground"+ title={t(`text.${check}Hint`)}+ >+ {rule.on ? t(`status.${check}`) : t('status.off')}+ </span>+ </li>+ );+}++/** Write a rule, or paste many: each line becomes a rule (bullets and numbering taken off). */+function AddTextRules({ onAdd }: { onAdd: (lines: string[]) => void }) {+ const t = useTranslations('contentEditor.editor.rules.text');+ const [text, setText] = useState('');+ const [pasting, setPasting] = useState(false);+ const [pasted, setPasted] = useState('');+ const lines = splitRules(text);+ const pastedLines = splitRules(pasted);++ return (+ <div className="space-y-1.5 rounded-lg border p-2">+ <Textarea+ value={text}+ onChange={(e) => setText(e.target.value)}+ placeholder={t('placeholder')}+ aria-label={t('write')}+ rows={2}+ className="min-h-0 resize-none border-0 p-1 text-xs shadow-none focus-visible:ring-0"+ onKeyDown={(e) => {+ if (e.key === 'Enter' && !e.shiftKey && lines.length) {+ e.preventDefault();+ onAdd(lines);+ setText('');+ }+ }}+ />+ <div className="flex items-center gap-2">+ <span className="min-w-0 flex-1 text-[11px] text-muted-foreground">{t('help')}</span>+ <Button size="sm" variant="ghost" onClick={() => setPasting(true)}>+ {t('pasteMany')}+ </Button>+ <Button+ size="sm"+ variant="outline"+ disabled={!lines.length}+ onClick={() => {+ onAdd(lines);+ setText('');+ }}+ >+ {t('add')}+ </Button>+ </div>+ <Dialog open={pasting} onOpenChange={setPasting}>+ <DialogContent className="sm:max-w-lg">+ <DialogHeader>+ <DialogTitle>{t('pasteTitle')}</DialogTitle>+ <DialogDescription>{t('pasteDescription')}</DialogDescription>+ </DialogHeader>+ <Textarea+ value={pasted}+ onChange={(e) => setPasted(e.target.value)}+ aria-label={t('pasteTitle')}+ rows={8}+ className="text-xs"+ />+ <DialogFooter>+ <Button variant="outline" onClick={() => setPasting(false)}>+ {t('cancel')}+ </Button>+ <Button+ disabled={!pastedLines.length}+ onClick={() => {+ onAdd(pastedLines);+ setPasted('');+ setPasting(false);+ }}+ >+ {t('addMany', { count: pastedLines.length })}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog></div>);}@@ -124,24 +328,11 @@ function RuleRow({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>+ <Switch+ on={rule.on}+ label={t('toggle', { name })}+ onToggle={() => onChange({ on: !rule.on })}+ /><spanclassName="min-w-0 flex-1 text-xs"title={HINTED.has(rule.key) ? t(`hints.${rule.key}`) : undefined}@@ -246,3 +437,26 @@ function StatusBadge({ on, status }: { on: boolean; status: RuleStatus }) {</span>);}++function Switch({ on, label, onToggle }: { on: boolean; label: string; onToggle: () => void }) {+ return (+ <button+ type="button"+ role="switch"+ aria-checked={on}+ aria-label={label}+ onClick={onToggle}+ className={cn(+ 'relative h-4 w-7 shrink-0 rounded-full transition-colors',+ on ? 'bg-primary' : 'bg-muted-foreground/30',+ )}+ >+ <span+ className={cn(+ 'absolute top-0.5 h-3 w-3 rounded-full bg-background transition-all',+ on ? 'left-3.5' : 'left-0.5',+ )}+ />+ </button>+ );+}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.tsindex afbf3ce95..d32802e6a 100644--- 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@@ -1,21 +1,26 @@'use client';-import { useDeferredValue, useMemo, useState } from 'react';+import { useDeferredValue, useEffect, useMemo, useState } from 'react';import { useTranslations } from 'next-intl';import { toast } from 'sonner';-import { saveDraftRules } from '@/lib/actions/content-drafts';+import { getMyRuleSets, saveDraftRules, saveMyRuleSet } from '@/lib/actions/content-drafts';import { isPageType, type ContentDraft, type PageType } from '@/lib/content/drafts';import {+ MAX_TEXT_RULES,activeRules,checkRule,+ effectiveRules,readPage,ruleLength,ruleSet,rulesMet,+ textRuleCheck,type ActiveRule,type DraftRules,type RuleContext,type RuleStatus,+ type SavedRuleSet,+ type TextRule,} from '@/lib/content/rules';import { buildSourceGroups } from '@/lib/content/sources';import type { DraftReads } from './_use-draft-reads';@@ -23,24 +28,47 @@ import type { DraftReads } from './_use-draft-reads';export interface DraftRulesState {/** The page type whose set applies. */setType: PageType | null;+ /** The set the draft's rules come from: Ansvisor's default or the workspace's My rules. */+ source: 'default' | 'mine';rules: { rule: ActiveRule; status: RuleStatus }[];+ /** The person's own rules, each checked as a number or by AI (not counted). */+ textRules: { rule: TextRule; check: 'numberCheck' | 'aiCheck' }[];+ /** The page types the workspace has My rules for. */+ mineTypes: PageType[];+ /** My rules have been read: until then a change would leave the workspace's set out. */+ ready: boolean;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;+ /** Loads a set into the draft: a type's Ansvisor default, or the workspace's My rules for it. */+ pickSet: (type: PageType, source: 'default' | 'mine') => void;+ /** Adds rules in the person's own words, one per line. */+ addTextRules: (lines: string[]) => void;+ /** Edits a text rule, turns it on or off; an empty text removes it. */+ changeTextRule: (id: string, change: { text?: string; on?: boolean }) => void;+ /** Save as my rules: the draft's choices become the workspace's set for the type. */+ saveAsMine: () => void;+ /** Back to Ansvisor's default set for the type. */+ reset: () => void;}+const newId = () =>+ typeof crypto !== 'undefined' && 'randomUUID' in crypto+ ? crypto.randomUUID()+ : `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;+/*** 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.+ * the header's chip and the Rules tab show the same. A draft no one has set+ * rules on starts from the workspace's My rules for its type, if it has+ * them, read once. 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,@@ -56,7 +84,25 @@ export function useDraftRules({reads: Pick<DraftReads, 'brief' | 'sources'>;}): DraftRulesState {const t = useTranslations('contentEditor.editor.rules');+ const tTypes = useTranslations('contentEditor.pageTypes');const [choices, setChoices] = useState<DraftRules>(draft.rules);+ const [mine, setMine] = useState<Partial<Record<PageType, SavedRuleSet>>>({});+ const [mineRead, setMineRead] = useState(false);++ useEffect(() => {+ let cancelled = false;+ getMyRuleSets(draft.brandId)+ .then((sets) => {+ if (!cancelled) setMine(sets);+ })+ .catch((err) => console.error('Failed to read My rules:', err))+ .finally(() => {+ if (!cancelled) setMineRead(true);+ });+ return () => {+ cancelled = true;+ };+ }, [draft.brandId]);const sources = reads.sources;const ctx = useMemo<RuleContext>(() => {@@ -82,9 +128,13 @@ export function useDraftRules({const draftType = isPageType(pageType) ? pageType : null;const setType = choices.set ?? draftType;+ const effective = useMemo(+ () => effectiveRules(choices, setType ? mine[setType] : undefined),+ [choices, setType, mine],+ );const rules = useMemo(- () => activeRules(ruleSet(setType, { keywords }), choices),- [setType, keywords, choices],+ () => activeRules(ruleSet(setType, { keywords }), effective),+ [setType, keywords, effective],);// The checks follow the page a beat behind typing.const deferredHtml = useDeferredValue(html);@@ -99,29 +149,95 @@ export function useDraftRules({);const { met, total } = rulesMet(checked);- const save = (next: DraftRules) => {+ const save = (next: DraftRules, message: string) => {+ // Before My rules are read, the draft would save Ansvisor's set over the workspace's.+ if (!mineRead) return;const before = choices;setChoices(next);saveDraftRules(draft.id, next)- .then(() => toast(t('updated')))+ .then(() => toast(message)).catch((err) => {console.error('Failed to save the rules:', err);setChoices(before);toast.error(t('saveFailed'));});};+ // A change keeps the set the draft's rules come from.+ const edited = (change: Partial<DraftRules>, message = t('updated')) =>+ save({ ...effective, source: effective.source ?? 'default', ...change }, message);+ const typeName = (type: PageType | null) => (type ? tTypes(type) : '');return {setType,+ source: effective.source ?? 'default',rules: checked,+ textRules: effective.textRules.map((rule) => ({ rule, check: textRuleCheck(rule.text) })),+ mineTypes: (Object.keys(mine) as PageType[]).filter((type) => mine[type]),+ ready: mineRead,met,total,length: ruleLength(rules, setType),change: (key, change) =>- save({- ...choices,- overrides: { ...choices.overrides, [key]: { ...choices.overrides[key], ...change } },+ edited({+ overrides: { ...effective.overrides, [key]: { ...effective.overrides[key], ...change } },}),- pickSet: (type) => save({ ...choices, set: type }),+ pickSet: (type, source) => {+ const set = source === 'mine' ? mine[type] : undefined;+ save(+ {+ set: type === draftType ? null : type,+ source,+ overrides: set?.overrides ?? {},+ textRules: set?.textRules ?? [],+ },+ t('setPicked'),+ );+ },+ addTextRules: (lines) => {+ const room = MAX_TEXT_RULES - effective.textRules.length;+ if (room <= 0) {+ toast.error(t('text.tooMany', { max: MAX_TEXT_RULES }));+ return;+ }+ const added = lines.slice(0, room).map((text) => ({ id: newId(), text, on: true }));+ edited(+ { textRules: [...effective.textRules, ...added] },+ t('text.added', { count: added.length }),+ );+ },+ changeTextRule: (id, change) => {+ const removed = change.text !== undefined && !change.text.trim();+ edited(+ {+ textRules: removed+ ? effective.textRules.filter((r) => r.id !== id)+ : effective.textRules.map((r) =>+ r.id === id+ ? {+ ...r,+ ...change,+ ...(change.text !== undefined && { text: change.text.trim() }),+ }+ : r,+ ),+ },+ removed ? t('text.removed') : t('updated'),+ );+ },+ saveAsMine: () => {+ if (!setType) return;+ const set: SavedRuleSet = { overrides: effective.overrides, textRules: effective.textRules };+ saveMyRuleSet(draft.brandId, setType, set)+ .then(() => {+ setMine((prev) => ({ ...prev, [setType]: set }));+ save({ ...effective, source: 'mine' }, t('savedMine', { type: typeName(setType) }));+ })+ .catch((err) => {+ console.error('Failed to save My rules:', err);+ toast.error(t('saveMineFailed'));+ });+ },+ reset: () =>+ save({ set: choices.set, source: 'default', overrides: {}, textRules: [] }, t('resetDone')),};}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsxindex 8dad1bff7..5e1b24148 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@@ -3,6 +3,7 @@ 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 { RoleProvider } from '@/components/providers/role-provider';import type { ContentDraft } from '@/lib/content/drafts';import ContentEditorPage from './page';@@ -16,7 +17,11 @@ const getDraftSources = vi.fn();const getDraftBrief = vi.fn();const rebuildDraftBrief = vi.fn();const saveDraftRules = vi.fn();+const getMyRuleSets = vi.fn();+const saveMyRuleSet = vi.fn();vi.mock('@/lib/actions/content-drafts', () => ({+ getMyRuleSets: (...args: unknown[]) => getMyRuleSets(...args),+ saveMyRuleSet: (...args: unknown[]) => saveMyRuleSet(...args),saveDraftRules: (...args: unknown[]) => saveDraftRules(...args),getDraftSources: (...args: unknown[]) => getDraftSources(...args),getDraftBrief: (...args: unknown[]) => getDraftBrief(...args),@@ -116,7 +121,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: {} },+ rules: { set: null, source: null, overrides: {}, textRules: [] },updatedAt: '2026-10-20T10:00:00Z',...over,});@@ -128,7 +133,9 @@ async function renderPage() {await act(async () => {root.render(<NextIntlClientProvider locale="en" messages={messages}>- <ContentEditorPage />+ <RoleProvider role="admin">+ <ContentEditorPage />+ </RoleProvider></NextIntlClientProvider>,);});@@ -155,6 +162,8 @@ beforeEach(() => {getDraftBrief.mockReset().mockResolvedValue({ brief: null });rebuildDraftBrief.mockReset();saveDraftRules.mockReset().mockResolvedValue(undefined);+ getMyRuleSets.mockReset().mockResolvedValue({});+ saveMyRuleSet.mockReset().mockResolvedValue(undefined);localStorage.clear();brandState.activeBrandId = 'b1';brandState.setActiveBrand.mockReset();@@ -740,12 +749,58 @@ describe('the side panel', () => {await act(async () => sentence.click());expect(saveDraftRules).toHaveBeenCalledWith('d1', {set: null,+ source: 'default',overrides: { sentence: { on: false } },+ textRules: [],});expect(chip.getAttribute('aria-label')).toBe(`Rules ${met - 1}/${total - 1}`);expect(toast).toHaveBeenCalledWith('Rule updated for this draft');});+ it('starts a draft from the workspace’s My rules, and saves a draft’s set as them', async () => {+ getMyRuleSets.mockResolvedValue({+ blog_post: {+ overrides: { sentence: { on: false } },+ textRules: [{ id: 'm1', text: 'Mention free shipping', on: true }],+ },+ });+ getContentDraft.mockResolvedValue(draft({ pageType: 'blog_post' }));+ window.innerWidth = 1440;+ await renderPage();++ const rulesTab = [...panel()!.querySelectorAll<HTMLElement>('[role="tab"]')].find(+ (el) => el.textContent === 'Rules',+ )!;+ await act(async () => {+ rulesTab.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));+ rulesTab.click();+ });+ expect(getMyRuleSets).toHaveBeenCalledWith('b1');+ expect(panel()!.textContent).toContain('My rules · Blog post');+ expect(panel()!.textContent).toContain('Your text rules');+ expect(+ panel()!+ .querySelector('[role="switch"][aria-label="Max sentence length: on or off"]')!+ .getAttribute('aria-checked'),+ ).toBe('false');+ // Nothing is saved on the draft until something changes.+ expect(saveDraftRules).not.toHaveBeenCalled();++ const save = [...panel()!.querySelectorAll('button')].find(+ (b) => b.textContent === 'Save as my rules',+ )!;+ await act(async () => save.click());+ expect(saveMyRuleSet).toHaveBeenCalledWith('b1', 'blog_post', {+ overrides: { sentence: { on: false } },+ textRules: [{ id: 'm1', text: 'Mention free shipping', on: true }],+ });+ expect(saveDraftRules).toHaveBeenCalledWith(+ 'd1',+ expect.objectContaining({ source: 'mine', overrides: { sentence: { on: false } } }),+ );+ expect(toast).toHaveBeenCalledWith('Saved as My rules for Blog post');+ });+it('starts open on a wide window, and remembers it closed', async () => {getContentDraft.mockResolvedValue(draft({ method: 'create' }));window.innerWidth = 1440;diff --git a/web/src/lib/actions/content-drafts-my-rules.test.ts b/web/src/lib/actions/content-drafts-my-rules.test.tsnew file mode 100644index 000000000..cebb39c19--- /dev/null+++ b/web/src/lib/actions/content-drafts-my-rules.test.ts@@ -0,0 +1,95 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/** My rules (CE-009, 00214): the workspace's rule set per page type. */++const BRAND = '33333333-3333-3333-3333-333333333333';++let reads: Record<string, unknown>;+let upserts: { table: string; value: unknown; options: unknown }[];+let filters: [string, string, unknown][];+let user: { id: string } | null;++vi.mock('@/lib/action-center/assignees', () => ({ readAssignees: vi.fn(async () => new Map()) }));+vi.mock('@/lib/supabase/server', () => ({+ createClient: vi.fn(async () => ({+ auth: { getUser: async () => ({ data: { user } }) },+ from: (table: string) => {+ const result = () => ({ data: reads[table] ?? null, error: null });+ const chain: Record<string, unknown> = {+ select: () => chain,+ eq: (col: string, v: unknown) => (filters.push([table, col, v]), chain),+ upsert: async (value: unknown, options: unknown) => {+ upserts.push({ table, value, options });+ return { error: null };+ },+ maybeSingle: async () => result(),+ then: (resolve: (r: unknown) => void) => resolve(result()),+ };+ return chain;+ },+ })),+}));++const { getMyRuleSets, saveMyRuleSet } = await import('./content-drafts');++const set = {+ overrides: { sentence: { value: '120' } },+ textRules: [{ id: 'r1', text: 'Mention free shipping', on: true }],+};++beforeEach(() => {+ reads = { brands: { organization_id: 'org1' } };+ upserts = [];+ filters = [];+ user = { id: 'u1' };+});++describe('getMyRuleSets', () => {+ it('reads the organization’s sets by page type, leaving out ones that don’t read as rules', async () => {+ reads.content_rule_sets = [+ { page_type: 'blog_post', overrides: set.overrides, text_rules: set.textRules },+ { page_type: 'nope', overrides: {}, text_rules: [] },+ { page_type: 'guide', overrides: [], text_rules: [] },+ ];+ expect(await getMyRuleSets(BRAND)).toEqual({ blog_post: set });+ expect(filters).toEqual([+ ['brands', 'id', BRAND],+ ['content_rule_sets', 'organization_id', 'org1'],+ ]);+ });++ it('has none for a brand the member can’t read', async () => {+ reads.brands = null;+ expect(await getMyRuleSets(BRAND)).toEqual({});+ await expect(getMyRuleSets('b1')).rejects.toThrow('invalid');+ });+});++describe('saveMyRuleSet', () => {+ it('keeps the set for the organization and page type, as the member', async () => {+ await saveMyRuleSet(BRAND, 'blog_post', set);+ expect(upserts).toEqual([+ {+ table: 'content_rule_sets',+ value: expect.objectContaining({+ organization_id: 'org1',+ page_type: 'blog_post',+ overrides: set.overrides,+ text_rules: set.textRules,+ updated_by: 'u1',+ }),+ options: { onConflict: 'organization_id,page_type' },+ },+ ]);+ });++ it('refuses a set out of shape, an unknown type, or no member', async () => {+ await expect(+ saveMyRuleSet(BRAND, 'blog_post', { ...set, textRules: [{ id: 'x', text: ' ', on: true }] }),+ ).rejects.toThrow('invalid');+ await expect(saveMyRuleSet(BRAND, 'nope' as never, set)).rejects.toThrow('invalid');+ user = null;+ await expect(saveMyRuleSet(BRAND, 'blog_post', set)).rejects.toThrow('not_found');+ expect(upserts).toEqual([]);+ });+});diff --git a/web/src/lib/actions/content-drafts-rules.test.ts b/web/src/lib/actions/content-drafts-rules.test.tsindex c78ec6b16..2f499c57b 100644--- a/web/src/lib/actions/content-drafts-rules.test.ts+++ b/web/src/lib/actions/content-drafts-rules.test.ts@@ -61,18 +61,36 @@ describe('the draft’s rules', () => {row = { ...base, rules: { set: 'guide', overrides: { faq: { on: false } } } };expect((await getContentDraft(DRAFT))?.rules).toEqual({set: 'guide',+ source: null,overrides: { faq: { on: false } },+ textRules: [],});row = { ...base, rules: null };- expect((await getContentDraft(DRAFT))?.rules).toEqual({ set: null, overrides: {} });+ expect((await getContentDraft(DRAFT))?.rules).toEqual({+ set: null,+ source: null,+ overrides: {},+ textRules: [],+ });row = { ...base, rules: { set: 'nope', overrides: {} } };- expect((await getContentDraft(DRAFT))?.rules).toEqual({ set: null, overrides: {} });+ expect((await getContentDraft(DRAFT))?.rules).toEqual({+ set: null,+ source: null,+ overrides: {},+ textRules: [],+ });});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]] }]);+ expect(updates).toEqual([+ {+ op: 'update',+ value: { rules: { ...rules, source: null, textRules: [] } },+ filters: [['id', DRAFT]],+ },+ ]);});it('refuses rules out of shape, and says when the draft isn’t found', async () => {diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex 35107ba32..68ab9a83b 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -29,7 +29,13 @@ import {} from '@/lib/content/editor';import { detectPageType, siteTypeOf, type SiteType } from '@/lib/content/page-types';import { sanitizeDraftHtml } from '@/lib/content/sanitize-draft-html';-import { NO_DRAFT_RULES, draftRulesSchema, type DraftRules } from '@/lib/content/rules';+import {+ NO_DRAFT_RULES,+ draftRulesSchema,+ savedRuleSetSchema,+ type DraftRulesInput,+ type SavedRuleSet,+} from '@/lib/content/rules';import {briefFromOpportunity,draftBriefSchema,@@ -879,7 +885,7 @@ export async function rebuildDraftBrief(* this draft ("Rule updated for this draft"). Throws 'not_found' when no* row changed.*/-export async function saveDraftRules(id: string, rules: DraftRules): Promise<void> {+export async function saveDraftRules(id: string, rules: DraftRulesInput): Promise<void> {const parsed = draftRulesSchema.safeParse(rules);if (!draftId.safeParse(id).success || !parsed.success) throw new Error('invalid');const supabase = await createClient();@@ -892,3 +898,77 @@ export async function saveDraftRules(id: string, rules: DraftRules): Promise<voiif (error) throw new Error(error.message);if (!data) throw new Error('not_found');}++/**+ * The workspace's My rules (CE-009, 00214), by page type: what a new draft+ * of the type starts from. Sets that don't read as rules are left out.+ */+export async function getMyRuleSets(+ brandId: string,+): Promise<Partial<Record<PageType, SavedRuleSet>>> {+ if (!draftId.safeParse(brandId).success) throw new Error('invalid');+ const supabase = await createClient();+ const { data: brand, error: brandError } = await supabase+ .from('brands')+ .select('organization_id')+ .eq('id', brandId)+ .maybeSingle();+ if (brandError) throw new Error(brandError.message);+ if (!brand?.organization_id) return {};+ const { data, error } = await supabase+ .from('content_rule_sets')+ .select('page_type, overrides, text_rules')+ .eq('organization_id', brand.organization_id);+ if (error) throw new Error(error.message);+ const sets: Partial<Record<PageType, SavedRuleSet>> = {};+ for (const row of data ?? []) {+ const set = savedRuleSetSchema.safeParse({+ overrides: row.overrides,+ textRules: row.text_rules,+ });+ if (pageTypeInput.safeParse(row.page_type).success && set.success) {+ sets[row.page_type as PageType] = set.data;+ }+ }+ return sets;+}++/**+ * Save as my rules (CE-009): a draft's rule choices become the workspace's+ * set for the page type, for every draft of it that starts after.+ */+export async function saveMyRuleSet(+ brandId: string,+ pageType: PageType,+ set: SavedRuleSet,+): Promise<void> {+ const parsed = savedRuleSetSchema.safeParse(set);+ if (+ !draftId.safeParse(brandId).success ||+ !pageTypeInput.safeParse(pageType).success ||+ !parsed.success+ ) {+ throw new Error('invalid');+ }+ const supabase = await createClient();+ const [userRes, brandRes] = await Promise.all([+ supabase.auth.getUser(),+ supabase.from('brands').select('organization_id').eq('id', brandId).maybeSingle(),+ ]);+ if (brandRes.error) throw new Error(brandRes.error.message);+ const userId = userRes.data.user?.id;+ const organizationId = brandRes.data?.organization_id;+ if (!userId || !organizationId) throw new Error('not_found');+ const { error } = await supabase.from('content_rule_sets').upsert(+ {+ organization_id: organizationId,+ page_type: pageType,+ overrides: parsed.data.overrides,+ text_rules: parsed.data.textRules,+ updated_by: userId,+ updated_at: new Date().toISOString(),+ },+ { onConflict: 'organization_id,page_type' },+ );+ if (error) throw new Error(error.message);+}diff --git a/web/src/lib/content/rules.test.ts b/web/src/lib/content/rules.test.tsindex e0e8d0cdb..6c61f9e3e 100644--- a/web/src/lib/content/rules.test.ts+++ b/web/src/lib/content/rules.test.ts@@ -2,6 +2,9 @@ import { describe, expect, it } from 'vitest';import {NO_DRAFT_RULES,activeRules,+ effectiveRules,+ splitRules,+ textRuleCheck,checkRule,draftRulesSchema,readPage,@@ -29,7 +32,7 @@ const rule = (): ActiveRule => {const rules = activeRules(ruleSet(pageType),- value === undefined ? NO_DRAFT_RULES : { set: null, overrides: { [key]: { value } } },+ value === undefined ? NO_DRAFT_RULES : { overrides: { [key]: { value } } },);const found = rules.find((r) => r.key === key);if (!found) throw new Error(`no rule ${key}`);@@ -62,7 +65,6 @@ describe('rule sets', () => {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({@@ -74,18 +76,15 @@ describe('rule sets', () => {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);@@ -97,8 +96,7 @@ describe('rule sets', () => {).toBe(true);expect(draftRulesSchema.safeParse({ set: 'nope', overrides: {} }).success).toBe(false);expect(- draftRulesSchema.safeParse({ set: null, overrides: { tone: { value: 'x'.repeat(501) } } })- .success,+ draftRulesSchema.safeParse({ overrides: { tone: { value: 'x'.repeat(501) } } }).success,).toBe(false);});});@@ -306,7 +304,6 @@ describe('page type rules', () => {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);@@ -318,3 +315,43 @@ describe('rulesMet', () => {expect(met).toBeLessThan(total);});});++describe('My rules and text rules', () => {+ const mine = {+ overrides: { sentence: { value: '120' } },+ textRules: [{ id: 'm1', text: 'Mention free shipping', on: true }],+ };++ it('starts an untouched draft from the workspace’s My rules', () => {+ expect(effectiveRules(NO_DRAFT_RULES, mine)).toEqual({ set: null, source: 'mine', ...mine });+ expect(effectiveRules(NO_DRAFT_RULES, undefined)).toEqual(NO_DRAFT_RULES);+ });++ it('keeps a draft’s own choices, and a reset draft on the default', () => {+ const own = { ...NO_DRAFT_RULES, overrides: { faq: { on: false } } };+ expect(effectiveRules(own, mine)).toEqual(own);+ const reset = { ...NO_DRAFT_RULES, source: 'default' as const };+ expect(effectiveRules(reset, mine)).toEqual(reset);+ });++ it('reads rules saved before text rules with none', () => {+ expect(draftRulesSchema.parse({ set: 'guide', overrides: {} })).toEqual({+ set: 'guide',+ source: null,+ overrides: {},+ textRules: [],+ });+ });++ it('splits pasted rules into lines, bullets and numbering off', () => {+ expect(+ splitRules('- Mention free shipping\n\n2) Use 3 images\n• Keep it short \n1. '),+ ).toEqual(['Mention free shipping', 'Use 3 images', 'Keep it short']);+ expect(splitRules('x'.repeat(400))[0]).toHaveLength(300);+ });++ it('checks a rule with a number as a number, the rest by AI', () => {+ expect(textRuleCheck('Use at least 3 images')).toBe('numberCheck');+ expect(textRuleCheck('Mention free shipping')).toBe('aiCheck');+ });+});diff --git a/web/src/lib/content/rules.ts b/web/src/lib/content/rules.tsindex 0aa46255e..ac0c5fe42 100644--- a/web/src/lib/content/rules.ts+++ b/web/src/lib/content/rules.ts@@ -195,19 +195,83 @@ export function ruleSet(];}+/** Per rule: whether it is on, and the value used. */+const overridesSchema = 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);++/** A rule written in the person's own words ("Your text rules"). */+export const MAX_TEXT_RULES = 50;+export const MAX_TEXT_RULE_LENGTH = 300;+export const textRuleSchema = z.object({+ id: z.string().min(1).max(40),+ text: z.string().trim().min(1).max(MAX_TEXT_RULE_LENGTH),+ on: z.boolean(),+});+export type TextRule = z.infer<typeof textRuleSchema>;+/** 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),+ /**+ * The set the draft started from: Ansvisor's default, or the workspace's+ * My rules (00214). Null until the person changes something: the+ * workspace's My rules for the type apply, if it has them.+ */+ source: z.enum(['default', 'mine']).nullable().default(null),+ overrides: overridesSchema,+ textRules: z.array(textRuleSchema).max(MAX_TEXT_RULES).default([]),});export type DraftRules = z.infer<typeof draftRulesSchema>;-export const NO_DRAFT_RULES: DraftRules = { set: null, overrides: {} };+/** As saved: the source and text rules may be left out (rules from before 00214 have neither). */+export type DraftRulesInput = z.input<typeof draftRulesSchema>;+export const NO_DRAFT_RULES: DraftRules = {+ set: null,+ source: null,+ overrides: {},+ textRules: [],+};++/** A workspace's My rules for one page type (content_rule_sets, 00214). */+export const savedRuleSetSchema = z.object({+ overrides: overridesSchema,+ textRules: z.array(textRuleSchema).max(MAX_TEXT_RULES),+});+export type SavedRuleSet = z.infer<typeof savedRuleSetSchema>;++/**+ * The choices in effect: the draft's own; or, for a draft no one has set+ * rules on yet, the workspace's My rules for the set's type, as a template.+ */+export function effectiveRules(rules: DraftRules, mine: SavedRuleSet | undefined): DraftRules {+ const untouched =+ rules.source === null && !Object.keys(rules.overrides).length && !rules.textRules.length;+ if (untouched && mine) {+ return { ...rules, source: 'mine', overrides: mine.overrides, textRules: mine.textRules };+ }+ return rules;+}++/**+ * Paste many: one rule per line, bullets and numbering taken off ("- ",+ * "• ", "1. ", "2) "), empty lines dropped, each cut to the limit.+ */+export function splitRules(text: string): string[] {+ return text+ .split(/\r?\n+/)+ .map((line) => line.replace(/^\s*(?:[-*•–]|\d+[.)])\s*/, '').trim())+ .filter(Boolean)+ .map((line) => line.slice(0, MAX_TEXT_RULE_LENGTH));+}++/** How a text rule is checked: a number makes it a number check; anything else, AI. */+export function textRuleCheck(text: string): 'numberCheck' | 'aiCheck' {+ return /\d/.test(text) ? 'numberCheck' : 'aiCheck';+}export interface ActiveRule extends RuleDef {on: boolean;@@ -216,7 +280,7 @@ export interface ActiveRule extends RuleDef {changed: boolean;}-export function activeRules(defs: RuleDef[], rules: DraftRules): ActiveRule[] {+export function activeRules(defs: RuleDef[], rules: Pick<DraftRules, 'overrides'>): ActiveRule[] {return defs.map((def) => {const override = rules.overrides[def.key];const current = override?.value ?? def.value;diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 779f97d55..bdb8a84ea 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -825,6 +825,33 @@ export type Database = {},]}+ content_rule_sets: {+ Row: {+ organization_id: string+ overrides: Json+ page_type: string+ text_rules: Json+ updated_at: string+ updated_by: string | null+ }+ Insert: {+ organization_id: string+ overrides?: Json+ page_type: string+ text_rules?: Json+ updated_at?: string+ updated_by?: string | null+ }+ Update: {+ organization_id?: string+ overrides?: Json+ page_type?: string+ text_rules?: Json+ updated_at?: string+ updated_by?: string | null+ }+ Relationships: []+ }content_drafts: {Row: {action_id: string | null