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): score Trust from the page's sourced figures, fresh sources and working links (CE-039) (#1416)
Cihan8bbf0daee3cc
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 077e33aef..900951d3b 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -4136,6 +4136,18 @@"fernandezHuerta": "Fernández-Huerta"},"checks": {+ "claimsSourced": {+ "line": "{count, plural, one {# sentence with a figure has} other {# sentences with figures have}} no source",+ "detail": "Link each figure's source in the same paragraph, or take the figure out. Content Agent won't make one up."+ },+ "freshSources": {+ "line": "{count} of {total} dated {total, plural, one {source} other {sources}} {count, plural, one {is} other {are}} over {months} months old",+ "detail": "Swap them for a newer source, or check whether the page has an update."+ },+ "noBrokenLinks": {+ "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}}}"+ },"byline": {"line": "The page is by {byline}, not a person","detail": "Pick the person who wrote it: a named author with a short bio and profile links shows who stands behind the page."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 916401332..e04b8424b 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_draft-editor.tsx@@ -74,7 +74,7 @@ import { PAGE_READ_DELAY_MS, draftTitleFromDoc, safeLinkHref } from '@/lib/conteimport { JsonLd } from '@/lib/content/json-ld-node';import { detectPageType } from '@/lib/content/page-types';import { BAND_CLASSES, qualityAverage, qualityBand, qualityPhase } from '@/lib/content/quality';-import { eeat } from '@/lib/content/quality-checks';+import { eeat, linksToCheck, trust, trustBlocks } from '@/lib/content/quality-checks';import { readability } from '@/lib/content/readability';import { aiTracesFound, fanoutsToUse, lengthWarns, openRulesForAgent } from '@/lib/content/rules';import { saveBlob } from '@/lib/download';@@ -85,6 +85,7 @@ import { AgentDrafting, draftingKey } from './_agent-drafting';import { AuthorMenu } from './_author-menu';import { FlashBlock, findBlock, flashKey } from './_flash-block';import { useAgentRun } from './_use-agent-run';+import { useLinkChecks } from './_use-link-checks';import { WorkingDots } from './_working-dots';import { DropOverlay, useAttachments } from './_attach';import {@@ -442,18 +443,39 @@ export function DraftEditor({const brandName =authorsRead?.brands.find((b) => b.id === draft.brandId)?.name ?? storeBrandName ?? '';const pageAuthor = authorsRead?.authors.find((a) => a.id === authorId) ?? null;- // E-E-A-T from the author (CE-039): with Readability, the scores and the- // header chip's average. Trust waits for a check that can read the page.+ // E-E-A-T from the author, Trust from the page's figures and links (their+ // reads from the API): with Readability, the scores and the header chip's+ // average (CE-039).const eeatScore = useMemo(() => (qualityOn && authorsRead ? eeat({ author: pageAuthor }) : null),[qualityOn, authorsRead, pageAuthor],);- const qualityScore = qualityAverage([eeatScore?.score ?? null, readable?.score ?? null]);+ const pageBlocks = useMemo(() => (qualityOn ? trustBlocks(pageHtml) : []), [qualityOn, pageHtml]);+ const linkChecks = useLinkChecks(draft.id, autosave.savedAt, linksToCheck(pageBlocks), qualityOn);+ const brandDomains = reads.sources?.data?.brandDomains;+ // The brand's own links aren't sources: Trust waits for its domains.+ const trustScore = useMemo(+ () =>+ qualityOn && brandDomains+ ? trust({+ blocks: pageBlocks,+ links: linkChecks,+ brandDomains,+ now: Date.now(),+ })+ : null,+ [qualityOn, pageBlocks, linkChecks, brandDomains],+ );+ const qualityScore = qualityAverage([+ eeatScore?.score ?? null,+ trustScore?.score ?? null,+ readable?.score ?? null,+ ]);const quality: QualityRead | null = qualityOn? {readability: readable,eeat: eeatScore,- trust: null,+ trust: trustScore,author: pageAuthor,canEdit: !!pageAuthor && !!authorsRead && canEditAuthor(pageAuthor, authorsRead.me),hasAuthors: (authorsRead?.authors.length ?? 0) > 0,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 46ef68aaa..87d48a0a4 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@@ -3,7 +3,7 @@ import { createRoot, type Root } from 'react-dom/client';import { NextIntlClientProvider } from 'next-intl';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import messages from '../../../../../../../../messages/en.json';-import { eeat } from '@/lib/content/quality-checks';+import { eeat, trust, trustBlocks, type LinkCheck } from '@/lib/content/quality-checks';import type { ContentAuthor } from '@/lib/content/authors';import type { Readability } from '@/lib/content/readability';@@ -204,6 +204,91 @@ describe('QualityTab', () => {expect(container.textContent).not.toContain('Nothing to raise');});+ it('asks to source figures, swap stale sources and fix links, each with Show', async () => {+ const html =+ '<p>Win rates rose 42% last year.</p>' ++ '<p>See <a href="https://old.example/">this study</a> and <a href="https://gone.example/">that one</a>.</p>';+ const links = new Map<string, LinkCheck>([+ [+ 'https://old.example/',+ {+ href: 'https://old.example/',+ status: 'ok',+ httpStatus: 200,+ date: '2020-01-01T00:00:00.000Z',+ },+ ],+ [+ 'https://gone.example/',+ { href: 'https://gone.example/', status: 'broken', httpStatus: 404, date: null },+ ],+ ]);+ const result = trust({+ blocks: trustBlocks(html),+ links,+ brandDomains: ['acme.com'],+ now: Date.parse('2026-10-23T12:00:00Z'),+ });+ await render({ ...read(null), trust: result });+ const scores = container.querySelector('[aria-label="Quality scores"]')!;+ // Figures 0 of 30, fresh 0 of 7, links 1.5 of 3: 4 of 100.+ expect(scores.textContent).toContain('Trust4Needs work');+ const rows = [...container.querySelectorAll('li')].map((li) => li.textContent);+ expect(rows).toContainEqual(expect.stringContaining('1 sentence with a figure has no source'));+ expect(rows).toContainEqual(+ expect.stringContaining('1 of 1 dated source is over 24 months old'),+ );+ expect(rows).toContainEqual(+ expect.stringContaining("1 link doesn't workFix or remove it: https://gone.example/Show"),+ );+ const figure = [...container.querySelectorAll('li')].find((li) =>+ li.textContent?.includes('figure'),+ )!;+ await act(async () => figure.querySelector('button')!.click());+ expect(onShow).toHaveBeenCalledWith('Win rates rose 42% last year.');+ });++ it('lists a broken link before Trust is scored, its gain out of the Phase 1 points', async () => {+ const result = trust({+ blocks: trustBlocks('<p>See <a href="https://gone.example/">that one</a>.</p>'),+ links: new Map<string, LinkCheck>([+ [+ 'https://gone.example/',+ { href: 'https://gone.example/', status: 'broken', httpStatus: 404, date: null },+ ],+ ]),+ brandDomains: ['acme.com'],+ now: Date.parse('2026-10-23T12:00:00Z'),+ });+ await render({ ...read(null), trust: result });+ const scores = container.querySelector('[aria-label="Quality scores"]')!;+ expect(scores.textContent).toContain('TrustNot scored yet');+ const rows = [...container.querySelectorAll('li')].map((li) => li.textContent);+ // 3 of the 40 Phase 1 points.+ expect(rows).toContainEqual(expect.stringContaining("+8 Trust1 link doesn't work"));+ });++ it('counts the dated sources and the stale ones each in its own number', async () => {+ const dated = (date: string) => ({ status: 'ok' as const, httpStatus: 200, date });+ const result = trust({+ blocks: trustBlocks(+ '<p>See <a href="https://a.example/">a</a>, <a href="https://b.example/">b</a> and <a href="https://c.example/">c</a>.</p>',+ ),+ links: new Map<string, LinkCheck>([+ ['https://a.example/', { href: 'https://a.example/', ...dated('2020-01-01T00:00:00Z') }],+ ['https://b.example/', { href: 'https://b.example/', ...dated('2021-01-01T00:00:00Z') }],+ ['https://c.example/', { href: 'https://c.example/', ...dated('2026-01-01T00:00:00Z') }],+ ]),+ brandDomains: ['acme.com'],+ now: Date.parse('2026-10-23T12:00:00Z'),+ });+ await render({ ...read(null), trust: result });+ const rows = [...container.querySelectorAll('li')].map((li) => li.textContent);+ expect(rows).toContainEqual(+ expect.stringContaining('2 of 3 dated sources are over 24 months old'),+ );+ });+it('says when the page’s language isn’t read yet, not that it is too short', async () => {await render({ score: null, unscored: 'language', checks: [], words: 240 });expect(container.textContent).toContain("Readability isn't read for this language yet.");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 a0c6a2f2f..cfdf7d142 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@@ -7,9 +7,12 @@ import type { ContentAuthor } from '@/lib/content/authors';import { BAND_CLASSES, qualityBand } from '@/lib/content/quality';import {authorProfile,+ FRESH_MONTHS,scoreGain,+ trustGain,type EeatCheckId,type Score,+ type TrustRead,} from '@/lib/content/quality-checks';import {readabilityGain,@@ -26,8 +29,8 @@ export interface QualityRead {readability: Readability | null;/** E-E-A-T from the author, or null before the authors are read. */eeat: Score<EeatCheckId> | null;- /** Trust, or null while none of its checks is live for the page. */- trust: Score | null;+ /** Trust from the page's figures and links, its score null until a figure or a dated source is read. */+ trust: TrustRead | null;/** The page's author, or null for the organization byline. */author: ContentAuthor | null;/** Whether the member reading may edit that author in Settings › Authors. */@@ -80,6 +83,7 @@ export function QualityTab({const suggestions = [...readabilitySuggestions(t, readability),...eeatSuggestions(t, quality, tAuthor('organization', { brand: quality.brandName })),+ ...trustSuggestions(t, trust),].filter((s) => s.gain > 0).sort((a, b) => b.gain - a.gain);@@ -133,7 +137,9 @@ export function QualityTab({</span><div className="min-w-0 flex-1"><p className="font-medium [overflow-wrap:anywhere]">{s.line}</p>- <p className="text-xs text-muted-foreground">{s.detail}</p>+ <p className="text-xs text-muted-foreground [overflow-wrap:anywhere]">+ {s.detail}+ </p></div><SuggestionAction action={s.action} onShow={onShow} onPickAuthor={onPickAuthor} /></li>@@ -245,6 +251,54 @@ function eeatSuggestions(t: T, quality: QualityRead, teamByline: string): Sugges];}+/**+ * Trust's: figures without a source, sources past FRESH_MONTHS, links that+ * 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.+ */+function trustSuggestions(t: T, trust: TrustRead | null): Suggestion[] {+ if (!trust) return [];+ const out: Suggestion[] = [];+ if (trust.unsourced.length) {+ out.push({+ key: 'trust:claimsSourced',+ score: 'trust',+ gain: trustGain(trust, ['claimsSourced']),+ line: t('checks.claimsSourced.line', { count: trust.unsourced.length }),+ detail: t('checks.claimsSourced.detail'),+ action: { kind: 'show', text: trust.unsourced[0] },+ });+ }+ if (trust.stale.length) {+ out.push({+ key: 'trust:freshSources',+ score: 'trust',+ gain: trustGain(trust, ['freshSources']),+ line: t('checks.freshSources.line', {+ count: trust.stale.length,+ total: trust.dated,+ months: FRESH_MONTHS,+ }),+ detail: t('checks.freshSources.detail'),+ action: { kind: 'show', text: trust.stale[0].text },+ });+ }+ if (trust.broken.length) {+ out.push({+ key: 'trust:noBrokenLinks',+ score: 'trust',+ gain: trustGain(trust, ['noBrokenLinks']),+ line: t('checks.noBrokenLinks.line', { count: trust.broken.length }),+ detail: t('checks.noBrokenLinks.detail', {+ count: trust.broken.length,+ url: trust.broken[0].url,+ }),+ action: { kind: 'show', text: trust.broken[0].text },+ });+ }+ return out;+}+/** A Readability check's one line: what the draft does now. */function line(t: T, check: ReadabilityCheck): string {switch (check.id) {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-link-checks.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-link-checks.test.tsxnew file mode 100644index 000000000..b61cd26f1--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-link-checks.test.tsx@@ -0,0 +1,122 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { LinkCheck } from '@/lib/content/quality-checks';++const checkDraftLinks = vi.fn();+vi.mock('@/lib/actions/content-drafts', () => ({+ checkDraftLinks: (...args: unknown[]) => checkDraftLinks(...args),+}));++const { LINK_CHECK_DELAY_MS, useLinkChecks } = await import('./_use-link-checks');++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++/**+ * Trust's link reads (Quality spec §2.2): the saved draft's links, asked+ * about after the links or the save change; a link without a read is asked+ * about again only after the next save.+ */++let container: HTMLDivElement;+let root: Root;+/** The links the API reads from the saved draft. */+let saved: string[];+/** The links the API never reads. */+let skipped: string[];++function Probe({+ hrefs,+ savedAt,+ enabled,+}: {+ hrefs: string[];+ savedAt: string;+ enabled: boolean;+}) {+ const checks = useLinkChecks('d1', savedAt, hrefs, enabled);+ return <pre data-checks={JSON.stringify([...checks])} />;+}++/** The reads the hook holds, by link. */+const seen = () =>+ new Map<string, LinkCheck>(+ JSON.parse(container.querySelector('pre')?.getAttribute('data-checks') ?? '[]'),+ );++const render = (hrefs: string[], savedAt = 's1', enabled = true) =>+ act(async () => root.render(<Probe hrefs={hrefs} savedAt={savedAt} enabled={enabled} />));+const wait = (ms = LINK_CHECK_DELAY_MS) => act(async () => vi.advanceTimersByTimeAsync(ms));+const ok = (href: string): LinkCheck => ({ href, status: 'ok', httpStatus: 200, date: null });++beforeEach(() => {+ vi.useFakeTimers();+ saved = [];+ skipped = [];+ checkDraftLinks.mockReset().mockImplementation(async () => ({ links: saved.map(ok), skipped }));+ container = document.createElement('div');+ root = createRoot(container);+});+afterEach(() => {+ act(() => root.unmount());+ vi.useRealTimers();+});++describe('useLinkChecks', () => {+ it('asks about the saved draft once the links settle, and keeps the reads', async () => {+ saved = ['https://a.example/', 'https://b.example/'];+ await render(['https://a.example/']);+ await wait(LINK_CHECK_DELAY_MS - 100);+ await render(['https://a.example/', 'https://b.example/']);+ await wait();+ expect(checkDraftLinks).toHaveBeenCalledTimes(1);+ expect(checkDraftLinks).toHaveBeenCalledWith('d1');+ expect([...seen().keys()]).toEqual(['https://a.example/', 'https://b.example/']);++ // Nothing new to read: no ask.+ await render(['https://a.example/', 'https://b.example/'], 's2');+ await wait();+ expect(checkDraftLinks).toHaveBeenCalledTimes(1);+ });++ it('asks about a link not saved yet again after the next save', async () => {+ saved = ['https://a.example/'];+ await render(['https://a.example/', 'https://new.example/']);+ await wait();+ expect(seen().has('https://new.example/')).toBe(false);++ // Same save: not asked again.+ await render(['https://a.example/', 'https://new.example/', 'https://a.example/']);+ await wait();+ expect(checkDraftLinks).toHaveBeenCalledTimes(1);++ saved = ['https://a.example/', 'https://new.example/'];+ await render(['https://a.example/', 'https://new.example/'], 's2');+ await wait();+ expect(checkDraftLinks).toHaveBeenCalledTimes(2);+ expect(seen().get('https://new.example/')?.status).toBe('ok');+ });++ it("doesn't ask again in the same save after a failed ask, nor with Quality off", async () => {+ checkDraftLinks.mockResolvedValue({ error: 'failed' });+ vi.spyOn(console, 'error').mockImplementation(() => {});+ await render(['https://a.example/']);+ await wait(LINK_CHECK_DELAY_MS * 3);+ expect(checkDraftLinks).toHaveBeenCalledTimes(1);+ expect(seen().size).toBe(0);++ await render(['https://d.example/'], 's1', false);+ await wait();+ expect(checkDraftLinks).toHaveBeenCalledTimes(1);+ });++ it("doesn't ask again about a link the API never reads", async () => {+ skipped = ['https://a.example/unsubscribe'];+ await render(['https://a.example/unsubscribe']);+ await wait();+ await render(['https://a.example/unsubscribe'], 's2');+ await wait();+ expect(checkDraftLinks).toHaveBeenCalledTimes(1);+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-link-checks.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-link-checks.tsnew file mode 100644index 000000000..969d796c5--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-link-checks.ts@@ -0,0 +1,72 @@+'use client';++import { useEffect, useRef, useState } from 'react';+import { checkDraftLinks } from '@/lib/actions/content-drafts';+import type { LinkCheck } from '@/lib/content/quality-checks';++/** How long after a save the links are asked about. */+export const LINK_CHECK_DELAY_MS = 3_000;++/**+ * The page's links as the API reads them (Trust, Quality spec §2.2). The API+ * reads the draft as saved, so the editor asks a few seconds after the links+ * or the save change, for links it has no read of, and keeps each read; the+ * API keeps each a day. A link without a read (not saved yet, an account+ * link the API leaves out, one over its budget, a failed ask) is asked about+ * again only after the next save: until then the checks it would feed leave+ * it out. One the API never reads (an account link) isn't asked about again.+ * The links are compared as the draft saves them (cleanHref).+ *+ * @param hrefs the page's http(s) links now, as it has them+ * @param savedAt when the page was last saved+ */+export function useLinkChecks(+ draftId: string,+ savedAt: string,+ hrefs: string[],+ enabled: boolean,+): Map<string, LinkCheck> {+ const [checks, setChecks] = useState<Map<string, LinkCheck>>(() => new Map());+ // The links read, and the save each other link was last asked about at.+ const read = useRef(new Set<string>());+ const askedAt = useRef(new Map<string, string>());+ // A read that lands after the page changed still counts; only a closed editor drops it.+ const open = useRef(true);+ useEffect(() => {+ open.current = true;+ return () => {+ open.current = false;+ };+ }, []);+ const key = hrefs.join('\n');++ useEffect(() => {+ if (!enabled) return;+ const fresh = key+ .split('\n')+ .filter((href) => href && !read.current.has(href) && askedAt.current.get(href) !== savedAt);+ if (!fresh.length) return;+ const timer = setTimeout(() => {+ for (const href of fresh) askedAt.current.set(href, savedAt);+ void checkDraftLinks(draftId).then((result) => {+ if ('error' in result) {+ console.error('Failed to check the draft links:', result.error);+ return;+ }+ if (!open.current) return;+ // A link the API never reads is as good as read: it isn't asked about again.+ for (const href of [...result.links.map((l) => l.href), ...result.skipped]) {+ read.current.add(href);+ }+ setChecks((prev) => {+ const next = new Map(prev);+ for (const link of result.links) next.set(link.href, link);+ return next;+ });+ });+ }, LINK_CHECK_DELAY_MS);+ return () => clearTimeout(timer);+ }, [draftId, savedAt, key, enabled]);++ return checks;+}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 c33480d10..b52c1a795 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@@ -16,6 +16,7 @@ const markContentDraftReady = vi.fn();const saveContentDraft = vi.fn();const setContentDraftPageType = vi.fn();const setContentDraftAuthor = vi.fn();+const checkDraftLinks = vi.fn();const getContentAuthors = vi.fn();vi.mock('@/lib/actions/content-authors', () => ({getContentAuthors: (...args: unknown[]) => getContentAuthors(...args),@@ -68,6 +69,7 @@ vi.mock('@/lib/actions/content-drafts', () => ({saveContentDraft: (...args: unknown[]) => saveContentDraft(...args),setContentDraftPageType: (...args: unknown[]) => setContentDraftPageType(...args),setContentDraftAuthor: (...args: unknown[]) => setContentDraftAuthor(...args),+ checkDraftLinks: (...args: unknown[]) => checkDraftLinks(...args),}));vi.mock('next/navigation', () => ({ useParams: () => ({ draftId: 'd1' }) }));vi.mock('@/i18n/navigation', () => ({@@ -230,6 +232,7 @@ beforeEach(() => {saveBlob.mockReset();setContentDraftPageType.mockReset().mockResolvedValue(undefined);setContentDraftAuthor.mockReset().mockResolvedValue(undefined);+ checkDraftLinks.mockReset().mockResolvedValue({ links: [] });getContentAuthors.mockReset().mockResolvedValue(null);saveContentDraft.mockReset()diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex 51f180bcd..4f7022053 100644--- a/web/src/lib/actions/content-drafts.ts+++ b/web/src/lib/actions/content-drafts.ts@@ -37,6 +37,7 @@ import {import { detectPageType, siteTypeOf, type SiteType } from '@/lib/content/page-types';import { sanitizeDraftHtml } from '@/lib/content/sanitize-draft-html';import { matchPagePrompts } from '@/lib/content/page-prompts';+import type { LinkCheck } from '@/lib/content/quality-checks';import {NO_DRAFT_RULES,draftRulesFit,@@ -620,6 +621,40 @@ export async function importContentPage(}}+/**+ * The saved draft's links, read by the API for Trust (Quality spec §2.2):+ * whether each answers and how old its page is, each read at most once a+ * day; `skipped` are the links it never reads (one-time or account links).+ * The API reads the links from the draft as saved, never from here. The+ * reason comes back, not a throw: production hides a server action's errors.+ */+export async function checkDraftLinks(+ id: string,+): Promise<{ links: LinkCheck[]; skipped: string[] } | { error: 'invalid' | 'failed' }> {+ 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/links`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${session.access_token}`,+ },+ body: JSON.stringify({ draftId: id }),+ });+ if (!res.ok) return { error: 'failed' };+ const body = (await res.json()) as { links?: LinkCheck[]; skipped?: string[] };+ return { links: body.links ?? [], skipped: body.skipped ?? [] };+ } catch (err) {+ console.error('Failed to check the draft links:', err);+ return { error: 'failed' };+ }+}+/*** "Team" in Start (CE-015): the draft sent to the Action Center as an action* for someone on the team to write (the API's from-content-draft.js), or thediff --git a/web/src/lib/content/quality-checks.test.ts b/web/src/lib/content/quality-checks.test.tsindex f3189b70f..ceafeb282 100644--- a/web/src/lib/content/quality-checks.test.ts+++ b/web/src/lib/content/quality-checks.test.ts@@ -1,6 +1,19 @@import { describe, expect, it } from 'vitest';import type { ContentAuthor } from './authors';-import { EEAT_WEIGHTS, authorProfile, eeat, scoreGain } from './quality-checks';+import {+ EEAT_WEIGHTS,+ MAX_LINK_CHECKS,+ TRUST_PHASE1_POINTS,+ TRUST_WEIGHTS,+ authorProfile,+ eeat,+ linksToCheck,+ scoreGain,+ trust,+ trustBlocks,+ trustGain,+ type LinkCheck,+} from './quality-checks';const author = (over: Partial<ContentAuthor> = {}): ContentAuthor => ({id: 'a1',@@ -42,3 +55,148 @@ describe('eeat (Phase 1: the author)', () => {expect(authorProfile(author({ bio: ' ' }))).toEqual({ bio: false, links: true });});});++describe('trust (Phase 1: figures and links)', () => {+ const NOW = Date.parse('2026-10-23T12:00:00Z');+ const blocks = (html: string) => trustBlocks(html);+ const read = (rows: Partial<LinkCheck>[]) =>+ new Map(+ rows.map((r) => [r.href!, { status: 'ok', httpStatus: 200, date: null, ...r } as LinkCheck]),+ );+ const run = (html: string, links = new Map<string, LinkCheck>()) =>+ trust({ blocks: blocks(html), links, brandDomains: ['acme.com'], now: NOW });++ it("isn't scored while the page has no figure, dated source or link read", () => {+ const result = run('<h1>Pipeline</h1><p>Teams forecast 5 steps ahead in 2026.</p>');+ expect(result.score).toBeNull();+ expect(result.figures).toBe(0);+ });++ it('counts a figure as sourced when its paragraph links another site', () => {+ const result = run(+ '<p>Win rates rose 42% last year (<a href="https://research.example/report">report</a>).</p>' ++ '<p>Deals close $2.5 million faster.</p>' ++ '<p>Our own page says 3x <a href="https://www.acme.com/pricing">pricing</a>.</p>' ++ '<ul><li>%40 daha hızlı</li></ul>',+ );+ // Our own site is no source: three of four figures have none.+ expect(result.figures).toBe(4);+ expect(result.unsourced).toEqual([+ 'Deals close $2.5 million faster.',+ 'Our own page says 3x pricing.',+ '%40 daha hızlı',+ ]);+ expect(result.checks).toEqual([+ { id: 'claimsSourced', points: TRUST_WEIGHTS.claimsSourced / 4, max: 30 },+ ]);+ expect(result.score).toBe(25);+ });++ it('reads sources older than 24 months as stale, and leaves undated ones out', () => {+ const result = run(+ '<p>See <a href="https://old.example/a">old</a>, <a href="https://new.example/b">new</a> and <a href="https://undated.example/">undated</a>.</p>',+ read([+ { href: 'https://old.example/a', date: '2024-09-01T00:00:00.000Z' },+ { href: 'https://new.example/b', date: '2025-01-01T00:00:00.000Z' },+ { href: 'https://undated.example/' },+ ]),+ );+ expect(result.dated).toBe(2);+ expect(result.stale.map((l) => l.url)).toEqual(['https://old.example/a']);+ expect(result.checks.find((c) => c.id === 'freshSources')).toEqual({+ id: 'freshSources',+ points: 3.5,+ max: 7,+ });+ });++ it("counts the links that answer, and leaves out the ones that wouldn't tell", () => {+ const result = run(+ '<p><a href="https://gone.example/">gone</a> <a href="https://www.acme.com/x">ours</a> <a href="https://walled.example/">walled</a></p>',+ read([+ { href: 'https://gone.example/', status: 'broken', httpStatus: 404 },+ { href: 'https://www.acme.com/x' },+ { href: 'https://walled.example/', status: 'unknown', httpStatus: 403 },+ ]),+ );+ expect(result.broken.map((l) => l.url)).toEqual(['https://gone.example/']);+ expect(result.checks).toEqual([{ id: 'noBrokenLinks', points: 1.5, max: 3 }]);+ // Links alone don't score Trust; the dead one is worth 1.5 of the 40 Phase 1 points.+ expect(result.score).toBeNull();+ expect(TRUST_PHASE1_POINTS).toBe(40);+ expect(trustGain(result, ['noBrokenLinks'])).toBe(4);+ });++ it('scores Trust only once a figure or a dated source is there', () => {+ const dead = read([{ href: 'https://gone.example/', status: 'broken', httpStatus: 404 }]);+ const working = read([{ href: 'https://gone.example/' }]);+ const linkOnly = '<p>See <a href="https://gone.example/">this</a>.</p>';+ // One link would otherwise set the whole score: 0 dead, 100 working.+ expect(run(linkOnly, dead).score).toBeNull();+ expect(run(linkOnly, working).score).toBeNull();+ expect(trustGain(run(linkOnly, dead), ['noBrokenLinks'])).toBe(8);+ expect(trustGain(run(linkOnly, working), ['noBrokenLinks'])).toBe(0);++ // With a figure the links count among Trust's live checks: 30 + 0 of 33.+ const withFigure = run(+ '<p>Win rates rose 42% (<a href="https://gone.example/">this</a>).</p>',+ dead,+ );+ expect(withFigure.score).toBe(91);+ expect(trustGain(withFigure, ['noBrokenLinks'])).toBe(scoreGain(withFigure, ['noBrokenLinks']));+ // A dated source alone is enough too.+ const dated = read([{ href: 'https://gone.example/', date: '2026-01-01T00:00:00.000Z' }]);+ expect(run(linkOnly, dated).score).toBe(100);+ });++ it(`asks for each http(s) link once, ${MAX_LINK_CHECKS} at most`, () => {+ const many = Array.from({ length: 25 }, (_, i) => `<a href="https://s${i}.example/">s</a>`);+ const html = `<p><a href="/pricing">p</a> <a href="https://a.example/">a</a> <a href="https://a.example/">a</a></p><p>${many.join(' ')}</p>`;+ const urls = linksToCheck(blocks(html));+ expect(urls[0]).toBe('https://a.example/');+ expect(urls).toHaveLength(MAX_LINK_CHECKS);+ });++ it('reads only figures as claims: not prices, sizes, years or ranks', () => {+ const claims = [+ 'Teams grew 10k accounts.',+ 'Revenue hit 2M last year.',+ 'It loads 3 times faster.',+ 'Rates rose 12 percent.',+ 'Costs fell by €4.5 million.',+ '100% of our customers renewed.',+ 'Get 50% off and 20% more reach.',+ ];+ const plain = [+ 'Plans start at $29/month.',+ 'A 10 x 20 cm box.',+ 'Room 3X is upstairs.',+ 'Support is open 24/7.',+ 'We ranked #1 in 2026.',+ 'Save 20% on your first order.',+ 'Get 50% off all shoes.',+ 'A 0% APR loan.',+ 'Made from 100% organic cotton.',+ 'Our 100% money-back guarantee covers every plan.',+ 'Watch it in 4K on any TV.',+ 'Roll it into your 401k.',+ 'Plans from $1.2k/month.',+ ];+ const result = run(`<p>${[...claims, ...plain].join(' ')}</p>`);+ expect(result.unsourced).toEqual(claims);+ });++ it('counts a link and a sentence once, as the draft saves the link', () => {+ const html =+ '<p>Read <a href="https://WWW.Gone.example?utm_source=mail">this</a>.</p>' ++ '<p>And <a href="https://www.gone.example/">this again</a>.</p>' ++ '<ul><li>Up 40% now.<ul><li>Up 40% now.</li></ul></li></ul>';+ expect(linksToCheck(blocks(html))).toEqual(['https://www.gone.example/']);+ const result = run(+ html,+ read([{ href: 'https://www.gone.example/', status: 'broken', httpStatus: 404 }]),+ );+ expect(result.broken).toHaveLength(1);+ expect(result.figures).toBe(1);+ });+});diff --git a/web/src/lib/content/quality-checks.ts b/web/src/lib/content/quality-checks.tsindex 7d7d82d9a..ebcb08466 100644--- a/web/src/lib/content/quality-checks.ts+++ b/web/src/lib/content/quality-checks.ts@@ -1,4 +1,7 @@+import { classifyDomain, normalizeDomain } from '@/lib/citations/classify';import type { ContentAuthor } from './authors';+import { cleanHref } from './html-allowlist';+import { ownText, sentencesOf } from './readability';/*** E-E-A-T and Trust (Content Editor Quality spec §2.1, §2.2): checks read@@ -32,6 +35,46 @@ export const EEAT_WEIGHTS = {} as const;export type EeatCheckId = keyof typeof EEAT_WEIGHTS;+/**+ * Trust's checks and points; Phase 1 reads the page's links and figures:+ * sourced figures, fresh sources, working links. Site trust joins with Site+ * Audit (CE-043); the rest are Phase 2.+ */+export const TRUST_WEIGHTS = {+ claimsSourced: 30,+ primarySources: 15,+ noWeakSources: 10,+ brandFacts: 10,+ expertQuote: 8,+ freshSources: 7,+ balanced: 7,+ disclosure: 5,+ noBrokenLinks: 3,+ siteTrust: 5,+} as const;+export type TrustCheckId = keyof typeof TRUST_WEIGHTS;++/**+ * Trust's Phase 1 points (sourced figures, fresh sources, working links):+ * what a broken link's gain is out of while Trust isn't scored (trustGain).+ */+export const TRUST_PHASE1_POINTS =+ TRUST_WEIGHTS.claimsSourced + TRUST_WEIGHTS.freshSources + TRUST_WEIGHTS.noBrokenLinks;++/** The most links the API reads for one draft at a time (link-check.js). */+export const MAX_LINK_CHECKS = 20;+/** A source older than this many months isn't fresh. */+export const FRESH_MONTHS = 24;++/** A link's read (the API's content_link_checks): does it answer, and its page's own date. */+export interface LinkCheck {+ /** The link as the page has it. */+ href: string;+ status: 'ok' | 'broken' | 'unknown';+ httpStatus: number | null;+ date: string | null;+}+function scoreOf<Id extends string>(checks: ScoreCheck<Id>[]): Score<Id> {const max = checks.reduce((sum, c) => sum + c.max, 0);if (max === 0) return { score: null, checks };@@ -49,6 +92,19 @@ export function scoreGain<Id extends string>(result: Score<Id>, ids: Id[]): numbreturn (scoreOf(raised).score ?? 0) - result.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+ * points, so a broken link still says what fixing it is worth.+ */+export function trustGain(result: Score<TrustCheckId>, ids: TrustCheckId[]): number {+ if (result.score !== null) return scoreGain(result, ids);+ const missing = result.checks+ .filter((c) => ids.includes(c.id))+ .reduce((sum, c) => sum + c.max - c.points, 0);+ return Math.round((missing / TRUST_PHASE1_POINTS) * 100);+}+/** What an author's profile has: a short bio, and profile links (Person schema's sameAs). */export function authorProfile(author: ContentAuthor | null): { bio: boolean; links: boolean } {return { bio: !!author?.bio?.trim(), links: (author?.sameAs.length ?? 0) > 0 };@@ -72,3 +128,197 @@ export function eeat({ author }: { author: ContentAuthor | null }): Score<EeatCh},]);}++/**+ * A figure, the kind of claim that wants a source: a percentage, an amount+ * with a magnitude ("$2.5 million", "€10M"), a number with a magnitude or a+ * multiplier ("2 million", "10k", "3x", "3 times faster"). A bare number+ * ("5 steps", "2026", "24/7"), a price ("$29/month") or a size ("10 x 20 cm")+ * isn't one.+ */+const FIGURE_WORDS =+ /%\s?\d|\d[\d.,]*\s?(?:%|percent\b|per cent\b|prozent\b)|[$€£¥₺]\s?\d[\d.,]*\s?(?:[km]\b|bn\b|thousand|million|billion|trillion)|\d[\d.,]*\s?(?:thousand|million|billion|trillion|millones|milyon|milyar|milliard|millionen|milliarden)s?\b|\d+(?:[.,]\d+)?\s?times\s(?:more|less|faster|slower|higher|lower|as|bigger|smaller|better|cheaper)\b/i;+const FIGURE_SHORT = /\b\d+(?:[.,]\d+)?(?:x|k|K|M|bn|B)\b/;+/** A percentage, either way round ("20%", "20 percent", "%20"). */+const PERCENT = String.raw`(?:\d[\d.,]*\s?(?:%|percent\b|per cent\b)|%\s?\d[\d.,]*)`;+/**+ * Numbers that read as figures but claim nothing, taken out before the+ * figures are looked for. Product and category pages have them in almost+ * every block:+ * - a discount or a rate: "Save 20%", "50% off", "a 0% APR loan";+ * - a material or a guarantee: "100% cotton", "100% money-back" ("100% of+ * our customers" stays a figure);+ * - short forms that aren't amounts: "4K", "8K", "401k";+ * - a price with a magnitude: "$1.2k/month", "$2 million per year".+ */+const NOT_FIGURES = [+ new RegExp(String.raw`\bsave\s+(?:up\s+to\s+)?${PERCENT}`, 'gi'),+ new RegExp(String.raw`${PERCENT}\s*(?:off|discount|apr|apy)\b`, 'gi'),+ /(?:\b100\s?(?:%|percent\b|per cent\b)|%\s?100\b)(?!\s*of\b)/gi,+ // Screens say "4K" in capitals; "4k" stays four thousand.+ /\b[48]K\b/g,+ /\b401\s?\(?k\b\)?/gi,+ /[$€£¥₺]\s?\d[\d.,]*\s?(?:[km]|bn|thousand|million|billion|trillion)\s*(?:\/|per\b)/gi,+];+const hasFigure = (sentence: string) => {+ const text = NOT_FIGURES.reduce((rest, re) => rest.replace(re, ' '), sentence);+ return FIGURE_WORDS.test(text) || FIGURE_SHORT.test(text);+};++/** A block of the page's text, with the links in it, as Trust reads them. */+export interface TrustBlock {+ tag: string;+ text: string;+ links: string[];+}++/**+ * The page's paragraphs, list items, quotes and table cells, each with its+ * own words and links: a list item without the list nested in it (as+ * Readability reads it), a paragraph in an item or a cell with it.+ */+export function trustBlocks(html: string): TrustBlock[] {+ const doc = new DOMParser().parseFromString(html, 'text/html');+ const out: TrustBlock[] = [];+ for (const el of doc.body.querySelectorAll('p, li, blockquote, td, th')) {+ const tag = el.tagName.toLowerCase();+ if (tag === 'p' && el.closest('li, blockquote, td, th')) continue;+ if (tag !== 'td' && tag !== 'th' && el.parentElement?.closest('td, th')) continue;+ // An inline link's edges leave no space before the punctuation after it.+ const text = ownText(el)+ .replace(/\s+/g, ' ')+ .replace(/ ([.,;:!?…)])/g, '$1')+ .trim();+ if (!text) continue;+ const links = [...el.querySelectorAll('a[href]')]+ // A list item's links, not its nested list's.+ .filter((a) => tag !== 'li' || a.closest('li') === el)+ .map((a) => a.getAttribute('href') ?? '');+ out.push({ tag, text, links });+ }+ return out;+}++/**+ * The page's links, as the draft saves them (cleanHref): http(s) only, each+ * with its block's place and whether it is on the brand's own site.+ */+function pageLinks(blocks: TrustBlock[], brandDomains: string[]) {+ const own = brandDomains.map(normalizeDomain).filter(Boolean);+ const out: { url: string; block: number; text: string; external: boolean }[] = [];+ blocks.forEach((block, index) => {+ for (const raw of block.links) {+ const href = cleanHref(raw);+ if (!href || !/^https?:\/\//i.test(href)) continue;+ const host = normalizeDomain(href);+ const external =+ !!host && classifyDomain(host, { brandDomains: own, competitorDomains: [] }) !== 'you';+ out.push({ url: href, block: index, text: block.text, external });+ }+ });+ return out;+}++/** Each link once, by its address. */+const byUrl = <T extends { url: string }>(links: T[]) => [+ ...new Map(links.map((l) => [l.url, l])).values(),+];++/** The page's links to read, each once, MAX_LINK_CHECKS at most: Trust's link checks. */+export function linksToCheck(blocks: TrustBlock[]): string[] {+ return [...new Set(pageLinks(blocks, []).map((l) => l.url))].slice(0, MAX_LINK_CHECKS);+}++export interface TrustRead extends Score<TrustCheckId> {+ /** Links that don't answer, with the block each is in (for Show). */+ broken: { url: string; text: string }[];+ /** Sources older than FRESH_MONTHS, and how many give a date at all. */+ stale: { url: string; text: string }[];+ dated: number;+ /** Sentences with a figure and no source in their block, and how many have a figure. */+ unsourced: string[];+ figures: number;+}++/**+ * Trust from the page as written (Phase 1): figures with a source (a link+ * to another site in the same block), sources from the last FRESH_MONTHS,+ * and links that answer. A check with nothing to read on the page (no+ * figure, no dated source, no link read yet) is left out, and Trust is+ * scored only once a figure or a dated source is there: working links alone+ * are 3 points, and one link would set the whole score (one dead link 0,+ * one working link 100), as Readability waits for MIN_WORDS.+ */+export function trust({+ blocks,+ links,+ brandDomains,+ now,+}: {+ /** The page's blocks (trustBlocks). */+ blocks: TrustBlock[];+ /** Each link's read, by the link as the page has it; one not read yet isn't counted. */+ links: Map<string, LinkCheck>;+ brandDomains: string[];+ now: number;+}): TrustRead {+ const all = pageLinks(blocks, brandDomains);+ const checks: ScoreCheck<TrustCheckId>[] = [];++ // Each sentence once: a nested list item's text is its parent's too.+ const figures = new Map<string, boolean>();+ blocks.forEach((b, index) => {+ const sourced = all.some((l) => l.external && l.block === index);+ for (const sentence of sentencesOf(b.text)) {+ if (hasFigure(sentence)) figures.set(sentence, (figures.get(sentence) ?? false) || sourced);+ }+ });+ const figureSentences = [...figures].map(([sentence, sourced]) => ({ sentence, sourced }));+ const unsourced = figureSentences.filter((f) => !f.sourced).map((f) => f.sentence);+ if (figureSentences.length) {+ checks.push({+ id: 'claimsSourced',+ points:+ (TRUST_WEIGHTS.claimsSourced * (figureSentences.length - unsourced.length)) /+ figureSentences.length,+ max: TRUST_WEIGHTS.claimsSourced,+ });+ }++ const cutoff = new Date(now);+ cutoff.setUTCMonth(cutoff.getUTCMonth() - FRESH_MONTHS);+ const sources = byUrl(all.filter((l) => l.external && links.get(l.url)?.date));+ const stale = sources.filter((l) => new Date(links.get(l.url)!.date!) < cutoff);+ if (sources.length) {+ checks.push({+ id: 'freshSources',+ points: (TRUST_WEIGHTS.freshSources * (sources.length - stale.length)) / sources.length,+ max: TRUST_WEIGHTS.freshSources,+ });+ }++ const read = byUrl(+ all.filter((l) => {+ const status = links.get(l.url)?.status;+ return status === 'ok' || status === 'broken';+ }),+ );+ const broken = read.filter((l) => links.get(l.url)!.status === 'broken');+ if (read.length) {+ checks.push({+ id: 'noBrokenLinks',+ points: (TRUST_WEIGHTS.noBrokenLinks * (read.length - broken.length)) / read.length,+ max: TRUST_WEIGHTS.noBrokenLinks,+ });+ }++ const scored = checks.some((c) => c.id === 'claimsSourced' || c.id === 'freshSources');+ return {+ ...(scored ? scoreOf(checks) : { score: null, checks }),+ broken: broken.map(({ url, text }) => ({ url, text })),+ stale: stale.map(({ url, text }) => ({ url, text })),+ dated: sources.length,+ unsourced,+ figures: figureSentences.length,+ };+}diff --git a/web/src/lib/content/readability.ts b/web/src/lib/content/readability.tsindex 2734d6d5f..f0d2c24c5 100644--- a/web/src/lib/content/readability.ts+++ b/web/src/lib/content/readability.ts@@ -92,7 +92,7 @@ const countWords = (text: string) => text.match(WORD)?.length ?? 0;* break (the editor's HTML has none between tags), a list item's own words* without the list nested in it.*/-function ownText(el: Element): string {+export function ownText(el: Element): string {let out = '';for (const node of el.childNodes) {if (node.nodeType === 3) out += node.textContent ?? '';