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

src/triage.js

// Rule-based triage and filter suggestions for email-organizer. Deterministic given the same input and `now`.
// Message text is untrusted: it is only pattern-matched, never interpreted as instructions.

import { parseAddress, splitAddressList, truncate } from "./mime.js";

const DAY = 86400000;
const WEEKDAYS = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
const MONTHS = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
const MONTH_RE = "(jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)\\.?";
const WEEKDAY_RE = "(mon(?:day)?|tue(?:s(?:day)?)?|wed(?:nesday)?|thu(?:r(?:s(?:day)?)?)?|fri(?:day)?|sat(?:urday)?|sun(?:day)?)";
const AUTOMATED_LOCAL = /^(no-?reply|do-?not-?reply|donotreply|notifications?|notify|alerts?|mailer-daemon|postmaster|bounces?|automated|system)([+._-].*)?$/i;
const REQUEST_PHRASES = [
  "please reply", "please respond", "please confirm", "please let me know", "please advise", "please review", "please send",
  "please approve", "let me know", "can you", "could you", "would you", "are you able", "rsvp", "get back to me",
  "awaiting your", "waiting for your", "need your", "your thoughts", "your feedback", "action required",
];

export function utcDateOnly(ms) {
  return new Date(ms).toISOString().slice(0, 10);
}

function startOfUtcDay(ms) {
  const d = new Date(ms);
  return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
}

function monthIndex(name) {
  const n = name.toLowerCase().replace(/\.$/, "").slice(0, 3);
  return MONTHS.findIndex((m) => m.startsWith(n));
}

function weekdayIndex(name) {
  const n = name.toLowerCase().slice(0, 3);
  return WEEKDAYS.findIndex((d) => d.startsWith(n));
}

function validYmd(y, m, d) {
  const ms = Date.UTC(y, m, d);
  const dt = new Date(ms);
  return dt.getUTCFullYear() === y && dt.getUTCMonth() === m && dt.getUTCDate() === d ? ms : null;
}

// Resolves a month/day with no year to the occurrence nearest the reference (within ~10 months ahead).
function inferYear(m, d, refMs) {
  const ref = new Date(refMs);
  const y = ref.getUTCFullYear();
  const same = validYmd(y, m, d);
  if (same !== null && same >= refMs - 60 * DAY) return same;
  return validYmd(y + 1, m, d);
}

const DEADLINE_LEAD = "(?:\\bby|\\bbefore|\\bdue(?:\\s+(?:on|by))?|\\bdeadline(?:\\s+is)?:?|\\bno later than|\\buntil)";
// An optional clock time between the lead word and the date ("by 5pm Friday", "before noon on Dec 3").
// The time itself is not used: deadlines are calendar dates.
const TIME_PREFIX = "(?:(?:\\d{1,2}(?::\\d{2})?\\s*(?:am|pm|a\\.m\\.|p\\.m\\.)|\\d{1,2}:\\d{2}|noon|midday|midnight)\\s+(?:on\\s+)?)?";
// A weekday before a date may be abbreviated with a period ("Wed., Dec 2").
const DATE_EXPR = [
  "(\\d{4}-\\d{2}-\\d{2})",
  `(?:${WEEKDAY_RE}\\.?,?\\s+)?${MONTH_RE}\\s+(\\d{1,2})(?:st|nd|rd|th)?(?:,?\\s+(\\d{4}))?`,
  `(?:${WEEKDAY_RE}\\.?,?\\s+)?(\\d{1,2})(?:st|nd|rd|th)?\\s+(?:of\\s+)?${MONTH_RE}(?:,?\\s+(\\d{4}))?`,
  "(\\d{1,2}/\\d{1,2}(?:/\\d{2,4})?)",
  `(?:(?:this|next)\\s+)?${WEEKDAY_RE}`,
  "(today|tonight|tomorrow|end of (?:the )?day|end of (?:the )?week|eod|eow|cob)",
].join("|");
const DEADLINE_RE = new RegExp(`${DEADLINE_LEAD}\\s+${TIME_PREFIX}(?:the\\s+)?(?:${DATE_EXPR})\\b`, "gi");
const BARE_ISO_RE = /\b(\d{4}-\d{2}-\d{2})\b/g;

// Extracts deadline phrases. Dates are resolved relative to `refMs` (the message date when known).
// Ambiguous numeric dates such as 03/04 are reported with date: null rather than guessed.
export function extractDeadlines(text, refMs) {
  const found = [];
  const seen = new Set();
  const ref = startOfUtcDay(refMs);
  for (const m of text.matchAll(DEADLINE_RE)) {
    const phrase = m[0].replace(/\s+/g, " ").trim();
    const g = m.slice(1);
    let ms = null;
    if (g[0]) ms = validYmd(Number(g[0].slice(0, 4)), Number(g[0].slice(5, 7)) - 1, Number(g[0].slice(8, 10)));
    else if (g[2]) {
      const mi = monthIndex(g[2]);
      ms = g[4] ? validYmd(Number(g[4]), mi, Number(g[3])) : inferYear(mi, Number(g[3]), ref);
    } else if (g[6]) {
      const mi = monthIndex(g[7]);
      ms = g[8] ? validYmd(Number(g[8]), mi, Number(g[6])) : inferYear(mi, Number(g[6]), ref);
    } else if (g[9]) {
      const [a, b, y] = g[9].split("/").map(Number);
      // Only unambiguous when one side cannot be a month.
      const year = y === undefined ? null : y < 100 ? 2000 + y : y;
      if (a > 12 && b <= 12) ms = year ? validYmd(year, b - 1, a) : inferYear(b - 1, a, ref);
      else if (b > 12 && a <= 12) ms = year ? validYmd(year, a - 1, b) : inferYear(a - 1, b, ref);
    } else if (g[10]) {
      const wd = weekdayIndex(g[10]);
      let delta = (wd - new Date(ref).getUTCDay() + 7) % 7;
      if (/\bnext\s+\w+$/i.test(m[0]) && delta === 0) delta = 7;
      ms = ref + delta * DAY;
    } else if (g[11]) {
      const w = g[11].toLowerCase();
      if (w === "tomorrow") ms = ref + DAY;
      else if (w.includes("week") || w === "eow") ms = ref + ((5 - new Date(ref).getUTCDay() + 7) % 7) * DAY;
      else ms = ref;
    }
    const date = ms === null ? null : utcDateOnly(ms);
    const key = `${phrase.toLowerCase()}|${date}`;
    if (seen.has(key)) continue;
    seen.add(key);
    found.push({ text: phrase, date });
  }
  // A bare ISO date next to "deadline"/"due" words anywhere in the same line is also a deadline.
  for (const line of text.split("\n")) {
    if (!/\b(deadline|due)\b/i.test(line)) continue;
    for (const m of line.matchAll(BARE_ISO_RE)) {
      const ms = validYmd(Number(m[1].slice(0, 4)), Number(m[1].slice(5, 7)) - 1, Number(m[1].slice(8, 10)));
      if (ms === null || found.some((f) => f.date === utcDateOnly(ms))) continue;
      found.push({ text: truncate(line.trim(), 80), date: utcDateOnly(ms) });
    }
  }
  return found;
}

// Removes quoted replies, forwarded history and signatures so heuristics only see the new text.
export function newContent(body) {
  const lines = (body ?? "").split("\n");
  const out = [];
  for (const line of lines) {
    if (/^On .{4,200}wrote:\s*$/.test(line) || /^-{2,}\s*(Original Message|Forwarded message)\s*-{2,}/i.test(line) || /^-- ?$/.test(line)) break;
    if (/^From: .+/.test(line) && out.length && /^\s*$/.test(out[out.length - 1] ?? "")) break;
    if (/^\s*>/.test(line)) continue;
    out.push(line);
  }
  return out.join("\n");
}

// Paragraphs (blank-line separated) are split first so greetings like "Hi Bob," stay separate.
function sentences(text) {
  return text
    .split(/\n[ \t]*\n/)
    .flatMap((p) => p.replace(/\s+/g, " ").split(/(?<=[.!?])\s+(?=["'(\[]?[A-Z0-9])/))
    .map((s) => s.trim())
    .filter(Boolean);
}

function senderMatches(address, entry) {
  if (!address) return false;
  const e = entry.trim().toLowerCase();
  if (!e) return false;
  if (e.startsWith("@")) return address.endsWith(e);
  if (!e.includes("@")) return address.endsWith(`@${e}`) || address.endsWith(`.${e}`);
  return address === e;
}

function escapeRe(s) {
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

function keywordHit(text, kw) {
  const k = kw.trim();
  if (!k) return false;
  const re = new RegExp(`(^|[^\\p{L}\\p{N}])${escapeRe(k)}($|[^\\p{L}\\p{N}])`, "iu");
  return re.test(text);
}

function addressesOf(list) {
  const arr = Array.isArray(list) ? list : typeof list === "string" ? splitAddressList(list) : [];
  return arr.map((a) => parseAddress(a).address).filter(Boolean);
}

export function isAutomated(msg) {
  const addr = msg.from_address ?? parseAddress(msg.from ?? "").address ?? "";
  const local = addr.split("@")[0] ?? "";
  if (AUTOMATED_LOCAL.test(local)) return `Sender address looks automated (${addr})`;
  if (msg.auto_submitted && !/^no$/i.test(msg.auto_submitted.trim())) return `Auto-Submitted header: ${truncate(msg.auto_submitted, 40)}`;
  if (msg.precedence && /^(bulk|junk|list|auto_reply)$/i.test(msg.precedence.trim())) return `Precedence header: ${msg.precedence.trim()}`;
  return null;
}

export function isNewsletter(msg) {
  if (msg.list_unsubscribe) return "List-Unsubscribe header present (mailing list or newsletter)";
  if (msg.list_id) return `List-Id header present: ${truncate(msg.list_id, 60)}`;
  return null;
}

const PRIORITY_RANK = { low: 0, normal: 1, high: 2 };

export function triageMessages(messages, rules = {}, nowMs) {
  const vip = rules.vip_senders ?? [];
  const mine = (rules.my_addresses ?? []).map((a) => a.trim().toLowerCase()).filter(Boolean);
  const keywordRules = rules.keyword_rules ?? [];
  const urgentDays = rules.urgent_within_days ?? 2;
  const detectNewsletters = rules.newsletter_detection !== false;
  const today = startOfUtcDay(nowMs);

  const results = messages.map((msg) => {
    const reasons = [];
    const address = msg.from_address ?? parseAddress(msg.from ?? "").address;
    const subject = msg.subject ?? "";
    const body = msg.body_text ?? "";
    let category = null;
    let priority = "normal";
    let priorityLocked = false;

    // 1. User keyword rules (explicit user intent wins for category and priority).
    keywordRules.forEach((rule, i) => {
      const field = rule.field ?? "any";
      const haystacks = field === "subject" ? { subject } : field === "body" ? { body } : { subject, body };
      for (const kw of rule.keywords) {
        const where = Object.keys(haystacks).find((k) => keywordHit(haystacks[k], kw));
        if (!where) continue;
        reasons.push(`Keyword rule ${i + 1} matched "${kw}" in ${where}`);
        if (rule.category && !category) category = rule.category;
        if (rule.priority && !priorityLocked) { priority = rule.priority; priorityLocked = true; }
        break;
      }
    });

    // 2. VIP senders.
    const vipEntry = vip.find((v) => senderMatches(address, v));
    if (vipEntry) {
      reasons.push(`Sender ${address} matches VIP entry "${vipEntry}"`);
      category ??= "vip";
      if (!priorityLocked) priority = "high";
    }

    // 3. Bulk mail: newsletters (List-Unsubscribe / List-Id) and automated notifications.
    const newsletter = detectNewsletters ? isNewsletter(msg) : null;
    const automated = isAutomated(msg);
    if (newsletter) {
      reasons.push(newsletter);
      category ??= "newsletter";
      if (!priorityLocked && !vipEntry) priority = "low";
    } else if (automated) {
      reasons.push(automated);
      category ??= "notification";
      if (!priorityLocked && !vipEntry) priority = "low";
    }

    // 4. Reply-needed heuristics (skipped for bulk/automated mail, whose questions are rhetorical or unanswerable).
    let replyNeeded = false;
    const deadlines = [];
    const fresh = newContent(body);
    if (!newsletter && !automated) {
      const questions = sentences(fresh).filter((s) => s.endsWith("?") && s.split(/\s+/).length >= 3);
      if (subject.trim().endsWith("?") && !/^(re|fwd?):/i.test(subject.trim())) questions.unshift(subject.trim());
      if (questions.length) {
        replyNeeded = true;
        reasons.push(`Direct question: "${truncate(questions[0], 100)}"${questions.length > 1 ? ` (+${questions.length - 1} more)` : ""}`);
      }
      const lower = `${subject}\n${fresh}`.toLowerCase();
      const phrase = REQUEST_PHRASES.find((p) => new RegExp(`\\b${escapeRe(p)}\\b`).test(lower));
      if (phrase) {
        replyNeeded = true;
        reasons.push(`Request phrase: "${phrase}"`);
      }
      const refMs = msg.date && !Number.isNaN(Date.parse(msg.date)) ? Date.parse(msg.date) : nowMs;
      for (const d of extractDeadlines(`${subject}\n${fresh}`, refMs)) deadlines.push(d);
      if (deadlines.length) {
        replyNeeded = true;
        for (const d of deadlines) reasons.push(`Deadline mentioned: "${truncate(d.text, 60)}"${d.date ? ` (${d.date})` : " (date ambiguous, not resolved)"}`);
        const dated = deadlines.filter((d) => d.date).map((d) => Date.parse(`${d.date}T00:00:00Z`)).sort((a, b) => a - b);
        if (dated.length && !priorityLocked) {
          const days = Math.round((dated[0] - today) / DAY);
          if (days < 0) { priority = "high"; reasons.push(`Deadline ${utcDateOnly(dated[0])} has passed`); }
          else if (days <= urgentDays) { priority = "high"; reasons.push(`Deadline ${utcDateOnly(dated[0])} is within ${urgentDays} day(s) of ${utcDateOnly(today)}`); }
        }
      }
      if (replyNeeded) category ??= "needs_reply";
    }

    // 5. Addressing.
    if (mine.length) {
      const to = addressesOf(msg.to);
      const cc = addressesOf(msg.cc);
      if (to.some((a) => mine.includes(a))) reasons.push("You are a direct (To:) recipient");
      else if (cc.some((a) => mine.includes(a))) {
        reasons.push("You are only in Cc:");
        if (replyNeeded && !priorityLocked && !vipEntry && priority === "high") priority = "normal";
      }
    }

    if (!category) {
      category = "fyi";
      reasons.push("No rule matched; filed as FYI");
    }
    return { id: msg.id, category, priority, reply_needed: replyNeeded, deadlines, reasons };
  });

  const byCategory = {};
  const byPriority = { high: 0, normal: 0, low: 0 };
  for (const r of results) {
    byCategory[r.category] = (byCategory[r.category] ?? 0) + 1;
    byPriority[r.priority]++;
  }
  // Highest priority first; stable within a priority (input order).
  const ordered = results.map((r, i) => ({ r, i })).sort((a, b) => PRIORITY_RANK[b.r.priority] - PRIORITY_RANK[a.r.priority] || a.i - b.i).map((x) => x.r.id);
  return {
    messages: results,
    summary: {
      total: results.length,
      by_category: byCategory,
      by_priority: byPriority,
      reply_needed: results.filter((r) => r.reply_needed).length,
      order: ordered,
    },
    generated_at: new Date(nowMs).toISOString(),
  };
}

// ---------------------------------------------------------------------------------------------
// Filter suggestions (data only; nothing is applied anywhere)
// ---------------------------------------------------------------------------------------------
function domainOf(address) {
  return address ? address.split("@")[1] ?? "" : "";
}

function listName(listId) {
  const angle = /<([^>]+)>/.exec(listId);
  return (angle ? angle[1] : listId).trim().toLowerCase();
}

export function suggestFilters(messages, triage, minGroup) {
  const categoryById = new Map((triage?.messages ?? []).map((t) => [t.id, t.category]));
  const filters = [];
  const covered = new Set();
  const groups = (keyFn) => {
    const map = new Map();
    for (const m of messages) {
      const k = keyFn(m);
      if (!k) continue;
      if (!map.has(k)) map.set(k, []);
      map.get(k).push(m);
    }
    return [...map.entries()].filter(([, ms]) => ms.length >= minGroup).sort((a, b) => b[1].length - a[1].length || (a[0] < b[0] ? -1 : 1));
  };
  const add = (f, ms) => {
    filters.push({ id: `filter-${filters.length + 1}`, ...f, matches: ms.map((m) => m.id) });
    for (const m of ms) covered.add(m.id);
  };

  for (const [key, ms] of groups((m) => (m.list_id ? `list:${listName(m.list_id)}` : null))) {
    const name = key.slice(5);
    add({ kind: "newsletter", description: `Label mailing-list mail from ${name}`, criteria: { list_id: name }, actions: { label: `Newsletters/${name}`, skip_inbox: true }, rationale: `${ms.length} message(s) carry List-Id ${name}` }, ms);
  }
  for (const [addr, ms] of groups((m) => (!covered.has(m.id) && m.list_unsubscribe ? m.from_address ?? parseAddress(m.from ?? "").address : null))) {
    add({ kind: "newsletter", description: `Label newsletters from ${addr}`, criteria: { from: addr, has_list_unsubscribe: true }, actions: { label: `Newsletters/${domainOf(addr) || addr}`, skip_inbox: true }, rationale: `${ms.length} message(s) from ${addr} include a List-Unsubscribe header` }, ms);
  }
  for (const [domain, ms] of groups((m) => (!covered.has(m.id) && isAutomated(m) ? domainOf(m.from_address ?? parseAddress(m.from ?? "").address) : null))) {
    add({ kind: "notification", description: `Label automated notifications from ${domain}`, criteria: { from_domain: domain }, actions: { label: `Notifications/${domain}`, skip_inbox: false }, rationale: `${ms.length} automated message(s) (no-reply sender or Auto-Submitted/Precedence header) from ${domain}` }, ms);
  }
  for (const [tag, ms] of groups((m) => {
    if (covered.has(m.id)) return null;
    const t = /^\s*(?:(?:re|fwd?):\s*)*\[([^\]\n]{2,30})\]/i.exec(m.subject ?? "");
    return t ? t[1].trim() : null;
  })) {
    add({ kind: "subject_tag", description: `Label messages whose subject starts with [${tag}]`, criteria: { subject_contains: `[${tag}]` }, actions: { label: tag, skip_inbox: false }, rationale: `${ms.length} message(s) share the subject tag [${tag}]` }, ms);
  }
  if (triage) {
    // VIP filters apply even to a single message: the user already declared these senders important.
    const vipMap = new Map();
    for (const m of messages) {
      if (categoryById.get(m.id) !== "vip") continue;
      const a = m.from_address ?? parseAddress(m.from ?? "").address;
      if (!a) continue;
      if (!vipMap.has(a)) vipMap.set(a, []);
      vipMap.get(a).push(m);
    }
    for (const [addr, ms] of [...vipMap.entries()].sort((x, y) => (x[0] < y[0] ? -1 : 1))) {
      filters.push({ id: `filter-${filters.length + 1}`, kind: "vip", description: `Star mail from VIP ${addr}`, criteria: { from: addr }, actions: { label: "VIP", star: true, skip_inbox: false }, rationale: `Triage categorised ${ms.length} message(s) from ${addr} as VIP`, matches: ms.map((m) => m.id) });
    }
  }
  return filters;
}

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