Skip to content

Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.

fix(ops-inbox): scan the whole inbox, and split archive from keep in code (#806)

Aurora Capital9f98c267aee6
diff --git a/claude-ops/bin/ops-inbox-archive-set b/claude-ops/bin/ops-inbox-archive-set
new file mode 100755
index 00000000..5ec7254f
--- /dev/null
+++ b/claude-ops/bin/ops-inbox-archive-set
@@ -0,0 +1,457 @@
+#!/usr/bin/env python3
+# ops-inbox-archive-set - turn an ops-inbox-scan result into an explicit
+# ARCHIVE / KEEP split, then (only with --apply) archive the ARCHIVE half.
+#
+# WHY: ops-inbox-scan tells you what the inbox looks like, but the "inbox zero"
+# half of /ops:ops-inbox was still done by hand every run - eyeballing a few
+# hundred rows to decide which are courtesy tails ("thanks!", "will do!!") and
+# which carry a real open ask. That judgement is mechanical and was being redone,
+# inconsistently, from scratch each session. This script makes it deterministic,
+# reviewable, and above all report-only until a human says otherwise.
+#
+# THE SPLIT:
+# ARCHIVE - newsletters/broadcasts, WAITING (you sent last), courtesy tails
+# with no open ask, bare media with no caption, threads past the
+# stale window, and long-dead group chats.
+# KEEP - anything with a genuine unanswered ask, plus every email carrying
+# one of the user's todo/action labels.
+#
+# GUARDRAIL (hard, non-negotiable): an email labelled with a todo/action label
+# (Respond, Action, Reply, Follow up, Awaiting Reply, To-do, Task, URGENT, ...)
+# is an open task the user is tracking. It is NEVER archived, however much it
+# looks like a newsletter. "Actioned" is a completion label and does not protect.
+# Keeping something is always the safe direction and archiving is the risky one,
+# so every ambiguous case resolves to KEEP.
+#
+# READ-ONLY BY DEFAULT. Without --apply this writes nothing and archives nothing;
+# it only prints the proposed split. --apply is meant to be run only after a
+# human has seen the exact counts and a sample. It never sends a message.
+#
+# PYTHON: standard library only, and deliberately kept 3.9-compatible - plugin
+# scripts get run by whatever `python3` resolves to, which on macOS is Xcode's
+# 3.9. No datetime.UTC, no `X | None` annotations.
+#
+# USAGE
+# ops-inbox-archive-set # runs ops-inbox-scan itself
+# ops-inbox-scan | ops-inbox-archive-set - # read a scan from stdin
+# ops-inbox-archive-set --scan /tmp/scan.json
+# ops-inbox-archive-set --wa-store <db> --bridge-port 8082 # extra account
+# ops-inbox-archive-set --json # machine-readable split
+# ops-inbox-archive-set --apply # archive, AFTER approval
+
+import argparse
+import json
+import os
+import re
+import sqlite3
+import subprocess
+import sys
+
+# --------------------------------------------------------------------------
+# email label guardrail
+# --------------------------------------------------------------------------
+
+SYSTEM_LABELS = set("INBOX SENT DRAFT UNREAD IMPORTANT STARRED TRASH SPAM".split())
+
+PROTECTED_TERMS = (
+ "to-do", "todo", "task", "tasklet", "action", "respond", "reply",
+ "follow up", "followup", "reply later", "needs action", "awaiting reply",
+ "timed action", "urgent",
+)
+
+
+def protecting_label(labels):
+ """Return the todo/action label protecting this message, or None."""
+ for raw in labels or []:
+ if raw in SYSTEM_LABELS or raw.startswith("CATEGORY_"):
+ continue
+ name = raw.lower().replace("_", " ").strip()
+ if "actioned" in name: # completion marker, not an open todo
+ continue
+ for term in PROTECTED_TERMS:
+ if term in name:
+ return raw
+ return None
+
+
+# --------------------------------------------------------------------------
+# "is this just a courtesy tail?" heuristic
+# --------------------------------------------------------------------------
+
+# Matched as a WORD SET, not a regex. The obvious spelling of this - one big
+# alternation wrapped in (...)* - is a ReDoS: the branches overlap (ok / oke /
+# oké, and \W swallowing anything), so a long non-matching message backtracks
+# exponentially and hangs the scan on attacker- or accident-supplied text.
+# Splitting into words and testing set membership is linear and easier to read.
+ACK_WORDS = frozenset("""
+ok oke okay oké okey top thanks thank thanx thx ty dank dankje dankjewel
+danku bedankt graag gedaan great nice cool perfect awesome amazing super
+mooi goed prima fijn leuk top yes ja jazeker yep yup sure will do sounds
+good got it see you tot dan straks congrats gefeliciteerd welcome no
+worries np haha hahaha lol bro man brother mate dude thx you u de het je
+""".split())
+
+# Letters only: drops punctuation, digits and emoji so "Thanks bro! ❤️" is a
+# plain two-word ack.
+WORD_RE = re.compile(r"[^\W\d_]+", re.UNICODE)
+
+# Signals a real ask even inside a short message.
+ASK_RE = re.compile(
+ r"\?|\b(kun|kan|could|can|would|will|please|graag|laat.*weten|let me know|"
+ r"need|nodig|wanneer|when|hoe|how|wat|what|waarom|why|stuur|send|call|bel)\b",
+ re.IGNORECASE)
+
+
+# A placeholder and nothing else: "[image]", "[voice]", "[document]". The
+# bridge writes these for media it has not enriched or transcribed yet.
+BARE_MEDIA_RE = re.compile(
+ r"^\[\s*(voice|audio|image|photo|video|gif|sticker|document|file)\s*\]$",
+ re.IGNORECASE)
+
+
+def is_courtesy_tail(text, media_type=None):
+ """True when the last inbound message closes the thread rather than opening one.
+
+ Undescribed media is never a tail. A bare "[image]" does not mean the
+ message was empty, it means nobody has read it yet - and the photo may be
+ an invoice, a signed page, or a question written on paper. Enrichment fills
+ these in as "[image] <description>"; until it does, the only safe reading
+ is "unknown", which keeps the thread. An enriched body classifies on its
+ description like any other text.
+ """
+ body = (text or "").strip()
+ if BARE_MEDIA_RE.match(body):
+ return False
+ if media_type and not body:
+ return False # media row the enricher has not reached yet
+ if not body:
+ return True # genuinely nothing inbound to answer
+ if ASK_RE.search(body):
+ return False
+ words = WORD_RE.findall(body.lower())
+ if words and len(body) <= 60 and all(w in ACK_WORDS for w in words):
+ return True
+ # Very short and not a question: nothing to answer.
+ if len(body) <= 25:
+ return True
+ return False
+
+
+def last_inbound_text(record):
+ inbound = [p for p in (record.get("preview") or []) if not p.get("from_me")]
+ if not inbound:
+ return ""
+ return inbound[-1].get("text") or ""
+
+
+# --------------------------------------------------------------------------
+# scan input
+# --------------------------------------------------------------------------
+
+def load_scan(args, plugin_root):
+ if args.scan == "-":
+ return json.load(sys.stdin)
+ if args.scan:
+ with open(args.scan) as fh:
+ return json.load(fh)
+ scan_bin = os.path.join(plugin_root, "bin", "ops-inbox-scan")
+ if not os.path.exists(scan_bin):
+ sys.exit("ops-inbox-archive-set: cannot find ops-inbox-scan; pass --scan")
+ out = subprocess.run([scan_bin], capture_output=True, text=True)
+ if out.returncode != 0 or not out.stdout.strip():
+ sys.exit("ops-inbox-archive-set: ops-inbox-scan failed: %s"
+ % (out.stderr or "")[-400:])
+ return json.loads(out.stdout)
+
+
+# --------------------------------------------------------------------------
+# classification
+# --------------------------------------------------------------------------
+
+def classify_whatsapp(scan, stale_min, dead_group_min):
+ archive, keep, fyi = [], [], []
+ wa = scan.get("whatsapp", {})
+
+ for rec in wa.get("needs_reply", []):
+ age = rec.get("age_min") or 0
+ row = {"who": rec.get("who"), "jid": rec.get("jid"),
+ "alt_jids": rec.get("alt_jids") or [], "account": "default"}
+ if age > stale_min:
+ row["why"] = "stale (older than window)"
+ archive.append(row)
+ elif is_courtesy_tail(last_inbound_text(rec)):
+ row["why"] = "courtesy tail / no open ask"
+ archive.append(row)
+ else:
+ row["age_min"] = age
+ row["last"] = last_inbound_text(rec)[:140]
+ keep.append(row)
+
+ for rec in wa.get("waiting", []):
+ archive.append({"who": rec.get("who"), "jid": rec.get("jid"),
+ "alt_jids": rec.get("alt_jids") or [], "account": "default",
+ "why": "WAITING (you sent last)"})
+
+ for rec in wa.get("fyi", []):
+ fyi.append({"who": rec.get("who"), "jid": rec.get("jid"),
+ "alt_jids": [], "account": "default",
+ "why": rec.get("reason") or "newsletter/broadcast"})
+
+ for rec in wa.get("groups", []):
+ if (rec.get("age_min") or 0) > dead_group_min:
+ archive.append({"who": rec.get("who"), "jid": rec.get("jid"),
+ "alt_jids": [], "account": "default",
+ "why": "dead group chat"})
+ return archive, keep, fyi
+
+
+def classify_store(path, label, stale_min):
+ """Same split for an extra WhatsApp account, read straight from its store.
+
+ Working set is `archived=0` - the full inbox, not a recency slice.
+ """
+ archive, keep, error = [], [], None
+ try:
+ con = sqlite3.connect("file:%s?mode=ro" % path, uri=True)
+ chats = con.execute(
+ "SELECT jid, COALESCE(NULLIF(name,''), jid), last_message_time "
+ "FROM chats WHERE COALESCE(archived,0)=0 "
+ "ORDER BY last_message_time DESC").fetchall()
+ for jid, name, _ in chats:
+ row = {"who": name, "jid": jid, "alt_jids": [], "account": label}
+ if jid.endswith("@newsletter") or jid == "status@broadcast":
+ row["why"] = "newsletter/broadcast"
+ archive.append(row)
+ continue
+ # media_type matters: an un-enriched media row has empty content
+ # but is NOT an empty message, and must not be archived unread.
+ last = con.execute(
+ "SELECT is_from_me, COALESCE(content,''), COALESCE(media_type,'') "
+ "FROM messages WHERE chat_jid=? "
+ "ORDER BY timestamp DESC LIMIT 1", (jid,)).fetchone()
+ if last is None:
+ row["why"] = "empty chat"
+ archive.append(row)
+ continue
+ from_me, body, media_type = last
+ if from_me:
+ row["why"] = "WAITING (you sent last)"
+ archive.append(row)
+ elif is_courtesy_tail(body, media_type):
+ row["why"] = "courtesy tail / no open ask"
+ archive.append(row)
+ else:
+ row["last"] = body[:140] or ("[%s, not yet enriched]" % media_type)
+ keep.append(row)
+ con.close()
+ except Exception as exc: # noqa: BLE001 - report, never crash
+ error = str(exc)
+ return archive, keep, error
+
+
+def classify_email(scan):
+ """FYI mail is NEVER auto-archived: it becomes a review list, not an archive
+ set. A run of "FYI" recently held a Docusign contract, a private-bank
+ document, a failed payment and four ACTION REQUIRED notices - a bucket that
+ can contain those is a bucket a human reads before anything is swept."""
+ fyi, kept = [], []
+ for item in scan.get("email", {}).get("fyi", []):
+ label = protecting_label(item.get("labels"))
+ row = {"who": item.get("who"), "subject": item.get("subject"),
+ "threadId": item.get("threadId")}
+ if label:
+ row["protected_by"] = label
+ kept.append(row)
+ else:
+ fyi.append(row)
+ return fyi, kept
+
+
+# --------------------------------------------------------------------------
+# apply
+# --------------------------------------------------------------------------
+
+def archive_whatsapp(rows, port, dry):
+ import urllib.request
+ ok = fail = 0
+ for row in rows:
+ for jid in [row.get("jid")] + list(row.get("alt_jids") or []):
+ if not jid:
+ continue
+ if dry:
+ ok += 1
+ continue
+ body = json.dumps({"chat_jid": jid, "archive": True}).encode()
+ req = urllib.request.Request(
+ "http://127.0.0.1:%d/api/archive" % port, data=body,
+ headers={"Content-Type": "application/json"})
+ try:
+ urllib.request.urlopen(req, timeout=20).read()
+ ok += 1
+ except Exception as exc: # noqa: BLE001
+ fail += 1
+ print(" archive failed %s: %s" % (jid, exc), file=sys.stderr)
+ return ok, fail
+
+
+def archive_email(rows, account, dry):
+ ids = [r["threadId"] for r in rows if r.get("threadId")]
+ if not ids or dry:
+ return len(ids), 0
+ # The scan hands us thread IDs, and `gog gmail archive` treats bare
+ # arguments as MESSAGE ids unless --thread is given. Without it the call
+ # either errors or archives the wrong thing.
+ cmd = ["gog", "gmail", "archive"]
+ if account:
+ cmd += ["-a", account]
+ cmd += ids + ["--thread", "--force", "--no-input"]
+ res = subprocess.run(cmd, capture_output=True, text=True)
+ if res.returncode != 0:
+ print(" gmail archive failed: %s" % (res.stderr or "")[-300:], file=sys.stderr)
+ return 0, len(ids)
+ return len(ids), 0
+
+
+# --------------------------------------------------------------------------
+
+def main():
+ ap = argparse.ArgumentParser(
+ description="Split an ops-inbox-scan into ARCHIVE / KEEP. Report-only "
+ "unless --apply is given.")
+ # Both spellings write the same dest. The positional MUST default to
+ # SUPPRESS: with nargs="?" an absent positional otherwise writes its default
+ # over a value already parsed from --scan, which silently made the tool
+ # re-run a live scan instead of reading the file it was handed.
+ ap.add_argument("scan", nargs="?", default=argparse.SUPPRESS,
+ help="path to a scan JSON, or '-' for stdin "
+ "(default: run ops-inbox-scan)")
+ ap.add_argument("--scan", dest="scan", default=None, help=argparse.SUPPRESS)
+ ap.add_argument("--wa-store", action="append", default=[], metavar="DB",
+ help="extra WhatsApp account store (repeatable)")
+ ap.add_argument("--bridge-port", action="append", default=[], type=int,
+ help="bridge port for the matching --wa-store (repeatable)")
+ ap.add_argument("--default-bridge-port", type=int, default=8080)
+ ap.add_argument("--stale-days", type=int, default=7)
+ ap.add_argument("--dead-group-days", type=int, default=30)
+ ap.add_argument("--gmail-account", default=os.environ.get("GMAIL_ACCOUNT"))
+ ap.add_argument("--json", action="store_true", help="emit JSON only")
+ ap.add_argument("--apply", action="store_true",
+ help="actually archive (only after human approval)")
+ ap.add_argument("--archive-fyi", action="store_true",
+ help="include the FYI review list in the sweep. Only pass "
+ "this after the user has read the FYI briefing and "
+ "asked for a mass archive.")
+ ap.add_argument("--dry-run", action="store_true",
+ help="with --apply, go through the motions without calling out")
+ args = ap.parse_args()
+ args.scan = getattr(args, "scan", None)
+
+ plugin_root = os.environ.get(
+ "CLAUDE_PLUGIN_ROOT",
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+ scan = load_scan(args, plugin_root)
+ stale_min = args.stale_days * 24 * 60
+ dead_min = args.dead_group_days * 24 * 60
+
+ wa_archive, wa_keep, wa_fyi = classify_whatsapp(scan, stale_min, dead_min)
+ em_fyi, em_kept = classify_email(scan)
+
+ # FYI is a REVIEW list, never part of the default sweep. It only joins the
+ # archive set when the user has seen the briefing and explicitly opted in.
+ em_archive = em_fyi if args.archive_fyi else []
+ if args.archive_fyi:
+ wa_archive = wa_archive + wa_fyi
+
+ extra, errors = [], []
+ for idx, store in enumerate(args.wa_store):
+ label = os.path.basename(os.path.dirname(os.path.dirname(store))) or "extra%d" % idx
+ arch, keep, err = classify_store(store, label, stale_min)
+ port = args.bridge_port[idx] if idx < len(args.bridge_port) else None
+ extra.append({"label": label, "port": port, "archive": arch, "keep": keep})
+ if err:
+ errors.append("%s: %s" % (label, err))
+
+ result = {
+ "archive": {
+ "whatsapp_default": wa_archive,
+ "whatsapp_extra": [{"account": e["label"], "chats": e["archive"]} for e in extra],
+ "email": em_archive,
+ },
+ "keep": {
+ "whatsapp_default": wa_keep,
+ "whatsapp_extra": [{"account": e["label"], "chats": e["keep"]} for e in extra],
+ "email_protected": em_kept,
+ },
+ # Read these, brief the user on them, THEN ask about a mass archive.
+ "review_fyi": {"email": em_fyi, "whatsapp": wa_fyi},
+ "counts": {
+ "archive_whatsapp": len(wa_archive) + sum(len(e["archive"]) for e in extra),
+ "archive_email": len(em_archive),
+ "keep_whatsapp": len(wa_keep) + sum(len(e["keep"]) for e in extra),
+ "keep_email_protected": len(em_kept),
+ "review_fyi_email": len(em_fyi),
+ "review_fyi_whatsapp": len(wa_fyi),
+ },
+ "errors": errors,
+ "applied": False,
+ }
+
+ if args.apply:
+ ok, fail = archive_whatsapp(wa_archive, args.default_bridge_port, args.dry_run)
+ for e in extra:
+ if e["port"] is None:
+ errors.append("%s: no --bridge-port given, chats left alone" % e["label"])
+ continue
+ o2, f2 = archive_whatsapp(e["archive"], e["port"], args.dry_run)
+ ok += o2
+ fail += f2
+ eok, efail = archive_email(em_archive, args.gmail_account, args.dry_run)
+ result["applied"] = True
+ result["apply_result"] = {"whatsapp_ok": ok, "whatsapp_failed": fail,
+ "email_ok": eok, "email_failed": efail,
+ "dry_run": args.dry_run}
+
+ if args.json:
+ print(json.dumps(result, indent=1))
+ return
+
+ c = result["counts"]
+ print("PROPOSED ARCHIVE whatsapp=%d email=%d"
+ % (c["archive_whatsapp"], c["archive_email"]))
+ print("KEEP whatsapp=%d email(protected)=%d"
+ % (c["keep_whatsapp"], c["keep_email_protected"]))
+ if errors:
+ print("ERRORS: " + "; ".join(errors))
+ print("\n--- KEEP: WhatsApp, genuine open ask ---")
+ for row in sorted(wa_keep, key=lambda r: r.get("age_min") or 0):
+ print(" %-26s %s" % ((row.get("who") or "?")[:26],
+ (row.get("last") or "")[:78].replace("\n", " ")))
+ for e in extra:
+ for row in e["keep"]:
+ print(" [%s] %-20s %s" % (e["label"][:10], str(row.get("who"))[:20],
+ (row.get("last") or "")[:60].replace("\n", " ")))
+ if em_kept:
+ print("\n--- KEEP: email held by a todo/action label ---")
+ for row in em_kept:
+ print(" [%s] %s" % (row["protected_by"], (row.get("subject") or "")[:66]))
+ if (em_fyi or wa_fyi) and not args.archive_fyi:
+ print("\n--- FYI: read + brief the user, then ask about a mass archive "
+ "(%d email, %d whatsapp) ---" % (len(em_fyi), len(wa_fyi)))
+ for row in em_fyi:
+ print(" %-32s %s" % (str(row.get("who"))[:32],
+ (row.get("subject") or "")[:60]))
+ for row in wa_fyi:
+ print(" %-32s %s" % (str(row.get("who"))[:32], row.get("why")))
+ print(" NOT archived. Pass --archive-fyi only after the user asks.")
+ if result["applied"]:
+ r = result["apply_result"]
+ print("\nARCHIVED whatsapp ok=%d failed=%d email ok=%d failed=%d%s"
+ % (r["whatsapp_ok"], r["whatsapp_failed"], r["email_ok"],
+ r["email_failed"], " (dry run)" if r["dry_run"] else ""))
+ else:
+ print("\nReport only. Nothing was archived. Re-run with --apply after approval.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/claude-ops/bin/ops-inbox-scan b/claude-ops/bin/ops-inbox-scan
index 4e0aa157..b93e7909 100755
--- a/claude-ops/bin/ops-inbox-scan
+++ b/claude-ops/bin/ops-inbox-scan
@@ -24,9 +24,17 @@
# READ-ONLY: opens every sqlite db in immutable/read-only mode; never sends,
# archives, or mutates anything. All sending stays in the skill under Rule 6.
#
+# FULL INBOX, ALWAYS. Both channels scan everything that is not archived, never
+# just the unread. WhatsApp's working set is `archived=0`; email's is `in:inbox`.
+# Neither is sliced by a recency window, because an unanswered ask from three
+# weeks ago is still an unanswered ask. --days sizes only the WhatsApp send-log
+# lookback used for reconciliation; it never hides a chat or a mail.
+#
# FLAGS:
# --whatsapp-only / --email-only limit to one channel
-# --days N recency window (default 7)
+# --days N send-log lookback, in days (default 7)
+# --email-query Q Gmail working set (default "in:inbox")
+# --email-max N max Gmail results (default 400)
# --gmail-account ADDR override Gmail account (default: gog default)
# --pretty pretty-print JSON
set -euo pipefail
@@ -36,12 +44,16 @@ DO_WA=1
DO_EMAIL=1
GMAIL_ACCOUNT="${GMAIL_ACCOUNT:-}"
PRETTY=0
+EMAIL_QUERY="in:inbox"
+EMAIL_MAX=400
while [ $# -gt 0 ]; do
case "$1" in
--whatsapp-only) DO_EMAIL=0 ;;
--email-only) DO_WA=0 ;;
--days) DAYS="${2:-7}"; shift ;;
+ --email-query) EMAIL_QUERY="${2:-in:inbox}"; shift ;;
+ --email-max) EMAIL_MAX="${2:-400}"; shift ;;
--gmail-account) GMAIL_ACCOUNT="${2:-}"; shift ;;
--pretty) PRETTY=1 ;;
-h|--help)
@@ -131,8 +143,15 @@ if [ "$DO_EMAIL" = 1 ]; then
trap 'rm -f "$GMAIL_JSON_FILE" "${OIS_SENDLOG_FILE:-}"' EXIT
ACCT_ARGS=()
[ -n "$GMAIL_ACCOUNT" ] && ACCT_ARGS=(-a "$GMAIL_ACCOUNT")
+ # FULL INBOX, always. The working set is "not archived" -- i.e. everything
+ # still carrying the INBOX label -- never "unread", and never a recency slice.
+ # This used to be `in:inbox newer_than:${DAYS}d --max 30`, which silently hid
+ # every unanswered thread older than the window or past the 30th result, so a
+ # mail you never replied to just aged out of the scan. --days now only sizes
+ # the WhatsApp send-log lookback; it does not filter the mailbox. Narrow the
+ # mailbox deliberately with --email-query if you ever need to.
if ! gog gmail search "${ACCT_ARGS[@]}" -j --results-only --no-input \
- --max 30 "in:inbox newer_than:${DAYS}d" >"$GMAIL_JSON_FILE" 2>"${GMAIL_JSON_FILE}.err"; then
+ --max "$EMAIL_MAX" "$EMAIL_QUERY" >"$GMAIL_JSON_FILE" 2>"${GMAIL_JSON_FILE}.err"; then
GMAIL_ERR="$(head -c 400 "${GMAIL_JSON_FILE}.err" 2>/dev/null | tr '\n' ' ')"
: >"$GMAIL_JSON_FILE" # blank => unreachable
fi
diff --git a/claude-ops/skills/ops-inbox/SKILL.md b/claude-ops/skills/ops-inbox/SKILL.md
index 36385ab7..0b96ebe8 100644
--- a/claude-ops/skills/ops-inbox/SKILL.md
+++ b/claude-ops/skills/ops-inbox/SKILL.md
@@ -337,6 +337,40 @@ JSON. No subagents, no MCP, near-zero tokens.
"$CLAUDE_PLUGIN_ROOT/bin/ops-inbox-scan" --days 14 # wider window
```
+**ARCHIVE/KEEP SPLIT — `bin/ops-inbox-archive-set`.** The scan says what the
+inbox looks like; this turns that into the two lists inbox-zero actually needs,
+deterministically, instead of re-deciding a few hundred rows by eye every run:
+
+```bash
+"$CLAUDE_PLUGIN_ROOT/bin/ops-inbox-archive-set" # report only
+"$CLAUDE_PLUGIN_ROOT/bin/ops-inbox-scan" | \
+ "$CLAUDE_PLUGIN_ROOT/bin/ops-inbox-archive-set" - # reuse a scan
+"$CLAUDE_PLUGIN_ROOT/bin/ops-inbox-archive-set" --scan /tmp/scan.json --json
+# extra WhatsApp account (repeat the pair per account):
+"$CLAUDE_PLUGIN_ROOT/bin/ops-inbox-archive-set" \
+ --wa-store ~/.local/share/whatsapp-mcp/whatsapp-bridge-us/store/messages.db \
+ --bridge-port 8082
+"$CLAUDE_PLUGIN_ROOT/bin/ops-inbox-archive-set" --apply # AFTER approval
+```
+
+- **ARCHIVE** — WAITING (you sent last), courtesy tails with no open ask
+ ("thanks!", "will do!!"), threads past `--stale-days` (7), dead groups past
+ `--dead-group-days` (30).
+- **REVIEW (FYI)** — newsletters, broadcasts, automated mail. **Never swept.**
+ Read it, brief the user, then ask; `--archive-fyi` is the opt-in that answer
+ unlocks. See the FYI core principle below.
+- Undescribed media (`[image]`, `[voice]` with no enrichment yet) is **unknown**,
+ never a tail — it always lands in KEEP.
+- **KEEP** — every genuine unanswered ask, plus every email carrying a
+ todo/action label. Ambiguity always resolves to KEEP; keeping is safe,
+ archiving is the risky direction.
+- **Report-only by default.** It archives nothing without `--apply`, and never
+ sends. Present the counts plus the KEEP list with `AskUserQuestion`, and only
+ re-run with `--apply` after an explicit OK. `--apply --dry-run` walks the path
+ without calling out.
+- It enforces the todo/action-label HARD GUARDRAIL in code, so a labelled mail
+ cannot be swept even when it looks exactly like a newsletter.
+
**ONE-SHOT TRIAGE (Sam 2026-07-21):** `bin/ops-inbox-zero` attempts the inbox-zero
pipeline (scan → Paperclip SSOT → Slack direct API → dual-JID deep-read → proposed WA/email
archive actions → KEEP report) in one shell call. Gmail, Slack, or Paperclip can be skipped
@@ -680,9 +714,122 @@ All channel credentials come from env vars or CLI auth — no hardcoded secrets.
Surface the appropriate tier to the user when archive blocks; don't abandon inbox-zero.
-## Core principle: FULL INBOX SCAN
-
-Do NOT just check unread. Scan the FULL recent inbox for each channel and classify every conversation:
+## Core principle: FULL INBOX SCAN (the working set is "not archived", not "unread")
+
+Do NOT just check unread. Unread is a display state the user may have already
+cleared by glancing at a phone; it says nothing about whether a thread is
+answered. The working set per channel is defined by what is still IN the inbox:
+
+| Channel | Working set | NOT the working set |
+|---|---|---|
+| WhatsApp (every account) | every chat where `archived` is not true — `chats.archived=0`, all ages | unread count, a 7-day slice |
+| Email | everything still carrying the `INBOX` label — `gog gmail search "in:inbox"` | `is:unread`, `newer_than:Nd`, a low `--max` |
+| Slack | every **unread** DM/channel/thread that has **not been replied to** | unreads already answered (see below) |
+| iMessage / Telegram / Discord / Notion | every allowlisted or configured conversation with recent activity | unread badge only |
+
+**Slack is the deliberate exception.** Slack has no archive, and its channel
+volume makes "everything not archived" meaningless, so there the working set is
+*unread and unreplied*: read the unread DMs, group DMs, channels, and every
+thread with unread replies, then drop the ones the user already answered (their
+own Slack user id posted after the last inbound). What survives is the Slack
+NEEDS_REPLY set. An unread that the user already replied to is HANDLED.
+
+**No recency cutoff anywhere.** An unanswered ask from three weeks ago is still
+an unanswered ask. Recency orders the list; it never filters it. `ops-inbox-scan
+--days N` sizes only the WhatsApp send-log reconciliation lookback — it does not
+hide a chat or a mail.
+
+Classify every conversation in that working set:
+
+## Core principle: FYI IS NEVER AUTO-ARCHIVED — READ IT, BRIEF IT, THEN ASK
+
+FYI is the bucket that looks like noise and is not. One real run of "FYI"
+contained a Docusign contract awaiting signature, a private-bank document, a
+failed €85.90 payment, a GitHub secret-risk assessment, a hotel proposal, and
+four `ACTION REQUIRED` data-retention notices. Sweeping that bucket because the
+senders are automated is how a run loses something that mattered.
+
+So FYI never enters the sweep by itself. The flow is fixed:
+
+1. **Never auto-archive it.** FYI is a REVIEW list, not an archive set.
+ `ops-inbox-archive-set` keeps it out of `--apply` entirely; it only joins the
+ sweep under the explicit `--archive-fyi` opt-in.
+2. **Read it.** Actually open the FYI items — subject and sender are not enough
+ to tell a newsletter from a payment failure.
+3. **Brief the user.** Summarise the FYI set in one compact briefing, grouped by
+ what it means for them, and call out anything that is secretly actionable
+ (money, contracts, legal, security, deadlines, account/data loss) as its own
+ line. The briefing IS the deliverable — the user should not have to open
+ Gmail to know what was in there.
+4. **Then ask.** One `AskUserQuestion`: mass-archive everything in the briefing,
+ archive all but the flagged items, or leave it. Only on approval re-run with
+ `--archive-fyi`.
+
+**This is DEFAULT behaviour on every run, and the user never sees a flag.**
+A bare `/ops:ops-inbox` does all four steps by itself — the user does not opt in,
+ask for a briefing, or know that `--archive-fyi` exists. Flags are how the agent
+drives the script; they are never mentioned to the user, never required from the
+user, and never offered as a choice. Phrase the question in plain language
+("Archive these 26?"), never as a flag or a command. The same goes for every
+other option in this skill: the user asks for their inbox, and everything else
+is the agent's job.
+
+**Anything actionable found while reading stops being FYI** — promote it to
+NEEDS_REPLY or a USER-OWES reminder and keep it in the inbox regardless of what
+the mass-archive answer is.
+
+## Core principle: ARCHIVE/MARK-READ COMMANDS MUST BE VALID FOR THE CHANNEL
+
+Every archive or mark-read call must be one the channel's own tooling actually
+accepts. A call that silently no-ops leaves the inbox dirty while the run
+reports success. Verified surfaces, per channel:
+
+| Channel | Archive | Mark read | Notes |
+|---|---|---|---|
+| WhatsApp | `mcp__<server>__archive_chat {chat_jid, archive:true}`, or `POST http://127.0.0.1:<port>/api/archive` `{"chat_jid","archive":true}` | `mcp__<server>__mark_read` | `<server>` is the REAL server name. Single-account installs have `mcp__whatsapp__*`; multi-account installs have **one server per account** (`whatsapp-nl`, `whatsapp-us`, …) **and no plain `mcp__whatsapp__*` at all**. Resolve the name from the live tool list before the first call, and archive on **each** account's own port. Archive every JID the person owns — phone **and** every `@lid` in `alt_jids`. |
+| Email | `gog gmail archive <messageId> … --force --no-input`; for THREAD ids you MUST add `--thread` | `gog gmail mark-read <messageId> … --no-input` | Bare arguments are message ids. `ops-inbox-scan` emits **thread** ids, so `--thread` is required or the call errors / hits the wrong object. |
+| iMessage | none — the plugin exposes no archive | none | Never attempt to "archive" an iMessage thread. Non-actionable threads are simply not surfaced. |
+| Slack | none | mark the conversation read via the Slack surface in use | Slack has no archive; see the FULL INBOX SCAN table. |
+| Telegram / Discord / Notion | none in this skill | — | Do not invent an archive call. |
+
+**Archiving is NOT an outbound send and is NOT approval-gated.** It changes local
+account state only: nothing leaves the account, no third party sees anything,
+and it is trivially reversible (`archive:false`, and a chat un-archives itself
+the moment a new message lands). The same holds for mark-read. Only genuine
+EXTERNAL sends — `send_message` / `send_file` / `send_audio_message` /
+`gmail_send` / a Slack or iMessage reply — go through the Rule-6 approval gate.
+If an archive call comes back "explicit owner approval is required", the proxy
+policy has archive miscategorised as a send; fix the policy rather than asking
+the user to tap approve a few hundred times.
+
+## Core principle: REPLY → VERIFY → AUTO-ARCHIVE (one atomic step, every channel)
+
+A thread that has just been answered must not stay in the inbox. Reply and
+archive are one step, not two, and the archive is automatic — never a separate
+question to the user.
+
+Per thread, in order:
+
+1. **Send** the approved draft (Rule 6 / PER-DRAFT APPROVAL — one draft, one
+ approval, one send).
+2. **VERIFY the reply actually landed.** Do not archive on the send tool
+ returning without an error; confirm the message exists on the channel:
+ - WhatsApp — the send result reports success AND the outbound row appears in
+ the thread (`list_messages` shows it with `is_from_me: true`), or the send
+ shows in the bridge send log. Re-read the thread; do not trust the return
+ value alone.
+ - Email — the sent message carries the `SENT` label (`gog gmail raw <id>` →
+ `"SENT" in labelIds`). A `DRAFT` is not a delivery.
+ - iMessage / Slack / Telegram / Notion — the reply is visible in the thread
+ on a fresh read.
+3. **Archive that thread immediately** on every JID/address it owns, using the
+ channel's valid command from the matrix above. On a channel with no archive
+ (iMessage, Slack, Telegram), mark it handled and stop surfacing it instead.
+4. Only then move to the next draft.
+
+**If verification fails, do NOT archive.** An unverified send is an unanswered
+thread; leave it visible and report the failure. Archiving a thread whose reply
+never left is the one way this flow can lose a message for good.
## Core principle: FULL CONTEXT — NEVER ASSUME
diff --git a/claude-ops/tests/test-ops-inbox-archive-set.sh b/claude-ops/tests/test-ops-inbox-archive-set.sh
new file mode 100755
index 00000000..a9726177
--- /dev/null
+++ b/claude-ops/tests/test-ops-inbox-archive-set.sh
@@ -0,0 +1,236 @@
+#!/usr/bin/env bash
+# Coverage for ops-inbox-archive-set and the full-inbox contract of
+# ops-inbox-scan. Hermetic: no bridge, no network, no Gmail. Everything runs
+# against a fixture scan JSON, and the script is exercised in its report-only
+# default so a test run can never archive anything.
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+SPLIT="$ROOT/bin/ops-inbox-archive-set"
+SCAN="$ROOT/bin/ops-inbox-scan"
+TMP="$(mktemp -d)"
+trap 'rm -rf "$TMP"' EXIT
+
+# Plugin scripts are run by whatever `python3` resolves to, which on macOS is
+# Xcode's 3.9. Prefer the oldest interpreter available so a 3.10+ construct
+# fails here rather than in a user's hook.
+PY=python3
+[ -x /usr/bin/python3 ] && PY=/usr/bin/python3
+
+fail() { echo "FAIL: $*" >&2; exit 1; }
+
+# --------------------------------------------------------------------------
+# static checks
+# --------------------------------------------------------------------------
+bash -n "$SCAN" || fail "ops-inbox-scan is not valid bash"
+"$PY" -c "import py_compile,sys; py_compile.compile(sys.argv[1], doraise=True)" \
+ "$SPLIT" || fail "ops-inbox-archive-set must compile on $PY"
+
+# --------------------------------------------------------------------------
+# full-inbox contract: the working set is "not archived", never "unread",
+# and never a recency slice. Regression guard for the old
+# `in:inbox newer_than:7d --max 30` query that aged mail out of the scan.
+# --------------------------------------------------------------------------
+CODE="$TMP/scan-code.sh" # comments name the old query on purpose
+sed 's/[[:space:]]*#.*$//' "$SCAN" >"$CODE"
+
+grep -q 'EMAIL_QUERY="in:inbox"' "$CODE" \
+ || fail "email working set must default to the whole inbox"
+grep -q 'newer_than' "$CODE" \
+ && fail "email query must not be sliced by a recency window"
+grep -q 'WHERE archived=0 OR last_message_time' "$CODE" \
+ || fail "whatsapp working set must be driven by the archived flag"
+
+# gog treats bare args as MESSAGE ids; the scan emits THREAD ids.
+grep -q '"--thread"' "$SPLIT" \
+ || fail "gmail archive must pass --thread when given thread ids"
+
+# --------------------------------------------------------------------------
+# fixture
+# --------------------------------------------------------------------------
+cat >"$TMP/scan.json" <<'JSON'
+{
+ "whatsapp": {
+ "needs_reply": [
+ {"who":"Asker","jid":"[email protected]","alt_jids":["9@lid"],"age_min":60,
+ "preview":[{"from_me":true,"text":"sent you the file"},
+ {"from_me":false,"text":"Can you resend it? I never got the attachment."}]},
+ {"who":"Tail","jid":"[email protected]","alt_jids":[],"age_min":60,
+ "preview":[{"from_me":false,"text":"Thanks bro!"}]},
+ {"who":"BareMedia","jid":"[email protected]","alt_jids":[],"age_min":60,
+ "preview":[{"from_me":false,"text":"[image]"}]},
+ {"who":"Stale","jid":"[email protected]","alt_jids":[],"age_min":100000,
+ "preview":[{"from_me":false,"text":"Are we still on for the show?"}]},
+ {"who":"ShortAsk","jid":"[email protected]","alt_jids":[],"age_min":60,
+ "preview":[{"from_me":false,"text":"Hoe was Ibiza?"}]}
+ ],
+ "waiting": [{"who":"Waiter","jid":"[email protected]","alt_jids":[]}],
+ "fyi": [{"who":"News","jid":"7@newsletter","reason":"newsletter/broadcast"}],
+ "groups": [{"who":"LiveGroup","jid":"[email protected]","age_min":60},
+ {"who":"DeadGroup","jid":"[email protected]","age_min":100000}]
+ },
+ "email": {
+ "needs_reply": [], "waiting": [],
+ "fyi": [
+ {"who":"[email protected]","subject":"Plain newsletter","threadId":"t1","labels":["INBOX","CATEGORY_UPDATES"]},
+ {"who":"[email protected]","subject":"Held by todo label","threadId":"t2","labels":["INBOX","Respond"]},
+ {"who":"[email protected]","subject":"Awaiting reply label","threadId":"t3","labels":["INBOX","AWAITING REPLY"]},
+ {"who":"[email protected]","subject":"Already actioned","threadId":"t4","labels":["INBOX","Actioned"]},
+ {"who":"[email protected]","subject":"Urgent flag","threadId":"t5","labels":["INBOX","URGENT"]}
+ ]
+ },
+ "counts": {}, "notes": []
+}
+JSON
+
+run_json() { "$PY" "$SPLIT" --scan "$TMP/scan.json" --json "$@"; }
+
+# --------------------------------------------------------------------------
+# --scan must actually be honoured.
+# Regression guard: a positional `scan` sharing its dest with --scan used to
+# overwrite it with None, so the tool silently ran a LIVE scan instead of the
+# file it was handed. On a machine with no bridge that looked like an empty
+# inbox; on a real one it archived against freshly-scanned data nobody reviewed.
+# --------------------------------------------------------------------------
+run_json >"$TMP/out.json" 2>"$TMP/err.txt" || fail "run failed: $(cat "$TMP/err.txt")"
+"$PY" - "$TMP/out.json" <<'PY' || exit 1
+import json, sys
+d = json.load(open(sys.argv[1]))
+c = d["counts"]
+
+# The fixture has exactly 5 email FYI rows; a live scan would not.
+review = {r["threadId"] for r in d["review_fyi"]["email"]}
+protected = {r["threadId"] for r in d["keep"]["email_protected"]}
+assert review | protected == {"t1", "t2", "t3", "t4", "t5"}, \
+ "--scan was ignored; the tool re-scanned instead of reading the file"
+
+# Guardrail: todo/action labels are never archived. "Actioned" is completion,
+# so it is ordinary FYI; "URGENT" is protected.
+assert protected == {"t2", "t3", "t5"}, "wrong protected set: %s" % protected
+assert review == {"t1", "t4"}, "wrong FYI review set: %s" % review
+
+# FYI is NEVER part of the default sweep - it gets briefed, then the user
+# decides. A default run must archive no mail at all.
+assert d["archive"]["email"] == [], "FYI must never be auto-archived"
+assert d["counts"]["archive_email"] == 0
+assert {r["jid"] for r in d["review_fyi"]["whatsapp"]} == {"7@newsletter"}
+assert "7@newsletter" not in {r["jid"] for r in d["archive"]["whatsapp_default"]}, \
+ "whatsapp newsletters are FYI and must not be auto-archived"
+
+# WhatsApp split.
+keep = {r["who"] for r in d["keep"]["whatsapp_default"]}
+arch = {r["who"] for r in d["archive"]["whatsapp_default"]}
+assert keep == {"Asker", "ShortAsk", "BareMedia"}, "wrong keep set: %s" % keep
+for who in ("Tail", "Stale", "Waiter", "DeadGroup"):
+ assert who in arch, "%s should be archived" % who
+assert "News" not in arch, "newsletters are FYI: brief them, never auto-archive"
+assert "BareMedia" not in arch, "undescribed media must never be archived unread"
+assert "LiveGroup" not in arch, "a live group must not be archived"
+
+# A kept chat must never also appear in the archive set.
+assert not (keep & arch), "overlap between keep and archive: %s" % (keep & arch)
+
+assert c["keep_email_protected"] == 3
+assert d["applied"] is False, "report-only run must not report applied"
+print("split + guardrail: PASS")
+PY
+
+# --------------------------------------------------------------------------
+# report-only default: no --apply means nothing is archived and nothing is
+# reported as applied.
+# --------------------------------------------------------------------------
+"$PY" "$SPLIT" --scan "$TMP/scan.json" >"$TMP/plain.txt" 2>&1 \
+ || fail "plain run failed"
+grep -q "Report only" "$TMP/plain.txt" \
+ || fail "default run must state that nothing was archived"
+grep -q "apply_result" "$TMP/out.json" \
+ && fail "report-only run must not carry an apply_result"
+
+# --------------------------------------------------------------------------
+# --apply --dry-run walks the apply path without calling out.
+# --------------------------------------------------------------------------
+run_json --apply --dry-run >"$TMP/dry.json" || fail "dry-run failed"
+"$PY" - "$TMP/dry.json" <<'PY' || exit 1
+import json, sys
+d = json.load(open(sys.argv[1]))
+r = d["apply_result"]
+assert d["applied"] is True and r["dry_run"] is True
+assert r["whatsapp_failed"] == 0 and r["email_failed"] == 0
+# Asker carries an alt_jid, so both of its JIDs are archived.
+assert r["whatsapp_ok"] >= len(d["archive"]["whatsapp_default"]), "alt_jids must be archived too"
+assert r["email_ok"] == 0, "a default sweep must not touch FYI mail"
+print("dry-run apply: PASS")
+PY
+
+# --------------------------------------------------------------------------
+# stale window is configurable and actually moves a thread across the line.
+# --------------------------------------------------------------------------
+run_json --stale-days 99999 >"$TMP/wide.json" || fail "wide-window run failed"
+"$PY" - "$TMP/wide.json" <<'PY' || exit 1
+import json, sys
+d = json.load(open(sys.argv[1]))
+keep = {r["who"] for r in d["keep"]["whatsapp_default"]}
+assert "Stale" in keep, "a wide stale window must keep the old open ask"
+print("stale window: PASS")
+PY
+
+# --------------------------------------------------------------------------
+# ReDoS guard (CodeQL py/redos). The ack test used to be one alternation
+# wrapped in (...)* with overlapping branches, so a long almost-matching
+# string backtracked exponentially and hung the scan. Classification must stay
+# linear on hostile input.
+# --------------------------------------------------------------------------
+"$PY" - "$SPLIT" <<'PY' || exit 1
+import sys, time, importlib.util
+from importlib.machinery import SourceFileLoader
+
+# The script has no .py suffix, so it needs an explicit source loader.
+loader = SourceFileLoader("split", sys.argv[1])
+spec = importlib.util.spec_from_loader("split", loader)
+mod = importlib.util.module_from_spec(spec)
+loader.exec_module(mod)
+
+for probe in ("oké" * 4000 + "!", "ok" * 8000 + "", " " * 20000 + "x"):
+ start = time.time()
+ mod.is_courtesy_tail(probe)
+ spent = time.time() - start
+ assert spent < 1.0, "classification took %.1fs on a %d-char message (ReDoS)" % (
+ spent, len(probe))
+
+# Behaviour the word-set must preserve.
+assert mod.is_courtesy_tail("Thanks bro!") is True
+assert mod.is_courtesy_tail("dankjewel!! 🙏") is True
+assert mod.is_courtesy_tail("Can you resend the file?") is False
+assert mod.is_courtesy_tail("Hoe was Ibiza?") is False
+assert mod.is_courtesy_tail("") is True
+
+# Undescribed media is UNKNOWN, never a tail. A bare "[image]" means the
+# enricher has not read it yet, and the photo may be an invoice or a signed
+# page - archiving it unread is how this tool would lose real work.
+for placeholder in ("[image]", "[voice]", "[document]", "[video]", "[ IMAGE ]".strip()):
+ assert mod.is_courtesy_tail(placeholder) is False, placeholder
+assert mod.is_courtesy_tail("", "image") is False # empty body + media row
+assert mod.is_courtesy_tail("", "") is True # genuinely nothing inbound
+# Once enriched it classifies on the description like any other text.
+assert mod.is_courtesy_tail("[image] invoice for 200 euro, due Friday") is False
+print("redos + ack behaviour: PASS")
+PY
+
+# --------------------------------------------------------------------------
+# --archive-fyi is the explicit opt-in the briefing leads to, and only then
+# does FYI join the sweep.
+# --------------------------------------------------------------------------
+run_json --archive-fyi --apply --dry-run >"$TMP/fyi.json" || fail "--archive-fyi failed"
+"$PY" - "$TMP/fyi.json" <<'PY' || exit 1
+import json, sys
+d = json.load(open(sys.argv[1]))
+assert d["counts"]["archive_email"] == 2, "opt-in must sweep the 2 unprotected FYI"
+assert d["apply_result"]["email_ok"] == 2
+# Protected mail stays protected even under the opt-in.
+ids = {r["threadId"] for r in d["archive"]["email"]}
+assert ids == {"t1", "t4"}, ids
+assert "7@newsletter" in {r["jid"] for r in d["archive"]["whatsapp_default"]}
+print("--archive-fyi opt-in: PASS")
+PY
+
+echo "ops-inbox-archive-set: ALL PASS"