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.
Shell agent-teamsai-agentai-automationanthropicautonomous-agentawsbusiness-operationsclaudeclaude-codeclaude-code-plugindevopsecommerceinbox-zeroklaviyomarketingmcpmorning-briefingpr-automationshopifyterminal
fix(whatsapp-mcp): port apply-patches.py Fix A/B (pairing) + C/D/F/G/L to current upstream + whatsmeow API (#479)
Aurora Capital1c958e46624f
diff --git a/claude-ops/CHANGELOG.md b/claude-ops/CHANGELOG.mdindex 29fd5fa8..abf52997 100644--- a/claude-ops/CHANGELOG.md+++ b/claude-ops/CHANGELOG.md@@ -15,6 +15,11 @@ whatsapp-mcp: self-installing archive_chat via healing /api/archive (Fix M, PR ### [Unreleased]### Fixed+- fix(whatsapp-mcp): port apply-patches.py Fix A/B (pairing) and Fix C/D (`FetchAppState`) to the current upstream + pinned-whatsmeow API — these were genuine API/behaviour drift, not anchor bit-rot, so a fresh reinstall failed to apply and/or failed to compile (`go build`/`go vet` errored). Verified signatures against whatsmeow `v0.0.0-20250318233852-06705625cf82` via `go doc`/source. Changes:+ - **Fix A/B (pairing):** upstream switched to **QR-only** login (no `PairPhone` call to anchor on). `Client.PairPhone` still exists in the pinned whatsmeow, so per "prefer phone-pair when supported" the patcher now **re-introduces phone-number (pairing-code) linking** into upstream's QR block — `WA_PHONE` set → pairing code; unset → QR loop unchanged. `PairPhone` also **lost its `context.Context` parameter** (`PairPhone(phone, showPushNotification, clientType, clientDisplayName)`), so Fix B's old `context.WithTimeout` deadline can't be passed in; the 3-minute hang-bound is preserved by racing `PairPhone` in a goroutine against a `time.After` watchdog. Fix A's 3s post-`Connect` sleep retained. New sentinel keys on inserted-content invariant. Also dropped the old hardcoded fallback phone number (now `os.Getenv("WA_PHONE")` only).+ - **Fix C/D + F/G (`FetchAppState`/`SendAppState`):** current whatsmeow **dropped the `context.Context` first arg** from `FetchAppState(name, fullSync, onlyIfNotSynced)` and `SendAppState(patch)` — `go vet` reported "too many arguments". Updated all four call sites (Fix D resync endpoint, Fix G `healLTHash`, Fix F `/api/archive`). Fix C (`StoreMessage`/`StoreChat` outbound persistence) already matched upstream and is unchanged.+ - **⚠️ BEHAVIOUR CHANGE — Fix L `recover_app_state` degraded:** the pinned whatsmeow **removed the public primary-device peer-recovery path** — `whatsmeow.BuildAppStateRecoveryRequest` no longer exists and `SendPeerMessage` is now only an unexported `DangerousInternals()` method. `sendRecoveryAndBackfill` can no longer ask the phone for an unencrypted snapshot to **bypass a corrupt server patch chain** (#382/#858). It now logs that loudly and falls back to a best-effort **full server-side resync** (`FetchAppState(name, true, false)`) + backfill — which re-applies the server chain but **cannot recover a fatally-unverifiable one**. To restore true peer-recovery, pin a whatsmeow that still exports those APIs. Documented in `ENDPOINTS.md`. **Owner decision needed:** accept resync-only recovery, or pin an older whatsmeow.+ - Verified: fresh upstream clone → all four (+F/G) apply once; `go mod download && go build ./... && go vet ./...` PASS (were 5 errors before); rerun → all `[skip]` (idempotent); live-tree copy → no duplicate insertions, build clean; `py_compile` + `tests/test-no-secrets.sh` clean; no real phone number in the diff. Live install untouched (source-only patcher change).- fix(whatsapp-mcp): apply-patches.py Fix M makes the `archive_chat` + `resync_app_state` MCP surface self-contained — current upstream lharries/whatsapp-mcp ships none of it, so a fresh reinstall left the MCP server with no working `archive_chat`. The MCP tool now durably routes through the healing `POST /api/archive` endpoint (auto-recovers LTHash 409s, whatsmeow #382/#858) instead of a raw app-state mutation. Idempotent against both pristine upstream and already-patched live trees (no duplicate defs on rerun). ENDPOINTS.md documents the heal routing.- fix(whatsapp-mcp): re-anchor apply-patches.py Fix E, Fix H (`*events.Archive` subscriber) and Fix J (`list_chats` archived filter) against current upstream. Their needles had bit-rotted — upstream reflowed whitespace (collapsed a blank line before `get_sender_name`, trailing space after the `SELECT` keyword, blank-line indentation in `list_chats`), dropped trailing commas (last `list_chats` param, last `Chat()` kwarg) and changed the `events.LoggedOut` log string — so a fresh reinstall silently skipped all three (`needle not found`), leaving the bridge with no archive-event subscriber and the MCP server with no `archived` column/filter. Re-anchored each splice to a minimal stable nearby token (e.g. `def get_sender_name`, `case *events.LoggedOut:`, `…last_is_from_me\n FROM chats`) and moved the Fix E / Fix J-row sentinels onto the inserted content's invariant (`def _open_db(`, `archived=bool(chat_data[6])`) so they no-op on the older-patcher-patched live tree instead of duplicating the helper. Inserted content (runtime behaviour) is unchanged. Verified: fresh upstream → all apply once; rerun → all skip; live-tree copy → no duplicate insertions; gofmt + py_compile clean. (Out of scope, flagged: Fix A/B PairPhone and Fix C/D no longer match upstream either — upstream switched to QR pairing and changed `FetchAppState`/send shapes; those are behaviour/API drifts, not just bit-rot.)diff --git a/claude-ops/scripts/whatsapp/ENDPOINTS.md b/claude-ops/scripts/whatsapp/ENDPOINTS.mdindex 20169db6..bf534d4c 100644--- a/claude-ops/scripts/whatsapp/ENDPOINTS.md+++ b/claude-ops/scripts/whatsapp/ENDPOINTS.md@@ -38,6 +38,22 @@ and the **decision rule for MCP vs direct REST vs direct sqlite**.| MCP proxy :8090 | `ss -ltn \| grep :8090` + `curl -sS -m3 http://127.0.0.1:8090/servers/whatsapp/sse \| head -1` | If :8090 down, `mcp__whatsapp__*` will never load even though the bridge is healthy. || systemd | `systemctl --user is-active whatsapp-bridge.service` | `Restart=always`; `whatsapp-bridge-keepalive.timer` (60s) catches hangs. |+## Pairing / login (Fix A/B)++On a fresh, unpaired install the bridge links to the primary device. Upstream+`lharries/whatsapp-mcp` is now **QR-only**. The claude-ops patcher (Fix A/B)+re-introduces **phone-number (pairing-code) linking** for headless EC2 use:++- Set `WA_PHONE=<international digits, no +>` → the bridge calls+ `client.PairPhone(...)` and prints a pairing code to enter in WhatsApp.+- Leave `WA_PHONE` unset → upstream's QR-scan loop runs unchanged.++**API-drift note (2026-06):** the pinned whatsmeow `PairPhone` lost its+`context.Context` parameter, so Fix B's old `context.WithTimeout` deadline can no+longer be passed into the call. The 3-minute hang-bound is preserved by racing+`PairPhone` in a goroutine against a `time.After(3*time.Minute)` watchdog; Fix A's+godoc-endorsed 3s post-`Connect` sleep is retained.+## Bridge REST endpoints (direct API, `http://127.0.0.1:8080`)All POST, JSON body. Source: `whatsapp-bridge/main.go`.@@ -48,7 +64,7 @@ All POST, JSON body. Source: `whatsapp-bridge/main.go`.| `POST /api/download` | `{"message_id":"…","chat_jid":"…"}` | media bytes / path | Fetch media for a message. || `POST /api/backfill` | (none) | `{success:"backfill requested"}` | Request history sync for the ~50 most-active chats. Also auto-runs 5s after each `Connected`. || `POST /api/resync_app_state` | `{"name":"regular_low","full_sync":true}` | `{success,message}` | Force app-state resync from existing patches. **Cannot fix a fatally-corrupt patch chain — use `/api/recover_app_state`.** |-| `POST /api/recover_app_state` | `{"name":"regular_low"}` | `{success,message}` | **Fatal recovery** for an unverifiable collection (`mismatching LTHash`). Asks the PRIMARY device for an unencrypted snapshot (`BuildAppStateRecoveryRequest`→`SendPeerMessage`); whatsmeow's `handleAppStateRecovery` rebuilds it, bypassing broken patches, and a history backfill fires while the link is alive (Fix L). **Phone-online gated (Fix L):** returns `503 phone offline` if the bridge isn't connected+logged-in, instead of a misleading `success:true`. The ONLY thing that unblocks archive when LTHash is fatally desynced. |+| `POST /api/recover_app_state` | `{"name":"regular_low"}` | `{success,message}` | Recovery for a corrupt collection (`mismatching LTHash`). **API-DRIFT DEGRADE (2026-06):** the pinned whatsmeow (`v0.0.0-20250318233852`) **removed** the public primary-device peer-recovery path — `BuildAppStateRecoveryRequest` is gone and `SendPeerMessage` is now only an unexported `DangerousInternals()` method — so this endpoint **no longer asks the phone for an unencrypted snapshot**. It now does a best-effort **full server-side resync** (`FetchAppState(name, fullSync=true)`) + a history backfill while the link is alive (Fix L). This re-applies the server's patch chain but **cannot bypass a server chain that is itself unverifiable** (a truly fatal #382/#858 corruption is no longer auto-recoverable from the bridge on this whatsmeow). **Phone-online gated (Fix L):** returns `503 phone offline` if the bridge isn't connected+logged-in. To restore true peer-recovery, pin a whatsmeow that still exports `BuildAppStateRecoveryRequest`/`SendPeerMessage`. || `POST /api/archive` | `{"chat_jid":"<JID>","archive":true}` | `{success,message}` | Archive / unarchive (`archive:false`). Writes `chats.archived` AND pushes a `regular_low` app-state mutation. **Phone-online gated + auto-recovering (Fix L):** on a local LTHash mismatch OR a server `409 conflict` it auto-heals, then escalates to `recover_app_state` + a bounded retry (~20s) so callers never need a manual recover→retry. Still returns `503 phone offline` if the link is down. |There is **no** delete/mark-read/group-admin endpoint. There is no `/api/health` — probe `/` (404 = alive).diff --git a/claude-ops/scripts/whatsapp/apply-patches.py b/claude-ops/scripts/whatsapp/apply-patches.pyindex 16df6036..9b3555fb 100755--- a/claude-ops/scripts/whatsapp/apply-patches.py+++ b/claude-ops/scripts/whatsapp/apply-patches.py@@ -83,44 +83,116 @@ import sysREPO_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)+# ─── main.go: phone-number pairing path (Fix A + Fix B) ──────────────────────+# API DRIFT PORT (2026-06): upstream lharries/whatsapp-mcp switched its login path+# to QR-code ONLY — there is no PairPhone call to anchor on anymore (the old+# PAIR_NEEDLE referenced a `// No ID stored — pairing-code mode (PairPhone)` block+# that no longer exists). However the pinned whatsmeow+# (v0.0.0-20250318233852-06705625cf82) STILL exports Client.PairPhone, so per the+# task's "prefer phone-pair when supported" we RE-INTRODUCE the phone-number+# pairing path into upstream's QR-only block rather than dropping the behaviour.+#+# Two further drifts handled here vs. the old fix:+# • PairPhone lost its leading context.Context parameter. Current signature is+# PairPhone(phone string, showPushNotification bool, clientType PairClientType,+# clientDisplayName string) (string, error)+# so Fix B can no longer pass a context deadline INTO the call. We preserve Fix+# B's INTENT (PairPhone must not hang forever) by running it in a goroutine and+# racing it against a 3-minute watchdog timer — equivalent bounding without the+# removed ctx arg.+# • The needle now matches upstream's real QR-only block (GetQRChannel + the QR+# print loop). When WA_PHONE is set we take the pairing-code path; otherwise we+# fall through to upstream's QR loop unchanged.+PAIR_NEEDLE = """\tif client.Store.ID == nil {+\t\t// No ID stored, this is a new client, need to pair with phone+\t\tqrChan, _ := client.GetQRChannel(context.Background())\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\t// Print QR code for pairing with phone+\t\tfor evt := range qrChan {+\t\t\tif evt.Event == \"code\" {+\t\t\t\tfmt.Println(\"\\nScan this QR code with your WhatsApp app:\")+\t\t\t\tqrterminal.GenerateHalfBlock(evt.Code, qrterminal.L, os.Stdout)+\t\t\t} else if evt.Event == \"success\" {+\t\t\t\tconnected <- true+\t\t\t\tbreak+\t\t\t}+\t\t}"""++PAIR_REPLACEMENT = """\tif client.Store.ID == nil {+\t\t// No ID stored, this is a new client, need to pair with phone.+\t\t// claude-ops Fix A/B: when WA_PHONE is set, prefer phone-number (pairing-code)+\t\t// linking over QR — the bridge runs headless on EC2 where nobody can scan a QR.+\t\t// We still open the QR channel first because whatsmeow requires it (and the+\t\t// godoc says to wait for the first QR event before calling PairPhone).+\t\tqrChan, _ := client.GetQRChannel(context.Background())\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)\")"""+\t\tif phone != \"\" {+\t\t\t// claude-ops Fix A: per whatsmeow PairPhone godoc — wait for the+\t\t\t// websocket+noise handshake to complete before requesting a pair code,+\t\t\t// otherwise PairPhone silently hangs on the IQ response (no PairSuccess,+\t\t\t// no error). Sleeping ~3s after Connect is the godoc-endorsed gate.+\t\t\ttime.Sleep(3 * time.Second)+\t\t\t// claude-ops Fix B: current whatsmeow PairPhone has NO context parameter+\t\t\t// (signature: PairPhone(phone, showPushNotification, clientType,+\t\t\t// clientDisplayName)), so we can no longer pass a deadline into the call.+\t\t\t// Preserve Fix B's intent — an internal PairPhone hang must be recoverable —+\t\t\t// by racing the call against a 3-minute watchdog instead of a ctx deadline.+\t\t\ttype pairResult struct {+\t\t\t\tcode string+\t\t\t\terr error+\t\t\t}+\t\t\tpairCh := make(chan pairResult, 1)+\t\t\tgo func() {+\t\t\t\tc, perr := client.PairPhone(phone, true, whatsmeow.PairClientChrome, \"Chrome (Linux)\")+\t\t\t\tpairCh <- pairResult{code: c, err: perr}+\t\t\t}()+\t\t\tselect {+\t\t\tcase pr := <-pairCh:+\t\t\t\tif pr.err != nil {+\t\t\t\t\tlogger.Errorf(\"Failed to pair phone %s: %v\", phone, pr.err)+\t\t\t\t\treturn+\t\t\t\t}+\t\t\t\tfmt.Printf(\"\\nEnter this pairing code in WhatsApp on %s: %s\\n\", phone, pr.code)+\t\t\tcase <-time.After(3 * time.Minute):+\t\t\t\tlogger.Errorf(\"Timeout requesting pairing code for %s\", phone)+\t\t\t\treturn+\t\t\t}+\t\t\t// Drain the QR channel so the goroutine inside whatsmeow doesn't block;+\t\t\t// the *events.PairSuccess that lands when the user enters the code drives+\t\t\t// the Connected handler. We still watch for the success event below.+\t\t\tgo func() {+\t\t\t\tfor evt := range qrChan {+\t\t\t\t\tif evt.Event == \"success\" {+\t\t\t\t\t\tconnected <- true+\t\t\t\t\t\treturn+\t\t\t\t\t}+\t\t\t\t}+\t\t\t}()+\t\t} else {+\t\t\t// No WA_PHONE — fall back to upstream's QR pairing loop unchanged.+\t\t\tfor evt := range qrChan {+\t\t\t\tif evt.Event == \"code\" {+\t\t\t\t\tfmt.Println(\"\\nScan this QR code with your WhatsApp app:\")+\t\t\t\t\tqrterminal.GenerateHalfBlock(evt.Code, qrterminal.L, os.Stdout)+\t\t\t\t} else if evt.Event == \"success\" {+\t\t\t\t\tconnected <- true+\t\t\t\t\tbreak+\t\t\t\t}+\t\t\t}+\t\t}"""-PAIR_SENTINEL = "per whatsmeow PairPhone godoc"+PAIR_SENTINEL = "claude-ops Fix A/B: when WA_PHONE is set"# ─── main.go: auto-backfill on Connected ─────────────────────────────────────AUTO_BACKFILL_NEEDLE = """\t\tcase *events.Connected:@@ -482,7 +554,10 @@ RESYNC_ENDPOINT_REPLACEMENT = """\t// claude-ops Fix D: POST /api/resync_app_sta\t\t\t\treq.Name = \"regular_low\"\t\t\t}\t\t}-\t\tif err := client.FetchAppState(context.Background(), appstate.WAPatchName(req.Name), req.FullSync, false); err != nil {+\t\t// claude-ops API-drift port (2026-06): current whatsmeow FetchAppState has NO+\t\t// context.Context parameter — signature is FetchAppState(name, fullSync,+\t\t// onlyIfNotSynced). Dropped the leading context.Background() arg.+\t\tif err := client.FetchAppState(appstate.WAPatchName(req.Name), req.FullSync, false); err != nil {\t\t\tw.WriteHeader(http.StatusInternalServerError)\t\t\tfmt.Fprintf(w, `{\"success\":false,\"message\":%q}`, err.Error())\t\t\treturn@@ -1015,7 +1090,9 @@ func healLTHash(ctx context.Context, client *whatsmeow.Client, patchName appstat\t\twdb.Close()\t\t// Re-fetch from version 0 (fullSync=true, onlyIfNotSynced=false).-\t\terr = client.FetchAppState(ctx, patchName, true, false)+\t\t// claude-ops API-drift port (2026-06): FetchAppState dropped its ctx param.+\t\t// (ctx is still used above for the wdb.ExecContext snapshot-row deletes.)+\t\terr = client.FetchAppState(patchName, true, false)\t\tif err == nil {\t\t\treturn nil\t\t}@@ -1040,15 +1117,38 @@ func phoneOnline(client *whatsmeow.Client) bool {\treturn client.IsConnected() && client.IsLoggedIn()}-// claude-ops Fix L: sendRecoveryAndBackfill asks the primary device for a fresh-// app-state snapshot (BuildAppStateRecoveryRequest -> SendPeerMessage) and, now that-// the link is alive, fires a history backfill so the message store stops drifting.-// Returns an error only if the peer-message could not be dispatched; the snapshot-// itself is applied asynchronously by whatsmeow's handleAppStateRecovery when the-// phone answers, so callers that need the applied state must poll/retry.+// claude-ops Fix L: sendRecoveryAndBackfill recovers a corrupt app-state collection+// and fires a history backfill while the link is alive.+//+// API-DRIFT DEGRADE (2026-06): the original implementation asked the PRIMARY device+// for a fresh unencrypted snapshot via whatsmeow.BuildAppStateRecoveryRequest ->+// client.SendPeerMessage, which BYPASSED a broken server patch chain (mismatching+// LTHash, whatsmeow #382/#858). BOTH of those APIs were REMOVED from the public+// whatsmeow surface in the pinned version (v0.0.0-20250318233852-06705625cf82):+// BuildAppStateRecoveryRequest no longer exists, and SendPeerMessage is now only an+// unexported method reachable via client.DangerousInternals(). There is no+// supported public replacement for primary-device peer-recovery in this version.+//+// Closest correct equivalent without reaching into Dangerous internals: a full+// server-side resync (FetchAppState fullSync=true), i.e. the same primitive+// healLTHash already uses. IMPORTANT BEHAVIOUR CHANGE: this can re-fetch and+// re-apply the server's patch chain, but it CANNOT bypass a server chain that is+// itself unverifiable — so a truly fatal #382/#858 corruption is no longer+// auto-recoverable from the bridge on this whatsmeow version. We log that loudly,+// attempt the resync as a best effort, and still fire the backfill. Documented in+// the PR body + CHANGELOG so the owner can decide whether to pin a whatsmeow that+// still exposes peer-recovery or accept resync-only semantics.func sendRecoveryAndBackfill(client *whatsmeow.Client, patchName appstate.WAPatchName) error {-\tmsg := whatsmeow.BuildAppStateRecoveryRequest(patchName)-\tif _, err := client.SendPeerMessage(context.Background(), msg); err != nil {+\tfmt.Printf(+\t\t"Fix L: primary-device app-state recovery (peer-message) is unavailable on this "++\t\t\t"whatsmeow version; falling back to a best-effort full server resync of %s "++\t\t\t"(cannot bypass an unverifiable server patch chain — see whatsmeow #382/#858)\\n",+\t\tstring(patchName),+\t)+\t// Best-effort full server-side resync. Errors are non-fatal here — the caller+\t// (archive auto-retry / recover endpoint) reports its own outcome.+\tif err := client.FetchAppState(patchName, true, false); err != nil {+\t\tfmt.Printf("Fix L: best-effort resync of %s failed: %v\\n", string(patchName), err)\t\treturn err\t}\tgo requestHistorySync(client) // backfill on alive — refresh history while the link is up@@ -1119,7 +1219,11 @@ ARCHIVE_ENDPOINT_REPLACEMENT = """\t// claude-ops Fix F: POST /api/archive — a\t\tctx := r.Context()\t\tdo := func() error {-\t\t\treturn client.SendAppState(ctx, patch)+\t\t\t// claude-ops API-drift port (2026-06): current whatsmeow SendAppState has NO+\t\t\t// context.Context parameter — signature is SendAppState(patch+\t\t\t// appstate.PatchInfo). Dropped the leading ctx arg. (ctx is still used below+\t\t\t// for healLTHash.)+\t\t\treturn client.SendAppState(patch)\t\t}\t\terr = do()\t\t// claude-ops Fix L: treat both a local LTHash mismatch and a server-side 409