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.

feat(ops-inbox): autonomous refresh + send-log reconciliation on every scan (#501)

Aurora Capitald5284aa04cd0
diff --git a/claude-ops/bin/ops-inbox-scan b/claude-ops/bin/ops-inbox-scan
index e5d1f265..5e5acc7d 100755
--- a/claude-ops/bin/ops-inbox-scan
+++ b/claude-ops/bin/ops-inbox-scan
@@ -64,13 +64,71 @@ export OIS_DAYS="$DAYS" OIS_DO_WA="$DO_WA" OIS_DO_EMAIL="$DO_EMAIL"
export OIS_WA_MSGDB="$WA_MSGDB" OIS_WA_WADB="$WA_WADB"
export OIS_GMAIL_ACCOUNT="$GMAIL_ACCOUNT" OIS_PRETTY="$PRETTY"
+BRIDGE_DIR="${WHATSAPP_BRIDGE_DIR:-$HOME/.local/share/whatsapp-mcp/whatsapp-bridge}"
+
+# --------------------------------------------------------- refresh on load ----
+# Autonomous "always pull latest before classifying" pass (Sam directive
+# 2026-06-05: "ensure backfill and frontfill is fully done automatically when I
+# run /ops-inbox"). Best-effort + bounded — NEVER blocks the scan for long and
+# NEVER fails it. Only runs when the bridge is actually reachable on :8080.
+# Skip with OIS_NO_REFRESH=1 (e.g. CI / repeated calls in one session).
+if [ "$DO_WA" = 1 ] && [ "${OIS_NO_REFRESH:-0}" != 1 ]; then
+ if curl -s -o /dev/null -m 4 http://127.0.0.1:8080/ 2>/dev/null; then
+ # frontfill: recent-conversation history backfill (idempotent)
+ curl -fsS -m 10 -X POST http://127.0.0.1:8080/api/backfill >/dev/null 2>&1 || true
+ # contacts link: phone + LID aliases -> names (idempotent)
+ [ -f "$BRIDGE_DIR/link_contacts.py" ] && \
+ python3 "$BRIDGE_DIR/link_contacts.py" >/dev/null 2>&1 || true
+ # bounded settle: wait until the newest stored message stops advancing
+ # (or ~18s elapses), so the classify pass reads a converged store.
+ if command -v sqlite3 >/dev/null 2>&1 && [ -f "$WA_MSGDB" ]; then
+ _prev=""; _stable=0
+ for _i in 1 2 3 4 5 6; do
+ _cur=$(sqlite3 "file:$WA_MSGDB?mode=ro" "SELECT max(timestamp) FROM messages;" 2>/dev/null || echo "")
+ if [ -n "$_cur" ] && [ "$_cur" = "$_prev" ]; then
+ _stable=$((_stable+1)); [ "$_stable" -ge 2 ] && break
+ else
+ _stable=0
+ fi
+ _prev="$_cur"
+ sleep 3
+ done
+ fi
+ fi
+fi
+
+# Send-log reconciliation feed: hand python the bridge's outbound-send journal so
+# it can demote NEEDS_REPLY threads already answered via /api/send or a
+# phone-originated send that hasn't landed in messages.db yet (Sam directive:
+# "include all things I sent to all people"). Linux: systemd journal. macOS /
+# other: bridge log file. Best-effort; empty feed => reconciliation is a no-op.
+OIS_SENDLOG_FILE=""
+if [ "$DO_WA" = 1 ]; then
+ OIS_SENDLOG_FILE="$(mktemp "${TMPDIR:-/tmp}/ois-sendlog.XXXXXX")"
+ trap 'rm -f "$OIS_SENDLOG_FILE" "${GMAIL_JSON_FILE:-}"' EXIT
+ if command -v journalctl >/dev/null 2>&1; then
+ journalctl --user -u whatsapp-bridge.service -o short-unix --no-pager \
+ --since "${DAYS} days ago" 2>/dev/null \
+ | grep -E "Received request to send message|Message sent to " \
+ > "$OIS_SENDLOG_FILE" 2>/dev/null || true
+ fi
+ # Fallback: scan the bridge's own log files if journal yielded nothing.
+ if [ ! -s "$OIS_SENDLOG_FILE" ]; then
+ for _lg in "$BRIDGE_DIR/logs/bridge.log" "$BRIDGE_DIR/logs/bridge.err.log"; do
+ [ -f "$_lg" ] && grep -E "Received request to send message|Message sent to " \
+ "$_lg" 2>/dev/null >> "$OIS_SENDLOG_FILE" || true
+ done
+ fi
+fi
+export OIS_SENDLOG_FILE
+
# Gmail is fetched in bash (gog is a CLI) and handed to python via a temp file so
# python never shells out. Empty file => python emits an "unreachable" note.
GMAIL_JSON_FILE=""
GMAIL_ERR=""
if [ "$DO_EMAIL" = 1 ]; then
GMAIL_JSON_FILE="$(mktemp "${TMPDIR:-/tmp}/ois-gmail.XXXXXX")"
- trap 'rm -f "$GMAIL_JSON_FILE"' EXIT
+ trap 'rm -f "$GMAIL_JSON_FILE" "${OIS_SENDLOG_FILE:-}"' EXIT
ACCT_ARGS=()
[ -n "$GMAIL_ACCOUNT" ] && ACCT_ARGS=(-a "$GMAIL_ACCOUNT")
if ! gog gmail search "${ACCT_ARGS[@]}" -j --results-only --no-input \
@@ -95,10 +153,57 @@ ACCT = os.environ.get("OIS_GMAIL_ACCOUNT", "")
PRETTY = os.environ.get("OIS_PRETTY") == "1"
GMAIL_F = os.environ.get("OIS_GMAIL_JSON_FILE", "")
GMAIL_ERR = os.environ.get("OIS_GMAIL_ERR", "")
+SENDLOG_F = os.environ.get("OIS_SENDLOG_FILE", "")
now = datetime.now(timezone.utc)
notes = []
+def ts_epoch(ts_str):
+ """messages.db timestamp string -> unix epoch (float), or None."""
+ if not ts_str:
+ return None
+ s = ts_str.strip().replace("Z", "+00:00")
+ for cand in (s, re.sub(r"\.\d+", "", s)):
+ try:
+ dt = datetime.fromisoformat(cand)
+ if dt.tzinfo is None:
+ dt = dt.replace(tzinfo=timezone.utc)
+ return dt.timestamp()
+ except ValueError:
+ continue
+ return None
+
+def load_send_log():
+ """Parse the bridge outbound-send journal into {recipient_jid: latest_epoch}.
+
+ Source lines (journalctl -o short-unix) look like:
+ <epoch>.<frac> host whatsapp-bridge[pid]: ... Message sent to <JID>
+ This lets the WhatsApp classifier demote a NEEDS_REPLY thread that was
+ already answered via /api/send (or a phone send not yet in messages.db) —
+ Sam directive 2026-06-05 "include all things I sent to all people".
+ Only epoch-stamped lines drive demotion; undated lines are ignored so we
+ never demote a thread whose send actually predates the last inbound.
+ """
+ sent = {}
+ if not SENDLOG_F or not os.path.exists(SENDLOG_F):
+ return sent
+ pat = re.compile(r"^(\d+)(?:\.\d+)?\s.*Message sent to\s+(\S+@\S+)")
+ try:
+ with open(SENDLOG_F, "r", errors="ignore") as fh:
+ for line in fh:
+ m = pat.search(line)
+ if not m:
+ continue
+ ep = float(m.group(1))
+ jid = m.group(2).strip().rstrip(".,;")
+ if jid not in sent or ep > sent[jid]:
+ sent[jid] = ep
+ except OSError:
+ pass
+ return sent
+
+SEND_LOG = load_send_log()
+
def age_min(ts_str):
if not ts_str:
return None
@@ -255,7 +360,24 @@ def scan_whatsapp():
if last["is_from_me"]:
out["waiting"].append(item)
else:
- out["needs_reply"].append(item)
+ # Send-log reconciliation: if we sent to ANY of this person's JIDs
+ # AFTER their last inbound message, the thread is already answered
+ # (the reply went out via /api/send or a phone send the store hasn't
+ # ingested yet). Demote NEEDS_REPLY -> waiting so we never re-flag or
+ # re-draft a thread the user already handled.
+ inbound_ep = ts_epoch(last["timestamp"])
+ answered_ep = None
+ if SEND_LOG and inbound_ep is not None:
+ for mj in members:
+ se = SEND_LOG.get(mj)
+ if se is not None and se > inbound_ep + 30: # 30s tolerance
+ answered_ep = se if (answered_ep is None or se > answered_ep) else answered_ep
+ if answered_ep is not None:
+ item["last_from_me"] = True
+ item["reconciled"] = "answered via send-log (reply sent, not yet in store)"
+ out["waiting"].append(item)
+ else:
+ out["needs_reply"].append(item)
# Group chats — surface recent ones for the skill to scan for @mentions /
# direct questions. Provisional status from last-message direction only.
diff --git a/claude-ops/skills/ops-inbox/SKILL.md b/claude-ops/skills/ops-inbox/SKILL.md
index fdccf657..4c397899 100644
--- a/claude-ops/skills/ops-inbox/SKILL.md
+++ b/claude-ops/skills/ops-inbox/SKILL.md
@@ -97,6 +97,12 @@ Before executing, load available context:
**0c. Voice notes are first-class.** Incoming voice notes (`media_type='audio'`, empty `content`) are auto-transcribed into `content` as `[voice] <text>` by the `whatsapp-transcribe.timer` (systemd-user, every 10 min, OpenAI `whisper-1`) — and `wa-inbox-fresh.sh` triggers a transcribe pass on every scan. So a voice note shows up in NEEDS_REPLY / thread scans exactly like a text message; treat a `[voice] …` body as the sender's words. Transcription is idempotent (only ever fills empty audio rows, never clobbers real text) and capped per run, so it never re-bills or stacks.
+ **0d. The scan engine self-refreshes + self-reconciles on EVERY run — this is automatic, you do not orchestrate it.** `bin/ops-inbox-scan` (the primary classifier, step "Scan engine" below) now does the refresh/pull itself, BLOCKING and bounded, before it classifies — so the data is converged by the time you read its JSON, regardless of whether the background `ops-inbox-autosync` hook has finished. On each invocation the scan:
+ - **Refreshes (frontfill/backfill):** if the bridge is reachable on `:8080`, it fires `POST /api/backfill` + `link_contacts.py`, then **waits (bounded ~18s) for the newest stored message timestamp to stop advancing** so the classify pass reads a settled store. This is the blocking guarantee the background hook alone does NOT give. Skip with `OIS_NO_REFRESH=1` (set automatically on repeat calls in one session to avoid re-waiting).
+ - **Reconciles outbound sends (Sam directive 2026-06-05 "include all things I sent to all people"):** it reads the bridge's outbound-send journal (`journalctl --user -u whatsapp-bridge.service`, or the bridge log file on non-systemd hosts) into a `{recipient_jid → latest_send_epoch}` map, and **demotes any NEEDS_REPLY thread whose last inbound is older than a send to any of that person's JIDs** (`reconciled` flag set, moved to WAITING). This catches replies that went out via `/api/send` or a phone send that has not yet landed in `messages.db` — the single most common false-NEEDS_REPLY. Only epoch-stamped send lines drive demotion (a send that genuinely predates the inbound never demotes).
+
+ Net effect: running `/ops:ops-inbox` autonomously pulls the latest state AND folds in everything the user already sent, with **zero extra orchestration on your part** — just read the scan JSON. A `reconciled` field on a WAITING item means "already answered, reply not yet in the store"; never re-draft it. You still clear the FULL-THREAD AWARENESS GATE on whatever genuine NEEDS_REPLY candidates remain.
+
1. **Self-heal plugin version pin** — if any `${CLAUDE_PLUGIN_DATA_DIR}` file or `~/.claude/plugins/installed_plugins.json` references a `cache/ops-marketplace/ops/X.Y.Z/` path that no longer exists on disk, downstream hooks (`stop-all.sh`, `ops-post-session-cleanup`) emit `Plugin directory does not exist`. Resolve before scanning:
```bash
INSTALLED="$HOME/.claude/plugins/installed_plugins.json"