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 the Content Agent write from Brief › Your input, as the person gave it (CE-048, part b) (#1454)
Cihan1d5398dce958
diff --git a/server/src/lib/content-agent.js b/server/src/lib/content-agent.jsindex 5892f01a7..c8c2b9ea1 100644--- a/server/src/lib/content-agent.js+++ b/server/src/lib/content-agent.js@@ -5,6 +5,7 @@ import { z } from 'zod';import supabaseAdmin from '../config/supabase.js';import { resolveModel } from './ai-provider.js';import { contentBriefModelId, rebuildSources } from './content-brief.js';+import { inputSources, readDraftInputs } from './content-inputs.js';import { linkAllowList, linkKey, linkTargetsPrompt, readLinkTargets } from './content-links.js';import { siteTypeLine, pageTypeFormat } from './content-page-types.js';import { authorWords, guardPeopleInHtml, knownPeople } from './content-people.js';@@ -669,14 +670,19 @@ async function fixWithRun({ draft, brand, brandId, draftId, input, passages, morconst modelId = contentBriefModelId();const lockedKeys = new Set(input.locked.map(passageKey));const ruleKeys = new Set(input.rules.map((r) => r.key));- // The data it writes from, numbered; the numbers it may write unmarked.+ // The data it writes from, numbered, Brief › Your input last (CE-048);+ // the numbers it may write unmarked.await advanceRun(run, 1);- const prompts = await readPrompts(brandId, input.sources?.promptIds ?? []);+ const [prompts, inputRow] = await Promise.all([+ readPrompts(brandId, input.sources?.promptIds ?? []),+ readDraftInputs(draftId),+ ]);const numbered = numberSources({prompts,fanouts: input.sources?.fanouts,pages: input.sources?.pages,queries: input.sources?.queries,+ inputs: inputSources(inputRow, brand.name),});const known = knownNumbers(htmlText(draft.body_html),diff --git a/server/src/lib/content-agent.test.js b/server/src/lib/content-agent.test.jsindex c4d7a27b4..0b3483797 100644--- a/server/src/lib/content-agent.test.js+++ b/server/src/lib/content-agent.test.js@@ -912,6 +912,83 @@ describe('fixDraftRules', () => {);});+ it("writes from Brief › Your input in Quality's second phase, numbered last (CE-048)", async () => {+ rows.content_draft_inputs = {+ experience: null,+ data: [+ {+ name: 'Survey',+ rows: [+ ['Teams', 'Share'],+ ['1,250', '42%'],+ ],+ },+ ],+ ansvisor_data: [],+ quotes: [+ {+ name: 'Ada Lovelace',+ title: 'Head of Research, Acme',+ text: 'We cut our forecast misses in half.',+ sourceUrl: 'https://acme.example/talk',+ },+ ],+ };+ generateObject.mockResolvedValue({+ object: {+ suggestions: [+ suggestion({+ after: 'good coffee and hot water: 1,250 teams brew this way',+ sources: ['S3'],+ marks: [],+ }),+ suggestion({+ passage: 3,+ before: 'A dripper and a filter',+ after:+ 'A dripper and a filter. “We cut our forecast misses in half,” says Ada Lovelace',+ sources: ['S4'],+ marks: [],+ }),+ ],+ },+ usage: { inputTokens: 900, outputTokens: 200 },+ });+ const before = process.env.CONTENT_QUALITY_PHASE;+ process.env.CONTENT_QUALITY_PHASE = '2';+ try {+ await fixDraftRules({ draftId: DRAFT, brandId: BRAND, input: input({ sources: SOURCES }) });+ } finally {+ if (before === undefined) delete process.env.CONTENT_QUALITY_PHASE;+ else process.env.CONTENT_QUALITY_PHASE = before;+ }+ const prompt = generateObject.mock.calls[0][0].prompt;+ expect(prompt).toContain(+ `S3 Your input (the person's own, given for this page): "Survey" (Their own data, a table: Teams | Share; 1,250 | 42%)`,+ );+ expect(prompt).toContain('S4 Your input');+ expect(prompt).toContain('quote an expert word for word');+ // Its number and its expert are the person's own: kept, each with its source.+ const batch = writes.find((w) => w.table === 'content_draft_suggestions');+ expect(batch.value.map((row) => [row.after_text, row.sources])).toEqual([+ [+ 'good coffee and hot water: 1,250 teams brew this way',+ [{ kind: 'input', ref: 'data:1', label: 'Survey' }],+ ],+ [+ 'A dripper and a filter. “We cut our forecast misses in half,” says Ada Lovelace',+ [{ kind: 'input', ref: 'quote:1', label: 'Ada Lovelace, Head of Research, Acme' }],+ ],+ ]);+ });++ it("reads no input before Quality's second phase", async () => {+ rows.content_draft_inputs = { experience: 'We tested it for six weeks.' };+ generateObject.mockResolvedValue({ object: { suggestions: [] }, usage: {} });+ await fixDraftRules({ draftId: DRAFT, brandId: BRAND, input: input({ sources: SOURCES }) });+ expect(generateObject.mock.calls[0][0].prompt).not.toContain('Your input');+ });+it('keeps nothing once stopped, and says so (CE-027)', async () => {const { RunStoppedError } = await import('./content-runs.js');stopIfStopped.mockRejectedValueOnce(new RunStoppedError());diff --git a/server/src/lib/content-inputs.js b/server/src/lib/content-inputs.jsnew file mode 100644index 000000000..c523347bc--- /dev/null+++ b/server/src/lib/content-inputs.js@@ -0,0 +1,152 @@+import supabaseAdmin from '../config/supabase.js';+import { qualityPhase } from './content-quality.js';++/**+ * Brief › Your input (Content Editor Quality spec §6, CE-048): what only the+ * person can give a page (content_draft_inputs, 00265) — their first-hand+ * experience, their data (their own tables, and Ansvisor data they chose)+ * and expert quotes — numbered after the draft's other sources, as the+ * person gave them. The agent writes from them and adds nothing beyond+ * them: a number it writes must be in a source's words (content-sources.js)+ * and a person or a quote in what it was given (content-people.js), and+ * these are. Read with Quality's second phase only.+ *+ * Each is { kind: 'input', ref, label, detail }: the label short, as a+ * "Based on" chip shows it; the detail the words the model reads and the+ * guards read numbers, names and quotes from.+ */++/** A table's rows as the model reads them, at most: enough to cite, not a page of cells. */+export const TABLE_CHARS = 3000;+/** An experience's first words, as its chip names it. */+const LABEL_CHARS = 80;++/** Characters, never half of one (an emoji), as many as `max`. */+const cut = (text, max) => Array.from(text).slice(0, max).join('');++/**+ * The person's words as the prompt lists them: on one line (a line break+ * would start a line of its own in the list), straight double quotes as+ * single ones (they'd close the quotes around them), cut to `max`.+ */+const textOf = (value, max) =>+ typeof value === 'string'+ ? cut(value.replace(/\s+/g, ' ').replace(/"/g, "'").trim(), max).trimEnd()+ : '';+const listOf = (value) => (Array.isArray(value) ? value : []);++/** "2026-10-24" as Ansvisor data is cited: "October 2026". */+function monthOf(day) {+ if (!/^\d{4}-\d{2}-\d{2}$/.test(day ?? '')) return null;+ const date = new Date(`${day}T12:00:00Z`);+ if (Number.isNaN(date.getTime())) return null;+ return date.toLocaleString('en-US', { month: 'long', year: 'numeric', timeZone: 'UTC' });+}++/** The draft's input as kept, or null: none given, or Quality's second phase not live. */+export async function readDraftInputs(draftId) {+ if (qualityPhase() < 2) return null;+ const { data, error } = await supabaseAdmin+ .from('content_draft_inputs')+ .select('experience, data, ansvisor_data, quotes')+ .eq('draft_id', draftId)+ .maybeSingle();+ if (error) throw error;+ return data ?? null;+}++/**+ * The input as sources, in the order Brief › Your input lists it: the+ * experience, each table, each prompt's Ansvisor data, each quote. An item+ * missing what makes it real (a quote without its name, title, words or an+ * http(s) source) is left out. `brandName` is who Ansvisor data counts.+ *+ * What only places a source (a quote's address, the days Ansvisor data+ * covers) is its `note`: the model reads it, the guards don't, so its+ * digits are no number the agent may write (sourceWords). Refs are by+ * place in the list, for a chip to open Your input by: an item removed+ * since moves the ones after it, so none is looked up by its ref.+ */+export function inputSources(row, brandName) {+ if (!row) return [];+ const sources = [];++ const experience = textOf(row.experience, 4000);+ if (experience) {+ sources.push({+ kind: 'input',+ ref: 'experience',+ label:+ Array.from(experience).length > LABEL_CHARS+ ? `${cut(experience, LABEL_CHARS).trimEnd()}…`+ : experience,+ detail: `Their experience, first-hand: ${experience}`,+ });+ }++ listOf(row.data)+ .slice(0, 5)+ .forEach((table, i) => {+ const name = textOf(table?.name, 120);+ const all = listOf(table?.rows)+ .filter(Array.isArray)+ .map((cells) => cells.map((cell) => textOf(String(cell ?? ''), 200)).join(' | '))+ .join('; ');+ // A table cut says so: its rows go on past what the model reads.+ const rows =+ Array.from(all).length > TABLE_CHARS ? `${cut(all, TABLE_CHARS)}… (first rows)` : all;+ if (name && rows) {+ sources.push({+ kind: 'input',+ ref: `data:${i + 1}`,+ label: name,+ detail: `Their own data, a table: ${rows}`,+ });+ }+ });++ for (const d of listOf(row.ansvisor_data).slice(0, 10)) {+ const prompt = textOf(d?.prompt, 500);+ const month = monthOf(d?.asOf);+ if (+ typeof d?.promptId !== 'string' ||+ !prompt ||+ !month ||+ !Number.isInteger(d.answers) ||+ !Number.isInteger(d.mentioned) ||+ !Number.isInteger(d.days)+ ) {+ continue;+ }+ // The share, as a page says it: "named in 3.4% of AI answers".+ const share = d.answers > 0 ? ` (${Math.round((d.mentioned / d.answers) * 1000) / 10}%)` : '';+ sources.push({+ kind: 'input',+ ref: `ansvisor:${d.promptId}`,+ label: prompt,+ // The days are the data the person chose: the page may say them. The+ // date is a note: its digits are no figure.+ detail: `Ansvisor data: ${brandName || 'the brand'} was named in ${d.mentioned} of ${d.answers} AI answers to this prompt over the last ${d.days} days${share}. Cite it as "Ansvisor data, ${month}"`,+ note: `to ${d.asOf}`,+ });+ }++ listOf(row.quotes)+ .slice(0, 10)+ .forEach((q, i) => {+ const name = textOf(q?.name, 120);+ const title = textOf(q?.title, 160);+ const said = textOf(q?.text, 600);+ const url = typeof q?.sourceUrl === 'string' ? q.sourceUrl.trim().slice(0, 2048) : '';+ if (!name || !title || !said || !/^https?:\/\/\S+$/i.test(url)) return;+ sources.push({+ kind: 'input',+ ref: `quote:${i + 1}`,+ label: `${name}, ${title}`,+ detail: `An expert's words, to quote word for word with their name and title: "${said}"`,+ note: `said at ${url}`,+ });+ });++ return sources;+}diff --git a/server/src/lib/content-inputs.test.js b/server/src/lib/content-inputs.test.jsnew file mode 100644index 000000000..5224929ab--- /dev/null+++ b/server/src/lib/content-inputs.test.js@@ -0,0 +1,199 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * Brief › Your input as the Content Agent reads it (CE-048): numbered after+ * the draft's other sources, each as the person gave it, with Quality's+ * second phase only.+ */++let row;+const reads = [];+vi.mock('../config/supabase.js', () => ({+ default: {+ from: (table) => {+ const chain = {+ select: () => chain,+ eq: (col, value) => (reads.push([table, col, value]), chain),+ maybeSingle: async () => ({ data: row, error: null }),+ };+ return chain;+ },+ },+}));++const { TABLE_CHARS, inputSources, readDraftInputs } = await import('./content-inputs.js');+const { knownNumbers, numberSources, sourceWords, sourcesPrompt } =+ await import('./content-sources.js');+const { guardPeople, knownPeople } = await import('./content-people.js');++const QUOTE = {+ name: 'Ada Lovelace',+ title: 'Head of Research, Acme',+ text: 'We cut our forecast misses in half.',+ sourceUrl: 'https://acme.example/talk',+};++let phase;+beforeEach(() => {+ phase = process.env.CONTENT_QUALITY_PHASE;+ row = null;+ reads.length = 0;+});+afterEach(() => {+ if (phase === undefined) delete process.env.CONTENT_QUALITY_PHASE;+ else process.env.CONTENT_QUALITY_PHASE = phase;+});++describe('readDraftInputs', () => {+ it("reads nothing before Quality's second phase", async () => {+ row = { experience: 'We tested it.' };+ process.env.CONTENT_QUALITY_PHASE = '1';+ expect(await readDraftInputs('d1')).toBeNull();+ expect(reads).toEqual([]);+ });++ it("reads the draft's input in it", async () => {+ row = { experience: 'We tested it.' };+ process.env.CONTENT_QUALITY_PHASE = '2';+ expect(await readDraftInputs('d1')).toEqual(row);+ expect(reads).toEqual([['content_draft_inputs', 'draft_id', 'd1']]);+ });+});++describe('inputSources', () => {+ it('lists the experience, each table, each prompt’s Ansvisor data and each quote, in order', () => {+ const sources = inputSources(+ {+ experience: `We tested three grinders for six weeks in our roastery. ${'More. '.repeat(20)}`,+ data: [+ {+ name: 'Survey',+ rows: [+ ['Teams', 'Share'],+ ['1,250', '42%'],+ ],+ },+ ],+ ansvisor_data: [+ {+ promptId: '5e8cd4c2-2bc4-4fb7-8711-bc0ad1bb4a29',+ prompt: 'best pour-over grinder',+ answers: 825,+ mentioned: 28,+ asOf: '2026-10-03',+ days: 30,+ },+ ],+ quotes: [QUOTE],+ },+ 'Acme Coffee',+ );+ expect(sources.map((s) => [s.kind, s.ref, s.label])).toEqual([+ [+ 'input',+ 'experience',+ 'We tested three grinders for six weeks in our roastery. More. More. More. More.…',+ ],+ ['input', 'data:1', 'Survey'],+ ['input', 'ansvisor:5e8cd4c2-2bc4-4fb7-8711-bc0ad1bb4a29', 'best pour-over grinder'],+ ['input', 'quote:1', 'Ada Lovelace, Head of Research, Acme'],+ ]);+ expect(sources[1].detail).toBe('Their own data, a table: Teams | Share; 1,250 | 42%');+ expect(sources[2].detail).toBe(+ 'Ansvisor data: Acme Coffee was named in 28 of 825 AI answers to this prompt over the last 30 days (3.4%). Cite it as "Ansvisor data, October 2026"',+ );+ expect(sources[2].note).toBe('to 2026-10-03');+ expect(sources[3].detail).toContain('"We cut our forecast misses in half."');+ expect(sources[3].note).toBe('said at https://acme.example/talk');+ });++ it('gives no number from where a source was said or when: its address and date are notes', () => {+ // The days are the data the person chose: a page may say them.+ const [ansvisor, quote] = inputSources(+ {+ ansvisor_data: [+ {+ promptId: 'p1',+ prompt: 'crm for teams',+ answers: 825,+ mentioned: 28,+ asOf: '2026-10-03',+ days: 30,+ },+ ],+ quotes: [{ ...QUOTE, sourceUrl: 'https://acme.example/blog/2024/05/report-500-teams' }],+ },+ 'Acme',+ );+ expect(knownNumbers(sourceWords(quote)).has('500')).toBe(false);+ expect(knownNumbers(sourceWords(ansvisor)).has('10')).toBe(false);+ expect(knownNumbers(sourceWords(ansvisor)).has('03')).toBe(false);+ expect(knownNumbers(sourceWords(ansvisor)).has('30')).toBe(true);+ expect(knownNumbers(sourceWords(ansvisor)).has('825')).toBe(true);+ // The model still reads them.+ expect(sourcesPrompt(numberSources({ inputs: [quote] }))).toContain(+ '— said at https://acme.example/blog/2024/05/report-500-teams',+ );+ });++ it('keeps the person’s words on one line, its quotes closed, never half of an emoji', () => {+ const [experience, table, quote] = inputSources({+ experience: `We tested it.\n\n- Then we ${'😀'.repeat(80)}`,+ data: [{ name: 'Visits', rows: [['Oct', '3,400\n(est.)']] }],+ quotes: [{ ...QUOTE, text: 'It "just works".' }],+ });+ expect(experience.detail).toBe(+ `Their experience, first-hand: We tested it. - Then we ${'😀'.repeat(80)}`,+ );+ expect(experience.label.endsWith('😀…')).toBe(true);+ expect(experience.label).not.toMatch(/[\ud800-\udbff](?![\udc00-\udfff])/);+ expect(table.detail).toBe('Their own data, a table: Oct | 3,400 (est.)');+ expect(quote.detail).toContain(`"It 'just works'."`);+ });++ it('leaves out what isn’t whole: a quote without its parts, a table without rows', () => {+ expect(+ inputSources({+ experience: ' ',+ data: [{ name: 'Empty', rows: [] }, { rows: [['1']] }],+ ansvisor_data: [{ promptId: 'p', prompt: 'x', answers: 1, mentioned: 0 }],+ quotes: [+ { ...QUOTE, title: '' },+ { ...QUOTE, sourceUrl: 'javascript:alert(1)' },+ ],+ }),+ ).toEqual([]);+ expect(inputSources(null)).toEqual([]);+ });++ it('gives the model a table only up to its cap', () => {+ const rows = Array.from({ length: 100 }, () =>+ Array.from({ length: 12 }, () => 'x'.repeat(50)),+ );+ const [table] = inputSources({ data: [{ name: 'Big', rows }] });+ expect(table.detail).toHaveLength(+ 'Their own data, a table: '.length + TABLE_CHARS + '… (first rows)'.length,+ );+ expect(table.detail.endsWith('… (first rows)')).toBe(true);+ });++ it('numbers them last, tells the model what to do with them, and lets their numbers and people in', () => {+ const inputs = inputSources({ data: [{ name: 'Survey', rows: [['1,250']] }], quotes: [QUOTE] });+ const numbered = numberSources({+ fanouts: [{ query: 'pour over ratio', platforms: [] }],+ inputs,+ });+ expect(numbered.map((s) => s.id)).toEqual(['S1', 'S2', 'S3']);+ const prompt = sourcesPrompt(numbered);+ expect(prompt).toContain(`S2 Your input (the person's own, given for this page): "Survey"`);+ expect(prompt).toContain('add nothing to it');+ expect(+ sourcesPrompt(numberSources({ fanouts: [{ query: 'q', platforms: [] }] })),+ ).not.toContain('Your input is');+ expect(knownNumbers(sourceWords(numbered[1])).has('1250')).toBe(true);+ const people = knownPeople(...numbered.map(sourceWords));+ expect(+ guardPeople('“We cut our forecast misses in half,” says Ada Lovelace.', people).text,+ ).toBe('“We cut our forecast misses in half,” says Ada Lovelace.');+ });+});diff --git a/server/src/lib/content-sources.js b/server/src/lib/content-sources.jsindex 3ea858b20..ecac1dce2 100644--- a/server/src/lib/content-sources.js+++ b/server/src/lib/content-sources.js@@ -53,9 +53,16 @@ export function normalizeQuery(query) {/*** The sources numbered: [{ id: 'S1', kind, ref, label, detail }], refs as the* Sources tab keys its rows (a prompt's id, a normalized query, a page's- * address), so the editor finds each one there.+ * address), so the editor finds each one there. Brief › Your input comes+ * last, as inputSources (content-inputs.js) lists it (CE-048).*/-export function numberSources({ prompts = [], fanouts = [], pages = [], queries = [] }) {+export function numberSources({+ prompts = [],+ fanouts = [],+ pages = [],+ queries = [],+ inputs = [],+}) {const list = [...prompts.map((p) => ({ kind: 'prompt', ref: p.id, label: p.text })),...fanouts.map((f) => ({@@ -66,6 +73,7 @@ export function numberSources({ prompts = [], fanouts = [], pages = [], queries})),...pages.map((p) => ({ kind: 'cited_page', ref: p.url, label: p.url, detail: p.kind })),...queries.map((q) => ({ kind: 'gsc_query', ref: normalizeQuery(q), label: q })),+ ...inputs,].filter((s) => s.ref && s.label);return list.map((s, i) => ({ id: `S${i + 1}`, ...s }));}@@ -75,16 +83,21 @@ const KIND_NAMES = {fanout: 'Fan-out (a search AI ran while answering)',cited_page: 'Cited page (AI answers cite it today; answer better, never copy)',gsc_query: 'Search Console query (a Google search people use)',+ input: "Your input (the person's own, given for this page)",};+/** What the agent does with Brief › Your input, when the list has any (CE-048). */+export const INPUT_RULE = `- Your input is the person's own: write their experience as first-hand ("we tested…") and add nothing to it; quote an expert word for word, with their name and title; cite Ansvisor data as its line says. Never invent people, quotes, customer stories, test results or numbers beyond what you were given: where one is missing, write a placeholder in square brackets.`;+/** The numbered list as the model reads it, or '' with none. */export function sourcesPrompt(numbered) {if (!numbered.length) return '';const lines = numbered.map((s) =>- `${s.id} ${KIND_NAMES[s.kind]}: ${s.kind === 'cited_page' ? s.label : `"${s.label}"`}${s.detail ? ` (${s.detail})` : ''}`,+ `${s.id} ${KIND_NAMES[s.kind]}: ${s.kind === 'cited_page' ? s.label : `"${s.label}"`}${s.detail ? ` (${s.detail})` : ''}${s.note ? ` — ${s.note}` : ''}`,);- return `Your data, numbered (cite by number):\n${lines.join('\n')}`;+ const rule = numbered.some((s) => s.kind === 'input') ? `\n${INPUT_RULE}` : '';+ return `Your data, numbered (cite by number):\n${lines.join('\n')}${rule}`;}/** A source number written into the words in brackets ("(S2)", "[S1, S3]"): never the page's. */@@ -121,8 +134,12 @@ function unitOf(text, start, end) {/** A placeholder the agent leaves ("[figure, source, 2025]"): it holds no claim. */const BRACKETS = /\[[^\]]*\]/g;-/** A number's value as compared: thousands separators dropped ("1,299" is 1299). */-const valueOf = (token) => token.replace(/[.,](?=\d{3}(?!\d))/g, '');+/**+ * A number's value as compared: thousands separators dropped ("1,299" and+ * "1.299" are 1299), then a decimal comma read as a point ("3,4" is 3.4,+ * "1.250,5" is 1250.5), as Turkish, German, French and others write it.+ */+const valueOf = (token) => token.replace(/[.,](?=\d{3}(?!\d))/g, '').replace(',', '.');/** The numbers a text holds, each with where it is and its unit ('' for none). */export function numbersIn(text) {@@ -155,7 +172,11 @@ export function todayText(now = new Date()) {return `${now.getUTCFullYear()}`;}-/** A source's words its numbers are read from: a cited page's address is none ("/2024/03/15/post-1234"). */+/**+ * A source's words its numbers are read from: a cited page's address is+ * none ("/2024/03/15/post-1234"), nor what only places a source, its note+ * (a quote's address, the days Ansvisor data covers: content-inputs.js).+ */export function sourceWords(source) {return source.kind === 'cited_page' ? '' : `${source.label} ${source.detail ?? ''}`;}@@ -265,13 +286,23 @@ export function sourceSuggestion({ named, marks, pieces, numbered, known }) {if (at !== -1) kept.push({ start: at, end: at + words.length, source });}- // Each number it adds: the page's own, or one of its sources' words'.+ // Each number it adds: the page's own, or one of its sources' words' —+ // the ones it named or marked first, so a number two sources have goes+ // to the one it used, then the rest in their order.const own = numbered.map((s) => knownNumbers(sourceWords(s)));+ const used = new Set(sources.map((s) => `${s.kind}:${s.ref}`));+ const order = numbered+ .map((_, i) => i)+ .sort(+ (a, b) =>+ Number(!used.has(`${numbered[a].kind}:${numbered[a].ref}`)) -+ Number(!used.has(`${numbered[b].kind}:${numbered[b].ref}`)),+ );for (const piece of pieces) {for (const n of addedNumbers(piece.text, known)) {const start = piece.start + n.start;const end = piece.start + n.end;- const from = numbered.findIndex((_, i) => own[i].has(n.unit ? unitKey(n) : n.value));+ const from = order.find((i) => own[i].has(n.unit ? unitKey(n) : n.value)) ?? -1;if (from === -1) return null;const source = indexOf(numbered[from]);if (source === -1) return null;diff --git a/server/src/lib/content-sources.test.js b/server/src/lib/content-sources.test.jsindex 0f556513f..9a5d8ef9d 100644--- a/server/src/lib/content-sources.test.js+++ b/server/src/lib/content-sources.test.js@@ -70,6 +70,24 @@ describe('sourceSuggestion', () => {const known = knownNumbers('Trackers compared in 2026.');const one = (text) => [{ text, start: 0 }];+ it('gives a number two sources have to the one it used, then the first', () => {+ const both = numberSources({+ fanouts: [{ query: 'crm for 50 users', platforms: [] }],+ inputs: [+ { kind: 'input', ref: 'data:1', label: 'Seats', detail: 'Their own data, a table: 50' },+ ],+ });+ const text = 'Teams of 50 forecast weekly.';+ expect(+ sourceSuggestion({ named: ['S2'], marks: [], pieces: one(text), numbered: both, known })+ .sources,+ ).toEqual([{ kind: 'input', ref: 'data:1', label: 'Seats' }]);+ // Named by none: the first that has it.+ expect(+ sourceSuggestion({ named: [], marks: [], pieces: one(text), numbered: both, known }).sources,+ ).toEqual([{ kind: 'fanout', ref: 'crm for 50 users', label: 'crm for 50 users' }]);+ });+it('keeps the sources named and each mark where its words are, marked ones first', () => {const text = 'Trackers cover AI answers, per Profound, for the llm visibility tool.';expect(@@ -236,6 +254,18 @@ describe('no number without a source', () => {]);});+ it('reads a decimal comma as a point, once thousands separators are gone', () => {+ // Ansvisor data's share is written "3.4%"; a Turkish or a German page writes it with a comma.+ const share = knownNumbers('named in 28 of 825 AI answers over the last 30 days (3.4%)');+ expect(addedNumbers('825 yanıtın 28 tanesinde anıldı (%3,4).', share)).toEqual([]);+ expect(addedNumbers('in 28 von 825 Antworten genannt (3,4 %).', share)).toEqual([]);+ expect(addedNumbers('Son 30 günde 825 yanıtın 28 tanesinde.', share)).toEqual([]);+ expect(addedNumbers('in 3,5 % der Antworten', share).map((n) => n.value)).toEqual(['3.5']);+ // Thousands still read as thousands, both ways.+ const counts = knownNumbers('1,250 teams and 1250.5 hours');+ expect(addedNumbers('1.250 Teams, 1.250,5 Stunden, 1,250 teams', counts)).toEqual([]);+ });+it('puts a placeholder where a page written whole adds one, sign and unit with it', () => {expect(placeholderNumbers('Teams see 40% more, at $49 a month, in 2026.', known)).toBe(`Teams see ${NUMBER_PLACEHOLDER} more, at ${NUMBER_PLACEHOLDER} a month, in 2026.`,diff --git a/server/src/lib/content-writer.js b/server/src/lib/content-writer.jsindex 8893755e8..b811c1b4e 100644--- a/server/src/lib/content-writer.js+++ b/server/src/lib/content-writer.js@@ -18,10 +18,12 @@ import {WRITING_STALE_MS,} from './content-agent.js';import { contentBriefModelId, rebuildSources } from './content-brief.js';+import { inputSources, readDraftInputs } from './content-inputs.js';import { linkAllowList, linkTargetsPrompt, readLinkTargets } from './content-links.js';import { siteTypeLine, pageTypeFormat } from './content-page-types.js';import { authorWords, guardPeople, guardPeopleInHtml, knownPeople } from './content-people.js';import {+ INPUT_RULE,SOURCES_RULE,htmlText,knownNumbers,@@ -253,6 +255,10 @@ export function buildWritePrompt({const of = (kind) => numbered.filter((s) => s.kind === kind);const rules = input.rules.map((r) => `${r.key}: ${r.name}${r.detail ? ` — ${r.detail}` : ''}`);const own = input.textRules.map((text) => `- ${text}`);+ // Brief › Your input, the person's own (CE-048): with what to do with it.+ const given = of('input').map(+ (s) => `${s.id} "${s.label}" (${s.detail})${s.note ? ` — ${s.note}` : ''}`,+ );const page = current? rewritePagePrompt(current): passages@@ -288,7 +294,7 @@ ${list(of('gsc_query').map((s) => `${s.id} "${s.label}"`))}Pages AI cites for these questions today (answer better than them, never copy them):${list(of('cited_page').map((s) => `${s.id} ${s.label}`))}-+${given.length ? `\nYour input, the person's own for this page:\n${given.join('\n')}\n${INPUT_RULE}\n` : ''}Rules (key: rule — what it asks):${list(rules)}${own.length ? `\nThe writer's own rules:\n${own.join('\n')}\n` : ''}${linkTargets ? `\n${linkTargets}\n` : ''}@@ -677,8 +683,9 @@ function startWritingRun(draft, input, rewrite) {/** The run itself, step by step: nothing is kept once it is stopped. */async function writeWithRun({ draft, brand, model, input, budget, rewrite, run }) {await advanceRun(run, 1);- const [prompts, opportunityRes] = await Promise.all([+ const [prompts, inputRow, opportunityRes] = await Promise.all([readPrompts(draft.brand_id, input.sources.promptIds),+ readDraftInputs(draft.id),draft.opportunity_id && !draft.brief? supabaseAdmin.from('content_opportunities')@@ -690,14 +697,16 @@ async function writeWithRun({ draft, brand, model, input, budget, rewrite, run }]);if (opportunityRes.error) throw opportunityRes.error;const brief = briefText(draft.brief, opportunityRes.data?.brief);- // The data it writes from, numbered (CE-033); the numbers a suggestion- // may write unmarked (the page's, the brand's, the brief's, the rules',- // today's), and those a page written whole may (the sources' words too).+ // The data it writes from, numbered (CE-033), Brief › Your input last+ // (CE-048); the numbers a suggestion may write unmarked (the page's, the+ // brand's, the brief's, the rules', today's), and those a page written+ // whole may (the sources' words too).const numbered = numberSources({prompts,fanouts: input.sources.fanouts,pages: input.sources.pages,queries: input.sources.queries,+ inputs: inputSources(inputRow, brand.name),});const known = knownNumbers(htmlText(draft.body_html),diff --git a/server/src/lib/content-writer.test.js b/server/src/lib/content-writer.test.jsindex 669896197..2e3620eae 100644--- a/server/src/lib/content-writer.test.js+++ b/server/src/lib/content-writer.test.js@@ -421,6 +421,50 @@ describe('runDraftWriting on a new page', () => {]);});+ it("writes from Brief › Your input in Quality's second phase, its numbers and people kept (CE-048)", async () => {+ rows.content_draft_inputs = {+ experience: null,+ data: [{ name: 'Survey', rows: [['Teams'], ['1,250']] }],+ ansvisor_data: [],+ quotes: [+ {+ name: 'Ada Lovelace',+ title: 'Head of Research, Acme',+ text: 'We cut our forecast misses in half.',+ sourceUrl: 'https://acme.example/talk',+ },+ ],+ };+ generateObject.mockResolvedValue({+ object: {+ ...page,+ intro: [+ '1,250 teams brew this way. “We cut our forecast misses in half,” says Ada Lovelace.',+ 'Marco Rossi said 3,400 cups a day.',+ ],+ },+ usage: { inputTokens: 10, outputTokens: 20 },+ });+ const before = process.env.CONTENT_QUALITY_PHASE;+ process.env.CONTENT_QUALITY_PHASE = '2';+ try {+ await expect(run(draftRow())).resolves.toEqual({ written: true });+ } finally {+ if (before === undefined) delete process.env.CONTENT_QUALITY_PHASE;+ else process.env.CONTENT_QUALITY_PHASE = before;+ }+ expect(generateObject.mock.calls[0][0].prompt).toContain(+ '"Survey" (Their own data, a table: Teams; 1,250)',+ );+ const written = draftUpdates().find((u) => u.body_html)?.body_html;+ expect(written).toContain(+ '1,250 teams brew this way. “We cut our forecast misses in half,” says Ada Lovelace.',+ );+ // What the person didn't give is still a placeholder.+ expect(written).not.toContain('Marco Rossi');+ expect(written).not.toContain('3,400');+ });+it('leaves a draft marked ready during the run as it is', async () => {finished = null;await expect(run(draftRow())).resolves.toEqual({ skipped: true });diff --git a/web/messages/en.json b/web/messages/en.jsonindex af1f12b19..2763285b2 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3859,7 +3859,8 @@"prompt": "Prompt","fanout": "Fan-out","cited_page": "Cited page",- "gsc_query": "Search Console"+ "gsc_query": "Search Console",+ "input": "Your input"},"sourceMark": "Source {n}: {label}","acceptedToast": "{count, plural, one {Accepted} other {# changes accepted}} · undo any time",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsxindex 55c2f450c..23515d8ab 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx@@ -74,7 +74,7 @@ import {type SuggestionStatus,} from '@/lib/content/suggestions';import { REBUILD_LIMITS, rebuildSources } from '@/lib/content/brief';-import { buildSourceGroups, includedCounts } from '@/lib/content/sources';+import { buildSourceGroups, includedCounts, type DraftSourceKind } from '@/lib/content/sources';import {cleanHtml,formatHtmlSource,@@ -351,13 +351,13 @@ export function DraftEditor({tab: PanelTarget;n: number;/** A source to show in Sources: a "Based on" chip or mark clicked (CE-033). */- source?: Pick<SuggestionSource, 'kind' | 'ref'>;+ source?: { kind: DraftSourceKind; ref: string };/** The brief to build, from the Next step basket's Build brief. */build?: boolean;/** Brief › Your input to show: Quality's Add (CE-048). */input?: boolean;} | null>(null);- const openPanelTab = (tab: PanelTarget, source?: SuggestionSource) => {+ const openPanelTab = (tab: PanelTarget, source?: { kind: DraftSourceKind; ref: string }) => {if (!panelOpen) togglePanel();setTabRequest((prev) => ({tab,@@ -769,7 +769,12 @@ export function DraftEditor({useEffect(() => {attachRef.current = (files) => void attachments.attach(files);onDecide.current = (id, decision) => void decide([id], decision);- onSource.current = (source) => openPanelTab('sources', source);+ // The person's own input opens where they gave it (CE-048): Brief ›+ // Your input, there only with Quality's second phase.+ onSource.current = (source) => {+ if (source.kind !== 'input') openPanelTab('sources', { kind: source.kind, ref: source.ref });+ else if (qualityPhase() >= 2) addInput();+ };});/** "ChatGPT 14× and Perplexity 6×": the platforms quoting a passage, the most first. */@@ -886,6 +891,7 @@ export function DraftEditor({fanout: t('suggestions.sourceKinds.fanout'),cited_page: t('suggestions.sourceKinds.cited_page'),gsc_query: t('suggestions.sourceKinds.gsc_query'),+ input: t('suggestions.sourceKinds.input'),},sourceMark: (n, label) => t('suggestions.sourceMark', { n, label }),sourceTip: sourceRowsdiff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_suggestions.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_suggestions.tsindex e9aaa3dff..2dd004cfc 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_suggestions.ts+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_suggestions.ts@@ -10,7 +10,7 @@ import { Decoration, DecorationSet } from '@tiptap/pm/view';import { cleanHtml } from '@/lib/content/clean-html';import { passageKey } from '@/lib/content/cited-passages';import { normalizeDomain } from '@/lib/citations/classify';-import type { DraftSourceKind } from '@/lib/content/sources';+import type { SuggestionSourceKind } from '@/lib/content/sources';import {growsPastLimit,type DraftSuggestion,@@ -50,7 +50,7 @@ export interface SuggestionLabels {/** "Based on": before the sources a suggestion was written from. */basedOn: string;/** Each kind of source, as a chip names it: "Fan-out", "Cited page"… */- sourceKinds: Record<DraftSourceKind, string>;+ sourceKinds: Record<SuggestionSourceKind, string>;/** "Source 2: …": a mark's label for a screen reader. */sourceMark: (n: number, label: string) => string;/** What the Sources tab knows of a source, on hover ("Cited 12× in AI answers"), or null. */@@ -356,7 +356,7 @@ function el<K extends keyof HTMLElementTagNameMap>(/** Linked words on a card: underlined, the address on hover. */const LINKED = 'underline decoration-dotted underline-offset-2';-/** What opens a source in the Sources tab, from a chip or a mark. */+/** What opens a source in the Sources tab (Brief › Your input for the person's own), from a chip or a mark. */type OpenSource = (source: SuggestionSource) => void;/** A source as a chip names it: a cited page by its site, the others by their words. */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 ee3c7185e..c937e5896 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@@ -4426,6 +4426,39 @@ describe('the side panel', () => {}});+ it("shows the person's own input it was written from, and opens it in Brief (CE-048)", async () => {+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '2';+ try {+ getDraftInputs.mockResolvedValue({+ experience: '',+ data: [{ name: 'Survey', rows: [['Teams'], ['1,250']] }],+ ansvisorData: [],+ quotes: [],+ });+ getContentDraft.mockResolvedValue(traced);+ getDraftSuggestions.mockResolvedValue([+ {+ ...agentSuggestion,+ afterText: '1,250 teams forecast weekly',+ sources: [{ kind: 'input', ref: 'data:1', label: 'Survey' }],+ sourceMarks: [{ start: 0, end: 5, source: 0 }],+ },+ ]);+ await openRules();+ const card = container.querySelector<HTMLElement>('[data-suggestion="n1"]')!;+ expect(card.querySelector('ins')!.textContent).toBe('1,2501 teams forecast weekly');+ expect(card.textContent).toContain('Based on1Your input ·Survey');+ const chip = [...card.querySelectorAll<HTMLButtonElement>('button')].find((b) =>+ b.textContent?.includes('Your input'),+ )!;+ await act(async () => chip.click());+ expect(selectedSegment()).toBe('Brief');+ expect(panel()!.textContent).toContain('Survey · 2 rows');+ } finally {+ delete process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE;+ }+ });+it('marks an insert’s words by its text, found again in the card as drawn', async () => {getContentDraft.mockResolvedValue(traced);getDraftSuggestions.mockResolvedValue([diff --git a/web/src/lib/content/sources.ts b/web/src/lib/content/sources.tsindex 87003b79b..333312e5c 100644--- a/web/src/lib/content/sources.ts+++ b/web/src/lib/content/sources.ts@@ -10,6 +10,13 @@ import { classifyDomain, normalizeDomain, type SourceCategory } from '@/lib/citaexport const DRAFT_SOURCE_KINDS = ['prompt', 'fanout', 'cited_page', 'gsc_query'] as const;export type DraftSourceKind = (typeof DRAFT_SOURCE_KINDS)[number];+/**+ * What an agent's suggestion can be written from: the Sources tab's kinds,+ * and Brief › Your input (Quality spec §6, CE-048), the person's own.+ */+export const SUGGESTION_SOURCE_KINDS = [...DRAFT_SOURCE_KINDS, 'input'] as const;+export type SuggestionSourceKind = (typeof SUGGESTION_SOURCE_KINDS)[number];+/** The sources of the last 30 days, as content_draft_sources reads them. */export const SOURCES_DAYS = 30;/** Search Console queries shown beside the draft, the most clicked first. */diff --git a/web/src/lib/content/suggestions.test.ts b/web/src/lib/content/suggestions.test.tsindex 06f0904ad..ef97dc50f 100644--- a/web/src/lib/content/suggestions.test.ts+++ b/web/src/lib/content/suggestions.test.ts@@ -107,6 +107,14 @@ describe('a suggestion’s sources (00248, CE-033)', () => {expect(suggestionSources([], null, 'x')).toEqual({ sources: null, marks: null });});+ it("keeps Brief › Your input's sources, the person's own (CE-048)", () => {+ const table = { kind: 'input' as const, ref: 'data:1', label: 'Survey' };+ expect(suggestionSources([table], [{ start: 0, end: 5, source: 0 }], '1,250 teams')).toEqual({+ sources: [table],+ marks: [{ start: 0, end: 5, source: 0 }],+ });+ });+it('counts a batch’s sources once: "built from N of your sources"', () => {const s = (sources: DraftSuggestion['sources']) => ({ sources }) as DraftSuggestion;expect(batchSources([s([fanout, page]), s([fanout]), s(null)])).toEqual([fanout, page]);diff --git a/web/src/lib/content/suggestions.ts b/web/src/lib/content/suggestions.tsindex 23e6203cc..6d18437fe 100644--- a/web/src/lib/content/suggestions.ts+++ b/web/src/lib/content/suggestions.ts@@ -11,7 +11,7 @@*/import { safeLinkHref } from './editor';-import { DRAFT_SOURCE_KINDS, type DraftSourceKind } from './sources';+import { SUGGESTION_SOURCE_KINDS, type SuggestionSourceKind } from './sources';export const SUGGESTION_STATUSES = ['open', 'accepted', 'rejected'] as const;export type SuggestionStatus = (typeof SUGGESTION_STATUSES)[number];@@ -46,9 +46,12 @@ export interface DraftSuggestion {sourceMarks?: SourceMark[] | null;}-/** A source a suggestion was written from, keyed as the Sources tab keys its row. */+/**+ * A source a suggestion was written from, keyed as the Sources tab keys its+ * row; Brief › Your input's as content-inputs.js keys them.+ */export interface SuggestionSource {- kind: DraftSourceKind;+ kind: SuggestionSourceKind;ref: string;label: string;}@@ -138,7 +141,7 @@ export function suggestionSources(text: string,): { sources: SuggestionSource[] | null; marks: SourceMark[] | null } {if (!Array.isArray(rawSources)) return { sources: null, marks: null };- const kinds: readonly string[] = DRAFT_SOURCE_KINDS;+ const kinds: readonly string[] = SUGGESTION_SOURCE_KINDS;const sources: SuggestionSource[] = [];// Where each stored source is now, or -1 when it is left out.const at = (rawSources as Partial<SuggestionSource>[]).map((item) => {@@ -151,7 +154,7 @@ export function suggestionSources() {return -1;}- sources.push({ kind: item.kind as DraftSourceKind, ref: item.ref, label: item.label });+ sources.push({ kind: item.kind as SuggestionSourceKind, ref: item.ref, label: item.label });return sources.length - 1;});const marks: SourceMark[] = [];