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

Content Research v0.1.2 · claude-code

Archive SHA-256 85b0ee7982b2c880d0d1535b3f0f89bb61c688194230c8c488ff79b9951acc65 · 28.6 KB · built Nov 27, 2026

src/index.js

// AgentRove native agent: content-research (MIT).
// Turns a source_list into a research_brief by extractive summarisation: every key point is a
// sentence copied verbatim from a source, linked to every source that corroborates it. Sources that
// disagree on figures or polarity, and points with thin support, become open questions.
// Deterministic: no model, no randomness, 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, jaccard, extractQuantities, compareQuantities } from "./text.js";

export { makeContext, handleMcpMessage, runCli, runMcpStdio };

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

const BOILERPLATE = /\b(click here|subscribe|sign up|newsletter|cookie|cookies|all rights reserved|read more|share this|follow us|advertisement|terms of service|privacy policy)\b/i;
const MAX_SENTENCES_PER_SOURCE = 300;
const MAX_PAIRWISE = 1500;

const clip = (s, n = 140) => (s.length > n ? `${s.slice(0, n - 1).trimEnd()}…` : s);
const round3 = (x) => Math.round(x * 1000) / 1000;

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

async function build_brief(input, ctx) {
  const maxPoints = input.max_points ?? 8;
  const minWords = input.min_sentence_words ?? 6;
  const maxWords = input.max_sentence_words ?? 60;
  const simThreshold = input.similarity_threshold ?? 0.5;
  if (maxWords < minWords) throw new ToolError("invalid_input", "max_sentence_words must be >= min_sentence_words");

  // 1. Sources (deduplicated by URL) and candidate sentences.
  const sources = [];
  const seen = new Map();
  let duplicateSources = 0;
  for (const s of input.sources) {
    const key = sourceKey(s.url);
    if (seen.has(key)) {
      duplicateSources++;
      continue;
    }
    seen.set(key, sources.length);
    sources.push({ url: s.url, title: cleanText(s.title ?? ""), published_at: s.published_at, body: cleanText(s.text ?? s.excerpt ?? ""), sentences: [] });
  }
  const sentences = [];
  for (const [si, src] of sources.entries()) {
    const parts = splitSentences(src.body).slice(0, MAX_SENTENCES_PER_SOURCE);
    parts.forEach((text, position) => {
      const n = words(text).length;
      if (n < minWords || n > maxWords) return;
      if (/\?["'”’)]*$/.test(text) || BOILERPLATE.test(text) || !/\p{L}/u.test(text)) return;
      const terms = contentTerms(text);
      if (terms.size < 2) return;
      const sent = { text, si, position, terms, quantities: extractQuantities(text), negated: hasNegation(text), dir: direction(text) };
      src.sentences.push(sent);
      sentences.push(sent);
    });
  }
  const usable = sources.filter((s) => s.sentences.length > 0);
  const n = usable.length;

  // 2. Scoring: topical overlap + cross-source centrality + lead position + a small bonus for figures.
  const topicTerms = contentTerms([input.topic, ...(input.focus_terms ?? [])].join(" . "));
  const df = new Map();
  for (const src of usable) {
    const termsInSource = new Set();
    for (const s of src.sentences) for (const t of s.terms) termsInSource.add(t);
    for (const t of termsInSource) df.set(t, (df.get(t) ?? 0) + 1);
  }
  for (const s of sentences) {
    let central = 0;
    let topical = 0;
    for (const t of s.terms) {
      central += ((df.get(t) ?? 1) - 1) / Math.max(1, n - 1);
      if (topicTerms.has(t)) topical++;
    }
    s.score =
      (topicTerms.size ? topical / topicTerms.size : 0) +
      (0.6 * central) / Math.sqrt(s.terms.size) +
      0.2 / (1 + s.position) +
      (s.quantities.length ? 0.05 : 0);
  }
  const ranked = [...sentences].sort((a, b) => b.score - a.score || a.si - b.si || a.position - b.position);

  // 3. Greedy selection with de-duplication. Similar sentences from other sources corroborate a
  //    point only if they state the same figures, polarity and direction of change ("rose" versus
  //    "fell"); a clash is a disagreement. A sentence that leaves out a figure or the direction is
  //    absorbed without counting as corroboration.
  const points = [];
  const disagreements = [];
  for (const s of ranked) {
    let absorbed = false;
    for (const p of points) {
      if (jaccard(s.terms, p.lead.terms) < simThreshold) continue;
      absorbed = true;
      if (p.sourceIdx.has(s.si)) break;
      const q = compareQuantities(p.lead.quantities, s.quantities);
      const qBack = compareQuantities(s.quantities, p.lead.quantities);
      if (q.conflicts.length || qBack.conflicts.length || p.lead.negated !== s.negated || directionClash(p.lead.dir, s.dir)) {
        disagreements.push([p.lead, s]);
      } else if (q.missing.length === 0 && (p.lead.dir === s.dir || p.lead.dir === "mixed" || s.dir === "mixed")) {
        p.sourceIdx.add(s.si);
        s.canon = p.lead;
      }
      break;
    }
    if (!absorbed && points.length < maxPoints) {
      const p = { lead: s, sourceIdx: new Set([s.si]) };
      s.canon = s;
      s.point = p;
      points.push(p);
    }
  }

  // 4. Other cross-source disagreements among related (not near-duplicate) sentences.
  const pool = ranked.slice(0, MAX_PAIRWISE);
  for (let i = 0; i < pool.length; i++) {
    for (let j = i + 1; j < pool.length; j++) {
      const a = pool[i];
      const b = pool[j];
      if (a.si === b.si) continue;
      const sim = jaccard(a.terms, b.terms);
      if (sim < 0.35) continue;
      const q = compareQuantities(a.quantities, b.quantities);
      const qBack = compareQuantities(b.quantities, a.quantities);
      if (q.conflicts.length || qBack.conflicts.length || (sim >= simThreshold && (a.negated !== b.negated || directionClash(a.dir, b.dir)))) disagreements.push([a, b]);
    }
  }

  // 5. Open questions.
  const questions = [];
  // A sentence that corroborates a key point is represented by that point (its lead and all its URLs).
  const seenPairs = new Set();
  const idOf = (x) => `${x.si}:${x.position}`;
  const urlsOf = (x) => (x.point ? [...x.point.sourceIdx].sort((m, k) => m - k).map((i) => sources[i].url) : [sources[x.si].url]).join(", ");
  for (const [rawA, rawB] of disagreements) {
    const a = rawA.canon ?? rawA;
    const b = rawB.canon ?? rawB;
    if (a === b) continue;
    const key = [idOf(a), idOf(b)].sort().join("|");
    if (seenPairs.has(key)) continue;
    seenPairs.add(key);
    const q = compareQuantities(a.quantities, b.quantities);
    const qBack = compareQuantities(b.quantities, a.quantities);
    const figures = q.conflicts.length
      ? q.conflicts.map((c) => `${c.claim} vs ${c.source.join("/")}`)
      : qBack.conflicts.map((c) => `${c.source.join("/")} vs ${c.claim}`);
    const what = figures.length
      ? `figures differ (${figures.join("; ")})`
      : directionClash(a.dir, b.dir)
        ? `one says it ${a.dir === "up" ? "rose" : "fell"}, the other that it ${b.dir === "up" ? "rose" : "fell"}`
        : "one states the opposite of the other";
    questions.push(`Sources disagree, ${what}: "${clip(a.text)}" (${urlsOf(a)}) versus "${clip(b.text)}" (${urlsOf(b)}). Which is correct?`);
    if (seenPairs.size >= 6) break;
  }
  const thin = points.filter((p) => p.sourceIdx.size === 1);
  for (const p of thin.slice(0, 5)) questions.push(`Only one source supports: "${clip(p.lead.text)}" (${sources[p.lead.si].url}). Is there independent confirmation?`);
  if (thin.length > 5) questions.push(`${thin.length - 5} more key point(s) rest on a single source.`);
  if (n < 2) questions.push(`Only ${n} source(s) had usable text, so agreement between sources cannot be checked. Add more independent sources.`);
  const missingTopic = [...contentTerms(input.topic)].filter((t) => !df.has(t));
  if (missingTopic.length && n > 0) questions.push(`No source sentence mentions: ${missingTopic.map((t) => `"${t}"`).join(", ")}. Is the topic covered by these sources?`);
  const undated = usable.filter((s) => !s.published_at || Number.isNaN(Date.parse(s.published_at))).length;
  if (undated) questions.push(`${undated} of ${n} usable source(s) have no publication date. Check that the information is current.`);

  const notes = [
    "Key points are sentences copied verbatim from the sources (extractive, not paraphrased). Nothing was added that is not in a source.",
    "A source corroborates a point when it has a near-duplicate sentence with the same figures, polarity and direction of change.",
  ];
  const empty = sources.filter((s) => !s.sentences.length);
  if (empty.length) notes.push(`${empty.length} source(s) had no usable sentences (missing text/excerpt, too short, or only questions/boilerplate): ${empty.slice(0, 5).map((s) => s.url).join(", ")}${empty.length > 5 ? ", …" : ""}.`);
  if (duplicateSources) notes.push(`${duplicateSources} duplicate source URL(s) were ignored.`);

  return {
    brief: {
      topic: input.topic,
      generated_at: ctx.now().toISOString(),
      key_points: points.map((p) => ({
        claim: p.lead.text,
        sources: [...p.sourceIdx].sort((a, b) => a - b).map((i) => sources[i].url),
        support_count: p.sourceIdx.size,
        score: round3(p.lead.score),
      })),
      open_questions: questions,
    },
    sources_used: sources.map((s) => ({ url: s.url, title: s.title, sentences_considered: s.sentences.length })),
    notes,
  };
}

const agent = defineAgent(manifest, { build_brief });
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).