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-bridge): add archive endpoint + auto-heal LTHash + persist archive state + stop flap (#408)
Aurora Capitalb866c8458e56
diff --git a/claude-ops/bin/wa-inbox-fresh.sh b/claude-ops/bin/wa-inbox-fresh.shindex 1aaab265..3a54ee81 100755--- a/claude-ops/bin/wa-inbox-fresh.sh+++ b/claude-ops/bin/wa-inbox-fresh.sh@@ -22,14 +22,24 @@ WAIT_TICKS="${WA_FRESH_WAIT_TICKS:-8}" # ×4s ≈ 32s max waitlog() { printf '%s\n' "$*"; }-# 1. bridge up? Liveness = a real TCP/HTTP connection to :8080 (curl exit 7 =-# connection refused). Do NOT use `ss | grep :8080` — ss resolves 8080 to the-# service name "webcache", so the grep never matches and we'd bounce a healthy-# bridge. Only restart when the connection probe genuinely fails twice.-alive() { curl -s -o /dev/null -m 4 "$BRIDGE/" >/dev/null 2>&1; } # exit 0 even on 404; nonzero only if not listening-if ! { alive || { sleep 2; alive; }; }; then- log "wa-fresh: bridge :8080 not responding — restarting…"+# 1. bridge up? Liveness = a real TCP/HTTP connection to :8080.+# curl exit 7 = connection refused (not listening); exit 0 even on 404.+# Do NOT use `ss | grep :8080` — ss renders port 8080 as the service name+# "webcache" so the grep never matches and would bounce a healthy bridge.+#+# Restart gate: only restart when BOTH consecutive probes fail (1s apart).+# Previously the bridge was bounced 4× in 6 min because a single slow probe+# (bridge still starting up) triggered a restart loop. The fix: fail-fast+# probe × 2 with a 1s gap; only then restart; then wait up to 20s for it to+# come back up before declaring dead.+alive() { curl -s -o /dev/null -m 4 "$BRIDGE/" >/dev/null 2>&1; }+probe_dead() { ! alive && { sleep 1; ! alive; }; } # two consecutive failures = truly dead++if probe_dead; then+ log "wa-fresh: bridge :8080 not responding (2 consecutive probes failed) — restarting…"systemctl --user restart whatsapp-bridge.service 2>/dev/null+ # Wait up to 20 s for the bridge to come back (it needs a few seconds to+ # open the SQLite store and establish the WhatsApp websocket).for i in $(seq 1 10); do sleep 2; alive && break; donefiif ! alive; thendiff --git a/claude-ops/scripts/whatsapp/apply-patches.py b/claude-ops/scripts/whatsapp/apply-patches.pyindex 369b8d0c..b33fea80 100755--- a/claude-ops/scripts/whatsapp/apply-patches.py+++ b/claude-ops/scripts/whatsapp/apply-patches.py@@ -29,6 +29,20 @@ Patches included:(single source of truth). Fixes the 30+ pydantic validation errors onlist_chats, list_messages, search_contacts, get_chat, get_contact_chats,get_direct_chat_by_contact, get_last_interaction, get_message_context.+ Fix F — POST /api/archive endpoint: implement archive/unarchive via+ whatsmeow's appstate.BuildArchive + client.SendAppState. Body:+ {"chat_jid":"...","archive":true}. On LTHash mismatch, auto-heals+ by clearing the stale patch rows and retrying once (Fix G below).+ Fix G — Auto-heal LTHash corruption: when any app-state op returns an error+ wrapping appstate.ErrMismatchingLTHash, delete the stale version/MAC+ rows for that patch name from whatsapp.db and re-request a full_sync+ from version 0 (max 2 attempts, never loops). Identity/session/+ pre_key tables are never touched.+ Fix H — Persist archive state: idempotent ALTER TABLE to add an `archived`+ INTEGER NOT NULL DEFAULT 0 column to the chats table in messages.db.+ Subscribes to *events.Archive and UPSERT-updates the flag. Makes+ inbox = WHERE archived=0 directly queryable without hitting the+ bridge's app-state layer on every scan.Every patch is gated on a sentinel string so re-running is a no-op.@@ -560,6 +574,228 @@ def get_sender_name(sender_jid: str) -> str:"""PY_SHAPE_SENTINEL = "claude-ops Fix E: serialization helpers + WAL-mode DB open"+# ─── main.go Fix H: idempotent chats.archived migration + SetArchived helper ──+# The chats table only has (jid, name, last_message_time). Without an `archived`+# column the ops-inbox skill can't query "inbox = non-archived" without a live+# app-state round-trip. This patch:+# 1. adds an idempotent ALTER TABLE in NewMessageStore (guarded by PRAGMA table_info)+# 2. adds a SetArchivedStatus(*sql.DB, jid, bool) helper used by Fix F+# 3. subscribes to *events.Archive inside the event handler to keep the flag current+# The archived column migration is spliced in just before `return &MessageStore{db: db}, nil`.+CHATS_SCHEMA_MIGRATION_NEEDLE = """\treturn &MessageStore{db: db}, nil+}"""++CHATS_SCHEMA_MIGRATION_REPLACEMENT = """\t// claude-ops Fix H: idempotent migration — add `archived` column if absent.+\t// Uses PRAGMA table_info so it is safe to run on every startup against an+\t// existing DB that was created before this patch (ALTER TABLE fails if the+\t// column already exists; the PRAGMA guard prevents that).+\tvar colExists int+\t_ = db.QueryRow(+\t\t`SELECT COUNT(*) FROM pragma_table_info('chats') WHERE name='archived'`,+\t).Scan(&colExists)+\tif colExists == 0 {+\t\tif _, err := db.Exec(`ALTER TABLE chats ADD COLUMN archived INTEGER NOT NULL DEFAULT 0`); err != nil {+\t\t\tdb.Close()+\t\t\treturn nil, fmt.Errorf("failed to add archived column: %v", err)+\t\t}+\t}++\treturn &MessageStore{db: db}, nil+}++// SetArchivedStatus persists the WhatsApp archive flag for a chat into messages.db.+// Called by the /api/archive handler (Fix F) and the *events.Archive subscriber (Fix H).+// claude-ops Fix H.+func (store *MessageStore) SetArchivedStatus(jid string, archived bool) error {+\tarchVal := 0+\tif archived {+\t\tarchVal = 1+\t}+\t_, err := store.db.Exec(+\t\t`INSERT INTO chats (jid, archived) VALUES (?, ?)+\t\t ON CONFLICT(jid) DO UPDATE SET archived=excluded.archived`,+\t\tjid, archVal,+\t)+\treturn err+}"""++CHATS_SCHEMA_MIGRATION_SENTINEL = "claude-ops Fix H: idempotent migration"++# ─── main.go Fix H: subscribe to *events.Archive in the event handler ──────+# Keeps messages.db.chats.archived in sync when WhatsApp pushes app-state+# archive mutations from another device (phone or Web).+ARCHIVE_EVENT_NEEDLE = """\t\tcase *events.LoggedOut:+\t\t\tlogger.Warnf(\"Device logged out, re-pair via WhatsApp app\")+\t\t}+\t})"""++ARCHIVE_EVENT_REPLACEMENT = """\t\tcase *events.Archive:+\t\t\t// claude-ops Fix H: mirror app-state archive changes into messages.db so+\t\t\t// the inbox query (WHERE archived=0) stays accurate without a live+\t\t\t// app-state round-trip.+\t\t\tif err := messageStore.SetArchivedStatus(v.JID.String(), v.Action.GetArchived()); err != nil {+\t\t\t\tlogger.Warnf("Fix H: failed to persist archive status for %s: %v", v.JID, err)+\t\t\t}++\t\tcase *events.LoggedOut:+\t\t\tlogger.Warnf(\"Device logged out, re-pair via WhatsApp app\")+\t\t}+\t})"""++ARCHIVE_EVENT_SENTINEL = "claude-ops Fix H: mirror app-state archive changes"++# ─── main.go Fix G: healLTHash helper ────────────────────────────────────────+# When whatsmeow returns an error wrapping ErrMismatchingLTHash it means the+# local app-state snapshot is corrupt/stale. The only safe recovery is:+# 1. delete the stale version+MAC rows for that patch name from whatsapp.db+# (DO NOT touch sync_keys, identity, or session tables — those force re-pair)+# 2. call FetchAppState with fullSync=true, version 0 to re-download from server+# This is injected as a standalone helper right before startRESTServer.+HEAL_LTHASH_NEEDLE = """// Start a REST API server to expose the WhatsApp client functionality+func startRESTServer(client *whatsmeow.Client, messageStore *MessageStore, port int) {"""++HEAL_LTHASH_REPLACEMENT = """// healLTHash recovers from an ErrMismatchingLTHash app-state corruption by+// deleting the stale snapshot rows for patchName from whatsapp.db and triggering+// a fresh full_sync from version 0. Returns nil when the resync succeeds or the+// error is not an LTHash mismatch (caller should not retry in that case).+//+// SAFE: only whatsmeow_app_state_version and whatsmeow_app_state_mutation_macs+// rows for the named patch are deleted. sync_keys, identity, sessions, pre_keys,+// and sender_keys are never touched — deleting those forces a re-pair.+//+// claude-ops Fix G.+func healLTHash(ctx context.Context, client *whatsmeow.Client, patchName appstate.WAPatchName) error {+\tconst maxAttempts = 2+\tfor attempt := 1; attempt <= maxAttempts; attempt++ {+\t\t// Open whatsapp.db directly to wipe the stale snapshot rows.+\t\twdb, err := sql.Open("sqlite3", "file:store/whatsapp.db?_foreign_keys=on")+\t\tif err != nil {+\t\t\treturn fmt.Errorf("healLTHash: open whatsapp.db: %w", err)+\t\t}+\t\tjid := ""+\t\tif client.Store != nil && client.Store.ID != nil {+\t\t\tjid = client.Store.ID.String()+\t\t}+\t\t_, _ = wdb.ExecContext(ctx,+\t\t\t`DELETE FROM whatsmeow_app_state_version WHERE jid=? AND name=?`, jid, string(patchName))+\t\t_, _ = wdb.ExecContext(ctx,+\t\t\t`DELETE FROM whatsmeow_app_state_mutation_macs WHERE jid=? AND name=?`, jid, string(patchName))+\t\twdb.Close()++\t\t// Re-fetch from version 0 (fullSync=true, onlyIfNotSynced=false).+\t\terr = client.FetchAppState(ctx, patchName, true, false)+\t\tif err == nil {+\t\t\treturn nil+\t\t}+\t\t// Only retry on another LTHash mismatch; any other error is permanent.+\t\tif !strings.Contains(err.Error(), "mismatching LTHash") {+\t\t\treturn err+\t\t}+\t\tif attempt < maxAttempts {+\t\t\ttime.Sleep(2 * time.Second)+\t\t}+\t}+\treturn fmt.Errorf("healLTHash: still failing after %d attempts", maxAttempts)+}++// Start a REST API server to expose the WhatsApp client functionality+func startRESTServer(client *whatsmeow.Client, messageStore *MessageStore, port int) {"""++HEAL_LTHASH_SENTINEL = "claude-ops Fix G."++# ─── main.go Fix F: POST /api/archive endpoint ───────────────────────────────+# Inserts the /api/archive handler just before the "Run server in goroutine" block.+# Uses whatsmeow appstate.BuildArchive + client.SendAppState (the correct path for+# companion-device archive mutations — not FetchAppState, which is read-only).+# On LTHash mismatch, calls healLTHash then retries once.+# Also UPSERTs the archived flag into messages.db via messageStore.SetArchivedStatus.+ARCHIVE_ENDPOINT_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}()+}"""++ARCHIVE_ENDPOINT_REPLACEMENT = """\t// claude-ops Fix F: POST /api/archive — archive or unarchive a chat.+\t// Body: {"chat_jid":"<JID>","archive":true}+\t// Uses whatsmeow's appstate.BuildArchive + client.SendAppState which is the+\t// correct companion-device path. On LTHash mismatch, auto-heals via Fix G+\t// and retries once so callers never need to manually resync first.+\thttp.HandleFunc(\"/api/archive\", 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,"message":"client not connected"}`)+\t\t\treturn+\t\t}+\t\tvar req struct {+\t\t\tChatJID string `json:"chat_jid"`+\t\t\tArchive bool `json:"archive"`+\t\t}+\t\tif err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.ChatJID == "" {+\t\t\tw.WriteHeader(http.StatusBadRequest)+\t\t\tfmt.Fprintln(w, `{"success":false,"message":"chat_jid required"}`)+\t\t\treturn+\t\t}+\t\ttargetJID, err := types.ParseJID(req.ChatJID)+\t\tif err != nil {+\t\t\tw.WriteHeader(http.StatusBadRequest)+\t\t\tfmt.Fprintf(w, `{"success":false,"message":"invalid chat_jid: %s"}`, err.Error())+\t\t\treturn+\t\t}++\t\t// Look up the last message timestamp for this chat so WhatsApp clients+\t\t// display the archive state correctly in the chat list.+\t\tvar lastMsgTime time.Time+\t\t_ = messageStore.db.QueryRow(+\t\t\t`SELECT timestamp FROM messages WHERE chat_jid=? ORDER BY timestamp DESC LIMIT 1`,+\t\t\treq.ChatJID,+\t\t).Scan(&lastMsgTime)++\t\tpatch := appstate.BuildArchive(targetJID, req.Archive, lastMsgTime, nil)+\t\tctx := r.Context()++\t\tdo := func() error {+\t\t\treturn client.SendAppState(ctx, patch)+\t\t}+\t\terr = do()+\t\tif err != nil && strings.Contains(err.Error(), "mismatching LTHash") {+\t\t\t// Auto-heal the stale snapshot then retry once (Fix G).+\t\t\tif healErr := healLTHash(ctx, client, appstate.WAPatchRegularLow); healErr != nil {+\t\t\t\tw.WriteHeader(http.StatusConflict)+\t\t\t\tfmt.Fprintf(w, `{"success":false,"message":"LTHash heal failed: %s"}`, healErr.Error())+\t\t\t\treturn+\t\t\t}+\t\t\terr = do()+\t\t}+\t\tif err != nil {+\t\t\tw.WriteHeader(http.StatusInternalServerError)+\t\t\tfmt.Fprintf(w, `{"success":false,"message":%q}`, err.Error())+\t\t\treturn+\t\t}++\t\t// Persist the flag locally so the inbox query is immediately consistent.+\t\t_ = messageStore.SetArchivedStatus(req.ChatJID, req.Archive)++\t\tfmt.Fprintf(w, `{"success":true,"message":"chat %s archived=%v"}`, req.ChatJID, req.Archive)+\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}()+}"""++ARCHIVE_ENDPOINT_SENTINEL = "claude-ops Fix F: POST /api/archive"++def replace_idempotent(p: pathlib.Path, needle: str, replacement: str, sentinel: str, label: str) -> bool:@@ -674,6 +910,34 @@ def main() -> int:RESYNC_ENDPOINT_SENTINEL,"Fix D: POST /api/resync_app_state endpoint",)+ changed_go |= replace_idempotent(+ main_go,+ CHATS_SCHEMA_MIGRATION_NEEDLE,+ CHATS_SCHEMA_MIGRATION_REPLACEMENT,+ CHATS_SCHEMA_MIGRATION_SENTINEL,+ "Fix H: chats.archived column migration + SetArchivedStatus helper",+ )+ changed_go |= replace_idempotent(+ main_go,+ ARCHIVE_EVENT_NEEDLE,+ ARCHIVE_EVENT_REPLACEMENT,+ ARCHIVE_EVENT_SENTINEL,+ "Fix H: subscribe *events.Archive to persist archive flag",+ )+ changed_go |= replace_idempotent(+ main_go,+ HEAL_LTHASH_NEEDLE,+ HEAL_LTHASH_REPLACEMENT,+ HEAL_LTHASH_SENTINEL,+ "Fix G: healLTHash auto-recovery helper",+ )+ changed_go |= replace_idempotent(+ main_go,+ ARCHIVE_ENDPOINT_NEEDLE,+ ARCHIVE_ENDPOINT_REPLACEMENT,+ ARCHIVE_ENDPOINT_SENTINEL,+ "Fix F: POST /api/archive endpoint",+ )print(" whatsapp.py:")changed_py = replace_idempotent(diff --git a/claude-ops/scripts/whatsapp/systemd/whatsapp-bridge.service.template b/claude-ops/scripts/whatsapp/systemd/whatsapp-bridge.service.templateindex d6e0fd60..576729c3 100644--- a/claude-ops/scripts/whatsapp/systemd/whatsapp-bridge.service.template+++ b/claude-ops/scripts/whatsapp/systemd/whatsapp-bridge.service.template@@ -10,8 +10,10 @@ WorkingDirectory=%h/.local/share/whatsapp-mcp/whatsapp-bridgeExecStart=%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+# always restart: WhatsApp never backfills phone-sent messages from offline periods,+# so maximum uptime = minimum send gaps. on-failure was too conservative.+Restart=always+RestartSec=10sStandardOutput=journalStandardError=journalSyslogIdentifier=whatsapp-bridgediff --git a/claude-ops/skills/ops-inbox/SKILL.md b/claude-ops/skills/ops-inbox/SKILL.mdindex 52ea02ca..4d17c690 100644--- a/claude-ops/skills/ops-inbox/SKILL.md+++ b/claude-ops/skills/ops-inbox/SKILL.md@@ -206,13 +206,24 @@ This clones lharries/whatsapp-mcp into `~/.local/share/whatsapp-mcp`, applies th**Bulk archive non-actionable WA chats** — for newsletters, dead group chats, one-word reactions, etc.:```bash+DB="${WHATSAPP_BRIDGE_DB:-$HOME/.local/share/whatsapp-mcp/whatsapp-bridge/store/messages.db}"for jid in "<NEWSLETTER_JID>@newsletter" "<GROUP_JID>@g.us" "<CONTACT_PHONE>@s.whatsapp.net"; docurl -s -X POST http://localhost:8080/api/archive \-H 'Content-Type: application/json' \-d "{\"chat_jid\":\"$jid\",\"archive\":true}"done+# The /api/archive endpoint auto-heals LTHash corruption internally (Fix G) and+# immediately UPSERTs archived=1 into messages.db so the inbox query reflects it.+# If you still get HTTP 409, the heal failed — run resync manually as a last resort:+# curl -s -X POST http://localhost:8080/api/resync_app_state -d '{"name":"regular_low","full_sync":true}'+```+**Archive state is locally queryable** (Fix H — bridge persists `archived` flag in `chats` table):+```bash+# Inbox = all non-archived chats:+sqlite3 "$DB" "SELECT jid, name, last_message_time FROM chats WHERE archived=0 ORDER BY last_message_time DESC;"+# Confirm a specific chat was archived:+sqlite3 "$DB" "SELECT jid, archived FROM chats WHERE jid='<JID>';"```-If you get `409 conflict / LTHash mismatch`, run resync first: `curl -s -X POST http://localhost:8080/api/resync_app_state -d '{"name":"regular_low","full_sync":true}'`.**Full-text search** — use `mcp__whatsapp__list_messages` with a `query` param (backed by FTS5 after running `scripts/whatsapp-bridge-migrate.sh`):```bash@@ -554,8 +565,17 @@ The per-channel classify/draft steps below (WhatsApp, iMessage, email) all refer### WhatsApp (FULL SCAN + DEEP CONTEXT)**Phase 1 — Classify:**-1. Get all chats: `mcp__whatsapp__list_chats` with `{sort_by: "last_active"}`-2. Filter to chats with `last_message_time` in the last 7 days+1. Get all **non-archived** chats. The bridge now persists archive state locally (Fix H), so the inbox working set is chats where `archived=0`:+ ```bash+ DB="${WHATSAPP_BRIDGE_DB:-$HOME/.local/share/whatsapp-mcp/whatsapp-bridge/store/messages.db}"+ # Paginate: fetch all non-archived chats ordered by last activity.+ # Do NOT hard-truncate to 7 days — archived chats are excluded by the column,+ # so this returns the full real inbox regardless of age.+ sqlite3 "$DB" "SELECT jid, name, last_message_time FROM chats WHERE archived=0 ORDER BY last_message_time DESC;"+ ```+ When the MCP tool is used instead (`mcp__whatsapp__list_chats {sort_by:"last_active"}`), filter client-side by `archived != 1` on the returned objects. The MCP server exposes the `archived` field from the `chats` table once the column exists.++ **7-day recency is a secondary signal, not a hard cutoff.** Apply it to deprioritise very old non-archived chats when there are many, but never use it to silently drop chats from the working set — an unanswered message from 10 days ago is still actionable.**TIME_AGO — `last_message_time` is an RFC3339 string with timezone offset** (e.g. `"2026-05-24T14:55:06+02:00"`), NOT a unix epoch integer. Parse with full TZ awareness:```python@@ -582,7 +602,7 @@ The per-channel classify/draft steps below (WhatsApp, iMessage, email) all refer6. Assign provisional buckets only (same direction signals as step 4 — use `last_is_from_me` on the chat object; only after the step 5 thread fallback use the last element's `is_from_me`). **Do not confirm NEEDS REPLY here** — step 7 clears the FULL-THREAD AWARENESS GATE first:- **NEEDS REPLY candidate**: `last_is_from_me == 0`, or (fallback only) last thread message `is_from_me: false`- **WAITING** (provisional): `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.+ - **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. The bridge's `/api/archive` endpoint (Fix F) auto-heals LTHash corruption internally and retries once — you no longer need to manually run `resync_app_state` first. If it still returns `409 conflict`, run `mcp__whatsapp__resync_app_state {name: "regular_low", full_sync: true}` as a fallback 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`, call `mcp__whatsapp__list_messages {chat_jid, limit: 25}` and scan ALL of them (capturing `is_from_me=1` rows and `[voice]` transcripts) for `is_from_me: true` after the inbound message — if one exists, reclassify as WAITING. This is part of clearing the FULL-THREAD AWARENESS GATE, not an optional extra.