diff --git a/.github/workflows/edge-function-check.yml b/.github/workflows/edge-function-check.yml index 326ad4c..bc7ff19 100644 --- a/.github/workflows/edge-function-check.yml +++ b/.github/workflows/edge-function-check.yml @@ -26,5 +26,7 @@ jobs: run: deno test --no-check --node-modules-dir=none --allow-read supabase/functions/visibility-tracking/brand-matching.test.ts - name: Test site audit and shared text helpers run: deno test --no-check --node-modules-dir=none --allow-read --allow-net --allow-env supabase/functions/site-audit/*.test.ts supabase/functions/_shared/html-text.test.ts supabase/functions/_shared/text-metrics.test.ts + - name: Test mention text and source association + run: deno test --no-check --node-modules-dir=none --allow-read supabase/functions/visibility-tracking/mention-accuracy.test.ts - name: Test provider retry policy run: deno test --no-check --node-modules-dir=none supabase/functions/visibility-tracking/provider-retry.test.ts diff --git a/.github/workflows/replacement-rerun-db-tests.yml b/.github/workflows/replacement-rerun-db-tests.yml index 408a7ae..5fadb31 100644 --- a/.github/workflows/replacement-rerun-db-tests.yml +++ b/.github/workflows/replacement-rerun-db-tests.yml @@ -66,7 +66,8 @@ jobs: supabase/migrations/20261117160000_standardise_category_run_kind.sql \ supabase/migrations/20261118100000_harden_metric_finalization_search_path.sql \ supabase/migrations/20261204120000_multilingual_brand_matching.sql \ - supabase/migrations/20261204160000_recompute_keeps_history.sql + supabase/migrations/20261204160000_recompute_keeps_history.sql \ + supabase/migrations/20261204200000_fewer_false_mentions.sql do echo "Applying $migration" psql "$DB_URL" -v ON_ERROR_STOP=1 -f "$migration" @@ -90,6 +91,12 @@ jobs: -v ON_ERROR_STOP=1 \ -f supabase/tests/replacement_rerun_competitor_recompute_behaviour.sql + - name: Check link text is ignored when finding brand mentions + run: | + psql "postgresql://postgres:postgres@127.0.0.1:54322/postgres" \ + -v ON_ERROR_STOP=1 \ + -f supabase/tests/mention_text_behaviour.sql + - name: Run recalculation keeps-history behavioural tests run: | psql "postgresql://postgres:postgres@127.0.0.1:54322/postgres" \ @@ -197,4 +204,4 @@ jobs: run: deno check supabase/functions/visibility-tracking/index.ts - name: Run visibility tracking Edge Function unit tests - run: deno test --allow-net supabase/functions/visibility-tracking/*.test.ts + run: deno test --allow-net --allow-read=supabase/tests supabase/functions/visibility-tracking/*.test.ts diff --git a/supabase/functions/visibility-tracking/index.ts b/supabase/functions/visibility-tracking/index.ts index 364856f..b832ec9 100644 --- a/supabase/functions/visibility-tracking/index.ts +++ b/supabase/functions/visibility-tracking/index.ts @@ -1,4 +1,6 @@ import { aliasMatcher } from "./brand-matching.ts"; +import { mentionText } from "./mention-text.ts"; +import { associateSource, citedContext, onOwnSite, ownSiteHost, strongerStatus } from "./source-association.ts"; import { urlsIn } from "./inline-urls.ts"; import { reduceEvidenceRows } from "./evidence-reducer.ts"; import { rankAgainstEligiblePopulation } from "./rank-population.ts"; @@ -113,7 +115,7 @@ function cachedTermMatches(result: object, text: string, terms: string[]): Match } const cached = responseCache.get(key); if (cached) return cached; - const summary = summarizeTermMatches(text, terms); + const summary = summarizeTermMatches(mentionText(text), terms); responseCache.set(key, summary); return summary; } @@ -305,7 +307,7 @@ async function classifyDirectCompetitors( const name = String(raw.brand_name ?? candidate.brand_name ?? "").trim(); if (!name) continue; const aliases = [...new Set([ - name, domain, domain.split(".")[0].replace(/[-_]+/g, " "), + name, domain, ...(Array.isArray(raw.aliases) ? raw.aliases.map(String) : []), ].map((value) => value.trim()).filter((value) => value.length > 1))]; accepted.push({ domain, brand_name: name, aliases }); @@ -349,7 +351,7 @@ async function processPrompts(prompts: Array>, providers } const brandName = String(project.brand_name ?? ""); const terms = [brandName, ...(Array.isArray(project.brand_terms) ? project.brand_terms.map(String) : [])].filter(Boolean); - const brandMentioned = containsTerm(text, terms); + const brandMentioned = containsTerm(mentionText(text), terms); const responseCitations = Array.isArray(answer.citations) ? answer.citations : []; // Inline URLs are retained as a separate signal, not promoted to citations: // a URL appearing in prose is not proof that the answer cited that page. @@ -994,7 +996,7 @@ export function createVisibilityTrackingHandler( ...(Array.isArray(directory.aliases) ? directory.aliases.map(String) : []), ...(Array.isArray(assignment.aliases) ? assignment.aliases.map(String) : []), ].map((value) => value.trim()).filter((value) => value.length > 1))]; - if (summarizeTermMatches(text, aliases).count <= 0) continue; + if (summarizeTermMatches(mentionText(text), aliases).count <= 0) continue; const id = String(directory.id); observed.push(id); const websiteValue = String(directory.primary_website ?? (Array.isArray(assignment.websites) ? assignment.websites[0] : "") ?? ""); @@ -1137,7 +1139,6 @@ export function createVisibilityTrackingHandler( ...(Array.isArray(directory.aliases) ? directory.aliases.map(String) : []), ...(Array.isArray(assignment.aliases) ? assignment.aliases.map(String) : []), ...websites, - ...websites.map((domain) => domain.split(".")[0].replace(/[-_]+/g, " ")), ].map((value) => value.trim()).filter((value) => value.length > 1))]; return { id: String(directory.id), @@ -1264,34 +1265,41 @@ export function createVisibilityTrackingHandler( const host = hostOf(source.url); if (!host) continue; const sourceText = (source.title + " " + source.url).toLocaleLowerCase(); - const directlyMatchedBrands: Array<{id:string;name:string}> = []; - for (const assignment of categoryAssignments) { + const candidates = categoryAssignments.flatMap((assignment: Record) => { const directory = directoryById.get(String(assignment.brand_id)); - if (!directory) continue; + if (!directory) return []; const aliases = [...new Set([ String(directory.canonical_name ?? ""), ...(Array.isArray(directory.aliases) ? directory.aliases.map(String) : []), ...(Array.isArray(assignment.aliases) ? assignment.aliases.map(String) : []), ...(String(assignment.role) === "tracked_brand" && Array.isArray(project.brand_terms) ? project.brand_terms.map(String) : []), ].map((v) => v.trim()).filter((v) => v.length > 1))]; - // Match against each URL/title independently rather than using the - // response-text cache, which is scoped to the full answer text. - if (summarizeTermMatches(sourceText, aliases).count > 0) directlyMatchedBrands.push({ - id: String(directory.id), name: String(directory.canonical_name ?? ""), - }); - } - const directIds = new Set(directlyMatchedBrands.map((brand) => brand.id)); - const sourceRelatedBrands = directlyMatchedBrands.length ? directlyMatchedBrands : matchedBrands; - // Keep only websites associated with a configured brand. URL/title - // matches provide direct evidence; same-answer associations are inferred - // and should be reviewed before outreach. - if (!sourceRelatedBrands.length) continue; + const ownHosts = [ + ...(Array.isArray(assignment.websites) ? assignment.websites : []), + directory.primary_website, + ...(Array.isArray(directory.additional_websites) ? directory.additional_websites : []), + ].map((site) => ownSiteHost(String(site ?? ""))).filter(Boolean); + return [{ id: String(directory.id), name: String(directory.canonical_name ?? ""), aliases, ownHosts }]; + }); + // Match against each URL/title independently rather than using the + // response-text cache, which is scoped to the full answer text. + const association = associateSource( + candidates, + (brand) => onOwnSite(host, brand.ownHosts) || summarizeTermMatches(sourceText, brand.aliases).count > 0, + (brand, text) => summarizeTermMatches(text, brand.aliases).count > 0, + citedContext(responseText, source.url), + ); + const sourceRelatedBrands = association.brands; + // Keep only websites cited in answers that name a configured brand. The page + // is linked to a brand only when its title/address names it (verified) or the + // brand is named beside the citation (inferred). + if (!matchedBrands.length && !sourceRelatedBrands.length) continue; for (const brand of sourceRelatedBrands) { if (responseId) evidenceRows.push({ project_id: projectId, response_id: responseId, brand_id: brand.id, category, match_source: source.source_type === "citation_annotation" ? "citation_domain" : source.source_type === "research_source" ? "research_source" : "mentioned_url", matched_value: host, evidence_text: source.url, first_position: null, occurrence_count: 1, - confidence: directIds.has(brand.id) ? "deterministic" : "review_required", + confidence: association.status === "verified" ? "deterministic" : "review_required", }); } thirdPartyRows.push({ @@ -1301,7 +1309,7 @@ export function createVisibilityTrackingHandler( website_name: source.title || titleFromUrl(source.url), source_type: source.source_type, associated_brand_ids: sourceRelatedBrands.map((brand) => brand.id), associated_brand_names: sourceRelatedBrands.map((brand) => brand.name), - association_status: "inferred", frequency: 1, + association_status: association.status, frequency: 1, }); } } @@ -1335,6 +1343,7 @@ export function createVisibilityTrackingHandler( website_name: String(existing.website_name ?? "").trim() || String(row.website_name ?? "").trim(), associated_brand_ids: union(existing.associated_brand_ids, row.associated_brand_ids), associated_brand_names: union(existing.associated_brand_names, row.associated_brand_names), + association_status: strongerStatus(existing.association_status, row.association_status), frequency: Math.max(0, Number(existing.frequency ?? 0)) + Math.max(0, Number(row.frequency ?? 0)), }); } diff --git a/supabase/functions/visibility-tracking/mention-accuracy.test.ts b/supabase/functions/visibility-tracking/mention-accuracy.test.ts new file mode 100644 index 0000000..68f90be --- /dev/null +++ b/supabase/functions/visibility-tracking/mention-accuracy.test.ts @@ -0,0 +1,46 @@ +import { assert, assertEquals } from "https://deno.land/std@0.224.0/assert/mod.ts"; +import { mentionText } from "./mention-text.ts"; +import { associateSource, citedContext, onOwnSite, ownSiteHost, strongerStatus } from "./source-association.ts"; + +Deno.test("link addresses are blanked without moving anything else", async () => { + const cases = JSON.parse(await Deno.readTextFile(new URL("../../tests/mention_text_cases.json", import.meta.url))); + for (const item of cases) assertEquals(mentionText(item.text).replace(/ +/g, " "), item.visible.replace(/ +/g, " "), item.name); + for (const item of cases) assertEquals(mentionText(item.text).length, item.text.length, item.name); +}); + +const answer = [ + "1. **Alpha Clinic**: laser care.", + "", + " Open daily. ([news.example](https://news.example/alpha))", + "", + "2. **Beta Clinic**: skin care. ([guide.example](https://guide.example/beta?utm_source=openai))", + "", + "Gamma is also popular.", + "", + "([list.example](https://list.example/all))", +].join("\n"); +const brands = ["Alpha", "Beta", "Gamma"]; +const names = (url: string, title = "") => + associateSource(brands, (brand) => (title + " " + url).toLowerCase().includes(brand.toLowerCase()), (brand, text) => text.includes(brand), citedContext(answer, url)); + +Deno.test("a page is linked only to the brands named beside its citation", () => { + assertEquals(names("https://news.example/alpha-x"), { brands: ["Alpha"], status: "verified" }); + assertEquals(names("https://guide.example/beta?utm_source=openai", "Guide"), { brands: ["Beta"], status: "verified" }); + assertEquals(names("https://list.example/all"), { brands: ["Gamma"], status: "inferred" }); + assert(citedContext(answer, "https://news.example/alpha").includes("Alpha Clinic")); + assert(!citedContext(answer, "https://news.example/alpha").includes("Beta")); + assertEquals(names("https://unseen.example/page"), { brands: [], status: "unverified" }); +}); + +Deno.test("merging keeps the stronger link", () => { + assertEquals(strongerStatus("inferred", "verified"), "verified"); + assertEquals(strongerStatus("unverified", "inferred"), "inferred"); +}); + +Deno.test("a brand's own website is linked to it, a page inside a larger site is not", () => { + assertEquals(ownSiteHost("https://www.Alpha.example/"), "alpha.example"); + assertEquals(ownSiteHost("market.example/stores/alpha"), ""); + assert(onOwnSite("shop.alpha.example", ["alpha.example"])); + assert(!onOwnSite("notalpha.example", ["alpha.example"])); + assert(!onOwnSite("market.example", [""])); +}); diff --git a/supabase/functions/visibility-tracking/mention-text.ts b/supabase/functions/visibility-tracking/mention-text.ts new file mode 100644 index 0000000..672d7fe --- /dev/null +++ b/supabase/functions/visibility-tracking/mention-text.ts @@ -0,0 +1,22 @@ +/** + * Answer text as a reader sees it, for finding brand mentions: link addresses and + * bracketed domain citations such as "([example.com](https://example.com/page))" are + * blanked, because a brand that only appears there was not named in the answer. + * + * Every blanked character becomes a space, so match positions stay valid. + * public.mention_text in the database applies the same pattern; change both together + * (supabase/tests/mention_text_cases.json is run against each of them). + */ +const HIDDEN = new RegExp( + // A citation marker: a bare domain as the link label, wrapped in brackets. + "\\(\\[\\s*(?:www[.])?[A-Za-z0-9-]+(?:[.][A-Za-z0-9-]+)+\\s*\\]\\(https?://(?:[^()\\s]|\\([^()\\s]*\\))*\\)\\)" + + // The address part of any other markdown link; its label stays. + "|\\]\\(https?://(?:[^()\\s]|\\([^()\\s]*\\))*\\)" + + // A bare address. + "|https?://[^\\]\\[\\s<>\"'()‘’“”、。〃〈《》「」『』【】!(),:;?]+", + "gi", +); + +export function mentionText(text: string) { + return text.replace(HIDDEN, (hidden) => " ".repeat(hidden.length)); +} diff --git a/supabase/functions/visibility-tracking/source-association.ts b/supabase/functions/visibility-tracking/source-association.ts new file mode 100644 index 0000000..4a4c357 --- /dev/null +++ b/supabase/functions/visibility-tracking/source-association.ts @@ -0,0 +1,73 @@ +/** + * Which brands an outside web page may be linked to. + * + * A page on a brand's own website, or one that names the brand in its title or + * address, is linked to it. Otherwise only + * brands named in the same list item or paragraph as the citation are. Appearing + * somewhere else in the same answer is not enough. + */ +import { mentionText } from "./mention-text.ts"; + +export type AssociationStatus = "verified" | "inferred" | "unverified"; + +// A line that begins a new heading, list item, table row or bold lead-in. +const OPENS_BLOCK = /^(?:#{1,6}\s|\d+[.)、]|[-*•]\s|\*\*|\|)/; + +/** The answer text around each place the address is cited, with link addresses blanked. */ +export function citedContext(text: string, url: string) { + const lines = text.split("\n"); + let needle = url; + if (!text.includes(needle)) needle = url.split(/[?#]/)[0]; + if (!needle || !text.includes(needle)) return ""; + const visible = lines.map((line) => mentionText(line)); + const hasWords = (index: number) => /[\p{L}\p{N}]/u.test(visible[index]); + const opens = (index: number) => { + // A line holding only a citation belongs to the text above it. + if (!hasWords(index)) return false; + if (OPENS_BLOCK.test(lines[index])) return true; + return !/^\s/.test(lines[index]) && (index === 0 || lines[index - 1].trim() === ""); + }; + const blocks: string[] = []; + lines.forEach((line, index) => { + if (!line.includes(needle)) return; + let start = index; + while (start > 0 && !opens(start)) start--; + blocks.push(visible.slice(start, index + 1).join("\n")); + }); + return blocks.join("\n"); +} + +export function associateSource( + brands: Brand[], + namedOnPage: (brand: Brand) => boolean, + namedInText: (brand: Brand, text: string) => boolean, + context: string, +): { brands: Brand[]; status: AssociationStatus } { + const direct = brands.filter(namedOnPage); + if (direct.length) return { brands: direct, status: "verified" }; + const nearby = context ? brands.filter((brand) => namedInText(brand, context)) : []; + return nearby.length ? { brands: nearby, status: "inferred" } : { brands: [], status: "unverified" }; +} + +const STRENGTH: Record = { unverified: 0, inferred: 1, verified: 2 }; + +export function strongerStatus(left: unknown, right: unknown) { + const a = (String(left) in STRENGTH ? String(left) : "unverified") as AssociationStatus; + const b = (String(right) in STRENGTH ? String(right) : "unverified") as AssociationStatus; + return STRENGTH[a] >= STRENGTH[b] ? a : b; +} + +/** + * Host of a configured brand website, given as a domain or a full address. A page + * inside a larger site (a path, such as a marketplace profile) does not own that host. + */ +export function ownSiteHost(site: string) { + const bare = site.trim().toLowerCase().replace(/^[a-z]+:\/\//, ""); + if (/\/[^/?#]/.test(bare.split(/[?#]/)[0])) return ""; + return bare.split(/[/?#:]/)[0].replace(/^www\./, ""); +} + +export function onOwnSite(host: string, ownHosts: string[]) { + const page = host.toLowerCase().replace(/^www\./, ""); + return ownHosts.some((own) => own.includes(".") && (page === own || page.endsWith("." + own))); +} diff --git a/supabase/maintenance/20261204_brand_name_additions.sql b/supabase/maintenance/20261204_brand_name_additions.sql new file mode 100644 index 0000000..694f1c4 --- /dev/null +++ b/supabase/maintenance/20261204_brand_name_additions.sql @@ -0,0 +1,50 @@ +-- Brand name additions for 20261204: names that only matched through a web address before, +-- local-language names, and KFM's too-broad alias. Run after 20261204200000_fewer_false_mentions.sql. +-- Saving registry aliases queues a competitor recalculation for the project. + +update public.brand_registry b +set aliases = coalesce(b.aliases, '{}') || array(select x from unnest(a.extra) x where not x = any(coalesce(b.aliases, '{}'))) +from (values + ('1d64a537', 'Guangdong Magwise Precision Technology', '{Magwise}'::text[]), + ('1d64a537', 'AlumCasting (KingShip Dongguan Precision Manufacturing)', '{AlumCasting}'::text[]), + ('1d64a537', 'OKDieCast (Shenzhen Leijing Technology)', '{OKDieCast}'::text[]), + ('1d64a537', 'Seasky Medical', '{SeaskyMedical}'::text[]), + ('1d64a537', 'Huzhou Rui Magnesium Precision Metal', '{湖州瑞镁精密金属有限公司,瑞镁精密}'::text[]), + ('45994de2', 'Ding Precision', '{DINGPRECISION}'::text[]), + ('45994de2', 'MST Fab', '{MSTFAB}'::text[]), + ('45994de2', 'Mansfield Group', '{Mansfield Manufacturing}'::text[]), + ('45994de2', 'ACE Sheet Metal Manufacturing', '{Ace Mach}'::text[]), + ('45994de2', 'Hoorenwell', '{鸿仁模具}'::text[]), + ('45994de2', 'Deepproto', '{深度原型}'::text[]), + ('45994de2', 'Weiyadakeji', '{维亚达科技}'::text[]), + ('45994de2', 'Balford', '{百富都}'::text[]), + ('45994de2', 'Needmakes', '{多点智造}'::text[]), + ('181fed02', 'TELUS International AI', '{TELUS Digital}'::text[]), + ('181fed02', 'RWS Group', '{RWS TrainAI}'::text[]), + ('181fed02', 'Media.Monks', '{Monks}'::text[]), + ('58a67e81', 'Sunoh.ai', '{Sunoh}'::text[]), + ('58a67e81', 'Tali AI', '{Tali}'::text[]), + ('5e7e3ec9', 'StarTech.com', '{StarTech}'::text[]), + ('5e7e3ec9', 'Twelve South', '{TwelveSouth}'::text[]), + ('5e7e3ec9', 'Anker', '{安克,アンカー,앤커}'::text[]), + ('5e7e3ec9', 'Belkin', '{贝尔金,벨킨}'::text[]), + ('e5c1e7aa', 'Aqara', '{アカラ}'::text[]), + ('e5c1e7aa', 'TP-Link', '{ティーピーリンク}'::text[]), + ('e5c1e7aa', 'UGREEN', '{ユージグリーン}'::text[]), + ('e5c1e7aa', 'SwitchBot', '{スイッチボット}'::text[]) +) as a(project_prefix, brand, extra) +where b.project_id::text like a.project_prefix || '%' and b.canonical_name = a.brand; + +-- KFM: the bare name 金德 also matches an unrelated Guangdong company. +update public.projects +set brand_terms = array_remove(brand_terms, '金德') || array['金德科技', '金德控股', '金德精密'] +where id = '45994de2-1a38-433e-be8d-fb5358653b91' and '金德' = any(brand_terms); + +update public.brand_registry +set aliases = array_remove(aliases, '金德') || array['金德科技', '金德控股', '金德精密'] +where project_id = '45994de2-1a38-433e-be8d-fb5358653b91' and is_tracked_brand and '金德' = any(aliases); + +update public.category_brand_assignments a +set aliases = array_remove(a.aliases, '金德') || array['金德科技', '金德控股', '金德精密'] +from public.brand_registry b +where b.id = a.brand_id and b.is_tracked_brand and a.project_id = '45994de2-1a38-433e-be8d-fb5358653b91' and '金德' = any(a.aliases); diff --git a/supabase/maintenance/20261204_narrow_website_brand_links.sql b/supabase/maintenance/20261204_narrow_website_brand_links.sql new file mode 100644 index 0000000..f21f0a9 --- /dev/null +++ b/supabase/maintenance/20261204_narrow_website_brand_links.sql @@ -0,0 +1,116 @@ +-- One-time cleanup of old website-to-brand links (run after 20261204200000_fewer_false_mentions.sql). +-- It only narrows existing links; it never adds a brand to a page. +-- 1. Run this file to create the helpers. +-- 2. select maint_20261204.compute('', '', ''); -- repeat per project (split large ones by date) +-- 3. select maint_20261204.apply(''); +-- maint_20261204.tp_new keeps the previous values (old_ids, old_names, old_status) for restoring. + +create schema if not exists maint_20261204; +revoke all on schema maint_20261204 from public; + +create or replace function maint_20261204.cited_context(t text, url text) returns text +language plpgsql immutable set search_path = public, pg_temp as $fn$ +declare + needle text := url; l text[]; v text[]; i int; s int; out text := ''; +begin + if position(needle in t) = 0 then needle := split_part(split_part(url,'?',1),'#',1); end if; + if needle = '' or position(needle in t) = 0 then return ''; end if; + l := string_to_array(t, E'\n'); + for i in 1..array_length(l,1) loop v[i] := public.mention_text(l[i]); end loop; + for i in 1..array_length(l,1) loop + continue when position(needle in l[i]) = 0; + s := i; + while s > 1 and not (v[s] ~ '[[:alnum:]]' and (l[s] ~ '^(#{1,6}\s|\d+[.)、]|[-*•]\s|\*\*|\|)' + or (l[s] !~ '^\s' and l[s-1] ~ '^\s*$'))) loop + s := s - 1; + end loop; + out := out || E'\n' || array_to_string(v[s:i], E'\n'); + end loop; + return out; +end $fn$; + +create table if not exists maint_20261204.tp_new( + id uuid primary key, project_id uuid, old_ids uuid[], old_names text[], old_status text, + new_ids uuid[], new_names text[], new_status text); + +create or replace function maint_20261204.compute(p uuid, d0 date, d1 date) returns void +language plpgsql set search_path = public, pg_temp as $fn$ +begin + drop table if exists _bp, _rows, _resp, _ctx; + create temp table _bp as + with pair as ( + select distinct t.category, u.brand_id from third_party_mentions t cross join lateral unnest(t.associated_brand_ids) u(brand_id) + where t.project_id = p and t.association_status = 'inferred' and t.metric_date between d0 and d1) + select pair.category, pair.brand_id, br.canonical_name, + alias_match_pattern(array(select distinct btrim(x) from unnest( + array[br.canonical_name] || coalesce(br.aliases,'{}') || coalesce(a.aliases,'{}') + || case when a.role = 'tracked_brand' or br.is_tracked_brand then coalesce(pj.brand_terms,'{}') else '{}'::text[] end) x + where length(btrim(x)) > 1)) as pattern, + array(select distinct h from ( + select regexp_replace(regexp_replace(s.bare, '[/?#:].*$', ''), '^www[.]', '') as h + from (select regexp_replace(lower(btrim(w)), '^[a-z]+://', '') as bare + from unnest(coalesce(a.websites,'{}') || array[br.primary_website] || coalesce(br.additional_websites,'{}')) w + where w is not null) s + where split_part(split_part(s.bare,'?',1),'#',1) !~ '/[^/]') o + where position('.' in h) > 0) as hosts + from pair join brand_registry br on br.id = pair.brand_id + join projects pj on pj.id = p + left join category_brand_assignments a on a.project_id = p and a.brand_id = pair.brand_id and a.category = pair.category; + create index on _bp(category, brand_id); + + create temp table _rows as + select t.id, t.response_id, t.metric_date, t.category, t.url, t.associated_brand_ids as ids, t.associated_brand_names as names, + t.association_status as status, lower(coalesce(t.website_name,'') || ' ' || t.url) as page, + regexp_replace(lower(t.hostname), '^www[.]', '') as host + from third_party_mentions t + where t.project_id = p and t.association_status = 'inferred' and t.metric_date between d0 and d1 + and cardinality(t.associated_brand_ids) > 0 + and not exists (select 1 from maint_20261204.tp_new n where n.id = t.id); + + create temp table _resp as + select ar.id, (ar.captured_at at time zone 'Asia/Kuala_Lumpur')::date as d, ar.response_text + from ai_responses ar where ar.project_id = p and ar.response_text is not null + and (ar.id in (select response_id from _rows) + or (exists (select 1 from _rows where response_id is null) + and (ar.captured_at at time zone 'Asia/Kuala_Lumpur')::date between d0 and d1)); + create index on _resp(id); create index on _resp(d); + analyze _rows; analyze _resp; + + create temp table _ctx as + select x.id, string_agg(maint_20261204.cited_context(r.response_text, x.url), E'\n') as context + from _rows x join _resp r on r.id = x.response_id group by x.id; + insert into _ctx + with nr as (select x.id, x.url, x.metric_date, split_part(split_part(x.url,'?',1),'#',1) as bare from _rows x where x.response_id is null), + hit as (select nr.id, nr.url, r.id as rid, position(nr.url in r.response_text) > 0 as exact + from nr join _resp r on r.d = nr.metric_date and position(nr.bare in r.response_text) > 0), + best as (select h.*, bool_or(h.exact) over (partition by h.id) as any_exact from hit h) + select b.id, string_agg(maint_20261204.cited_context(r.response_text, b.url), E'\n') + from best b join _resp r on r.id = b.rid where b.exact or not b.any_exact group by b.id; + create index on _ctx(id); analyze _ctx; + + insert into maint_20261204.tp_new + select x.id, p, x.ids, x.names, x.status, + coalesce(case when d.ids is not null then d.ids else n.ids end, '{}'), + coalesce(case when d.ids is not null then d.names else n.names end, '{}'), + case when d.ids is not null then 'verified' when n.ids is not null then 'inferred' else 'unverified' end + from _rows x + left join _ctx c on c.id = x.id + left join lateral (select array_agg(b.brand_id order by b.canonical_name) ids, array_agg(b.canonical_name order by b.canonical_name) names + from _bp b where b.category = x.category and b.brand_id = any(x.ids) + and (x.page ~* b.pattern or exists (select 1 from unnest(b.hosts) h where x.host = h or right(x.host, length(h)+1) = '.' || h))) d on true + left join lateral (select array_agg(b.brand_id order by b.canonical_name) ids, array_agg(b.canonical_name order by b.canonical_name) names + from _bp b where d.ids is null and coalesce(c.context,'') <> '' and b.category = x.category and b.brand_id = any(x.ids) and c.context ~* b.pattern) n on true; + drop table _bp, _rows, _resp, _ctx; +end $fn$; + +create or replace function maint_20261204.apply(p uuid) returns integer +language plpgsql set search_path = public, pg_temp as $fn$ +declare n integer; +begin + update third_party_mentions t + set associated_brand_ids = x.new_ids, associated_brand_names = x.new_names, association_status = x.new_status + from maint_20261204.tp_new x + where x.project_id = p and t.id = x.id; + get diagnostics n = row_count; + return n; +end $fn$; diff --git a/supabase/migrations/20261204200000_fewer_false_mentions.sql b/supabase/migrations/20261204200000_fewer_false_mentions.sql new file mode 100644 index 0000000..0627e92 --- /dev/null +++ b/supabase/migrations/20261204200000_fewer_false_mentions.sql @@ -0,0 +1,454 @@ +-- Fewer false brand mentions. +-- +-- 1. public.mention_text blanks link addresses and bracketed domain citations before +-- brand names are looked for. Same pattern as visibility-tracking/mention-text.ts. +-- 2. The first part of a competitor's web address is no longer treated as its name. +-- 3. Recalculation applies both, removes competitor mentions that no longer match and +-- refreshes the tracked brand's share of voice and position to match. Published +-- visibility scores of the tracked brand are not restated. + +create or replace function public.mention_text(t text) returns text +language plpgsql immutable parallel safe set search_path = public, pg_temp as $fn$ +declare + c_hidden constant text := '\(\[\s*(?:www[.])?[A-Za-z0-9-]+(?:[.][A-Za-z0-9-]+)+\s*\]\(https?://(?:[^()\s]|\([^()\s]*\))*\)\)|\]\(https?://(?:[^()\s]|\([^()\s]*\))*\)|https?://[^][\s<>"''()‘’“”、。〃〈《》「」『』【】!(),:;?]+'; + v_parts text[]; + v_match text[]; + v_i integer := 1; + v_out text := ''; +begin + if t is null or t !~* 'https?://' then return t; end if; + v_parts := regexp_split_to_array(t, c_hidden, 'i'); + for v_match in select regexp_matches(t, '(' || c_hidden || ')', 'gi') loop + v_out := v_out || v_parts[v_i] || repeat(' ', char_length(v_match[1])); + v_i := v_i + 1; + end loop; + return v_out || v_parts[v_i]; +end +$fn$; + +CREATE OR REPLACE FUNCTION public.competitor_entities(p_project_id uuid) + RETURNS TABLE(category text, brand_id uuid, canonical_name text, websites text[], aliases text[], pattern text) + LANGUAGE sql + STABLE SECURITY DEFINER + SET search_path TO 'public' +AS $function$ + with base as ( + select a.category, b.id as brand_id, b.canonical_name, + array(select distinct public.site_host(w) from unnest( + coalesce(a.websites, '{}') || array[b.primary_website] || coalesce(b.additional_websites, '{}')) w + where public.site_host(w) is not null) as websites, + coalesce(b.aliases, '{}') as b_aliases, coalesce(a.aliases, '{}') as a_aliases + from public.category_brand_assignments a + join public.brand_registry b on b.id = a.brand_id and b.is_active + where a.project_id = p_project_id and a.role = 'competitor' and a.include_in_metrics + ) + select base.category, base.brand_id, base.canonical_name, base.websites, q.al, public.alias_match_pattern(q.al) + from base + cross join lateral ( + select array(select distinct btrim(v) from unnest( + array[base.canonical_name] || base.b_aliases || base.a_aliases || base.websites) v + where length(btrim(v)) > 1) as al + ) q; +$function$; + +CREATE OR REPLACE FUNCTION public.recompute_competitor_metrics(p_project_id uuid, p_date_from date DEFAULT NULL::date, p_date_to date DEFAULT NULL::date) + RETURNS jsonb + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path TO 'public', 'pg_temp' + SET statement_timeout TO '20min' +AS $function$ +declare + v_project public.projects%rowtype; + v_categories text[]; + v_tracked_id uuid; + v_tracked_pattern text; + v_tracked_sites text[]; + fr record; + tn text; + ur record; + v_pres integer; + v_resp integer; + v_score numeric; + v_synth uuid; + v_slices integer := 0; + v_skipped jsonb := '[]'::jsonb; + v_blocked jsonb := '[]'::jsonb; + v_units integer := 0; + v_obs integer := 0; + v_evidence integer := 0; + v_citations integer := 0; + v_archived integer := 0; + v_overall integer := 0; + v_entities integer := 0; + v_preserved jsonb := '[]'::jsonb; + v_restored integer := 0; +begin + perform pg_advisory_xact_lock(hashtextextended(p_project_id::text || '|__TRACKING_REPLACEMENT_RECOMPUTE__', 0)); + select * into v_project from public.projects where id = p_project_id; + if not found then raise exception 'project % not found', p_project_id; end if; + v_categories := array(select x from unnest(v_project.categories) x where x <> 'Overall'); + if coalesce(cardinality(v_categories), 0) = 0 then + return jsonb_build_object('status', 'skipped', 'reason', 'project has no categories'); + end if; + + select b.id, + public.alias_match_pattern(array_remove( + array[v_project.brand_name, b.canonical_name, b.primary_website] + || coalesce(b.aliases, '{}') || coalesce(v_project.brand_terms, '{}') + || coalesce(v_project.brand_domains, '{}') || coalesce(b.additional_websites, '{}'), null)) + into v_tracked_id, v_tracked_pattern + from public.brand_registry b + where b.project_id = p_project_id and b.is_tracked_brand and b.is_active + limit 1; + + select array(select distinct public.site_host(w) from unnest( + coalesce(v_project.brand_domains, '{}') || array[b.primary_website] || coalesce(b.additional_websites, '{}')) w + where public.site_host(w) is not null) + into v_tracked_sites + from public.brand_registry b + where b.project_id = p_project_id and b.is_tracked_brand and b.is_active + limit 1; + + -- 1. Republish verifiable per-category slices of older all-category runs. + for fr in + select distinct on (tr.d, tr.tracking_location, tr.provider) tr.* + from ( + select r.*, (r.completed_at at time zone 'Asia/Kuala_Lumpur')::date as d + from public.tracking_runs r + where r.project_id = p_project_id and r.run_kind = 'full' and r.status = 'completed' + and r.completed_at is not null and r.provider = 'chatgpt' + ) tr + where (p_date_from is null or tr.d >= p_date_from) and (p_date_to is null or tr.d <= p_date_to) + and not exists ( + select 1 from public.tracking_runs x + where x.project_id = tr.project_id and x.run_kind = 'category' and x.source_run_id is null + and x.status = 'completed' and x.published_at is not null and x.superseded_at is null + and x.tracking_location = tr.tracking_location and x.provider = tr.provider + and (x.published_at at time zone 'Asia/Kuala_Lumpur')::date = tr.d) + order by tr.d, tr.tracking_location, tr.provider, tr.completed_at desc + loop + foreach tn in array v_categories loop + if exists (select 1 from public.tracking_runs x + where x.source_run_id = fr.id and x.category = tn and x.published_at is not null and x.superseded_at is null) then + continue; + end if; + select p.presence_count, p.response_count into v_pres, v_resp from public.run_tracked_presence(fr.id, tn, fr.tracking_location) p; + select v.visibility_score into v_score from public.visibility_daily v + where v.project_id = p_project_id and v.metric_date = fr.d and v.category = tn + and v.llm_provider = 'Overall' and v.tracking_location = fr.tracking_location; + if coalesce(v_resp, 0) > 0 and v_score is not null + and abs(round(v_pres::numeric / v_resp * 100, 1) - v_score) <= 0.05 then + insert into public.tracking_runs ( + project_id, provider, status, total_prompts, completed_prompts, failed_prompts, started_at, completed_at, + tracking_location, category, published_at, run_kind, source_run_id, error_message) + values (p_project_id, fr.provider, 'completed', v_resp, v_resp, 0, fr.started_at, fr.completed_at, + fr.tracking_location, tn, fr.completed_at, 'category', fr.id, 'Backfilled category slice of all-category run ' || fr.id) + returning id into v_synth; + update public.visibility_daily set run_id = v_synth + where project_id = p_project_id and metric_date = fr.d and category = tn + and tracking_location = fr.tracking_location and llm_provider in ('Overall', 'chatgpt'); + v_slices := v_slices + 1; + else + v_skipped := v_skipped || jsonb_build_object( + 'date', fr.d, 'category', tn, 'stored_score', v_score, + 'recomputed', case when coalesce(v_resp, 0) > 0 then round(v_pres::numeric / v_resp * 100, 1) end); + end if; + end loop; + end loop; + + -- 2. Units = published category runs (real or backfilled slices) in range. + -- Temp tables are transaction-scoped; process one project per transaction. + create temp table _cm_units on commit drop as + select tr.id as unit_run, coalesce(tr.source_run_id, tr.id) as src_run, tr.category, tr.tracking_location as loc, + tr.provider, (tr.published_at at time zone 'Asia/Kuala_Lumpur')::date as d + from public.tracking_runs tr + where tr.project_id = p_project_id and tr.run_kind = 'category' and tr.status = 'completed' + and tr.published_at is not null and tr.superseded_at is null and tr.provider <> 'Overall' + and tr.category = any(v_categories) + and (p_date_from is null or (tr.published_at at time zone 'Asia/Kuala_Lumpur')::date >= p_date_from) + and (p_date_to is null or (tr.published_at at time zone 'Asia/Kuala_Lumpur')::date <= p_date_to); + + create temp table _cm_resp on commit drop as + select distinct on (u.unit_run, coalesce(ar.prompt_id::text, md5(btrim(ar.prompt_snapshot)), ar.id::text)) + u.unit_run, u.src_run, u.category, u.loc, u.d, u.provider, + ar.id as response_id, ar.response_text, public.mention_text(ar.response_text) as visible_text, ar.raw_response + from _cm_units u + cross join lateral public.run_category_responses(u.unit_run) c + join public.ai_responses ar on ar.id = c.response_id and ar.response_status = 'completed' + and coalesce(btrim(ar.response_text), '') <> '' + where c.category = u.category + order by u.unit_run, coalesce(ar.prompt_id::text, md5(btrim(ar.prompt_snapshot)), ar.id::text), + ar.captured_at desc, ar.id desc; + create index on _cm_resp (unit_run); + + -- Never rewrite a unit whose published figures cannot be reproduced from what is + -- stored: rebuilding it would silently replace correct history. + create temp table _cm_check on commit drop as + select u.unit_run, u.category, u.loc, u.d, u.provider, s.published_responses, coalesce(f.n, 0) as response_found, + coalesce(f.n, 0) > 0 and (s.published_score is null + or abs(round(f.with_evidence::numeric / f.n * 100, 1) - s.published_score) <= 0.05) as evidence_ok, + -- Older data can lack stored tracked-brand mentions that the answer text still shows. + coalesce(f.n, 0) > 0 and v_tracked_id is not null + and not exists (select 1 from public.tracking_runs tx where tx.id = u.unit_run and tx.data_source = 'profound_import') + and abs(round(f.with_either::numeric / f.n * 100, 1) - s.published_score) <= 0.05 as text_ok + from _cm_units u + left join ( + select r.unit_run, count(*)::integer as n, + count(*) filter (where h.has_evidence)::integer as with_evidence, + count(*) filter (where h.has_evidence or r.response_text ~* v_tracked_pattern)::integer as with_either + from _cm_resp r + cross join lateral (select exists ( + select 1 from public.response_brand_evidence e + where e.response_id = r.response_id and e.brand_id = v_tracked_id and e.match_source = 'response_text') as has_evidence) h + group by r.unit_run) f on f.unit_run = u.unit_run + left join lateral ( + select max(v.response_count) as published_responses, max(v.visibility_score) as published_score + from public.visibility_daily v where v.run_id = u.unit_run and v.category = u.category) s on true; + + create temp table _cm_preserved on commit drop as + select c.unit_run, c.category, c.loc, c.d, c.provider, c.published_responses, c.response_found, + case when c.response_found = 0 or c.published_responses <> c.response_found + then 'answers_missing' else 'score_not_reproducible' end as reason + from _cm_check c + where c.response_found = 0 or c.published_responses <> c.response_found + or (not c.evidence_ok and not coalesce(c.text_ok, false)); + delete from _cm_resp r using _cm_preserved p where p.unit_run = r.unit_run; + delete from _cm_units u using _cm_preserved p where p.unit_run = u.unit_run; + select coalesce(jsonb_agg(jsonb_build_object( + 'date', d, 'category', category, 'provider', provider, 'location', loc, 'reason', reason, + 'published_responses', published_responses, 'stored_responses_found', response_found) + order by d, category, provider), '[]'::jsonb) + into v_preserved from _cm_preserved; + + -- Restore missing tracked-brand mentions only where doing so reproduces the published score. + insert into public.response_brand_evidence ( + project_id, response_id, brand_id, category, match_source, matched_value, evidence_text, + first_position, occurrence_count, confidence) + select p_project_id, r.response_id, v_tracked_id, r.category, 'response_text', v_project.brand_name, + substr(r.response_text, greatest(1, regexp_instr(r.response_text, v_tracked_pattern, 1, 1, 0, 'i') - 80), 260), + regexp_instr(r.response_text, v_tracked_pattern, 1, 1, 0, 'i') - 1, + regexp_count(r.response_text, v_tracked_pattern, 1, 'i'), 'deterministic' + from _cm_resp r + join _cm_check c on c.unit_run = r.unit_run and not c.evidence_ok and c.text_ok + where r.response_text ~* v_tracked_pattern + and not exists (select 1 from public.response_brand_evidence e + where e.response_id = r.response_id and e.brand_id = v_tracked_id and e.match_source = 'response_text') + on conflict (response_id, brand_id, category, match_source, matched_value) do nothing; + get diagnostics v_restored = row_count; + + create temp table _cm_entities on commit drop as + select * from public.competitor_entities(p_project_id) e where e.pattern is not null and e.category = any(v_categories); + select count(distinct brand_id) into v_entities from _cm_entities; + + -- 3a. Text matches (competitors) plus the tracked brand for position ordering. + create temp table _cm_hits on commit drop as + select r.unit_run, r.response_id, e.brand_id, false as is_tracked, + regexp_count(r.visible_text, e.pattern, 1, 'i') as n, + regexp_instr(r.visible_text, e.pattern, 1, 1, 0, 'i') as pos + from _cm_resp r + join _cm_entities e on e.category = r.category and r.visible_text ~* e.pattern; + if v_tracked_pattern is not null then + insert into _cm_hits + select r.unit_run, r.response_id, v_tracked_id, true, + regexp_count(r.visible_text, v_tracked_pattern, 1, 'i'), + regexp_instr(r.visible_text, v_tracked_pattern, 1, 1, 0, 'i') + from _cm_resp r where r.visible_text ~* v_tracked_pattern + and not exists (select 1 from public.tracking_runs tx where tx.id = r.unit_run and tx.data_source = 'profound_import'); + -- Imported runs: the tracked brand's presence is the stored evidence (it may come from the source's own flag). + insert into _cm_hits + select r.unit_run, r.response_id, v_tracked_id, true, e.occurrence_count, e.first_position + 1 + from _cm_resp r + join public.response_brand_evidence e on e.response_id = r.response_id and e.brand_id = v_tracked_id and e.match_source = 'response_text' + where exists (select 1 from public.tracking_runs tx where tx.id = r.unit_run and tx.data_source = 'profound_import'); + end if; + + -- Mentions stored earlier that today's matching rules no longer find are removed. + delete from public.response_brand_evidence e + using _cm_resp r, _cm_entities en + where e.project_id = p_project_id and e.response_id = r.response_id and e.category = r.category + and en.category = r.category and en.brand_id = e.brand_id and e.match_source = 'response_text' + and e.brand_id is distinct from v_tracked_id + and not exists (select 1 from _cm_hits h where h.unit_run = r.unit_run and h.response_id = r.response_id + and h.brand_id = e.brand_id); + + -- 3b. Evidence for the current competitor set (response-text matches). + insert into public.response_brand_evidence ( + project_id, response_id, brand_id, category, match_source, matched_value, evidence_text, + first_position, occurrence_count, confidence) + select p_project_id, h.response_id, h.brand_id, e.category, 'response_text', e.canonical_name, + substr(r.response_text, greatest(1, h.pos - 80), 260), h.pos - 1, h.n, 'deterministic' + from _cm_hits h + join _cm_resp r on r.response_id = h.response_id and r.unit_run = h.unit_run + join _cm_entities e on e.brand_id = h.brand_id and e.category = r.category + where not h.is_tracked + on conflict (response_id, brand_id, category, match_source, matched_value) do update set + evidence_text = excluded.evidence_text, first_position = excluded.first_position, + occurrence_count = excluded.occurrence_count; + get diagnostics v_evidence = row_count; + + -- 3c. Citation occurrences: cited URLs (url_citation annotations) attributed by domain to each entity. + -- Competitors are rebuilt for their current set. The tracked brand is rebuilt only where it has no normalized + -- occurrences yet (older days), so already-correct tracked counts are left untouched. + create temp table _cm_cit_entities on commit drop as + select e.category, e.brand_id, e.websites, false as is_tracked from _cm_entities e + union all + select tp.category_name, v_tracked_id, coalesce(v_tracked_sites, '{}'), true + from unnest(v_categories) as tp(category_name) where v_tracked_id is not null; + + create temp table _cm_tracked_missing on commit drop as + select u.unit_run from _cm_units u + where v_tracked_id is not null and not exists ( + select 1 from public.citation_occurrences co join _cm_resp r on r.response_id = co.response_id + where r.unit_run = u.unit_run and co.entity_id = v_tracked_id); + + create temp table _cm_cit on commit drop as + select distinct r.unit_run, r.src_run, r.response_id, r.category, r.loc, r.d, r.provider, e.brand_id, e.is_tracked, + cu.url as citation_url, public.canonicalize_citation_url(cu.url) as canonical_url, + lower(split_part(split_part(regexp_replace(public.canonicalize_citation_url(cu.url), '^https?://', '', 'i'), '/', 1), ':', 1)) as host + from _cm_resp r + cross join lateral ( + select a ->> 'url' as url + from jsonb_path_query(r.raw_response, '$.output[*].content[*].annotations[*] ? (@.type == "url_citation")') a + ) cu + join _cm_cit_entities e on e.category = r.category + where cu.url ~* '^https?://' + and (not e.is_tracked or r.unit_run in (select unit_run from _cm_tracked_missing)) + and exists (select 1 from unnest(e.websites) w + where lower(split_part(split_part(regexp_replace(public.canonicalize_citation_url(cu.url), '^https?://', '', 'i'), '/', 1), ':', 1)) = w + or lower(split_part(split_part(regexp_replace(public.canonicalize_citation_url(cu.url), '^https?://', '', 'i'), '/', 1), ':', 1)) like '%.' || w); + + delete from public.citation_occurrences co + using _cm_resp r, _cm_entities e + where co.response_id = r.response_id and co.entity_id = e.brand_id and e.category = r.category; + insert into public.citation_occurrences ( + project_id, response_id, entity_id, category, metric_date, provider, tracking_location, run_id, + citation_url, canonical_url, canonical_domain, citation_index) + select distinct on (response_id, brand_id, canonical_url) + p_project_id, response_id, brand_id, category, d, provider, loc, src_run, citation_url, canonical_url, host, 1 + from _cm_cit + order by response_id, brand_id, canonical_url, citation_url + on conflict (response_id, entity_id, canonical_url) do nothing; + get diagnostics v_citations = row_count; + + -- Tracked-brand daily citation count for the units that were just (re)built. + update public.visibility_daily v set citation_count = x.n + from (select m.unit_run, count(distinct c.response_id::text || '|' || c.canonical_url)::integer as n -- NULL-safe: a unit with no tracked citations counts 0, not 1 + from _cm_tracked_missing m + left join _cm_cit c on c.unit_run = m.unit_run and c.is_tracked + group by m.unit_run) x + where v.run_id = x.unit_run; + + -- 3d. Competitor observations for every unit (zero-presence competitors included). + insert into public.category_brand_observations ( + project_id, brand_id, category, metric_date, tracking_location, llm_provider, + presence_count, response_count, mention_count, citation_count, average_position, run_id) + select p_project_id, e.brand_id, u.category, u.d, u.loc, u.provider, + coalesce(h.presence, 0), rc.n, coalesce(h.mentions, 0), coalesce(cc.n, 0), ap.avg_pos, u.unit_run + from _cm_units u + join (select unit_run, count(*)::integer as n from _cm_resp group by unit_run) rc on rc.unit_run = u.unit_run + join _cm_entities e on e.category = u.category + left join (select unit_run, brand_id, count(*)::integer as presence, sum(n)::integer as mentions + from _cm_hits where not is_tracked group by unit_run, brand_id) h + on h.unit_run = u.unit_run and h.brand_id = e.brand_id + left join (select unit_run, brand_id, count(distinct (response_id, canonical_url))::integer as n + from _cm_cit where not is_tracked group by unit_run, brand_id) cc + on cc.unit_run = u.unit_run and cc.brand_id = e.brand_id + left join (select unit_run, brand_id, round(avg(rk)::numeric, 2) as avg_pos + from (select unit_run, brand_id, + row_number() over (partition by response_id order by pos, is_tracked desc, brand_id) as rk + from _cm_hits) z group by unit_run, brand_id) ap + on ap.unit_run = u.unit_run and ap.brand_id = e.brand_id + on conflict (project_id, brand_id, category, metric_date, tracking_location, llm_provider) do update set + presence_count = excluded.presence_count, response_count = excluded.response_count, + mention_count = excluded.mention_count, citation_count = excluded.citation_count, + average_position = excluded.average_position, run_id = excluded.run_id; + get diagnostics v_obs = row_count; + + -- 3e. Archive then remove derived observations of brands that are no longer competitors in these scopes. + insert into public.category_brand_observations_archive + select o.*, now(), 'competitor set replaced' + from public.category_brand_observations o + join _cm_units u on u.category = o.category and u.d = o.metric_date and u.loc = o.tracking_location and u.provider = o.llm_provider + where o.project_id = p_project_id + and not exists (select 1 from _cm_entities e where e.category = o.category and e.brand_id = o.brand_id); + get diagnostics v_archived = row_count; + delete from public.category_brand_observations o + using _cm_units u + where o.project_id = p_project_id and u.category = o.category and u.d = o.metric_date + and u.loc = o.tracking_location and u.provider = o.llm_provider + and not exists (select 1 from _cm_entities e where e.category = o.category and e.brand_id = o.brand_id); + + -- 3f. Tracked-brand share of voice and position depend on the competitor mentions, so they follow them. + update public.visibility_daily v set + share_of_voice_score = x.sov, share_of_voice_rank = x.sov_rank, + average_position = x.pos, average_position_rank = x.pos_rank + from ( + select u.unit_run, + case when t.total > 0 then round(t.mine::numeric / t.total * 100, 1) else 0 end as sov, + 1 + (select count(*) from public.category_brand_observations o + where o.run_id = u.unit_run and o.category = u.category and o.response_count > 0 and o.mention_count > t.mine)::integer as sov_rank, + tp.avg_pos as pos, + case when tp.avg_pos is not null and exists ( + select 1 from public.category_brand_observations o + where o.run_id = u.unit_run and o.category = u.category and o.average_position is not null) + then 1 + (select count(*) from public.category_brand_observations o + where o.run_id = u.unit_run and o.category = u.category and o.average_position is not null + and o.average_position < tp.avg_pos)::integer end as pos_rank + from _cm_units u + cross join lateral (select coalesce(sum(h.n) filter (where h.is_tracked), 0) as mine, coalesce(sum(h.n), 0) as total + from _cm_hits h where h.unit_run = u.unit_run) t + left join lateral ( + select round(avg(z.rk)::numeric, 2) as avg_pos + from (select row_number() over (partition by hh.response_id order by hh.pos, hh.is_tracked desc, hh.brand_id) as rk, hh.is_tracked, hh.pos + from _cm_hits hh where hh.unit_run = u.unit_run) z + where z.is_tracked and z.pos is not null) tp on true + ) x + where v.run_id = x.unit_run; + + -- 4. Rank + population via the canonical implementation; a unit whose tracked score no longer reproduces is reported. + for ur in select * from _cm_units order by d, category loop + begin + perform public.finalize_run_metrics(ur.unit_run); + v_units := v_units + 1; + exception when others then + v_blocked := v_blocked || jsonb_build_object('date', ur.d, 'category', ur.category, 'reason', sqlerrm); + insert into _cm_preserved (unit_run, category, loc, d, provider) values (ur.unit_run, ur.category, ur.loc, ur.d, ur.provider); + end; + end loop; + + -- 5. Overall pools the category runs of each day. + -- A day with a preserved unit keeps its published Overall figures. + for ur in select distinct u.d, u.loc, u.provider from _cm_units u + where not exists (select 1 from _cm_preserved p where p.d = u.d and p.loc = u.loc and p.provider = u.provider) + order by u.d loop + if public.publish_engine_overall_metrics(p_project_id, ur.d, ur.loc, ur.provider, not exists ( + select 1 from public.tracking_runs tx + where tx.project_id = p_project_id and tx.tracking_location = ur.loc and tx.run_kind = 'category' + and tx.status = 'completed' and tx.published_at is not null and tx.superseded_at is null + and tx.provider <> 'Overall' and tx.provider <> ur.provider + and (tx.published_at at time zone 'Asia/Kuala_Lumpur')::date = ur.d)) is not null then + v_overall := v_overall + 1; + end if; + -- Days with several engines are also pooled across engines (idempotent per day). + if exists (select 1 from public.tracking_runs tx + where tx.project_id = p_project_id and tx.tracking_location = ur.loc and tx.run_kind = 'category' + and tx.status = 'completed' and tx.published_at is not null and tx.superseded_at is null + and tx.provider <> 'Overall' and tx.provider <> ur.provider + and (tx.published_at at time zone 'Asia/Kuala_Lumpur')::date = ur.d) + and not exists (select 1 from _cm_preserved p where p.d = ur.d and p.loc = ur.loc) + -- Cross-engine share of voice and position still need the live prompt link. + and not exists (select 1 from _cm_resp r join public.ai_responses ar on ar.id = r.response_id + where r.d = ur.d and r.loc = ur.loc and ar.prompt_id is null) then + perform public.publish_cross_engine_metrics(p_project_id, ur.d, ur.loc); + end if; + end loop; + + return jsonb_build_object( + 'status', 'completed', 'competitors', v_entities, 'slices_backfilled', v_slices, + 'units_finalized', v_units, 'overall_days', v_overall, + 'observations_written', v_obs, 'evidence_rows', v_evidence, 'citation_occurrences_added', v_citations, + 'observations_archived', v_archived, 'slices_unverified', v_skipped, 'units_blocked', v_blocked, + 'units_preserved', v_preserved, 'tracked_mentions_restored', v_restored); +end; +$function$; diff --git a/supabase/tests/mention_text_behaviour.sql b/supabase/tests/mention_text_behaviour.sql new file mode 100644 index 0000000..14f2147 --- /dev/null +++ b/supabase/tests/mention_text_behaviour.sql @@ -0,0 +1,33 @@ +-- public.mention_text must agree with visibility-tracking/mention-text.ts. +-- Generated from mention_text_cases.json. +do $mention$ +begin + if public.mention_text('We like Targus.') is distinct from 'We like Targus.' then + raise exception 'mention_text case failed: plain name kept'; + end if; + if public.mention_text('See https://www.targus.com/us?x=1 for more') is distinct from 'See for more' then + raise exception 'mention_text case failed: bare address'; + end if; + if public.mention_text('**[Ace Mach](https://www.google.com/maps/search/Ace+Mach)** is local') is distinct from '**[Ace Mach ** is local' then + raise exception 'mention_text case failed: link keeps label'; + end if; + if public.mention_text('Good value. ([belkin.com](https://www.belkin.com/p/a?utm_source=openai))') is distinct from 'Good value. ' then + raise exception 'mention_text case failed: bracketed domain citation'; + end if; + if public.mention_text('Book on [Booking.com](https://www.booking.com/).') is distinct from 'Book on [Booking.com .' then + raise exception 'mention_text case failed: domain label outside brackets stays'; + end if; + if public.mention_text('[Wiki](https://en.wikipedia.org/wiki/Moshi_(brand)) says') is distinct from '[Wiki says' then + raise exception 'mention_text case failed: brackets inside the address'; + end if; + if public.mention_text('Order at lovnscoffee.com today') is distinct from 'Order at lovnscoffee.com today' then + raise exception 'mention_text case failed: written domain stays'; + end if; + if public.mention_text('官网https://kfm-hk.com。金德科技') is distinct from '官网 。金德科技' then + raise exception 'mention_text case failed: Chinese punctuation ends an address'; + end if; + if public.mention_text('😀 金德 https://a.com/x 后') is distinct from '😀 金德 后' then + raise exception 'mention_text case failed: emoji before a link'; + end if; +end +$mention$; diff --git a/supabase/tests/mention_text_cases.json b/supabase/tests/mention_text_cases.json new file mode 100644 index 0000000..462b463 --- /dev/null +++ b/supabase/tests/mention_text_cases.json @@ -0,0 +1,47 @@ +[ + { + "name": "plain name kept", + "text": "We like Targus.", + "visible": "We like Targus." + }, + { + "name": "bare address", + "text": "See https://www.targus.com/us?x=1 for more", + "visible": "See for more" + }, + { + "name": "link keeps label", + "text": "**[Ace Mach](https://www.google.com/maps/search/Ace+Mach)** is local", + "visible": "**[Ace Mach ** is local" + }, + { + "name": "bracketed domain citation", + "text": "Good value. ([belkin.com](https://www.belkin.com/p/a?utm_source=openai))", + "visible": "Good value. " + }, + { + "name": "domain label outside brackets stays", + "text": "Book on [Booking.com](https://www.booking.com/).", + "visible": "Book on [Booking.com ." + }, + { + "name": "brackets inside the address", + "text": "[Wiki](https://en.wikipedia.org/wiki/Moshi_(brand)) says", + "visible": "[Wiki says" + }, + { + "name": "written domain stays", + "text": "Order at lovnscoffee.com today", + "visible": "Order at lovnscoffee.com today" + }, + { + "name": "Chinese punctuation ends an address", + "text": "官网https://kfm-hk.com。金德科技", + "visible": "官网 。金德科技" + }, + { + "name": "emoji before a link", + "text": "😀 金德 https://a.com/x 后", + "visible": "😀 金德 后" + } +] \ No newline at end of file