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.
Shell agent-teamsai-agentai-automationanthropicautonomous-agentawsbusiness-operationsclaudeclaude-codeclaude-code-plugindevopsecommerceinbox-zeroklaviyomarketingmcpmorning-briefingpr-automationshopifyterminal
fix(ops-inbox): beantwoorde en zelf-opgeruimde draden tellen niet meer als openstaand werk (#977)
Aurora Capital4f63b0886d46
diff --git a/claude-ops/bin/ops-inbox-archive-set b/claude-ops/bin/ops-inbox-archive-setindex d4619922..0b982e79 100755--- a/claude-ops/bin/ops-inbox-archive-set+++ b/claude-ops/bin/ops-inbox-archive-set@@ -358,6 +358,53 @@ def write_sweep_watermarks(archived_jids, store_paths):print(" watermark write failed (%s): %s" % (path, exc), file=sys.stderr)+def email_watermark_path(account):+ """Where the per-thread email sweep watermarks live for this account.++ Mirrors write_sweep_watermarks() for WhatsApp. Gmail's archive is the same+ trap: removing the INBOX label says "dealt with as of now", it does not say+ "nobody may ever owe a reply here again". The scan's forgotten-debt pass+ reopens archived threads where they spoke last, which is right for a thread+ Gmail filed away on its own, and wrong for one we just swept on purpose.+ A timestamp per thread is the only thing that separates the two.+ """+ base = os.environ.get("HERMES_HOME") or os.path.expanduser("~/.hermes")+ d = os.path.join(base, "state")+ # Same key the scan reads back: the mailbox actually queried, not the alias+ # asked for. Every Sam alias forwards into one real Gmail account, so keying+ # on the alias writes a file nobody reads and the sweep never sticks.+ read_acct = os.environ.get("OPS_GOG_ACCOUNT") or account or "default"+ safe = re.sub(r"[^a-z0-9._-]+", "_", read_acct.lower())+ return os.path.join(d, "ops-email-sweep-watermarks-%s.json" % safe)+++def write_email_watermarks(thread_ids, account):+ """Record WHEN each email thread was archived. Best-effort, never fatal."""+ thread_ids = [t for t in thread_ids if t]+ if not thread_ids:+ return+ path = email_watermark_path(account)+ stamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S+00:00")+ marks = {}+ try:+ with open(path) as fh:+ loaded = json.load(fh)+ if isinstance(loaded, dict):+ marks = loaded+ except (OSError, ValueError):+ marks = {}+ for tid in thread_ids:+ marks[tid] = stamp+ try:+ os.makedirs(os.path.dirname(path), exist_ok=True)+ tmp = path + ".tmp"+ with open(tmp, "w") as fh:+ json.dump(marks, fh, indent=1, sort_keys=True)+ os.replace(tmp, path)+ except OSError as exc: # noqa: BLE001 - never fatal+ print(" email watermark write failed (%s): %s" % (path, exc), file=sys.stderr)++def archive_email(rows, account, dry):ids = [r["threadId"] for r in rows if r.get("threadId")]if not ids or dry:@@ -373,6 +420,7 @@ def archive_email(rows, account, dry):if res.returncode != 0:print(" gmail archive failed: %s" % (res.stderr or "")[-300:], file=sys.stderr)return 0, len(ids)+ write_email_watermarks(ids, account)return len(ids), 0diff --git a/claude-ops/bin/ops-inbox-scan b/claude-ops/bin/ops-inbox-scanindex c658b412..4c67c18a 100755--- a/claude-ops/bin/ops-inbox-scan+++ b/claude-ops/bin/ops-inbox-scan@@ -437,6 +437,8 @@ if [ "$DO_EMAIL" = 1 ]; thenACCT_ARGS=()if ops_gog_ready; thenACCT_ARGS=(-a "$OPS_GOG_ACCOUNT")+ # The python pass keys sweep watermarks on the mailbox actually read.+ export OPS_GOG_ACCOUNTelseGMAIL_ERR="$OPS_GOG_NOTE"fi@@ -460,6 +462,32 @@ if [ "$DO_EMAIL" = 1 ]; thenGMAIL_OK=1firm -f "${GMAIL_JSON_FILE}.err" 2>/dev/null || true++ # FORGOTTEN EMAIL DEBT. The inbox query above only sees threads that still+ # carry the INBOX label. A filter, a Gmail category, a mute, or one stray+ # archive removes that label while the other person is still waiting for an+ # answer — and every later scan then reports the mailbox as handled. That is+ # exactly how a Believe thread ("MRT Gen AI Videos") sat unanswered across+ # several clean runs: Gmail had filed the thread out of the inbox, so the+ # scan never saw it, three times in a row.+ #+ # This mirrors the WhatsApp forgotten-debt sweep: pull archived inbound mail+ # (never from Sam) plus his own sent mail over --debt-days, and let python+ # keep only the threads whose LAST message is inbound. Conversation debt is+ # direction, not label state.+ if [ "$GMAIL_OK" = 1 ] && [ ${#ACCT_ARGS[@]} -gt 0 ]; then+ GMAIL_DEBT_IN_FILE="$(mktemp "${TMPDIR:-/tmp}/ois-gmail-debt-in.XXXXXX")"+ GMAIL_DEBT_OUT_FILE="$(mktemp "${TMPDIR:-/tmp}/ois-gmail-debt-out.XXXXXX")"+ gog gmail messages search "${ACCT_ARGS[@]}" -j --max "$EMAIL_MAX" -- \+ "-in:inbox -in:chats -in:spam -in:trash -from:me newer_than:${DEBT_DAYS}d" \+ >"$GMAIL_DEBT_IN_FILE" 2>/dev/null || : >"$GMAIL_DEBT_IN_FILE"+ gog gmail messages search "${ACCT_ARGS[@]}" -j --max "$EMAIL_MAX" -- \+ "in:sent newer_than:${DEBT_DAYS}d" \+ >"$GMAIL_DEBT_OUT_FILE" 2>/dev/null || : >"$GMAIL_DEBT_OUT_FILE"+ export OIS_GMAIL_DEBT_IN_FILE="$GMAIL_DEBT_IN_FILE" \+ OIS_GMAIL_DEBT_OUT_FILE="$GMAIL_DEBT_OUT_FILE"+ trap 'rm -f "$GMAIL_JSON_FILE" "${OIS_SENDLOG_FILE:-}" "${GMAIL_DEBT_IN_FILE:-}" "${GMAIL_DEBT_OUT_FILE:-}"' EXIT+ fifiexport OIS_GMAIL_JSON_FILE="$GMAIL_JSON_FILE" OIS_GMAIL_ERR="$GMAIL_ERR" OIS_GMAIL_OK="$GMAIL_OK"@@ -478,6 +506,8 @@ PRETTY = os.environ.get("OIS_PRETTY") == "1"GMAIL_F = os.environ.get("OIS_GMAIL_JSON_FILE", "")GMAIL_ERR = os.environ.get("OIS_GMAIL_ERR", "")GMAIL_OK = os.environ.get("OIS_GMAIL_OK") == "1"+GMAIL_DEBT_IN = os.environ.get("OIS_GMAIL_DEBT_IN_FILE", "")+GMAIL_DEBT_OUT = os.environ.get("OIS_GMAIL_DEBT_OUT_FILE", "")SENDLOG_F = os.environ.get("OIS_SENDLOG_FILE", "")PEER_STORES = [p for p in os.environ.get("OIS_PEER_STORES", "").split(":") if p]@@ -1106,7 +1136,238 @@ def from_email_addr(header):m = re.search(r"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}", header.lower())return m.group(0) if m else header.lower().strip()+def _load_msg_list(path):+ """Read a `gog gmail messages search -j` dump -> list of message dicts."""+ if not path or not os.path.exists(path) or os.path.getsize(path) == 0:+ return []+ try:+ with open(path) as fh:+ data = json.load(fh)+ except (json.JSONDecodeError, OSError):+ return []+ if isinstance(data, dict):+ return data.get("messages") or data.get("results") or []+ return data if isinstance(data, list) else []+++def _msg_when(m):+ return m.get("internalDateIso") or m.get("date") or ""+++# Machine senders, by address only — never by subject keyword, which would risk+# hiding a real human. Deliberately wider than the inbox pass: the debt sweep+# reads ARCHIVED mail, where transactional traffic dominates. Bare support@ /+# info@ mailers, ticket robots, DMARC reporters, OTP senders and calendar+# plumbing otherwise drown the handful of humans actually waiting — measured+# 2026-09-16: 47 raw rows, 12 real conversations. Anything genuinely human+# writing from such an address still reaches Sam through the inbox pass.+MACHINE_SENDER_RE = re.compile(+ r"(no[-_.]?reply|do[-_.]?not[-_.]?reply|notifications?@|notifications?_at_|alerts?@|"+ r"mailer-daemon|postmaster@|@.*\.amazonses\.com|bounce|"+ r"^support@|@.*\.atlassian\.net|automation@|billing@|invoice|receipts?@|"+ r"dmarc|newsletter|marketing@|welcome@|techcomms@|via google|"+ r"@mail\.notion\.so|flyingblue|klm_royal|@notifications\.|@.*\.ikosresorts\.com)",+ re.IGNORECASE)+++def _answered_threads():+ """Thread ids where OUR newest message is newer than THEIR newest.++ Gmail keeps the INBOX label on a thread after you reply from another client+ (phone, web, a different alias). The envelope pass only sees the last+ *inbound* message and calls that debt, so a thread Sam answered himself+ minutes ago still reads as "waiting for Sam". That happened on 2026-09-16:+ he replied to Tjark at 11:03, the scan still listed it, and he had to catch+ it. Debt is direction, not label state, so build the set of threads we+ already answered and let the inbox pass demote them.+ """+ outbound = _load_msg_list(GMAIL_DEBT_OUT)+ if not outbound:+ return {}+ inbound = _load_msg_list(GMAIL_DEBT_IN)+ last_out, last_in = {}, {}+ for m in outbound:+ tid = m.get("threadId") or m.get("id")+ when = _msg_when(m)+ if tid and when and when > last_out.get(tid, ""):+ last_out[tid] = when+ for m in inbound:+ tid = m.get("threadId") or m.get("id")+ when = _msg_when(m)+ if tid and when and when > last_in.get(tid, ""):+ last_in[tid] = when+ return {tid: when for tid, when in last_out.items()+ if when > last_in.get(tid, "")}+++def _when_epoch(s):+ """ISO-ish timestamp -> epoch seconds, or None.++ Gmail hands back "2026-09-16T10:00:00+00:00" while the sweep watermark is+ written as "2026-09-16 10:00:00+00:00". Comparing those as STRINGS silently+ always favours the Gmail one ("T" sorts after " "), so every swept thread+ read as "they wrote after the sweep" and came straight back. Compare real+ instants, never text.+ """+ if not s:+ return None+ t = str(s).strip().replace("Z", "+00:00")+ if len(t) > 10 and t[10] == " ":+ t = t[:10] + "T" + t[11:]+ for cand in (t, re.sub(r"\.\d+", "", t)):+ try:+ dt = datetime.fromisoformat(cand)+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=timezone.utc)+ return dt.timestamp()+ except ValueError:+ continue+ return None+++def _email_watermarks():+ """When did WE deliberately archive each thread? Written by ops-inbox-archive-set.++ Without this the forgotten-debt pass re-opens everything a sweep just filed,+ because "archived + they spoke last" is true for every thread we close out.+ On 2026-09-16 that turned a genuinely empty inbox into 47 items, all of them+ mail archived minutes earlier. A watermark separates "Gmail filed this away+ on its own" (real debt) from "we dealt with this at 12:05" (not debt, unless+ they wrote again AFTER that).+ """+ base = os.environ.get("HERMES_HOME") or os.path.expanduser("~/.hermes")+ # Key on the mailbox actually READ, not the one requested. --gmail-account+ # names Sam's alias ([email protected]), but every alias forwards into one real+ # mailbox and lib/gog-account.sh resolves the query to that account. Keying+ # on the alias wrote watermarks nobody ever reads back, so a swept thread+ # came straight back on the next scan of that alias.+ read_acct = os.environ.get("OPS_GOG_ACCOUNT") or ACCT or "default"+ safe = re.sub(r"[^a-z0-9._-]+", "_", read_acct.lower())+ path = os.path.join(base, "state", "ops-email-sweep-watermarks-%s.json" % safe)+ try:+ with open(path) as fh:+ loaded = json.load(fh)+ return {k: str(v) for k, v in loaded.items()} if isinstance(loaded, dict) else {}+ except (OSError, ValueError):+ return {}+++def forgotten_email_threads():+ """Archived mail where THEY spoke last and we never answered.++ Label state is not conversation state: a Gmail filter, a category, a mute+ or one stray archive strips INBOX from a live thread, and an inbox-only+ scan then calls the mailbox clean while someone waits. Direction is the+ only honest test, so compare the newest inbound message per thread against+ the newest message we sent in that same thread.+ """+ inbound = _load_msg_list(GMAIL_DEBT_IN)+ if not inbound:+ return []+ outbound = _load_msg_list(GMAIL_DEBT_OUT)+ last_in, last_out, newest = {}, {}, {}+ for m in inbound:+ tid = m.get("threadId") or m.get("id")+ when = _msg_when(m)+ if not tid or not when:+ continue+ if when > last_in.get(tid, ""):+ last_in[tid] = when+ newest[tid] = m+ for m in outbound:+ tid = m.get("threadId") or m.get("id")+ when = _msg_when(m)+ if not tid or not when:+ continue+ if when > last_out.get(tid, ""):+ last_out[tid] = when+ # Threads the owner has ever written into are real conversations, not+ # one-way blasts. Used as a confidence signal, never as a filter: a first+ # approach from a new human is still debt.+ participated = set(last_out)+ self_addr = (ACCT or "").lower()+ swept = _email_watermarks()+ items = []+ for tid, when in last_in.items():+ if when <= last_out.get(tid, ""):+ continue # we answered after them: not debt+ # We archived this on purpose. Only real if they wrote again AFTER that.+ #+ # EXCEPTION, and it matters: a watermark closes ONE-WAY mail, never a+ # conversation Sam is actually in. A bulk sweep stamps hundreds of+ # threads in one second (1007 on 2026-09-16) without a human reading any+ # of them, and that wiped all 12 genuine two-way threads — Believe,+ # PingPong, Ace, Ikos — from the result. Archiving is a filing decision;+ # it is not evidence that a reply was sent. So a thread Sam has written+ # into survives its watermark and is demoted only by the direction test+ # above (we answered after them), which is the honest signal.+ mark = _when_epoch(swept.get(tid))+ inbound_at = _when_epoch(when)+ if (mark is not None and inbound_at is not None and inbound_at <= mark+ and tid not in participated):+ continue+ m = newest[tid]+ frm = (m.get("from") or "").lower()+ if self_addr and self_addr == from_email_addr(frm):+ continue+ labels = [str(l).upper() for l in (m.get("labels") or m.get("labelIds") or [])]+ if any(l in labels for l in ("CATEGORY_PROMOTIONS", "CATEGORY_SOCIAL",+ "CATEGORY_UPDATES", "CATEGORY_FORUMS")):+ continue+ if MACHINE_SENDER_RE.search(frm):+ continue+ items.append({+ "who": m.get("from") or "(unknown)",+ "subject": trunc(m.get("subject") or "(no subject)", 120),+ "threadId": tid,+ "date": m.get("date"),+ "labels": labels,+ "forgotten": True,+ "sam_participated": tid in participated,+ "note": ("KEEP — archived/filtered out of the inbox but they still "+ "spoke last inside the %d-day debt window; deep-read before "+ "drafting" % DEBT_DAYS),+ })+ # Threads the owner already joined rank first: those are live conversations+ # someone is actively waiting on. Recency breaks ties inside each group.+ items.sort(key=lambda x: (x["sam_participated"], last_in.get(x["threadId"], "")),+ reverse=True)+ return items+++def _merge_forgotten(res):+ """Add archived-but-unanswered threads to needs_reply, without duplicates."""+ try:+ extra = forgotten_email_threads()+ except Exception as exc: # never let the sweep break the whole scan+ res.setdefault("notes", []).append("email forgotten-debt check failed (%s)" % exc)+ return res+ if not extra:+ return res+ seen = {i.get("threadId") for bucket in ("needs_reply", "waiting", "fyi")+ for i in res.get(bucket, [])}+ added = [i for i in extra if i.get("threadId") not in seen]+ if not added:+ return res+ res["needs_reply"].extend(added)+ res["forgotten_count"] = len(added)+ res.setdefault("notes", []).append(+ "email: %d archived/filtered thread(s) reopened — they spoke last inside "+ "the %d-day debt window, so the INBOX label was hiding real debt"+ % (len(added), DEBT_DAYS))+ if res.pop("empty", None):+ res["note"] = ("inbox label is empty, but %d archived/filtered thread(s) "+ "still owe a reply" % len(added))+ return res++def scan_email():+ # Two passes, one answer: the INBOX-labelled working set, plus the archived+ # threads that still owe a reply. A thread Gmail filed away is still debt.+ return _merge_forgotten(_scan_email_inbox())+++def _scan_email_inbox():res = {"account": ACCT or "(gog default account)","needs_reply": [], "waiting": [], "fyi": [], "reachable": True}if not GMAIL_F or not os.path.exists(GMAIL_F) or os.path.getsize(GMAIL_F) == 0:@@ -1126,6 +1387,7 @@ def scan_email():res["note"] = f"gmail result unparseable: {e}"return resrows = data if isinstance(data, list) else data.get("results", data.get("threads", []))+ ANSWERED = _answered_threads()if not rows:# Parsed fine, zero hits. That is inbox zero, and it must never read the# same as a call that failed — an agent cannot act on an ambiguous empty.@@ -1156,6 +1418,16 @@ def scan_email():res["needs_reply"].append(item) # surface as actionable, never FYI/archivecontinueis_sent_last = ("SENT" in labels) or (self_addr and self_addr == from_email_addr(frm))+ # Did we already answer this THREAD? The envelope row is the last+ # inbound message, which stays visible after a reply sent from Sam's+ # phone or another alias. Without this the scan hands him back work he+ # finished himself.+ if not is_sent_last and tid and tid in ANSWERED:+ item["note"] = ("KEEP OUT OF NEEDS-REPLY — we already replied in this "+ "thread at %s; ball is with them" % ANSWERED[tid])+ item["answered_by_us"] = True+ res["waiting"].append(item)+ continuepromo = any(l in labels for l in ("CATEGORY_PROMOTIONS", "CATEGORY_SOCIAL","CATEGORY_UPDATES", "CATEGORY_FORUMS"))# Conservative no-reply / automated-sender heuristic: route obviousdiff --git a/claude-ops/tests/run-all.sh b/claude-ops/tests/run-all.shindex 8f6344d3..8d1cb94b 100755--- a/claude-ops/tests/run-all.sh+++ b/claude-ops/tests/run-all.sh@@ -69,6 +69,9 @@ run_suite "$TESTS_DIR/test-agent-teams.sh"run_suite "$TESTS_DIR/test-pocket-env-broker.sh"run_suite "$TESTS_DIR/test-ops-pocket-notify.sh"run_suite "$TESTS_DIR/test-ops-inbox-zero.sh"+run_suite "$TESTS_DIR/test-ops-inbox-email-forgotten-debt.sh"+run_suite "$TESTS_DIR/test-ops-inbox-answered-thread.sh"+run_suite "$TESTS_DIR/test-ops-inbox-email-watermark.sh"run_suite "$TESTS_DIR/test-ops-inbox-scan-arg-parse.sh"run_suite "$TESTS_DIR/test-ops-wa-accounts.sh"run_suite "$TESTS_DIR/test-ops-daemon-manager.sh"diff --git a/claude-ops/tests/test-ops-inbox-answered-thread.sh b/claude-ops/tests/test-ops-inbox-answered-thread.shnew file mode 100755index 00000000..623c4e91--- /dev/null+++ b/claude-ops/tests/test-ops-inbox-answered-thread.sh@@ -0,0 +1,133 @@+#!/usr/bin/env bash+# test-ops-inbox-answered-thread.sh — a thread Sam already answered is not debt.+#+# 2026-09-16, caught by Sam: "Hebben tjark toch al terug gemaild?" The scan+# listed a Wave Wave thread as needing his reply while he had answered it at+# 11:03 that same morning from another client. Gmail keeps the INBOX label on+# the thread after such a reply, and the envelope pass only reads the last+# INBOUND message, so it read as debt.+#+# Debt is direction, not label state. If our newest message in a thread is+# newer than theirs, the ball is with them: it belongs in waiting, never in+# needs_reply.+#+# Mutation-proof: remove the _answered_threads() lookup from the inbox pass and+# the first check goes red.+set -uo pipefail++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+ROOT="$(cd "$HERE/.." && pwd)"+SCAN="$ROOT/bin/ops-inbox-scan"++pass=0; fail=0+ok() { pass=$((pass+1)); printf ' ok %s\n' "$1"; }+bad() { fail=$((fail+1)); printf ' FAIL %s\n' "$1"; }++TMP="$(mktemp -d "${TMPDIR:-/tmp}/ops-answered.XXXXXX")"+trap 'rm -rf "$TMP"' EXIT++# ------------------------------------------------------------------ fixtures --+# Three Gmail threads, written straight into the files the scan reads. The+# shapes are the ones that actually occur:+# t-answered : they wrote, WE replied later. Same shape as the Wave Wave+# thread Sam answered from his phone. Must NOT be needs_reply.+# t-open : they wrote, we never replied. Must stay needs_reply.+# t-stale : we replied, THEN they wrote again. Ball is back with us.+python3 - "$TMP" <<'PY'+import json, os, sys+from datetime import datetime, timedelta, timezone++tmp = sys.argv[1]+now = datetime.now(timezone.utc)+def ts(**kw):+ return (now - timedelta(**kw)).isoformat()++def msg(mid, tid, frm, subj, when, labels):+ return {"id": mid, "threadId": tid, "from": frm, "subject": subj,+ "date": when, "internalDateIso": when, "labels": labels}++# What the INBOX query returns: the last INBOUND message of each thread.+# All three still carry INBOX, which is exactly why label state cannot decide.+inbox = [+ msg("m1", "t-answered", "Tjark <[email protected]>", "Re: First version",+ ts(days=1), ["INBOX"]),+ msg("m2", "t-open", "Nina <[email protected]>", "Quote for the remix",+ ts(days=2), ["INBOX"]),+ msg("m3", "t-stale", "Pim <[email protected]>", "Re: Contract",+ ts(hours=2), ["INBOX"]),+]++# Archived inbound over the debt window (the forgotten-debt pass).+debt_in = list(inbox)++# Our own sent mail over the debt window.+sent = [+ # Answered AFTER Tjark wrote: this is the fix under test.+ msg("s1", "t-answered", "Sam <[email protected]>", "Re: First version",+ ts(hours=3), ["SENT"]),+ # Answered BEFORE Pim wrote again: still our turn.+ msg("s2", "t-stale", "Sam <[email protected]>", "Re: Contract",+ ts(days=3), ["SENT"]),+]++for name, rows in (("inbox.json", inbox), ("debt-in.json", debt_in),+ ("sent.json", sent)):+ with open(os.path.join(tmp, name), "w") as fh:+ json.dump(rows, fh)+PY++# ------------------------------------------------------------------- run it --+# Drive the scan's own python block with the fixture files, so the test+# exercises the shipped classifier and not a copy of it.+run_scan() {+ OIS_DAYS=7 OIS_DEBT_DAYS=90 OIS_DO_WA=0 OIS_DO_EMAIL=1 \+ OIS_GMAIL_ACCOUNT="[email protected]" \+ OIS_GMAIL_JSON_FILE="$TMP/inbox.json" OIS_GMAIL_OK=1 \+ OIS_GMAIL_DEBT_IN_FILE="$TMP/debt-in.json" \+ OIS_GMAIL_DEBT_OUT_FILE="$TMP/sent.json" \+ python3 - "$SCAN" <<'PY'+import os, re, sys+src = open(sys.argv[1]).read()+body = src.split("python3 <<'PY'", 1)[1].rsplit("PY", 1)[0]+g = {"__name__": "__scan__"}+exec(compile(body, "ops-inbox-scan", "exec"), g)+PY+}++bucket_of() { # bucket_of <json> <subject-fragment>+ python3 -c '+import json, sys+d = json.loads(sys.stdin.read() or "{}")+em = d.get("email", {})+frag = sys.argv[1]+for b in ("needs_reply", "waiting", "fyi"):+ for row in em.get(b, []):+ if frag in (row.get("subject") or ""):+ print(b); sys.exit(0)+print("ABSENT")' "$2" <<<"$1"+}++echo "a thread we already answered is not debt"+OUT="$(run_scan 2>/dev/null)"+if [ -z "$OUT" ]; then+ bad "scan produced no output"+else+ b="$(bucket_of "$OUT" "First version")"+ [ "$b" = "waiting" ] && ok "answered-from-another-client thread lands in waiting" \+ || bad "answered thread landed in '$b', expected waiting"++ b="$(bucket_of "$OUT" "Quote for the remix")"+ [ "$b" = "needs_reply" ] && ok "genuinely unanswered thread stays needs_reply" \+ || bad "unanswered thread landed in '$b'"++ b="$(bucket_of "$OUT" "Re: Contract")"+ [ "$b" = "needs_reply" ] && ok "they wrote again after our reply: still our turn" \+ || bad "re-asked thread landed in '$b', expected needs_reply"++ grep -q "already replied in this thread" <<<"$OUT" \+ && ok "scan says why it demoted the thread" \+ || bad "no explanation on the demoted thread"+fi++printf '\n%d passed, %d failed\n' "$pass" "$fail"+[ "$fail" -eq 0 ]diff --git a/claude-ops/tests/test-ops-inbox-email-forgotten-debt.sh b/claude-ops/tests/test-ops-inbox-email-forgotten-debt.shnew file mode 100755index 00000000..204c41e0--- /dev/null+++ b/claude-ops/tests/test-ops-inbox-email-forgotten-debt.sh@@ -0,0 +1,226 @@+#!/usr/bin/env bash+# test-ops-inbox-email-forgotten-debt.sh — archived/filtered mail that still+# owes a reply must surface.+#+# WHY (real miss, 2026-09-16): Salim Jawad at Believe sent the finished UGC fan+# videos on the "MRT Gen AI Videos" thread. Gmail had that thread filed out of+# the inbox, so the email half of ops-inbox-scan — which queried `in:inbox` and+# nothing else — never saw it. Three consecutive scans reported the mailbox as+# handled while a counterparty waited. Label state is not conversation state.+#+# The rule this pins: debt is DIRECTION, not label. If their message is the last+# one in a thread and we never answered inside --debt-days, it is open, whether+# or not Gmail still calls it INBOX. Promotions/social/updates/forums categories+# and no-reply senders stay shut, and a thread we already answered stays shut.+#+# Mutation-proof: delete the debt queries in bin/ops-inbox-scan, drop the+# _merge_forgotten call, or stop filtering on direction, and this goes red.+set -uo pipefail++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+ROOT="$(cd "$HERE/.." && pwd)"+SCAN="$ROOT/bin/ops-inbox-scan"++pass=0; fail=0+ok() { pass=$((pass+1)); printf ' ok %s\n' "$1"; }+bad() { fail=$((fail+1)); printf ' FAIL %s\n' "$1"; }++TMP="$(mktemp -d "${TMPDIR:-/tmp}/ops-email-debt.XXXXXX")"+trap 'rm -rf "$TMP"' EXIT++# ---------------------------------------------------------------- gog stub --+# Offline stand-in for the real CLI. Three shapes matter:+# gog auth list -> account resolution+# gog gmail search ... <query> -> the INBOX working set (JSON array)+# gog gmail messages search ... -- <query> -> debt sweeps (JSON object)+mkdir -p "$TMP/bin"+cat >"$TMP/bin/gog" <<'STUB'+#!/usr/bin/env bash+# Minimal gog stub. Query text decides which fixture is returned.+args="$*"++if [ "${1:-}" = "auth" ]; then+ printf '[email protected]\tdefault\toauth\n'+ exit 0+fi++# The last argument is always the query string in our call sites.+query="${!#}"++case "$args" in+ *"gmail messages search"*)+ case "$query" in+ *"in:sent"*) cat "$OPS_TEST_FIXTURES/sent.json" ;;+ *"-in:inbox"*) cat "$OPS_TEST_FIXTURES/archived.json" ;;+ *) printf '{"messages":[]}\n' ;;+ esac+ ;;+ *"gmail search"*)+ cat "$OPS_TEST_FIXTURES/inbox.json"+ ;;+ *)+ printf '[]\n'+ ;;+esac+exit 0+STUB+chmod +x "$TMP/bin/gog"++# ----------------------------------------------------------------- fixtures --+FIX="$TMP/fixtures"+mkdir -p "$FIX"++# INBOX working set: one ordinary live thread, so the scan is not "empty".+cat >"$FIX/inbox.json" <<'JSON'+[+ {+ "id": "live-1",+ "threadId": "t-live",+ "date": "2026-09-16 09:00",+ "internalDateIso": "2026-09-16T09:00:00+02:00",+ "from": "Live Human <[email protected]>",+ "subject": "Still in the inbox",+ "labels": ["IMPORTANT", "CATEGORY_PERSONAL"]+ }+]+JSON++# Archived inbound mail (not from us), i.e. the debt candidates.+cat >"$FIX/archived.json" <<'JSON'+{+ "messages": [+ {+ "id": "believe-1",+ "threadId": "t-believe",+ "date": "2026-09-15 14:27",+ "internalDateIso": "2026-09-15T14:27:56+02:00",+ "from": "Salim JAWAD <[email protected]>",+ "subject": "Re: MRT Gen AI Videos",+ "labels": ["IMPORTANT", "CATEGORY_PERSONAL"]+ },+ {+ "id": "answered-1",+ "threadId": "t-answered",+ "date": "2026-09-10 10:00",+ "internalDateIso": "2026-09-10T10:00:00+02:00",+ "from": "Polite Person <[email protected]>",+ "subject": "Can you send the file?",+ "labels": ["CATEGORY_PERSONAL"]+ },+ {+ "id": "promo-1",+ "threadId": "t-promo",+ "date": "2026-09-14 08:00",+ "internalDateIso": "2026-09-14T08:00:00+02:00",+ "from": "Shop <[email protected]>",+ "subject": "50% off everything",+ "labels": ["CATEGORY_PROMOTIONS"]+ },+ {+ "id": "robot-1",+ "threadId": "t-robot",+ "date": "2026-09-14 09:00",+ "internalDateIso": "2026-09-14T09:00:00+02:00",+ "from": "Build bot <[email protected]>",+ "subject": "Your build finished",+ "labels": ["CATEGORY_PERSONAL"]+ }+ ]+}+JSON++# Our sent mail. We answered t-answered AFTER their message; never t-believe.+cat >"$FIX/sent.json" <<'JSON'+{+ "messages": [+ {+ "id": "sent-1",+ "threadId": "t-answered",+ "date": "2026-09-10 11:30",+ "internalDateIso": "2026-09-10T11:30:00+02:00",+ "from": "Sam <[email protected]>",+ "subject": "Re: Can you send the file?",+ "labels": ["SENT"]+ },+ {+ "id": "sent-2",+ "threadId": "t-believe",+ "date": "2026-09-12 10:25",+ "internalDateIso": "2026-09-12T10:25:00+02:00",+ "from": "Sam <[email protected]>",+ "subject": "Re: MRT Gen AI Videos",+ "labels": ["SENT"]+ }+ ]+}+JSON++run_scan() {+ OPS_TEST_FIXTURES="$FIX" \+ PATH="$TMP/bin:$PATH" \+ GOG_ACCOUNT="[email protected]" \+ GOG_KEYRING_PASSWORD="test" \+ "$SCAN" --email-only --debt-days 90 2>/dev/null+}++bucket_of() {+ python3 -c '+import json, sys+d = json.loads(sys.stdin.read() or "{}")+em = d.get("email", {})+subj = sys.argv[1]+for b in ("needs_reply", "waiting", "fyi"):+ for row in em.get(b, []):+ if subj in (row.get("subject") or ""):+ print(b + (":forgotten" if row.get("forgotten") else ":live"))+ sys.exit(0)+print("ABSENT")' "$2" <<<"$1"+}++echo "email forgotten debt"+OUT="$(run_scan)"+if [ -z "$OUT" ]; then+ bad "scan produced no output"+else+ b="$(bucket_of "$OUT" "MRT Gen AI Videos")"+ [ "$b" = "needs_reply:forgotten" ] \+ && ok "archived thread where they spoke last comes back as forgotten" \+ || bad "Believe thread landed in '$b'"++ b="$(bucket_of "$OUT" "Still in the inbox")"+ [ "$b" = "needs_reply:live" ] \+ && ok "ordinary inbox thread stays live, not forgotten" \+ || bad "live inbox thread landed in '$b'"++ b="$(bucket_of "$OUT" "Can you send the file?")"+ [ "$b" = "ABSENT" ] \+ && ok "thread we already answered stays shut" \+ || bad "answered thread came back as '$b'"++ b="$(bucket_of "$OUT" "50% off everything")"+ [ "$b" = "ABSENT" ] \+ && ok "promotions category stays shut" \+ || bad "promo came back as '$b'"++ b="$(bucket_of "$OUT" "Your build finished")"+ [ "$b" = "ABSENT" ] \+ && ok "no-reply sender stays shut" \+ || bad "robot mail came back as '$b'"++ grep -q "archived/filtered thread" <<<"$OUT" \+ && ok "scan states that it reopened filtered mail" \+ || bad "no note explaining the email reopen"+fi++echo "debt window bounds the reopen"+OUT1="$(OPS_TEST_FIXTURES="$FIX" PATH="$TMP/bin:$PATH" \+ GOG_ACCOUNT="[email protected]" GOG_KEYRING_PASSWORD="test" \+ "$SCAN" --email-only --debt-days 1 2>/dev/null)"+# The stub ignores newer_than, so a 1-day window must still produce valid JSON+# and must not crash the scan. The real bound is exercised by the query itself.+python3 -c 'import json,sys; json.loads(sys.stdin.read())' <<<"$OUT1" \+ && ok "scan still emits valid JSON with a 1-day debt window" \+ || bad "scan emitted invalid JSON with --debt-days 1"++printf '\n%d passed, %d failed\n' "$pass" "$fail"+[ "$fail" -eq 0 ]diff --git a/claude-ops/tests/test-ops-inbox-email-watermark.sh b/claude-ops/tests/test-ops-inbox-email-watermark.shnew file mode 100755index 00000000..64eb72d5--- /dev/null+++ b/claude-ops/tests/test-ops-inbox-email-watermark.sh@@ -0,0 +1,123 @@+#!/usr/bin/env bash+# test-ops-inbox-email-watermark.sh — a sweep we ran ourselves must stay swept.+#+# 2026-09-16: the mailbox was genuinely at zero after a clean-up, and the very+# next scan reported 47 items needing a reply. Every one of them was mail+# archived minutes earlier: the forgotten-debt pass reopens "archived AND they+# spoke last", which is true for basically everything you ever close out.+#+# WhatsApp already solved this with ops-sweep-watermarks.json. Email now has the+# same thing: ops-inbox-archive-set stamps each thread it archives, and the scan+# only reopens a swept thread when they wrote again AFTER that stamp.+#+# Mutation-proof: drop the watermark check and the first case goes red.+set -uo pipefail++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+ROOT="$(cd "$HERE/.." && pwd)"+SCAN="$ROOT/bin/ops-inbox-scan"++pass=0; fail=0+ok() { pass=$((pass+1)); printf ' ok %s\n' "$1"; }+bad() { fail=$((fail+1)); printf ' FAIL %s\n' "$1"; }++TMP="$(mktemp -d "${TMPDIR:-/tmp}/ops-wm.XXXXXX")"+trap 'rm -rf "$TMP"' EXIT+mkdir -p "$TMP/state"++# ------------------------------------------------------------------ fixtures --+# Three archived threads, all "they spoke last". Only one is real debt.+# t-swept : we archived it at 12:05, they last wrote at 12:00. Handled.+# t-reopen : we archived it at 12:05, they wrote AGAIN at 12:30. Real debt.+# t-filtered: no watermark at all — Gmail filed it away itself. Real debt.+python3 - "$TMP" <<'PY'+import json, os, sys+from datetime import datetime, timedelta, timezone++tmp = sys.argv[1]+now = datetime.now(timezone.utc)+def ts(**kw):+ return (now - timedelta(**kw)).isoformat()+def stamp(**kw):+ return (now - timedelta(**kw)).strftime("%Y-%m-%d %H:%M:%S+00:00")++def msg(mid, tid, frm, subj, when, labels):+ return {"id": mid, "threadId": tid, "from": frm, "subject": subj,+ "date": when, "internalDateIso": when, "labels": labels}++inbox = [] # inbox label is empty: the whole point+debt_in = [+ msg("m1", "t-swept", "Anna <[email protected]>", "Swept thread",+ ts(hours=3), []),+ msg("m2", "t-reopen", "Bo <[email protected]>", "Reopened thread",+ ts(minutes=30), []),+ msg("m3", "t-filtered", "Cas <[email protected]>", "Filtered thread",+ ts(days=2), []),+]+sent = [] # we never replied in any of them++# Watermarks: we swept two of the three, two hours ago.+marks = {"t-swept": stamp(hours=2), "t-reopen": stamp(hours=2)}++with open(os.path.join(tmp, "inbox.json"), "w") as fh:+ json.dump(inbox, fh)+with open(os.path.join(tmp, "debt-in.json"), "w") as fh:+ json.dump(debt_in, fh)+with open(os.path.join(tmp, "sent.json"), "w") as fh:+ json.dump(sent, fh)+os.makedirs(os.path.join(tmp, "state"), exist_ok=True)+with open(os.path.join(tmp, "state",+ "ops-email-sweep-watermarks-sam_example.com.json"), "w") as fh:+ json.dump(marks, fh)+PY++# ------------------------------------------------------------------- run it --+run_scan() {+ HERMES_HOME="$TMP" \+ OIS_DAYS=7 OIS_DEBT_DAYS=90 OIS_DO_WA=0 OIS_DO_EMAIL=1 \+ OIS_GMAIL_ACCOUNT="[email protected]" \+ OIS_GMAIL_JSON_FILE="$TMP/inbox.json" OIS_GMAIL_OK=1 \+ OIS_GMAIL_DEBT_IN_FILE="$TMP/debt-in.json" \+ OIS_GMAIL_DEBT_OUT_FILE="$TMP/sent.json" \+ python3 - "$SCAN" <<'PY'+import os, re, sys+src = open(sys.argv[1]).read()+body = src.split("python3 <<'PY'", 1)[1].rsplit("PY", 1)[0]+g = {"__name__": "__scan__"}+exec(compile(body, "ops-inbox-scan", "exec"), g)+PY+}++has_subject() { # has_subject <json> <fragment>+ python3 -c '+import json, sys+d = json.loads(sys.stdin.read() or "{}")+em = d.get("email", {})+frag = sys.argv[1]+for b in ("needs_reply", "waiting", "fyi"):+ for row in em.get(b, []):+ if frag in (row.get("subject") or ""):+ print(b); sys.exit(0)+print("ABSENT")' "$2" <<<"$1"+}++echo "email sweep watermark"+OUT="$(run_scan 2>/dev/null)"+if [ -z "$OUT" ]; then+ bad "scan produced no output"+else+ b="$(has_subject "$OUT" "Swept thread")"+ [ "$b" = "ABSENT" ] && ok "a thread we swept ourselves stays swept" \+ || bad "swept thread came back as '$b'"++ b="$(has_subject "$OUT" "Reopened thread")"+ [ "$b" = "needs_reply" ] && ok "they wrote again after the sweep: real debt" \+ || bad "re-asked thread landed in '$b'"++ b="$(has_subject "$OUT" "Filtered thread")"+ [ "$b" = "needs_reply" ] && ok "no watermark (Gmail filtered it): still debt" \+ || bad "filtered thread landed in '$b'"+fi++printf '\n%d passed, %d failed\n' "$pass" "$fail"+[ "$fail" -eq 0 ]