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.

Resolve which WhatsApp account ops-inbox reads and sends from (#815)

Aurora Capital97b49b65be24
diff --git a/claude-ops/bin/ops-inbox-archive-set b/claude-ops/bin/ops-inbox-archive-set
index 5ec7254f..a48e7201 100755
--- a/claude-ops/bin/ops-inbox-archive-set
+++ b/claude-ops/bin/ops-inbox-archive-set
@@ -330,7 +330,12 @@ def main():
help="extra WhatsApp account store (repeatable)")
ap.add_argument("--bridge-port", action="append", default=[], type=int,
help="bridge port for the matching --wa-store (repeatable)")
- ap.add_argument("--default-bridge-port", type=int, default=8080)
+ # No baked-in port. 8080 used to be the default, which meant that on a box
+ # running one bridge per phone number this tool archived whichever account
+ # happened to sit on the low port. It is resolved from the scan instead —
+ # the scan records the account it read — and archiving is skipped outright
+ # when that cannot be established.
+ ap.add_argument("--default-bridge-port", type=int, default=None)
ap.add_argument("--stale-days", type=int, default=7)
ap.add_argument("--dead-group-days", type=int, default=30)
ap.add_argument("--gmail-account", default=os.environ.get("GMAIL_ACCOUNT"))
@@ -397,8 +402,41 @@ def main():
"applied": False,
}
+ # Which bridge the main WhatsApp set belongs to: the flag wins, else the
+ # account the scan actually read, else the one account policy allows. If
+ # none of those answer, the WhatsApp sweep is skipped rather than aimed at
+ # a guess — archiving the wrong number's inbox is not a recoverable mistake.
+ main_port = args.default_bridge_port
+ port_source = "--default-bridge-port" if main_port else None
+ if main_port is None:
+ acct = (scan or {}).get("whatsapp_account") or {}
+ if acct.get("bridge_port"):
+ main_port = int(acct["bridge_port"])
+ port_source = "scan (%s)" % (acct.get("phone") or acct.get("store") or "account")
+ if main_port is None:
+ resolver = os.path.join(plugin_root, "bin", "ops-wa-accounts")
+ if os.path.exists(resolver):
+ try:
+ out = subprocess.run([resolver, "--port"], capture_output=True,
+ text=True, timeout=15)
+ if out.returncode == 0 and out.stdout.strip().isdigit():
+ main_port = int(out.stdout.strip())
+ port_source = "ops-wa-accounts policy"
+ 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.")
+ result["whatsapp_bridge_port"] = main_port
+ result["whatsapp_bridge_port_source"] = port_source
+
if args.apply:
- ok, fail = archive_whatsapp(wa_archive, args.default_bridge_port, args.dry_run)
+ if main_port is None:
+ ok, fail = 0, 0
+ else:
+ ok, fail = archive_whatsapp(wa_archive, main_port, args.dry_run)
for e in extra:
if e["port"] is None:
errors.append("%s: no --bridge-port given, chats left alone" % e["label"])
diff --git a/claude-ops/bin/ops-inbox-scan b/claude-ops/bin/ops-inbox-scan
index b93e7909..de02a7de 100755
--- a/claude-ops/bin/ops-inbox-scan
+++ b/claude-ops/bin/ops-inbox-scan
@@ -36,7 +36,16 @@
# --email-query Q Gmail working set (default "in:inbox")
# --email-max N max Gmail results (default 400)
# --gmail-account ADDR override Gmail account (default: gog default)
+# --wa-store DB WhatsApp messages.db to scan
+# --bridge-port N bridge REST port for that store
# --pretty pretty-print JSON
+#
+# WHICH WHATSAPP ACCOUNT: more than one bridge can run here, one per number, and
+# they differ only by port and store. This script never assumes a port. It asks
+# `ops-wa-accounts` for the single account policy marks as agent-enabled, and
+# refuses to scan at all when that is ambiguous — a wrong guess means reading,
+# and later replying from, a number that was meant to be left alone. Override
+# both --wa-store and --bridge-port together to target a specific account.
set -euo pipefail
DAYS=7
@@ -46,6 +55,8 @@ GMAIL_ACCOUNT="${GMAIL_ACCOUNT:-}"
PRETTY=0
EMAIL_QUERY="in:inbox"
EMAIL_MAX=400
+WA_STORE_OVERRIDE=""
+BRIDGE_PORT_OVERRIDE=""
while [ $# -gt 0 ]; do
case "$1" in
@@ -55,6 +66,8 @@ while [ $# -gt 0 ]; do
--email-query) EMAIL_QUERY="${2:-in:inbox}"; shift ;;
--email-max) EMAIL_MAX="${2:-400}"; shift ;;
--gmail-account) GMAIL_ACCOUNT="${2:-}"; shift ;;
+ --wa-store) WA_STORE_OVERRIDE="${2:-}"; shift ;;
+ --bridge-port) BRIDGE_PORT_OVERRIDE="${2:-}"; shift ;;
--pretty) PRETTY=1 ;;
-h|--help)
grep '^#' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
@@ -63,9 +76,55 @@ while [ $# -gt 0 ]; do
shift
done
-WA_STORE="${WHATSAPP_BRIDGE_DIR:-$HOME/.local/share/whatsapp-mcp/whatsapp-bridge}/store"
-WA_MSGDB="${WHATSAPP_BRIDGE_DB:-$WA_STORE/messages.db}"
+# --------------------------------------------------------- which account ----
+# Resolution order: explicit flags, then the long-standing WHATSAPP_BRIDGE_*
+# env vars, then whichever single account policy marks agent-enabled. The last
+# step is the only one that can be ambiguous, and when it is we stop rather
+# than fall back to a port — the whole point is to never pick a number by luck.
+WA_ACCOUNT_PHONE=""
+WA_ACCOUNT_SOURCE=""
+BRIDGE_PORT=""
+
+if [ -n "$WA_STORE_OVERRIDE" ] || [ -n "$BRIDGE_PORT_OVERRIDE" ]; then
+ if [ -z "$WA_STORE_OVERRIDE" ] || [ -z "$BRIDGE_PORT_OVERRIDE" ]; then
+ echo "ops-inbox-scan: --wa-store and --bridge-port must be given together" >&2
+ exit 2
+ fi
+ WA_MSGDB="$WA_STORE_OVERRIDE"
+ BRIDGE_PORT="$BRIDGE_PORT_OVERRIDE"
+ WA_ACCOUNT_SOURCE="flags"
+elif [ -n "${WHATSAPP_BRIDGE_DIR:-}" ] || [ -n "${WHATSAPP_BRIDGE_DB:-}" ]; then
+ _envstore="${WHATSAPP_BRIDGE_DIR:-$HOME/.local/share/whatsapp-mcp/whatsapp-bridge}/store"
+ WA_MSGDB="${WHATSAPP_BRIDGE_DB:-$_envstore/messages.db}"
+ BRIDGE_PORT="${WHATSAPP_BRIDGE_PORT:-8080}"
+ WA_ACCOUNT_SOURCE="env"
+elif [ "$DO_WA" = 1 ]; then
+ _resolver="$(dirname "$0")/ops-wa-accounts"
+ if [ -x "$_resolver" ]; then
+ if _acct="$("$_resolver" --default 2>/dev/null)"; then
+ BRIDGE_PORT="$(printf '%s' "$_acct" | cut -f1)"
+ WA_MSGDB="$(printf '%s' "$_acct" | cut -f2)"
+ WA_ACCOUNT_PHONE="$(printf '%s' "$_acct" | cut -f3)"
+ WA_ACCOUNT_SOURCE="policy"
+ else
+ echo "ops-inbox-scan: cannot resolve a WhatsApp account to scan." >&2
+ "$_resolver" --list >&2 2>/dev/null || true
+ echo "ops-inbox-scan: pass --wa-store DB --bridge-port N, or set agent_enabled in the policy file." >&2
+ exit 3
+ fi
+ else
+ # No resolver on this install: fall back to the historical single-account
+ # layout, which is correct precisely when there is only one bridge.
+ WA_MSGDB="$HOME/.local/share/whatsapp-mcp/whatsapp-bridge/store/messages.db"
+ BRIDGE_PORT=8080
+ WA_ACCOUNT_SOURCE="legacy-default"
+ fi
+fi
+
+WA_STORE="$(dirname "${WA_MSGDB:-$HOME/.local/share/whatsapp-mcp/whatsapp-bridge/store/messages.db}")"
WA_WADB="$WA_STORE/whatsapp.db"
+BRIDGE_PORT="${BRIDGE_PORT:-8080}"
+BRIDGE_API="http://127.0.0.1:${BRIDGE_PORT}"
# Resolve a default Gmail account from gog if not supplied (best-effort).
if [ "$DO_EMAIL" = 1 ] && [ -z "$GMAIL_ACCOUNT" ]; then
@@ -75,19 +134,23 @@ fi
export OIS_DAYS="$DAYS" OIS_DO_WA="$DO_WA" OIS_DO_EMAIL="$DO_EMAIL"
export OIS_WA_MSGDB="$WA_MSGDB" OIS_WA_WADB="$WA_WADB"
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"
-BRIDGE_DIR="${WHATSAPP_BRIDGE_DIR:-$HOME/.local/share/whatsapp-mcp/whatsapp-bridge}"
+# 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")"
# --------------------------------------------------------- refresh on load ----
# Autonomous "always pull latest before classifying" pass (owner directive
# 2026-06-05: "ensure backfill and frontfill is fully done automatically when I
# run /ops-inbox"). Best-effort + bounded — NEVER blocks the scan for long and
-# NEVER fails it. Only runs when the bridge is actually reachable on :8080.
+# NEVER fails it. Only runs when this account's own bridge is reachable.
# Skip with OIS_NO_REFRESH=1 (e.g. CI / repeated calls in one session).
if [ "$DO_WA" = 1 ] && [ "${OIS_NO_REFRESH:-0}" != 1 ]; then
- if curl -s -o /dev/null -m 4 http://127.0.0.1:8080/ 2>/dev/null; then
+ if curl -s -o /dev/null -m 4 "$BRIDGE_API/" 2>/dev/null; then
# frontfill: recent-conversation history backfill (idempotent)
- curl -fsS -m 10 -X POST http://127.0.0.1:8080/api/backfill >/dev/null 2>&1 || true
+ curl -fsS -m 10 -X POST "$BRIDGE_API/api/backfill" >/dev/null 2>&1 || true
# contacts link: phone + LID aliases -> names (idempotent)
[ -f "$BRIDGE_DIR/link_contacts.py" ] && \
python3 "$BRIDGE_DIR/link_contacts.py" >/dev/null 2>&1 || true
@@ -570,6 +633,16 @@ result = {
"notes": notes,
}
if DO_WA:
+ # Which number these rows belong to. Carried through so a reply is composed
+ # against the account the thread actually lives on, and so a scan pasted
+ # into a later session still says which inbox it came from.
+ result["whatsapp_account"] = {
+ "phone": os.environ.get("OIS_WA_PHONE") or None,
+ "bridge_port": int(os.environ.get("OIS_WA_PORT") or 0) or None,
+ "bridge_api": "http://127.0.0.1:%s" % os.environ.get("OIS_WA_PORT", ""),
+ "store": MSGDB,
+ "resolved_by": os.environ.get("OIS_WA_ACCOUNT_SOURCE") or None,
+ }
result["whatsapp"] = scan_whatsapp()
if DO_EMAIL:
result["email"] = scan_email()
diff --git a/claude-ops/bin/ops-wa-accounts b/claude-ops/bin/ops-wa-accounts
new file mode 100755
index 00000000..62e83431
--- /dev/null
+++ b/claude-ops/bin/ops-wa-accounts
@@ -0,0 +1,253 @@
+#!/usr/bin/env python3
+# ops-wa-accounts — resolve every whatsmeow bridge on this box to an account.
+#
+# Why this exists: more than one bridge can run at once, one per phone number.
+# They differ only by port and store directory, and the lowest port answers
+# first. Code that hardcodes 127.0.0.1:8080 therefore reads, archives and sends
+# on whichever account happens to sit on the low port — which is how a full
+# inbox run once replied to everyone from the wrong number.
+#
+# Nothing here guesses. An account is usable by an agent only when policy says
+# so, and when exactly one such account exists. Two candidates with no policy is
+# an error, not a coin flip.
+#
+# Usage:
+# ops-wa-accounts # JSON: every discovered account
+# ops-wa-accounts --list # human-readable table
+# ops-wa-accounts --default # "<port>\t<store>\t<phone>" for the one
+# # agent-enabled account; exit 3 if unclear
+# ops-wa-accounts --port # just the port of that account
+# ops-wa-accounts --store # just the messages.db of that account
+#
+# Policy file (never committed — it holds real numbers):
+# ~/.config/whatsapp/agent-policy.json
+# {
+# "accounts": {
+# "<e164>": { "agent_enabled": false, "note": "managed by someone else" }
+# },
+# "default_agent_enabled": true
+# }
+#
+# Exit codes: 0 ok · 3 no single agent-enabled account · 4 nothing discovered.
+
+import argparse
+import glob
+import json
+import os
+import re
+import sqlite3
+import sys
+
+HOME = os.path.expanduser("~")
+BRIDGE_GLOB = os.environ.get(
+ "WHATSAPP_BRIDGE_GLOB", os.path.join(HOME, ".local/share/whatsapp-mcp/whatsapp-bridge*")
+)
+POLICY_PATH = os.environ.get(
+ "WHATSAPP_AGENT_POLICY", os.path.join(HOME, ".config/whatsapp/agent-policy.json")
+)
+DEFAULT_BRIDGE_PORT = 8080 # whatsmeow's own default when WA_PORT is unset
+
+# `export WA_PHONE="${WA_PHONE:-31612345678}"` and friends.
+_DEFAULT_RE = r'{0}=(?:"|\')?\$\{{{0}:-([^}}]*)\}}'
+# A plain `WA_PORT=8082` line in an env file.
+_PLAIN_RE = r'^\s*(?:export\s+)?{0}=(?:"|\')?([^"\'\s#]+)'
+
+
+def _scan(text, var):
+ """Value of var from a shell snippet: ${VAR:-default} first, then VAR=x."""
+ m = re.search(_DEFAULT_RE.format(var), text)
+ if m and m.group(1).strip():
+ return m.group(1).strip()
+ m = re.search(_PLAIN_RE.format(var), text, re.M)
+ if m and m.group(1).strip():
+ return m.group(1).strip()
+ return None
+
+
+def _sourced_env_files(text):
+ """Env files the launcher sources, so their values can override defaults."""
+ out = []
+ for m in re.finditer(r'^\s*(?:\.|source)\s+"?([^"\s]+)"?', text, re.M):
+ p = m.group(1).replace("$HOME", HOME).replace("${HOME}", HOME)
+ out.append(os.path.expanduser(p))
+ 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")
+ if not os.path.exists(db):
+ return None
+ try:
+ con = sqlite3.connect("file:%s?mode=ro" % db, uri=True, timeout=2.0)
+ try:
+ row = con.execute("SELECT jid FROM whatsmeow_device LIMIT 1").fetchone()
+ finally:
+ con.close()
+ except sqlite3.Error:
+ return None
+ if not row or not row[0]:
+ return None
+ return str(row[0]).split(":", 1)[0].split("@", 1)[0] or None
+
+
+def _load_policy():
+ try:
+ with open(POLICY_PATH) as fh:
+ pol = json.load(fh)
+ except (OSError, ValueError):
+ return {}, None, "no policy file at %s" % POLICY_PATH
+ accounts = pol.get("accounts") or {}
+ return accounts, pol.get("default_agent_enabled"), None
+
+
+def discover():
+ accounts, policy_default, policy_note = _load_policy()
+ notes = []
+ if policy_note:
+ notes.append(policy_note)
+
+ found = []
+ for d in sorted(glob.glob(BRIDGE_GLOB)):
+ if not os.path.isdir(d):
+ continue
+ store = os.path.join(d, "store")
+ msgdb = os.path.join(store, "messages.db")
+ if not os.path.exists(msgdb):
+ continue # a bridge dir without a store is not a usable account
+
+ launcher = os.path.join(d, "run-bridge.sh")
+ text = ""
+ if os.path.exists(launcher):
+ try:
+ with open(launcher) as fh:
+ text = fh.read()
+ except OSError:
+ text = ""
+
+ phone_cfg = _scan(text, "WA_PHONE")
+ port = _scan(text, "WA_PORT")
+ # An env file sourced with `set -a` overrides the launcher defaults.
+ for env_path in _sourced_env_files(text):
+ if not os.path.exists(env_path):
+ continue
+ try:
+ with open(env_path) as fh:
+ env_text = fh.read()
+ except OSError:
+ continue
+ phone_cfg = _scan(env_text, "WA_PHONE") or phone_cfg
+ port = _scan(env_text, "WA_PORT") or port
+
+ try:
+ port = int(port) if port else DEFAULT_BRIDGE_PORT
+ except ValueError:
+ port = DEFAULT_BRIDGE_PORT
+
+ phone_paired = _paired_jid(store)
+ phone = phone_paired or phone_cfg
+
+ rule = accounts.get(phone) if phone else None
+ if rule is None and phone_cfg and phone_cfg != phone:
+ rule = accounts.get(phone_cfg)
+ if rule is None:
+ enabled = policy_default
+ reason = "policy default" if enabled is not None else "no policy entry"
+ else:
+ enabled = rule.get("agent_enabled", True)
+ reason = rule.get("note") or "policy entry"
+
+ acct = {
+ "label": os.path.basename(d),
+ "dir": d,
+ "store": msgdb,
+ "port": port,
+ "api": "http://127.0.0.1:%d" % port,
+ "phone": phone,
+ "phone_configured": phone_cfg,
+ "phone_paired": phone_paired,
+ "agent_enabled": bool(enabled) if enabled is not None else None,
+ "policy_reason": reason,
+ }
+ # The launcher claiming one number while the store is paired to another
+ # is exactly the trap this tool exists to catch.
+ if phone_cfg and phone_paired and phone_cfg != phone_paired:
+ acct["mismatch"] = (
+ "run-bridge.sh says %s but the store is paired to %s — trust the store"
+ % (phone_cfg, phone_paired)
+ )
+ notes.append("%s: %s" % (acct["label"], acct["mismatch"]))
+ found.append(acct)
+
+ enabled = [a for a in found if a["agent_enabled"] is True]
+ unknown = [a for a in found if a["agent_enabled"] is None]
+
+ default = None
+ if len(enabled) == 1:
+ default = enabled[0]
+ elif len(enabled) > 1:
+ notes.append(
+ "%d accounts are agent-enabled (%s) — pass --wa-store/--bridge-port explicitly"
+ % (len(enabled), ", ".join(a["phone"] or a["label"] for a in enabled))
+ )
+ elif len(found) == 1 and unknown:
+ # One bridge and no policy: unambiguous, so using it is not a guess.
+ default = found[0]
+ notes.append("single bridge and no policy — using %s" % found[0]["label"])
+ elif unknown:
+ notes.append(
+ "%d accounts have no policy entry — write %s before agents touch them"
+ % (len(unknown), POLICY_PATH)
+ )
+
+ return {"accounts": found, "default": default, "notes": notes, "policy": POLICY_PATH}
+
+
+def main():
+ ap = argparse.ArgumentParser(add_help=True, description=__doc__)
+ g = ap.add_mutually_exclusive_group()
+ g.add_argument("--list", action="store_true", help="human-readable table")
+ g.add_argument("--default", action="store_true", help="port, store and phone of the agent account")
+ g.add_argument("--port", action="store_true", help="port of the agent account")
+ g.add_argument("--store", action="store_true", help="messages.db of the agent account")
+ args = ap.parse_args()
+
+ res = discover()
+
+ if args.list:
+ if not res["accounts"]:
+ print("no whatsmeow bridge found under %s" % BRIDGE_GLOB, file=sys.stderr)
+ return 4
+ print("%-24s %-6s %-16s %-8s %s" % ("BRIDGE", "PORT", "PHONE", "AGENT", "STORE"))
+ for a in res["accounts"]:
+ state = {True: "yes", False: "NO", None: "unset"}[a["agent_enabled"]]
+ print("%-24s %-6d %-16s %-8s %s" % (a["label"], a["port"], a["phone"] or "?", state, a["store"]))
+ for n in res["notes"]:
+ print("note: %s" % n, file=sys.stderr)
+ return 0
+
+ if args.default or args.port or args.store:
+ d = res["default"]
+ if not d:
+ for n in res["notes"]:
+ print("ops-wa-accounts: %s" % n, file=sys.stderr)
+ print(
+ "ops-wa-accounts: no single agent-enabled account — refusing to guess",
+ file=sys.stderr,
+ )
+ return 3 if res["accounts"] else 4
+ if args.port:
+ print(d["port"])
+ elif args.store:
+ print(d["store"])
+ else:
+ print("%d\t%s\t%s" % (d["port"], d["store"], d["phone"] or ""))
+ return 0
+
+ json.dump(res, sys.stdout, indent=2)
+ sys.stdout.write("\n")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/claude-ops/skills/ops-inbox/SKILL.md b/claude-ops/skills/ops-inbox/SKILL.md
index 43df4f8d..44ac27d0 100644
--- a/claude-ops/skills/ops-inbox/SKILL.md
+++ b/claude-ops/skills/ops-inbox/SKILL.md
@@ -81,12 +81,51 @@ If you find yourself reaching for any `wacli ...` shell command, stop and use th
| Resolve a contact | `mcp__whatsapp__search_contacts {query: "<name>"}` | `wacli contacts` |
| Send a reply (after approval) | `mcp__whatsapp__send_message {recipient: "<JID>", message: "<text>"}` | `wacli send` |
| Health check | `lsof -i :8080 \| grep LISTEN` + (macOS) `launchctl print "gui/$(id -u)/com.${USER}.whatsapp-bridge"` / (Linux) `systemctl --user is-active whatsapp-bridge.service` | `wacli doctor` / `~/.wacli/.health` |
-| Trigger history backfill | `curl -fsS -X POST http://127.0.0.1:8080/api/backfill` (claude-ops patch — runs per-chat against the 50 most-recent chats; bridge also auto-backfills 5s after every Connected event) | — |
+| Trigger history backfill | `curl -fsS -X POST "$WA_API/api/backfill"` (resolve `$WA_API` first — see "WHICH NUMBER" below; claude-ops patch — runs per-chat against the 50 most-recent chats; bridge also auto-backfills 5s after every Connected event) | — |
**Rationale:** the bridge exposes a typed MCP surface, returns consistent JSON shapes (`is_from_me`, `content`, `timestamp`, `sender`), supports FTS5 search natively, and avoids store-lock contention with the wacli keepalive daemon. Mixing the two surfaces caused inconsistent state in past sessions.
**Sole exception:** the `~/.wacli/.health` file is still readable for legacy daemon-health surfacing in other skills, but no `wacli` command should be invoked from this skill.
+## ⚠️ WHICH NUMBER — resolve the account before the first read or send
+
+**This box may run more than one WhatsApp bridge, one per phone number.** They are identical
+processes that differ only by port and store directory. The lowest port answers first, so
+`127.0.0.1:8080` looks authoritative whether or not it is the account you want. Every literal
+`:8080` below is legacy shorthand for "this account's bridge", never an instruction to use 8080.
+
+**Resolve first, every run, before any read, archive, or send:**
+
+```bash
+"$CLAUDE_PLUGIN_ROOT/bin/ops-wa-accounts" --list # every bridge: port, number, agent yes/no
+WA_PORT=$("$CLAUDE_PLUGIN_ROOT/bin/ops-wa-accounts" --port) # the one agent-enabled account
+WA_API="http://127.0.0.1:${WA_PORT}"
+```
+
+`ops-wa-accounts` reads each bridge's `run-bridge.sh` and — authoritatively — the number actually
+paired in its store, then applies `~/.config/whatsapp/agent-policy.json` (never committed; it holds
+real numbers). It exits non-zero rather than pick one when the answer is ambiguous.
+
+**The rules:**
+
+1. **Never hardcode a port, and never use whichever port answers.** Use `$WA_API` from the resolver,
+ or the `whatsapp_account.bridge_port` that `ops-inbox-scan` records in its JSON.
+2. **A number can be agent-disabled.** An account with `agent_enabled: false` is off-limits: do not
+ scan it, do not archive it, do not send from it, do not pair or re-pair it. Someone else may be
+ managing that inbox, and traffic from an agent on it is a real-world problem.
+3. **If resolution is ambiguous, stop and ask.** Two enabled accounts, or none, is a question for the
+ user — `AskUserQuestion` with the candidate numbers. It is never a coin flip.
+4. **Reply on the number the thread lives on.** A reply from the wrong number reaches someone who does
+ not recognise the sender, and it leaks which numbers the user owns. Cross-account replies are never
+ an acceptable fallback.
+5. **Rule 8 applies to the MCP surface too.** With several accounts the servers are named per account
+ (`mcp__whatsapp-us__*`, `mcp__whatsapp-nl__*`) and a bare `mcp__whatsapp__*` may not exist. Match
+ the registered name; do not assume.
+
+**Why this section exists:** on 2026-08-16 a full inbox run followed this skill's hardcoded
+`127.0.0.1:8080` and sent every reply from the number that was supposed to stay untouched. The
+classification was fine. The account was wrong, and nothing in the run could tell.
+
## Runtime Context
**Standing default posture — read this first, every run.** Before the offline scan-engine, before any per-channel MCP call, the default mode of this skill is: spin up one agent per available/configured channel (WhatsApp, Email, Slack, Telegram, iMessage, Notion, Discord — whichever are configured; see "Channel availability + fallback" below) via the `Workflow` tool (Agent Teams as the fallback), running in parallel. This is the standing default for the whole skill — you do not wait for triage to discover volume before fanning out; fanning out IS the first move. Each per-channel agent: deep-reads every conversation in its channel, clears the FULL-THREAD AWARENESS GATE, and — for any NEEDS_REPLY candidate — pulls full cross-channel context on that person/topic/thread (gmail search, whatsapp search, the ops-memories contact profile, etc. — per "FULL CONTEXT — NEVER ASSUME" / "FULL-CONTEXT RECALL + CROSS-CHANNEL DEDUP" below) before drafting a reply where one is genuinely needed. It reports back structured recommendations (classification + draft + reasoning, grounded in that cross-channel research) to the orchestrating session. **"READ-ONLY" here means one thing only — never send, archive, mark-read, or mutate anything — it does NOT mean "stay inside your one assigned channel"; agents are granted the cross-channel read/search tools they need for context-gathering.** Every send still goes through the main session's Rule-6 one-draft → one-approval → one-send gate, unchanged (see "Standing behavior: RUN WIDE" and "Workflow fan-out" below for the mechanics and hard constraints). The offline `bin/ops-inbox-scan` step below is a fast pre-filter that FEEDS this fan-out — not a replacement for it, so the per-channel agents aren't blindly scanning everything from scratch. The only exception: skip the fan-out in the genuinely trivial case (script covered everything, ~1-3 candidates left) — that stays the exception, not the default framing.
@@ -114,8 +153,10 @@ The whatsmeow bridge can **silently miss inbound messages** when its history/app
```bash
BR="${WHATSAPP_BRIDGE_DIR:-$HOME/.local/share/whatsapp-mcp/whatsapp-bridge}"
- if curl -s -o /dev/null -m 4 http://127.0.0.1:8080/ 2>/dev/null; then
- curl -fsS -m 10 -X POST http://127.0.0.1:8080/api/backfill >/dev/null 2>&1 & # recent-conversation backfill
+ WA_PORT=$("$CLAUDE_PLUGIN_ROOT/bin/ops-wa-accounts" --port) || exit 3 # never assume 8080
+ WA_API="http://127.0.0.1:${WA_PORT}"
+ if curl -s -o /dev/null -m 4 "$WA_API/" 2>/dev/null; then
+ curl -fsS -m 10 -X POST "$WA_API/api/backfill" >/dev/null 2>&1 & # recent-conversation backfill
[ -f "$BR/link_contacts.py" ] && python3 "$BR/link_contacts.py" >/dev/null 2>&1 & # contacts link (phone + LID aliases)
fi
```
@@ -127,7 +168,7 @@ The whatsmeow bridge can **silently miss inbound messages** when its history/app
**0c-bis. ALL media is now first-class, not just voice.** Beyond voice→`[voice]` (transcribe above), incoming **video / image / document** media (empty `content`) is auto-enriched into `content` as `[video] …` / `[image] …` / `[document] …` by `transcriber/enrich_media.py` (vision for stills/video frames + Whisper for any audio track) on the `whatsapp-enrich.timer` (systemd-user, every 10 min) — and `wa-inbox-fresh.sh` queues an enrich pass on every scan. So an image, clip, or PDF shows up in NEEDS_REPLY / thread scans with a real, readable body, exactly like text. Enrichment is idempotent (only fills empty media rows) and capped per run. The bridge also **self-heals media that 403/404/410s** (stale `directPath`, common for larger media) by asking the sender's phone to re-upload via `SendMediaRetryReceipt` (`apply-patches.py` Fix M), so large media never silently drops.
**0d. The scan engine self-refreshes + self-reconciles on EVERY run — this is automatic, you do not orchestrate it.** `bin/ops-inbox-scan` (the primary classifier, step "Scan engine" below) now does the refresh/pull itself, BLOCKING and bounded, before it classifies — so the data is converged by the time you read its JSON, regardless of whether the background `ops-inbox-autosync` hook has finished. On each invocation the scan:
- - **Refreshes (frontfill/backfill):** if the bridge is reachable on `:8080`, it fires `POST /api/backfill` + `link_contacts.py`, then **waits (bounded ~18s) for the newest stored message timestamp to stop advancing** so the classify pass reads a settled store. This is the blocking guarantee the background hook alone does NOT give. Skip with `OIS_NO_REFRESH=1` (set automatically on repeat calls in one session to avoid re-waiting).
+ - **Refreshes (frontfill/backfill):** if this account's bridge is reachable (the port it resolved, not a fixed `:8080`), it fires `POST /api/backfill` + `link_contacts.py`, then **waits (bounded ~18s) for the newest stored message timestamp to stop advancing** so the classify pass reads a settled store. This is the blocking guarantee the background hook alone does NOT give. Skip with `OIS_NO_REFRESH=1` (set automatically on repeat calls in one session to avoid re-waiting).
- **Reconciles outbound sends (owner directive 2026-06-05 "include all things I sent to all people"):** it reads the bridge's outbound-send journal (`journalctl --user -u whatsapp-bridge.service`, or the bridge log file on non-systemd hosts) into a `{recipient_jid → latest_send_epoch}` map, and **demotes any NEEDS_REPLY thread whose last inbound is older than a send to any of that person's JIDs** (`reconciled` flag set, moved to WAITING). This catches replies that went out via `/api/send` or a phone send that has not yet landed in `messages.db` — the single most common false-NEEDS_REPLY. Only epoch-stamped send lines drive demotion (a send that genuinely predates the inbound never demotes).
Net effect: running `/ops:ops-inbox` autonomously pulls the latest state AND folds in everything the user already sent, with **zero extra orchestration on your part** — just read the scan JSON. A `reconciled` field on a WAITING item means "already answered, reply not yet in the store"; never re-draft it. You still clear the FULL-THREAD AWARENESS GATE on whatever genuine NEEDS_REPLY candidates remain.
@@ -251,15 +292,16 @@ This clones lharries/whatsapp-mcp into `~/.local/share/whatsapp-mcp`, applies th
```bash
DB="${WHATSAPP_BRIDGE_DB:-$HOME/.local/share/whatsapp-mcp/whatsapp-bridge/store/messages.db}"
+WA_API="http://127.0.0.1:$("$CLAUDE_PLUGIN_ROOT/bin/ops-wa-accounts" --port)" # resolve, never assume
for jid in "<NEWSLETTER_JID>@newsletter" "<GROUP_JID>@g.us" "<CONTACT_PHONE>@s.whatsapp.net"; do
- curl -s -X POST http://localhost:8080/api/archive \
+ curl -s -X POST "$WA_API/api/archive" \
-H 'Content-Type: application/json' \
-d "{\"chat_jid\":\"$jid\",\"archive\":true}"
done
# The /api/archive endpoint auto-heals LTHash corruption internally (Fix G) and
# immediately UPSERTs archived=1 into messages.db so the inbox query reflects it.
# If you still get HTTP 409, the heal failed — run resync manually as a last resort:
-# curl -s -X POST http://localhost:8080/api/resync_app_state -d '{"name":"regular_low","full_sync":true,"skip_bad":true}'
+# curl -s -X POST "$WA_API/api/resync_app_state" -d '{"name":"regular_low","full_sync":true,"skip_bad":true}'
```
**Archive state is locally queryable** (Fix H — bridge persists `archived` flag in `chats` table):
@@ -335,8 +377,17 @@ JSON. No subagents, no MCP, near-zero tokens.
"$CLAUDE_PLUGIN_ROOT/bin/ops-inbox-scan" --pretty # both channels
"$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):
+"$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.
+
**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:
@@ -668,7 +719,8 @@ All channel credentials come from env vars or CLI auth — no hardcoded secrets.
> 1. **When Paperclip is on the box**, before KEEP-classifying or drafting money/legal/hire/product: scan open issues + pending `issue_thread_interactions` for that counterparty/thread id (e.g. a payment-round thread → its tracking issue, a card/supplier thread → its issue, a comp/hire thread → its issue). Resolve the concrete counterparty→issue mappings from your local prefs/board, not from this public skill. Prefer the board gate + staged draft over a new Telegram `AskUserQuestion` when the same decision is already wired. Never re-ask a locked Q or contradict answered options.
> 2. **WhatsApp archive is mandatory every pass** — not “demote only.” After classify, call the bridge archive endpoint on **every non-actionable chat and every chat you just replied to** (phone `@s.whatsapp.net` **and** every `@lid` / `alt_jids`):
> ```bash
-> curl -s -X POST http://127.0.0.1:8080/api/archive \
+> # $WA_API = this account's bridge, from `ops-wa-accounts --port`. Never 8080 by default.
+> curl -s -X POST "$WA_API/api/archive" \
> -H 'Content-Type: application/json' \
> -d '{"chat_jid":"<jid>","archive":true}'
> ```
@@ -1033,12 +1085,12 @@ For each channel, detect availability at runtime:
1. **Email**: Try `gog` CLI first. If `gog` unavailable, try `mcp__gog__gmail_*` MCP tools. If neither, report unavailable.
2. **WhatsApp**: Two layers must be checked — DO NOT misdiagnose by only probing one.
- - **Layer A — whatsmeow bridge** (`:8080`): `lsof -i :8080 | grep LISTEN`. If absent, bridge is down — run the robust restart recipe above (`launchctl load -w` fallback before `kickstart`), wait 5s, re-check.
+ - **Layer A — whatsmeow bridge** (this account's port — `ops-wa-accounts --port`, NOT a fixed 8080): `lsof -i :"$WA_PORT" | grep LISTEN`. With several accounts, check the one you resolved; another number's bridge being up says nothing about this one. If absent, bridge is down — run the robust restart recipe above (`launchctl load -w` fallback before `kickstart`), wait 5s, re-check.
- **Layer B — MCP transport**: Claude's client connects to `mcp__whatsapp__*` via the ops mcp-proxy at `127.0.0.1:8090/servers/whatsapp/sse`, NOT directly to :8080. Verify: `lsof -i :8090 | grep LISTEN` and `curl -sS -m 3 http://127.0.0.1:8090/servers/whatsapp/sse | head -1` (should emit `event: endpoint`). If :8090 isn't listening, the ops mcp-proxy daemon is down — restart via `bash ~/.claude/scripts/hooks/ops-plugin-version-heal.sh` then check `${CLAUDE_PLUGIN_DATA_DIR}/daemon-services.json` for the proxy service entry.
- **MCP tool-load handshake**: when both layers are up but `mcp__whatsapp__*` tools aren't listed yet, the SSE handshake is still in flight. Retry `ToolSearch select:mcp__whatsapp__list_chats,mcp__whatsapp__list_messages,mcp__whatsapp__search_contacts,mcp__whatsapp__send_message,mcp__whatsapp__archive_chat,mcp__whatsapp__get_chat,mcp__whatsapp__resync_app_state` **up to 3 times with 5s spacing** before declaring unavailable. Never report "WhatsApp MCP not available" while :8080 AND :8090 are both LISTEN — that is a transient handshake, not a configuration failure.
- **Proxy fd exhaustion** (`EMFILE / Too many open files` in `~/.claude/mcp-proxy/logs/proxy.err.log`): mcp-proxy's `--stateless` mode spawns a new subprocess per SSE connection. macOS launchd's default `maxfiles=256` runs out quickly. Symptom: SSE endpoint resets with `Connection reset by peer` and many stale `whatsapp-mcp-server main.py` zombies linger (`ps aux | grep whatsapp-mcp-server`). Fix: ensure `~/Library/LaunchAgents/com.${USER}.mcp-proxy.plist` has `SoftResourceLimits.NumberOfFiles=4096` + `HardResourceLimits.NumberOfFiles=8192`, then `launchctl unload ~/Library/LaunchAgents/com.${USER}.mcp-proxy.plist && pkill -f whatsapp-mcp-server/.venv && launchctl load -w ~/Library/LaunchAgents/com.${USER}.mcp-proxy.plist`. After restart, Claude's MCP client typically needs a new session to re-handshake; surface this to the user.
- **QR re-pair**: only if :8080 is up but the bridge itself rejects calls (`/api/health` returns auth error, or messages return 401), check `~/.local/share/whatsapp-mcp/whatsapp-bridge/logs/bridge.err.log` for QR pairing prompts.
- - **Headless / no-MCP-transport fallback (EC2, Linux dev-sandbox, any box where Claude-in-Chrome/Kapture are unreachable) — DO NOT declare WhatsApp unavailable.** If `:8080` is LISTEN and `store/messages.db` exists but `mcp__whatsapp__*` never loads after the 3× retry, the WhatsApp MCP server simply isn't registered in _this_ Claude session — the bridge is healthy and the data is right there. **Scan READ-ONLY by querying `messages.db` directly** (`chats`, `messages`, `contacts`, `messages_fts`): NEEDS*REPLY/WAITING from each person's **merged** thread — union both JIDs' `messages` by `timestamp` and classify on the true last row's `is_from_me` (never per-chat `chats.last_is_from_me`; see FULL-THREAD AWARENESS GATE step 1), plus name resolution via `contacts` (populated by step-0 `link_contacts.py`) and thread reads offline. **Merge lid↔phone before classifying** — `whatsmeow_lid_map` when `whatsapp.db` attaches, else `contacts.phone` (same gate recipe). Only \_sending* needs a live transport — use `mcp__whatsapp__send_message` if it loaded, else `curl -X POST http://127.0.0.1:8080/api/send -d '{"recipient":"<jid>","message":"<text>"}'` — still under the Rule-6 one-draft→one-approval gate. **Never report "bridge not installed / WhatsApp unavailable" while `:8080` is LISTEN and the DB has rows** — that is a misdiagnosis; classify from the DB instead.
+ - **Headless / no-MCP-transport fallback (EC2, Linux dev-sandbox, any box where Claude-in-Chrome/Kapture are unreachable) — DO NOT declare WhatsApp unavailable.** If `:8080` is LISTEN and `store/messages.db` exists but `mcp__whatsapp__*` never loads after the 3× retry, the WhatsApp MCP server simply isn't registered in _this_ Claude session — the bridge is healthy and the data is right there. **Scan READ-ONLY by querying `messages.db` directly** (`chats`, `messages`, `contacts`, `messages_fts`): NEEDS*REPLY/WAITING from each person's **merged** thread — union both JIDs' `messages` by `timestamp` and classify on the true last row's `is_from_me` (never per-chat `chats.last_is_from_me`; see FULL-THREAD AWARENESS GATE step 1), plus name resolution via `contacts` (populated by step-0 `link_contacts.py`) and thread reads offline. **Merge lid↔phone before classifying** — `whatsmeow_lid_map` when `whatsapp.db` attaches, else `contacts.phone` (same gate recipe). Only \_sending* needs a live transport — use `mcp__whatsapp__send_message` if it loaded, else `curl -X POST "$WA_API/api/send" -d '{"recipient":"<jid>","message":"<text>"}'`, where `$WA_API` comes from `ops-wa-accounts --port` for **the account this thread lives on** (see "WHICH NUMBER" — a hardcoded 8080 here sends from whichever number owns the low port) — still under the Rule-6 one-draft→one-approval gate. **Never report "bridge not installed / WhatsApp unavailable" while `:8080` is LISTEN and the DB has rows** — that is a misdiagnosis; classify from the DB instead.
- **User prompt** (only after ALL the above fail — i.e. `:8080` genuinely down AND no usable `messages.db`): `AskUserQuestion` with `[Restart bridge]`, `[Restart mcp-proxy]`, `[Skip WhatsApp]`.
3. **Slack**: Read the derived `channels.slack` object from pre-gathered `bin/ops-unread` data (it resolves each `token_env` and reports per-workspace `available`; do NOT read raw `preferences.json → slack_workspaces[]` directly — that array has no `available` flag).
- **Multi-workspace** (`"multi_workspace": true`): iterate the `workspaces` array. For each `available: true` entry, scan via `mcp__claude_ai_Slack__*` if the MCP token matches, or via direct curl. To resolve the token for direct curl, validate `token_env` matches `^[A-Za-z_][A-Za-z0-9_]*$` before `${!token_env}` indirect expansion. Aggregate results; label each message block with the workspace name.
@@ -1292,7 +1344,8 @@ Reply via: `mcp__whatsapp__send_message` with `{recipient: "<JID>", message: "<m
| Send message | `mcp__whatsapp__send_message {recipient, message}` |
| Chat metadata | `mcp__whatsapp__get_chat {chat_jid}` |
| Message context | `mcp__whatsapp__get_message_context {chat_jid, message_id}` |
-| Check bridge (whatsmeow) | `lsof -i :8080 \| grep LISTEN` |
+| Resolve which account/port | `"$CLAUDE_PLUGIN_ROOT/bin/ops-wa-accounts" --list` / `--port` |
+| Check bridge (whatsmeow) | `lsof -i :"$WA_PORT" \| grep LISTEN` (resolved port, not 8080) |
| Check MCP proxy (Claude client transport) | `lsof -i :8090 \| grep LISTEN` + `curl -sS -m 3 http://127.0.0.1:8090/servers/whatsapp/sse \| head -1` |
| Load WhatsApp MCP tool schemas | `ToolSearch select:mcp__whatsapp__list_chats,mcp__whatsapp__list_messages,mcp__whatsapp__search_contacts,mcp__whatsapp__send_message,mcp__whatsapp__archive_chat,mcp__whatsapp__get_chat,mcp__whatsapp__resync_app_state` (retry 3× at 5s) |
| Restart bridge | See robust restart recipe above (load-then-kickstart). Bare `launchctl kickstart` fails if the agent isn't loaded. |