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.

feat(ops-inbox): WhatsApp autosync, LID contact linking, headless fallback + cross-thread scan rule (#403)

Aurora Capitalf9ca30d5f54c
diff --git a/claude-ops/bin/ops-inbox-autosync b/claude-ops/bin/ops-inbox-autosync
new file mode 100755
index 00000000..4f180371
--- /dev/null
+++ b/claude-ops/bin/ops-inbox-autosync
@@ -0,0 +1,40 @@
+#!/usr/bin/env bash
+# ops-inbox-autosync — UserPromptSubmit hook.
+#
+# Fires a recent-conversation WhatsApp backfill + contacts-link in the BACKGROUND
+# whenever ANY ops inbox command is invoked (/ops:ops-inbox, /ops:ops-comms,
+# /ops:ops-go, /ops:ops-next, or the bare /ops:ops router). Non-blocking and
+# throttled (max 1 run / 60s) so it never stacks. Silent: emits nothing into the
+# prompt context.
+#
+# - backfill: POST /api/backfill (50 most-active chats) — pulls recent history
+# - link: link_contacts.py — populates messages.db.contacts from the
+# whatsmeow store so <pn>@s.whatsapp.net AND <lid>@lid resolve to names
+set -uo pipefail
+
+INPUT="$(cat 2>/dev/null || true)"
+PROMPT="$(printf '%s' "$INPUT" | python3 -c 'import sys,json
+try:
+ print(json.load(sys.stdin).get("prompt",""))
+except Exception:
+ print("")' 2>/dev/null || true)"
+
+# Only act on ops inbox-family commands.
+printf '%s' "$PROMPT" | grep -Eq '/ops:ops($|[[:space:]])|/ops:ops-inbox|/ops:ops-comms|/ops:ops-go|/ops:ops-next' || exit 0
+
+# Throttle to avoid stacking (max 1 run / 60s). Fail-open if guard lib absent.
+if [ -f "$HOME/.claude/scripts/lib/once.sh" ]; then
+ # shellcheck disable=SC1090
+ source "$HOME/.claude/scripts/lib/once.sh"
+ claude_once ops-inbox-autosync 60 || exit 0
+fi
+
+BR="${WHATSAPP_BRIDGE_DIR:-$HOME/.local/share/whatsapp-mcp/whatsapp-bridge}"
+if lsof -i :8080 2>/dev/null | grep -q LISTEN; 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
+ ) >/dev/null 2>&1 &
+ disown 2>/dev/null || true
+fi
+exit 0
diff --git a/claude-ops/hooks/hooks.json b/claude-ops/hooks/hooks.json
index 98f29af2..b6e7fae5 100644
--- a/claude-ops/hooks/hooks.json
+++ b/claude-ops/hooks/hooks.json
@@ -1,5 +1,16 @@
{
"hooks": {
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "bash ${CLAUDE_PLUGIN_ROOT}/bin/ops-inbox-autosync 2>/dev/null || true",
+ "timeout": 5
+ }
+ ]
+ }
+ ],
"SessionStart": [
{
"hooks": [
diff --git a/claude-ops/scripts/install-whatsapp-bridge-linux.sh b/claude-ops/scripts/install-whatsapp-bridge-linux.sh
index 494e4df9..2467a6b8 100755
--- a/claude-ops/scripts/install-whatsapp-bridge-linux.sh
+++ b/claude-ops/scripts/install-whatsapp-bridge-linux.sh
@@ -91,6 +91,11 @@ fi
echo "▶ Applying source patches"
python3 "$WA_ASSETS/apply-patches.py" --install-dir "$INSTALL_DIR"
+# ─── Ship contacts-link helper (ops-inbox auto-syncs it on every invocation) ──
+echo "▶ Installing link_contacts.py (contacts link: phone + LID aliases)"
+cp "$WA_ASSETS/link_contacts.py" "$INSTALL_DIR/whatsapp-bridge/link_contacts.py"
+chmod +x "$INSTALL_DIR/whatsapp-bridge/link_contacts.py"
+
# ─── Bump Go deps + build ────────────────────────────────────────────────────
if [ "$SKIP_BUILD" -ne 1 ]; then
echo "▶ Bumping Go deps + building bridge"
diff --git a/claude-ops/scripts/ops-pocket-approvals.py b/claude-ops/scripts/ops-pocket-approvals.py
index 973ed32e..7de8f144 100644
--- a/claude-ops/scripts/ops-pocket-approvals.py
+++ b/claude-ops/scripts/ops-pocket-approvals.py
@@ -245,13 +245,31 @@ def cmd_digest():
log("digest: wrote missing approval-codemap.json for unchanged open set")
return 0
- ok, info, to = send_via_bridge(f"[Pocket] {len(items)} item(s) need approval", body)
+ # Honour email-config "enabled": when false, suppress the email send but STILL
+ # write CODEMAP + NOTIFIED so the phone-channel fanout (Telegram, etc.) keeps
+ # firing off the state change. (Sam 2026-05-30: email Pocket digest off, Telegram kept.)
+ try:
+ email_enabled = bool(json.loads(CFG.read_text()).get("enabled", True))
+ except Exception:
+ email_enabled = True
+ if email_enabled:
+ ok, info, to = send_via_bridge(
+ f"[Pocket] {len(items)} item(s) need approval", body
+ )
+ else:
+ ok, info, to = (
+ True,
+ "email disabled — state updated for phone fanout only",
+ "(email off)",
+ )
CODEMAP.write_text(json.dumps(codemap, indent=2))
if ok:
NOTIFIED.write_text(
json.dumps({"hash": h, "ts": time.time(), "count": len(items)})
)
- log(f"digest: emailed {len(items)} items to {to} ok={ok} info={info}")
+ log(
+ f"digest: {'emailed' if email_enabled else 'state-only (email off)'} {len(items)} items to {to} ok={ok} info={info}"
+ )
return 0 if ok else 1
diff --git a/claude-ops/scripts/whatsapp/link_contacts.py b/claude-ops/scripts/whatsapp/link_contacts.py
new file mode 100644
index 00000000..2c8ff16e
--- /dev/null
+++ b/claude-ops/scripts/whatsapp/link_contacts.py
@@ -0,0 +1,98 @@
+#!/usr/bin/env python3
+"""Link WhatsApp contacts: populate messages.db `contacts` from the whatsmeow
+session store (whatsapp.db). Resolves both phone JIDs (<pn>@s.whatsapp.net) and
+their LID aliases (<lid>@lid) to display names so chat name-resolution works for
+LID-format chats. Idempotent (INSERT OR REPLACE). Safe to run on every invocation.
+
+Usage: python3 link_contacts.py [--store-dir DIR]
+Prints a one-line JSON summary.
+"""
+
+import sqlite3, os, sys, json
+
+store = os.path.join(os.path.dirname(os.path.abspath(__file__)), "store")
+if "--store-dir" in sys.argv:
+ store = sys.argv[sys.argv.index("--store-dir") + 1]
+MSG_DB = os.path.join(store, "messages.db")
+WA_DB = os.path.join(store, "whatsapp.db")
+
+
+def pick_name(first, full, push, biz):
+ for v in (full, first, push, biz):
+ if v and v.strip():
+ return v.strip()
+ return None
+
+
+def main():
+ if not (os.path.exists(MSG_DB) and os.path.exists(WA_DB)):
+ print(
+ json.dumps(
+ {"ok": False, "error": "db missing", "msg_db": MSG_DB, "wa_db": WA_DB}
+ )
+ )
+ return 1
+ wa = sqlite3.connect(f"file:{WA_DB}?mode=ro", uri=True)
+ # pn -> lid (reverse of lid_map)
+ pn2lid = {}
+ try:
+ for lid, pn in wa.execute("SELECT lid, pn FROM whatsmeow_lid_map"):
+ pn2lid[str(pn)] = str(lid)
+ except sqlite3.OperationalError:
+ pass
+ rows = wa.execute(
+ "SELECT DISTINCT their_jid, first_name, full_name, push_name, business_name "
+ "FROM whatsmeow_contacts"
+ ).fetchall()
+ wa.close()
+
+ msg = sqlite3.connect(MSG_DB)
+ cur = msg.cursor()
+ upserts = 0
+ lid_upserts = 0
+ for their_jid, first, full, push, biz in rows:
+ name = pick_name(first, full, push, biz)
+ if not name or not their_jid:
+ continue
+ node = str(their_jid).split("@")[0]
+ suffix = (
+ str(their_jid).split("@")[1] if "@" in str(their_jid) else "s.whatsapp.net"
+ )
+ phone = node if suffix == "s.whatsapp.net" else None
+ cur.execute(
+ "INSERT INTO contacts(jid,name,phone,source,updated_at) VALUES(?,?,?, 'whatsmeow_link', strftime('%s','now')) "
+ "ON CONFLICT(jid) DO UPDATE SET name=excluded.name, phone=COALESCE(excluded.phone,contacts.phone), "
+ "source='whatsmeow_link', updated_at=strftime('%s','now')",
+ (str(their_jid), name, phone),
+ )
+ upserts += 1
+ # LID alias
+ lid = pn2lid.get(node)
+ if lid:
+ cur.execute(
+ "INSERT INTO contacts(jid,name,phone,source,updated_at) VALUES(?,?,?, 'whatsmeow_link', strftime('%s','now')) "
+ "ON CONFLICT(jid) DO UPDATE SET name=excluded.name, phone=COALESCE(excluded.phone,contacts.phone), "
+ "source='whatsmeow_link', updated_at=strftime('%s','now')",
+ (f"{lid}@lid", name, node),
+ )
+ lid_upserts += 1
+ msg.commit()
+ total = cur.execute(
+ "SELECT count(*) FROM contacts WHERE name IS NOT NULL AND name<>''"
+ ).fetchone()[0]
+ msg.close()
+ print(
+ json.dumps(
+ {
+ "ok": True,
+ "phone_contacts": upserts,
+ "lid_aliases": lid_upserts,
+ "named_total": total,
+ }
+ )
+ )
+ 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 aff1d47f..3da0e90d 100644
--- a/claude-ops/skills/ops-inbox/SKILL.md
+++ b/claude-ops/skills/ops-inbox/SKILL.md
@@ -79,6 +79,16 @@ If you find yourself reaching for any `wacli ...` shell command, stop and use th
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 fire a recent-conversation history backfill **and** a contacts-link in the background, non-blocking. The backfill pulls recent messages for the 50 most-active chats; the link populates `messages.db.contacts` from the whatsmeow session store so both `<pn>@s.whatsapp.net` and `<lid>@lid` chat JIDs resolve to names (without it the `contacts` table is empty and LID-format chats show raw phone numbers). Both are idempotent and safe to run every time:
+ ```bash
+ BR="${WHATSAPP_BRIDGE_DIR:-$HOME/.local/share/whatsapp-mcp/whatsapp-bridge}"
+ if lsof -i :8080 2>/dev/null | grep -q LISTEN; then
+ curl -fsS -m 10 -X POST http://127.0.0.1:8080/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
+ ```
+ Kick this off, then continue with the steps below while it runs — give the link ~2s before name-resolving chats. `link_contacts.py` resolves names via `whatsmeow_contacts` + `whatsmeow_lid_map` (name preference: full_name → first_name → push_name → business_name). It ships via `scripts/install-whatsapp-bridge-linux.sh` into the bridge dir; recreate it from `whatsmeow_contacts`/`whatsmeow_lid_map` if absent.
+
1. **Self-heal plugin version pin** — if any `${CLAUDE_PLUGIN_DATA_DIR}` file or `~/.claude/plugins/installed_plugins.json` references a `cache/ops-marketplace/ops/X.Y.Z/` path that no longer exists on disk, downstream hooks (`stop-all.sh`, `ops-post-session-cleanup`) emit `Plugin directory does not exist`. Resolve before scanning:
```bash
INSTALLED="$HOME/.claude/plugins/installed_plugins.json"
@@ -449,7 +459,8 @@ For each channel, detect availability at runtime:
- **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.
- - **User prompt** (only after the above checks all fail): `AskUserQuestion` with `[Restart bridge]`, `[Restart mcp-proxy]`, `[Skip WhatsApp]`.
+ - **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`): full NEEDS_REPLY/WAITING classification (`last_is_from_me` ≈ last message's `is_from_me`), name resolution (`contacts` table, populated by the step-0 `link_contacts.py`), and thread reads all work offline. 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.
+ - **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.
- **Legacy** (`"multi_workspace": false`): use `mcp__claude_ai_Slack__*` if `channels.slack.available == true` (which itself reflects `SLACK_MCP_ENABLED`).
@@ -544,6 +555,12 @@ If only 3 channels are configured, "All channels" + 3 channel options = 4, fits
- **WAITING**: `last_is_from_me == 1`, or (fallback only) last thread message `is_from_me: true`
- **ARCHIVE**: Newsletters (`@newsletter` JIDs), dead group chats with no recent activity, one-word reactions, or concluded conversations. Bulk-archive these via `mcp__whatsapp__archive_chat {chat_jid, archive: true}` after user confirmation. If the call fails with `LTHash mismatch`, run `mcp__whatsapp__resync_app_state {name: "regular_low", full_sync: true}` first, then retry.
+7. **Cross-thread answered-elsewhere check (BOTH DIRECTIONS — scan Sam's own sent messages).** Before presenting any chat as NEEDS REPLY, verify it has not already been answered in another channel or in a later message within the same thread that the `last_is_from_me` flag missed. This is the most common source of false NEEDS_REPLY:
+ - **Same-thread recheck**: when `last_is_from_me == 0` but the chat has been active recently, call `mcp__whatsapp__list_messages {chat_jid, limit: 5}` and scan ALL five messages for `is_from_me: true` after the inbound message — if one exists, reclassify as WAITING.
+ - **Cross-thread outbound check**: for a NEEDS REPLY candidate, search Sam's own sent messages across ALL threads: `mcp__whatsapp__list_messages {query: "<contact_name_or_topic>", limit: 10}` and check `is_from_me: true` entries — if Sam sent a reply on a different JID (e.g. replied in a group that includes the same person, or via a secondary number) after the inbound timestamp, reclassify as HANDLED.
+ - **DB fallback** (when MCP tools unavailable): `SELECT m.is_from_me, m.timestamp FROM messages m WHERE m.chat_jid != '<this_jid>' AND m.is_from_me=1 AND m.timestamp > <inbound_ts> AND m.body LIKE '%<keyword>%' LIMIT 5` — a hit reclassifies as HANDLED.
+ - **Never surface a NEEDS REPLY that Sam already answered** — a scan that misses Sam's own outbound reply is a misdiagnosis that wastes attention.
+
**Phase 2 — Build context for NEEDS REPLY chats (run in parallel):**
For each NEEDS REPLY chat:
1. **Full conversation summary** — read all 20 messages, summarize the arc: what was discussed, key decisions, open questions