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-editor): ask for the proof of the page's own claims as to-dos (CE-049, part b) (#1468)

Cihanb28c19d07f8b
diff --git a/web/messages/en.json b/web/messages/en.json
index f6fa1bcb3..1ad69a9fd 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -4564,6 +4564,7 @@
},
"linksPending": "Still reading {count, plural, one {# of the page's links} other {# of the page's links}}, so Trust may change.",
"claimsReading": "Still reading the claims in your own words, so Trust may change.",
+ "pageReading": "Still reading the page for claims that need your proof, so your to-dos may change.",
"datesNote": "The dates are today's: change them if the page goes out on another day.",
"headlineLeftOut": "The title still has a placeholder in square brackets, so the code leaves the headline out. Fill it in, and the headline comes back here.",
"states": {
@@ -4679,6 +4680,26 @@
"detail": "Prices, your trial and other facts read from your own site: the page is checked against the ones you approve",
"done": "Your brand facts are reviewed"
},
+ "proof": {
+ "title": {
+ "award": "Link the award page for “{claim}”",
+ "certification": "{site, select, b2b {Link the audit report or trust page for “{claim}”} ecommerce {Link the certificate or lab result for “{claim}”} other {Link the license or certificate for “{claim}”}}",
+ "research": "Link the study behind “{claim}”",
+ "rating": "Link the review source for “{claim}”",
+ "ranking": "Link the ranking or test behind “{claim}”",
+ "number": "Link the source of “{claim}”",
+ "test": "{site, select, ecommerce {Link the test report for “{claim}”} other {Link your test result for “{claim}”}}",
+ "customer_case": "Link the customer case for “{claim}”",
+ "unknown": "What proves “{claim}”?"
+ },
+ "next": "add proof for “{claim}”",
+ "detail": {
+ "default": "Only you have this proof: link it on your site or where it's published",
+ "soften": "Link its proof, or soften the claim",
+ "customerCase": "Link the published case, and only with the customer's permission to name them"
+ },
+ "done": "The proof is linked"
+ },
"title": "Your to-dos",
"left": "{count, plural, =0 {All done} other {# left · only you can do these}}",
"done": "Done",
@@ -4735,7 +4756,8 @@
"addAuthor": "Add now",
"editAuthor": "Edit now",
"addInput": "Add now",
- "reviewBrandFacts": "Review now"
+ "reviewBrandFacts": "Review now",
+ "addProof": "Add now"
},
"later": "Later"
},
@@ -4751,11 +4773,15 @@
"aiCheck": "AI check",
"addSource": "Add source",
"addSourceTo": "Add a source to “{claim}”",
+ "addProof": "Add proof link",
+ "addProofFor": "Add a proof link to “{claim}”",
"remove": "Remove",
"removeClaim": "Remove “{sentence}” from the page",
"claimNoSource": "No source for this claim. Add a source, or take it out. Content Agent will not make one up.",
"claimsPaused": "Claims in your own words wait for an AI check: this month's AI usage is used up. They're read again when it renews.",
"claimsLimited": "Today's AI checks of this page's claims are used up. Paragraphs you change now are checked when you open the page again tomorrow.",
+ "pagePaused": "Claims that need your proof wait for an AI read of the page: this month's AI usage is used up. The page is read again when it renews.",
+ "pageLimited": "Today's AI reads of this page are used up. Changes you make now are read when you open the page again tomorrow.",
"aiPaused": "Sources the rules can't place wait for an AI check: this month's AI usage is used up. They count again when it renews.",
"keepFailed": "Couldn't keep the source. Try again.",
"confirmFailed": "Couldn't save that. Try again.",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsx
index 0c17daa43..e0662c306 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.tsx
@@ -119,7 +119,8 @@ export function BeforePublish({
const authorsRead = quality.eeat !== null;
const trust = quality.trust?.score ?? null;
const below = trust !== null && trust < TRUST_GATE;
- // The biggest of what would raise Trust: the warning's reason.
+ // The biggest of what would raise Trust: the warning's reason. The claims
+ // a proof to-do covers count here too: the warning names them.
const [fix] = below
? trustSuggestions(tQuality, quality.trust)
.filter((s) => s.gain > 0)
@@ -221,6 +222,11 @@ export function BeforePublish({
{t('claimsReading')}
</p>
)}
+ {quality.pageReading && (
+ <p role="status" className="text-xs text-muted-foreground">
+ {t('pageReading')}
+ </p>
+ )}
<ul className="divide-y rounded-xl border text-sm">
{rows.map((row) => (
<li key={row.title} className="flex items-start gap-2.5 px-3 py-2.5">
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 e43da9e0d..a882fed25 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
@@ -106,9 +106,10 @@ import {
unplacedSites,
type ClaimMark,
} from '@/lib/content/quality-checks';
-import { qualityTodos } from '@/lib/content/quality-todos';
+import { proofKey, qualityTodos } from '@/lib/content/quality-todos';
import { readability, sentencesOf } from '@/lib/content/readability';
import { brandFactsPath, factMismatches } from '@/lib/content/brand-facts';
+import { MAX_PROOF_TODOS, proofsOnPage } from '@/lib/content/page-read';
import {
liveSkips,
nextStep,
@@ -161,6 +162,7 @@ import { WeakSourcesMarks, weakSourcesKey } from './_weak-sources';
import { ClaimMarksExtension, claimMarksKey, textRanges, writingBlock } from './_claim-marks';
import { useClaims } from './_use-claims';
import { useBrandFacts } from './_use-brand-facts';
+import { usePageRead } from './_use-page-read';
import { useSourceClasses } from './_use-source-classes';
import { HeaderTip } from './_header-tip';
import {
@@ -676,6 +678,25 @@ export function DraftEditor({
editor && !editor.isDestroyed && editor.isFocused ? writingBlock(editor) : null,
);
const { blocks: claimBlocks, recheck: recheckClaims } = claimsRead;
+ // The page's own claims that need the brand's proof (CE-049), read from
+ // the whole page after a save: proof to-dos while their paragraph has no
+ // link, and its own-site link counts as their source.
+ // Only changes on their way hold the ask, as the claims': not a failed
+ // save, a conflict or a page too large.
+ const pageRead = usePageRead(draft.id, autosave.savedAt, sourcesOn, saving);
+ const proofAsks = useMemo(
+ () => (pageRead.read ? proofsOnPage(pageBlocks, pageRead.read.proofs) : []),
+ [pageRead.read, pageBlocks],
+ );
+ // A proof to-do asked for this session stays, checked once it has a link.
+ const [hadProofs, setHadProofs] = useState<ReadonlySet<string>>(() => new Set());
+ // The ones shown open: the first MAX_PROOF_TODOS with no link, as the to-dos list them.
+ const newProofs = proofAsks
+ .filter((ask) => !ask.linked)
+ .slice(0, MAX_PROOF_TODOS)
+ .map(proofKey)
+ .filter((key) => !hadProofs.has(key));
+ if (newProofs.length > 0) setHadProofs(new Set([...hadProofs, ...newProofs]));
// Out of the editor (to Quality, to Before you publish): the block left
// for later is read too.
useEffect(() => {
@@ -710,6 +731,7 @@ export function DraftEditor({
sources: sourceRead,
claims: claimBlocks,
brandFacts: factCheck,
+ proofs: proofAsks,
now: Date.now(),
})
: null,
@@ -724,6 +746,7 @@ export function DraftEditor({
sourceRead,
claimBlocks,
factCheck,
+ proofAsks,
],
);
// Their links underlined in the draft, Quality's suggestion naming them.
@@ -842,6 +865,7 @@ export function DraftEditor({
given: inputs ? inputsGiven(inputs) : null,
trust: trustScore,
brandFacts: brandFacts ? { pending: pendingFacts, had: hadPendingFacts } : null,
+ proofs: sourcesOn ? { asks: proofAsks, had: hadProofs } : null,
confirmed: authorConfirmed,
})
: [];
@@ -862,6 +886,10 @@ export function DraftEditor({
claimsPaused: claimsRead.paused,
claimsLimited: claimsRead.limited,
claimsReading: claimsRead.reading,
+ pagePaused: pageRead.paused,
+ pageLimited: pageRead.limited,
+ pageReading: pageRead.reading,
+ siteType,
brandFactsPath: sourcesOn ? brandFactsPath(draft.brandId) : null,
authorConfirmed,
authorConfirming: confirming,
@@ -894,8 +922,10 @@ export function DraftEditor({
linksPending === 0 &&
!claimsRead.reading &&
!sourcesReading &&
- // Phase 2: the brand's approved facts, which Trust checks the page against.
+ // Phase 2: the brand's approved facts, which Trust checks the page
+ // against, and the page's read (its proof to-dos; what it finds scores).
!(sourcesOn && factsState.status === 'loading') &&
+ !pageRead.reading &&
// Phase 2 reads the page as saved: an edit's score waits for its save.
!(sourcesOn && saving);
const [shownQuality, setShownQuality] = useState<{ score: number | null } | null>(null);
@@ -2062,7 +2092,9 @@ export function DraftEditor({
// a minute): they move Trust, which a proof skip was made at. Only the
// dropping waits; the Next step shows meanwhile, each skip held against
// its step's state as it is.
- factsState.status !== 'loading';
+ factsState.status !== 'loading' &&
+ // The proof to-dos (CE-049) come with the page's read, seconds after it opens.
+ (!qualityOn || pageRead.settled);
const staleSkips =
nextRead && Object.keys(liveSkips(nextState)).length !== Object.keys(skipped).length;
useEffect(() => {
@@ -2759,6 +2791,7 @@ export function DraftEditor({
onShowPlaceholder={showFirstPlaceholder}
onPickAuthor={() => setAuthorMenuOpen(true)}
onAddInput={addInput}
+ onAddSource={sourcesOn ? addSource : undefined}
onLater={nudge.later}
onAct={nudge.close}
/>
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 d72089169..a080749e3 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
@@ -55,6 +55,7 @@ let container: HTMLDivElement;
let root: Root;
const onPickAuthor = vi.fn();
const onShowPlaceholder = vi.fn();
+const onAddSource = vi.fn();
const MOMENTS: NudgeMoment[] = ['agent', 'acceptAll', 'markReady'];
/** The editor's part: the hook, a button per moment, and the nudge while it shows. */
@@ -75,6 +76,7 @@ function Harness({ todos, author }: { todos: QualityTodo[]; author: ContentAutho
}}
onShowPlaceholder={onShowPlaceholder}
onPickAuthor={onPickAuthor}
+ onAddSource={onAddSource}
onLater={nudge.later}
onAct={nudge.close}
/>
@@ -102,6 +104,7 @@ beforeEach(() => {
sessionStorage.clear();
onPickAuthor.mockReset();
onShowPlaceholder.mockReset();
+ onAddSource.mockReset();
container = document.createElement('div');
root = createRoot(container);
});
@@ -159,6 +162,34 @@ describe('NextNudge', () => {
);
});
+ it("selects a proof to-do's claim for its link, each claim once per moment (CE-049)", async () => {
+ const proof = (claim: string): QualityTodo => ({
+ id: 'proof',
+ key: `proof:${claim}\nWe are ${claim}.`,
+ done: false,
+ gain: 4,
+ score: 'trust',
+ action: 'addProof',
+ proof: { claim, block: `We are ${claim}.`, kind: 'award', sentence: `We are ${claim}.` },
+ });
+ await render([proof('award-winning'), proof('SOC 2 certified')]);
+ await act(async () => nudgeAt('agent'));
+ expect(nudge()!.textContent).toBe(
+ 'Next for you: add proof for “award-winning” · 1 of 2Add nowLater',
+ );
+ await act(async () => button('Add now').click());
+ expect(onAddSource).toHaveBeenCalledWith({
+ text: 'award-winning',
+ sentence: 'We are award-winning.',
+ block: 'We are award-winning.',
+ });
+ expect(nudge()).toBeNull();
+ // The next claim is another to-do: the same moment shows it.
+ await render([proof('SOC 2 certified')]);
+ await act(async () => nudgeAt('agent'));
+ expect(nudge()!.textContent).toContain('add proof for “SOC 2 certified”');
+ });
+
it('counts the open ones and skips the done', async () => {
await render([{ ...pick, done: true }, profile], ada);
await act(async () => nudgeAt('markReady'));
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 96a2eb288..1cc7c204e 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
@@ -3,6 +3,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslations } from 'next-intl';
import { Link } from '@/i18n/navigation';
+import type { ClaimMark } from '@/lib/content/quality-checks';
import type { QualityTodo } from '@/lib/content/quality-todos';
import { MANAGE_AUTHORS_PATH } from './_author-menu';
import { useTodoCopy, type QualityRead } from './_quality-tab';
@@ -58,7 +59,7 @@ export function useNextNudge(draftId: string, todos: QualityTodo[]) {
const first = openNow.current[0];
if (!first) return;
const seen = readSeen(draftId);
- const step = `${moment}:${first.id}`;
+ const step = `${moment}:${first.key ?? first.id}`;
if (seen.later || seen.steps.includes(step)) return;
writeSeen(draftId, { ...seen, steps: [...seen.steps, step] });
setShowing(true);
@@ -90,16 +91,20 @@ export function NextNudge({
onShowPlaceholder,
onPickAuthor,
onAddInput,
+ onAddSource,
onLater,
onAct,
}: {
shown: { todo: QualityTodo; count: number } | null;
- quality: Pick<QualityRead, 'author' | 'team' | 'canEdit' | 'brandFactsPath'>;
+ quality: Pick<QualityRead, 'author' | 'team' | 'canEdit' | 'brandFactsPath'> &
+ Partial<Pick<QualityRead, 'siteType'>>;
/** Selects the page's first placeholder, to type over. */
onShowPlaceholder: () => void;
onPickAuthor: () => void;
/** Opens Brief › Your input (CE-048). */
onAddInput?: () => void;
+ /** A proof to-do's: its claim selected, the link dialog open (CE-049). */
+ onAddSource?: (claim: ClaimMark) => void;
onLater: () => void;
/** It was acted on: it goes. */
onAct: () => void;
@@ -166,6 +171,21 @@ export function NextNudge({
{t('act.addInput')}
</button>
)
+ ) : action === 'addProof' ? (
+ onAddSource &&
+ shown.todo.proof && (
+ <button
+ type="button"
+ className={actClass}
+ onClick={() => {
+ onAct();
+ const { claim, sentence, block } = shown.todo.proof!;
+ onAddSource({ text: claim, sentence, block });
+ }}
+ >
+ {t('act.addProof')}
+ </button>
+ )
) : action === 'reviewBrandFacts' ? (
quality.brandFactsPath && (
<Link href={quality.brandFactsPath} className={actClass} onClick={onAct}>
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 2783314d2..f3ed73507 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
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import messages from '../../../../../../../../messages/en.json';
import { eeat, trust, trustBlocks, type LinkCheck } from '@/lib/content/quality-checks';
import type { ContentAuthor } from '@/lib/content/authors';
+import { proofsOnPage } from '@/lib/content/page-read';
import { qualityTodos } from '@/lib/content/quality-todos';
import type { Readability } from '@/lib/content/readability';
@@ -90,6 +91,7 @@ const onPickAuthor = vi.fn();
const onShowPlaceholder = vi.fn();
const onAddInput = vi.fn();
const onKeep = vi.fn();
+const onAddSource = vi.fn();
const onConfirmAuthor = vi.fn();
async function render(quality: QualityRead | Readability | null) {
@@ -104,6 +106,7 @@ async function render(quality: QualityRead | Readability | null) {
onPickAuthor={onPickAuthor}
onAddInput={onAddInput}
onKeep={onKeep}
+ onAddSource={onAddSource}
onConfirmAuthor={onConfirmAuthor}
/>
</NextIntlClientProvider>,
@@ -115,6 +118,7 @@ beforeEach(() => {
onShow.mockReset();
onPickAuthor.mockReset();
onKeep.mockReset();
+ onAddSource.mockReset();
onConfirmAuthor.mockReset();
container = document.createElement('div');
root = createRoot(container);
@@ -557,6 +561,68 @@ describe('QualityTab', () => {
);
});
+ it("asks for the proof of the page's own claims by kind and business, with Add proof link (CE-049)", async () => {
+ const html =
+ '<p>Ledgerly is 40% faster than spreadsheets.</p>' +
+ '<p>Every plan is SOC 2 certified.</p>' +
+ '<p>Teams forecast 3x more often.</p>';
+ const blocks = trustBlocks(html);
+ const proofs = proofsOnPage(blocks, [
+ { claim: '40% faster', block: blocks[0].text, kind: 'test' },
+ { claim: 'SOC 2 certified', block: blocks[1].text, kind: 'certification' },
+ { claim: 'the best', block: 'a paragraph since rewritten', kind: 'ranking' },
+ ]);
+ const trustScore = trust({
+ blocks,
+ links: new Map(),
+ brandDomains: ['acme.com'],
+ proofs,
+ now: Date.parse('2026-10-24T12:00:00Z'),
+ });
+ const quality = (siteType: QualityRead['siteType']): QualityRead => ({
+ ...read(null),
+ trust: trustScore,
+ siteType,
+ pageLimited: true,
+ todos: qualityTodos({
+ eeat: null,
+ author: null,
+ hasAuthors: true,
+ trust: trustScore,
+ proofs: { asks: proofs, had: new Set() },
+ }),
+ });
+ await render(quality('b2b'));
+ const todos = container.querySelector('[aria-label="Your to-dos"]')!;
+ const rows = [...todos.querySelectorAll('li')].map((li) => li.textContent);
+ expect(rows).toEqual([
+ expect.stringMatching(
+ /^Link your test result for “40% faster” · To doOnly you have this proof/,
+ ),
+ expect.stringMatching(/^Link the audit report or trust page for “SOC 2 certified”/),
+ ]);
+ // The page's other figure is still the agent's to source: one sentence, its share of the gain.
+ const suggestions = container.querySelector('[aria-label="What would raise it"]')!;
+ expect(suggestions.textContent).toContain('1 sentence with a figure has no source');
+ expect(container.textContent).toContain("Today's AI reads of this page are used up.");
+ await act(async () =>
+ container
+ .querySelector<HTMLButtonElement>('[aria-label="Add a proof link to “40% faster”"]')!
+ .click(),
+ );
+ expect(onAddSource).toHaveBeenCalledWith({
+ text: '40% faster',
+ sentence: 'Ledgerly is 40% faster than spreadsheets.',
+ block: 'Ledgerly is 40% faster than spreadsheets.',
+ });
+
+ await render(quality('ecommerce'));
+ expect(container.textContent).toContain(
+ 'Link the certificate or lab result for “SOC 2 certified”',
+ );
+ expect(container.textContent).toContain('Link the test report for “40% faster”');
+ });
+
it("shows the site's trust, what is missing and the way to Site Audit", async () => {
const siteTrust = {
checks: {
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 bee62765c..338cca4f4 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
@@ -61,6 +61,13 @@ export interface QualityRead {
claimsReading?: boolean;
/** Where the brand's facts are approved: Brand settings › Brand facts (CE-047). */
brandFactsPath?: string | null;
+ /** The brand's business type: a proof to-do's wording follows it (CE-049). */
+ siteType?: 'b2b' | 'ecommerce' | 'b2c';
+ /** The page read for proof waits: the AI budget is spent, or its reads for the day made (CE-049). */
+ pagePaused?: boolean;
+ pageLimited?: boolean;
+ /** The page read for proof is under way: its to-dos may change. */
+ pageReading?: boolean;
/**
* With no author picked, what the person confirmed of the author their
* site names (00271): a real person, and their profile there.
@@ -137,7 +144,10 @@ export function QualityTab({
];
const { todos } = quality;
const todosLeft = todos.filter((todo) => !todo.done).length;
- const suggestions = [...readabilitySuggestions(t, readability), ...trustSuggestions(t, trust)]
+ const suggestions = [
+ ...readabilitySuggestions(t, readability),
+ ...trustSuggestions(t, trust, proofSentences(todos)),
+ ]
.filter((s) => s.gain > 0)
.sort((a, b) => b.gain - a.gain);
// Every live check has its points: none to raise, none of the person's left
@@ -186,12 +196,13 @@ export function QualityTab({
<ul className="space-y-2">
{todos.map((todo) => (
<TodoRow
- key={todo.id}
+ key={todo.key ?? todo.id}
todo={todo}
quality={quality}
onShowPlaceholder={onShowPlaceholder}
onPickAuthor={onPickAuthor}
onAddInput={onAddInput}
+ onAddSource={onAddSource}
onConfirm={onConfirmAuthor}
/>
))}
@@ -281,6 +292,10 @@ export function QualityTab({
{quality.aiPaused && <p className="text-xs text-muted-foreground">{t('aiPaused')}</p>}
{quality.claimsPaused && <p className="text-xs text-muted-foreground">{t('claimsPaused')}</p>}
+ {quality.pagePaused && <p className="text-xs text-muted-foreground">{t('pagePaused')}</p>}
+ {quality.pageLimited && !quality.pagePaused && (
+ <p className="text-xs text-muted-foreground">{t('pageLimited')}</p>
+ )}
{quality.claimsLimited && !quality.claimsPaused && (
<p className="text-xs text-muted-foreground">{t('claimsLimited')}</p>
)}
@@ -318,7 +333,12 @@ export function useTodoCopy() {
const t = useTranslations('contentEditor.editor.quality.todos');
return (
todo: QualityTodo,
- { author, team, canEdit }: Pick<QualityRead, 'author' | 'team' | 'canEdit'>,
+ {
+ author,
+ team,
+ canEdit,
+ siteType,
+ }: Pick<QualityRead, 'author' | 'team' | 'canEdit'> & Partial<Pick<QualityRead, 'siteType'>>,
) => {
if (todo.id === 'placeholders') {
const count = todo.count ?? 0;
@@ -343,6 +363,21 @@ export function useTodoCopy() {
: t('byline.detail.pickAuthor', { byline: team }),
};
}
+ // The page's own claims, their proof asked for by kind and business (CE-049).
+ if (todo.id === 'proof' && todo.proof) {
+ const { claim, kind } = todo.proof;
+ return {
+ title: t(`proof.title.${kind}`, { claim, site: siteType ?? 'b2b' }),
+ next: t('proof.next', { claim }),
+ detail: todo.done
+ ? t('proof.done')
+ : kind === 'ranking' || kind === 'unknown'
+ ? t('proof.detail.soften')
+ : kind === 'customer_case'
+ ? t('proof.detail.customerCase')
+ : t('proof.detail.default'),
+ };
+ }
// The brand's facts read from its site, to approve (CE-047).
if (todo.id === 'brandFacts') {
const count = todo.count ?? 0;
@@ -404,6 +439,7 @@ function TodoRow({
onShowPlaceholder,
onPickAuthor,
onAddInput,
+ onAddSource,
onConfirm,
}: {
todo: QualityTodo;
@@ -411,6 +447,8 @@ function TodoRow({
onShowPlaceholder: () => void;
onPickAuthor: () => void;
onAddInput?: () => void;
+ /** A proof to-do's Add proof link: its claim selected, the link dialog open (CE-049). */
+ onAddSource?: (claim: ClaimMark) => void;
onConfirm?: (what: 'real' | 'profile', on: boolean) => void;
}) {
const t = useTranslations('contentEditor.editor.quality');
@@ -496,6 +534,25 @@ function TodoRow({
<Button variant="outline" size="sm" className="h-7 shrink-0" onClick={onPickAuthor}>
{t('pickAuthor')}
</Button>
+ ) : todo.action === 'addProof' ? (
+ onAddSource &&
+ todo.proof && (
+ <Button
+ variant="outline"
+ size="sm"
+ className="h-7 shrink-0"
+ aria-label={t('addProofFor', { claim: todo.proof.claim })}
+ onClick={() =>
+ onAddSource({
+ text: todo.proof!.claim,
+ sentence: todo.proof!.sentence,
+ block: todo.proof!.block,
+ })
+ }
+ >
+ {t('addProof')}
+ </Button>
+ )
) : todo.action === 'reviewBrandFacts' ? (
quality.brandFactsPath && (
<Link
@@ -545,23 +602,33 @@ export type TrustSuggestion = Suggestion & { check: TrustCheckId; count: number
* founding year that differs from the brand's approved facts, listed before
* Trust is scored too, as a broken link is.
*/
-export function trustSuggestions(t: T, trust: TrustRead | null): TrustSuggestion[] {
+export function trustSuggestions(
+ t: T,
+ trust: TrustRead | null,
+ covered: ReadonlySet<string> = new Set(),
+): TrustSuggestion[] {
if (!trust) return [];
const out: TrustSuggestion[] = [];
- if (trust.unsourced.length) {
+ // A sentence a proof to-do asks the person to prove isn't the agent's to
+ // source as well (CE-049).
+ const unsourced = trust.unsourced.filter((sentence) => !covered.has(sentence));
+ if (unsourced.length) {
// Phase 2 (CE-045): claims the model read count with the figures, so
// the line says claims; Add source and Remove act on the page's first.
const claims = trust.aiClaims > 0;
- const first = trust.unsourced[0];
+ const first = unsourced[0];
out.push({
key: 'trust:claimsSourced',
check: 'claimsSourced',
score: 'trust',
- gain: trustGain(trust, ['claimsSourced']),
+ // Each sentence's share: the covered ones' is their to-dos'.
+ gain: Math.round(
+ (trustGain(trust, ['claimsSourced']) * unsourced.length) / trust.unsourced.length,
+ ),
line: t(claims ? 'checks.claimsSourced.lineClaims' : 'checks.claimsSourced.line', {
- count: trust.unsourced.length,
+ count: unsourced.length,
}),
- count: trust.unsourced.length,
+ count: unsourced.length,
detail: t(claims ? 'checks.claimsSourced.detailClaims' : 'checks.claimsSourced.detail'),
show: first,
ai: claims,
@@ -693,3 +760,8 @@ function detail(t: T, check: ReadabilityCheck): string {
}
return t(`checks.${check.id}.detail`);
}
+
+/** The sentences the open proof to-dos ask the person to prove (CE-049). */
+export function proofSentences(todos: readonly QualityTodo[]): ReadonlySet<string> {
+ return new Set(todos.flatMap((todo) => (todo.proof && !todo.done ? [todo.proof.sentence] : [])));
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-page-read.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-page-read.test.tsx
new file mode 100644
index 000000000..f42e149fb
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-page-read.test.tsx
@@ -0,0 +1,163 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const readDraftPage = vi.fn();
+vi.mock('@/lib/actions/content-drafts', () => ({
+ readDraftPage: (...args: unknown[]) => readDraftPage(...args),
+}));
+
+const { PROOF_READ_DELAY_MS, PROOF_READ_EVERY_MS, PROOF_READ_SLACK_MS, usePageRead } =
+ await import('./_use-page-read');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+/**
+ * The page's read for proof (Quality CE-049): asked a few seconds after a
+ * save, a minute apart at most, one at a time, not with changes to save;
+ * a kept answer is asked about again; a spent budget or the day's reads
+ * stop the asks.
+ */
+
+let container: HTMLDivElement;
+let root: Root;
+const PAGE = {
+ spots: [],
+ proofs: [{ claim: 'waterproof', block: 'Our pack is waterproof.', kind: 'certification' }],
+ regulated: null,
+};
+
+function Probe({ savedAt, unsaved = false }: { savedAt: string; unsaved?: boolean }) {
+ const state = usePageRead('d1', savedAt, true, unsaved);
+ return (
+ <pre
+ data-read={JSON.stringify(state.read)}
+ data-reading={String(state.reading)}
+ data-paused={String(state.paused)}
+ data-limited={String(state.limited)}
+ data-settled={String(state.settled)}
+ />
+ );
+}
+const attr = (name: string) => container.querySelector('pre')!.getAttribute(name)!;
+const render = (savedAt: string, unsaved = false) =>
+ act(async () => root.render(<Probe savedAt={savedAt} unsaved={unsaved} />));
+const wait = (ms: number) => act(async () => vi.advanceTimersByTimeAsync(ms));
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ readDraftPage
+ .mockReset()
+ .mockResolvedValue({ ...PAGE, pending: false, limited: false, paused: false });
+ container = document.createElement('div');
+ root = createRoot(container);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ vi.useRealTimers();
+});
+
+describe('usePageRead', () => {
+ it('asks a few seconds after a save, not while there are changes to save, a minute apart', async () => {
+ await render('s1', true);
+ await wait(PROOF_READ_EVERY_MS);
+ expect(readDraftPage).not.toHaveBeenCalled();
+ await render('s1');
+ await wait(PROOF_READ_DELAY_MS);
+ expect(readDraftPage).toHaveBeenCalledWith('d1');
+ expect(JSON.parse(attr('data-read'))).toEqual(PAGE);
+ await render('s2');
+ await wait(PROOF_READ_DELAY_MS);
+ expect(readDraftPage).toHaveBeenCalledTimes(1);
+ // A few seconds past the minute: the API counts it from when the last ask reached it.
+ await wait(PROOF_READ_EVERY_MS);
+ expect(readDraftPage).toHaveBeenCalledTimes(1);
+ await wait(PROOF_READ_SLACK_MS);
+ expect(readDraftPage).toHaveBeenCalledTimes(2);
+ });
+
+ it('counts a save not asked about yet as reading, until its ask is answered or fails (review, #1468)', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ await render('s1');
+ expect(attr('data-reading')).toBe('true');
+ await wait(PROOF_READ_DELAY_MS);
+ expect(attr('data-reading')).toBe('false');
+ // A save within the API's minute: not asked yet, still reading.
+ await render('s2');
+ await wait(PROOF_READ_DELAY_MS);
+ expect(readDraftPage).toHaveBeenCalledTimes(1);
+ expect(attr('data-reading')).toBe('true');
+ readDraftPage.mockResolvedValueOnce({ error: 'failed' });
+ await wait(PROOF_READ_EVERY_MS + PROOF_READ_SLACK_MS);
+ expect(readDraftPage).toHaveBeenCalledTimes(2);
+ // Failed: nothing more comes before the next save.
+ expect(attr('data-reading')).toBe('false');
+ error.mockRestore();
+ });
+
+ it('asks again for a kept answer a minute later, without a save', async () => {
+ readDraftPage.mockResolvedValueOnce({ ...PAGE, pending: true, limited: false, paused: false });
+ await render('s1');
+ await wait(PROOF_READ_DELAY_MS);
+ expect(attr('data-reading')).toBe('true');
+ await wait(PROOF_READ_EVERY_MS + PROOF_READ_SLACK_MS);
+ expect(readDraftPage).toHaveBeenCalledTimes(2);
+ expect(attr('data-reading')).toBe('false');
+ });
+
+ it('stops for the session once the budget is spent or the day’s reads are made', async () => {
+ readDraftPage.mockResolvedValueOnce({ ...PAGE, pending: false, limited: false, paused: true });
+ await render('s1');
+ await wait(PROOF_READ_DELAY_MS);
+ expect(attr('data-paused')).toBe('true');
+ await render('s2');
+ await wait(PROOF_READ_EVERY_MS * 2);
+ expect(readDraftPage).toHaveBeenCalledTimes(1);
+
+ act(() => root.unmount());
+ root = createRoot(container);
+ readDraftPage
+ .mockReset()
+ .mockResolvedValue({ ...PAGE, pending: false, limited: true, paused: false });
+ await render('s1');
+ await wait(PROOF_READ_DELAY_MS);
+ expect(attr('data-limited')).toBe('true');
+ await render('s2');
+ await wait(PROOF_READ_EVERY_MS * 2);
+ expect(readDraftPage).toHaveBeenCalledTimes(1);
+ });
+
+ it('is settled once its first answer is in, and not reading after a kept answer’s ask fails', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ readDraftPage
+ .mockResolvedValueOnce({ ...PAGE, pending: true, limited: false, paused: false })
+ .mockResolvedValueOnce({ error: 'failed' });
+ await render('s1');
+ expect(attr('data-settled')).toBe('false');
+ await wait(PROOF_READ_DELAY_MS);
+ expect(attr('data-settled')).toBe('true');
+ expect(attr('data-reading')).toBe('true');
+ await wait(PROOF_READ_EVERY_MS + PROOF_READ_SLACK_MS);
+ expect(readDraftPage).toHaveBeenCalledTimes(2);
+ expect(attr('data-reading')).toBe('false');
+ error.mockRestore();
+ });
+
+ it('stops silently when the API has it off, and waits for a save after a failure', async () => {
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ readDraftPage.mockResolvedValueOnce({ error: 'failed' });
+ await render('s1');
+ await wait(PROOF_READ_DELAY_MS);
+ await wait(PROOF_READ_EVERY_MS * 2);
+ expect(readDraftPage).toHaveBeenCalledTimes(1);
+ readDraftPage.mockResolvedValueOnce({ error: 'off' });
+ await render('s2');
+ await wait(PROOF_READ_EVERY_MS);
+ expect(readDraftPage).toHaveBeenCalledTimes(2);
+ await render('s3');
+ await wait(PROOF_READ_EVERY_MS * 2);
+ expect(readDraftPage).toHaveBeenCalledTimes(2);
+ error.mockRestore();
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-page-read.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-page-read.ts
new file mode 100644
index 000000000..27fb0dbc0
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-page-read.ts
@@ -0,0 +1,137 @@
+'use client';
+
+import { useEffect, useRef, useState } from 'react';
+import { readDraftPage } from '@/lib/actions/content-drafts';
+import type { PageRead } from '@/lib/content/page-read';
+
+/** How long after a save the page is asked about, as the claims are. */
+export const PROOF_READ_DELAY_MS = 3_000;
+/** Asks no closer together than this: the API reads a changed page once a minute. */
+export const PROOF_READ_EVERY_MS = 60_000;
+/**
+ * Slack on the API's minute: it counts from when the last ask reached it,
+ * which may be a little after the editor sent it.
+ */
+export const PROOF_READ_SLACK_MS = 5_000;
+
+export interface PageReadState {
+ /** The page's spots and proof asks, null until the first read. */
+ read: PageRead | null;
+ /** The workspace's AI budget is spent: no more asks this session. */
+ paused: boolean;
+ /** The draft's page reads for the day are made: no more asks this session. */
+ limited: boolean;
+ /**
+ * An ask is out, the page changed within the API's minute, or a save is
+ * still to be asked about (its read may move the scores).
+ */
+ reading: boolean;
+ /**
+ * The read's first answer is in (a read, a failure, its limits, or off):
+ * what waits on the proof to-dos (Next step's skips) can read them.
+ */
+ settled: boolean;
+}
+
+/**
+ * The page's read for proof (Quality CE-049). The API reads the draft as
+ * saved and keeps its read by the page's hash, so the editor asks a few
+ * seconds after a save, PROOF_READ_EVERY_MS apart at most, one ask at a
+ * time, and not while there are changes to save. An answer the API kept
+ * from before the page changed (`pending`) is asked about again a minute
+ * later, without a save. A spent AI budget or the day's reads made stop the
+ * asks for the session; an API with them off stops them silently; a failed
+ * ask waits for the next save.
+ */
+export function usePageRead(
+ draftId: string,
+ savedAt: string,
+ enabled: boolean,
+ unsaved: boolean,
+): PageReadState {
+ const [read, setRead] = useState<PageRead | null>(null);
+ const [paused, setPaused] = useState(false);
+ const [limited, setLimited] = useState(false);
+ const [off, setOff] = useState(false);
+ const [failed, setFailed] = useState(false);
+ const [out, setOut] = useState(false);
+ const [pending, setPending] = useState(false);
+ // The save the last ask went out for: a later one is still to be read.
+ const [askedSave, setAskedSave] = useState<string | null>(null);
+ // Bumped when the next ask needn't wait for a save.
+ const [again, setAgain] = useState(0);
+ const asking = useRef(false);
+ const latest = useRef(savedAt);
+ const askedFor = useRef<string | null>(null);
+ const lastAsk = useRef(0);
+ const left = useRef(false);
+ const open = useRef(true);
+ useEffect(() => {
+ latest.current = savedAt;
+ });
+ useEffect(() => {
+ open.current = true;
+ return () => {
+ open.current = false;
+ };
+ }, []);
+
+ useEffect(() => {
+ // Changes not saved yet: their save asks.
+ if (!enabled || paused || limited || off || unsaved) return;
+ if (askedFor.current === savedAt && !left.current) return;
+ const wait = Math.max(
+ PROOF_READ_DELAY_MS,
+ lastAsk.current + PROOF_READ_EVERY_MS + PROOF_READ_SLACK_MS - Date.now(),
+ );
+ const timer = setTimeout(() => {
+ // One at a time: a save while one is out is asked about after it.
+ if (asking.current) return;
+ asking.current = true;
+ askedFor.current = savedAt;
+ setAskedSave(savedAt);
+ lastAsk.current = Date.now();
+ left.current = false;
+ setOut(true);
+ readDraftPage(draftId)
+ .then((result) => {
+ if (!open.current) return;
+ if ('error' in result) {
+ if (result.error === 'off') setOff(true);
+ // Failed: asked about again after the next save, not on a timer.
+ else {
+ console.error('Failed to read the page:', result.error);
+ setFailed(true);
+ setPending(false);
+ }
+ return;
+ }
+ const { pending: kept, limited: full, paused: spent, ...page } = result;
+ setRead(page);
+ setPending(kept);
+ if (spent) setPaused(true);
+ else if (full) setLimited(true);
+ else if (kept) left.current = true;
+ })
+ .catch((err) => {
+ console.error('Failed to read the page:', err);
+ if (!open.current) return;
+ setFailed(true);
+ setPending(false);
+ })
+ .finally(() => {
+ asking.current = false;
+ if (!open.current) return;
+ setOut(false);
+ if (latest.current !== askedFor.current || left.current) setAgain((n) => n + 1);
+ });
+ }, wait);
+ return () => clearTimeout(timer);
+ }, [draftId, savedAt, enabled, paused, limited, off, unsaved, again]);
+
+ // A save not asked about yet counts, as the claims' does (useClaims).
+ const reading =
+ enabled && !paused && !limited && !off && (out || pending || askedSave !== savedAt);
+ const settled = !enabled || read !== null || failed || off || paused || limited;
+ return { read, paused, limited, reading, settled };
+}
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 4e3d27491..91ce66626 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
@@ -10,6 +10,7 @@ import type { DraftSuggestion } from '@/lib/content/suggestions';
import { passageKey, type CitedPassage } from '@/lib/content/cited-passages';
import { encodeHtmlBlock } from '@/lib/content/html-allowlist';
import { CLAIMS_EVERY_MS } from './_use-claims';
+import { PROOF_READ_EVERY_MS, PROOF_READ_SLACK_MS } from './_use-page-read';
import ContentEditorPage from './page';
const getContentDraft = vi.fn();
@@ -21,6 +22,7 @@ const setContentDraftAuthor = vi.fn();
const keepDraftSource = vi.fn();
const confirmDraftAuthor = vi.fn();
const checkDraftClaims = vi.fn();
+const readDraftPage = vi.fn();
const getBrandFacts = vi.fn();
const checkDraftLinks = vi.fn();
const getSiteTrust = vi.fn();
@@ -92,6 +94,7 @@ vi.mock('@/lib/actions/content-drafts', () => ({
keepDraftSource: (...args: unknown[]) => keepDraftSource(...args),
confirmDraftAuthor: (...args: unknown[]) => confirmDraftAuthor(...args),
checkDraftClaims: (...args: unknown[]) => checkDraftClaims(...args),
+ readDraftPage: (...args: unknown[]) => readDraftPage(...args),
checkDraftLinks: (...args: unknown[]) => checkDraftLinks(...args),
}));
vi.mock('next/navigation', () => ({ useParams: () => ({ draftId: 'd1' }) }));
@@ -293,6 +296,7 @@ beforeEach(() => {
keepDraftSource.mockReset();
confirmDraftAuthor.mockReset().mockResolvedValue(undefined);
checkDraftClaims.mockReset().mockResolvedValue({ blocks: [], pending: 0, limited: false });
+ readDraftPage.mockReset().mockResolvedValue({ error: 'off' });
getBrandFacts.mockReset().mockResolvedValue({
facts: [],
pages: [],
@@ -2769,6 +2773,68 @@ describe('the side panel', () => {
}
});
+ it('holds the score until the page as saved is read for proof, then settles once (review, #1468)', async () => {
+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '2';
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ try {
+ getContentAuthors.mockResolvedValue({
+ authors: [],
+ brands: [{ id: 'b1', name: 'Acme' }],
+ me: { id: 'u1', role: 'admin' },
+ });
+ const read = {
+ spots: [],
+ proofs: [],
+ regulated: null,
+ pending: false,
+ limited: false,
+ paused: false,
+ };
+ let pageIn: (value: unknown) => void = () => {};
+ readDraftPage
+ .mockResolvedValueOnce(read)
+ .mockReturnValueOnce(new Promise((resolve) => (pageIn = resolve)));
+ getContentDraft.mockResolvedValue(readable);
+ saveContentDraft.mockResolvedValue({
+ ok: true,
+ updatedAt: '2026-10-20T10:01:00Z',
+ bodyHash: 'h1',
+ });
+ window.innerWidth = 1440;
+ await renderPage();
+ await act(async () => void (await vi.advanceTimersByTimeAsync(3_000)));
+ expect(readDraftPage).toHaveBeenCalledTimes(1);
+ expect(qualityChip()?.textContent).not.toContain('updating');
+ const shown = qualityChip()?.textContent;
+ const editor = (container.querySelector('.ProseMirror') as HTMLElement & { editor: Editor })
+ .editor;
+ await act(async () => {
+ editor.commands.insertContentAt(
+ editor.state.doc.content.size,
+ '<p>Forecasts missed by less each quarter.</p>',
+ );
+ });
+ await act(async () => void (await vi.advanceTimersByTimeAsync(2_000)));
+ expect(saveContentDraft).toHaveBeenCalledTimes(1);
+ // The claims are in; the page's read for the save waits for the API's minute.
+ await act(async () => void (await vi.advanceTimersByTimeAsync(CLAIMS_EVERY_MS)));
+ expect(checkDraftClaims).toHaveBeenCalledTimes(2);
+ expect(qualityChip()?.textContent).toContain('updating as the page is read');
+ await act(
+ async () =>
+ void (await vi.advanceTimersByTimeAsync(PROOF_READ_EVERY_MS + PROOF_READ_SLACK_MS)),
+ );
+ expect(readDraftPage).toHaveBeenCalledTimes(2);
+ // Asked, not answered: the last settled score stays.
+ expect(qualityChip()?.textContent).toContain(shown!.replace(/ ·.*$/, ''));
+ expect(qualityChip()?.textContent).toContain('updating as the page is read');
+ await act(async () => pageIn(read));
+ expect(qualityChip()?.textContent).not.toContain('updating');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
/** The draft above, its Language rule changed for this draft. */
const inLanguage = (language: { on?: boolean; value?: string }) => ({
...readable,
@@ -2936,6 +3002,72 @@ describe('the side panel', () => {
expect(link?.textContent).toBe('the fastest forecasting app');
});
+ it("asks for the proof of the brand's own claim, and Add proof link selects it (CE-049)", async () => {
+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '2';
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ const block = `${said} It is easy to set up for any team.`;
+ checkDraftClaims.mockResolvedValue({
+ blocks: [
+ { text: block, claims: [{ text: 'the fastest forecasting app', kind: 'superlative' }] },
+ ],
+ pending: 0,
+ limited: false,
+ });
+ readDraftPage.mockResolvedValue({
+ spots: [],
+ proofs: [{ claim: 'the fastest forecasting app', block, kind: 'ranking' }],
+ regulated: null,
+ pending: false,
+ limited: false,
+ paused: false,
+ });
+ getContentDraft.mockResolvedValue(claimed);
+ window.innerWidth = 1440;
+ await renderPage();
+ await act(async () => void (await vi.advanceTimersByTimeAsync(3_000)));
+ expect(readDraftPage).toHaveBeenCalledWith('d1');
+ const chip = [...container.querySelectorAll<HTMLButtonElement>('header button')].find((b) =>
+ b.textContent?.startsWith('Quality'),
+ )!;
+ await act(async () => chip.click());
+ const row = [...panel()!.querySelectorAll('li')].find((li) =>
+ li.textContent?.includes('Link the ranking or test behind “the fastest forecasting app”'),
+ )!;
+ expect(row.textContent).toContain('Link its proof, or soften the claim');
+ // Its sentence is the person's to prove: not the agent's to source as well.
+ expect(panel()!.textContent).not.toContain('claim has no source');
+ await act(async () =>
+ [...row.querySelectorAll('button')]
+ .find((b) => b.textContent === 'Add proof link')!
+ .click(),
+ );
+ expect(document.querySelector('#content-link-href')).not.toBeNull();
+ const { state } = (
+ container.querySelector('.ProseMirror') as HTMLElement & { editor: Editor }
+ ).editor;
+ expect(state.doc.textBetween(state.selection.from, state.selection.to)).toBe(
+ 'the fastest forecasting app',
+ );
+ // Linked to its proof: the row is checked, not gone.
+ const field = document.querySelector<HTMLInputElement>('#content-link-href')!;
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(
+ field,
+ 'https://www.acme.com/benchmarks',
+ );
+ field.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ await act(async () =>
+ [...document.querySelectorAll('button')].find((b) => b.textContent === 'Apply')!.click(),
+ );
+ // The page is read again once typing pauses.
+ await act(async () => void (await vi.advanceTimersByTimeAsync(3_000)));
+ const done = [...panel()!.querySelectorAll('li')].find((li) =>
+ li.textContent?.includes('the fastest forecasting app'),
+ )!;
+ expect(done.textContent).toContain('The proof is linked');
+ });
+
it('takes the claim’s sentence out on Remove', async () => {
process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '2';
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
@@ -4309,9 +4441,12 @@ describe('the side panel', () => {
localStorage.setItem('aeo:next-step-skips:d1', JSON.stringify({ plan: 'true' }));
let factsIn!: (read: unknown) => void;
getBrandFacts.mockReturnValue(new Promise((resolve) => (factsIn = resolve)));
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
await act(async () => root.unmount());
root = createRoot(container);
await renderPage();
+ // The page's read for proof is in, a few seconds after it opens.
+ await act(async () => void (await vi.advanceTimersByTimeAsync(3_000)));
expect(skips()).toEqual({ plan: 'true' });
await act(async () =>
factsIn({
@@ -4325,6 +4460,7 @@ describe('the side panel', () => {
);
expect(skips()).toEqual({});
} finally {
+ vi.useRealTimers();
delete process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE;
}
});
diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.ts
index c4e00588b..40864965b 100644
--- a/web/src/lib/actions/content-drafts.ts
+++ b/web/src/lib/actions/content-drafts.ts
@@ -39,6 +39,7 @@ import { sanitizeDraftHtml } from '@/lib/content/sanitize-draft-html';
import { matchPagePrompts } from '@/lib/content/page-prompts';
import type { LinkCheck } from '@/lib/content/quality-checks';
import { CLAIM_KINDS, type ClaimBlock } from '@/lib/content/claims';
+import { PROOF_KINDS, type PageRead } from '@/lib/content/page-read';
import { MAX_SOURCE_SITES, type AiSourceClass } from '@/lib/content/source-class';
import {
NO_DRAFT_RULES,
@@ -2342,3 +2343,65 @@ export async function saveMyRuleSet(
);
if (error) throw new Error(error.message);
}
+
+/**
+ * Quality's page read for proof (CE-049): the draft's visual proof spots
+ * and proof asks, read by the API from the page as saved, with its page
+ * type and the brand's business type; once a minute at most (`pending`:
+ * the kept read stands, ask again), `limited` once the draft's page reads
+ * for the day are made, `paused` when the AI budget is spent. Returned, not
+ * thrown: 'off' before Quality's phase 2 is live on the API.
+ */
+export async function readDraftPage(
+ id: string,
+): Promise<
+ | (PageRead & { pending: boolean; limited: boolean; paused: boolean })
+ | { error: 'invalid' | 'failed' | 'off' }
+> {
+ if (!draftId.safeParse(id).success) return { error: 'invalid' };
+ const supabase = await createClient();
+ const {
+ data: { session },
+ } = await supabase.auth.getSession();
+ if (!session) return { error: 'failed' };
+ try {
+ const res = await fetch(`${API_BASE_URL}/api/content-pages/page-read`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${session.access_token}`,
+ },
+ body: JSON.stringify({ draftId: id }),
+ });
+ if (res.status === 404) {
+ const body = (await res.json().catch(() => ({}))) as { code?: string };
+ return { error: body.code === 'off' ? 'off' : 'failed' };
+ }
+ if (!res.ok) return { error: 'failed' };
+ const body = (await res.json()) as Partial<PageRead> & {
+ pending?: boolean;
+ limited?: boolean;
+ paused?: boolean;
+ };
+ const kinds: readonly string[] = PROOF_KINDS;
+ const text = (value: unknown) => typeof value === 'string' && value.length > 0;
+ return {
+ spots: (body.spots ?? []).filter(
+ (s) => text(s.passage) && text(s.block) && text(s.image) && text(s.alt),
+ ),
+ proofs: (body.proofs ?? []).filter(
+ (p) => text(p.claim) && text(p.block) && kinds.includes(p.kind),
+ ),
+ regulated:
+ body.regulated === 'health' || body.regulated === 'finance' || body.regulated === 'legal'
+ ? body.regulated
+ : null,
+ pending: body.pending ?? false,
+ limited: body.limited ?? false,
+ paused: body.paused ?? false,
+ };
+ } catch (err) {
+ console.error('Failed to read the draft page:', err);
+ return { error: 'failed' };
+ }
+}
diff --git a/web/src/lib/content/next-step.test.ts b/web/src/lib/content/next-step.test.ts
index 48e0ccb1f..76124e4f0 100644
--- a/web/src/lib/content/next-step.test.ts
+++ b/web/src/lib/content/next-step.test.ts
@@ -211,6 +211,22 @@ describe('nextStep', () => {
expect(liveSkips(skipped)).toEqual({ fixRules: 'faq,summary' });
expect(liveSkips({ ...skipped, openRules: ['faq'] })).toEqual({});
});
+
+ it('reads each proof to-do by its own key: another claim opening brings a skipped step back (CE-049)', () => {
+ const proof = (key: string) =>
+ todo({ id: 'proof', key, score: 'trust', action: 'addProof', gain: 3 });
+ const s = state({
+ quality: { trust: 54, trustLow: true, todos: [proof('proof:a:1'), proof('proof:b:2')] },
+ });
+ const skipped = { ...s, skipped: { proof: stepState('proof', s) } };
+ expect(liveSkips(skipped)).toEqual({ proof: 'true:proof:a:1,proof:b:2' });
+ expect(
+ liveSkips({
+ ...skipped,
+ quality: { trust: 54, trustLow: true, todos: [proof('proof:a:1'), proof('proof:c:3')] },
+ }),
+ ).toEqual({});
+ });
});
describe('rulesForNext', () => {
diff --git a/web/src/lib/content/next-step.ts b/web/src/lib/content/next-step.ts
index 733b9af9d..d39af9f28 100644
--- a/web/src/lib/content/next-step.ts
+++ b/web/src/lib/content/next-step.ts
@@ -136,7 +136,7 @@ export function stepState(id: NextStepId, s: NextStepState): string {
// a skip made before then holds.
return `${s.quality?.trustLow ?? false}:${openTodos(s)
.filter((todo) => todo.id !== 'brandFacts')
- .map((todo) => todo.id)
+ .map((todo) => todo.key ?? todo.id)
.join(',')}`;
default:
return '';
diff --git a/web/src/lib/content/page-read.test.ts b/web/src/lib/content/page-read.test.ts
new file mode 100644
index 000000000..b079a67df
--- /dev/null
+++ b/web/src/lib/content/page-read.test.ts
@@ -0,0 +1,80 @@
+import { describe, expect, it } from 'vitest';
+import { proofsOnPage, type ProofAsk } from './page-read';
+import { trustBlocks } from './quality-checks';
+
+/** The page read's proof asks on the page as it is now (Quality spec §4b, CE-049). */
+
+describe('proofsOnPage', () => {
+ const html =
+ '<p>Ledgerly is award-winning. Teams love it.</p>' +
+ '<p>Every plan is SOC 2 certified (<a href="https://ledgerly.example/trust">trust</a>).</p>' +
+ '<ul><li>Rated 4.8 by 2,000 teams.</li></ul>' +
+ '<p>Ledgerly is award-winning. Teams love it.</p>';
+ const blocks = trustBlocks(html);
+ const ask = (claim: string, block: string, kind: ProofAsk['kind'] = 'award'): ProofAsk => ({
+ claim,
+ block,
+ kind,
+ });
+
+ it("gives each ask in the page's order, with its sentence and whether its block links out", () => {
+ const proofs = [
+ ask('Rated 4.8', 'Rated 4.8 by 2,000 teams.', 'rating'),
+ ask('award-winning', 'Ledgerly is award-winning. Teams love it.'),
+ ask('SOC 2 certified', 'Every plan is SOC 2 certified ( trust).', 'certification'),
+ ];
+ expect(proofsOnPage(blocks, proofs)).toEqual([
+ {
+ ...proofs[1],
+ sentence: 'Ledgerly is award-winning.',
+ linked: false,
+ },
+ {
+ ...proofs[2],
+ sentence: 'Every plan is SOC 2 certified ( trust).',
+ linked: true,
+ },
+ { ...proofs[0], sentence: 'Rated 4.8 by 2,000 teams.', linked: false },
+ ]);
+ });
+
+ it('leaves out an ask whose block changed, and a block the page has twice gives its claims once', () => {
+ expect(
+ proofsOnPage(blocks, [
+ ask('award-winning', 'Ledgerly is award-winning.'),
+ ask('the best', 'Ledgerly is award-winning. Teams love it.', 'ranking'),
+ ask('award-winning', 'Ledgerly is award-winning. Teams love it.'),
+ ]).map((p) => p.claim),
+ ).toEqual(['award-winning']);
+ });
+
+ it('finds a claim once a link on it adds a space at its edge, and keeps its block as read', () => {
+ const read = 'We are ISO 27001-certified and the best-rated tool in Europe.';
+ const linked = trustBlocks(
+ '<p>We are <a href="https://ledgerly.example/trust">ISO 27001</a>-certified and the best-rated tool in Europe.</p>',
+ );
+ expect(linked[0].text).toBe('We are ISO 27001 -certified and the best-rated tool in Europe.');
+ const proofs = proofsOnPage(linked, [
+ ask('the best-rated tool in Europe', read, 'ranking'),
+ ask('ISO 27001-certified', read, 'certification'),
+ ]);
+ // In the block's order, each with the block as read.
+ expect(proofs.map((p) => [p.claim, p.block, p.linked])).toEqual([
+ ['ISO 27001-certified', read, true],
+ ['the best-rated tool in Europe', read, true],
+ ]);
+ expect(proofs[0].sentence).toBe(
+ 'We are ISO 27001 -certified and the best-rated tool in Europe.',
+ );
+ });
+
+ it("counts only an http(s) link as the block's proof", () => {
+ const linkless = trustBlocks(
+ '<p>We are ISO 27001 certified (<a href="mailto:[email protected]">ask</a>).</p>',
+ );
+ expect(
+ proofsOnPage(linkless, [ask('ISO 27001 certified', linkless[0].text, 'certification')])[0]
+ .linked,
+ ).toBe(false);
+ });
+});
diff --git a/web/src/lib/content/page-read.ts b/web/src/lib/content/page-read.ts
new file mode 100644
index 000000000..358e541b6
--- /dev/null
+++ b/web/src/lib/content/page-read.ts
@@ -0,0 +1,94 @@
+import { cleanHref } from './html-allowlist';
+import { sentencesOf } from './readability';
+import { squeeze, type TrustBlock } from './quality-checks';
+
+/**
+ * A page's read for proof (Content Editor Quality spec §4b, CE-049), as the
+ * API's page read gives it (content-quality-page.js): visual proof spots —
+ * one specific image the business can take itself, for a passage — and
+ * proof asks — the page's own claims whose proof only the business has,
+ * each with the kind of proof it needs. Each names its block by its words
+ * as Trust's blocks have them.
+ */
+
+export const PROOF_KINDS = [
+ 'award',
+ 'certification',
+ 'research',
+ 'rating',
+ 'ranking',
+ 'number',
+ 'test',
+ 'customer_case',
+ 'unknown',
+] as const;
+export type ProofKind = (typeof PROOF_KINDS)[number];
+
+export interface ProofSpot {
+ /** The words the image supports, as the page has them. */
+ passage: string;
+ /** Its block's words (trustBlocks). */
+ block: string;
+ /** What the image shows. */
+ image: string;
+ /** Its alt text, drafted from the passage. */
+ alt: string;
+}
+
+export interface ProofAsk {
+ /** The claim's words, as the page has them. */
+ claim: string;
+ block: string;
+ kind: ProofKind;
+}
+
+export interface PageRead {
+ spots: ProofSpot[];
+ proofs: ProofAsk[];
+ regulated: 'health' | 'finance' | 'legal' | null;
+}
+
+/** The proof to-dos open at once at most: the page's first claims. */
+export const MAX_PROOF_TODOS = 5;
+
+/** A proof ask on the page as it is: its sentence, and whether its block links out. */
+export interface PageProof extends ProofAsk {
+ sentence: string;
+ linked: boolean;
+}
+
+/**
+ * The page's proof asks as the page is now, in its order (a block's by
+ * where its claim is): each whose block is still there, with the sentence
+ * that holds its claim and whether the block links out (an http(s) link,
+ * as Trust reads it: its proof, on the brand's site or another). Blocks
+ * and claims are matched by their words without spaces: a link put on a
+ * claim adds one at its edge ("ISO 27001 -certified"). Its to-do's key
+ * reads the block without spaces (proofKey), so it stays as the block's
+ * spacing changes.
+ */
+export function proofsOnPage(blocks: TrustBlock[], proofs: readonly ProofAsk[]): PageProof[] {
+ const seen = new Set<string>();
+ return blocks.flatMap((block) => {
+ const words = squeeze(block.text);
+ return (
+ proofs
+ .filter((proof) => squeeze(proof.block) === words && words.includes(squeeze(proof.claim)))
+ // A block the page has twice: its claims once.
+ .filter((proof) => {
+ const key = `${proof.claim}\n${proof.block}`;
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ })
+ .sort((a, b) => words.indexOf(squeeze(a.claim)) - words.indexOf(squeeze(b.claim)))
+ .map((proof) => ({
+ ...proof,
+ sentence:
+ sentencesOf(block.text).find((s) => squeeze(s).includes(squeeze(proof.claim))) ??
+ proof.claim,
+ linked: block.links.some((href) => /^https?:\/\//i.test(cleanHref(href) ?? '')),
+ }))
+ );
+ });
+}
diff --git a/web/src/lib/content/quality-checks.test.ts b/web/src/lib/content/quality-checks.test.ts
index cc9b176c1..2db15c3fa 100644
--- a/web/src/lib/content/quality-checks.test.ts
+++ b/web/src/lib/content/quality-checks.test.ts
@@ -9,6 +9,7 @@ import {
eeat,
linksToCheck,
scoreGain,
+ sentenceGain,
trust,
trustBlocks,
trustGain,
@@ -588,3 +589,57 @@ describe('trust: consistent with brand facts (Phase 2, CE-047)', () => {
expect(read(null).mismatches).toEqual([]);
});
});
+
+describe('trust: the proof of the brand’s own claims (Phase 2, CE-049)', () => {
+ const NOW = Date.parse('2026-10-24T12:00:00Z');
+ const html =
+ '<p>Ledgerly cut close times by 40% (<a href="https://www.acme.com/awards">award</a>). The market grew 12% in 2025.</p>' +
+ '<p>Teams forecast 3x faster (<a href="https://www.acme.com/blog">blog</a>).</p>';
+ const blocks = trustBlocks(html);
+ const read = (proofs: { block: string; sentence: string }[] | null, page = blocks) =>
+ trust({ blocks: page, links: new Map(), brandDomains: ['acme.com'], proofs, now: NOW });
+ const award = { block: blocks[0].text, sentence: 'Ledgerly cut close times by 40% ( award).' };
+
+ it("counts a link to the brand's own site as the source of its own claim's sentence, and nowhere else", () => {
+ expect(read(null).unsourced).toEqual([
+ 'Ledgerly cut close times by 40% ( award).',
+ 'The market grew 12% in 2025.',
+ 'Teams forecast 3x faster ( blog).',
+ ]);
+ // The block's other figure isn't the brand's to prove: its own link doesn't source it.
+ expect(read([award]).unsourced).toEqual([
+ 'The market grew 12% in 2025.',
+ 'Teams forecast 3x faster ( blog).',
+ ]);
+ });
+
+ it('finds the proof once a link on its claim adds a space at its edge', () => {
+ const linked = trustBlocks(
+ '<p>We are <a href="https://www.acme.com/trust">ISO 27001</a>-certified for 3 years.</p>',
+ );
+ expect(linked[0].text).toBe('We are ISO 27001 -certified for 3 years.');
+ expect(
+ read(
+ [
+ {
+ block: 'We are ISO 27001-certified for 3 years.',
+ sentence: 'We are ISO 27001-certified for 3 years.',
+ },
+ ],
+ linked,
+ ).unsourced,
+ ).toEqual([]);
+ });
+
+ it("gives a sentence's gain only while it is unsourced", () => {
+ const result = read(null);
+ const sentence = 'Teams forecast 3x faster ( blog).';
+ const gain = sentenceGain(result, sentence);
+ expect(gain).toBeGreaterThan(0);
+ expect(gain).toBe(
+ (read([{ block: blocks[1].text, sentence }]).score ?? 0) - (result.score ?? 0),
+ );
+ expect(sentenceGain(result, 'Not on the page.')).toBe(0);
+ expect(sentenceGain(null, sentence)).toBe(0);
+ });
+});
diff --git a/web/src/lib/content/quality-checks.ts b/web/src/lib/content/quality-checks.ts
index 148a18cde..4ce97d266 100644
--- a/web/src/lib/content/quality-checks.ts
+++ b/web/src/lib/content/quality-checks.ts
@@ -6,6 +6,9 @@ import type { FactMismatch } from './brand-facts';
import type { ClaimBlock } from './claims';
import { askableSite, sourceClass, type AiSourceClass, type SourceClass } from './source-class';
+/** A text's words without their spaces, as compared where an inline tag may add one. */
+export const squeeze = (text: string) => text.replace(/\s+/g, '');
+
/**
* E-E-A-T and Trust (Content Editor Quality spec §2.1, §2.2): checks read
* from the page's facts, each worth its points. Only the checks live in the
@@ -96,6 +99,25 @@ export function scoreGain<Id extends string>(result: Score<Id>, ids: Id[]): numb
return (scoreOf(raised).score ?? 0) - result.score;
}
+/**
+ * What sourcing one sentence would add to Trust: its share of the claims'
+ * points (CE-049's proof to-dos). Zero when Trust isn't scored or the
+ * sentence has its source.
+ */
+export function sentenceGain(
+ trust: (Score<TrustCheckId> & Partial<Pick<TrustRead, 'unsourced' | 'figures'>>) | null,
+ sentence: string,
+): number {
+ if (!trust || trust.score === null || !trust.unsourced?.includes(sentence)) return 0;
+ const figures = trust.figures ?? 0;
+ const raised = trust.checks.map((c) =>
+ c.id === 'claimsSourced' && figures > 0
+ ? { ...c, points: Math.min(c.max, c.points + c.max / figures) }
+ : c,
+ );
+ return (scoreOf(raised).score ?? 0) - trust.score;
+}
+
/**
* A Trust suggestion's gain. While Trust isn't scored (no figure and no
* dated source yet), the checks' missing points count out of the Phase 1
@@ -349,6 +371,11 @@ export interface SourceRead {
* With `brandFacts` (Phase 2, CE-047), the page's prices, trial and founding
* year compared with the brand's approved facts count: the share that
* matched. Like a working link, it doesn't score Trust on its own.
+ *
+ * With `proofs` (Phase 2, CE-049), the sentence holding the brand's own
+ * claim (an award, a certification, its own test) is sourced by a link in
+ * its block to the brand's own site too: its award or trust page is the
+ * proof. The block's other sentences aren't.
*/
export function trust({
blocks,
@@ -359,6 +386,7 @@ export function trust({
sources: kinds = null,
claims = null,
brandFacts = null,
+ proofs = null,
now,
}: {
/** The page's blocks (trustBlocks). */
@@ -379,6 +407,11 @@ export function trust({
claims?: readonly ClaimBlock[] | null;
/** Phase 2: the page against the brand's approved facts (factMismatches, CE-047); left out before. */
brandFacts?: { compared: number; mismatches: FactMismatch[] } | null;
+ /**
+ * Phase 2: the brand's own claims' sentences, each in its block (the page
+ * read's proofs on the page, CE-049).
+ */
+ proofs?: readonly { block: string; sentence: string }[] | null;
now: number;
}): TrustRead {
const all = pageLinks(blocks, brandDomains);
@@ -387,11 +420,19 @@ export function trust({
// Each sentence once, where the page has it first: a nested list item's
// text is its parent's too.
const figures = new Map<string, { sourced: boolean; block: number }>();
- const sourcedBlock = (index: number) => all.some((l) => l.external && l.block === index);
+ // A proof's block and sentence by their words without spaces: a link put
+ // on its claim adds one at the link's edge ("ISO 27001 -certified").
+ const proofOf = (block: string, sentence: string) => `${squeeze(block)}\n${squeeze(sentence)}`;
+ const ownProof = new Set((proofs ?? []).map((p) => proofOf(p.block, p.sentence)));
+ const sourcedIn = (index: number, sentence: string) =>
+ all.some(
+ (l) =>
+ l.block === index && (l.external || ownProof.has(proofOf(blocks[index].text, sentence))),
+ );
const addFigure = (sentence: string, block: number) => {
const had = figures.get(sentence);
figures.set(sentence, {
- sourced: (had?.sourced ?? false) || sourcedBlock(block),
+ sourced: (had?.sourced ?? false) || sourcedIn(block, sentence),
block: had?.block ?? block,
});
};
diff --git a/web/src/lib/content/quality-todos.test.ts b/web/src/lib/content/quality-todos.test.ts
index ba4b2a183..7b8d168ba 100644
--- a/web/src/lib/content/quality-todos.test.ts
+++ b/web/src/lib/content/quality-todos.test.ts
@@ -1,7 +1,8 @@
import { describe, expect, it } from 'vitest';
import type { ContentAuthor } from './authors';
-import { eeat, trust } from './quality-checks';
-import { qualityTodos } from './quality-todos';
+import type { PageProof } from './page-read';
+import { eeat, trust, trustBlocks } from './quality-checks';
+import { proofKey, qualityTodos } from './quality-todos';
/** Your to-dos (Quality spec §4, CE-040): only what the person can do, read from the checks. */
@@ -209,6 +210,128 @@ describe('qualityTodos', () => {
expect(qualityTodos({ eeat: null, author: null, hasAuthors: true })).toEqual([]);
});
+ it("asks for the proof of the page's own claims, at most five open, and keeps one checked once linked (CE-049)", () => {
+ const NOW = Date.parse('2026-10-24');
+ const proof = (claim: string, linked = false): PageProof => ({
+ claim,
+ block: `Ledgerly is ${claim}.`,
+ kind: 'award',
+ sentence: `Ledgerly is ${claim}.`,
+ linked,
+ });
+ const trustScore = trust({
+ blocks: trustBlocks('<p>Ledgerly is 40% faster.</p><p>Sales grew 3x in 2025.</p>'),
+ links: new Map(),
+ brandDomains: [],
+ now: NOW,
+ });
+ const read = (asks: PageProof[], had: string[] = []) =>
+ qualityTodos({
+ eeat: null,
+ author: null,
+ hasAuthors: true,
+ trust: trustScore,
+ proofs: { asks, had: new Set(had) },
+ brandFacts: { pending: 1, had: true },
+ });
+ const [first] = read([proof('40% faster')]);
+ expect(first).toEqual({
+ id: 'proof',
+ key: proofKey(proof('40% faster')),
+ done: false,
+ // Its sentence is one of Trust's two unsourced figures.
+ gain: expect.any(Number),
+ score: 'trust',
+ action: 'addProof',
+ proof: {
+ claim: '40% faster',
+ block: 'Ledgerly is 40% faster.',
+ kind: 'award',
+ sentence: 'Ledgerly is 40% faster.',
+ },
+ });
+ expect(first.gain).toBeGreaterThan(0);
+ // A claim Trust doesn't count: no gain made up. The brand facts stay last.
+ expect(read([proof('award-winning')]).map((t) => [t.id, t.gain])).toEqual([
+ ['proof', 0],
+ ['brandFacts', 0],
+ ]);
+ // Linked before it was asked for: no to-do. Linked after: checked.
+ expect(read([proof('award-winning', true)]).map((t) => t.id)).toEqual(['brandFacts']);
+ expect(
+ read([proof('award-winning', true)], [proofKey(proof('award-winning'))])[0],
+ ).toMatchObject({ id: 'proof', done: true, gain: 0 });
+ // Five open at once, in the page's order; a checked one doesn't count.
+ const many = ['a', 'b', 'c', 'd', 'e', 'f'].map((c) => proof(`claim ${c}`));
+ const open = read([proof('done', true), ...many], [proofKey(proof('done'))]);
+ expect(open.filter((t) => t.id === 'proof').map((t) => t.proof!.claim)).toEqual([
+ 'done',
+ 'claim a',
+ 'claim b',
+ 'claim c',
+ 'claim d',
+ 'claim e',
+ ]);
+ });
+
+ it("lists the proof to-dos after the person's input and before the brand facts", () => {
+ const none = { experience: false, data: false, quote: false };
+ const ids = qualityTodos({
+ eeat: eeat({ author: author(), used: none }),
+ author: author(),
+ hasAuthors: true,
+ used: none,
+ given: null,
+ proofs: {
+ asks: [
+ {
+ claim: 'award-winning',
+ block: 'We are award-winning.',
+ kind: 'award',
+ sentence: 'We are award-winning.',
+ linked: false,
+ },
+ ],
+ had: new Set(),
+ },
+ brandFacts: { pending: 2, had: true },
+ }).map((t) => t.id);
+ expect(ids).toEqual([
+ 'byline',
+ 'authorProfile',
+ 'experience',
+ 'originalData',
+ 'expertQuote',
+ 'proof',
+ 'brandFacts',
+ ]);
+ });
+
+ it("keeps a linked proof checked when the next read carries its block with the link's space (review, #1468)", () => {
+ const read = 'We are ISO 27001-certified for every plan.';
+ const linked = 'We are ISO 27001 -certified for every plan.';
+ // The API cuts the claim from the block as it has it: the space too.
+ const ask = (block: string, isLinked: boolean): PageProof => ({
+ claim: isLinked ? 'ISO 27001 -certified' : 'ISO 27001-certified',
+ block,
+ kind: 'certification',
+ sentence: block,
+ linked: isLinked,
+ });
+ expect(proofKey(ask(linked, true))).toBe(proofKey(ask(read, false)));
+ // Asked while open on the first read; linked, the API's next answer
+ // names the block as the page has it now.
+ const had = new Set([proofKey(ask(read, false))]);
+ expect(
+ qualityTodos({
+ eeat: null,
+ author: null,
+ hasAuthors: true,
+ proofs: { asks: [ask(linked, true)], had },
+ }),
+ ).toMatchObject([{ id: 'proof', done: true }]);
+ });
+
it('offers to confirm the author the site names instead of picking one, the profile once they are', () => {
const read = (real: boolean, profile: boolean) =>
qualityTodos({
diff --git a/web/src/lib/content/quality-todos.ts b/web/src/lib/content/quality-todos.ts
index ea33c6789..85cc7d6ac 100644
--- a/web/src/lib/content/quality-todos.ts
+++ b/web/src/lib/content/quality-todos.ts
@@ -1,10 +1,14 @@
import type { ContentAuthor } from './authors';
+import { MAX_PROOF_TODOS, type PageProof, type ProofKind } from './page-read';
import {
authorProfile,
scoreGain,
+ sentenceGain,
type EeatCheckId,
type Score,
type TrustCheckId,
+ type TrustRead,
+ squeeze,
} from './quality-checks';
/**
@@ -25,6 +29,7 @@ export type QualityTodoId =
| 'experience'
| 'originalData'
| 'expertQuote'
+ | 'proof'
| 'brandFacts';
/**
@@ -38,6 +43,7 @@ export type QualityTodoAction =
| 'addAuthor'
| 'editAuthor'
| 'addInput'
+ | 'addProof'
| 'reviewBrandFacts';
export interface QualityTodo {
@@ -51,6 +57,10 @@ export interface QualityTodo {
action: QualityTodoAction | null;
/** Given in Brief › Your input, though the page doesn't use it yet (CE-048). */
given?: boolean;
+ /** Its own key when it has more than one row (each proof's). */
+ key?: string;
+ /** The claim a proof to-do asks proof for (CE-049). */
+ proof?: { claim: string; block: string; kind: ProofKind; sentence: string };
/** How many it is about (placeholders, brand facts to approve). */
count?: number;
/**
@@ -67,7 +77,8 @@ export interface QualityTodo {
* count holds. Done ones stay on the list, checked; placeholders are listed
* once the page has had some (`had`, this session), the brand facts to
* approve likewise, last (Phase 2: the brand's, worth no points of the
- * page's). The author's wait for E-E-A-T to be read.
+ * page's). The proof of the page's own claims comes after the person's
+ * input (Phase 2, CE-049). The author's wait for E-E-A-T to be read.
*/
export function qualityTodos({
eeat,
@@ -79,6 +90,7 @@ export function qualityTodos({
given = null,
trust = null,
brandFacts = null,
+ proofs = null,
confirmed = null,
}: {
eeat: Score<EeatCheckId> | null;
@@ -95,13 +107,19 @@ export function qualityTodos({
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;
+ /** Trust, for an expert quote's gain and a proof's (its unsourced sentences). */
+ trust?: (Score<TrustCheckId> & Partial<Pick<TrustRead, 'unsourced' | 'figures'>>) | null;
/**
* Phase 2 (CE-047): the brand's facts read from its site that no one has
* approved or rejected yet, and whether there were some this session.
*/
brandFacts?: { pending: number; had: boolean } | null;
+ /**
+ * Phase 2 (CE-049): the page's own claims that need the brand's proof, as
+ * the page is now (proofsOnPage), and the keys of the ones asked for this
+ * session: done ones stay listed, checked.
+ */
+ proofs?: { asks: readonly PageProof[]; had: ReadonlySet<string> } | null;
/** What the person confirmed of the author their site names (00271), or null where they can't. */
confirmed?: { real: boolean; profile: boolean } | null;
}): QualityTodo[] {
@@ -132,7 +150,26 @@ export function qualityTodos({
},
]
: [];
- if (!eeat || eeat.score === null) return [...fill, ...facts];
+ // The page's own claims, in its order: open while its paragraph has no
+ // link, checked once it has; MAX_PROOF_TODOS open at once.
+ let open = 0;
+ const proofTodos: QualityTodo[] = (proofs?.asks ?? []).flatMap((ask) => {
+ const key = proofKey(ask);
+ if (ask.linked && !proofs?.had.has(key)) return [];
+ if (!ask.linked && (open += 1) > MAX_PROOF_TODOS) return [];
+ return [
+ {
+ id: 'proof',
+ key,
+ done: ask.linked,
+ gain: ask.linked ? 0 : sentenceGain(trust, ask.sentence),
+ score: 'trust',
+ action: 'addProof',
+ proof: { claim: ask.claim, block: ask.block, kind: ask.kind, sentence: ask.sentence },
+ } satisfies QualityTodo,
+ ];
+ });
+ if (!eeat || eeat.score === null) return [...fill, ...proofTodos, ...facts];
// No author picked: the one the site names may be confirmed instead, the
// profile once the author is.
const byConfirm = !author && !!confirmed;
@@ -187,6 +224,26 @@ export function qualityTodos({
},
] satisfies QualityTodo[])
: []),
+ ...proofTodos,
...facts,
];
}
+
+/** A text's 32-bit FNV-1a hash, in base 36: a short, stable name for it. */
+function shortHash(text: string): string {
+ let hash = 0x811c9dc5;
+ for (let i = 0; i < text.length; i++) {
+ hash ^= text.charCodeAt(i);
+ hash = Math.imul(hash, 0x01000193);
+ }
+ return (hash >>> 0).toString(36);
+}
+
+/**
+ * A proof to-do's key: its claim in its block, both by their words without
+ * spaces, the block by a short hash (the nudge keeps the keys it showed). A
+ * link put on the claim adds a space at its edge, and the API's next answer
+ * carries the claim and its block as the page has them then: the key stays.
+ */
+export const proofKey = (ask: { claim: string; block: string }) =>
+ `proof:${squeeze(ask.claim)}:${shortHash(squeeze(ask.block))}`;