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): name the brand, its products and competitors as written, and plan links to the pages listed only, in the brief behind CONTENT_BRIEF_RULES (brief rules PR 6) (#1545)
Cihandfa51a0f3552
diff --git a/server/src/lib/__fixtures__/brief-eval/cases.js b/server/src/lib/__fixtures__/brief-eval/cases.jsindex 81b376860..e3974f996 100644--- a/server/src/lib/__fixtures__/brief-eval/cases.js+++ b/server/src/lib/__fixtures__/brief-eval/cases.js@@ -4,8 +4,9 @@* types each site type has, new pages and live ones. Each is what Rebuild* outline is given: the brand, the draft, the prompts and the Sources tab's* fan-outs, Search Console queries, cited pages, the live page's headings- * and the length its rules ask for. Made-up brands and pages only: no- * customer's.+ * and the length its rules ask for; a few, with the brief rules (2026),+ * the brand's competitors and the pages it may link to. Made-up brands and+ * pages only: no customer's.** `node src/scripts/eval-brief.js` writes each one's brief and the judge's* scores beside them (recorded.json).@@ -90,6 +91,11 @@ function kase(siteType, language, pageType, page) {headings: page.headings ?? [],length: LENGTHS[page.length ?? 'medium'],},+ competitors: page.competitors ?? [],+ targets: {+ own: (page.own ?? []).map(([url, title]) => ({ url, title })),+ sources: (page.cited ?? []).map(([url]) => ({ url, title: '' })),+ },};}@@ -120,6 +126,11 @@ export const CASES = [],queries: ['cash forecasting excel vs software'],cited: [['https://www.g2.com/categories/cash-flow-management', 'review']],+ competitors: ['Cashwise', 'Forecastly'],+ own: [+ ['https://ledgerly.example/features/rolling-forecasts', 'Rolling cash forecasts'],+ ['https://ledgerly.example/pricing', 'Ledgerly pricing'],+ ],}),kase('b2b', 'en', 'guide', {title: 'How to reconcile a cash forecast with the bank',@@ -264,6 +275,11 @@ export const CASES = [],queries: ['small group hiking tours europe'],cited: [['https://www.example-travel-mag.com/best-hiking-tours', 'blog']],+ competitors: ['Summit Circle', 'Wanderwise'],+ own: [+ ['https://trailhead.example/trips/dolomites', 'Dolomites Hut Trek'],+ ['https://trailhead.example/trips/picos', 'Picos de Europa Traverse'],+ ],}),// B2C, Turkish.kase('b2c', 'tr', 'guide', {@@ -355,6 +371,11 @@ export const CASES = [queries: ['how to choose a city bike'],cited: [['https://www.reddit.com/r/bikecommuting/comments/def', 'forum']],length: 'long',+ competitors: ['Urban Pedal Co'],+ own: [+ ['https://velo.example/bikes/city-eight', 'City Eight'],+ ['https://velo.example/size-guide', 'Bike size guide'],+ ],}),kase('ecommerce', 'en', 'sizing_guide', {title: 'Bike size guide',diff --git a/server/src/lib/content-brief-eval.js b/server/src/lib/content-brief-eval.jsindex d19f851fa..3b388b718 100644--- a/server/src/lib/content-brief-eval.js+++ b/server/src/lib/content-brief-eval.js@@ -101,8 +101,8 @@ function urlKey(url) {* goal, the audience, version 2's essentials, angle and proof to gather,* each heading and key point, a section's answer, format and facts (with the* kind of source each needs and the source to check it against), the- * keywords as one line, the fan-outs left out and the freshness; each with- * whether it's a heading.+ * keywords as one line, the fan-outs left out, the freshness, the names as+ * written and the links planned; each with whether it's a heading.*/function briefFields(brief) {const fresh = brief.freshness;@@ -144,6 +144,24 @@ function briefFields(brief) {.join('; '),heading: false,},+ {+ label: 'Names as written: ',+ text: [+ brief.entities?.brand,+ ...(brief.entities?.products ?? []),+ ...(brief.entities?.competitors ?? []),+ ]+ .filter(Boolean)+ .join(', '),+ heading: false,+ },+ ...['internal', 'outbound'].flatMap((kind) =>+ (brief.links?.[kind] ?? []).map((link) => ({+ label: `Link (${kind}${link.section ? `, in "${link.section}"` : ''}): `,+ text: `${link.anchor} → ${link.url}`,+ heading: false,+ })),+ ),].filter((f) => f.text);}@@ -172,8 +190,16 @@ export function briefChecks(brief, c) {const guard = briefGuard(c);// Each field read as the guard reads it: a heading as one, a question in quotes kept.const found = briefFields(brief).map((f) => guard.found(f.text, f.heading));+ // The addresses it was given: the cited pages, the live page, the pages it may link to.const given = new Set(- [...c.sources.pages.map((p) => p.url), c.draft.source_url].filter(Boolean).map(urlKey),+ [+ ...c.sources.pages.map((p) => p.url),+ c.draft.source_url,+ ...(c.targets?.own ?? []).map((p) => p.url),+ ...(c.targets?.sources ?? []).map((p) => p.url),+ ]+ .filter(Boolean)+ .map(urlKey),);const answered = new Set(brief.outline.map((s) => s.fanout).filter(Boolean));const leftOut = new Set(brief.leftOut ?? []);@@ -237,7 +263,7 @@ ${list(c.prompts)}AI searches (fan-outs) it was given:${list(c.sources.fanouts.map((f) => f.query))}-+${c.competitors?.length ? `\nCompetitors it was given: ${c.competitors.join(', ')}\n` : ''}${c.targets?.own?.length ? `\nThe brand's pages it may link to:\n${list(c.targets.own.map((p) => `${p.title} — ${p.url}`))}\n` : ''}The brief:${briefFields(brief).map((f) => `${f.label}${f.text}`)diff --git a/server/src/lib/content-brief-eval.test.js b/server/src/lib/content-brief-eval.test.jsindex 05b3e5e41..76bf3fb0f 100644--- a/server/src/lib/content-brief-eval.test.js+++ b/server/src/lib/content-brief-eval.test.js@@ -203,6 +203,7 @@ describe('the checks anyone can repeat', () => {expect(prompt).toContain('Angle: Ledgerly’s own variance data across customers');expect(prompt).toContain('Proof to gather (data): Average error before and after switching');expect(prompt).toContain('Freshness: date The error figure, with its month');+ expect(prompt).toContain('Names as written: Ledgerly');expect(briefChecks(brief, FIRST).invented.urls).toEqual(['www.made-up.example/tldr']);});@@ -220,6 +221,21 @@ describe('the checks anyone can repeat', () => {expect(left).toMatchObject({ fanoutCoverage: 1, leftOut: 1 });});+ it('take the pages a case may link to as given, and tell the judge its competitors', () => {+ const c = CASES.find((k) => k.competitors.length && k.targets.own.length);+ const brief = {+ ...shapeBrief(GOOD, c),+ links: {+ internal: [{ url: c.targets.own[0].url, anchor: 'see the page', section: null }],+ outbound: [],+ },+ };+ expect(briefChecks(brief, c).invented.urls).toEqual([]);+ const prompt = buildJudgePrompt(c, brief);+ expect(prompt).toContain(`Competitors it was given: ${c.competitors.join(', ')}`);+ expect(prompt).toContain(`Link (internal): see the page → ${c.targets.own[0].url}`);+ });+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(diff --git a/server/src/lib/content-brief.js b/server/src/lib/content-brief.jsindex d037017f3..ee5738b68 100644--- a/server/src/lib/content-brief.js+++ b/server/src/lib/content-brief.js@@ -9,6 +9,8 @@ import {siteTypeLine,} from './content-page-types.js';import { inputSources, readDraftInputs } from './content-inputs.js';+import { NO_LINK_TARGETS, linkKey, readLinkTargets } from './content-links.js';+import { logger } from './logger.js';import { getLanguageName } from './languages.js';import {RunStoppedError,@@ -145,7 +147,23 @@ export const BRIEF_V2_LIMITS = {leftOut: 20,leftOutQuery: 300,datedPoint: 300,+ entity: 120,+ entities: 10,+ internalLinks: 8,+ outboundLinks: 5,+ anchor: 120,+ linkSection: 300,};+/**+ * The pages a brief may plan links to, as many as its prompt lists: the+ * brand's own (the most cited and visited first) and the sources kept.+ */+export const BRIEF_LINK_PAGES = { own: 12, sources: 8 };+/** The competitors a brief's prompt lists, and how long a page's title is there. */+const COMPETITORS_LISTED = 20;+const TITLE_CHARS = 150;+/** The link rules readLinkTargets reads both lists for. */+const LINK_RULES = new Set(['internalLinks', 'outboundLinks']);/*** How a section is best shown; the kind of source a fact needs; the brand's* own proof to gather, as Brief › Your input takes it (web brief.ts).@@ -178,6 +196,13 @@ export const outlineSchema = z.object({keywords: z.array(z.string()).describe('Up to 10 keywords.'),});+/** A link a brief plans: a page listed, the words to link, the H2 it goes in. */+const LINK_ITEM = z.object({+ url: z.string().describe('The address, copied exactly from the list.'),+ anchor: z.string().describe('The words to link: a few words the section says.'),+ section: z.string().nullable().describe('The H2 it goes in, as written, or null for anywhere.'),+});+/*** Version 2's: each section with its answer, format and facts; the page's* essentials, angle, proof to gather, fan-outs left out and point to date.@@ -206,6 +231,16 @@ export const outlineSchemaV2 = outlineSchema.extend({.string().nullable().describe('What the page should date, as a note, or null when nothing in it dates.'),+ products: z+ .array(z.string())+ .describe("The brand's products the page names, written exactly as the data writes them."),+ competitors: z+ .array(z.string())+ .describe('The competitors listed that the page names, written as listed.'),+ links: z.object({+ internal: z.array(LINK_ITEM).describe("Up to 5 of the brand's pages listed to link to."),+ outbound: z.array(LINK_ITEM).describe('Up to 3 of the sources listed to link to.'),+ }),outline: z.array(outlineSchema.shape.outline.element.extend({@@ -269,6 +304,8 @@ export const SYSTEM_PROMPT_V2 = `${SYSTEM_PROMPT}- One topic: in "leftOut", copy exactly the fan-outs listed that belong on another page; none when they all fit.- In "datedPoint", say what the page should date (a price, a figure with its month), or null when nothing in it dates.- The person's input, when listed, is their own: plan with it as given. Never invent a customer, a test, a quote or a figure beyond it.+- Names as written: in "products", the brand's products the page names, written exactly as the data writes them; in "competitors", the competitors listed that it names, as listed. Never another spelling.+- In "links", pick up to 5 of the brand's pages and up to 3 of the sources listed to link to, each by its address copied exactly, with the words to link and the H2 it goes in. None when none is listed.- "format", "sourceType" and a proof's "kind" 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.@@ -317,7 +354,7 @@ export async function rebuildDraftBrief({ draftId, brandId, sources, rules = []throw Object.assign(new Error('Draft not found'), { status: 404 });}- const [brandRes, promptsRes, inputRow] = await Promise.all([+ const [brandRes, promptsRes, inputRow, competitorsRes, linkTargets] = await Promise.all([supabaseAdmin.from('brands').select(@@ -334,9 +371,37 @@ export async function rebuildDraftBrief({ draftId, brandId, sources, rules = []: Promise.resolve({ data: [], error: null }),// Brief › Your input (CE-048, Quality's second phase), with the brief rules on.briefRulesOn() ? readDraftInputs(draftId) : Promise.resolve(null),+ // The competitors' names as written, and the pages it may link to (a failed read: none).+ briefRulesOn()+ ? supabaseAdmin.from('competitors').select('name').eq('brand_id', brandId)+ : Promise.resolve({ data: [], error: null }),+ briefRulesOn()+ ? readLinkTargets({ brandId, draftId, sourceUrl: draft.source_url, ruleKeys: LINK_RULES })+ : Promise.resolve(NO_LINK_TARGETS),]);if (brandRes.error) throw brandRes.error;if (promptsRes.error) throw promptsRes.error;+ // A failed read of the competitors leaves none, as a failed read of the link targets does.+ if (competitorsRes.error) {+ logger.warn({ err: competitorsRes.error, draftId }, '[content-brief] competitors not read');+ }+ const competitors = [+ ...new Set(+ (competitorsRes.error ? [] : (competitorsRes.data ?? []))+ .map((c) => String(c.name ?? '').trim())+ .filter(Boolean),+ ),+ ].slice(0, COMPETITORS_LISTED);+ // An address the web keeps (BRIEF_V2_LIMITS.url), and a title the prompt can hold.+ const linkable = (pages, max) =>+ pages+ .filter((page) => page.url.length <= BRIEF_V2_LIMITS.url)+ .slice(0, max)+ .map((page) => ({ ...page, title: String(page.title ?? '').slice(0, TITLE_CHARS) }));+ const targets = {+ own: linkable(linkTargets.own, BRIEF_LINK_PAGES.own),+ sources: linkable(linkTargets.sources, BRIEF_LINK_PAGES.sources),+ };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.@@ -368,6 +433,8 @@ export async function rebuildDraftBrief({ draftId, brandId, sources, rules = []sources,rules: planTo,inputs,+ competitors,+ targets,run,});await finishRun(run, 'done');@@ -383,7 +450,18 @@ export async function rebuildDraftBrief({ draftId, brandId, sources, rules = []}/** The rebuild itself, step by step: nothing is saved once it is stopped. */-async function briefWithRun({ draft, draftId, brand, prompts, sources, rules, inputs, run }) {+async function briefWithRun({+ draft,+ draftId,+ brand,+ prompts,+ sources,+ rules,+ inputs,+ competitors,+ targets,+ 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, {@@ -407,7 +485,16 @@ async function briefWithRun({ draft, draftId, brand, prompts, sources, rules, inmodel: resolveModel(modelId),schema: briefSchema(),system: briefSystemPrompt(),- prompt: buildBriefPrompt({ brand, draft, prompts, sources, rules, inputs }),+ prompt: buildBriefPrompt({+ brand,+ draft,+ prompts,+ sources,+ rules,+ inputs,+ competitors,+ targets,+ }),abortSignal,}),);@@ -426,7 +513,7 @@ async function briefWithRun({ draft, draftId, brand, prompts, sources, rules, inawait advanceRun(run, 2);const brief = {- ...shapeBrief(object, { brand, draft, prompts, sources, rules, inputs }),+ ...shapeBrief(object, { brand, draft, prompts, sources, rules, inputs, competitors, targets }),origin: 'rebuild',builtAt: new Date().toISOString(),builtFrom: {@@ -460,9 +547,9 @@ export function shapeBrief(object, args) {/*** Under content_drafts.brief's 64 KB (00212), with room for jsonb's spaces:- * past it, the fan-outs left out go, then the facts' sources (a whole- * address, 2 KB at most), then the facts, so a brief charged for is one that- * saves.+ * past it, the links go, then the fan-outs left out, then the facts' sources+ * (a whole address, 2 KB at most), then the facts, so a brief charged for is+ * one that saves.*/const BRIEF_BYTES = 60_000;const withFacts = (brief, strip) => ({@@ -470,6 +557,7 @@ const withFacts = (brief, strip) => ({outline: brief.outline.map((section) => ({ ...section, facts: strip(section.facts ?? []) })),});const FIT_STEPS = [+ (brief) => ({ ...brief, links: null }),(brief) => ({ ...brief, leftOut: [] }),(brief) => withFacts(brief, (list) => list.map((f) => ({ ...f, source: null }))),(brief) => withFacts(brief, () => []),@@ -485,8 +573,20 @@ function fitBrief(brief) {return fitted;}-function shapeWhole(object, { brand, draft, prompts, sources, rules, inputs = [] }) {- const guard = briefGuard({ brand, draft, prompts, sources, rules, inputs });+function shapeWhole(+ object,+ {+ brand,+ draft,+ prompts,+ sources,+ rules,+ inputs = [],+ competitors = [],+ targets = NO_LINK_TARGETS,+ },+) {+ const guard = briefGuard({ brand, draft, prompts, sources, rules, inputs, competitors });// Version 2's (a model answer with them): each section's plan, the page's.const v2 ='tldr' in object ||@@ -517,7 +617,31 @@ function shapeWhole(object, { brand, draft, prompts, sources, rules, inputs = [].filter(Boolean),),].slice(0, BRIEF_LIMITS.keywords),- ...(v2 ? { version: 2, ...pagePlan(object, { guard, words, outline, sources, draft }) } : {}),+ ...(v2+ ? {+ version: 2,+ ...pagePlan(object, { guard, words, outline, sources, draft }),+ ...namesAndLinks(object, {+ guard,+ words,+ outline,+ brand,+ competitors,+ targets,+ // The brand's own words: a product is one it writes (never a+ // prompt's, a search's or a rule's name: "ChatGPT", "FAQ").+ own: [+ brand?.name,+ brand?.industry,+ brand?.description,+ draft.title,+ ...sources.headings,+ ...inputs.map(sourceWords),+ ...targets.own.map((page) => page.title),+ ],+ }),+ }+ : {}),};}@@ -571,6 +695,84 @@ function pagePlan(object, { guard, words, outline, sources, draft }) {};}+/** Text as a name is compared: one form of each character, in small letters. */+const nameKey = (text) =>+ String(text ?? '')+ .normalize('NFKC')+ .trim()+ .replace(/\s+/g, ' ')+ .toLowerCase();++/**+ * The names and links of version 2, the brief rules' entities and links:+ * - the brand's name as kept;+ * - competitors the model names, each one listed, as listed;+ * - products the model names, each where the brand's own words write it+ * (`own`: its name, description, the page's title and headings, Your+ * input, its pages' titles), as written there (never the brand's or a+ * competitor's name), so none is made up or respelled;+ * - links to the pages listed only (`targets`, by their address as links+ * compare it), each with its words guarded and cut (one whose words came+ * back with a placeholder goes), and the H2 it goes in when the outline+ * has it (else anywhere).+ */+function namesAndLinks(object, { guard, words, outline, brand, competitors, targets, own }) {+ const L = BRIEF_V2_LIMITS;+ const listed = new Map(competitors.map((name) => [nameKey(name), name]));+ const competitorsNamed = [+ ...new Set((object.competitors ?? []).map((name) => listed.get(nameKey(name))).filter(Boolean)),+ ]+ .map((name) => name.slice(0, L.entity))+ .slice(0, L.entities);+ // Straight and curly apostrophes alike: a match's place is the same in both.+ const straight = (text) => text.replace(/[‘’]/g, "'");+ const data = own.filter(Boolean).join('\n');+ const plain = straight(data);+ const taken = new Set([nameKey(brand?.name), ...listed.keys()]);+ const products = [];+ for (const name of object.products ?? []) {+ const wanted = String(name ?? '').trim();+ if (!wanted || wanted.length > L.entity || taken.has(nameKey(wanted))) continue;+ const escaped = straight(wanted).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ const at = plain.match(new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, 'iu'));+ const asWritten = at ? data.slice(at.index, at.index + at[0].length) : null;+ if (!asWritten || taken.has(nameKey(asWritten))) continue;+ taken.add(nameKey(asWritten));+ products.push(asWritten);+ if (products.length >= L.entities) break;+ }+ const headings = new Map(outline.map((section) => [nameKey(section.heading), section.heading]));+ const linksTo = (items, pages, max) => {+ const allowed = new Map(pages.map((page) => [linkKey(page.url), page.url]));+ const seen = new Set();+ const kept = [];+ for (const item of items ?? []) {+ const key = linkKey(item?.url);+ const url = key && allowed.get(key);+ const anchor = clip(guard.text(words(item?.anchor ?? '')), L.anchor);+ // Words that came back with a placeholder aren't ones to link.+ if (!url || !anchor || /\[[^\]]*\]/.test(anchor) || seen.has(key)) continue;+ seen.add(key);+ const section = headings.get(nameKey(item?.section)) ?? null;+ kept.push({ url, anchor, section: section ? section.slice(0, L.linkSection) : null });+ if (kept.length >= max) break;+ }+ return kept;+ };+ const internal = linksTo(object.links?.internal, targets.own, L.internalLinks);+ const outbound = linksTo(object.links?.outbound, targets.sources, L.outboundLinks);+ return {+ entities: {+ brand: String(brand?.name ?? '')+ .trim()+ .slice(0, L.entity),+ products,+ competitors: competitorsNamed,+ },+ links: internal.length || outbound.length ? { internal, outbound } : null,+ };+}+/** A key the model was asked for, as the web lists it: trimmed, in small letters. */const keyOf = (value) =>String(value ?? '')@@ -631,8 +833,16 @@ export function briefNumbered(sources, inputs = []) {* 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, rules, inputs }) {- const { given, known, people } = briefKnown({ brand, draft, prompts, sources, rules, inputs });+export function briefGuard({ brand, draft, prompts, sources, rules, inputs, competitors }) {+ const { given, known, people } = briefKnown({+ brand,+ draft,+ prompts,+ sources,+ rules,+ inputs,+ competitors,+ });// 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]);@@ -665,7 +875,15 @@ export function briefGuard({ brand, draft, prompts, sources, rules, inputs }) {* The rules it plans to are among them ("aim: 60 words"), and the person's* own input, word for word.*/-export function briefKnown({ brand, draft, prompts, sources, rules = [], inputs = [] }) {+export function briefKnown({+ brand,+ draft,+ prompts,+ sources,+ rules = [],+ inputs = [],+ competitors = [],+}) {const given = [brand?.name,brand?.industry,@@ -678,6 +896,7 @@ export function briefKnown({ brand, draft, prompts, sources, rules = [], inputsString(sources.length),...rules.flatMap((rule) => [rule.name, rule.detail]),...inputs.map(sourceWords),+ ...competitors,];return { given, known: knownNumbers(...given, todayText()), people: knownPeople(...given) };}@@ -726,7 +945,16 @@ function fanoutMatcher(fanouts) {}/** What the model is told: the brand, the page, and the sources kept. */-export function buildBriefPrompt({ brand, draft, prompts, sources, rules = [], inputs = [] }) {+export function buildBriefPrompt({+ brand,+ draft,+ prompts,+ sources,+ rules = [],+ inputs = [],+ competitors = [],+ targets = NO_LINK_TARGETS,+}) {const list = (items) => (items.length ? items.map((item) => `- ${item}`).join('\n') : '- none');const v2 = briefRulesOn();// With the brief rules on, each cited page and each piece of the person's@@ -738,6 +966,18 @@ export function buildBriefPrompt({ brand, draft, prompts, sources, rules = [], i.map((n) => `${n.id}: ${n.label} (${n.detail})`): sources.pages.map((p) => `${p.url} (${p.kind})`);// Without a note (a quote's address, a day): a fact cites the input by its number.+ const pageLines = (pages) => pages.map((p) => `${p.title || p.url} — ${p.url}`);+ const linkable = v2+ ? [+ competitors.length ? `\nCompetitors (names as written): ${competitors.join(', ')}\n` : '',+ targets.own.length+ ? `\nThe brand's pages to link to:\n${list(pageLines(targets.own))}\n`+ : '',+ targets.sources.length+ ? `\nSources to link to and cite:\n${list(pageLines(targets.sources))}\n`+ : '',+ ].join('')+ : '';const given = numbered.filter((n) => n.kind === 'input').map((n) => `${n.id} "${n.label}": ${n.detail}`);@@ -766,6 +1006,6 @@ ${list(sources.queries)}Pages AI cites for these prompts today:${list(pages)}-${given.length ? `\nThe person's own input for this page (Brief › Your input):\n${list(given)}\n` : ''}+${given.length ? `\nThe person's own input for this page (Brief › Your input):\n${list(given)}\n` : ''}${linkable}${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 9c0de6d94..871fd60f6 100644--- a/server/src/lib/content-brief.test.js+++ b/server/src/lib/content-brief.test.js@@ -22,7 +22,11 @@ vi.mock('../config/supabase.js', () => ({from: (table) => {const call = { table, filters: [] };filters.push(call);- const result = () => ({ data: rows[table] ?? null, error: null });+ // A table set to an Error fails its read.+ const result = () =>+ rows[table] instanceof Error+ ? { data: null, error: rows[table] }+ : { data: rows[table] ?? null, error: null };const chain = {select: () => chain,eq: (col, v) => (call.filters.push(['eq', col, v]), chain),@@ -54,6 +58,11 @@ vi.mock('./plan-guard.js', async (importOriginal) => ({reserveAiBudget: (...args) => reserveAiBudget(...args),}));vi.mock('./logger.js', () => ({ logger: { error: vi.fn(), warn: vi.fn() } }));+const readLinkTargets = vi.fn();+vi.mock('./content-links.js', async (importOriginal) => ({+ ...(await importOriginal()),+ readLinkTargets: (...args) => readLinkTargets(...args),+}));const citedPagesLength = vi.fn();vi.mock('./content-cited-length.js', () => ({citedPagesLength: (...args) => citedPagesLength(...args),@@ -122,6 +131,7 @@ const outline = [beforeEach(() => {stopIfStopped.mockReset().mockResolvedValue(undefined);citedPagesLength.mockReset().mockResolvedValue({ characters: 4300, pages: 1 });+ readLinkTargets.mockReset().mockResolvedValue({ own: [], sources: [] });writes = [];filters = [];rows = {@@ -737,6 +747,9 @@ describe('the brief rules (2026), behind CONTENT_BRIEF_RULES', () => {proof: [{ kind: 'Fallstudie', what: 'w' }],leftOut: [],datedPoint: null,+ products: [],+ competitors: [],+ links: { internal: [], outbound: [] },outline: [{heading: 'h',@@ -887,6 +900,190 @@ describe('the brief rules (2026), behind CONTENT_BRIEF_RULES', () => {});});+ it('names the brand, its competitors as listed and its products as the data writes them, and links to the pages listed only', async () => {+ process.env.CONTENT_BRIEF_RULES = 'true';+ rows.competitors = [{ name: 'Acme Rival' }, { name: ' ' }];+ readLinkTargets.mockResolvedValue({+ own: [+ { url: 'https://acme.example/guides/grinders', title: 'Grinder guide' },+ ...Array.from({ length: 14 }, (_, i) => ({+ url: `https://acme.example/p/${i}`,+ title: `Page ${i}`,+ })),+ ],+ sources: [{ url: 'https://sca.example/brew', title: 'SCA brew' }],+ });+ generateObject.mockResolvedValue({+ object: {+ goal: 'g',+ audience: 'a',+ tldr: null,+ angle: null,+ proof: [],+ leftOut: [],+ datedPoint: null,+ products: ['bambino plus', 'Made Up 3000', 'Acme Coffee', 'acme rival', 'Bambino Plus'],+ competitors: ['acme rival', 'Unknown Co'],+ links: {+ internal: [+ {+ url: 'https://acme.example/guides/grinders/?utm_source=x',+ anchor: 'our grinder guide',+ section: 'grinders',+ },+ { url: 'https://made-up.example/x', anchor: 'made up', section: null },+ { url: 'https://acme.example/guides/grinders', anchor: 'again', section: null },+ ],+ outbound: [+ { url: 'https://sca.example/brew', anchor: '73% of baristas agree', section: 'Nope' },+ { url: 'https://acme.example/p/13', anchor: 'not a source', section: null },+ ],+ },+ outline: [+ {+ heading: 'Grinders',+ keyPoints: [],+ fanout: null,+ platform: null,+ answer: null,+ format: null,+ facts: [],+ },+ ],+ keywords: [],+ },+ usage: { inputTokens: 10, outputTokens: 5 },+ });+ const brief = await rebuildDraftBrief({+ draftId: DRAFT,+ brandId: BRAND,+ sources: sources({ headings: ['Breville Bambino Plus vs Gaggia Classic'] }),+ });+ expect(readLinkTargets).toHaveBeenCalledWith({+ brandId: BRAND,+ draftId: DRAFT,+ sourceUrl: 'https://acme.example/guides/espresso',+ ruleKeys: new Set(['internalLinks', 'outboundLinks']),+ });+ const prompt = generateObject.mock.calls[0][0].prompt;+ expect(prompt).toContain('Competitors (names as written): Acme Rival\n');+ expect(prompt).toContain(+ "The brand's pages to link to:\n- Grinder guide — https://acme.example/guides/grinders",+ );+ expect(prompt).toContain('Sources to link to and cite:\n- SCA brew — https://sca.example/brew');+ // Twelve of the brand's pages at most: the most cited first.+ expect(prompt).toContain('Page 10 — ');+ expect(prompt).not.toContain('Page 11 — ');+ expect(brief.entities).toEqual({+ brand: 'Acme Coffee',+ // As the data writes it, once; none made up, never the brand's or a competitor's.+ products: ['Bambino Plus'],+ competitors: ['Acme Rival'],+ });+ expect(brief.links).toEqual({+ // A page listed, by its address as listed, in the H2 the outline has.+ internal: [+ {+ url: 'https://acme.example/guides/grinders',+ anchor: 'our grinder guide',+ section: 'Grinders',+ },+ ],+ // Words that came back with a placeholder aren't linked; a source as an internal link isn't one.+ outbound: [],+ });+ });++ it('takes a product only from the brand’s own words, as written there, and caps each list', async () => {+ process.env.CONTENT_BRIEF_RULES = 'true';+ vi.stubEnv('CONTENT_QUALITY_PHASE', '2');+ rows.brands.name = null;+ rows.competitors = new Error('down');+ rows.content_draft_inputs = {+ experience: 'We tune every Barista Pro before it ships.',+ data: [],+ ansvisor_data: [],+ quotes: [],+ };+ const page = (i, host) => ({+ url: `https://${host}.example/${i}`,+ title: `T${i}${'x'.repeat(200)}`,+ });+ readLinkTargets.mockResolvedValue({+ own: [+ { url: `https://acme.example/${'p'.repeat(2100)}`, title: 'Too long an address' },+ ...Array.from({ length: 14 }, (_, i) => page(i, 'acme')),+ ],+ sources: Array.from({ length: 10 }, (_, i) => page(i, 'sca')),+ });+ const link = (host) => (_, i) => ({+ url: `https://${host}.example/${i}`,+ anchor: `words ${i}`,+ section: null,+ });+ generateObject.mockResolvedValue({+ object: {+ goal: 'g',+ audience: 'a',+ tldr: null,+ angle: null,+ proof: [],+ leftOut: [],+ datedPoint: null,+ // "ChatGPT" is a prompt's, "FAQ" a rule's: neither the brand's.+ products: [+ 'barista pro',+ 'C++ SDK',+ 'ChatGPT',+ 'FAQ',+ ...Array.from({ length: 12 }, (_, i) => `Kit ${i}`),+ ],+ competitors: [],+ links: {+ internal: Array.from({ length: 12 }, link('acme')),+ outbound: Array.from({ length: 8 }, link('sca')),+ },+ outline: [],+ keywords: [],+ },+ usage: { inputTokens: 10, outputTokens: 5 },+ });+ const brief = await rebuildDraftBrief({+ draftId: DRAFT,+ brandId: BRAND,+ sources: sources({+ headings: [`The C++ SDK, ${Array.from({ length: 12 }, (_, i) => `Kit ${i}`).join(', ')}`],+ }),+ rules: [{ key: 'faq', name: 'FAQ', detail: '' }],+ });+ const prompt = generateObject.mock.calls[0][0].prompt;+ // A failed read of the competitors: none listed, the rebuild goes on.+ expect(prompt).not.toContain('Competitors');+ // An address the web can't keep isn't offered; titles are cut; 12 and 8 pages at most.+ expect(prompt).not.toContain('Too long an address');+ expect(prompt).toContain(`T0${'x'.repeat(148)} — https://acme.example/0`);+ expect(prompt).toContain('https://acme.example/11');+ expect(prompt).not.toContain('https://acme.example/12');+ expect(prompt).toContain('https://sca.example/7');+ expect(prompt).not.toContain('https://sca.example/8');+ expect(brief.entities.brand).toBe('');+ expect(brief.entities.products).toEqual([+ 'Barista Pro',+ 'C++ SDK',+ ...Array.from({ length: 8 }, (_, i) => `Kit ${i}`),+ ]);+ expect(brief.links.internal).toHaveLength(BRIEF_V2_LIMITS.internalLinks);+ expect(brief.links.outbound).toHaveLength(BRIEF_V2_LIMITS.outboundLinks);+ });++ it('reads no competitors and no pages to link to while the brief rules are off', async () => {+ rows.competitors = [{ name: 'Acme Rival' }];+ await rebuildDraftBrief({ draftId: DRAFT, brandId: BRAND, sources: sources() });+ expect(readLinkTargets).not.toHaveBeenCalled();+ expect(filters.some((f) => f.table === 'competitors')).toBe(false);+ expect(generateObject.mock.calls[0][0].prompt).not.toContain('Competitors');+ });+it('reads no input while the brief rules are off', async () => {vi.stubEnv('CONTENT_QUALITY_PHASE', '2');rows.content_draft_inputs = {@@ -960,6 +1157,54 @@ describe('the brief rules (2026), behind CONTENT_BRIEF_RULES', () => {expect(brief.outline.every((s) => s.facts.every((f) => f.source === null))).toBe(true);});+ it('lets the links go first, when that is enough to fit', async () => {+ process.env.CONTENT_BRIEF_RULES = 'true';+ const long = (i) => `https://acme.example/${'p'.repeat(1900)}/${i}`;+ readLinkTargets.mockResolvedValue({+ own: Array.from({ length: 8 }, (_, i) => ({ url: long(i), title: `P${i}` })),+ sources: [],+ });+ const section = (i) => ({+ heading: `Machines ${String.fromCharCode(97 + i)}`,+ keyPoints: [],+ fanout: null,+ platform: null,+ answer: '中'.repeat(600),+ format: null,+ // Two bytes a character: with the links past the limit, without them under it.+ facts: Array(4).fill({ claim: 'é'.repeat(300), sourceType: 'study', source: null }),+ });+ generateObject.mockResolvedValue({+ object: {+ goal: 'g',+ audience: 'a',+ tldr: null,+ angle: null,+ proof: [],+ leftOut: ['home espresso grinder'],+ datedPoint: null,+ products: [],+ competitors: [],+ links: {+ internal: Array.from({ length: 8 }, (_, i) => ({+ url: long(i),+ anchor: 'a'.repeat(120),+ section: null,+ })),+ outbound: [],+ },+ 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.links).toBeNull();+ expect(brief.leftOut).toEqual(['home espresso grinder']);+ expect(brief.outline[0].facts).toHaveLength(4);+ });+it('lets the fan-outs left out go first, when that is enough to fit', async () => {process.env.CONTENT_BRIEF_RULES = 'true';const long = 'https://www.reddit.com/r/espresso/' + 'x'.repeat(2000);