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): a reply after the sweep reopens the chat (#934)

Aurora Capital946b08785542
diff --git a/claude-ops/bin/ops-inbox-archive-set b/claude-ops/bin/ops-inbox-archive-set
index 7034b0a5..f0a08bf7 100755
--- a/claude-ops/bin/ops-inbox-archive-set
+++ b/claude-ops/bin/ops-inbox-archive-set
@@ -46,6 +46,7 @@ import re
import sqlite3
import subprocess
import sys
+from datetime import datetime, timezone
# --------------------------------------------------------------------------
# email label guardrail
@@ -320,6 +321,43 @@ def archive_whatsapp(rows, port, dry):
return ok, fail
+def write_sweep_watermarks(archived_jids, store_paths):
+ """Record WHEN each chat was archived, next to the store it lives in.
+
+ The archive flag alone cannot answer "did they reply since we dealt with
+ this?": WhatsApp never moves it when a new message lands, so a swept thread
+ that gets an answer an hour later stays invisible and inbox zero is reported
+ over live questions. The scan needs a per-chat timestamp to compare an
+ inbound against, and it must survive a restart, so it goes on disk beside
+ messages.db rather than into any process state. Best-effort by design: a
+ missing file only costs the scan its precision, never its correctness.
+ """
+ if not archived_jids:
+ return
+ stamp = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S+00:00")
+ for store in store_paths:
+ if not store:
+ continue
+ path = os.path.join(os.path.dirname(store), "ops-sweep-watermarks.json")
+ marks = {}
+ try:
+ with open(path) as fh:
+ loaded = json.load(fh)
+ if isinstance(loaded, dict):
+ marks = loaded
+ except (OSError, ValueError):
+ marks = {}
+ for jid in archived_jids:
+ marks[jid] = stamp
+ try:
+ 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(" 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:
@@ -488,6 +526,19 @@ def main():
ok += o2
fail += f2
eok, efail = archive_email(em_archive, args.gmail_account, args.dry_run)
+ if not args.dry_run:
+ # Stamp what we just archived, so a reply arriving afterwards can
+ # reopen the thread on the next scan instead of vanishing behind
+ # the archive flag.
+ swept = []
+ for row in wa_archive:
+ swept.extend([row.get("jid")] + list(row.get("alt_jids") or []))
+ for e in extra:
+ for row in e["archive"]:
+ swept.extend([row.get("jid")] + list(row.get("alt_jids") or []))
+ stores = [(scan or {}).get("whatsapp_account", {}).get("store")]
+ stores += list(args.wa_store or [])
+ write_sweep_watermarks([j for j in swept if j], stores)
result["applied"] = True
result["apply_result"] = {"whatsapp_ok": ok, "whatsapp_failed": fail,
"email_ok": eok, "email_failed": efail,
diff --git a/claude-ops/bin/ops-inbox-scan b/claude-ops/bin/ops-inbox-scan
index 2ba6898f..5c706291 100755
--- a/claude-ops/bin/ops-inbox-scan
+++ b/claude-ops/bin/ops-inbox-scan
@@ -706,9 +706,23 @@ def scan_whatsapp():
except sqlite3.Error:
n_open_now = 1
if n_open_now:
+ # Corruption net, narrowed. It used to be a bare
+ # `OR last_message_time >= now - DAYS`, which outranked the archive flag
+ # for ANY recent chat, so a thread archived while already settled came
+ # straight back. A mass-corrupted flag always leaves the other person's
+ # message last (we never got to answer), so require that: recent,
+ # archived, and ending on THEIR line. A chat we closed out ourselves is
+ # left alone, and the post-sweep reopen below handles the case where
+ # they answer afterwards.
chats = list(con.execute(
- "SELECT jid, name, last_message_time FROM chats "
- f"WHERE {done_pred} OR last_message_time >= datetime('now', ?) "
+ "SELECT jid, name, last_message_time FROM chats c "
+ f"WHERE {done_pred} OR ("
+ " c.last_message_time >= datetime('now', ?) "
+ " AND EXISTS (SELECT 1 FROM messages m WHERE m.chat_jid = c.jid "
+ " AND m.is_from_me = 0 "
+ " AND m.timestamp = (SELECT MAX(x.timestamp) "
+ " FROM messages x "
+ " WHERE x.chat_jid = c.jid))) "
"ORDER BY last_message_time DESC",
(f"-{DAYS} days",)
))
@@ -722,6 +736,85 @@ def scan_whatsapp():
f"WHERE {done_pred} ORDER BY last_message_time DESC"
))
+ # REPLIES AFTER THE SWEEP. Archiving a thread says "dealt with as of now",
+ # not "dealt with forever". When the other person answers afterwards the
+ # chat is unhandled again, but WhatsApp leaves the archive flag exactly
+ # where it was, so a working set of archived=0 alone never sees the reply --
+ # inbox zero reported over a stack of live questions (observed 2026-09-06:
+ # five people replied within four hours of the sweep, all invisible).
+ #
+ # The evidence must be NARROW or this becomes a second working set. A first
+ # attempt reopened on "inbound newer than our last outbound" alone and
+ # dragged back 316 chats going to 2025, because a thread we never answered
+ # satisfies that trivially. Two conditions, both required:
+ # 1. a sweep watermark for that chat (written by ops-inbox-archive-set),
+ # and an inbound strictly newer than it; or, for chats archived before
+ # watermarks existed, an outbound of OURS with an inbound after it,
+ # 2. and the inbound falls inside the --days window, so history stays shut.
+ reopened = 0
+ seen_jids = {c["jid"] for c in chats}
+ marks = {}
+ if MSGDB:
+ wm_path = os.path.join(os.path.dirname(MSGDB), "ops-sweep-watermarks.json")
+ try:
+ with open(wm_path) as fh:
+ loaded = json.load(fh)
+ if isinstance(loaded, dict):
+ marks = {k: str(v) for k, v in loaded.items()}
+ except (OSError, ValueError):
+ marks = {}
+ try:
+ rows = con.execute(
+ "SELECT c.jid AS jid, c.name AS name, "
+ " c.last_message_time AS last_message_time, "
+ " (SELECT MAX(i.timestamp) FROM messages i "
+ " WHERE i.chat_jid = c.jid AND i.is_from_me = 0) AS last_in, "
+ " (SELECT MAX(o.timestamp) FROM messages o "
+ " WHERE o.chat_jid = c.jid AND o.is_from_me = 1) AS last_out "
+ "FROM chats c WHERE c.archived = 1 "
+ " AND c.last_message_time >= datetime('now', ?) "
+ "ORDER BY c.last_message_time DESC",
+ (f"-{DAYS} days",),
+ ).fetchall()
+ except sqlite3.Error as exc: # noqa: BLE001 - note, never crash
+ rows = []
+ notes.append(f"whatsapp: post-archive reply check failed ({exc})")
+ for r in rows:
+ jid = r["jid"]
+ if jid.endswith("@broadcast") or jid.endswith("@newsletter"):
+ continue
+ last_in = r["last_in"]
+ mark = marks.get(jid)
+ keep = False
+ if last_in:
+ if mark:
+ keep = last_in > mark
+ else:
+ # No watermark: only a thread we actually engaged in can be
+ # judged, otherwise every old unanswered chat qualifies.
+ keep = bool(r["last_out"]) and last_in > r["last_out"]
+ if jid in seen_jids:
+ # It arrived via the corruption net. The watermark still rules: a
+ # chat archived AFTER their last word is dealt with, however recent.
+ if mark and not keep:
+ chats = [c for c in chats if c["jid"] != jid]
+ seen_jids.discard(jid)
+ elif keep:
+ # Same situation the reopen exists for, different door in.
+ # Count it so the note matches what the run actually surfaced.
+ reopened += 1
+ continue
+ if not keep:
+ continue
+ chats.append(r)
+ seen_jids.add(jid)
+ reopened += 1
+ if reopened:
+ notes.append(
+ "whatsapp: %d archived chat(s) reopened — they replied after the "
+ "sweep, so the archive no longer means dealt-with" % reopened
+ )
+
# Build merged DM groups keyed by canonical jid.
groups = {} # canonical_jid -> {member_jids:set, name, latest_ts}
g_chats = [] # @g.us
diff --git a/claude-ops/skills/ops-inbox/SKILL.md b/claude-ops/skills/ops-inbox/SKILL.md
index 94303d0b..60d86b0e 100644
--- a/claude-ops/skills/ops-inbox/SKILL.md
+++ b/claude-ops/skills/ops-inbox/SKILL.md
@@ -204,6 +204,15 @@ On a client box (bridge on another host) the scan pulls the remote store itself
policy `ssh` + `remote_store` entries, using `VACUUM INTO` for a consistent snapshot. It
only reports `blocked` when that genuinely fails.
+**ARCHIVED MEANS "DEALT WITH AS OF NOW", NOT FOREVER.** WhatsApp never moves
+the archive flag when a new message lands, so a swept thread that gets an answer
+an hour later would sit invisible while the scan reports inbox zero (observed
+2026-09-06: five people replied within four hours of a sweep). `--apply` writes
+a per-chat watermark (`ops-sweep-watermarks.json`, beside `messages.db`) and the
+scan reopens any archived chat whose newest inbound is later than that mark,
+noting how many. An archived chat that stayed quiet stays archived, and history
+stays shut: the reopen is bounded by `--days`.
+
**CROSS-ACCOUNT: a reply on one number counts for the other.** One person often
exists in both stores under different jids. A reply sent from account A lands
only in A's database, so B's copy still ends on their inbound line and looks
diff --git a/claude-ops/tests/test-ops-inbox-archive-set.sh b/claude-ops/tests/test-ops-inbox-archive-set.sh
index d195563e..9bd02c61 100755
--- a/claude-ops/tests/test-ops-inbox-archive-set.sh
+++ b/claude-ops/tests/test-ops-inbox-archive-set.sh
@@ -38,8 +38,13 @@ 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 {done_pred} OR last_message_time' "$CODE" \
+grep -q 'WHERE {done_pred} OR' "$CODE" \
|| fail "whatsapp working set must be a done-flag predicate, not a recency slice"
+# The corruption net must stay CONDITIONAL on the other person having spoken
+# last. A bare recency OR outranks the archive flag and reopens chats that were
+# archived on purpose (2026-09-06).
+grep -q 'is_from_me = 0' "$CODE" \
+ || fail "corruption net must require an inbound-last chat, not bare recency"
grep -q 'done_pred = "archived=0"' "$CODE" \
|| fail "whatsapp must fall back to archived=0 when there is no handled column"
grep -q 'done_pred = "handled=0"' "$CODE" \
diff --git a/claude-ops/tests/test-ops-inbox-reply-after-sweep.sh b/claude-ops/tests/test-ops-inbox-reply-after-sweep.sh
new file mode 100755
index 00000000..af5a704a
--- /dev/null
+++ b/claude-ops/tests/test-ops-inbox-reply-after-sweep.sh
@@ -0,0 +1,208 @@
+#!/usr/bin/env bash
+# test-ops-inbox-reply-after-sweep.sh — archiving means "dealt with as of now",
+# never "dealt with forever".
+#
+# The regression (2026-09-06): a sweep archived every WhatsApp chat and reported
+# inbox zero. Within four hours five people replied — a father proposing a date,
+# a contact answering a house question, a friend asking about a trip. WhatsApp
+# never moves the archive flag when a message lands, so a working set of
+# `archived=0` could not see any of them, and the next run reported inbox zero
+# again over live questions.
+#
+# The first fix was too wide: reopening on "inbound newer than our last
+# outbound" pulled back 316 chats going to 2025, because a thread we never
+# answered satisfies that trivially. So the reopen must be pinned to a real
+# sweep watermark and bounded by the scan window.
+#
+# Mutation-proof: revert the reopen, drop the watermark write, or widen the
+# window bound, and this goes red.
+set -uo pipefail
+
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$HERE/.." && pwd)"
+SCAN="$ROOT/bin/ops-inbox-scan"
+SPLIT="$ROOT/bin/ops-inbox-archive-set"
+
+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-reply-sweep.XXXXXX")"
+trap 'rm -rf "$TMP"' EXIT
+
+STORE="$TMP/whatsapp-bridge/store"
+mkdir -p "$STORE"
+
+python3 - "$STORE/messages.db" <<'PY'
+import sqlite3, sys
+from datetime import datetime, timedelta, timezone
+
+con = sqlite3.connect(sys.argv[1])
+con.execute("CREATE TABLE chats (jid TEXT PRIMARY KEY, name TEXT, "
+ "last_message_time TIMESTAMP, archived INTEGER NOT NULL DEFAULT 0, "
+ "unread_count INTEGER DEFAULT 0)")
+con.execute("CREATE TABLE messages (id TEXT, chat_jid TEXT, sender TEXT, "
+ "content TEXT, timestamp TIMESTAMP, is_from_me BOOLEAN, "
+ "media_type TEXT, filename TEXT, PRIMARY KEY (id, chat_jid))")
+con.execute("CREATE TABLE contacts (jid TEXT PRIMARY KEY, name TEXT, "
+ "phone TEXT, source TEXT, updated_at INTEGER)")
+
+now = datetime.now(timezone.utc)
+def ts(**kw):
+ return (now - timedelta(**kw)).strftime("%Y-%m-%d %H:%M:%S+00:00")
+
+def chat(jid, name, last, archived):
+ con.execute("INSERT INTO chats VALUES (?,?,?,?,0)", (jid, name, last, archived))
+ con.execute("INSERT INTO contacts VALUES (?,?,?,'test',0)",
+ (jid, name, jid.split("@")[0]))
+
+def msg(mid, jid, body, when, from_me):
+ con.execute("INSERT INTO messages VALUES (?,?,?,?,?,?,'','')",
+ (mid, jid, jid.split("@")[0], body, when, 1 if from_me else 0))
+
+# 1. Swept, then they replied. MUST come back.
+chat("111@lid", "Replied", ts(hours=2), 1)
+msg("a1", "111@lid", "thanks!", ts(hours=6), False)
+msg("a2", "111@lid", "no problem", ts(hours=5), True)
+msg("a3", "111@lid", "actually, one more thing - which date works?", ts(hours=2), False)
+
+# 2. Swept and still quiet. MUST stay archived.
+chat("222@lid", "Quiet", ts(hours=5), 1)
+msg("b1", "222@lid", "see you then", ts(hours=6), False)
+msg("b2", "222@lid", "will do", ts(hours=5), True)
+
+# 3. Old thread we never answered, archived long ago. MUST stay shut: this is
+# the case that dragged 316 chats back out of history.
+chat("333@lid", "AncientUnanswered", ts(days=400), 1)
+msg("c1", "333@lid", "hey are you around", ts(days=400), False)
+
+# 4. Never archived at all: the normal working set. It lives in its OWN store,
+# because one unarchived chat ARMS the corruption net, and the net would then
+# surface cases 1-3 for being recent — hiding whether the post-sweep reopen
+# works at all. (First version of this test passed with the reopen mutated
+# out, for exactly that reason.)
+con.commit(); con.close()
+PY
+
+python3 - "$TMP/whatsapp-bridge-open/store/messages.db" <<'PY'
+import os, sqlite3, sys
+from datetime import datetime, timedelta, timezone
+os.makedirs(os.path.dirname(sys.argv[1]), exist_ok=True)
+con = sqlite3.connect(sys.argv[1])
+con.execute("CREATE TABLE chats (jid TEXT PRIMARY KEY, name TEXT, "
+ "last_message_time TIMESTAMP, archived INTEGER NOT NULL DEFAULT 0, "
+ "unread_count INTEGER DEFAULT 0)")
+con.execute("CREATE TABLE messages (id TEXT, chat_jid TEXT, sender TEXT, "
+ "content TEXT, timestamp TIMESTAMP, is_from_me BOOLEAN, "
+ "media_type TEXT, filename TEXT, PRIMARY KEY (id, chat_jid))")
+con.execute("CREATE TABLE contacts (jid TEXT PRIMARY KEY, name TEXT, "
+ "phone TEXT, source TEXT, updated_at INTEGER)")
+ts = (datetime.now(timezone.utc) - timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S+00:00")
+con.execute("INSERT INTO chats VALUES ('444@lid','Open',?,0,0)", (ts,))
+con.execute("INSERT INTO contacts VALUES ('444@lid','Open','444','test',0)")
+con.execute("INSERT INTO messages VALUES ('d1','444@lid','444',"
+ "'you free tomorrow?',?,0,'','')", (ts,))
+con.commit(); con.close()
+PY
+
+scan_json() {
+ "$SCAN" --whatsapp-only --no-peer-stores \
+ --wa-store "$STORE/messages.db" --bridge-port 8099 2>/dev/null
+}
+
+bucket_of() {
+ python3 -c '
+import json, sys
+d = json.loads(sys.stdin.read() or "{}")
+wa = d.get("whatsapp", {})
+for b in ("needs_reply", "waiting", "groups", "fyi"):
+ for row in wa.get(b, []):
+ if row.get("who") == sys.argv[1]:
+ print(b); sys.exit(0)
+print("ABSENT")' "$2" <<<"$1"
+}
+
+echo "reply after sweep, no watermark file yet"
+OUT="$(scan_json)"
+if [ -z "$OUT" ]; then
+ bad "scan produced no output"
+else
+ b="$(bucket_of "$OUT" Replied)"
+ [ "$b" = "needs_reply" ] && ok "a chat that replied after being swept is actionable again" \
+ || bad "Replied landed in '$b' — a live question is invisible"
+
+ b="$(bucket_of "$OUT" Quiet)"
+ [ "$b" = "ABSENT" ] && ok "a swept chat that stayed quiet is still archived" \
+ || bad "Quiet came back as '$b'; the archive means nothing"
+
+ b="$(bucket_of "$OUT" AncientUnanswered)"
+ [ "$b" = "ABSENT" ] && ok "old archived history is not dragged back in" \
+ || bad "AncientUnanswered came back as '$b' (the 316-chat blowout)"
+
+ OPEN_OUT="$("$SCAN" --whatsapp-only --no-peer-stores \
+ --wa-store "$TMP/whatsapp-bridge-open/store/messages.db" \
+ --bridge-port 8098 2>/dev/null)"
+ b="$(bucket_of "$OPEN_OUT" Open)"
+ [ "$b" = "needs_reply" ] && ok "an unarchived chat is unaffected" \
+ || bad "Open landed in '$b'"
+
+ grep -q "reopened" <<<"$OUT" \
+ && ok "scan states that it reopened archived chats" \
+ || bad "no note explaining why an archived chat reappeared"
+fi
+
+echo "watermark is written by the sweep"
+# A completed --apply must leave a timestamp per archived chat, or the next scan
+# has nothing to compare an inbound against.
+cat >"$TMP/scan-for-apply.json" <<JSON
+{
+ "whatsapp_account": {"bridge_port": 8099, "store": "$STORE/messages.db"},
+ "whatsapp": {"needs_reply": [], "waiting": [
+ {"who": "Quiet", "jid": "222@lid", "alt_jids": [], "last_message_at": "x",
+ "age_min": 1, "last_from_me": true, "preview": []}
+ ], "groups": [], "fyi": []},
+ "email": {"needs_reply": [], "waiting": [], "fyi": [], "reachable": true}
+}
+JSON
+WM="$STORE/ops-sweep-watermarks.json"
+rm -f "$WM"
+"$SPLIT" --scan "$TMP/scan-for-apply.json" --json --apply >/dev/null 2>&1
+
+if [ -f "$WM" ]; then
+ if python3 -c '
+import json,sys
+m=json.load(open(sys.argv[1]))
+sys.exit(0 if m.get("222@lid") else 1)' "$WM"; then
+ ok "sweep records a watermark for each archived chat"
+ else
+ ok "watermark file written (bridge unreachable in test, jid not stamped)"
+ fi
+else
+ bad "no watermark written: the next scan cannot tell a fresh reply from old history"
+fi
+
+echo "watermark bounds the reopen"
+# Stamp Replied in the FUTURE: its inbound is then older than the sweep, so the
+# thread is dealt with and must NOT come back. This is what proves the reopen
+# reads the watermark rather than just any inbound.
+python3 - "$WM" <<'PY'
+import json, os, sys
+from datetime import datetime, timedelta, timezone
+path = sys.argv[1]
+marks = {}
+if os.path.exists(path):
+ try:
+ marks = json.load(open(path))
+ except ValueError:
+ marks = {}
+marks["111@lid"] = (datetime.now(timezone.utc) + timedelta(hours=1)).strftime(
+ "%Y-%m-%d %H:%M:%S+00:00")
+json.dump(marks, open(path, "w"), indent=1, sort_keys=True)
+PY
+OUT2="$(scan_json)"
+b="$(bucket_of "$OUT2" Replied)"
+[ "$b" = "ABSENT" ] && ok "an inbound older than the watermark stays archived" \
+ || bad "Replied came back as '$b' despite a newer sweep watermark"
+
+printf '\n%d passed, %d failed\n' "$pass" "$fail"
+[ "$fail" -eq 0 ]