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
fix(shopping): sharper "Why not you?", "What AI says" and product page, and an honest 7-day re-check (Product Visibility follow-ups, part 3) (#1667)
Cihan3052f6b95ddd
diff --git a/web/messages/en.json b/web/messages/en.jsonindex 424bf4f1a..8dc784e18 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -8145,13 +8145,19 @@"pending": "Done {done}. Its result shows on {ready}, 7 days on.","result": "In the 7 days after it was done, on {after} of {afterShelves, plural, one {# shelf} other {# shelves}}. In the 7 days before, on {before} of {beforeShelves}.","noRuns": "Done {done}. No shopping answers were read in the 7 days after it, so there's nothing to compare.",+ "tooMany": "Done {done}. Its questions have too many answers to read them all, so the 7 days before and after aren't compared.",+ "resultNew": "In the 7 days after it was done, on {after} of {afterShelves, plural, one {# shelf} other {# shelves}}. None of its shelves was read in the 7 days before.","trend": {"better": "On more of its shelves","worse": "On fewer of its shelves",- "same": "No change"+ "same": "No change",+ "new": "New: nothing to compare"},"open": "Open the action","short": "#{number}: {before}/{beforeShelves} → {after}/{afterShelves} shelves",+ "shortNew": "#{number}: new · {after}/{afterShelves} shelves",+ "shortNoRuns": "#{number} done · not run in the 7 days after",+ "shortTooMany": "#{number} done · too many answers to compare","shortPending": "#{number} done · result {ready}"},"detail": {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_action-result.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_action-result.tsxindex 9fe1f22e2..49886ae7c 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_action-result.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_action-result.tsx@@ -1,7 +1,7 @@'use client';import { useTranslations } from 'next-intl';-import { ArrowRight, Minus, TrendingDown, TrendingUp } from 'lucide-react';+import { ArrowRight, Minus, Sparkles, TrendingDown, TrendingUp } from 'lucide-react';import { Link } from '@/i18n/navigation';import { buttonVariants } from '@/components/ui/button-variants';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';@@ -27,6 +27,8 @@ const TREND = {tone: 'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-900 dark:bg-amber-950/40 dark:text-amber-400',},same: { icon: Minus, tone: 'bg-muted text-muted-foreground' },+ // No shelf read the week before: nothing to compare yet.+ new: { icon: Sparkles, tone: 'border-primary/30 bg-primary/10 text-primary' },} as const;export function ActionResultCard({ result }: { result: ActionResult }) {@@ -56,14 +58,18 @@ export function ActionResultCard({ result }: { result: ActionResult }) {<p className="text-sm text-muted-foreground">{result.after === null? t('pending', { done, ready: formatDate(result.readyAt) })- : result.after.shelves === 0- ? t('noRuns', { done })- : t('result', {- after: result.after.on,- afterShelves: result.after.shelves,- before: result.before.on,- beforeShelves: result.before.shelves,- })}+ : result.partial+ ? t('tooMany', { done })+ : result.after.shelves === 0+ ? t('noRuns', { done })+ : trend === 'new'+ ? t('resultNew', { after: result.after.on, afterShelves: result.after.shelves })+ : t('result', {+ after: result.after.on,+ afterShelves: result.after.shelves,+ before: result.before.on,+ beforeShelves: result.before.shelves,+ })}</p><Linkhref={actionHref(result)}@@ -96,13 +102,23 @@ export function ActionResultLine({ result }: { result: ActionResult | undefined>{result.after === null? t('shortPending', { number: result.actionNo, ready: formatDate(result.readyAt) })- : t('short', {- number: result.actionNo,- before: result.before.on,- beforeShelves: result.before.shelves,- after: result.after.on,- afterShelves: result.after.shelves,- })}+ : result.partial+ ? t('shortTooMany', { number: result.actionNo })+ : result.after.shelves === 0+ ? t('shortNoRuns', { number: result.actionNo })+ : trend === 'new'+ ? t('shortNew', {+ number: result.actionNo,+ after: result.after.on,+ afterShelves: result.after.shelves,+ })+ : t('short', {+ number: result.actionNo,+ before: result.before.on,+ beforeShelves: result.before.shelves,+ after: result.after.on,+ afterShelves: result.after.shelves,+ })}</Link>);}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_categories-table.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_categories-table.test.tsxindex d6b16e6b9..6dc908d0e 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/_categories-table.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/_categories-table.test.tsx@@ -132,6 +132,62 @@ describe('CategoriesTable', () => {]);});+ it('says a category whose shelves were not run after its action, or not before it, apart', () => {+ const done = {+ actionId: 'a9',+ actionNo: 9,+ completedAt: '2026-10-12T09:00:00Z',+ readyAt: '2026-10-19T09:00:00Z',+ before: { shelves: 5, on: 1 },+ after: { shelves: 0, on: 0 },+ };+ render(+ <CategoriesTable+ categories={[row({}), row({ id: 'packs', leaf: 'Hiking backpacks' })]}+ loading={false}+ failed={false}+ results={{+ 'category:shoes': done,+ 'category:packs': {+ ...done,+ actionId: 'a10',+ actionNo: 10,+ before: { shelves: 0, on: 0 },+ after: { shelves: 3, on: 2 },+ },+ }}+ />,+ );+ expect([...container.querySelectorAll('tbody a')].map((a) => a.textContent)).toEqual([+ '#9 done · not run in the 7 days after',+ '#10: new · 2/3 shelves',+ ]);+ });++ it('says a category whose answers were too many to read all is not compared', () => {+ render(+ <CategoriesTable+ categories={[row({})]}+ loading={false}+ failed={false}+ results={{+ 'category:shoes': {+ actionId: 'a9',+ actionNo: 9,+ completedAt: '2026-10-12T09:00:00Z',+ readyAt: '2026-10-19T09:00:00Z',+ before: { shelves: 0, on: 0 },+ after: { shelves: 3, on: 2 },+ partial: true,+ },+ }}+ />,+ );+ const link = container.querySelector('tbody a')!;+ expect(link.textContent).toBe('#9 done · too many answers to compare');+ expect(link.className).toContain('text-muted-foreground');+ });+it("plans a category's actions in a dialog, measured on its questions", async () => {sendShoppingActions.mockResolvedValue({ actionId: 'a1', actionNo: 302, created: true });render(diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.test.tsxindex c947fe458..34b4d3a87 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.test.tsx@@ -207,6 +207,19 @@ describe('ShoppingProductPage', () => {).toBe('Open the action');});+ it('says new, not better, when none of its shelves was read the week before', async () => {+ getShoppingProductDetail.mockResolvedValue({+ ...detail,+ result: { ...result, before: { shelves: 0, on: 0 } },+ });+ const text = await render();+ expect(text).toContain('New: nothing to compare');+ expect(text).not.toContain('On more of its shelves');+ expect(text).toContain(+ 'In the 7 days after it was done, on 2 of 4 shelves. None of its shelves was read in the 7 days before.',+ );+ });+it('says when a done action’s result shows', async () => {getShoppingProductDetail.mockResolvedValue({ ...detail, result: { ...result, after: null } });const text = await render();@@ -267,4 +280,11 @@ describe('ShoppingProductPage', () => {gate.allowed = false;expect(await render()).toContain('Product Visibility comes with the Growth plan.');});++ it('reads nothing while the plan locks the page', async () => {+ gate.allowed = false;+ expect(await render()).toContain('Product Visibility comes with the Growth plan.');+ expect(getShoppingProductDetail).not.toHaveBeenCalled();+ expect(getProductAiSays).not.toHaveBeenCalled();+ });});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.tsxindex 7fd69b3d3..df903b0c3 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/shopping/products/[productId]/page.tsx@@ -33,6 +33,8 @@ export default function ShoppingProductPage() {const platform = search.get('platform');const activeBrandId = useBrandStore((s) => s.activeBrandId);const { canUse } = useFeatureGate();+ // A plan without Product Visibility reads nothing: the page says it's locked.+ const allowed = canUse('shopping_analytics');const [read, setRead] = useState<{key: string;detail: ShoppingProductDetail | null | 'failed';@@ -42,7 +44,7 @@ export default function ShoppingProductPage() {const saysKey = `${activeBrandId}:${productId}`;useEffect(() => {- if (!activeBrandId || !productId) return;+ if (!allowed || !activeBrandId || !productId) return;let cancelled = false;getShoppingProductDetail(activeBrandId,@@ -60,10 +62,10 @@ export default function ShoppingProductPage() {return () => {cancelled = true;};- }, [activeBrandId, productId, key, prompt, platform]);+ }, [allowed, activeBrandId, productId, key, prompt, platform]);useEffect(() => {- if (!activeBrandId || !productId) return;+ if (!allowed || !activeBrandId || !productId) return;let cancelled = false;getProductAiSays(activeBrandId, productId, { datePreset: '30d' }).then((read) => {@@ -76,7 +78,7 @@ export default function ShoppingProductPage() {return () => {cancelled = true;};- }, [activeBrandId, productId, saysKey]);+ }, [allowed, activeBrandId, productId, saysKey]);const back = (<Link@@ -89,16 +91,12 @@ export default function ShoppingProductPage() {);const detail = read?.key === key ? read.detail : undefined;- if (!canUse('shopping_analytics') || detail === null || detail === 'failed') {+ if (!allowed || detail === null || detail === 'failed') {return (<div className="space-y-6">{back}<p className="rounded-lg border border-dashed px-4 py-10 text-center text-sm text-muted-foreground">- {!canUse('shopping_analytics')- ? t('locked')- : detail === 'failed'- ? t('failed')- : t('notFound')}+ {!allowed ? t('locked') : detail === 'failed' ? t('failed') : t('notFound')}</p></div>);diff --git a/web/src/lib/actions/shopping-product-detail.test.ts b/web/src/lib/actions/shopping-product-detail.test.tsindex 2de9cf29f..94b91834c 100644--- a/web/src/lib/actions/shopping-product-detail.test.ts+++ b/web/src/lib/actions/shopping-product-detail.test.ts@@ -1,4 +1,5 @@import { beforeEach, describe, expect, it, vi } from 'vitest';+import { resultTrend } from '@/lib/shopping/recheck';/** A product's page read (ECOM-011). */@@ -11,13 +12,15 @@ let filtered: [string, string, number][];let rpcArgs: Record<string, unknown>[];// The id lists the catalog reads filtered by, as [table, column, the ids].let byIds: [string, string, unknown[]][];+// The equality filters each read made, as [table, column, value].+let eqs: [string, string, unknown][];function query(table: string) {let range: [number, number] | undefined;let single = false;const q = {select: () => q,- eq: () => q,+ eq: (column: string, value: unknown) => (eqs.push([table, column, value]), q),is: () => q,in: (column: string, values: unknown[]) => (filtered.push([table, column, values.length]),@@ -56,13 +59,15 @@ vi.mock('@/lib/supabase/server', () => ({})),}));-const { getProductAiSays, getShoppingProductDetail } = await import('./shopping');+const { getProductAiSays, getShoppingActionResults, getShoppingProductDetail } =+ await import('./shopping');beforeEach(() => {tables = {};filtered = [];rpcArgs = [];byIds = [];+ eqs = [];});const card = (over: Record<string, unknown>) => ({@@ -80,17 +85,20 @@ const card = (over: Record<string, unknown>) => ({matched_brand_role: 'competitor',catalog_product_id: null,prompt_results: {- search_queries: [{ query: 'women hiking backpack' }],- prompt: { id: 'q1', text: 'lightweight 30L hiking backpack for women' },+ prompt_id: 'q1',+ prompt: { text: 'lightweight 30L hiking backpack for women' },},...over,});describe('getShoppingProductDetail', () => {- it("refuses ids that aren't ids, and reads a product not in the catalog as none", async () => {- await expect(getShoppingProductDetail(BRAND, 'nope', { datePreset: '30d' })).rejects.toThrow(+ it("refuses a brand id that isn't one, and reads a product not in the catalog as none", async () => {+ await expect(getShoppingProductDetail('nope', PRODUCT, { datePreset: '30d' })).rejects.toThrow('invalid',);+ // An address with no product's id in it: none, not a failure, and nothing read.+ expect(await getShoppingProductDetail(BRAND, 'nope', { datePreset: '30d' })).toBeNull();+ expect(byIds).toEqual([]);expect(await getShoppingProductDetail(BRAND, PRODUCT, { datePreset: '30d' })).toBeNull();});@@ -109,6 +117,11 @@ describe('getShoppingProductDetail', () => {{ product_id: PRODUCT, category: { name: 'Hiking backpacks' } },];tables.brand_domains = [{ domain: 'northwind.example' }];+ tables.prompts = [+ { id: 'q1', text: 'lightweight 30L hiking backpack for women' },+ { id: 'q7', text: 'espresso machine for home' },+ ];+ tables.prompt_results = [{ id: 'r1', search_queries: [{ query: 'women hiking backpack' }] }];tables.prompt_result_shopping_cards = [card({}),card({@@ -148,6 +161,15 @@ describe('getShoppingProductDetail', () => {{ p_brand_id: BRAND, p_from: expect.any(String), p_product_id: PRODUCT },]);expect(detail?.result).toBeNull();+ // Its own cards, then the shelves of its questions alone, and AI's+ // searches for each shelf's latest answer only.+ expect(eqs).toContainEqual(['prompt_result_shopping_cards', 'catalog_product_id', PRODUCT]);+ expect(byIds).toContainEqual([+ 'prompt_result_shopping_cards',+ 'prompt_results.prompt_id',+ ['q1'],+ ]);+ expect(byIds).toContainEqual(['prompt_results', 'id', ['r1']]);});it('sets the week after its last done action beside the week before (ECOM-018)', async () => {@@ -172,8 +194,7 @@ describe('getShoppingProductDetail', () => {];const prompt = {prompt_id: 'q1',- search_queries: [],- prompt: { id: 'q1', text: 'lightweight 30L hiking backpack for women' },+ prompt: { text: 'lightweight 30L hiking backpack for women' },};tables.prompt_result_shopping_cards = [card({@@ -191,9 +212,10 @@ describe('getShoppingProductDetail', () => {}),];const detail = await getShoppingProductDetail(BRAND, PRODUCT, { datePreset: '30d' });- // One read for the action's one question.+ // One read for the action's one question (and one for the page's shelves of it).expect(filtered.filter(([, column]) => column === 'prompt_results.prompt_id')).toEqual([['prompt_result_shopping_cards', 'prompt_results.prompt_id', 1],+ ['prompt_result_shopping_cards', 'prompt_results.prompt_id', 1],]);expect(detail?.result).toEqual({actionId: 'a7',@@ -265,7 +287,7 @@ describe('getProductAiSays (ECOM-012)', () => {});describe('the re-check read (ECOM-018)', () => {- it('reads the cards of many questions a hundred ids at a time', async () => {+ it('reads the cards of every question, past 400, a hundred ids at a time', async () => {tables.catalog_products = [{ id: PRODUCT, title: 'Ridge 30L Backpack', description: null }];tables.actions = [{@@ -274,7 +296,7 @@ describe('the re-check read (ECOM-018)', () => {completed_at: new Date(Date.now() - 86_400_000).toISOString(),payload: {target: { type: 'product', id: PRODUCT },- promptIds: Array.from({ length: 250 }, (_, i) => `q${i}`),+ promptIds: Array.from({ length: 450 }, (_, i) => `q${i}`),},},];@@ -283,6 +305,86 @@ describe('the re-check read (ECOM-018)', () => {filtered.filter(([, column]) => column === 'prompt_results.prompt_id').map(([, , count]) => count),- ).toEqual([100, 100, 50]);+ ).toEqual([100, 100, 100, 100, 50]);+ });++ it("counts a category's own products on its shelves, not the brand's others", async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-10-30T00:00:00Z'));+ try {+ const CATEGORY = '22222222-0000-0000-0000-000000000002';+ tables.actions = [+ {+ id: 'a8',+ action_no: 8,+ completed_at: '2026-10-20T00:00:00Z',+ payload: { target: { type: 'category', id: CATEGORY }, promptIds: ['q1'] },+ },+ ];+ tables.catalog_product_categories = [{ product_id: 'boot', category_id: CATEGORY }];+ const prompt = { prompt_id: 'q1' };+ tables.prompt_result_shopping_cards = [+ // Before: one of the brand's products, not of the category.+ {+ created_at: '2026-10-15T08:00:00Z',+ platform: 'chatgpt-shopping',+ catalog_product_id: 'tee',+ prompt_results: prompt,+ },+ // After: the category's own.+ {+ created_at: '2026-10-22T08:00:00Z',+ platform: 'chatgpt-shopping',+ catalog_product_id: 'boot',+ prompt_results: prompt,+ },+ ];+ const results = await getShoppingActionResults(BRAND, [{ type: 'category', id: CATEGORY }]);+ expect(results[`category:${CATEGORY}`]).toMatchObject({+ before: { shelves: 1, on: 0 },+ after: { shelves: 1, on: 1 },+ });+ expect(byIds).toContainEqual(['catalog_product_categories', 'category_id', [CATEGORY]]);+ } finally {+ vi.useRealTimers();+ }+ });++ it("doesn't compare an action whose questions' cards stopped at the read's limit", async () => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date('2026-10-30T00:00:00Z'));+ try {+ tables.actions = [+ {+ id: 'a9',+ action_no: 9,+ completed_at: '2026-10-20T00:00:00Z',+ payload: { target: { type: 'product', id: PRODUCT }, promptIds: ['q1'] },+ },+ ];+ // Only the week after's cards fit in the read, the newest first.+ const after = {+ created_at: '2026-10-22T08:00:00Z',+ platform: 'chatgpt-shopping',+ catalog_product_id: PRODUCT,+ prompt_results: { prompt_id: 'q1' },+ };+ const key = `product:${PRODUCT}`;+ tables.prompt_result_shopping_cards = Array.from({ length: 50_000 }, () => after);+ const cut = (await getShoppingActionResults(BRAND, [{ type: 'product', id: PRODUCT }]))[key];+ // The week before wasn't reached: not "new", nor "better".+ expect(cut).toMatchObject({ before: { shelves: 0 }, after: { shelves: 1, on: 1 } });+ expect(cut.partial).toBe(true);+ expect(resultTrend(cut)).toBeNull();+ // One card short of the limit: every card was read.+ tables.prompt_result_shopping_cards = Array.from({ length: 49_999 }, () => after);+ const whole = (await getShoppingActionResults(BRAND, [{ type: 'product', id: PRODUCT }]))[+ key+ ];+ expect(whole.partial).toBeUndefined();+ expect(resultTrend(whole)).toBe('new');+ } finally {+ vi.useRealTimers();+ }});});diff --git a/web/src/lib/actions/shopping.ts b/web/src/lib/actions/shopping.tsindex 42986ed1e..c766d08a5 100644--- a/web/src/lib/actions/shopping.ts+++ b/web/src/lib/actions/shopping.ts@@ -21,6 +21,7 @@ import {import { categoryRows, type CategoryCardRow, type CategoryRow } from '@/lib/shopping/categories';import {comparison,+ detailPrompts,focusShelf,productShelves,type ComparisonRow,@@ -368,6 +369,17 @@ async function fetchAllCards<T>(// eslint-disable-next-line @typescript-eslint/no-explicit-any -- PostgREST builder genericsbuild: () => any,): Promise<T[]> {+ return (await readCardPages<T>(build)).rows;+}++/**+ * fetchAllCards' read, and whether it stopped at CARD_MAX_ROWS with every+ * page full (`cut`): the oldest cards past it may not have been read.+ */+async function readCardPages<T>(+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- PostgREST builder generics+ build: () => any,+): Promise<{ rows: T[]; cut: boolean }> {const rows: T[] = [];for (let start = 0; start < CARD_MAX_ROWS; start += CARD_PAGE_SIZE) {const { data, error } = await build()@@ -377,9 +389,9 @@ async function fetchAllCards<T>(if (error) throw new Error(error.message);const batch = (data ?? []) as T[];rows.push(...batch);- if (batch.length < CARD_PAGE_SIZE) break;+ if (batch.length < CARD_PAGE_SIZE) return { rows, cut: false };}- return rows;+ return { rows, cut: true };}/**@@ -1687,7 +1699,19 @@ export interface ShoppingProductDetail {result: ActionResult | null;}-/** A product of the brand's catalog, on the AI shelves of the questions it belongs on. Null when it isn't the brand's. */+/** The brand's questions read at most, to find those a product belongs on. */+const DETAIL_PROMPTS_READ = 5_000;++/**+ * A product of the brand's catalog, on the AI shelves of the questions it+ * belongs on. Null when it isn't the brand's, or the id can't be a product's.+ *+ * Reads only what the page shows: the product's own cards (the questions it+ * was on, its rating as the answers showed it), the brand's questions, then+ * the shelves of those it may belong on (detailPrompts), and AI's searches+ * for each shelf's latest answer, not every card of the window with its+ * answer's searches.+ */export async function getShoppingProductDetail(brandId: string,productId: string,@@ -1695,9 +1719,9 @@ export async function getShoppingProductDetail(/** The shelf to explain first: the Shelf's "Why not you?" (a question, its channel). */focusOn: { promptId: string; platform?: string | null } | null = null,): Promise<ShoppingProductDetail | null> {- if (!z.guid().safeParse(brandId).success || !z.guid().safeParse(productId).success) {- throw new Error('invalid');- }+ if (!z.guid().safeParse(brandId).success) throw new Error('invalid');+ // An address with no product's id in it: the page says it isn't in the catalog.+ if (!z.guid().safeParse(productId).success) return null;const asked = focusOn && z.guid().safeParse(focusOn.promptId).success ? focusOn : null;const supabase = await createClient();// Read beside the rest; a re-check that can't be read leaves the page as it is.@@ -1708,33 +1732,30 @@ export async function getShoppingProductDetail(return {} as Record<string, ActionResult>;});const { from } = resolveDateRange(filters);- const [[product], cards, stats, domain] = await Promise.all([+ const [[product], ownCards, prompts, stats, domain] = await Promise.all([readCatalogProducts(supabase, brandId, [productId]),fetchAllCards<{- prompt_result_id: string;- position: number;created_at: string;- platform: string;- product_title: string | null;- price_amount: number | null;- price_currency: string | null;rating: number | null;review_count: number | null;- merchant_domain: string | null;- image_url: string | null;- matched_brand_role: string;catalog_product_id: string | null;- prompt_results: {- search_queries: unknown;- prompt: { id: string; text: string } | null;- } | null;+ prompt_results: { prompt_id: string } | null;}>(() =>cardsInWindow(supabase,brandId,filters,- 'prompt_result_id, position, created_at, platform, product_title, price_amount, price_currency, rating, review_count, merchant_domain, image_url, matched_brand_role, catalog_product_id, prompt_results:prompt_result_id ( search_queries, prompt:prompt_id ( id, text ) )',- ),+ 'created_at, rating, review_count, catalog_product_id, prompt_results:prompt_result_id ( prompt_id )',+ ).eq('catalog_product_id', productId),+ ),+ readCatalogRows<{ id: string; text: string }>(+ () =>+ supabase+ .from('prompts')+ .select('id, text, prompt_sets!inner(brand_id)')+ .eq('prompt_sets.brand_id', brandId)+ .order('id'),+ DETAIL_PROMPTS_READ,),// Its own row only (00361), none without AI visits or orders.supabase.rpc('catalog_product_ai_stats', {@@ -1752,13 +1773,67 @@ export async function getShoppingProductDetail(if (!product) return null;if (stats.error) throw new Error(stats.error.message);+ const own = ownCards.filter((card) => card.catalog_product_id === productId);+ const promptIds = detailPrompts(product, prompts, {+ appeared: new Set(own.flatMap((card) => card.prompt_results?.prompt_id ?? [])),+ include: asked?.promptId ?? null,+ });+ const cards = await readForIds(promptIds, (some) =>+ fetchAllCards<{+ prompt_result_id: string;+ position: number;+ created_at: string;+ platform: string;+ product_title: string | null;+ price_amount: number | null;+ price_currency: string | null;+ rating: number | null;+ review_count: number | null;+ merchant_domain: string | null;+ image_url: string | null;+ matched_brand_role: string;+ catalog_product_id: string | null;+ prompt_results: { prompt_id: string; prompt: { text: string } | null } | null;+ }>(() =>+ cardsInWindow(+ supabase,+ brandId,+ filters,+ 'prompt_result_id, position, created_at, platform, product_title, price_amount, price_currency, rating, review_count, merchant_domain, image_url, matched_brand_role, catalog_product_id, prompt_results!inner ( prompt_id, prompt:prompt_id ( text ) )',+ ).in('prompt_results.prompt_id', some),+ ),+ );+ // AI's searches for each shelf's latest answer, the one the page explains.+ const latestRun = new Map<string, { id: string; at: string }>();+ for (const card of cards) {+ const key = `${card.prompt_results?.prompt_id}:${card.platform}`;+ const kept = latestRun.get(key);+ if (!kept || card.created_at > kept.at) {+ latestRun.set(key, { id: card.prompt_result_id, at: card.created_at });+ }+ }+ const runs = await readForIds(+ [...new Set([...latestRun.values()].map((run) => run.id))],+ async (some) => {+ const { data, error } = await supabase+ .from('prompt_results')+ .select('id, search_queries')+ .eq('brand_id', brandId)+ .in('id', some);+ if (error) throw new Error(error.message);+ return (data ?? []) as { id: string; search_queries: unknown }[];+ },+ );+ const searchesOfRun = new Map(runs.map((run) => [run.id, searchesOf(run.search_queries)]));+const detailCards: DetailCard[] = cards.flatMap((card) => {- const prompt = card.prompt_results?.prompt;- if (!prompt || !card.product_title?.trim()) return [];+ const promptId = card.prompt_results?.prompt_id;+ const promptText = card.prompt_results?.prompt?.text;+ if (!promptId || !promptText || !card.product_title?.trim()) return [];return [{- promptId: prompt.id,- promptText: prompt.text,+ promptId,+ promptText,platform: card.platform,promptResultId: card.prompt_result_id,at: card.created_at,@@ -1772,14 +1847,12 @@ export async function getShoppingProductDetail(image: card.image_url,role: card.matched_brand_role,productId: card.catalog_product_id,- searches: searchesOf(card.prompt_results?.search_queries),+ searches: searchesOfRun.get(card.prompt_result_id) ?? [],},];});// How the answers showed it, its latest card first: its rating there.- const shown = detailCards- .filter((card) => card.productId === productId)- .sort((a, b) => (a.at < b.at ? 1 : -1))[0];+ const shown = [...own].sort((a, b) => (a.created_at < b.created_at ? 1 : -1))[0];const results = await resultsRead;const shelves = productShelves(product, detailCards, { include: asked?.promptId ?? null });const focus = focusShelf(shelves, asked);@@ -1791,7 +1864,7 @@ export async function getShoppingProductDetail(focus,comparison: focus? comparison(product, focus, {- own: shown ? { rating: shown.rating, reviews: shown.reviews } : null,+ own: shown ? { rating: shown.rating, reviews: shown.review_count } : null,price: priceText,storeDomain: domain.data?.domain ?? null,})@@ -1832,13 +1905,18 @@ export async function getProductAiSays(}const supabase = await createClient();const [cards, product] = await Promise.all([- cardsInWindow(supabase, brandId, filters, 'prompt_result_id, product_title, created_at')+ cardsInWindow(+ supabase,+ brandId,+ filters,+ 'prompt_result_id, product_title, product_brand, created_at',+ ).eq('catalog_product_id', productId).order('created_at', { ascending: false }).limit(AI_SAYS_CARDS),supabase.from('catalog_products')- .select('title')+ .select('title, product_brand').eq('brand_id', brandId).eq('id', productId).maybeSingle(),@@ -1846,15 +1924,20 @@ export async function getProductAiSays(if (cards.error) throw new Error(cards.error.message);if (product.error) throw new Error(product.error.message);- // The answers, the latest first, with how each one's cards titled the product.+ // The answers, the latest first, with how each one's cards titled the+ // product, and the brand they named, to look for the product's own name.const titlesOf = new Map<string, string[]>();+ const brands = new Set<string>();+ if (product.data?.product_brand) brands.add(product.data.product_brand);for (const card of (cards.data ?? []) as unknown as {prompt_result_id: string;product_title: string | null;+ product_brand: string | null;}[]) {const titles = titlesOf.get(card.prompt_result_id) ?? [];if (card.product_title?.trim()) titles.push(card.product_title.trim());titlesOf.set(card.prompt_result_id, titles);+ if (card.product_brand?.trim()) brands.add(card.product_brand.trim());}const ids = [...titlesOf.keys()];if (!ids.length) return { answers: 0, quotes: [], sources: [] };@@ -1908,6 +1991,7 @@ export async function getProductAiSays(),product.data?.title ? [product.data.title] : [],ids.length,+ [...brands],);}@@ -1917,10 +2001,6 @@ export async function getProductAiSays(const RECHECK_SINCE_DAYS = 60;/** The actions read at most, the latest done first. */const RECHECK_ACTIONS = 500;-/** The questions read at most across the actions re-checked. */-const RECHECK_PROMPTS = 400;-/** Question ids one card read filters by: each request's address stays short. */-const RECHECK_PROMPTS_PER_READ = 100;const recheckTargets = z.array(z.object({ type: z.enum(['product', 'category']), id: z.guid() }))@@ -1929,8 +2009,12 @@ const recheckTargets = z/*** Each target's last done action from Products, 7 days on: the shelves of* its questions in the week before it was done beside the week after- * (recheck.ts), by "product:<id>" / "category:<id>". Through the member's- * session (RLS): only the brand's own actions and cards.+ * (recheck.ts), by "product:<id>" / "category:<id>". Every question the+ * actions name is read, IDS_PER_READ ids a read; a category's own products+ * are what count on its shelves. A read that stops at CARD_MAX_ROWS leaves+ * its oldest cards (the week before, first) unread: an action with one of+ * its questions is `partial`, and isn't compared. Through the member's+ * session (RLS): only the brand's own actions, cards and catalog.*/async function readActionResults(supabase: Awaited<ReturnType<typeof createClient>>,@@ -1976,38 +2060,58 @@ async function readActionResults(}if (!actions.size) return {};- const promptIds = [...new Set([...actions.values()].flatMap((a) => a.promptIds))].slice(- 0,- RECHECK_PROMPTS,- );+ const promptIds = [...new Set([...actions.values()].flatMap((a) => a.promptIds))];const dones = [...actions.values()].map((a) => Date.parse(a.completedAt));const week = RECHECK_DAYS * 86_400_000;const from = new Date(Math.min(...dones) - week).toISOString();const to = new Date(Math.min(now, Math.max(...dones) + week)).toISOString();- const reads = [];- for (let i = 0; i < promptIds.length; i += RECHECK_PROMPTS_PER_READ) {- const some = promptIds.slice(i, i + RECHECK_PROMPTS_PER_READ);- reads.push(- fetchAllCards<{+ const categoryIds = [...actions.values()].flatMap((a) =>+ a.target.type === 'category' ? [a.target.id] : [],+ );+ // The questions of a read cut at CARD_MAX_ROWS.+ const cutPrompts = new Set<string>();+ const [rows, links] = await Promise.all([+ readForIds(promptIds, async (some) => {+ const { rows: read, cut } = await readCardPages<{created_at: string;platform: string;- matched_brand_role: string;catalog_product_id: string | null;prompt_results: { prompt_id: string } | null;}>(() =>supabase.from('prompt_result_shopping_cards')- .select(- 'created_at, platform, matched_brand_role, catalog_product_id, prompt_results!inner ( prompt_id )',- )+ .select('created_at, platform, catalog_product_id, prompt_results!inner ( prompt_id )').eq('brand_id', brandId).gte('created_at', from).lt('created_at', to).in('prompt_results.prompt_id', some),+ );+ if (cut) for (const id of some) cutPrompts.add(id);+ return read;+ }),+ // A category's products: those its shelves count.+ readForIds(categoryIds, (some) =>+ readCatalogRows<{ product_id: string; category_id: string }>(+ () =>+ supabase+ .from('catalog_product_categories')+ .select('product_id, category_id')+ .eq('brand_id', brandId)+ .in('category_id', some)+ .order('product_id')+ .order('category_id'),+ CARD_MAX_ROWS,),- );+ ),+ ]);+ const productsOf = new Map<string, string[]>();+ for (const link of links) {+ if (!productsOf.has(link.category_id)) productsOf.set(link.category_id, []);+ productsOf.get(link.category_id)!.push(link.product_id);+ }+ for (const action of actions.values()) {+ if (action.target.type === 'category') action.products = productsOf.get(action.target.id) ?? [];}- const rows = (await Promise.all(reads)).flat();const cards: RecheckCard[] = rows.flatMap((row) =>row.prompt_results? [@@ -2015,14 +2119,17 @@ async function readActionResults(promptId: row.prompt_results.prompt_id,platform: row.platform,at: row.created_at,- own: row.matched_brand_role === 'own',productId: row.catalog_product_id,},]: [],);return Object.fromEntries(- [...actions].map(([key, action]) => [key, actionResult(action, cards, now)]),+ [...actions].map(([key, action]) => {+ const result = actionResult(action, cards, now);+ if (action.promptIds.some((id) => cutPrompts.has(id))) result.partial = true;+ return [key, result];+ }),);}diff --git a/web/src/lib/shopping/ai-says.test.ts b/web/src/lib/shopping/ai-says.test.tsindex c56983829..3e8c0bacd 100644--- a/web/src/lib/shopping/ai-says.test.ts+++ b/web/src/lib/shopping/ai-says.test.ts@@ -17,6 +17,50 @@ describe('productNames', () => {});});+describe('productNames, beside its brand', () => {+ it("looks for the product's own name, never the brand's alone", () => {+ const brands = ['The North Face'];+ expect(productNames(['The North Face | Borealis Backpack'], brands)).toEqual([+ 'The North Face | Borealis Backpack',+ 'Borealis Backpack',+ ]);+ // The brand opening the title, or after it, or the title being the brand.+ expect(productNames(['The North Face Borealis Backpack - Black'], brands)).toContain(+ 'Borealis Backpack',+ );+ expect(productNames(['Borealis Backpack | The North Face'], brands)).toContain(+ 'Borealis Backpack',+ );+ expect(productNames(['the north face'], brands)).toEqual([]);+ // Unknown, the brand is the title's head as before.+ expect(productNames(['The North Face | Borealis Backpack'])).toContain('The North Face');+ });++ it("doesn't quote a sentence about the brand as the product's", () => {+ const response =+ 'The North Face makes dependable gear. For school, the Borealis Backpack has a laptop sleeve.';+ const says = productAiSays(+ [+ {+ promptResultId: 'r1',+ platform: 'chatgpt-shopping',+ at: '2026-10-27T08:00:00Z',+ promptText: 'best school backpack',+ response,+ titles: ['The North Face | Borealis Backpack'],+ },+ ],+ [],+ [],+ 1,+ ['The North Face'],+ );+ expect(says.quotes.map((quote) => quote.text)).toEqual([+ 'For school, the Borealis Backpack has a laptop sleeve.',+ ]);+ });+});+describe('productQuote', () => {const response = ['## Best 30L packs',diff --git a/web/src/lib/shopping/ai-says.ts b/web/src/lib/shopping/ai-says.tsindex 9a216f75d..52fa75b60 100644--- a/web/src/lib/shopping/ai-says.ts+++ b/web/src/lib/shopping/ai-says.ts@@ -44,21 +44,47 @@ export interface ProductAiSays {export const MAX_QUOTES = 5;export const MAX_SOURCES = 5;-/** Where a title's name ends and its variant starts: "Ridge 30L Backpack - Black". */+/** Where a title's parts meet: its name, its variant, its brand ("Ridge 30L Backpack - Black"). */const TITLE_TAIL = /\s+[-–—|:,(/]\s*|\s*[|,(]\s*/;+const spaced = (text: string) => text.replace(/\s+/g, ' ').trim();+/**- * The names an answer may call the product by: each title, and its head- * before " - ", " | ", ",", ":" or "(" when that keeps two words or more.+ * The names an answer may call the product by: each title, and the+ * product's own name in it, without its variant or its brand. A title's+ * parts split at " - ", " | ", ",", ":" or "(": a part that is the brand+ * ("The North Face | Borealis Backpack") is left out, and a brand opening a+ * part is cut off ("The North Face Borealis Backpack" → "Borealis+ * Backpack"); the first part left is the name when it keeps two words or+ * more. The brand alone is never a name: every sentence about the brand+ * would quote as the product's.+ *+ * @param brands the product's brand as the catalog and the cards name it*/-export function productNames(titles: readonly string[]): string[] {+export function productNames(+ titles: readonly string[],+ brands: readonly (string | null | undefined)[] = [],+): string[] {+ const brandKeys = [+ ...new Set(brands.map((brand) => spaced(brand ?? '').toLowerCase()).filter(Boolean)),+ ];+ const isBrand = (text: string) => brandKeys.includes(text.toLowerCase());+ const withoutBrand = (part: string) => {+ const lower = part.toLowerCase();+ const brand = brandKeys.find((key) => lower.startsWith(`${key} `));+ return brand ? part.slice(brand.length).trim() : part;+ };const names = new Set<string>();for (const title of titles) {- const full = title.replace(/\s+/g, ' ').trim();- if (!full) continue;+ const full = spaced(title);+ if (!full || isBrand(full)) continue;names.add(full);- const head = full.split(TITLE_TAIL)[0].trim();- if (head.split(' ').length >= 2) names.add(head);+ const own = full+ .split(TITLE_TAIL)+ .map((part) => part.trim())+ .filter((part) => part && !isBrand(part))+ .map(withoutBrand)[0];+ if (own && own.split(' ').length >= 2 && !isBrand(own)) names.add(own);}return [...names];}@@ -74,7 +100,8 @@ export function productQuote(response: string, names: string[]): string | null {* What the answers said: a quote from each, the latest first, one per text,* and the sources most of them cited. `titles`: the catalog's own, beside* how each answer's cards titled it; `total`: the answers that showed the- * product, when more than those read.+ * product, when more than those read; `brands`: the product's brand, kept+ * out of the names it's looked for by (productNames).*/export function productAiSays(answers: readonly AiSaysAnswer[],@@ -86,13 +113,14 @@ export function productAiSays(}[],titles: readonly string[],total: number = answers.length,+ brands: readonly (string | null | undefined)[] = [],): ProductAiSays {const latest = [...answers].sort((a, b) => (a.at < b.at ? 1 : -1));const quotes: AiSaysQuote[] = [];const said = new Set<string>();for (const answer of latest) {if (quotes.length >= MAX_QUOTES) break;- const text = productQuote(answer.response, productNames([...answer.titles, ...titles]));+ const text = productQuote(answer.response, productNames([...answer.titles, ...titles], brands));if (!text || said.has(text)) continue;said.add(text);quotes.push({diff --git a/web/src/lib/shopping/product-detail.test.ts b/web/src/lib/shopping/product-detail.test.tsindex f216e1b74..f7b47b483 100644--- a/web/src/lib/shopping/product-detail.test.ts+++ b/web/src/lib/shopping/product-detail.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import {comparison,+ detailPrompts,focusShelf,productShelves,productText,@@ -108,6 +109,28 @@ describe('productShelves', () => {expect(lines.find((line) => line.promptId === 'q2')!.winner).toBeNull();});+ it("never names one of the brand's own products the winner", () => {+ const own = (over: Partial<DetailCard>) =>+ card({ promptId: 'q5', promptResultId: 'r5', role: 'own', ...over });+ const shelf = (...on: DetailCard[]) =>+ productShelves(product, on, { include: 'q5' }).find((line) => line.promptId === 'q5')!;+ // Its sister product first, a rival second, the product absent: the rival.+ expect(+ shelf(+ own({ title: 'Ridge 40L Backpack', productId: 'ridge-40' }),+ card({ promptId: 'q5', promptResultId: 'r5', position: 1, title: 'TrailCo Lite 28' }),+ ).winner?.title,+ ).toBe('TrailCo Lite 28');+ // Only its own above it: nothing to beat.+ const second = shelf(+ own({ title: 'Ridge 40L Backpack', productId: 'ridge-40' }),+ own({ position: 1, title: 'Ridge 30L Backpack', productId: 'ridge' }),+ card({ promptId: 'q5', promptResultId: 'r5', position: 2, title: 'TrailCo Lite 28' }),+ );+ expect(second.rank).toBe(2);+ expect(second.winner).toBeNull();+ });+it('reads the title and the first 40 words of the description', () => {expect(productText({ ...product, description: 'word '.repeat(60) }).split(' ')).toHaveLength(3 + 40,@@ -129,6 +152,28 @@ describe('focusShelf', () => {});});+describe('detailPrompts', () => {+ const prompts = [+ { id: 'q3', text: 'best trail running shoes' },+ { id: 'q1', text: 'lightweight 30L hiking backpack for women' },+ { id: 'q4', text: 'backpack for school' },+ { id: 'q2', text: 'durable 30 litre daypack' },+ { id: 'q9', text: 'gifts for runners' },+ ];++ it('reads the shelves asked for, it was on, of its category, then those sharing its words', () => {+ expect(detailPrompts(product, prompts, { appeared: new Set(['q2']), include: 'q9' })).toEqual([+ 'q9',+ 'q2',+ 'q1',+ 'q4',+ ]);+ // Not a word in common, nor asked for: not read.+ expect(detailPrompts(product, prompts, { appeared: new Set() })).not.toContain('q3');+ expect(detailPrompts(product, prompts, { appeared: new Set(), max: 1 })).toEqual(['q1']);+ });+});+describe('a shelf asked for (the Shelf’s "Why not you?")', () => {it('keeps the question whatever its match, and explains that shelf first', () => {// q3 isn't the product's: kept when it's the one asked for.diff --git a/web/src/lib/shopping/product-detail.ts b/web/src/lib/shopping/product-detail.tsindex ead79d8de..0c3cc19f7 100644--- a/web/src/lib/shopping/product-detail.ts+++ b/web/src/lib/shopping/product-detail.ts@@ -1,5 +1,5 @@import { categoryWords } from '@/lib/shopping/categories';-import { matchScores, missingWords, queryTerms } from '@/lib/shopping/match-score';+import { contentWords, matchScores, missingWords, queryTerms } from '@/lib/shopping/match-score';import {FIRST_WORDS,readiness,@@ -52,7 +52,7 @@ export interface ProductShelfLine {platform: string;/** Its place on the latest shelf, from 1, or null when it isn't on it. */rank: number | null;- /** The shelf's first product, when it isn't this one. */+ /** The shelf's first product not the brand's own, above this one; null when none is. */winner: ShelfProduct | null;/** Its keyword match with the question and AI's searches, 0–100 (Ansvisor estimate). */score: number;@@ -65,6 +65,8 @@ export interface ProductShelfLine {export const RELEVANT_SCORE = 40;/** Questions a product's page lists at most. */export const MAX_LINES = 20;+/** Questions whose shelves a product's page reads at most (detailPrompts). */+export const DETAIL_PROMPTS = 60;/** What the product says first: its title and its description's opening (ECOM-024). */export function productText(product: CatalogProductRow): string {@@ -76,6 +78,56 @@ export function productText(product: CatalogProductRow): string {return `${product.title} ${opening}`.trim();}+/** The product's category's last level, as words: "Bags > Hiking backpacks" → hiking, backpack. */+function categoryOf(product: CatalogProductRow): string[] {+ return product.category ? categoryWords(product.category.split('>').at(-1)!) : [];+}++/**+ * The questions whose shelves a product's page reads (ECOM-011), so it+ * reads those, not every shelf of the window: the one asked for, those it+ * was on (listed in `prompts` or not), those of its category, then those+ * sharing the most words with its title and opening; `max` at most. A+ * question none of these ties to it could only make its list through AI's+ * searches alone (productShelves).+ */+export function detailPrompts(+ product: CatalogProductRow,+ prompts: readonly { id: string; text: string }[],+ {+ appeared,+ include = null,+ max = DETAIL_PROMPTS,+ }: { appeared: ReadonlySet<string>; include?: string | null; max?: number },+): string[] {+ const category = categoryOf(product);+ const words = new Set(contentWords(productText(product)));+ const listed = new Set(prompts.map((prompt) => prompt.id));+ const unlisted = [include, ...appeared].flatMap((id) =>+ id && !listed.has(id) ? [{ id, text: '', tier: id === include ? 0 : 1, shared: 0 }] : [],+ );+ const ranked = prompts.flatMap((prompt) => {+ const promptWords = new Set(categoryWords(prompt.text));+ const tier =+ prompt.id === include+ ? 0+ : appeared.has(prompt.id)+ ? 1+ : category.length > 0 && category.every((word) => promptWords.has(word))+ ? 2+ : 3;+ const shared = contentWords(prompt.text).filter((word) => words.has(word)).length;+ return tier < 3 || shared > 0 ? [{ id: prompt.id, text: prompt.text, tier, shared }] : [];+ });+ return [+ ...new Set(+ [...unlisted, ...ranked]+ .sort((a, b) => a.tier - b.tier || b.shared - a.shared || a.text.localeCompare(b.text))+ .map((prompt) => prompt.id),+ ),+ ].slice(0, max);+}+/*** The product's shelves: the questions of its category (its name in them),* those it was on, and those its words match well enough, each channel's@@ -87,7 +139,7 @@ export function productShelves(cards: readonly DetailCard[],{ include = null }: { include?: string | null } = {},): ProductShelfLine[] {- const category = product.category ? categoryWords(product.category.split('>').at(-1)!) : [];+ const category = categoryOf(product);const text = productText(product);const shelves = new Map<string, DetailCard[]>();for (const card of cards) {@@ -111,7 +163,12 @@ export function productShelves(const inCategory = category.length > 0 && category.every((word) => promptWords.has(word));const asked = include !== null && first.promptId === include;if (!asked && !appeared && !inCategory && scores[0] < RELEVANT_SCORE) continue;- const winnerCard = at === 0 ? null : latest[0];+ // The rival above it (above all, when it isn't on the shelf): never one+ // of the brand's own products, which it needn't beat.+ const winnerCard =+ latest.find(+ (card, i) => card.role !== 'own' && card.productId !== product.id && (at < 0 || i < at),+ ) ?? null;lines.push({promptId: first.promptId,promptText: first.promptText,diff --git a/web/src/lib/shopping/recheck.test.ts b/web/src/lib/shopping/recheck.test.tsindex 5b5ff0373..82b0ba7e2 100644--- a/web/src/lib/shopping/recheck.test.ts+++ b/web/src/lib/shopping/recheck.test.ts@@ -25,7 +25,6 @@ const card = (over: Partial<RecheckCard>): RecheckCard => ({promptId: 'q1',platform: 'chatgpt-shopping',at: '2026-10-15T08:00:00Z',- own: false,productId: null,...over,});@@ -33,15 +32,15 @@ const card = (over: Partial<RecheckCard>): RecheckCard => ({const cards = [// The week before: two shelves, the product on neither (another of the brand's on one).card({}),- card({ platform: 'gemini-web', own: true, productId: 'other' }),+ card({ platform: 'gemini-web', productId: 'other' }),// The week after: the product on q1's ChatGPT shelf, q2's read without it.card({ at: '2026-10-22T08:00:00Z' }),- card({ at: '2026-10-22T08:00:00Z', own: true, productId: 'ridge' }),+ card({ at: '2026-10-22T08:00:00Z', productId: 'ridge' }),card({ promptId: 'q2', at: '2026-10-23T08:00:00Z' }),// Not its questions, or outside both weeks.- card({ promptId: 'q9', at: '2026-10-22T08:00:00Z', own: true, productId: 'ridge' }),- card({ at: '2026-10-28T08:00:00Z', own: true, productId: 'ridge' }),- card({ at: '2026-10-01T08:00:00Z', own: true, productId: 'ridge' }),+ card({ promptId: 'q9', at: '2026-10-22T08:00:00Z', productId: 'ridge' }),+ card({ at: '2026-10-28T08:00:00Z', productId: 'ridge' }),+ card({ at: '2026-10-01T08:00:00Z', productId: 'ridge' }),];describe('shelfPresence', () => {@@ -51,10 +50,18 @@ describe('shelfPresence', () => {expect(shelfPresence(cards, action, done, done + 7 * DAY)).toEqual({ shelves: 2, on: 1 });});- it("counts any of the brand's products for a category", () => {+ it("counts the category's products for a category, not any of the brand's", () => {const done = Date.parse(DONE);const category = { ...action, target: { type: 'category' as const, id: 'c1' } };- expect(shelfPresence(cards, category, done - 7 * DAY, done)).toEqual({ shelves: 2, on: 1 });+ // "other" is the category's: on one of the two shelves the week before.+ expect(+ shelfPresence(cards, { ...category, products: ['other', 'ridge'] }, done - 7 * DAY, done),+ ).toEqual({ shelves: 2, on: 1 });+ // Another category's product on the shelf: not this one's.+ expect(+ shelfPresence(cards, { ...category, products: ['ridge'] }, done - 7 * DAY, done),+ ).toEqual({ shelves: 2, on: 0 });+ expect(shelfPresence(cards, category, done - 7 * DAY, done)).toEqual({ shelves: 2, on: 0 });});});@@ -96,7 +103,26 @@ describe('resultTrend', () => {expect(result([2, 4], [2, 2])).toBe('better');expect(result([2, 2], [2, 4])).toBe('worse');expect(result([1, 2], [2, 4])).toBe('same');- expect(result([0, 0], [0, 3])).toBe('same');+ });++ it('says new, not better, when no shelf was read in the week before', () => {+ expect(result([0, 0], [2, 3])).toBe('new');+ expect(result([0, 0], [0, 3])).toBe('new');+ });++ it("reads no trend when not every answer could be read: a missing week isn't new", () => {+ const partial = (before: [number, number], after: [number, number]) =>+ resultTrend({+ actionId: 'a1',+ actionNo: 1,+ completedAt: DONE,+ readyAt: DONE,+ before: { on: before[0], shelves: before[1] },+ after: { on: after[0], shelves: after[1] },+ partial: true,+ });+ expect(partial([0, 0], [2, 3])).toBeNull();+ expect(partial([1, 4], [2, 2])).toBeNull();});});diff --git a/web/src/lib/shopping/recheck.ts b/web/src/lib/shopping/recheck.tsindex f6f0d3f9e..63726b5dc 100644--- a/web/src/lib/shopping/recheck.ts+++ b/web/src/lib/shopping/recheck.ts@@ -3,8 +3,8 @@* Product Visibility (a product to get on the AI shelf, a category to win)* names the shopping questions it's measured on; once someone completes it,* the shelves of those questions in the 7 days after are set beside the 7- * days before: how many the brand's product (or, for a category, any of its- * products) was on. Read from the cards already kept, when the page opens:+ * days before: how many the product (or, for a category, any product of the+ * category) was on. Read from the cards already kept, when the page opens:* no job, nothing stored.*/@@ -13,12 +13,11 @@ export const RECHECK_DAYS = 7;export const RECHECK_TARGETS = 500;const DAY_MS = 86_400_000;-/** A card as the re-check reads it: its shelf (question × channel), when, and whose. */+/** A card as the re-check reads it: its shelf (question × channel), when, and the catalog product it shows. */export interface RecheckCard {promptId: string;platform: string;at: string;- own: boolean;productId: string | null;}@@ -30,6 +29,8 @@ export interface RecheckAction {completedAt: string;/** The shopping questions it's measured on. */promptIds: string[];+ /** A category's products: one of them on a shelf counts. */+ products?: readonly string[];}/** Shelves read in a window, and how many the brand was on. */@@ -47,22 +48,34 @@ export interface ActionResult {before: ShelfPresence;/** Null until the 7 days after have passed. */after: ShelfPresence | null;+ /**+ * True when its questions had more answers than a read takes: the oldest+ * weren't read, so the two weeks aren't compared.+ */+ partial?: boolean;}-/** The action's shelves read in [from, to), and how many had the brand's product on them. */+/**+ * The action's shelves read in [from, to), and how many had its product on+ * them: the product, or for a category one of its products, not any of the+ * brand's.+ */export function shelfPresence(cards: readonly RecheckCard[],- action: Pick<RecheckAction, 'target' | 'promptIds'>,+ action: Pick<RecheckAction, 'target' | 'promptIds' | 'products'>,from: number,to: number,): ShelfPresence {const prompts = new Set(action.promptIds);+ const products = new Set(+ action.target.type === 'product' ? [action.target.id] : (action.products ?? []),+ );const shelves = new Map<string, boolean>();for (const card of cards) {const at = Date.parse(card.at);if (!(at >= from && at < to) || !prompts.has(card.promptId)) continue;const key = `${card.promptId}:${card.platform}`;- const ours = action.target.type === 'product' ? card.productId === action.target.id : card.own;+ const ours = card.productId !== null && products.has(card.productId);shelves.set(key, (shelves.get(key) ?? false) || ours);}return { shelves: shelves.size, on: [...shelves.values()].filter(Boolean).length };@@ -87,12 +100,16 @@ export function actionResult(}/**- * Which way it went: the share of shelves it was on, after beside before.- * Null while the week after runs, or when no answer was read in it.+ * Which way it went: the share of shelves it was on, after beside before;+ * 'new' when no shelf was read in the week before, so nothing to compare.+ * Null while the week after runs, when no answer was read in it, or when+ * not every answer could be read (partial): a week missing in the read+ * would read as 'new' or 'better'.*/-export function resultTrend(result: ActionResult): 'better' | 'worse' | 'same' | null {+export function resultTrend(result: ActionResult): 'better' | 'worse' | 'same' | 'new' | null {const { before, after } = result;- if (!after?.shelves) return null;+ if (result.partial || !after?.shelves) return null;+ if (!before.shelves) return 'new';const share = (p: ShelfPresence) => (p.shelves ? p.on / p.shelves : 0);const change = share(after) - share(before);return change > 0 ? 'better' : change < 0 ? 'worse' : 'same';diff --git a/web/src/lib/shopping/shelf.test.ts b/web/src/lib/shopping/shelf.test.tsindex 7d5c144c6..b22d0fd46 100644--- a/web/src/lib/shopping/shelf.test.ts+++ b/web/src/lib/shopping/shelf.test.ts@@ -237,12 +237,80 @@ describe('whyNotYou', () => {// On a tie, the readier one.expect(whyNotYou(absent, [- productRow('a', { title: 'Backpack A' }, 40),- productRow('b', { title: 'Backpack B' }, 80),+ productRow('a', { title: 'Hiking Backpack A' }, 40),+ productRow('b', { title: 'Hiking Backpack B' }, 80),])?.product.id,).toBe('b');});+ it('needs two of the question’s words, or its category, not "best", "under" or a price', () => {+ const shoes = buildShelf(+ [+ card({+ prompt_text: 'best running shoes for men under $100',+ matched_brand_role: 'competitor',+ }),+ ],+ NOW,+ )[0];+ const tee = productRow('tee', {+ title: "Men's Best Seller Tee",+ category: 'Apparel > T-shirts',+ });+ // "best" and "under" ask, "100" is a price: only "men" is left, one word.+ expect(whyNotYou(shoes, [tee])).toBeNull();+ expect(whyNotYou(shoes, [productRow('top', { title: 'Top 100 Under Armour Cap' })])).toBeNull();+ // Its category is what the question names: a candidate on one word less.+ const runner = productRow('runner', {+ title: 'Trail Runner X',+ category: 'Shoes > Running shoes',+ });+ expect(whyNotYou(shoes, [tee, runner])?.product.id).toBe('runner');+ // Or by its type.+ expect(+ whyNotYou(shoes, [+ tee,+ productRow('glide', { title: 'Glide 3', productType: 'Running shoes' }),+ ])?.product.id,+ ).toBe('glide');+ });++ it("never makes a product a candidate on who it's for alone, but breaks a tie on it", () => {+ const asking = (prompt_text: string) =>+ buildShelf([card({ prompt_text, matched_brand_role: 'competitor' })], NOW)[0];+ const shoes = asking('best running shoes for men under $100');+ // A category or a type that only says who it's for isn't what the question names.+ for (const [question, audience, title] of [+ [shoes, 'Men', "Men's Best Seller Tee"],+ [asking('best running shoes for women under $100'), 'Women', "Women's Best Seller Tee"],+ [asking('best running shoes for kids'), 'Kids', "Kids' Best Seller Tee"],+ ] as const) {+ expect(+ whyNotYou(question, [productRow('tee', { title, category: `Clothing > ${audience}` })]),+ ).toBeNull();+ expect(whyNotYou(question, [productRow('tee', { title, productType: audience })])).toBeNull();+ }+ // Nor does it make up the two words: only "hiking" says what it is.+ expect(+ whyNotYou(asking('hiking boots for women'), [+ productRow('socks', { title: "Women's Hiking Socks" }),+ ]),+ ).toBeNull();+ // A category that names what it is, past who it's for, still does.+ expect(+ whyNotYou(shoes, [+ productRow('pace', { title: 'Pace 2', category: "Footwear > Men's running shoes" }),+ ])?.product.id,+ ).toBe('pace');+ // Among candidates, the one for whom the question asks, before the readier one.+ expect(+ whyNotYou(asking('running shoes for women'), [+ productRow('his', { title: "Men's Running Shoe" }, 90),+ productRow('hers', { title: "Women's Running Shoe" }, 40),+ ])?.product.id,+ ).toBe('hers');+ });+it('names none for a shelf the brand is on, or when nothing shares a word with the question', () => {expect(whyNotYou(absent, [productRow('mug', { title: 'Coffee mug' })])).toBeNull();const on = { ...absent, ownRank: 2 };diff --git a/web/src/lib/shopping/shelf.ts b/web/src/lib/shopping/shelf.tsindex 6b9def82e..f555babf0 100644--- a/web/src/lib/shopping/shelf.ts+++ b/web/src/lib/shopping/shelf.ts@@ -235,21 +235,123 @@ export function inPriceBand(row: ShelfRow, band: PriceBand): boolean {return middle >= min && middle < max;}+/**+ * Words a shopping question asks with, not for: what's wanted of a product+ * ("best", "under", "cheap") rather than which one, as categoryWords reads+ * them (singular). "Why not you?" matches on neither these nor numbers.+ */+const ASKING_WORDS = new Set([+ 'best',+ 'top',+ 'good',+ 'great',+ 'cheap',+ 'cheapest',+ 'affordable',+ 'budget',+ 'under',+ 'over',+ 'below',+ 'above',+ 'less',+ 'more',+ 'than',+ 'most',+ 'popular',+ 'rated',+ 'review',+ 'recommend',+ 'recommended',+ 'buy',+ 'price',+ 'deal',+ 'sale',+ 'new',+ 'vs',+ 'versu',+ 'what',+ 'which',+ 'where',+ 'how',+ 'is',+ 'are',+ 'in',+ 'on',+ 'to',+ 'my',+ 'me',+ 'should',+ 'need',+ 'want',+ 'seller',+]);++/**+ * Words that say who a product is for ("men", "kids") rather than what it+ * is, as categoryWords reads them (singular). In "Why not you?" they break+ * a tie, but never make a product a candidate: "best running shoes for men"+ * doesn't ask for a tee of "Clothing > Men".+ */+const AUDIENCE_WORDS = new Set([+ 'men',+ 'man',+ 'women',+ 'woman',+ 'lady',+ 'male',+ 'female',+ 'unisex',+ 'adult',+ 'kid',+ 'child',+ 'children',+ 'boy',+ 'girl',+ 'baby',+ 'toddler',+ 'infant',+ 'teen',+ 'youth',+ 'junior',+]);++/** A text's words that name a product: no asking words, numbers or single letters. */+function productWords(text: string): string[] {+ return categoryWords(text).filter(+ (word) => word.length > 1 && !/^\d+$/.test(word) && !ASKING_WORDS.has(word),+ );+}++/**+ * "Why not you?" needs this many of the question's words in a product, short+ * of its category, not counting who it's for (AUDIENCE_WORDS).+ */+export const WHY_NOT_WORDS = 2;+/*** "Why not you?" (the mockup's Shelf): for a shelf the brand isn't on, the* product of its catalog the question asks for most, by the question's* words in the product's title, category and type; the readier one on a- * tie. Null when none shares a word with the question, or the brand is on- * the shelf.+ * tie. A product is a candidate when it has WHY_NOT_WORDS of the question's+ * words, or when its category or type is what the question names (all its+ * words in it), past who it's for: "best running shoes for men under $100"+ * isn't "Men's Best Seller Tee", even of "Clothing > Men". Null when none+ * is, or the brand is on the shelf.*/export function whyNotYou(row: ShelfRow, products: readonly ProductRow[]): ProductRow | null {if (row.ownRank !== null) return null;- const asked = new Set(categoryWords(row.promptText));+ const asked = new Set(productWords(row.promptText));+ const names = (text: string | null) => {+ const words = productWords(text ?? '');+ return (+ words.some((word) => !AUDIENCE_WORDS.has(word)) && words.every((word) => asked.has(word))+ );+ };let best: { row: ProductRow; score: number } | null = null;for (const candidate of products) {const { product } = candidate;const words = new Set(- categoryWords(+ productWords([product.title,product.category ? categoryLeaf(product.category) : '',@@ -260,8 +362,16 @@ export function whyNotYou(row: ShelfRow, products: readonly ProductRow[]): Produ),);let score = 0;- for (const word of asked) if (words.has(word)) score += 1;- if (score === 0) continue;+ // The shared words that say what it is, not who it's for.+ let what = 0;+ for (const word of asked) {+ if (!words.has(word)) continue;+ score += 1;+ if (!AUDIENCE_WORDS.has(word)) what += 1;+ }+ const ofCategory =+ names(product.category ? categoryLeaf(product.category) : null) || names(product.productType);+ if (what < WHY_NOT_WORDS && !ofCategory) continue;if (!best ||score > best.score ||