Skip to content

Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.

fix(daemon): read WA state from bridge DB; auto-fire migrations on update (v2.0.3) (#177)

Aurora Capital7962101a519a
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index acfc924d..ab3e348b 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -11,7 +11,7 @@
"name": "ops",
"description": "Business operations command center for Claude Code \u2014 30 skills, 14 agents, smart background daemon. Manage communications (WhatsApp/Email/Slack/Telegram), projects, infrastructure (AWS), revenue (Stripe+RevenueCat), e-commerce, marketing, monitoring (Datadog/New Relic/OTEL), and voice. Includes /gtm go-to-market planner, /ops:projects portfolio dashboard, and YOLO autonomous mode with 4 parallel C-suite agents.",
"source": "./claude-ops",
- "version": "2.0.2",
+ "version": "2.0.3",
"category": "productivity",
"keywords": [
"ops",
@@ -38,4 +38,4 @@
]
}
]
-}
+}
\ No newline at end of file
diff --git a/claude-ops/.claude-plugin/plugin.json b/claude-ops/.claude-plugin/plugin.json
index 67654479..45fa4e71 100644
--- a/claude-ops/.claude-plugin/plugin.json
+++ b/claude-ops/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "ops",
- "version": "2.0.2",
+ "version": "2.0.3",
"description": "Business operations command center for Claude Code \u2014 30 skills, 14 agents, and a smart background daemon that manage communications (WhatsApp/Email/Slack/Telegram), projects, infrastructure (all AWS services), revenue (Stripe + RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4/GSC), monitoring (Datadog/New Relic/OTEL), and voice (Bland AI/ElevenLabs/Whisper). Includes /gtm go-to-market planner, /ops:projects portfolio dashboard, and YOLO mode for autonomous operation with 4 parallel C-suite agents.",
"author": {
"name": "Lifecycle Innovations Limited",
@@ -575,4 +575,4 @@
"default": ""
}
}
-}
+}
\ No newline at end of file
diff --git a/claude-ops/CHANGELOG.md b/claude-ops/CHANGELOG.md
index 9b7595a7..099f9409 100644
--- a/claude-ops/CHANGELOG.md
+++ b/claude-ops/CHANGELOG.md
@@ -2,6 +2,16 @@
All notable changes to this project will be documented in this file.
+## [2.0.3] — 2026-04-30
+
+### Fixed
+
+- **Daemon: WhatsApp state now reads from Baileys bridge `messages.db` directly.** Removed last 4 references to deprecated `wacli_chats.json` / `wacli_urgent.json` keepalive caches in `scripts/ops-daemon.sh` (briefing refresh, urgent-message detection, smart memory trigger, contact activity index). Briefings no longer surface false "WhatsApp disconnected" warnings when the bridge is healthy.
+
+### Added
+
+- **`bin/ops-post-update-migrate`: auto-fire migrations on plugin update.** Wired into `hooks/hooks.json` SessionStart and `scripts/ops-daemon-manager.sh ensure-current`. Idempotent, gated by per-version sentinel (`$DATA_DIR/.migrated/v<VERSION>`), wall-clock budget 60s. Currently runs: `whatsapp-bridge-migrate.sh` (FTS5 + contacts), refreshes `com.claude-ops.whatsapp-bridge` LaunchAgent, decommissions stale `com.claude-ops.wacli-keepalive` plist. Future migrations chain into `run_migrations()`.
+
## [Unreleased] — 2026-04-27
### Changed
diff --git a/claude-ops/bin/ops-post-update-migrate b/claude-ops/bin/ops-post-update-migrate
new file mode 100755
index 00000000..79b5384c
--- /dev/null
+++ b/claude-ops/bin/ops-post-update-migrate
@@ -0,0 +1,89 @@
+#!/usr/bin/env bash
+# ops-post-update-migrate — auto-fire idempotent migrations after plugin install/update.
+#
+# Runs ONCE per plugin version (sentinel: $DATA_DIR/.migrated/v<VERSION>).
+# Wired from hooks/hooks.json (SessionStart) and scripts/ops-daemon-manager.sh.
+#
+# Add new migrations to the run_migrations() function below — they MUST be
+# idempotent so a re-run is a no-op.
+
+set -euo pipefail
+
+PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
+DATA_DIR="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"
+PLUGIN_JSON="$PLUGIN_ROOT/.claude-plugin/plugin.json"
+
+[[ -f "$PLUGIN_JSON" ]] || exit 0
+
+VERSION=$(python3 -c "import json,sys; print(json.load(open('$PLUGIN_JSON'))['version'])" 2>/dev/null || echo "unknown")
+SENTINEL_DIR="$DATA_DIR/.migrated"
+SENTINEL="$SENTINEL_DIR/v${VERSION}"
+
+# Already migrated this version → exit fast (SessionStart hook fires every session)
+[[ -f "$SENTINEL" ]] && exit 0
+
+mkdir -p "$SENTINEL_DIR" 2>/dev/null || true
+LOG="$DATA_DIR/post-update-migrate.log"
+mkdir -p "$DATA_DIR" 2>/dev/null || true
+
+log() { printf "[%s] %s\n" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >> "$LOG"; }
+
+run_migrations() {
+ log "post-update-migrate START version=$VERSION plugin_root=$PLUGIN_ROOT"
+
+ # 1. WhatsApp bridge: FTS5 + contacts table (idempotent — script self-checks)
+ local wa_migrate="$PLUGIN_ROOT/scripts/whatsapp-bridge-migrate.sh"
+ if [[ -x "$wa_migrate" ]]; then
+ if bash "$wa_migrate" >> "$LOG" 2>&1; then
+ log " ok: whatsapp-bridge-migrate"
+ else
+ log " warn: whatsapp-bridge-migrate exit=$? (non-fatal)"
+ fi
+ fi
+
+ # 2. Refresh whatsapp-bridge LaunchAgent (idempotent — only writes if template changed)
+ if [[ "$(uname -s)" == "Darwin" ]]; then
+ local plist_src="$PLUGIN_ROOT/scripts/assets/launchagents/com.claude-ops.whatsapp-bridge.plist"
+ local plist_dst="$HOME/Library/LaunchAgents/com.claude-ops.whatsapp-bridge.plist"
+ if [[ -f "$plist_src" ]] && [[ ! -f "$plist_dst" || "$plist_src" -nt "$plist_dst" ]]; then
+ mkdir -p "$HOME/Library/LaunchAgents" 2>/dev/null || true
+ local bridge_dir="${WHATSAPP_BRIDGE_HOME:-$HOME/.local/share/whatsapp-mcp/whatsapp-bridge}"
+ sed -e "s#__BRIDGE_BINARY_PATH__#$bridge_dir/whatsapp-bridge#g" \
+ -e "s#__BRIDGE_WORKING_DIR__#$bridge_dir#g" \
+ "$plist_src" > "$plist_dst" 2>/dev/null && {
+ launchctl unload "$plist_dst" 2>/dev/null || true
+ launchctl load "$plist_dst" 2>/dev/null || true
+ log " ok: whatsapp-bridge LaunchAgent refreshed"
+ }
+ fi
+ fi
+
+ # 3. Decommission deprecated wacli-keepalive plist (idempotent)
+ if [[ "$(uname -s)" == "Darwin" ]]; then
+ local stale_plist="$HOME/Library/LaunchAgents/com.claude-ops.wacli-keepalive.plist"
+ if [[ -f "$stale_plist" ]]; then
+ launchctl unload "$stale_plist" 2>/dev/null || true
+ rm -f "$stale_plist" 2>/dev/null || true
+ log " ok: removed deprecated wacli-keepalive LaunchAgent"
+ fi
+ fi
+
+ # 4. Add future migrations here. Pattern:
+ # if needs_migration; then
+ # run_idempotent_migration && log " ok: <name>"
+ # fi
+
+ log "post-update-migrate DONE version=$VERSION"
+}
+
+# Run with a 60s wall-clock budget so a SessionStart hook never blocks Claude.
+( run_migrations ) &
+MIGRATE_PID=$!
+( sleep 60; kill -0 "$MIGRATE_PID" 2>/dev/null && kill "$MIGRATE_PID" 2>/dev/null ) &
+
+wait "$MIGRATE_PID" 2>/dev/null || true
+
+# Stamp sentinel even on partial failure — individual migrations log their own state.
+# Re-run forced by deleting the sentinel or bumping plugin.json version.
+touch "$SENTINEL"
+exit 0
diff --git a/claude-ops/hooks/hooks.json b/claude-ops/hooks/hooks.json
index 71daf689..98f29af2 100644
--- a/claude-ops/hooks/hooks.json
+++ b/claude-ops/hooks/hooks.json
@@ -14,6 +14,10 @@
{
"type": "command",
"command": "bash ${CLAUDE_PLUGIN_ROOT}/scripts/ops-daemon-manager.sh ensure-current --plugin-root ${CLAUDE_PLUGIN_ROOT} 2>/dev/null || true"
+ },
+ {
+ "type": "command",
+ "command": "CLAUDE_PLUGIN_ROOT=${CLAUDE_PLUGIN_ROOT} bash ${CLAUDE_PLUGIN_ROOT}/bin/ops-post-update-migrate 2>/dev/null || true"
}
]
}
diff --git a/claude-ops/scripts/ops-daemon-manager.sh b/claude-ops/scripts/ops-daemon-manager.sh
index 22fe46a5..e728d161 100755
--- a/claude-ops/scripts/ops-daemon-manager.sh
+++ b/claude-ops/scripts/ops-daemon-manager.sh
@@ -290,6 +290,13 @@ cmd_upgrade() {
}
cmd_ensure_current() {
+ # Always run post-update migrations FIRST (idempotent — sentinel-gated per-version).
+ # This catches version bumps even when the daemon plist itself didn't change.
+ local migrate_bin="$PLUGIN_ROOT/bin/ops-post-update-migrate"
+ if [[ -x "$migrate_bin" ]]; then
+ CLAUDE_PLUGIN_ROOT="$PLUGIN_ROOT" bash "$migrate_bin" 2>/dev/null || true
+ fi
+
[[ "$OS" == "macos" ]] || exit 0
[[ -n "$PLUGIN_ROOT" ]] && [[ -d "$PLUGIN_ROOT/scripts" ]] || exit 0
[[ -f "$PLIST_DEST" ]] || exit 0
diff --git a/claude-ops/scripts/ops-daemon.sh b/claude-ops/scripts/ops-daemon.sh
index d1666a7c..e582bca9 100755
--- a/claude-ops/scripts/ops-daemon.sh
+++ b/claude-ops/scripts/ops-daemon.sh
@@ -538,15 +538,20 @@ prefetch_briefing_cache() {
tmpdir=$(mktemp -d)
local -a _refresh_pids=()
- # Unread counts — read from keepalive cache to avoid store-lock contention
- local wacli_cache="$DATA_DIR/cache/wacli_chats.json"
- (if [[ -f "$wacli_cache" ]]; then
+ # Unread counts — read directly from Baileys bridge messages.db (wacli decommissioned)
+ local bridge_db="${WHATSAPP_BRIDGE_DB:-$HOME/.local/share/whatsapp-mcp/whatsapp-bridge/store/messages.db}"
+ (if [[ -f "$bridge_db" ]]; then
python3 -c "
-import json,datetime
-data=json.load(open('$wacli_cache')).get('data',[]) or []
-cutoff=(datetime.datetime.now(datetime.timezone.utc)-datetime.timedelta(days=7)).isoformat()
-recent=[c for c in data if c.get('LastMessageTS','')>cutoff]
-print(json.dumps({'total_chats':len(recent),'count':len(data)}))
+import json, sqlite3
+try:
+ con = sqlite3.connect('file:$bridge_db?mode=ro', uri=True, timeout=2)
+ cur = con.cursor()
+ recent = cur.execute(\"SELECT COUNT(DISTINCT chat_jid) FROM messages WHERE timestamp >= datetime('now','-7 days')\").fetchone()[0]
+ total = cur.execute('SELECT COUNT(*) FROM chats').fetchone()[0]
+ print(json.dumps({'total_chats': recent, 'count': total}))
+ con.close()
+except Exception:
+ print(json.dumps({'total_chats': 0, 'count': 0}))
" > "$tmpdir/wa.json" 2>/dev/null
fi) &
_refresh_pids+=($!)
@@ -608,18 +613,32 @@ detect_urgent_messages() {
if (( now - last < 300 )); then return 0; fi
fi
- # Check WhatsApp urgent messages — read from keepalive cache (no store-lock contention)
- local urgent_cache="$DATA_DIR/cache/wacli_urgent.json"
- if [[ -f "$urgent_cache" ]]; then
+ # Check WhatsApp urgent messages — read directly from Baileys bridge messages.db
+ local bridge_db="${WHATSAPP_BRIDGE_DB:-$HOME/.local/share/whatsapp-mcp/whatsapp-bridge/store/messages.db}"
+ if [[ -f "$bridge_db" ]]; then
python3 -c "
-import json,datetime
-data=json.load(open('$urgent_cache'))
-msgs=data.get('data',{}).get('messages',[]) or []
-cutoff=(datetime.datetime.now(datetime.timezone.utc)-datetime.timedelta(hours=4)).isoformat()
-urgent=[m for m in msgs if m.get('Timestamp','')>cutoff and not m.get('FromMe',True)]
-if urgent:
- with open('$URGENT_FILE','w') as f:
- json.dump({'urgent_count':len(urgent),'messages':[{'from':m.get('ChatName',''),'text':m.get('Text','')[:100],'ts':m.get('Timestamp','')} for m in urgent[:5]]},f,indent=2)
+import json, sqlite3
+try:
+ con = sqlite3.connect('file:$bridge_db?mode=ro', uri=True, timeout=2)
+ cur = con.cursor()
+ rows = cur.execute('''
+ SELECT m.chat_jid, COALESCE(c.name, m.chat_jid) AS chat_name, m.content, m.timestamp
+ FROM messages m
+ LEFT JOIN chats c ON c.jid = m.chat_jid
+ WHERE m.is_from_me = 0
+ AND m.timestamp >= datetime('now','-4 hours')
+ ORDER BY m.timestamp DESC
+ LIMIT 5
+ ''').fetchall()
+ if rows:
+ with open('$URGENT_FILE','w') as f:
+ json.dump({
+ 'urgent_count': len(rows),
+ 'messages': [{'from': r[1], 'text': (r[2] or '')[:100], 'ts': r[3]} for r in rows]
+ }, f, indent=2)
+ con.close()
+except Exception:
+ pass
" 2>/dev/null || true
fi
@@ -652,16 +671,24 @@ try:
except: print('')
" 2>/dev/null)
- # Read from keepalive cache to check for new messages (no store-lock contention)
- local wacli_chats_cache="$DATA_DIR/cache/wacli_chats.json"
- if [[ -f "$wacli_chats_cache" ]]; then
+ # Read from Baileys bridge messages.db to check for new messages (wacli decommissioned)
+ local bridge_db="${WHATSAPP_BRIDGE_DB:-$HOME/.local/share/whatsapp-mcp/whatsapp-bridge/store/messages.db}"
+ if [[ -f "$bridge_db" ]]; then
local new_count
new_count=$(python3 -c "
-import json,datetime
-data=json.load(open('$wacli_chats_cache')).get('data',[]) or []
-last='${last_ts:-}'
-recent=[c for c in data if c.get('LastMessageTS','')>last] if last else data[:5]
-print(len(recent))
+import sqlite3
+try:
+ con = sqlite3.connect('file:$bridge_db?mode=ro', uri=True, timeout=2)
+ cur = con.cursor()
+ last = '${last_ts:-}'
+ if last:
+ n = cur.execute('SELECT COUNT(DISTINCT chat_jid) FROM messages WHERE timestamp > ?', (last,)).fetchone()[0]
+ else:
+ n = cur.execute(\"SELECT COUNT(DISTINCT chat_jid) FROM messages WHERE timestamp >= datetime('now','-1 day')\").fetchone()[0]
+ print(n)
+ con.close()
+except Exception:
+ print(0)
" 2>/dev/null || echo 0)
if [[ "$new_count" -gt 3 ]] && [[ -f "$MEM_SCRIPT" ]]; then
@@ -708,21 +735,26 @@ import json, subprocess, sys, datetime, os, collections
data_dir = sys.argv[1]
contacts = collections.defaultdict(lambda: {"channels": [], "last_seen": "", "msg_count": 0, "needs_reply": False})
-# WhatsApp contacts — read from keepalive cache (no store-lock contention)
+# WhatsApp contacts — read directly from Baileys bridge messages.db (wacli decommissioned)
try:
- cache_path = os.path.join(data_dir, "cache", "wacli_chats.json")
- if os.path.exists(cache_path):
- wa = json.load(open(cache_path))
- else:
- wa = {"data": []}
- cutoff = (datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=7)).isoformat()
- for chat in (wa.get("data") or []):
- if chat.get("LastMessageTS", "") < cutoff: continue
- name = chat.get("Name", "Unknown")
- contacts[name]["channels"].append("whatsapp")
- contacts[name]["last_seen"] = max(contacts[name]["last_seen"], chat.get("LastMessageTS", ""))
- contacts[name]["jid"] = chat.get("JID", "")
-except: pass
+ import sqlite3
+ bridge_db = os.environ.get("WHATSAPP_BRIDGE_DB",
+ os.path.expanduser("~/.local/share/whatsapp-mcp/whatsapp-bridge/store/messages.db"))
+ if os.path.exists(bridge_db):
+ con = sqlite3.connect(f"file:{bridge_db}?mode=ro", uri=True, timeout=2)
+ cur = con.cursor()
+ rows = cur.execute("""
+ SELECT COALESCE(c.name, c.jid) AS name, c.jid, c.last_message_time
+ FROM chats c
+ WHERE c.last_message_time >= datetime('now','-7 days')
+ """).fetchall()
+ for name, jid, last_seen in rows:
+ name = name or "Unknown"
+ contacts[name]["channels"].append("whatsapp")
+ contacts[name]["last_seen"] = max(contacts[name]["last_seen"], str(last_seen or ""))
+ contacts[name]["jid"] = jid or ""
+ con.close()
+except Exception: pass
# Email contacts (recent senders)
try: