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.

fix(citations): apply the source scope inside the URL cap, not after it (#791)

Gökhan Geyikfe673af80d88
diff --git a/supabase/migrations/00076_citations_urls_scope.sql b/supabase/migrations/00076_citations_urls_scope.sql
new file mode 100644
index 000000000..840ba41e1
--- /dev/null
+++ b/supabase/migrations/00076_citations_urls_scope.sql
@@ -0,0 +1,151 @@
+-- Apply the source scope inside the URL cap, not after it (#745).
+--
+-- Two changes that are each right on their own combined badly. #744 caps the
+-- URL list at the top 2,000 by citation count, which is what makes the page
+-- affordable — the largest brand has 97,320 distinct cited URLs in a 30-day
+-- window. #742 then moved the source scope (All · Brand · Competitors ·
+-- Third-party) to the client, over the rows that arrived, which is what
+-- removed the round trip the scope used to cost.
+--
+-- So the scope filters *within* the global top 2,000. Measured on that brand:
+--
+-- scope shown actually exist
+-- Brand 21 395
+-- Competitors 125 2,794
+--
+-- And it is silent. The pager counts what it filtered, so the tab reads
+-- "125 of 125" — a reader cannot tell "this brand has 125 competitor URLs"
+-- from "125 of them happened to rank in the global top two thousand".
+--
+-- The fix is to hand the function the domains the scope resolves to and let
+-- it cut the set before the limit. What a brand or competitor domain *is*
+-- stays in TypeScript: `classifyDomain` decides it from brand_domains and
+-- competitors with a suffix match, the caller already runs it over every
+-- aggregated domain to build the Domains tab, and duplicating that rule in
+-- SQL would give it two definitions to drift apart.
+--
+-- Two parameters rather than one, and this is a deliberate departure from the
+-- issue's sketch. Resolving every scope to an include list would mean sending
+-- 17,532 domains for Third-party — the whole cited set minus fourteen. Naming
+-- the fourteen to exclude says the same thing in a request that fits in a
+-- packet. Every scope now resolves to a handful of domains:
+--
+-- All neither parameter
+-- Brand p_domains — the cited domains classified 'you'
+-- Competitors p_domains — those classified 'competitor'
+-- Third-party p_exclude_domains — both of the above
+--
+-- The filter sits after the aggregate, not inside it, and that placement is
+-- load-bearing. Pushed down into the citation scan, the planner abandons the
+-- hash join for a nested loop over the matching url ids: 4.57s against a
+-- 1.67s unscoped baseline, uncomfortably close to the 8s statement timeout on
+-- a warm cache. Applied to the aggregated rows it stays a hash semi-join
+-- costing 11ms, and every scope lands within noise of the unscoped query —
+-- 1.62s (Brand), 1.68s (Competitors), 1.73s (Third-party).
+--
+-- The old 8-argument signature is dropped rather than left beside the new
+-- one: keeping both makes an 8-argument call ambiguous. PostgREST binds by
+-- name, so no in-flight request depends on argument position and the deploy
+-- window is safe — the same reason 00072 could do this.
+
+drop function if exists public.citations_urls(
+ uuid, timestamptz, timestamptz, text[], text[], uuid[], uuid[], integer
+);
+
+create or replace function public.citations_urls(
+ p_brand_id uuid,
+ p_date_from timestamptz default null,
+ p_date_to timestamptz default null,
+ p_models text[] default null,
+ p_regions text[] default null,
+ p_prompt_ids uuid[] default null,
+ p_topic_ids uuid[] default null,
+ p_limit integer default 2000,
+ p_domains text[] default null,
+ p_exclude_domains text[] default null
+)
+returns table (
+ url text,
+ domain text,
+ title text,
+ total_citations bigint,
+ results_citing bigint,
+ models text[],
+ total_urls bigint
+)
+language sql
+stable
+security definer
+set search_path = public
+set work_mem = '96MB'
+as $$
+ with allowed as (
+ select 1 from brands b
+ join profiles pf on pf.organization_id = b.organization_id
+ where b.id = p_brand_id and pf.id = auth.uid()
+ ),
+ pairs as (
+ select c.url_id as uid, c.prompt_result_id as rid, count(*) as n,
+ min(coalesce(pr.model_used, pr.platform)) as m
+ from public.prompt_result_citations c
+ join public.prompt_results pr on pr.id = c.prompt_result_id
+ where exists (select 1 from allowed)
+ and c.brand_id = p_brand_id
+ and pr.brand_id = p_brand_id
+ and pr.platform <> 'chatgpt-shopping'
+ and (p_date_from is null or (c.created_at >= p_date_from and pr.created_at >= p_date_from))
+ and (p_date_to is null or (c.created_at <= p_date_to and pr.created_at <= p_date_to))
+ and (p_models is null or pr.model_used = any(p_models))
+ and (p_regions is null or pr.region = any(p_regions))
+ and (p_prompt_ids is null or pr.prompt_id = any(p_prompt_ids))
+ and (p_topic_ids is null or pr.prompt_id in (
+ select pp.id from public.prompts pp where pp.topic_id = any(p_topic_ids)))
+ group by c.url_id, c.prompt_result_id
+ ),
+ agg as (
+ select uid, sum(n)::bigint as tc, count(*)::bigint as rc, array_agg(distinct m) as ms
+ from pairs group by uid
+ ),
+ -- Domains resolve to url ids through citation_urls.domain, which is indexed
+ -- and stored already lowercased and without `www.` — so this is a probe per
+ -- domain rather than a scan. Both sets stay empty when their parameter is
+ -- null, which is what keeps the unscoped path identical to before.
+ include_ids as (
+ select cu.id from public.citation_urls cu
+ where p_domains is not null and cu.domain = any(p_domains)
+ ),
+ exclude_ids as (
+ select cu.id from public.citation_urls cu
+ where p_exclude_domains is not null and cu.domain = any(p_exclude_domains)
+ ),
+ scoped as (
+ select a.*
+ from agg a
+ where (p_domains is null
+ or exists (select 1 from include_ids i where i.id = a.uid))
+ and (p_exclude_domains is null
+ or not exists (select 1 from exclude_ids e where e.id = a.uid))
+ )
+ -- total_urls counts the scoped set, so the tab reports how many URLs the
+ -- selected scope actually has rather than how many survived the cap. The
+ -- dictionary is still joined after the limit, so URL text is fetched for
+ -- the rows that survive rather than for all 97,320 of them.
+ select cu.url, cu.domain, cu.title, a.tc, a.rc, a.ms,
+ (select count(*)::bigint from scoped)
+ from (select * from scoped order by tc desc, uid limit p_limit) a
+ join public.citation_urls cu on cu.id = a.uid
+ order by a.tc desc;
+$$;
+
+revoke all on function public.citations_urls(
+ uuid, timestamptz, timestamptz, text[], text[], uuid[], uuid[], integer, text[], text[]
+) from public;
+
+grant execute on function public.citations_urls(
+ uuid, timestamptz, timestamptz, text[], text[], uuid[], uuid[], integer, text[], text[]
+) to authenticated, service_role;
+
+comment on function public.citations_urls(
+ uuid, timestamptz, timestamptz, text[], text[], uuid[], uuid[], integer, text[], text[]
+) is
+ 'Top cited URLs for one brand, capped at p_limit by citation count (#732). p_domains / p_exclude_domains apply the source scope before the cap so it never reports a slice of the global top N as the whole scope (#745); the caller resolves the scope to domains, and total_urls counts the scoped set. Security definer with an explicit org-membership guard (#780).';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index c2e89be95..8f8b1057b 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -8932,3 +8932,158 @@ alter table public.page_opportunities
comment on column public.page_opportunities.citation_state is
'Why this page gets no AI traffic (#719): cited anyway, targeted by a prompt and not cited, or not targeted at all. Null until the first run that classifies it.';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00076_citations_urls_scope.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Apply the source scope inside the URL cap, not after it (#745).
+--
+-- Two changes that are each right on their own combined badly. #744 caps the
+-- URL list at the top 2,000 by citation count, which is what makes the page
+-- affordable — the largest brand has 97,320 distinct cited URLs in a 30-day
+-- window. #742 then moved the source scope (All · Brand · Competitors ·
+-- Third-party) to the client, over the rows that arrived, which is what
+-- removed the round trip the scope used to cost.
+--
+-- So the scope filters *within* the global top 2,000. Measured on that brand:
+--
+-- scope shown actually exist
+-- Brand 21 395
+-- Competitors 125 2,794
+--
+-- And it is silent. The pager counts what it filtered, so the tab reads
+-- "125 of 125" — a reader cannot tell "this brand has 125 competitor URLs"
+-- from "125 of them happened to rank in the global top two thousand".
+--
+-- The fix is to hand the function the domains the scope resolves to and let
+-- it cut the set before the limit. What a brand or competitor domain *is*
+-- stays in TypeScript: `classifyDomain` decides it from brand_domains and
+-- competitors with a suffix match, the caller already runs it over every
+-- aggregated domain to build the Domains tab, and duplicating that rule in
+-- SQL would give it two definitions to drift apart.
+--
+-- Two parameters rather than one, and this is a deliberate departure from the
+-- issue's sketch. Resolving every scope to an include list would mean sending
+-- 17,532 domains for Third-party — the whole cited set minus fourteen. Naming
+-- the fourteen to exclude says the same thing in a request that fits in a
+-- packet. Every scope now resolves to a handful of domains:
+--
+-- All neither parameter
+-- Brand p_domains — the cited domains classified 'you'
+-- Competitors p_domains — those classified 'competitor'
+-- Third-party p_exclude_domains — both of the above
+--
+-- The filter sits after the aggregate, not inside it, and that placement is
+-- load-bearing. Pushed down into the citation scan, the planner abandons the
+-- hash join for a nested loop over the matching url ids: 4.57s against a
+-- 1.67s unscoped baseline, uncomfortably close to the 8s statement timeout on
+-- a warm cache. Applied to the aggregated rows it stays a hash semi-join
+-- costing 11ms, and every scope lands within noise of the unscoped query —
+-- 1.62s (Brand), 1.68s (Competitors), 1.73s (Third-party).
+--
+-- The old 8-argument signature is dropped rather than left beside the new
+-- one: keeping both makes an 8-argument call ambiguous. PostgREST binds by
+-- name, so no in-flight request depends on argument position and the deploy
+-- window is safe — the same reason 00072 could do this.
+
+drop function if exists public.citations_urls(
+ uuid, timestamptz, timestamptz, text[], text[], uuid[], uuid[], integer
+);
+
+create or replace function public.citations_urls(
+ p_brand_id uuid,
+ p_date_from timestamptz default null,
+ p_date_to timestamptz default null,
+ p_models text[] default null,
+ p_regions text[] default null,
+ p_prompt_ids uuid[] default null,
+ p_topic_ids uuid[] default null,
+ p_limit integer default 2000,
+ p_domains text[] default null,
+ p_exclude_domains text[] default null
+)
+returns table (
+ url text,
+ domain text,
+ title text,
+ total_citations bigint,
+ results_citing bigint,
+ models text[],
+ total_urls bigint
+)
+language sql
+stable
+security definer
+set search_path = public
+set work_mem = '96MB'
+as $$
+ with allowed as (
+ select 1 from brands b
+ join profiles pf on pf.organization_id = b.organization_id
+ where b.id = p_brand_id and pf.id = auth.uid()
+ ),
+ pairs as (
+ select c.url_id as uid, c.prompt_result_id as rid, count(*) as n,
+ min(coalesce(pr.model_used, pr.platform)) as m
+ from public.prompt_result_citations c
+ join public.prompt_results pr on pr.id = c.prompt_result_id
+ where exists (select 1 from allowed)
+ and c.brand_id = p_brand_id
+ and pr.brand_id = p_brand_id
+ and pr.platform <> 'chatgpt-shopping'
+ and (p_date_from is null or (c.created_at >= p_date_from and pr.created_at >= p_date_from))
+ and (p_date_to is null or (c.created_at <= p_date_to and pr.created_at <= p_date_to))
+ and (p_models is null or pr.model_used = any(p_models))
+ and (p_regions is null or pr.region = any(p_regions))
+ and (p_prompt_ids is null or pr.prompt_id = any(p_prompt_ids))
+ and (p_topic_ids is null or pr.prompt_id in (
+ select pp.id from public.prompts pp where pp.topic_id = any(p_topic_ids)))
+ group by c.url_id, c.prompt_result_id
+ ),
+ agg as (
+ select uid, sum(n)::bigint as tc, count(*)::bigint as rc, array_agg(distinct m) as ms
+ from pairs group by uid
+ ),
+ -- Domains resolve to url ids through citation_urls.domain, which is indexed
+ -- and stored already lowercased and without `www.` — so this is a probe per
+ -- domain rather than a scan. Both sets stay empty when their parameter is
+ -- null, which is what keeps the unscoped path identical to before.
+ include_ids as (
+ select cu.id from public.citation_urls cu
+ where p_domains is not null and cu.domain = any(p_domains)
+ ),
+ exclude_ids as (
+ select cu.id from public.citation_urls cu
+ where p_exclude_domains is not null and cu.domain = any(p_exclude_domains)
+ ),
+ scoped as (
+ select a.*
+ from agg a
+ where (p_domains is null
+ or exists (select 1 from include_ids i where i.id = a.uid))
+ and (p_exclude_domains is null
+ or not exists (select 1 from exclude_ids e where e.id = a.uid))
+ )
+ -- total_urls counts the scoped set, so the tab reports how many URLs the
+ -- selected scope actually has rather than how many survived the cap. The
+ -- dictionary is still joined after the limit, so URL text is fetched for
+ -- the rows that survive rather than for all 97,320 of them.
+ select cu.url, cu.domain, cu.title, a.tc, a.rc, a.ms,
+ (select count(*)::bigint from scoped)
+ from (select * from scoped order by tc desc, uid limit p_limit) a
+ join public.citation_urls cu on cu.id = a.uid
+ order by a.tc desc;
+$$;
+
+revoke all on function public.citations_urls(
+ uuid, timestamptz, timestamptz, text[], text[], uuid[], uuid[], integer, text[], text[]
+) from public;
+
+grant execute on function public.citations_urls(
+ uuid, timestamptz, timestamptz, text[], text[], uuid[], uuid[], integer, text[], text[]
+) to authenticated, service_role;
+
+comment on function public.citations_urls(
+ uuid, timestamptz, timestamptz, text[], text[], uuid[], uuid[], integer, text[], text[]
+) is
+ 'Top cited URLs for one brand, capped at p_limit by citation count (#732). p_domains / p_exclude_domains apply the source scope before the cap so it never reports a slice of the global top N as the whole scope (#745); the caller resolves the scope to domains, and total_urls counts the scoped set. Security definer with an explicit org-membership guard (#780).';
+
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsx
index 89c08c6d9..0cd0a8daf 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/citations/page.tsx
@@ -830,6 +830,10 @@ export default function CitationsPage() {
}
});
+ // The server already scoped these (#745). This is kept for the moment
+ // between picking a scope and the refetch landing, when `data` still holds
+ // the previous scope's rows — without it the table would show the old scope
+ // under the new one's name. Once the fresh rows arrive it filters nothing.
const filteredUrlRows = (data?.urlRows ?? []).filter((urlRow) => {
switch (filters.sourceScope) {
case 'own':
@@ -892,6 +896,15 @@ export default function CitationsPage() {
filters.prompt,
]);
+ // The URL list is capped, so its scope has to be applied in the query rather
+ // than to what came back (#745) — which means changing the scope refetches
+ // the overview. Kept separate from gapFilters above so Competitor Gaps, which
+ // the scope does not apply to, still doesn't refetch when it changes.
+ const overviewFilters = useMemo<CitationsFilters>(
+ () => ({ ...gapFilters, sourceScope: filters.sourceScope }),
+ [gapFilters, filters.sourceScope],
+ );
+
useEffect(() => {
if (!activeBrandId) return;
getTopics(activeBrandId)
@@ -918,7 +931,7 @@ export default function CitationsPage() {
setIsLoading(true);
setLoadFailed(false);
try {
- const overview = await getCitationsOverview(activeBrandId, gapFilters);
+ const overview = await getCitationsOverview(activeBrandId, overviewFilters);
if (stale()) return;
setData(overview);
@@ -949,7 +962,7 @@ export default function CitationsPage() {
} finally {
if (!stale()) setIsLoading(false);
}
- }, [activeBrandId, gapFilters]);
+ }, [activeBrandId, overviewFilters]);
useEffect(() => {
if (!activeBrandId) return;
diff --git a/web/src/lib/actions/citations.ts b/web/src/lib/actions/citations.ts
index 3d23f9e32..15177eb4a 100644
--- a/web/src/lib/actions/citations.ts
+++ b/web/src/lib/actions/citations.ts
@@ -10,12 +10,15 @@ import {
SOURCE_CATEGORIES,
} from '@/lib/citations/classify';
import { classifyArticleType } from '@/lib/citations/article-type';
+import { scopeDomainArgs, type CitationsSourceScope } from '@/lib/citations/scope';
import { citationUrlMatchKey, normalizeCitationUrl } from '@/lib/citations/normalize';
// ─── Types ────────────────────────────────────────────────────────────────────
export type CitationsDatePreset = '24h' | '7d' | '30d' | '90d' | 'all' | 'custom';
+export type { CitationsSourceScope };
+
export interface CitationsFilters {
datePreset: CitationsDatePreset;
dateFrom?: string;
@@ -24,6 +27,15 @@ export interface CitationsFilters {
topicIds?: string[];
promptIds?: string[];
regions?: string[];
+ /**
+ * Which sources the URL list covers (#745).
+ *
+ * Only the URL list needs it. The domain list is returned uncapped, so
+ * filtering that after the fact is exact and stays on the client; the URL
+ * list is capped at the top 2,000, and a scope applied to what arrived
+ * reports a slice of the global top N as though it were the whole scope.
+ */
+ sourceScope?: CitationsSourceScope;
}
export interface CitationArticleTypeCount {
@@ -205,16 +217,19 @@ export async function getCitationsOverview(
const classifyCtx = { brandDomains, competitorDomains };
const args = overviewArgs(brandId, filters, topicPromptIds);
+ const scoped = Boolean(filters.sourceScope && filters.sourceScope !== 'all');
- // In parallel: the three are independent, and the slowest decides the wait.
- const [domainRes, urlRes, statsRes] = await Promise.all([
+ // A scope is resolved from the classified domain list, so a scoped URL query
+ // has to wait for the domain query to land. The unscoped view — the one every
+ // page open starts on — keeps all three in flight, because serializing it
+ // would double the default load for a filter nobody selected.
+ const [domainRes, statsRes, parallelUrlRes] = await Promise.all([
supabase.rpc('citations_domains', args),
- supabase.rpc('citations_urls', { ...args, p_limit: CITATIONS_URL_LIMIT }),
supabase.rpc('citations_window_stats', args),
+ scoped ? null : supabase.rpc('citations_urls', { ...args, p_limit: CITATIONS_URL_LIMIT }),
]);
if (domainRes.error) throw new Error(domainRes.error.message);
- if (urlRes.error) throw new Error(urlRes.error.message);
if (statsRes.error) throw new Error(statsRes.error.message);
const stats = (statsRes.data as { results: number; regions: string[] | null }[] | null)?.[0];
@@ -252,6 +267,15 @@ export async function getCitationsOverview(
};
});
+ const urlRes =
+ parallelUrlRes ??
+ (await supabase.rpc('citations_urls', {
+ ...args,
+ p_limit: CITATIONS_URL_LIMIT,
+ ...scopeDomainArgs(filters.sourceScope, rows),
+ }));
+ if (urlRes.error) throw new Error(urlRes.error.message);
+
const urlRowsRaw = (urlRes.data as UrlAggRow[] | null) ?? [];
const urlRows: CitationUrlRow[] = urlRowsRaw
.map((row) => ({ row, category: categoryOf(row.domain) }))
@@ -290,8 +314,10 @@ export async function getCitationsOverview(
urlRows,
totals: {
domains: rows.length,
- // The uncapped count, so the page never implies it has every URL. Falls
- // back to what arrived when the window produced nothing at all.
+ // The uncapped count *within the selected scope*, so the page never
+ // implies it has every URL and never reports a slice of the global top
+ // 2,000 as the whole scope (#745). Falls back to what arrived when the
+ // window produced nothing at all.
urls: Number(urlRowsRaw[0]?.total_urls ?? urlRows.length),
citations,
results: totalResults,
diff --git a/web/src/lib/citations/scope.test.ts b/web/src/lib/citations/scope.test.ts
new file mode 100644
index 000000000..d668ff965
--- /dev/null
+++ b/web/src/lib/citations/scope.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it } from 'vitest';
+import { scopeDomainArgs } from './scope.js';
+import type { SourceCategory } from './classify.js';
+
+/**
+ * Resolving a source scope to RPC arguments (#745).
+ *
+ * The whole point is that the query, not the result set, gets narrowed — the
+ * URL list is capped at the top 2,000 by citation count, so a scope applied
+ * afterwards reports a slice of the global top N as the whole scope. These
+ * pin the two things that would quietly reintroduce that: sending nothing
+ * when a scope covers nothing, and sending an include list where the exclude
+ * list belongs.
+ */
+
+const row = (domain: string, category: SourceCategory) => ({ domain, category });
+
+const rows = [
+ row('mybrand.com', 'you'),
+ row('blog.mybrand.com', 'you'),
+ row('rival.com', 'competitor'),
+ row('other-rival.com', 'competitor'),
+ row('reddit.com', 'forum'),
+ row('techcrunch.com', 'editorial'),
+ row('randomsite.com', 'other'),
+];
+
+describe('scopeDomainArgs', () => {
+ it('sends no scope at all for All', () => {
+ expect(scopeDomainArgs('all', rows)).toEqual({});
+ expect(scopeDomainArgs(undefined, rows)).toEqual({});
+ });
+
+ it('includes the brand-owned domains for Brand', () => {
+ expect(scopeDomainArgs('own', rows)).toEqual({
+ p_domains: ['mybrand.com', 'blog.mybrand.com'],
+ });
+ });
+
+ it('includes the competitor domains for Competitors', () => {
+ expect(scopeDomainArgs('competitors', rows)).toEqual({
+ p_domains: ['rival.com', 'other-rival.com'],
+ });
+ });
+
+ it('excludes rather than includes for Third-party', () => {
+ // The set this scope covers is everything else — 17,532 domains on the
+ // largest brand. Naming the four to leave out is the same statement in a
+ // request that fits in a packet.
+ expect(scopeDomainArgs('third_party', rows)).toEqual({
+ p_exclude_domains: ['mybrand.com', 'blog.mybrand.com', 'rival.com', 'other-rival.com'],
+ });
+ });
+
+ it('sends an empty include list when a scope covers nothing', () => {
+ // A brand with no competitor ever cited must see an empty table, not
+ // every URL in the window. The empty array is the instruction.
+ const noRivals = rows.filter((r) => r.category !== 'competitor');
+ expect(scopeDomainArgs('competitors', noRivals)).toEqual({ p_domains: [] });
+ });
+
+ it('omits the exclude list when there is nothing to exclude', () => {
+ // The mirror image: with nothing to leave out, Third-party is the whole
+ // set, and an empty array would be sent as a filter that matches nothing.
+ const thirdPartyOnly = rows.filter((r) => r.category !== 'you' && r.category !== 'competitor');
+ expect(scopeDomainArgs('third_party', thirdPartyOnly)).toEqual({});
+ });
+
+ it('treats every category that is neither ours nor a rival as third-party', () => {
+ // forum / editorial / other are not enumerated anywhere in the resolver;
+ // it decides by what a domain is *not*, so a new category added to
+ // classifyDomain lands in Third-party without a change here.
+ const args = scopeDomainArgs('third_party', rows);
+ expect(args.p_exclude_domains).not.toContain('reddit.com');
+ expect(args.p_exclude_domains).not.toContain('techcrunch.com');
+ expect(args.p_exclude_domains).not.toContain('randomsite.com');
+ });
+
+ it('handles a window with no citations at all', () => {
+ expect(scopeDomainArgs('own', [])).toEqual({ p_domains: [] });
+ expect(scopeDomainArgs('third_party', [])).toEqual({});
+ });
+});
diff --git a/web/src/lib/citations/scope.ts b/web/src/lib/citations/scope.ts
new file mode 100644
index 000000000..3006c5945
--- /dev/null
+++ b/web/src/lib/citations/scope.ts
@@ -0,0 +1,47 @@
+import type { SourceCategory } from './classify';
+
+/** Which sources the Citations URL list covers. */
+export type CitationsSourceScope = 'all' | 'own' | 'competitors' | 'third_party';
+
+/** The classified domain rows the Domains tab is built from. */
+interface ClassifiedDomain {
+ domain: string;
+ category: SourceCategory;
+}
+
+/**
+ * A source scope, expressed as domains `citations_urls` can filter on (#745).
+ *
+ * The URL list is capped at the top 2,000 by citation count, so a scope
+ * applied to the rows that arrived reports a slice of the global top N as
+ * though it were the whole scope — 125 competitor URLs on a brand that has
+ * 2,794. Pushing the scope into the query means the cap applies inside it.
+ *
+ * Returns an include list for the two narrow scopes and an *exclude* list for
+ * Third-party, which says the same thing in far less space: on the largest
+ * brand a window holds 17,532 cited domains, of which fourteen are the
+ * brand's own or a competitor's. Naming the fourteen beats sending 17,518.
+ *
+ * `rows` is the already-classified domain list, so what counts as a brand or
+ * competitor domain keeps exactly one definition — `classifyDomain`, applied
+ * once, upstream of both tabs. Nothing here re-decides it.
+ */
+export function scopeDomainArgs(
+ scope: CitationsSourceScope | undefined,
+ rows: ClassifiedDomain[],
+): { p_domains?: string[]; p_exclude_domains?: string[] } {
+ if (!scope || scope === 'all') return {};
+
+ const own = rows.filter((r) => r.category === 'you').map((r) => r.domain);
+ const competitors = rows.filter((r) => r.category === 'competitor').map((r) => r.domain);
+
+ // An empty include list is meaningful — the scope genuinely covers nothing,
+ // and the query must return nothing rather than everything.
+ if (scope === 'own') return { p_domains: own };
+ if (scope === 'competitors') return { p_domains: competitors };
+
+ const excluded = [...own, ...competitors];
+ // An empty exclude list is the opposite case: Third-party is then the whole
+ // set, so the parameter is left off rather than sent as an empty array.
+ return excluded.length > 0 ? { p_exclude_domains: excluded } : {};
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index ab7d1df23..36b7df8ee 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -2526,6 +2526,8 @@ export type Database = {
p_brand_id: string
p_date_from?: string
p_date_to?: string
+ p_domains?: string[]
+ p_exclude_domains?: string[]
p_limit?: number
p_models?: string[]
p_prompt_ids?: string[]