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): count a reply sent from another account, and read the live bridge port (#929)

Aurora Capitalf22275f1fb49
diff --git a/claude-ops/bin/ops-inbox-archive-set b/claude-ops/bin/ops-inbox-archive-set
index 5f5a93cb..7034b0a5 100755
--- a/claude-ops/bin/ops-inbox-archive-set
+++ b/claude-ops/bin/ops-inbox-archive-set
@@ -454,18 +454,29 @@ def main():
# 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:
+ if not untagged:
+ port_source = "per-row account tag (merged multi-account scan)"
+ elif args.dry_run:
+ # A dry run contacts no bridge, so an unresolved port cannot send an
+ # archive to the wrong number. Blocking it there made the preview
+ # machine-dependent: on a box with two agent-enabled accounts the
+ # resolver refuses to pick one, and the dry run reported 0 planned
+ # archives -- a preview that silently disagreed with the real run.
+ errors.append(
+ "WhatsApp bridge port unresolved for %d chat(s): dry run counts "
+ "the planned archives, but a live --apply will refuse until you "
+ "pass --default-bridge-port." % len(untagged))
+ else:
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 and not any(r.get("bridge_port") for r in wa_archive):
+ if (main_port is None and not args.dry_run
+ 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 fb11f143..a0c3b1bf 100755
--- a/claude-ops/bin/ops-inbox-scan
+++ b/claude-ops/bin/ops-inbox-scan
@@ -39,6 +39,10 @@
# --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
+# --peer-store DB another account's store, read ONLY to see
+# whether a person was already answered there
+# (repeatable; auto-discovered by default)
+# --no-peer-stores disable that auto-discovery
# --pretty pretty-print JSON
#
# WHICH WHATSAPP ACCOUNT: more than one bridge can run here, one per number, and
@@ -59,6 +63,8 @@ EMAIL_MAX=400
WA_STORE_OVERRIDE=""
BRIDGE_PORT_OVERRIDE=""
ALL_ACCOUNTS=0
+PEER_STORES=""
+AUTO_PEERS=1
while [ $# -gt 0 ]; do
case "$1" in
@@ -71,6 +77,8 @@ while [ $# -gt 0 ]; do
--wa-store) WA_STORE_OVERRIDE="${2:-}"; shift ;;
--bridge-port) BRIDGE_PORT_OVERRIDE="${2:-}"; shift ;;
--all-accounts) ALL_ACCOUNTS=1 ;;
+ --peer-store) PEER_STORES="${PEER_STORES}${PEER_STORES:+:}${2:-}"; shift ;;
+ --no-peer-stores) AUTO_PEERS=0 ;;
--pretty) PRETTY=1 ;;
-h|--help)
grep '^#' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
@@ -279,6 +287,37 @@ export OIS_GMAIL_ACCOUNT="$GMAIL_ACCOUNT" OIS_PRETTY="$PRETTY"
export OIS_WA_PHONE="$WA_ACCOUNT_PHONE" OIS_WA_PORT="$BRIDGE_PORT"
export OIS_WA_ACCOUNT_SOURCE="$WA_ACCOUNT_SOURCE"
+# ---------------------------------------------------- peer account stores ----
+# One person, two numbers, two stores. A reply sent from account A lands ONLY in
+# A's messages.db, so B's copy of that same conversation still ends in an
+# inbound message and the scan calls it NEEDS_REPLY -- an already-answered
+# thread, offered up for a second, duplicate reply. (2026-09-06: a contact was
+# answered on the NL number two days earlier; the US store had no idea.)
+# Peer stores are read-only evidence of "already answered", never a scan target.
+if [ "$DO_WA" = 1 ] && [ "$AUTO_PEERS" = 1 ] && [ -z "$PEER_STORES" ]; then
+ _resolver="$(dirname "$0")/ops-wa-accounts"
+ if [ -x "$_resolver" ]; then
+ PEER_STORES="$("$_resolver" 2>/dev/null | python3 -c '
+import json, os, sys
+try:
+ data = json.load(sys.stdin)
+except Exception:
+ sys.exit(0)
+mine = os.path.realpath(os.environ.get("OIS_WA_MSGDB", ""))
+out = []
+for a in data.get("accounts", []):
+ st = a.get("store")
+ if not st:
+ continue
+ st = os.path.realpath(st)
+ if st != mine and os.path.exists(st):
+ out.append(st)
+print(":".join(out))
+' 2>/dev/null || true)"
+ fi
+fi
+export OIS_PEER_STORES="$PEER_STORES"
+
# The bridge dir that owns the store we are actually scanning — not a fixed
# path, or link_contacts.py would be run out of the wrong account's install.
BRIDGE_DIR="$(dirname "$WA_STORE")"
@@ -396,6 +435,7 @@ 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", "")
+PEER_STORES = [p for p in os.environ.get("OIS_PEER_STORES", "").split(":") if p]
now = datetime.now(timezone.utc)
notes = []
@@ -473,6 +513,56 @@ def ro(path):
# messages. mode=ro respects WAL + locking and never mutates.
return sqlite3.connect(f"file:{path}?mode=ro", uri=True)
+
+def load_peer_outbound():
+ """person-key -> newest epoch WE sent them from ANY other account.
+
+ Keys are both the raw jid and its bare local part (the digits before @), so
+ a peer's `12345@lid` matches this account's `[email protected]`: the
+ lid<->phone map is per-store, and the same person is routinely filed under a
+ different jid suffix on the other number. Matching on the digits is what
+ makes the cross-account check actually fire.
+ """
+ sent = {}
+ for path in PEER_STORES:
+ if not os.path.exists(path):
+ continue
+ try:
+ con = ro(path)
+ rows = con.execute(
+ "SELECT chat_jid, MAX(timestamp) FROM messages "
+ "WHERE is_from_me=1 GROUP BY chat_jid"
+ ).fetchall()
+ con.close()
+ except sqlite3.Error as exc: # noqa: BLE001 - note, never crash
+ notes.append(f"whatsapp: peer store unreadable ({path}): {exc}")
+ continue
+ for jid, ts in rows:
+ ep = ts_epoch(ts)
+ if ep is None or not jid:
+ continue
+ for key in (jid, re.sub(r"@.*$", "", jid)):
+ if key and (key not in sent or ep > sent[key]):
+ sent[key] = ep
+ return sent
+
+
+PEER_OUTBOUND = load_peer_outbound()
+
+
+def peer_answered_after(jids, inbound_ep):
+ """Newest cross-account send to any of these jids after inbound_ep."""
+ if inbound_ep is None or not PEER_OUTBOUND:
+ return None
+ best = None
+ for j in jids:
+ for key in (j, re.sub(r"@.*$", "", j)):
+ ep = PEER_OUTBOUND.get(key)
+ if ep is not None and ep > inbound_ep + 30 and (best is None or ep > best):
+ best = ep
+ return best
+
+
def scan_whatsapp():
out = {"needs_reply": [], "waiting": [], "groups": [], "fyi": []}
if not os.path.exists(MSGDB):
@@ -563,18 +653,43 @@ def scan_whatsapp():
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.
+ # "Every chat is archived" has two very different causes:
+ # * flag corruption — the store mass-set archived=1 while threads were
+ # still live and unanswered (observed 2026-06-09).
+ # * a completed inbox-zero run — every chat archived ON PURPOSE.
+ # The old code assumed the first and fell back to `handled=0`. That is
+ # only a working set if something actually WRITES `handled`. Nothing in
+ # this toolchain does, so on a genuinely-empty inbox the fallback
+ # reopened the entire history: 1803 of 1806 archived chats came back as
+ # unanswered asks, and inbox zero became unreachable by construction.
+ # A column nobody maintains cannot arbitrate anything, so use it only
+ # when it is demonstrably in use.
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"
- )
+ try:
+ n_handled = con.execute(
+ "SELECT count(*) FROM chats WHERE handled=1").fetchone()[0]
+ n_total = con.execute("SELECT count(*) FROM chats").fetchone()[0]
+ except sqlite3.Error:
+ n_handled, n_total = 0, 0
+ # In use = it tracks the archiving it is being asked to stand in for.
+ # A handful of rows out of thousands is a leftover, not a signal.
+ if n_total and n_handled * 2 >= n_total:
+ done_pred = "handled=0"
+ notes.append(
+ "whatsapp: every chat is flagged archived=1 (known corruption); "
+ "using handled=0 as the working set instead"
+ )
+ else:
+ notes.append(
+ "whatsapp: every chat is archived and `handled` is not "
+ "maintained (%d of %d rows), so the archive is taken at face "
+ "value: inbox zero, not flag corruption"
+ % (n_handled, n_total)
+ )
else:
done_pred = "archived=0"
chats = list(con.execute(
@@ -670,7 +785,16 @@ def scan_whatsapp():
item["reconciled"] = "answered via send-log (reply sent, not yet in store)"
out["waiting"].append(item)
else:
- out["needs_reply"].append(item)
+ # Cross-account: same person, other number, answer already sent
+ # there. Without this the second account re-offers a handled
+ # thread and a duplicate reply goes out.
+ peer_ep = peer_answered_after(members, inbound_ep)
+ if peer_ep is not None:
+ item["last_from_me"] = True
+ item["reconciled"] = "answered from another WhatsApp account"
+ out["waiting"].append(item)
+ else:
+ out["needs_reply"].append(item)
# Group chats — surface recent ones for the skill to scan for @mentions /
# direct questions. Provisional status from last-message direction only.
@@ -832,6 +956,7 @@ def scan_email():
result = {
"generated_at": now.isoformat(),
"window_days": DAYS,
+ "peer_stores_read": PEER_STORES,
"notes": notes,
}
if DO_WA:
diff --git a/claude-ops/bin/ops-wa-accounts b/claude-ops/bin/ops-wa-accounts
index f92ff8bd..97cc785e 100755
--- a/claude-ops/bin/ops-wa-accounts
+++ b/claude-ops/bin/ops-wa-accounts
@@ -106,6 +106,73 @@ def _sourced_env_files(text):
return out
+def _live_ports_by_dir():
+ """Map bridge directory -> port actually LISTENing, read from the OS.
+
+ A launcher script is not the only way a bridge starts. When a bridge is run
+ directly (systemd, a wrapper, a supervisor, by hand) there is no
+ run-bridge.sh to scan, and _scan() falls back to DEFAULT_BRIDGE_PORT. Every
+ account then reports the same port, so callers that trust it hit ONE bridge
+ for both numbers -- reading, archiving and replying on the wrong account.
+ That is the exact failure this whole file exists to prevent, so the port has
+ to come from the same place the phone does: live ground truth.
+
+ /proc/<pid>/cwd is the bridge's own working directory (whatsmeow stores
+ relative to it), which keys the mapping without guessing a binary name.
+ Linux-only by construction; on any other platform this returns {} and the
+ launcher/policy path stays authoritative.
+ """
+ out = {}
+ proc = "/proc"
+ if not os.path.isdir(proc):
+ return out
+ # inode -> port for every listening TCP socket (v4 + v6)
+ port_by_inode = {}
+ for tcp in ("net/tcp", "net/tcp6"):
+ try:
+ with open(os.path.join(proc, tcp)) as fh:
+ next(fh, None)
+ for line in fh:
+ f = line.split()
+ if len(f) < 10 or f[3] != "0A": # 0A = TCP_LISTEN
+ continue
+ try:
+ port_by_inode[f[9]] = int(f[1].rsplit(":", 1)[1], 16)
+ except (ValueError, IndexError):
+ continue
+ except OSError:
+ continue
+ if not port_by_inode:
+ return out
+ for pid in os.listdir(proc):
+ if not pid.isdigit():
+ continue
+ try:
+ cwd = os.path.realpath(os.path.join(proc, pid, "cwd"))
+ except OSError:
+ continue
+ fd_dir = os.path.join(proc, pid, "fd")
+ try:
+ fds = os.listdir(fd_dir)
+ except OSError:
+ continue
+ for fd in fds:
+ try:
+ target = os.readlink(os.path.join(fd_dir, fd))
+ except OSError:
+ continue
+ if not target.startswith("socket:["):
+ continue
+ inode = target[8:-1]
+ port = port_by_inode.get(inode)
+ if port is None:
+ continue
+ # lowest listening port wins, deterministic across restarts
+ if cwd not in out or port < out[cwd]:
+ out[cwd] = port
+ return out
+
+
def _paired_jid(store_dir):
"""The number actually paired in the store — ground truth, unlike config."""
db = os.path.join(store_dir, "whatsapp.db")
@@ -203,6 +270,7 @@ def discover():
notes.append(policy_note)
found = []
+ live_ports = _live_ports_by_dir()
for d in sorted(glob.glob(BRIDGE_GLOB)):
if not os.path.isdir(d):
continue
@@ -239,6 +307,16 @@ def discover():
except ValueError:
port = DEFAULT_BRIDGE_PORT
+ # A LISTENing socket beats a config guess. Without this every bridge
+ # started outside run-bridge.sh reports DEFAULT_BRIDGE_PORT, and two
+ # accounts collapse onto one port.
+ live_port = live_ports.get(os.path.realpath(d))
+ if live_port:
+ port = live_port
+ port_source = "live socket"
+ else:
+ port_source = "launcher/default"
+
phone_paired = _paired_jid(store)
phone = phone_paired or phone_cfg
@@ -257,6 +335,7 @@ def discover():
"dir": d,
"store": msgdb,
"port": port,
+ "port_source": port_source,
"api": "http://127.0.0.1:%d" % port,
"phone": phone,
"phone_configured": phone_cfg,
diff --git a/claude-ops/skills/ops-inbox/SKILL.md b/claude-ops/skills/ops-inbox/SKILL.md
index 47c98db0..94303d0b 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.
+**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
+unanswered. The scan therefore reads every OTHER account's store as read-only
+evidence and demotes such a thread to `waiting` with
+`reconciled: "answered from another WhatsApp account"`. That discovery is
+automatic; `--peer-store DB` names one explicitly and `--no-peer-stores` turns
+it off. Never draft a reply for a thread carrying a `reconciled` field.
+
**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:
diff --git a/claude-ops/tests/test-ops-inbox-cross-account.sh b/claude-ops/tests/test-ops-inbox-cross-account.sh
new file mode 100755
index 00000000..f127a78d
--- /dev/null
+++ b/claude-ops/tests/test-ops-inbox-cross-account.sh
@@ -0,0 +1,260 @@
+#!/usr/bin/env bash
+# test-ops-inbox-cross-account.sh — a thread answered on ANOTHER WhatsApp account
+# must never be offered up for a second reply, and a bridge's port must come
+# from the live socket rather than a launcher default.
+#
+# Both regressions are real:
+# 2026-09-06 — a contact was answered from the NL number two days earlier. The
+# US store's copy of that same conversation still ended on their inbound line,
+# so the scan called it NEEDS_REPLY and a duplicate reply was drafted.
+# Same run — ops-wa-accounts reported both bridges on 8080 (the whatsmeow
+# default) because neither was started by run-bridge.sh, while they actually
+# listened on 8082 and 8083. Anything trusting that port hits one account for
+# both numbers.
+#
+# Mutation-proof: revert either fix and this test goes red.
+set -uo pipefail
+
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$HERE/.." && pwd)"
+SCAN="$ROOT/bin/ops-inbox-scan"
+ACCOUNTS="$ROOT/bin/ops-wa-accounts"
+
+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-xacct.XXXXXX")"
+trap 'rm -rf "$TMP"' EXIT
+
+# --------------------------------------------------------------- fixtures ----
+# Two stores, one person. Their inbound sits in BOTH; our reply exists only in
+# the peer store, which is exactly the shape that produced the duplicate.
+mk_store() { # mk_store <dir>
+ local d="$1/store"
+ mkdir -p "$d"
+ python3 - "$d/messages.db" <<'PY'
+import sqlite3, sys
+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)")
+con.commit(); con.close()
+PY
+ printf '%s' "$d"
+}
+
+MAIN_DIR="$TMP/whatsapp-bridge"
+PEER_DIR="$TMP/whatsapp-bridge-us"
+MAIN_STORE="$(mk_store "$MAIN_DIR")"
+PEER_STORE="$(mk_store "$PEER_DIR")"
+
+# Scanned account: their question is the last line here.
+python3 - "$MAIN_STORE/messages.db" <<'PY'
+import sqlite3, sys
+con = sqlite3.connect(sys.argv[1])
+con.execute("INSERT INTO chats VALUES ('999111@lid','Casey','2026-09-01 11:00:00+00:00',0,0)")
+con.execute("INSERT INTO contacts VALUES ('999111@lid','Casey','999111','test',0)")
+con.execute("INSERT INTO messages VALUES ('m1','999111@lid','999111',"
+ "'How was the trip?','2026-09-01 11:00:00+00:00',0,'','')")
+# An unrelated contact nobody answered anywhere: the control.
+con.execute("INSERT INTO chats VALUES ('999222@lid','Robin','2026-09-01 12:00:00+00:00',0,0)")
+con.execute("INSERT INTO contacts VALUES ('999222@lid','Robin','999222','test',0)")
+con.execute("INSERT INTO messages VALUES ('m2','999222@lid','999222',"
+ "'Still on for Friday?','2026-09-01 12:00:00+00:00',0,'','')")
+con.commit(); con.close()
+PY
+
+# Peer account: the reply to Casey went out HERE, under a different jid suffix.
+python3 - "$PEER_STORE/messages.db" <<'PY'
+import sqlite3, sys
+con = sqlite3.connect(sys.argv[1])
+con.execute("INSERT INTO chats VALUES ('[email protected]','Casey',"
+ "'2026-09-02 09:00:00+00:00',1,0)")
+con.execute("INSERT INTO messages VALUES ('p1','[email protected]','me',"
+ "'Trip was great, thanks for asking!','2026-09-02 09:00:00+00:00',1,'','')")
+con.commit(); con.close()
+PY
+
+run_scan() { # run_scan [extra args...]
+ "$SCAN" --whatsapp-only --pretty \
+ --wa-store "$MAIN_STORE/messages.db" --bridge-port 8099 "$@" 2>/dev/null
+}
+
+bucket_of() { # bucket_of <json> <name>
+ 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 "cross-account reconciliation"
+OUT="$(run_scan --peer-store "$PEER_STORE/messages.db")"
+
+if [ -z "$OUT" ]; then
+ bad "scan produced no output"
+else
+ b="$(bucket_of "$OUT" Casey)"
+ [ "$b" = "waiting" ] && ok "answered-elsewhere thread demoted out of needs_reply" \
+ || bad "Casey landed in '$b', expected waiting (duplicate-reply bug)"
+
+ b="$(bucket_of "$OUT" Robin)"
+ [ "$b" = "needs_reply" ] && ok "genuinely unanswered thread still needs_reply" \
+ || bad "Robin landed in '$b', expected needs_reply (gate too wide)"
+
+ # The reason must be visible, or a human cannot tell why it was skipped.
+ if grep -q "answered from another WhatsApp account" <<<"$OUT"; then
+ ok "demotion carries a stated reason"
+ else
+ bad "no 'reconciled' reason on the demoted thread"
+ fi
+
+ # The peer store must be reported, so a run can prove what it read.
+ if python3 -c '
+import json,sys
+d=json.loads(sys.stdin.read() or "{}")
+sys.exit(0 if d.get("peer_stores_read") else 1)' <<<"$OUT"; then
+ ok "scan reports which peer stores it read"
+ else
+ bad "peer_stores_read missing from scan output"
+ fi
+fi
+
+# Without the peer store the same thread MUST look unanswered: proves the demotion
+# comes from peer evidence and not from some unrelated blanket rule.
+OUT_NOPEER="$(run_scan --no-peer-stores)"
+b="$(bucket_of "$OUT_NOPEER" Casey)"
+[ "$b" = "needs_reply" ] && ok "no peer evidence => thread stays actionable" \
+ || bad "Casey was '$b' with no peer store; demotion is not evidence-driven"
+
+echo "live port resolution"
+# A bridge with no launcher script, listening on a non-default port.
+PORT_OUT="$(WHATSAPP_BRIDGE_GLOB="$TMP/whatsapp-bridge*" \
+ WHATSAPP_AGENT_POLICY="$TMP/nonexistent-policy.json" \
+ "$ACCOUNTS" 2>/dev/null)"
+if python3 -c '
+import json,sys
+d=json.loads(sys.stdin.read() or "{}")
+accts=d.get("accounts",[])
+sys.exit(0 if accts and all("port_source" in a for a in accts) else 1)' <<<"$PORT_OUT"; then
+ ok "every account states where its port came from"
+else
+ bad "port_source missing: a caller cannot tell a live port from a guess"
+fi
+
+# Real listener on a real port, in a directory shaped like a bridge.
+LIVE_DIR="$TMP/whatsapp-bridge-live"
+mk_store "$LIVE_DIR" >/dev/null
+python3 - "$LIVE_DIR" <<'PY' &
+import os, socket, sys, time
+os.chdir(sys.argv[1])
+s = socket.socket()
+s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+s.bind(("127.0.0.1", 0))
+s.listen(1)
+with open("port.txt", "w") as fh:
+ fh.write(str(s.getsockname()[1]))
+time.sleep(20)
+PY
+LISTENER=$!
+for _ in $(seq 1 40); do [ -s "$LIVE_DIR/port.txt" ] && break; sleep 0.1; done
+LIVE_PORT="$(cat "$LIVE_DIR/port.txt" 2>/dev/null || echo)"
+
+if [ -z "$LIVE_PORT" ] || [ ! -d /proc ]; then
+ echo " skip live-socket check (no /proc or listener failed to start)"
+else
+ LIVE_OUT="$(WHATSAPP_BRIDGE_GLOB="$LIVE_DIR" \
+ WHATSAPP_AGENT_POLICY="$TMP/nonexistent-policy.json" \
+ "$ACCOUNTS" 2>/dev/null)"
+ got="$(python3 -c '
+import json,sys
+d=json.loads(sys.stdin.read() or "{}")
+a=d.get("accounts") or [{}]
+print(a[0].get("port",""))' <<<"$LIVE_OUT")"
+ if [ "$got" = "$LIVE_PORT" ]; then
+ ok "port read from the live socket ($got), not the 8080 default"
+ else
+ bad "reported port $got, listener is on $LIVE_PORT (stale launcher default)"
+ fi
+fi
+kill "$LISTENER" 2>/dev/null || true
+wait "$LISTENER" 2>/dev/null || true
+
+echo "fully-archived store is inbox zero, not corruption"
+# A store where every chat is archived on purpose, with a `handled` column that
+# nothing maintains. The old fallback treated this as flag corruption and
+# switched the working set to handled=0, which reopened the entire history --
+# 1803 of 1806 archived chats came back as unanswered asks, so a box that had
+# just reached inbox zero could never stay there.
+ZERO_DIR="$TMP/whatsapp-bridge-zero"
+ZERO_STORE="$(mk_store "$ZERO_DIR")"
+python3 - "$ZERO_STORE/messages.db" <<'PY'
+import sqlite3, sys
+con = sqlite3.connect(sys.argv[1])
+con.execute("ALTER TABLE chats ADD COLUMN handled INTEGER NOT NULL DEFAULT 0")
+# Old, deliberately archived, and last word was theirs: the shape the fallback
+# used to resurrect. Well outside the recency floor.
+for i in range(6):
+ jid = "8000%02d@lid" % i
+ con.execute("INSERT INTO chats VALUES (?,?, '2025-01-05 10:00:00+00:00', 1, 0, 0)",
+ (jid, "Old%d" % i))
+ con.execute("INSERT INTO messages VALUES (?,?,?,'an old question',"
+ "'2025-01-05 10:00:00+00:00',0,'','')", ("mm%d" % i, jid, jid))
+con.commit(); con.close()
+PY
+
+ZOUT="$("$SCAN" --whatsapp-only --pretty --no-peer-stores \
+ --wa-store "$ZERO_STORE/messages.db" --bridge-port 8098 2>/dev/null)"
+n_needs="$(python3 -c '
+import json,sys
+d=json.loads(sys.stdin.read() or "{}")
+print(len(d.get("whatsapp",{}).get("needs_reply",[])))' <<<"$ZOUT")"
+[ "$n_needs" = "0" ] && ok "archived history stays archived (needs_reply=0)" \
+ || bad "$n_needs archived chats resurrected; inbox zero unreachable"
+
+if grep -q "not flag corruption" <<<"$ZOUT"; then
+ ok "scan states why it trusted the archive flag"
+else
+ bad "no note explaining the archived-store verdict"
+fi
+
+# The genuine corruption case must STILL be caught: archived=1 everywhere while
+# `handled` is actively maintained means the flag, not the inbox, is wrong.
+CORRUPT_DIR="$TMP/whatsapp-bridge-corrupt"
+CORRUPT_STORE="$(mk_store "$CORRUPT_DIR")"
+python3 - "$CORRUPT_STORE/messages.db" <<'PY'
+import sqlite3, sys
+con = sqlite3.connect(sys.argv[1])
+con.execute("ALTER TABLE chats ADD COLUMN handled INTEGER NOT NULL DEFAULT 0")
+# handled is maintained here: most rows carry it, one live thread does not.
+for i in range(5):
+ jid = "9000%02d@lid" % i
+ con.execute("INSERT INTO chats VALUES (?,?, '2025-01-05 10:00:00+00:00', 1, 0, 1)",
+ (jid, "Done%d" % i))
+ con.execute("INSERT INTO messages VALUES (?,?,?,'settled',"
+ "'2025-01-05 10:00:00+00:00',1,'','')", ("cm%d" % i, jid, jid))
+con.execute("INSERT INTO chats VALUES ('900099@lid','Victim',"
+ "'2025-01-06 10:00:00+00:00', 1, 0, 0)")
+con.execute("INSERT INTO messages VALUES ('cv','900099@lid','900099',"
+ "'you never answered me','2025-01-06 10:00:00+00:00',0,'','')")
+con.commit(); con.close()
+PY
+
+COUT="$("$SCAN" --whatsapp-only --pretty --no-peer-stores \
+ --wa-store "$CORRUPT_STORE/messages.db" --bridge-port 8097 2>/dev/null)"
+b="$(bucket_of "$COUT" Victim)"
+[ "$b" = "needs_reply" ] && ok "real flag corruption still recovers the live thread" \
+ || bad "Victim was '$b'; corruption fallback no longer fires"
+
+printf '\n%d passed, %d failed\n' "$pass" "$fail"
+[ "$fail" -eq 0 ]
\ No newline at end of file