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: auto-install wacli-keepalive launchd agent + self-healing supervisor

auroracapital873e7a72a545
diff --git a/claude-ops/bin/wacli-health b/claude-ops/bin/wacli-health
new file mode 100755
index 00000000..d2e71c60
--- /dev/null
+++ b/claude-ops/bin/wacli-health
@@ -0,0 +1,123 @@
+#!/usr/bin/env bash
+# wacli-health — Check wacli + keepalive health. Returns 0 if healthy, 1 if not.
+#
+# Usage: wacli-health # exit code only
+# wacli-health --json # JSON output
+# wacli-health --repair # auto-fix if unhealthy
+#
+# Any ops skill can call this before using wacli to ensure the connection is live.
+set -euo pipefail
+
+WACLI="${WACLI_BIN:-/usr/local/bin/wacli}"
+STORE="${WACLI_STORE:-$HOME/.wacli}"
+HEALTH_FILE="$STORE/.health"
+KEEPALIVE_LABEL="com.claude-ops.wacli-keepalive"
+SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
+
+JSON_MODE=0
+REPAIR_MODE=0
+for arg in "$@"; do
+ case "$arg" in
+ --json) JSON_MODE=1 ;;
+ --repair) REPAIR_MODE=1 ;;
+ esac
+done
+
+healthy=1
+issues=()
+
+# 1. Check wacli binary exists
+if ! command -v "$WACLI" &>/dev/null; then
+ healthy=0
+ issues+=("wacli binary not found at $WACLI")
+fi
+
+# 2. Check authentication
+if [[ $healthy -eq 1 ]]; then
+ doctor_out=$("$WACLI" doctor 2>&1) || true
+ if ! echo "$doctor_out" | grep -q "AUTHENTICATED.*true"; then
+ healthy=0
+ issues+=("not authenticated — QR scan required")
+ fi
+fi
+
+# 3. Check health file
+if [[ -f "$HEALTH_FILE" ]]; then
+ status=$(grep '^status=' "$HEALTH_FILE" 2>/dev/null | cut -d= -f2- || echo "unknown")
+ case "$status" in
+ connected|running|ok) ;;
+ needs_auth|needs_reauth)
+ healthy=0
+ issues+=("health file reports: $status")
+ ;;
+ paused)
+ issues+=("sync currently paused for external command")
+ ;;
+ *)
+ issues+=("health file status: $status")
+ ;;
+ esac
+ health_pid=$(grep '^pid=' "$HEALTH_FILE" 2>/dev/null | cut -d= -f2- || true)
+ if [[ -n "$health_pid" ]] && ! kill -0 "$health_pid" 2>/dev/null; then
+ healthy=0
+ issues+=("keepalive pid=$health_pid is dead")
+ fi
+else
+ healthy=0
+ issues+=("no health file — keepalive may not be running")
+fi
+
+# 4. Check launchd/systemd registration
+if [[ "$(uname -s)" == "Darwin" ]]; then
+ pid_str=$(launchctl list 2>/dev/null | awk -v lbl="$KEEPALIVE_LABEL" '$3==lbl {print $1}' || true)
+ if [[ -z "$pid_str" ]]; then
+ healthy=0
+ issues+=("$KEEPALIVE_LABEL not registered in launchd")
+ elif [[ "$pid_str" == "-" ]]; then
+ healthy=0
+ issues+=("$KEEPALIVE_LABEL registered but not running")
+ elif ! kill -0 "$pid_str" 2>/dev/null; then
+ healthy=0
+ issues+=("$KEEPALIVE_LABEL has stale PID $pid_str")
+ fi
+elif command -v systemctl &>/dev/null; then
+ if ! systemctl --user is-active claude-ops-wacli-keepalive.service &>/dev/null; then
+ healthy=0
+ issues+=("claude-ops-wacli-keepalive.service not active")
+ fi
+fi
+
+# Output
+if [[ $JSON_MODE -eq 1 ]]; then
+ issues_json="["
+ first=1
+ for i in "${issues[@]+"${issues[@]}"}"; do
+ [[ $first -eq 0 ]] && issues_json+=","
+ first=0
+ issues_json+="\"$(echo "$i" | sed 's/"/\\"/g')\""
+ done
+ issues_json+="]"
+ echo "{\"healthy\": $([ $healthy -eq 1 ] && echo true || echo false), \"issues\": $issues_json}"
+else
+ if [[ $healthy -eq 1 ]]; then
+ echo "wacli: healthy"
+ else
+ echo "wacli: UNHEALTHY"
+ for i in "${issues[@]+"${issues[@]}"}"; do
+ echo " - $i"
+ done
+ fi
+fi
+
+# Auto-repair if requested and unhealthy
+if [[ $REPAIR_MODE -eq 1 ]] && [[ $healthy -eq 0 ]]; then
+ echo "Attempting auto-repair..."
+ if [[ -f "$SCRIPT_DIR/scripts/ops-daemon.sh" ]]; then
+ bash "$SCRIPT_DIR/scripts/ops-daemon.sh" --install 2>&1 || true
+ echo "Reinstalled launchd/systemd services. Check again in ~15s."
+ else
+ echo "Cannot find ops-daemon.sh for repair" >&2
+ fi
+fi
+
+exit $(( 1 - healthy ))
diff --git a/claude-ops/bin/wacli-safe b/claude-ops/bin/wacli-safe
new file mode 100755
index 00000000..63db5ac1
--- /dev/null
+++ b/claude-ops/bin/wacli-safe
@@ -0,0 +1,48 @@
+#!/usr/bin/env bash
+# wacli-safe — Run a one-shot wacli command without store-lock conflicts.
+#
+# Pauses the persistent keepalive sync, runs the command, then lets sync resume.
+# Usage: wacli-safe send --to "+1234567890" --text "Hello"
+# wacli-safe history backfill --chat "[email protected]" --count 50
+#
+# The keepalive script watches for the pause signal file and gracefully stops
+# its persistent sync. After this script exits (or after 60s timeout), the
+# keepalive resumes automatically.
+set -euo pipefail
+
+WACLI="${WACLI_BIN:-/usr/local/bin/wacli}"
+STORE="${WACLI_STORE:-$HOME/.wacli}"
+PAUSE_SIGNAL="$STORE/.pause_sync"
+
+if [[ $# -eq 0 ]]; then
+ echo "Usage: wacli-safe <wacli-subcommand> [args...]" >&2
+ echo " Pauses keepalive sync, runs the wacli command, then resumes sync." >&2
+ exit 1
+fi
+
+cleanup() {
+ rm -f "$PAUSE_SIGNAL"
+}
+trap cleanup EXIT INT TERM
+
+# Write pause signal with our PID + timestamp
+mkdir -p "$STORE"
+echo "$$" > "$PAUSE_SIGNAL"
+
+# Wait for keepalive to stop its sync (check every 500ms, max 10s)
+waited=0
+while pgrep -f "wacli sync --follow" >/dev/null 2>&1 && [[ $waited -lt 20 ]]; do
+ sleep 0.5
+ (( waited++ )) || true
+done
+
+if pgrep -f "wacli sync --follow" >/dev/null 2>&1; then
+ echo "warning: keepalive sync still running after 10s — proceeding anyway" >&2
+fi
+
+# Run the actual wacli command
+"$WACLI" "$@"
+exit_code=$?
+
+# Cleanup happens via trap
+exit $exit_code
diff --git a/claude-ops/scripts/ops-daemon.sh b/claude-ops/scripts/ops-daemon.sh
index c12fe50a..e16d8c80 100755
--- a/claude-ops/scripts/ops-daemon.sh
+++ b/claude-ops/scripts/ops-daemon.sh
@@ -285,6 +285,17 @@ write_daemon_health() {
local pid_val
if [[ "$pid" == "null" ]] || [[ -z "$pid" ]]; then
pid_val="null"
+ # No PID tracked — status cannot be "running"
+ if [[ "$status" == "running" ]]; then
+ status="dead"
+ SERVICE_STATUS["$name"]="dead"
+ fi
+ elif ! kill -0 "$pid" 2>/dev/null; then
+ # PID exists in our tracking but process is dead
+ pid_val="null"
+ status="dead"
+ SERVICE_STATUS["$name"]="dead"
+ SERVICE_PIDS["$name"]=""
else
pid_val="$pid"
fi
@@ -705,31 +716,57 @@ install_daemon_launchd() {
return 1
fi
- # Substitute placeholders while copying.
- if [[ -f "$daemon_plist_src" ]]; then
- sed \
- -e "s|__BASH_PATH__|$bash_path|g" \
- -e "s|__PLUGIN_ROOT__|$plugin_root|g" \
- -e "s|__DAEMON_SCRIPT_PATH__|$OPS_DAEMON_SCRIPT|g" \
- -e "s|__LOG_DIR__|$LOG_DIR|g" \
- -e "s|__HOME__|$HOME|g" \
- "$daemon_plist_src" > "$daemon_plist_dst"
- launchctl unload -w "$daemon_plist_dst" 2>/dev/null || true
- launchctl load -w "$daemon_plist_dst"
- log "INSTALL(launchd): loaded $daemon_plist_dst"
+ _install_launchd_plist "$daemon_plist_src" "$daemon_plist_dst" \
+ "$bash_path" "$plugin_root" "com.claude-ops.daemon"
+ _install_launchd_plist "$keepalive_plist_src" "$keepalive_plist_dst" \
+ "$bash_path" "$plugin_root" "com.claude-ops.wacli-keepalive"
+}
+
+# Install a single launchd plist: substitute placeholders, copy, bootstrap.
+# Args: $1=src $2=dst $3=bash_path $4=plugin_root $5=label
+_install_launchd_plist() {
+ local src="$1" dst="$2" bash_path="$3" plugin_root="$4" label="$5"
+ if [[ ! -f "$src" ]]; then
+ log "INSTALL(launchd): source plist not found: $src"
+ return 1
+ fi
+
+ # Check if already running with a live PID — skip reinstall
+ local existing_pid
+ existing_pid=$(launchctl list "$label" 2>/dev/null | awk '/PID/{print $2}' || true)
+ if [[ -z "$existing_pid" ]]; then
+ # Also try parsing the list output (format: PID\tStatus\tLabel)
+ existing_pid=$(launchctl list 2>/dev/null | awk -v lbl="$label" '$3==lbl && $1!="-" {print $1}' || true)
+ fi
+ if [[ -n "$existing_pid" ]] && kill -0 "$existing_pid" 2>/dev/null; then
+ log "INSTALL(launchd): $label already running (pid=$existing_pid) — skipping"
+ return 0
fi
- if [[ -f "$keepalive_plist_src" ]]; then
- sed \
- -e "s|__BASH_PATH__|$bash_path|g" \
- -e "s|__PLUGIN_ROOT__|$plugin_root|g" \
- -e "s|__KEEPALIVE_SCRIPT_PATH__|$OPS_KEEPALIVE_SCRIPT|g" \
- -e "s|__LOG_DIR__|$LOG_DIR|g" \
- -e "s|__HOME__|$HOME|g" \
- "$keepalive_plist_src" > "$keepalive_plist_dst"
- launchctl unload -w "$keepalive_plist_dst" 2>/dev/null || true
- launchctl load -w "$keepalive_plist_dst"
- log "INSTALL(launchd): loaded $keepalive_plist_dst"
+ # Substitute placeholders
+ sed \
+ -e "s|__BASH_PATH__|$bash_path|g" \
+ -e "s|__PLUGIN_ROOT__|$plugin_root|g" \
+ -e "s|__DAEMON_SCRIPT_PATH__|$OPS_DAEMON_SCRIPT|g" \
+ -e "s|__KEEPALIVE_SCRIPT_PATH__|$OPS_KEEPALIVE_SCRIPT|g" \
+ -e "s|__LOG_DIR__|$LOG_DIR|g" \
+ -e "s|__HOME__|$HOME|g" \
+ "$src" > "$dst"
+
+ # Bootstrap: prefer modern launchctl bootstrap, fallback to legacy load
+ local uid
+ uid=$(id -u)
+ local gui_domain="gui/$uid"
+
+ # Bootout first to clear stale registrations
+ launchctl bootout "$gui_domain/$label" 2>/dev/null || true
+ if launchctl bootstrap "$gui_domain" "$dst" 2>/dev/null; then
+ log "INSTALL(launchd): bootstrapped $label into $gui_domain"
+ else
+ # Fallback: legacy load (macOS <10.10 or restricted environments)
+ launchctl unload -w "$dst" 2>/dev/null || true
+ launchctl load -w "$dst"
+ log "INSTALL(launchd): loaded $label via legacy launchctl load"
fi
}
@@ -882,6 +919,139 @@ uninstall_daemon_schtasks() {
log "UNINSTALL(schtasks): removed ClaudeOpsDaemon + ClaudeOpsWacliKeepalive"
}
+# ── General self-healing supervisor for all com.claude-ops.* services ─────
+# Enumerates expected services, checks each is installed + alive, auto-repairs.
+# Called at daemon startup and periodically during the monitor loop.
+ENSURE_SERVICES_LAST_RUN=0
+ENSURE_SERVICES_INTERVAL="${ENSURE_SERVICES_INTERVAL:-300}" # every 5 min
+
+# Expected launchd agents (macOS) / systemd units (Linux).
+# Format: "label|plist_src_basename|description"
+EXPECTED_SERVICES=(
+ "com.claude-ops.daemon|com.claude-ops.daemon.plist|ops daemon"
+ "com.claude-ops.wacli-keepalive|com.claude-ops.wacli-keepalive.plist|wacli keepalive"
+)
+
+ensure_all_services() {
+ local now
+ now=$(date +%s)
+ # Throttle: skip if ran recently (unless force=1 passed)
+ if [[ "${1:-}" != "force" ]] && (( now - ENSURE_SERVICES_LAST_RUN < ENSURE_SERVICES_INTERVAL )); then
+ return 0
+ fi
+ ENSURE_SERVICES_LAST_RUN=$now
+
+ local os
+ os="$(ops_os 2>/dev/null || uname -s)"
+
+ case "$os" in
+ macos|Darwin*) _ensure_all_services_launchd ;;
+ debian|fedora|arch|suse|alpine|linux|wsl|Linux*) _ensure_all_services_systemd ;;
+ *) return 0 ;; # Windows/unsupported — skip
+ esac
+}
+
+_ensure_all_services_launchd() {
+ command -v launchctl >/dev/null 2>&1 || return 0
+ local agents_dir="$HOME/Library/LaunchAgents"
+ local entry label plist_base desc
+ local repaired=0
+
+ for entry in "${EXPECTED_SERVICES[@]}"; do
+ IFS='|' read -r label plist_base desc <<< "$entry"
+ local plist_dst="$agents_dir/$plist_base"
+ local plist_src="$SCRIPT_DIR/scripts/$plist_base"
+
+ # 1. Check if plist is installed
+ if [[ ! -f "$plist_dst" ]]; then
+ log "ENSURE: $label plist missing from $agents_dir — installing"
+ _repair_launchd_service "$label" "$plist_src" "$plist_dst"
+ (( repaired++ )) || true
+ continue
+ fi
+
+ # 2. Check if service is registered and has a live PID
+ local pid_str
+ pid_str=$(launchctl list 2>/dev/null | awk -v lbl="$label" '$3==lbl {print $1}' || true)
+
+ if [[ -z "$pid_str" ]]; then
+ # Not registered at all — bootstrap it
+ log "ENSURE: $label not registered in launchctl — bootstrapping"
+ _repair_launchd_service "$label" "$plist_src" "$plist_dst"
+ (( repaired++ )) || true
+ continue
+ fi
+
+ if [[ "$pid_str" == "-" ]]; then
+ # Registered but no PID — crashed or not started
+ local exit_status
+ exit_status=$(launchctl list 2>/dev/null | awk -v lbl="$label" '$3==lbl {print $2}' || true)
+ if [[ "$exit_status" != "0" ]] && [[ -n "$exit_status" ]] && [[ "$exit_status" != "-" ]]; then
+ log "ENSURE: $label crashed (exit=$exit_status) — kickstarting"
+ launchctl kickstart "gui/$(id -u)/$label" 2>/dev/null || {
+ # Fallback: full reinstall
+ _repair_launchd_service "$label" "$plist_src" "$plist_dst"
+ }
+ (( repaired++ )) || true
+ fi
+ continue
+ fi
+
+ # 3. Has a PID — verify it's actually alive
+ if ! kill -0 "$pid_str" 2>/dev/null; then
+ log "ENSURE: $label has stale PID $pid_str — kickstarting"
+ launchctl kickstart -k "gui/$(id -u)/$label" 2>/dev/null || {
+ _repair_launchd_service "$label" "$plist_src" "$plist_dst"
+ }
+ (( repaired++ )) || true
+ fi
+ done
+
+ if [[ $repaired -gt 0 ]]; then
+ log "ENSURE: repaired $repaired service(s)"
+ fi
+}
+
+_repair_launchd_service() {
+ local label="$1" plist_src="$2" plist_dst="$3"
+ local bash_path
+ bash_path="$(command -v bash)"
+ local plugin_root="$SCRIPT_DIR"
+ if [[ -z "$bash_path" ]] || [[ ! -f "$plist_src" ]]; then
+ log "ENSURE: cannot repair $label — missing bash or source plist"
+ return 1
+ fi
+ _install_launchd_plist "$plist_src" "$plist_dst" "$bash_path" "$plugin_root" "$label"
+}
+
+_ensure_all_services_systemd() {
+ command -v systemctl >/dev/null 2>&1 || return 0
+ local repaired=0
+
+ # Check wacli-keepalive systemd unit
+ if ! systemctl --user is-active claude-ops-wacli-keepalive.service &>/dev/null; then
+ log "ENSURE: claude-ops-wacli-keepalive.service not active — restarting"
+ systemctl --user restart claude-ops-wacli-keepalive.service 2>/dev/null || {
+ # Unit may not exist — trigger full install
+ install_daemon_systemd
+ }
+ (( repaired++ )) || true
+ fi
+
+ # Check timer
+ if ! systemctl --user is-active claude-ops.timer &>/dev/null; then
+ log "ENSURE: claude-ops.timer not active — restarting"
+ systemctl --user restart claude-ops.timer 2>/dev/null || {
+ install_daemon_systemd
+ }
+ (( repaired++ )) || true
+ fi
+
+ if [[ $repaired -gt 0 ]]; then
+ log "ENSURE: repaired $repaired systemd service(s)"
+ fi
+}
+
install_daemon() {
local os
os="$(ops_os 2>/dev/null || uname -s)"
@@ -968,6 +1138,9 @@ done
log "START: ops-daemon pid=$$ starting (run_once=$OPS_RUN_ONCE)"
rotate_log
+# Ensure all com.claude-ops.* services are installed and healthy at startup
+ensure_all_services "force"
+
if ! load_services_config; then
log "FATAL: no services config — writing empty health and sleeping"
cat > "$HEALTH_FILE" <<EOF
@@ -1023,6 +1196,9 @@ while true; do
fi
done < <(get_enabled_services)
+ # ── Service self-healing pass ────────────────────────────────────────────
+ ensure_all_services # Every 5 min: verify all launchd/systemd services
+
# ── Intelligence pass (smart brain) ──────────────────────────────────────
# These run with their own internal throttles — safe to call every loop
prefetch_briefing_cache # Every 5 min: WA/email/PR counts for ops-go
diff --git a/claude-ops/scripts/wacli-keepalive.sh b/claude-ops/scripts/wacli-keepalive.sh
index 14b64bed..230cec3f 100755
--- a/claude-ops/scripts/wacli-keepalive.sh
+++ b/claude-ops/scripts/wacli-keepalive.sh
@@ -24,13 +24,18 @@ fi
WACLI="${WACLI_BIN:-/usr/local/bin/wacli}"
STORE="${WACLI_STORE:-$HOME/.wacli}"
-LOG_DIR="${WACLI_LOG_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace/logs}"
+DATA_DIR="${OPS_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"
+LOG_DIR="${WACLI_LOG_DIR:-$DATA_DIR/logs}"
LOG="$LOG_DIR/wacli-keepalive.log"
HEALTH_FILE="$STORE/.health"
+MEMORY_DIR="$DATA_DIR/memories"
MAX_LOG_SIZE=1048576 # 1MB
SYNC_PROBE_TIMEOUT=20
+BACKFILL_INTERVAL="${BACKFILL_INTERVAL:-1800}" # 30 min default
+PAUSE_SIGNAL="$STORE/.pause_sync"
+SYNC_PID_FILE="$STORE/.sync_pid"
-mkdir -p "$LOG_DIR" "$STORE"
+mkdir -p "$LOG_DIR" "$STORE" "$MEMORY_DIR"
log() { printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" >> "$LOG"; }
@@ -41,6 +46,15 @@ fi
log "START: keepalive pid=$$ starting"
+# ── Step 0: Race condition prevention ───────────────────────────────────
+# Both com.claude-ops.daemon and com.claude-ops.wacli-keepalive start at boot.
+# If both try wacli sync simultaneously, one crashes on the store lock.
+# Wait briefly for any concurrent sync to claim the lock first.
+if pgrep -f "wacli sync" >/dev/null 2>&1; then
+ log "START: another wacli sync is running — waiting 15s for lock release"
+ sleep 15
+fi
+
# ── Step 1: Kill orphaned wacli sync processes ──────────────────────────
cleanup_stale() {
local stale_pids
@@ -187,21 +201,221 @@ if jids:
}
auto_detect_empty_chats
+detect_missed_messages
run_backfill
write_health "connected" "persistent sync starting"
-# Persistent sync for real-time messages. If it exits, launchd restarts us.
+# ── Pause-signal handler ────────────────────────────────────────────────
+# External processes (send, backfill) write $PAUSE_SIGNAL to request exclusive
+# wacli access. We stop the persistent sync, wait for the signal to clear
+# (or auto-expire after 60s), then restart.
+check_pause_signal() {
+ if [[ ! -f "$PAUSE_SIGNAL" ]]; then return 1; fi
+
+ # Auto-expire stale pause signals (>60s old)
+ local pause_age
+ pause_age=$(( $(date +%s) - $(stat -f%m "$PAUSE_SIGNAL" 2>/dev/null || stat -c%Y "$PAUSE_SIGNAL" 2>/dev/null || echo 0) ))
+ if [[ $pause_age -gt 60 ]]; then
+ log "PAUSE: stale pause signal (${pause_age}s old) — removing"
+ rm -f "$PAUSE_SIGNAL"
+ return 1
+ fi
+
+ local requester_pid
+ requester_pid=$(head -1 "$PAUSE_SIGNAL" 2>/dev/null | grep -o '[0-9]*' || true)
+ if [[ -n "$requester_pid" ]] && ! kill -0 "$requester_pid" 2>/dev/null; then
+ log "PAUSE: requester pid=$requester_pid is dead — removing signal"
+ rm -f "$PAUSE_SIGNAL"
+ return 1
+ fi
+
+ return 0
+}
+
+# ── Periodic backfill in background ─────────────────────────────────────
+# Runs every BACKFILL_INTERVAL during persistent sync. Non-blocking.
+LAST_BACKFILL_TIME=$(date +%s)
+
+periodic_backfill() {
+ local now
+ now=$(date +%s)
+ if (( now - LAST_BACKFILL_TIME < BACKFILL_INTERVAL )); then return 0; fi
+ LAST_BACKFILL_TIME=$now
+
+ log "PERIODIC-BACKFILL: checking for chats needing backfill"
+ (
+ auto_detect_empty_chats
+ detect_missed_messages
+ if [[ -f "$STORE/.backfill_jids" ]] && [[ -s "$STORE/.backfill_jids" ]]; then
+ run_backfill
+ write_backfill_memory
+ fi
+ ) &
+}
+
+# ── Missed message detection ───────────────────────────────────────────
+# Compare chat metadata LastMessageTS against actual latest DB message.
+# If gap > 1 hour, the chat has missing messages and needs backfill.
+detect_missed_messages() {
+ command -v "$WACLI" &>/dev/null || return 0
+ local backfill_file="$STORE/.backfill_jids"
+
+ "$WACLI" chats list --json 2>/dev/null | python3 -c "
+import json, sys, subprocess, datetime
+
+data = json.load(sys.stdin)
+chats = data.get('data', []) or []
+wacli = '${WACLI}'
+cutoff = (datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=14)).isoformat()
+gap_threshold = 3600 # 1 hour in seconds
+missed = []
+
+for c in chats:
+ jid = c.get('JID', '')
+ meta_ts = c.get('LastMessageTS', '')
+ if not jid or not meta_ts or meta_ts < cutoff:
+ continue
+ try:
+ result = subprocess.run(
+ [wacli, 'messages', 'list', '--chat', jid, '--limit', '1', '--json'],
+ capture_output=True, text=True, timeout=10
+ )
+ if result.returncode != 0:
+ continue
+ msg_data = json.loads(result.stdout)
+ msgs = msg_data.get('data', {}).get('messages', []) or []
+ if not msgs:
+ missed.append(jid)
+ continue
+ db_ts = msgs[0].get('Timestamp', '')
+ if not db_ts:
+ continue
+ # Parse both timestamps and compare
+ from dateutil.parser import parse as dtparse
+ meta_dt = dtparse(meta_ts)
+ db_dt = dtparse(db_ts)
+ gap = abs((meta_dt - db_dt).total_seconds())
+ if gap > gap_threshold:
+ missed.append(jid)
+ except Exception:
+ continue
+
+if missed:
+ # Append to existing backfill file (don't overwrite)
+ existing = set()
+ try:
+ with open('${backfill_file}') as f:
+ existing = set(l.strip() for l in f if l.strip())
+ except: pass
+ with open('${backfill_file}', 'w') as f:
+ for jid in sorted(existing | set(missed)):
+ f.write(jid + '\n')
+ print(f'MISSED: {len(missed)} chats with message gaps detected')
+" 2>/dev/null | while IFS= read -r line; do
+ log "$line"
+ done || true
+}
+
+# ── Write backfill summary to ops memory ────────────────────────────────
+write_backfill_memory() {
+ command -v "$WACLI" &>/dev/null || return 0
+
+ "$WACLI" chats list --json 2>/dev/null | python3 -c "
+import json, sys, subprocess, datetime, os
+
+data = json.load(sys.stdin)
+chats = data.get('data', []) or []
+wacli = '${WACLI}'
+memory_dir = '${MEMORY_DIR}'
+now = datetime.datetime.now(datetime.timezone.utc)
+summaries = []
+
+for c in chats[:20]:
+ jid = c.get('JID', '')
+ name = c.get('Name', '') or c.get('PushName', '') or jid
+ meta_ts = c.get('LastMessageTS', '')
+ if not jid or not meta_ts:
+ continue
+ try:
+ result = subprocess.run(
+ [wacli, 'messages', 'list', '--chat', jid, '--limit', '3', '--json'],
+ capture_output=True, text=True, timeout=10
+ )
+ if result.returncode != 0:
+ continue
+ msg_data = json.loads(result.stdout)
+ msgs = msg_data.get('data', {}).get('messages', []) or []
+ if not msgs:
+ continue
+ # Build summary
+ texts = [m.get('Text', '')[:100] for m in msgs if m.get('Text')]
+ if texts:
+ summaries.append({
+ 'contact': name,
+ 'jid': jid,
+ 'last_message_ts': meta_ts,
+ 'recent_topics': texts[:3],
+ 'msg_count_local': len(msgs)
+ })
+ except:
+ continue
+
+if summaries:
+ summary_file = os.path.join(memory_dir, 'whatsapp_backfill_summary.json')
+ with open(summary_file, 'w') as f:
+ json.dump({
+ 'updated': now.isoformat(),
+ 'backfilled_chats': summaries
+ }, f, indent=2)
+ print(f'MEMORY: wrote backfill summary for {len(summaries)} chats')
+" 2>/dev/null | while IFS= read -r line; do
+ log "$line"
+ done || true
+}
+
+# ── Persistent sync with pause-signal + periodic backfill ──────────────
log "SYNC: starting persistent sync --follow"
-"$WACLI" sync --follow --refresh-contacts --refresh-groups 2>&1 | while IFS= read -r line; do
- # Filter noise
- case "$line" in
- *"app state key"*|*"Failed to sync app state"*|*"Failed to do initial fetch"*) ;;
- *"ERROR"*) log "SYNC-ERR: $line" ;;
- *"Synced"*|*"Connected"*|*"Stopping"*) log "SYNC: $line" ;;
- esac
+
+while true; do
+ # Check for pause signal before starting sync
+ if check_pause_signal; then
+ log "SYNC: pause signal detected — waiting for external command to finish"
+ write_health "paused" "sync paused for external wacli command"
+ while check_pause_signal; do sleep 2; done
+ log "SYNC: pause cleared — resuming"
+ write_health "connected" "sync resuming after pause"
+ fi
+
+ # Start persistent sync in background so we can monitor pause signals
+ "$WACLI" sync --follow --refresh-contacts --refresh-groups 2>&1 &
+ local_sync_pid=$!
+ echo "$local_sync_pid" > "$SYNC_PID_FILE"
+
+ # Monitor loop: check pause signals + trigger periodic backfill
+ while kill -0 "$local_sync_pid" 2>/dev/null; do
+ # If pause signal appears, stop sync gracefully
+ if check_pause_signal; then
+ log "SYNC: pause signal received — stopping sync pid=$local_sync_pid"
+ kill -TERM "$local_sync_pid" 2>/dev/null || true
+ wait "$local_sync_pid" 2>/dev/null || true
+ rm -f "$SYNC_PID_FILE"
+ break
+ fi
+
+ # Periodic backfill (non-blocking, runs in subshell)
+ periodic_backfill
+
+ sleep 5
+ done
+
+ # If sync exited on its own (not paused), break out of the restart loop
+ if ! check_pause_signal; then
+ break
+ fi
done
+rm -f "$SYNC_PID_FILE"
write_health "disconnected" "sync exited"
log "EXIT: sync process ended — launchd will restart"
exit 0