Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(content): plan each section's answer, format and facts in the brief behind CONTENT_BRIEF_RULES, with the cited pages numbered and the rules in effect (brief rules PR 4) (#1540)
Cihan6dd30f9ebe84
diff --git a/server/.env.example b/server/.env.exampleindex 8d0c6b4ef..975bed904 100644--- a/server/.env.example+++ b/server/.env.example@@ -59,6 +59,10 @@ COMPETITOR_SUGGESTION_MODEL=google/gemini-3-flash-preview# another model family than the brief's, so it doesn't grade its own. Falls# back to anthropic/claude-haiku-4-5 (needs ANTHROPIC_API_KEY).# BRIEF_EVAL_JUDGE_MODEL=+# Content Editor briefs plan with the brief rules (2026): each section's+# answer, format and facts, as version 2 (web brief.ts). Off until the brief+# eval passes them (node src/scripts/eval-brief.js with it on).+# CONTENT_BRIEF_RULES=true# Content Editor Quality's AI checks (CE-046 on: the kind of a source's# site the rules can't place): a small, cheap model. Metered from the same# AI budget as "quality". Falls back to DEFAULT_SUGGESTION_MODEL, thendiff --git a/server/src/lib/content-brief-eval.js b/server/src/lib/content-brief-eval.jsindex 1319f83ec..b1f164d88 100644--- a/server/src/lib/content-brief-eval.js+++ b/server/src/lib/content-brief-eval.js@@ -1,7 +1,13 @@import { createHash } from 'node:crypto';import { z } from 'zod';import { HEADING_LIMITS } from './content-agent.js';-import { SYSTEM_PROMPT, briefGuard, buildBriefPrompt, outlineSchema } from './content-brief.js';+import {+ briefGuard,+ briefRulesOn,+ briefSchema,+ briefSystemPrompt,+ buildBriefPrompt,+} from './content-brief.js';import { NAME_PLACEHOLDER, QUOTE_PLACEHOLDER } from './content-people.js';import { qualityPhase } from './content-quality.js';import { NUMBER_PLACEHOLDER } from './content-sources.js';@@ -60,7 +66,7 @@ export const BRIEF_CRITERIA = [},{key: 'format',- ask: 'Does it say how each part is best shown (a table for a comparison, steps for a how-to, a question FAQ at the end), with short headings (H1 up to 60 characters, H2 about 8–15 words)?',+ ask: 'Does it say how each part is best shown (a table for a comparison, steps for a how-to, a question FAQ at the end), with short H2 headings (about 8–15 words)?',},{key: 'naturalLanguage',@@ -92,8 +98,9 @@ function urlKey(url) {/*** A brief's fields as the judge sees them and as a quote is read in: the- * goal, the audience, each heading and key point, the keywords as one line;- * each with whether it's a heading.+ * goal, the audience, each heading and key point, version 2's answer, format+ * and facts (with the kind of source each needs and the page to check it+ * against), the keywords as one line; each with whether it's a heading.*/function briefFields(brief) {return [@@ -102,6 +109,13 @@ function briefFields(brief) {...brief.outline.flatMap((s) => [{ label: 'H2: ', text: s.heading, heading: true },...s.keyPoints.map((point) => ({ label: '- ', text: point, heading: false })),+ { label: 'Answer: ', text: s.answer, heading: false },+ { label: 'Format: ', text: s.format, heading: false },+ ...(s.facts ?? []).map((f) => ({+ label: `Fact (${f.sourceType}${f.source ? `, check against ${f.source.label}` : ''}): `,+ text: f.claim,+ heading: false,+ })),]),{ label: 'Keywords: ', text: brief.keywords.join(', '), heading: false },].filter((f) => f.text);@@ -253,21 +267,32 @@ export function readJudged(answer, brief) {/*** The brief's prompt as recorded: a hash of its rules, its schema and the- * prompt each case gets, under Quality's phase (the site type line shows- * from phase 2). A record made under another one is stale.+ * prompt each case gets, under Quality's phase (the site type line shows from+ * phase 2) and with the brief rules (2026) on or off (CONTENT_BRIEF_RULES:+ * version 2's rules, schema and numbered data). A record made under another+ * one is stale.*/-export function promptVersion(cases, phase = qualityPhase()) {- const before = process.env.CONTENT_QUALITY_PHASE;+export function promptVersion(cases, { phase = qualityPhase(), rules = briefRulesOn() } = {}) {+ const before = {+ phase: process.env.CONTENT_QUALITY_PHASE,+ rules: process.env.CONTENT_BRIEF_RULES,+ };process.env.CONTENT_QUALITY_PHASE = String(phase);+ process.env.CONTENT_BRIEF_RULES = rules ? 'true' : 'false';try {const hash = createHash('sha256')- .update(SYSTEM_PROMPT)- .update(JSON.stringify(z.toJSONSchema(outlineSchema)));+ .update(briefSystemPrompt())+ .update(JSON.stringify(z.toJSONSchema(briefSchema())));for (const c of cases) hash.update(buildBriefPrompt(c));return hash.digest('hex').slice(0, 12);} finally {- if (before === undefined) delete process.env.CONTENT_QUALITY_PHASE;- else process.env.CONTENT_QUALITY_PHASE = before;+ for (const [key, name] of [+ ['phase', 'CONTENT_QUALITY_PHASE'],+ ['rules', 'CONTENT_BRIEF_RULES'],+ ]) {+ if (before[key] === undefined) delete process.env[name];+ else process.env[name] = before[key];+ }}}diff --git a/server/src/lib/content-brief-eval.test.js b/server/src/lib/content-brief-eval.test.jsindex 37a76b94f..13a3edde9 100644--- a/server/src/lib/content-brief-eval.test.js+++ b/server/src/lib/content-brief-eval.test.js@@ -152,6 +152,40 @@ describe('the checks anyone can repeat', () => {expect(briefChecks(brief, FIRST).invented.urls).toEqual(['www.made-up.example/x']);});+ it('read version 2’s answers and facts too: the judge sees them, the gate reads them', () => {+ const page = FIRST.sources.pages[0].url;+ const section = {+ ...GOOD.outline[0],+ answer: 'Say what a rolling forecast is, as https://made-up.example/answer does.',+ format: 'paragraphs',+ facts: [+ { claim: 'How often teams re-forecast', sourceType: 'study', source: 'S1' },+ { claim: 'What www.made-up.example/claim found', sourceType: 'statistic', source: null },+ ],+ };+ const brief = shapeBrief({ ...GOOD, outline: [section, ...GOOD.outline.slice(1)] }, FIRST);+ const prompt = buildJudgePrompt(FIRST, brief);+ expect(prompt).toContain('Answer: Say what a rolling forecast is');+ expect(prompt).toContain('Format: paragraphs');+ expect(prompt).toContain(`Fact (study, check against ${page}): How often teams re-forecast`);+ expect(prompt).toContain('Fact (statistic): What www.made-up.example/claim found');+ expect(briefChecks(brief, FIRST).invented.urls).toEqual([+ 'https://made-up.example/answer',+ 'www.made-up.example/claim',+ ]);+ // A figure the model wrote in a fact, before the guard.+ const raw = {+ ...brief,+ outline: [+ {+ ...brief.outline[0],+ facts: [{ claim: '73% re-forecast', sourceType: 'study', source: null }],+ },+ ],+ };+ expect(briefChecks(raw, FIRST).invented.figures).toEqual(['73']);+ });+it('take an address the case gave: a cited page, or the live page', () => {const live = CASES.find((c) => c.draft.method === 'optimize');const brief = shapeBrief(@@ -235,12 +269,19 @@ describe('a judge’s answer as kept', () => {expect(promptVersion(CASES)).toMatch(/^[0-9a-f]{12}$/);expect(promptVersion(CASES)).toBe(promptVersion(CASES));expect(promptVersion(CASES.slice(1))).not.toBe(promptVersion(CASES));- // From phase 2 the prompt names the site type.- expect(promptVersion(CASES, 2)).not.toBe(promptVersion(CASES, 0));- // The phase is read for it, and left as it was.- const before = process.env.CONTENT_QUALITY_PHASE;- promptVersion(CASES, 3);- expect(process.env.CONTENT_QUALITY_PHASE).toBe(before);+ // From phase 2 the prompt names the site type; the brief rules change it too.+ expect(promptVersion(CASES, { phase: 2 })).not.toBe(promptVersion(CASES, { phase: 0 }));+ expect(promptVersion(CASES, { rules: true })).not.toBe(promptVersion(CASES, { rules: false }));+ // Both are read for it, and left as they were.+ const before = [process.env.CONTENT_QUALITY_PHASE, process.env.CONTENT_BRIEF_RULES];+ promptVersion(CASES, { phase: 3, rules: true });+ expect([process.env.CONTENT_QUALITY_PHASE, process.env.CONTENT_BRIEF_RULES]).toEqual(before);+ });++ it('asks as version 1 always has with the brief rules off: the baseline’s hashes', () => {+ // Changed on purpose? Record the version 1 baseline again, then these.+ expect(promptVersion(CASES, { phase: 0, rules: false })).toBe('245d727b9091');+ expect(promptVersion(CASES, { phase: 2, rules: false })).toBe('bfa5ca4994bf');});});@@ -249,8 +290,11 @@ describe('a judge’s answer as kept', () => {// written under. Their checks are made again here, for free.const recordedPath = new URL('./__fixtures__/brief-eval/recorded.json', import.meta.url);const recorded = existsSync(recordedPath) ? JSON.parse(readFileSync(recordedPath, 'utf8')) : null;-const current =- recorded && recorded.promptVersion === promptVersion(CASES, recorded.qualityPhase ?? 0);+const recordedUnder = {+ phase: recorded?.qualityPhase ?? 0,+ rules: recorded?.briefRules ?? false,+};+const current = recorded && recorded.promptVersion === promptVersion(CASES, recordedUnder);describe('the recorded briefs', () => {it.skipIf(!current)(@@ -272,7 +316,7 @@ describe('the recorded briefs', () => {'waits for a new record: the brief’s prompt changed since',() => {// A stale record is said, not failed: the maintainer records again.- expect(recorded.promptVersion).not.toBe(promptVersion(CASES, recorded.qualityPhase ?? 0));+ expect(recorded.promptVersion).not.toBe(promptVersion(CASES, recordedUnder));},);});diff --git a/server/src/lib/content-brief.js b/server/src/lib/content-brief.jsindex ecb9f03ba..f352ce1f5 100644--- a/server/src/lib/content-brief.js+++ b/server/src/lib/content-brief.js@@ -2,7 +2,7 @@ import { NoObjectGeneratedError, generateObject } from 'ai';import { z } from 'zod';import supabaseAdmin from '../config/supabase.js';import { resolveModel } from './ai-provider.js';-import { siteTypeLine, pageTypeFormat } from './content-page-types.js';+import { PAGE_TYPE_SECTION_FORMATS, pageTypeFormat, siteTypeLine } from './content-page-types.js';import { getLanguageName } from './languages.js';import {RunStoppedError,@@ -15,7 +15,14 @@ import {} from './content-runs.js';import { citedPagesLength } from './content-cited-length.js';import { guardPeople, knownPeople, peopleEdits } from './content-people.js';-import { addedNumbers, knownNumbers, placeholderNumbers, todayText } from './content-sources.js';+import {+ addedNumbers,+ knownNumbers,+ numberSources,+ placeholderNumbers,+ stripSourceIds,+ todayText,+} from './content-sources.js';import { reserveAiBudget } from './plan-guard.js';/**@@ -80,6 +87,15 @@ export const rebuildSources = z.object({.transform((n) => Math.min(BRIEF_LENGTH_MAX, Math.max(BRIEF_LENGTH_MIN, n))),});+/**+ * The rules in effect, as Fix sends them to the agent (content-writer.js+ * writeDraftInput), beside the sources: with the brief rules (2026) on, the+ * brief plans to them. Cut to fit, as the sources are.+ */+export const briefRules = z+ .array(z.object({ key: cut(60), name: cut(200), detail: cut(500).default('') }))+ .max(60);+/*** The limits the web reads a brief with (web/src/lib/content/brief.ts* draftBriefSchema): the model's output is cut to them, so a brief saved and@@ -96,6 +112,25 @@ export const BRIEF_LIMITS = {keyword: 80,};+/**+ * The brief rules (2026) on (CONTENT_BRIEF_RULES=true): the brief plans each+ * section's answer, format and facts, as version 2 (web brief.ts). Off until+ * the brief eval (content-brief-eval.js) passes them: then the brief is+ * version 1, as before.+ */+export function briefRulesOn() {+ return process.env.CONTENT_BRIEF_RULES === 'true';+}++/**+ * Version 2's limits, as the web reads them (web/src/lib/content/brief.ts+ * BRIEF_V2_LIMITS, which content-brief.test.js reads to compare).+ */+export const BRIEF_V2_LIMITS = { answer: 600, facts: 4, claim: 300, url: 2048 };+/** How a section is best shown; the kind of source a fact needs (web brief.ts). */+export const BRIEF_FORMATS = ['paragraphs', 'list', 'steps', 'table', 'faq'];+export const FACT_SOURCES = ['statistic', 'study', 'quote', 'example', 'official'];+// No counts or lengths enforced on the model: a miss would fail the whole// call (charged all the same). They are asked for here and cut afterwards.export const outlineSchema = z.object({@@ -120,6 +155,50 @@ export const outlineSchema = z.object({keywords: z.array(z.string()).describe('Up to 10 keywords.'),});+/** Version 2's: each section with its answer, format and facts. */+export const outlineSchemaV2 = outlineSchema.extend({+ outline: z+ .array(+ outlineSchema.shape.outline.element.extend({+ answer: z+ .string()+ .nullable()+ .describe(+ "What the section's first sentences must answer directly, in one line: a note to the writer, not the answer.",+ ),+ // Keys from the list, in the JSON schema the model is held to: a+ // brief in Turkish or German would translate a free word ("tablo").+ // Read as any text, so a model that writes "Table" doesn't fail the+ // whole call (charged all the same): sectionPlan reads the key.+ format: z+ .string()+ .meta({ enum: BRIEF_FORMATS })+ .nullable()+ .describe('How the section is best shown.'),+ facts: z+ .array(+ z.object({+ claim: z+ .string()+ .describe('A fact the section should state, as what to find out: never a figure.'),+ sourceType: z+ .string()+ .meta({ enum: FACT_SOURCES })+ .describe('The kind of source it needs.'),+ source: z+ .string()+ .nullable()+ .describe(+ 'The number (S1…) of the cited page to check it against, or null to find one.',+ ),+ }),+ )+ .describe('Up to 2 facts.'),+ }),+ )+ .describe('3 to 10 sections.'),+});+export const SYSTEM_PROMPT = `You are a senior content strategist for Answer Engine Optimization (AEO). You plan one web page so AI assistants (ChatGPT, Perplexity, Gemini, Copilot, Google's AI Overviews) cite it.Rules:@@ -130,7 +209,28 @@ Rules:- Cited pages show what AI quotes today; plan to answer better than them, never to copy them.- Write every field in the language asked for.`;+/** Version 2's rules (the brief rules, 2026), after version 1's. */+export const SYSTEM_PROMPT_V2 = `${SYSTEM_PROMPT}+- Answer first: in "answer", say what each section's first sentences must answer directly, as a note to the writer, with no word count: the rules give the length.+- In "facts", name about one fact per section the page should state, with the kind of source it needs. In "source", give the number (S1…) of a cited page only when it is the one to check that fact against; you see only its address, never its words, so when unsure, null. Never write a figure of your own.+- The numbers (S1…) go in "source" only, never in another field.+- In "format", say how each section is best shown: a table for a comparison, numbered steps for a how-to, a list for picks or criteria, paragraphs for an explanation, faq for questions (its key points are the questions).+- "format" and "sourceType" are keys: write them as listed, in English, whatever the brief's language.+- Headings: each H2 about 8 to 15 words, under 90 characters.+- No keyword stuffing, and no wording made to trigger a citation: write for the reader.+- Follow the rules the page is written to, when listed.`;++/** The brief's rules and schema: version 2's with the brief rules on, else version 1's. */+export function briefSystemPrompt() {+ return briefRulesOn() ? SYSTEM_PROMPT_V2 : SYSTEM_PROMPT;+}+export function briefSchema() {+ return briefRulesOn() ? outlineSchemaV2 : outlineSchema;+}+const norm = (text) => text.trim().replace(/\s+/g, ' ').toLowerCase();+/** A fan-out as matched: without the quotes the prompt lists it in, as the model may copy them. */+const fanoutKey = (text) => norm(text.trim().replace(/^["“„«]\s*|\s*["”“»]$/g, ''));/*** Text cut to `max` characters, never inside a placeholder: one the cut would@@ -152,7 +252,7 @@ const QUOTED_QUESTION = /["“„«»]([^"“”„«»\n]{1,300}\?)["”“»«* brand, 422 with no sources to build from, PlanLimitError once the budget* is spent.*/-export async function rebuildDraftBrief({ draftId, brandId, sources }) {+export async function rebuildDraftBrief({ draftId, brandId, sources, rules = [] }) {const { data: draft, error: draftError } = await supabaseAdmin.from('content_drafts').select('id, brand_id, title, page_type, method, source_url')@@ -183,6 +283,8 @@ export async function rebuildDraftBrief({ draftId, brandId, sources }) {if (promptsRes.error) throw promptsRes.error;const brand = brandRes.data;const prompts = (promptsRes.data ?? []).map((p) => p.text);+ // The rules only with the brief rules on: the brief plans to them then, and may say their numbers.+ const planTo = briefRulesOn() ? rules : [];if (!prompts.length && !sources.fanouts.length && !sources.queries.length) {throw Object.assign(new Error('No prompts, fan-outs or queries to build from'), {@@ -201,7 +303,15 @@ export async function rebuildDraftBrief({ draftId, brandId, sources }) {},});try {- const brief = await briefWithRun({ draft, draftId, brand, prompts, sources, run });+ const brief = await briefWithRun({+ draft,+ draftId,+ brand,+ prompts,+ sources,+ rules: planTo,+ run,+ });await finishRun(run, 'done');return brief;} catch (err) {@@ -215,7 +325,7 @@ export async function rebuildDraftBrief({ draftId, brandId, sources }) {}/** The rebuild itself, step by step: nothing is saved once it is stopped. */-async function briefWithRun({ draft, draftId, brand, prompts, sources, run }) {+async function briefWithRun({ draft, draftId, brand, prompts, sources, rules, run }) {const modelId = contentBriefModelId();// Held on the budget before the call, so calls at once can't pass it.const budget = await reserveAiBudget(brand.organization_id, {@@ -237,9 +347,9 @@ async function briefWithRun({ draft, draftId, brand, prompts, sources, run }) {generated = await runCall(run, budget, CALL_TIMEOUT_MS, (abortSignal) =>generateObject({model: resolveModel(modelId),- schema: outlineSchema,- system: SYSTEM_PROMPT,- prompt: buildBriefPrompt({ brand, draft, prompts, sources }),+ schema: briefSchema(),+ system: briefSystemPrompt(),+ prompt: buildBriefPrompt({ brand, draft, prompts, sources, rules }),abortSignal,}),);@@ -258,7 +368,7 @@ async function briefWithRun({ draft, draftId, brand, prompts, sources, run }) {await advanceRun(run, 2);const brief = {- ...shapeBrief(object, { brand, draft, prompts, sources }),+ ...shapeBrief(object, { brand, draft, prompts, sources, rules }),origin: 'rebuild',builtAt: new Date().toISOString(),builtFrom: {@@ -286,30 +396,108 @@ async function briefWithRun({ draft, draftId, brand, prompts, sources, run }) {* The brief eval (content-brief-eval.js) reads the model's answers through* it too.*/-export function shapeBrief(object, { brand, draft, prompts, sources }) {- const guard = briefGuard({ brand, draft, prompts, sources });+export function shapeBrief(object, args) {+ return fitBrief(shapeWhole(object, args));+}++/**+ * Under content_drafts.brief's 64 KB (00212), with room for jsonb's spaces:+ * past it, the facts' sources go, then the facts (a fact's source is a whole+ * address, 2 KB at most), so a brief charged for is one that saves.+ */+const BRIEF_BYTES = 60_000;+function fitBrief(brief) {+ const size = (b) => Buffer.byteLength(JSON.stringify(b));+ if (brief.version !== 2 || size(brief) <= BRIEF_BYTES) return brief;+ const without = (strip) => ({+ ...brief,+ outline: brief.outline.map((section) => ({ ...section, facts: strip(section.facts ?? []) })),+ });+ const unsourced = without((facts) => facts.map((f) => ({ ...f, source: null })));+ return size(unsourced) <= BRIEF_BYTES ? unsourced : without(() => []);+}++function shapeWhole(object, { brand, draft, prompts, sources, rules }) {+ const guard = briefGuard({ brand, draft, prompts, sources, rules });+ // Version 2's (a model answer with them): each section's answer, format and facts.+ const v2 = object.outline.some((section) => 'answer' in section || 'facts' in section);+ const byId = v2 ? new Map(briefNumbered(sources).map((n) => [n.id, n])) : null;+ // Version 2's numbers (S1…) belong in a fact's source only: taken out of the words.+ const words = v2 ? (text) => stripSourceIds(text, byId.size) : (text) => text;return {- goal: clip(guard.text(object.goal), BRIEF_LIMITS.goal),- audience: clip(guard.text(object.audience), BRIEF_LIMITS.audience),+ goal: clip(guard.text(words(object.goal)), BRIEF_LIMITS.goal),+ audience: clip(guard.text(words(object.audience)), BRIEF_LIMITS.audience),outline: mapOutline(object.outline.map((section) => ({...section,- heading: guard.heading(section.heading),- keyPoints: (section.keyPoints ?? []).map((point) => guard.text(point)),+ heading: guard.heading(words(section.heading)),+ keyPoints: (section.keyPoints ?? []).map((point) => guard.text(words(point))),+ ...(v2 ? sectionPlan(section, guard, byId, words) : {}),})),sources.fanouts,),keywords: [...new Set(object.keywords+ .map((keyword) => words(keyword)).filter(guard.keeps).map((k) => k.trim().slice(0, BRIEF_LIMITS.keyword)).filter(Boolean),),].slice(0, BRIEF_LIMITS.keywords),+ ...(v2 ? { version: 2 } : {}),};}+/** A key the model was asked for, as the web lists it: trimmed, in small letters. */+const keyOf = (value) =>+ String(value ?? '')+ .trim()+ .toLowerCase();++/**+ * A section's plan of version 2, cut to the web's limits (BRIEF_V2_LIMITS)+ * and guarded as the rest: its answer, its format if one the web knows, its+ * facts (a kind of source the web knows; the cited page to check it against+ * by kind and ref, as a suggestion keeps its source, never its number in+ * this run: S1 is another page once the Sources tab changes).+ */+function sectionPlan(section, guard, byId, words) {+ const answer = clip(guard.text(words(section.answer ?? '')), BRIEF_V2_LIMITS.answer);+ const format = BRIEF_FORMATS.includes(keyOf(section.format)) ? keyOf(section.format) : null;+ const facts = (section.facts ?? [])+ .map((fact) => {+ const claim = clip(guard.text(words(fact?.claim ?? '')), BRIEF_V2_LIMITS.claim);+ const sourceType = keyOf(fact?.sourceType);+ if (!claim || !FACT_SOURCES.includes(sourceType)) return null;+ const given = byId.get(+ String(fact?.source ?? '')+ .trim()+ .toUpperCase(),+ );+ const label = given ? given.label.trim().slice(0, BRIEF_V2_LIMITS.claim) : '';+ return {+ claim,+ sourceType,+ source: label+ ? { kind: given.kind, ref: given.ref.slice(0, BRIEF_V2_LIMITS.url), label }+ : null,+ };+ })+ .filter(Boolean)+ .slice(0, BRIEF_V2_LIMITS.facts);+ return { answer: answer || null, format, facts };+}++/**+ * The cited pages, numbered as the writer numbers its data (S1…,+ * numberSources): version 2's facts name the one to check them against by+ * it. Only pages: a prompt, a fan-out or a query is a question, not a source.+ */+export function briefNumbered(sources) {+ return numberSources({ pages: sources.pages });+}+/*** What a brief may say without a placeholder: the numbers (CE-033), names* and quotes (CE-044) of what it was built from — the brand, the page, the@@ -321,8 +509,8 @@ export function shapeBrief(object, { brand, draft, prompts, sources }) {* one, as a placeholder can't be searched for; `found` lists what a text* adds, read the same way (the brief eval's gate).*/-export function briefGuard({ brand, draft, prompts, sources }) {- const { given, known, people } = briefKnown({ brand, draft, prompts, sources });+export function briefGuard({ brand, draft, prompts, sources, rules }) {+ const { given, known, people } = briefKnown({ brand, draft, prompts, sources, rules });// The names and quotes a text may have: a question in quotes in it too.const askedIn = (words) => {const questions = [...words.matchAll(QUOTED_QUESTION)].map((m) => m[1]);@@ -352,8 +540,9 @@ export function briefGuard({ brand, draft, prompts, sources }) {/*** What a brief is built from (`given`), and the numbers (`known`) and the* names and quotes (`people`) it may say: briefGuard's, and the brief eval's.+ * The rules it plans to are among them ("aim: 60 words").*/-export function briefKnown({ brand, draft, prompts, sources }) {+export function briefKnown({ brand, draft, prompts, sources, rules = [] }) {const given = [brand?.name,brand?.industry,@@ -364,6 +553,7 @@ export function briefKnown({ brand, draft, prompts, sources }) {...sources.queries,...sources.headings,String(sources.length),+ ...rules.flatMap((rule) => [rule.name, rule.detail]),];return { given, known: knownNumbers(...given, todayText()), people: knownPeople(...given) };}@@ -375,10 +565,14 @@ export function briefKnown({ brand, draft, prompts, sources }) {* left empty goes, long text is shortened, and the lists are capped.*/export function mapOutline(outline, fanouts) {- const byQuery = new Map(fanouts.map((f) => [norm(f.query), f]));+ // As listed first; then without its quotes, as the model may copy it.+ const asListed = new Map(fanouts.map((f) => [norm(f.query), f]));+ const unquoted = new Map(fanouts.map((f) => [fanoutKey(f.query), f]));return outline.map((section) => {- const fanout = section.fanout ? byQuery.get(norm(section.fanout)) : undefined;+ const fanout = section.fanout+ ? (asListed.get(norm(section.fanout)) ?? unquoted.get(fanoutKey(section.fanout)))+ : undefined;const platform =fanout && fanout.platforms.includes(section.platform)? section.platform@@ -391,6 +585,10 @@ export function mapOutline(outline, fanouts) {.slice(0, BRIEF_LIMITS.keyPoints),fanout: fanout?.query ?? null,platform: fanout ? platform : null,+ // Version 2's plan (shapeBrief), as shaped.+ ...('answer' in section+ ? { answer: section.answer, format: section.format, facts: section.facts }+ : {}),};}).filter((section) => section.heading)@@ -398,17 +596,27 @@ export function mapOutline(outline, fanouts) {}/** What the model is told: the brand, the page, and the sources kept. */-export function buildBriefPrompt({ brand, draft, prompts, sources }) {+export function buildBriefPrompt({ brand, draft, prompts, sources, rules = [] }) {const list = (items) => (items.length ? items.map((item) => `- ${item}`).join('\n') : '- none');+ const v2 = briefRulesOn();+ // With the brief rules on, each cited page by its number (S1…), for the facts' sources.+ const pages = v2+ ? briefNumbered(sources).map((n) => `${n.id}: ${n.label} (${n.detail})`)+ : sources.pages.map((p) => `${p.url} (${p.kind})`);+ const leans =+ v2 && Object.hasOwn(PAGE_TYPE_SECTION_FORMATS, draft.page_type ?? '')+ ? PAGE_TYPE_SECTION_FORMATS[draft.page_type]+ : null;+ const listed = v2 ? rules.filter((r) => r.name) : [];return `Brand: ${brand?.name || 'Unknown'}Industry: ${brand?.industry || 'Not specified'}${siteTypeLine(brand)}Description: ${brand?.description || 'N/A'}Page: ${draft.title || 'Untitled'}Page type: ${pageTypeFormat(draft.page_type)}-${draft.method === 'optimize' && draft.source_url ? `Existing page to improve: ${draft.source_url}` : 'A new page.'}+${leans ? `Its sections lean to: ${leans}.\n` : ''}${draft.method === 'optimize' && draft.source_url ? `Existing page to improve: ${draft.source_url}` : 'A new page.'}Length: about ${sources.length} characters.-+${listed.length ? `\nRules the page is written to:\n${list(listed.map((r) => (r.detail ? `${r.name}: ${r.detail}` : r.name)))}\n` : ''}Prompts the page must answer:${list(prompts)}@@ -419,7 +627,7 @@ Google searches people use (Search Console):${list(sources.queries)}Pages AI cites for these prompts today:-${list(sources.pages.map((p) => `${p.url} (${p.kind})`))}+${list(pages)}${sources.headings.length ? `The page's headings now:\n${list(sources.headings)}\n\n` : ''}Write the brief in ${getLanguageName(brand?.language)}.`;}diff --git a/server/src/lib/content-brief.test.js b/server/src/lib/content-brief.test.jsindex 73a5ab15c..f0010042a 100644--- a/server/src/lib/content-brief.test.js+++ b/server/src/lib/content-brief.test.js@@ -1,4 +1,6 @@+import { existsSync, readFileSync } from 'node:fs';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { z } from 'zod';/*** Rebuild outline (Content Editor CE-007): the brief written from the@@ -62,8 +64,22 @@ vi.mock('./content-runs.js', async (importOriginal) => ({stopIfStopped: (...args) => stopIfStopped(...args),}));-const { briefGuard, buildBriefPrompt, mapOutline, rebuildDraftBrief, rebuildSources } =- await import('./content-brief.js');+const {+ BRIEF_FORMATS,+ BRIEF_V2_LIMITS,+ FACT_SOURCES,+ SYSTEM_PROMPT,+ SYSTEM_PROMPT_V2,+ briefGuard,+ buildBriefPrompt,+ mapOutline,+ outlineSchema,+ outlineSchemaV2,+ briefNumbered,+ briefRules,+ rebuildDraftBrief,+ rebuildSources,+} = await import('./content-brief.js');const { NAME_PLACEHOLDER, QUOTE_PLACEHOLDER } = await import('./content-people.js');const { NUMBER_PLACEHOLDER } = await import('./content-sources.js');const { PlanLimitError } = await import('./plan-guard.js');@@ -83,6 +99,9 @@ const sources = (over = {}) => ({...over,});+/** The rules in effect, as Fix sends them. */+const RULES = [{ key: 'h2Answer', name: 'Answer under each H2', detail: 'aim: 60 words' }];+const outline = [{heading: 'The best espresso machines under $500',@@ -414,6 +433,21 @@ describe('rebuildSources', () => {});});+describe('briefRules', () => {+ it('reads the rules as Fix sends them, cut to fit, a rule without a detail too', () => {+ expect(+ briefRules.parse([+ { key: 'faq', name: 'FAQ' },+ { key: 'h2Answer', name: 'n'.repeat(250), detail: 'd'.repeat(600) },+ ]),+ ).toEqual([+ { key: 'faq', name: 'FAQ', detail: '' },+ { key: 'h2Answer', name: 'n'.repeat(200), detail: 'd'.repeat(500) },+ ]);+ expect(briefRules.safeParse(Array(61).fill({ key: 'faq', name: 'FAQ' })).success).toBe(false);+ });+});+describe('the brief guard', () => {const guardFor = (over = {}) =>briefGuard({@@ -531,6 +565,21 @@ describe('the brief prompt', () => {expect(read('1')).toContain('Industry: Fashion & Apparel\nDescription:');});+ it('matches a fan-out copied in its quotes, one written as listed first', () => {+ const fanouts = [+ { query: 'best crm', platforms: ['chatgpt'] },+ { query: '"best crm"', platforms: ['copilot-web'] },+ { query: 'crm for startups', platforms: ['perplexity-web'] },+ ];+ const section = (fanout) => ({ heading: 'H', keyPoints: [], fanout, platform: null });+ expect(+ mapOutline(+ [section('"best crm"'), section('best crm'), section('“crm for startups”')],+ fanouts,+ ).map((s) => s.fanout),+ ).toEqual(['"best crm"', 'best crm', 'crm for startups']);+ });+it('maps an outline with no fan-outs kept to none', () => {expect(mapOutline(outline.slice(0, 1), [])).toEqual([{@@ -542,3 +591,314 @@ describe('the brief prompt', () => {]);});});++describe('the brief rules (2026), behind CONTENT_BRIEF_RULES', () => {+ afterEach(() => {+ delete process.env.CONTENT_BRIEF_RULES;+ });++ it('asks as before while they are off: the same rules, schema and prompt', async () => {+ await rebuildDraftBrief({ draftId: DRAFT, brandId: BRAND, sources: sources(), rules: RULES });+ const call = generateObject.mock.calls[0][0];+ expect(call.system).toBe(SYSTEM_PROMPT);+ expect(call.schema).toBe(outlineSchema);+ expect(call.prompt).not.toMatch(/\bS\d+: /);+ expect(call.prompt).not.toContain('Its sections lean to');+ expect(call.prompt).not.toContain('Rules the page is written to');+ const brief = writes.find((w) => w.table === 'content_drafts')?.value.brief;+ expect(brief).not.toHaveProperty('version');+ expect(brief.outline[0]).not.toHaveProperty('answer');+ });++ it('asks for each section’s answer, format and facts, with the cited pages numbered and the rules', async () => {+ process.env.CONTENT_BRIEF_RULES = 'true';+ generateObject.mockResolvedValue({+ object: { goal: 'g', audience: 'a', outline: [], keywords: [] },+ usage: { inputTokens: 10, outputTokens: 5 },+ });+ await rebuildDraftBrief({ draftId: DRAFT, brandId: BRAND, sources: sources(), rules: RULES });+ const call = generateObject.mock.calls[0][0];+ expect(call.system).toBe(SYSTEM_PROMPT_V2);+ expect(call.schema).toBe(outlineSchemaV2);+ // The cited pages by number; a prompt, a fan-out or a query is a question, not a source.+ expect(call.prompt).toContain('- S1: https://www.reddit.com/r/espresso/x (forum)');+ expect(call.prompt).toContain('- Best espresso machines under $500?');+ expect(call.prompt).toContain('- "Best espresso machine under 500"');+ expect(call.prompt).not.toContain('S2');+ expect(call.prompt).toContain(+ 'Its sections lean to: a list of the criteria, and a table of the picks.',+ );+ expect(call.prompt).toContain(+ 'Rules the page is written to:\n- Answer under each H2: aim: 60 words',+ );+ });++ it('keeps each section’s plan, cut and guarded as the rest, its facts’ sources by kind and ref', async () => {+ process.env.CONTENT_BRIEF_RULES = 'true';+ const fact = (over) => ({+ claim: 'Average price of a machine',+ sourceType: 'statistic',+ source: 'S1',+ ...over,+ });+ generateObject.mockResolvedValue({+ object: {+ goal: 'Help buyers pick',+ audience: 'Home baristas',+ outline: [+ {+ heading: 'The best espresso machines under $500',+ keyPoints: ['Price bands'],+ // Copied with the quotes it was listed in.+ fanout: '“Best espresso machine under 500”',+ platform: 'copilot-web',+ answer: 'Say that 73% of buyers pick a single boiler (S1), in 60 words.',+ format: 'carousel',+ facts: [+ fact(),+ fact({ sourceType: 'rumour' }),+ fact({ claim: '41% of baristas say so [S1]', sourceType: 'Study', source: 'S99' }),+ fact({ source: 's1' }),+ // S2 isn't a page: a fan-out is a question, not a source.+ fact({ source: 'S2' }),+ fact({ claim: ' ' }),+ fact(),+ ],+ },+ {+ heading: 'Grinders (S1)',+ // Only the numbers given go: a name with one stays.+ keyPoints: ['Burr vs blade [S1]', 'Model (S23) grinders'],+ fanout: null,+ platform: null,+ answer: null,+ format: ' Table ',+ facts: [],+ },+ ],+ keywords: ['espresso'],+ },+ usage: { inputTokens: 1000, outputTokens: 500 },+ });+ const brief = await rebuildDraftBrief({+ draftId: DRAFT,+ brandId: BRAND,+ sources: sources(),+ rules: RULES,+ });+ expect(brief.version).toBe(2);+ const [section, second] = brief.outline;+ expect(section.fanout).toBe('Best espresso machine under 500');+ // Its numbers out of the words; the rule's number kept, one of its own a placeholder.+ expect(section.answer).toBe(+ 'Say that [figure, source] of buyers pick a single boiler, in 60 words.',+ );+ // A format the web doesn't know: none; one it knows, as it lists it.+ expect(section.format).toBeNull();+ expect(second).toMatchObject({+ heading: 'Grinders',+ keyPoints: ['Burr vs blade', 'Model (S23) grinders'],+ format: 'table',+ });+ const page = {+ kind: 'cited_page',+ ref: 'https://www.reddit.com/r/espresso/x',+ label: 'https://www.reddit.com/r/espresso/x',+ };+ expect(section.facts).toEqual([+ { claim: 'Average price of a machine', sourceType: 'statistic', source: page },+ // A number the data doesn't have, a source it doesn't list.+ { claim: '[figure, source] of baristas say so', sourceType: 'study', source: null },+ { claim: 'Average price of a machine', sourceType: 'statistic', source: page },+ { claim: 'Average price of a machine', sourceType: 'statistic', source: null },+ ]);+ expect(section.facts.length).toBeLessThanOrEqual(BRIEF_V2_LIMITS.facts);+ });++ it('holds the model to the format and source keys, without failing a call on one off the list', () => {+ // The JSON schema the model is given, as the AI SDK writes it.+ const json = z.toJSONSchema(outlineSchemaV2, { target: 'draft-7', io: 'input' });+ const section = json.properties.outline.items.properties;+ expect(section.format.anyOf).toEqual([+ { type: 'string', enum: BRIEF_FORMATS },+ { type: 'null' },+ ]);+ expect(section.facts.items.properties.sourceType.enum).toEqual(FACT_SOURCES);+ expect(SYSTEM_PROMPT_V2).toContain('write them as listed, in English');+ // A model that writes "Table" or a translated key still answers: read by key afterwards.+ const read = outlineSchemaV2.safeParse({+ goal: 'g',+ audience: 'a',+ outline: [+ {+ heading: 'h',+ keyPoints: [],+ fanout: null,+ platform: null,+ answer: null,+ format: 'Tablo',+ facts: [{ claim: 'c', sourceType: 'Statistic', source: null }],+ },+ ],+ keywords: [],+ });+ expect(read.success).toBe(true);+ });++ it('leaves version 1’s words as they were: numbers aren’t taken out, the rules aren’t known', async () => {+ generateObject.mockResolvedValue({+ object: {+ goal: 'g',+ audience: 'a',+ outline: [+ {+ heading: 'Machines',+ keyPoints: ['Price bands (S1)', 'Answer in 60 words'],+ fanout: null,+ platform: null,+ },+ ],+ keywords: [],+ },+ usage: { inputTokens: 10, outputTokens: 5 },+ });+ const brief = await rebuildDraftBrief({+ draftId: DRAFT,+ brandId: BRAND,+ sources: sources(),+ rules: RULES,+ });+ expect(brief.outline[0].keyPoints).toEqual([+ 'Price bands (S1)',+ `Answer in ${NUMBER_PLACEHOLDER} words`,+ ]);+ });++ it('fits the brief under the column’s 64 KB: sources go first, then facts', async () => {+ process.env.CONTENT_BRIEF_RULES = 'true';+ const long = 'https://www.reddit.com/r/espresso/' + 'x'.repeat(2000);+ const section = (i) => ({+ heading: `Machines ${String.fromCharCode(97 + i)}`,+ keyPoints: [],+ fanout: null,+ platform: null,+ answer: null,+ format: null,+ facts: Array(4).fill({ claim: 'c'.repeat(300), sourceType: 'study', source: 'S1' }),+ });+ generateObject.mockResolvedValue({+ object: {+ goal: 'g',+ audience: 'a',+ outline: Array.from({ length: 12 }, (_, i) => section(i)),+ keywords: [],+ },+ usage: { inputTokens: 10, outputTokens: 5 },+ });+ const brief = await rebuildDraftBrief({+ draftId: DRAFT,+ brandId: BRAND,+ sources: sources({ pages: [{ url: long, kind: 'forum' }] }),+ });+ expect(Buffer.byteLength(JSON.stringify(brief))).toBeLessThan(64_000);+ expect(brief.outline[0].facts).toHaveLength(4);+ expect(brief.outline.every((s) => s.facts.every((f) => f.source === null))).toBe(true);+ });++ it('lets the facts go too when the brief is still too big without their sources', async () => {+ process.env.CONTENT_BRIEF_RULES = 'true';+ // Three bytes a character: the answers fit, the facts don't beside them.+ const section = (i) => ({+ heading: `Machines ${String.fromCharCode(97 + i)}`,+ keyPoints: [],+ fanout: null,+ platform: null,+ answer: '中'.repeat(600),+ format: null,+ facts: Array(4).fill({ claim: '中'.repeat(300), sourceType: 'study', source: null }),+ });+ generateObject.mockResolvedValue({+ object: {+ goal: 'g',+ audience: 'a',+ outline: Array.from({ length: 12 }, (_, i) => section(i)),+ keywords: [],+ },+ usage: { inputTokens: 10, outputTokens: 5 },+ });+ const brief = await rebuildDraftBrief({ draftId: DRAFT, brandId: BRAND, sources: sources() });+ expect(Buffer.byteLength(JSON.stringify(brief))).toBeLessThan(64_000);+ expect(brief.outline).toHaveLength(12);+ expect(brief.outline.every((s) => s.facts.length === 0)).toBe(true);+ expect(brief.outline[0].answer).toHaveLength(BRIEF_V2_LIMITS.answer);+ });++ it('cuts a long answer and claim to the web’s limits, never splitting a placeholder', async () => {+ process.env.CONTENT_BRIEF_RULES = 'true';+ generateObject.mockResolvedValue({+ object: {+ goal: 'g',+ audience: 'a',+ outline: [+ {+ heading: 'Machines',+ keyPoints: [],+ fanout: null,+ platform: null,+ answer: 'a'.repeat(700),+ format: 'table',+ facts: [{ claim: 'c'.repeat(400), sourceType: 'study', source: null }],+ },+ ],+ keywords: [],+ },+ usage: { inputTokens: 10, outputTokens: 5 },+ });+ const brief = await rebuildDraftBrief({ draftId: DRAFT, brandId: BRAND, sources: sources() });+ expect(brief.outline[0].answer).toHaveLength(BRIEF_V2_LIMITS.answer);+ expect(brief.outline[0].format).toBe('table');+ expect(brief.outline[0].facts[0].claim).toHaveLength(BRIEF_V2_LIMITS.claim);+ });++ // The web's reading of version 2 (web/src/lib/content/brief.ts, #1539): read+ // here so the two can't drift apart unseen; skipped until the web has it.+ const webBrief = new URL('../../../web/src/lib/content/brief.ts', import.meta.url);+ const webText = existsSync(webBrief) ? readFileSync(webBrief, 'utf8') : '';+ const webHasV2 = webText.includes('BRIEF_V2_LIMITS');+ it.skipIf(!webHasV2)('writes version 2 to the web’s limits, kinds and sample', () => {+ const limits = webText.match(/export const BRIEF_V2_LIMITS = \{([\s\S]*?)\} as const/)[1];+ const limit = (key) => Number(limits.match(new RegExp(`\\b${key}: (\\d+)`))[1]);+ for (const key of ['answer', 'facts', 'claim', 'url']) {+ expect(BRIEF_V2_LIMITS[key], key).toBe(limit(key));+ }+ const kinds = (name) =>+ [+ ...webText+ .match(new RegExp(`export const ${name} = \\[([^\\]]*)\\]`))[1]+ .matchAll(/'([a-z_]+)'/g),+ ].map((m) => m[1]);+ expect(BRIEF_FORMATS).toEqual(kinds('BRIEF_FORMATS'));+ expect(FACT_SOURCES).toEqual(kinds('FACT_SOURCES'));+ const sample = JSON.parse(+ readFileSync(+ new URL('../../../web/src/lib/content/__fixtures__/brief-v2.json', import.meta.url),+ 'utf8',+ ),+ );+ for (const section of sample.outline) {+ expect(BRIEF_FORMATS).toContain(section.format);+ for (const f of section.facts) expect(FACT_SOURCES).toContain(f.sourceType);+ }+ // A fact's source is a kind the web keeps (sources.ts DRAFT_SOURCE_KINDS).+ const webSources = readFileSync(+ new URL('../../../web/src/lib/content/sources.ts', import.meta.url),+ 'utf8',+ );+ const draftKinds = [+ ...webSources+ .match(/export const DRAFT_SOURCE_KINDS = \[([^\]]*)\]/)[1]+ .matchAll(/'([a-z_]+)'/g),+ ].map((m) => m[1]);+ for (const n of briefNumbered(sources())) expect(draftKinds).toContain(n.kind);+ });+});diff --git a/server/src/lib/content-page-types.js b/server/src/lib/content-page-types.jsindex 6ab476083..e680e51ce 100644--- a/server/src/lib/content-page-types.js+++ b/server/src/lib/content-page-types.js@@ -38,6 +38,28 @@ export function pageTypeFormat(pageType) {return Object.hasOwn(PAGE_TYPE_FORMATS, pageType) ? PAGE_TYPE_FORMATS[pageType] : pageType;}+/**+ * What a page type's sections lean to (the brief rules, 2026: format hints),+ * for the brief's v2 prompt (content-brief.js, CONTENT_BRIEF_RULES). A type+ * not here leans to paragraphs.+ */+export const PAGE_TYPE_SECTION_FORMATS = {+ comparison: 'a table comparing the options, with a verdict',+ alternatives: 'a table comparing the options',+ pricing: 'a table of the plans',+ guide: 'numbered steps',+ itinerary: 'a day-by-day list',+ best_of: 'a ranked list, with the reason for each',+ buying_guide: 'a list of the criteria, and a table of the picks',+ sizing_guide: 'a size chart table',+ docs_faq: 'questions answered directly, as an FAQ',+ help_faq: 'questions answered directly, as an FAQ',+ product_page: 'a specs table',+ category_page: 'a list of the range',+ collection_page: 'a list of the picks',+ definition: 'the term defined in its first sentence, then paragraphs',+};+/** Kinds of site (brands.site_type, 00205), as web/src/lib/content/page-types.ts has them. */export const SITE_TYPES = ['b2b', 'ecommerce', 'b2c'];diff --git a/server/src/lib/content-sources.js b/server/src/lib/content-sources.jsindex 9dbf57b72..aed7938a6 100644--- a/server/src/lib/content-sources.js+++ b/server/src/lib/content-sources.js@@ -103,9 +103,15 @@ export function sourcesPrompt(numbered) {/** A source number written into the words in brackets ("(S2)", "[S1, S3]"): never the page's. */const SOURCE_ID = /\s?[([]S\d{1,3}(?:\s*[,;]\s*S\d{1,3})*[)\]]/g;-/** Words with the source numbers the model wrote into them taken out. */-export function stripSourceIds(text) {- return String(text ?? '').replace(SOURCE_ID, '');+/**+ * Words with the source numbers the model wrote into them taken out: with+ * `count`, only S1 to S{count}, the numbers it was given, so a name with one+ * ("Galaxy (S23)") stays.+ */+export function stripSourceIds(text, count = Infinity) {+ return String(text ?? '').replace(SOURCE_ID, (ids) =>+ ids.match(/\d+/g).every((n) => Number(n) <= count) ? '' : ids,+ );}/**diff --git a/server/src/lib/content-sources.test.js b/server/src/lib/content-sources.test.jsindex 9a5d8ef9d..f2fb3b6ff 100644--- a/server/src/lib/content-sources.test.js+++ b/server/src/lib/content-sources.test.js@@ -238,6 +238,10 @@ describe('no number without a source', () => {expect(stripSourceIds('Trackers (S2) cover AI [S1, S3]. Amazon S3 stays.')).toBe('Trackers cover AI. Amazon S3 stays.',);+ // Only the numbers given: a name with one stays.+ expect(stripSourceIds('Grinders (S1) for the Galaxy (S23) [S1, S9]', 2)).toBe(+ 'Grinders for the Galaxy (S23) [S1, S9]',+ );});it('reads no figure in words with digits, and matches a claim to its unit', () => {diff --git a/server/src/routes/content-drafts.js b/server/src/routes/content-drafts.jsindex 5b995d614..7a25f1599 100644--- a/server/src/routes/content-drafts.js+++ b/server/src/routes/content-drafts.js@@ -4,7 +4,7 @@ import { assertBrandAccess } from '../lib/access.js';import { fixDraftRules, fixRulesInput } from '../lib/content-agent.js';import { handOffDraft, handOffInput } from '../lib/content-handoff.js';import { qualityPhase } from '../lib/content-quality.js';-import { rebuildDraftBrief, rebuildSources } from '../lib/content-brief.js';+import { briefRules, rebuildDraftBrief, rebuildSources } from '../lib/content-brief.js';import { DeliveryError, sendContentPages, sendInput } from '../lib/content-delivery.js';import { checkWebflowPublished } from '../lib/cms/webflow-status.js';import { liveAddress, publishDraft } from '../lib/content-published.js';@@ -170,11 +170,13 @@ const rebuildBody = z.object({// guid, not uuid: brand ids aren't all RFC 4122 versions (seeded ones).brandId: z.guid(),sources: rebuildSources,+ /** The rules in effect, as Fix sends them: read with the brief rules (2026) on. */+ rules: briefRules.optional(),});/*** POST /api/content-drafts/:draftId/brief- * Body: { brandId, sources: { promptIds, fanouts, pages, queries, headings, length } }+ * Body: { brandId, sources: { promptIds, fanouts, pages, queries, headings, length }, rules? }*/router.post('/:draftId/brief', async (req, res) => {const draftId = z.guid().safeParse(req.params.draftId);@@ -182,10 +184,10 @@ router.post('/:draftId/brief', async (req, res) => {if (!draftId.success || !parsed.success) {return res.status(400).json({ error: 'Invalid request', code: 'invalid' });}- const { brandId, sources } = parsed.data;+ const { brandId, sources, rules } = parsed.data;try {await assertBrandAccess(brandId, req.user.id);- const brief = await rebuildDraftBrief({ draftId: draftId.data, brandId, sources });+ const brief = await rebuildDraftBrief({ draftId: draftId.data, brandId, sources, rules });return res.json({ brief });} catch (err) {if (err instanceof PlanLimitError) {diff --git a/server/src/routes/content-drafts.test.js b/server/src/routes/content-drafts.test.jsindex 63f11aa6f..5faba020b 100644--- a/server/src/routes/content-drafts.test.js+++ b/server/src/routes/content-drafts.test.js@@ -114,11 +114,30 @@ describe('POST /api/content-drafts/:draftId/brief', () => {expect(rebuildDraftBrief).toHaveBeenCalledWith({ draftId: DRAFT, brandId: BRAND, sources });});+ it('passes the rules in effect on, cut to fit', async () => {+ const rules = [+ { key: 'faq', name: 'F'.repeat(250), detail: 'aim: 5 questions' },+ { key: 'h1', name: 'H1' },+ ];+ const res = await rebuild({ brandId: BRAND, sources, rules });+ expect(res.status).toBe(200);+ expect(rebuildDraftBrief).toHaveBeenCalledWith({+ draftId: DRAFT,+ brandId: BRAND,+ sources,+ rules: [+ { ...rules[0], name: 'F'.repeat(200) },+ { ...rules[1], detail: '' },+ ],+ });+ });+it('refuses a malformed draft, brand or source list', async () => {for (const [body, draftId] of [[{ brandId: BRAND, sources }, 'd1'],[{ brandId: 'b1', sources }, DRAFT],[{ brandId: BRAND, sources: { ...sources, promptIds: ['p1'] } }, DRAFT],+ [{ brandId: BRAND, sources, rules: Array(61).fill({ key: 'faq', name: 'FAQ' }) }, DRAFT],]) {const res = await rebuild(body, draftId);expect(res.status).toBe(400);diff --git a/server/src/scripts/eval-brief.js b/server/src/scripts/eval-brief.jsindex 1748d1692..d6fe2f5d7 100644--- a/server/src/scripts/eval-brief.js+++ b/server/src/scripts/eval-brief.js@@ -20,9 +20,9 @@* prints a key, and isn't run in CI:* the answers it keeps are the models' of the day, for a person to record* again when the brief's prompt or the models change (the test skips a- * record made under another prompt or Quality phase: run it with the phase- * the API runs with, CONTENT_QUALITY_PHASE). Under a dollar at today's- * prices.+ * record made under another prompt, Quality phase or brief rules: run it+ * with the CONTENT_QUALITY_PHASE the API runs with, and CONTENT_BRIEF_RULES=+ * true to record version 2's briefs). Under a dollar at today's prices.*/import 'dotenv/config';import { writeFileSync } from 'fs';@@ -30,10 +30,11 @@ import { generateObject } from 'ai';import { CASES } from '../lib/__fixtures__/brief-eval/cases.js';import { resolveModel } from '../lib/ai-provider.js';import {- SYSTEM_PROMPT,+ briefRulesOn,+ briefSchema,+ briefSystemPrompt,buildBriefPrompt,contentBriefModelId,- outlineSchema,shapeBrief,} from '../lib/content-brief.js';import { qualityPhase } from '../lib/content-quality.js';@@ -69,8 +70,8 @@ for (const c of CASES.slice(0, count)) {try {const written = await generateObject({model,- schema: outlineSchema,- system: SYSTEM_PROMPT,+ schema: briefSchema(),+ system: briefSystemPrompt(),prompt: buildBriefPrompt(c),abortSignal: AbortSignal.timeout(CALL_TIMEOUT_MS),});@@ -116,6 +117,7 @@ writeFileSync(model: modelId,judgeModel: judgeModelId,qualityPhase: qualityPhase(),+ briefRules: briefRulesOn(),promptVersion: promptVersion(CASES),recordedAt: new Date().toISOString(),cases: recorded,