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(whatsapp): resolve client bridges from plugin-written prefs (#892)

Aurora Capitalfa72fe529e1a
diff --git a/claude-ops/CHANGELOG.md b/claude-ops/CHANGELOG.md
index 477a0342..3f8eeca8 100644
--- a/claude-ops/CHANGELOG.md
+++ b/claude-ops/CHANGELOG.md
@@ -1,5 +1,15 @@
## Unreleased
+- fix(whatsapp): `ops-wa-accounts` resolves client-of-remote-bridge accounts from
+ `$PREFS_PATH` `.channels.whatsapp` (written by `/ops:setup` step 3b) and
+ `$OPS_DATA_DIR/registry.json` `.whatsapp`, with legacy
+ `~/.config/whatsapp/agent-policy.json` as fallback. Policy `api` /
+ `bridge_port` wins over a leftover local store. Inbox skills probe the
+ resolved `api` (or `ssh` + `remote_store`); they never guess `:8080` and
+ never `launchctl kickstart` a leftover local bridge. `ops-inbox-autosync`
+ posts `/api/backfill` to each resolved `api`. Template:
+ `scripts/registry.example.json`. Tests in `tests/test-ops-wa-accounts.sh`.
+
- fix(hermes): stop the native plugin registering duplicate `/ops-*` handlers.
Hermes displays a plugin command handler's return value as the final reply,
so those handlers echoed an instruction to load the skill and ended the turn
diff --git a/claude-ops/bin/ops-inbox-autosync b/claude-ops/bin/ops-inbox-autosync
index 4f180371..45af7ade 100755
--- a/claude-ops/bin/ops-inbox-autosync
+++ b/claude-ops/bin/ops-inbox-autosync
@@ -30,10 +30,26 @@ if [ -f "$HOME/.claude/scripts/lib/once.sh" ]; then
fi
BR="${WHATSAPP_BRIDGE_DIR:-$HOME/.local/share/whatsapp-mcp/whatsapp-bridge}"
-if lsof -i :8080 2>/dev/null | grep -q LISTEN; then
+WA_ACCOUNTS_BIN="$(dirname "$0")/ops-wa-accounts"
+APIS=""
+if [ -x "$WA_ACCOUNTS_BIN" ]; then
+ APIS="$(python3 -c 'import json,sys
+try:
+ d=json.load(sys.stdin)
+except Exception:
+ d={}
+for a in d.get("accounts") or []:
+ if a.get("agent_enabled") and a.get("api"):
+ print(a["api"])
+' < <("$WA_ACCOUNTS_BIN" 2>/dev/null) || true)"
+fi
+if [ -n "$APIS" ]; then
(
- curl -fsS -m 10 -X POST http://127.0.0.1:8080/api/backfill >/dev/null 2>&1
- [ -f "$BR/link_contacts.py" ] && python3 "$BR/link_contacts.py" >/dev/null 2>&1
+ while IFS= read -r api; do
+ [ -n "$api" ] || continue
+ curl -fsS -m 10 -X POST "${api}/api/backfill" >/dev/null 2>&1 || true
+ done <<< "$APIS"
+ [ -f "$BR/link_contacts.py" ] && python3 "$BR/link_contacts.py" >/dev/null 2>&1 || true
) >/dev/null 2>&1 &
disown 2>/dev/null || true
fi
diff --git a/claude-ops/bin/ops-unread b/claude-ops/bin/ops-unread
index 69b4643d..c70c50f0 100755
--- a/claude-ops/bin/ops-unread
+++ b/claude-ops/bin/ops-unread
@@ -13,30 +13,26 @@ set -euo pipefail
RESULT='{"channels":{}}'
-# ── WhatsApp via Baileys bridge ──
-BRIDGE_DB="${WHATSAPP_BRIDGE_DB:-$HOME/.local/share/whatsapp-mcp/whatsapp-bridge/store/messages.db}"
-BRIDGE_RUNNING=0
-if lsof -i :8080 2>/dev/null | grep -q LISTEN; then
- BRIDGE_RUNNING=1
+# ── WhatsApp: policy/resolver, never assume :8080 ──
+WA_ACCOUNTS_BIN="$(dirname "$0")/ops-wa-accounts"
+if [ -x "$WA_ACCOUNTS_BIN" ]; then
+ WA_JSON="$("$WA_ACCOUNTS_BIN" 2>/dev/null || true)"
+else
+ WA_JSON=""
fi
-
-if [[ $BRIDGE_RUNNING -eq 1 ]] && [[ -f "$BRIDGE_DB" ]]; then
- # Count chats with recent activity (7 days) directly from bridge messages.db
- WA_RECENT=$(sqlite3 "$BRIDGE_DB" "
- SELECT COUNT(DISTINCT chat_jid) FROM messages
- WHERE timestamp >= datetime('now', '-7 days');
- " 2>/dev/null || echo "0")
- [[ "$WA_RECENT" =~ ^[0-9]+$ ]] || WA_RECENT="0"
- RESULT=$(echo "$RESULT" | jq \
- --argjson c "$WA_RECENT" \
- '.channels.whatsapp = {"recent_chats": $c, "connected": true, "available": true}')
-elif [[ $BRIDGE_RUNNING -eq 0 ]]; then
- RESULT=$(echo "$RESULT" | jq \
- --arg uid "${UID:-}" \
- --arg user "${USER:-}" \
- '.channels.whatsapp = {"unread": 0, "available": false, "note": ("whatsapp-bridge not running — restart: launchctl kickstart -k gui/" + $uid + "/com." + $user + ".whatsapp-bridge")}')
+WA_N=$(printf '%s' "$WA_JSON" | python3 -c 'import json,sys
+try:
+ d=json.load(sys.stdin)
+ print(len([a for a in d.get("accounts") or [] if a.get("agent_enabled")]))
+except Exception:
+ print(0)
+' 2>/dev/null || echo 0)
+if [ "$WA_N" != "0" ]; then
+ RESULT=$(echo "$RESULT" | jq --argjson n "$WA_N" \
+ '.channels.whatsapp = {"accounts": $n, "available": true, "note": "resolved via ops-wa-accounts; classify via policy api or ssh remote_store"}')
else
- RESULT=$(echo "$RESULT" | jq '.channels.whatsapp = {"unread": 0, "available": false, "note": "whatsapp-bridge DB not found — run scripts/whatsapp-bridge-migrate.sh"}')
+ RESULT=$(echo "$RESULT" | jq \
+ '.channels.whatsapp = {"unread": 0, "available": false, "note": "no WhatsApp accounts in $PREFS_PATH / registry — run /ops:setup step 3b. Do not launchctl a leftover local bridge."}')
fi
# ── Email via gog ──
diff --git a/claude-ops/bin/ops-wa-accounts b/claude-ops/bin/ops-wa-accounts
index 62e83431..f92ff8bd 100755
--- a/claude-ops/bin/ops-wa-accounts
+++ b/claude-ops/bin/ops-wa-accounts
@@ -19,14 +19,30 @@
# 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
+# Account policy (never committed — it holds real numbers). /ops:setup writes
+# it. Later files overlay earlier:
+# 1. ~/.config/whatsapp/agent-policy.json (legacy)
+# 2. $OPS_DATA_DIR/registry.json .whatsapp (gitignored)
+# 3. $PREFS_PATH .channels.whatsapp (plugin data dir; wins)
+#
+# {
+# "default_agent_enabled": true,
+# "accounts": {
+# "<e164>": {
+# "label": "personal",
+# "agent_enabled": true,
+# "api": "http://127.0.0.1:<proxy-port>",
+# "bridge_port": "<proxy-port>",
+# "ssh": "user@bridge-host",
+# "remote_store": "/path/on/host/store/messages.db"
+# }
# }
+# }
+#
+# Bridges may run on another host. This machine is then a client: `api` is the
+# local reverse-proxy URL (never a remote IP, never a guessed :8080).
+# `bridge_port` is that local listen port. A store path is optional; a client
+# box often has no local messages.db. Template: scripts/registry.example.json.
#
# Exit codes: 0 ok · 3 no single agent-enabled account · 4 nothing discovered.
@@ -37,6 +53,7 @@ import os
import re
import sqlite3
import sys
+from urllib.parse import urlparse
HOME = os.path.expanduser("~")
BRIDGE_GLOB = os.environ.get(
@@ -47,6 +64,22 @@ POLICY_PATH = os.environ.get(
)
DEFAULT_BRIDGE_PORT = 8080 # whatsmeow's own default when WA_PORT is unset
+
+def _data_dir():
+ return os.environ.get(
+ "CLAUDE_PLUGIN_DATA_DIR",
+ os.path.join(HOME, ".claude/plugins/data/ops-ops-marketplace"),
+ )
+
+
+def _prefs_path():
+ return os.environ.get("PREFS_PATH") or os.path.join(_data_dir(), "preferences.json")
+
+
+def _registry_path():
+ data = os.environ.get("OPS_DATA_DIR") or _data_dir()
+ return os.environ.get("OPS_REGISTRY") or os.path.join(data, "registry.json")
+
# `export WA_PHONE="${WA_PHONE:-31612345678}"` and friends.
_DEFAULT_RE = r'{0}=(?:"|\')?\$\{{{0}:-([^}}]*)\}}'
# A plain `WA_PORT=8082` line in an env file.
@@ -91,14 +124,76 @@ def _paired_jid(store_dir):
return str(row[0]).split(":", 1)[0].split("@", 1)[0] or None
-def _load_policy():
+def _read_json(path):
try:
- with open(POLICY_PATH) as fh:
- pol = json.load(fh)
+ with open(path) as fh:
+ data = 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
+ return None
+ return data if isinstance(data, dict) else None
+
+
+def _accounts_from_blob(blob):
+ """Return (accounts_map, default_agent_enabled) from a policy-shaped dict."""
+ if not isinstance(blob, dict):
+ return {}, None
+ if isinstance(blob.get("accounts"), dict):
+ return dict(blob["accounts"]), blob.get("default_agent_enabled")
+ values = list(blob.values())
+ if values and all(isinstance(v, dict) for v in values):
+ sample = values[0]
+ if any(k in sample for k in ("api", "bridge_port", "agent_enabled", "ssh", "remote_store")):
+ return dict(blob), None
+ return {}, None
+
+
+def _merge_account_maps(base, overlay):
+ out = dict(base or {})
+ for phone, rule in (overlay or {}).items():
+ if not isinstance(rule, dict):
+ continue
+ phone = str(phone)
+ if phone in out and isinstance(out[phone], dict):
+ merged = dict(out[phone])
+ merged.update(rule)
+ out[phone] = merged
+ else:
+ out[phone] = dict(rule)
+ return out
+
+
+def _load_policy():
+ """Merge WhatsApp accounts from legacy policy, registry, then prefs (wins)."""
+ accounts = {}
+ policy_default = None
+
+ pol = _read_json(POLICY_PATH)
+ if pol is not None:
+ a, d = _accounts_from_blob(pol)
+ accounts = _merge_account_maps(accounts, a)
+ if d is not None:
+ policy_default = d
+
+ reg = _read_json(_registry_path())
+ if reg is not None and isinstance(reg.get("whatsapp"), dict):
+ a, d = _accounts_from_blob(reg["whatsapp"])
+ accounts = _merge_account_maps(accounts, a)
+ if d is not None:
+ policy_default = d
+
+ prefs = _read_json(_prefs_path())
+ if prefs is not None:
+ channels = prefs.get("channels") if isinstance(prefs.get("channels"), dict) else {}
+ wa = channels.get("whatsapp")
+ if wa is None:
+ wa = prefs.get("whatsapp")
+ if isinstance(wa, dict):
+ a, d = _accounts_from_blob(wa)
+ accounts = _merge_account_maps(accounts, a)
+ if d is not None:
+ policy_default = d
+
+ return accounts, policy_default, None
def discover():
@@ -179,6 +274,8 @@ def discover():
notes.append("%s: %s" % (acct["label"], acct["mismatch"]))
found.append(acct)
+ found = _merge_policy_clients(found, accounts, policy_default, notes)
+
enabled = [a for a in found if a["agent_enabled"] is True]
unknown = [a for a in found if a["agent_enabled"] is None]
@@ -196,11 +293,106 @@ def discover():
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)
+ "%d accounts have no policy entry — write channels.whatsapp.accounts "
+ "in %s (or %s) before agents touch them"
+ % (len(unknown), _prefs_path(), POLICY_PATH)
)
- return {"accounts": found, "default": default, "notes": notes, "policy": POLICY_PATH}
+ return {
+ "accounts": found,
+ "default": default,
+ "notes": notes,
+ "policy": _prefs_path(),
+ "policy_sources": {
+ "prefs": _prefs_path(),
+ "registry": _registry_path(),
+ "legacy": POLICY_PATH,
+ },
+ }
+
+
+def _port_from_api(api):
+ if not api:
+ return None
+ try:
+ p = urlparse(api)
+ if p.port:
+ return int(p.port)
+ except ValueError:
+ return None
+ return None
+
+
+def _merge_policy_clients(found, accounts_pol, policy_default, notes):
+ """Overlay policy `api`/`bridge_port` and add client-only accounts.
+
+ A box can have no local whatsmeow store (the bridge runs on another host).
+ Policy then carries the local reverse-proxy URL the agent must dial.
+ Policy port/api always wins over a leftover local store's launcher port.
+ """
+ by_phone = {}
+ for a in found:
+ if a.get("phone"):
+ by_phone[str(a["phone"])] = a
+
+ for phone, rule in (accounts_pol or {}).items():
+ if not isinstance(rule, dict):
+ continue
+ phone = str(phone)
+ api = (rule.get("api") or "").rstrip("/")
+ port = rule.get("bridge_port") or rule.get("caddy_port")
+ try:
+ port = int(port) if port is not None else _port_from_api(api)
+ except (TypeError, ValueError):
+ port = _port_from_api(api)
+ store = rule.get("store") or ""
+ if not api and port:
+ api = "http://127.0.0.1:%d" % port
+ if not api and not port and not store:
+ continue
+ enabled = rule.get("agent_enabled", policy_default)
+ reason = rule.get("note") or "policy client"
+
+ existing = by_phone.get(phone)
+ ssh = (rule.get("ssh") or "").strip()
+ ssh_fallback = (rule.get("ssh_fallback") or "").strip()
+ remote_store = (rule.get("remote_store") or "").strip()
+ if existing:
+ if port:
+ existing["port"] = port
+ if api:
+ existing["api"] = api
+ if store:
+ existing["store"] = store
+ if ssh:
+ existing["ssh"] = ssh
+ if ssh_fallback:
+ existing["ssh_fallback"] = ssh_fallback
+ if remote_store:
+ existing["remote_store"] = remote_store
+ existing["policy_reason"] = reason
+ if enabled is not None:
+ existing["agent_enabled"] = bool(enabled)
+ continue
+
+ found.append({
+ "label": rule.get("label") or phone,
+ "dir": "",
+ "store": store,
+ "port": port or 0,
+ "api": api or "",
+ "ssh": ssh,
+ "ssh_fallback": ssh_fallback,
+ "remote_store": remote_store,
+ "phone": phone,
+ "phone_configured": phone,
+ "phone_paired": None,
+ "agent_enabled": bool(enabled) if enabled is not None else None,
+ "policy_reason": reason,
+ })
+ by_phone[phone] = found[-1]
+ notes.append("policy client %s → %s" % (phone, api or store or ("port %s" % port)))
+ return found
def main():
@@ -216,12 +408,17 @@ def main():
if args.list:
if not res["accounts"]:
- print("no whatsmeow bridge found under %s" % BRIDGE_GLOB, file=sys.stderr)
+ print(
+ "no WhatsApp accounts in %s, %s, or %s"
+ % (_prefs_path(), _registry_path(), POLICY_PATH),
+ file=sys.stderr,
+ )
return 4
- print("%-24s %-6s %-16s %-8s %s" % ("BRIDGE", "PORT", "PHONE", "AGENT", "STORE"))
+ print("%-24s %-6s %-16s %-8s %s" % ("BRIDGE", "PORT", "PHONE", "AGENT", "API/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"]))
+ loc = a.get("api") or a.get("store") or ""
+ print("%-24s %-6s %-16s %-8s %s" % (a["label"], a.get("port") or "-", a["phone"] or "?", state, loc))
for n in res["notes"]:
print("note: %s" % n, file=sys.stderr)
return 0
diff --git a/claude-ops/scripts/registry.example.json b/claude-ops/scripts/registry.example.json
index 766c2d3d..d034bdea 100644
--- a/claude-ops/scripts/registry.example.json
+++ b/claude-ops/scripts/registry.example.json
@@ -1,6 +1,21 @@
{
"version": "1.0",
"owner": "Your Name",
+ "whatsapp": {
+ "backend": "whatsapp-bridge",
+ "default_agent_enabled": true,
+ "accounts": {
+ "<e164>": {
+ "label": "personal",
+ "agent_enabled": true,
+ "api": "http://127.0.0.1:<proxy-port>",
+ "bridge_port": "<proxy-port>",
+ "ssh": "",
+ "ssh_fallback": "",
+ "remote_store": ""
+ }
+ }
+ },
"projects": [
{
"alias": "my-app",
diff --git a/claude-ops/skills/ops-inbox/CHANNELS.md b/claude-ops/skills/ops-inbox/CHANNELS.md
index 9a7c788a..7730f9ee 100644
--- a/claude-ops/skills/ops-inbox/CHANNELS.md
+++ b/claude-ops/skills/ops-inbox/CHANNELS.md
@@ -2,50 +2,57 @@
This document explains how to configure each communication channel for the `/ops:ops-inbox` skill. All credentials come from environment variables or CLI auth — **no secrets are committed to this repo**.
-## WhatsApp (Baileys bridge)
+## WhatsApp (whatsmeow bridge)
-**Status:** MCP-based via `mcp__whatsapp__*` tools. No CLI needed.
+**Status:** MCP (`mcp__whatsapp__*` or per-account `mcp__whatsapp-<label>__*`) plus `bin/ops-wa-accounts`.
-The Baileys `whatsapp-bridge` binary runs as a persistent LaunchAgent (`com.${USER}.whatsapp-bridge`)
-and exposes WhatsApp over a local HTTP/MCP interface on port 8080.
+The whatsmeow bridge may run **on this machine** or **on another host**. This client never
+guesses `:8080` and never starts a local LaunchAgent unless policy says the bridge is local.
-### Setup
+### Resolve
-1. Ensure the bridge binary is installed at `~/.local/share/whatsapp-mcp/whatsapp-bridge/whatsapp-bridge`
-2. Install the LaunchAgent plist from the template at `assets/launchagents/com.claude-ops.whatsapp-bridge.plist`. The installed plist's Label is parameterized per-user via `${USER}` so each macOS user gets their own bridge:
- ```bash
- PLIST="$HOME/Library/LaunchAgents/com.${USER}.whatsapp-bridge.plist"
- BRIDGE_DIR="$HOME/.local/share/whatsapp-mcp/whatsapp-bridge"
- sed -e "s|__BRIDGE_BINARY_PATH__|$BRIDGE_DIR/whatsapp-bridge|g" \
- -e "s|__BRIDGE_WORKING_DIR__|$BRIDGE_DIR|g" \
- -e "s|__HOME__|$HOME|g" \
- -e "s|__USER__|$USER|g" \
- "${CLAUDE_PLUGIN_ROOT}/assets/launchagents/com.claude-ops.whatsapp-bridge.plist" > "$PLIST"
- launchctl bootstrap gui/$(id -u) "$PLIST"
- ```
-3. On first run the bridge prints a QR code to its log — scan from WhatsApp → Linked Devices.
-4. Run schema migration: `${CLAUDE_PLUGIN_ROOT}/scripts/whatsapp-bridge-migrate.sh`
+```bash
+"$CLAUDE_PLUGIN_ROOT/bin/ops-wa-accounts" --list
+```
+
+Accounts come from local `~/.local/share/whatsapp-mcp/whatsapp-bridge*` stores **and** from
+policy `/ops:setup` writes (never committed):
+
+1. `$PREFS_PATH` → `.channels.whatsapp` (wins)
+2. `$OPS_DATA_DIR/registry.json` → `.whatsapp` (see `scripts/registry.example.json`)
+3. `~/.config/whatsapp/agent-policy.json` (legacy)
+
+A client-only account sets:
+
+```json
+"<e164>": { "label": "personal", "agent_enabled": true, "api": "http://127.0.0.1:<proxy-port>", "bridge_port": "<proxy-port>", "ssh": "user@bridge-host", "remote_store": "/path/on/host/store/messages.db" }
+```
+
+`api` is the local reverse-proxy URL. Do not put a remote IP there. Two agent-enabled
+accounts: scan each, labelled. `--port` exits 3 on purpose.
### Check health
```bash
-lsof -i :8080 | grep LISTEN # bridge running?
-launchctl list com.${USER}.whatsapp-bridge # launchd status
-cat ~/.local/share/whatsapp-mcp/whatsapp-bridge/logs/bridge.err.log | tail -20
+# Per account from the resolver JSON:
+curl -s -o /dev/null -w "%{http_code}\n" "$WA_API/api/v1/status"
+# 401 = healthy when /api/v1/* is Bearer-gated. 000 = proxy/upstream down.
```
### Troubleshooting
-- `bridge not running`: `launchctl kickstart -k gui/$(id -u)/com.${USER}.whatsapp-bridge`
-- Auth expired: check `bridge.err.log` for QR prompt; session stored in `whatsapp.db`
-- Missing messages: restart bridge (re-syncs history on connect)
-- FTS search slow: run `scripts/whatsapp-bridge-migrate.sh` to add FTS5 index
+- **000 / connection refused on the policy `api`:** fix the reverse proxy or the remote
+ bridge. Do **not** `launchctl kickstart` a leftover local plist — that is a duplicate
+ session and kicks the live device off.
+- **Local leftover `messages.db`:** stale. Policy `api`/`bridge_port` wins. Do not scan
+ or send against the leftover store.
+- Auth expired: pairing is human-only on the machine that owns the bridge, never here
+ if this box is a client.
### Persistence note
-The bridge syncs messages continuously while running. History is stored in
-`~/.local/share/whatsapp-mcp/whatsapp-bridge/store/messages.db`.
-The `WHATSAPP_BRIDGE_DB` env var overrides the DB path.
+Live history lives next to the bridge process. A client box may keep a snapshot DB for
+offline classify (`store` in policy). `WHATSAPP_BRIDGE_DB` overrides a local path only.
## Email (gog)
diff --git a/claude-ops/skills/ops-inbox/SKILL.md b/claude-ops/skills/ops-inbox/SKILL.md
index 93872b2f..611f109f 100644
--- a/claude-ops/skills/ops-inbox/SKILL.md
+++ b/claude-ops/skills/ops-inbox/SKILL.md
@@ -83,7 +83,7 @@ If you find yourself reaching for any `wacli ...` shell command, stop and use th
| Full-text search | `mcp__whatsapp__list_messages {query: "<text>", limit: 20}` | `wacli messages search` |
| 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` |
+| Health check | `ops-wa-accounts --list`, then `curl -s -o /dev/null -w "%{http_code}" "$WA_API/api/v1/status"` (401 is healthy when the route is Bearer-gated). Never `lsof :8080`, never `launchctl kickstart` unless policy says the bridge is local. | `wacli doctor` / `~/.wacli/.health` |
| 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.
@@ -92,42 +92,45 @@ If you find yourself reaching for any `wacli ...` shell command, stop and use th
## ⚠️ 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.
+**This box may run more than one WhatsApp account.** The bridge process may be local, or it may
+run on another host with this machine as a **client**. Clients dial a local reverse-proxy URL from
+policy (`api` / `bridge_port` in `$PREFS_PATH` `.channels.whatsapp`, written by `/ops:setup`
+step 3b; `$OPS_DATA_DIR/registry.json` `.whatsapp` is the same shape). They never dial a remote
+IP, never guess `:8080`, and never start a local LaunchAgent "to recover" when policy says the
+bridge is elsewhere. A 401 on `$WA_API/api/v1/status` is healthy when that route is Bearer-gated.
**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}"
+"$CLAUDE_PLUGIN_ROOT/bin/ops-wa-accounts" --list # every account: port, number, agent, api
+# Two agent-enabled accounts: scan EACH, labelled. Do not call --port (exits 3 on purpose).
+# For each agent_enabled account in the JSON: WA_API=$account.api
```
-`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.
+`ops-wa-accounts` reads local `whatsapp-bridge*` stores if present, then **overlays policy**
+from `$PREFS_PATH` (wins), then registry, then legacy `~/.config/whatsapp/agent-policy.json`.
+Policy `api` / `bridge_port` always wins over a leftover local store's launcher port. A client
+box with no `messages.db` is still resolved. It exits 3 rather than pick one account when more
+than one is agent-enabled — that is a loop, not a stop.
**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.
+1. **Never hardcode a port, never use whichever port answers, never probe a remote IP.** Use
+ each account's `api` from the resolver 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.
+ scan it, do not archive it, do not send from it, do not pair or re-pair it.
+3. **Two agent-enabled accounts is not ambiguous.** Scan each, keep results labelled by account,
+ reply on the number the thread lives on. Stop and ask only when none are enabled, or when
+ unpolicy'd bridges appear with no `api`.
+4. **Reply on the number the thread lives on.** 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.
+ (`mcp__whatsapp-personal__*`, `mcp__whatsapp-work__*`) and a bare `mcp__whatsapp__*` may not exist. Match
+ the registered name; do not assume. Hermes `wa status` / `wa thread` / `wa find` is a valid
+ read path on a client box when MCP is down.
-**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.
+**Why this section exists:** a full inbox run once followed this skill's hardcoded
+`127.0.0.1:8080` and sent every reply from the wrong number. Guessing a port, or treating a
+missing local `messages.db` as "WhatsApp down", repeats that class of failure.
## Runtime Context
@@ -185,8 +188,8 @@ deterministically, instead of re-deciding a few hundred rows by eye every run:
"$CLAUDE_PLUGIN_ROOT/bin/ops-inbox-archive-set" --scan /tmp/scan.json --json
# extra WhatsApp account (repeat the pair per account):
"$CLAUDE_PLUGIN_ROOT/bin/ops-inbox-archive-set" \
- --wa-store ~/.local/share/whatsapp-mcp/whatsapp-bridge-us/store/messages.db \
- --bridge-port 8082
+ --wa-store ~/.local/share/whatsapp-mcp/whatsapp-bridge-<label>/store/messages.db \
+ --bridge-port <port>
"$CLAUDE_PLUGIN_ROOT/bin/ops-inbox-archive-set" --apply # AFTER approval
```
diff --git a/claude-ops/skills/ops-inbox/references/runtime.md b/claude-ops/skills/ops-inbox/references/runtime.md
index dd7b9646..5b223a93 100644
--- a/claude-ops/skills/ops-inbox/references/runtime.md
+++ b/claude-ops/skills/ops-inbox/references/runtime.md
@@ -10,7 +10,7 @@ Before executing, load available context:
0. **Auto-sync WhatsApp in the background (DEFAULT — every invocation)** — the FIRST thing this skill does, before any scan or menu, is guarantee the store is fresh, then fire a recent-conversation history backfill **and** a contacts-link in the background, non-blocking.
- **0a. Freshness gate (run FIRST, blocking, bounded).** Before classifying anything, run `~/bin/wa-inbox-fresh.sh` (shipped by `scripts/install-whatsapp-bridge-linux.sh`). It probes the bridge with a real **curl connection probe** (`curl -s -m4 http://127.0.0.1:8080/`), forces a backfill, triggers voice-note transcription, and waits (bounded ~32s) for the newest message to settle, then prints a FRESHNESS report (`newest message = … (N min old)`). It **only restarts the bridge if the curl probe genuinely fails twice** — do NOT gate liveness on `ss | grep :8080`, because `ss` renders port 8080 as the service name `webcache`, so the grep never matches and you'd needlessly bounce a healthy bridge. Exit 2 means the bridge is down and unrecoverable → the store is STALE, do not trust last-sender classification.
+ **0a. Freshness gate (run FIRST, blocking, bounded).** Resolve accounts with `ops-wa-accounts` first. Probe **that account's** `api` (local reverse-proxy from `$PREFS_PATH` / registry), never `:8080`, never a remote IP. If policy has `ssh` + `remote_store`, classify by SSH against the live remote sqlite (`/api/chats/unread` on the bridge host loopback, or `sqlite3` over `ssh`). Do **not** treat a missing local `messages.db` as "WhatsApp down". Do **not** `launchctl kickstart` a leftover local LaunchAgent — that is a duplicate session. `~/bin/wa-inbox-fresh.sh` may still backfill via the resolved `api`. Exit 2 from freshness means that account's proxy/upstream failed; try the policy `ssh` path before skipping the channel.
### Mac WhatsApp.app fallback (bridge-miss recovery)
@@ -29,8 +29,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}"
- WA_PORT=$("$CLAUDE_PLUGIN_ROOT/bin/ops-wa-accounts" --port) || exit 3 # never assume 8080
- WA_API="http://127.0.0.1:${WA_PORT}"
+ # Per agent-enabled account: use that account's `api` from ops-wa-accounts JSON.
+ # `--port` exits 3 when more than one account is enabled — that is a loop, not a stop.
+ WA_API="$(python3 -c 'import json,sys; d=json.load(sys.stdin); a=next((x for x in d.get("accounts") or [] if x.get("agent_enabled") and x.get("api")), None); print(a["api"] if a else "")' < <("$CLAUDE_PLUGIN_ROOT/bin/ops-wa-accounts"))"
+ [ -n "$WA_API" ] || exit 3
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)
@@ -77,10 +79,10 @@ The whatsmeow bridge can **silently miss inbound messages** when its history/app
- `secrets_manager` / `doppler` — how to resolve channel credentials if not in env
3. **Daemon health**: Read `${CLAUDE_PLUGIN_DATA_DIR}/daemon-health.json`
- - Check `whatsapp-bridge` status — verify `com.${USER}.whatsapp-bridge` is running (`lsof -i :8080` or `launchctl print "gui/$(id -u)/com.${USER}.whatsapp-bridge"`)
- - Also verify the **ops mcp-proxy** is up on `:8090` (`lsof -i :8090 | grep LISTEN`) — Claude's MCP client connects through the proxy SSE endpoint, not directly to the bridge. If :8080 is up but :8090 is down, `mcp__whatsapp__*` tools will never load.
- - If either layer is down, surface the issue before WhatsApp operations
- - **Do not declare WhatsApp MCP unavailable purely because tools haven't loaded yet** — when both ports are LISTEN, retry `ToolSearch select:mcp__whatsapp__list_chats,...` up to 3× at 5s intervals to let the SSE handshake complete
+ - Check WhatsApp via `ops-wa-accounts` (policy `api` / `ssh`), never `lsof :8080` and never `launchctl kickstart` unless policy says the bridge is local
+ - Also verify the **ops mcp-proxy** is up (`lsof -i :8090 | grep LISTEN` only if this box actually runs that proxy) — Claude's MCP client connects through the proxy SSE endpoint, not directly to the bridge
+ - If the resolved `api` is down, try policy `ssh` before skipping the channel
+ - **Do not declare WhatsApp MCP unavailable purely because tools haven't loaded yet** — when the resolved `api` answers, retry `ToolSearch select:mcp__whatsapp__list_chats,...` up to 3× at 5s intervals to let the SSE handshake complete
4. **Ops memories**: Check `${CLAUDE_PLUGIN_DATA_DIR}/memories/` before drafting any reply:
- `contact_*.md` — load profile for the contact you're about to reply to
diff --git a/claude-ops/skills/setup/SKILL.md b/claude-ops/skills/setup/SKILL.md
index a54ce9ae..1cbecff1 100644
--- a/claude-ops/skills/setup/SKILL.md
+++ b/claude-ops/skills/setup/SKILL.md
@@ -52,7 +52,7 @@ Every Bash tool call MUST include a short `description` parameter (5-10 words, e
- Show what's already configured first, so the user only fills gaps.
- **Never show the user's real name or email in output unless the user explicitly provided it in THIS session.** Do not read from memory, existing configs, or environment variables to populate display names.
- **Max 4 options per `AskUserQuestion` call.** The tool schema enforces `<=4` items in the `options` array. When a step lists >4 choices, filter already-configured items first, then batch the rest into multiple sequential calls of <=4 options each, grouped logically. Use `[More options...]` as the last option to bridge between batches.
-- Run ALL diagnostic/probe commands in parallel when possible. Use multiple Bash tool calls in a single message. Never run sequential probes when they're independent (e.g., `gog auth status` AND `lsof -i :8080 | grep LISTEN` AND keychain scouts should all run simultaneously).
+- Run ALL diagnostic/probe commands in parallel when possible. Use multiple Bash tool calls in a single message. Never run sequential probes when they're independent (e.g., `gog auth status` AND `ops-wa-accounts --list` AND keychain scouts should all run simultaneously).
- All writes go to one of these paths — and nothing else:
- **`$PREFS_PATH`** — per-user preferences + secrets. Resolves to `${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json`. Lives in Claude Code's plugin data dir so it survives plugin reinstalls and version bumps. Never committed to git.
- **`${CLAUDE_PLUGIN_ROOT}/scripts/registry.json`** — per-user project registry (gitignored in the source repo). `mkdir -p` its parent if missing.
diff --git a/claude-ops/skills/setup/channels/whatsapp.md b/claude-ops/skills/setup/channels/whatsapp.md
index e1186fe3..7fc8806b 100644
--- a/claude-ops/skills/setup/channels/whatsapp.md
+++ b/claude-ops/skills/setup/channels/whatsapp.md
@@ -2,7 +2,35 @@
> **Cross-OS gate (read first):** the `launchctl` / `~/Library/LaunchAgents` steps below are **macOS-only**. Branch on `case "$(uname -s)" in Darwin) … ;; Linux) … ;; esac`. On **Linux**, the bridge is a `systemd --user` unit — install via `scripts/install-whatsapp-bridge-linux.sh` (do NOT run the launchctl commands); manage with `systemctl --user {status,restart} whatsapp-bridge`. On **WSL** use the systemd path if `systemctl --user` works, else run the bridge under `nohup`. Secrets use the cross-OS `credential-store.sh` (`secret-tool`/file on Linux), not macOS `security`.
-WhatsApp is handled by the whatsmeow `whatsapp-bridge` (macOS: `com.${USER}.whatsapp-bridge` LaunchAgent, `${USER}` expanded at install time; Linux: `whatsapp-bridge` systemd --user unit) and accessed via `mcp__whatsapp__*` tools.
+WhatsApp is handled by the whatsmeow `whatsapp-bridge` and accessed via `mcp__whatsapp__*` (or per-account `mcp__whatsapp-<label>__*`) tools. The bridge may run **on this machine** or **on another host** (this box is then a client).
+
+Account topology is **user data written by this wizard**, never committed:
+
+- `$PREFS_PATH` → `.channels.whatsapp` (wins)
+- `$OPS_DATA_DIR/registry.json` → `.whatsapp` (same shape; see `scripts/registry.example.json`)
+
+Do not hardcode ports, IPs, PIDs, or phone numbers in the plugin repo.
+
+#### Step 3b.0 — Where does the bridge run?
+
+`AskUserQuestion`:
+
+- `[This machine runs the bridge]`
+- `[This machine is a client — bridge is on another host]`
+- `[Skip WhatsApp]`
+
+**Client path:** do **not** install a local LaunchAgent or systemd unit. Collect, then jump to 3b.5:
+
+- E.164 (digits only, no `+`)
+- `label` (e.g. `personal`, `work`)
+- `api` — local reverse-proxy URL (`http://127.0.0.1:<port>`). Never a remote IP.
+- `bridge_port` — that local listen port
+- optional `ssh` (`user@host`) and `remote_store` (path on that host to `messages.db`)
+- `agent_enabled` true/false
+
+Repeat per extra number (max 4 options per `AskUserQuestion`).
+
+**Local path:** continue 3b.1.
#### Step 3b.1 — Presence
@@ -14,7 +42,7 @@ case "$(uname -s)" in
Darwin) launchctl list com.${USER}.whatsapp-bridge 2>/dev/null | head -3 ;;
Linux) systemctl --user status whatsapp-bridge --no-pager ;;
esac
-lsof -i :8080 2>/dev/null | grep LISTEN
+"${CLAUDE_PLUGIN_ROOT}/bin/ops-wa-accounts" --list
```
If binary missing: ask `AskUserQuestion`: `[Show install docs]`, `[Skip WhatsApp]`. On install docs, print:
@@ -84,29 +112,91 @@ This adds FTS5 index and contacts table to messages.db. Safe to re-run.
#### Step 3b.4 — Smoke test
```bash
-lsof -i :8080 | grep LISTEN # bridge running?
-DB="$HOME/.local/share/whatsapp-mcp/whatsapp-bridge/store/messages.db"
-sqlite3 "$DB" "SELECT COUNT(*) FROM messages;" 2>/dev/null # messages present?
-sqlite3 "$DB" "SELECT COUNT(*) FROM messages_fts;" 2>/dev/null # FTS index present?
+"${CLAUDE_PLUGIN_ROOT}/bin/ops-wa-accounts" --list
+# Per agent_enabled account: curl the resolved `api` (401 is healthy when Bearer-gated).
+# Local store only: sqlite3 "$store" "SELECT COUNT(*) FROM messages;"
```
-If messages > 0 and FTS index present, print:
+If at least one agent-enabled account resolves, print:
```
-✓ WhatsApp — bridge running, N messages, FTS indexed
+✓ WhatsApp — N account(s) in $PREFS_PATH
```
#### Step 3b.5 — Record state
-Write `channels.whatsapp = "whatsapp-bridge"` to `$PREFS_PATH`.
+Write the accounts object to **both** `$PREFS_PATH` and `$OPS_DATA_DIR/registry.json`. Merge; do not clobber other keys. Never commit these files.
+
+```bash
+PREFS_PATH="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/preferences.json"
+OPS_DATA_DIR="${OPS_DATA_DIR:-${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}}"
+mkdir -p "$(dirname "$PREFS_PATH")" "$OPS_DATA_DIR"
+
+# $WA_JSON is the object below, built from answers (local discovery or 3b.0 client).
+# Example shape only — use the user's values, never invent numbers or hosts.
+# {
+# "backend": "whatsapp-bridge",
+# "default_agent_enabled": true,
+# "accounts": {
+# "<e164>": {
+# "label": "personal",
+# "agent_enabled": true,
+# "api": "http://127.0.0.1:<proxy-port>",
+# "bridge_port": "<proxy-port>",
+# "ssh": "",
+# "remote_store": ""
+# }
+# }
+# }
+
+python3 - "$PREFS_PATH" "$OPS_DATA_DIR/registry.json" "$WA_JSON" <<'PY'
+import json, os, sys
+prefs_path, reg_path, blob = sys.argv[1], sys.argv[2], json.loads(sys.argv[3])
+
+def load(path):
+ try:
+ with open(path) as fh:
+ data = json.load(fh)
+ return data if isinstance(data, dict) else {}
+ except (OSError, ValueError):
+ return {}
+
+prefs = load(prefs_path)
+channels = prefs.get("channels") if isinstance(prefs.get("channels"), dict) else {}
+channels["whatsapp"] = blob
+prefs["channels"] = channels
+os.makedirs(os.path.dirname(prefs_path) or ".", exist_ok=True)
+tmp = prefs_path + ".tmp"
+with open(tmp, "w") as fh:
+ json.dump(prefs, fh, indent=2)
+ fh.write("\n")
+os.replace(tmp, prefs_path)
+os.chmod(prefs_path, 0o600)
+
+reg = load(reg_path)
+if not reg:
+ reg = {"version": "1.0"}
+reg["whatsapp"] = blob
+os.makedirs(os.path.dirname(reg_path) or ".", exist_ok=True)
+tmp = reg_path + ".tmp"
+with open(tmp, "w") as fh:
+ json.dump(reg, fh, indent=2)
+ fh.write("\n")
+os.replace(tmp, reg_path)
+os.chmod(reg_path, 0o600)
+print("wrote WhatsApp accounts to prefs + registry")
+PY
+```
+
+For a local single-bridge install, fill `api` from `ops-wa-accounts` after pairing (`http://127.0.0.1:<port>`), `label` from the store directory name, E.164 from the paired JID. Keep `channels.whatsapp.backend = "whatsapp-bridge"` so older readers that expected a string still see a backend key.
**Health contract for other ops skills:**
-All ops skills that use WhatsApp must check `lsof -i :8080 | grep LISTEN` before MCP tool calls.
-If bridge is not running:
+All ops skills that use WhatsApp must call `ops-wa-accounts` and probe each account's `api`. Never `lsof :8080`. Never `launchctl kickstart` unless policy says the bridge is local.
-1. Print: "WhatsApp bridge is not running."
-2. Use `AskUserQuestion`: `[Restart bridge]`, `[Skip WhatsApp]`.
-3. On restart: `launchctl kickstart -k gui/$(id -u)/com.${USER}.whatsapp-bridge`, wait 5s.
+1. Print: "WhatsApp: no accounts in $PREFS_PATH — run /ops:setup step 3b."
+2. Use `AskUserQuestion`: `[Re-run setup 3b]`, `[Skip WhatsApp]`.
+3. On a **local** bridge restart only: `launchctl kickstart` / `systemctl --user restart whatsapp-bridge`, wait 5s.
+4. On a **client** box: fix the reverse proxy or the remote bridge. Do not start a leftover local plist.
> **Deep-dive:** see `${CLAUDE_PLUGIN_ROOT}/skills/ops-comms/SKILL.md` and `${CLAUDE_PLUGIN_ROOT}/skills/ops-inbox/SKILL.md` for full operational instructions.
diff --git a/claude-ops/tests/run-all.sh b/claude-ops/tests/run-all.sh
index 4e825de9..b351265a 100755
--- a/claude-ops/tests/run-all.sh
+++ b/claude-ops/tests/run-all.sh
@@ -62,6 +62,7 @@ run_suite "$TESTS_DIR/test-agent-teams.sh"
run_suite "$TESTS_DIR/test-pocket-env-broker.sh"
run_suite "$TESTS_DIR/test-ops-pocket-notify.sh"
run_suite "$TESTS_DIR/test-ops-inbox-zero.sh"
+run_suite "$TESTS_DIR/test-ops-wa-accounts.sh"
run_suite "$TESTS_DIR/test-ops-daemon-manager.sh"
run_suite "$TESTS_DIR/test-ops-package.sh"
run_suite "$TESTS_DIR/test-safety-hooks.sh"
diff --git a/claude-ops/tests/test-ops-wa-accounts.sh b/claude-ops/tests/test-ops-wa-accounts.sh
new file mode 100755
index 00000000..87f9e2ed
--- /dev/null
+++ b/claude-ops/tests/test-ops-wa-accounts.sh
@@ -0,0 +1,231 @@
+#!/usr/bin/env bash
+# Hermetic coverage for ops-wa-accounts: prefs / registry / leftover-store overlay.
+# No real bridge, no network, no personal numbers.
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+BIN="$ROOT/bin/ops-wa-accounts"
+TMP="$(mktemp -d)"
+trap 'rm -rf "$TMP"' EXIT
+
+PY=python3
+[ -x /usr/bin/python3 ] && PY=/usr/bin/python3
+
+fail() { echo "FAIL: $*" >&2; exit 1; }
+ok() { echo " PASS: $*"; }
+
+"$PY" -c "import py_compile,sys; py_compile.compile(sys.argv[1], doraise=True)" "$BIN" \
+ || fail "ops-wa-accounts must compile"
+
+# Placeholders in the public tree — never personal ports or hostnames.
+for needle in 8482 8483 8082; do
+ if grep -R --include='*.md' --include='*.py' --include='*.sh' --include='*.json' \
+ -n "$needle" "$ROOT/bin/ops-wa-accounts" "$ROOT/skills/ops-inbox" \
+ "$ROOT/skills/setup/channels/whatsapp.md" "$ROOT/scripts/registry.example.json" \
+ >/dev/null 2>&1; then
+ fail "public WhatsApp docs/code still mention port $needle"
+ fi
+done
+ok "no personal bridge ports in public WhatsApp files"
+
+export CLAUDE_PLUGIN_DATA_DIR="$TMP/data"
+export OPS_DATA_DIR="$TMP/data"
+export PREFS_PATH="$TMP/data/preferences.json"
+export OPS_REGISTRY="$TMP/data/registry.json"
+export WHATSAPP_AGENT_POLICY="$TMP/missing-policy.json"
+export WHATSAPP_BRIDGE_GLOB="$TMP/bridges/whatsapp-bridge*"
+mkdir -p "$TMP/data" "$TMP/bridges"
+
+run_json() {
+ "$PY" "$BIN"
+}
+
+# --------------------------------------------------------------------------
+# 1. empty → exit 4 on --list
+# --------------------------------------------------------------------------
+if "$PY" "$BIN" --list >/dev/null 2>"$TMP/err"; then
+ fail "empty discovery should fail --list"
+fi
+grep -q "no WhatsApp accounts" "$TMP/err" || fail "--list stderr should name prefs/registry"
+ok "empty --list exits non-zero"
+
+# --------------------------------------------------------------------------
+# 2. client-only account from $PREFS_PATH
+# --------------------------------------------------------------------------
+cat > "$PREFS_PATH" <<'EOF'
+{
+ "channels": {
+ "whatsapp": {
+ "backend": "whatsapp-bridge",
+ "default_agent_enabled": true,
+ "accounts": {
+ "15551230001": {
+ "label": "personal",
+ "agent_enabled": true,
+ "api": "http://127.0.0.1:19001",
+ "bridge_port": 19001,
+ "ssh": "user@bridge-host",
+ "remote_store": "/var/lib/wa/store/messages.db"
+ }
+ }
+ }
+ }
+}
+EOF
+
+JSON="$(run_json)"
+echo "$JSON" | "$PY" -c '
+import json,sys
+d=json.load(sys.stdin)
+accts=d["accounts"]
+assert len(accts)==1, accts
+a=accts[0]
+assert a["phone"]=="15551230001"
+assert a["api"]=="http://127.0.0.1:19001"
+assert a["port"]==19001
+assert a["agent_enabled"] is True
+assert a["ssh"]=="user@bridge-host"
+assert a["remote_store"]=="/var/lib/wa/store/messages.db"
+assert a["store"]==""
+assert d["default"]["phone"]=="15551230001"
+assert d["policy_sources"]["prefs"].endswith("preferences.json")
+'
+ok "prefs client-only account resolves"
+
+PORT="$("$PY" "$BIN" --port)"
+[ "$PORT" = "19001" ] || fail "--port expected 19001, got $PORT"
+ok "--port from prefs api"
+
+# --------------------------------------------------------------------------
+# 3. registry used when prefs has no accounts (string leftover is ignored)
+# --------------------------------------------------------------------------
+cat > "$PREFS_PATH" <<'EOF'
+{ "channels": { "whatsapp": "whatsapp-bridge" } }
+EOF
+cat > "$OPS_REGISTRY" <<'EOF'
+{
+ "version": "1.0",
+ "whatsapp": {
+ "default_agent_enabled": true,
+ "accounts": {
+ "15551230002": {
+ "label": "work",
+ "agent_enabled": true,
+ "api": "http://127.0.0.1:19002",
+ "bridge_port": 19002
+ }
+ }
+ }
+}
+EOF
+
+JSON="$(run_json)"
+echo "$JSON" | "$PY" -c '
+import json,sys
+d=json.load(sys.stdin)
+assert len(d["accounts"])==1
+assert d["accounts"][0]["phone"]=="15551230002"
+assert d["accounts"][0]["port"]==19002
+'
+ok "registry accounts used when prefs is a legacy string"
+
+# --------------------------------------------------------------------------
+# 4. prefs overlay wins over registry
+# --------------------------------------------------------------------------
+cat > "$PREFS_PATH" <<'EOF'
+{
+ "channels": {
+ "whatsapp": {
+ "accounts": {
+ "15551230002": {
+ "api": "http://127.0.0.1:19099",
+ "bridge_port": 19099,
+ "agent_enabled": true
+ }
+ }
+ }
+ }
+}
+EOF
+
+JSON="$(run_json)"
+echo "$JSON" | "$PY" -c '
+import json,sys
+d=json.load(sys.stdin)
+a=d["accounts"][0]
+assert a["phone"]=="15551230002"
+assert a["port"]==19099, a
+assert a["api"]=="http://127.0.0.1:19099"
+'
+ok "prefs wins over registry on the same number"
+
+# --------------------------------------------------------------------------
+# 5. leftover local store port loses to policy api
+# --------------------------------------------------------------------------
+STORE="$TMP/bridges/whatsapp-bridge/store"
+mkdir -p "$STORE"
+: > "$STORE/messages.db"
+cat > "$TMP/bridges/whatsapp-bridge/run-bridge.sh" <<'EOF'
+#!/bin/bash
+WA_PHONE="${WA_PHONE:-15551230002}"
+WA_PORT="${WA_PORT:-8080}"
+EOF
+
+JSON="$(run_json)"
+echo "$JSON" | "$PY" -c '
+import json,sys
+d=json.load(sys.stdin)
+assert len(d["accounts"])==1, d
+a=d["accounts"][0]
+assert a["phone"]=="15551230002"
+assert a["port"]==19099, a
+assert a["api"]=="http://127.0.0.1:19099"
+'
+ok "policy api wins over leftover local launcher port"
+
+# --------------------------------------------------------------------------
+# 6. two agent-enabled accounts → --port exits 3
+# --------------------------------------------------------------------------
+rm -rf "$TMP/bridges/whatsapp-bridge"
+cat > "$PREFS_PATH" <<'EOF'
+{
+ "channels": {
+ "whatsapp": {
+ "accounts": {
+ "15551230001": {
+ "label": "personal",
+ "agent_enabled": true,
+ "api": "http://127.0.0.1:19001",
+ "bridge_port": 19001
+ },
+ "15551230002": {
+ "label": "work",
+ "agent_enabled": true,
+ "api": "http://127.0.0.1:19002",
+ "bridge_port": 19002
+ }
+ }
+ }
+ }
+}
+EOF
+rm -f "$OPS_REGISTRY"
+
+if "$PY" "$BIN" --port >/dev/null 2>"$TMP/err2"; then
+ fail "--port must exit 3 when two accounts are enabled"
+fi
+RC=0
+"$PY" "$BIN" --port >/dev/null 2>/dev/null || RC=$?
+[ "$RC" = "3" ] || fail "--port exit $RC, expected 3"
+ok "two enabled accounts: --port exits 3"
+
+JSON="$(run_json)"
+echo "$JSON" | "$PY" -c '
+import json,sys
+d=json.load(sys.stdin)
+assert d["default"] is None
+assert len([a for a in d["accounts"] if a["agent_enabled"]])==2
+'
+ok "two enabled accounts listed, default is null"
+
+echo "ops-wa-accounts: PASS"