Skip to content

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.

feat(action-center): keep when a competitor page was first cited and when it changed (learning C3, part 1) (#1745)

Cihanc1537325a1b1
diff --git a/server/src/config/action-engine.js b/server/src/config/action-engine.js
index b7ceb0101..d698d1038 100644
--- a/server/src/config/action-engine.js
+++ b/server/src/config/action-engine.js
@@ -456,6 +456,24 @@ export const ENGINE_THRESHOLDS = Object.freeze({
missingPages: 5,
retryDays: 7,
}),
+
+ /**
+ * A competitor's pages over time (learning C3). first_cited: a competitor
+ * never read is read back `backfillDays` once, the others from their last
+ * read. changed: each night, a brand's `pagesPerBrand` competitor pages its
+ * answers cited most over the last `citedDays` are read again once their
+ * last read is `rereadDays` old, within what is left of the brand's
+ * `competitorPages.perBrandPerDay` reads after the tasks' (C1, C4), and
+ * compared with that read's word sketch (task-checks' CHANGED_BELOW and
+ * MIN_CHANGED_RUNS). At most `brandsPerNight` brands a night.
+ */
+ competitorTimeline: Object.freeze({
+ backfillDays: 90,
+ citedDays: 14,
+ pagesPerBrand: 10,
+ rereadDays: 7,
+ brandsPerNight: 200,
+ }),
});
/**
diff --git a/server/src/lib/action-center/competitor-pages.js b/server/src/lib/action-center/competitor-pages.js
index 824bc493a..17e1fcf92 100644
--- a/server/src/lib/action-center/competitor-pages.js
+++ b/server/src/lib/action-center/competitor-pages.js
@@ -30,6 +30,7 @@ import { logger } from '../logger.js';
import { topicPromptIds } from './basket-metrics.js';
import { promptIdsOf } from './priority.js';
import { FEATURE_CHECKS, featureGaps, pageFeatures } from './page-features.js';
+import { sketch as wordSketch, visibleText } from './task-checks.js';
// The page checks live in page-features.js, which reads no database; kept
// here for the imports that name this module.
@@ -187,21 +188,30 @@ export async function scopePromptIds(brandId, payload) {
* Each page's features, set on it as `features` when it could be read: one
* read (or found unreadable) within `freshDays` is reused, the rest are read
* now, unless their site's robots.txt shuts the reader out, and kept
- * (cited_page_features) with what the checks found, never the text. All of
- * the pages are read the same night, or none: ReadLaterError when the
- * brand's reads left today (`perBrandPerDay`, shared by every task that
- * reads pages: C1's and C4's) can't cover them.
+ * (cited_page_features) with what the checks found and a sketch of its words
+ * (learning C3), never the text. A page read now gets its new sketch as
+ * `sketch`, and what the read before kept as `before` ({ features, sketch }).
+ * All of the pages are read the same night, or none: ReadLaterError when the
+ * brand's reads left today (`perBrandPerDay`, shared by every reader: C1's,
+ * C4's and C3's weekly re-read) can't cover them.
*
* @param {{ brandId: string,
- * pages: Array<{ key: string, url: string, domain: string, own?: boolean, features?: object }>,
- * now: Date, read: typeof fetchPage }} input
+ * pages: Array<{ key: string, url: string, domain: string, own?: boolean, features?: object,
+ * sketch?: object, before?: object }>,
+ * now: Date, read?: typeof fetchPage, freshDays?: number }} input
*/
-export async function readPages({ brandId, pages, now, read = fetchPage }) {
+export async function readPages({
+ brandId,
+ pages,
+ now,
+ read = fetchPage,
+ freshDays = C.freshDays,
+}) {
if (pages.length === 0) return;
const [knownRes, todayRes] = await Promise.all([
supabaseAdmin
.from('cited_page_features')
- .select('page_key, features, read_at')
+ .select('page_key, features, sketch, read_at')
.eq('brand_id', brandId)
.in(
'page_key',
@@ -215,7 +225,8 @@ export async function readPages({ brandId, pages, now, read = fetchPage }) {
]);
if (knownRes.error) throw new Error(knownRes.error.message);
if (todayRes.error) throw new Error(todayRes.error.message);
- const freshSince = now.getTime() - C.freshDays * DAY_MS;
+ const freshSince = now.getTime() - freshDays * DAY_MS;
+ const known = new Map((knownRes.data ?? []).map((row) => [row.page_key, row]));
const fresh = new Map(
(knownRes.data ?? [])
.filter((row) => Date.parse(row.read_at) >= freshSince)
@@ -234,7 +245,10 @@ export async function readPages({ brandId, pages, now, read = fetchPage }) {
if (!known.unreadable) page.features = known;
continue;
}
+ const before = known.get(page.key);
+ if (before) page.before = { features: before.features ?? {}, sketch: before.sketch ?? null };
let features = null;
+ let sketched = null;
let disallowed = false;
try {
const origin = new URL(page.url).origin;
@@ -243,11 +257,14 @@ export async function readPages({ brandId, pages, now, read = fetchPage }) {
if (!disallowed) {
const fetched = await read(page.url, { timeoutMs: READ_TIMEOUT_MS });
features = await pageFeatures(fetched.url, fetched.html, now.getTime());
+ // Its words as the page checks measure a change: what changes by itself left out.
+ if (features) sketched = wordSketch(visibleText(fetched.html, undefined, { steady: true }));
}
} catch {
// A page that blocks the reader, or isn't one: unreadable, not a failure.
}
if (features) page.features = features;
+ if (sketched) page.sketch = sketched;
// An unreadable page is kept too: it counts against the day's reads and
// isn't tried again while it would be fresh.
const { error } = await supabaseAdmin.from('cited_page_features').upsert(
@@ -258,6 +275,8 @@ export async function readPages({ brandId, pages, now, read = fetchPage }) {
domain: page.domain,
own: Boolean(page.own),
features: features ?? { unreadable: true, ...(disallowed ? { disallowed: true } : {}) },
+ // An unreadable read keeps the last sketch, to compare the next one with.
+ sketch: sketched ?? before?.sketch ?? null,
read_at: now.toISOString(),
},
{ onConflict: 'brand_id,page_key' },
diff --git a/server/src/lib/action-center/competitor-timeline.js b/server/src/lib/action-center/competitor-timeline.js
new file mode 100644
index 000000000..f2f6dd31d
--- /dev/null
+++ b/server/src/lib/action-center/competitor-timeline.js
@@ -0,0 +1,348 @@
+/**
+ * A competitor's pages over time (learning C3).
+ *
+ * A competitor rising in AI answers had no "why" beside it. This keeps two
+ * kinds of dated events for the competitor pages the brand's own tracked
+ * answers cite (competitor_page_events, 00376):
+ *
+ * - first_cited: the first day the brand's answers cited the page, read in
+ * the database from its citations (competitor_cited_urls): no page read.
+ * A competitor never read is read back `backfillDays` once
+ * (competitor_timeline_scans), so it is the first since then;
+ * - changed: a weekly re-read of the competitor pages the answers cite most
+ * found its words changed by more than a date or a price moving (the
+ * Action Center's page checks' rule, task-checks.js), with the Site Audit
+ * checks it gained and lost.
+ *
+ * Pages are read as "Analyze competitor content" reads them
+ * (competitor-pages.js readPages): free, robots.txt respected, within the
+ * brand's daily reads, after the night's tasks have read theirs. What is
+ * kept of a read is what the checks found and a sketch of its words, never
+ * its text. Nothing is compared across brands.
+ */
+
+import supabaseAdmin from '../../config/supabase.js';
+import { resolve } from '../../config/action-engine.js';
+import { isCloud, isSubscriptionActive } from '../../config/plans.js';
+import { fetchPage } from '../safe-fetch.js';
+import { logger } from '../logger.js';
+import { selectInChunks } from '../chunked-in.js';
+import { opportunityKey } from '../audit/opportunities.js';
+import { describeSignal } from '../audit/rubric.js';
+import { readPages } from './competitor-pages.js';
+import { FEATURE_CHECKS } from './page-features.js';
+import {
+ CHANGED_BELOW,
+ MIN_CHANGED_RUNS,
+ SKETCH_VERSION,
+ changedRuns,
+ similarity,
+} from './task-checks.js';
+
+const { competitorPages: CP, competitorTimeline: T } = resolve();
+
+const DAY_MS = 86_400_000;
+/** A night's sweep stops starting brands after this, as the brand facts sweep. */
+const SWEEP_DEADLINE_MS = 10 * 60_000;
+/** PostgREST's most rows a read returns (max_rows): a longer read goes page by page. */
+const PAGE_ROWS = 1000;
+/** Page keys per `in` filter: they are addresses, so fewer than ids fit a request's URL. */
+const KEYS_PER_READ = 30;
+
+/**
+ * Every row of a read, past PostgREST's row cap: `build` makes the ordered
+ * query, read a page of PAGE_ROWS at a time.
+ */
+async function allRows(build) {
+ const rows = [];
+ for (let from = 0; ; from += PAGE_ROWS) {
+ const { data, error } = await build().range(from, from + PAGE_ROWS - 1);
+ if (error) throw new Error(error.message);
+ rows.push(...(data ?? []));
+ if ((data ?? []).length < PAGE_ROWS) return rows;
+ }
+}
+
+/**
+ * The cited competitor URLs as pages: one per page key (a URL's query left
+ * out), its first citation the earliest of its URLs', its answers summed.
+ *
+ * @param {Array<{ url: string, domain: string, competitor_id: string,
+ * first_at: string, answers: number }>} rows
+ */
+export function citedCompetitorPages(rows) {
+ const pages = new Map();
+ for (const row of rows) {
+ const key = row.url ? opportunityKey(row.url) : null;
+ if (!key || !/^https?:\/\//i.test(row.url)) continue;
+ const page = pages.get(key);
+ if (!page) {
+ pages.set(key, {
+ key,
+ url: row.url,
+ domain: row.domain,
+ competitorId: row.competitor_id,
+ firstAt: row.first_at,
+ answers: Number(row.answers ?? 0),
+ });
+ continue;
+ }
+ page.answers += Number(row.answers ?? 0);
+ if (Date.parse(row.first_at) < Date.parse(page.firstAt)) page.firstAt = row.first_at;
+ }
+ return [...pages.values()];
+}
+
+/** A Site Audit check as an event keeps it: its key, and its name as the rubric gives it. */
+const checkOf = (key) => ({ key, label: describeSignal(key)?.label ?? key });
+
+/**
+ * Whether a re-read page changed since the read before: its words by the
+ * page checks' rule, and the Site Audit checks it gained and lost. Null when
+ * there is no earlier sketch to compare (the first read), or it didn't.
+ */
+export function pageChange(before, sketch, checks) {
+ const first = before?.sketch;
+ if (
+ !sketch ||
+ !Array.isArray(first?.hashes) ||
+ !Number.isFinite(first?.runs) ||
+ first.v !== SKETCH_VERSION ||
+ sketch.v !== SKETCH_VERSION
+ ) {
+ return null;
+ }
+ const j = similarity(first.hashes, sketch.hashes);
+ if (j >= CHANGED_BELOW || changedRuns(first, sketch) < MIN_CHANGED_RUNS) return null;
+ const was = before.features?.checks ?? {};
+ const now = checks ?? {};
+ return {
+ similarity: Math.round(j * 100) / 100,
+ gained: FEATURE_CHECKS.filter((key) => now[key] === 'pass' && was[key] !== 'pass').map(checkOf),
+ lost: FEATURE_CHECKS.filter((key) => was[key] === 'pass' && now[key] !== 'pass').map(checkOf),
+ };
+}
+
+async function citedUrls(brandId, since) {
+ // A brand's 90 days back can cite more competitor addresses than a read returns.
+ const rows = await allRows(() =>
+ supabaseAdmin
+ .rpc('competitor_cited_urls', { p_brand_id: brandId, p_since: since.toISOString() })
+ .order('url')
+ .order('competitor_id'),
+ );
+ return citedCompetitorPages(rows);
+}
+
+/**
+ * Records the brand's competitor pages first cited since each competitor's
+ * last read (`backfillDays` back for one never read), once each.
+ */
+export async function recordFirstCitations(brandId, now = new Date()) {
+ const [competitorsRes, scansRes] = await Promise.all([
+ supabaseAdmin.from('competitors').select('id').eq('brand_id', brandId),
+ supabaseAdmin
+ .from('competitor_timeline_scans')
+ .select('competitor_id, scanned_at')
+ .eq('brand_id', brandId),
+ ]);
+ for (const res of [competitorsRes, scansRes]) if (res.error) throw new Error(res.error.message);
+ const competitorIds = (competitorsRes.data ?? []).map((row) => row.id);
+ if (competitorIds.length === 0) return 0;
+ const scanned = new Map((scansRes.data ?? []).map((row) => [row.competitor_id, row.scanned_at]));
+ // A day's overlap with the last read: answers stamped late aren't missed.
+ const sinceMs = Math.min(
+ ...competitorIds.map((id) =>
+ scanned.has(id)
+ ? Date.parse(scanned.get(id)) - DAY_MS
+ : now.getTime() - T.backfillDays * DAY_MS,
+ ),
+ );
+ const pages = await citedUrls(brandId, new Date(sinceMs));
+
+ let recorded = 0;
+ if (pages.length > 0) {
+ // Read in parts: hundreds of addresses in one filter pass a request's URL limit.
+ const { data: known, error } = await selectInChunks(
+ pages.map((page) => page.key),
+ (keys) =>
+ supabaseAdmin
+ .from('competitor_page_events')
+ .select('page_key')
+ .eq('brand_id', brandId)
+ .eq('kind', 'first_cited')
+ .in('page_key', keys),
+ KEYS_PER_READ,
+ );
+ if (error) throw new Error(error.message);
+ const seen = new Set((known ?? []).map((row) => row.page_key));
+ const fresh = pages.filter((page) => !seen.has(page.key));
+ if (fresh.length > 0) {
+ const { error: insertError } = await supabaseAdmin.from('competitor_page_events').insert(
+ fresh.map((page) => ({
+ brand_id: brandId,
+ competitor_id: page.competitorId,
+ page_key: page.key,
+ url: page.url,
+ domain: page.domain,
+ kind: 'first_cited',
+ at: page.firstAt,
+ detail: { answers: page.answers },
+ })),
+ );
+ if (insertError) throw new Error(insertError.message);
+ recorded = fresh.length;
+ }
+ }
+
+ const { error: scanError } = await supabaseAdmin.from('competitor_timeline_scans').upsert(
+ competitorIds.map((id) => ({
+ competitor_id: id,
+ brand_id: brandId,
+ scanned_at: now.toISOString(),
+ })),
+ { onConflict: 'competitor_id' },
+ );
+ if (scanError) throw new Error(scanError.message);
+ return recorded;
+}
+
+/**
+ * Reads again the brand's competitor pages its answers cited most lately
+ * whose last read is `rereadDays` old, as many as its reads left today
+ * allow, and records those that changed.
+ *
+ * @param {string} brandId
+ * @param {{ now?: Date, read?: typeof fetchPage }} [options] read: the page reader, for tests
+ */
+export async function recordPageChanges(brandId, { now = new Date(), read = fetchPage } = {}) {
+ const cited = await citedUrls(brandId, new Date(now.getTime() - T.citedDays * DAY_MS));
+ const top = cited
+ .sort((a, b) => b.answers - a.answers || a.key.localeCompare(b.key))
+ .slice(0, T.pagesPerBrand);
+ if (top.length === 0) return 0;
+
+ const [knownRes, todayRes] = await Promise.all([
+ supabaseAdmin
+ .from('cited_page_features')
+ .select('page_key, read_at')
+ .eq('brand_id', brandId)
+ .in(
+ 'page_key',
+ top.map((page) => page.key),
+ ),
+ supabaseAdmin
+ .from('cited_page_features')
+ .select('id', { count: 'exact', head: true })
+ .eq('brand_id', brandId)
+ .gte('read_at', `${now.toISOString().slice(0, 10)}T00:00:00.000Z`),
+ ]);
+ for (const res of [knownRes, todayRes]) if (res.error) throw new Error(res.error.message);
+ const readAt = new Map((knownRes.data ?? []).map((row) => [row.page_key, row.read_at]));
+ const staleBefore = now.getTime() - T.rereadDays * DAY_MS;
+ const left = Math.max(0, CP.perBrandPerDay - (todayRes.count ?? 0));
+ const pages = top
+ .filter((page) => !readAt.has(page.key) || Date.parse(readAt.get(page.key)) < staleBefore)
+ .slice(0, left)
+ .map((page) => ({
+ key: page.key,
+ url: page.url,
+ domain: page.domain,
+ competitorId: page.competitorId,
+ }));
+ if (pages.length === 0) return 0;
+
+ // Every page here is due, so none is reused as fresh.
+ await readPages({ brandId, pages, now, read, freshDays: T.rereadDays });
+ const changed = pages.flatMap((page) => {
+ const change = pageChange(page.before, page.sketch, page.features?.checks);
+ return change
+ ? [
+ {
+ brand_id: brandId,
+ competitor_id: page.competitorId,
+ page_key: page.key,
+ url: page.url,
+ domain: page.domain,
+ kind: 'changed',
+ at: now.toISOString(),
+ detail: change,
+ },
+ ]
+ : [];
+ });
+ if (changed.length > 0) {
+ const { error } = await supabaseAdmin.from('competitor_page_events').insert(changed);
+ if (error) throw new Error(error.message);
+ }
+ return changed.length;
+}
+
+/**
+ * The night's pass over the brands with competitors (on Cloud, those whose
+ * organization's plan is active): their first citations, then their pages'
+ * changes. A brand that fails is logged and the next one goes on.
+ */
+export async function sweepCompetitorTimeline({
+ now = new Date(),
+ limit = T.brandsPerNight,
+ read = fetchPage,
+} = {}) {
+ // Every brand's competitors and reads, past the read's row cap.
+ const rows = await allRows(() =>
+ supabaseAdmin
+ .from('competitors')
+ .select('id, brand_id, brands!inner(organization_id, is_active)')
+ .eq('brands.is_active', true)
+ .neq('domain', '')
+ .order('id'),
+ );
+ const brands = new Map();
+ for (const row of rows) brands.set(row.brand_id, row.brands.organization_id);
+ // The brands read longest ago first, never read before them: past the
+ // night's limit, the rest are first in line the next night.
+ const scans = await allRows(() =>
+ supabaseAdmin
+ .from('competitor_timeline_scans')
+ .select('competitor_id, brand_id, scanned_at')
+ .order('competitor_id'),
+ );
+ const lastRead = new Map();
+ for (const scan of scans) {
+ const at = Date.parse(scan.scanned_at);
+ if (!(at <= (lastRead.get(scan.brand_id) ?? -Infinity))) lastRead.set(scan.brand_id, at);
+ }
+ const order = [...brands.keys()].sort(
+ (a, b) => (lastRead.get(a) ?? -Infinity) - (lastRead.get(b) ?? -Infinity),
+ );
+
+ let active = () => true;
+ if (brands.size > 0 && isCloud()) {
+ const { data: orgs, error: orgError } = await selectInChunks([...brands.values()], (ids) =>
+ supabaseAdmin.from('organizations').select('id, subscription_status').in('id', ids),
+ );
+ if (orgError) throw new Error(orgError.message);
+ const subscribed = new Set(
+ (orgs ?? []).filter((o) => isSubscriptionActive(o.subscription_status)).map((o) => o.id),
+ );
+ active = (orgId) => subscribed.has(orgId);
+ }
+
+ const outcome = { brands: 0, firstCited: 0, changed: 0, failed: 0 };
+ const started = Date.now();
+ for (const brandId of order) {
+ const orgId = brands.get(brandId);
+ if (outcome.brands >= limit || Date.now() - started > SWEEP_DEADLINE_MS) break;
+ if (!active(orgId)) continue;
+ outcome.brands += 1;
+ try {
+ outcome.firstCited += await recordFirstCitations(brandId, now);
+ outcome.changed += await recordPageChanges(brandId, { now, read });
+ } catch (err) {
+ outcome.failed += 1;
+ logger.warn({ err, brandId }, '[competitor-timeline] brand failed');
+ }
+ }
+ logger.info(outcome, '[competitor-timeline] sweep done');
+ return outcome;
+}
diff --git a/server/src/lib/action-center/competitor-timeline.test.js b/server/src/lib/action-center/competitor-timeline.test.js
new file mode 100644
index 000000000..495c2ac2d
--- /dev/null
+++ b/server/src/lib/action-center/competitor-timeline.test.js
@@ -0,0 +1,367 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * A competitor's pages over time (learning C3): the pages first cited, read
+ * from the citations once each, and the weekly re-read of those cited most,
+ * within the brand's reads left, recording the ones whose words changed.
+ */
+
+let tables;
+let inserts;
+let upserts;
+let rpcCalls;
+let todayReads;
+/** The values of each `in` filter, and the pages each read asked for. */
+let inFilters;
+let ranges;
+
+/** A read's rows, past the cap a page at a time as PostgREST's `range` gives them. */
+const paged = (rows, range) => (range ? rows.slice(range[0], range[1] + 1) : rows.slice(0, 1000));
+
+/** A table as the service role reads it: `eq`, `neq` and `in` keep the rows that match. */
+vi.mock('../../config/supabase.js', () => ({
+ default: {
+ rpc: (name, args) => {
+ rpcCalls.push([name, args]);
+ let range = null;
+ const chain = {
+ order: () => chain,
+ range: (from, to) => ((range = [from, to]), ranges.push([`rpc:${name}`, from]), chain),
+ then: (resolve) =>
+ resolve({ data: paged(tables[`rpc:${name}`] ?? [], range), error: null }),
+ };
+ return chain;
+ },
+ from: (table) => {
+ const where = [];
+ let head = false;
+ let range = null;
+ const chain = {
+ select: (_cols, opts) => ((head = opts?.head ?? false), chain),
+ eq: (column, value) => {
+ const [own, nested] = column.split('.');
+ where.push((row) => (nested ? row[own]?.[nested] : row[own]) === value);
+ return chain;
+ },
+ neq: (column, value) => (where.push((row) => row[column] !== value), chain),
+ in: (column, values) => (
+ inFilters.push([table, values.length]),
+ where.push((row) => values.includes(row[column])),
+ chain
+ ),
+ range: (from, to) => ((range = [from, to]), ranges.push([table, from]), chain),
+ gte: () => chain,
+ order: () => chain,
+ limit: () => chain,
+ insert: async (rows) => (inserts.push([table, rows]), { error: null }),
+ upsert: async (rows) => (upserts.push([table, rows]), { error: null }),
+ then: (resolve) =>
+ resolve(
+ head
+ ? { count: todayReads, error: null }
+ : {
+ data: paged(
+ (tables[table] ?? []).filter((row) => where.every((keep) => keep(row))),
+ range,
+ ),
+ error: null,
+ },
+ ),
+ };
+ return chain;
+ },
+ },
+}));
+vi.mock('../logger.js', () => ({ logger: { warn: vi.fn(), error: vi.fn(), info: vi.fn() } }));
+
+const {
+ citedCompetitorPages,
+ pageChange,
+ recordFirstCitations,
+ recordPageChanges,
+ sweepCompetitorTimeline,
+} = await import('./competitor-timeline.js');
+const { sketch, visibleText } = await import('./task-checks.js');
+
+const NOW = new Date('2026-10-29T03:00:00Z');
+const BRAND = 'brand-1';
+
+const paragraph = (word) =>
+ `<p>${Array.from({ length: 60 }, (_, i) => `${word} kettle number ${i} boils water fast`).join(' ')}</p>`;
+const PAGE_V1 = `<html><body><h1>Kettles</h1>${paragraph('steel')}</body></html>`;
+// Rewritten, and an FAQ added: its words and its checks changed.
+const PAGE_V2 = `<html><head><script type="application/ld+json">${JSON.stringify({
+ '@type': 'FAQPage',
+ mainEntity: [{ '@type': 'Question' }],
+})}</script></head><body><h1>Kettles</h1>${paragraph('glass')}<h2>FAQ</h2>${paragraph('copper')}</body></html>`;
+const wordsOf = (html) => sketch(visibleText(html, undefined, { steady: true }));
+const notFound = () =>
+ Object.assign(new Error('The page answered 404'), { code: 'http_error', status: 404 });
+const reader = (pages) =>
+ vi.fn(async (url) => {
+ if (url.endsWith('/robots.txt')) throw notFound();
+ return { url, html: pages[url] ?? PAGE_V1 };
+ });
+
+const cited = (url, answers, firstAt = '2026-10-20T00:00:00Z', competitor = 'c1') => ({
+ url,
+ domain: new URL(url).hostname.replace(/^www\./, ''),
+ competitor_id: competitor,
+ first_at: firstAt,
+ answers,
+});
+
+beforeEach(() => {
+ inserts = [];
+ upserts = [];
+ rpcCalls = [];
+ inFilters = [];
+ ranges = [];
+ todayReads = 0;
+ tables = {
+ competitors: [{ id: 'c1', brand_id: BRAND, domain: 'rival.com' }],
+ competitor_timeline_scans: [],
+ competitor_page_events: [],
+ cited_page_features: [],
+ 'rpc:competitor_cited_urls': [],
+ };
+});
+
+describe('citedCompetitorPages', () => {
+ it('reads one page per key: its first citation the earliest, its answers summed', () => {
+ expect(
+ citedCompetitorPages([
+ cited('https://rival.com/kettles?utm=x', 2, '2026-10-21T00:00:00Z'),
+ cited('https://www.rival.com/kettles/', 3, '2026-10-18T00:00:00Z'),
+ {
+ url: 'not a url',
+ domain: '',
+ competitor_id: 'c1',
+ first_at: '2026-10-01T00:00:00Z',
+ answers: 9,
+ },
+ ]),
+ ).toEqual([
+ {
+ key: 'rival.com/kettles',
+ url: 'https://rival.com/kettles?utm=x',
+ domain: 'rival.com',
+ competitorId: 'c1',
+ firstAt: '2026-10-18T00:00:00Z',
+ answers: 5,
+ },
+ ]);
+ });
+});
+
+describe('pageChange', () => {
+ it('says nothing for a first read, or a page whose words barely moved', () => {
+ expect(pageChange(undefined, wordsOf(PAGE_V1), {})).toBeNull();
+ expect(pageChange({ sketch: wordsOf(PAGE_V1) }, wordsOf(PAGE_V1), {})).toBeNull();
+ });
+
+ it('says a rewritten page changed, and the checks it gained and lost', () => {
+ const change = pageChange(
+ { sketch: wordsOf(PAGE_V1), features: { checks: { lists: 'pass', 'faq-schema': 'fail' } } },
+ wordsOf(PAGE_V2),
+ { lists: 'fail', 'faq-schema': 'pass' },
+ );
+ expect(change).toMatchObject({
+ gained: [{ key: 'faq-schema', label: expect.any(String) }],
+ lost: [{ key: 'lists', label: expect.any(String) }],
+ });
+ expect(change.similarity).toBeLessThan(0.9);
+ });
+});
+
+describe('recordFirstCitations', () => {
+ it('reads a new competitor back 90 days, and records each page first cited once', async () => {
+ tables['rpc:competitor_cited_urls'] = [
+ cited('https://rival.com/kettles', 4, '2026-09-10T00:00:00Z'),
+ cited('https://rival.com/old', 1, '2026-08-01T00:00:00Z'),
+ ];
+ tables.competitor_page_events = [
+ { brand_id: BRAND, kind: 'first_cited', page_key: 'rival.com/old' },
+ ];
+ expect(await recordFirstCitations(BRAND, NOW)).toBe(1);
+ expect(rpcCalls).toEqual([
+ ['competitor_cited_urls', { p_brand_id: BRAND, p_since: '2026-07-31T03:00:00.000Z' }],
+ ]);
+ expect(inserts).toEqual([
+ [
+ 'competitor_page_events',
+ [
+ {
+ brand_id: BRAND,
+ competitor_id: 'c1',
+ page_key: 'rival.com/kettles',
+ url: 'https://rival.com/kettles',
+ domain: 'rival.com',
+ kind: 'first_cited',
+ at: '2026-09-10T00:00:00Z',
+ detail: { answers: 4 },
+ },
+ ],
+ ],
+ ]);
+ expect(upserts).toEqual([
+ [
+ 'competitor_timeline_scans',
+ [{ competitor_id: 'c1', brand_id: BRAND, scanned_at: NOW.toISOString() }],
+ ],
+ ]);
+ });
+
+ it("reads every page a brand cited past a read's row cap, and asks for the known ones in parts", async () => {
+ tables['rpc:competitor_cited_urls'] = Array.from({ length: 2_500 }, (_, i) =>
+ cited(`https://rival.com/page-${i}`, 1),
+ );
+ tables.competitor_page_events = [
+ { brand_id: BRAND, kind: 'first_cited', page_key: 'rival.com/page-2400' },
+ ];
+ expect(await recordFirstCitations(BRAND, NOW)).toBe(2_499);
+ expect(ranges.filter(([name]) => name === 'rpc:competitor_cited_urls')).toEqual([
+ ['rpc:competitor_cited_urls', 0],
+ ['rpc:competitor_cited_urls', 1000],
+ ['rpc:competitor_cited_urls', 2000],
+ ]);
+ const keyReads = inFilters.filter(([table]) => table === 'competitor_page_events');
+ expect(keyReads.length).toBeGreaterThan(1);
+ expect(Math.max(...keyReads.map(([, n]) => n))).toBeLessThanOrEqual(30);
+ });
+
+ it('reads a competitor read before from a day before its last read', async () => {
+ tables.competitor_timeline_scans = [
+ { competitor_id: 'c1', brand_id: BRAND, scanned_at: '2026-10-28T03:00:00Z' },
+ ];
+ expect(await recordFirstCitations(BRAND, NOW)).toBe(0);
+ expect(rpcCalls[0][1].p_since).toBe('2026-10-27T03:00:00.000Z');
+ expect(inserts).toEqual([]);
+ });
+});
+
+describe('recordPageChanges', () => {
+ it('reads again the most cited pages whose last read is a week old, and records those that changed', async () => {
+ tables['rpc:competitor_cited_urls'] = [
+ cited('https://rival.com/kettles', 9),
+ cited('https://rival.com/fresh', 7),
+ cited('https://rival.com/new', 3),
+ ];
+ tables.cited_page_features = [
+ {
+ brand_id: BRAND,
+ page_key: 'rival.com/kettles',
+ read_at: '2026-10-20T00:00:00Z',
+ features: { words: 600, checks: { 'faq-schema': 'fail' } },
+ sketch: wordsOf(PAGE_V1),
+ },
+ // Read three days ago: not due.
+ { brand_id: BRAND, page_key: 'rival.com/fresh', read_at: '2026-10-26T00:00:00Z' },
+ ];
+ const read = reader({ 'https://rival.com/kettles': PAGE_V2 });
+
+ expect(await recordPageChanges(BRAND, { now: NOW, read })).toBe(1);
+ const pagesRead = read.mock.calls
+ .map(([url]) => url)
+ .filter((url) => !url.endsWith('robots.txt'));
+ expect(pagesRead).toEqual(['https://rival.com/kettles', 'https://rival.com/new']);
+ // Each read keeps its sketch for the next one.
+ const kept = upserts.filter(([table]) => table === 'cited_page_features').map(([, row]) => row);
+ expect(kept.map((row) => [row.page_key, row.sketch?.v])).toEqual([
+ ['rival.com/kettles', 2],
+ ['rival.com/new', 2],
+ ]);
+ // The new page's first read is a baseline, not a change.
+ expect(inserts).toEqual([
+ [
+ 'competitor_page_events',
+ [
+ expect.objectContaining({
+ competitor_id: 'c1',
+ page_key: 'rival.com/kettles',
+ kind: 'changed',
+ at: NOW.toISOString(),
+ // The JSON-LD it now has, among what Site Audit's checks found.
+ detail: expect.objectContaining({
+ gained: expect.arrayContaining([
+ expect.objectContaining({ key: 'json-ld-presence' }),
+ ]),
+ lost: [],
+ }),
+ }),
+ ],
+ ],
+ ]);
+ });
+
+ it("reads only as many as the brand's reads left today allow", async () => {
+ tables['rpc:competitor_cited_urls'] = [
+ cited('https://rival.com/a', 5),
+ cited('https://rival.com/b', 4),
+ cited('https://rival.com/c', 3),
+ ];
+ todayReads = 11;
+ const read = reader({});
+ await recordPageChanges(BRAND, { now: NOW, read });
+ const pagesRead = read.mock.calls
+ .map(([url]) => url)
+ .filter((url) => !url.endsWith('robots.txt'));
+ expect(pagesRead).toEqual(['https://rival.com/a']);
+ todayReads = 12;
+ read.mockClear();
+ expect(await recordPageChanges(BRAND, { now: NOW, read })).toBe(0);
+ expect(read).not.toHaveBeenCalled();
+ });
+});
+
+describe('sweepCompetitorTimeline', () => {
+ it("goes over the brands with competitors on an active plan, and a brand's failure stops no other", async () => {
+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');
+ vi.stubEnv('IS_CLOUD', 'true');
+ tables.competitors = [
+ {
+ id: 'c1',
+ brand_id: BRAND,
+ domain: 'rival.com',
+ brands: { organization_id: 'o1', is_active: true },
+ },
+ {
+ id: 'c2',
+ brand_id: 'brand-2',
+ domain: 'other.com',
+ brands: { organization_id: 'o2', is_active: true },
+ },
+ {
+ id: 'c3',
+ brand_id: 'brand-3',
+ domain: '',
+ brands: { organization_id: 'o1', is_active: true },
+ },
+ ];
+ tables.organizations = [
+ { id: 'o1', subscription_status: 'active' },
+ { id: 'o2', subscription_status: 'canceled' },
+ ];
+ const outcome = await sweepCompetitorTimeline({ now: NOW, read: reader({}) });
+ vi.unstubAllEnvs();
+ expect(outcome).toMatchObject({ brands: 1, failed: 0 });
+ expect(rpcCalls.map(([, args]) => args.p_brand_id)).toEqual([BRAND, BRAND]);
+ });
+
+ it('reaches a brand past the first thousand competitors read', async () => {
+ tables.competitors = Array.from({ length: 1_200 }, (_, i) => ({
+ id: `c${String(i).padStart(4, '0')}`,
+ brand_id: i < 1_100 ? 'brand-busy' : BRAND,
+ domain: 'rival.com',
+ brands: { organization_id: 'o1', is_active: true },
+ }));
+ // The busy brand was read last night; the other never was, so it goes first.
+ tables.competitor_timeline_scans = Array.from({ length: 1_100 }, (_, i) => ({
+ competitor_id: `c${String(i).padStart(4, '0')}`,
+ brand_id: 'brand-busy',
+ scanned_at: '2026-10-28T03:00:00Z',
+ }));
+ await sweepCompetitorTimeline({ now: NOW, read: reader({}), limit: 1 });
+ expect(rpcCalls[0][1].p_brand_id).toBe(BRAND);
+ });
+});
diff --git a/server/src/server.js b/server/src/server.js
index 6013f86b4..411507077 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -58,6 +58,7 @@ import { runPulseCatchUp } from './lib/pulse/engine.js';
import { runSignalCatchUp } from './lib/signals/pass.js';
import { integrationsConfig } from './routes/integrations.js';
import { sweepTaskExecution } from './lib/action-center/execution/run.js';
+import { sweepCompetitorTimeline } from './lib/action-center/competitor-timeline.js';
import { sweepActionTasks } from './lib/action-center/task-writer/index.js';
import { sweepTaskChecks } from './lib/action-center/task-checks.js';
import { sendHealthReport } from './lib/health/report.js';
@@ -190,9 +191,17 @@ async function runDailyTracking() {
// in action_task_runs and, where the user needs to know, in the action's own
// trail. Fire-and-forget like the rest — an unexecuted task is a step
// somebody does by hand, not a reason to hold up tracking.
- sweepTaskExecution().catch((err) => {
- logger.error({ err }, '[task-run] sweep crashed');
- });
+ sweepTaskExecution()
+ .catch((err) => {
+ logger.error({ err }, '[task-run] sweep crashed');
+ })
+ // Then a competitor's pages over time (learning C3): their first
+ // citations, and the weekly re-read of those cited most, within what is
+ // left of each brand's page reads after the tasks'.
+ .then(() => sweepCompetitorTimeline())
+ .catch((err) => {
+ logger.error({ err }, '[competitor-timeline] sweep crashed');
+ });
// Write the tasks of recent actions whose writing a pass missed (AC-004):
// the budget was spent, the model failed, or the process restarted.
diff --git a/supabase/migrations/00376_competitor_page_timeline.sql b/supabase/migrations/00376_competitor_page_timeline.sql
new file mode 100644
index 000000000..85a798557
--- /dev/null
+++ b/supabase/migrations/00376_competitor_page_timeline.sql
@@ -0,0 +1,128 @@
+-- ============================================================================
+-- 00376: a competitor's pages over time (learning C3)
+-- ============================================================================
+-- A competitor rising in AI answers had no "why" beside it. This keeps two
+-- kinds of dated events for each competitor page the brand's own tracked
+-- answers cite (server action-center/competitor-timeline.js):
+--
+-- first_cited the first day the brand's answers cited the page, read from
+-- prompt_result_citations (no page read; the first night goes
+-- back 90 days, so it is the first since then);
+-- changed a weekly re-read found the page's words changed by more than
+-- a date or a price moving (the Action Center's page checks'
+-- rule, task-checks.js), with the Site Audit checks it gained
+-- and lost.
+--
+-- The page is read free (safe-fetch), within the brand's daily page reads,
+-- as the pages "Analyze competitor content" reads (00369). What is kept of a
+-- read is what Site Audit's checks found and a sketch of its words (hashes
+-- of its 4-word runs, not the text), so the next read can tell it changed.
+-- Members read the events; the server writes them.
+
+alter table public.cited_page_features
+ add column if not exists sketch jsonb;
+
+comment on column public.cited_page_features.sketch is
+ 'Learning C3 (00376): the read page''s word sketch (task-checks.js sketch(): hashes of its 4-word runs, never its text), compared with the next read to tell whether the page changed.';
+
+create table if not exists public.competitor_page_events (
+ id uuid primary key default gen_random_uuid(),
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ competitor_id uuid not null references public.competitors(id) on delete cascade,
+ -- The page as Site Audit keys it: host and path, lower case.
+ page_key text not null,
+ url text not null,
+ domain text not null,
+ kind text not null check (kind in ('first_cited', 'changed')),
+ at timestamptz not null,
+ -- first_cited: { answers }; changed: { similarity, gained: [{ key, label }], lost: [{ key, label }] }.
+ detail jsonb not null default '{}'::jsonb,
+ created_at timestamptz not null default now()
+);
+
+-- A page is first cited once.
+create unique index if not exists competitor_page_events_first_cited_uidx
+ on public.competitor_page_events (brand_id, page_key)
+ where kind = 'first_cited';
+
+-- The Competitors page reads one competitor's events, newest first.
+create index if not exists competitor_page_events_competitor_idx
+ on public.competitor_page_events (brand_id, competitor_id, at desc);
+
+alter table public.competitor_page_events enable row level security;
+
+create policy competitor_page_events_member_select on public.competitor_page_events
+ for select
+ using (
+ brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+revoke all on table public.competitor_page_events from anon, authenticated;
+grant select on table public.competitor_page_events to authenticated;
+grant all on table public.competitor_page_events to service_role;
+
+comment on table public.competitor_page_events is
+ 'Learning C3 (00376): when a competitor page was first cited in the brand''s tracked answers, and when a weekly re-read found it changed (and which Site Audit checks it gained or lost). Server writes; members read.';
+
+-- When each competitor's citations were last read for first_cited events: a
+-- competitor never read is read back 90 days once, the rest from their last
+-- read, so a night doesn't read a brand's whole history again.
+create table if not exists public.competitor_timeline_scans (
+ competitor_id uuid primary key references public.competitors(id) on delete cascade,
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ scanned_at timestamptz not null
+);
+
+alter table public.competitor_timeline_scans enable row level security;
+revoke all on table public.competitor_timeline_scans from anon, authenticated;
+grant all on table public.competitor_timeline_scans to service_role;
+
+comment on table public.competitor_timeline_scans is
+ 'Learning C3 (00376): when each competitor''s cited pages were last read for first_cited events. Server only.';
+
+-- ----------------------------------------------------------------------------
+-- The competitor pages the brand's answers cited since p_since: each cited
+-- URL on a competitor's domain (its subdomains too), its competitor, the
+-- first time it was cited and in how many answers. Read in the database so a
+-- brand's citations never travel; the server only.
+-- ----------------------------------------------------------------------------
+create or replace function public.competitor_cited_urls(p_brand_id uuid, p_since timestamptz)
+returns table (
+ url text,
+ domain text,
+ competitor_id uuid,
+ first_at timestamptz,
+ answers bigint
+)
+language sql
+stable
+security definer
+set search_path = public
+as $$
+ with rivals as (
+ select c.id,
+ -- As citation_urls.domain is kept: host without www., lower case.
+ regexp_replace(
+ regexp_replace(lower(trim(c.domain)), '^[a-z]+://', ''),
+ '^www\.|[/:?#].*$', '', 'g'
+ ) as host
+ from public.competitors c
+ where c.brand_id = p_brand_id and trim(c.domain) <> ''
+ )
+ select u.url, u.domain, r.id, min(prc.created_at), count(distinct prc.prompt_result_id)
+ from public.prompt_result_citations prc
+ join public.citation_urls u on u.id = prc.url_id
+ join rivals r on r.host <> '' and (u.domain = r.host or u.domain like '%.' || r.host)
+ where prc.brand_id = p_brand_id
+ and prc.created_at >= p_since
+ group by u.url, u.domain, r.id
+$$;
+
+revoke all on function public.competitor_cited_urls(uuid, timestamptz) from public, anon, authenticated;
+grant execute on function public.competitor_cited_urls(uuid, timestamptz) to service_role;
+
+notify pgrst, 'reload schema';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 6d7fadbb2..bd53aa388 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -43322,6 +43322,138 @@ update public.profiles set work_areas_asked_at = now() where work_areas_asked_at
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00376_competitor_page_timeline.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00376: a competitor's pages over time (learning C3)
+-- ============================================================================
+-- A competitor rising in AI answers had no "why" beside it. This keeps two
+-- kinds of dated events for each competitor page the brand's own tracked
+-- answers cite (server action-center/competitor-timeline.js):
+--
+-- first_cited the first day the brand's answers cited the page, read from
+-- prompt_result_citations (no page read; the first night goes
+-- back 90 days, so it is the first since then);
+-- changed a weekly re-read found the page's words changed by more than
+-- a date or a price moving (the Action Center's page checks'
+-- rule, task-checks.js), with the Site Audit checks it gained
+-- and lost.
+--
+-- The page is read free (safe-fetch), within the brand's daily page reads,
+-- as the pages "Analyze competitor content" reads (00369). What is kept of a
+-- read is what Site Audit's checks found and a sketch of its words (hashes
+-- of its 4-word runs, not the text), so the next read can tell it changed.
+-- Members read the events; the server writes them.
+
+alter table public.cited_page_features
+ add column if not exists sketch jsonb;
+
+comment on column public.cited_page_features.sketch is
+ 'Learning C3 (00376): the read page''s word sketch (task-checks.js sketch(): hashes of its 4-word runs, never its text), compared with the next read to tell whether the page changed.';
+
+create table if not exists public.competitor_page_events (
+ id uuid primary key default gen_random_uuid(),
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ competitor_id uuid not null references public.competitors(id) on delete cascade,
+ -- The page as Site Audit keys it: host and path, lower case.
+ page_key text not null,
+ url text not null,
+ domain text not null,
+ kind text not null check (kind in ('first_cited', 'changed')),
+ at timestamptz not null,
+ -- first_cited: { answers }; changed: { similarity, gained: [{ key, label }], lost: [{ key, label }] }.
+ detail jsonb not null default '{}'::jsonb,
+ created_at timestamptz not null default now()
+);
+
+-- A page is first cited once.
+create unique index if not exists competitor_page_events_first_cited_uidx
+ on public.competitor_page_events (brand_id, page_key)
+ where kind = 'first_cited';
+
+-- The Competitors page reads one competitor's events, newest first.
+create index if not exists competitor_page_events_competitor_idx
+ on public.competitor_page_events (brand_id, competitor_id, at desc);
+
+alter table public.competitor_page_events enable row level security;
+
+create policy competitor_page_events_member_select on public.competitor_page_events
+ for select
+ using (
+ brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()
+ )
+ );
+
+revoke all on table public.competitor_page_events from anon, authenticated;
+grant select on table public.competitor_page_events to authenticated;
+grant all on table public.competitor_page_events to service_role;
+
+comment on table public.competitor_page_events is
+ 'Learning C3 (00376): when a competitor page was first cited in the brand''s tracked answers, and when a weekly re-read found it changed (and which Site Audit checks it gained or lost). Server writes; members read.';
+
+-- When each competitor's citations were last read for first_cited events: a
+-- competitor never read is read back 90 days once, the rest from their last
+-- read, so a night doesn't read a brand's whole history again.
+create table if not exists public.competitor_timeline_scans (
+ competitor_id uuid primary key references public.competitors(id) on delete cascade,
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ scanned_at timestamptz not null
+);
+
+alter table public.competitor_timeline_scans enable row level security;
+revoke all on table public.competitor_timeline_scans from anon, authenticated;
+grant all on table public.competitor_timeline_scans to service_role;
+
+comment on table public.competitor_timeline_scans is
+ 'Learning C3 (00376): when each competitor''s cited pages were last read for first_cited events. Server only.';
+
+-- ----------------------------------------------------------------------------
+-- The competitor pages the brand's answers cited since p_since: each cited
+-- URL on a competitor's domain (its subdomains too), its competitor, the
+-- first time it was cited and in how many answers. Read in the database so a
+-- brand's citations never travel; the server only.
+-- ----------------------------------------------------------------------------
+create or replace function public.competitor_cited_urls(p_brand_id uuid, p_since timestamptz)
+returns table (
+ url text,
+ domain text,
+ competitor_id uuid,
+ first_at timestamptz,
+ answers bigint
+)
+language sql
+stable
+security definer
+set search_path = public
+as $$
+ with rivals as (
+ select c.id,
+ -- As citation_urls.domain is kept: host without www., lower case.
+ regexp_replace(
+ regexp_replace(lower(trim(c.domain)), '^[a-z]+://', ''),
+ '^www\.|[/:?#].*$', '', 'g'
+ ) as host
+ from public.competitors c
+ where c.brand_id = p_brand_id and trim(c.domain) <> ''
+ )
+ select u.url, u.domain, r.id, min(prc.created_at), count(distinct prc.prompt_result_id)
+ from public.prompt_result_citations prc
+ join public.citation_urls u on u.id = prc.url_id
+ join rivals r on r.host <> '' and (u.domain = r.host or u.domain like '%.' || r.host)
+ where prc.brand_id = p_brand_id
+ and prc.created_at >= p_since
+ group by u.url, u.domain, r.id
+$$;
+
+revoke all on function public.competitor_cited_urls(uuid, timestamptz) from public, anon, authenticated;
+grant execute on function public.competitor_cited_urls(uuid, timestamptz) to service_role;
+
+notify pgrst, 'reload schema';
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00379_brand_site_type_source.sql
-- ─────────────────────────────────────────────────────────────────────────