Public Beta
Not set

Experience

Changes how pages explain things, never what you can do.

More

Experience

Changes how pages explain things, never what you can do.

Sign inGet started

Fact Check v0.1.2 · claude-code

Archive SHA-256 ae804cec2897e15adcdc52ed8df50b7a76145df072b9e46d56eadd2d87df6436 · 30.0 KB · built Nov 27, 2026

src/index.js

// AgentRove native agent: fact-check (MIT).
// Checks claims against sources the user provides. A claim is "supported" only when at least one
// source sentence covers its content words AND states the same numbers/dates with the same
// polarity; the matching excerpt is always returned. Conflicting figures are flagged.
// Deterministic; no model, no network. Source text is untrusted data.

import { readFileSync } from "node:fs";
import { defineAgent, makeContext, handleMcpMessage, runCli, runMcpStdio } from "../sdk/index.js";
import { ToolError } from "./errors.js";
import { cleanText, splitSentences, words, contentTerms, hasNegation, direction, directionClash, extractQuantities, compareQuantities } from "./text.js";

export { makeContext, handleMcpMessage, runCli, runMcpStdio };

const manifest = JSON.parse(readFileSync(new URL("../agent.json", import.meta.url), "utf8"));

const MAX_SENTENCES_PER_SOURCE = 2000;
const MAX_TOTAL_SENTENCES = 20000;
const temporal = (kind) => kind === "year" || kind === "date";
const round3 = (x) => Math.round(x * 1000) / 1000;
const norm = (s) => String(s).replace(/\s+/g, " ").trim();

function sourceKey(url) {
  try {
    const u = new URL(url);
    u.hash = "";
    return u.toString().replace(/\/$/, "");
  } catch {
    return String(url);
  }
}

function prepareSources(list) {
  const out = [];
  const seen = new Set();
  let total = 0;
  for (const s of list) {
    const key = sourceKey(s.url);
    if (seen.has(key)) continue;
    seen.add(key);
    const texts = [];
    const title = cleanText(s.title ?? "");
    if (title) texts.push(title);
    texts.push(...splitSentences(cleanText(s.text ?? s.excerpt ?? "")).slice(0, MAX_SENTENCES_PER_SOURCE));
    const candidates = [];
    for (const [position, text] of texts.entries()) {
      if (total >= MAX_TOTAL_SENTENCES) break;
      if (words(text).length < 3) continue;
      candidates.push({ text, position, terms: contentTerms(text), qty: extractQuantities(text), neg: hasNegation(text), dir: direction(text) });
      total++;
    }
    out.push({ url: s.url, key, candidates });
  }
  return { sources: out, truncated: total >= MAX_TOTAL_SENTENCES };
}

/** Relation of one source sentence to a claim: supports | conflicts | partial | none. */
function assess(claim, cand, t) {
  let matched = 0;
  for (const term of claim.terms) if (cand.terms.has(term)) matched++;
  const coverage = claim.terms.size ? matched / claim.terms.size : 0;
  if (coverage < t.review) return { relation: "none", coverage };
  const q = compareQuantities(claim.qty, cand.qty);
  // A different year/date next to other figures usually means a different period, not a contradiction.
  const differentPeriod = claim.qty.some((x) => !temporal(x.kind)) && q.conflicts.some((c) => temporal(c.kind));
  const polarityClash = coverage >= t.support && claim.neg !== cand.neg;
  // Direction of change ("rose" / "fell"): opposite directions conflict; a claim that states a
  // direction is not supported by a sentence that states none.
  const dirClash = coverage >= t.support && directionClash(claim.dir, cand.dir);
  const dirMissing = (claim.dir === "up" || claim.dir === "down") && !cand.dir;
  const base = { coverage, matched, q, polarityClash, dirClash };
  if (differentPeriod) return { ...base, relation: "partial", note: "different period" };
  if (q.conflicts.length || polarityClash || dirClash) return { ...base, relation: "conflicts" };
  if (coverage >= t.support && matched >= Math.min(3, claim.terms.size) && q.missing.length === 0 && !dirMissing) return { ...base, relation: "supports" };
  return { ...base, relation: "partial", ...(dirMissing ? { note: "direction not stated" } : {}) };
}

function checkClaim(raw, sources, t) {
  const text = norm(raw.text);
  const claim = { text, terms: contentTerms(text), qty: extractQuantities(text), neg: hasNegation(text), dir: direction(text) };
  const cited = [raw.source_url, ...(raw.sources ?? [])].filter((u) => typeof u === "string" && u).map(sourceKey);
  const result = { text, verdict: "unsupported", evidence: [], excerpts: [], reasons: [], number_mismatches: [] };
  if (claim.terms.size === 0) {
    result.verdict = "needs_review";
    result.reasons.push("The claim has no checkable content words.");
    return result;
  }
  const order = { supports: 0, conflicts: 1, partial: 2 };
  const perSource = [];
  for (const src of sources) {
    let best = null;
    for (const cand of src.candidates) {
      const a = assess(claim, cand, t);
      if (a.relation === "none") continue;
      const better =
        !best ||
        order[a.relation] < order[best.a.relation] ||
        (a.relation === best.a.relation && (a.coverage > best.a.coverage || (a.coverage === best.a.coverage && cand.text.length < best.cand.text.length)));
      if (better) best = { a, cand };
    }
    // A source that also contains a conflicting sentence about the same thing is reported as such.
    let conflict = null;
    if (best && best.a.relation === "supports") {
      for (const cand of src.candidates) {
        const a = assess(claim, cand, t);
        if (a.relation === "conflicts" && a.coverage >= t.support && (!conflict || a.coverage > conflict.a.coverage)) conflict = { a, cand };
      }
    }
    if (best) perSource.push({ src, best, conflict });
  }
  const supports = perSource.filter((p) => p.best.a.relation === "supports");
  const conflicts = [
    ...perSource.filter((p) => p.best.a.relation === "conflicts").map((p) => ({ src: p.src, hit: p.best })),
    ...perSource.filter((p) => p.conflict).map((p) => ({ src: p.src, hit: p.conflict })),
  ];
  const partials = perSource.filter((p) => p.best.a.relation === "partial");

  const excerpt = (src, hit, relation) => ({ url: src.url, text: hit.cand.text, relation, coverage: round3(hit.a.coverage) });
  for (const p of supports) result.excerpts.push(excerpt(p.src, p.best, "supports"));
  for (const c of conflicts) {
    result.excerpts.push(excerpt(c.src, c.hit, "conflicts"));
    for (const m of c.hit.a.q.conflicts) result.number_mismatches.push({ claim_value: m.claim, source_values: m.source, url: c.src.url });
    if (c.hit.a.polarityClash) result.reasons.push(`Polarity differs: one of the claim and ${c.src.url} negates the statement.`);
    if (c.hit.a.dirClash) result.reasons.push(`Direction differs: the claim says it ${claim.dir === "up" ? "rose" : "fell"}, but ${c.src.url} says it ${claim.dir === "up" ? "fell" : "rose"}.`);
  }
  for (const p of partials) result.excerpts.push(excerpt(p.src, p.best, "partial"));

  const strongConflict = conflicts.some((c) => c.hit.a.coverage >= t.support);
  if (supports.length && !conflicts.length) {
    result.verdict = "supported";
    result.reasons.push(`${supports.length} source(s) contain a sentence covering the claim's content words with the same figures.`);
  } else if (supports.length && conflicts.length) {
    result.verdict = "needs_review";
    result.reasons.push("Some source sentences support the claim and others state different figures or the opposite.");
  } else if (conflicts.length && strongConflict && !partials.length) {
    result.verdict = "unsupported";
    result.reasons.push("The closest source sentences state different figures or the opposite of the claim.");
  } else if (conflicts.length || partials.length) {
    result.verdict = "needs_review";
    const mismatched = conflicts.filter((c) => c.hit.a.q.conflicts.length).map((c) => `${c.hit.a.q.conflicts.map((m) => `${m.claim} vs ${m.source.join("/")}`).join("; ")} (${c.src.url})`);
    if (mismatched.length) result.reasons.push(`Source sentences about the same thing state different figures: ${[...new Set(mismatched)].join("; ")}.`);
    const missing = [...new Set(partials.flatMap((p) => p.best.a.q.missing))];
    if (missing.length) result.reasons.push(`Related source sentences do not state: ${missing.join(", ")}.`);
    if (partials.some((p) => p.best.a.note === "different period")) result.reasons.push("Related source sentences refer to a different year or date.");
    if (partials.some((p) => p.best.a.note === "direction not stated")) result.reasons.push("Related source sentences do not say whether it rose or fell.");
    result.reasons.push("Only partial matches were found; a person should compare the excerpts with the claim.");
  } else {
    result.reasons.push("No provided source contains a sentence that matches this claim.");
  }

  if (cited.length) {
    const citedProvided = sources.filter((s) => cited.includes(s.key));
    if (!citedProvided.length) result.reasons.push("The source cited for this claim was not among the provided sources.");
    const citedSupports = supports.some((p) => cited.includes(p.src.key));
    result.cited_source_matched = citedSupports;
    if (result.verdict === "supported" && !citedSupports) {
      result.verdict = "needs_review";
      result.reasons.push("Support came from a different source than the one cited for this claim; fix the citation.");
    }
  }

  // Invariant: never "supported" without at least one supporting excerpt.
  if (result.verdict === "supported" && !result.excerpts.some((e) => e.relation === "supports")) {
    result.verdict = "needs_review";
    result.reasons.push("Internal check: no supporting excerpt was recorded.");
  }
  const evidenceFrom = result.verdict === "supported" ? result.excerpts.filter((e) => e.relation === "supports") : result.verdict === "needs_review" ? result.excerpts : [];
  result.evidence = [...new Set(evidenceFrom.map((e) => e.url))];
  return result;
}

async function check_claims(input, ctx) {
  const t = { support: input.support_threshold ?? 0.8, review: input.review_threshold ?? 0.5 };
  if (t.review > t.support) throw new ToolError("invalid_input", "review_threshold must not exceed support_threshold");
  const given = [
    ...(input.claims ?? []).map((c, i) => ({ ...(typeof c === "string" ? { text: c } : c), from: `claims[${i}]` })),
    ...(input.script?.claims ?? []).map((c, i) => ({ ...c, from: `script.claims[${i}]` })),
    ...(input.text !== undefined ? [{ text: input.text, from: "text" }] : []),
  ].filter((c) => norm(c.text ?? "").length > 0);
  if (!given.length) throw new ToolError("invalid_input", "Provide at least one non-empty claim in claims, script.claims or text");
  // One verdict per factual statement: text with several sentences is split into one claim per
  // sentence (each keeps the citation it came with); questions are not statements and are skipped.
  const raw = [];
  const skipped = [];
  for (const c of given) {
    const parts = splitSentences(norm(c.text));
    if (parts.length <= 1 && c.from !== "text") {
      raw.push(c);
      continue;
    }
    for (const part of parts) {
      if (/\?["'”’)\]]*$/.test(part) || words(part).length < 2) skipped.push(part.slice(0, 120));
      else raw.push(parts.length > 1 ? { ...c, text: part, split_from: c.from } : { ...c, text: part });
    }
  }
  if (!raw.length) throw new ToolError("invalid_input", "No factual statement to check: the text contains only questions or fragments.");
  if (raw.length > 500) throw new ToolError("invalid_input", "At most 500 claims (sentences) per call");
  const { sources, truncated } = prepareSources(input.sources);
  const claims = raw.map((c) => {
    const r = checkClaim(c, sources, t);
    return c.split_from ? { ...r, split_from: c.split_from } : r;
  });
  const count = (v) => claims.filter((c) => c.verdict === v).length;
  const notes = [
    "Verdicts compare claims only with the sources provided. 'unsupported' means these sources do not support the claim; it does not prove the claim false.",
    "Matching is lexical (shared content words with light stemming) plus number, percentage, currency, year, date and direction-of-change (rose/fell) consistency. Paraphrases with different words may be missed.",
  ];
  const splitCount = new Set(raw.filter((c) => c.split_from).map((c) => c.split_from)).size;
  if (splitCount) notes.push(`${splitCount} input(s) contained several sentences and were checked one sentence at a time (see split_from).`);
  if (skipped.length) notes.push(`Skipped ${skipped.length} question(s) or fragment(s) that are not factual statements: ${skipped.slice(0, 3).map((x) => `"${x}"`).join(", ")}${skipped.length > 3 ? ", ..." : ""}.`);
  if (!sources.length) notes.push("No sources were provided, so no claim can be supported.");
  if (truncated) notes.push(`Only the first ${MAX_TOTAL_SENTENCES} source sentences were checked.`);
  return {
    report: {
      claims,
      summary: { total: claims.length, supported: count("supported"), unsupported: count("unsupported"), needs_review: count("needs_review") },
      generated_at: ctx.now().toISOString(),
      method: { support_threshold: t.support, review_threshold: t.review },
      notes,
    },
  };
}

const agent = defineAgent(manifest, { check_claims });
export default agent;

Find an agent

Do not include passwords, keys, customer data or other confidential details.
Rule-based matching is free during the public beta (fair use).