src/matrix.js
// Competitor matrix built only from sentences present in the user's sources. A cell is either a
// verbatim quote with citations, or "not found in sources". Values (amounts, numbers) are substrings
// of the quote, never computed or inferred.
import { ToolError } from "./errors.js";
import { clean, fold, sentences, termsRe, md, window, hostOf } from "./text.js";
const AMOUNT_BODY = /(?:(?:US|CA|AU|NZ)?[$\u20ac\u00a3\u00a5]|\b(?:USD|EUR|GBP|CAD|AUD|JPY|CHF|INR)\s?)\d[\d,]*(?:\.\d+)?(?:\s?[kKmMbB]n?\b)?(?:\s?(?:\/|per\s)\s?(?:month|mo|year|yr|annum|user|seat|member|license)\b(?:\s?(?:\/|per\s)\s?(?:month|mo|year|yr|user|seat))?)?|\b\d[\d,]*(?:\.\d+)?\s?(?:USD|EUR|GBP|dollars|euros|pounds)\b(?:\s?(?:\/|per\s)\s?(?:month|mo|year|yr|user|seat)\b)?/;
const NUMBER_BODY = /\b\d[\d,]*(?:\.\d+)?(?:\s?(?:%|percent\b|[kKmMbB]\b|thousand\b|million\b|billion\b))?(?:\s?\+)?(?:\s[\p{L}-]{2,30})?/;
// Qualifiers such as "over", "about" or "starts at" change what a figure means ("over 1,200
// clinics" is a lower bound), so they are kept as part of the extracted value. A qualifier's first
// letter may be upper case (sentence start).
const qualifier = (list) => {
const alts = list.map((w) => `[${w[0].toUpperCase()}${w[0]}]${w.slice(1).replace(/\./g, "\\.")}`);
return `(?:\\b(?:${alts.join("|")})\\s+|~\\s?)?`;
};
const COMMON_QUALIFIERS = ["approximately", "approx.", "about", "around", "roughly", "nearly", "almost", "over", "under", "more than", "less than", "fewer than", "at least", "at most", "up to"];
const AMOUNT_QUALIFIERS = [...COMMON_QUALIFIERS, "starting at", "starts at", "as low as", "as much as", "from"];
const AMOUNT_RE = new RegExp(`${qualifier(AMOUNT_QUALIFIERS)}(?:${AMOUNT_BODY.source})`, "g");
const LEADING_QUALIFIER = new RegExp(`^${qualifier(AMOUNT_QUALIFIERS)}`);
/** The figure without its qualifier, folded: "starts at $49 per month" and "$49 per month" agree. */
const bareValue = (v) => fold(v.replace(LEADING_QUALIFIER, ""));
const NUMBER_RE = new RegExp(`${qualifier(COMMON_QUALIFIERS)}(?:${NUMBER_BODY.source})`, "gu");
function nearest(matches, pos) {
let best = null;
for (const m of matches) {
const d = Math.abs(m.index - pos);
if (!best || d < best.d) best = { m, d };
}
return best?.m ?? null;
}
export function buildMatrix(input, nowIso) {
const warnings = [];
const maxCites = input.max_citations_per_cell ?? 3;
const maxQuote = input.max_quote_chars ?? 300;
// Sources (first copy of a URL wins).
const seen = new Set();
const srcs = [];
for (const s of input.sources) {
if (seen.has(s.url)) {
warnings.push(`Duplicate source URL ignored: ${s.url.slice(0, 200)}`);
continue;
}
seen.add(s.url);
const content = [s.title, s.excerpt, s.text].filter(Boolean).join("\n");
srcs.push({ ...s, host: hostOf(s.url), sents: sentences(content), folded: fold(content) });
}
if (!srcs.length) warnings.push("No sources were given, so every cell is 'not found in sources'.");
if (srcs.length && srcs.every((s) => !s.text && !s.excerpt)) warnings.push("Sources have no excerpt or text, only titles: add the text you are permitted to use to get real matches.");
const names = new Set();
const comps = input.competitors.map((c) => {
const k = c.name.trim().toLowerCase();
if (names.has(k)) throw new ToolError("invalid_input", `Duplicate competitor: ${c.name}`);
names.add(k);
if (!k) throw new ToolError("invalid_input", "Competitor names must not be blank.");
return { ...c, re: termsRe([c.name, ...(c.aliases ?? [])]), domains: (c.domains ?? []).map((d) => d.toLowerCase().replace(/^\.+/, "")), urls: new Set(c.source_urls ?? []) };
});
const keys = new Set();
const attrs = input.attributes.map((a) => {
if (keys.has(a.key)) throw new ToolError("invalid_input", `Duplicate attribute key: ${a.key}`);
keys.add(a.key);
if (!a.keywords.some((w) => w.trim())) throw new ToolError("invalid_input", `Attribute ${a.key} needs at least one non-blank keyword.`);
return { ...a, label: a.label ?? a.key, kind: a.kind ?? "text", re: termsRe(a.keywords) };
});
const about = (s, c) => c.urls.has(s.url) || c.domains.some((d) => s.host === d || s.host.endsWith(`.${d}`));
const mentionAt = (c, text) => {
c.re.lastIndex = 0;
const m = c.re.exec(text);
return m ? m.index : -1;
};
const citeIds = new Map();
const cite = (s) => {
if (!citeIds.has(s.url)) citeIds.set(s.url, citeIds.size + 1);
return citeIds.get(s.url);
};
const cells = [];
for (const c of comps) {
for (const a of attrs) {
const cands = [];
for (const [si, s] of srcs.entries()) {
const isAbout = about(s, c);
for (const [ki, sent] of s.sents.entries()) {
const mAt = mentionAt(c, sent);
const others = comps.filter((o) => o !== c && mentionAt(o, sent) >= 0).map((o) => o.name);
if (mAt < 0 && (!isAbout || others.length)) continue; // not about this competitor, or about another one
const hits = [...sent.matchAll(a.re)];
if (!hits.length) continue;
const distinct = new Set(hits.map((h) => h[0].toLowerCase())).size;
const valueRe = a.kind === "price" ? AMOUNT_RE : a.kind === "number" ? NUMBER_RE : null;
const values = valueRe ? [...sent.matchAll(valueRe)] : [];
const anchor = mAt >= 0 ? mAt : hits[0].index;
const value = valueRe ? nearest(values, anchor) : null;
cands.push({ s, si, ki, sent, score: distinct * 2 + (mAt >= 0 ? 1 : 0) + (isAbout ? 1 : 0), others, value, kwAt: hits[0].index });
}
}
const hasValueKind = a.kind !== "text";
cands.sort((x, y) => (hasValueKind ? Number(Boolean(y.value)) - Number(Boolean(x.value)) : 0) || y.score - x.score || x.si - y.si || x.ki - y.ki);
if (!cands.length) {
cells.push({ competitor: c.name, attribute: a.key, status: "not_found", value: null, quote: null, citations: [], origin: "none", notes: [] });
continue;
}
const best = cands[0];
const notes = [];
if (best.others.length) notes.push(`The quoted sentence also mentions ${best.others.join(", ")}; check which company it refers to.`);
if (hasValueKind && !best.value) notes.push(`No ${a.kind === "price" ? "amount" : "number"} appears in the matching sentences; the quote is shown instead.`);
const quote = window(best.sent, best.value ? best.value.index : best.kwAt, maxQuote);
// Cite only sources that state the same thing as the cell (the same amount or number, or the
// same sentence for a quote). Other sources that mention the attribute are listed as related.
const agrees = (x) => (best.value ? Boolean(x.value) && bareValue(x.value[0]) === bareValue(best.value[0]) : fold(x.sent) === fold(best.sent));
const supporting = [best.s];
for (const x of cands) if (!supporting.includes(x.s) && agrees(x)) supporting.push(x.s);
const related = [];
for (const x of cands) if (!supporting.includes(x.s) && !related.includes(x.s)) related.push(x.s);
const citations = supporting.slice(0, maxCites).map(cite);
const relatedCitations = related.slice(0, maxCites).map(cite);
if (relatedCitations.length) notes.push(`Other sources mention this but say something different: ${relatedCitations.map((n) => `[${n}]`).join("")}. Compare them before relying on this cell.`);
cells.push({
competitor: c.name,
attribute: a.key,
status: "found",
value: best.value ? best.value[0].trim() : quote,
value_type: best.value ? (a.kind === "price" ? "amount" : "number") : "quote",
quote,
citations,
...(relatedCitations.length ? { related_citations: relatedCitations } : {}),
origin: "extracted",
notes,
});
}
}
// User-supplied facts: accepted only when the quote appears in that source and the value in the quote.
const rejected = [];
for (const [index, f] of (input.facts ?? []).entries()) {
const c = comps.find((x) => x.name.toLowerCase() === f.competitor.trim().toLowerCase() || (x.aliases ?? []).some((al) => al.toLowerCase() === f.competitor.trim().toLowerCase()));
if (!c) {
rejected.push({ index, reason: `Unknown competitor "${f.competitor.slice(0, 100)}".` });
continue;
}
const a = attrs.find((x) => x.key === f.attribute);
if (!a) {
rejected.push({ index, reason: `Unknown attribute "${f.attribute.slice(0, 41)}".` });
continue;
}
const s = srcs.find((x) => x.url === f.source_url);
if (!s) {
rejected.push({ index, reason: "source_url is not one of the provided sources." });
continue;
}
if (!s.text && !s.excerpt && !s.title) {
rejected.push({ index, reason: "That source has no text to verify the quote against." });
continue;
}
if (!s.folded.includes(fold(f.quote))) {
rejected.push({ index, reason: "The quote does not appear in that source's title, excerpt or text." });
continue;
}
if (!fold(f.quote).includes(fold(f.value))) {
rejected.push({ index, reason: "The value does not appear inside the quote." });
continue;
}
const cell = cells.find((x) => x.competitor === c.name && x.attribute === a.key);
Object.assign(cell, { status: "found", value: clean(f.value).trim(), value_type: "verified_fact", quote: clean(f.quote).replace(/\s+/g, " ").trim(), citations: [cite(s)], origin: "verified_fact", notes: ["Supplied by you and verified: the quote appears in the cited source."] });
}
if (rejected.length) warnings.push(`${rejected.length} supplied fact(s) were rejected because they could not be verified against the sources.`);
const citations = [...citeIds.entries()].map(([url, id]) => {
const s = srcs.find((x) => x.url === url);
const c = { id, url };
if (s.title) c.title = clean(s.title).slice(0, 300);
if (s.source_name) c.source_name = clean(s.source_name).slice(0, 300);
if (s.published_at) c.published_at = String(s.published_at).slice(0, 40);
return c;
});
// Markdown.
const topic = input.topic ?? "Competitor comparison";
const cellOf = (c, a) => cells.find((x) => x.competitor === c.name && x.attribute === a.key);
const lines = [
`# ${md(topic)}`,
"",
"_Every filled cell quotes one of your sources (numbers in brackets are citations). \"Not found in sources\" means none of your sources covers it; nothing was looked up, inferred or estimated._",
"",
`| Competitor | ${attrs.map((a) => md(a.label)).join(" | ")} |`,
`| --- | ${attrs.map(() => "---").join(" | ")} |`,
...comps.map((c) => `| ${md(c.name)} | ${attrs.map((a) => { const x = cellOf(c, a); return x.status === "found" ? `${md(x.value.slice(0, 160))} ${x.citations.map((n) => `[${n}]`).join("")}` : "_not found in sources_"; }).join(" | ")} |`),
"",
"## Evidence",
"",
];
const found = cells.filter((x) => x.status === "found");
if (!found.length) lines.push("_No matching sentences in the sources._");
for (const x of found) {
const a = attrs.find((y) => y.key === x.attribute);
lines.push(`- **${md(x.competitor)} \u00b7 ${md(a.label)}** ${x.citations.map((n) => `[${n}]`).join("")}: "${md(x.quote)}"${x.notes.length ? ` _(${md(x.notes.join(" "))})_` : ""}`);
}
lines.push("", "## Sources", "");
if (!citations.length) lines.push("_None cited._");
for (const c of citations) lines.push(`${c.id}. ${c.title ? `${md(c.title)}. ` : ""}${c.source_name ? `${md(c.source_name)}. ` : ""}${c.published_at ? `${md(c.published_at)}. ` : ""}${md(c.url)}`);
const brief = {
topic,
generated_at: nowIso,
key_points: found.map((x) => {
const a = attrs.find((y) => y.key === x.attribute);
return { claim: `${x.competitor} (${a.label}): "${x.quote}"`, sources: x.citations.map((n) => citations.find((c) => c.id === n).url) };
}),
open_questions: cells.filter((x) => x.status === "not_found").map((x) => `No supplied source covers ${attrs.find((a) => a.key === x.attribute).label} for ${x.competitor}.`),
};
return {
matrix: { competitors: comps.map((c) => c.name), attributes: attrs.map((a) => ({ key: a.key, label: a.label, kind: a.kind })), cells },
citations,
markdown: lines.join("\n") + "\n",
brief,
rejected_facts: rejected,
warnings,
};
}