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

Email Organizer v0.1.2 · claude-code

Archive SHA-256 7a4d147fa8307973542ae8b9b01c7716550b73cede62314210845cb969e444d6 · 40.2 KB · built Nov 27, 2026

tests/email-organizer.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 NOW = () => new Date("2026-11-25T12:00:00Z");

const ALT_EML = [
  "Return-Path: <alice@example.com>",
  "From: =?UTF-8?Q?Alice_M=C3=BCller?= <Alice@Example.com>",
  "To: Bob <bob@example.org>,",
  "\tCarol <carol@example.org>",
  "Cc: dave@example.org",
  "Subject: =?UTF-8?B?Q2Fmw6kgbWVldGluZw==?= =?UTF-8?Q?_=E2=9C=93?=",
  "Date: Mon, 23 Nov 2026 09:30:00 -0500",
  "Message-ID: <abc123@example.com>",
  "MIME-Version: 1.0",
  'Content-Type: multipart/alternative; boundary="b1"',
  "",
  "This is a multi-part message in MIME format.",
  "--b1",
  "Content-Type: text/plain; charset=utf-8",
  "Content-Transfer-Encoding: quoted-printable",
  "",
  "Hi Bob,=0A=0ACan you send the budget deck by Friday? It costs 5=E2=82=AC per=",
  " seat.",
  "",
  "> earlier quoted text?",
  "--b1",
  "Content-Type: text/html; charset=utf-8",
  "",
  "<p>HTML version should not be used</p>",
  "--b1--",
  "",
].join("\r\n");

const MBOX = [
  "From news@shop.example Mon Nov 23 08:00:00 2026",
  "From: Shop News <news@shop.example>",
  "To: bob@example.org",
  "Subject: Our weekly deals - what will you buy?",
  "Date: Mon, 23 Nov 2026 08:00:00 +0000",
  "Message-ID: <n1@shop.example>",
  "List-Unsubscribe: <https://shop.example/unsub>",
  "List-Id: Shop Deals <deals.shop.example>",
  "",
  "Would you like 20% off? Click now!",
  ">From the archive: older deals.",
  "",
  "From news@shop.example Tue Nov 24 08:00:00 2026",
  "From: Shop News <news@shop.example>",
  "To: bob@example.org",
  "Subject: More deals",
  "Date: Tue, 24 Nov 2026 08:00:00 +0000",
  "Message-ID: <n2@shop.example>",
  "List-Unsubscribe: <mailto:unsub@shop.example>",
  "List-Id: Shop Deals <deals.shop.example>",
  "",
  "Deals again.",
  "",
  "From noreply@github.com Tue Nov 24 10:00:00 2026",
  "From: GitHub <noreply@github.com>",
  "To: bob@example.org",
  "Subject: [GitHub] A new SSH key was added",
  "Date: Tue, 24 Nov 2026 10:00:00 +0000",
  "Message-ID: <g1@github.com>",
  "",
  "A key was added. Was this you?",
  "",
  "From noreply@github.com Tue Nov 24 11:00:00 2026",
  "From: GitHub <noreply@github.com>",
  "To: bob@example.org",
  "Subject: [GitHub] Sign-in from new device",
  "Date: Tue, 24 Nov 2026 11:00:00 +0000",
  "Message-ID: <g2@github.com>",
  "",
  "New sign-in.",
  "",
].join("\n");

const LATIN1_B64 = [
  "From: José <jose@example.es>",
  "To: bob@example.org",
  "Subject: =?ISO-8859-1?Q?Informe_a=F1o?=",
  "Date: Tue, 24 Nov 2026 16:00:00 +0100",
  "Content-Type: text/plain; charset=ISO-8859-1",
  "Content-Transfer-Encoding: base64",
  "",
  Buffer.from("Señor, the invoice is due 2026-11-26.", "latin1").toString("base64"),
  "",
].join("\n");

const ATTACH_EML = [
  "From: carol@example.org",
  "To: bob@example.org",
  "Subject: Report attached",
  "Date: 24 Nov 2026 10:00 +0000",
  'Content-Type: multipart/mixed; boundary="mix"',
  "",
  "--mix",
  "Content-Type: text/plain",
  "",
  "Report attached, FYI.",
  "--mix",
  "Content-Type: application/pdf",
  "Content-Disposition: attachment; filename*=UTF-8''r%C3%A9sum%C3%A9.pdf",
  "Content-Transfer-Encoding: base64",
  "",
  "JVBERi0xLjQK",
  "--mix--",
].join("\n");

const HTML_ONLY = [
  "From: promo@example.net",
  "To: bob@example.org",
  "Subject: Html only",
  "Content-Type: text/html; charset=utf-8",
  "",
  "<html><head><style>p{}</style><script>alert('x')</script></head><body><p>Hello &amp; welcome</p><p>Line&nbsp;two</p></body></html>",
].join("\n");

async function parse(raw: string | string[], extra: Record<string, unknown> = {}) {
  return agent.call("parse_messages", { raw, ...extra }, { now: NOW });
}

describe("email-organizer manifest", () => {
  it("passes validateManifest and declares no network or credentials", () => {
    expect(validateManifest(manifest)).toEqual([]);
    expect(manifest.id).toBe("agentrove.email-organizer");
    expect(manifest.permissions).toEqual({ filesystem: "none", network: [], credentials: [] });
    expect(manifest.tools.every((t: { side_effects: string }) => t.side_effects === "none")).toBe(true);
  });
});

describe("parse_messages", () => {
  it("parses multipart/alternative with QP, folded headers and encoded-word subject", async () => {
    const out = await parse(ALT_EML);
    expect(out.count).toBe(1);
    const m = out.messages[0];
    expect(m.id).toBe("abc123@example.com");
    expect(m.subject).toBe("Café meeting ✓");
    expect(m.from).toBe("Alice Müller <alice@example.com>");
    expect(m.from_address).toBe("alice@example.com");
    expect(m.to).toEqual(["Bob <bob@example.org>", "Carol <carol@example.org>"]);
    expect(m.cc).toEqual(["dave@example.org"]);
    expect(m.date).toBe("2026-11-23T14:30:00.000Z");
    expect(m.body_source).toBe("text/plain");
    expect(m.body_text).toContain("Can you send the budget deck by Friday? It costs 5€ per seat.");
    expect(m.body_text).not.toContain("HTML version");
  });

  it("splits mbox text and unescapes >From lines", async () => {
    const out = await parse(MBOX);
    expect(out.format).toBe("mbox");
    expect(out.count).toBe(4);
    expect(out.messages[0].body_text).toContain("From the archive");
    expect(out.messages[0].body_text).not.toContain(">From");
    expect(out.messages[0].list_unsubscribe).toBe("<https://shop.example/unsub>");
  });

  it("decodes base64 bodies and ISO-8859-1 encoded words", async () => {
    const out = await parse(LATIN1_B64);
    expect(out.messages[0].subject).toBe("Informe año");
    expect(out.messages[0].body_text).toBe("Señor, the invoice is due 2026-11-26.");
    expect(out.messages[0].date).toBe("2026-11-24T15:00:00.000Z");
  });

  it("records attachment metadata only (RFC 2231 filename) and keeps inline text", async () => {
    const out = await parse(ATTACH_EML);
    const m = out.messages[0];
    expect(m.body_text).toBe("Report attached, FYI.");
    expect(m.attachments).toEqual([{ filename: "résumé.pdf", content_type: "application/pdf", size_bytes: 9 }]);
    expect(m.id).toMatch(/^sha256:[0-9a-f]{16}$/);
  });

  it("falls back to stripped HTML without script/style content", async () => {
    const m = (await parse(HTML_ONLY)).messages[0];
    expect(m.body_source).toBe("text/html");
    expect(m.body_text).toBe("Hello & welcome\nLine two");
    expect(m.body_text).not.toContain("alert");
    expect(m.date).toBeNull();
  });

  it("accepts an array of .eml texts and de-duplicates ids", async () => {
    const out = await parse([ALT_EML, ALT_EML]);
    expect(out.messages.map((m: { id: string }) => m.id)).toEqual(["abc123@example.com", "abc123@example.com~2"]);
  });

  it("survives malformed MIME with warnings instead of crashing", async () => {
    const noBoundary = "From: a@b.example\nSubject: x\nContent-Type: multipart/mixed\n\nplain body";
    const unclosed = 'From: a@b.example\nSubject: y\nContent-Type: multipart/mixed; boundary="zz"\n\n--zz\nContent-Type: text/plain\n\nfirst part';
    const badB64 = "From: a@b.example\nSubject: z\nContent-Transfer-Encoding: base64\n\n@@@aGVsbG8=";
    const badHeader = "From: a@b.example\nthis is not a header\nSubject: ok\n\nbody";
    const out = await parse([noBoundary, unclosed, badB64, badHeader]);
    expect(out.messages[0].body_text).toBe("plain body");
    expect(out.messages[0].warnings.join(" ")).toMatch(/without a boundary/);
    expect(out.messages[1].body_text).toBe("first part");
    expect(out.messages[1].warnings.join(" ")).toMatch(/missing its closing boundary/);
    expect(out.messages[2].body_text).toBe("hello");
    expect(out.messages[2].warnings.join(" ")).toMatch(/Invalid characters in base64/);
    expect(out.messages[3].subject).toBe("ok");
    expect(out.messages[3].warnings.join(" ")).toMatch(/Malformed header line/);
  });

  it("handles empty input and message caps", async () => {
    const empty = await parse("   ");
    expect(empty.count).toBe(0);
    expect(empty.warnings[0]).toMatch(/empty/);
    const capped = await parse(MBOX, { max_messages: 2 });
    expect(capped.count).toBe(2);
    expect(capped.truncated).toBe(true);
  });

  it("rejects invalid input", async () => {
    await expect(agent.call("parse_messages", {})).rejects.toMatchObject({ code: "invalid_input" });
    await expect(agent.call("parse_messages", { raw: 42 })).rejects.toMatchObject({ code: "invalid_input" });
    await expect(agent.call("parse_messages", { raw: "x", format: "pst" })).rejects.toMatchObject({ code: "invalid_input" });
    await expect(agent.call("parse_messages", { raw: "x", unexpected: true })).rejects.toMatchObject({ code: "invalid_input" });
    await expect(agent.call("nope", {})).rejects.toMatchObject({ code: "unknown_tool" });
  });
});

describe("triage", () => {
  it("applies VIP, newsletter, notification and reply-needed rules with reasons", async () => {
    const parsed = await parse([ALT_EML, MBOX, LATIN1_B64, ATTACH_EML]);
    const out = await agent.call(
      "triage",
      { messages: parsed.messages, rules: { vip_senders: ["alice@example.com"], my_addresses: ["bob@example.org"], keyword_rules: [{ keywords: ["invoice"], category: "finance", priority: "high" }] } },
      { now: NOW },
    );
    const byId = Object.fromEntries(out.messages.map((m: { id: string }) => [m.id, m]));
    const alice = byId["abc123@example.com"];
    expect(alice.category).toBe("vip");
    expect(alice.priority).toBe("high");
    expect(alice.reply_needed).toBe(true);
    expect(alice.deadlines).toEqual([{ text: "by Friday", date: "2026-11-27" }]);
    expect(alice.reasons.join("\n")).toMatch(/matches VIP entry/);
    expect(alice.reasons.join("\n")).toMatch(/Direct question: "Can you send the budget deck by Friday\?"/);
    expect(alice.reasons.join("\n")).toMatch(/You are a direct \(To:\) recipient/);
    // The quoted line ("> earlier quoted text?") is not counted as a question.
    expect(alice.reasons.join("\n")).not.toMatch(/\+1 more/);

    const news = byId["n1@shop.example"];
    expect(news.category).toBe("newsletter");
    expect(news.priority).toBe("low");
    expect(news.reply_needed).toBe(false);
    expect(news.reasons[0]).toMatch(/List-Unsubscribe/);

    expect(byId["g1@github.com"].category).toBe("notification");
    expect(byId["g1@github.com"].reply_needed).toBe(false);

    const invoice = parsed.messages.find((m: { subject: string }) => m.subject === "Informe año");
    expect(byId[invoice.id].category).toBe("finance");
    expect(byId[invoice.id].priority).toBe("high");
    expect(byId[invoice.id].deadlines[0].date).toBe("2026-11-26");

    const fyi = parsed.messages.find((m: { subject: string }) => m.subject === "Report attached");
    expect(byId[fyi.id].category).toBe("fyi");
    expect(byId[fyi.id].reasons).toContain("No rule matched; filed as FYI");

    expect(out.summary.total).toBe(7);
    expect(out.summary.by_priority).toEqual({ high: 2, normal: 1, low: 4 });
    expect(out.summary.order[0]).toBe("abc123@example.com");
    expect(out.generated_at).toBe("2026-11-25T12:00:00.000Z");
  });

  it("resolves deadline phrases deterministically and leaves ambiguous dates unresolved", async () => {
    const msg = (body: string) => ({ id: "x", from: "pat@example.com", subject: "Plan", body_text: body, date: "2026-11-23T10:00:00.000Z" });
    const run = async (body: string) => (await agent.call("triage", { messages: [msg(body)], now: "2026-11-23T12:00:00Z" })).messages[0];
    expect((await run("Please send it by December 3rd.")).deadlines).toEqual([{ text: "by December 3rd", date: "2026-12-03" }]);
    expect((await run("Due 5 Jan.")).deadlines[0].date).toBe("2027-01-05");
    expect((await run("Need it by tomorrow.")).deadlines[0].date).toBe("2026-11-24");
    expect((await run("Need it by next Monday.")).deadlines[0].date).toBe("2026-11-30");
    expect((await run("Reply by 03/04 please.")).deadlines[0]).toEqual({ text: "by 03/04", date: null });
    expect((await run("Reply by 25/12.")).deadlines[0].date).toBe("2026-12-25");
    // A weekday abbreviated with a period belongs to the date that follows (not "this Wednesday").
    expect((await run("Can you reply by Wed., Dec 2?")).deadlines).toEqual([{ text: "by Wed., Dec 2", date: "2026-12-02" }]);
    // A clock time between the lead word and the date is allowed; the date is what counts.
    expect((await run("Send it before 5pm Friday.")).deadlines).toEqual([{ text: "before 5pm Friday", date: "2026-11-27" }]);
    expect((await run("I need it by noon tomorrow.")).deadlines[0].date).toBe("2026-11-24");
    expect((await run("Due by 5 p.m. next Monday.")).deadlines[0].date).toBe("2026-11-30");
    expect((await run("We open by 5 January.")).deadlines[0].date).toBe("2027-01-05");
    const overdue = await agent.call("triage", { messages: [msg("This was due 2026-11-01.")], now: "2026-11-23T12:00:00Z" });
    expect(overdue.messages[0].priority).toBe("high");
    expect(overdue.messages[0].reasons.join(" ")).toMatch(/has passed/);
  });

  it("does not treat cc-only deadline mail as urgent and honours keyword field scoping", async () => {
    const m = { id: "c", from: "x@example.com", to: "someone@example.com", cc: "Bob <bob@example.org>", subject: "Status", body_text: "Can everyone confirm by tomorrow?", date: "2026-11-25T08:00:00Z" };
    const out = await agent.call("triage", { messages: [m], rules: { my_addresses: ["bob@example.org"], keyword_rules: [{ keywords: ["status"], field: "body", category: "status" }] } }, { now: NOW });
    expect(out.messages[0].priority).toBe("normal");
    expect(out.messages[0].category).toBe("needs_reply");
    expect(out.messages[0].reasons).toContain("You are only in Cc:");
  });

  it("rejects invalid rules", async () => {
    const messages = [{ id: "a", from: "a@b.example", subject: "s", body_text: "b" }];
    await expect(agent.call("triage", { messages, rules: { keyword_rules: [{ keywords: [] }] } })).rejects.toMatchObject({ code: "invalid_input" });
    await expect(agent.call("triage", { messages, rules: { keyword_rules: [{ keywords: ["x"], category: "Has Spaces" }] } })).rejects.toMatchObject({ code: "invalid_input" });
    await expect(agent.call("triage", { messages: [{ id: "a" }] })).rejects.toMatchObject({ code: "invalid_input" });
    await expect(agent.call("triage", { messages, now: "not a date" })).rejects.toMatchObject({ code: "invalid_input" });
  });
});

describe("suggest_filters", () => {
  it("proposes list, notification and VIP filters as data without applying them", async () => {
    const parsed = await parse([MBOX, ALT_EML]);
    const triage = await agent.call("triage", { messages: parsed.messages, rules: { vip_senders: ["@example.com"] } }, { now: NOW });
    const out = await agent.call("suggest_filters", { messages: parsed.messages, triage });
    expect(out.applied).toBe(false);
    expect(out.note).toMatch(/Nothing was changed/);
    const kinds = out.filters.map((f: { kind: string }) => f.kind);
    expect(kinds).toEqual(["newsletter", "notification", "vip"]);
    expect(out.filters[0]).toMatchObject({ criteria: { list_id: "deals.shop.example" }, actions: { label: "Newsletters/deals.shop.example", skip_inbox: true }, matches: ["n1@shop.example", "n2@shop.example"] });
    expect(out.filters[1]).toMatchObject({ criteria: { from_domain: "github.com" }, matches: ["g1@github.com", "g2@github.com"] });
    expect(out.filters[2]).toMatchObject({ criteria: { from: "alice@example.com" }, actions: { star: true } });
  });

  it("groups subject tags when senders differ and respects min_group_size", async () => {
    const messages = [
      { id: "1", from: "a@x.example", subject: "[ops] disk full" },
      { id: "2", from: "b@y.example", subject: "Re: [ops] disk full" },
      { id: "3", from: "c@z.example", subject: "hello" },
    ];
    const out = await agent.call("suggest_filters", { messages });
    expect(out.filters).toHaveLength(1);
    expect(out.filters[0]).toMatchObject({ kind: "subject_tag", criteria: { subject_contains: "[ops]" }, matches: ["1", "2"] });
    const strict = await agent.call("suggest_filters", { messages, min_group_size: 3 });
    expect(strict.filters).toEqual([]);
  });
});

describe("MCP stdio protocol", () => {
  it("lists tools and calls them", async () => {
    const init = await handleMcpMessage(agent, { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18" } });
    expect(init.result.serverInfo.name).toBe("agentrove.email-organizer");
    const list = await handleMcpMessage(agent, { jsonrpc: "2.0", id: 2, method: "tools/list" });
    expect(list.result.tools.map((t: { name: string }) => t.name)).toEqual(["parse_messages", "triage", "suggest_filters"]);
    expect(list.result.tools[0].inputSchema.required).toEqual(["raw"]);
    const call = await handleMcpMessage(agent, { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "parse_messages", arguments: { raw: ALT_EML } } });
    expect(call.result.isError).toBe(false);
    expect(call.result.structuredContent.messages[0].subject).toBe("Café meeting ✓");
    const bad = await handleMcpMessage(agent, { jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "triage", arguments: {} } });
    expect(bad.result.isError).toBe(true);
    expect(bad.result.content[0].text).toMatch(/^invalid_input/);
  });
});

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