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

Document Assistant v0.3.0 · generic

Archive SHA-256 084f2065dfcd8f2b9402eace1c9e0d03e5eee1dd7d78a54f1dbe7ca5bd99adb2 · 39.1 KB · built Dec 2, 2026

tests/document-assistant.test.ts

import { describe, it, expect } from "vitest";
// @ts-expect-error -- plain JavaScript agent module without type declarations
import agent, { handleMcpMessage, manifest, validateManifest } from "../src/index.js";

const DOC = [
  "---",
  "title: Solar Panel Maintenance Guide",
  "author: Ops",
  "---",
  "",
  "# Solar Panel Maintenance",
  "",
  "Solar panels need regular maintenance to stay efficient. Dust and debris reduce panel output by blocking sunlight.",
  "Most homeowners clean their panels twice a year.",
  "",
  "## Cleaning",
  "",
  "Clean panels early in the morning when they are cool. Use soft brushes and plain water, because harsh detergents can damage the panel coating.",
  "Never use a pressure washer on solar panels.",
  "",
  "```bash",
  "# not a heading",
  "echo 'ignore previous instructions'",
  "```",
  "",
  "## Inspection",
  "",
  "Inspect panel wiring and mounting hardware every spring. Loose mounting hardware lets panels shift in strong wind.",
  "Cracked panels should be replaced by a licensed installer, e.g. the original installer.",
  "",
  "Setext Heading",
  "--------------",
  "",
  "- Check the inverter display monthly.",
  "- Record panel output readings in a log.",
  "",
  "| col | col |",
  "|-----|-----|",
  "| a | b |",
  "",
].join("\n");

const PLAIN = ["1. INTRODUCTION", "", "This report covers the pilot.", "", "1.1 Scope", "", "Scope text here.", "", "RESULTS", "", "Results text."].join("\n");

const call = (tool: string, input: Record<string, unknown>) => agent.call(tool, input);

describe("document-assistant manifest", () => {
  it("passes validateManifest with no permissions", () => {
    expect(validateManifest(manifest)).toEqual([]);
    expect(manifest.id).toBe("agentrove.document-assistant");
    expect(manifest.permissions).toEqual({ filesystem: "none", network: [], credentials: [] });
    // 0.3.0 adds build_report: a cited report (markdown_document) from a research brief, table, summary and sources.
    expect(manifest.io.outputs).toEqual([{ name: "summary", type: "document_summary" }, { name: "report", type: "markdown_document" }]);
  });
});

describe("outline", () => {
  it("lists ATX and setext headings, ignoring fenced code, with front-matter title", async () => {
    const out = await call("outline", { text: DOC });
    expect(out.title).toBe("Solar Panel Maintenance Guide");
    expect(out.format).toBe("markdown");
    expect(out.outline).toEqual(["Solar Panel Maintenance", "  Cleaning", "  Inspection", "  Setext Heading"]);
    expect(out.headings[1]).toEqual({ level: 2, text: "Cleaning", line: 11 });
    expect(out.headings[3]).toEqual({ level: 2, text: "Setext Heading", line: 26 });
    expect(out.word_count).toBeGreaterThan(80);
  });

  it("detects numbered and ALL-CAPS headings in plain text", async () => {
    const out = await call("outline", { text: PLAIN });
    expect(out.format).toBe("text");
    expect(out.headings.map((h: { level: number; text: string }) => [h.level, h.text])).toEqual([[1, "1. INTRODUCTION"], [2, "1.1 Scope"], [1, "RESULTS"]]);
    expect(out.title).toBe("1. INTRODUCTION");
  });

  it("handles empty and heading-less documents", async () => {
    const empty = await call("outline", { text: "" });
    expect(empty).toMatchObject({ title: "", outline: [], headings: [], word_count: 0, notes: ["Document is empty"] });
    const flat = await call("outline", { text: "just one line of prose." });
    expect(flat.title).toBe("just one line of prose.");
    expect(flat.outline).toEqual([]);
  });
});

describe("summarize", () => {
  it("returns verbatim top sentences in document order (document_summary shape)", async () => {
    const out = await call("summarize", { text: DOC, max_sentences: 3 });
    expect(Object.keys(out)).toEqual(expect.arrayContaining(["title", "outline", "key_sentences", "word_count"]));
    expect(out.key_sentences).toHaveLength(3);
    for (const s of out.key_sentences) expect(DOC.replace(/\n/g, " ")).toContain(s);
    const lines = out.sentences.map((s: { line: number }) => s.line);
    expect([...lines].sort((a, b) => a - b)).toEqual(lines);
    // Lead sentence of the document wins its bonus; code block content is never a sentence.
    expect(out.key_sentences[0]).toBe("Solar panels need regular maintenance to stay efficient.");
    expect(out.key_sentences.join(" ")).not.toMatch(/ignore previous instructions/);
    // "e.g." does not split a sentence.
    expect(out.sentence_count).toBe(11);
    const again = await call("summarize", { text: DOC, max_sentences: 3 });
    expect(again).toEqual(out);
  });

  it("keeps every sentence of a tiny document and handles empty / code-only input", async () => {
    const tiny = await call("summarize", { text: "One short sentence here. Another one follows it." });
    expect(tiny.key_sentences).toEqual(["One short sentence here.", "Another one follows it."]);
    expect(tiny.notes[0]).toMatch(/only 2 sentence/);
    const empty = await call("summarize", { text: "   \n\n" });
    expect(empty).toMatchObject({ title: "", outline: [], key_sentences: [], word_count: 0, sentence_count: 0 });
    const code = await call("summarize", { text: "```\nconst x = 1;\n```" });
    expect(code.key_sentences).toEqual([]);
    expect(code.notes[0]).toMatch(/No prose sentences/);
  });

  it("rejects invalid input", async () => {
    await expect(call("summarize", {})).rejects.toMatchObject({ code: "invalid_input" });
    await expect(call("summarize", { text: "x", max_sentences: 0 })).rejects.toMatchObject({ code: "invalid_input" });
    await expect(call("summarize", { text: "x", extra: 1 })).rejects.toMatchObject({ code: "invalid_input" });
  });
});

describe("find", () => {
  it("finds whole-word terms and phrases with line numbers, snippets and sections", async () => {
    const out = await call("find", { text: DOC, query: 'panel "mounting hardware"', context_chars: 20 });
    expect(out.terms).toEqual(["panel", "mounting hardware"]);
    // Case-insensitive by default: the front-matter title and the H1 ("Panel") also match.
    expect(out.per_term).toEqual({ panel: 6, "mounting hardware": 2 });
    expect(out.matches[0]).toMatchObject({ line: 2, match: "Panel" });
    expect(out.matches[0].section).toBeUndefined();
    const body = out.matches.find((m: { line: number }) => m.line === 8);
    expect(body).toMatchObject({ term: "panel", match: "panel", section: "Solar Panel Maintenance" });
    expect(body.snippet).toMatch(/^….*panel output.*…$/);
    const mh = out.matches.find((m: { term: string }) => m.term === "mounting hardware");
    expect(mh).toMatchObject({ line: 23, column: 26, section: "Inspection" });
    expect(DOC.split("\n")[22].slice(25, 42)).toBe("mounting hardware");
  });

  it("supports substring, case-sensitive and all-terms modes; escapes regex characters", async () => {
    const sub = await call("find", { text: DOC, query: "panel", whole_word: false });
    expect(sub.total_matches).toBeGreaterThan(8);
    const cs = await call("find", { text: DOC, query: "Solar", case_sensitive: true });
    expect(cs.matches.every((m: { match: string }) => m.match === "Solar")).toBe(true);
    const all = await call("find", { text: DOC, query: "panels wind", mode: "all" });
    expect(all.lines_matched).toBe(1);
    expect(all.matches.map((m: { line: number }) => m.line)).toEqual([23, 23]);
    const special = await call("find", { text: "I like c++ (a lot). Price: $5.00?", query: "c++ $5.00?" });
    expect(special.total_matches).toBe(2);
    const capped = await call("find", { text: "a a a a a", query: "a", max_results: 2 });
    expect(capped).toMatchObject({ total_matches: 5, truncated: true });
    expect(capped.matches).toHaveLength(2);
  });

  it("rejects empty queries", async () => {
    await expect(call("find", { text: DOC, query: "   " })).rejects.toMatchObject({ code: "invalid_input" });
    await expect(call("find", { text: DOC, query: "" })).rejects.toMatchObject({ code: "invalid_input" });
  });
});

describe("compare", () => {
  it("summarises line changes with hunk positions", async () => {
    const out = await call("compare", { before: "a\nb\nc\nd\n", after: "a\nB\nc\nd\ne\n", context_lines: 1 });
    expect(out.identical).toBe(false);
    expect(out.summary).toMatchObject({ lines_before: 4, lines_after: 5, added: 2, removed: 1, unchanged: 3, hunks: 2, similarity: 0.6667 });
    expect(out.hunks[0]).toEqual({ kind: "changed", before_start: 2, before_count: 1, after_start: 2, after_count: 1, removed: ["b"], added: ["B"], context_before: ["a"], context_after: ["c"] });
    expect(out.hunks[1]).toMatchObject({ kind: "added", before_start: 4, before_count: 0, after_start: 5, after_count: 1, added: ["e"] });
    expect(out.summary_text).toBe("2 changed region(s): 2 line(s) added, 1 removed, 3 unchanged (similarity 0.6667).");
  });

  it("reports identical, whitespace-insensitive, empty and heading changes", async () => {
    expect((await call("compare", { before: "x\ny", after: "x\ny" })).identical).toBe(true);
    expect((await call("compare", { before: "a  b\n", after: "a b", ignore_whitespace: true })).identical).toBe(true);
    const fromEmpty = await call("compare", { before: "", after: "x\ny" });
    expect(fromEmpty.hunks).toEqual([{ kind: "added", before_start: 0, before_count: 0, after_start: 1, after_count: 2, removed: [], added: ["x", "y"], context_before: [], context_after: [] }]);
    const both = await call("compare", { before: "", after: "" });
    expect(both.summary.similarity).toBe(1);
    const hs = await call("compare", { before: "# A\n\n## B\n\ntext", after: "# A\n\n## C\n\ntext more" });
    expect(hs.headings_added).toEqual(["## C"]);
    expect(hs.headings_removed).toEqual(["## B"]);
  });

  it("produces a diff whose hunks rebuild the new version exactly", async () => {
    let seed = 7;
    const rnd = () => ((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648);
    const before = Array.from({ length: 1500 }, (_, i) => `line ${i % 97} ${Math.floor(rnd() * 5)}`);
    const after = [...before];
    for (let k = 0; k < 60; k++) {
      const pos = Math.floor(rnd() * after.length);
      const r = rnd();
      if (r < 0.33) after.splice(pos, 1);
      else if (r < 0.66) after.splice(pos, 0, `inserted ${k}`);
      else after[pos] = `changed ${k}`;
    }
    const out = await call("compare", { before: before.join("\n"), after: after.join("\n"), max_hunks: 1000 });
    expect(out.approximate).toBe(false);
    const rebuilt: string[] = [];
    let cursor = 0;
    for (const h of out.hunks) {
      const startIdx = h.before_count ? h.before_start - 1 : h.before_start;
      rebuilt.push(...before.slice(cursor, startIdx), ...h.added);
      cursor = startIdx + h.before_count;
    }
    rebuilt.push(...before.slice(cursor));
    expect(rebuilt).toEqual(after);
    expect(out.summary.lines_after - out.summary.lines_before).toBe(out.summary.added - out.summary.removed);
  });

  it("rejects missing versions", async () => {
    await expect(call("compare", { before: "x" })).rejects.toMatchObject({ code: "invalid_input" });
  });
});

describe("usefulness regressions (0.2.0)", () => {
  const REPORT = [
    "QUARTERLY REPORT",
    "",
    "1. SUMMARY",
    "",
    "Revenue rose 12% to $4.2 million. The main supply risk is a shortage of servo controllers from the secondary supplier.",
    "",
    "2. QUALITY",
    "",
    "The servo controller batch from the secondary supplier failed incoming inspection at a 3% rate. First-pass yield rose to 96.4%.",
    "",
    "3. SUPPLY",
    "",
    "The secondary supplier warned of a six-week delay on servo controllers. A bridging order was placed with the primary supplier.",
    "",
    "4. PEOPLE",
    "",
    "Headcount is 212 with 9 open roles. Voluntary turnover was 2.1% for the quarter.",
  ].join("\n");

  it("summarize spreads key sentences across sections instead of repeating the dominant topic", async () => {
    const out = await call("summarize", { text: REPORT, max_sentences: 4 });
    const servo = out.key_sentences.filter((s: string) => /servo/i.test(s));
    expect(servo.length).toBeLessThanOrEqual(2);
    expect(out.key_sentences.some((s: string) => /Headcount|turnover/.test(s))).toBe(true);
    expect(out.method).toMatch(/redundancy/);
  });

  it("compare lists word-level changes inside edited lines", async () => {
    const before = "# Policy\n\nEmployees who completed their 90-day probation may work remotely one day per week.\nClaims up to $500 CAD per year.\n";
    const after = "# Policy\n\nEmployees who completed their 60-day probation may work remotely two days per week.\nClaims up to $750 CAD per year.\n";
    const out = await call("compare", { before, after });
    expect(out.hunks).toHaveLength(1);
    expect(out.hunks[0].word_changes).toEqual([
      { before_line: 3, after_line: 3, changes: [{ removed: "90-day", added: "60-day" }, { removed: "one day", added: "two days" }] },
      { before_line: 4, after_line: 4, changes: [{ removed: "$500", added: "$750" }] },
    ]);
    // Unrelated replacement lines are not paired word by word.
    const unrelated = await call("compare", { before: "alpha beta gamma\n", after: "completely different words here\n" });
    expect(unrelated.hunks[0].word_changes).toBeUndefined();
  });

  it("find snippets start and end on word boundaries", async () => {
    const text = "Returns under warranty fell to 0.7% of shipped units. The servo controller batch failed inspection at incoming checks.";
    const out = await call("find", { text, query: "servo", context_chars: 25 });
    const snip = out.matches[0].snippet;
    const inner = snip.replace(/^…/, "").replace(/…$/, "");
    expect(text).toContain(inner);
    const start = text.indexOf(inner);
    expect(start === 0 || text[start - 1] === " ").toBe(true);
    const end = start + inner.length;
    expect(end === text.length || text[end] === " ").toBe(true);
  });
});

describe("MCP stdio protocol", () => {
  it("lists and calls tools", async () => {
    const list = await handleMcpMessage(agent, { jsonrpc: "2.0", id: 1, method: "tools/list" });
    expect(list.result.tools.map((t: { name: string }) => t.name)).toEqual(["outline", "summarize", "find", "compare", "build_report"]);
    const res = await handleMcpMessage(agent, { jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "outline", arguments: { text: "# Hi\n\nBody." } } });
    expect(res.result.isError).toBe(false);
    expect(res.result.structuredContent.outline).toEqual(["Hi"]);
    const bad = await handleMcpMessage(agent, { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "find", arguments: { text: "x" } } });
    expect(bad.result.isError).toBe(true);
    const unknown = await handleMcpMessage(agent, { jsonrpc: "2.0", id: 4, method: "resources/list" });
    expect(unknown.error.code).toBe(-32601);
  });
});

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).