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
ops-inbox: autonomy upgrade — tone/lang match, cross-channel dedup, snooze intelligence, safe chores, offline contact registry (#626)
Aurora Capital7e449edd913f
diff --git a/claude-ops/bin/ops-contact-registry b/claude-ops/bin/ops-contact-registrynew file mode 100755index 00000000..bae5ae35--- /dev/null+++ b/claude-ops/bin/ops-contact-registry@@ -0,0 +1,321 @@+#!/usr/bin/env python3+# ops-contact-registry — build & query an offline cross-channel contact registry.+#+# WHY: scans, the FULL-CONTEXT-RECALL dedup, and TONE matching all need to know+# *who* a sender / number / JID actually is, across channels, without paying for+# live lookups every time. This builds one JSON file keyed by person that merges:+# - WhatsApp : messages.db `contacts` (jid,name,phone) + whatsapp.db+# `whatsmeow_lid_map` (lid<->pn) so a person's @lid and phone JIDs+# collapse to one record.+# - ops-memories: contact_*.md → context blurb, tone, plus any emails / phones /+# slack ids mentioned in the note.+# - Gmail : (optional, --with-gmail) frequent correspondents' addresses.+# - Slack : (optional, --with-slack) user id <-> name, when SLACK_* present.+#+# It is READ-ONLY reference data: it never sends, archives, or mutates a channel.+#+# USAGE:+# ops-contact-registry build [--with-gmail] [--with-slack] [--out PATH]+# ops-contact-registry lookup "<name|email|phone|jid|lid>" # JSON record(s)+# ops-contact-registry stats+#+# OUTPUT registry record shape:+# { "name", "emails":[], "phones":[], "wa_jid", "wa_lid", "slack_id",+# "last_channel", "context", "tone", "sources":[] }+#+# The registry path defaults to+# ${CLAUDE_PLUGIN_DATA_DIR:-~/.claude/plugins/data/ops-ops-marketplace}/contact-registry.json++import json, os, re, sqlite3, sys, subprocess, glob++HOME = os.path.expanduser("~")+DATA_DIR = os.environ.get("CLAUDE_PLUGIN_DATA_DIR",+ os.path.join(HOME, ".claude/plugins/data/ops-ops-marketplace"))+BRIDGE = os.environ.get("WHATSAPP_BRIDGE_DIR",+ os.path.join(HOME, ".local/share/whatsapp-mcp/whatsapp-bridge"))+MSGDB = os.environ.get("WHATSAPP_BRIDGE_DB", os.path.join(BRIDGE, "store/messages.db"))+WADB = os.path.join(BRIDGE, "store/whatsapp.db")+MEM_DIR = os.path.join(DATA_DIR, "memories")+DEFAULT_OUT = os.path.join(DATA_DIR, "contact-registry.json")++EMAIL_RE = re.compile(r"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}", re.I)+PHONE_RE = re.compile(r"\+?\d[\d ()\-]{7,}\d")+SLACKID_RE = re.compile(r"\b[UW][A-Z0-9]{6,}\b")+++def ro(path):+ """Open sqlite read-only/immutable; None if absent."""+ if not os.path.exists(path):+ return None+ try:+ return sqlite3.connect(f"file:{path}?mode=ro&immutable=1", uri=True, timeout=5)+ except sqlite3.Error:+ try:+ return sqlite3.connect(path, timeout=5)+ except sqlite3.Error:+ return None+++def norm_phone(p):+ if not p:+ return ""+ d = re.sub(r"[^\d]", "", str(p))+ return d+++def merge_into(rec, **kw):+ for k, v in kw.items():+ if not v:+ continue+ if isinstance(rec.get(k), list):+ for item in (v if isinstance(v, list) else [v]):+ if item and item not in rec[k]:+ rec[k].append(item)+ elif not rec.get(k):+ rec[k] = v+++def new_record(name=""):+ return {"name": name or "", "emails": [], "phones": [], "wa_jid": "",+ "wa_lid": "", "slack_id": "", "last_channel": "", "context": "",+ "tone": "", "sources": []}+++def build(with_gmail=False, with_slack=False, out=DEFAULT_OUT):+ # key people by normalized phone when we have one, else by jid/name.+ by_phone = {} # phone -> record+ records = [] # records with no phone key++ def rec_for_phone(phone):+ ph = norm_phone(phone)+ if ph and ph in by_phone:+ return by_phone[ph]+ r = new_record()+ if ph:+ by_phone[ph] = r+ else:+ records.append(r)+ return r++ # ---- WhatsApp lid<->pn map (so @lid and phone collapse) ----+ lid_to_pn, pn_to_lid = {}, {}+ wac = ro(WADB)+ if wac:+ try:+ for lid, pn in wac.execute("SELECT lid, pn FROM whatsmeow_lid_map"):+ if lid and pn:+ lid_to_pn[str(lid)] = str(pn)+ pn_to_lid[str(pn)] = str(lid)+ except sqlite3.Error:+ pass+ wac.close()++ # ---- WhatsApp contacts ----+ mc = ro(MSGDB)+ wa_n = 0+ if mc:+ try:+ rows = mc.execute(+ "SELECT jid, name, phone FROM contacts WHERE name IS NOT NULL AND name!=''").fetchall()+ except sqlite3.Error:+ rows = []+ for jid, name, phone in rows:+ jid = str(jid or "")+ phone = phone or (jid.split("@")[0] if jid.endswith("@s.whatsapp.net") else "")+ r = rec_for_phone(phone)+ merge_into(r, name=name, sources="whatsapp")+ if not r["name"]:+ r["name"] = name+ if phone:+ merge_into(r, phones=norm_phone(phone))+ if jid.endswith("@lid"):+ r["wa_lid"] = jid+ pn = lid_to_pn.get(jid.split("@")[0])+ if pn:+ merge_into(r, phones=norm_phone(pn))+ elif jid.endswith("@s.whatsapp.net"):+ r["wa_jid"] = jid+ lid = pn_to_lid.get(jid.split("@")[0])+ if lid:+ r["wa_lid"] = lid + "@lid"+ r["last_channel"] = r["last_channel"] or "whatsapp"+ wa_n += 1+ mc.close()++ # ---- ops-memories enrichment (context, tone, extra ids) ----+ mem_n = 0+ for f in glob.glob(os.path.join(MEM_DIR, "contact_*.md")):+ try:+ body = open(f, encoding="utf-8", errors="ignore").read()+ except OSError:+ continue+ emails = list(dict.fromkeys(m.lower() for m in EMAIL_RE.findall(body)))+ phones = list(dict.fromkeys(norm_phone(m) for m in PHONE_RE.findall(body) if len(norm_phone(m)) >= 9))+ slack = SLACKID_RE.findall(body)+ # name = first markdown heading or filename slug+ mname = re.search(r"^#\s+(.+)$", body, re.M)+ name = (mname.group(1).strip() if mname+ else os.path.basename(f)[len("contact_"):-3].replace("_", " ").title())+ # context = first non-heading paragraph; tone = a line mentioning tone/voice+ ctx = ""+ for line in body.splitlines():+ s = line.strip()+ if s and not s.startswith("#"):+ ctx = s[:240]+ break+ tone = ""+ for line in body.splitlines():+ if re.search(r"tone|toon|voice|stijl|register|emoji", line, re.I):+ tone = line.strip()[:200]+ break+ # attach to an existing record by phone/email, else new+ target = None+ for ph in phones:+ if ph in by_phone:+ target = by_phone[ph]+ break+ if target is None:+ target = new_record(name)+ records.append(target)+ for ph in phones:+ by_phone[ph] = target+ merge_into(target, name=name, emails=emails, phones=phones,+ slack_id=(slack[0] if slack else ""), context=ctx, tone=tone,+ sources="memory")+ mem_n += 1++ # ---- optional Gmail frequent correspondents ----+ gm_n = 0+ if with_gmail:+ acct = os.environ.get("GMAIL_ACCOUNT", "")+ cmd = ["gog", "gmail", "search", "in:anywhere newer_than:120d",+ "-j", "--results-only", "--no-input", "--max", "300"]+ if acct:+ cmd[2:2] = ["-a", acct]+ try:+ p = subprocess.run(cmd, capture_output=True, text=True, timeout=60)+ data = json.loads(p.stdout) if p.stdout.strip() else []+ rows = data if isinstance(data, list) else data.get("results", [])+ for r in rows or []:+ for hdr in (r.get("from", ""), r.get("to", "")):+ for em in EMAIL_RE.findall(hdr or ""):+ em = em.lower()+ # attach to a record whose name appears in the header, else skip-create+ name_m = re.sub(r"<[^>]+>", "", hdr).strip().strip('"') if hdr else ""+ tgt = None+ for rec in list(by_phone.values()) + records:+ if rec["name"] and name_m and rec["name"].lower() in name_m.lower():+ tgt = rec+ break+ if tgt is None:+ tgt = new_record(name_m or em.split("@")[0])+ records.append(tgt)+ merge_into(tgt, emails=em, sources="gmail")+ tgt["last_channel"] = tgt["last_channel"] or "email"+ gm_n += 1+ except (subprocess.SubprocessError, json.JSONDecodeError, OSError):+ pass++ # ---- optional Slack users ----+ sl_n = 0+ if with_slack:+ tok = os.environ.get("SLACK_MCP_XOXC_TOKEN") or os.environ.get("SLACK_BOT_TOKEN") or ""+ if tok:+ try:+ import urllib.request+ req = urllib.request.Request(+ "https://slack.com/api/users.list?limit=200",+ headers={"Authorization": f"Bearer {tok}"})+ resp = json.loads(urllib.request.urlopen(req, timeout=20).read())+ for m in resp.get("members", []):+ if m.get("deleted") or m.get("is_bot"):+ continue+ prof = m.get("profile", {})+ name = prof.get("real_name") or m.get("name", "")+ email = (prof.get("email") or "").lower()+ tgt = None+ if email:+ for rec in list(by_phone.values()) + records:+ if email in rec["emails"]:+ tgt = rec+ break+ if tgt is None:+ tgt = new_record(name)+ records.append(tgt)+ merge_into(tgt, name=name, emails=email, slack_id=m.get("id", ""),+ sources="slack")+ sl_n += 1+ except Exception:+ pass++ allrecs = list(by_phone.values()) + records+ # de-dup identical-name records that share a phone/email already handled by keys.+ out_obj = {+ "generated_at": __import__("datetime").datetime.now().astimezone().isoformat(),+ "count": len(allrecs),+ "sources": {"whatsapp": wa_n, "memory": mem_n, "gmail": gm_n, "slack": sl_n},+ "contacts": sorted(allrecs, key=lambda r: (r.get("name") or "").lower()),+ }+ os.makedirs(os.path.dirname(out), exist_ok=True)+ tmp = out + ".tmp"+ with open(tmp, "w", encoding="utf-8") as fh:+ json.dump(out_obj, fh, ensure_ascii=False, indent=1)+ os.replace(tmp, out)+ print(json.dumps({"ok": True, "out": out, "count": out_obj["count"],+ "sources": out_obj["sources"]}, ensure_ascii=False))+++def _load(out=DEFAULT_OUT):+ if not os.path.exists(out):+ sys.stderr.write(f"registry not built yet: {out}\nrun: ops-contact-registry build\n")+ sys.exit(3)+ return json.load(open(out, encoding="utf-8"))+++def lookup(query, out=DEFAULT_OUT):+ reg = _load(out)+ q = query.lower().strip()+ qd = norm_phone(query)+ hits = []+ for r in reg["contacts"]:+ hay = " ".join([r.get("name", ""), " ".join(r.get("emails", [])),+ r.get("wa_jid", ""), r.get("wa_lid", ""), r.get("slack_id", "")]).lower()+ phones = "".join(r.get("phones", []))+ if (q and q in hay) or (qd and len(qd) >= 6 and qd in phones):+ hits.append(r)+ print(json.dumps({"query": query, "count": len(hits), "matches": hits[:25]},+ ensure_ascii=False, indent=1))+++def stats(out=DEFAULT_OUT):+ reg = _load(out)+ print(json.dumps({"count": reg["count"], "sources": reg["sources"],+ "generated_at": reg["generated_at"]}, ensure_ascii=False))+++def main(argv):+ if not argv:+ sys.stderr.write(__doc__ or "usage: build | lookup <q> | stats\n")+ sys.exit(2)+ cmd, rest = argv[0], argv[1:]+ out = DEFAULT_OUT+ if "--out" in rest:+ i = rest.index("--out")+ out = rest[i + 1]+ del rest[i:i + 2]+ if cmd == "build":+ build(with_gmail=("--with-gmail" in rest), with_slack=("--with-slack" in rest), out=out)+ elif cmd == "lookup":+ if not rest:+ sys.stderr.write("usage: ops-contact-registry lookup <name|email|phone|jid>\n")+ sys.exit(2)+ lookup(" ".join(rest), out=out)+ elif cmd == "stats":+ stats(out=out)+ else:+ sys.stderr.write(f"unknown command: {cmd}\n")+ sys.exit(2)+++if __name__ == "__main__":+ main(sys.argv[1:])diff --git a/claude-ops/bin/ops-inbox-scan b/claude-ops/bin/ops-inbox-scanindex 167aafb6..864ef611 100755--- a/claude-ops/bin/ops-inbox-scan+++ b/claude-ops/bin/ops-inbox-scan@@ -443,6 +443,35 @@ def scan_whatsapp():return out# ------------------------------------------------------------------- Email ----+# Protected todo/action labels — an email carrying any of these is a user-tracked+# open task and MUST NEVER be archived until verified done (see the HARD GUARDRAIL+# in ops-inbox SKILL.md). Match by normalized label NAME (gog returns names, which+# we upper() before comparing). System labels are excluded.+SYSTEM_LABELS = {"INBOX", "SENT", "DRAFT", "UNREAD", "IMPORTANT", "STARRED",+ "TRASH", "SPAM", "CHAT", "FYI"}+def _norm_label(l):+ return re.sub(r"[^A-Z0-9]+", " ", str(l).upper()).strip()+# substring signals (normalized) that imply an open task+PROTECTED_SUBSTRINGS = (+ "TO RESPOND", "RESPOND", "REPLY LATER", "REPLY", "NEEDS ACTION", "ACTION",+ "FOLLOW UP", "FOLLOWUP", "AWAITING REPLY", "TO DO", "TODO", "TASKLET",+ "TASK", "TIMED ACTIONS",+)+# a 'done/completed' label clears protection even if a stale todo label lingers+COMPLETION_SUBSTRINGS = ("ACTIONED", "DONE", "COMPLETED", "RESOLVED", "HANDLED", "ARCHIVED")+def protected_todo_labels(labels):+ """Return the list of protected todo/action labels on a message (empty if none/done)."""+ hits, done = [], False+ for raw in labels or []:+ if str(raw).upper() in SYSTEM_LABELS or str(raw).upper().startswith("CATEGORY_"):+ continue+ n = _norm_label(raw)+ if any(c in n for c in COMPLETION_SUBSTRINGS):+ done = True+ if any(s in n for s in PROTECTED_SUBSTRINGS):+ hits.append(str(raw))+ return [] if done else hits+def from_email_addr(header):"""Bare address from a From header (exact match; avoids substring false positives)."""if not header:@@ -482,6 +511,15 @@ def scan_email():"date": r.get("date"),"labels": labels,}+ # HARD GUARDRAIL: a protected todo/action label pins this to KEEP, never archive.+ prot = protected_todo_labels(r.get("labels") or r.get("labelIds") or [])+ if prot:+ item["protected_todo"] = True+ item["protected_labels"] = prot+ item["note"] = ("KEEP — carries todo/action label(s) " + ", ".join(prot) ++ "; never archive until verified done")+ res["needs_reply"].append(item) # surface as actionable, never FYI/archive+ continueis_sent_last = ("SENT" in labels) or (self_addr and self_addr == from_email_addr(frm))promo = any(l in labels for l in ("CATEGORY_PROMOTIONS", "CATEGORY_SOCIAL","CATEGORY_UPDATES", "CATEGORY_FORUMS"))diff --git a/claude-ops/skills/ops-inbox/SKILL.md b/claude-ops/skills/ops-inbox/SKILL.mdindex f25ad4f5..b0bb97d0 100644--- a/claude-ops/skills/ops-inbox/SKILL.md+++ b/claude-ops/skills/ops-inbox/SKILL.md@@ -646,6 +646,70 @@ The user does NOT remember every thread. For EVERY message you present, you MUST- **HANDLED** — conversation concluded, can be archived- **FYI** — newsletters, notifications, automated messages (bulk archive)+## Core principle: TONE & LANGUAGE MATCH (every draft, every channel)++A reply that is correct but in the wrong voice is a defect. Before drafting on any channel:++1. **Language follows the thread, not your default.** Reply in the language the user actually uses **with that specific contact** — Dutch with Dutch contacts, English with English contacts, etc. Detect it from the thread history (the user's own `is_from_me`/SENT messages in this thread), never from your locale. For a shared-audience group/thread, match the thread's common language, not one participant's.+2. **Match the user's register with this contact.** Read the user's own prior messages in the thread for: formality (jij/u, first-name vs formal), greeting/sign-off style, emoji density (default sparse — often zero; never add emoji the user doesn't use), sentence length, and any pet phrases. Mirror it. A casual one-liner contact gets a casual one-liner; a formal business contact gets formal prose.+3. **Honour stored contact tone.** Check `~/.claude/plugins/data/ops-ops-marketplace/memories/contact_*.md` and the contact registry (below) for a recorded tone profile and apply it verbatim (e.g. partner threads: warm, short, no business framing).+4. **Never restate known context back at the contact** and never sound like an AI assistant — write as the user would.++## Core principle: FULL-CONTEXT RECALL + CROSS-CHANNEL / ALREADY-SENT DEDUP++The single most damaging error is replying to something the user already handled — in this thread, in another thread, in a group, on another channel, or by phone/voice that never landed in the store. Before confirming ANY NEEDS_REPLY or drafting:++1. **Same-thread recheck** — scan the full thread both directions (incl. `[voice]`/`[image]`/`[document]` enrichments). If the user replied after the last inbound, it is WAITING/HANDLED.+2. **Cross-thread, same person** — the user may have answered the same person on their other JID (lid↔phone), in a group both are in, or a secondary number. Search the contact across threads (`mcp__whatsapp__list_messages {query, limit:25}`, `is_from_me:true` after the inbound timestamp).+3. **Cross-channel** — the user may have answered the email by WhatsApp, or the WhatsApp by email/iMessage. For a NEEDS_REPLY candidate, search the OTHER channels for a recent outbound to the same person/topic: `gog gmail search "to:<addr> newer_than:3d"`, `mcp__whatsapp__list_messages {query:"<name|topic>"}`, iMessage `chat_messages`. A hit → reclassify HANDLED.+4. **Already-sent (email)** — a reply sent from another client may not be the thread's last message in the envelope first-pass. Open the thread (`gog gmail thread get`) and check for a SENT message after the last inbound before classifying NEEDS_REPLY.+5. **Use the contact registry** (below) to resolve who a sender/number/JID actually is and pull their cross-channel identity + context in one offline lookup, so step 2–3 searches are precise.+6. **Trust the user's word over the store** — if the user says they replied, it is HANDLED even if the store doesn't show it.++Only after 1–5 come up empty is a thread a true NEEDS_REPLY. This is the FULL-THREAD AWARENESS GATE, extended cross-channel.++## Core principle: SNOOZE & FOLLOW-UP INTELLIGENCE (never let the user lose a thread)++Cleanup must never silently drop something the user still owes or is owed. Archiving WAITING is safe **only** because new inbound auto-resurfaces it — but a thread where the ball is in the user's court, or where the other side has gone quiet on something the user needs, must be **snoozed with a reminder**, not just archived-and-forgotten.++When cleaning up, classify each non-NEEDS_REPLY item one more level:++- **USER-OWES (todo)** — the user promised an action ("ik pak het vanavond op", "I'll resend the env file", "stuur ik je"), or a meeting-note / email assigned the user a task. → **KEEP visible** and schedule a follow-up reminder. Never archive an unfulfilled user commitment.+- **AWAITING-OTHER, time-sensitive** — the user is waiting on a reply tied to a deadline/deal. → archive (auto-resurfaces) **but** set a nudge reminder if no response by a sensible horizon (default 3 days) so the user can chase.+- **CONCLUDED** — courtesy close, social tail, fully-answered. → archive, no reminder.++**Scheduling reminders (a safe, non-outbound chore — do autonomously):** use `CronCreate` (one-shot, `recurring:false`) for each USER-OWES / nudge item. The reminder prompt should name the contact, the owed action, and the source thread, e.g. *"Reminder: you told Twan you'd handle Dennis's email tonight — follow up (WhatsApp 31642218102)."* Pick a sensible fire time (same evening for "tonight", +3d for nudges). Reminders fire to the user; they are NOT outbound third-party comms, so no approval gate applies.++**Meeting-note / assigned-todo capture:** when an email or message contains action items assigned to the user (meeting recaps, "can you…", "actie Sam:"), extract them and schedule reminders so they are never lost — even if the thread itself is then archived. Surface the extracted todos in the run summary.++## Core principle: SAFE AUTONOMOUS CHORES (do these without asking)++The user wants chores handled autonomously. A **chore** is a low-risk action with **no decision, no commitment, no approval, and no uncertainty**. Do these in the cleanup pass without prompting:++- **Archive things clearly already replied to / concluded** (per the dedup principle).+- **Schedule reminders / snoozes** for USER-OWES and nudge items (`CronCreate`, non-outbound).+- **Reconnect / re-auth integrations** that have a known, automatable flow (e.g. a "reconnect your X" nudge where the repair is a scripted browser/OAuth step you've done before) — verify success, report it.+- **Forward simple receipts / invoices** to a pre-configured destination (e.g. the accountant) **only when that routing is already established** in preferences/memories — this is a fixed-destination chore, not a new outbound decision.+- **Mark-read / label hygiene** (move concluded items, apply `Actioned`).++**Hard limits on "autonomous" — these are NOT chores and still gate:**++- **Any new outbound message to a third party** (a reply, an ack, a "got it 👍", a forward to a new recipient) is covered outbound comms → Rule 6: stage ONE draft, get explicit per-message approval, then send. The `block-outbound-comms.py` hook enforces this with a single-use token regardless of flags — do not attempt to bypass it. "Ack all" still means "stage each ack for one-tap approval", because an ack is an outbound message.+- Anything involving a **decision, a commitment, money, legal/medical content, or any uncertainty** → surface to the user, do not act.++When in doubt whether something is a chore, it is not — surface it.++## Contact registry (offline cross-channel identity + context)++`bin/ops-contact-registry` builds and reads a single offline JSON registry that maps every known person to their cross-channel identities and a short context blurb — so scans resolve names instantly and the dedup/tone principles have ground truth without live lookups.++- **Build / refresh:** `bin/ops-contact-registry build` — merges WhatsApp `contacts.db` (+ `whatsmeow_lid_map` for lid↔phone), Gmail frequent senders, and Slack users (when configured) into `${CLAUDE_PLUGIN_DATA_DIR}/contact-registry.json`. Idempotent; safe to run on every inbox pass (cheap, offline). Enriches with ops-memories `contact_*.md` context + recorded tone.+- **Lookup:** `bin/ops-contact-registry lookup "<name|email|phone|jid>"` → the merged record `{name, emails[], phones[], wa_jid, wa_lid, slack_id, last_channel, context, tone}`. Use it to resolve a sender/number/JID and to drive the cross-channel dedup search precisely.+- **During a scan:** prefer the registry for name resolution before falling back to `contacts.db` → chat `name` → giga. Use the merged identities to search the SAME person across channels for already-sent dedup.++The registry is read-only reference data — never a send surface.++## Channel availability + fallbackFor each channel, detect availability at runtime: