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
feat(ops-pocket): Layer 2 cloud webhook receiver + auto-dispatch (#341)
Aurora Capital4be65280a11f
diff --git a/claude-ops/scripts/ops-pocket-layer2-dispatcher.py b/claude-ops/scripts/ops-pocket-layer2-dispatcher.pynew file mode 100644index 00000000..f2caaffd--- /dev/null+++ b/claude-ops/scripts/ops-pocket-layer2-dispatcher.py@@ -0,0 +1,295 @@+#!/usr/bin/env python3+"""ops-pocket-layer2-dispatcher — Local queue consumer for Layer 2.++Reads new rows from $POCKET_QUEUE_PATH (JSONL written by the Render webhook+receiver, synced to this machine), dispatches a Claude subagent per task, then+stages a WhatsApp/email notification draft for Sam's approval.++Designed to run from cron (every 5 min) or on-demand. Uses the same+once.sh-style lock pattern to prevent stacking.++Env vars:+ POCKET_QUEUE_PATH Path to pocket_queue.jsonl (required)+ POCKET_DISPATCHER_CURSOR Cursor file path (default: alongside queue file)+ POCKET_DISPATCHER_LOCK Exclusive lock file (default: cursor path + ".lock")+ POCKET_NOTIFY_CHANNEL "whatsapp" | "email" | "both" (default: whatsapp)+ POCKET_WA_JID WhatsApp JID for self-chat notifications+ POCKET_EMAIL_TO Email address for notifications+ ANTHROPIC_API_KEY For subagent dispatch (auto from keychain if unset)+ POCKET_DRY_RUN=1 Log dispatch intent without actually spawning agents+"""++from __future__ import annotations++import fcntl+import json+import logging+import os+import subprocess+import sys+import tempfile+from datetime import datetime, timezone+from pathlib import Path++log = logging.getLogger("pocket-dispatcher")+logging.basicConfig(+ level=os.environ.get("LOG_LEVEL", "INFO"),+ format="%(asctime)s %(levelname)s %(message)s",+)++# ---------------------------------------------------------------------------+# Config+# ---------------------------------------------------------------------------++QUEUE_PATH = Path(os.environ.get("POCKET_QUEUE_PATH", str(Path.home() / ".claude/state/pocket/pocket_queue.jsonl")))+CURSOR_PATH = Path(os.environ.get("POCKET_DISPATCHER_CURSOR", str(QUEUE_PATH.parent / "pocket_queue.cursor")))+LOCK_PATH = Path(os.environ.get("POCKET_DISPATCHER_LOCK", str(CURSOR_PATH) + ".lock"))+NOTIFY_CHANNEL = os.environ.get("POCKET_NOTIFY_CHANNEL", "whatsapp")+WA_JID = os.environ.get("POCKET_WA_JID", "")+EMAIL_TO = os.environ.get("POCKET_EMAIL_TO", "")+DRY_RUN = os.environ.get("POCKET_DRY_RUN", "0") == "1"++# ---------------------------------------------------------------------------+# Skill tags → subagent prompt templates+# ---------------------------------------------------------------------------++SKILL_PROMPTS: dict[str, str] = {+ "calendar": (+ "You are handling a calendar/scheduling task from a Pocket voice memo. "+ "Parse the action items, create or update calendar events as needed, "+ "then write a concise completion report to stdout."+ ),+ "code": (+ "You are handling a code/engineering task from a Pocket voice memo. "+ "Implement the requested change, run tests, open a PR if appropriate, "+ "then write a concise completion report to stdout."+ ),+ "research": (+ "You are handling a research task from a Pocket voice memo. "+ "Use Tavily + Context7 to gather the requested information, "+ "then write a concise summary report to stdout."+ ),+ "general": (+ "You are handling a general task from a Pocket voice memo. "+ "Complete the requested action and write a concise completion report to stdout."+ ),+}++# ---------------------------------------------------------------------------+# Cursor — byte-offset into JSONL so we never re-process+# ---------------------------------------------------------------------------++def _read_cursor() -> int:+ try:+ return int(CURSOR_PATH.read_text().strip())+ except (FileNotFoundError, ValueError):+ return 0+++def _write_cursor(offset: int) -> None:+ CURSOR_PATH.write_text(str(offset))+++# ---------------------------------------------------------------------------+# Subagent dispatch+# ---------------------------------------------------------------------------++def _dispatch_subagent(task: dict) -> str | None:+ """Spawn a background claude subagent. Returns task_id or None on error."""+ if DRY_RUN:+ log.info("[DRY_RUN] would dispatch skill=%s recording_id=%s", task["skill"], task["recording_id"])+ return task["recording_id"]++ skill = task.get("skill", "general")+ system_prompt = SKILL_PROMPTS.get(skill, SKILL_PROMPTS["general"])++ action_items_text = "\n".join(f"- {ai}" for ai in task.get("action_items", []))+ user_prompt = (+ f"<task>\n"+ f"Recording ID: {task['recording_id']}\n"+ f"Title: {task.get('title', 'Untitled')}\n"+ f"Summary: {task.get('summary', '')}\n"+ f"Action items:\n{action_items_text or '(none extracted)'}\n"+ f"Transcript snippet: {task.get('transcript_snippet', '')}\n"+ f"</task>\n\n"+ f"Complete the task above and report back."+ )++ # Write prompt to temp file, invoke claude --bg+ with tempfile.NamedTemporaryFile(mode="w", suffix=".md", delete=False) as f:+ f.write(user_prompt)+ prompt_file = f.name++ tag = f"pocket-{task['recording_id'][:12]}"+ cmd = [+ "claude", "--bg",+ "--system", system_prompt,+ "--print", prompt_file,+ "--output-format", "text",+ ]++ try:+ result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)+ if result.returncode != 0:+ log.error("claude --bg failed: %s", result.stderr[:500])+ return None+ log.info("dispatched subagent tag=%s recording_id=%s", tag, task["recording_id"])+ return task["recording_id"]+ except subprocess.TimeoutExpired:+ log.error("claude --bg timed out for recording_id=%s", task["recording_id"])+ return None+ except FileNotFoundError:+ log.error("claude binary not found — is Claude Code on PATH?")+ return None+ finally:+ Path(prompt_file).unlink(missing_ok=True)+++# ---------------------------------------------------------------------------+# Notification draft (respects outbound-comms guardrail — staged, not sent)+# ---------------------------------------------------------------------------++def _stage_notification(task: dict, dispatched: bool) -> None:+ """Write a staged notification draft to the out-queue; does NOT send."""+ status_word = "dispatched" if dispatched else "FAILED to dispatch"+ body = (+ f"[Pocket] {status_word}: {task.get('title', task['recording_id'])}\n"+ f"Skill: {task.get('skill', 'general')}\n"+ f"Event: {task.get('event', '')}\n"+ f"Recording: {task['recording_id']}"+ )++ staged_at = datetime.now(timezone.utc).isoformat()++ def _draft_row(kind: str, to_addr: str) -> dict:+ return {+ "kind": kind,+ "to": to_addr,+ "body": body,+ "recording_id": task["recording_id"],+ "staged_at": staged_at,+ "requires_approval": True, # outbound-comms guardrail+ }++ if NOTIFY_CHANNEL == "email":+ rows = [_draft_row("email", EMAIL_TO)]+ elif NOTIFY_CHANNEL == "both":+ rows = [_draft_row("whatsapp", WA_JID), _draft_row("email", EMAIL_TO)]+ else:+ rows = [_draft_row("whatsapp", WA_JID)]++ draft_path = QUEUE_PATH.parent / "pocket_notify_drafts.jsonl"+ with draft_path.open("a") as f:+ for row in rows:+ f.write(json.dumps(row) + "\n")+ log.info(+ "staged %d notification draft(s) for recording_id=%s",+ len(rows),+ task["recording_id"],+ )+++# ---------------------------------------------------------------------------+# Main+# ---------------------------------------------------------------------------++def main() -> int:+ LOCK_PATH.parent.mkdir(parents=True, exist_ok=True)+ lock_file = LOCK_PATH.open("a+")+ try:+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)+ except BlockingIOError:+ log.info("lock held — another dispatcher is running, exiting")+ lock_file.close()+ return 0++ try:+ return _dispatch_main()+ finally:+ try:+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)+ finally:+ lock_file.close()+++def _dispatch_main() -> int:+ if not QUEUE_PATH.exists():+ log.info("queue not found at %s — nothing to process", QUEUE_PATH)+ return 0++ cursor = _read_cursor()+ new_cursor = cursor+ processed = 0+ errors = 0++ try:+ size = QUEUE_PATH.stat().st_size+ except OSError as exc:+ log.error("stat queue failed: %s", exc)+ return 1++ if cursor > size:+ log.warning(+ "cursor %d > queue size %d (queue truncated or replaced); resetting cursor to 0",+ cursor,+ size,+ )+ cursor = 0+ new_cursor = 0++ if cursor >= size:+ log.info("cursor at EOF — nothing new (cursor=%d size=%d)", cursor, size)+ return 0++ with QUEUE_PATH.open("rb") as f:+ f.seek(cursor)+ while True:+ line_start = f.tell()+ raw = f.readline()+ if not raw:+ break+ if not raw.endswith(b"\n"):+ break+ line_end = f.tell()+ line = raw.decode().strip()+ if not line:+ new_cursor = line_end+ continue+ try:+ task = json.loads(line)+ except json.JSONDecodeError as exc:+ log.warning("bad JSONL line @offset=%d: %s", line_start, exc)+ new_cursor = line_end+ continue++ log.info(+ "processing recording_id=%s event=%s skill=%s",+ task.get("recording_id", "?"),+ task.get("event", "?"),+ task.get("skill", "?"),+ )++ task_id = _dispatch_subagent(task)+ dispatched = task_id is not None+ if dispatched:+ processed += 1+ else:+ errors += 1++ _stage_notification(task, dispatched)+ if dispatched:+ new_cursor = line_end+ else:+ # Rewind so transient claude --bg failures retry on the next run (see ops-pocket-out-queue.py).+ new_cursor = line_start+ break++ if new_cursor != cursor:+ _write_cursor(new_cursor)++ log.info("done — processed=%d errors=%d new_cursor=%d", processed, errors, new_cursor)+ return 0 if errors == 0 else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/claude-ops/skills/ops-pocket/webhook-server/Dockerfile b/claude-ops/skills/ops-pocket/webhook-server/Dockerfilenew file mode 100644index 00000000..b94cbc82--- /dev/null+++ b/claude-ops/skills/ops-pocket/webhook-server/Dockerfile@@ -0,0 +1,15 @@+FROM python:3.12-slim++WORKDIR /app++COPY requirements.txt .+RUN pip install --no-cache-dir -r requirements.txt++COPY main.py .++# Data directory — mount a persistent volume here on Render/ECS+RUN mkdir -p /data++EXPOSE 8000++CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"]diff --git a/claude-ops/skills/ops-pocket/webhook-server/main.py b/claude-ops/skills/ops-pocket/webhook-server/main.pynew file mode 100644index 00000000..60375425--- /dev/null+++ b/claude-ops/skills/ops-pocket/webhook-server/main.py@@ -0,0 +1,249 @@+#!/usr/bin/env python3+"""+ops-pocket Layer 2 — Webhook receiver (FastAPI)++Receives HeyPocket webhook events, deduplicates, and enqueues subagent tasks.++Events handled:+ - summary.completed+ - action_items.regenerated+ - recording.created++Env vars (required):+ POCKET_HMAC_SECRET HMAC-SHA256 signing secret from HeyPocket dashboard+ POCKET_WEBHOOK_URL Public URL of this service (for self-reference in logs)++Env vars (optional):+ POCKET_DB_PATH SQLite path (default: /data/pocket_events.db)+ POCKET_QUEUE_PATH JSONL task queue path (default: /data/pocket_queue.jsonl)+ POCKET_REPLAY_WINDOW Replay attack window in seconds (default: 300)+ LOG_LEVEL default: INFO+"""++from __future__ import annotations++import hashlib+import hmac+import json+import logging+import os+import sqlite3+import time+from contextlib import asynccontextmanager+from datetime import datetime, timezone+from pathlib import Path+from typing import Any++from fastapi import FastAPI, Header, HTTPException, Request, status+from fastapi.responses import JSONResponse++# ---------------------------------------------------------------------------+# Config+# ---------------------------------------------------------------------------++HMAC_SECRET: str = os.environ["POCKET_HMAC_SECRET"]+DB_PATH: Path = Path(os.environ.get("POCKET_DB_PATH", "/data/pocket_events.db"))+QUEUE_PATH: Path = Path(os.environ.get("POCKET_QUEUE_PATH", "/data/pocket_queue.jsonl"))+REPLAY_WINDOW: int = int(os.environ.get("POCKET_REPLAY_WINDOW", "300"))++logging.basicConfig(+ level=os.environ.get("LOG_LEVEL", "INFO"),+ format="%(asctime)s %(levelname)s %(name)s %(message)s",+)+log = logging.getLogger("pocket-webhook")++# ---------------------------------------------------------------------------+# Database — deduplication store+# ---------------------------------------------------------------------------++def _init_db(conn: sqlite3.Connection) -> None:+ conn.execute("""+ CREATE TABLE IF NOT EXISTS events (+ id TEXT NOT NULL,+ event_type TEXT NOT NULL,+ received_at TEXT NOT NULL,+ payload TEXT NOT NULL,+ PRIMARY KEY (id, event_type)+ )+ """)+ conn.commit()+++def _get_db() -> sqlite3.Connection:+ DB_PATH.parent.mkdir(parents=True, exist_ok=True)+ conn = sqlite3.connect(str(DB_PATH))+ _init_db(conn)+ return conn+++# ---------------------------------------------------------------------------+# HMAC verification+# ---------------------------------------------------------------------------++def _verify_signature(body: bytes, signature_header: str | None, ts_header: str | None) -> None:+ """Raises HTTPException 401 if signature invalid or timestamp outside replay window."""+ if not signature_header:+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Missing signature")++ if not ts_header or not ts_header.strip():+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Missing timestamp")++ try:+ ts = int(ts_header.strip())+ except ValueError:+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid timestamp")++ age = abs(time.time() - ts)+ if age > REPLAY_WINDOW:+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail=f"Timestamp outside replay window ({int(age)}s > {REPLAY_WINDOW}s)",+ )++ expected = hmac.new(+ HMAC_SECRET.encode(),+ body,+ hashlib.sha256,+ ).hexdigest()++ sig = signature_header.removeprefix("sha256=")+ if not hmac.compare_digest(expected, sig):+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid signature")+++# ---------------------------------------------------------------------------+# Routing — decide which subagent skill to tag the task with+# ---------------------------------------------------------------------------++_CALENDAR_KEYWORDS = frozenset([+ "calendar", "meeting", "schedule", "appointment", "standup", "call",+ "zoom", "teams", "remind", "reminder", "due date", "deadline",+])+_CODE_KEYWORDS = frozenset([+ "code", "bug", "fix", "pr", "pull request", "deploy", "build",+ "test", "script", "function", "api", "endpoint", "database", "db",+])+_RESEARCH_KEYWORDS = frozenset([+ "research", "look up", "find out", "investigate", "check", "analyse",+ "analyze", "compare", "summarize", "summarise", "report",+])+++def _route_skill(text: str) -> str:+ """Return the skill tag to dispatch based on memory content."""+ lower = text.lower()+ tokens = set(lower.split())++ if tokens & _CALENDAR_KEYWORDS:+ return "calendar"+ if tokens & _CODE_KEYWORDS:+ return "code"+ if tokens & _RESEARCH_KEYWORDS:+ return "research"+ return "general"+++# ---------------------------------------------------------------------------+# Queue writer+# ---------------------------------------------------------------------------++def _enqueue(task: dict[str, Any]) -> None:+ QUEUE_PATH.parent.mkdir(parents=True, exist_ok=True)+ with QUEUE_PATH.open("a") as f:+ f.write(json.dumps(task) + "\n")+ log.info("enqueued task recording_id=%s skill=%s", task["recording_id"], task["skill"])+++# ---------------------------------------------------------------------------+# FastAPI app+# ---------------------------------------------------------------------------++@asynccontextmanager+async def lifespan(app: FastAPI):+ log.info("pocket-webhook Layer 2 starting up — DB=%s QUEUE=%s", DB_PATH, QUEUE_PATH)+ yield+ log.info("pocket-webhook shutting down")+++app = FastAPI(title="pocket-webhook-layer2", lifespan=lifespan)++[email protected]("/health")+async def health() -> JSONResponse:+ return JSONResponse({"status": "ok", "ts": datetime.now(timezone.utc).isoformat()})++[email protected]("/webhook")+async def webhook(+ request: Request,+ x_heypocket_signature: str | None = Header(default=None),+ x_heypocket_timestamp: str | None = Header(default=None),+) -> JSONResponse:+ body = await request.body()++ # 1. Verify HMAC+ _verify_signature(body, x_heypocket_signature, x_heypocket_timestamp)++ # 2. Parse payload+ try:+ payload: dict[str, Any] = json.loads(body)+ except json.JSONDecodeError as exc:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"Invalid JSON: {exc}")++ event_type: str = payload.get("event", "")+ recording: dict[str, Any] = payload.get("recording", {})+ recording_id: str = str(recording.get("id", ""))++ if not recording_id:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Missing recording.id")++ handled_events = {"summary.completed", "action_items.regenerated", "recording.created"}+ if event_type not in handled_events:+ log.info("ignoring event_type=%s recording_id=%s", event_type, recording_id)+ return JSONResponse({"status": "ignored", "event": event_type})++ transcript: str = recording.get("transcript", "") or ""+ summary: str = recording.get("summary", "") or ""+ action_items: list[str] = [+ ai.get("text", "") for ai in payload.get("actionItems", []) if ai.get("text")+ ]+ text_for_routing = " ".join([transcript, summary] + action_items)+ skill = _route_skill(text_for_routing)++ task = {+ "recording_id": recording_id,+ "event": event_type,+ "skill": skill,+ "title": recording.get("title", ""),+ "summary": summary,+ "action_items": action_items,+ "transcript_snippet": transcript[:500] if transcript else "",+ "received_at": datetime.now(timezone.utc).isoformat(),+ }++ conn = _get_db()+ try:+ conn.execute("BEGIN IMMEDIATE")+ cur = conn.execute(+ "INSERT OR IGNORE INTO events (id, event_type, received_at, payload) VALUES (?,?,?,?)",+ (+ recording_id,+ event_type,+ datetime.now(timezone.utc).isoformat(),+ json.dumps(payload),+ ),+ )+ if cur.rowcount == 0:+ conn.rollback()+ log.info("duplicate recording_id=%s event=%s — skipping", recording_id, event_type)+ return JSONResponse({"status": "duplicate"})+ # Enqueue before commit so a failed append rolls back dedup and HeyPocket retries can re-insert.+ _enqueue(task)+ conn.commit()+ except Exception:+ conn.rollback()+ raise+ finally:+ conn.close()++ return JSONResponse({"status": "accepted", "skill": skill, "recording_id": recording_id})diff --git a/claude-ops/skills/ops-pocket/webhook-server/render.yaml b/claude-ops/skills/ops-pocket/webhook-server/render.yamlnew file mode 100644index 00000000..f769bad6--- /dev/null+++ b/claude-ops/skills/ops-pocket/webhook-server/render.yaml@@ -0,0 +1,28 @@+# Render deployment manifest for ops-pocket Layer 2 webhook receiver.+# Deploy: connect this repo to Render, point to this file.+# Persistent disk mounts at /data (SQLite + JSONL queue survive redeploys).++services:+ - type: web+ name: pocket-webhook-layer2+ runtime: docker+ dockerfilePath: ./claude-ops/skills/ops-pocket/webhook-server/Dockerfile+ dockerContext: ./claude-ops/skills/ops-pocket/webhook-server+ region: frankfurt # co-located with dev-sandbox-fra for latency parity+ plan: starter # $7/mo — free tier has no persistent disk+ disk:+ name: pocket-data+ mountPath: /data+ sizeGB: 1+ envVars:+ - key: POCKET_HMAC_SECRET+ sync: false # set manually in Render dashboard (never commit)+ - key: POCKET_WEBHOOK_URL+ fromService:+ type: web+ name: pocket-webhook-layer2+ property: host+ - key: LOG_LEVEL+ value: INFO+ healthCheckPath: /health+ autoDeploy: truediff --git a/claude-ops/skills/ops-pocket/webhook-server/requirements.txt b/claude-ops/skills/ops-pocket/webhook-server/requirements.txtnew file mode 100644index 00000000..784c26e6--- /dev/null+++ b/claude-ops/skills/ops-pocket/webhook-server/requirements.txt@@ -0,0 +1,2 @@+fastapi==0.115.5+uvicorn[standard]==0.32.1