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 every account, pull the remote store, stop reading unread (#926)

Aurora Capital08cdd727ce7b
diff --git a/claude-ops/bin/ops-inbox-archive-set b/claude-ops/bin/ops-inbox-archive-set
index a48e7201..5f5a93cb 100755
--- a/claude-ops/bin/ops-inbox-archive-set
+++ b/claude-ops/bin/ops-inbox-archive-set
@@ -172,10 +172,22 @@ def classify_whatsapp(scan, stale_min, dead_group_min):
archive, keep, fyi = [], [], []
wa = scan.get("whatsapp", {})
+ def _acct(rec):
+ """Which number this row lives on.
+
+ A merged multi-account scan tags every row with its account and bridge
+ port. Falling back to a single "default" here is how an archive lands on
+ the wrong number — so carry the tag whenever the scan provides one.
+ """
+ out = {"account": rec.get("account") or "default"}
+ if rec.get("bridge_port"):
+ out["bridge_port"] = rec["bridge_port"]
+ return out
+
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"}
+ "alt_jids": rec.get("alt_jids") or [], **_acct(rec)}
if age > stale_min:
row["why"] = "stale (older than window)"
archive.append(row)
@@ -189,18 +201,18 @@ def classify_whatsapp(scan, stale_min, dead_group_min):
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",
+ "alt_jids": rec.get("alt_jids") or [], **_acct(rec),
"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",
+ "alt_jids": [], **_acct(rec),
"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",
+ "alt_jids": [], **_acct(rec),
"why": "dead group chat"})
return archive, keep, fyi
@@ -255,7 +267,7 @@ def classify_email(scan):
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", []):
+ for item in (scan.get("email") or {}).get("fyi", []) or []:
label = protecting_label(item.get("labels"))
row = {"who": item.get("who"), "subject": item.get("subject"),
"threadId": item.get("threadId")}
@@ -272,9 +284,23 @@ def classify_email(scan):
# --------------------------------------------------------------------------
def archive_whatsapp(rows, port, dry):
+ """Archive each chat on ITS OWN bridge.
+
+ `port` is only the fallback for rows that carry no account tag. A merged
+ multi-account scan tags every row with the bridge it came from, and sending
+ all of them to one port would archive a thread on a number it does not live
+ on — the same wrong-number class this toolchain already fixed once for
+ sending. Rows whose tagged port is unknown are LEFT ALONE, never guessed.
+ """
import urllib.request
ok = fail = 0
for row in rows:
+ row_port = row.get("bridge_port") or port
+ if not row_port:
+ fail += 1
+ print(" archive skipped %s: no bridge port for account %s"
+ % (row.get("jid"), row.get("account")), file=sys.stderr)
+ continue
for jid in [row.get("jid")] + list(row.get("alt_jids") or []):
if not jid:
continue
@@ -283,7 +309,7 @@ def archive_whatsapp(rows, port, dry):
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,
+ "http://127.0.0.1:%d/api/archive" % int(row_port), data=body,
headers={"Content-Type": "application/json"})
try:
urllib.request.urlopen(req, timeout=20).read()
@@ -425,15 +451,21 @@ def main():
except (OSError, subprocess.SubprocessError):
pass
if main_port is None and wa_archive:
- errors.append(
- "WhatsApp archive skipped: could not resolve which account these "
- "chats belong to. Pass --default-bridge-port, or set agent_enabled "
- "in the ops-wa-accounts policy file.")
+ # Rows that carry their own bridge_port do not need a global default;
+ # only the untagged remainder is genuinely unroutable.
+ untagged = [r for r in wa_archive if not r.get("bridge_port")]
+ if untagged:
+ errors.append(
+ "WhatsApp archive skipped for %d chat(s): could not resolve which "
+ "account they belong to. Pass --default-bridge-port, or set "
+ "agent_enabled in the ops-wa-accounts policy file." % len(untagged))
+ else:
+ port_source = "per-row account tag (merged multi-account scan)"
result["whatsapp_bridge_port"] = main_port
result["whatsapp_bridge_port_source"] = port_source
if args.apply:
- if main_port is None:
+ if main_port is None and not any(r.get("bridge_port") for r in wa_archive):
ok, fail = 0, 0
else:
ok, fail = archive_whatsapp(wa_archive, main_port, args.dry_run)
diff --git a/claude-ops/bin/ops-inbox-scan b/claude-ops/bin/ops-inbox-scan
index ba5d605d..ef7f0f17 100755
--- a/claude-ops/bin/ops-inbox-scan
+++ b/claude-ops/bin/ops-inbox-scan
@@ -38,6 +38,7 @@
# --gmail-account ADDR override Gmail account (default: gog default)
# --wa-store DB WhatsApp messages.db to scan
# --bridge-port N bridge REST port for that store
+# --all-accounts scan EVERY agent-enabled account, not one
# --pretty pretty-print JSON
#
# WHICH WHATSAPP ACCOUNT: more than one bridge can run here, one per number, and
@@ -57,6 +58,7 @@ EMAIL_QUERY="in:inbox"
EMAIL_MAX=400
WA_STORE_OVERRIDE=""
BRIDGE_PORT_OVERRIDE=""
+ALL_ACCOUNTS=0
while [ $# -gt 0 ]; do
case "$1" in
@@ -68,6 +70,7 @@ while [ $# -gt 0 ]; do
--gmail-account) GMAIL_ACCOUNT="${2:-}"; shift ;;
--wa-store) WA_STORE_OVERRIDE="${2:-}"; shift ;;
--bridge-port) BRIDGE_PORT_OVERRIDE="${2:-}"; shift ;;
+ --all-accounts) ALL_ACCOUNTS=1 ;;
--pretty) PRETTY=1 ;;
-h|--help)
grep '^#' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
@@ -76,6 +79,102 @@ while [ $# -gt 0 ]; do
shift
done
+# ------------------------------------------------- every agent-enabled acct ----
+# THE DEFECT THIS CLOSES (2026-09-06). With two agent-enabled numbers the
+# resolver correctly refuses to pick one and this script exited 3. Callers then
+# either passed one account (silently scanning half the inbox) or fell back to
+# an `unread` listing — and `unread` is a DISPLAY state, empty for every thread
+# the owner already opened on their phone. A person's real unanswered ask does
+# not have to be unread. So: scan EVERY enabled account and merge, labelled.
+if [ "$ALL_ACCOUNTS" = 1 ]; then
+ [ -n "$WA_STORE_OVERRIDE$BRIDGE_PORT_OVERRIDE" ] && {
+ echo "ops-inbox-scan: --all-accounts cannot be combined with --wa-store/--bridge-port" >&2
+ exit 2
+ }
+ _resolver="$(dirname "$0")/ops-wa-accounts"
+ [ -x "$_resolver" ] || { echo "ops-inbox-scan: ops-wa-accounts not found" >&2; exit 4; }
+ _self="$0"
+ "$_resolver" | OIS_SELF="$_self" OIS_DAYS="$DAYS" OIS_DO_EMAIL="$DO_EMAIL" \
+ OIS_EMAIL_QUERY="$EMAIL_QUERY" OIS_EMAIL_MAX="$EMAIL_MAX" \
+ OIS_GMAIL_ACCOUNT="$GMAIL_ACCOUNT" OIS_PRETTY="$PRETTY" python3 -c '
+import json, os, subprocess, sys
+
+blob = json.load(sys.stdin)
+enabled = [a for a in blob.get("accounts", []) if a.get("agent_enabled") is True]
+if not enabled:
+ print(json.dumps({"error": "no agent-enabled WhatsApp account", "notes": blob.get("notes", [])}))
+ sys.exit(3)
+
+self_bin = os.environ["OIS_SELF"]
+merged = {"generated_at": None, "window_days": int(os.environ["OIS_DAYS"]),
+ "notes": [], "whatsapp_accounts": []}
+first = True
+for acct in enabled:
+ store = acct.get("store") or acct.get("remote_store") or ""
+ port = acct.get("port")
+ cmd = [self_bin, "--whatsapp-only", "--days", os.environ["OIS_DAYS"],
+ "--wa-store", store, "--bridge-port", str(port)]
+ env = dict(os.environ, OIS_SSH=acct.get("ssh") or "",
+ OIS_SSH_FALLBACK=acct.get("ssh_fallback") or "",
+ OIS_REMOTE_STORE=acct.get("remote_store") or "",
+ OIS_LABEL=acct.get("label") or "", OIS_PHONE=acct.get("phone") or "")
+ try:
+ out = subprocess.run(cmd, capture_output=True, text=True, timeout=300, env=env)
+ one = json.loads(out.stdout or "{}")
+ except Exception as exc: # a broken account must be LOUD, never silent
+ one = {"whatsapp": {"reachable": False, "error": str(exc)}}
+ merged["generated_at"] = merged["generated_at"] or one.get("generated_at")
+ merged["notes"].extend(one.get("notes", []))
+ merged["whatsapp_accounts"].append({
+ "account": acct.get("label"), "phone": acct.get("phone"),
+ "bridge_port": port, "store": store,
+ **one.get("whatsapp", {}),
+ })
+ first = False
+
+if os.environ.get("OIS_DO_EMAIL") == "1":
+ cmd = [self_bin, "--email-only", "--email-query", os.environ["OIS_EMAIL_QUERY"],
+ "--email-max", os.environ["OIS_EMAIL_MAX"]]
+ if os.environ.get("OIS_GMAIL_ACCOUNT"):
+ cmd += ["--gmail-account", os.environ["OIS_GMAIL_ACCOUNT"]]
+ try:
+ out = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
+ one = json.loads(out.stdout or "{}")
+ merged["email"] = one.get("email")
+ merged["notes"].extend(one.get("notes", []))
+ except Exception as exc:
+ merged["email"] = {"reachable": False, "note": "email scan failed: %s" % exc}
+
+merged["counts"] = {
+ "whatsapp": {a["account"]: {b: len(a.get(b) or []) for b in
+ ("needs_reply", "waiting", "groups", "fyi")}
+ for a in merged["whatsapp_accounts"]},
+ "email": {b: len((merged.get("email") or {}).get(b) or [])
+ for b in ("needs_reply", "waiting", "fyi")} if merged.get("email") else None,
+}
+# BACK-COMPAT: every existing consumer (ops-inbox-archive-set, ops-inbox-zero)
+# iterates scan["whatsapp"][bucket]. Adding only the per-account list would make
+# them silently see nothing — the exact silent-drop class this fix exists to
+# kill. So also emit the flat union, with each row tagged by account so a reply
+# still goes out on the number the thread actually lives on.
+flat = {"needs_reply": [], "waiting": [], "groups": [], "fyi": [],
+ "reachable": any(a.get("reachable") is not False for a in merged["whatsapp_accounts"])}
+for a in merged["whatsapp_accounts"]:
+ for b in ("needs_reply", "waiting", "groups", "fyi"):
+ for row in (a.get(b) or []):
+ row = dict(row)
+ row["account"] = a.get("account")
+ row["bridge_port"] = a.get("bridge_port")
+ flat[b].append(row)
+for b in ("needs_reply", "waiting", "groups", "fyi"):
+ flat[b].sort(key=lambda x: x.get("age_min") if x.get("age_min") is not None else 1 << 30)
+merged["whatsapp"] = flat
+print(json.dumps(merged, indent=2 if os.environ.get("OIS_PRETTY") == "1" else None,
+ ensure_ascii=False))
+'
+ exit $?
+fi
+
# --------------------------------------------------------- which account ----
# Resolution order: explicit flags, then the long-standing WHATSAPP_BRIDGE_*
# env vars, then whichever single account policy marks agent-enabled. The last
@@ -127,9 +226,51 @@ WA_WADB="$WA_STORE/whatsapp.db"
BRIDGE_PORT="${BRIDGE_PORT:-8080}"
BRIDGE_API="http://127.0.0.1:${BRIDGE_PORT}"
+# ------------------------------------------------------- remote store pull ----
+# THE DEFECT THIS CLOSES (2026-09-06). When the bridge runs on another host this
+# box is a CLIENT: there is no local messages.db at all. The scan used to answer
+# that with empty buckets plus a note telling the agent to "use live MCP" — and
+# an agent that only calls the unread listing then reports inbox zero on a
+# mailbox full of unanswered asks. Empty output is never evidence of an empty
+# inbox. Policy already carries `ssh` + `remote_store`, so USE them: snapshot the
+# remote sqlite read-only into a temp file and classify it exactly like a local
+# store. Only when that genuinely fails do we fall back to the remote-only note.
+WA_REMOTE_PULLED=0
+if [ "$DO_WA" = 1 ] && [ ! -f "$WA_MSGDB" ]; then
+ _rs="${OIS_REMOTE_STORE:-$WA_MSGDB}"
+ for _host in "${OIS_SSH:-}" "${OIS_SSH_FALLBACK:-}"; do
+ [ -n "$_host" ] || continue
+ _tmpdir="$(mktemp -d "${TMPDIR:-/tmp}/ois-wa.XXXXXX")"
+ # VACUUM INTO is the only safe way to copy a live sqlite db: it takes a
+ # consistent snapshot without a writer lock and never risks the WAL. A plain
+ # `scp` of a hot db can copy a torn page set.
+ if ssh -o BatchMode=yes -o ConnectTimeout=8 "$_host" \
+ "rm -f /tmp/ois-snap.db && sqlite3 'file:${_rs}?mode=ro' \"VACUUM INTO '/tmp/ois-snap.db'\"" \
+ >/dev/null 2>&1 &&
+ scp -q -o BatchMode=yes -o ConnectTimeout=8 "$_host:/tmp/ois-snap.db" "$_tmpdir/messages.db" 2>/dev/null; then
+ ssh -o BatchMode=yes -o ConnectTimeout=8 "$_host" "rm -f /tmp/ois-snap.db" >/dev/null 2>&1 || true
+ WA_MSGDB="$_tmpdir/messages.db"
+ WA_STORE="$_tmpdir"
+ WA_WADB="$_tmpdir/whatsapp.db" # optional; absent => lid map falls back
+ WA_REMOTE_PULLED=1
+ WA_ACCOUNT_SOURCE="${WA_ACCOUNT_SOURCE}+ssh:${_host}"
+ break
+ fi
+ rm -rf "$_tmpdir"
+ done
+fi
+export OIS_WA_REMOTE_PULLED="$WA_REMOTE_PULLED"
+
# Resolve a default Gmail account from gog if not supplied (best-effort).
+# `gog whoami` prints several tab-separated lines (name, email, photo...) and
+# the address is NOT on the first one. Piping through `head -1` therefore threw
+# the account away, and every downstream call ran without --account: on a box
+# with many tokens gog then refuses with "missing --account" and the scan
+# reports an unreachable mailbox that is in fact perfectly reachable. Scan all
+# lines and take the first address.
if [ "$DO_EMAIL" = 1 ] && [ -z "$GMAIL_ACCOUNT" ]; then
- GMAIL_ACCOUNT="$(gog whoami 2>/dev/null | head -1 | grep -oE '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+' || true)"
+ GMAIL_ACCOUNT="$(gog whoami 2>/dev/null \
+ | grep -oE '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}' | head -1 || true)"
fi
export OIS_DAYS="$DAYS" OIS_DO_WA="$DO_WA" OIS_DO_EMAIL="$DO_EMAIL"
@@ -202,6 +343,7 @@ export OIS_SENDLOG_FILE
# python never shells out. Empty file => python emits an "unreachable" note.
GMAIL_JSON_FILE=""
GMAIL_ERR=""
+GMAIL_OK=0
if [ "$DO_EMAIL" = 1 ]; then
GMAIL_JSON_FILE="$(mktemp "${TMPDIR:-/tmp}/ois-gmail.XXXXXX")"
trap 'rm -f "$GMAIL_JSON_FILE" "${OIS_SENDLOG_FILE:-}"' EXIT
@@ -218,10 +360,17 @@ if [ "$DO_EMAIL" = 1 ]; 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
+ else
+ # A GENUINELY EMPTY INBOX IS A RESULT, NOT A FAILURE. gog prints `[]` for
+ # zero hits, and the old code could not tell that apart from a call that
+ # never ran — both left an unusable file and the scan said "unreachable".
+ # Marking the success explicitly keeps "inbox zero" and "scan broke" as two
+ # different answers, which is the whole point.
+ GMAIL_OK=1
fi
rm -f "${GMAIL_JSON_FILE}.err" 2>/dev/null || true
fi
-export OIS_GMAIL_JSON_FILE="$GMAIL_JSON_FILE" OIS_GMAIL_ERR="$GMAIL_ERR"
+export OIS_GMAIL_JSON_FILE="$GMAIL_JSON_FILE" OIS_GMAIL_ERR="$GMAIL_ERR" OIS_GMAIL_OK="$GMAIL_OK"
python3 <<'PY'
import os, sys, json, sqlite3, re
@@ -236,6 +385,7 @@ ACCT = os.environ.get("OIS_GMAIL_ACCOUNT", "")
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"
SENDLOG_F = os.environ.get("OIS_SENDLOG_FILE", "")
now = datetime.now(timezone.utc)
@@ -317,19 +467,19 @@ def ro(path):
def scan_whatsapp():
out = {"needs_reply": [], "waiting": [], "groups": [], "fyi": []}
if not os.path.exists(MSGDB):
- # No local WhatsApp store. Treat WhatsApp as REMOTE-ONLY: the canonical
- # bridge may run on a remote host, reached via the live MCP tools
- # (mcp__whatsapp__*). An absent local sqlite store must NOT be read as
- # "no messages" — signal the orchestrator to scan WhatsApp via live MCP.
+ # No store, local OR pulled. The SSH snapshot above already tried and
+ # failed, so this is a genuine blocker, not a quiet "nothing here".
out["reachable"] = False
out["source"] = "remote"
out["scan_via"] = "live-mcp"
+ out["blocked"] = True
notes.append(
- "whatsapp: no local store — scan via the LIVE MCP tools "
- "(mcp__whatsapp__list_chats / list_messages), which read the canonical "
- "bridge. Do NOT treat these empty buckets as 'no messages'. WA replies are "
- "DRAFT-ONLY: never auto-send based on store state (the store can lag "
- "phone-sent messages)."
+ "whatsapp: NO STORE — the local store is absent and the ssh/remote_store "
+ "snapshot failed. These empty buckets are a FAILED SCAN, not an empty "
+ "inbox. Do not report inbox zero. Fix the ssh path in policy, or scan "
+ "every non-handled chat via the live bridge tools (find/thread — NOT the "
+ "unread listing, which is a display state and is empty for any thread "
+ "already opened on a phone). WA replies stay DRAFT-ONLY."
)
return out
con = ro(MSGDB)
@@ -381,15 +531,46 @@ def scan_whatsapp():
return cand
return jid
- # Working set: non-archived OR any chat with activity in the recency window.
- # The local `archived` flag has been observed mass-corrupted (every chat
- # flagged archived=1, including live two-way threads), which silently blinds
- # the scan into a false "inbox zero". Falling back to recency guarantees a
- # corrupt flag can NEVER hide an actively-conversing chat; genuinely-archived
- # OLD chats (no msgs in the window) still stay hidden. (2026-06-09 fix.)
+ # Working set: everything the owner has not DEALT WITH yet.
+ #
+ # Three columns can define "still in my inbox" and only one of them means
+ # what we need:
+ # * unread_count — a DISPLAY state. The owner reads on a phone, so every
+ # real thread reads 0. Scanning unread reports inbox
+ # zero on a mailbox full of unanswered asks. Never use it.
+ # * archived — has been observed mass-corrupted (every chat flagged
+ # archived=1, live two-way threads included), which
+ # silently blinds the scan the same way.
+ # * handled — set by this toolchain when a thread was actioned or
+ # swept. That is the real "done" bit, so `handled=0` is
+ # the working set when the column exists.
+ # Recency is kept as a floor so a corrupt flag can never hide an actively
+ # conversing chat, and genuinely old dealt-with chats still stay hidden.
+ has_handled = False
+ try:
+ has_handled = any(r[1] == "handled" for r in
+ con.execute("PRAGMA table_info(chats)"))
+ except sqlite3.Error:
+ pass
+ if has_handled:
+ done_pred = "(handled=0 AND archived=0)"
+ # A store where EVERY chat is archived=1 is the corruption case above;
+ # there `handled` alone is the only trustworthy signal.
+ try:
+ n_open = con.execute("SELECT count(*) FROM chats WHERE archived=0").fetchone()[0]
+ except sqlite3.Error:
+ n_open = 1
+ if not n_open:
+ done_pred = "handled=0"
+ notes.append(
+ "whatsapp: every chat is flagged archived=1 (known corruption); "
+ "using handled=0 as the working set instead"
+ )
+ else:
+ done_pred = "archived=0"
chats = list(con.execute(
"SELECT jid, name, last_message_time FROM chats "
- "WHERE archived=0 OR last_message_time >= datetime('now', ?) "
+ f"WHERE {done_pred} OR last_message_time >= datetime('now', ?) "
"ORDER BY last_message_time DESC",
(f"-{DAYS} days",)
))
@@ -575,6 +756,11 @@ def scan_email():
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:
+ if GMAIL_OK:
+ # The call succeeded and returned nothing: a real, empty inbox.
+ res["empty"] = True
+ res["note"] = "inbox is empty (gog gmail search returned no results)"
+ return res
res["reachable"] = False
res["note"] = "gmail unreachable: " + (GMAIL_ERR or "empty result from gog gmail search")
return res
@@ -586,6 +772,12 @@ def scan_email():
res["note"] = f"gmail result unparseable: {e}"
return res
rows = data if isinstance(data, list) else data.get("results", data.get("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.
+ res["empty"] = True
+ res["note"] = "inbox is empty (gog gmail search returned no results)"
+ return res
self_addr = ACCT.lower()
for r in rows or []:
labels = r.get("labels") or r.get("labelIds") or []
diff --git a/claude-ops/skills/ops-inbox/SKILL.md b/claude-ops/skills/ops-inbox/SKILL.md
index 1145e515..47c98db0 100644
--- a/claude-ops/skills/ops-inbox/SKILL.md
+++ b/claude-ops/skills/ops-inbox/SKILL.md
@@ -146,7 +146,7 @@ Every run, in order:
Before drafting to any person, load `relations` for their brief and open
commitments.
1. Resolve the WhatsApp account (`ops-wa-accounts` — never hardcode a port).
-2. Freshness: `~/bin/wa-inbox-fresh.sh` (blocking, bounded). Then `bin/ops-inbox-scan`.
+2. Freshness: `~/bin/wa-inbox-fresh.sh` (blocking, bounded). Then `bin/ops-inbox-scan --all-accounts`. Never an unread listing: unread is a display state and is empty for every thread already opened on a phone.
3. **All-context sweep** (Rule 9 + `references/details.md` "ALL CONTEXT SOURCES"): query every configured calendar, mailbox, and messaging channel before any schedule claim or NEEDS_REPLY draft. Google Calendar alone is not enough — Notion show/calendar databases count when Notion is configured. A miss on one store is not absence.
4. `bin/ops-inbox-archive-set` report-only. Present KEEP vs ARCHIVE; `--apply` only after explicit OK.
5. Deep-read KEEP / NEEDS_REPLY. Fan out if volume (`references/fan-out.md`).
@@ -171,19 +171,38 @@ heaviest channels — WhatsApp (direct read of the whatsmeow sqlite store) and E
JSON. No subagents, no MCP, near-zero tokens.
```bash
-"$CLAUDE_PLUGIN_ROOT/bin/ops-inbox-scan" --pretty # both channels
+"$CLAUDE_PLUGIN_ROOT/bin/ops-inbox-scan" --all-accounts --pretty # EVERY enabled number
"$CLAUDE_PLUGIN_ROOT/bin/ops-inbox-scan" --whatsapp-only # WA only
"$CLAUDE_PLUGIN_ROOT/bin/ops-inbox-scan" --days 14 # wider window
-# target a specific WhatsApp account (both flags, or neither):
+# target one specific WhatsApp account instead:
"$CLAUDE_PLUGIN_ROOT/bin/ops-inbox-scan" \
--wa-store ~/.local/share/whatsapp-mcp/whatsapp-bridge-<label>/store/messages.db \
--bridge-port <port>
```
-With no flags the scan resolves the single agent-enabled account itself and **exits 3 rather than
-guess** when that is ambiguous. Its JSON carries a `whatsapp_account` block (`phone`, `bridge_port`,
-`store`, `resolved_by`) — that is the account every downstream archive and reply must use, and
-`ops-inbox-archive-set` reads it so the two can never drift onto different numbers.
+**`--all-accounts` is the default choice when more than one number is agent-enabled.**
+It scans each one, labels every row with its account and bridge port, and still emits the
+flat `whatsapp` buckets older consumers read. Without it the scan exits 3 rather than pick
+a number, and a caller that "handles" that by scanning one account silently reports half
+an inbox.
+
+**NEVER substitute an unread listing for a scan.** `unread` is a DISPLAY state: an owner
+who reads on a phone leaves every real thread at zero unread, so an unread-only sweep
+reports inbox zero over a mailbox full of unanswered asks. The working set is what has not
+been DEALT WITH (`handled=0`, falling back to `archived=0`), never what has not been seen.
+
+**Empty buckets are only trustworthy when the scan says it succeeded.** Check the flags
+before believing a zero:
+
+| field | meaning | what you do |
+|---|---|---|
+| `email.empty: true` | search ran, zero hits | real inbox zero |
+| `email.reachable: false` | the call failed | fix it, never report zero |
+| `whatsapp.blocked: true` | no store, local or pulled | fix ssh/policy, never report zero |
+
+On a client box (bridge on another host) the scan pulls the remote store itself over the
+policy `ssh` + `remote_store` entries, using `VACUUM INTO` for a consistent snapshot. It
+only reports `blocked` when that genuinely fails.
**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,
diff --git a/claude-ops/tests/test-ops-inbox-archive-set.sh b/claude-ops/tests/test-ops-inbox-archive-set.sh
index a9726177..d195563e 100755
--- a/claude-ops/tests/test-ops-inbox-archive-set.sh
+++ b/claude-ops/tests/test-ops-inbox-archive-set.sh
@@ -38,13 +38,88 @@ 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"
+grep -q 'WHERE {done_pred} OR last_message_time' "$CODE" \
+ || fail "whatsapp working set must be a done-flag predicate, not a recency slice"
+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" \
+ || fail "whatsapp must fall back to handled=0 when every chat is flagged archived"
+grep -q 'unread_count' "$CODE" \
+ && fail "whatsapp working set must never be driven by unread_count (a display state)"
# 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"
+# --------------------------------------------------------------------------
+# EMPTY IS NOT BROKEN (regression guard, 2026-09-06).
+# `gog whoami` prints name/email/photo on separate lines and the address is not
+# on the first one, so `head -1 | grep` threw the account away. Every gog call
+# then ran without --account, gog refused with "missing --account", and the scan
+# reported an unreachable mailbox that was perfectly reachable — a real inbox
+# read as inbox zero. Two invariants: resolve the account from ANY line, and
+# keep "empty result" distinguishable from "call failed".
+# --------------------------------------------------------------------------
+grep -q 'head -1 | grep' "$CODE" \
+ && fail "gmail account must not be parsed from only the first whoami line"
+grep -q 'OIS_GMAIL_OK' "$CODE" \
+ || fail "a successful-but-empty gmail search must be distinguishable from a failure"
+
+FAKEBIN="$TMP/fakebin"
+mkdir -p "$FAKEBIN"
+cat >"$FAKEBIN/gog" <<'SH'
+#!/usr/bin/env bash
+# whoami puts the address on line 2, exactly like the real CLI.
+if [ "$1" = "whoami" ]; then
+ printf 'name\tTest User\nemail\[email protected]\nphoto\thttps://example.com/a.png\n'
+ exit 0
+fi
+# refuse unless an account was passed, exactly like a multi-token box.
+case " $* " in
+ *" -a "*) echo '[]'; exit 0 ;;
+ *) echo 'missing --account' >&2; exit 2 ;;
+esac
+SH
+chmod +x "$FAKEBIN/gog"
+
+PATH="$FAKEBIN:$PATH" OIS_NO_REFRESH=1 "$SCAN" --email-only >"$TMP/empty.json" 2>/dev/null \
+ || fail "email-only scan must not fail on an empty inbox"
+"$PY" - "$TMP/empty.json" <<'PY' || exit 1
+import json, sys
+d = json.load(open(sys.argv[1]))
+e = d["email"]
+assert e["account"] == "[email protected]", \
+ "account must be read from the email line, got %r" % e["account"]
+assert e["reachable"] is True, "an empty inbox is reachable, not broken: %r" % e
+assert e.get("empty") is True, "an empty inbox must say so explicitly"
+print("empty-inbox vs unreachable: PASS")
+PY
+
+# --------------------------------------------------------------------------
+# A MISSING STORE IS A FAILED SCAN, NOT AN EMPTY INBOX (guard, 2026-09-06).
+# On a client box the bridge lives on another host and there is no local
+# messages.db. The scan used to answer with empty buckets plus a soft note, and
+# an agent reading only those buckets reported inbox zero over a full inbox.
+# --------------------------------------------------------------------------
+OIS_NO_REFRESH=1 OIS_SSH= OIS_SSH_FALLBACK= "$SCAN" --whatsapp-only \
+ --wa-store "$TMP/does-not-exist.db" --bridge-port 9 >"$TMP/nostore.json" 2>/dev/null \
+ || fail "missing-store scan must still emit valid JSON"
+"$PY" - "$TMP/nostore.json" <<'PY' || exit 1
+import json, sys
+d = json.load(open(sys.argv[1]))
+w = d["whatsapp"]
+assert w["reachable"] is False, "a missing store is not reachable"
+assert w.get("blocked") is True, "a missing store must be marked as a blocked scan"
+note = " ".join(d["notes"]).lower()
+assert "failed scan" in note, "the note must say the scan failed, not that it is empty"
+assert "do not report inbox zero" in note, "the note must forbid claiming inbox zero"
+print("missing-store is a blocker: PASS")
+PY
+
+# The remote pull must use a consistent sqlite snapshot, never a hot-file copy.
+grep -q 'VACUUM INTO' "$CODE" \
+ || fail "remote store pull must use VACUUM INTO, not a raw copy of a live db"
+
# --------------------------------------------------------------------------
# fixture
# --------------------------------------------------------------------------
@@ -148,8 +223,11 @@ grep -q "apply_result" "$TMP/out.json" \
# --------------------------------------------------------------------------
# --apply --dry-run walks the apply path without calling out.
+# The fixture carries no whatsapp_account, so a port must be supplied: without
+# one the tool correctly refuses to archive rather than aim at a guessed bridge.
# --------------------------------------------------------------------------
-run_json --apply --dry-run >"$TMP/dry.json" || fail "dry-run failed"
+run_json --apply --dry-run --default-bridge-port 8080 >"$TMP/dry.json" \
+ || fail "dry-run failed"
"$PY" - "$TMP/dry.json" <<'PY' || exit 1
import json, sys
d = json.load(open(sys.argv[1]))
@@ -162,6 +240,61 @@ assert r["email_ok"] == 0, "a default sweep must not touch FYI mail"
print("dry-run apply: PASS")
PY
+# --------------------------------------------------------------------------
+# MULTI-ACCOUNT ROUTING (regression guard, 2026-09-06).
+# Two defects shipped together and both were silent:
+# 1. a merged scan tagged each row with its account, but the split dropped
+# the tag and stamped every row "default";
+# 2. the archiver sent every row to ONE port, so a chat on number A was
+# archived against number B's bridge — the wrong-number class already
+# fixed once for sending.
+# A row that carries bridge_port must route to THAT port, and an untagged row
+# with no default must be refused rather than guessed.
+# --------------------------------------------------------------------------
+cat >"$TMP/multi.json" <<'JSON'
+{
+ "whatsapp": {
+ "needs_reply": [],
+ "waiting": [
+ {"who":"OnA","jid":"[email protected]","alt_jids":[],"account":"acct_a","bridge_port":8483},
+ {"who":"OnB","jid":"[email protected]","alt_jids":[],"account":"acct_b","bridge_port":8482},
+ {"who":"Untagged","jid":"[email protected]","alt_jids":[]}
+ ],
+ "fyi": [], "groups": []
+ },
+ "counts": {}, "notes": []
+}
+JSON
+"$PY" "$SPLIT" --scan "$TMP/multi.json" --json >"$TMP/multi-out.json" \
+ || fail "multi-account run failed"
+"$PY" - "$TMP/multi-out.json" <<'PY' || exit 1
+import json, sys
+d = json.load(open(sys.argv[1]))
+rows = {r["who"]: r for r in d["archive"]["whatsapp_default"]}
+assert rows["OnA"]["account"] == "acct_a", "account tag must survive the split"
+assert rows["OnB"]["account"] == "acct_b", "account tag must survive the split"
+assert rows["OnA"]["bridge_port"] == 8483, "each row must keep its own bridge port"
+assert rows["OnB"]["bridge_port"] == 8482, "each row must keep its own bridge port"
+assert rows["Untagged"]["account"] == "default", "an untagged row falls back to default"
+assert "bridge_port" not in rows["Untagged"], "an untagged row must not invent a port"
+print("multi-account tagging: PASS")
+PY
+
+# The untagged row has no port and no --default-bridge-port: it must be counted
+# as a failure and skipped, never sent to whichever bridge happens to answer.
+"$PY" "$SPLIT" --scan "$TMP/multi.json" --json --apply --dry-run \
+ >"$TMP/multi-dry.json" 2>"$TMP/multi-dry.err" || fail "multi dry-run failed"
+"$PY" - "$TMP/multi-dry.json" <<'PY' || exit 1
+import json, sys
+d = json.load(open(sys.argv[1]))
+r = d["apply_result"]
+assert r["whatsapp_ok"] == 2, "both tagged rows must route to their own bridge, got %s" % r
+assert r["whatsapp_failed"] == 1, "the untagged row must be refused, not guessed"
+print("per-row bridge routing: PASS")
+PY
+grep -q "no bridge port" "$TMP/multi-dry.err" \
+ || fail "a skipped untagged row must say why on stderr"
+
# --------------------------------------------------------------------------
# stale window is configurable and actually moves a thread across the line.
# --------------------------------------------------------------------------