OR Key
drop another .md file to compare - side-by-side diff against inbox-sweep

inbox-sweep

Pulls every channel's messages into one list of what needs you.
description: "Triggers on prompt mention of 'inbox-sweep'."
personal 2 files 10 recent evals

What it does for you

Pulls every channel's messages into one list of what needs you.

What it produces

A recent result, so you can see the kind of work it returns.

loading…

How to get it

These run inside the Snappy workspace. Want this working in your business? I set skills like this up with you, in one focused week.

Work with me
For developers how this skill is built, graded, and how it runs

at a glance- the short version

actorExported functions in state/lib/inbox-sweep.ts.
auditorNone wired yet - eval is manual (Robert review).
eval modeshape
categoryChannels
stages2
dependssweep

what's inside - the parts that make up a skill 3/4 present

A skill is just a few plain-text files. Only the main one is required. The rest are optional, added as the work needs them. This is what the skill is made of; how it runs is just below.

The skill
state/skills/inbox-sweep/SKILL.md present
the skill itself, in plain text
The main file. It says what the skill is and lays out the steps in plain English.
Code
state/lib/inbox-sweep.ts present
code the skill can run
Reusable code this skill can call when it needs to.
Scripts
state/bin/inbox-sweep/ not present
helper scripts
Optional. Added when a skill has a few commands to run.
Loader
state/skills/inbox-sweep/AGENTS.md present
what the AI loads on the fly
Loaded automatically the moment this skill is needed. Kept short on purpose.

how it's graded - what counts as a good run 4 criteria · 4 deterministic

Each row is one thing a good run has to get right. deterministic means a quick check decides, pass or fail. judge means the AI reads the result and rates it. Grading each piece on its own (instead of one overall score) shows exactly where a run fell short, so the fix is obvious.

name
kind
check
slack_messages_fetched
deterministic
The skill execution log indicates that fetchSlackRecent() and fetchSlackUnread() were called successfully.
gmail_messages_fetched
deterministic
The skill execution log indicates that fetchGmailRecent() and fetchGmailUnread() were called successfully.
inbox_zero_attempted
deterministic
The skill execution log confirms the invocation of inboxZero() or sweepAll() during the run.
eval_log_entry_created
deterministic
A new row is appended to state/log/pending-eval.ndjson for this execution.

how it runs - the shared frame every skill uses 5/5 present

Every skill runs the same way. One part does the work, a separate part checks it, and a short loader hands the AI exactly what it needs for the job. Anything this skill doesn't use shows a one-line note saying why, on purpose, not by accident.

makes the work The worker
present
Exported functions in state/lib/inbox-sweep.ts. the worker
Does the actual work. Whatever it produces is what gets checked next.
checks the work The reviewer
present
None wired yet - eval is manual (Robert review). the checker
A separate checker grades the work, so the part that made it can't approve its own work.
frame
learns Self-correction
present
fixes itself learns from gaps
When a run hits a gap, the skill gets edited on the spot [FIXED] or queued for a bigger rewrite [LOGGED], so it keeps getting better.
tidies up Background fixes
present
queued for rewrite runs in the background
Bigger fixes that can't be made on the spot get queued and rewritten in the background later.
remembers Run history
present
state/log/pending-eval.ndjson pending runs
Every run is written down here, then reviewed by hand each week.
Critical rules the things this skill must not get wrong
No must-not-break rules called out for this skill. Anything important lives in the writeup below.

what it has learned - fixes written back in over time sample

When a run hits something this skill didn't handle, the fix gets written back into the skill so it doesn't happen again. FIXED means it was corrected on the spot. LOGGED means it's queued for a bigger rewrite. Either way, the skill gets a little better and never makes the same mistake twice.

  1. Loading feedback rows…

how the work flows- who makes it, who checks it

inputs sweep
actor Exported functions in state/lib/inbox-sweep.ts.
1 generator
invoke
actor = Exported functions in state/lib/inbox-sweep.ts.
import from `state/lib/inbox-sweep.ts` — `fetchSlackRecent/Unread`, `sendSlackReply`, `fetchGmailRecent/Unread`, `archiveGmail`, `classifyAll`, `inboxZero`, `sweepAll`, `sendSkoolReply
auditor None wired yet - eval is manual (Robert review).
2 data
eval log
`state/log/pending-eval.ndjson` (manual review until shape gate added)

SKILL.md- the skill, written out in plain English

inbox-sweep

snappy-inbox-sweep/api.ts - Deterministic multi-channel inbox sweep.

Ported from kernel snappy-inbox-sweep in Phase 0.5. See state/lib/inbox-sweep.ts for the full API surface.

Steps

  • fetchSlackRecent() - see state/lib/inbox-sweep.ts
  • fetchSlackUnread() - see state/lib/inbox-sweep.ts
  • sendSlackReply() - see state/lib/inbox-sweep.ts
  • fetchGmailRecent() - see state/lib/inbox-sweep.ts
  • fetchGmailUnread() - see state/lib/inbox-sweep.ts
  • archiveGmail() - see state/lib/inbox-sweep.ts
  • batchArchiveGmail() - see state/lib/inbox-sweep.ts
  • markSlackRead() - see state/lib/inbox-sweep.ts
  • classifyItem() - see state/lib/inbox-sweep.ts
  • classifyAll() - see state/lib/inbox-sweep.ts
  • inboxZero() - see state/lib/inbox-sweep.ts
  • sweepAll() - see state/lib/inbox-sweep.ts
  • sendSkoolReply() - see state/lib/inbox-sweep.ts

Eval

Actor: the exported functions in state/lib/inbox-sweep.ts. Auditor: none wired yet - eval is manual (Robert review). File a state/log/pending-eval.ndjson row on each run.

Score convention:

OutcomeScore
Pass on first try1.0
Failed first, auto-fix applied, re-check passed0.5
Still failing or unrecoverable0.0

Gotchas

via the Phase 0.5 driver. Only these rewrites were applied: already in state/lib/)

  1. realpathSync(process.argv[1]) CLI guard wrapped in try/catch
  • See the kernel SKILL.md for the original long-form guidance if you need it

(read-only reference at the kernel path above).

Graduation

This skill is prose. Graduate by defining a deterministic auditor and flipping eval: auto.

Rubric

criteria:
  - name: slack_messages_fetched
    kind: deterministic
    check: "The skill execution log indicates that fetchSlackRecent() and fetchSlackUnread() were called successfully."
  - name: gmail_messages_fetched
    kind: deterministic
    check: "The skill execution log indicates that fetchGmailRecent() and fetchGmailUnread() were called successfully."
  - name: inbox_zero_attempted
    kind: deterministic
    check: "The skill execution log confirms the invocation of inboxZero() or sweepAll() during the run."
  - name: eval_log_entry_created
    kind: deterministic
    check: "A new row is appended to state/log/pending-eval.ndjson for this execution."

AGENTS.md- what the AI loads when this skill comes up

inbox-sweep - loader

Per-turn rules for the inbox-sweep skill. Full reference: state/skills/inbox-sweep/SKILL.md. Do not skip these.

Critical Rules

_(no failures recorded yet - this skill is a Phase 0.5 mechanical port from snappy-inbox-sweep with no hard-won rules in the page. The richer cross-channel skill is sweep (see state/skills/sweep/SKILL.md and state/lib/sweep.ts - 741-line graduated lib). Read both before invoking.)_

Commands

| ui dashboard | state/skills/inbox-sweep/resources/ui.openui | |invoke: import from state/lib/inbox-sweep.ts - fetchSlackRecent/Unread, sendSlackReply, fetchGmailRecent/Unread, archiveGmail, classifyAll, inboxZero, sweepAll, sendSkoolReply |graduated alternative: state/lib/sweep.tssweepAll() (the shape-gated production path) |eval log: state/log/pending-eval.ndjson (manual review until shape gate added)

OpenUI Resource

  • Skill-owned OpenUI Lang resource: state/skills/inbox-sweep/resources/ui.openui. Read it before rendering or editing this skill's generated component surface.
  • Treat this resource as a first-class artifact of the skill, not a generic chat response. Improve it when the skill's user-facing output needs to become richer.
  • System resources compose OpenUI primitives and inherit SnappyChat tokens. Use ui_contract: branded in SKILL.md only for deliberate platform or client visuals.

Known Pitfalls

  • Two libs exist - inbox-sweep.ts (Phase 0.5 port) AND sweep.ts (graduated). Default to sweep.ts for production runs; inbox-sweep.ts is the unported original surface
  • Skill page advertises eval: shape but no auditor is wired - log to pending-eval.ndjson, not evals.ndjson
  • Never fan out parallel agent-browser writes for Skool replies - serialize per program.md "no parallel agent-browser writes" rule

Self-Test

An agent reading this should correctly:

  1. [ ] Pick state/lib/sweep.ts over inbox-sweep.ts when there's a choice?
  2. [ ] Serialize Skool/LinkedIn DM writes rather than parallelizing?
  3. [ ] Log to pending-eval.ndjson because no shape auditor exists yet?

Self-report

If this loader fell short, append a line:

echo "[$(date -u +%FT%TZ)] inbox-sweep: <what was missing>" >> state/log/loader-feedback.log

<!-- kernel-ok: historical attribution for the PID-loader pattern. -->

Self-correcting loader (PID feedback)

This is the rule that makes loaders learn. Ported from snappy-kernel, where it demonstrably worked: the snappy-dom-cartographer skill mapped Skool admin UI once, every later ship-agent inherited the full map for free.

Before you finish, do two things:

1. Fix gaps (P - proportional). MANDATORY. If this loader didn't cover your case - if you had to read another file, run an undocumented command, work around a wrong selector, or discover a quirk - you MUST attempt an Edit to this AGENTS.md before you log.

  • Default action: edit this file. Surgical. Add the missing line, table

row, or code example where it belongs. No restructuring.

  • Only LOGGED is allowed when: the fix needs >10 lines, spans multiple

files, or requires a structural rewrite. In that case the state/regen/drain.sh queue picks it up asynchronously.

  • "I didn't have time" / "it's minor" / "the next agent will figure it out"

are NOT valid reasons. Minor gaps compound - that's the whole point of this loop.

  • Concrete example of a valid P-fix: discover agent-browser screenshot

takes path positionally not as --output <path>. One line in a table. Edit it in. Do not just log it.

  • The goal: the next agent never has to leave the loader.

2. Log the result.

echo "[$(date -u +%FT%TZ)] inbox-sweep: <what was missing or fixed> [FIXED|LOGGED]" >> state/log/loader-feedback.log
  • FIXED = you patched this loader inline (P-fix).
  • LOGGED = too large for inline; the PostToolUse enqueue + Stop-hook drain

will rewrite the loader from scratch on next session-end.

Do not skip this. Every agent run must leave the system better than it found it. The loader is the setpoint; you are the sensor; the gap is the error signal; closing the gap is the correction.

api.ts- the code it can call

#!/usr/bin/env npx tsx
/**
 * snappy-inbox-sweep/api.ts — Deterministic multi-channel inbox sweep.
 *
 * Public API:
 *   fetchSlackUnread()        — Slack DMs + mpIMs with unread_count > 0
 *   sweepAll()                — Run every ready fetcher in parallel, merge, write to out/
 *   sendSlackReply(item,text) — Send an approved reply back to Slack
 *
 * CLI:
 *   npx tsx api.ts sweep       — run full sweep, print JSON
 *   npx tsx api.ts slack       — only Slack fetcher
 *   npx tsx api.ts send-slack <channel> <text>
 *   npx tsx api.ts help
 */

import { env } from "./env.ts";
import { mkdirSync, readFileSync, realpathSync, writeFileSync } from "fs";
import { join, dirname } from "path";
import { fileURLToPath } from "url";
import { createSign } from "crypto";

const __dirname = dirname(fileURLToPath(import.meta.url));
const OUT_DIR = join(__dirname, "out");

export type InboxItem = {
  source: "slack" | "gmail" | "linkedin" | "skool" | "statechange";
  channel_id: string;
  channel_name: string;
  user_id: string;
  user_name: string;
  ts: string;
  text: string;
  permalink?: string;
  thread_id?: string;
  /** True if Robert already replied and is waiting for the other person's response. */
  awaiting_reply?: boolean;
};

// --- Slack fetcher -----------------------------------------------------------
// Note: uses its own lightweight GET-based Slack client for DM sweep operations
// (conversations.info, conversations.history, users.info). snappy-slack handles
// general-purpose channel reads/sends via POST. Both use SLACK_USER_TOKEN.

async function slack(method: string, params: Record<string, string> = {}): Promise<any> {
  const token = env("SLACK_USER_TOKEN");
  const url = `https://slack.com/api/${method}?${new URLSearchParams(params)}`;
  const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
  const json = await res.json() as any;
  if (!json.ok) throw new Error(`slack ${method}: ${json.error}`);
  return json;
}

const _userCache = new Map<string, string>();
async function slackUserName(uid: string): Promise<string> {
  if (!uid) return "";
  if (_userCache.has(uid)) return _userCache.get(uid)!;
  try {
    const { user } = await slack("users.info", { user: uid });
    const name = user?.profile?.display_name || user?.real_name || uid;
    _userCache.set(uid, name);
    return name;
  } catch {
    return uid;
  }
}

export async function fetchSlackRecent(sinceMs: number, limitPerChannel = 100): Promise<InboxItem[]> {
  // 90d window across all IM (DM) conversations. No unread filter — pulls history.
  const me = (await slack("auth.test")).user_id as string;
  const oldest = (sinceMs / 1000).toFixed(6);
  const { channels } = await slack("users.conversations", {
    types: "im",
    limit: "200",
  });
  const items: InboxItem[] = [];
  for (const c of channels || []) {
    if (c.is_archived || c.is_user_deleted) continue;
    try {
      const { messages } = await slack("conversations.history", {
        channel: c.id,
        oldest,
        limit: String(limitPerChannel),
      });
      if (!messages?.length) continue;
      const cname = c.user ? await slackUserName(c.user) : c.id;
      for (const m of messages.reverse()) {
        if (m.subtype === "channel_join" || m.subtype === "channel_leave") continue;
        if (!m.user || m.user === me) continue;
        items.push({
          source: "slack",
          channel_id: c.id,
          channel_name: cname,
          user_id: m.user || "",
          user_name: m.user ? await slackUserName(m.user) : "",
          ts: m.ts,
          text: m.text || "",
          thread_id: m.thread_ts,
          awaiting_reply: false,
        });
      }
    } catch { continue; }
  }
  return items;
}

export async function fetchSlackUnread(): Promise<InboxItem[]> {
  // User token scopes: im:read, im:history. (mpim:read not granted — skip mpIMs.)
  // users.conversations does NOT return unread_count — we must call
  // conversations.info per DM to get unread_count_display.
  const me = (await slack("auth.test")).user_id as string;
  const { channels } = await slack("users.conversations", {
    types: "im",
    limit: "200",
  });
  const items: InboxItem[] = [];
  for (const c of channels || []) {
    if (c.is_archived || c.is_user_deleted) continue;
    let unread = 0;
    try {
      const info = await slack("conversations.info", { channel: c.id });
      unread = info.channel?.unread_count_display || info.channel?.unread_count || 0;
    } catch { continue; }
    if (!unread) continue;
    const { messages } = await slack("conversations.history", {
      channel: c.id,
      limit: String(Math.min(unread, 20)),
    });
    const cname = c.user ? await slackUserName(c.user) : c.id;
    for (const m of (messages || []).reverse()) {
      if (m.subtype === "channel_join" || m.subtype === "channel_leave") continue;
      if (!m.user || m.user === me) continue; // skip own messages
      items.push({
        source: "slack",
        channel_id: c.id,
        channel_name: cname,
        user_id: m.user || "",
        user_name: m.user ? await slackUserName(m.user) : "",
        ts: m.ts,
        text: m.text || "",
        thread_id: m.thread_ts,
      });
    }
  }
  return items;
}

export async function sendSlackReply(channel: string, text: string, thread_ts?: string): Promise<any> {
  const token = env("SLACK_USER_TOKEN");
  const body: Record<string, string> = { channel, text };
  if (thread_ts) body.thread_ts = thread_ts;
  const res = await fetch("https://slack.com/api/chat.postMessage", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json; charset=utf-8",
    },
    body: JSON.stringify(body),
  });
  const json = await res.json() as any;
  if (!json.ok) throw new Error(`slack send: ${json.error}`);
  return json;
}

// --- Gmail fetcher ------------------------------------------------------------

// Service account JWT for robert@snappy.ai (domain-wide delegation)
async function getServiceAccountToken(sub: string): Promise<string> {
  const email = env("GOOGLE_SERVICE_ACCOUNT_EMAIL");
  const key = env("GOOGLE_SERVICE_ACCOUNT_KEY").replace(/\\n/g, "\n");
  const now = Math.floor(Date.now() / 1000);
  const header = Buffer.from(JSON.stringify({ alg: "RS256", typ: "JWT" })).toString("base64url");
  const payload = Buffer.from(JSON.stringify({
    iss: email,
    sub,
    scope: "https://www.googleapis.com/auth/gmail.modify",
    aud: "https://oauth2.googleapis.com/token",
    iat: now,
    exp: now + 3600,
  })).toString("base64url");
  const sig = createSign("RSA-SHA256").update(`${header}.${payload}`).sign(key, "base64url");
  const jwt = `${header}.${payload}.${sig}`;
  const res = await fetch("https://oauth2.googleapis.com/token", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
      assertion: jwt,
    }),
  });
  const data = await res.json() as any;
  if (data.error) throw new Error(`SA token for ${sub}: ${data.error_description || data.error}`);
  return data.access_token;
}

// OAuth refresh for robertjboulos@gmail.com
async function getPersonalGmailToken(): Promise<string> {
  const rt = env("GMAIL_PERSONAL_REFRESH_TOKEN", false);
  if (!rt) throw new Error("Gmail personal OAuth not configured — GMAIL_PERSONAL_REFRESH_TOKEN missing from .env.cache. Run: npx tsx ~/.claude/skills/snappy-inbox-sweep/gmail-oauth.ts consent");
  const res = await fetch("https://oauth2.googleapis.com/token", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      refresh_token: rt,
      client_id: env("GOOGLE_CLIENT_ID"),
      client_secret: env("GOOGLE_CLIENT_SECRET"),
      grant_type: "refresh_token",
    }),
  });
  const data = await res.json() as any;
  if (data.error) throw new Error(`Personal Gmail refresh: ${data.error_description || data.error}`);
  return data.access_token;
}

type GmailAccount = "robert@snappy.ai" | "robertjboulos@gmail.com";

async function gmailAccessToken(account: GmailAccount): Promise<string> {
  if (account === "robert@snappy.ai") return getServiceAccountToken(account);
  return getPersonalGmailToken();
}

async function gmailApi(token: string, path: string): Promise<any> {
  const res = await fetch(`https://gmail.googleapis.com/gmail/v1/users/me/${path}`, {
    headers: { Authorization: `Bearer ${token}` },
  });
  if (!res.ok) throw new Error(`Gmail API ${path}: ${res.status} ${await res.text()}`);
  return res.json();
}

export async function fetchGmailRecent(account: GmailAccount, sinceMs: number, pageCap = 10): Promise<InboxItem[]> {
  const token = await gmailAccessToken(account);
  const days = Math.max(1, Math.ceil((Date.now() - sinceMs) / 86_400_000));
  const q = `newer_than:${days}d -in:spam -in:trash`;
  const ids: string[] = [];
  let pageToken: string | undefined;
  for (let i = 0; i < pageCap; i++) {
    const qs = new URLSearchParams({ q, maxResults: "100" });
    if (pageToken) qs.set("pageToken", pageToken);
    const page = await gmailApi(token, `messages?${qs}`);
    for (const m of page.messages ?? []) ids.push(m.id);
    pageToken = page.nextPageToken;
    if (!pageToken) break;
  }
  if (!ids.length) return [];

  const items: InboxItem[] = [];
  for (const id of ids) {
    try {
      const full = await gmailApi(token, `messages/${id}?format=metadata&metadataHeaders=From&metadataHeaders=Subject&metadataHeaders=Date`);
      const headers = full.payload?.headers || [];
      const from = headers.find((h: any) => h.name === "From")?.value || "";
      const subject = headers.find((h: any) => h.name === "Subject")?.value || "";
      const nameMatch = from.match(/^"?([^"<]+)"?\s*</);
      const emailMatch = from.match(/<([^>]+)>/);
      const senderName = nameMatch ? nameMatch[1].trim() : from;
      const senderEmail = emailMatch ? emailMatch[1] : from;

      const robertEmails = ["robert@snappy.ai", "robertjboulos@gmail.com"];
      const fromIsRobert = robertEmails.some(e => senderEmail.toLowerCase().includes(e));
      if (fromIsRobert) continue;

      items.push({
        source: "gmail",
        channel_id: account,
        channel_name: account === "robert@snappy.ai" ? "Gmail (work)" : "Gmail (personal)",
        user_id: senderEmail,
        user_name: senderName,
        ts: full.internalDate || "",
        text: subject,
        thread_id: full.threadId,
        permalink: `https://mail.google.com/mail/u/?authuser=${account}#inbox/${id}`,
        awaiting_reply: false,
      });
    } catch { continue; }
  }
  return items;
}

export async function fetchGmailUnread(account: GmailAccount): Promise<InboxItem[]> {
  const token = await gmailAccessToken(account);
  // Get unread messages from inbox (max 25)
  const list = await gmailApi(token, "messages?q=is%3Aunread%20in%3Ainbox&maxResults=25");
  if (!list.messages?.length) return [];

  const items: InboxItem[] = [];
  // Fetch each message (batch of metadata)
  for (const msg of list.messages) {
    try {
      const full = await gmailApi(token, `messages/${msg.id}?format=metadata&metadataHeaders=From&metadataHeaders=Subject&metadataHeaders=Date`);
      const headers = full.payload?.headers || [];
      const from = headers.find((h: any) => h.name === "From")?.value || "";
      const subject = headers.find((h: any) => h.name === "Subject")?.value || "";
      const date = headers.find((h: any) => h.name === "Date")?.value || "";

      // Parse sender name from "Name <email>" format
      const nameMatch = from.match(/^"?([^"<]+)"?\s*</);
      const emailMatch = from.match(/<([^>]+)>/);
      const senderName = nameMatch ? nameMatch[1].trim() : from;
      const senderEmail = emailMatch ? emailMatch[1] : from;

      // Check thread state: did Robert already reply?
      let awaitingReply = false;
      if (full.threadId) {
        try {
          const thread = await gmailApi(token, `threads/${full.threadId}?format=metadata&metadataHeaders=From`);
          const msgs = thread.messages || [];
          if (msgs.length > 1) {
            const lastMsg = msgs[msgs.length - 1];
            const lastFrom = (lastMsg.payload?.headers || []).find((h: any) => h.name === "From")?.value || "";
            const robertEmails = ["robert@snappy.ai", "robertjboulos@gmail.com"];
            awaitingReply = robertEmails.some(e => lastFrom.toLowerCase().includes(e));
          }
        } catch { /* thread fetch failed, assume not awaiting */ }
      }

      items.push({
        source: "gmail",
        channel_id: account,
        channel_name: account === "robert@snappy.ai" ? "Gmail (work)" : "Gmail (personal)",
        user_id: senderEmail,
        user_name: senderName,
        ts: full.internalDate || "",
        text: subject,
        thread_id: full.threadId,
        permalink: `https://mail.google.com/mail/u/?authuser=${account}#inbox/${msg.id}`,
        awaiting_reply: awaitingReply,
      });
    } catch {
      // Skip individual message errors
      continue;
    }
  }
  return items;
}

// --- Gmail actions (archive, mark read) --------------------------------------

async function gmailModify(token: string, messageId: string, addLabels: string[], removeLabels: string[]): Promise<void> {
  const res = await fetch(`https://gmail.googleapis.com/gmail/v1/users/me/messages/${messageId}/modify`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ addLabelIds: addLabels, removeLabelIds: removeLabels }),
  });
  if (!res.ok) throw new Error(`Gmail modify ${messageId}: ${res.status} ${await res.text()}`);
}

/** Archive a Gmail message (remove from INBOX, mark as read). */
export async function archiveGmail(account: GmailAccount, messageId: string): Promise<void> {
  const token = await gmailAccessToken(account);
  await gmailModify(token, messageId, [], ["INBOX", "UNREAD"]);
}

/** Batch archive multiple Gmail messages. Returns count of successes. */
export async function batchArchiveGmail(account: GmailAccount, messageIds: string[]): Promise<number> {
  const token = await gmailAccessToken(account);
  let ok = 0;
  for (const id of messageIds) {
    try {
      await gmailModify(token, id, [], ["INBOX", "UNREAD"]);
      ok++;
    } catch { /* continue on individual failures */ }
  }
  return ok;
}

// --- Slack actions (mark as read) --------------------------------------------

/** Mark a Slack conversation as read up to the given timestamp. */
export async function markSlackRead(channel: string, ts: string): Promise<void> {
  const token = env("SLACK_USER_TOKEN");
  const res = await fetch("https://slack.com/api/conversations.mark", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json; charset=utf-8",
    },
    body: JSON.stringify({ channel, ts }),
  });
  const json = await res.json() as any;
  if (!json.ok) throw new Error(`slack conversations.mark: ${json.error}`);
}

// --- Noise classifier --------------------------------------------------------

// Noise sender domains — any email from these domains is noise
const NOISE_DOMAINS = [
  "groupon.com", "lafitness.com", "flexiti.com", "meetup.com", "termius.com",
  "webflow.com", "holistics.io", "calendly.com", "bitwarden.com",
  "onlinesellersolutions.com", "beehiiv.com", "loom.com", "segmind.com",
  "browserbase.com", "digitalocean.com", "arizer.com", "featurebase.app",
  "rockymountainflannel.com", "cpe-agility.com", "canineperformanceevents.com",
  "thatcherfarms.com", "barnswallowfields.com", "microconf.com", "openrouter.ai",
  "lu.ma", "levi.com", "levis.com", "helium10.com", "replit.com",
  "gamma.app", "notion.so", "notion.com", "flickr.com", "buildship.com",
  "namecheap.com", "xano.com", "407etr.com", "twilio.com", "sendgrid.net",
  "mermaid.live", "klingai.com", "plex.tv", "twelvelabs.io", "untitledui.com",
  "exa.ai", "spline.design", "krisp.ai", "zapier.com", "nocodeops.com",
  "mermaidchart.com", "mermaid.ink", "appflowy.io", "starbucks.com", "starbucks.ca",
  "dev.to", "forem.com", "tella.tv", "aldoshoes.com", "aldo.com",
  "clearme.com", "id.me", "michaelhill.com", "postman.com",
  "bravesoftware.com", "orbiter.io",
  // Added 2026-04-13 after inbox-zero leak of 5 marketing items through to actionable
  "squadcast.fm", "kleo.so", "mermaid.ai", "annahickman.com", "wordzen.com",
  // Added 2026-04-13 round 2: WeWeb pricing upsell, DataCamp newsletter, Michael Hill retail
  "weweb.io", "datacamp.com", "michaelhill.ca",
];

const NOISE_PATTERNS = [
  // Generic spam signals (word-boundary so "Name noreply@..." matches, not just "<noreply@...>")
  /\bnoreply@/i, /\bno-reply@/i, /\bnotifications@/i, /\bdonotreply/i, /newsletter/i, /unsubscribe/i,
  // Marketing-mailer localparts — senders that use a generic role address are
  // almost always one-way broadcasts, not real humans expecting a reply.
  // Fixed 2026-04-13: use word boundary instead of < / ^ anchors — the classified
  // line is "Name email@domain subject", so email is never at ^ and rarely in <>.
  /\b(hello|invite|news|marketing|promo|announce|updates?|info|contact|team|support|sales|storage|harmony)@/i,
  // Marketing-mailer subdomains (mail.kleo.so, email.foo.com, etc.)
  /@(mail|email|send|sendgrid|marketing|news|updates?|newsletter|mktg|e|em|m|link|go|announce|promo)\./i,
  // Security/device notifications
  /device.*sign/i, /new device/i, /new login/i, /sign.?in link/i, /security-noreply/i, /recovery email/i,
  // Calendar auto-generated
  /calendar briefing/i, /is starting in \d+ (hour|minute)/i, /is starting tomorrow/i,
  // Promos and marketing
  /% off/i, /offer expires/i, /limited time/i, /sitewide savings/i, /free shipping/i,
  // Luma event notifications
  /luma/i, /new registration for/i,
  // Specific known noise senders
  /team@termius/i, /team@learn\.termius/i, /lafitness/i, /onlinesellersolutions/i,
  /flexiti@/i, /teamcalendly@/i, /contact@hello\.webflow/i, /cleverly-co@/i,
  /david\.bui@holistics/i, /groupon/i, /la fitness/i, /flexiti/i, /meetup/i,
  // SaaS marketing / product update emails
  /see how teams/i, /see what your .* returned/i, /flannel shirts/i,
  /q chronicles/i, /canine performance/i, /thatcher farms/i, /barn swallow/i,
  /rocky mountain flannel/i, /say.*i do/i, /brunch wedding/i,
  // SaaS product updates / terms / marketing
  /product update/i, /subprocessor update/i, /updates to.*terms/i,
  /don.t miss out/i, /free access.*ends/i, /final call/i,
  /amazon ppc/i, /g2 spring/i, /where.*stood out/i,
  // Calendar accept/decline notifications (FYI, not actionable)
  /Accepted:.*@/i, /Declined:.*@/i, /Canceled event:/i, /Cancelled event:/i,
  // Appointment booked (calendar auto-notification)
  /Appointment booked:/i, /survey closing/i, /chance to win/i,
  /your team has been/i, /touch grass/i,
  // More newsletters/marketing
  /spline team/i, /introducing.*by/i, /omega latin dance/i,
  /fastest switch/i, /more flow/i, /reminder: no classes/i,
  // Newsletter noise
  /what.s new in mermaid/i, /less cleanup.*more diagramming/i,
  /untitled ui/i,
  // Self-sent agent cron emails (cross-account robert@snappy.ai → personal)
  /requested picture of a horse/i, /pictures of horses/i,
  /raccoon picture/i, /browser skill execution/i,
  // AWS marketing (not security alerts)
  /limited.time.*try aws/i, /risk.free.*days/i,
  // AppFlowy / Starbucks / rewards / design newsletters
  /appflowy update/i, /free customization/i, /starbucks rewards/i,
  /shadcnblocks/i, /figma kit/i, /ux pilot/i, /adam fard/i,
  /thesys/i, /open sourcing.*rendering/i, /from promt to/i,
  /rian doris/i, /science behind momentum/i,
  /mermaid community/i, /officially open/i,
  // Microsoft rewards / Tella / marketing surveys
  /earn rewards points/i, /microsoft account.*rewards/i,
  /watch for free/i, /grant from tella/i,
  /is ready to download/i, /tech brains assemble/i, /ellie rofe/i,
  /welcome.*microsoft account/i, /your microsoft account is here/i,
  /mckinsey/i, /what does it take to achieve/i,
  /it.s been a while.*let.s catch up/i, /edward freidlin/i,
  /reptile.*plant.*expo/i, /exclusive ticket discount/i,
  /tell us more about your first month/i,
  /update on our pricing/i, /notification@hetzner/i,
  /getting started was the hard part/i, /shareholder communication/i,
  /vanguard funds/i, /vanguard.*important information/i,
  // CLEAR / ID.me / jewelry marketing
  /still want to hear from/i, /manage your.*benefits online/i,
  /valentine.s day gifts/i, /gifts under \$/i,
  // SaaS plan change / ToS notifications (FYI, not actionable)
  /upcoming updates to your.*plan/i, /new tos.*plans/i,
  // Lining up capacity / cold outreach patterns
  /lining up capacity/i,
  // API usage threshold (FYI notifications)
  /api usage.*reached.*threshold/i,
  // Statechange community notifications
  /statechange pro/i, /you.re confirmed for the scc/i,
];

export type ClassifiedItem = InboxItem & {
  classification: "noise" | "actionable" | "awaiting" | "fyi";
  /** Gmail message ID extracted from permalink for archive operations */
  gmail_msg_id?: string;
};

export function classifyItem(item: InboxItem): ClassifiedItem {
  const line = `${item.user_name} ${item.user_id} ${item.text}`;
  const senderDomain = (item.user_id || "").split("@")[1]?.toLowerCase() || "";
  const domainNoise = NOISE_DOMAINS.some(d => senderDomain === d || senderDomain.endsWith(`.${d}`));
  // Self-sent emails (same-account or cross-account robert@snappy.ai ↔ personal)
  const ROBERT_EMAILS = ["robert@snappy.ai", "robertjboulos@gmail.com"];
  const selfSent = item.source === "gmail" && ROBERT_EMAILS.includes((item.user_id || "").toLowerCase());
  const isNoise = domainNoise || selfSent || NOISE_PATTERNS.some(p => p.test(line));

  // Extract Gmail message ID from permalink
  let gmail_msg_id: string | undefined;
  if (item.source === "gmail" && item.permalink) {
    const match = item.permalink.match(/#inbox\/([a-f0-9]+)$/);
    if (match) gmail_msg_id = match[1];
  }

  // Conversation state: if Robert already replied, this is "awaiting" not "actionable"
  const awaiting = !isNoise && item.awaiting_reply === true;

  return {
    ...item,
    gmail_msg_id,
    classification: isNoise ? "noise" : awaiting ? "awaiting" : "actionable",
  };
}

export function classifyAll(items: InboxItem[]): { noise: ClassifiedItem[]; actionable: ClassifiedItem[]; awaiting: ClassifiedItem[] } {
  const noise: ClassifiedItem[] = [];
  const actionable: ClassifiedItem[] = [];
  const awaiting: ClassifiedItem[] = [];
  for (const item of items) {
    const c = classifyItem(item);
    if (c.classification === "noise") noise.push(c);
    else if (c.classification === "awaiting") awaiting.push(c);
    else actionable.push(c);
  }
  return { noise, actionable, awaiting };
}

// --- Inbox Zero orchestrator -------------------------------------------------

export type InboxZeroResult = {
  fetched: number;
  noise_archived: number;
  noise_failed: number;
  actionable: ClassifiedItem[];
  awaiting: ClassifiedItem[];
  slack_marked_read: number;
  errors: Record<string, string>;
  file: string;
};

/**
 * Full inbox zero: fetch → classify → archive noise → mark Slack read → return actionable.
 * Noise gets archived automatically. Actionable items are returned for Robert's judgment.
 */
export async function inboxZero(): Promise<InboxZeroResult> {
  // 1. Fetch everything
  const { items, errors, file } = await sweepAll();

  // 2. Classify
  const { noise, actionable, awaiting } = classifyAll(items);

  // 3. Archive Gmail noise
  let noise_archived = 0;
  let noise_failed = 0;
  const workNoiseIds = noise
    .filter(n => n.channel_id === "robert@snappy.ai" && n.gmail_msg_id)
    .map(n => n.gmail_msg_id!);
  const personalNoiseIds = noise
    .filter(n => n.channel_id === "robertjboulos@gmail.com" && n.gmail_msg_id)
    .map(n => n.gmail_msg_id!);

  if (workNoiseIds.length) {
    const ok = await batchArchiveGmail("robert@snappy.ai", workNoiseIds);
    noise_archived += ok;
    noise_failed += workNoiseIds.length - ok;
  }
  if (personalNoiseIds.length) {
    const ok = await batchArchiveGmail("robertjboulos@gmail.com", personalNoiseIds);
    noise_archived += ok;
    noise_failed += personalNoiseIds.length - ok;
  }

  // 4. Mark Slack channels as read (for noise items only — actionable stays unread)
  let slack_marked_read = 0;
  const slackNoiseByChannel = new Map<string, string>();
  for (const n of noise.filter(n => n.source === "slack")) {
    const existing = slackNoiseByChannel.get(n.channel_id);
    if (!existing || n.ts > existing) slackNoiseByChannel.set(n.channel_id, n.ts);
  }
  for (const [channel, ts] of slackNoiseByChannel) {
    try {
      await markSlackRead(channel, ts);
      slack_marked_read++;
    } catch { /* continue */ }
  }

  // 5. Write results
  const stamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 16);
  const zeroFile = join(OUT_DIR, `${stamp}-inbox-zero.json`);
  writeFileSync(zeroFile, JSON.stringify({
    fetched: items.length,
    noise_archived,
    noise_failed,
    actionable: actionable.length,
    actionable_items: actionable,
    awaiting: awaiting.length,
    awaiting_items: awaiting,
    noise_items: noise.map(n => `${n.user_name}: ${n.text}`),
  }, null, 2));

  return {
    fetched: items.length,
    noise_archived,
    noise_failed,
    actionable,
    awaiting,
    slack_marked_read,
    errors,
    file: zeroFile,
  };
}

// --- Skool reply (re-export from skool-fetcher) ------------------------------

export { sendSkoolReply } from "./skool-fetcher.ts";

// --- Sweep orchestrator ------------------------------------------------------

type FetcherResult = { source: string; items: InboxItem[]; error?: string };

async function runFetcher(source: string, fn: () => Promise<InboxItem[]>): Promise<FetcherResult> {
  try {
    return { source, items: await fn() };
  } catch (e: any) {
    return { source, items: [], error: e.message };
  }
}

export async function sweepAll(): Promise<{ items: InboxItem[]; errors: Record<string, string>; file: string }> {
  // Lazy-import browser-based fetchers to avoid pulling in heavy deps when not needed
  const { fetchLinkedInDMs } = await import("./linkedin-fetcher.ts");
  const { fetchSkoolNotifications } = await import("./skool-fetcher.ts");
  // sendSkoolReply also exported from skool-fetcher.ts but not used in sweep

  const results = await Promise.all([
    runFetcher("slack", fetchSlackUnread),
    runFetcher("gmail-work", () => fetchGmailUnread("robert@snappy.ai")),
    runFetcher("gmail-personal", () => fetchGmailUnread("robertjboulos@gmail.com")),
    runFetcher("linkedin", fetchLinkedInDMs),
    runFetcher("skool", fetchSkoolNotifications),
    // linkedin, skool, statechange — pending per-channel fetchers
  ]);

  const items = results.flatMap((r) => r.items);
  const errors: Record<string, string> = {};
  for (const r of results) if (r.error) errors[r.source] = r.error;

  mkdirSync(OUT_DIR, { recursive: true });
  const stamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 16);
  const file = join(OUT_DIR, `${stamp}-inbox.json`);
  writeFileSync(file, JSON.stringify({ items, errors, stamp }, null, 2));

  return { items, errors, file };
}

// --- CLI ---------------------------------------------------------------------

if ((() => { try { return import.meta.url === `file://${realpathSync(process.argv[1])}`; } catch { return false; } })()) {
  const [, , cmd, ...args] = process.argv;
  (async () => {
    if (!cmd || cmd === "help") {
      console.log(`snappy-inbox-sweep CLI
  inbox-zero                     Full inbox zero: fetch, archive noise, return actionable
  sweep                          Run all ready fetchers, write out/<stamp>-inbox.json
  slack                          Fetch Slack unread only
  gmail-work                     Fetch Gmail unread (robert@snappy.ai)
  gmail-personal                 Fetch Gmail unread (robertjboulos@gmail.com)
  send-slack <channel> <text>    Send a Slack reply (thread_ts via SLACK_THREAD_TS env)
  send-skool <post-url> <text>   Post a reply to a Skool post via browser automation
  help                           This message`);
      process.exit(0);
    }
    if (cmd === "sweep") {
      const r = await sweepAll();
      console.log(JSON.stringify(r, null, 2));
      process.exit(0);
    }
    if (cmd === "inbox-zero") {
      const r = await inboxZero();
      console.log(`\n=== INBOX ZERO ===`);
      console.log(`Fetched: ${r.fetched} items`);
      console.log(`Noise archived: ${r.noise_archived}${r.noise_failed ? ` (${r.noise_failed} failed)` : ""}`);
      console.log(`Slack marked read: ${r.slack_marked_read}`);
      if (Object.keys(r.errors).length) console.log(`Errors: ${JSON.stringify(r.errors)}`);
      console.log(`\nActionable (${r.actionable.length}):`);
      for (const a of r.actionable) {
        console.log(`  [${a.source}] ${a.user_name}: ${a.text}`);
      }
      if (r.awaiting.length) {
        console.log(`\nAwaiting reply (${r.awaiting.length}):`);
        for (const a of r.awaiting) {
          console.log(`  [${a.source}] ${a.user_name}: ${a.text}`);
        }
      }
      console.log(`\nResults: ${r.file}`);
      process.exit(0);
    }
    if (cmd === "slack") {
      const items = await fetchSlackUnread();
      console.log(JSON.stringify(items, null, 2));
      process.exit(0);
    }
    if (cmd === "gmail-work") {
      const items = await fetchGmailUnread("robert@snappy.ai");
      console.log(JSON.stringify(items, null, 2));
      process.exit(0);
    }
    if (cmd === "gmail-personal") {
      const items = await fetchGmailUnread("robertjboulos@gmail.com");
      console.log(JSON.stringify(items, null, 2));
      process.exit(0);
    }
    if (cmd === "send-slack") {
      const [channel, ...rest] = args;
      const text = rest.join(" ");
      const r = await sendSlackReply(channel, text, process.env.SLACK_THREAD_TS);
      console.log(JSON.stringify(r, null, 2));
      process.exit(0);
    }
    if (cmd === "send-skool") {
      const [postUrl, ...rest] = args;
      const text = rest.join(" ");
      if (!postUrl || !text) { console.error("Usage: api.ts send-skool <post-url> <text>"); process.exit(1); }
      const { sendSkoolReply: sendSkool } = await import("./skool-fetcher.ts");
      const r = await sendSkool(postUrl, text);
      console.log(JSON.stringify(r, null, 2));
      if (!r.success) process.exit(1);
      process.exit(0);
    }
    console.error(`Unknown command: ${cmd}`);
    process.exit(1);
  })().catch((e) => {
    console.error(e);
    process.exit(1);
  });
}

scripts- helper scripts it can run

prose-only skill - 1 inline code block live in SKILL.md above (no state/bin/ sidecar yet).

how we check it- the checks, plus the last 10 runs

rubric shape schema-shape check (no inline rubric)
recent mean 1.00 · 10 runs actor/auditor: unverifiable
deps sweep
timestamp verb score primary_issue artifact
2026-05-03 16:00Z - 1.00 - -
2026-05-03 14:00Z - 1.00 - -
2026-05-03 12:00Z - 1.00 - -
2026-05-03 10:00Z - 1.00 - -
2026-05-03 08:00Z - 1.00 - -
2026-05-03 06:00Z - 1.00 - -
2026-05-03 04:00Z - 1.00 - -
2026-05-03 02:00Z - 1.00 - -
2026-05-03 00:00Z - 1.00 - -
2026-05-02 22:00Z - 1.00 - -