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 WhatsApp freshness gate and voice transcription edge cases

Cursor Agentee3e02cb596a
diff --git a/claude-ops/bin/wa-inbox-fresh.sh b/claude-ops/bin/wa-inbox-fresh.sh
index 535600cd..a0e45081 100755
--- a/claude-ops/bin/wa-inbox-fresh.sh
+++ b/claude-ops/bin/wa-inbox-fresh.sh
@@ -4,12 +4,12 @@
#
# 1. ensure the whatsmeow bridge is up + connected (restart if :8080 is dead)
# 2. force a history backfill (POST /api/backfill)
-# 3. fill any new voice notes with transcripts (whatsapp-transcribe.service)
-# 4. wait (bounded) for the store's newest message to settle
+# 3. wait (bounded) for the store's newest message to settle
+# 4. queue voice transcription (async; does not block on Whisper)
# 5. print a FRESHNESS report so the caller never classifies blind
#
# Exit 0 = store is as-fresh-as-this-bridge-can-be (report printed).
-# Exit 2 = bridge unreachable and could not be recovered (do NOT trust the store).
+# Exit 2 = bridge unreachable or messages store unreadable (do NOT trust the store).
#
# HARD LIMIT (state it, don't hide it): messages YOU send from your PHONE may not
# replicate to a companion bridge — WhatsApp's multi-device protocol does not
@@ -43,16 +43,21 @@ if journalctl --user -u whatsapp-bridge.service -n 40 --no-pager 2>/dev/null \
log "wa-fresh: bridge connected ✓"
fi
-before=$(sqlite3 "$DB" "SELECT COALESCE(datetime(MAX(timestamp)),'1970-01-01') FROM messages;" 2>/dev/null)
+if [ ! -r "$DB" ]; then
+ log "wa-fresh: ERROR messages store missing or unreadable at $DB — do not trust it"
+ exit 2
+fi
+
+before=$(sqlite3 "$DB" "SELECT COALESCE(datetime(MAX(timestamp)),'1970-01-01') FROM messages;") || {
+ log "wa-fresh: ERROR cannot read messages store at $DB — do not trust it"
+ exit 2
+}
# 2. force backfill
code=$(curl -fsS -m 20 -X POST -o /dev/null -w "%{http_code}" "$BRIDGE/api/backfill" 2>/dev/null || echo "ERR")
log "wa-fresh: backfill → HTTP ${code}"
-# 3. transcribe any freshly-synced voice notes (idempotent, lock-guarded)
-systemctl --user start whatsapp-transcribe.service 2>/dev/null && log "wa-fresh: voice transcription triggered"
-
-# 4. bounded wait for the store to settle
+# 3. bounded wait for the store to settle (after backfill, before transcription)
new=0
for i in $(seq 1 "$WAIT_TICKS"); do
sleep 4
@@ -60,9 +65,19 @@ for i in $(seq 1 "$WAIT_TICKS"); do
[ "${cnt:-0}" -gt 0 ] && { new=$cnt; break; }
done
+# 4. transcribe voice notes synced during backfill (async — gate stays bounded)
+if systemctl --user start --no-block whatsapp-transcribe.service 2>/dev/null; then
+ log "wa-fresh: voice transcription queued"
+else
+ log "wa-fresh: voice transcription not started"
+fi
+
# 5. freshness report
-after=$(sqlite3 "$DB" "SELECT COALESCE(datetime(MAX(timestamp)),'?') FROM messages;" 2>/dev/null)
-age_min=$(sqlite3 "$DB" "SELECT CAST((julianday('now')-julianday(MAX(timestamp)))*1440 AS INT) FROM messages;" 2>/dev/null)
+after=$(sqlite3 "$DB" "SELECT COALESCE(datetime(MAX(timestamp)),'?') FROM messages;") || {
+ log "wa-fresh: ERROR cannot read messages store at $DB — do not trust it"
+ exit 2
+}
+age_min=$(sqlite3 "$DB" "SELECT CAST((julianday('now')-julianday(MAX(timestamp)))*1440 AS INT) FROM messages;") || age_min=""
log "wa-fresh: newest message = ${after} (${age_min:-?} min old) | new rows this cycle = ${new}"
if [ "${age_min:-9999}" -gt 120 ]; then
log "wa-fresh: WARNING newest message is >2h old — store may be lagging; treat 'last-sender' classification with caution"
diff --git a/claude-ops/scripts/whatsapp/systemd/whatsapp-transcribe.service b/claude-ops/scripts/whatsapp/systemd/whatsapp-transcribe.service
index 206d5551..9df8bc78 100644
--- a/claude-ops/scripts/whatsapp/systemd/whatsapp-transcribe.service
+++ b/claude-ops/scripts/whatsapp/systemd/whatsapp-transcribe.service
@@ -7,6 +7,8 @@ PartOf=whatsapp-bridge.service
[Service]
Type=oneshot
+# Batch may run many Whisper calls; disable the default ~90s start timeout.
+TimeoutStartSec=0
# OPENAI_API_KEY (and other secrets) for the metered Whisper API.
EnvironmentFile=%h/.config/systemd/env/mcp-secrets.env
# Wait up to 10s for the bridge :8080 before downloading media.
diff --git a/claude-ops/scripts/whatsapp/transcribe_voice_notes.py b/claude-ops/scripts/whatsapp/transcribe_voice_notes.py
index 7859f442..e902041a 100755
--- a/claude-ops/scripts/whatsapp/transcribe_voice_notes.py
+++ b/claude-ops/scripts/whatsapp/transcribe_voice_notes.py
@@ -15,30 +15,75 @@ Guards (per global cost-leak + no-stacking rules):
* idempotent: only ever touches empty-content audio rows
Env: OPENAI_API_KEY (from ~/.config/systemd/env/mcp-secrets.env).
+ WHATSAPP_BRIDGE_DB (same default as wa-inbox-fresh / ops tooling).
Args: --days N (lookback window, default 2) --max N (cap per run, default 80)
"""
-import argparse, json, os, shutil, sqlite3, subprocess, sys, time, urllib.request
-
-DB = os.path.expanduser("~/.local/share/whatsapp-mcp/whatsapp-bridge/store/messages.db")
+import argparse
+import json
+import os
+import shutil
+import signal
+import sqlite3
+import subprocess
+import sys
+import time
+import urllib.request
+
+DB = os.path.expanduser(
+ os.environ.get(
+ "WHATSAPP_BRIDGE_DB",
+ "~/.local/share/whatsapp-mcp/whatsapp-bridge/store/messages.db",
+ )
+)
BRIDGE = "http://127.0.0.1:8080/api/download"
LOCKDIR = "/tmp/.wa-transcribe.lock"
+PIDFILE = os.path.join(LOCKDIR, "pid")
+FAIL_MARKER = "[voice] (transcription unavailable)"
-def acquire_lock():
+def _pid_alive(pid):
try:
- os.mkdir(LOCKDIR) # atomic; fails if another run holds it
+ os.kill(pid, 0)
return True
+ except OSError:
+ return False
+
+
+def release_lock(signum=None, frame=None):
+ shutil.rmtree(LOCKDIR, ignore_errors=True)
+ if signum is not None:
+ sys.exit(128 + signum)
+
+
+def acquire_lock():
+ try:
+ os.mkdir(LOCKDIR)
except FileExistsError:
- # stale lock older than 30 min → reclaim
try:
- if time.time() - os.path.getmtime(LOCKDIR) > 1800:
- shutil.rmtree(LOCKDIR, ignore_errors=True)
- os.mkdir(LOCKDIR)
- return True
- except FileNotFoundError:
+ with open(PIDFILE) as f:
+ old = int(f.read().strip())
+ if _pid_alive(old):
+ return False
+ except (FileNotFoundError, ValueError, OSError):
pass
- return False
+ shutil.rmtree(LOCKDIR, ignore_errors=True)
+ try:
+ os.mkdir(LOCKDIR)
+ except FileExistsError:
+ return False
+ with open(PIDFILE, "w") as f:
+ f.write(str(os.getpid()))
+ return True
+
+
+def mark_unavailable(con, mid, jid):
+ con.execute(
+ "UPDATE messages SET content=? WHERE id=? AND chat_jid=? "
+ "AND (content='' OR content IS NULL)",
+ (FAIL_MARKER, mid, jid),
+ )
+ con.commit()
def download(msg_id, chat_jid):
@@ -86,13 +131,16 @@ def main():
if not key:
print("transcriber: OPENAI_API_KEY not set — abort", flush=True)
sys.exit(1)
- if not os.path.exists(DB):
+ if not os.path.isfile(DB):
print(f"transcriber: db not found {DB} — abort", flush=True)
- sys.exit(0)
+ sys.exit(2)
if not acquire_lock():
print("transcriber: another run holds the lock — exit", flush=True)
sys.exit(0)
+ signal.signal(signal.SIGTERM, release_lock)
+ signal.signal(signal.SIGINT, release_lock)
+
try:
con = sqlite3.connect(DB, timeout=15)
con.execute("PRAGMA busy_timeout=8000;")
@@ -116,11 +164,13 @@ def main():
path = download(mid, jid)
if not path or not os.path.exists(path):
fail += 1
+ mark_unavailable(con, mid, jid)
print(f" [{i}] {mid[:8]} download-fail", flush=True)
continue
text = transcribe(path, key)
if not text:
fail += 1
+ mark_unavailable(con, mid, jid)
print(f" [{i}] {mid[:8]} transcribe-fail", flush=True)
continue
con.execute(
@@ -133,12 +183,13 @@ def main():
print(f" [{i}] {mid[:8]} ({'me' if mine else 'them'}) ok", flush=True)
except Exception as e:
fail += 1
+ mark_unavailable(con, mid, jid)
print(f" [{i}] {mid[:8]} err {e}", flush=True)
time.sleep(0.2)
con.close()
print(f"transcriber: done — {ok} transcribed, {fail} failed", flush=True)
finally:
- shutil.rmtree(LOCKDIR, ignore_errors=True)
+ release_lock()
if __name__ == "__main__":