Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(content): check a page's prices against approved brand facts in Trust, with an Approve to-do (CE-047, part d) (#1465)
Cihan0628125b265d
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 8435fff3c..f6fa1bcb3 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -4673,6 +4673,12 @@"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"},+ "brandFacts": {+ "title": "{count, plural, =0 {Review your brand facts} one {Approve # brand fact} other {Approve # brand facts}}",+ "next": "approve {count, plural, one {# brand fact} other {# brand facts}}",+ "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"+ },"title": "Your to-dos","left": "{count, plural, =0 {All done} other {# left · only you can do these}}","done": "Done",@@ -4728,7 +4734,8 @@"pickAuthor": "Pick now","addAuthor": "Add now","editAuthor": "Edit now",- "addInput": "Add now"+ "addInput": "Add now",+ "reviewBrandFacts": "Review now"},"later": "Later"},@@ -4739,6 +4746,7 @@"band": "{score, number}, {band}","show": "Show","addInput": "Add",+ "reviewBrandFacts": "Review","keep": "Keep","aiCheck": "AI check","addSource": "Add source",@@ -4783,6 +4791,10 @@"line": "{count, plural, one {# link doesn't} other {# links don't}} work","detail": "{count, plural, one {Fix or remove it: {url}} other {Fix or remove them, starting with {url}}}"},+ "brandFacts": {+ "line": "{kind, select, price {Price} trial {Trial length} founded {Founding year} other {A fact}} differs from brand facts · Page {page} · {source, select, pricing {pricing page} about {About page} product {product page} other {your site}} {fact}",+ "detail": "{count, plural, one {Match the page to the fact you approved, or check it in Brand settings} other {# facts differ: match the page to the facts you approved, or check them in Brand settings}}"+ },"avgSentence": {"line": "Sentences average {words, number} words","detail": "Aim for 15–20 words: shorter sentences read faster, and AI answers quote them whole.",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsxindex c00965263..c1b6dddb7 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_before-publish.test.tsx@@ -151,6 +151,7 @@ const trustRead = (over: Partial<TrustRead>): TrustRead => ({aiClaims: 0,weak: [],classified: 0,+ mismatches: [],...over,});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsxindex 1dd391601..e43da9e0d 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@@ -107,7 +107,8 @@ import {type ClaimMark,} from '@/lib/content/quality-checks';import { qualityTodos } from '@/lib/content/quality-todos';-import { readability } from '@/lib/content/readability';+import { readability, sentencesOf } from '@/lib/content/readability';+import { brandFactsPath, factMismatches } from '@/lib/content/brand-facts';import {liveSkips,nextStep,@@ -159,6 +160,7 @@ import { PageInfoStrip, pageInfoKey } from './_page-info';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 { useSourceClasses } from './_use-source-classes';import { HeaderTip } from './_header-tip';import {@@ -627,6 +629,25 @@ export function DraftEditor({// person kept.const sourcesOn = qualityPhase() >= 2;const competitorDomains = reads.sources?.data?.competitorDomains;+ // Phase 2 (CE-047): the page's prices, trial and founding year against the+ // brand's approved facts, read from its own site.+ const factsState = useBrandFacts(draft.brandId, sourcesOn);+ const brandFacts = factsState.status === 'ready' ? factsState.read.facts : null;+ const factCheck = useMemo(+ () =>+ brandFacts+ ? factMismatches({+ sentences: pageBlocks.flatMap((b) => sentencesOf(b.text)),+ facts: brandFacts,+ brandName,+ competitorDomains: competitorDomains ?? [],+ })+ : null,+ [brandFacts, pageBlocks, brandName, competitorDomains],+ );+ const pendingFacts = brandFacts?.filter((f) => f.status === 'pending').length ?? 0;+ const [hadPendingFacts, setHadPendingFacts] = useState(false);+ if (pendingFacts > 0 && !hadPendingFacts) setHadPendingFacts(true);const [keptSources, setKeptSources] = useState(draft.keptSources);// A site the rules can't place, as the model reads it (part b): asked// after a save, as the links are.@@ -688,6 +709,7 @@ export function DraftEditor({quote: used ? used.quote : null,sources: sourceRead,claims: claimBlocks,+ brandFacts: factCheck,now: Date.now(),}): null,@@ -701,6 +723,7 @@ export function DraftEditor({used,sourceRead,claimBlocks,+ factCheck,],);// Their links underlined in the draft, Quality's suggestion naming them.@@ -818,6 +841,7 @@ export function DraftEditor({used,given: inputs ? inputsGiven(inputs) : null,trust: trustScore,+ brandFacts: brandFacts ? { pending: pendingFacts, had: hadPendingFacts } : null,confirmed: authorConfirmed,}): [];@@ -838,6 +862,7 @@ export function DraftEditor({claimsPaused: claimsRead.paused,claimsLimited: claimsRead.limited,claimsReading: claimsRead.reading,+ brandFactsPath: sourcesOn ? brandFactsPath(draft.brandId) : null,authorConfirmed,authorConfirming: confirming,}@@ -856,7 +881,7 @@ export function DraftEditor({// The score the header and the panel show (CE-039): once the reads that// move it are in, or failed (the authors and, in phase 2, Your input for// E-E-A-T; the site's trust, the sources, the links and, in phase 2, the- // claims and the sites' kinds for Trust). Until the first time it says+ // claims, the sites' kinds and the brand's facts for Trust). Until the first time it says// it's reading; after, it keeps the last settled score while new reads// land (a link added, the agent's page), so it never jumps through the// partial averages on the way.@@ -869,6 +894,8 @@ export function DraftEditor({linksPending === 0 &&!claimsRead.reading &&!sourcesReading &&+ // Phase 2: the brand's approved facts, which Trust checks the page against.+ !(sourcesOn && factsState.status === 'loading') &&// 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);@@ -2030,7 +2057,12 @@ export function DraftEditor({reads.brief.status !== 'loading' &&reads.sources !== null &&rules.ready &&- (!qualityOn || (todosRead && siteTrustRead && linksPending === 0));+ (!qualityOn || (todosRead && siteTrustRead && linksPending === 0)) &&+ // In phase 2 the brand's facts too (their first read of the site can take+ // 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';const staleSkips =nextRead && Object.keys(liveSkips(nextState)).length !== Object.keys(skipped).length;useEffect(() => {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.tsxindex 493169dcc..d72089169 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@@ -67,7 +67,12 @@ function Harness({ todos, author }: { todos: QualityTodo[]; author: ContentAutho))}<NextNudgeshown={nudge.shown}- quality={{ author, team: 'Acme Team', canEdit: true }}+ quality={{+ author,+ team: 'Acme Team',+ canEdit: true,+ brandFactsPath: '/dashboard/brands/b1/settings?tab=facts',+ }}onShowPlaceholder={onShowPlaceholder}onPickAuthor={onPickAuthor}onLater={nudge.later}@@ -135,6 +140,25 @@ describe('NextNudge', () => {expect(nudge()).toBeNull();});+ it('sends the brand facts to approve to Brand settings (CE-047)', async () => {+ const facts: QualityTodo = {+ id: 'brandFacts',+ done: false,+ gain: 0,+ score: 'trust',+ action: 'reviewBrandFacts',+ count: 2,+ };+ await render([facts]);+ await act(async () => nudgeAt('agent'));+ expect(nudge()!.textContent).toBe(+ 'Next for you: approve 2 brand facts · 1 of 1Review nowLater',+ );+ expect(button('Review now').getAttribute('href')).toBe(+ '/dashboard/brands/b1/settings?tab=facts',+ );+ });+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.tsxindex 382a4f4fd..96a2eb288 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@@ -94,7 +94,7 @@ export function NextNudge({onAct,}: {shown: { todo: QualityTodo; count: number } | null;- quality: Pick<QualityRead, 'author' | 'team' | 'canEdit'>;+ quality: Pick<QualityRead, 'author' | 'team' | 'canEdit' | 'brandFactsPath'>;/** Selects the page's first placeholder, to type over. */onShowPlaceholder: () => void;onPickAuthor: () => void;@@ -166,6 +166,12 @@ export function NextNudge({{t('act.addInput')}</button>)+ ) : action === 'reviewBrandFacts' ? (+ quality.brandFactsPath && (+ <Link href={quality.brandFactsPath} className={actClass} onClick={onAct}>+ {t('act.reviewBrandFacts')}+ </Link>+ )) : (action && (<Link href={MANAGE_AUTHORS_PATH} 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.tsxindex 7d97f9a4c..2783314d2 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@@ -300,6 +300,60 @@ describe('QualityTab', () => {expect(done.querySelector('button')).toBeNull();});+ it('links the brand facts to approve to Brand settings, and names a price that differs (CE-047)', async () => {+ const author = ada;+ const score = eeat({ author });+ const blocks = trustBlocks(+ '<p>Pro costs $59 per month.</p><p>Up 40% (<a href="https://a.example">report</a>).</p>',+ );+ const trustRead = trust({+ blocks,+ links: new Map(),+ brandDomains: [],+ brandFacts: {+ compared: 1,+ mismatches: [+ {+ kind: 'price',+ page: '$59',+ fact: '$49',+ source: 'pricing',+ sentence: 'Pro costs $59 per month.',+ },+ ],+ },+ now: Date.parse('2026-10-24T12:00:00Z'),+ });+ await render({+ ...read(result),+ trust: trustRead,+ brandFactsPath: '/dashboard/brands/b1/settings?tab=facts',+ todos: qualityTodos({+ eeat: score,+ author,+ hasAuthors: true,+ brandFacts: { pending: 2, had: true },+ }),+ });+ // Last: the brand's, worth no points of the page's.+ const rows = [...container.querySelectorAll('[aria-label="Your to-dos"] li')];+ const row = rows.at(-1)!;+ expect(row.textContent).toContain('Approve 2 brand facts');+ expect(row.querySelector('a')!.getAttribute('href')).toBe(+ '/dashboard/brands/b1/settings?tab=facts',+ );+ const suggestion = [...container.querySelectorAll('li')].find((li) =>+ li.textContent?.includes('differs from brand facts'),+ )!;+ expect(suggestion.textContent).toContain(+ 'Price differs from brand facts · Page $59 · pricing page $49',+ );+ await act(async () =>+ [...suggestion.querySelectorAll('button')].find((b) => b.textContent === 'Show')!.click(),+ );+ expect(onShow).toHaveBeenCalledWith('Pro costs $59 per month.');+ });+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 });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.tsxindex 5566d3f9c..bee62765c 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@@ -59,6 +59,8 @@ export interface QualityRead {claimsLimited?: boolean;/** Some of the page's claims aren't read yet: Trust may change (CE-045). */claimsReading?: boolean;+ /** Where the brand's facts are approved: Brand settings › Brand facts (CE-047). */+ brandFactsPath?: string | null;/*** With no author picked, what the person confirmed of the author their* site names (00271): a real person, and their profile there.@@ -341,6 +343,15 @@ export function useTodoCopy() {: t('byline.detail.pickAuthor', { byline: team }),};}+ // The brand's facts read from its site, to approve (CE-047).+ if (todo.id === 'brandFacts') {+ const count = todo.count ?? 0;+ return {+ title: t('brandFacts.title', { count }),+ next: t('brandFacts.next', { count }),+ detail: todo.done ? t('brandFacts.done') : t('brandFacts.detail'),+ };+ }// What only the person can give (Brief › Your input, CE-048).if (todo.id === 'experience' || todo.id === 'originalData' || todo.id === 'expertQuote') {return {@@ -485,6 +496,15 @@ function TodoRow({<Button variant="outline" size="sm" className="h-7 shrink-0" onClick={onPickAuthor}>{t('pickAuthor')}</Button>+ ) : todo.action === 'reviewBrandFacts' ? (+ quality.brandFactsPath && (+ <Link+ href={quality.brandFactsPath}+ className={cn(buttonVariants({ variant: 'outline', size: 'sm' }), 'h-7 shrink-0')}+ >+ {t('reviewBrandFacts')}+ </Link>+ )) : (<Linkhref={MANAGE_AUTHORS_PATH}@@ -521,7 +541,9 @@ export type TrustSuggestion = Suggestion & { check: TrustCheckId; count: number* don't answer, each with Show on the first one in the page. A broken link* is listed before Trust is scored too, its gain out of the Phase 1 points.* Phase 2 (CE-046): weak or competitors' sources, Show and Keep on the first,- * and no primary source among them.+ * and no primary source among them. Phase 2 (CE-047): a price, trial or+ * 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[] {if (!trust) return [];@@ -546,6 +568,24 @@ export function trustSuggestions(t: T, trust: TrustRead | null): TrustSuggestionclaim: trust.marks.find((mark) => mark.sentence === first),});}+ if (trust.mismatches.length) {+ const [first] = trust.mismatches;+ out.push({+ key: 'trust:brandFacts',+ check: 'brandFacts',+ score: 'trust',+ gain: trustGain(trust, ['brandFacts']),+ line: t('checks.brandFacts.line', {+ kind: first.kind,+ page: first.page,+ source: first.source,+ fact: first.fact,+ }),+ count: trust.mismatches.length,+ detail: t('checks.brandFacts.detail', { count: trust.mismatches.length }),+ show: first.sentence,+ });+ }if (trust.stale.length) {out.push({key: 'trust:freshSources',diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brand-facts.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brand-facts.test.tsxnew file mode 100644index 000000000..4305fb526--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brand-facts.test.tsx@@ -0,0 +1,79 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { BrandFactsRead } from '@/lib/content/brand-facts';++const getBrandFacts = vi.fn();+vi.mock('@/lib/actions/brand-facts', () => ({+ getBrandFacts: (...args: unknown[]) => getBrandFacts(...args),+}));++const { useBrandFacts } = await import('./_use-brand-facts');++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++/**+ * The brand's facts in the editor (Quality CE-047): read with phase 2, again+ * when the tab comes back (from Brand settings, where they're approved).+ */++const READ: BrandFactsRead = {+ facts: [],+ pages: [],+ checkedAt: null,+ recheckAt: null,+ paused: false,+ noDomain: false,+};+let container: HTMLDivElement;+let root: Root;++function Probe({ enabled = true }: { enabled?: boolean }) {+ const state = useBrandFacts('b1', enabled);+ return <pre>{state.status}</pre>;+}+const render = (enabled = true) => act(async () => root.render(<Probe enabled={enabled} />));+const status = () => container.querySelector('pre')!.textContent;++beforeEach(() => {+ getBrandFacts.mockReset().mockResolvedValue(READ);+ container = document.createElement('div');+ root = createRoot(container);+});+afterEach(() => act(() => root.unmount()));++describe('useBrandFacts', () => {+ it('reads once, and again when the tab comes back', async () => {+ await render();+ expect(status()).toBe('ready');+ expect(getBrandFacts).toHaveBeenCalledTimes(1);+ await act(async () => document.dispatchEvent(new Event('visibilitychange')));+ expect(getBrandFacts).toHaveBeenCalledTimes(2);+ });++ it('keeps a read when a later one fails, says off when the API has them off, and reads nothing before phase 2', async () => {+ await render();+ getBrandFacts.mockResolvedValueOnce({ error: 'failed' });+ await act(async () => document.dispatchEvent(new Event('visibilitychange')));+ expect(status()).toBe('ready');+ getBrandFacts.mockResolvedValueOnce({ error: 'off' });+ await act(async () => document.dispatchEvent(new Event('visibilitychange')));+ expect(status()).toBe('off');++ act(() => root.unmount());+ root = createRoot(container);+ getBrandFacts.mockClear();+ await render(false);+ expect(status()).toBe('off');+ expect(getBrandFacts).not.toHaveBeenCalled();+ });++ it('fails, not loads for ever, when the action throws', async () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ getBrandFacts.mockRejectedValueOnce(new Error('deploy skew'));+ await render();+ expect(status()).toBe('failed');+ error.mockRestore();+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brand-facts.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brand-facts.tsnew file mode 100644index 000000000..e8be5ee57--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-brand-facts.ts@@ -0,0 +1,52 @@+'use client';++import { useEffect, useState } from 'react';+import { getBrandFacts } from '@/lib/actions/brand-facts';+import type { BrandFactsRead } from '@/lib/content/brand-facts';++export type BrandFactsState =+ | { status: 'off' }+ | { status: 'loading' }+ | { status: 'ready'; read: BrandFactsRead }+ | { status: 'failed' };++/**+ * The brand's facts in the editor (Quality CE-047): read once with Quality's+ * second phase (the editor opens again after Review, from Brand settings),+ * and again when its browser tab comes back (Brand settings open in+ * another). An API with them off is 'off'; a failed read keeps the one+ * before it, or is 'failed'.+ */+export function useBrandFacts(brandId: string, enabled: boolean): BrandFactsState {+ const [state, setState] = useState<BrandFactsState>({ status: 'loading' });+ const [visits, setVisits] = useState(0);+ useEffect(() => {+ if (!enabled) return;+ const onVisible = () => {+ if (document.visibilityState === 'visible') setVisits((n) => n + 1);+ };+ document.addEventListener('visibilitychange', onVisible);+ return () => document.removeEventListener('visibilitychange', onVisible);+ }, [enabled]);+ useEffect(() => {+ if (!enabled) return;+ let live = true;+ const failed = () =>+ setState((prev) => (prev.status === 'ready' ? prev : { status: 'failed' }));+ getBrandFacts(brandId)+ .then((result) => {+ if (!live) return;+ if (!('error' in result)) setState({ status: 'ready', read: result });+ else if (result.error === 'off') setState({ status: 'off' });+ else failed();+ })+ .catch((err) => {+ console.error('Failed to read the brand facts:', err);+ if (live) failed();+ });+ return () => {+ live = false;+ };+ }, [brandId, enabled, visits]);+ return enabled ? state : { status: 'off' };+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/page.test.tsxindex b46f2fea1..4e3d27491 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@@ -21,6 +21,7 @@ const setContentDraftAuthor = vi.fn();const keepDraftSource = vi.fn();const confirmDraftAuthor = vi.fn();const checkDraftClaims = vi.fn();+const getBrandFacts = vi.fn();const checkDraftLinks = vi.fn();const getSiteTrust = vi.fn();vi.mock('@/lib/actions/audits', () => ({@@ -60,6 +61,9 @@ const keepAgentBeforeVersion = vi.fn();const fixDraftRules = vi.fn();const startAgentWriting = vi.fn();const startPageRewrite = vi.fn();+vi.mock('@/lib/actions/brand-facts', () => ({+ getBrandFacts: (...args: unknown[]) => getBrandFacts(...args),+}));vi.mock('@/lib/actions/content-drafts', () => ({fixDraftRules: (...args: unknown[]) => fixDraftRules(...args),startAgentWriting: (...args: unknown[]) => startAgentWriting(...args),@@ -289,6 +293,14 @@ beforeEach(() => {keepDraftSource.mockReset();confirmDraftAuthor.mockReset().mockResolvedValue(undefined);checkDraftClaims.mockReset().mockResolvedValue({ blocks: [], pending: 0, limited: false });+ getBrandFacts.mockReset().mockResolvedValue({+ facts: [],+ pages: [],+ checkedAt: null,+ recheckAt: null,+ paused: false,+ noDomain: false,+ });checkDraftLinks.mockReset().mockResolvedValue({ links: [], skipped: [] });getSiteTrust.mockReset().mockRejectedValue(new Error('not in this test'));getContentAuthors.mockReset().mockResolvedValue(null);@@ -2681,6 +2693,41 @@ describe('the side panel', () => {}});+ it('holds the score until the brand’s facts are read: Trust checks the page against them', 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' },+ });+ let factsIn: (value: unknown) => void = () => {};+ getBrandFacts.mockReturnValue(new Promise((resolve) => (factsIn = resolve)));+ getContentDraft.mockResolvedValue(readable);+ window.innerWidth = 1440;+ await renderPage();+ await act(async () => void (await vi.advanceTimersByTimeAsync(3_000)));+ // Every other read is in: the facts still hold it.+ expect(qualityChip()?.textContent).toBe('Quality · reading…');+ await act(async () =>+ factsIn({+ facts: [],+ pages: [],+ checkedAt: null,+ recheckAt: null,+ paused: false,+ noDomain: false,+ }),+ );+ expect(qualityChip()?.textContent).toMatch(+ /^Quality \d+ · (Strong|Can improve|Needs work)$/,+ );+ } finally {+ vi.useRealTimers();+ }+ });+it('holds the score while an edit waits for its save: phase 2 reads the page as saved', async () => {process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '2';vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });@@ -2979,6 +3026,86 @@ describe('the side panel', () => {});});+ describe('Brand facts (Quality CE-047)', () => {+ afterEach(() => {+ delete process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE;+ });+ beforeEach(() => {+ getDraftSources.mockResolvedValue({+ data: {+ prompts: [],+ fanouts: [],+ citedPages: [],+ gscQueries: [],+ brandDomains: ['acme.com'],+ competitorDomains: [],+ },+ choices: [],+ });+ });+ const fact = (over: Record<string, unknown>) => ({+ id: 'f1',+ kind: 'price',+ value: { plan: 'Pro', amount: 49, currency: 'USD', period: 'month', billed: null, per: null },+ quote: '$49 per month',+ sourceUrl: 'https://acme.com/pricing',+ sourceKind: 'pricing',+ status: 'approved',+ reviewedAt: null,+ firstSeenAt: '2026-10-24T00:00:00Z',+ gone: false,+ replaces: null,+ ...over,+ });++ it('names a price the page gives that differs, and asks to approve the facts read', async () => {+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '2';+ getBrandFacts.mockResolvedValue({+ facts: [+ fact({}),+ fact({ id: 'f2', kind: 'trial', value: { days: 14 }, status: 'pending' }),+ ],+ pages: [],+ checkedAt: null,+ recheckAt: null,+ paused: false,+ noDomain: false,+ });+ getContentDraft.mockResolvedValue(+ draft({+ bodyHtml:+ '<h1>Pricing</h1><p>The Pro plan costs $59 per month.</p>' ++ // A sourced figure: Trust is scored, so Quality's chip is there.+ '<p>Teams cut 40% of their busywork (<a href="https://research.example/r">report</a>).</p>',+ }),+ );+ window.innerWidth = 1440;+ await renderPage();+ expect(getBrandFacts).toHaveBeenCalledWith(draft().brandId);+ const chip = [...container.querySelectorAll<HTMLButtonElement>('header button')].find((b) =>+ b.textContent?.startsWith('Quality'),+ )!;+ await act(async () => chip.click());+ expect(panel()!.textContent).toContain(+ 'Price differs from brand facts · Page $59 · pricing page $49',+ );+ const todo = [...panel()!.querySelectorAll('li')].find((li) =>+ li.textContent?.includes('Approve 1 brand fact'),+ )!;+ expect(todo.querySelector('a')!.getAttribute('href')).toBe(+ `/dashboard/brands/${draft().brandId}/settings?tab=facts`,+ );+ });++ it('reads no brand facts before Quality’s second phase', async () => {+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '1';+ getContentDraft.mockResolvedValue(draft({}));+ window.innerWidth = 1440;+ await renderPage();+ expect(getBrandFacts).not.toHaveBeenCalled();+ });+ });+describe('Sources by kind (Quality CE-046)', () => {afterEach(() => {delete process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE;@@ -4162,6 +4289,46 @@ describe('the side panel', () => {expect(nextButton()!.getAttribute('aria-label')).not.toBe('Next · Plan the page');});+ it('drops a stale skip once the reads are in, in phase 2 the brand facts too', async () => {+ const skips = () => JSON.parse(localStorage.getItem('aeo:next-step-skips:d1')!);+ getContentAuthors.mockResolvedValue({+ authors: [],+ brands: [{ id: 'b1', name: 'Acme' }],+ me: { id: 'u1', role: 'admin' },+ });+ getContentDraft.mockResolvedValue(draft({ method: 'create' }));+ try {+ // Phase 1 reads no brand facts: nothing to wait for.+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '1';+ localStorage.setItem('aeo:next-step-skips:d1', JSON.stringify({ plan: 'true' }));+ await renderPage();+ expect(skips()).toEqual({});++ // Phase 2: they move Trust, which a proof skip was made at.+ process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE = '2';+ localStorage.setItem('aeo:next-step-skips:d1', JSON.stringify({ plan: 'true' }));+ let factsIn!: (read: unknown) => void;+ getBrandFacts.mockReturnValue(new Promise((resolve) => (factsIn = resolve)));+ await act(async () => root.unmount());+ root = createRoot(container);+ await renderPage();+ expect(skips()).toEqual({ plan: 'true' });+ await act(async () =>+ factsIn({+ facts: [],+ pages: [],+ checkedAt: null,+ recheckAt: null,+ paused: false,+ noDomain: false,+ }),+ );+ expect(skips()).toEqual({});+ } finally {+ delete process.env.NEXT_PUBLIC_CONTENT_QUALITY_PHASE;+ }+ });+it("stays open on Skip, and leaves an empty page to the person once they'll write it", async () => {getContentDraft.mockResolvedValue(draft({ method: 'create', bodyHtml: '<h1>Pipeline forecasting</h1><p></p>' }),diff --git a/web/src/lib/content/brand-facts.test.ts b/web/src/lib/content/brand-facts.test.tsindex 2ea6c1b6c..78f580d2a 100644--- a/web/src/lib/content/brand-facts.test.ts+++ b/web/src/lib/content/brand-facts.test.ts@@ -1,5 +1,11 @@import { describe, expect, it } from 'vitest';-import { brandFactsPath, factValueText } from './brand-facts';+import {+ brandFactsPath,+ factMismatches,+ factValueText,+ pagePrices,+ type BrandFact,+} from './brand-facts';/** A brand fact's value as a person reads it (Quality CE-047). */describe('factValueText', () => {@@ -21,3 +27,296 @@ describe('factValueText', () => {expect(brandFactsPath('b1')).toBe('/dashboard/brands/b1/settings?tab=facts');});});++const approved = (over: Partial<BrandFact>): BrandFact => ({+ id: 'f',+ kind: 'price',+ value: {+ plan: 'Pro',+ amount: 49,+ currency: 'USD',+ period: 'month',+ billed: 'monthly',+ per: null,+ },+ quote: '$49 per month',+ sourceUrl: 'https://ledgerly.example/pricing',+ sourceKind: 'pricing',+ status: 'approved',+ reviewedAt: null,+ firstSeenAt: '2026-10-24T00:00:00Z',+ gone: false,+ replaces: null,+ ...over,+});+const price = (plan: string, amount: number, billed: 'monthly' | 'annually' | null = null) =>+ approved({+ id: `${plan}-${amount}`,+ value: { plan, amount, currency: 'USD', period: 'month', billed, per: null },+ });+const FACTS = [+ price('Free', 0),+ price('Starter', 19, 'monthly'),+ price('Starter', 15, 'annually'),+ price('Pro', 49, 'monthly'),+ price('Pro', 39, 'annually'),+ price('Team', 99),+ price('Business', 199),+ price('Growth', 299),+ approved({ id: 'trial', kind: 'trial', value: { days: 14 }, quote: '14-day free trial' }),+ approved({+ id: 'year',+ kind: 'founded',+ value: { year: 2015 },+ quote: 'Founded in 2015',+ sourceKind: 'about',+ }),+ // Not approved, or gone from the site: never compared.+ approved({+ id: 'p',+ status: 'pending',+ value: { plan: 'Pro', amount: 59, currency: 'USD', period: 'month', billed: null, per: null },+ }),+ approved({+ id: 'g',+ gone: true,+ value: { plan: 'Pro', amount: 69, currency: 'USD', period: 'month', billed: null, per: null },+ }),+];+const check = (sentences: string[], facts = FACTS) =>+ factMismatches({+ sentences,+ facts,+ brandName: 'Ledgerly',+ competitorDomains: ['northwind.example'],+ });++describe('pagePrices', () => {+ it('reads a price with its currency and period, and no scale, range or "off"', () => {+ expect(+ pagePrices('Pro costs $49 per month, or €45/mo in Europe.').map((p) => [p.text, p.period]),+ ).toEqual([+ ['$49', 'month'],+ ['€45', 'month'],+ ]);+ expect(pagePrices('Plans start at $19 a month.')[0]).toMatchObject({ amount: 19, from: true });+ expect(+ pagePrices('Teams raised $2M, get $5 off, paying $10–$20 or between $30 and $40.'),+ ).toEqual([]);+ expect(pagePrices('Pro coûte de 49 € à 99 € par mois, ou 49 TL ile 99 TL arası.')).toEqual([]);+ expect(pagePrices('1 299 € par an')[0]).toMatchObject({ amount: 1299, period: 'year' });+ // A dash after a plan's name isn't a range.+ expect(pagePrices('Pro – $49 per month')[0]).toMatchObject({ amount: 49 });+ expect(pagePrices('Since 2019 199 € per month')[0]).toMatchObject({ amount: 199 });+ });+});++describe('factMismatches', () => {+ it('names a plan’s price that differs, against any of its approved ones', () => {+ expect(check(['Ledgerly Pro costs $59 per month.'])).toEqual({+ compared: 1,+ mismatches: [+ {+ kind: 'price',+ page: '$59',+ fact: '$49',+ source: 'pricing',+ sentence: 'Ledgerly Pro costs $59 per month.',+ },+ ],+ });+ expect(+ check([+ 'Ledgerly Pro is $49 per month.',+ 'The Pro plan is $39/mo billed annually.',+ 'The Starter plan is $19/month and the Pro plan $49/month.',+ 'Ledgerly starts at $19 per month.',+ ]),+ ).toEqual({ compared: 5, mismatches: [] });+ expect(check(['The Pro plan costs $45 a month billed annually.']).mismatches[0]).toMatchObject({+ page: '$45',+ fact: '$39',+ });+ });++ it('cries no wolf on everyday copy', () => {+ expect(+ check([+ 'Pro tip: budget $100 a month for ads.',+ 'Our team spent $5,000 a month on ads.',+ 'For a small business, expect to pay $30 per month for hosting.',+ 'Growth agencies charge $5,000 a month.',+ 'Get a free consultation worth $200.',+ 'Start free, then pay $49 per month for Pro.',+ 'Upgrades are pro-rated, so you pay $12 a month.',+ 'We spent $2,000 a month on ads before switching.',+ 'Most of our clients budget $1,000 a month for SEO.',+ 'If you hire an agency, expect to pay $3,000 per month; with us it is less.',+ 'Unlike Profound, which charges $499 a month, we start at $79.',+ 'Pro is now $39/month (was $49).',+ 'Ledgerly Pro: $39 a month instead of $49.',+ 'Ledgerly Pro is €49 per month, €58.31 incl. VAT.',+ 'The Pro plan includes $50 a month in ad credits.',+ 'A 5-person team on Pro pays $245 a month.',+ 'Pro is €45 per month in Europe.',+ 'Northwind Pro costs $29 per month.',+ 'HubSpot Starter costs $20 per month per seat.',+ 'Ledgerly Pro costs $49 per month billed monthly.',+ ]),+ ).toMatchObject({ mismatches: [] });+ });++ it('ties a figure to the brand, not only to a sentence that names it (review, #1465)', () => {+ expect(+ check([+ // A price with no plan named: only right after the brand's name and a pricing verb.+ 'If you hire an agency, expect to pay $3,000 per month; with Ledgerly it is less.',+ // A year the brand's data is about, not when it was founded.+ "Ledgerly's data shows startups founded in 2020 grew faster.",+ // Two trial lengths: another brand's beside the brand's.+ "Acme offers a free 15-day trial; Ledgerly's runs for 14 days.",+ // Each plan's own price: Business isn't found, its price isn't read.+ 'The Pro plan is $49 a month, and Business is $199 a month.',+ // An add-on beside the plan's price.+ 'The Pro plan is $49 per month, plus $10 per month for each extra seat.',+ ]),+ ).toMatchObject({ mismatches: [] });+ expect(+ check([+ // Another plan named beside the price's: which is whose isn't sure.+ 'The Starter plan has fewer features, while the Pro plan is $49 a month.',+ 'Unlike the Starter plan, the Pro plan costs $49 a month.',+ // More prices than plans named: which is whose isn't sure.+ 'The Pro plan is $49/month or $39/month billed annually.',+ // Another brand's trial, in a part that doesn't name the brand.+ "Acme offers a free 15-day trial; Ledgerly's is longer.",+ // Another bill than the plan's.+ 'Ledgerly setup costs $500 once.',+ 'Ledgerly customer acquisition costs $45 on average.',+ 'The Pro plan setup costs $500.',+ // Two prices with no plan named, or a plan between: which is whose isn't sure.+ 'Ledgerly costs $29/month, or $24/month billed annually.',+ 'The Pro plan, unlike the Starter plan, costs $49 a month.',+ // A partner's trial.+ 'Ledgerly integrates with Acme, which offers a 30-day free trial.',+ // Someone else's founding, and quoted speech.+ 'The agency that built Ledgerly was founded in 2009.',+ '“We were founded in 2018,” says Acme’s CEO.',+ ]),+ ).toMatchObject({ mismatches: [] });+ // Said of the brand, they're still read.+ expect(check(["Ledgerly's pricing starts at $25 per month."]).mismatches).toMatchObject([+ { kind: 'price', page: '$25' },+ ]);+ expect(+ check(['The Starter plan is $25 a month, and the Pro plan is $49 a month.']).mismatches,+ ).toMatchObject([{ kind: 'price', page: '$25', fact: '$19' }]);+ expect(check(["Ledgerly's trial runs for 30 days."]).mismatches).toMatchObject([+ { kind: 'trial', page: '30-day' },+ ]);+ expect(+ check(['Setup takes 3 days, and your free trial lasts 30 days.']).mismatches,+ ).toMatchObject([{ kind: 'trial', page: '30-day' }]);+ expect(check(['Since Ledgerly was founded in 2012, it has grown.']).mismatches).toMatchObject([+ { kind: 'founded', page: '2012' },+ ]);+ expect(check(['Ledgerly was founded in 2016.']).mismatches).toMatchObject([+ { kind: 'founded', page: '2016' },+ ]);+ });++ it('reads a plan’s price only right after its name, and no figure compared or saved (review 2, #1465)', () => {+ expect(+ check([+ 'The Pro plan costs $30 more than Starter.',+ 'Ledgerly Pro saves most teams $300 a month.',+ 'Pro plan users invoice an average of $12,000 a month.',+ 'Moving from Starter to the Pro plan adds $30 a month.',+ 'Team leads at Ledgerly approve $40,000 a month in expenses.',+ 'Ledgerly costs $20 less per month than most bookkeeping apps.',+ // A trial that's another's before the brand's name, or files and support kept free.+ "Unlike Acme's 30-day trial, Ledgerly's needs no credit card.",+ 'Unlike Acme, which offers a 30-day trial, Ledgerly gives you 14 days free.',+ 'Ledgerly keeps your files free for 30 days after you cancel.',+ 'Every plan includes priority support free for 30 days.',+ // "We" after a colon: someone quoted without quote marks.+ "Acme's CEO told us: we were founded in 2018 to fix bookkeeping.",+ ]),+ ).toEqual({ compared: 0, mismatches: [] });+ // Right after the plan's name, with a colon, a dash or "(", they're still read.+ expect(+ check([+ 'Ledgerly Pro: $59 a month.',+ 'Ledgerly Pro – $59 per month.',+ 'Ledgerly Pro ($59/month).',+ ]).mismatches,+ ).toMatchObject([+ { kind: 'price', page: '$59' },+ { kind: 'price', page: '$59' },+ { kind: 'price', page: '$59' },+ ]);+ expect(check(['Try Ledgerly free for 3 weeks.']).mismatches).toMatchObject([+ { kind: 'trial', page: '21-day' },+ ]);+ expect(check(['Ledgerly is free for 30 days during the trial.']).mismatches).toMatchObject([+ { kind: 'trial', page: '30-day' },+ ]);+ expect(check(['Since 2014: we were founded in 2014.']).mismatches).toEqual([]);+ expect(check(['After years of planning, we were founded in 2018.']).mismatches).toEqual([]);+ expect(check(['We were founded in 2018 in Lisbon.']).mismatches).toMatchObject([+ { kind: 'founded', page: '2018' },+ ]);+ });++ it('compares a trial only where it is the brand’s, its days beside it', () => {+ expect(check(['Every plan has a 30-day free trial.']).mismatches).toEqual([+ {+ kind: 'trial',+ page: '30-day',+ fact: '14-day',+ source: 'pricing',+ sentence: 'Every plan has a 30-day free trial.',+ },+ ]);+ expect(+ check([+ 'Every plan comes with a 30-day money-back guarantee and a free trial.',+ 'In a 12-week clinical trial, patients improved.',+ 'We ran a 90-day trial of the new workflow.',+ 'Setup takes 3 days, and your free trial lasts 14 days.',+ 'Help Scout offers a free 15-day trial.',+ 'Try Ledgerly free for 2 weeks.',+ ]).mismatches,+ ).toEqual([]);+ });++ it('compares a founding year only right after "founded", said of the brand', () => {+ expect(check(['Ledgerly was founded in 2012.']).mismatches).toEqual([+ {+ kind: 'founded',+ page: '2012',+ fact: '2015',+ source: 'about',+ sentence: 'Ledgerly was founded in 2012.',+ },+ ]);+ expect(+ check([+ 'In 2023, we celebrated 10 years since Ledgerly was founded.',+ 'Our data shows startups founded in 2020 grew faster.',+ 'In 2022 we established a new baseline.',+ 'We helped Acme Bank (founded 1998) grow.',+ 'We were founded in 2015 in Lisbon.',+ ]).mismatches,+ ).toEqual([]);+ });++ it('reads each sentence once', () => {+ const same = 'Every plan has a 30-day free trial.';+ expect(check([same, same, same])).toMatchObject({ compared: 1 });+ expect(check(['Ledgerly Pro costs $59 per month.'], [])).toEqual({+ compared: 0,+ mismatches: [],+ });+ });+});diff --git a/web/src/lib/content/brand-facts.ts b/web/src/lib/content/brand-facts.tsindex 3700e398e..acb43ce3a 100644--- a/web/src/lib/content/brand-facts.ts+++ b/web/src/lib/content/brand-facts.ts@@ -87,3 +87,552 @@ export function factValueText(kind: FactKind, value: FactValue, quote = ''): strif (kind === 'founded') return String((value as { year: number }).year);return quote;}++/** Currency marks, the longest first ("US$" before "$"), as the API reads them. */+const CURRENCY_MARKS: [string, string][] = [+ ['US$', 'USD'],+ ['CA$', 'CAD'],+ ['AU$', 'AUD'],+ ['NZ$', 'NZD'],+ ['HK$', 'HKD'],+ ['R$', 'BRL'],+ ['C$', 'CAD'],+ ['A$', 'AUD'],+ ['S$', 'SGD'],+ ['$', 'USD'],+ ['€', 'EUR'],+ ['£', 'GBP'],+ ['₺', 'TRY'],+ ['¥', 'JPY'],+ ['₹', 'INR'],+];+const ISO = [+ 'USD',+ 'EUR',+ 'GBP',+ 'TRY',+ 'JPY',+ 'INR',+ 'CHF',+ 'CAD',+ 'AUD',+ 'NZD',+ 'SEK',+ 'NOK',+ 'DKK',+ 'PLN',+ 'BRL',+ 'MXN',+ 'SGD',+ 'HKD',+ 'ZAR',+];+const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+const MARK = `(?:${CURRENCY_MARKS.map(([m]) => escape(m)).join('|')})`;+const CODE = `(?<![\\p{L}])(?:${ISO.join('|')}|TL)(?![\\p{L}])`;+/** Thousands by a comma or a point, or by a space when the currency comes after ("1 299 €"). */+const amount = (groups: string) =>+ String.raw`(?<![\d.,])(?:\d{1,3}(?:${groups}\d{3})+(?:[.,]\d{1,2})?|\d+(?:[.,]\d{1,2})?)(?![\d]|[.,]\d)`;+const PRICE = new RegExp(+ `(?<before>${MARK}|${CODE})\\s?(?<a>${amount('[.,]')})|(?<b>${amount('[.,\\s]')})\\s?(?<after>${MARK}|${CODE}|zł)`,+ 'gu',+);+const MAGNITUDE =+ /^\s*(?:[kmb](?!\p{L})|bn\b|mn\b|thousand|million|billion|milyon|milyar|mio\b|mrd\b)/iu;+/** "$10–$20", "between $10 and $20": a range, its two ends (a number before the word or dash). */+const RANGE_AFTER =+ /^\s?(?:[–—-]|to\b|bis\b|ile\b|ila\b|and\b|und\b|et\b|ve\b|à(?=\s)|a(?=\s)|y(?=\s))\s?\S{0,4}\d/iu;+const RANGE_BEFORE = /\d\s?(?:\S{1,3}\s)?(?:[–—-]|to|bis|ile|ila|and|und|et|ve|à|a|y)\s?\S{0,4}$/iu;+/**+ * A sentence whose amounts aren't a plan's price: an old price, a saving,+ * a discount, credits, tax added, or a team's bill ("A 5-person team pays+ * $245").+ */+const NOT_A_PRICE =+ /(?<!\p{L})(?:was|instead\s+of|regularly|originally|sav(?:e|es|ed|ing|ings)|off|discount|coupon|credits?|incl\.?|including\s+(?:vat|tax)|inkl\.?|kdv\s+dahil|statt|rabatt|indirim|tasarruf|économisez|ahorra|refund|money-back|extra|additional|add-ons?|ek\s+ücret|zusätzlich|setup|set-up|onboarding|implementation|installation|one-time|kurulum)(?!\p{L})|\d+[\s-]?(?:person|people|users?|seats?|members?|kişi(?:lik)?|kullanıcı)(?!\p{L})/iu;+const MONTH =+ /^[^\d$€£¥₹₺]{0,20}?(?:\/\s?(?:mo|mth|month|ay|monat|mois|mes)\b|\b(?:per|a|each)\s+month\b|\bmonthly\b|\baylık\b|\bayda\b|\bmonatlich\b|\b(?:pro|im)\s+monat\b|\bpar\s+mois\b|\b(?:al|por)\s+mes\b)/iu;+const YEAR =+ /^[^\d$€£¥₹₺]{0,20}?(?:\/\s?(?:yr|year|yıl|jahr|an|año)\b|\b(?:per|a|each)\s+year\b|\bannually\b|\byearly\b|\byıllık\b|\byılda\b|\bjährlich\b|\b(?:pro|im)\s+jahr\b|\bpar\s+an\b|\b(?:al|por)\s+año\b)/iu;+/** How a sentence says a price is billed: "billed annually", "with annual billing". */+const BILLED_YEAR =+ /billed\s+(?:annually|yearly)|(?:annual|yearly)\s+(?:billing|plan)|paid\s+(?:annually|yearly)|yıllık\s+ödeme|jährliche\s+zahlung/iu;+const BILLED_MONTH =+ /billed\s+monthly|monthly\s+billing|paid\s+monthly|aylık\s+ödeme|monatliche\s+zahlung/iu;+const FROM = /\b(?:from|start(?:s|ing)?\s+(?:at|from)|ab|à\s+partir\s+de|desde)\s*$/iu;+/** "₺499'dan başlayan": Turkish says it after the price. */+const FROM_AFTER = /^['’]?(?:den|dan|ten|tan)\s+(?:başlayan|itibaren)/iu;++const currencyOf = (mark: string) =>+ mark === 'TL'+ ? 'TRY'+ : mark === 'zł'+ ? 'PLN'+ : (CURRENCY_MARKS.find(([m]) => m === mark)?.[1] ?? (ISO.includes(mark) ? mark : null));++/** An amount as written: a separator before exactly three digits groups thousands. */+const amountOf = (token: string) => {+ const value = Number(token.replace(/[.,\s](?=\d{3}(?!\d))/g, '').replace(',', '.'));+ return Number.isFinite(value) ? value : null;+};++/** A price a page's sentence gives: as written, its amount, currency and period, where, and whether it is "from". */+export interface PagePrice {+ text: string;+ amount: number;+ currency: string;+ period: 'month' | 'year' | null;+ from: boolean;+ at: number;+}++/**+ * The prices a sentence gives, the way the API reads a brand's: a scale+ * ("$2M"), a range ("$10–$20") and "$10 off" are none.+ */+export function pagePrices(sentence: string): PagePrice[] {+ const out: PagePrice[] = [];+ for (const m of sentence.matchAll(PRICE)) {+ const g = m.groups!;+ const end = m.index + m[0].length;+ const before = sentence.slice(Math.max(0, m.index - 24), m.index);+ const after = sentence.slice(end, end + 40);+ if (MAGNITUDE.test(after) || /^\s*off(?!\p{L})/iu.test(after)) continue;+ if (RANGE_AFTER.test(after) || RANGE_BEFORE.test(before)) continue;+ const currency = currencyOf(g.before ?? g.after);+ const value = amountOf(g.a ?? g.b);+ if (!currency || value === null) continue;+ out.push({+ text: m[0].trim(),+ amount: value,+ currency,+ period: MONTH.test(after) ? 'month' : YEAR.test(after) ? 'year' : null,+ from: FROM.test(before) || FROM_AFTER.test(after),+ at: m.index,+ });+ }+ return out;+}++/** A page's fact that differs from an approved one: Trust's suggestion names both. */+export interface FactMismatch {+ kind: 'price' | 'trial' | 'founded';+ /** The page's value, as written ("$39"). */+ page: string;+ /** The approved value ("$49"). */+ fact: string;+ /** The page the approved one was read from. */+ source: FactSource;+ /** The sentence it is in: Show goes there. */+ sentence: string;+}++/**+ * Plan names that are everyday words ("Pro tip", "our team", "a free+ * consultation"): named only beside "plan" or "tier", or in a sentence+ * that names the brand.+ */+const COMMON_PLANS = new Set([+ 'free',+ 'pro',+ 'plus',+ 'team',+ 'teams',+ 'business',+ 'basic',+ 'starter',+ 'growth',+ 'standard',+ 'premium',+ 'enterprise',+ 'personal',+ 'professional',+ 'essential',+ 'essentials',+ 'advanced',+ 'ultimate',+ 'lite',+ 'max',+ 'scale',+ 'startup',+ 'agency',+ 'solo',+ 'individual',+ 'small business',+]);+const PLAN_WORD = /^\s*(?:plan|tier|package|edition|paket|planı|tarif)(?!\p{L})/iu;+/** "Ledgerly" as a word, the brand's name as written. */+const named = (sentence: string, name: string) =>+ name.trim().length > 2 &&+ new RegExp(`(?<![\\p{L}\\p{N}])${escape(name.trim())}(?![\\p{L}\\p{N}])`, 'u').test(sentence);+/** Where a plan is named in a sentence, as the page writes it (its case too); -1 when it isn't. */+function planAt(sentence: string, plan: string, brandNamed: boolean): number {+ const re = new RegExp(`(?<![\\p{L}\\p{N}])${escape(plan)}(?![\\p{L}\\p{N}])`, 'gu');+ for (const m of sentence.matchAll(re)) {+ const common = COMMON_PLANS.has(plan.toLowerCase());+ if (!common || brandNamed || PLAN_WORD.test(sentence.slice(m.index + m[0].length))) {+ return m.index;+ }+ }+ return -1;+}+/**+ * The brand's own price, said of it right after its name ("Ledgerly costs+ * $29 a month", "Ledgerly's pricing starts at $19"): a pricing verb right+ * after the name, or after its plan or pricing ("Ledgerly setup costs" is+ * another bill), then the price, no other amount between.+ */+const PRICED_AFTER_NAME =+ /^['’]?s?\s+(?:(?:monthly|annual|yearly|base|basic)\s+)?(?:(?:plans?|pricing|price|subscriptions?|licen[cs]es?|membership)\s+)?(?:(?:now|currently|only|just)\s+)?(?:costs?|charges?|is\s+priced\s+at|priced\s+at|starts?\s+(?:at|from)|starting\s+at|kostet|coûte|cuesta)\s+(?:(?:just|only|from|ab|desde)\s+)?$/iu;+/**+ * A named plan's own price, said right after its name ("Ledgerly Pro costs+ * $59", "The Pro plan is $39/mo", "…and the Pro plan $49/month", "Pro:+ * $49", "Pro ($49/month)"): its "plan" or "tier" word, then nothing, "is",+ * a colon, a dash, "(" or a pricing verb, and "just", "only" or "from" ("Pro+ * plan users invoice $12,000", "the Pro plan adds $30" are other amounts).+ */+const PRICED_AFTER_PLAN =+ /^(?:\s+(?:plan|tier|package|edition|paket|planı|tarif)(?!\p{L}))?(?:['’]s)?\s*(?:(?:is|:|[–—-]|\()\s*)?(?:(?:now|currently)\s+)?(?:(?:costs?|charges?|is\s+priced\s+at|priced\s+at|starts?\s+(?:at|from)|starting\s+at|kostet|coûte|cuesta)\s+)?(?:(?:just|only|from|ab|desde)\s+)?$/iu;+/** Words that compare a price with another ("$30 more than Starter", "$20 less per month than…"). */+const COMPARING = new Set([+ 'more',+ 'less',+ 'cheaper',+ 'pricier',+ 'than',+ 'mehr',+ 'weniger',+ 'günstiger',+ 'teurer',+ 'als',+ 'daha',+ 'moins',+ 'más',+ 'menos',+]);+/** A price compared with another, within a few words after it: no plan's price. */+const comparedAfter = (sentence: string, price: PagePrice) =>+ sentence+ .slice(price.at + price.text.length)+ .split(/\s+/)+ .slice(0, 5)+ .some((word) => COMPARING.has(word.toLowerCase().replace(/[^\p{L}]/gu, '')));+/** Where a name is in a sentence, as whole words: each start. */+const namedAt = (sentence: string, name: string) =>+ name.trim().length > 2+ ? [+ ...sentence.matchAll(+ new RegExp(`(?<![\\p{L}\\p{N}])${escape(name.trim())}(?![\\p{L}\\p{N}])`, 'gu'),+ ),+ ].map((m) => ({ at: m.index, end: m.index + m[0].length }))+ : [];+const TRIAL_DAYS = [+ /(?<!\d)(\d{1,3})[\s-]?days?[\s-]+(?:free\s+)?trial/iu,+ /trial\s+(?:of|for|lasts?|is)\s+(\d{1,3})\s+days?(?!\p{L})/iu,+ /(?<!\d)(\d{1,3})\s+günlük\s+(?:ücretsiz\s+)?deneme/iu,+ /(?<!\d)(\d{1,3})[\s-]?(?:tage|tägige)\s+(?:kostenlose\s+)?(?:testphase|testversion)/iu,+];+const TRIAL_WEEKS = [+ /(?<!\d)(\d{1,2})[\s-]?weeks?[\s-]+(?:free\s+)?trial/iu,+ /trial\s+(?:of|for|lasts?|is)\s+(\d{1,2})\s+weeks?(?!\p{L})/iu,+];+/**+ * "Free for 14 days": a trial only in a sentence that says "trial", or+ * after "try" or "use" and the brand ("Ledgerly keeps your files free for+ * 30 days", "priority support free for 30 days" are no trial).+ */+const FREE_FOR: [RegExp, number][] = [+ [/free\s+for\s+(\d{1,3})\s+days?(?!\p{L})/iu, 1],+ [/free\s+for\s+(\d{1,2})\s+weeks?(?!\p{L})/iu, 7],+];+const SAYS_TRIAL = /trial|deneme|testphase|testversion/iu;+/** A trial said of the brand's plans: "your free trial", "every plan". */+const OWN_TRIAL =+ /\b(?:your|our)\s+(?:free\s+)?trial\b|\b(?:every|all|each)\s+plans?\b|\bher\s+plan|\btüm\s+planlar/iu;+/** A trial length a text gives, in days, and where it is. */+interface TrialLength {+ days: number;+ at: number;+}+/** Every trial length a text gives; "free for N days" where `tried` says it's a trial there. */+const trialLengths = (text: string, tried: (before: string) => boolean): TrialLength[] => [+ ...TRIAL_DAYS.flatMap((re) =>+ [...text.matchAll(new RegExp(re.source, 'giu'))].map((m) => ({+ days: Number(m[1]),+ at: m.index,+ })),+ ),+ ...TRIAL_WEEKS.flatMap((re) =>+ [...text.matchAll(new RegExp(re.source, 'giu'))].map((m) => ({+ days: Number(m[1]) * 7,+ at: m.index,+ })),+ ),+ ...FREE_FOR.flatMap(([re, unit]) =>+ [...text.matchAll(new RegExp(re.source, 'giu'))]+ .filter((m) => tried(text.slice(0, m.index)))+ .map((m) => ({ days: Number(m[1]) * unit, at: m.index })),+ ),+];+/**+ * A length said of someone's own: "…; Ledgerly's runs for 14 days" (a trial+ * named before it), "Ledgerly's trial runs for 30 days".+ */+const OWNED_LENGTH =+ /(?:['’]s|\b(?:its|theirs|ours|yours))\s+(?:[\p{L}-]+\s+)?(?:runs?|lasts?|is|are)\s+(?:for\s+)?(?:(?:just|only)\s+)?(\d{1,3})[\s-]?(days?|weeks?)(?!\p{L})/giu;+/**+ * Where a sentence turns to another subject ("Acme offers a 15-day trial;+ * Ledgerly's is longer"): a trial is the brand's only in a part that names+ * it, or says "your trial", "every plan".+ */+const TURN =+ /[;:–—]|,\s*(?:and|but|while|whereas|which|whose|who)\b|\b(?:but|while|whereas|unlike|than|compared\s+(?:to|with))\b/iu;+/**+ * The brand's own founding year, said right after who, who at the start of+ * its clause: "Ledgerly was founded in 2015", "we were…" ("the agency that+ * built Ledgerly was founded" is the agency's). "We" only outside quoted+ * speech, which may be anyone's.+ */+const foundedOf = (brandName: string, we: boolean) => {+ const name = brandName.trim().length > 2 ? escape(brandName.trim()) : null;+ const nameStart = `(?:^|[,;:(–—]\\s*|(?<![\\p{L}\\p{N}])(?:and|since|when|after|as|ve)\\s+)`;+ // "We" only at the sentence's start or after since/when/after/and: after+ // a colon it may be someone quoted without quote marks ("Acme's CEO told+ // us: we were founded in 2018").+ const weStart = `(?:^|(?<![\\p{L}\\p{N}])(?:and|since|when|after|ve)\\s+)`;+ const forms: [string[], string][] = [+ [+ ['we', 'our\\s+company'],+ `\\s+(?:was|were)\\s+(?:founded|established)\\s+(?:in\\s+)?((?:18|19|20)\\d{2})(?!\\d)`,+ ],+ [+ ['biz', 'şirketimiz'],+ `\\s+((?:18|19|20)\\d{2})['’]?(?:de|da|te|ta)?\\s+(?:yılında\\s+)?kurul(?:du|muştur|duk)`,+ ],+ [['wir'], `\\s+(?:wurde|wurden)\\s+(?:im\\s+jahr\\s+)?((?:18|19|20)\\d{2})\\s+gegründet`],+ ];+ return forms.flatMap(([ours, said]) => {+ const who = [+ ...(name ? [`${nameStart}(?:${name})`] : []),+ ...(we ? [`${weStart}(?:${ours.join('|')})`] : []),+ ];+ return who.length ? [new RegExp(`(?:${who.join('|')})${said}`, 'iu')] : [];+ });+};+/** Quoted speech in a sentence. */+const QUOTED = /["“”«»„]/u;++/**+ * The page's prices, trial and founding year against the brand's approved+ * facts still on its site (Trust's "consistent with brand facts", CE-047),+ * read so as never to cry wolf (a wrong warning on a right page is worse+ * than none):+ *+ * * a price is compared with the plan named nearest it in the sentence+ * (the closest pairs first, no other price between, none read unless+ * the sentence has as many prices as plans named), its name as the page+ * writes it, a name that is an everyday word ("Pro", "Team", "Free")+ * only beside "plan" or "tier" or with the brand named; with no plan+ * named, only right after the brand's name and what it costs+ * ("Ledgerly costs $29 a month");+ * * in its currency only; with a period or a billing ("billed+ * annually") only against prices of that period or billing; it+ * matches when it is any of them (a plan's monthly and annual prices+ * both count), "from $19" too; free ($0) is never compared;+ * * a sentence with an old price, a saving, a discount, credits, tax,+ * an add-on, a setup fee or a team's bill ("was $49", "5 users pay")+ * isn't read for prices, nor one naming a competitor;+ * * a trial in days in the part of the sentence that says it is the+ * brand's ("your free trial", "every plan", the brand's name), its days+ * right beside the trial, and none with two trial lengths in the+ * sentence; a founding year right after "the brand was founded" ("we+ * were founded" too, outside quoted speech), who at the start of its+ * clause.+ *+ * Each sentence once. `compared` is how many were compared: the check's+ * points are the share that matched.+ */+export function factMismatches({+ sentences,+ facts,+ brandName,+ competitorDomains,+}: {+ /** The page's sentences (its Trust blocks', sentencesOf). */+ sentences: string[];+ facts: BrandFact[];+ brandName: string;+ competitorDomains: string[];+}): { compared: number; mismatches: FactMismatch[] } {+ const approved = facts.filter((f) => f.status === 'approved' && !f.gone);+ const prices = approved.filter(isPrice).filter((p) => p.value.amount > 0);+ const trials = approved.filter((f) => f.kind === 'trial');+ const years = approved.filter((f) => f.kind === 'founded');+ if (!prices.length && !trials.length && !years.length) return { compared: 0, mismatches: [] };+ const rivals = competitorDomains+ .map(+ (d) =>+ d+ .toLowerCase()+ .replace(/^https?:\/\//, '')+ .replace(/^www\./, '')+ .split('/')[0],+ )+ .flatMap((d) => [d, d.split('.')[0]])+ .filter((d) => d.length >= 3);+ const plans = [...new Set(prices.map((p) => p.value.plan))].filter((p) => p.trim().length > 1);+ const founded = foundedOf(brandName, true);+ const foundedNamed = foundedOf(brandName, false);+ const same = (a: number, b: number) => Math.abs(a - b) < 0.005;+ const shown = (f: BrandFact) => factValueText(f.kind, f.value, f.quote);++ let compared = 0;+ const mismatches: FactMismatch[] = [];+ for (const sentence of new Set(sentences)) {+ const lower = sentence.toLowerCase();+ if (rivals.some((r) => named(lower, r))) continue;+ const brand = named(sentence, brandName);++ if (prices.length && !NOT_A_PRICE.test(sentence)) {+ const places = plans+ .map((plan) => ({ plan, at: planAt(sentence, plan, brand) }))+ .filter((p) => p.at !== -1);+ const billed = BILLED_YEAR.test(sentence)+ ? 'annually'+ : BILLED_MONTH.test(sentence)+ ? 'monthly'+ : null;+ const found = pagePrices(sentence).filter((price) => price.amount > 0);+ // Each named plan with the one price nearest it, the closest pairs+ // first, none other between. As many prices as plans named (one with+ // none named), else which is whose isn't sure ("Pro is $49/month or+ // $39/month billed annually", "…, and Business is $199" with only Pro+ // found, "Pro, unlike the Starter plan, costs $49"): none is read.+ const sure = found.length === Math.max(places.length, 1);+ const planOf = new Map<number, (typeof places)[number]>();+ const pairs = places+ .flatMap((place) => found.map((price) => ({ place, price })))+ .sort((a, b) => Math.abs(a.price.at - a.place.at) - Math.abs(b.price.at - b.place.at));+ const paired = new Set<string>();+ for (const { place, price } of pairs) {+ if (planOf.has(price.at) || paired.has(place.plan)) continue;+ const [from, to] = [Math.min(place.at, price.at), Math.max(place.at, price.at)];+ if (found.some((other) => other !== price && other.at > from && other.at < to)) continue;+ planOf.set(price.at, place);+ paired.add(place.plan);+ }+ const names = namedAt(sentence, brandName);+ // What is said between a name and its price, its currency mark aside.+ const between = (end: number, price: PagePrice) =>+ sentence.slice(end, price.at).replace(/[$€£¥₹₺]\s*$/u, '');+ for (const price of sure ? found : []) {+ const nearest = places.length ? (planOf.get(price.at) ?? null) : null;+ if (places.length && !nearest) continue;+ // A named plan's price: right after its name, as the brand's is.+ if (+ nearest &&+ !(+ nearest.at < price.at &&+ PRICED_AFTER_PLAN.test(between(nearest.at + nearest.plan.length, price))+ )+ ) {+ continue;+ }+ // No plan named: only a price said right after the brand's name.+ if (+ !nearest &&+ !names.some((n) => n.end <= price.at && PRICED_AFTER_NAME.test(between(n.end, price)))+ ) {+ continue;+ }+ if (comparedAfter(sentence, price)) continue;+ let pool = prices.filter(+ (p) => p.value.currency === price.currency && (!nearest || p.value.plan === nearest.plan),+ );+ if (price.period)+ pool = pool.filter((p) => !p.value.period || p.value.period === price.period);+ if (billed) pool = pool.filter((p) => !p.value.billed || p.value.billed === billed);+ if (!pool.length) continue;+ compared += 1;+ if (!pool.some((p) => same(p.value.amount, price.amount))) {+ mismatches.push({+ kind: 'price',+ page: price.text,+ fact: shown(pool[0]),+ source: pool[0].sourceKind,+ sentence,+ });+ }+ }+ }++ if (trials.length && (brand || OWN_TRIAL.test(sentence))) {+ // Two different trial lengths in the sentence (another brand's beside+ // the brand's, "…; Ledgerly's runs for 14 days") say nothing sure.+ const owned = (text: string, trial: boolean): TrialLength[] =>+ [...text.matchAll(OWNED_LENGTH)]+ .filter((m) => !trial || /trial/iu.test(m[0]))+ .map((m) => ({ days: Number(m[1]) * (/^week/i.test(m[2]) ? 7 : 1), at: m.index }));+ // "Free for N days" is a trial in a sentence that says so, or after "try Ledgerly".+ const tryBrand =+ brandName.trim().length > 2+ ? new RegExp(`(?:try|use)\\s+${escape(brandName.trim())}\\s+$`, 'iu')+ : null;+ const tried = (before: string) => SAYS_TRIAL.test(sentence) || !!tryBrand?.test(before);+ const lengths = new Set(+ [...trialLengths(sentence, tried), ...owned(sentence, false)].map((l) => l.days),+ );+ // In a part that is the brand's, only a length after its name or "your+ // trial", "every plan" ("Unlike Acme's 30-day trial, Ledgerly's needs no+ // card" is Acme's).+ const own = new Set(+ sentence.split(TURN).flatMap((part) => {+ const anchors = [+ ...namedAt(part, brandName).map((n) => n.at),+ ...[...part.matchAll(new RegExp(OWN_TRIAL.source, 'giu'))].map((m) => m.index),+ ];+ if (!anchors.length) return [];+ const from = Math.min(...anchors);+ return [...trialLengths(part, tried), ...owned(part, true)]+ .filter((l) => l.at >= from)+ .map((l) => l.days);+ }),+ );+ const days = lengths.size === 1 && own.size === 1 ? [...own][0] : null;+ if (days) {+ compared += 1;+ const fact = trials.find((f) => (f.value as { days: number }).days === days);+ if (!fact) {+ mismatches.push({+ kind: 'trial',+ page: `${days}-day`,+ fact: `${(trials[0].value as { days: number }).days}-day`,+ source: trials[0].sourceKind,+ sentence,+ });+ }+ }+ }++ if (years.length) {+ // Only the brand's (or "we", "our company") right before "was founded".+ const m = (QUOTED.test(sentence) ? foundedNamed : founded)+ .map((re) => sentence.match(re))+ .find(Boolean);+ const year = m ? m[1] : null;+ if (year) {+ compared += 1;+ if (!years.some((f) => (f.value as { year: number }).year === Number(year))) {+ mismatches.push({+ kind: 'founded',+ page: year,+ fact: shown(years[0]),+ source: years[0].sourceKind,+ sentence,+ });+ }+ }+ }+ }+ return { compared, mismatches };+}diff --git a/web/src/lib/content/next-step.test.ts b/web/src/lib/content/next-step.test.tsindex da86137b5..48e0ccb1f 100644--- a/web/src/lib/content/next-step.test.ts+++ b/web/src/lib/content/next-step.test.ts@@ -188,6 +188,23 @@ describe('nextStep', () => {).toBe('length');});+ it("keeps a proof skip when the brand facts' to-do joins later (review, #1465)", () => {+ const s = state({ quality: { trust: 54, trustLow: true, todos: [todo({})] } });+ const skipped = { ...s, skipped: { proof: stepState('proof', s) } };+ const withFacts = {+ ...skipped,+ quality: {+ trust: 54,+ trustLow: true,+ todos: [+ todo({}),+ todo({ id: 'brandFacts', action: 'reviewBrandFacts', score: 'trust', gain: 0, count: 2 }),+ ],+ },+ };+ expect(liveSkips(withFacts)).toEqual({ proof: stepState('proof', s) });+ });+it('drops a skip once its state changed, so it never comes back to life', () => {const s = state({ openRules: ['faq', 'summary'] });const skipped = { ...s, skipped: { fixRules: stepState('fixRules', s) } };diff --git a/web/src/lib/content/next-step.ts b/web/src/lib/content/next-step.tsindex 56e84659d..733b9af9d 100644--- a/web/src/lib/content/next-step.ts+++ b/web/src/lib/content/next-step.ts@@ -132,7 +132,10 @@ export function stepState(id: NextStepId, s: NextStepState): string {case 'fixRules':return s.openRules.join(',');case 'proof':+ // Not the brand facts' to-do: it joins when the brand's site is read,+ // a skip made before then holds.return `${s.quality?.trustLow ?? false}:${openTodos(s)+ .filter((todo) => todo.id !== 'brandFacts').map((todo) => todo.id).join(',')}`;default:diff --git a/web/src/lib/content/quality-checks.test.ts b/web/src/lib/content/quality-checks.test.tsindex f539f6c08..cc9b176c1 100644--- a/web/src/lib/content/quality-checks.test.ts+++ b/web/src/lib/content/quality-checks.test.ts@@ -555,3 +555,36 @@ describe('trust: the claims the model read (Phase 2, CE-045)', () => {]);});});++describe('trust: consistent with brand facts (Phase 2, CE-047)', () => {+ const NOW = Date.parse('2026-10-24T12:00:00Z');+ const mismatch = {+ kind: 'price' as const,+ page: '$59',+ fact: '$49',+ source: 'pricing' as const,+ sentence: 'Pro costs $59 per month.',+ };+ const read = (+ brandFacts: Parameters<typeof trust>[0]['brandFacts'],+ html = '<p>Pro costs $59 per month.</p>',+ ) =>+ trust({ blocks: trustBlocks(html), links: new Map(), brandDomains: [], brandFacts, now: NOW });++ it('gives the share of the compared facts that match, and names the ones that don’t', () => {+ const result = read({ compared: 2, mismatches: [mismatch] });+ expect(result.checks.find((c) => c.id === 'brandFacts')).toEqual({+ id: 'brandFacts',+ points: 5,+ max: 10,+ });+ expect(result.mismatches).toEqual([mismatch]);+ });++ it('leaves the check out with nothing compared, and scores no Trust from it alone', () => {+ expect(read({ compared: 0, mismatches: [] }).checks.map((c) => c.id)).toEqual([]);+ const alone = read({ compared: 1, mismatches: [] }, '<p>A page with no figure.</p>');+ expect(alone.score).toBeNull();+ expect(read(null).mismatches).toEqual([]);+ });+});diff --git a/web/src/lib/content/quality-checks.ts b/web/src/lib/content/quality-checks.tsindex 50eb12b4f..148a18cde 100644--- a/web/src/lib/content/quality-checks.ts+++ b/web/src/lib/content/quality-checks.ts@@ -2,6 +2,7 @@ import { classifyDomain, normalizeDomain } from '@/lib/citations/classify';import type { ContentAuthor } from './authors';import { cleanHref } from './html-allowlist';import { ownText, sentencesOf } from './readability';+import type { FactMismatch } from './brand-facts';import type { ClaimBlock } from './claims';import { askableSite, sourceClass, type AiSourceClass, type SourceClass } from './source-class';@@ -300,6 +301,8 @@ export interface TrustRead extends Score<TrustCheckId> {*/weak: { url: string; text: string; kind: 'weak' | 'competitor'; ai: boolean }[];classified: number;+ /** Phase 2 (CE-047): the page's facts that differ from the brand's approved ones. */+ mismatches: FactMismatch[];}/**@@ -342,6 +345,10 @@ export interface SourceRead {** With `claims` (Phase 2, CE-045), the claims the model read count as the* figures do, each sentence once: Trust is scored from them alone too.+ *+ * 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.*/export function trust({blocks,@@ -351,6 +358,7 @@ export function trust({quote = null,sources: kinds = null,claims = null,+ brandFacts = null,now,}: {/** The page's blocks (trustBlocks). */@@ -369,6 +377,8 @@ export function trust({sources?: SourceRead | null;/** Phase 2: the claims the model read in the page's own words (CE-045); left out before. */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;now: number;}): TrustRead {const all = pageLinks(blocks, brandDomains);@@ -497,6 +507,16 @@ export function trust({});}+ if (brandFacts && brandFacts.compared > 0) {+ checks.push({+ id: 'brandFacts',+ points:+ (TRUST_WEIGHTS.brandFacts * (brandFacts.compared - brandFacts.mismatches.length)) /+ brandFacts.compared,+ max: TRUST_WEIGHTS.brandFacts,+ });+ }+if (quote !== null) {checks.push({id: 'expertQuote',@@ -529,6 +549,7 @@ export function trust({aiClaims,weak,classified: classified.length,+ mismatches: brandFacts?.mismatches ?? [],};}diff --git a/web/src/lib/content/quality-todos.test.ts b/web/src/lib/content/quality-todos.test.tsindex 7bc2cbee7..ba4b2a183 100644--- a/web/src/lib/content/quality-todos.test.ts+++ b/web/src/lib/content/quality-todos.test.ts@@ -186,6 +186,29 @@ describe('qualityTodos', () => {expect(todos(author()).map((t) => t.id)).toEqual(['byline', 'authorProfile']);});+ it('asks to approve the brand facts read from its site, and keeps it checked once done (CE-047)', () => {+ const facts = (pending: number, had: boolean) =>+ qualityTodos({+ eeat: null,+ author: null,+ hasAuthors: true,+ brandFacts: { pending, had },+ });+ expect(facts(3, true)).toEqual([+ {+ id: 'brandFacts',+ done: false,+ gain: 0,+ score: 'trust',+ action: 'reviewBrandFacts',+ count: 3,+ },+ ]);+ expect(facts(0, true)).toEqual([expect.objectContaining({ id: 'brandFacts', done: true })]);+ expect(facts(0, false)).toEqual([]);+ expect(qualityTodos({ eeat: null, author: null, hasAuthors: true })).toEqual([]);+ });+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.tsindex 8e23df762..ea33c6789 100644--- a/web/src/lib/content/quality-todos.ts+++ b/web/src/lib/content/quality-todos.ts@@ -14,7 +14,8 @@ import {* 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. Phase 2 adds what only the person can give (Brief › Your- * input, CE-048): their experience, their data and an expert's quote.+ * input, CE-048): their experience, their data and an expert's quote; and+ * the brand's facts read from its site, to approve (CE-047).*/export type QualityTodoId =@@ -23,18 +24,21 @@ export type QualityTodoId =| 'authorProfile'| 'experience'| 'originalData'- | 'expertQuote';+ | 'expertQuote'+ | 'brandFacts';/*** A to-do's one button: Show (the first placeholder, selected to type over),- * the header's author menu, or Settings › Authors.+ * the header's author menu, Settings › Authors, Brief › Your input, or+ * Brand settings › Brand facts.*/export type QualityTodoAction =| 'showPlaceholder'| 'pickAuthor'| 'addAuthor'| 'editAuthor'- | 'addInput';+ | 'addInput'+ | 'reviewBrandFacts';export interface QualityTodo {id: QualityTodoId;@@ -47,7 +51,7 @@ export interface QualityTodo {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). */+ /** How many it is about (placeholders, brand facts to approve). */count?: number;/*** With no author picked: the person's own word for the author their site@@ -61,8 +65,9 @@ export interface QualityTodo {* export never ships one), pick its author (or add one when the workspace* has none), then complete their profile, listed from the start so the* count holds. Done ones stay on the list, checked; placeholders are listed- * once the page has had some (`had`, this session). The author's wait for- * E-E-A-T to be read.+ * 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.*/export function qualityTodos({eeat,@@ -73,6 +78,7 @@ export function qualityTodos({used = null,given = null,trust = null,+ brandFacts = null,confirmed = null,}: {eeat: Score<EeatCheckId> | null;@@ -91,6 +97,11 @@ export function qualityTodos({given?: { experience: boolean; data: boolean; quote: boolean } | null;/** Trust, for an expert quote's gain. */trust?: Score<TrustCheckId> | 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;/** What the person confirmed of the author their site names (00271), or null where they can't. */confirmed?: { real: boolean; profile: boolean } | null;}): QualityTodo[] {@@ -107,7 +118,21 @@ export function qualityTodos({},]: [];- if (!eeat || eeat.score === null) return fill;+ // The brand's, not the page's, and worth no points itself: last.+ const facts: QualityTodo[] =+ brandFacts && (brandFacts.pending || brandFacts.had)+ ? [+ {+ id: 'brandFacts',+ done: brandFacts.pending === 0,+ gain: 0,+ score: 'trust',+ action: 'reviewBrandFacts',+ count: brandFacts.pending,+ },+ ]+ : [];+ if (!eeat || eeat.score === null) return [...fill, ...facts];// No author picked: the one the site names may be confirmed instead, the// profile once the author is.const byConfirm = !author && !!confirmed;@@ -162,5 +187,6 @@ export function qualityTodos({},] satisfies QualityTodo[]): []),+ ...facts,];}