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(whatsapp): Linux (systemd-user) install path + bridge patches (#366)

Aurora Capital77e8c8cc4502
diff --git a/claude-ops/CHANGELOG.md b/claude-ops/CHANGELOG.md
index a9daf6e7..122d9070 100644
--- a/claude-ops/CHANGELOG.md
+++ b/claude-ops/CHANGELOG.md
@@ -4,6 +4,18 @@ All notable changes to this project will be documented in this file.
## [Unreleased]
+### Added
+- **WhatsApp bridge: Linux (systemd-user) install path.** `scripts/install-whatsapp-bridge-linux.sh` clones lharries/whatsapp-mcp, applies the in-repo claude-ops patches (`scripts/whatsapp/apply-patches.py`), drops three systemd-user units (`whatsapp-bridge.service`, `whatsapp-backfill.service`, `whatsapp-backfill.timer`), and pairs via the bridge's pairing-code flow. Idempotent — re-running is safe and only applies missing patches.
+- **`POST /api/backfill` REST endpoint** on the bridge (patch). Lets the claude-ops daemon, a 2h systemd timer, or `curl` trigger a fresh history backfill without restarting the bridge. Returns `{"success":true,"message":"backfill requested"}` when connected; 503 otherwise.
+- **Auto-backfill on `events.Connected`** (patch). Every reconnect fires `requestHistorySync` 5s after Connected — replaces the previous "manual backfill only" behaviour. Idempotent; whatsmeow dedups by message ID.
+- **Cross-platform `whatsapp-bridge` daemon entry** in `scripts/daemon-services.default.json` via `scripts/lib/whatsapp-bridge-up.sh` wrapper that branches `launchctl` (macOS) / `systemctl --user` (Linux). Replaces the previous launchctl-only `command`.
+- **`whatsapp-backfill` daemon entry** (cron `0 */2 * * *`) — fallback trigger for hosts without the systemd timer.
+- **Python MCP server (`whatsapp.py`) LID/contact resolver** (patch). `get_sender_name` now resolves via `whatsmeow_contacts.full_name/push_name/business_name` and `whatsmeow_lid_map` from the bridge's `whatsapp.db`, instead of relying on the macOS-only `contacts` table populated by Contacts.app. Group senders in `@lid` form now resolve to their real names on Linux.
+
+### Fixed
+- **`PairPhone` silent hang** in lharries/whatsapp-mcp (patch). Two fixes per the upstream whatsmeow godoc: (Fix A) `time.Sleep(3 * time.Second)` between `client.Connect()` and `client.PairPhone(...)` so the noise handshake completes; (Fix B) `context.WithTimeout(..., 3*time.Minute)` on `PairPhone` so an internal hang is recoverable instead of leaving the process zombied with no PairSuccess and no Timeout error.
+- **`requestHistorySync` SIGSEGV** (patch). whatsmeow's `BuildHistorySyncRequest(nil, count)` panics because it dereferences `.Chat`/`.ID`/`.Timestamp` on the nil first arg (`send.go:572`). Rewritten to open `messages.db` read-only, pick the 50 most-recently-active chats, and anchor against each chat's oldest stored message — also more efficient than a global request.
+
## [2.11.6] — 2026-05-27
### Added
diff --git a/claude-ops/scripts/daemon-services.default.json b/claude-ops/scripts/daemon-services.default.json
index 2a8ac1f5..879934a4 100644
--- a/claude-ops/scripts/daemon-services.default.json
+++ b/claude-ops/scripts/daemon-services.default.json
@@ -15,10 +15,19 @@
},
"whatsapp-bridge": {
"enabled": true,
- "command": "launchctl kickstart -k gui/$UID/com.${USER}.whatsapp-bridge",
+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/lib/whatsapp-bridge-up.sh",
"health_check": "lsof -i :8080 | grep LISTEN",
"restart_delay": 60,
- "max_restarts": 10
+ "max_restarts": 10,
+ "_note": "Cross-platform bridge starter. Looks at uname: macOS → launchctl kickstart gui/$UID/com.${USER}.whatsapp-bridge ; Linux → systemctl --user restart whatsapp-bridge.service. Install via `bash scripts/install-whatsapp-bridge-linux.sh --wa-phone <E.164>` on Linux hosts; on macOS the legacy launchctl plist still applies. Bridge source: github.com/lharries/whatsapp-mcp (with claude-ops patches applied by install script — see scripts/whatsapp/apply-patches.py)."
+ },
+ "whatsapp-backfill": {
+ "enabled": true,
+ "command": "curl -fsS -m 30 -X POST http://127.0.0.1:8080/api/backfill",
+ "cron": "0 */2 * * *",
+ "restart_delay": 0,
+ "max_restarts": 3,
+ "_note": "On-demand WhatsApp history backfill — POSTs to the bridge's /api/backfill endpoint added by claude-ops patches. Idempotent (whatsmeow dedups by message ID). On Linux installs the systemd timer `whatsapp-backfill.timer` (installed by the install script) is the primary trigger; this daemon entry is the fallback for hosts using the cron-driven claude-ops-daemon. Bridge auto-backfills 5s after every Connected event regardless."
},
"memory-extractor": {
"enabled": true,
diff --git a/claude-ops/scripts/install-whatsapp-bridge-linux.sh b/claude-ops/scripts/install-whatsapp-bridge-linux.sh
new file mode 100755
index 00000000..494e4df9
--- /dev/null
+++ b/claude-ops/scripts/install-whatsapp-bridge-linux.sh
@@ -0,0 +1,181 @@
+#!/usr/bin/env bash
+# install-whatsapp-bridge-linux.sh — set up the WhatsApp MCP stack on a
+# Linux (systemd-user) host so /ops:ops-inbox whatsapp works the same way
+# it does on macOS (where launchctl manages com.${USER}.whatsapp-bridge).
+#
+# Idempotent: rerunning is safe. Existing unit files are overwritten only
+# if the in-tree templates differ; source patches use sentinel strings so
+# they apply at most once. A live pairing session is NOT disturbed unless
+# --reset-session is passed.
+#
+# Required:
+# --wa-phone <E.164> The phone number of the WhatsApp account that
+# will host this device. E.164 without '+' or
+# spaces (e.g. --wa-phone 12025551234).
+#
+# Optional:
+# --install-dir <path> Where to clone the lharries/whatsapp-mcp repo
+# (default: ~/.local/share/whatsapp-mcp)
+# --skip-build Don't rebuild the bridge binary
+# --reset-session Delete whatsapp.db so a fresh pair code is
+# generated (you'll need to scan with the phone)
+# --no-backfill-timer Drop only the bridge unit, skip the 2h timer
+
+set -euo pipefail
+
+REPO_URL="https://github.com/lharries/whatsapp-mcp.git"
+INSTALL_DIR_DEFAULT="$HOME/.local/share/whatsapp-mcp"
+SYSTEMD_DIR="$HOME/.config/systemd/user"
+
+WA_PHONE=""
+INSTALL_DIR="$INSTALL_DIR_DEFAULT"
+SKIP_BUILD=0
+RESET_SESSION=0
+WITH_BACKFILL_TIMER=1
+
+# Source-tree dir (where this script lives in claude-ops checkout)
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+WA_ASSETS="$SCRIPT_DIR/whatsapp"
+
+usage() {
+ sed -n '2,/^$/p' "${BASH_SOURCE[0]}" | sed 's/^# \?//'
+ exit "${1:-0}"
+}
+
+while (("$#")); do
+ case "$1" in
+ --wa-phone) WA_PHONE="$2"; shift 2 ;;
+ --install-dir) INSTALL_DIR="$2"; shift 2 ;;
+ --skip-build) SKIP_BUILD=1; shift ;;
+ --reset-session) RESET_SESSION=1; shift ;;
+ --no-backfill-timer) WITH_BACKFILL_TIMER=0; shift ;;
+ -h|--help) usage 0 ;;
+ *) echo "unknown flag: $1" >&2; usage 1 ;;
+ esac
+done
+
+# ─── Preconditions ───────────────────────────────────────────────────────────
+if [ -z "$WA_PHONE" ]; then
+ echo "ERROR: --wa-phone <E.164> is required (e.g. --wa-phone 12025551234)" >&2
+ exit 2
+fi
+if ! [[ "$WA_PHONE" =~ ^[0-9]+$ ]]; then
+ echo "ERROR: --wa-phone must be digits only, no '+' or spaces. Got: $WA_PHONE" >&2
+ exit 2
+fi
+if ! command -v go >/dev/null && [ "$SKIP_BUILD" -ne 1 ]; then
+ echo "ERROR: 'go' not found. Install Go (1.22+) or pass --skip-build to skip." >&2
+ exit 3
+fi
+if ! command -v systemctl >/dev/null; then
+ echo "ERROR: systemctl not found. This script targets systemd-based Linux hosts." >&2
+ exit 3
+fi
+
+echo "▶ claude-ops WhatsApp bridge install"
+echo " install dir: $INSTALL_DIR"
+echo " wa-phone: $WA_PHONE"
+echo " backfill timer: $([ "$WITH_BACKFILL_TIMER" -eq 1 ] && echo on || echo off)"
+
+# ─── Clone / refresh upstream ────────────────────────────────────────────────
+mkdir -p "$(dirname "$INSTALL_DIR")"
+if [ ! -d "$INSTALL_DIR/whatsapp-bridge" ]; then
+ echo "▶ Cloning $REPO_URL → $INSTALL_DIR"
+ git clone --depth 1 "$REPO_URL" "$INSTALL_DIR"
+else
+ echo "▶ Install dir already present — leaving upstream as-is"
+ echo " (run a manual 'git pull' inside $INSTALL_DIR if you want the latest upstream)"
+fi
+
+# ─── Apply patches (idempotent via sentinels) ────────────────────────────────
+echo "▶ Applying source patches"
+python3 "$WA_ASSETS/apply-patches.py" --install-dir "$INSTALL_DIR"
+
+# ─── Bump Go deps + build ────────────────────────────────────────────────────
+if [ "$SKIP_BUILD" -ne 1 ]; then
+ echo "▶ Bumping Go deps + building bridge"
+ pushd "$INSTALL_DIR/whatsapp-bridge" >/dev/null
+ go get -u go.mau.fi/whatsmeow@latest
+ go get -u ./...
+ go mod tidy
+ go build -o whatsapp-bridge .
+ popd >/dev/null
+fi
+
+# ─── Python venv for whatsapp-mcp-server ─────────────────────────────────────
+if [ -d "$INSTALL_DIR/whatsapp-mcp-server" ]; then
+ echo "▶ Syncing Python MCP server deps"
+ pushd "$INSTALL_DIR/whatsapp-mcp-server" >/dev/null
+ if command -v uv >/dev/null; then
+ uv sync --upgrade
+ else
+ echo " (uv not found — install with 'pip install uv' for a managed venv)"
+ fi
+ popd >/dev/null
+fi
+
+# ─── Drop systemd-user units ─────────────────────────────────────────────────
+echo "▶ Writing systemd-user units → $SYSTEMD_DIR"
+mkdir -p "$SYSTEMD_DIR"
+
+# Bridge: substitute WA_PHONE into the template
+sed "s/__WA_PHONE__/$WA_PHONE/" \
+ "$WA_ASSETS/systemd/whatsapp-bridge.service.template" \
+ > "$SYSTEMD_DIR/whatsapp-bridge.service"
+
+if [ "$WITH_BACKFILL_TIMER" -eq 1 ]; then
+ cp "$WA_ASSETS/systemd/whatsapp-backfill.service" "$SYSTEMD_DIR/"
+ cp "$WA_ASSETS/systemd/whatsapp-backfill.timer" "$SYSTEMD_DIR/"
+fi
+
+# ─── Disable deprecated wacli daemon if present ──────────────────────────────
+if systemctl --user list-unit-files claude-ops-wacli-keepalive.service 2>/dev/null | grep -q wacli-keepalive; then
+ echo "▶ Disabling deprecated claude-ops-wacli-keepalive.service (replaced by systemd-managed bridge)"
+ systemctl --user disable --now claude-ops-wacli-keepalive.service 2>/dev/null || true
+fi
+
+# ─── Optionally wipe the device store for a clean re-pair ────────────────────
+if [ "$RESET_SESSION" -eq 1 ]; then
+ echo "▶ --reset-session: wiping pairing state"
+ rm -f "$INSTALL_DIR/whatsapp-bridge/store/whatsapp.db" \
+ "$INSTALL_DIR/whatsapp-bridge/store/messages.db"
+fi
+
+# ─── Reload + enable + start ─────────────────────────────────────────────────
+echo "▶ Reloading systemd + starting services"
+loginctl enable-linger "$USER" 2>/dev/null || true # survive logout
+systemctl --user daemon-reload
+systemctl --user enable --now whatsapp-bridge.service
+if [ "$WITH_BACKFILL_TIMER" -eq 1 ]; then
+ systemctl --user enable --now whatsapp-backfill.timer
+fi
+
+# ─── Surface the pairing code if present ─────────────────────────────────────
+echo "▶ Waiting briefly for the bridge to come up"
+sleep 6
+CODE=$(journalctl --user -u whatsapp-bridge.service --no-pager --since "30 seconds ago" 2>/dev/null \
+ | grep -oE "pairing code: [A-Z0-9-]+" | tail -1 || true)
+if [ -n "$CODE" ]; then
+ echo ""
+ echo "════════════════════════════════════════════════════════════════════"
+ echo " WhatsApp pairing code: ${CODE#pairing code: }"
+ echo " Enter on +$WA_PHONE WhatsApp → Settings → Linked Devices →"
+ echo " Link a Device → Link with phone number"
+ echo "════════════════════════════════════════════════════════════════════"
+ echo ""
+ echo " Codes expire in 3 minutes. After successful pair, the bridge will"
+ echo " open :8080 and the auto-backfill timer will fire periodically."
+else
+ if lsof -nP -iTCP:8080 2>/dev/null | grep -q LISTEN; then
+ echo "▶ Bridge is already paired and listening on :8080 — done."
+ else
+ echo "▶ No pairing code visible yet. Tail the log:"
+ echo " journalctl --user -u whatsapp-bridge.service -f"
+ fi
+fi
+
+echo ""
+echo "▶ Status reference:"
+echo " systemctl --user status whatsapp-bridge.service"
+echo " systemctl --user list-timers whatsapp-backfill.timer"
+echo " curl -fsS -X POST http://127.0.0.1:8080/api/backfill # on-demand"
diff --git a/claude-ops/scripts/lib/whatsapp-bridge-up.sh b/claude-ops/scripts/lib/whatsapp-bridge-up.sh
new file mode 100755
index 00000000..5cc741b3
--- /dev/null
+++ b/claude-ops/scripts/lib/whatsapp-bridge-up.sh
@@ -0,0 +1,48 @@
+#!/usr/bin/env bash
+# Cross-platform "ensure WhatsApp bridge is up" wrapper used by claude-ops's
+# daemon-services. On macOS it kickstarts the launchd plist; on Linux it
+# restarts the systemd-user unit. Idempotent — safe to call repeatedly.
+
+set -euo pipefail
+
+# Already healthy?
+if lsof -nP -iTCP:8080 2>/dev/null | grep -q LISTEN; then
+ exit 0
+fi
+
+OS="$(uname -s)"
+case "$OS" in
+ Darwin)
+ LABEL="com.${USER}.whatsapp-bridge"
+ TARGET="gui/$(id -u)/${LABEL}"
+ if ! launchctl kickstart -k "$TARGET" 2>/dev/null; then
+ # Fall back to load + retry if the agent isn't loaded yet
+ PLIST="$HOME/Library/LaunchAgents/${LABEL}.plist"
+ [ -f "$PLIST" ] && launchctl load -w "$PLIST" 2>/dev/null || true
+ sleep 2
+ launchctl kickstart -k "$TARGET" 2>/dev/null || true
+ fi
+ ;;
+ Linux)
+ if command -v systemctl >/dev/null && systemctl --user cat whatsapp-bridge.service >/dev/null 2>&1; then
+ systemctl --user restart whatsapp-bridge.service
+ else
+ echo "claude-ops/whatsapp-bridge-up: no whatsapp-bridge.service installed on this Linux host." >&2
+ echo "Run: bash \$CLAUDE_PLUGIN_ROOT/scripts/install-whatsapp-bridge-linux.sh --wa-phone <E.164>" >&2
+ exit 3
+ fi
+ ;;
+ *)
+ echo "claude-ops/whatsapp-bridge-up: unsupported OS: $OS" >&2
+ exit 4
+ ;;
+esac
+
+# Brief grace period for the listener to come up.
+for _ in 1 2 3 4 5; do
+ lsof -nP -iTCP:8080 2>/dev/null | grep -q LISTEN && exit 0
+ sleep 1
+done
+
+echo "claude-ops/whatsapp-bridge-up: bridge did not open :8080 within 5s" >&2
+exit 1
diff --git a/claude-ops/scripts/whatsapp/apply-patches.py b/claude-ops/scripts/whatsapp/apply-patches.py
new file mode 100755
index 00000000..2b8619e4
--- /dev/null
+++ b/claude-ops/scripts/whatsapp/apply-patches.py
@@ -0,0 +1,430 @@
+#!/usr/bin/env python3
+"""Idempotently patch upstream lharries/whatsapp-mcp for Linux EC2 deploys.
+
+Applied to ~/.local/share/whatsapp-mcp/{whatsapp-bridge/main.go, whatsapp-mcp-server/whatsapp.py}.
+
+Patches included:
+ Fix A — 3s sleep between client.Connect() and PairPhone (whatsmeow noise
+ handshake race; library hangs silently otherwise).
+ Fix B — context.WithTimeout(3m) wrapping PairPhone so internal hangs are
+ recoverable (context.Background() never times out).
+ Auto-backfill on events.Connected (5s delay).
+ POST /api/backfill REST endpoint for on-demand / scheduled backfill.
+ Crash-safe requestHistorySync — whatsmeow's BuildHistorySyncRequest panics
+ on nil *types.MessageInfo; new impl picks the 50 most-active chats
+ and anchors against each chat's oldest stored message.
+ Python whatsapp.py — LID-to-phone resolver via whatsmeow_lid_map, and
+ contact-name lookup via whatsmeow_contacts (replaces the macOS-only
+ `contacts` table populated by the Contacts.app mapper).
+
+Every patch is gated on a sentinel string so re-running is a no-op.
+
+Usage:
+ apply-patches.py [--install-dir PATH]
+ --install-dir Defaults to ~/.local/share/whatsapp-mcp
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import pathlib
+import sys
+
+REPO_DIR_DEFAULT = pathlib.Path.home() / ".local/share/whatsapp-mcp"
+
+# ─── main.go: PairPhone race (Fix A + Fix B) ─────────────────────────────────
+PAIR_NEEDLE = """\t\t// No ID stored — pairing-code mode (PairPhone)
+\t\terr = client.Connect()
+\t\tif err != nil {
+\t\t\tlogger.Errorf(\"Failed to connect: %v\", err)
+\t\t\treturn
+\t\t}
+
+\t\tphone := os.Getenv(\"WA_PHONE\")
+\t\tif phone == \"\" {
+\t\t\tphone = \"10000000000\"
+\t\t}
+\t\tcode, perr := client.PairPhone(context.Background(), phone, true, whatsmeow.PairClientChrome, \"Chrome (Linux)\")"""
+
+PAIR_REPLACEMENT = """\t\t// No ID stored — pairing-code mode (PairPhone)
+\t\terr = client.Connect()
+\t\tif err != nil {
+\t\t\tlogger.Errorf(\"Failed to connect: %v\", err)
+\t\t\treturn
+\t\t}
+
+\t\t// claude-ops Fix A: per whatsmeow PairPhone godoc — wait for the websocket+noise
+\t\t// handshake to complete before requesting a pair code, otherwise PairPhone
+\t\t// silently hangs on the IQ response (no PairSuccess, no error).
+\t\ttime.Sleep(3 * time.Second)
+
+\t\tphone := os.Getenv(\"WA_PHONE\")
+\t\tif phone == \"\" {
+\t\t\tphone = \"10000000000\"
+\t\t}
+\t\t// claude-ops Fix B: bound PairPhone with a real deadline. context.Background() has
+\t\t// no deadline, so an internal hang in PairPhone is unrecoverable; with a
+\t\t// deadline the call returns and we hit the outer select watchdog.
+\t\tpairCtx, pairCancel := context.WithTimeout(context.Background(), 3*time.Minute)
+\t\tdefer pairCancel()
+\t\tcode, perr := client.PairPhone(pairCtx, phone, true, whatsmeow.PairClientChrome, \"Chrome (Linux)\")"""
+
+PAIR_SENTINEL = "per whatsmeow PairPhone godoc"
+
+# ─── main.go: auto-backfill on Connected ─────────────────────────────────────
+AUTO_BACKFILL_NEEDLE = """\t\tcase *events.Connected:
+\t\t\tlogger.Infof(\"Connected to WhatsApp\")
+
+\t\tcase *events.LoggedOut:"""
+
+AUTO_BACKFILL_REPLACEMENT = """\t\tcase *events.Connected:
+\t\t\tlogger.Infof(\"Connected to WhatsApp\")
+\t\t\t// claude-ops: auto-trigger a deep history backfill on every Connected event.
+\t\t\t// Idempotent — whatsmeow dedups by message ID. Delayed 5s so the initial
+\t\t\t// history sync the server pushes on connect has a chance to settle.
+\t\t\tgo func(c *whatsmeow.Client) {
+\t\t\t\ttime.Sleep(5 * time.Second)
+\t\t\t\tlogger.Infof(\"Auto-backfill: requesting extra history\")
+\t\t\t\trequestHistorySync(c)
+\t\t\t}(client)
+
+\t\tcase *events.LoggedOut:"""
+
+AUTO_BACKFILL_SENTINEL = "deep history backfill on every Connected event"
+
+# ─── main.go: /api/backfill REST endpoint ────────────────────────────────────
+API_BACKFILL_NEEDLE = """\t// Run server in a goroutine so it doesn't block
+\tgo func() {
+\t\tif err := http.ListenAndServe(serverAddr, nil); err != nil {
+\t\t\tfmt.Printf(\"REST API server error: %v\\n\", err)
+\t\t}
+\t}()
+}"""
+
+API_BACKFILL_REPLACEMENT = """\t// claude-ops: on-demand history backfill — POST /api/backfill.
+\thttp.HandleFunc(\"/api/backfill\", func(w http.ResponseWriter, r *http.Request) {
+\t\tif r.Method != http.MethodPost {
+\t\t\thttp.Error(w, \"Method not allowed\", http.StatusMethodNotAllowed)
+\t\t\treturn
+\t\t}
+\t\tw.Header().Set(\"Content-Type\", \"application/json\")
+\t\tif !client.IsConnected() {
+\t\t\tw.WriteHeader(http.StatusServiceUnavailable)
+\t\t\tfmt.Fprintln(w, `{\"success\":false,\"error\":\"client not connected\"}`)
+\t\t\treturn
+\t\t}
+\t\tgo requestHistorySync(client)
+\t\tfmt.Fprintln(w, `{\"success\":true,\"message\":\"backfill requested\"}`)
+\t})
+
+\t// Run server in a goroutine so it doesn't block
+\tgo func() {
+\t\tif err := http.ListenAndServe(serverAddr, nil); err != nil {
+\t\t\tfmt.Printf(\"REST API server error: %v\\n\", err)
+\t\t}
+\t}()
+}"""
+
+API_BACKFILL_SENTINEL = 'http.HandleFunc("/api/backfill"'
+
+# ─── main.go: crash-safe requestHistorySync ──────────────────────────────────
+SAFE_RHS_NEEDLE = """// Request history sync from the server
+func requestHistorySync(client *whatsmeow.Client) {
+\tif client == nil {
+\t\tfmt.Println(\"Client is not initialized. Cannot request history sync.\")
+\t\treturn
+\t}
+
+\tif !client.IsConnected() {
+\t\tfmt.Println(\"Client is not connected. Please ensure you are connected to WhatsApp first.\")
+\t\treturn
+\t}
+
+\tif client.Store.ID == nil {
+\t\tfmt.Println(\"Client is not logged in. Please scan the QR code first.\")
+\t\treturn
+\t}
+
+\t// Build and send a history sync request
+\thistoryMsg := client.BuildHistorySyncRequest(nil, 100)
+\tif historyMsg == nil {
+\t\tfmt.Println(\"Failed to build history sync request.\")
+\t\treturn
+\t}
+
+\t_, err := client.SendMessage(context.Background(), types.JID{
+\t\tServer: \"s.whatsapp.net\",
+\t\tUser: \"status\",
+\t}, historyMsg)
+
+\tif err != nil {
+\t\tfmt.Printf(\"Failed to request history sync: %v\\n\", err)
+\t} else {
+\t\tfmt.Println(\"History sync requested. Waiting for server response...\")
+\t}
+}"""
+
+SAFE_RHS_REPLACEMENT = """// Request history sync from the server.
+//
+// claude-ops: whatsmeow's BuildHistorySyncRequest REQUIRES a non-nil
+// *types.MessageInfo (it dereferences .Chat / .ID / .Timestamp). Passing nil
+// panics with SIGSEGV — see whatsmeow send.go:572. To do a deep backfill we
+// therefore iterate the most recently active chats and request older messages
+// *before the oldest message we already have* in each. This is also more
+// efficient than asking the server for global history.
+func requestHistorySync(client *whatsmeow.Client) {
+\tif client == nil {
+\t\tfmt.Println(\"Client is not initialized. Cannot request history sync.\")
+\t\treturn
+\t}
+\tif !client.IsConnected() {
+\t\tfmt.Println(\"Client is not connected. Please ensure you are connected to WhatsApp first.\")
+\t\treturn
+\t}
+\tif client.Store.ID == nil {
+\t\tfmt.Println(\"Client is not logged in. Please scan the QR code first.\")
+\t\treturn
+\t}
+
+\tdb, err := sql.Open(\"sqlite3\", \"file:store/messages.db?_foreign_keys=on&mode=ro\")
+\tif err != nil {
+\t\tfmt.Printf(\"Backfill: failed to open messages.db: %v\\n\", err)
+\t\treturn
+\t}
+\tdefer db.Close()
+
+\trows, err := db.Query(`SELECT jid FROM chats ORDER BY last_message_time DESC LIMIT 50`)
+\tif err != nil {
+\t\tfmt.Printf(\"Backfill: chat enumeration failed: %v\\n\", err)
+\t\treturn
+\t}
+\tchatJIDs := []string{}
+\tfor rows.Next() {
+\t\tvar j string
+\t\tif err := rows.Scan(&j); err == nil {
+\t\t\tchatJIDs = append(chatJIDs, j)
+\t\t}
+\t}
+\trows.Close()
+\tif len(chatJIDs) == 0 {
+\t\tfmt.Println(\"Backfill: no chats yet — initial sync will populate; skipping.\")
+\t\treturn
+\t}
+
+\trequested := 0
+\tfor _, chatJID := range chatJIDs {
+\t\tvar msgID, sender string
+\t\tvar ts time.Time
+\t\tvar isFromMe bool
+\t\trow := db.QueryRow(
+\t\t\t`SELECT id, sender, timestamp, is_from_me
+ FROM messages WHERE chat_jid = ? ORDER BY timestamp ASC LIMIT 1`,
+\t\t\tchatJID)
+\t\tif err := row.Scan(&msgID, &sender, &ts, &isFromMe); err != nil {
+\t\t\tcontinue
+\t\t}
+\t\tchatJ, err := types.ParseJID(chatJID)
+\t\tif err != nil {
+\t\t\tcontinue
+\t\t}
+\t\tanchor := &types.MessageInfo{
+\t\t\tMessageSource: types.MessageSource{Chat: chatJ, IsFromMe: isFromMe},
+\t\t\tID: msgID,
+\t\t\tTimestamp: ts,
+\t\t}
+\t\thistoryMsg := client.BuildHistorySyncRequest(anchor, 100)
+\t\tif historyMsg == nil {
+\t\t\tcontinue
+\t\t}
+\t\tif _, err := client.SendMessage(context.Background(), types.JID{
+\t\t\tServer: \"s.whatsapp.net\",
+\t\t\tUser: \"status\",
+\t\t}, historyMsg); err == nil {
+\t\t\trequested++
+\t\t}
+\t}
+\tfmt.Printf(\"Backfill: requested extra history for %d chat(s)\\n\", requested)
+}"""
+
+SAFE_RHS_SENTINEL = "whatsmeow's BuildHistorySyncRequest REQUIRES"
+
+# ─── whatsapp.py: LID + whatsmeow_contacts resolver ──────────────────────────
+PY_PATH_NEEDLE = """MESSAGES_DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'whatsapp-bridge', 'store', 'messages.db')
+WHATSAPP_API_BASE_URL = "http://localhost:8080/api\""""
+
+PY_PATH_REPLACEMENT = """MESSAGES_DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'whatsapp-bridge', 'store', 'messages.db')
+# claude-ops: whatsmeow's own store DB — holds contacts (full_name / push_name) and
+# the LID↔phone map. Authoritative for contact name resolution; the messages.db
+# `chats.name` is only populated when whatsmeow happens to push the name, so it
+# leaves group senders unresolved.
+WHATSAPP_DEVICE_DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'whatsapp-bridge', 'store', 'whatsapp.db')
+WHATSAPP_API_BASE_URL = "http://localhost:8080/api"
+
+
+def _resolve_lid_to_pn(jid_or_lid: str) -> str:
+ \"\"\"claude-ops: If jid_or_lid is a LID jid (e.g. ``218030407741450@lid`` or bare
+ digits matching whatsmeow_lid_map.lid), return the phone-number form
+ (``<pn>@s.whatsapp.net``). Otherwise return the input unchanged.\"\"\"
+ if not jid_or_lid:
+ return jid_or_lid
+ bare = jid_or_lid.split('@')[0]
+ bare_core = bare.split(':')[0]
+ if not bare_core.isdigit():
+ return jid_or_lid
+ try:
+ conn = sqlite3.connect(WHATSAPP_DEVICE_DB_PATH)
+ cur = conn.cursor()
+ cur.execute(\"SELECT pn FROM whatsmeow_lid_map WHERE lid = ? LIMIT 1\", (bare_core,))
+ row = cur.fetchone()
+ if row and row[0]:
+ return f\"{row[0]}@s.whatsapp.net\"
+ except sqlite3.Error:
+ pass
+ finally:
+ if 'conn' in locals():
+ conn.close()
+ return jid_or_lid
+
+
+def _name_from_whatsmeow_contacts(jid: str):
+ \"\"\"claude-ops: Look up display name from whatsmeow's own contacts table
+ (full_name → push_name → business_name → first_name). Tries the jid as-given,
+ then a LID-resolved form, then a bare-phone LIKE match.\"\"\"
+ if not jid:
+ return None
+ try:
+ conn = sqlite3.connect(WHATSAPP_DEVICE_DB_PATH)
+ cur = conn.cursor()
+ candidates = {jid}
+ resolved = _resolve_lid_to_pn(jid)
+ if resolved != jid:
+ candidates.add(resolved)
+ bare = jid.split('@')[0].split(':')[0]
+ if bare.isdigit():
+ candidates.add(f\"{bare}@s.whatsapp.net\")
+ for cand in candidates:
+ cur.execute(
+ \"\"\"SELECT COALESCE(NULLIF(full_name,''), NULLIF(push_name,''),
+ NULLIF(business_name,''), NULLIF(first_name,''))
+ FROM whatsmeow_contacts
+ WHERE their_jid = ? LIMIT 1\"\"\",
+ (cand,))
+ row = cur.fetchone()
+ if row and row[0]:
+ return row[0]
+ if bare.isdigit():
+ cur.execute(
+ \"\"\"SELECT COALESCE(NULLIF(full_name,''), NULLIF(push_name,''),
+ NULLIF(business_name,''), NULLIF(first_name,''))
+ FROM whatsmeow_contacts
+ WHERE their_jid LIKE ? LIMIT 1\"\"\",
+ (f\"{bare}@%\",))
+ row = cur.fetchone()
+ if row and row[0]:
+ return row[0]
+ except sqlite3.Error:
+ pass
+ finally:
+ if 'conn' in locals():
+ conn.close()
+ return None"""
+
+PY_PATH_SENTINEL = "_name_from_whatsmeow_contacts"
+
+
+def replace_idempotent(
+ p: pathlib.Path, needle: str, replacement: str, sentinel: str, label: str
+) -> bool:
+ """Apply a single replace; return True if changed, False if already applied."""
+ text = p.read_text()
+ if sentinel in text:
+ print(f" [skip] {label}: already applied")
+ return False
+ if needle not in text:
+ print(f" [error] {label}: needle not found in {p}", file=sys.stderr)
+ print(
+ " (upstream may have changed shape; patch needs refresh)",
+ file=sys.stderr,
+ )
+ return False
+ p.write_text(text.replace(needle, replacement, 1))
+ print(f" [ok] {label}: applied")
+ return True
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
+ )
+ ap.add_argument(
+ "--install-dir",
+ type=pathlib.Path,
+ default=REPO_DIR_DEFAULT,
+ help="lharries/whatsapp-mcp install root (default: ~/.local/share/whatsapp-mcp)",
+ )
+ args = ap.parse_args()
+
+ main_go = args.install_dir / "whatsapp-bridge" / "main.go"
+ whatsapp_py = args.install_dir / "whatsapp-mcp-server" / "whatsapp.py"
+
+ for p in (main_go, whatsapp_py):
+ if not p.is_file():
+ print(f"ERROR: expected file does not exist: {p}", file=sys.stderr)
+ return 1
+
+ print(f"Applying claude-ops patches to {args.install_dir} ...")
+
+ changed_go = False
+ print(" main.go:")
+ changed_go |= replace_idempotent(
+ main_go,
+ PAIR_NEEDLE,
+ PAIR_REPLACEMENT,
+ PAIR_SENTINEL,
+ "Fix A/B (PairPhone handshake + deadline)",
+ )
+ changed_go |= replace_idempotent(
+ main_go,
+ AUTO_BACKFILL_NEEDLE,
+ AUTO_BACKFILL_REPLACEMENT,
+ AUTO_BACKFILL_SENTINEL,
+ "auto-backfill on events.Connected",
+ )
+ changed_go |= replace_idempotent(
+ main_go,
+ API_BACKFILL_NEEDLE,
+ API_BACKFILL_REPLACEMENT,
+ API_BACKFILL_SENTINEL,
+ "POST /api/backfill endpoint",
+ )
+ changed_go |= replace_idempotent(
+ main_go,
+ SAFE_RHS_NEEDLE,
+ SAFE_RHS_REPLACEMENT,
+ SAFE_RHS_SENTINEL,
+ "crash-safe requestHistorySync (per-chat anchor)",
+ )
+
+ print(" whatsapp.py:")
+ changed_py = replace_idempotent(
+ whatsapp_py,
+ PY_PATH_NEEDLE,
+ PY_PATH_REPLACEMENT,
+ PY_PATH_SENTINEL,
+ "LID resolver + whatsmeow_contacts lookup",
+ )
+
+ if changed_go:
+ print(" main.go changed — caller should `go build` the bridge")
+ if changed_py:
+ print(
+ " whatsapp.py changed — restart the MCP server (mcp-proxy.service) to load"
+ )
+ if not (changed_go or changed_py):
+ print("All patches already applied; nothing to do.")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/claude-ops/scripts/whatsapp/systemd/whatsapp-backfill.service b/claude-ops/scripts/whatsapp/systemd/whatsapp-backfill.service
new file mode 100644
index 00000000..2cd5808d
--- /dev/null
+++ b/claude-ops/scripts/whatsapp/systemd/whatsapp-backfill.service
@@ -0,0 +1,15 @@
+[Unit]
+Description=WhatsApp history backfill — POSTs /api/backfill to the bridge (oneshot)
+Documentation=https://github.com/lharries/whatsapp-mcp
+After=whatsapp-bridge.service
+Requires=whatsapp-bridge.service
+PartOf=whatsapp-bridge.service
+
+[Service]
+Type=oneshot
+# Allow the bridge a moment to be ready (up to 10s) before we POST.
+ExecStartPre=/bin/sh -c 'for i in 1 2 3 4 5; do ss -ltn 2>/dev/null | grep -q ":8080" && exit 0; sleep 2; done; exit 0'
+ExecStart=/usr/bin/curl -fsS -m 30 -X POST -o /dev/null -w "wa-backfill HTTP %%{http_code}\n" http://127.0.0.1:8080/api/backfill
+StandardOutput=journal
+StandardError=journal
+SyslogIdentifier=whatsapp-backfill
diff --git a/claude-ops/scripts/whatsapp/systemd/whatsapp-backfill.timer b/claude-ops/scripts/whatsapp/systemd/whatsapp-backfill.timer
new file mode 100644
index 00000000..1996a78d
--- /dev/null
+++ b/claude-ops/scripts/whatsapp/systemd/whatsapp-backfill.timer
@@ -0,0 +1,14 @@
+[Unit]
+Description=Trigger WhatsApp backfill every 2h + on boot (claude-ops integration)
+Documentation=https://github.com/lharries/whatsapp-mcp
+
+[Timer]
+# First fire 90s after boot/session start (lets the bridge connect first), then every 2h.
+OnBootSec=90s
+OnUnitActiveSec=2h
+AccuracySec=30s
+Persistent=true
+Unit=whatsapp-backfill.service
+
+[Install]
+WantedBy=timers.target
diff --git a/claude-ops/scripts/whatsapp/systemd/whatsapp-bridge.service.template b/claude-ops/scripts/whatsapp/systemd/whatsapp-bridge.service.template
new file mode 100644
index 00000000..d6e0fd60
--- /dev/null
+++ b/claude-ops/scripts/whatsapp/systemd/whatsapp-bridge.service.template
@@ -0,0 +1,22 @@
+[Unit]
+Description=WhatsApp Bridge (whatsmeow / lharries/whatsapp-mcp) for ops-inbox MCP
+Documentation=https://github.com/lharries/whatsapp-mcp
+After=network-online.target
+Wants=network-online.target
+
+[Service]
+Type=simple
+WorkingDirectory=%h/.local/share/whatsapp-mcp/whatsapp-bridge
+ExecStart=%h/.local/share/whatsapp-mcp/whatsapp-bridge/whatsapp-bridge
+# Replaced at install time with the operator's E.164 number (no '+', no spaces).
+Environment=WA_PHONE=__WA_PHONE__
+Restart=on-failure
+RestartSec=5s
+StandardOutput=journal
+StandardError=journal
+SyslogIdentifier=whatsapp-bridge
+# 3-min pairing window can keep the process busy with no output; don't kill it.
+TimeoutStartSec=300
+
+[Install]
+WantedBy=default.target
diff --git a/claude-ops/skills/ops-inbox/SKILL.md b/claude-ops/skills/ops-inbox/SKILL.md
index 3aef2e40..b91c7043 100644
--- a/claude-ops/skills/ops-inbox/SKILL.md
+++ b/claude-ops/skills/ops-inbox/SKILL.md
@@ -68,7 +68,8 @@ 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` + `launchctl list com.${USER}.whatsapp-bridge` | `wacli doctor` / `~/.wacli/.health` |
+| 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) | — |
**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.
@@ -119,32 +120,58 @@ Before executing, load available context:
### whatsapp-bridge (WhatsApp — mcp__whatsapp__*)
-**Bridge health** — check bridge is running before any WhatsApp operation:
+**Bridge health** — check bridge is running before any WhatsApp operation. Same `lsof` probe across platforms; supervisor command differs:
+
+```bash
+lsof -i :8080 | grep LISTEN # bridge listens on :8080 (same on macOS + Linux)
+
+# macOS — launchd:
+launchctl print "gui/$(id -u)/com.${USER}.whatsapp-bridge" 2>&1 | head -3 # use print, NOT list — list only shows already-loaded services
+
+# Linux — systemd-user (installed by scripts/install-whatsapp-bridge-linux.sh):
+systemctl --user is-active whatsapp-bridge.service
+journalctl --user -u whatsapp-bridge.service -n 10 --no-pager
+```
+
+**One-line cross-platform restart** — use the in-repo wrapper when you don't want to branch on uname yourself:
+
```bash
-lsof -i :8080 | grep LISTEN # bridge listens on :8080
-launchctl print "gui/$(id -u)/com.${USER}.whatsapp-bridge" 2>&1 | head -3 # check launchd status (use print, NOT list — list only shows already-loaded services)
+bash "$CLAUDE_PLUGIN_ROOT/scripts/lib/whatsapp-bridge-up.sh"
```
-If bridge is not running, use this **robust restart recipe** (handles the "service not loaded" case that breaks bare `kickstart`):
+It restarts via launchctl on Darwin and `systemctl --user` on Linux, then waits up to 5s for `:8080` to come up.
+
+If you need the raw recipes:
+**macOS** (handles the "service not loaded" case that breaks bare `kickstart`):
```bash
LABEL="com.${USER}.whatsapp-bridge"
PLIST="$HOME/Library/LaunchAgents/${LABEL}.plist"
TARGET="gui/$(id -u)/${LABEL}"
-
-# 1) If kickstart fails with "Could not find service", load the plist first.
if ! launchctl kickstart -k "$TARGET" 2>/dev/null; then
[ -f "$PLIST" ] && launchctl load -w "$PLIST"
sleep 2
launchctl kickstart -k "$TARGET" 2>/dev/null || true
fi
+sleep 5
+lsof -i :8080 | grep -q LISTEN && echo "bridge up" || echo "bridge FAILED — check ~/.local/share/whatsapp-mcp/whatsapp-bridge/logs/bridge.err.log"
+```
-# 2) Verify it's actually listening.
+**Linux** (systemd-user — the install script's standard path):
+```bash
+systemctl --user daemon-reload
+systemctl --user restart whatsapp-bridge.service
sleep 5
-lsof -i :8080 | grep -q LISTEN && echo "bridge up" || echo "bridge FAILED — check $HOME/.local/share/whatsapp-mcp/whatsapp-bridge/logs/bridge.err.log"
+lsof -i :8080 | grep -q LISTEN && echo "bridge up" || journalctl --user -u whatsapp-bridge.service -n 30 --no-pager
```
-**Why this matters:** bare `launchctl kickstart -k gui/$UID/<label>` exits with `Could not find service` if the LaunchAgent isn't loaded (common after reboot, plist edits, or when the daemon hasn't auto-registered). Always quote the target string and fall back to `launchctl load -w` before retrying.
+**Why the macOS recipe matters:** bare `launchctl kickstart -k gui/$UID/<label>` exits with `Could not find service` if the LaunchAgent isn't loaded (common after reboot, plist edits, or when the daemon hasn't auto-registered). Always quote the target string and fall back to `launchctl load -w` before retrying.
+
+**First-time Linux install** — if the bridge isn't installed yet on a Linux host:
+```bash
+bash "$CLAUDE_PLUGIN_ROOT/scripts/install-whatsapp-bridge-linux.sh" --wa-phone <E.164>
+```
+This clones lharries/whatsapp-mcp into `~/.local/share/whatsapp-mcp`, applies the in-repo claude-ops patches (Fix A/B pair-phone hardening, auto-backfill on Connected, `POST /api/backfill` REST endpoint, crash-safe `requestHistorySync`, Python LID↔phone↔contact resolver), drops three systemd-user units (`whatsapp-bridge.service`, `whatsapp-backfill.service`, `whatsapp-backfill.timer`), enables linger, and emits the pairing code via `journalctl --user -u whatsapp-bridge -f`. Idempotent: re-running is safe and updates patches in place.
**MCP tools** (use these instead of any wacli CLI command):