src/report.js
// Document Assistant: build_report (MIT). Builds a Markdown report from material other agents produced. Findings are
// the research brief's claims, copied word for word, each with numbered citations to the sources the brief attached to
// it; claims without a source are listed separately ("Statements that need a source"), never as findings. Nothing is
// invented, rephrased or looked up. Deterministic; no model, no network. All input text is untrusted data: it is shown,
// never followed.
import { AgentError } from "../sdk/index.js";
const MAX_SUMMARY_SENTENCES = 8;
const MAX_OPEN_QUESTIONS = 10;
const MAX_MARKDOWN = 100000;
/** One line of plain text: control characters removed, whitespace collapsed, capped. */
function line(s, max = 2000) {
return String(s ?? "").replace(/[\u0000-\u001f\u007f]/g, " ").replace(/\s+/g, " ").trim().slice(0, max);
}
/** Text that will sit inside a Markdown list item or heading: neutralise characters that would change the structure. */
function md(s, max = 2000) {
return line(s, max).replace(/^([#>*+-]|\d+[.)])\s/, "\\$1 ").replace(/\[(\d+)\]/g, "\\[$1\\]");
}
/** Comparable key for a URL: lower-case host, no fragment, no trailing slash. Never throws. */
function urlKey(u) {
const raw = line(u, 2048);
try {
const x = new URL(raw);
x.hash = "";
return `${x.protocol}//${x.host.toLowerCase()}${x.pathname.replace(/\/+$/, "")}${x.search}`;
} catch {
return raw.toLowerCase();
}
}
function hostOf(u) {
try {
return new URL(line(u, 2048)).host;
} catch {
return line(u, 120);
}
}
export function buildReport(input, now) {
const brief = input.brief && typeof input.brief === "object" ? input.brief : null;
const summary = input.summary && typeof input.summary === "object" ? input.summary : null;
const table = typeof input.markdown === "string" ? input.markdown.trim() : "";
if (!brief && !summary && !table) throw new AgentError("invalid_input", "Provide at least one of brief, markdown or summary.");
const maxFindings = Number.isInteger(input.max_findings) ? input.max_findings : 12;
const notes = [];
// 1. Citation list: the provided sources in their order, then any other URL a finding cites.
const sources = [];
const byKey = new Map();
const addSource = (url, title, provided) => {
const key = urlKey(url);
if (!key) return null;
if (byKey.has(key)) return byKey.get(key);
const entry = { n: sources.length + 1, url: line(url, 2048), title: line(title, 300) || hostOf(url), provided };
sources.push(entry);
byKey.set(key, entry);
return entry;
};
for (const s of Array.isArray(input.sources) ? input.sources : []) if (s && typeof s.url === "string") addSource(s.url, s.title || s.source_name, true);
// 2. Findings: the brief's claims word for word, deduplicated, each with its own sources.
const findings = [];
const unsourced = [];
const seen = new Set();
for (const kp of Array.isArray(brief?.key_points) ? brief.key_points : []) {
const text = line(kp?.claim);
if (!text) continue;
const key = text.toLowerCase();
if (seen.has(key)) continue;
seen.add(key);
const cites = [];
for (const u of Array.isArray(kp.sources) ? kp.sources : []) {
const e = addSource(u, "", false);
if (e && !cites.includes(e.n)) cites.push(e.n);
}
if (!cites.length) {
unsourced.push(text);
continue;
}
if (findings.length < maxFindings) findings.push({ n: findings.length + 1, text, citations: cites });
}
const extra = [...seen].length - findings.length - unsourced.length;
if (extra > 0) notes.push(`${extra} further sourced finding(s) were left out (max_findings is ${maxFindings}).`);
const uncited = sources.filter((s) => !s.provided);
if (uncited.length) notes.push(`${uncited.length} cited source(s) were not in the source list you provided; they are marked "(not in your source list)".`);
// 3. Title and sections.
const question = line(input.question, 500);
const topic = line(brief?.topic, 300);
const title = line(input.title, 200) || (question ? `Report: ${question}` : topic ? `Business intelligence report: ${topic}` : "Business intelligence report");
const generatedAt = now.toISOString();
const out = [`# ${md(title, 200)}`, "", `_Generated on ${generatedAt.slice(0, 10)} by Document Assistant from the material provided. No AI model and no web search were used; every finding below is quoted from the research brief with the sources it cited._`, ""];
const sections = [];
if (question) out.push(`**Question:** ${md(question, 500)}`, "");
if (findings.length) {
sections.push("Key findings");
out.push("## Key findings", "");
for (const f of findings) out.push(`${f.n}. ${md(f.text)} ${f.citations.map((c) => `[${c}]`).join("")}`);
out.push("");
}
const keySentences = (Array.isArray(summary?.key_sentences) ? summary.key_sentences : []).map((x) => line(x)).filter(Boolean).slice(0, MAX_SUMMARY_SENTENCES);
if (keySentences.length) {
sections.push("Summary");
out.push("## Summary", "", "_Key sentences extracted from the material by Document Assistant (not rewritten)._", "");
for (const k of keySentences) out.push(`- ${md(k)}`);
out.push("");
}
if (table) {
sections.push("Comparison");
// Headings inside the included section are demoted below this section's own heading (# → ###), so the report
// keeps one structure; the text itself is unchanged.
const cut = table.length > MAX_MARKDOWN ? `${table.slice(0, MAX_MARKDOWN)}\n\n…` : table;
const shown = cut.replace(/^(#{1,4})(?=\s)/gm, "##$1");
if (table.length > MAX_MARKDOWN) notes.push(`The comparison section was cut at ${MAX_MARKDOWN} characters.`);
out.push("## Comparison", "", "_Included as provided (for example by Startup Research); its own citation numbers refer to its own source list._", "", shown, "");
}
const openQuestions = (Array.isArray(brief?.open_questions) ? brief.open_questions : []).map((x) => line(x, 1000)).filter(Boolean).slice(0, MAX_OPEN_QUESTIONS);
if (openQuestions.length) {
sections.push("Open questions");
out.push("## Open questions", "");
for (const q of openQuestions) out.push(`- ${md(q, 1000)}`);
out.push("");
}
if (unsourced.length) {
sections.push("Statements that need a source");
out.push("## Statements that need a source", "", "_These came without any source, so they are not findings. Check them before you rely on them._", "");
for (const u of unsourced) out.push(`- ${md(u)}`);
out.push("");
}
const cited = sources.filter((s) => findings.some((f) => f.citations.includes(s.n)) || s.provided);
if (cited.length) {
sections.push("Sources");
out.push("## Sources", "");
for (const s of cited) out.push(`[${s.n}] ${md(s.title, 300)}: ${line(s.url, 2048)}${s.provided ? "" : " (not in your source list)"}`);
out.push("");
}
sections.push("How this report was made");
out.push(
"## How this report was made",
"",
"- Findings are the research brief's claims, copied word for word, each with the sources the brief attached to it.",
"- Claims without a source are listed separately and are not findings.",
"- The report checks nothing against the web. Open the sources to verify a finding before you rely on it.",
"",
);
if (!findings.length) notes.push("No sourced findings: the brief had no key points with sources.");
return {
report: out.join("\n"),
findings,
sources: sources.map(({ n, url, title, provided }) => ({ n, url, title, provided })),
unsourced,
sections,
generated_at: generatedAt,
notes,
};
}