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(competitors): show a competitor's pages over time under its comparison (learning C3, part 2) (#1746)
Cihan8f8d3b1f02d2
diff --git a/docs/guides/competitors.mdx b/docs/guides/competitors.mdxindex a8f3e24f4..837bcc72c 100644--- a/docs/guides/competitors.mdx+++ b/docs/guides/competitors.mdx@@ -34,6 +34,15 @@ For each competitor:</Step></Steps>+## A competitor's pages over time++Below a competitor's comparison, a card shows the competitor's pages over time: why it may be rising. A chart shows the answers that mentioned the competitor, and your brand, each week for the last twelve weeks. A marker sits on each week something happened to the competitor's pages, and a list below names those events, newest first:++- **First cited in your tracked answers**: the first day an AI answer to one of your prompts cited one of the competitor's pages. When a competitor is added, Ansvisor reads back 90 days of your answers once, so the first date is the first within that window.+- **Changed**: once a week, Ansvisor reads again the 10 competitor pages your answers cited most over the last two weeks. When a page's words changed by more than a date or a price moving, it says so, with the Site Audit checks the page gained (an FAQ, a table, statistics…) or lost.++Pages are read for free from their public address, never from a site whose robots.txt keeps crawlers out. These reads share a brand's 12 page reads a day with the Action Center's tasks, which go first. Only what Site Audit's checks found and a summary of the page's words are kept, never its text. Nothing is compared with another brand's answers.+## Auto-discovered competitorsEven if you don't add competitors manually, AI responses **mention** other brands when answering your prompts. The Insights drill-down sheet exposes these — recurring names you didn't add are strong candidates for the competitors list.diff --git a/web/messages/en.json b/web/messages/en.jsonindex 50c648510..a2f2f64d9 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -8338,6 +8338,25 @@"noDataDescription": "Run a tracking check from the Insights page to generate comparison data for this competitor.","loadError": "Failed to load comparison data."},+ "timeline": {+ "title": "{competitor}'s pages over time",+ "lead": "Answers mentioning {competitor} and {brand} each week, beside what happened to {competitor}'s pages: when AI first cited one in your tracked answers, and when one changed.",+ "weekOf": "Week of {date}",+ "mentions": "{count, plural, one {# answer} other {# answers}} mentioning",+ "firstCitedBadge": "{count, plural, one {# page first cited} other {# pages first cited}}",+ "changedBadge": "{count, plural, one {# page changed} other {# pages changed}}",+ "events": "What happened to their pages",+ "firstCited": "First cited in your tracked answers",+ "firstCitedAnswers": "{count, plural, one {# answer had cited it} other {# answers had cited it}} when Ansvisor found it",+ "changed": "Changed",+ "gained": "now has {checks}",+ "lost": "no longer has {checks}",+ "changedWords": "its words changed",+ "noEvents": "Nothing yet: Ansvisor reads {competitor}'s pages cited in your answers each night, and the ones cited most again each week. Their first citations and changes show here.",+ "note": "Pages are read for free from their public address, within a few reads a day, never from a site whose robots.txt keeps crawlers out; only what Site Audit's checks found and a summary of the words are kept, never the text.",+ "showAll": "Show all {count}",+ "loadError": "Couldn't load the timeline. Try again in a moment."+ },"suggestCompetitors": "Suggest competitors","suggestCompetitorsDescription": "Discover competitors for {brand} with AI research. Select the ones you want to track.","suggestCompetitorsLoading": "Researching competitors… This can take a little while.",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/competitors/_timeline-card.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/competitors/_timeline-card.test.tsxnew file mode 100644index 000000000..be59c3a32--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/competitors/_timeline-card.test.tsx@@ -0,0 +1,117 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../messages/en.json';+import type { CompetitorTimeline } from '@/lib/competitor-timeline';++/** A competitor's pages over time (learning C3), on the Competitors page. */++// The chart draws in a browser; here it says what it was given.+vi.mock('next/dynamic', () => ({+ default: () =>+ function Chart({ marks }: { marks: { week: string }[] }) {+ return <div data-testid="chart" data-marks={marks.map((m) => m.week).join(',')} />;+ },+}));++const { CompetitorTimelineCard } = await import('./_timeline-card');++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++function render(timeline: CompetitorTimeline | null | 'failed') {+ act(() =>+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ <CompetitorTimelineCard timeline={timeline} brandName="Acme" competitorName="Rival" />+ </NextIntlClientProvider>,+ ),+ );+ return container.textContent ?? '';+}++const weeks = [+ { week: '2026-10-19', brand: 4, competitor: 2 },+ { week: '2026-10-26', brand: 5, competitor: 9 },+];+const changed = {+ kind: 'changed' as const,+ at: '2026-10-28T03:00:00Z',+ url: 'https://www.rival.com/kettles/',+ domain: 'rival.com',+ answers: null,+ gained: [+ { key: 'faq-schema', label: 'FAQ schema' },+ { key: 'tables', label: 'Tables' },+ ],+ lost: [{ key: 'author-byline', label: 'Author byline' }],+};+const firstCited = {+ kind: 'first_cited' as const,+ at: '2026-10-20T00:00:00Z',+ url: 'https://rival.com/guide',+ domain: 'rival.com',+ answers: 3,+ gained: [],+ lost: [],+};++describe('CompetitorTimelineCard', () => {+ it("shows the weeks' mentions and what happened to the competitor's pages, newest first", () => {+ const text = render({ weeks, events: [changed, firstCited] });+ expect(text).toContain("Rival's pages over time");+ expect(text).toContain('Answers mentioning Rival and Acme each week');+ expect(container.querySelector('[data-testid="chart"]')?.getAttribute('data-marks')).toBe(+ '2026-10-19,2026-10-26',+ );+ const rows = [...container.querySelectorAll('li')].map((li) => li.textContent);+ expect(rows).toEqual([+ 'Oct 28, 2026Changed rival.com/kettlesnow has FAQ schema, Tables · no longer has Author byline',+ 'Oct 20, 2026First cited in your tracked answers rival.com/guide3 answers had cited it when Ansvisor found it',+ ]);+ expect(container.querySelector('a[href="https://www.rival.com/kettles/"]')).not.toBeNull();+ });++ it('says a page whose checks stayed the same changed in its words', () => {+ render({ weeks, events: [{ ...changed, gained: [], lost: [] }] });+ expect(container.querySelector('li')?.textContent).toContain('its words changed');+ });++ it('lists eight events, then all on asking', () => {+ const events = Array.from({ length: 10 }, (_, i) => ({+ ...firstCited,+ url: `https://rival.com/p${i}`,+ }));+ render({ weeks, events });+ expect(container.querySelectorAll('li')).toHaveLength(8);+ const all = [...container.querySelectorAll('button')].find((b) =>+ b.textContent?.includes('Show all 10'),+ )!;+ act(() => all.click());+ expect(container.querySelectorAll('li')).toHaveLength(10);+ });++ it('says what it reads before anything happened, and when it could not be read', () => {+ expect(render({ weeks, events: [] })).toContain(+ "Nothing yet: Ansvisor reads Rival's pages cited in your answers each night",+ );+ expect(render('failed')).toContain("Couldn't load the timeline.");+ render(null);+ expect(container.querySelector('[data-testid="chart"]')).toBeNull();+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/competitors/_timeline-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/competitors/_timeline-card.tsxnew file mode 100644index 000000000..562885002--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/competitors/_timeline-card.tsx@@ -0,0 +1,157 @@+'use client';++import { useState } from 'react';+import dynamic from 'next/dynamic';+import { useTranslations } from 'next-intl';+import { ArrowUpRight, History } from 'lucide-react';+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';+import { Button } from '@/components/ui/button';+import { Skeleton } from '@/components/ui/skeleton';+import { OWN_BRAND_COLOR } from '@/lib/insights-trend';+import { formatDate } from '@/lib/format';+import {+ COMPETITOR_COLOR,+ eventWeeks,+ type CompetitorPageEvent,+ type CompetitorTimeline,+} from '@/lib/competitor-timeline';++const CompetitorTimelineChart = dynamic(+ () => import('./_timeline-chart').then((m) => m.CompetitorTimelineChart),+ { ssr: false, loading: () => <Skeleton className="h-[220px] w-full" /> },+);++/** Events listed before "Show all". */+const EVENTS_SHOWN = 8;++function EventRow({ event }: { event: CompetitorPageEvent }) {+ const t = useTranslations('competitors.timeline');+ const shown = event.url.replace(/^https?:\/\/(www\.)?/i, '').replace(/\/$/, '');+ const names = (checks: { label: string }[]) => checks.map((c) => c.label).join(', ');+ const detail =+ event.kind === 'first_cited'+ ? event.answers !== null+ ? t('firstCitedAnswers', { count: event.answers })+ : null+ : [+ event.gained.length > 0 ? t('gained', { checks: names(event.gained) }) : null,+ event.lost.length > 0 ? t('lost', { checks: names(event.lost) }) : null,+ ]+ .filter(Boolean)+ .join(' · ') || t('changedWords');+ return (+ <li className="flex flex-col gap-0.5 border-b py-2 text-xs last:border-b-0 sm:flex-row sm:gap-3">+ <span className="w-24 shrink-0 tabular-nums text-muted-foreground">+ {formatDate(event.at)}+ </span>+ <span className="min-w-0 flex-1">+ <span className="font-medium">+ {t(event.kind === 'first_cited' ? 'firstCited' : 'changed')}+ </span>{' '}+ <a+ href={event.url}+ target="_blank"+ rel="noopener noreferrer"+ className="break-all text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"+ >+ {shown}+ <ArrowUpRight className="ml-0.5 inline h-3 w-3" />+ </a>+ {detail && <span className="block text-muted-foreground">{detail}</span>}+ </span>+ </li>+ );+}++/**+ * A competitor's pages over time (learning C3), under its head-to-head:+ * the answers mentioning it and the brand each week, a marker on the weeks+ * its pages were first cited or changed, and those events, newest first.+ */+export function CompetitorTimelineCard({+ timeline,+ brandName,+ competitorName,+}: {+ /** Null while it loads; 'failed' when it couldn't be read. */+ timeline: CompetitorTimeline | null | 'failed';+ brandName: string;+ competitorName: string;+}) {+ const t = useTranslations('competitors.timeline');+ const [all, setAll] = useState(false);+ const events = timeline && timeline !== 'failed' ? timeline.events : [];+ const shown = all ? events : events.slice(0, EVENTS_SHOWN);++ return (+ <Card>+ <CardHeader className="space-y-1 pb-2">+ <CardTitle className="flex items-center gap-2 text-sm font-semibold">+ <History className="h-4 w-4 text-muted-foreground" />+ {t('title', { competitor: competitorName })}+ </CardTitle>+ <p className="text-xs text-muted-foreground">+ {t('lead', { competitor: competitorName, brand: brandName })}+ </p>+ </CardHeader>+ <CardContent className="space-y-3">+ {timeline === null ? (+ <Skeleton className="h-[220px] w-full" />+ ) : timeline === 'failed' ? (+ <p role="status" className="text-xs text-muted-foreground">+ {t('loadError')}+ </p>+ ) : (+ <>+ <div className="flex flex-wrap gap-x-4 gap-y-1 text-xs">+ {[+ { name: competitorName, color: COMPETITOR_COLOR },+ { name: brandName, color: OWN_BRAND_COLOR },+ ].map((line) => (+ <span key={line.name} className="flex items-center gap-1.5">+ <span+ aria-hidden+ className="inline-block h-2 w-2 rounded-full"+ style={{ backgroundColor: line.color }}+ />+ {line.name}+ </span>+ ))}+ </div>+ <CompetitorTimelineChart+ weeks={timeline.weeks}+ marks={eventWeeks(timeline.events, timeline.weeks)}+ brandName={brandName}+ competitorName={competitorName}+ />+ <div>+ <p className="mb-1 text-xs font-medium">{t('events')}</p>+ {events.length === 0 ? (+ <p className="text-xs text-muted-foreground">+ {t('noEvents', { competitor: competitorName })}+ </p>+ ) : (+ <ul>+ {shown.map((event) => (+ <EventRow key={`${event.kind}-${event.url}-${event.at}`} event={event} />+ ))}+ </ul>+ )}+ {!all && events.length > EVENTS_SHOWN && (+ <Button+ variant="ghost"+ size="sm"+ className="mt-1 h-7 px-2 text-xs"+ onClick={() => setAll(true)}+ >+ {t('showAll', { count: events.length })}+ </Button>+ )}+ </div>+ <p className="text-[11px] text-muted-foreground">{t('note')}</p>+ </>+ )}+ </CardContent>+ </Card>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/competitors/_timeline-chart.tsx b/web/src/app/[locale]/(dashboard)/dashboard/competitors/_timeline-chart.tsxnew file mode 100644index 000000000..eb01facb7--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/competitors/_timeline-chart.tsx@@ -0,0 +1,174 @@+'use client';++import { useEffect, useRef, useState } from 'react';+import { useTranslations } from 'next-intl';+import { LineChart, Line, XAxis, YAxis, Tooltip, ReferenceLine } from 'recharts';+import { OWN_BRAND_COLOR } from '@/lib/insights-trend';+import { formatMonthDay, formatNumber } from '@/lib/format';+import { COMPETITOR_COLOR, type TimelineWeek } from '@/lib/competitor-timeline';+const HEIGHT = 220;++/** The chart's width follows its box. */+function useWidth() {+ const ref = useRef<HTMLDivElement>(null);+ const [width, setWidth] = useState(0);+ useEffect(() => {+ const el = ref.current;+ if (!el) return;+ const update = () => setWidth(el.clientWidth);+ update();+ const observer = new ResizeObserver(update);+ observer.observe(el);+ return () => observer.disconnect();+ }, []);+ return [ref, width] as const;+}++/** A week's events, as a badge on its line: how many pages were first cited or changed. */+function WeekBadge({+ viewBox,+ glyph,+ title,+}: {+ viewBox?: { x?: number; y?: number };+ glyph: string;+ title: string;+}) {+ if (viewBox?.x == null || viewBox.y == null) return <g />;+ return (+ <g>+ <title>{title}</title>+ <circle+ cx={viewBox.x}+ cy={viewBox.y + 9}+ r={8}+ className="fill-background stroke-muted-foreground/50"+ />+ <text+ x={viewBox.x}+ y={viewBox.y + 12.5}+ textAnchor="middle"+ fontSize={10}+ fontWeight={600}+ className="fill-muted-foreground"+ >+ {glyph}+ </text>+ </g>+ );+}++/**+ * The answers mentioning the brand and the competitor each week, and a+ * marker on each week something happened to the competitor's pages.+ */+export function CompetitorTimelineChart({+ weeks,+ marks,+ brandName,+ competitorName,+}: {+ weeks: TimelineWeek[];+ marks: { week: string; firstCited: number; changed: number }[];+ brandName: string;+ competitorName: string;+}) {+ const t = useTranslations('competitors.timeline');+ const [ref, width] = useWidth();+ const label = (week: string) => formatMonthDay(`${week}T00:00:00Z`, 'UTC');++ return (+ <div ref={ref} style={{ width: '100%', height: HEIGHT }}>+ {width > 0 && (+ <LineChart+ width={width}+ height={HEIGHT}+ data={weeks}+ margin={{ top: 4, right: 16, left: -24, bottom: 0 }}+ >+ <XAxis+ dataKey="week"+ tickFormatter={label}+ tick={{ fontSize: 11 }}+ tickLine={false}+ axisLine={false}+ className="fill-muted-foreground"+ />+ <YAxis+ allowDecimals={false}+ tickFormatter={(v: number) => formatNumber(v)}+ tick={{ fontSize: 11 }}+ tickLine={false}+ axisLine={false}+ className="fill-muted-foreground"+ />+ <Tooltip+ isAnimationActive={false}+ content={({ active, payload, label: week }) => {+ if (!active || !payload?.length) return null;+ const row = payload[0]?.payload as TimelineWeek | undefined;+ if (!row) return null;+ return (+ <div className="rounded-lg border bg-background px-3 py-2 text-xs shadow-md">+ <p className="mb-1 font-medium text-foreground">+ {t('weekOf', { date: label(String(week)) })}+ </p>+ {[+ { name: competitorName, value: row.competitor, color: COMPETITOR_COLOR },+ { name: brandName, value: row.brand, color: OWN_BRAND_COLOR },+ ].map((line) => (+ <div key={line.name} className="flex items-center gap-2">+ <span+ className="inline-block h-2 w-2 shrink-0 rounded-full"+ style={{ backgroundColor: line.color }}+ />+ <span className="text-muted-foreground">{line.name}:</span>+ <span className="font-medium text-foreground">+ {t('mentions', { count: line.value })}+ </span>+ </div>+ ))}+ </div>+ );+ }}+ />+ {marks.map((mark) => (+ <ReferenceLine+ key={mark.week}+ x={mark.week}+ className="stroke-muted-foreground/40"+ strokeDasharray="2 3"+ label={+ <WeekBadge+ glyph={String(mark.firstCited + mark.changed)}+ title={[+ mark.firstCited > 0 ? t('firstCitedBadge', { count: mark.firstCited }) : null,+ mark.changed > 0 ? t('changedBadge', { count: mark.changed }) : null,+ ]+ .filter(Boolean)+ .join(' · ')}+ />+ }+ />+ ))}+ <Line+ type="monotone"+ dataKey="brand"+ stroke={OWN_BRAND_COLOR}+ strokeWidth={2}+ dot={false}+ isAnimationActive={false}+ />+ <Line+ type="monotone"+ dataKey="competitor"+ stroke={COMPETITOR_COLOR}+ strokeWidth={2}+ dot={false}+ isAnimationActive={false}+ />+ </LineChart>+ )}+ </div>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.test.tsxindex fac231f01..375ab5517 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.test.tsx@@ -14,6 +14,7 @@ const competitorActions = vi.hoisted(() => ({getCompetitors: vi.fn(),addCompetitor: vi.fn(),deleteCompetitor: vi.fn(),+ getCompetitorTimeline: vi.fn(async () => ({ weeks: [], events: [] })),}));vi.mock('@/lib/actions/competitor', () => competitorActions);vi.mock('@/lib/actions/tracking', () => ({diff --git a/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsxindex 9f6c8e8a4..d65cba2cf 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx@@ -6,7 +6,14 @@ import { useTranslations } from 'next-intl';import { useBrandStore } from '@/stores/use-brand-store';import { useFeatureGate } from '@/hooks/use-feature-gate';import { useUpgradeGate } from '@/components/providers/upgrade-gate';-import { getCompetitors, addCompetitor, deleteCompetitor } from '@/lib/actions/competitor';+import {+ getCompetitors,+ addCompetitor,+ deleteCompetitor,+ getCompetitorTimeline,+} from '@/lib/actions/competitor';+import type { CompetitorTimeline } from '@/lib/competitor-timeline';+import { CompetitorTimelineCard } from './_timeline-card';import type { SuggestedCompetitor } from '@/lib/ai-brand-setup';import { SuggestCompetitorsDialog } from './_suggest-competitors-dialog';import {@@ -1277,6 +1284,11 @@ export default function CompetitorsPage() {}, []);const [h2hData, setH2hData] = useState<HeadToHeadData | null>(null);const [h2hLoading, setH2hLoading] = useState(false);+ // The selected competitor's pages over time (learning C3), kept with whose they are.+ const [timeline, setTimeline] = useState<{+ competitorId: string;+ data: CompetitorTimeline | 'failed';+ } | null>(null);const loadCompetitors = useCallback(async () => {if (!brand) return;@@ -1362,6 +1374,24 @@ export default function CompetitorsPage() {}}, [selectedCompetitorId, loadH2H]);+ useEffect(() => {+ if (!brand || !selectedCompetitorId) return;+ let cancelled = false;+ const competitorId = selectedCompetitorId;+ getCompetitorTimeline(brand.id, competitorId).then(+ (data) => {+ if (!cancelled) setTimeline({ competitorId, data });+ },+ (err) => {+ console.error('Failed to load the competitor timeline:', err);+ if (!cancelled) setTimeline({ competitorId, data: 'failed' });+ },+ );+ return () => {+ cancelled = true;+ };+ }, [brand, selectedCompetitorId]);+const loadRuns = useCallback((group: HeadToHeadGroup, limit: number) => {if (!brand || !selectedCompetitorId) return Promise.resolve([]);@@ -1680,6 +1710,12 @@ export default function CompetitorsPage() {</CardContent></Card>)}++ <CompetitorTimelineCard+ timeline={timeline?.competitorId === selectedCompetitorId ? timeline.data : null}+ brandName={brand.name}+ competitorName={selectedCompetitor?.name ?? ''}+ /></>)}</>diff --git a/web/src/lib/actions/competitor.ts b/web/src/lib/actions/competitor.tsindex 11f7eef31..51163eded 100644--- a/web/src/lib/actions/competitor.ts+++ b/web/src/lib/actions/competitor.ts@@ -4,6 +4,17 @@ import { createClient } from '@/lib/supabase/server';import { revalidatePath } from 'next/cache';import type { Competitor } from '@/types';import { assertWritable } from '@/lib/subscription-guard';+import { z } from 'zod';+import { readAllRpcRows } from '@/lib/supabase/rpc-pages';+import {+ parseTimelineEvents,+ timelineSince,+ weeklyMentions,+ type CompetitorTimeline,+} from '@/lib/competitor-timeline';++/** A competitor's page events the timeline reads at most. */+const TIMELINE_EVENTS = 50;function mapRow(row: Record<string, unknown>): Competitor {return {@@ -62,3 +73,56 @@ export async function deleteCompetitor(id: string): Promise<void> {revalidatePath('/dashboard/brands');}++/**+ * A competitor's pages over time (learning C3) for the Competitors page: the+ * brand's and the competitor's mentioning answers per week over the chart's+ * weeks (the daily rollups, every row read), and the competitor's page+ * events, newest first. RLS keeps both to the caller's organization.+ */+export async function getCompetitorTimeline(+ brandId: string,+ competitorId: string,+): Promise<CompetitorTimeline> {+ if (!z.guid().safeParse(brandId).success || !z.guid().safeParse(competitorId).success) {+ throw new Error('invalid');+ }+ const supabase = await createClient();+ const now = new Date();+ const since = timelineSince(now);+ type DayRow = { day: string; mention_answers: number | null };+ const daily = (table: 'insights_brand_daily' | 'insights_competitor_daily') =>+ readAllRpcRows<DayRow>((from, to) => {+ let query = supabase+ .from(table)+ .select('day, mention_answers')+ .eq('brand_id', brandId)+ .gte('day', since);+ if (table === 'insights_competitor_daily') query = query.eq('competitor_id', competitorId);+ return query+ .order('day')+ .order('platform')+ .order('model_used')+ .order('region')+ .range(from, to) as unknown as PromiseLike<{+ data: DayRow[] | null;+ error: { message: string } | null;+ }>;+ });+ const [brandRows, competitorRows, events] = await Promise.all([+ daily('insights_brand_daily'),+ daily('insights_competitor_daily'),+ supabase+ .from('competitor_page_events')+ .select('kind, at, url, domain, detail')+ .eq('brand_id', brandId)+ .eq('competitor_id', competitorId)+ .order('at', { ascending: false })+ .limit(TIMELINE_EVENTS),+ ]);+ if (events.error) throw new Error(events.error.message);+ return {+ weeks: weeklyMentions(brandRows, competitorRows, now),+ events: parseTimelineEvents(events.data ?? []),+ };+}diff --git a/web/src/lib/competitor-timeline.test.ts b/web/src/lib/competitor-timeline.test.tsnew file mode 100644index 000000000..ae08aa6d7--- /dev/null+++ b/web/src/lib/competitor-timeline.test.ts@@ -0,0 +1,122 @@+import { describe, expect, it } from 'vitest';+import {+ eventWeeks,+ parseTimelineEvents,+ timelineSince,+ weekStart,+ weeklyMentions,+} from './competitor-timeline';++/** A competitor's pages over time (learning C3), as the Competitors page reads them. */++// A Wednesday.+const NOW = new Date('2026-10-29T10:00:00Z');++describe('weeks', () => {+ it('start on Monday, and the chart reads twelve of them, this one last', () => {+ expect(weekStart('2026-10-29')).toBe('2026-10-26');+ expect(weekStart('2026-10-26T23:00:00Z')).toBe('2026-10-26');+ expect(weekStart('2026-11-01')).toBe('2026-10-26');+ expect(timelineSince(NOW)).toBe('2026-08-10');+ });++ it("sum each week's mentioning answers, a week with none at 0", () => {+ const weeks = weeklyMentions(+ [+ { day: '2026-10-27', mention_answers: 3 },+ { day: '2026-10-28', mention_answers: 2 },+ { day: '2026-08-01', mention_answers: 9 },+ ],+ [+ { day: '2026-10-29', mention_answers: 7 },+ { day: '2026-10-20', mention_answers: null },+ ],+ NOW,+ );+ expect(weeks).toHaveLength(12);+ expect(weeks[0]).toEqual({ week: '2026-08-10', brand: 0, competitor: 0 });+ expect(weeks.at(-1)).toEqual({ week: '2026-10-26', brand: 5, competitor: 7 });+ expect(weeks.at(-2)).toEqual({ week: '2026-10-19', brand: 0, competitor: 0 });+ });+});++describe('parseTimelineEvents', () => {+ it('reads the events, newest first, and nothing it does not know', () => {+ expect(+ parseTimelineEvents([+ {+ kind: 'first_cited',+ at: '2026-10-03T00:00:00Z',+ url: 'https://rival.com/kettles',+ domain: 'rival.com',+ detail: { answers: 4 },+ },+ {+ kind: 'changed',+ at: '2026-10-21T03:00:00Z',+ url: 'https://rival.com/kettles',+ domain: 'rival.com',+ detail: {+ similarity: 0.6,+ gained: [{ key: 'faq-schema', label: 'FAQ schema' }, { key: 'tables' }, 'x'],+ lost: [],+ },+ },+ { kind: 'other', at: '2026-10-21T03:00:00Z', url: 'https://rival.com/x' },+ { kind: 'changed', at: 'yesterday', url: 'https://rival.com/x' },+ { kind: 'changed', at: '2026-10-21T03:00:00Z', url: 'javascript:alert(1)' },+ ]),+ ).toEqual([+ {+ kind: 'changed',+ at: '2026-10-21T03:00:00Z',+ url: 'https://rival.com/kettles',+ domain: 'rival.com',+ answers: null,+ gained: [+ { key: 'faq-schema', label: 'FAQ schema' },+ { key: 'tables', label: 'tables' },+ ],+ lost: [],+ },+ {+ kind: 'first_cited',+ at: '2026-10-03T00:00:00Z',+ url: 'https://rival.com/kettles',+ domain: 'rival.com',+ answers: 4,+ gained: [],+ lost: [],+ },+ ]);+ });+});++describe('eventWeeks', () => {+ it("marks the chart's weeks with events, by kind, and none outside it", () => {+ const weeks = weeklyMentions([], [], NOW);+ const event = (kind: 'first_cited' | 'changed', at: string) => ({+ kind,+ at,+ url: 'https://rival.com/a',+ domain: 'rival.com',+ answers: null,+ gained: [],+ lost: [],+ });+ expect(+ eventWeeks(+ [+ event('changed', '2026-10-28T03:00:00Z'),+ event('first_cited', '2026-10-27T00:00:00Z'),+ event('first_cited', '2026-10-06T00:00:00Z'),+ event('first_cited', '2026-01-01T00:00:00Z'),+ ],+ weeks,+ ),+ ).toEqual([+ { week: '2026-10-05', firstCited: 1, changed: 0 },+ { week: '2026-10-26', firstCited: 1, changed: 1 },+ ]);+ });+});diff --git a/web/src/lib/competitor-timeline.ts b/web/src/lib/competitor-timeline.tsnew file mode 100644index 000000000..3987786c7--- /dev/null+++ b/web/src/lib/competitor-timeline.ts@@ -0,0 +1,152 @@+/**+ * A competitor's pages over time (learning C3), as the Competitors page shows+ * it: the competitor's and the brand's answers mentioning them, week by week,+ * beside the dated events the API keeps (competitor_page_events, 00376) —+ * the day a competitor page was first cited in the brand's answers, and the+ * days a weekly re-read found it changed, with the Site Audit checks it+ * gained and lost.+ */++/** Weeks the chart shows, the current one last. */+export const TIMELINE_WEEKS = 12;+/** The competitor's line: the Insights trend's first competitor color. */+export const COMPETITOR_COLOR = '#1e3a8a';++export interface TimelineWeek {+ /** The week's Monday, YYYY-MM-DD (UTC). */+ week: string;+ /** Answers that mentioned the brand, and the competitor. */+ brand: number;+ competitor: number;+}++export interface TimelineCheck {+ key: string;+ label: string;+}++export interface CompetitorPageEvent {+ kind: 'first_cited' | 'changed';+ /** When it happened (ISO). */+ at: string;+ url: string;+ domain: string;+ /** first_cited: the answers that cited it when it was first read. */+ answers: number | null;+ /** changed: the Site Audit checks it gained and lost. */+ gained: TimelineCheck[];+ lost: TimelineCheck[];+}++export interface CompetitorTimeline {+ weeks: TimelineWeek[];+ events: CompetitorPageEvent[];+}++const DAY_MS = 86_400_000;++/** The Monday of a day's week, YYYY-MM-DD (UTC). */+export function weekStart(day: string): string {+ const date = new Date(`${day.slice(0, 10)}T00:00:00Z`);+ const fromMonday = (date.getUTCDay() + 6) % 7;+ return new Date(date.getTime() - fromMonday * DAY_MS).toISOString().slice(0, 10);+}++/** The first day the chart reads: the Monday `weeks - 1` weeks before this one's. */+export function timelineSince(now: Date, weeks = TIMELINE_WEEKS): string {+ const monday = weekStart(now.toISOString());+ return new Date(Date.parse(`${monday}T00:00:00Z`) - (weeks - 1) * 7 * DAY_MS)+ .toISOString()+ .slice(0, 10);+}++/**+ * The daily rollups' mentioning answers summed per week: every week of the+ * chart, a week with none at 0.+ */+export function weeklyMentions(+ brandRows: readonly { day: string; mention_answers: number | null }[],+ competitorRows: readonly { day: string; mention_answers: number | null }[],+ now: Date,+ weeks = TIMELINE_WEEKS,+): TimelineWeek[] {+ const first = Date.parse(`${timelineSince(now, weeks)}T00:00:00Z`);+ const out = Array.from({ length: weeks }, (_, i) => ({+ week: new Date(first + i * 7 * DAY_MS).toISOString().slice(0, 10),+ brand: 0,+ competitor: 0,+ }));+ const byWeek = new Map(out.map((w) => [w.week, w]));+ for (const row of brandRows) {+ const week = byWeek.get(weekStart(row.day));+ if (week) week.brand += Number(row.mention_answers ?? 0);+ }+ for (const row of competitorRows) {+ const week = byWeek.get(weekStart(row.day));+ if (week) week.competitor += Number(row.mention_answers ?? 0);+ }+ return out;+}++const checks = (value: unknown): TimelineCheck[] =>+ Array.isArray(value)+ ? value.flatMap((c) => {+ const check = (c ?? {}) as Record<string, unknown>;+ return typeof check.key === 'string' && check.key+ ? [+ {+ key: check.key,+ label: typeof check.label === 'string' && check.label ? check.label : check.key,+ },+ ]+ : [];+ })+ : [];++/** The events as stored, read defensively, newest first. */+export function parseTimelineEvents(+ rows: readonly Record<string, unknown>[],+): CompetitorPageEvent[] {+ return rows+ .flatMap((row) => {+ const kind: CompetitorPageEvent['kind'] | null =+ row.kind === 'first_cited' || row.kind === 'changed' ? row.kind : null;+ const at = typeof row.at === 'string' && !Number.isNaN(Date.parse(row.at)) ? row.at : null;+ const url = typeof row.url === 'string' && /^https?:\/\//i.test(row.url) ? row.url : null;+ if (!kind || !at || !url) return [];+ const detail = (row.detail ?? {}) as Record<string, unknown>;+ return [+ {+ kind,+ at,+ url,+ domain: typeof row.domain === 'string' ? row.domain : '',+ answers:+ typeof detail.answers === 'number' && Number.isFinite(detail.answers)+ ? detail.answers+ : null,+ gained: checks(detail.gained),+ lost: checks(detail.lost),+ },+ ];+ })+ .sort((a, b) => Date.parse(b.at) - Date.parse(a.at));+}++/** The weeks of the chart with events in them, and how many of each kind. */+export function eventWeeks(+ events: readonly CompetitorPageEvent[],+ weeks: readonly TimelineWeek[],+): { week: string; firstCited: number; changed: number }[] {+ const shown = new Set(weeks.map((w) => w.week));+ const counts = new Map<string, { week: string; firstCited: number; changed: number }>();+ for (const event of events) {+ const week = weekStart(event.at);+ if (!shown.has(week)) continue;+ const count = counts.get(week) ?? { week, firstCited: 0, changed: 0 };+ if (event.kind === 'first_cited') count.firstCited += 1;+ else count.changed += 1;+ counts.set(week, count);+ }+ return [...counts.values()].sort((a, b) => a.week.localeCompare(b.week));+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 58d61313e..603d19ed4 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -1710,6 +1710,60 @@ export type Database = {},]}+ competitor_page_events: {+ Row: {+ at: string+ brand_id: string+ competitor_id: string+ created_at: string+ detail: Json+ domain: string+ id: string+ kind: string+ page_key: string+ url: string+ }+ Insert: {+ at: string+ brand_id: string+ competitor_id: string+ created_at?: string+ detail?: Json+ domain: string+ id?: string+ kind: string+ page_key: string+ url: string+ }+ Update: {+ at?: string+ brand_id?: string+ competitor_id?: string+ created_at?: string+ detail?: Json+ domain?: string+ id?: string+ kind?: string+ page_key?: string+ url?: string+ }+ Relationships: [+ {+ foreignKeyName: "competitor_page_events_brand_id_fkey"+ columns: ["brand_id"]+ isOneToOne: false+ referencedRelation: "brands"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "competitor_page_events_competitor_id_fkey"+ columns: ["competitor_id"]+ isOneToOne: false+ referencedRelation: "competitors"+ referencedColumns: ["id"]+ },+ ]+ }competitors: {Row: {brand_id: string