Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/edge-function-check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
11 changes: 9 additions & 2 deletions .github/workflows/replacement-rerun-db-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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" \
Expand Down Expand Up @@ -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
53 changes: 31 additions & 22 deletions supabase/functions/visibility-tracking/index.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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 });
Expand Down Expand Up @@ -349,7 +351,7 @@ async function processPrompts(prompts: Array<Record<string, unknown>>, 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.
Expand Down Expand Up @@ -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] : "") ?? "");
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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<string, unknown>) => {
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({
Expand All @@ -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,
});
}
}
Expand Down Expand Up @@ -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)),
});
}
Expand Down
46 changes: 46 additions & 0 deletions supabase/functions/visibility-tracking/mention-accuracy.test.ts
Original file line number Diff line number Diff line change
@@ -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", [""]));
});
22 changes: 22 additions & 0 deletions supabase/functions/visibility-tracking/mention-text.ts
Original file line number Diff line number Diff line change
@@ -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));
}
73 changes: 73 additions & 0 deletions supabase/functions/visibility-tracking/source-association.ts
Original file line number Diff line number Diff line change
@@ -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<Brand>(
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<AssociationStatus, number> = { 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)));
}
Loading
Loading