Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(content): add Brief › Your input, and count the experience, data and quotes the page uses (CE-048, part a) (#1452)

Cihanb1877eb5785f
diff --git a/supabase/migrations/00265_content_draft_inputs.sql b/supabase/migrations/00265_content_draft_inputs.sql
new file mode 100644
index 000000000..c66d04267
--- /dev/null
+++ b/supabase/migrations/00265_content_draft_inputs.sql
@@ -0,0 +1,78 @@
+-- ============================================================================
+-- 00265: Quality phase 2, CE-048 — Brief › Your input
+-- ============================================================================
+-- What only the person can give a page, kept beside its brief (a rebuild
+-- writes the brief over; this stays): their first-hand experience, their
+-- data (rows read from a CSV or Excel file in the browser, or pasted, and
+-- Ansvisor data they chose to use) and expert quotes, each with the
+-- person's name, title, the words as said and where they were said. The
+-- Content Agent writes from them as given and adds nothing beyond them;
+-- E-E-A-T and Trust count them once the page uses them.
+--
+-- One row a draft, read and written by the members of its workspace
+-- (content_draft_member, 00215), as the draft itself is; a write names its
+-- writer as updated_by, as content_rule_sets' do (00214). The sizes match
+-- what the editor keeps (web/src/lib/content/draft-inputs.ts).
+
+create table if not exists public.content_draft_inputs (
+ draft_id uuid primary key references public.content_drafts(id) on delete cascade,
+ experience text check (experience is null or char_length(experience) <= 4000),
+ -- [{ "name": "…", "rows": [["…"]] }]: the tables as read, 5 at most.
+ data jsonb not null default '[]'::jsonb
+ check (
+ jsonb_typeof(data) = 'array'
+ and jsonb_array_length(data) <= 5
+ and octet_length(data::text) <= 65536
+ ),
+ -- [{ "promptId", "prompt", "answers", "mentioned", "asOf", "days" }]: Ansvisor data used, with the day it was used and the days it covers.
+ ansvisor_data jsonb not null default '[]'::jsonb
+ check (
+ jsonb_typeof(ansvisor_data) = 'array'
+ and jsonb_array_length(ansvisor_data) <= 10
+ and octet_length(ansvisor_data::text) <= 16384
+ ),
+ -- [{ "name", "title", "text", "sourceUrl" }]: quotes from real people, word for word.
+ quotes jsonb not null default '[]'::jsonb
+ check (
+ jsonb_typeof(quotes) = 'array'
+ and jsonb_array_length(quotes) <= 10
+ and octet_length(quotes::text) <= 16384
+ ),
+ updated_by uuid references public.profiles(id) on delete set null,
+ updated_at timestamptz not null default now()
+);
+
+create or replace trigger content_draft_inputs_updated_at
+ before update on public.content_draft_inputs
+ for each row execute function public.handle_updated_at();
+
+alter table public.content_draft_inputs enable row level security;
+revoke all on table public.content_draft_inputs from anon;
+grant select, insert, update, delete on table public.content_draft_inputs to authenticated;
+grant all on table public.content_draft_inputs to service_role;
+
+drop policy if exists "content_draft_inputs: member select" on public.content_draft_inputs;
+create policy "content_draft_inputs: member select"
+ on public.content_draft_inputs for select
+ using (public.content_draft_member(draft_id));
+
+drop policy if exists "content_draft_inputs: member insert" on public.content_draft_inputs;
+create policy "content_draft_inputs: member insert"
+ on public.content_draft_inputs for insert
+ with check (public.content_draft_member(draft_id) and updated_by = auth.uid());
+
+drop policy if exists "content_draft_inputs: member update" on public.content_draft_inputs;
+create policy "content_draft_inputs: member update"
+ on public.content_draft_inputs for update
+ using (public.content_draft_member(draft_id))
+ with check (public.content_draft_member(draft_id) and updated_by = auth.uid());
+
+drop policy if exists "content_draft_inputs: member delete" on public.content_draft_inputs;
+create policy "content_draft_inputs: member delete"
+ on public.content_draft_inputs for delete
+ using (public.content_draft_member(draft_id));
+
+comment on table public.content_draft_inputs is
+ 'Quality CE-048 (00265): Brief › Your input — a draft''s first-hand experience, data and expert quotes, as the person gave them. The Content Agent writes from them and adds nothing beyond them.';
+
+notify pgrst, 'reload schema';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 8bb7f2630..3a98ba4e9 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -38348,3 +38348,85 @@ grant execute on function public.content_draft_keep_source(uuid, text) to authen
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00265_content_draft_inputs.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00265: Quality phase 2, CE-048 — Brief › Your input
+-- ============================================================================
+-- What only the person can give a page, kept beside its brief (a rebuild
+-- writes the brief over; this stays): their first-hand experience, their
+-- data (rows read from a CSV or Excel file in the browser, or pasted, and
+-- Ansvisor data they chose to use) and expert quotes, each with the
+-- person's name, title, the words as said and where they were said. The
+-- Content Agent writes from them as given and adds nothing beyond them;
+-- E-E-A-T and Trust count them once the page uses them.
+--
+-- One row a draft, read and written by the members of its workspace
+-- (content_draft_member, 00215), as the draft itself is; a write names its
+-- writer as updated_by, as content_rule_sets' do (00214). The sizes match
+-- what the editor keeps (web/src/lib/content/draft-inputs.ts).
+
+create table if not exists public.content_draft_inputs (
+ draft_id uuid primary key references public.content_drafts(id) on delete cascade,
+ experience text check (experience is null or char_length(experience) <= 4000),
+ -- [{ "name": "…", "rows": [["…"]] }]: the tables as read, 5 at most.
+ data jsonb not null default '[]'::jsonb
+ check (
+ jsonb_typeof(data) = 'array'
+ and jsonb_array_length(data) <= 5
+ and octet_length(data::text) <= 65536
+ ),
+ -- [{ "promptId", "prompt", "answers", "mentioned", "asOf", "days" }]: Ansvisor data used, with the day it was used and the days it covers.
+ ansvisor_data jsonb not null default '[]'::jsonb
+ check (
+ jsonb_typeof(ansvisor_data) = 'array'
+ and jsonb_array_length(ansvisor_data) <= 10
+ and octet_length(ansvisor_data::text) <= 16384
+ ),
+ -- [{ "name", "title", "text", "sourceUrl" }]: quotes from real people, word for word.
+ quotes jsonb not null default '[]'::jsonb
+ check (
+ jsonb_typeof(quotes) = 'array'
+ and jsonb_array_length(quotes) <= 10
+ and octet_length(quotes::text) <= 16384
+ ),
+ updated_by uuid references public.profiles(id) on delete set null,
+ updated_at timestamptz not null default now()
+);
+
+create or replace trigger content_draft_inputs_updated_at
+ before update on public.content_draft_inputs
+ for each row execute function public.handle_updated_at();
+
+alter table public.content_draft_inputs enable row level security;
+revoke all on table public.content_draft_inputs from anon;
+grant select, insert, update, delete on table public.content_draft_inputs to authenticated;
+grant all on table public.content_draft_inputs to service_role;
+
+drop policy if exists "content_draft_inputs: member select" on public.content_draft_inputs;
+create policy "content_draft_inputs: member select"
+ on public.content_draft_inputs for select
+ using (public.content_draft_member(draft_id));
+
+drop policy if exists "content_draft_inputs: member insert" on public.content_draft_inputs;
+create policy "content_draft_inputs: member insert"
+ on public.content_draft_inputs for insert
+ with check (public.content_draft_member(draft_id) and updated_by = auth.uid());
+
+drop policy if exists "content_draft_inputs: member update" on public.content_draft_inputs;
+create policy "content_draft_inputs: member update"
+ on public.content_draft_inputs for update
+ using (public.content_draft_member(draft_id))
+ with check (public.content_draft_member(draft_id) and updated_by = auth.uid());
+
+drop policy if exists "content_draft_inputs: member delete" on public.content_draft_inputs;
+create policy "content_draft_inputs: member delete"
+ on public.content_draft_inputs for delete
+ using (public.content_draft_member(draft_id));
+
+comment on table public.content_draft_inputs is
+ 'Quality CE-048 (00265): Brief › Your input — a draft''s first-hand experience, data and expert quotes, as the person gave them. The Content Agent writes from them and adds nothing beyond them.';
+
+notify pgrst, 'reload schema';
+
diff --git a/web/messages/en.json b/web/messages/en.json
index 08820cb91..cdd603617 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -4545,6 +4545,49 @@
"markReady": "Mark ready",
"markReadyAnyway": "Mark ready anyway"
},
+ "yourInput": {
+ "title": "Your input",
+ "usedAsWritten": "used only as you write it",
+ "save": "Save",
+ "saveFailed": "Couldn't save your input. Try again.",
+ "removeNamed": "Remove {name}",
+ "loadError": "Couldn't read your input.",
+ "retry": "Try again",
+ "experience": {
+ "label": "Your experience",
+ "placeholder": "What did you test or use? What happened? A customer story?",
+ "count": "{count, number} / {max, number}"
+ },
+ "data": {
+ "label": "Your data",
+ "offer": "From your Ansvisor data: in {answers, plural, one {# answer} other {# answers}} to “{prompt}” over the last {days, number} days, {mentioned, plural, =0 {you weren't named} one {you were named once} other {you were named # times}}.",
+ "ansvisor": "In {answers, plural, one {# answer} other {# answers}} to “{prompt}” over the last {days, number} days, {mentioned, plural, =0 {you weren't named} one {you were named once} other {you were named # times}}.",
+ "cited": "Cited as “Ansvisor data, {month}”.",
+ "use": "Use this",
+ "upload": "Upload CSV or Excel",
+ "paste": "Or paste numbers, one row a line, separated by commas",
+ "addPasted": "Add these numbers",
+ "pastedName": "Pasted numbers",
+ "rows": "{count, plural, one {# row} other {# rows}}",
+ "empty": "{name} has no rows to use.",
+ "trimmed": "{name} is kept to its first {count, plural, one {# row} other {# rows}}: that is what fits beside your other data.",
+ "full": "Your data is full. Remove a table to add another.",
+ "tooLarge": "{name} is over 10 MB.",
+ "unsupported": "{name} isn't a CSV or Excel (.xlsx) file."
+ },
+ "quotes": {
+ "label": "Expert quotes",
+ "name": "Name",
+ "title": "Title and company",
+ "text": "The quote, word for word",
+ "sourceUrl": "Source link (https://…)",
+ "source": "Source",
+ "realOnly": "Add quotes from real people only.",
+ "full": "Your quotes are full. Remove one, or shorten this one, to add it.",
+ "add": "Add quote"
+ },
+ "guard": "Content Agent never makes things up. No invented people, quotes, customer stories, test results or numbers. If something is missing, it leaves a [placeholder] for you."
+ },
"quality": {
"scores": "Quality scores",
"names": {
@@ -4571,6 +4614,27 @@
"addAuthor": "Add author",
"editAuthor": "Edit author",
"todos": {
+ "experience": {
+ "title": "Add your own experience",
+ "next": "add your own experience",
+ "detail": "What you tested or used, and what happened: the agent writes from it as you give it, and adds nothing to it",
+ "given": "It's in Your input, but the page doesn't use it yet: write it in, or let the agent write from it",
+ "done": "The page uses your experience"
+ },
+ "originalData": {
+ "title": "Add your own data",
+ "next": "add your own data",
+ "detail": "Your numbers, or Ansvisor data on this page's prompts: the page cites them as yours",
+ "given": "It's in Your input, but the page uses none of its numbers yet",
+ "done": "The page uses your data"
+ },
+ "expertQuote": {
+ "title": "Add an expert's quote",
+ "next": "add an expert's quote",
+ "detail": "A real person's words as said, with their name, title and where they said them",
+ "given": "It's in Your input, but the page doesn't quote it word for word yet",
+ "done": "The page quotes an expert word for word"
+ },
"title": "Your to-dos",
"left": "{count, plural, =0 {All done} other {# left · only you can do these}}",
"done": "Done",
@@ -4622,7 +4686,8 @@
"showPlaceholder": "Show now",
"pickAuthor": "Pick now",
"addAuthor": "Add now",
- "editAuthor": "Edit now"
+ "editAuthor": "Edit now",
+ "addInput": "Add now"
},
"later": "Later"
},
@@ -4632,6 +4697,7 @@
"gain": "+{gain, number} {score}",
"band": "{score, number}, {band}",
"show": "Show",
+ "addInput": "Add",
"keep": "Keep",
"keepFailed": "Couldn't keep the source. Try again.",
"keepFull": "This page keeps 50 sources already: replace one instead.",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx
index 8a3d9cf30..f3b98fa40 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
@@ -96,6 +96,7 @@ import {
} from '@/lib/content/ready-to-publish';
import { detectPageType, isSiteType, type SiteType } from '@/lib/content/page-types';
import { BAND_CLASSES, qualityAverage, qualityBand, qualityPhase } from '@/lib/content/quality';
+import { inputsGiven, inputsUsed } from '@/lib/content/draft-inputs';
import { eeat, linksToCheck, trust, trustBlocks } from '@/lib/content/quality-checks';
import { qualityTodos } from '@/lib/content/quality-todos';
import { readability } from '@/lib/content/readability';
@@ -169,6 +170,7 @@ import {
type SuggestionLabels,
} from './_suggestions';
import { ONE_H1_AS_IS, OneH1 } from './_one-h1';
+import { useDraftInputs } from './_use-draft-inputs';
import { useDraftReads } from './_use-draft-reads';
import { useDraftRules } from './_use-draft-rules';
import { EditorToolbar } from './_toolbar';
@@ -345,6 +347,8 @@ export function DraftEditor({
source?: Pick<SuggestionSource, 'kind' | 'ref'>;
/** 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) => {
if (!panelOpen) togglePanel();
@@ -506,14 +510,25 @@ export function DraftEditor({
const brandName =
authorsRead?.brands.find((b) => b.id === draft.brandId)?.name ?? storeBrandName ?? '';
const pageAuthor = authorsRead?.authors.find((a) => a.id === authorId) ?? null;
- // E-E-A-T from the author, Trust from the page's figures and links (their
- // reads from the API): with Readability, the scores and the header chip's
- // average (CE-039).
+ const pageBlocks = useMemo(() => (qualityOn ? trustBlocks(pageHtml) : []), [qualityOn, pageHtml]);
+ // Brief › Your input (CE-048), with Quality's second phase: what the page
+ // uses of it counts once it is read.
+ // In that phase the scores wait for it; a read that failed leaves them
+ // without it, and Brief offers to read it again.
+ const inputsRead = useDraftInputs(draft.id, qualityPhase() >= 2);
+ const inputs = inputsRead.status === 'ready' ? inputsRead.inputs : null;
+ const inputsPending = inputsRead.status === 'loading';
+ const used = useMemo(
+ () => (inputs ? inputsUsed(pageBlocks.map((b) => b.text).join('\n'), inputs) : null),
+ [inputs, pageBlocks],
+ );
+ // E-E-A-T from the author (and, in phase 2, the person's experience and
+ // data), Trust from the page's figures and links (their reads from the
+ // API): with Readability, the scores and the header chip's average (CE-039).
const eeatScore = useMemo(
- () => (qualityOn && authorsRead ? eeat({ author: pageAuthor }) : null),
- [qualityOn, authorsRead, pageAuthor],
+ () => (qualityOn && authorsRead && !inputsPending ? eeat({ author: pageAuthor, used }) : null),
+ [qualityOn, authorsRead, inputsPending, pageAuthor, used],
);
- const pageBlocks = useMemo(() => (qualityOn ? trustBlocks(pageHtml) : []), [qualityOn, pageHtml]);
const { checks: linkChecks, pending: linksPending } = useLinkChecks(
draft.id,
autosave.savedAt,
@@ -552,17 +567,18 @@ export function DraftEditor({
// The brand's own links aren't sources: Trust waits for its domains.
const trustScore = useMemo(
() =>
- qualityOn && brandDomains
+ qualityOn && brandDomains && !inputsPending
? trust({
blocks: pageBlocks,
links: linkChecks,
brandDomains,
siteTrust,
+ quote: used ? used.quote : null,
sources: sourceRead,
now: Date.now(),
})
: null,
- [qualityOn, pageBlocks, linkChecks, brandDomains, siteTrust, sourceRead],
+ [qualityOn, pageBlocks, linkChecks, brandDomains, siteTrust, inputsPending, used, sourceRead],
);
// Their links underlined in the draft, Quality's suggestion naming them.
const weakKey = (trustScore?.weak ?? []).map((w) => w.url).join('\n');
@@ -621,6 +637,9 @@ export function DraftEditor({
hasAuthors,
canEdit: canEditPageAuthor,
placeholders: { count: placeholderCount, had: hadPlaceholders },
+ used,
+ given: inputs ? inputsGiven(inputs) : null,
+ trust: trustScore,
})
: [];
const quality: QualityRead | null = qualityOn
@@ -639,6 +658,11 @@ export function DraftEditor({
: null;
// Quality's Pick author opens the header's menu.
const [authorMenuOpen, setAuthorMenuOpen] = useState(false);
+ // Quality's Add opens Brief › Your input.
+ const addInput = () => {
+ if (!panelOpen) togglePanel();
+ setTabRequest((prev) => ({ tab: 'brief', n: (prev?.n ?? 0) + 1, input: true }));
+ };
const nudge = useNextNudge(draft.id, todos);
const { at: nudgeAt } = nudge;
// The author's to-dos wait for E-E-A-T: the nudge waits for them.
@@ -2443,6 +2467,7 @@ export function DraftEditor({
quality={quality}
onShowPlaceholder={showFirstPlaceholder}
onPickAuthor={() => setAuthorMenuOpen(true)}
+ onAddInput={addInput}
onLater={nudge.later}
onAct={nudge.close}
/>
@@ -2480,6 +2505,8 @@ export function DraftEditor({
onShowInPage={showInPage}
onShowPlaceholder={showFirstPlaceholder}
onPickAuthor={() => setAuthorMenuOpen(true)}
+ yourInput={inputsRead.status === 'off' ? null : inputsRead}
+ onAddInput={addInput}
onKeepSource={sourcesOn ? (url) => void keepSource(url) : undefined}
/>
) : (
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-nudge.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-nudge.test.tsx
index 09469ae3f..493169dcc 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-nudge.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-nudge.test.tsx
@@ -36,8 +36,20 @@ const ada: ContentAuthor = {
defaultFor: [],
pages: null,
};
-const pick: QualityTodo = { id: 'byline', done: false, gain: 60, action: 'pickAuthor' };
-const profile: QualityTodo = { id: 'authorProfile', done: false, gain: 40, action: 'editAuthor' };
+const pick: QualityTodo = {
+ id: 'byline',
+ done: false,
+ gain: 60,
+ score: 'eeat',
+ action: 'pickAuthor',
+};
+const profile: QualityTodo = {
+ id: 'authorProfile',
+ done: false,
+ gain: 40,
+ score: 'eeat',
+ action: 'editAuthor',
+};
let container: HTMLDivElement;
let root: Root;
@@ -111,6 +123,7 @@ describe('NextNudge', () => {
id: 'placeholders',
done: false,
gain: 0,
+ score: 'eeat',
action: 'showPlaceholder',
count: 2,
};
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-nudge.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-nudge.tsx
index 18cbf2e5d..382a4f4fd 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-nudge.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-nudge.tsx
@@ -89,6 +89,7 @@ export function NextNudge({
quality,
onShowPlaceholder,
onPickAuthor,
+ onAddInput,
onLater,
onAct,
}: {
@@ -97,6 +98,8 @@ export function NextNudge({
/** Selects the page's first placeholder, to type over. */
onShowPlaceholder: () => void;
onPickAuthor: () => void;
+ /** Opens Brief › Your input (CE-048). */
+ onAddInput?: () => void;
onLater: () => void;
/** It was acted on: it goes. */
onAct: () => void;
@@ -150,6 +153,19 @@ export function NextNudge({
>
{t('act.pickAuthor')}
</button>
+ ) : action === 'addInput' ? (
+ onAddInput && (
+ <button
+ type="button"
+ className={actClass}
+ onClick={() => {
+ onAct();
+ onAddInput();
+ }}
+ >
+ {t('act.addInput')}
+ </button>
+ )
) : (
action && (
<Link href={MANAGE_AUTHORS_PATH} className={actClass} onClick={onAct}>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-step.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-step.test.tsx
index 505cd6d13..fa7f98e1b 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-step.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_next-step.test.tsx
@@ -139,7 +139,7 @@ describe('NextStepButton', () => {
quality: {
trust: 54,
trustLow: true,
- todos: [{ id: 'byline', done: false, gain: 15, action: 'pickAuthor' }],
+ todos: [{ id: 'byline', done: false, gain: 15, score: 'eeat', action: 'pickAuthor' }],
},
}),
{ todoLine: "pick the page's author" },
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_quality-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_quality-tab.test.tsx
index 539aafa98..4f28ce397 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_quality-tab.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_quality-tab.test.tsx
@@ -88,6 +88,7 @@ let root: Root;
const onShow = vi.fn();
const onPickAuthor = vi.fn();
const onShowPlaceholder = vi.fn();
+const onAddInput = vi.fn();
const onKeep = vi.fn();
async function render(quality: QualityRead | Readability | null) {
@@ -100,6 +101,7 @@ async function render(quality: QualityRead | Readability | null) {
onShow={onShow}
onShowPlaceholder={onShowPlaceholder}
onPickAuthor={onPickAuthor}
+ onAddInput={onAddInput}
onKeep={onKeep}
/>
</NextIntlClientProvider>,
@@ -256,6 +258,45 @@ describe('QualityTab', () => {
expect(done.querySelector('button')).toBeNull();
});
+ it('asks for what only the person can give, each with Add, and its gain (CE-048)', async () => {
+ const none = { experience: false, data: false, quote: false };
+ const score = eeat({ author: ada, used: none });
+ const trustScore = trust({
+ blocks: trustBlocks('<p>Up 40% (<a href="https://src.example/">source</a>).</p>'),
+ links: new Map(),
+ brandDomains: [],
+ quote: false,
+ now: Date.parse('2026-10-24T12:00:00Z'),
+ });
+ await render({
+ ...read(result),
+ eeat: score,
+ trust: trustScore,
+ todos: qualityTodos({
+ eeat: score,
+ author: ada,
+ hasAuthors: true,
+ canEdit: true,
+ used: none,
+ given: { experience: true, data: false, quote: false },
+ trust: trustScore,
+ }),
+ });
+ const rows = [...container.querySelectorAll('[aria-label="Your to-dos"] li')].map(
+ (li) => li.textContent,
+ );
+ expect(rows.slice(2)).toEqual([
+ "Add your own experience · To doIt's in Your input, but the page doesn't use it yet: write it in, or let the agent write from it · +33 E-E-A-TAdd",
+ "Add your own data · To doYour numbers, or Ansvisor data on this page's prompts: the page cites them as yours · +25 E-E-A-TAdd",
+ "Add an expert's quote · To doA real person's words as said, with their name, title and where they said them · +21 TrustAdd",
+ ]);
+ const add = [...container.querySelectorAll('[aria-label="Your to-dos"] li')]
+ .find((li) => li.textContent?.startsWith('Add your own data'))!
+ .querySelector('button')!;
+ await act(async () => add.click());
+ expect(onAddInput).toHaveBeenCalled();
+ });
+
it("says who can complete the profile when the reader can't edit the author", async () => {
await render(read(result, { ...ada, bio: null }, true, false));
const row = [...container.querySelectorAll('li')].find((li) =>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_quality-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_quality-tab.tsx
index 38c4e31b7..c63e9f5f4 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_quality-tab.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_quality-tab.tsx
@@ -77,6 +77,7 @@ export function QualityTab({
onShow,
onShowPlaceholder,
onPickAuthor,
+ onAddInput,
onKeep,
}: {
quality: QualityRead;
@@ -86,6 +87,8 @@ export function QualityTab({
onShowPlaceholder: () => void;
/** Opens the header's author menu. */
onPickAuthor: () => void;
+ /** Opens Brief › Your input (CE-048). */
+ onAddInput?: () => void;
/** Keeps a weak source or a competitor's on the page (CE-046). */
onKeep?: (url: string) => void;
}) {
@@ -155,6 +158,7 @@ export function QualityTab({
quality={quality}
onShowPlaceholder={onShowPlaceholder}
onPickAuthor={onPickAuthor}
+ onAddInput={onAddInput}
/>
))}
</ul>
@@ -262,6 +266,18 @@ export function useTodoCopy() {
: t('byline.detail.pickAuthor', { byline: team }),
};
}
+ // What only the person can give (Brief › Your input, CE-048).
+ if (todo.id === 'experience' || todo.id === 'originalData' || todo.id === 'expertQuote') {
+ return {
+ title: t(`${todo.id}.title`),
+ next: t(`${todo.id}.next`),
+ detail: todo.done
+ ? t(`${todo.id}.done`)
+ : todo.given
+ ? t(`${todo.id}.given`)
+ : t(`${todo.id}.detail`),
+ };
+ }
if (!author) {
return {
title: t('authorProfile.titleNoAuthor'),
@@ -296,11 +312,13 @@ function TodoRow({
quality,
onShowPlaceholder,
onPickAuthor,
+ onAddInput,
}: {
todo: QualityTodo;
quality: QualityRead;
onShowPlaceholder: () => void;
onPickAuthor: () => void;
+ onAddInput?: () => void;
}) {
const t = useTranslations('contentEditor.editor.quality');
const { title, detail } = useTodoCopy()(todo, quality);
@@ -346,7 +364,7 @@ function TodoRow({
<>
{' · '}
<span className="font-medium whitespace-nowrap text-emerald-700 tabular-nums dark:text-emerald-300">
- {t('gain', { gain: todo.gain, score: t('names.eeat') })}
+ {t('gain', { gain: todo.gain, score: t(`names.${todo.score}`) })}
</span>
</>
)}
@@ -358,6 +376,12 @@ function TodoRow({
<Button variant="outline" size="sm" className="h-7 shrink-0" onClick={onShowPlaceholder}>
{t('show')}
</Button>
+ ) : todo.action === 'addInput' ? (
+ onAddInput && (
+ <Button variant="outline" size="sm" className="h-7 shrink-0" onClick={onAddInput}>
+ {t('addInput')}
+ </Button>
+ )
) : todo.action === 'pickAuthor' ? (
<Button variant="outline" size="sm" className="h-7 shrink-0" onClick={onPickAuthor}>
{t('pickAuthor')}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx
index adee0cdae..314f9d630 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_side-panel.tsx
@@ -17,8 +17,10 @@ import { QualityTab, type QualityRead } from './_quality-tab';
import { RulesTab, type AgentFix, type PageRewrite } from './_rules-tab';
import { SourcesTab } from './_sources-tab';
import { useBriefRebuild, type PageNow } from './_use-brief-rebuild';
+import type { DraftInputsRead } from './_use-draft-inputs';
import type { DraftReads } from './_use-draft-reads';
import type { DraftRulesState } from './_use-draft-rules';
+import { YourInput, type InputPrompt } from './_your-input';
/** Remembers whether the panel is open, across drafts and visits. */
const PANEL_OPEN_KEY = 'aeo:content-editor-panel';
@@ -127,6 +129,8 @@ export function EditorSidePanel({
onShowInPage,
onShowPlaceholder,
onPickAuthor,
+ yourInput = null,
+ onAddInput,
onKeepSource,
}: {
draft: ContentDraft;
@@ -150,6 +154,8 @@ export function EditorSidePanel({
source?: { kind: DraftSourceKind; ref: string };
/** The brief to build (the Next step basket's Build brief). */
build?: boolean;
+ /** Brief › Your input to show (Quality's Add, CE-048). */
+ input?: boolean;
} | null;
/** Run Agent's Fix open rules, for Rules (CE-018, v1.1 CE-029). */
agentFix?: AgentFix;
@@ -177,6 +183,10 @@ export function EditorSidePanel({
onShowPlaceholder?: () => void;
/** Opens the header's author menu: Quality's Pick author. */
onPickAuthor?: () => void;
+ /** Brief › Your input (CE-048), with Quality's second phase. */
+ yourInput?: DraftInputsRead | null;
+ /** Opens Brief › Your input: Quality's Add. */
+ onAddInput?: () => void;
/** Keeps a weak source or a competitor's on the page (Quality CE-046), once phase 2 is live. */
onKeepSource?: (url: string) => void;
}) {
@@ -219,6 +229,16 @@ export function EditorSidePanel({
: null,
[reads.sources, title, draft.sourceUrl],
);
+ // Ansvisor data Your input offers: the draft's prompts with answers, those
+ // it targets first, the most answered first.
+ const inputPrompts = useMemo<InputPrompt[]>(
+ () =>
+ (reads.sources?.data?.prompts ?? [])
+ .filter((p) => p.answers > 0)
+ .sort((a, b) => Number(b.inDraft) - Number(a.inDraft) || b.answers - a.answers)
+ .map(({ id, text, answers, mentioned }) => ({ id, text, answers, mentioned })),
+ [reads.sources],
+ );
const sourcesInUse = sourceCounts ? Object.values(sourceCounts).reduce((a, b) => a + b, 0) : null;
const dataLine = sourceCounts && (
<UsesYourData counts={sourceCounts} onEdit={() => open('sources')} />
@@ -371,7 +391,24 @@ export function EditorSidePanel({
))}
</div>
{briefOpened && (
- <div hidden={segment !== 'brief'}>
+ <div hidden={segment !== 'brief'} className="space-y-4">
+ {yourInput?.status === 'ready' && (
+ <YourInput
+ inputs={yourInput.inputs}
+ prompts={inputPrompts}
+ onChange={yourInput.change}
+ // Once Brief shows: a hidden block can't be scrolled to.
+ scrollRequest={tabRequest?.input && segment === 'brief' ? tabRequest.n : null}
+ />
+ )}
+ {yourInput?.status === 'failed' && (
+ <p className="flex items-center gap-2 text-xs text-muted-foreground">
+ {tEditor('yourInput.loadError')}
+ <button type="button" className="font-medium underline" onClick={yourInput.retry}>
+ {tEditor('yourInput.retry')}
+ </button>
+ </p>
+ )}
<BriefTab
draftId={draft.id}
state={reads.brief}
@@ -396,6 +433,7 @@ export function EditorSidePanel({
onShow={(text) => onShowInPage?.(text)}
onShowPlaceholder={() => onShowPlaceholder?.()}
onPickAuthor={() => onPickAuthor?.()}
+ onAddInput={onAddInput}
onKeep={onKeepSource}
/>
</div>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-inputs.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-inputs.test.tsx
new file mode 100644
index 000000000..c6dc93d58
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-inputs.test.tsx
@@ -0,0 +1,119 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../../../../../../messages/en.json';
+import { NO_INPUTS, type DraftInputs } from '@/lib/content/draft-inputs';
+
+const getDraftInputs = vi.hoisted(() => vi.fn());
+const saveDraftInputs = vi.hoisted(() => vi.fn());
+vi.mock('@/lib/actions/content-draft-inputs', () => ({ getDraftInputs, saveDraftInputs }));
+const toast = vi.hoisted(() => Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn() }));
+vi.mock('sonner', () => ({ toast }));
+
+const { useDraftInputs } = await import('./_use-draft-inputs');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+/** Brief › Your input as the editor holds it (CE-048): read once, each change kept. */
+
+const DRAFT = '2f1d1c52-0f7a-4c1e-9b8a-5d6e7f8a9b0c';
+const KEPT: DraftInputs = { ...NO_INPUTS, experience: 'We tested it.' };
+/** Each change adds a mark to the experience as it is when the change lands. */
+const MARK = (current: DraftInputs) => ({ ...current, experience: `${current.experience}+` });
+
+let container: HTMLDivElement;
+let root: Root;
+
+/** Shows what the hook holds; its button makes a change, or reads again after a failed read. */
+function Probe({ on }: { on: boolean }) {
+ const read = useDraftInputs(DRAFT, on);
+ return (
+ <button
+ type="button"
+ data-read={JSON.stringify(read.status === 'ready' ? read.inputs : read.status)}
+ onClick={() => {
+ if (read.status === 'ready') read.change(MARK);
+ if (read.status === 'failed') read.retry();
+ }}
+ />
+ );
+}
+
+async function render(on: boolean) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <Probe on={on} />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+const held = () => JSON.parse(container.querySelector('button')!.getAttribute('data-read')!);
+const click = () => act(async () => container.querySelector('button')!.click());
+
+beforeEach(() => {
+ getDraftInputs.mockReset().mockResolvedValue(KEPT);
+ saveDraftInputs.mockReset().mockImplementation(async (_id, inputs) => inputs);
+ toast.error.mockReset();
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ container = document.createElement('div');
+ root = createRoot(container);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ vi.mocked(console.error).mockRestore();
+});
+
+describe('useDraftInputs', () => {
+ it("isn't read before Quality's second phase", async () => {
+ await render(false);
+ expect(getDraftInputs).not.toHaveBeenCalled();
+ expect(held()).toBe('off');
+ });
+
+ it('reads the input once, and makes each change to it as it is then', async () => {
+ await render(true);
+ expect(getDraftInputs).toHaveBeenCalledWith(DRAFT);
+ expect(held()).toEqual(KEPT);
+
+ await click();
+ await click();
+ expect(held()).toEqual({ ...KEPT, experience: 'We tested it.++' });
+ expect(saveDraftInputs).toHaveBeenLastCalledWith(DRAFT, {
+ ...KEPT,
+ experience: 'We tested it.++',
+ });
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+
+ it("says when a change can't be kept, and reads the input as kept again", async () => {
+ await render(true);
+ saveDraftInputs.mockRejectedValueOnce(new Error('denied'));
+ await click();
+ expect(toast.error).toHaveBeenCalledWith("Couldn't save your input. Try again.");
+ expect(getDraftInputs).toHaveBeenCalledTimes(2);
+ expect(held()).toEqual(KEPT);
+ });
+
+ it('keeps a change made since over that read', async () => {
+ await render(true);
+ let answer: (read: DraftInputs) => void = () => {};
+ getDraftInputs.mockImplementationOnce(() => new Promise((resolve) => (answer = resolve)));
+ saveDraftInputs.mockRejectedValueOnce(new Error('denied'));
+ await click();
+ await click();
+ await act(async () => answer(KEPT));
+ expect(held()).toEqual({ ...KEPT, experience: 'We tested it.++' });
+ });
+
+ it("says when it can't be read, and reads it again on Try again", async () => {
+ getDraftInputs.mockRejectedValueOnce(new Error('offline'));
+ await render(true);
+ expect(held()).toBe('failed');
+ await click();
+ expect(getDraftInputs).toHaveBeenCalledTimes(2);
+ expect(held()).toEqual(KEPT);
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-inputs.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-inputs.ts
new file mode 100644
index 000000000..4e276068f
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-inputs.ts
@@ -0,0 +1,87 @@
+'use client';
+
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { getDraftInputs, saveDraftInputs } from '@/lib/actions/content-draft-inputs';
+import type { DraftInputs } from '@/lib/content/draft-inputs';
+
+/** A change to the input, made to it as it is when the change lands. */
+export type InputsUpdate = (current: DraftInputs) => DraftInputs;
+
+export type DraftInputsRead =
+ | { status: 'off' | 'loading' }
+ | { status: 'ready'; inputs: DraftInputs; change: (update: InputsUpdate) => void }
+ | { status: 'failed'; retry: () => void };
+
+/**
+ * A draft's Brief › Your input (CE-048), read once when the editor opens
+ * with Quality's second phase: Brief shows it, E-E-A-T and Trust count what
+ * the page uses of it.
+ *
+ * A change is made to the input as it is when it lands (a file read
+ * meanwhile, or a card used, isn't lost), shows at once and is kept as a
+ * whole. One that can't be kept says so and reads the input as kept again;
+ * a change made since wins over that read. Server actions run one after
+ * another, so the read comes after every save before it.
+ */
+export function useDraftInputs(draftId: string, on: boolean): DraftInputsRead {
+ const t = useTranslations('contentEditor.editor.yourInput');
+ const [inputs, setInputs] = useState<DraftInputs | null>(null);
+ const [failed, setFailed] = useState(false);
+ const [attempt, setAttempt] = useState(0);
+ const latest = useRef<DraftInputs | null>(null);
+ const changes = useRef(0);
+
+ useEffect(() => {
+ if (!on) return;
+ let live = true;
+ getDraftInputs(draftId)
+ .then((read) => {
+ if (!live) return;
+ latest.current = read;
+ setInputs(read);
+ setFailed(false);
+ })
+ .catch((err) => {
+ console.error('Failed to read the input:', err);
+ if (live) setFailed(true);
+ });
+ return () => {
+ live = false;
+ };
+ }, [draftId, on, attempt]);
+
+ const change = useCallback(
+ (update: InputsUpdate) => {
+ const current = latest.current;
+ if (!current) return;
+ const next = update(current);
+ if (next === current) return;
+ latest.current = next;
+ changes.current += 1;
+ setInputs(next);
+ saveDraftInputs(draftId, next).catch((err) => {
+ console.error('Failed to save the input:', err);
+ toast.error(t('saveFailed'));
+ const at = changes.current;
+ getDraftInputs(draftId)
+ .then((read) => {
+ if (changes.current !== at) return;
+ latest.current = read;
+ setInputs(read);
+ })
+ .catch((readErr) => console.error('Failed to read the input:', readErr));
+ });
+ },
+ [draftId, t],
+ );
+ const retry = useCallback(() => {
+ setFailed(false);
+ setAttempt((n) => n + 1);
+ }, []);
+
+ if (!on) return { status: 'off' };
+ if (inputs) return { status: 'ready', inputs, change };
+ return failed ? { status: 'failed', retry } : { status: 'loading' };
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_your-input.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_your-input.test.tsx
new file mode 100644
index 000000000..a1d5ee03b
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_your-input.test.tsx
@@ -0,0 +1,303 @@
+import { act, useRef, useState } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../../../../../../messages/en.json';
+import { NO_INPUTS, type DraftInputs } from '@/lib/content/draft-inputs';
+import type { InputsUpdate } from './_use-draft-inputs';
+import { YourInput, type InputPrompt } from './_your-input';
+
+const toast = vi.hoisted(() => Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn() }));
+vi.mock('sonner', () => ({ toast }));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+// jsdom's files can't be read as text, as browsers' can.
+if (!('text' in Blob.prototype)) {
+ Object.assign(Blob.prototype, {
+ text(this: Blob) {
+ return new Promise<string>((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(reader.result as string);
+ reader.onerror = () => reject(reader.error);
+ reader.readAsText(this);
+ });
+ },
+ });
+}
+
+/** Brief › Your input (Quality spec §6, CE-048): what only the person can give. */
+
+const PROMPTS: InputPrompt[] = [
+ {
+ id: '5e8cd4c2-2bc4-4fb7-8711-bc0ad1bb4a29',
+ text: 'best pour-over grinder',
+ answers: 825,
+ mentioned: 28,
+ },
+ {
+ id: '0b7d0c43-6f1e-4b8e-9d0a-2f6b1c2f3e4d',
+ text: 'quiet coffee grinder',
+ answers: 12,
+ mentioned: 0,
+ },
+];
+
+let container: HTMLDivElement;
+let root: Root;
+const changes: DraftInputs[] = [];
+
+/** Makes each change to the input as it is then, as the editor does, so the block shows it. */
+function Harness({ initial, scrollRequest }: { initial: DraftInputs; scrollRequest?: number }) {
+ const [inputs, setInputs] = useState(initial);
+ const latest = useRef(initial);
+ const change = (update: InputsUpdate) => {
+ const next = update(latest.current);
+ if (next === latest.current) return;
+ latest.current = next;
+ changes.push(next);
+ setInputs(next);
+ };
+ return (
+ <YourInput
+ inputs={inputs}
+ prompts={PROMPTS}
+ scrollRequest={scrollRequest ?? null}
+ onChange={change}
+ />
+ );
+}
+
+async function render(initial: DraftInputs = NO_INPUTS, scrollRequest?: number) {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <Harness initial={initial} scrollRequest={scrollRequest} />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+const setValue = (el: HTMLInputElement | HTMLTextAreaElement, value: string) => {
+ const proto =
+ el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
+ Object.getOwnPropertyDescriptor(proto, 'value')!.set!.call(el, value);
+ el.dispatchEvent(new Event('input', { bubbles: true }));
+};
+const field = <T extends HTMLElement>(label: string) =>
+ container.querySelector<T>(`[aria-label="${label}"]`)!;
+const button = (text: string) =>
+ [...container.querySelectorAll('button')].find((b) => b.textContent?.trim() === text)!;
+const last = () => changes.at(-1)!;
+
+async function upload(file: File) {
+ const input = container.querySelector<HTMLInputElement>('input[type="file"]')!;
+ Object.defineProperty(input, 'files', { value: [file], configurable: true });
+ await act(async () => {
+ input.dispatchEvent(new Event('change', { bubbles: true }));
+ });
+ // The file is read as text after the change.
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+}
+
+beforeEach(() => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2026-10-24T12:00:00Z'));
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ changes.length = 0;
+ toast.mockReset();
+ toast.error.mockReset();
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ vi.useRealTimers();
+});
+
+describe('Your input', () => {
+ it("offers Ansvisor data from the draft's prompts, cited as of this month", async () => {
+ await render();
+ expect(container.textContent).toContain(
+ 'From your Ansvisor data: in 825 answers to “best pour-over grinder” over the last 30 days, you were named 28 times.',
+ );
+ expect(container.textContent).toContain("over the last 30 days, you weren't named.");
+
+ await act(async () => button('Use this').click());
+ expect(last().ansvisorData).toEqual([
+ {
+ promptId: PROMPTS[0].id,
+ prompt: 'best pour-over grinder',
+ answers: 825,
+ mentioned: 28,
+ asOf: '2026-10-24',
+ days: 30,
+ },
+ ]);
+ // Used: no longer offered, shown with how it is cited.
+ expect(container.textContent).toContain('Cited as “Ansvisor data, October 2026”.');
+ expect(container.textContent).not.toContain('From your Ansvisor data: in 825');
+
+ await act(async () => field<HTMLButtonElement>('Remove best pour-over grinder').click());
+ expect(last().ansvisorData).toEqual([]);
+ });
+
+ it('keeps the experience on Save, or when the person leaves its box', async () => {
+ await render();
+ const box = container.querySelector<HTMLTextAreaElement>('#your-experience')!;
+ expect(button('Save').disabled).toBe(true);
+ await act(async () => setValue(box, ' We tested three grinders for six weeks. '));
+ await act(async () => button('Save').click());
+ expect(last().experience).toBe('We tested three grinders for six weeks.');
+
+ await act(async () => setValue(box, 'We tested four grinders.'));
+ await act(async () => {
+ box.dispatchEvent(new FocusEvent('focusout', { bubbles: true }));
+ });
+ expect(last().experience).toBe('We tested four grinders.');
+ expect(changes).toHaveLength(2);
+ });
+
+ it('adds a quote only with all four of its parts, and an http(s) source', async () => {
+ await render();
+ const add = () => button('Add quote');
+ await act(async () => {
+ setValue(field('Name'), 'Ada Lovelace');
+ setValue(field('Title and company'), 'Head of Research, Acme');
+ setValue(field('The quote, word for word'), 'We cut our forecast misses in half.');
+ setValue(field('Source link (https://…)'), 'acme.example/talk');
+ });
+ expect(add().disabled).toBe(true);
+ await act(async () => setValue(field('Source link (https://…)'), 'https://acme.example/talk'));
+ expect(add().disabled).toBe(false);
+
+ await act(async () => add().click());
+ expect(last().quotes).toEqual([
+ {
+ name: 'Ada Lovelace',
+ title: 'Head of Research, Acme',
+ text: 'We cut our forecast misses in half.',
+ sourceUrl: 'https://acme.example/talk',
+ },
+ ]);
+ expect(container.textContent).toContain('“We cut our forecast misses in half.”');
+ // The form is empty again for the next one.
+ expect(field<HTMLInputElement>('Name').value).toBe('');
+ expect(container.textContent).toContain('Add quotes from real people only.');
+ });
+
+ it('reads a CSV in the browser, or pasted numbers, as a table', async () => {
+ await render();
+ await upload(new File(['Teams,Share\n1250,42%\n'], 'survey.csv', { type: 'text/csv' }));
+ expect(last().data).toEqual([
+ {
+ name: 'survey.csv',
+ rows: [
+ ['Teams', 'Share'],
+ ['1250', '42%'],
+ ],
+ },
+ ]);
+ expect(container.textContent).toContain('survey.csv · 2 rows');
+
+ const paste = field<HTMLTextAreaElement>(
+ 'Or paste numbers, one row a line, separated by commas',
+ );
+ await act(async () => setValue(paste, 'Month,Visits\nOctober,3400'));
+ await act(async () => button('Add these numbers').click());
+ expect(last().data[1]).toEqual({
+ name: 'Pasted numbers',
+ rows: [
+ ['Month', 'Visits'],
+ ['October', '3400'],
+ ],
+ });
+ });
+
+ it("says why a file can't be used, and keeps nothing from it", async () => {
+ await render();
+ await upload(new File(['hello'], 'notes.pdf'));
+ expect(toast.error).toHaveBeenCalledWith("notes.pdf isn't a CSV or Excel (.xlsx) file.");
+ const big = new File(['x'], 'big.csv');
+ Object.defineProperty(big, 'size', { value: 11 * 1024 * 1024 });
+ await upload(big);
+ expect(toast.error).toHaveBeenCalledWith('big.csv is over 10 MB.');
+ await upload(new File([''], 'empty.csv'));
+ expect(toast.error).toHaveBeenCalledWith('empty.csv has no rows to use.');
+ expect(changes).toHaveLength(0);
+ });
+
+ it('keeps a large table to the rows the draft can keep, and says so', async () => {
+ await render();
+ const row = Array.from({ length: 12 }, () => 'x'.repeat(200)).join(',');
+ const csv = Array.from({ length: 100 }, () => row).join('\n');
+ await upload(new File([csv], 'big.csv'));
+ const kept = last().data[0].rows.length;
+ expect(kept).toBeGreaterThan(0);
+ expect(kept).toBeLessThan(100);
+ expect(toast).toHaveBeenCalledWith(
+ `big.csv is kept to its first ${kept} rows: that is what fits beside your other data.`,
+ );
+ // Full: the next one isn't kept.
+ await upload(new File([csv], 'again.csv'));
+ expect(toast.error).toHaveBeenCalledWith('Your data is full. Remove a table to add another.');
+ expect(last().data).toHaveLength(1);
+ });
+
+ it('keeps a change made while a file is read', async () => {
+ await render();
+ const input = container.querySelector<HTMLInputElement>('input[type="file"]')!;
+ Object.defineProperty(input, 'files', {
+ value: [new File(['Teams,Share\n1250,42%\n'], 'survey.csv')],
+ configurable: true,
+ });
+ await act(async () => {
+ input.dispatchEvent(new Event('change', { bubbles: true }));
+ });
+ await act(async () => button('Use this').click());
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ });
+ expect(last().ansvisorData).toHaveLength(1);
+ expect(last().data.map((table) => table.name)).toEqual(['survey.csv']);
+ });
+
+ it('reads numbers pasted from a spreadsheet into their columns', async () => {
+ await render();
+ const paste = field<HTMLTextAreaElement>(
+ 'Or paste numbers, one row a line, separated by commas',
+ );
+ await act(async () => setValue(paste, 'Month\tVisits\nOctober\t3400'));
+ await act(async () => button('Add these numbers').click());
+ expect(last().data[0].rows).toEqual([
+ ['Month', 'Visits'],
+ ['October', '3400'],
+ ]);
+ });
+
+ it('says what the agent never does', async () => {
+ await render();
+ expect(container.textContent).toContain(
+ 'Content Agent never makes things up. No invented people, quotes, customer stories, test results or numbers.',
+ );
+ });
+
+ it("scrolls into view on Quality's Add", async () => {
+ const scrollIntoView = vi.fn();
+ Element.prototype.scrollIntoView = scrollIntoView;
+ try {
+ await render(NO_INPUTS, 3);
+ expect(scrollIntoView).toHaveBeenCalledTimes(1);
+ // The same Add, shown again: not again.
+ await render(NO_INPUTS, 3);
+ expect(scrollIntoView).toHaveBeenCalledTimes(1);
+ } finally {
+ delete (Element.prototype as Partial<Element>).scrollIntoView;
+ }
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_your-input.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_your-input.tsx
new file mode 100644
index 000000000..d77fcbbed
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_your-input.tsx
@@ -0,0 +1,428 @@
+'use client';
+
+import { useEffect, useRef, useState } from 'react';
+import { useFormatter, useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { Check, ShieldCheck, Upload, X } from 'lucide-react';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { Textarea } from '@/components/ui/textarea';
+import { MAX_ATTACHMENT_BYTES, tableRows } from '@/lib/content/attachments';
+import {
+ MAX_ANSVISOR_DATA,
+ MAX_DATA_TABLES,
+ MAX_EXPERIENCE,
+ MAX_QUOTES,
+ MAX_QUOTES_BYTES,
+ jsonbBytes,
+ keptRows,
+ pastedRows,
+ quoteSchema,
+ tableThatFits,
+ type DraftInputs,
+ type InputQuote,
+} from '@/lib/content/draft-inputs';
+import { SOURCES_DAYS } from '@/lib/content/sources';
+import { cellsToText, parseCsv } from '@/lib/prompt-import';
+import type { InputsUpdate } from './_use-draft-inputs';
+
+/** Where Quality's "Add" to-dos scroll to. */
+export const YOUR_INPUT_ID = 'your-input';
+
+/** A tracked prompt of the draft, as Sources reads it: its answers and the brand's mentions. */
+export interface InputPrompt {
+ id: string;
+ text: string;
+ answers: number;
+ mentioned: number;
+}
+
+const EMPTY_QUOTE: InputQuote = { name: '', title: '', text: '', sourceUrl: '' };
+
+/** A day, "2026-10-24", as its month and year: how Ansvisor data is cited. */
+const monthOf = (day: string) => new Date(`${day.slice(0, 7)}-01T12:00:00Z`);
+
+/**
+ * Brief › Your input (Content Editor Quality spec §6, CE-048), at the top
+ * of Brief: what only the person can give, used only as they write it.
+ * Their experience; their data, from Ansvisor (a prompt's answers and the
+ * brand's mentions, cited as "Ansvisor data, {month year}") or from a CSV
+ * or Excel file read here in the browser, or pasted; expert quotes, each
+ * with the four things that make it real. Under it, what the agent never
+ * does. Each change is kept at once (`onChange`, made to the input as it
+ * is then: a file read meanwhile doesn't undo another change); the
+ * experience on Save, or when the person leaves its box.
+ */
+export function YourInput({
+ inputs,
+ prompts,
+ onChange,
+ scrollRequest = null,
+}: {
+ inputs: DraftInputs;
+ /** The draft's prompts, those it targets first: Ansvisor data offered from them. */
+ prompts: InputPrompt[];
+ onChange: (update: InputsUpdate) => void;
+ /** A Quality "Add" (a new number each time), with Brief showing: the block scrolls into view. */
+ scrollRequest?: number | null;
+}) {
+ const t = useTranslations('contentEditor.editor.yourInput');
+ const format = useFormatter();
+ const [experience, setExperience] = useState(inputs.experience);
+ const [pasted, setPasted] = useState('');
+ const [quote, setQuote] = useState<InputQuote>(EMPTY_QUOTE);
+ const fileRef = useRef<HTMLInputElement>(null);
+ const sectionRef = useRef<HTMLElement>(null);
+ // Each Add scrolls once: not again when Brief is opened later.
+ const scrolled = useRef<number | null>(null);
+ useEffect(() => {
+ if (scrollRequest === null || scrolled.current === scrollRequest) return;
+ scrolled.current = scrollRequest;
+ sectionRef.current?.scrollIntoView?.({ block: 'start', behavior: 'smooth' });
+ }, [scrollRequest]);
+ const keepExperience = () => {
+ const next = experience.trim();
+ onChange((current) =>
+ next === current.experience ? current : { ...current, experience: next },
+ );
+ };
+ const monthLabel = (day: string) =>
+ format.dateTime(monthOf(day), { month: 'long', year: 'numeric' });
+ const used = new Set(inputs.ansvisorData.map((d) => d.promptId));
+ const offered = prompts.filter((p) => p.answers > 0 && !used.has(p.id));
+ const tablesFull = inputs.data.length >= MAX_DATA_TABLES;
+
+ const addTable = (name: string, rows: string[][]) => {
+ const kept = keptRows(tableRows(rows));
+ if (!kept.length) {
+ toast.error(t('data.empty', { name }));
+ return;
+ }
+ onChange((current) => {
+ // The draft keeps its tables to the database's size: the rows that fit.
+ const table = tableThatFits(current.data, { name: name.slice(0, 120), rows: kept });
+ if (current.data.length >= MAX_DATA_TABLES || !table.rows.length) {
+ toast.error(t('data.full'));
+ return current;
+ }
+ if (table.rows.length < kept.length) {
+ toast(t('data.trimmed', { name, count: table.rows.length }));
+ }
+ return { ...current, data: [...current.data, table] };
+ });
+ };
+
+ const readFile = async (file: File | undefined) => {
+ if (!file) return;
+ if (file.size > MAX_ATTACHMENT_BYTES) {
+ toast.error(t('data.tooLarge', { name: file.name }));
+ return;
+ }
+ if (/\.xlsx$/i.test(file.name)) {
+ // Loaded on demand, as Attach does: the reader is only needed when someone uploads.
+ const { default: readXlsxFile } = await import('read-excel-file/browser');
+ const sheets = await readXlsxFile(file).catch(() => null);
+ const first = sheets?.find((sheet) => sheet.data.length > 0);
+ if (!first) {
+ toast.error(t('data.empty', { name: file.name }));
+ return;
+ }
+ addTable(file.name, cellsToText(first.data as unknown[][]));
+ return;
+ }
+ if (/\.csv$/i.test(file.name)) {
+ addTable(file.name, parseCsv(await file.text()));
+ return;
+ }
+ toast.error(t('data.unsupported', { name: file.name }));
+ };
+
+ const addQuote = () => {
+ const added = quoteSchema.parse(quote);
+ let kept = false;
+ onChange((current) => {
+ const quotes = [...current.quotes, added];
+ if (quotes.length > MAX_QUOTES || jsonbBytes(quotes) > MAX_QUOTES_BYTES) {
+ toast.error(t('quotes.full'));
+ return current;
+ }
+ kept = true;
+ return { ...current, quotes };
+ });
+ if (kept) setQuote(EMPTY_QUOTE);
+ };
+ const quoteReady = quoteSchema.safeParse(quote).success;
+
+ return (
+ <section
+ ref={sectionRef}
+ id={YOUR_INPUT_ID}
+ aria-labelledby={`${YOUR_INPUT_ID}-title`}
+ className="space-y-4 rounded-xl border bg-card p-3"
+ >
+ <h4 id={`${YOUR_INPUT_ID}-title`} className="text-sm font-medium">
+ {t('title')}{' '}
+ <span className="font-normal text-muted-foreground">· {t('usedAsWritten')}</span>
+ </h4>
+
+ <div className="space-y-1.5">
+ <Label htmlFor="your-experience">{t('experience.label')}</Label>
+ <Textarea
+ id="your-experience"
+ value={experience}
+ maxLength={MAX_EXPERIENCE}
+ placeholder={t('experience.placeholder')}
+ className="min-h-20 text-sm"
+ onChange={(e) => setExperience(e.target.value)}
+ onBlur={keepExperience}
+ />
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-[11px] text-muted-foreground">
+ {t('experience.count', { count: experience.length, max: MAX_EXPERIENCE })}
+ </span>
+ <Button
+ size="sm"
+ variant="outline"
+ className="h-7"
+ disabled={experience.trim() === inputs.experience}
+ onClick={keepExperience}
+ >
+ {t('save')}
+ </Button>
+ </div>
+ </div>
+
+ <div className="space-y-2">
+ <p className="text-xs font-medium">{t('data.label')}</p>
+ {inputs.ansvisorData.map((d) => (
+ <div
+ key={d.promptId}
+ className="flex items-start gap-2 rounded-lg border bg-muted/40 px-2.5 py-2 text-xs"
+ >
+ <Check className="mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-600 dark:text-emerald-400" />
+ <span className="min-w-0 flex-1 [overflow-wrap:anywhere]">
+ {t('data.ansvisor', {
+ answers: d.answers,
+ mentioned: d.mentioned,
+ prompt: d.prompt,
+ days: d.days,
+ })}{' '}
+ <span className="text-muted-foreground">
+ {t('data.cited', { month: monthLabel(d.asOf) })}
+ </span>
+ </span>
+ <button
+ type="button"
+ aria-label={t('removeNamed', { name: d.prompt })}
+ className="shrink-0 rounded p-0.5 text-muted-foreground hover:text-foreground"
+ onClick={() =>
+ onChange((current) => ({
+ ...current,
+ ansvisorData: current.ansvisorData.filter((x) => x.promptId !== d.promptId),
+ }))
+ }
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
+ </div>
+ ))}
+ {inputs.ansvisorData.length < MAX_ANSVISOR_DATA &&
+ offered.slice(0, 3).map((p) => (
+ <div
+ key={p.id}
+ className="flex items-start gap-2 rounded-lg border px-2.5 py-2 text-xs"
+ >
+ <span className="min-w-0 flex-1 [overflow-wrap:anywhere]">
+ {t('data.offer', {
+ answers: p.answers,
+ mentioned: p.mentioned,
+ prompt: p.text,
+ days: SOURCES_DAYS,
+ })}
+ </span>
+ <Button
+ size="sm"
+ variant="outline"
+ className="h-7 shrink-0"
+ onClick={() =>
+ onChange((current) =>
+ current.ansvisorData.some((x) => x.promptId === p.id) ||
+ current.ansvisorData.length >= MAX_ANSVISOR_DATA
+ ? current
+ : {
+ ...current,
+ ansvisorData: [
+ ...current.ansvisorData,
+ {
+ promptId: p.id,
+ prompt: p.text.slice(0, 500),
+ answers: p.answers,
+ mentioned: p.mentioned,
+ // The day it is used, where the person is: the
+ // numbers are the SOURCES_DAYS up to it.
+ asOf: new Date().toLocaleDateString('en-CA'),
+ days: SOURCES_DAYS,
+ },
+ ],
+ },
+ )
+ }
+ >
+ {t('data.use')}
+ </Button>
+ </div>
+ ))}
+ {inputs.data.map((table, i) => (
+ <div key={`${table.name}-${i}`} className="flex items-center gap-2 text-xs">
+ <span className="min-w-0 flex-1 truncate">
+ {table.name}{' '}
+ <span className="text-muted-foreground">
+ · {t('data.rows', { count: table.rows.length })}
+ </span>
+ </span>
+ <button
+ type="button"
+ aria-label={t('removeNamed', { name: table.name })}
+ className="shrink-0 rounded p-0.5 text-muted-foreground hover:text-foreground"
+ onClick={() =>
+ onChange((current) => ({
+ ...current,
+ data: current.data.filter((x) => x !== table),
+ }))
+ }
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
+ </div>
+ ))}
+ {!tablesFull && (
+ <div className="space-y-1.5">
+ <input
+ ref={fileRef}
+ type="file"
+ accept=".csv,.xlsx"
+ className="sr-only"
+ tabIndex={-1}
+ aria-hidden
+ onChange={(e) => {
+ void readFile(e.target.files?.[0]);
+ e.target.value = '';
+ }}
+ />
+ <Button
+ size="sm"
+ variant="outline"
+ className="h-7"
+ onClick={() => fileRef.current?.click()}
+ >
+ <Upload className="h-3.5 w-3.5" />
+ {t('data.upload')}
+ </Button>
+ <Textarea
+ aria-label={t('data.paste')}
+ value={pasted}
+ placeholder={t('data.paste')}
+ className="min-h-14 text-xs"
+ onChange={(e) => setPasted(e.target.value)}
+ />
+ {pasted.trim() && (
+ <Button
+ size="sm"
+ variant="outline"
+ className="h-7"
+ onClick={() => {
+ addTable(t('data.pastedName'), pastedRows(pasted));
+ setPasted('');
+ }}
+ >
+ {t('data.addPasted')}
+ </Button>
+ )}
+ </div>
+ )}
+ </div>
+
+ <div className="space-y-2">
+ <p className="text-xs font-medium">{t('quotes.label')}</p>
+ {inputs.quotes.map((q, i) => (
+ <figure key={`${q.name}-${i}`} className="flex items-start gap-2 text-xs">
+ <div className="min-w-0 flex-1 space-y-0.5">
+ <blockquote className="[overflow-wrap:anywhere]">“{q.text}”</blockquote>
+ <figcaption className="text-muted-foreground [overflow-wrap:anywhere]">
+ {q.name}, {q.title} ·{' '}
+ <a
+ href={q.sourceUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="underline"
+ >
+ {t('quotes.source')}
+ </a>
+ </figcaption>
+ </div>
+ <button
+ type="button"
+ aria-label={t('removeNamed', { name: q.name })}
+ className="shrink-0 rounded p-0.5 text-muted-foreground hover:text-foreground"
+ onClick={() =>
+ onChange((current) => ({
+ ...current,
+ quotes: current.quotes.filter((x) => x !== q),
+ }))
+ }
+ >
+ <X className="h-3.5 w-3.5" />
+ </button>
+ </figure>
+ ))}
+ {inputs.quotes.length < MAX_QUOTES && (
+ <div className="grid gap-1.5">
+ <Input
+ aria-label={t('quotes.name')}
+ placeholder={t('quotes.name')}
+ value={quote.name}
+ onChange={(e) => setQuote({ ...quote, name: e.target.value })}
+ />
+ <Input
+ aria-label={t('quotes.title')}
+ placeholder={t('quotes.title')}
+ value={quote.title}
+ onChange={(e) => setQuote({ ...quote, title: e.target.value })}
+ />
+ <Textarea
+ aria-label={t('quotes.text')}
+ placeholder={t('quotes.text')}
+ value={quote.text}
+ className="min-h-14 text-xs"
+ onChange={(e) => setQuote({ ...quote, text: e.target.value })}
+ />
+ <Input
+ aria-label={t('quotes.sourceUrl')}
+ placeholder={t('quotes.sourceUrl')}
+ value={quote.sourceUrl}
+ onChange={(e) => setQuote({ ...quote, sourceUrl: e.target.value })}
+ />
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-[11px] text-muted-foreground">{t('quotes.realOnly')}</span>
+ <Button
+ size="sm"
+ variant="outline"
+ className="h-7"
+ disabled={!quoteReady}
+ onClick={addQuote}
+ >
+ {t('quotes.add')}
+ </Button>
+ </div>
+ </div>
+ )}
+ </div>
+
+ <p className="flex items-start gap-2 rounded-lg bg-foreground px-3 py-2 text-xs text-background">
+ <ShieldCheck className="mt-0.5 h-3.5 w-3.5 shrink-0" aria-hidden />
+ <span>{t('guard')}</span>
+ </p>
+ </section>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx
index be43612e9..11cf41652 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
@@ -27,6 +27,12 @@ const getContentAuthors = vi.fn();
vi.mock('@/lib/actions/content-authors', () => ({
getContentAuthors: (...args: unknown[]) => getContentAuthors(...args),
}));
+const getDraftInputs = vi.fn();
+const saveDraftInputs = vi.fn();
+vi.mock('@/lib/actions/content-draft-inputs', () => ({
+ getDraftInputs: (...args: unknown[]) => getDraftInputs(...args),
+ saveDraftInputs: (...args: unknown[]) => saveDraftInputs(...args),
+}));
const getContentImpact = vi.fn();
const getContentResults = vi.fn();
const getDraftSources = vi.fn();
@@ -277,6 +283,10 @@ beforeEach(() => {
checkDraftLinks.mockReset().mockResolvedValue({ links: [], skipped: [] });
getSiteTrust.mockReset().mockRejectedValue(new Error('not in this test'));
getContentAuthors.mockReset().mockResolvedValue(null);
+ getDraftInputs
+ .mockReset()
+ .mockResolvedValue({ experience: '', data: [], ansvisorData: [], quotes: [] });
+ saveDraftInputs.mockReset().mockImplementation(async (_id, inputs) => inputs);
saveContentDraft
.mockReset()
.mockResolvedValue({ ok: true, updatedAt: '2026-10-20T10:00:00Z', bodyHash: 'h0' });
@@ -2463,6 +2473,92 @@ describe('the side panel', () => {
expect(panel()!.textContent).toContain('Not a Google score.');
});
+ it("asks for Your input in its second phase, and Add opens it at Brief's top (CE-048)", async () => {
+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '2';
+ getContentAuthors.mockResolvedValue({
+ authors: [],
+ brands: [{ id: 'b1', name: 'Acme' }],
+ me: { id: 'u1', role: 'admin' },
+ });
+ const experience = 'We tested weekly forecasts with twelve small sales teams.';
+ getDraftInputs.mockResolvedValue({ experience, data: [], ansvisorData: [], quotes: [] });
+ getContentDraft.mockResolvedValue(readable);
+ window.innerWidth = 1440;
+ await renderPage();
+ expect(getDraftInputs).toHaveBeenCalledWith(readable.id);
+ const chip = [...container.querySelectorAll<HTMLButtonElement>('header button')].find((b) =>
+ b.textContent?.startsWith('Quality'),
+ )!;
+ await act(async () => chip.click());
+ const row = [...panel()!.querySelectorAll('[aria-label="Your to-dos"] li')].find((li) =>
+ li.textContent?.startsWith('Add your own experience'),
+ )!;
+ // Given, but the page doesn't use it yet.
+ expect(row.textContent).toContain("It's in Your input, but the page doesn't use it yet");
+ expect(
+ [...panel()!.querySelectorAll('[aria-label="Your to-dos"] li')].map(
+ (li) => li.textContent?.split(' · ')[0],
+ ),
+ ).toEqual([
+ 'Add an author for the page',
+ "Complete the author's profile",
+ 'Add your own experience',
+ 'Add your own data',
+ "Add an expert's quote",
+ ]);
+
+ await act(async () => row.querySelector('button')!.click());
+ expect(selectedSegment()).toBe('Brief');
+ const box = panel()!.querySelector<HTMLTextAreaElement>('#your-experience')!;
+ expect(box.value).toBe(experience);
+ expect(panel()!.textContent).toContain('Your input · used only as you write it');
+
+ // A change is kept as the whole input.
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!.call(
+ box,
+ `${experience} Forecasts missed by less.`,
+ );
+ box.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ await act(async () => {
+ box.dispatchEvent(new FocusEvent('focusout', { bubbles: true }));
+ });
+ expect(saveDraftInputs).toHaveBeenCalledWith(readable.id, {
+ experience: `${experience} Forecasts missed by less.`,
+ data: [],
+ ansvisorData: [],
+ quotes: [],
+ });
+ });
+
+ it('scores without Your input when it can’t be read, and Brief offers to read it again', async () => {
+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '2';
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ getContentAuthors.mockResolvedValue({
+ authors: [],
+ brands: [{ id: 'b1', name: 'Acme' }],
+ me: { id: 'u1', role: 'admin' },
+ });
+ getDraftInputs.mockRejectedValueOnce(new Error('offline'));
+ getContentDraft.mockResolvedValue(readable);
+ window.innerWidth = 1440;
+ await renderPage();
+ expect(qualityChip()?.textContent).toMatch(/^Quality \d+/);
+ await pickTab('Brief');
+ const retry = [...panel()!.querySelectorAll('button')].find(
+ (b) => b.textContent === 'Try again',
+ )!;
+ expect(retry.parentElement!.textContent).toBe("Couldn't read your input.Try again");
+ await act(async () => retry.click());
+ expect(getDraftInputs).toHaveBeenCalledTimes(2);
+ expect(panel()!.querySelector('#your-experience')).not.toBeNull();
+ } finally {
+ vi.mocked(console.error).mockRestore();
+ }
+ });
+
/** The draft above, its Language rule changed for this draft. */
const inLanguage = (language: { on?: boolean; value?: string }) => ({
...readable,
diff --git a/web/src/lib/actions/content-draft-inputs.test.ts b/web/src/lib/actions/content-draft-inputs.test.ts
new file mode 100644
index 000000000..e201066d6
--- /dev/null
+++ b/web/src/lib/actions/content-draft-inputs.test.ts
@@ -0,0 +1,112 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { NO_INPUTS } from '@/lib/content/draft-inputs';
+
+/**
+ * Brief › Your input (CE-048): kept per draft as the person gave it, read
+ * and written through RLS as the draft is.
+ */
+
+const DRAFT = '2f1d1c52-0f7a-4c1e-9b8a-5d6e7f8a9b0c';
+
+let row: Record<string, unknown> | null;
+let readError: { message: string } | null;
+let upserts: { value: Record<string, unknown>; options: unknown }[];
+let upsertError: { message: string } | null;
+let filters: [string, unknown][];
+
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(async () => ({
+ auth: { getUser: async () => ({ data: { user: { id: 'u1' } } }) },
+ from: (table: string) => {
+ expect(table).toBe('content_draft_inputs');
+ const chain = {
+ select: () => chain,
+ eq: (col: string, v: unknown) => (filters.push([col, v]), chain),
+ maybeSingle: async () => ({ data: row, error: readError }),
+ upsert: async (value: Record<string, unknown>, options: unknown) => {
+ upserts.push({ value, options });
+ return { error: upsertError };
+ },
+ };
+ return chain;
+ },
+ })),
+}));
+
+const { getDraftInputs, saveDraftInputs } = await import('./content-draft-inputs');
+
+beforeEach(() => {
+ row = null;
+ readError = null;
+ upserts = [];
+ upsertError = null;
+ filters = [];
+});
+
+const quote = {
+ name: 'Ada Lovelace',
+ title: 'Head of Research, Acme',
+ text: 'We cut our forecast misses in half.',
+ sourceUrl: 'https://acme.example/talk',
+};
+
+describe('getDraftInputs', () => {
+ it('reads none given as empty, and a kept row as given', async () => {
+ expect(await getDraftInputs(DRAFT)).toEqual(NO_INPUTS);
+ expect(filters).toEqual([['draft_id', DRAFT]]);
+
+ row = { experience: 'We tested it.', data: [], ansvisor_data: [], quotes: [quote] };
+ expect(await getDraftInputs(DRAFT)).toEqual({
+ experience: 'We tested it.',
+ data: [],
+ ansvisorData: [],
+ quotes: [quote],
+ });
+ });
+
+ it("keeps what still reads of a row, item by item, and says when it can't read", async () => {
+ row = {
+ experience: null,
+ data: 'nope',
+ ansvisor_data: [{ promptId: 'x' }],
+ quotes: [quote, { ...quote, sourceUrl: 'ftp://a.example' }],
+ };
+ expect(await getDraftInputs(DRAFT)).toEqual({ ...NO_INPUTS, quotes: [quote] });
+ readError = { message: 'denied' };
+ await expect(getDraftInputs(DRAFT)).rejects.toThrow('denied');
+ await expect(getDraftInputs('not-an-id')).rejects.toThrow('invalid');
+ });
+});
+
+describe('saveDraftInputs', () => {
+ it('keeps the whole input on the draft, by whom, an empty experience as none', async () => {
+ const saved = await saveDraftInputs(DRAFT, {
+ ...NO_INPUTS,
+ quotes: [{ ...quote, name: ' Ada ' }],
+ });
+ expect(saved.quotes[0].name).toBe('Ada');
+ expect(upserts).toEqual([
+ {
+ value: {
+ draft_id: DRAFT,
+ experience: null,
+ data: [],
+ ansvisor_data: [],
+ quotes: [{ ...quote, name: 'Ada' }],
+ updated_by: 'u1',
+ },
+ options: { onConflict: 'draft_id' },
+ },
+ ]);
+ });
+
+ it('keeps nothing that breaks the rules, and says when the write is refused', async () => {
+ await expect(
+ saveDraftInputs(DRAFT, { ...NO_INPUTS, quotes: [{ ...quote, sourceUrl: 'javascript:x' }] }),
+ ).rejects.toThrow('invalid');
+ await expect(saveDraftInputs('nope', NO_INPUTS)).rejects.toThrow('invalid');
+ expect(upserts).toHaveLength(0);
+ upsertError = { message: 'new row violates row-level security policy' };
+ await expect(saveDraftInputs(DRAFT, NO_INPUTS)).rejects.toThrow('row-level security');
+ });
+});
diff --git a/web/src/lib/actions/content-draft-inputs.ts b/web/src/lib/actions/content-draft-inputs.ts
new file mode 100644
index 000000000..a9a0ca32a
--- /dev/null
+++ b/web/src/lib/actions/content-draft-inputs.ts
@@ -0,0 +1,61 @@
+'use server';
+
+import { z } from 'zod';
+import {
+ NO_INPUTS,
+ draftInputsSchema,
+ keptInputs,
+ type DraftInputs,
+} from '@/lib/content/draft-inputs';
+import { createClient } from '@/lib/supabase/server';
+
+/**
+ * Brief › Your input (Content Editor Quality spec §6, CE-048): the person's
+ * experience, data and expert quotes for a draft (content_draft_inputs,
+ * 00265), read and written by the members of its workspace (RLS), as the
+ * draft is.
+ */
+
+const draftId = z.guid();
+
+/** The draft's input, as kept (keptInputs); none given reads as empty. */
+export async function getDraftInputs(id: string): Promise<DraftInputs> {
+ if (!draftId.safeParse(id).success) throw new Error('invalid');
+ const supabase = await createClient();
+ const { data, error } = await supabase
+ .from('content_draft_inputs')
+ .select('experience, data, ansvisor_data, quotes')
+ .eq('draft_id', id)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!data) return NO_INPUTS;
+ return keptInputs({
+ experience: data.experience,
+ data: data.data,
+ ansvisorData: data.ansvisor_data,
+ quotes: data.quotes,
+ });
+}
+
+/** Keeps the draft's input as given (all of it, as the editor holds it). */
+export async function saveDraftInputs(id: string, inputs: DraftInputs): Promise<DraftInputs> {
+ const parsed = draftInputsSchema.safeParse(inputs);
+ if (!draftId.safeParse(id).success || !parsed.success) throw new Error('invalid');
+ const supabase = await createClient();
+ const {
+ data: { user },
+ } = await supabase.auth.getUser();
+ const { error } = await supabase.from('content_draft_inputs').upsert(
+ {
+ draft_id: id,
+ experience: parsed.data.experience || null,
+ data: parsed.data.data,
+ ansvisor_data: parsed.data.ansvisorData,
+ quotes: parsed.data.quotes,
+ updated_by: user?.id ?? null,
+ },
+ { onConflict: 'draft_id' },
+ );
+ if (error) throw new Error(error.message);
+ return parsed.data;
+}
diff --git a/web/src/lib/content/draft-inputs.test.ts b/web/src/lib/content/draft-inputs.test.ts
new file mode 100644
index 000000000..6704b1d47
--- /dev/null
+++ b/web/src/lib/content/draft-inputs.test.ts
@@ -0,0 +1,263 @@
+import { describe, expect, it } from 'vitest';
+import {
+ MAX_DATA_BYTES,
+ NO_INPUTS,
+ draftInputsSchema,
+ inputsGiven,
+ inputsUsed,
+ jsonbBytes,
+ keptInputs,
+ keptRows,
+ pastedRows,
+ tableThatFits,
+ type DraftInputs,
+} from './draft-inputs';
+
+/**
+ * Brief › Your input (CE-048): kept as the person gave it, and counted only
+ * once the page can be read to use it.
+ */
+
+const inputs = (over: Partial<DraftInputs>): DraftInputs => ({ ...NO_INPUTS, ...over });
+
+describe('inputsUsed', () => {
+ it('reads a quote as used only word for word', () => {
+ const quote = {
+ name: 'Ada Lovelace',
+ title: 'Head of Research, Acme',
+ text: 'We cut our forecast misses in half.',
+ sourceUrl: 'https://acme.example/talk',
+ };
+ expect(
+ inputsUsed(
+ 'As Ada put it: “We cut our forecast misses in half.”',
+ inputs({ quotes: [quote] }),
+ ).quote,
+ ).toBe(true);
+ expect(inputsUsed('Ada says misses were halved.', inputs({ quotes: [quote] })).quote).toBe(
+ false,
+ );
+ });
+
+ it('reads data as used by a number from it, however its thousands are written', () => {
+ const data = [
+ {
+ name: 'Survey',
+ rows: [
+ ['Teams', 'Share'],
+ ['1,250', '42%'],
+ ],
+ },
+ ];
+ expect(inputsUsed('We asked 1250 teams.', inputs({ data })).data).toBe(true);
+ expect(inputsUsed('42% of them said so.', inputs({ data })).data).toBe(true);
+ // One digit says little.
+ expect(inputsUsed('In 3 steps.', inputs({ data: [{ name: 'x', rows: [['3']] }] })).data).toBe(
+ false,
+ );
+ const ansvisor = [
+ {
+ promptId: '5e8cd4c2-2bc4-4fb7-8711-bc0ad1bb4a29',
+ prompt: 'best pour-over grinder',
+ answers: 825,
+ mentioned: 28,
+ asOf: '2026-10-24',
+ days: 30,
+ },
+ ];
+ expect(inputsUsed('Named in 28 of 825 answers.', inputs({ ansvisorData: ansvisor })).data).toBe(
+ true,
+ );
+ // Its two numbers in different sentences are anyone's.
+ expect(
+ inputsUsed('Try it for 28 days. Over 825 people did.', inputs({ ansvisorData: ansvisor }))
+ .data,
+ ).toBe(false);
+ });
+
+ it("doesn't read years, dates or small counts as the person's data", () => {
+ const data = [
+ {
+ name: 'Visits',
+ rows: [
+ ['2026-01', '12', '01.02.2026'],
+ ['2025', '7%', '3.5'],
+ ],
+ },
+ ];
+ for (const page of ['The best CRMs in 2026.', 'In 12 steps.', 'Up 7% on 01.02.']) {
+ expect(inputsUsed(page, inputs({ data })).data).toBe(false);
+ }
+ // A decimal is someone's.
+ expect(inputsUsed('It took 3.5 hours.', inputs({ data })).data).toBe(true);
+ expect(
+ inputsUsed('Up %42 this year.', inputs({ data: [{ name: 'x', rows: [['42%']] }] })).data,
+ ).toBe(true);
+ });
+
+ it('reads a quote as said whatever marks end it, and dashes alike', () => {
+ const quote = (text: string) => ({
+ name: 'Ada',
+ title: 'CTO, Acme',
+ text,
+ sourceUrl: 'https://a.example',
+ });
+ expect(
+ inputsUsed(
+ '“It changed how we work,” says Ada.',
+ inputs({ quotes: [quote('It changed how we work.')] }),
+ ).quote,
+ ).toBe(true);
+ expect(
+ inputsUsed(
+ 'She said: “Fast — and cheap.”',
+ inputs({ quotes: [quote('"Fast – and cheap!"')] }),
+ ).quote,
+ ).toBe(true);
+ });
+
+ it('reads experience as used by its own words, and none given as unused', () => {
+ const experience =
+ 'We tested three grinders for six weeks in our roastery and the burr grinder kept the grind steadiest.';
+ expect(
+ inputsUsed(
+ 'In our roastery we tested grinders for six weeks: the burr grinder kept the grind steadiest.',
+ inputs({ experience }),
+ ).experience,
+ ).toBe(true);
+ expect(inputsUsed('Grinders differ.', inputs({ experience })).experience).toBe(false);
+ // Its topic and common words alone aren't it.
+ expect(
+ inputsUsed(
+ 'Their results were better with clients.',
+ inputs({ experience: 'We used it with our clients and their results were better.' }),
+ ).experience,
+ ).toBe(false);
+ expect(
+ inputsUsed(
+ 'Sales teams forecast pipeline every week.',
+ inputs({ experience: 'We tested weekly forecasts with twelve small sales teams.' }),
+ ).experience,
+ ).toBe(false);
+ expect(inputsUsed('Anything', NO_INPUTS)).toEqual({
+ experience: false,
+ data: false,
+ quote: false,
+ });
+ });
+});
+
+describe('the input as kept', () => {
+ it('needs all four fields of a quote, and an http(s) source', () => {
+ const quote = {
+ name: 'Ada',
+ title: 'CTO, Acme',
+ text: 'Hi there.',
+ sourceUrl: 'https://a.example',
+ };
+ expect(draftInputsSchema.safeParse(inputs({ quotes: [quote] })).success).toBe(true);
+ for (const over of [
+ { name: '' },
+ { title: ' ' },
+ { text: '' },
+ { sourceUrl: 'javascript:x' },
+ { sourceUrl: 'https://' },
+ ]) {
+ expect(draftInputsSchema.safeParse(inputs({ quotes: [{ ...quote, ...over }] })).success).toBe(
+ false,
+ );
+ }
+ });
+
+ it('keeps a table’s first rows and columns, each cell cut', () => {
+ const rows = Array.from({ length: 150 }, () =>
+ Array.from({ length: 20 }, () => 'x'.repeat(300)),
+ );
+ const kept = keptRows(rows);
+ expect(kept).toHaveLength(100);
+ expect(kept[0]).toHaveLength(12);
+ expect(kept[0][0]).toHaveLength(200);
+ });
+
+ it('measures a value as Postgres writes jsonb as text, which its size checks read', () => {
+ // `select octet_length('…'::jsonb::text)` reads 105 for it.
+ expect(
+ jsonbBytes([
+ {
+ name: 'Anket ğüş',
+ rows: [
+ ['1,250', '42%'],
+ ['a"b', ''],
+ ],
+ },
+ { name: 'x', rows: [['日本']] },
+ ]),
+ ).toBe(105);
+ });
+
+ it('keeps a new table to the rows that fit beside the others, and none when none do', () => {
+ const row = Array.from({ length: 12 }, () => 'x'.repeat(200));
+ const big = { name: 'Big', rows: Array.from({ length: 100 }, () => row) };
+ const first = tableThatFits([], big);
+ expect(first.rows.length).toBeLessThan(100);
+ expect(first.rows.length).toBeGreaterThan(0);
+ expect(jsonbBytes([first])).toBeLessThanOrEqual(MAX_DATA_BYTES);
+ expect(tableThatFits([first], big).rows.length).toBe(0);
+ // What the database would turn away isn't kept.
+ expect(draftInputsSchema.safeParse(inputs({ data: [big] })).success).toBe(false);
+ expect(draftInputsSchema.safeParse(inputs({ data: [first] })).success).toBe(true);
+ });
+
+ it('tells what was given from what the page uses', () => {
+ expect(inputsGiven(NO_INPUTS)).toEqual({ experience: false, data: false, quote: false });
+ expect(
+ inputsGiven(
+ inputs({
+ experience: ' ',
+ ansvisorData: [
+ {
+ promptId: '5e8cd4c2-2bc4-4fb7-8711-bc0ad1bb4a29',
+ prompt: 'p',
+ answers: 1,
+ mentioned: 0,
+ asOf: '2026-10-24',
+ days: 30,
+ },
+ ],
+ }),
+ ),
+ ).toEqual({ experience: false, data: true, quote: false });
+ });
+
+ it('cuts a cell by characters, never half of one, and drops NUL, which the database refuses', () => {
+ const [[cell]] = keptRows([['\0' + '😀'.repeat(250)]]);
+ expect(Array.from(cell)).toHaveLength(200);
+ expect(cell).not.toContain('\0');
+ expect(
+ draftInputsSchema.safeParse(inputs({ data: [{ name: 'x', rows: [[cell]] }] })).success,
+ ).toBe(true);
+ });
+
+ it('reads numbers pasted from a spreadsheet by their tabs', () => {
+ expect(pastedRows('Month\tVisits\nOctober\t3,400\n')).toEqual([
+ ['Month', 'Visits'],
+ ['October', '3,400'],
+ ]);
+ expect(pastedRows('Month,Visits\nOctober,3400')).toEqual([
+ ['Month', 'Visits'],
+ ['October', '3400'],
+ ]);
+ });
+
+ it('keeps what still reads of a row, item by item', () => {
+ const quote = { name: 'Ada', title: 'CTO', text: 'Hi.', sourceUrl: 'https://a.example' };
+ expect(
+ keptInputs({
+ experience: 'x'.repeat(5000),
+ data: 'nope',
+ ansvisorData: [{ promptId: 'x' }],
+ quotes: [quote, { ...quote, sourceUrl: 'https://' }],
+ }),
+ ).toEqual({ experience: 'x'.repeat(4000), data: [], ansvisorData: [], quotes: [quote] });
+ });
+});
diff --git a/web/src/lib/content/draft-inputs.ts b/web/src/lib/content/draft-inputs.ts
new file mode 100644
index 000000000..bd69b079a
--- /dev/null
+++ b/web/src/lib/content/draft-inputs.ts
@@ -0,0 +1,306 @@
+import { z } from 'zod';
+import { parseCsv } from '@/lib/prompt-import';
+
+/**
+ * Brief › Your input (Content Editor Quality spec §6, CE-048): what only the
+ * person can give a page, used only as they write it. Their first-hand
+ * experience; their data (tables read from a CSV or Excel file in the
+ * browser, or pasted, and Ansvisor data they chose to use); and expert
+ * quotes from real people, word for word, each with its source. Kept per
+ * draft beside the brief (content_draft_inputs, 00265): a rebuilt brief
+ * leaves them.
+ */
+
+export const MAX_EXPERIENCE = 4000;
+export const MAX_QUOTES = 10;
+export const MAX_DATA_TABLES = 5;
+/** The rows and columns a table keeps: enough for the agent to cite, small enough to store. */
+export const MAX_DATA_ROWS = 100;
+export const MAX_DATA_COLUMNS = 12;
+export const MAX_DATA_CELL = 200;
+export const MAX_ANSVISOR_DATA = 10;
+/** What the database keeps of a draft's tables and its quotes (00265), as jsonb writes them. */
+export const MAX_DATA_BYTES = 65_536;
+export const MAX_QUOTES_BYTES = 16_384;
+
+const utf8 = new TextEncoder();
+
+/**
+ * A value's size as Postgres writes jsonb as text, which its checks measure:
+ * JSON with ", " and ": " between items. Kept under the database's limits,
+ * a save isn't turned away.
+ */
+export function jsonbBytes(value: unknown): number {
+ if (Array.isArray(value)) {
+ return (
+ 2 +
+ value.reduce<number>((sum, v) => sum + jsonbBytes(v), 0) +
+ 2 * Math.max(0, value.length - 1)
+ );
+ }
+ if (value !== null && typeof value === 'object') {
+ const entries = Object.entries(value).filter(([, v]) => v !== undefined);
+ return (
+ 2 +
+ entries.reduce<number>(
+ (sum, [key, v]) => sum + utf8.encode(JSON.stringify(key)).length + 2 + jsonbBytes(v),
+ 0,
+ ) +
+ 2 * Math.max(0, entries.length - 1)
+ );
+ }
+ return utf8.encode(JSON.stringify(value) ?? 'null').length;
+}
+
+const address = z
+ .string()
+ .trim()
+ .max(2048)
+ .pipe(z.url({ protocol: /^https?$/ }));
+
+export const quoteSchema = z.object({
+ name: z.string().trim().min(1).max(120),
+ /** Their title and company. */
+ title: z.string().trim().min(1).max(160),
+ /** The quote word for word. */
+ text: z.string().trim().min(1).max(600),
+ sourceUrl: address,
+});
+export type InputQuote = z.infer<typeof quoteSchema>;
+
+export const dataTableSchema = z.object({
+ name: z.string().trim().min(1).max(120),
+ rows: z
+ .array(
+ z
+ .array(z.string().refine((cell) => Array.from(cell).length <= MAX_DATA_CELL))
+ .max(MAX_DATA_COLUMNS),
+ )
+ .min(1)
+ .max(MAX_DATA_ROWS),
+});
+export type InputTable = z.infer<typeof dataTableSchema>;
+
+/**
+ * Ansvisor data the person chose to use: one tracked prompt's answers and
+ * the brand's mentions in them, over the `days` up to `asOf` (Sources'
+ * SOURCES_DAYS). Cited as "Ansvisor data, {month year}" of `asOf`.
+ */
+export const ansvisorDataSchema = z.object({
+ promptId: z.guid(),
+ prompt: z.string().trim().min(1).max(500),
+ answers: z.number().int().min(0),
+ mentioned: z.number().int().min(0),
+ /** The day it was read, "2026-10-24", in the person's time zone. */
+ asOf: z.iso.date(),
+ days: z.number().int().min(1).max(366),
+});
+export type AnsvisorData = z.infer<typeof ansvisorDataSchema>;
+
+export const draftInputsSchema = z.object({
+ experience: z.string().trim().max(MAX_EXPERIENCE),
+ data: z
+ .array(dataTableSchema)
+ .max(MAX_DATA_TABLES)
+ .refine((tables) => jsonbBytes(tables) <= MAX_DATA_BYTES),
+ ansvisorData: z.array(ansvisorDataSchema).max(MAX_ANSVISOR_DATA),
+ quotes: z
+ .array(quoteSchema)
+ .max(MAX_QUOTES)
+ .refine((quotes) => jsonbBytes(quotes) <= MAX_QUOTES_BYTES),
+});
+export type DraftInputs = z.infer<typeof draftInputsSchema>;
+
+export const NO_INPUTS: DraftInputs = { experience: '', data: [], ansvisorData: [], quotes: [] };
+
+/**
+ * The input as kept, item by item: one that no longer reads as the schema
+ * does (a limit tightened since) is left out, not the rest with it, so the
+ * next save doesn't write over what still reads.
+ */
+export function keptInputs(row: {
+ experience: unknown;
+ data: unknown;
+ ansvisorData: unknown;
+ quotes: unknown;
+}): DraftInputs {
+ const items = <T>(schema: z.ZodType<T>, value: unknown, max: number): T[] =>
+ (Array.isArray(value) ? value : [])
+ .flatMap((item) => {
+ const read = schema.safeParse(item);
+ return read.success ? [read.data] : [];
+ })
+ .slice(0, max);
+ return {
+ experience:
+ typeof row.experience === 'string' ? row.experience.trim().slice(0, MAX_EXPERIENCE) : '',
+ data: items(dataTableSchema, row.data, MAX_DATA_TABLES),
+ ansvisorData: items(ansvisorDataSchema, row.ansvisorData, MAX_ANSVISOR_DATA),
+ quotes: items(quoteSchema, row.quotes, MAX_QUOTES),
+ };
+}
+
+/**
+ * Rows as a table keeps them: MAX_DATA_ROWS and MAX_DATA_COLUMNS at most,
+ * each cell cut to MAX_DATA_CELL characters (never half of one) and without
+ * the NUL character, which the database refuses.
+ */
+export function keptRows(rows: string[][]): string[][] {
+ return rows
+ .slice(0, MAX_DATA_ROWS)
+ .map((row) =>
+ row
+ .slice(0, MAX_DATA_COLUMNS)
+ .map((cell) => Array.from(cell.replaceAll('\0', '')).slice(0, MAX_DATA_CELL).join('')),
+ );
+}
+
+/**
+ * Numbers pasted as rows: a copy from Excel or Google Sheets is separated by
+ * tabs, a CSV by commas or semicolons.
+ */
+export function pastedRows(text: string): string[][] {
+ const first = text.split(/\r?\n/).find((line) => line.trim() !== '') ?? '';
+ if (!first.includes('\t')) return parseCsv(text);
+ return text
+ .split(/\r?\n/)
+ .map((line) => line.split('\t').map((cell) => cell.trim()))
+ .filter((row) => row.some((cell) => cell !== ''));
+}
+
+/**
+ * A new table as the draft can keep it beside its others: its rows from the
+ * first, as many as fit in MAX_DATA_BYTES (none when none do).
+ */
+export function tableThatFits(tables: InputTable[], table: InputTable): InputTable {
+ let rows = table.rows.length;
+ while (
+ rows > 0 &&
+ jsonbBytes([...tables, { ...table, rows: table.rows.slice(0, rows) }]) > MAX_DATA_BYTES
+ ) {
+ rows--;
+ }
+ return { ...table, rows: table.rows.slice(0, rows) };
+}
+
+/** Which kinds of input the person gave, used or not. */
+export function inputsGiven(inputs: DraftInputs): {
+ experience: boolean;
+ data: boolean;
+ quote: boolean;
+} {
+ return {
+ experience: inputs.experience.trim().length > 0,
+ data: inputs.data.length > 0 || inputs.ansvisorData.length > 0,
+ quote: inputs.quotes.length > 0,
+ };
+}
+
+/** Text as the checks compare it: lower case, no double quotes, one kind of dash, single spaces. */
+const plain = (text: string) =>
+ text
+ .toLowerCase()
+ .replace(/[“”„«»"]/g, '')
+ .replace(/[‘’`']/g, "'")
+ .replace(/[‐‑‒–—―]/g, '-')
+ .replace(/…/g, '...')
+ .replace(/\s+/g, ' ')
+ .trim();
+
+/** Thousands separators out ("1,250" and "1250" alike), and dates, whose pieces are no one's data. */
+const numbersOnly = (text: string) =>
+ text
+ .replace(/\b\d{4}-\d{1,2}(?:-\d{1,2})?\b/g, ' ')
+ .replace(/\b\d{1,2}[./]\d{1,2}[./]\d{2,4}\b/g, ' ')
+ .replace(/(?<=\d)[.,](?=\d{3}(?!\d))/g, '');
+
+/**
+ * The figures in a text that can only be someone's data: a share ("42%",
+ * "%42"), a decimal ("3.5"), or three digits or more that aren't a year.
+ * "3 steps", "28 days" and "in 2026" are anyone's.
+ */
+function figuresIn(text: string): string[] {
+ const figures: string[] = [];
+ for (const m of numbersOnly(text).matchAll(/(%\s?)?(\d+(?:[.,]\d+)?)(\s?%)?/g)) {
+ const n = m[2].replace(',', '.');
+ const decimal = n.includes('.');
+ if (m[1] || m[3]) {
+ if (decimal || n.length >= 2) figures.push(`${n}%`);
+ } else if (decimal || (n.length >= 3 && !/^(19|20)\d{2}$/.test(n))) {
+ figures.push(n);
+ }
+ }
+ return figures;
+}
+
+/** The page's sentences, each with its whole numbers. */
+const sentenceNumbers = (text: string) =>
+ text
+ .split(/(?<=[.!?])\s+|\n+/)
+ .map((sentence) => new Set(numbersOnly(sentence).match(/\d+/g) ?? []));
+
+/**
+ * The experience's runs of three words that say something (a word of five
+ * letters or more among them): a page that only shares its topic or common
+ * words with it doesn't use it.
+ */
+function runsOf(text: string): Set<string> {
+ const words = plain(text).match(/[\p{L}\p{N}']+/gu) ?? [];
+ const runs = new Set<string>();
+ for (let i = 0; i + 2 < words.length; i++) {
+ const run = words.slice(i, i + 3);
+ if (run.some((word) => word.length >= 5)) runs.add(run.join(' '));
+ }
+ return runs;
+}
+
+/** The share of the experience's runs the page must have, and the fewest. */
+const EXPERIENCE_SHARE = 0.3;
+const EXPERIENCE_RUNS = 3;
+
+/** A quote as said, without the marks around it: "…we work." and "…we work," alike. */
+const saidOf = (text: string) => plain(text).replace(/^[\p{P}\s]+|[\p{P}\s]+$/gu, '');
+
+/**
+ * What the page uses of the person's input, only as far as it can be read:
+ * - a quote word for word;
+ * - a figure from their data (figuresIn), or a prompt's answers and mentions
+ * from Ansvisor data in one sentence;
+ * - their experience by its own words: EXPERIENCE_SHARE of its runs of three
+ * words, EXPERIENCE_RUNS at least.
+ * An input not given isn't used.
+ */
+export function inputsUsed(
+ pageText: string,
+ inputs: DraftInputs,
+): { experience: boolean; data: boolean; quote: boolean } {
+ const page = plain(pageText);
+
+ const runs = runsOf(inputs.experience);
+ const pageRuns = runsOf(pageText);
+ const shared = [...runs].filter((run) => pageRuns.has(run)).length;
+ const experience =
+ runs.size >= EXPERIENCE_RUNS &&
+ shared >= Math.max(EXPERIENCE_RUNS, Math.ceil(runs.size * EXPERIENCE_SHARE));
+
+ const pageFigures = new Set(figuresIn(pageText));
+ const sentences = sentenceNumbers(pageText);
+ const data =
+ inputs.data.some((table) =>
+ table.rows
+ .flat()
+ .flatMap(figuresIn)
+ .some((n) => pageFigures.has(n)),
+ ) ||
+ inputs.ansvisorData.some((d) =>
+ sentences.some(
+ (numbers) => numbers.has(String(d.answers)) && numbers.has(String(d.mentioned)),
+ ),
+ );
+
+ const quote = inputs.quotes.some((q) => {
+ const said = saidOf(q.text);
+ return said.length > 0 && page.includes(said);
+ });
+ return { experience, data, quote };
+}
diff --git a/web/src/lib/content/next-step.test.ts b/web/src/lib/content/next-step.test.ts
index 47e2e2357..da86137b5 100644
--- a/web/src/lib/content/next-step.test.ts
+++ b/web/src/lib/content/next-step.test.ts
@@ -11,6 +11,7 @@ const todo = (over: Partial<QualityTodo>): QualityTodo => ({
id: 'byline',
done: false,
gain: 15,
+ score: 'eeat',
action: 'pickAuthor',
...over,
});
diff --git a/web/src/lib/content/quality-checks.test.ts b/web/src/lib/content/quality-checks.test.ts
index 475c6121c..9fd59854e 100644
--- a/web/src/lib/content/quality-checks.test.ts
+++ b/web/src/lib/content/quality-checks.test.ts
@@ -220,6 +220,40 @@ describe('trust (Phase 1: figures and links)', () => {
});
});
+describe('Your input (Phase 2, CE-048)', () => {
+ it("counts the person's experience and data in E-E-A-T once the page uses them", () => {
+ const none = eeat({ author: author(), used: { experience: false, data: false } });
+ // byline 15 + bio 10 of 60.
+ expect(none.score).toBe(42);
+ expect(none.checks.map((c) => c.id)).toEqual([
+ 'experience',
+ 'originalData',
+ 'byline',
+ 'authorBio',
+ ]);
+ expect(scoreGain(none, ['experience'])).toBe(33);
+ expect(eeat({ author: author(), used: { experience: true, data: true } }).score).toBe(100);
+ // Before Your input is read: Phase 1's checks alone.
+ expect(eeat({ author: author() }).checks.map((c) => c.id)).toEqual(['byline', 'authorBio']);
+ });
+
+ it("counts an expert's quote in Trust, once Trust is scored", () => {
+ const NOW = Date.parse('2026-10-23T12:00:00Z');
+ const run = (html: string, quote: boolean | null) =>
+ trust({ blocks: trustBlocks(html), links: new Map(), brandDomains: [], quote, now: NOW });
+ const sourced = '<p>Up 40% (<a href="https://src.example/">source</a>).</p>';
+ expect(run(sourced, true).checks).toEqual([
+ { id: 'claimsSourced', points: 30, max: 30 },
+ { id: 'expertQuote', points: TRUST_WEIGHTS.expertQuote, max: TRUST_WEIGHTS.expertQuote },
+ ]);
+ // 30 of 38.
+ expect(run(sourced, false).score).toBe(79);
+ expect(run(sourced, null).checks.map((c) => c.id)).toEqual(['claimsSourced']);
+ // A quote alone doesn't score Trust: one check would set the whole score.
+ expect(run('<p>No figures here.</p>', true).score).toBeNull();
+ });
+});
+
describe('trust (Phase 2: what kind of source each link is, CE-046)', () => {
const NOW = Date.parse('2026-10-23T12:00:00Z');
const run = (html: string, over: { pageType?: string; kept?: string[] } = {}) =>
diff --git a/web/src/lib/content/quality-checks.ts b/web/src/lib/content/quality-checks.ts
index aae4eb120..d9656d6d0 100644
--- a/web/src/lib/content/quality-checks.ts
+++ b/web/src/lib/content/quality-checks.ts
@@ -119,9 +119,33 @@ export function authorProfile(author: ContentAuthor | null): { bio: boolean; lin
* publish gives counts only once the page has it. Experience, data, proof
* and who/how/why are Phase 2.
*/
-export function eeat({ author }: { author: ContentAuthor | null }): Score<EeatCheckId> {
+export function eeat({
+ author,
+ used = null,
+}: {
+ author: ContentAuthor | null;
+ /**
+ * Phase 2 (CE-048): whether the page uses the person's experience and
+ * their data (Brief › Your input, inputsUsed); left out before.
+ */
+ used?: { experience: boolean; data: boolean } | null;
+}): Score<EeatCheckId> {
const { bio, links } = authorProfile(author);
return scoreOf<EeatCheckId>([
+ ...(used
+ ? [
+ {
+ id: 'experience' as const,
+ points: used.experience ? EEAT_WEIGHTS.experience : 0,
+ max: EEAT_WEIGHTS.experience,
+ },
+ {
+ id: 'originalData' as const,
+ points: used.data ? EEAT_WEIGHTS.originalData : 0,
+ max: EEAT_WEIGHTS.originalData,
+ },
+ ]
+ : []),
{ id: 'byline', points: author ? EEAT_WEIGHTS.byline : 0, max: EEAT_WEIGHTS.byline },
{
id: 'authorBio',
@@ -280,6 +304,7 @@ export function trust({
links,
brandDomains,
siteTrust = null,
+ quote = null,
sources: kinds = null,
now,
}: {
@@ -290,6 +315,11 @@ export function trust({
brandDomains: string[];
/** How many of the site's five trust checks pass (CE-043), when read. */
siteTrust?: { score: number } | null;
+ /**
+ * Phase 2 (CE-048): whether the page quotes a real expert from Brief ›
+ * Your input word for word; left out before.
+ */
+ quote?: boolean | null;
/** Phase 2: what each source is (CE-046); left out before. */
sources?: SourceRead | null;
now: number;
@@ -368,6 +398,14 @@ export function trust({
});
}
+ if (quote !== null) {
+ checks.push({
+ id: 'expertQuote',
+ points: quote ? TRUST_WEIGHTS.expertQuote : 0,
+ max: TRUST_WEIGHTS.expertQuote,
+ });
+ }
+
// The site's 5 points weigh with what the page itself shows: alone, they'd
// be the page's whole Trust.
if (siteTrust && checks.length) {
diff --git a/web/src/lib/content/quality-todos.test.ts b/web/src/lib/content/quality-todos.test.ts
index 51aca5c67..57e1bf420 100644
--- a/web/src/lib/content/quality-todos.test.ts
+++ b/web/src/lib/content/quality-todos.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import type { ContentAuthor } from './authors';
-import { eeat } from './quality-checks';
+import { eeat, trust } from './quality-checks';
import { qualityTodos } from './quality-todos';
/** Your to-dos (Quality spec §4, CE-040): only what the person can do, read from the checks. */
@@ -24,8 +24,8 @@ const todos = (a: ContentAuthor | null, hasAuthors = true, canEdit = true) =>
describe('qualityTodos', () => {
it("asks to pick the page's author, with the byline's gain, and lists the profile after it", () => {
expect(todos(null)).toEqual([
- { id: 'byline', done: false, gain: 60, action: 'pickAuthor' },
- { id: 'authorProfile', done: false, gain: 40, action: null },
+ { id: 'byline', done: false, gain: 60, score: 'eeat', action: 'pickAuthor' },
+ { id: 'authorProfile', done: false, gain: 40, score: 'eeat', action: null },
]);
});
@@ -34,19 +34,21 @@ describe('qualityTodos', () => {
id: 'byline',
done: false,
gain: 60,
+ score: 'eeat',
action: 'addAuthor',
});
});
it("keeps the byline done, then asks to complete the author's profile", () => {
expect(todos(author({ bio: null, sameAs: [] }))).toEqual([
- { id: 'byline', done: true, gain: 0, action: 'pickAuthor' },
- { id: 'authorProfile', done: false, gain: 40, action: 'editAuthor' },
+ { id: 'byline', done: true, gain: 0, score: 'eeat', action: 'pickAuthor' },
+ { id: 'authorProfile', done: false, gain: 40, score: 'eeat', action: 'editAuthor' },
]);
expect(todos(author({ sameAs: [] }))[1]).toEqual({
id: 'authorProfile',
done: false,
gain: 20,
+ score: 'eeat',
action: 'editAuthor',
});
});
@@ -74,6 +76,7 @@ describe('qualityTodos', () => {
id: 'placeholders',
done: count === 0,
gain: 0,
+ score: 'eeat',
action: 'showPlaceholder',
count,
});
@@ -116,4 +119,70 @@ describe('qualityTodos', () => {
}),
).toEqual([]);
});
+
+ it('asks for what only the person can give, once Your input is read (CE-048)', () => {
+ const none = { experience: false, data: false, quote: false };
+ const quoted = trust({
+ blocks: [{ tag: 'p', text: 'Sales grew 40% in 2025.', links: [] }],
+ links: new Map(),
+ brandDomains: [],
+ quote: false,
+ now: Date.parse('2026-10-24'),
+ });
+ const read = (
+ used: typeof none,
+ given: typeof none | null = null,
+ trustScore: typeof quoted | null = quoted,
+ ) =>
+ qualityTodos({
+ eeat: eeat({ author: author(), used }),
+ author: author(),
+ hasAuthors: true,
+ used,
+ given,
+ trust: trustScore,
+ }).slice(2);
+ expect(read(none)).toEqual([
+ { id: 'experience', done: false, given: false, gain: 33, score: 'eeat', action: 'addInput' },
+ {
+ id: 'originalData',
+ done: false,
+ given: false,
+ gain: 25,
+ score: 'eeat',
+ action: 'addInput',
+ },
+ {
+ id: 'expertQuote',
+ done: false,
+ given: false,
+ gain: 21,
+ score: 'trust',
+ action: 'addInput',
+ },
+ ]);
+ // Given in Your input, the page not using it yet: still to do, said so.
+ expect(read(none, { experience: true, data: false, quote: true }).map((t) => t.given)).toEqual([
+ true,
+ false,
+ true,
+ ]);
+ // Used: checked off, with no gain left.
+ expect(
+ read(
+ { experience: true, data: true, quote: true },
+ { experience: true, data: true, quote: true },
+ ),
+ ).toEqual([
+ expect.objectContaining({ id: 'experience', done: true, given: false, gain: 0 }),
+ expect.objectContaining({ id: 'originalData', done: true, given: false, gain: 0 }),
+ expect.objectContaining({ id: 'expertQuote', done: true, given: false, gain: 0 }),
+ ]);
+ // Trust not scored yet: a quote's gain isn't made up.
+ expect(read(none, null, null)[2]).toMatchObject({ id: 'expertQuote', gain: 0 });
+ });
+
+ it('has no input to-dos before Your input is read', () => {
+ expect(todos(author()).map((t) => t.id)).toEqual(['byline', 'authorProfile']);
+ });
});
diff --git a/web/src/lib/content/quality-todos.ts b/web/src/lib/content/quality-todos.ts
index a207711cf..c462f1953 100644
--- a/web/src/lib/content/quality-todos.ts
+++ b/web/src/lib/content/quality-todos.ts
@@ -1,5 +1,11 @@
import type { ContentAuthor } from './authors';
-import { authorProfile, scoreGain, type EeatCheckId, type Score } from './quality-checks';
+import {
+ authorProfile,
+ scoreGain,
+ type EeatCheckId,
+ type Score,
+ type TrustCheckId,
+} from './quality-checks';
/**
* Your to-dos (Content Editor Quality spec §4, CE-040): what only the person
@@ -7,24 +13,40 @@ import { authorProfile, scoreGain, type EeatCheckId, type Score } from './qualit
* hand). Everything else is a suggestion the agent can fix. Phase 1's are
* the placeholders the agent left where it had no real name, quote or
* number (CE-044), and the author's: the Content Agent can't add, pick or
- * edit authors.
+ * edit authors. Phase 2 adds what only the person can give (Brief › Your
+ * input, CE-048): their experience, their data and an expert's quote.
*/
-export type QualityTodoId = 'placeholders' | 'byline' | 'authorProfile';
+export type QualityTodoId =
+ | 'placeholders'
+ | 'byline'
+ | 'authorProfile'
+ | 'experience'
+ | 'originalData'
+ | 'expertQuote';
/**
* A to-do's one button: Show (the first placeholder, selected to type over),
* the header's author menu, or Settings › Authors.
*/
-export type QualityTodoAction = 'showPlaceholder' | 'pickAuthor' | 'addAuthor' | 'editAuthor';
+export type QualityTodoAction =
+ | 'showPlaceholder'
+ | 'pickAuthor'
+ | 'addAuthor'
+ | 'editAuthor'
+ | 'addInput';
export interface QualityTodo {
id: QualityTodoId;
done: boolean;
- /** What E-E-A-T gains once it is done; 0 when done, or when no score counts it. */
+ /** What its score gains once it is done; 0 when done, or when no score counts it. */
gain: number;
+ /** The score it raises: E-E-A-T, or Trust for an expert's quote. */
+ score: 'eeat' | 'trust';
/** None while it waits on the one before it. */
action: QualityTodoAction | null;
+ /** Given in Brief › Your input, though the page doesn't use it yet (CE-048). */
+ given?: boolean;
/** How many it is about (placeholders). */
count?: number;
}
@@ -43,6 +65,9 @@ export function qualityTodos({
hasAuthors,
placeholders = { count: 0, had: false },
canEdit = false,
+ used = null,
+ given = null,
+ trust = null,
}: {
eeat: Score<EeatCheckId> | null;
author: ContentAuthor | null;
@@ -54,6 +79,12 @@ export function qualityTodos({
* told who can.
*/
canEdit?: boolean;
+ /** Phase 2 (CE-048): what the page uses of Brief › Your input; left out before. */
+ used?: { experience: boolean; data: boolean; quote: boolean } | null;
+ /** What the person gave there (inputsGiven), used or not. */
+ given?: { experience: boolean; data: boolean; quote: boolean } | null;
+ /** Trust, for an expert quote's gain. */
+ trust?: Score<TrustCheckId> | null;
}): QualityTodo[] {
const fill: QualityTodo[] =
placeholders.count || placeholders.had
@@ -62,6 +93,7 @@ export function qualityTodos({
id: 'placeholders',
done: placeholders.count === 0,
gain: 0,
+ score: 'eeat',
action: 'showPlaceholder',
count: placeholders.count,
},
@@ -72,6 +104,7 @@ export function qualityTodos({
id: 'byline',
done: !!author,
gain: scoreGain(eeat, ['byline']),
+ score: 'eeat',
action: author || hasAuthors ? 'pickAuthor' : 'addAuthor',
};
const { bio, links } = authorProfile(author);
@@ -82,7 +115,37 @@ export function qualityTodos({
id: 'authorProfile',
done: !!author && bio && links,
gain: scoreGain(eeat, ['authorBio']),
+ score: 'eeat',
action: author && canEdit ? 'editAuthor' : null,
},
+ ...(used
+ ? ([
+ {
+ id: 'experience',
+ done: used.experience,
+ given: !used.experience && !!given?.experience,
+ gain: scoreGain(eeat, ['experience']),
+ score: 'eeat',
+ action: 'addInput',
+ },
+ {
+ id: 'originalData',
+ done: used.data,
+ given: !used.data && !!given?.data,
+ gain: scoreGain(eeat, ['originalData']),
+ score: 'eeat',
+ action: 'addInput',
+ },
+ {
+ id: 'expertQuote',
+ done: used.quote,
+ given: !used.quote && !!given?.quote,
+ gain:
+ !used.quote && trust && trust.score !== null ? scoreGain(trust, ['expertQuote']) : 0,
+ score: 'trust',
+ action: 'addInput',
+ },
+ ] satisfies QualityTodo[])
+ : []),
];
}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index cd97573a9..895b54d50 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -1336,6 +1336,44 @@ export type Database = {
},
]
}
+ content_draft_inputs: {
+ Row: {
+ ansvisor_data: Json
+ data: Json
+ draft_id: string
+ experience: string | null
+ quotes: Json
+ updated_at: string
+ updated_by: string | null
+ }
+ Insert: {
+ ansvisor_data?: Json
+ data?: Json
+ draft_id: string
+ experience?: string | null
+ quotes?: Json
+ updated_at?: string
+ updated_by?: string | null
+ }
+ Update: {
+ ansvisor_data?: Json
+ data?: Json
+ draft_id?: string
+ experience?: string | null
+ quotes?: Json
+ updated_at?: string
+ updated_by?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "content_draft_inputs_draft_id_fkey"
+ columns: ["draft_id"]
+ isOneToOne: true
+ referencedRelation: "content_drafts"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
content_draft_ready_log: {
Row: {
created_at: string