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-editor): check a product page's price, GTIN and stock against its product feed (00281, CE-053, part b) (#1498)
Cihan1f13a2da35a7
diff --git a/supabase/migrations/00281_catalog_variants_brand_live.sql b/supabase/migrations/00281_catalog_variants_brand_live.sqlnew file mode 100644index 000000000..2e2367796--- /dev/null+++ b/supabase/migrations/00281_catalog_variants_brand_live.sql@@ -0,0 +1,12 @@+-- ============================================================================+-- 00281: Quality phase 3, CE-053 — a brand's live variants, by its brand+-- ============================================================================+-- The Content Editor finds a product page's product in the brand's catalog+-- (00278) by the page's URL: the product's own (catalog_products_brand_live_idx+-- serves that read), else a variant's, when a feed gives a variant its own+-- page. This index serves the variants' read the same way, so it reads the+-- brand's live variants only, not every brand's.++create index if not exists catalog_variants_brand_live_idx+ on public.catalog_variants (brand_id)+ where removed_at is null;diff --git a/supabase/schema.sql b/supabase/schema.sqlindex db7e2f4fd..fc279af0d 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -39877,3 +39877,19 @@ create trigger content_draft_confirmations_capnotify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00281_catalog_variants_brand_live.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00281: Quality phase 3, CE-053 — a brand's live variants, by its brand+-- ============================================================================+-- The Content Editor finds a product page's product in the brand's catalog+-- (00278) by the page's URL: the product's own (catalog_products_brand_live_idx+-- serves that read), else a variant's, when a feed gives a variant its own+-- page. This index serves the variants' read the same way, so it reads the+-- brand's live variants only, not every brand's.++create index if not exists catalog_variants_brand_live_idx+ on public.catalog_variants (brand_id)+ where removed_at is null;+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 5b54a7621..b48323c78 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3882,6 +3882,7 @@"fixedMax": "Content Agent suggested {count} changes, the most one run makes · review them, then run it again for the rules still open","nothingToFix": "Content Agent found nothing it could change without new facts.","notForAgent": "Content Agent doesn't change heading levels: make the extra H1s H2s in the toolbar.",+ "notForAgentFeed": "Content Agent doesn't change a price, GTIN or stock: check which is right, the page or your product feed, and fix that one.","decideFirst": "{count, plural, one {Review the open suggestion first, then run the agent.} other {Review the open suggestions first, then run the agent.}}","citedLoading": "Reading which passages AI quotes, so the agent leaves them as they are…","agentBusy": "Content Agent is already working on this page. Wait for it to finish.",@@ -4714,13 +4715,18 @@"confirmCase": "Confirm","confirmCaseFailed": "Couldn't save that confirmation. Try again.","confirmCaseFull": "This page keeps 50 confirmations already.",+ "feed": {+ "none": "Price and stock aren't checked: no product feed is connected for this brand yet.",+ "connect": "Connect a feed",+ "notFound": "Price and stock aren't checked: no product in your feed has this page's URL or title."+ },"weightsFor": {"line": "Checks and weights for {type}{detected, select, yes { (detected)} other {}}:","noType": "an article (no page type yet)","change": "Change","changeLabel": "Change the page type","article": "an author with experience, sourced claims, short sentences and the answer first.",- "product": "no author (your brand's), your own product photos, proof for claims, prices that match, shipping and returns, a specs table and short plain copy.",+ "product": "no author (your brand's), your own product photos, proof for claims, the price and stock your product feed has, shipping and returns, a specs table and short plain copy.","category": "your own product images, your brand's information on its site, prices and claims that match, an intro and a buying FAQ.","feature": "your own screenshots and data, customer cases you may publish, sourced metrics, a price that matches, a comparison table, proof per section and use case steps in scannable sections.","comparison": "an author who says how the picks were made and when they were last checked, balance and a disclosure, a side-by-side table, the summary first."@@ -4985,6 +4991,10 @@"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}}"},+ "feedMatch": {+ "line": "{kind, select, price {Price} gtin {GTIN} other {Stock}} differs from your product feed · Page {kind, select, stock {{page, select, in {in stock} other {out of stock}}} other {{page}}} · Feed {kind, select, stock {{feed, select, in {in stock} other {out of stock}}} other {{feed}}}",+ "detail": "{count, plural, one {Check which is right, and fix the page or your feed: search engines and Merchant Center compare them} other {# differ: check which is right, and fix the page or your feed. Search engines and Merchant Center compare them}}"+ },"disclosure": {"line": "The page recommends {brand} without a disclosure","detail": "Add a line saying the product the page recommends is {brand}'s own: readers and AI engines trust a page that says so."@@ -5094,7 +5104,7 @@"aiTraces": "Finds phrases that read as machine-written (delve, in today's fast-paced world, not only… but also). Fixing them comes with the Content Agent.","whoFor": "Who the page is for, in one sentence, e.g. \"Sales leaders at 20–200 person B2B teams\".","first40Words": "ChatGPT reads about the first 50 tokens (~40 words) of a product description. The rest is ignored.",- "feedMatch": "Checked against the product feed once it's connected.",+ "feedMatch": "Checked against the product in your product feed with this page's URL, or else its name: the price, any GTIN the page gives, and the stock, where both say them.","definitionFirst": "The paragraph under the H1 says what the term is (\"X is …\") in a few words: what answer engines quote for \"what is\" prompts.","measureSteps": "The longest numbered list on the page counts as the steps."},@@ -5132,6 +5142,10 @@"notSet": "Not set","aiCheck": "AI check","needsFeed": "Needs feed",+ "feedReading": "Reading feed",+ "notInFeed": "Not in feed",+ "feedNothing": "Nothing to compare",+ "feedDiffers": "{count, plural, one {# differs} other {# differ}} from feed","noFanouts": "No fan-outs","addPrompts": "Add prompts","noFanoutsHint": "No fan-outs yet: they come from the page's prompts. Add its prompts in Sources.",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 084d63568..0ceefa217 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@@ -48,6 +48,7 @@ import {keepDraftSource,confirmDraftItem,confirmOwnImage,+ getCatalogMatch,getDraftConfirmations,getOwnImages,setContentDraftPageType,@@ -135,6 +136,7 @@ import {import { caseConfirmed, caseKey, proofKey, qualityTodos } from '@/lib/content/quality-todos';import { isByline, readability, sentencesOf, withTypeRules } from '@/lib/content/readability';import { brandFactsPath, factMismatches } from '@/lib/content/brand-facts';+import { feedCheck, type CatalogMatch } from '@/lib/content/feed-match';import {MAX_PROOF_TODOS,aiChecksOnPage,@@ -155,6 +157,7 @@ import {aiTracesFound,fanoutsToUse,lengthWarns,+ notForAgentMessage,openRulesForAgent,lengthBand,rewriteAdvice,@@ -553,6 +556,35 @@ export function DraftEditor({// The rules the page is written to, checked as it reads now (CE-009).// The brief and sources, read once: the rules check against them, the panel shows them.const reads = useDraftReads(draft.id);+ // Phase 3 (CE-053): a product page's product in the brand's catalog, by+ // its URL or its title, read once typing pauses: Trust and the Rules+ // tab's feed rule check the page against it. Undefined while not read.+ const feedOn = profileFor(pageType) === 'product';+ const [catalogRead, setCatalogRead] = useState<{ title: string; read: CatalogMatch | null }>();+ useEffect(() => {+ if (!feedOn) return;+ let live = true;+ const timer = setTimeout(() => {+ getCatalogMatch(draft.id, title)+ .then((read) => live && setCatalogRead({ title, read }))+ .catch((err) => {+ console.error('Failed to read the catalog:', err);+ if (live) setCatalogRead({ title, read: null });+ });+ }, PAGE_READ_DELAY_MS);+ return () => {+ live = false;+ clearTimeout(timer);+ };+ }, [feedOn, draft.id, title]);+ // A product found by its name is the page's while the title is that name:+ // after a change, it is read again.+ const catalog =+ catalogRead &&+ (catalogRead.read?.product?.via !== 'name' ||+ catalogRead.title.trim().toLowerCase() === title.trim().toLowerCase())+ ? catalogRead.read+ : undefined;const rules = useDraftRules({draft,siteType,@@ -560,6 +592,7 @@ export function DraftEditor({characters: (editor?.storage.characterCount.characters() as number | undefined) ?? 0,pageType,reads,+ catalog: feedOn ? (catalog === undefined ? 'reading' : catalog) : null,});// What a page rewrite keeps as it is (the passages AI answers quote, tables,// images…), read as the characters are: a Length under it is out of reach.@@ -972,6 +1005,18 @@ export function DraftEditor({offer: pageOffer(pageBlocks.map((block) => block.text)),};}, [profile, images, ownImages, pageHtml, pageBlocks]);+ // The page's price, GTIN and stock against its product in the feed (CE-053).+ const feedRead = useMemo(+ () =>+ feedOn && catalog?.product && productSchema+ ? feedCheck({+ texts: pageBlocks.map((block) => block.text),+ offer: productSchema.offer,+ variants: catalog.product.variants,+ })+ : null,+ [feedOn, catalog, productSchema, pageBlocks],+ );// Confirm: only the person can tell their own image from stock.const [confirmingImages, setConfirmingImages] = useState(false);// Quality's Confirm on a customer case (CE-052): the person's statement@@ -1048,8 +1093,9 @@ export function DraftEditor({brandFacts: factCheck,proofs: proofAsks,page: aiChecks,- // A product page's shipping and returns (CE-052).+ // A product page's shipping and returns (CE-052), price and stock (CE-053).shipping: shippingRead,+ feed: feedRead,now: Date.now(),}),weights.trust,@@ -1058,6 +1104,7 @@ export function DraftEditor({[weights,shippingRead,+ feedRead,qualityOn,pageBlocks,linkChecks,@@ -1215,6 +1262,14 @@ export function DraftEditor({qualityPhase() >= 3? { type: pageType ?? null, detected: picked === null, profile }: null,+ feed:+ feedOn && catalog+ ? !catalog.connected+ ? 'none'+ : !catalog.product+ ? 'notFound'+ : null+ : null,readability: readable,eeat: eeatScore,trust: trustScore,@@ -1943,7 +1998,7 @@ export function DraftEditor({const { forAgent: open, notForAgent } = openRulesForAgent(rules.rules, only);if (open.length === 0) {// Only rules it can't fix are open: say what to do instead.- if (notForAgent.length) toast(t('suggestions.notForAgent'));+ if (notForAgent.length) toast(t(`suggestions.${notForAgentMessage(notForAgent)}`));return;}const pageText = editor.getText({ blockSeparator: '\n' });@@ -2272,7 +2327,7 @@ export function DraftEditor({const cardRunBlocked =agentFix.blocked ??(agentRules.forAgent.length === 0 && agentRules.notForAgent.length > 0- ? t('suggestions.notForAgent')+ ? t(`suggestions.${notForAgentMessage(agentRules.notForAgent)}`): null);// A drag with files over the page shows where they go; one dropped besidediff --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 04c0e9611..59968860f 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@@ -145,7 +145,7 @@ describe('QualityTab', () => {p.textContent?.startsWith('Checks and weights for'),)!;expect(line.textContent).toBe(- "Checks and weights for Product page (detected): no author (your brand's), your own product photos, proof for claims, prices that match, shipping and returns, a specs table and short plain copy. Change",+ "Checks and weights for Product page (detected): no author (your brand's), your own product photos, proof for claims, the price and stock your product feed has, shipping and returns, a specs table and short plain copy. Change",);await act(async () => line.querySelector('button')!.click());expect(onChangeType).toHaveBeenCalled();@@ -162,6 +162,40 @@ describe('QualityTab', () => {expect(container.textContent).not.toContain('Checks and weights for');});+ it('names a price that differs from the product feed, and says when there is none to check (CE-053)', async () => {+ const trustRead = trust({+ blocks: trustBlocks('<p>The Ridge 28 costs $129.</p><p>In stock.</p>'),+ links: new Map(),+ brandDomains: [],+ feed: {+ compared: 2,+ mismatches: [+ { kind: 'price', page: '$129', feed: '$119', sentence: 'The Ridge 28 costs $129.' },+ { kind: 'stock', page: 'in', feed: 'out', sentence: 'In stock.' },+ ],+ },+ now: Date.parse('2026-10-25T12:00:00Z'),+ });+ await render({ ...read(result), trust: trustRead });+ expect(container.textContent).toContain(+ 'Price differs from your product feed · Page $129 · Feed $119',+ );+ expect(container.textContent).toContain('2 differ: check which is right');+ // No feed, or no product in it with the page's URL or title: a line says so.+ await render({ ...read(result), feed: 'none' });+ expect(container.textContent).toContain(+ "Price and stock aren't checked: no product feed is connected",+ );+ expect(+ container.querySelector<HTMLAnchorElement>('a[href="/dashboard/settings/integrations"]')+ ?.textContent,+ ).toBe('Connect a feed');+ await render({ ...read(result), feed: 'notFound' });+ expect(container.textContent).toContain("no product in your feed has this page's URL or title");+ await render(read(result));+ expect(container.textContent).not.toContain("Price and stock aren't checked");+ });+it('names the page type’s rules not met yet, and a product page’s shipping to-do (CE-052)', async () => {const typed: Readability = {...result,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 061c3e24b..3743d3ea1 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@@ -30,6 +30,7 @@ import {type ReadabilityCheck,} from '@/lib/content/readability';import { SITE_TRUST_PATH, siteTrustMissing, type SiteTrust } from '@/lib/content/site-trust';+import { CATALOG_SETTINGS_PATH } from '@/lib/content/feed-match';import { cn } from '@/lib/utils';import { MANAGE_AUTHORS_PATH } from './_author-menu';@@ -45,6 +46,12 @@ export interface QualityRead {* it was detected (not picked), and its profile; left out before.*/weightsFor?: { type: string | null; detected: boolean; profile: QualityProfile } | null;+ /**+ * Phase 3 (CE-053): why a product page isn't checked against a product+ * feed: no catalog connected, or none of its products is the page's;+ * null where it is checked, or isn't a product page.+ */+ feed?: 'none' | 'notFound' | null;/** The page's Readability as written, or null before it is read. */readability: Readability | null;/** E-E-A-T from the author, or null before the authors are read. */@@ -253,6 +260,22 @@ export function QualityTab({)}</p>)}+ {quality.feed && (+ <p className="text-xs text-muted-foreground">+ {t(`feed.${quality.feed}`)}+ {quality.feed === 'none' && (+ <>+ {' '}+ <Link+ href={CATALOG_SETTINGS_PATH}+ className="font-medium text-foreground underline-offset-2 hover:underline"+ >+ {t('feed.connect')}+ </Link>+ </>+ )}+ </p>+ )}{readability?.score === null && (<p className="rounded-xl border border-dashed px-3 py-2.5 text-xs text-muted-foreground">{t(readability?.unscored === 'language' ? 'notThisLanguage' : 'tooShort')}@@ -920,6 +943,26 @@ export function trustSuggestions(show: first.sentence,});}+ // Phase 3 (CE-053): the person checks which is right, the page or the+ // feed: Hand off leaves it (it isn't one of its keys).+ const feed = trust.feed ?? [];+ if (feed.length) {+ const [first] = feed;+ out.push({+ key: 'trust:feedMatch',+ check: 'feedMatch',+ score: 'trust',+ gain: trustGain(trust, ['feedMatch']),+ line: t('checks.feedMatch.line', {+ kind: first.kind,+ page: first.page,+ feed: first.feed,+ }),+ count: feed.length,+ detail: t('checks.feedMatch.detail', { count: feed.length }),+ show: first.sentence || null,+ });+ }if (trust.stale.length) {out.push({key: 'trust:freshSources',diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsxindex 732b1bfe1..709a81fea 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_rules-tab.tsx@@ -32,6 +32,7 @@ import { SITE_PAGE_TYPES, type SiteType } from '@/lib/content/page-types';import {MAX_TEXT_RULE_LENGTH,RULE_GROUPS,+ notForAgentMessage,openRulesForAgent,lengthOutOfReach,rewriteAdvice,@@ -252,14 +253,16 @@ export function RulesTab({const outOfReach = pageRewrite ? lengthOutOfReach(state.rules, pageRewrite.kept ?? 0) : null;// The rules the page doesn't meet now, in the tab's order, and those the agent fixes.const open = state.rules.filter(({ rule, status }) => rule.on && status.state === 'bad');- const fixable = openRulesForAgent(state.rules).forAgent.length;+ const { forAgent, notForAgent } = openRulesForAgent(state.rules);+ const fixable = forAgent.length;// Run Agent's choice: the safe default, or the whole page (▾) while it is offered.const [picked, setPicked] = useState<RunMode>('fix');const mode: RunMode = picked === 'rewrite' && pageRewrite ? 'rewrite' : 'fix';const runner = mode === 'rewrite' ? pageRewrite : agentFix;// Why Run Agent can't run its choice now, said under the card.const blocked =- runner?.blocked ?? (mode === 'fix' && fixable === 0 ? tSuggestions('notForAgent') : null);+ runner?.blocked ??+ (mode === 'fix' && fixable === 0 ? tSuggestions(notForAgentMessage(notForAgent)) : null);// A draft on My rules for a type the workspace has none for (its type// changed, or My rules couldn't be read) shows Ansvisor's set for it.diff --git a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.ts b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.tsindex 304e6029a..eef87057c 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.ts+++ b/web/src/app/[locale]/(dashboard)/dashboard/content/editor/[draftId]/_use-draft-rules.ts@@ -5,6 +5,7 @@ import { useTranslations } from 'next-intl';import { toast } from 'sonner';import { getMyRuleSets, saveDraftRules, saveMyRuleSet } from '@/lib/actions/content-drafts';import { isPageType, type ContentDraft, type PageType } from '@/lib/content/drafts';+import type { CatalogMatch } from '@/lib/content/feed-match';import type { SiteType } from '@/lib/content/page-types';import {MAX_TEXT_RULES,@@ -90,6 +91,7 @@ export function useDraftRules({characters,pageType,reads,+ catalog = null,}: {draft: ContentDraft;/** The brand's business type as the editor holds it: My rules are kept per type (00227). */@@ -98,6 +100,8 @@ export function useDraftRules({characters: number;pageType: string | null;reads: Pick<DraftReads, 'brief' | 'sources'>;+ /** The page's product in the brand's catalog (CE-053), for the feed rule (RuleContext's). */+ catalog?: CatalogMatch | 'reading' | null;}): DraftRulesState {const t = useTranslations('contentEditor.editor.rules');const tTypes = useTranslations('contentEditor.pageTypes');@@ -132,7 +136,7 @@ export function useDraftRules({const sources = reads.sources;const ctx = useMemo<RuleContext>(() => {if (!sources || sources.failed) {- return { brandDomains: [], competitorDomains: [], fanouts: [], language };+ return { brandDomains: [], competitorDomains: [], fanouts: [], language, catalog };}const fanouts = buildSourceGroups(sources.data, sources.choices, {title: draft.title,@@ -146,8 +150,9 @@ export function useDraftRules({competitorDomains: sources.data.competitorDomains,fanouts: fanouts ?? [],language,+ catalog,};- }, [sources, draft.title, draft.sourceUrl, language]);+ }, [sources, draft.title, draft.sourceUrl, language, catalog]);const brief = reads.brief;const keywords = useMemo(() => (brief.status === 'ready' ? (brief.brief?.keywords ?? []) : []),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 aa4b48bea..24d98d366 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@@ -26,6 +26,7 @@ const checkDraftClaims = vi.fn();const readDraftPage = vi.fn();const getOwnImages = vi.fn();const getDraftConfirmations = vi.fn();+const getCatalogMatch = vi.fn();const confirmDraftItem = vi.fn();const confirmOwnImage = vi.fn();const getBrandFacts = vi.fn();@@ -109,6 +110,7 @@ vi.mock('@/lib/actions/content-drafts', () => ({readDraftPage: (...args: unknown[]) => readDraftPage(...args),getOwnImages: (...args: unknown[]) => getOwnImages(...args),getDraftConfirmations: (...args: unknown[]) => getDraftConfirmations(...args),+ getCatalogMatch: (...args: unknown[]) => getCatalogMatch(...args),confirmDraftItem: (...args: unknown[]) => confirmDraftItem(...args),confirmOwnImage: (...args: unknown[]) => confirmOwnImage(...args),checkDraftLinks: (...args: unknown[]) => checkDraftLinks(...args),@@ -318,6 +320,7 @@ beforeEach(() => {readDraftPage.mockReset().mockResolvedValue({ error: 'off' });getOwnImages.mockReset().mockResolvedValue([]);getDraftConfirmations.mockReset().mockResolvedValue([]);+ getCatalogMatch.mockReset().mockResolvedValue({ connected: false, product: null });confirmDraftItem.mockReset().mockResolvedValue('ok');confirmOwnImage.mockReset().mockResolvedValue('ok');getBrandFacts.mockReset().mockResolvedValue({@@ -2605,6 +2608,9 @@ describe('the side panel', () => {expect(text).toMatch(/1 page type rule not met: Specs table/);expect(text).toContain('Say how shipping and returns work');expect(text).not.toContain('Add an author for the page');+ // No product feed yet (CE-053): the price and stock aren't checked, and it says so.+ expect(getCatalogMatch).toHaveBeenCalledWith('d1', readable.title);+ expect(text).toContain("Price and stock aren't checked: no product feed is connected");});it('leaves a date in the person’s words alone, and replaces only its own old line (#1495 review)', async () => {diff --git a/web/src/lib/actions/content-drafts.test.ts b/web/src/lib/actions/content-drafts.test.tsindex 8726d1d55..b96b5682c 100644--- a/web/src/lib/actions/content-drafts.test.ts+++ b/web/src/lib/actions/content-drafts.test.ts@@ -26,6 +26,10 @@ let rpcCalls: [string, unknown][];let rpcResult: { data: unknown; error: { message: string } | null };// What an upsert answers (an own image's confirm).let upsertError: { code: string; message: string } | null;+// Reads answered in turn, each with its own rows, when a test needs them (the catalog's).+let queue: Record<string, unknown>[][];+// A read that fails, when a test needs one.+let readError: string | null;vi.mock('@/lib/action-center/assignees', () => ({ readAssignees: vi.fn(async () => new Map()) }));vi.mock('@/lib/supabase/admin', () => ({ supabaseAdmin: {} }));@@ -57,15 +61,23 @@ vi.mock('@/lib/supabase/server', () => ({eq: (col: string, v: unknown) => (call.filters.push(['eq', col, v]), chain),in: (col: string, v: unknown) => (call.filters.push(['in', col, v]), chain),gte: (col: string, v: unknown) => (call.filters.push(['gte', col, v]), chain),+ is: (col: string, v: unknown) => (call.filters.push(['is', col, v]), chain),+ ilike: (col: string, v: unknown) => (call.filters.push(['ilike', col, v]), chain),or: (v: string) => (call.filters.push(['or', v, null]), chain),order: () => chain,// The list, by its batch when one is asked for; the first row alone// when the read is for one (the latest batch).limit: () => {+ if (readError) {+ const failed = { data: null, error: { message: readError } };+ return Object.assign(Promise.resolve(failed), { maybeSingle: async () => failed });+ }const batch = call.filters.find(([op, col]) => op === 'eq' && col === 'batch_id');- const rows = batch- ? list.filter((r) => (r as { batch_id?: unknown }).batch_id === batch[2])- : list;+ const rows = queue.length+ ? queue.shift()!+ : batch+ ? list.filter((r) => (r as { batch_id?: unknown }).batch_id === batch[2])+ : list;return Object.assign(Promise.resolve({ data: rows, error: null }), {maybeSingle: async () => ({ data: rows[0] ?? null, error: null }),});@@ -80,7 +92,8 @@ vi.mock('@/lib/supabase/server', () => ({// A read awaited as it is: the list.then: (resolve: (value: unknown) => void) =>resolve(call.op === 'select' ? { data: list, error: null } : result()),- maybeSingle: async () => result(),+ maybeSingle: async () =>+ queue.length ? { data: queue.shift()![0] ?? null, error: null } : result(),single: async () => result(),};return chain;@@ -111,6 +124,7 @@ const {getOwnImages,confirmDraftItem,getDraftConfirmations,+ getCatalogMatch,setContentDraftReviewer,} = await import('./content-drafts');const { bodyHash } = await import('@/lib/content/editor');@@ -122,6 +136,8 @@ beforeEach(() => {row = null;list = [];upsertError = null;+ queue = [];+ readError = null;rpcCalls = [];rpcResult = { data: 'v-new', error: null };completeDraftTasks.mockReset().mockResolvedValue(0);@@ -1081,3 +1097,116 @@ describe('fixDraftRules', () => {await expect(fixDraftRules('../etc', BRAND, request)).resolves.toEqual({ error: 'failed' });});});++describe('getCatalogMatch (Quality CE-053)', () => {+ const variant = {+ price: '129.00',+ sale_price: null,+ currency: 'USD',+ availability: 'in_stock',+ gtin: '00012345678905',+ };++ it('says when the brand has no catalog, and fails soft', async () => {+ queue = [[{ brand_id: 'b1', source_url: null }], []];+ expect(await getCatalogMatch(DRAFT, 'Ridge 28')).toEqual({ connected: false, product: null });+ expect(await getCatalogMatch('d1', 'Ridge 28')).toBeNull();+ // A read that fails: null, said in the log.+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});+ queue = [[{ brand_id: 'b1', source_url: null }]];+ readError = 'permission denied';+ expect(await getCatalogMatch(DRAFT, 'Ridge 28')).toBeNull();+ expect(log).toHaveBeenCalledWith('Failed to read the catalog:', expect.any(Error));+ log.mockRestore();+ });++ it('finds the page’s product by its URL as the feed writes it', async () => {+ queue = [+ [{ brand_id: 'b1', source_url: 'https://www.acme.com/products/ridge-28/' }],+ [{ id: 'p0' }],+ // Narrowed by the path: another product's longer URL isn't the page's.+ [+ { id: 'p9', url: 'https://acme.com/products/ridge-28-pro' },+ { id: 'p1', url: 'https://acme.com/products/ridge-28?variant=42' },+ ],+ [{ title: 'Ridge 28', url: 'https://acme.com/products/ridge-28' }],+ [variant],+ ];+ expect(await getCatalogMatch(DRAFT, 'Not its name')).toEqual({+ connected: true,+ product: {+ title: 'Ridge 28',+ url: 'https://acme.com/products/ridge-28',+ via: 'url',+ variants: [+ {+ price: 129,+ salePrice: null,+ currency: 'USD',+ availability: 'in_stock',+ gtin: '00012345678905',+ },+ ],+ },+ });+ expect(calls.flatMap((c) => c.filters).filter(([op]) => op === 'ilike')).toEqual([+ ['ilike', 'url', '%/products/ridge-28%'],+ ]);+ });++ it('finds a variant with its own page by its URL, when no product has it (CE-053 review)', async () => {+ queue = [+ [{ brand_id: 'b1', source_url: 'https://acme.com/products/boot-blue' }],+ [{ id: 'p0' }],+ // The product's URL is its first item's ("boot-red").+ [],+ [{ product_id: 'p2', url: 'https://acme.com/products/boot-blue?variant=7' }],+ [{ title: 'Boot', url: 'https://acme.com/products/boot-red' }],+ [],+ ];+ expect(await getCatalogMatch(DRAFT, 'Boot in blue')).toEqual({+ connected: true,+ product: {+ title: 'Boot',+ url: 'https://acme.com/products/boot-red',+ via: 'url',+ variants: [],+ },+ });+ });++ it('looks a path up as written and as an address encodes it', async () => {+ queue = [+ [{ brand_id: 'b1', source_url: 'https://acme.com.tr/%C3%BCr%C3%BCn' }],+ [{ id: 'p0' }],+ [{ id: 'p1', url: 'https://acme.com.tr/ürün' }],+ [],+ [{ title: 'Ürün', url: 'https://acme.com.tr/ürün' }],+ [],+ ];+ expect((await getCatalogMatch(DRAFT, 'x'))?.product?.via).toBe('url');+ expect(calls.flatMap((c) => c.filters).filter(([op]) => op === 'ilike')).toEqual([+ ['ilike', 'url', '%/ürün%'],+ // Its "%" escaped: a literal one, not a wildcard.+ ['ilike', 'url', '%/\\%C3\\%BCr\\%C3\\%BCn%'],+ ]);+ });++ it('finds it by its title when one product has it, its words matched as written', async () => {+ queue = [+ [{ brand_id: 'b1', source_url: null }],+ [{ id: 'p0' }],+ [{ id: 'p1' }],+ [{ title: 'Ridge_28 100%', url: null }],+ [],+ ];+ expect(await getCatalogMatch(DRAFT, ' Ridge_28 100% ')).toEqual({+ connected: true,+ product: { title: 'Ridge_28 100%', url: null, via: 'name', variants: [] },+ });+ expect(calls.flatMap((c) => c.filters)).toContainEqual(['ilike', 'title', 'Ridge\\_28 100\\%']);+ // Two products by that name: whose page this is isn't sure.+ queue = [[{ brand_id: 'b1', source_url: null }], [{ id: 'p0' }], [{ id: 'p1' }, { id: 'p2' }]];+ expect(await getCatalogMatch(DRAFT, 'Ridge 28')).toEqual({ connected: true, product: null });+ });+});diff --git a/web/src/lib/actions/content-drafts.ts b/web/src/lib/actions/content-drafts.tsindex 5a95b1f0a..0369845c6 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 { pageKey, type CatalogMatch } from '@/lib/content/feed-match';import type { LinkCheck } from '@/lib/content/quality-checks';import { CLAIM_KINDS, type ClaimBlock } from '@/lib/content/claims';import {@@ -2716,3 +2717,154 @@ export async function confirmDraftItem(if (error) throw new Error(error.message);return 'ok';}++/** A product's name as the page's title gives it: one line, up to the catalog's length. */+const catalogTitle = z.string().trim().min(1).max(1000);+/** A page's path as an address encodes it and as it reads, in its own case ("/%C3%9Cber", "/Über"). */+function pathForms(url: string): string[] {+ try {+ const path = new URL(url.trim()).pathname.replace(/\/+$/, '');+ if (path.length <= 1) return [];+ let decoded = path;+ try {+ decoded = decodeURIComponent(path);+ } catch {+ // Not encoded as UTF-8: looked up as it is.+ }+ return [...new Set([decoded, path])];+ } catch {+ return [];+ }+}+/** Escape `\`, `%` and `_`: a path or a title matched as written. */+const likeText = (value: string) => value.replace(/[\\%_]/g, (ch) => `\\${ch}`);++/**+ * The draft's product in the brand's catalog (00278; Quality CE-053): by+ * the page's URL (an optimize draft's), else by its title, when one product+ * has it. Says whether a catalog is connected at all, so Quality can say to+ * connect one. Fails soft: null, when it can't be read.+ */+export async function getCatalogMatch(id: string, title: string): Promise<CatalogMatch | null> {+ if (!draftId.safeParse(id).success) return null;+ try {+ const supabase = await createClient();+ const { data: draft, error: draftError } = await supabase+ .from('content_drafts')+ .select('brand_id, source_url')+ .eq('id', id)+ .maybeSingle();+ if (draftError) throw new Error(draftError.message);+ if (!draft) return null;+ const brand = draft.brand_id;+ const { data: one, error: oneError } = await supabase+ .from('catalog_products')+ .select('id')+ .eq('brand_id', brand)+ .is('removed_at', null)+ .limit(1);+ if (oneError) throw new Error(oneError.message);+ if (!one?.length) return { connected: false, product: null };++ let productId: string | null = null;+ let via: 'url' | 'name' = 'url';+ const key = pageKey(draft.source_url);+ const forms = key ? pathForms(draft.source_url!) : [];+ // PostgREST reads "*" in a pattern as a wildcard: such a path or title isn't looked up.+ if (key && forms.length && !forms.some((form) => form.includes('*'))) {+ // The brand's live products (their index), narrowed by the path as+ // written and as an address encodes it, in its own case, then compared+ // whole: a feed's URL may carry a query ("?variant=…") or another+ // form of the host.+ const byUrl = async (table: 'catalog_products' | 'catalog_variants') => {+ const ids = new Set<string>();+ for (const form of forms) {+ const read =+ table === 'catalog_products'+ ? await supabase+ .from('catalog_products')+ .select('id, url')+ .eq('brand_id', brand)+ .is('removed_at', null)+ .ilike('url', `%${likeText(form)}%`)+ .limit(100)+ : await supabase+ .from('catalog_variants')+ .select('product_id, url')+ .eq('brand_id', brand)+ .is('removed_at', null)+ .ilike('url', `%${likeText(form)}%`)+ .limit(100);+ if (read.error) throw new Error(read.error.message);+ for (const row of read.data ?? []) {+ if (pageKey(row.url) !== key) continue;+ ids.add('product_id' in row ? row.product_id : row.id);+ }+ }+ return ids;+ };+ // A product's URL is its first item's link: a variant with its own+ // page ("boot-blue" grouped under "boot-red") is found by its own.+ let ids = await byUrl('catalog_products');+ if (ids.size === 0) ids = await byUrl('catalog_variants');+ if (ids.size === 1) productId = [...ids][0];+ }+ const name = catalogTitle.safeParse(title);+ if (!productId && name.success && !name.data.includes('*')) {+ const { data, error } = await supabase+ .from('catalog_products')+ .select('id')+ .eq('brand_id', brand)+ .is('removed_at', null)+ .ilike('title', likeText(name.data))+ .limit(2);+ if (error) throw new Error(error.message);+ // Two products by one name: whose page this is isn't sure.+ if (data?.length === 1) {+ productId = data[0].id;+ via = 'name';+ }+ }+ if (!productId) return { connected: true, product: null };++ const [product, variants] = await Promise.all([+ supabase+ .from('catalog_products')+ .select('title, url')+ .eq('id', productId)+ .is('removed_at', null)+ .maybeSingle(),+ // By price, so a range's low end is among them however many there are.+ supabase+ .from('catalog_variants')+ .select('price, sale_price, currency, availability, gtin')+ .eq('product_id', productId)+ .is('removed_at', null)+ .order('price', { ascending: true })+ .limit(200),+ ]);+ if (product.error) throw new Error(product.error.message);+ if (variants.error) throw new Error(variants.error.message);+ if (!product.data) return { connected: true, product: null };+ const amount = (value: number | string | null) =>+ value === null || !Number.isFinite(Number(value)) ? null : Number(value);+ return {+ connected: true,+ product: {+ title: product.data.title,+ url: product.data.url,+ via,+ variants: (variants.data ?? []).map((v) => ({+ price: amount(v.price),+ salePrice: amount(v.sale_price),+ currency: v.currency,+ availability: v.availability,+ gtin: v.gtin,+ })),+ },+ };+ } catch (err) {+ console.error('Failed to read the catalog:', err);+ return null;+ }+}diff --git a/web/src/lib/content/feed-match.test.ts b/web/src/lib/content/feed-match.test.tsnew file mode 100644index 000000000..60459b6f1--- /dev/null+++ b/web/src/lib/content/feed-match.test.ts@@ -0,0 +1,201 @@+import { describe, expect, it } from 'vitest';+import { feedCheck, feedStock, pageKey, stockOnPage, type FeedVariant } from './feed-match';++/** A product page against its product feed (Quality spec §11, CE-053). */++const variant = (over: Partial<FeedVariant> = {}): FeedVariant => ({+ price: 129,+ salePrice: null,+ currency: 'USD',+ availability: 'in_stock',+ gtin: null,+ ...over,+});++describe('pageKey', () => {+ it('reads an address as feeds write it: no www, trailing slash or query', () => {+ expect(pageKey('https://www.Acme.com/products/Ridge-28/?variant=42#specs')).toBe(+ 'acme.com/products/ridge-28',+ );+ expect(pageKey('http://acme.com/products/ridge-28')).toBe('acme.com/products/ridge-28');+ expect(pageKey('https://acme.com.tr/%C3%BCr%C3%BCn/')).toBe('acme.com.tr/ürün');+ expect(pageKey('https://acme.com.tr/ürün')).toBe('acme.com.tr/ürün');+ expect(pageKey('ftp://acme.com/x')).toBeNull();+ expect(pageKey('not a url')).toBeNull();+ expect(pageKey(null)).toBeNull();+ });+});++describe('stockOnPage', () => {+ it('reads what the page says of its stock, and none where it says both', () => {+ expect(stockOnPage(['Ships in 2 days.', 'In stock and ready to ship.'])).toEqual({+ stock: 'in',+ sentence: 'In stock and ready to ship.',+ });+ expect(stockOnPage(['Sorry, this one is sold out.'])?.stock).toBe('out');+ expect(stockOnPage(['Stokta yok.'])?.stock).toBe('out');+ expect(stockOnPage(['Stokta, hemen kargoda.'])?.stock).toBe('in');+ expect(stockOnPage(['Derzeit ausverkauft.'])?.stock).toBe('out');+ expect(stockOnPage(['Black is in stock.', 'Blue is out of stock.'])).toBeNull();+ // Out, however it's said: not, no longer, "email me when it's back in stock".+ for (const out of [+ 'Email me when it is back in stock.',+ 'Not in stock right now.',+ 'No longer in stock.',+ 'Bu ürün stokta değil.',+ 'Stokta kalmadı.',+ 'Ürün stokta yoktur.',+ 'Stokta bulunmamaktadır.',+ 'Stokta mevcut değil.',+ 'Plus en stock.',+ 'Nicht mehr vorrätig.',+ ]) {+ expect(stockOnPage([out])?.stock, out).toBe('out');+ }+ // Back in stock is in stock.+ expect(stockOnPage(['Back in stock!'])?.stock).toBe('in');+ expect(stockOnPage(['In stock, back in stock alerts available.'])?.stock).toBe('in');+ // A shipping policy says nothing of this product's stock.+ expect(stockOnPage(['Orders for items in stock ship within 24 hours.'])).toBeNull();+ expect(stockOnPage(['Items not in stock ship within 3 weeks.'])).toBeNull();+ expect(stockOnPage(['Ships today.'])).toBeNull();+ expect(stockOnPage(['A daypack for wet hikes.'])).toBeNull();+ });+});++describe('feedStock', () => {+ it('is in when a variant is, out when every one is, and none for pre-orders', () => {+ expect(feedStock([variant({ availability: 'out_of_stock' }), variant()])).toBe('in');+ expect(feedStock([variant({ availability: 'out of stock' })])).toBe('out');+ expect(feedStock([variant({ availability: 'preorder' })])).toBeNull();+ expect(feedStock([variant({ availability: null })])).toBeNull();+ expect(feedStock([])).toBeNull();+ });+});++describe('feedCheck', () => {+ const texts = ['The Ridge 28 costs $129.', 'In stock.'];++ it('passes a page whose price and stock are the feed’s', () => {+ expect(+ feedCheck({ texts, offer: { price: 129, currency: 'USD' }, variants: [variant()] }),+ ).toEqual({ compared: 2, mismatches: [] });+ // A range is the feed's low and high; a sale price is the price now.+ expect(+ feedCheck({+ texts: ['Sizes run $119–$139.'],+ offer: { low: 119, high: 139, currency: 'USD' },+ variants: [variant({ price: 149, salePrice: 119 }), variant({ price: 139 })],+ }),+ ).toEqual({ compared: 1, mismatches: [] });+ });++ it('names a price, a GTIN or a stock that differs, with the sentence to show', () => {+ expect(+ feedCheck({+ texts,+ offer: { price: 129, currency: 'USD' },+ variants: [variant({ price: 119, availability: 'out_of_stock' })],+ }),+ ).toEqual({+ compared: 2,+ mismatches: [+ { kind: 'price', page: '$129', feed: '$119', sentence: 'The Ridge 28 costs $129.' },+ { kind: 'stock', page: 'in', feed: 'out', sentence: 'In stock.' },+ ],+ });+ // A range at the regular prices while the feed keeps an old sale.+ expect(+ feedCheck({+ texts: ['$139–$149.'],+ offer: { low: 139, high: 149, currency: 'USD' },+ variants: [variant({ price: 139, salePrice: 119 }), variant({ price: 149 })],+ }).mismatches,+ ).toEqual([]);+ // On sale in the feed: the sale price, or the regular one (the sale may be over).+ const onSale = [variant({ salePrice: 99.5 })];+ expect(+ feedCheck({ texts: ['$99.50.'], offer: { price: 99.5, currency: 'USD' }, variants: onSale })+ .mismatches,+ ).toEqual([]);+ expect(+ feedCheck({ texts: ['$129.'], offer: { price: 129, currency: 'USD' }, variants: onSale })+ .mismatches,+ ).toEqual([]);+ expect(+ feedCheck({ texts: ['$139.'], offer: { price: 139, currency: 'USD' }, variants: onSale })+ .mismatches[0],+ ).toMatchObject({ kind: 'price', page: '$139', feed: '$99.50' });+ // A GTIN's code alone, never the number after it; one that fails its check digit says nothing.+ expect(+ feedCheck({+ texts: ['UPC: 012345678905 12 months warranty.'],+ offer: null,+ variants: [variant({ gtin: '012345678905' })],+ }),+ ).toEqual({ compared: 1, mismatches: [] });+ expect(+ feedCheck({+ texts: ['EAN 1234567890123.'],+ offer: null,+ variants: [variant({ gtin: '4006381333931' })],+ }),+ ).toEqual({ compared: 0, mismatches: [] });+ // An EAN-8 by its label; all zeros is no product's code.+ expect(+ feedCheck({+ texts: ['EAN-8 96385074.'],+ offer: null,+ variants: [variant({ gtin: '96385074' })],+ }),+ ).toEqual({ compared: 1, mismatches: [] });+ expect(+ feedCheck({+ texts: ['EAN 0000000000000.'],+ offer: null,+ variants: [variant({ gtin: '4006381333931' })],+ }),+ ).toEqual({ compared: 0, mismatches: [] });+ // A GTIN the feed doesn't have; a UPC's leading zeros don't count.+ expect(+ feedCheck({+ texts: ['GTIN: 00012345678905.'],+ offer: null,+ variants: [variant({ gtin: '012345678905' })],+ }),+ ).toEqual({ compared: 1, mismatches: [] });+ expect(+ feedCheck({+ texts: ['EAN 4006381333931.'],+ offer: null,+ variants: [variant({ gtin: '4006381333948' })],+ }).mismatches,+ ).toEqual([+ {+ kind: 'gtin',+ page: '4006381333931',+ feed: '4006381333948',+ sentence: 'EAN 4006381333931.',+ },+ ]);+ });++ it('compares only what both state: no price, several, another currency, no stock', () => {+ const none = { compared: 0, mismatches: [] };+ expect(feedCheck({ texts: ['A daypack.'], offer: null, variants: [variant()] })).toEqual(none);+ expect(+ feedCheck({+ texts: ['$119. $139.'],+ offer: { several: ['$119', '$139'] },+ variants: [variant()],+ }),+ ).toEqual(none);+ expect(+ feedCheck({+ texts: ['€119.'],+ offer: { price: 119, currency: 'EUR' },+ variants: [variant({ availability: null })],+ }),+ ).toEqual(none);+ });+});diff --git a/web/src/lib/content/feed-match.ts b/web/src/lib/content/feed-match.tsnew file mode 100644index 000000000..9026ea96b--- /dev/null+++ b/web/src/lib/content/feed-match.ts@@ -0,0 +1,264 @@+import { factValueText, pagePrices } from './brand-facts';+import type { PageOfferRead } from './page-schema';+import { sentencesOf } from './readability';++/**+ * A product page against its product feed (Content Editor Quality spec §11,+ * CE-053): "Price and stock match the feed / Merchant Center". The feed is+ * the brand's catalog (00278, #1263), the product the page is for found by+ * its URL or its name. Its price, GTIN and stock are compared (the Rules+ * tab's "Price, GTIN and stock match the feed"), each only where both state+ * it: a page that gives no price, or a feed with no stock, isn't failed for+ * it.+ */++/** Where a brand's product feed is connected: Settings › Integrations' product catalog (#1263). */+export const CATALOG_SETTINGS_PATH = '/dashboard/settings/integrations';++/** A variant of the page's product as the feed gives it. */+export interface FeedVariant {+ price: number | null;+ salePrice: number | null;+ currency: string | null;+ availability: string | null;+ gtin: string | null;+}++/** The page's product in the brand's catalog, and how it was found. */+export interface CatalogProduct {+ title: string;+ url: string | null;+ /** By the page's own URL, or by its title (a new page has no URL yet). */+ via: 'url' | 'name';+ variants: FeedVariant[];+}++/** The catalog read for a draft: none connected, connected with no product for the page, or its product. */+export interface CatalogMatch {+ connected: boolean;+ product: CatalogProduct | null;+}++/** Where the page and the feed differ: Trust's suggestion names both. */+export type FeedMismatch = {+ /** The sentence the page says it in: Show goes there. */+ sentence: string;+} & (+ | {+ kind: 'price';+ /** The page's price as written ("$129"), the feed's as a price ("$119", "$119–$139"). */+ page: string;+ feed: string;+ }+ | { kind: 'stock'; page: 'in' | 'out'; feed: 'in' | 'out' }+ /** A GTIN (EAN, UPC) the page gives that no variant in the feed has; the feed's first. */+ | { kind: 'gtin'; page: string; feed: string }+);++/** A page's address as feeds write it: host without "www.", path without the trailing slash, no query. */+export function pageKey(url: string | null | undefined): string | null {+ if (!url) return null;+ try {+ const u = new URL(url.trim());+ if (u.protocol !== 'http:' && u.protocol !== 'https:') return null;+ // A path as written ("/ürün"), whether the address has it encoded or not.+ let path = u.pathname.replace(/\/+$/, '');+ try {+ path = decodeURIComponent(path);+ } catch {+ // Not encoded as UTF-8: compared as it is.+ }+ return `${u.hostname.toLowerCase().replace(/^www\./, '')}${path}`.toLowerCase();+ } catch {+ return null;+ }+}++const OUT_OF_STOCK =+ /(?<!\p{L})(?:out\s+of\s+stock|sold\s+out|currently\s+unavailable|(?:not|no\s+longer|isn['’]?t|aren['’]?t)\s+(?:currently\s+)?in\s+stock|(?:notify|email|tell|alert|let)\s+(?:me|us|you)?\s*(?:when|if|once)(?!\p{L})[^.]{0,40}?back\s+in\s+stock|stokta\s+(?:yok|değil|kalma|bulunma|mevcut\s+değil)\p{L}*|tükendi|ausverkauft|nicht\s+(?:mehr\s+)?(?:auf\s+lager|vorrätig|lieferbar)|épuisé|en\s+rupture(?:\s+de\s+stock)?|plus\s+en\s+stock|agotado|sin\s+stock)(?!\p{L})/iu;+const IN_STOCK =+ /(?<!\p{L})(?:in\s+stock|available\s+now|stokta(?!\s+(?:yok|değil|kalma|bulunma|mevcut\s+değil))|stoktan\s+teslim|auf\s+lager|vorrätig|sofort\s+lieferbar|en\s+stock)(?!\p{L})/iu;+/** A shipping policy's "items in stock ship in 24 hours": no word on this product's stock. */+const STOCK_POLICY =+ /(?<!\p{L})(?:items?|products?|orders?|articles?)\s+(?:(?:that|which)\s+are\s+)?(?:not\s+|no\s+longer\s+)?in\s+stock(?!\p{L})/iu;++/** What the page says of its stock, and where; none where it says nothing, or both. */+export function stockOnPage(+ texts: readonly string[],+): { stock: 'in' | 'out'; sentence: string } | null {+ let found: { stock: 'in' | 'out'; sentence: string } | null = null;+ for (const sentence of texts.flatMap((text) => sentencesOf(text))) {+ // A shipping policy first: "items not in stock ship in 3 weeks" says nothing of this one.+ const stock = STOCK_POLICY.test(sentence)+ ? null+ : OUT_OF_STOCK.test(sentence)+ ? 'out'+ : IN_STOCK.test(sentence)+ ? 'in'+ : null;+ if (!stock) continue;+ if (found && found.stock !== stock) return null;+ found ??= { stock, sentence };+ }+ return found;+}++/** The feed's stock: in when a variant is, out when every one is; none for pre-orders or none given. */+export function feedStock(variants: readonly FeedVariant[]): 'in' | 'out' | null {+ const read = variants.map((v) => {+ const a = (v.availability ?? '').toLowerCase().replace(/[\s-]+/g, '_');+ return ['in_stock', 'instock', 'available', 'limited_availability'].includes(a)+ ? 'in'+ : ['out_of_stock', 'outofstock', 'sold_out', 'discontinued'].includes(a)+ ? 'out'+ : null;+ });+ if (read.includes('in')) return 'in';+ return read.length && read.every((s) => s === 'out') ? 'out' : null;+}++/**+ * "GTIN: 00012345678905", "EAN 4006381333931", "ISBN 978-3-16-148410-0":+ * the code, hyphens allowed, never across a space ("UPC 012345678905 12+ * months" is the UPC alone).+ */+const GTIN_ON_PAGE =+ /(?<!\p{L})(?:gtin(?:-?(?:8|12|13|14))?|ean(?:-?(?:8|13))?|upc|isbn(?:-?13)?)\s*[:#]?\s*((?:\d-?){7,13}\d)(?![\d-])/iu;++/** A GTIN's own check: 8, 12, 13 or 14 digits, the last one GS1's check digit. */+function validGtin(digits: string): boolean {+ // All zeros pass the check digit, and are no product's.+ if (![8, 12, 13, 14].includes(digits.length) || !/[1-9]/.test(digits)) return false;+ const body = [...digits.slice(0, -1)].reverse().map(Number);+ const sum = body.reduce((total, d, i) => total + d * (i % 2 === 0 ? 3 : 1), 0);+ return (10 - (sum % 10)) % 10 === Number(digits.at(-1));+}++/** A GTIN as a number reads it: digits, leading zeros dropped (a UPC is a GTIN-14 with two). */+const gtinKey = (code: string) => code.replace(/\D/g, '').replace(/^0+/, '');++/** The GTINs the page gives, each with its sentence. */+function gtinsOnPage(texts: readonly string[]): { code: string; sentence: string }[] {+ return texts+ .flatMap((text) => sentencesOf(text))+ .flatMap((sentence) => {+ const m = GTIN_ON_PAGE.exec(sentence);+ const code = m?.[1].replace(/-/g, '') ?? '';+ // A number that isn't a GTIN's (its length or check digit) says nothing.+ return validGtin(code) ? [{ code, sentence }] : [];+ });+}++/** A variant's price now: its sale price under its price, else its price. */+const priceNow = (v: FeedVariant) =>+ v.salePrice !== null && (v.price === null || v.salePrice < v.price) ? v.salePrice : v.price;++const same = (a: number, b: number) => Math.abs(a - b) < 0.005;++/** An amount as a person reads it ("$119"), as brand facts write theirs. */+const money = (amount: number, currency: string) =>+ factValueText('price', { plan: '', amount, currency, period: null, billed: null, per: null });++/** The first sentence that gives an amount, as the page writes it. */+function priceSentence(+ texts: readonly string[],+ amount: number,+): { text: string; sentence: string } | null {+ for (const sentence of texts.flatMap((text) => sentencesOf(text))) {+ const price = pagePrices(sentence, { rangeEnds: true }).find((p) => same(p.amount, amount));+ if (price) return { text: price.text, sentence };+ }+ return null;+}++/**+ * The page against its product in the feed: its price (one, or the low and+ * high of a range, in the feed's currency, a sale price counting as the+ * price now), the GTINs it gives and its stock, each compared only where+ * both state it.+ */+export function feedCheck({+ texts,+ offer,+ variants,+}: {+ /** The page's blocks' text. */+ texts: readonly string[];+ /** The page's price (pageOffer). */+ offer: PageOfferRead;+ variants: readonly FeedVariant[];+}): { compared: number; mismatches: FeedMismatch[] } {+ const mismatches: FeedMismatch[] = [];+ let compared = 0;++ const priced = variants.flatMap((v) => {+ const now = priceNow(v);+ return now !== null && v.currency+ ? [{ now, regular: v.price, currency: v.currency.toUpperCase() }]+ : [];+ });+ if (offer && !('several' in offer)) {+ const inCurrency = priced.filter((p) => p.currency === offer.currency);+ const nows = inCurrency.map((p) => p.now);+ const regulars = inCurrency.flatMap((p) => (p.regular === null ? [] : [p.regular]));+ // Another currency is another market's feed: not compared.+ if (inCurrency.length) {+ compared += 1;+ const low = Math.min(...nows);+ const high = Math.max(...nows);+ const page = 'price' in offer ? offer.price : offer.low;+ // A sale price the feed keeps after the sale may be over: the regular+ // price matches too.+ const matches =+ 'price' in offer+ ? inCurrency.some(+ (p) =>+ same(p.now, offer.price) || (p.regular !== null && same(p.regular, offer.price)),+ )+ : (same(offer.low, low) && same(offer.high, high)) ||+ (regulars.length > 0 &&+ same(offer.low, Math.min(...regulars)) &&+ same(offer.high, Math.max(...regulars)));+ if (!matches) {+ const at = priceSentence(texts, page);+ mismatches.push({+ kind: 'price',+ page:+ 'price' in offer+ ? (at?.text ?? money(offer.price, offer.currency))+ : `${money(offer.low, offer.currency)}–${money(offer.high, offer.currency)}`,+ feed: same(low, high)+ ? money(low, offer.currency)+ : `${money(low, offer.currency)}–${money(high, offer.currency)}`,+ sentence: at?.sentence ?? '',+ });+ }+ }+ }++ const fedGtins = variants.flatMap((v) => (v.gtin ? [v.gtin] : []));+ const pageGtins = gtinsOnPage(texts);+ if (pageGtins.length && fedGtins.length) {+ compared += 1;+ const known = new Set(fedGtins.map(gtinKey));+ const wrong = pageGtins.find((g) => !known.has(gtinKey(g.code)));+ if (wrong) {+ mismatches.push({+ kind: 'gtin',+ page: wrong.code,+ feed: fedGtins[0],+ sentence: wrong.sentence,+ });+ }+ }++ const said = stockOnPage(texts);+ const fed = feedStock(variants);+ if (said && fed) {+ compared += 1;+ if (said.stock !== fed) {+ mismatches.push({ kind: 'stock', page: said.stock, feed: fed, sentence: said.sentence });+ }+ }+ return { compared, mismatches };+}diff --git a/web/src/lib/content/quality-checks.test.ts b/web/src/lib/content/quality-checks.test.tsindex 3a61c1beb..2cef1e846 100644--- a/web/src/lib/content/quality-checks.test.ts+++ b/web/src/lib/content/quality-checks.test.ts@@ -803,6 +803,39 @@ describe('trust: a product page’s shipping and returns (Phase 3, CE-052)', ()});});+describe('trust: a product page’s price and stock against its feed (Phase 3, CE-053)', () => {+ const NOW = Date.parse('2026-10-25');++ it('counts the share that matches, names what differs, and is left out where not compared', () => {+ const run = (feed: Parameters<typeof trust>[0]['feed']) =>+ trust({+ blocks: trustBlocks('<p>The Ridge 28 costs $129.</p>'),+ links: new Map(),+ brandDomains: ['acme.com'],+ feed,+ now: NOW,+ });+ const differs = {+ kind: 'price' as const,+ page: '$129',+ feed: '$119',+ sentence: 'The Ridge 28 costs $129.',+ };+ const read = run({ compared: 2, mismatches: [differs] });+ expect(read.checks.find((c) => c.id === 'feedMatch')).toEqual({+ id: 'feedMatch',+ points: 5,+ max: 10,+ });+ expect(read.feed).toEqual([differs]);+ expect(run({ compared: 0, mismatches: [] }).checks.some((c) => c.id === 'feedMatch')).toBe(+ false,+ );+ expect(run(null).checks.some((c) => c.id === 'feedMatch')).toBe(false);+ expect(run(null).feed).toEqual([]);+ });+});+describe('eeat: customer cases (Phase 3, CE-052)', () => {it('counts the share confirmed publishable, and none where the page has no case', () => {const check = (cases: { total: number; confirmed: number } | null) =>diff --git a/web/src/lib/content/quality-checks.ts b/web/src/lib/content/quality-checks.tsindex 4126d90da..9297f278a 100644--- a/web/src/lib/content/quality-checks.ts+++ b/web/src/lib/content/quality-checks.ts@@ -3,6 +3,7 @@ import type { ContentAuthor } from './authors';import { cleanHref } from './html-allowlist';import { languageCode, ownText, sentencesOf } from './readability';import type { FactMismatch } from './brand-facts';+import type { FeedMismatch } from './feed-match';import type { ClaimBlock } from './claims';import { askableSite, sourceClass, type AiSourceClass, type SourceClass } from './source-class';@@ -75,11 +76,16 @@ export const TRUST_WEIGHTS = {siteTrust: 5,// Phase 3 (CE-052): a product page's shipping and returns; weighed there.shippingReturns: 0,+ // Phase 3 (CE-053): a product page's price and stock against its product+ // feed; weighed there, and only where the feed has the page's product.+ feedMatch: 0,} as const;export type TrustCheckId = keyof typeof TRUST_WEIGHTS;/** The shipping and returns check's points before a page type weighs it. */const SHIPPING_POINTS = 10;+/** The product feed check's points before a page type weighs it. */+const FEED_POINTS = 10;/*** Words that say how a product ships, in a policy's terms: "free shipping",* "shipping takes 2 days", "Free UK delivery on orders over £50", "Standard@@ -540,6 +546,8 @@ export interface TrustRead extends Score<TrustCheckId> {mismatches: FactMismatch[];/** Phase 3 (CE-052): whether the page says how shipping and returns work; null where not read. */shipping?: { shipping: boolean; returns: boolean } | null;+ /** Phase 3 (CE-053): where the page's price and stock differ from its product feed's. */+ feed?: FeedMismatch[];}/**@@ -569,10 +577,10 @@ export interface SourceRead {* links that answer, and the site's trust (its five checks in Site Audit).* A check with nothing to read (no figure, no dated source, no link read* yet, no site trust read) is left out, and site trust counts only beside a- * check of the page's own. 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.+ * check of the page's own. Trust is scored only once a figure, a dated+ * source or a product feed's check 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.** With `sources` (Phase 2, CE-046), each source's kind counts too: a primary* one among them (official, research, standards), and none weak (forums,@@ -609,8 +617,14 @@ export function trust({proofs = null,page = null,shipping = null,+ feed = null,now,}: {+ /**+ * Phase 3 (CE-053): a product page's price and stock against its product+ * in the brand's feed (feedCheck); left out where the feed doesn't have it.+ */+ feed?: { compared: number; mismatches: FeedMismatch[] } | null;/*** Phase 3 (CE-052): whether a product page says how shipping and returns* work (shippingOnPage); left out elsewhere.@@ -811,6 +825,14 @@ export function trust({});}+ if (feed && feed.compared > 0) {+ checks.push({+ id: 'feedMatch',+ points: (FEED_POINTS * (feed.compared - feed.mismatches.length)) / feed.compared,+ max: FEED_POINTS,+ });+ }+// The site's 5 points weigh with what the page itself shows: alone, they'd// be the page's whole Trust.if (siteTrust && checks.length) {@@ -821,9 +843,11 @@ export function trust({});}+ // A product page's feed check is Trust's own too (CE-053).const scored =- checks.some((c) => c.id === 'claimsSourced' || c.id === 'freshSources') ||- classified.length >= 2;+ checks.some(+ (c) => c.id === 'claimsSourced' || c.id === 'freshSources' || c.id === 'feedMatch',+ ) || classified.length >= 2;return {...(scored ? scoreOf(checks) : { score: null, checks }),broken: broken.map(({ url, text }) => ({ url, text })),@@ -837,6 +861,7 @@ export function trust({classified: classified.length,mismatches: brandFacts?.mismatches ?? [],shipping: shippingSaid,+ feed: feed?.mismatches ?? [],};}diff --git a/web/src/lib/content/quality-profiles.test.ts b/web/src/lib/content/quality-profiles.test.tsindex 3ed5dddac..6da876e11 100644--- a/web/src/lib/content/quality-profiles.test.ts+++ b/web/src/lib/content/quality-profiles.test.ts@@ -54,14 +54,19 @@ describe('PROFILE_WEIGHTS', () => {it('asks a product page for no author, and a comparison for balance and a disclosure', () => {expect(checksOff('product')).toContain('byline');expect(checksOff('product')).toContain('authorBio');- // An article counts every check but the brand's information, the check date, shipping and the type rules.+ // An article counts every check but the brand's information, the check+ // date, customer cases, shipping, the product feed and the type rules.expect([...checksOff('article')].sort()).toEqual(['brandInfo','checkDate','customerCase',+ 'feedMatch','shippingReturns','typeRules',]);+ // A product page's price and stock against its feed weigh most in its Trust (CE-053).+ const productTrust = Object.values(PROFILE_WEIGHTS.product.trust);+ expect(PROFILE_WEIGHTS.product.trust.feedMatch).toBe(Math.max(...productTrust));expect(PROFILE_WEIGHTS.comparison.trust.balanced).toBeGreaterThan(PROFILE_WEIGHTS.article.trust.balanced,);@@ -162,12 +167,21 @@ describe('weighedTrust', () => {// A product page doesn't weigh freshness: a working link and the site aren't Trust.const product = weighedTrust(dated, PROFILE_WEIGHTS.product.trust);expect(product.score).toBeNull();- expect(product.phase1Points).toBe(35);+ expect(product.phase1Points).toBe(25);// A figure brings it in.const figure = read('<p>It cut costs by 40% (<a href="https://example.org/report">the report</a>).</p>',);expect(weighedTrust(figure, PROFILE_WEIGHTS.product.trust).score).not.toBeNull();+ // So does its product feed's check (CE-053).+ const fed = trust({+ blocks: trustBlocks('<p>The Ridge 28 costs $129.</p>'),+ links: new Map(),+ brandDomains: [],+ feed: { compared: 1, mismatches: [] },+ now: Date.parse('2026-10-25'),+ });+ expect(weighedTrust(fed, PROFILE_WEIGHTS.product.trust).score).toBe(100);});it('is scored by a compared price where brand facts weigh as much as sourced claims (#1491 review)', () => {diff --git a/web/src/lib/content/quality-profiles.ts b/web/src/lib/content/quality-profiles.tsindex 714a7896d..ca37d2952 100644--- a/web/src/lib/content/quality-profiles.ts+++ b/web/src/lib/content/quality-profiles.ts@@ -60,9 +60,9 @@ export interface ProfileWeights {/*** Each profile's checks and points. The article's are the spec's blog- * defaults (§2); the others follow §11's table. Checks a type still lacks- * (reviews, a product feed, a customer case, a check date: Phase 3's later- * parts) join with their own points, rescaling the rest.+ * defaults (§2); the others follow §11's table. A check a page can't be+ * read for yet (a product feed that doesn't have the page's product, and+ * reviews, not connected yet) is left out, the rest rescaled.*/export const PROFILE_WEIGHTS: Readonly<Record<QualityProfile, ProfileWeights>> = {article: {@@ -71,8 +71,8 @@ export const PROFILE_WEIGHTS: Readonly<Record<QualityProfile, ProfileWeights>> =readability: { ...READABILITY_WEIGHTS },},// No author (the brand's byline); real product photos; proof for its- // claims, prices that match, how it ships and goes back; short, plain- // copy with its specs table.+ // claims, the price and stock its feed has (most), how it ships and goes+ // back; short, plain copy with its specs table.product: {eeat: {experience: 20,@@ -88,17 +88,18 @@ export const PROFILE_WEIGHTS: Readonly<Record<QualityProfile, ProfileWeights>> =customerCase: 0,},trust: {- claimsSourced: 25,+ claimsSourced: 20,primarySources: 5,noWeakSources: 5,- brandFacts: 30,+ brandFacts: 20,expertQuote: 0,freshSources: 0,balanced: 0,disclosure: 0,- noBrokenLinks: 10,- siteTrust: 15,+ noBrokenLinks: 5,+ siteTrust: 10,shippingReturns: 10,+ feedMatch: 25,},readability: {avgSentence: 15,@@ -140,6 +141,7 @@ export const PROFILE_WEIGHTS: Readonly<Record<QualityProfile, ProfileWeights>> =noBrokenLinks: 15,siteTrust: 25,shippingReturns: 0,+ feedMatch: 0,},readability: {avgSentence: 15,@@ -181,6 +183,7 @@ export const PROFILE_WEIGHTS: Readonly<Record<QualityProfile, ProfileWeights>> =noBrokenLinks: 5,siteTrust: 10,shippingReturns: 0,+ feedMatch: 0,},readability: {avgSentence: 15,@@ -223,6 +226,7 @@ export const PROFILE_WEIGHTS: Readonly<Record<QualityProfile, ProfileWeights>> =noBrokenLinks: 5,siteTrust: 5,shippingReturns: 0,+ feedMatch: 0,},readability: {avgSentence: 15,@@ -278,11 +282,12 @@ export function weighed<Id extends string, S extends Score<Id>>(}/**- * Trust weighed for a profile, scored as trust() scores it: once a figure- * or fresh-sources check is left among the weighed ones, or two sources are- * placed; on a type that weighs brand facts as much as sourced claims, once- * a price is compared with them too. A type isn't scored by its links and- * site alone. Its unscored gains count out of the type's Phase 1 points.+ * Trust weighed for a profile, scored as trust() scores it: once a figure,+ * fresh-sources or product feed check is left among the weighed ones, or+ * two sources are placed; on a type that weighs brand facts as much as+ * sourced claims, once a price is compared with them too. A type isn't+ * scored by its links and site alone. Its unscored gains count out of the+ * type's Phase 1 points.*/export function weighedTrust(read: TrustRead,@@ -291,7 +296,9 @@ export function weighedTrust(// Scored here, by the weighed checks: trust() leaves it unscored by its own.const result = weighed({ ...read, score: read.score ?? 0 }, weights);const scored =- result.checks.some((c) => c.id === 'claimsSourced' || c.id === 'freshSources') ||+ result.checks.some(+ (c) => c.id === 'claimsSourced' || c.id === 'freshSources' || c.id === 'feedMatch',+ ) ||read.classified >= 2 ||// Where prices that match weigh as much as sourced claims (a product or a// category page), a compared one is Trust's own: every price wrong isn't "Not scored".diff --git a/web/src/lib/content/rules.test.ts b/web/src/lib/content/rules.test.tsindex e99ec87ad..89dde6448 100644--- a/web/src/lib/content/rules.test.ts+++ b/web/src/lib/content/rules.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';import {NO_DRAFT_RULES,NOT_FOR_AGENT,+ notForAgentMessage,fanoutsToUse,openRulesForAgent,activeRules,@@ -445,6 +446,45 @@ describe('page type rules', () => {});});+ it('checks a product page against its product in the feed, once one is connected (CE-053)', () => {+ const feed = (html: string, catalog: RuleContext['catalog']) =>+ checkRule(rule('feedMatch', 'product_page'), page(html), { ...ctx, catalog });+ const product = (price: number, availability = 'in_stock') => ({+ connected: true,+ product: {+ title: 'Ridge 28',+ url: 'https://acme.example/products/ridge-28',+ via: 'url' as const,+ variants: [{ price, salePrice: null, currency: 'USD', availability, gtin: null }],+ },+ });+ const html = '<p>The Ridge 28 costs $129.</p><p>In stock.</p>';+ expect(feed(html, null)).toEqual({ state: 'info', code: 'needsFeed' });+ expect(feed(html, 'reading')).toEqual({ state: 'info', code: 'feedReading' });+ expect(feed(html, { connected: false, product: null })).toEqual({+ state: 'info',+ code: 'needsFeed',+ });+ expect(feed(html, { connected: true, product: null })).toEqual({+ state: 'info',+ code: 'notInFeed',+ });+ expect(feed('<p>A daypack.</p>', product(129))).toEqual({ state: 'info', code: 'feedNothing' });+ expect(feed(html, product(129))).toEqual({ state: 'ok' });+ expect(feed(html, product(119, 'out_of_stock'))).toEqual({+ state: 'bad',+ code: 'feedDiffers',+ count: 2,+ });+ // The person checks which is right, the page or the feed: not the agent's,+ // and the message says so (the extra H1s' first, when both are open).+ expect(NOT_FOR_AGENT.has('feedMatch')).toBe(true);+ expect(notForAgentMessage([{ rule: { key: 'feedMatch' } }])).toBe('notForAgentFeed');+ expect(notForAgentMessage([{ rule: { key: 'feedMatch' } }, { rule: { key: 'oneH1' } }])).toBe(+ 'notForAgent',+ );+ });+it('checks a product and a category page', () => {expect(check('feedMatch', '<p>x</p>', undefined, 'product_page')).toEqual({state: 'info',diff --git a/web/src/lib/content/rules.ts b/web/src/lib/content/rules.tsindex 9f117d4e2..c1cffdc0c 100644--- a/web/src/lib/content/rules.ts+++ b/web/src/lib/content/rules.ts@@ -3,7 +3,9 @@ import { LANGUAGES } from '@/config/prompt-options';import { classifyDomain, normalizeDomain } from '@/lib/citations/classify';import { PAGE_TYPES, type DraftMethod, type PageType } from '@/lib/content/drafts';import { lengthTarget } from '@/lib/content/editor';+import { feedCheck, type CatalogMatch } from '@/lib/content/feed-match';import { decodeHtmlBlock } from '@/lib/content/html-allowlist';+import { pageOffer } from '@/lib/content/page-schema';import { countWords, languageCode } from '@/lib/content/readability';import { wordsOf } from '@/lib/content/sources';@@ -595,6 +597,8 @@ export type RuleStatus =/** Out of the Length rule's band, as it reads (lengthBand). */| { state: 'bad'; code: 'short' | 'long'; count: number; min: number; max: number }| { state: 'bad'; code: 'words'; count: number }+ /** The page's price, GTIN or stock differs from its product's in the feed (CE-053). */+ | { state: 'bad'; code: 'feedDiffers'; count: number }| { state: 'bad'; code: 'missing' | 'noH2' | 'notSet' }/** No FAQ yet: the fan-outs its questions should use, the most searched first. */| { state: 'bad'; code: 'needsFaq'; missing?: string[] }@@ -603,6 +607,9 @@ export type RuleStatus =code:| 'aiCheck'| 'needsFeed'+ | 'feedReading'+ | 'notInFeed'+ | 'feedNothing'| 'noFanouts'| 'addKeywords'| 'notHowTo'@@ -617,6 +624,12 @@ export interface RuleContext {fanouts: string[];/** The brand's language (brands.language); none reads as English. */language?: string | null;+ /**+ * The page's product in the brand's catalog (getCatalogMatch, Quality+ * CE-053), for "Price, GTIN and stock match the feed": 'reading' while it+ * is read; none where the feed isn't checked (before Phase 3, other types).+ */+ catalog?: CatalogMatch | 'reading' | null;}/** Phrases that read as machine-written (spec §10, "Remove AI traces"). */@@ -748,9 +761,15 @@ const atLeast = (have: number, want: number): RuleStatus =>/*** Rules the Content Agent can't fix: it changes words and adds blocks, never- * a heading's level, so a page's extra H1s are made H2s in the editor.+ * a heading's level, so a page's extra H1s are made H2s in the editor; a+ * price, GTIN or stock that differs from the feed is the person's to check+ * (the page or the feed may be the one that's wrong).*/-export const NOT_FOR_AGENT = new Set(['oneH1']);+export const NOT_FOR_AGENT = new Set(['oneH1', 'feedMatch']);++/** What to do instead, for the open rules the agent doesn't fix: its message's key. */+export const notForAgentMessage = (open: readonly { rule: { key: string } }[]) =>+ open.some(({ rule }) => rule.key === 'oneH1') ? 'notForAgent' : 'notForAgentFeed';/*** The fan-outs a rule still needs (fanoutH2, fanoutFaq), quoted for the@@ -888,9 +907,32 @@ export function rewriteAdvice<T extends { rule: ActiveRule; status: RuleStatus }return open >= REWRITE_OPEN_RULES ? { reason: 'open', count: open } : null;}+/**+ * "Price, GTIN and stock match the feed" (CE-053): the page against its+ * product in the brand's catalog, once a catalog is connected and has it.+ */+function feedStatus(+ page: PageRead,+ catalog: CatalogMatch | 'reading' | null | undefined,+): RuleStatus {+ if (catalog === 'reading') return { state: 'info', code: 'feedReading' };+ if (!catalog?.connected) return { state: 'info', code: 'needsFeed' };+ if (!catalog.product) return { state: 'info', code: 'notInFeed' };+ const texts = page.blocks.map((b) => b.text);+ const { compared, mismatches } = feedCheck({+ texts,+ offer: pageOffer(texts),+ variants: catalog.product.variants,+ });+ if (!compared) return { state: 'info', code: 'feedNothing' };+ return mismatches.length+ ? { state: 'bad', code: 'feedDiffers', count: mismatches.length }+ : { state: 'ok' };+}+/** Checks one rule against the page as written. */export function checkRule(rule: ActiveRule, page: PageRead, ctx: RuleContext): RuleStatus {- if (rule.check === 'feed') return { state: 'info', code: 'needsFeed' };+ if (rule.check === 'feed') return feedStatus(page, ctx.catalog);if (rule.key === 'whoFor' && !rule.current.trim()) return { state: 'bad', code: 'notSet' };if (rule.check === 'ai') return { state: 'info', code: 'aiCheck' };diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex ab0fe1dd3..445c5d96b 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -937,6 +937,93 @@ export type Database = {},]}+ catalog_variants: {+ Row: {+ attributes: Json+ availability: string | null+ brand_id: string+ condition: string | null+ content_hash: string+ currency: string | null+ external_id: string+ first_seen_at: string+ gtin: string | null+ id: string+ marketplace_item_id: string | null+ mpn: string | null+ price: number | null+ product_id: string+ removed_at: string | null+ sale_price: number | null+ sku: string | null+ source: string+ title: string | null+ updated_at: string+ url: string | null+ }+ Insert: {+ attributes?: Json+ availability?: string | null+ brand_id: string+ condition?: string | null+ content_hash: string+ currency?: string | null+ external_id: string+ first_seen_at?: string+ gtin?: string | null+ id?: string+ marketplace_item_id?: string | null+ mpn?: string | null+ price?: number | null+ product_id: string+ removed_at?: string | null+ sale_price?: number | null+ sku?: string | null+ source: string+ title?: string | null+ updated_at?: string+ url?: string | null+ }+ Update: {+ attributes?: Json+ availability?: string | null+ brand_id?: string+ condition?: string | null+ content_hash?: string+ currency?: string | null+ external_id?: string+ first_seen_at?: string+ gtin?: string | null+ id?: string+ marketplace_item_id?: string | null+ mpn?: string | null+ price?: number | null+ product_id?: string+ removed_at?: string | null+ sale_price?: number | null+ sku?: string | null+ source?: string+ title?: string | null+ updated_at?: string+ url?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "catalog_variants_brand_id_fkey"+ columns: ["brand_id"]+ isOneToOne: false+ referencedRelation: "brands"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "catalog_variants_product_id_fkey"+ columns: ["product_id"]+ isOneToOne: false+ referencedRelation: "catalog_products"+ referencedColumns: ["id"]+ },+ ]+ }citation_urls: {Row: {domain: string