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
fix(security): purge PII from public repo (audit F-001..F-006) (#268)
Aurora Capitala39b40cd217f
diff --git a/claude-ops/bin/ops-marketing-link-prewarm b/claude-ops/bin/ops-marketing-link-prewarmindex ac21e50d..8046f0b3 100755--- a/claude-ops/bin/ops-marketing-link-prewarm+++ b/claude-ops/bin/ops-marketing-link-prewarm@@ -72,7 +72,7 @@ category_mappings() {analytics_ga4)echo "property_id:ga4.property_id"echo "measurement_id:ga4.measurement_id"- echo "api_secret:ga4.api_secret"+ echo "api_secret:ga4.api_secret" # gitleaks:allow — prefs path reference, not a literal secret;;analytics_amplitude)echo "api_key:amplitude.api_key"diff --git a/claude-ops/scripts/com.claude-ops.daemon.plist b/claude-ops/scripts/com.claude-ops.daemon.plistindex aa587f19..6ff8a4fe 100644--- a/claude-ops/scripts/com.claude-ops.daemon.plist+++ b/claude-ops/scripts/com.claude-ops.daemon.plist@@ -32,8 +32,6 @@<string>/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin</string><key>HOME</key><string>__HOME__</string>- <key>CLAUDE_PLUGIN_ROOT</key>- <string>__PLUGIN_ROOT__</string></dict></dict></plist>diff --git a/claude-ops/scripts/install-ops-daemon.sh b/claude-ops/scripts/install-ops-daemon.shindex a5360df5..e5e9e756 100755--- a/claude-ops/scripts/install-ops-daemon.sh+++ b/claude-ops/scripts/install-ops-daemon.sh@@ -25,19 +25,28 @@ if [[ -z "$PLUGIN_ROOT" || ! -d "$PLUGIN_ROOT" ]]; thenfiDAEMON_SCRIPT="$PLUGIN_ROOT/scripts/ops-daemon.sh"+LAUNCHER_SCRIPT="$PLUGIN_ROOT/scripts/ops-daemon-launcher.sh"+LAUNCHER_DEST_DIR="$HOME/.claude/plugins/data/ops-ops-marketplace/bin"+LAUNCHER_DEST="$LAUNCHER_DEST_DIR/ops-daemon-launcher.sh"PLIST_TEMPLATE="$PLUGIN_ROOT/scripts/com.claude-ops.daemon.plist"PLIST_DEST="$HOME/Library/LaunchAgents/com.claude-ops.daemon.plist"DATA_DIR="${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}"LOG_DIR="$DATA_DIR/logs"SERVICES_CONFIG="$DATA_DIR/daemon-services.json"-for f in "$DAEMON_SCRIPT" "$PLIST_TEMPLATE"; do+for f in "$DAEMON_SCRIPT" "$LAUNCHER_SCRIPT" "$PLIST_TEMPLATE"; do[[ -f "$f" ]] || { echo "error: required plugin file not found: $f" >&2; exit 1; }done-mkdir -p "$LOG_DIR"+mkdir -p "$LOG_DIR" "$LAUNCHER_DEST_DIR"chmod +x "$DAEMON_SCRIPT"+# Install the version-agnostic launcher to a stable location outside the+# version-pinned cache dir. The plist points at THIS path forever — the+# launcher itself resolves the latest installed ops version at run time.+cp "$LAUNCHER_SCRIPT" "$LAUNCHER_DEST"+chmod +x "$LAUNCHER_DEST"+# Resolve bash 4+ (required for associative arrays in ops-daemon.sh).# macOS ships bash 3; Homebrew installs bash 5 at /opt/homebrew/bin/bash.BASH_PATH="/bin/bash"@@ -47,10 +56,13 @@ elif [[ -x /usr/local/bin/bash ]]; thenBASH_PATH="/usr/local/bin/bash"fi-# Generate plist from template.-sed -e "s|__DAEMON_SCRIPT_PATH__|$DAEMON_SCRIPT|g" \+# Generate plist from template. Point at the stable launcher path so plugin+# upgrades don't strand the plist on a deleted version dir.+# CLAUDE_PLUGIN_ROOT is intentionally NOT set in the plist — the launcher+# computes it at run time from the latest installed version.+sed -e "s|__DAEMON_SCRIPT_PATH__|$LAUNCHER_DEST|g" \-e "s|__BASH_PATH__|$BASH_PATH|g" \- -e "s|__PLUGIN_ROOT__|$PLUGIN_ROOT|g" \+ -e "s|__PLUGIN_ROOT__||g" \-e "s|__LOG_DIR__|$LOG_DIR|g" \-e "s|__HOME__|$HOME|g" \"$PLIST_TEMPLATE" > "$PLIST_DEST"diff --git a/claude-ops/scripts/ops-cron-pocket-executor.py b/claude-ops/scripts/ops-cron-pocket-executor.pynew file mode 100755index 00000000..739fdd57--- /dev/null+++ b/claude-ops/scripts/ops-cron-pocket-executor.py@@ -0,0 +1,356 @@+#!/usr/bin/env python3+"""ops-cron-pocket-executor — Watchdog for the persistent Pocket supervisor.++Architecture (v2 — Agent Teams):+ • A single long-lived Claude Code session runs in tmux window+ `pocket-exec:supervisor`. It uses Agent Teams (TeamCreate ++ Agent(team_name=...)) to spawn worker teammates per Pocket task.+ • The supervisor reads `tasks.jsonl` directly on each wake (via its own+ cursor file `supervisor-cursor.txt`) and dispatches up to N teammates.+ • This script's only job is to keep that supervisor window alive.++Behaviour each cron tick:+ 1. Ensure tmux session `pocket-exec` exists (with an `_idle` keepalive window).+ 2. Check that `supervisor` window still has a live `claude` process — if+ missing or dead, respawn it from the prompt template.+ 3. Write health heartbeat to `.executor-health`.++What this script does NOT do anymore:+ • Spawning per-task worker windows (the supervisor does that as teammates).+ • Reading tasks.jsonl (the supervisor handles it).++Env:+ POCKET_STATE_DIR default ~/.claude/state/pocket+ POCKET_TMUX_SESSION default pocket-exec+ POCKET_CLAUDE_BIN default $HOME/.local/bin/claude+ POCKET_EXEC_CWD supervisor working dir, default $HOME+ POCKET_SUPERVISOR_PROMPT path to supervisor prompt; default = bundled template+ POCKET_EXEC_DRY_RUN=1 skip tmux spawns, just log intent.+"""+from __future__ import annotations++import json+import os+import shlex+import subprocess+import sys+from datetime import datetime, timezone+from pathlib import Path++LOG_PREFIX = "[ops-cron-pocket-executor]"+HOME = Path(os.path.expanduser("~"))++STATE_DIR = Path(os.environ.get("POCKET_STATE_DIR", HOME / ".claude/state/pocket"))+TMUX_SESSION = os.environ.get("POCKET_TMUX_SESSION", "pocket-exec")+CLAUDE_BIN = os.environ.get("POCKET_CLAUDE_BIN", str(HOME / ".local/bin/claude"))+EXEC_CWD = Path(os.environ.get("POCKET_EXEC_CWD", str(HOME)))+DRY_RUN = os.environ.get("POCKET_EXEC_DRY_RUN") == "1"++SUPERVISOR_WINDOW = "supervisor"+SUPERVISOR_PROMPT = Path(+ os.environ.get(+ "POCKET_SUPERVISOR_PROMPT",+ str(Path(__file__).resolve().parent.parent / "templates" / "pocket-supervisor-prompt.md"),+ )+)++HEALTH_FILE = STATE_DIR / ".executor-health"+LOG_FILE = STATE_DIR / "executor.log"+++def now_iso() -> str:+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++def log(msg: str) -> None:+ line = f"{now_iso()} {LOG_PREFIX} {msg}"+ print(line, file=sys.stderr)+ try:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ with LOG_FILE.open("a") as f:+ f.write(line + "\n")+ except OSError:+ pass+++def write_health(status: str, msg: str = "", extra: dict | None = None) -> None:+ payload = {"status": status, "message": msg, "last_run": now_iso()}+ if extra:+ payload.update(extra)+ try:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ HEALTH_FILE.write_text(json.dumps(payload, indent=2))+ except OSError as e:+ log(f"health write failed: {e}")+++def tmux(*args: str, capture: bool = True) -> tuple[int, str, str]:+ cmd = ["tmux", *args]+ try:+ proc = subprocess.run(cmd, capture_output=capture, text=True, timeout=15)+ return proc.returncode, proc.stdout, proc.stderr+ except FileNotFoundError:+ log("tmux not found on PATH")+ return 127, "", "tmux not installed"+ except subprocess.TimeoutExpired:+ log(f"tmux {args[0]} timed out")+ return 124, "", "timeout"+++def list_windows() -> list[tuple[str, str]]:+ """Returns [(name, pid_of_first_pane), ...]"""+ rc, out, _ = tmux(+ "list-windows", "-t", TMUX_SESSION,+ "-F", "#{window_name}|#{pane_pid}",+ )+ if rc != 0:+ return []+ pairs: list[tuple[str, str]] = []+ for line in out.splitlines():+ if "|" in line:+ name, pid = line.split("|", 1)+ pairs.append((name, pid))+ return pairs+++def ensure_session() -> bool:+ rc, _, _ = tmux("has-session", "-t", TMUX_SESSION)+ if rc == 0:+ return True+ log(f"creating tmux session '{TMUX_SESSION}'")+ rc, _, err = tmux(+ "new-session", "-d", "-s", TMUX_SESSION, "-n", "_idle",+ "-c", str(EXEC_CWD),+ "bash", "-l",+ )+ if rc != 0:+ log(f"tmux new-session failed: {err.strip()[:200]}")+ return False+ return True+++def supervisor_alive() -> bool:+ """A 'live' supervisor has a `claude` process in its pane process tree."""+ for name, pid in list_windows():+ if name != SUPERVISOR_WINDOW:+ continue+ # pgrep -P checks children; we want to know if `claude` is anywhere in+ # the descendant tree.+ try:+ out = subprocess.run(+ ["pgrep", "-P", pid],+ capture_output=True, text=True, timeout=5,+ )+ except (FileNotFoundError, subprocess.TimeoutExpired):+ return True # can't verify; assume alive to avoid thrashing+ children_pids = [p for p in out.stdout.split() if p]+ # Walk one level: check `ps` for any descendant whose command contains 'claude'+ if not children_pids:+ return False+ try:+ ps = subprocess.run(+ ["ps", "-o", "command=", "-p", ",".join(children_pids)],+ capture_output=True, text=True, timeout=5,+ )+ except (FileNotFoundError, subprocess.TimeoutExpired):+ return True+ return "claude" in ps.stdout.lower()+ return False+++def ensure_supervisor() -> str:+ """Returns 'spawned', 'alive', 'respawned', 'missing_prompt', or 'failed'."""+ names = {n for n, _ in list_windows()}+ has_window = SUPERVISOR_WINDOW in names++ if has_window and supervisor_alive():+ return "alive"++ if not SUPERVISOR_PROMPT.exists():+ log(f"supervisor prompt missing at {SUPERVISOR_PROMPT}")+ return "missing_prompt"++ if has_window:+ log("supervisor window exists but Claude is not running — killing for clean respawn")+ tmux("kill-window", "-t", f"{TMUX_SESSION}:{SUPERVISOR_WINDOW}")++ log("spawning supervisor window")+ # Inner command: pipe prompt into claude; keep shell open after exit so a+ # post-mortem is visible if Claude crashes.+ inner = (+ f"export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1; "+ f"cat {shlex.quote(str(SUPERVISOR_PROMPT))} | "+ f"{shlex.quote(CLAUDE_BIN)} --dangerously-skip-permissions; "+ f"echo; echo '[supervisor] exited at $(date -u +%FT%TZ) — next watchdog tick will respawn'; "+ f"exec bash -l"+ )+ rc, _, err = tmux(+ "new-window", "-t", TMUX_SESSION, "-n", SUPERVISOR_WINDOW,+ "-c", str(EXEC_CWD),+ "bash", "-c", inner,+ )+ if rc != 0:+ log(f"supervisor spawn failed: {err.strip()[:200]}")+ return "failed"+ return "spawned" if not has_window else "respawned"+++SPAWN_LEDGER = STATE_DIR / "spawn-ledger.jsonl"+TEAM_MAILBOX = Path(os.path.expanduser("~/.claude/teams/pocket-orchestrator/inboxes/team-lead.json"))+RESULTS_DIR = STATE_DIR / "executor-results"+ORPHAN_DIR = STATE_DIR / "orphans"+DURABLE_LOG = STATE_DIR / "tasks.jsonl"+++def _load_ledger() -> dict[str, dict]:+ """Map worker_name -> {pocket_task_id, title, ts}. Latest entry wins."""+ if not SPAWN_LEDGER.exists():+ return {}+ out: dict[str, dict] = {}+ try:+ for raw in SPAWN_LEDGER.read_text().splitlines():+ raw = raw.strip()+ if not raw:+ continue+ try:+ e = json.loads(raw)+ except json.JSONDecodeError:+ continue+ w = e.get("worker")+ if w:+ out[w] = e+ except OSError:+ return {}+ return out+++def _load_durable_ids() -> set[str]:+ """All known pocket_task_ids from the durable log — used to validate ledger entries."""+ if not DURABLE_LOG.exists():+ return set()+ ids: set[str] = set()+ try:+ for raw in DURABLE_LOG.read_text().splitlines():+ raw = raw.strip()+ if not raw:+ continue+ try:+ t = json.loads(raw)+ tid = t.get("id")+ if tid:+ ids.add(tid)+ except json.JSONDecodeError:+ continue+ except OSError:+ pass+ return ids+++def reap_mailbox() -> tuple[int, int]:+ """Scan the team mailbox for substantive (non-idle) worker messages,+ persist each as a durable receipt linked to its pocket_task_id.++ Returns (persisted_count, orphan_count). Orphans are messages from+ workers not in the spawn-ledger — these indicate the supervisor either+ skipped writing the ledger entry OR a teammate did unauthorized work.+ Orphans are quarantined under STATE_DIR/orphans/ with a warning log.+ """+ if not TEAM_MAILBOX.exists():+ return (0, 0)+ try:+ messages = json.loads(TEAM_MAILBOX.read_text())+ except (OSError, json.JSONDecodeError):+ return (0, 0)+ if not isinstance(messages, list):+ return (0, 0)++ ledger = _load_ledger()+ durable_ids = _load_durable_ids()+ RESULTS_DIR.mkdir(parents=True, exist_ok=True)+ ORPHAN_DIR.mkdir(parents=True, exist_ok=True)++ persisted = 0+ orphans = 0+ for m in messages:+ text = m.get("text", "") or ""+ # Skip idle / heartbeat JSON payloads+ if text.startswith("{") and ("idle_notification" in text or "shutdown" in text):+ continue+ sender = m.get("from", "") or ""+ ts = m.get("timestamp", "") or now_iso()+ summary = (m.get("summary") or text[:300]).strip()+ if not summary:+ continue++ # Stable receipt id: ISO-timestamp + sender, sanitized+ safe_ts = ts.replace(":", "").replace(".", "_")[:20]+ receipt_name = f"{safe_ts}__{sender}.completed.json"++ ledger_entry = ledger.get(sender)+ if ledger_entry and ledger_entry.get("pocket_task_id") in durable_ids:+ target_dir = RESULTS_DIR+ pocket_task_id = ledger_entry["pocket_task_id"]+ kind = "linked"+ else:+ target_dir = ORPHAN_DIR+ pocket_task_id = None+ kind = "orphan"++ target = target_dir / receipt_name+ if target.exists():+ continue # idempotent++ receipt = {+ "ts": ts,+ "worker": sender,+ "summary": m.get("summary"),+ "text": text,+ "color": m.get("color"),+ "pocket_task_id": pocket_task_id,+ "ledger_entry": ledger_entry,+ "kind": kind,+ "captured_by": "executor-reaper",+ "captured_at": now_iso(),+ }+ try:+ target.write_text(json.dumps(receipt, indent=2))+ if kind == "orphan":+ orphans += 1+ log(f"ORPHAN work persisted: {sender} (no ledger entry) — {summary[:80]}")+ else:+ persisted += 1+ except OSError as e:+ log(f"failed to write receipt {target}: {e}")+ return (persisted, orphans)+++def main() -> int:+ write_health("running", "watchdog tick")+ log("watchdog tick")++ if DRY_RUN:+ log("(dry-run) skipping tmux ops")+ write_health("ok", "dry-run", extra={"supervisor": "skipped"})+ return 0++ if not ensure_session():+ write_health("error", "tmux session bootstrap failed")+ return 2++ status = ensure_supervisor()++ # Mechanical receipt persistence — independent of supervisor behavior.+ persisted, orphans = reap_mailbox()++ write_health("ok", f"supervisor={status} reaped={persisted} orphans={orphans}", extra={+ "supervisor": status,+ "session": TMUX_SESSION,+ "receipts_persisted": persisted,+ "orphan_receipts": orphans,+ })+ log(f"done supervisor={status} reaped={persisted} orphans={orphans}")+ return 0 if status in ("alive", "spawned", "respawned") else 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/claude-ops/scripts/ops-cron-pocket-watcher.py b/claude-ops/scripts/ops-cron-pocket-watcher.pynew file mode 100755index 00000000..a07508b7--- /dev/null+++ b/claude-ops/scripts/ops-cron-pocket-watcher.py@@ -0,0 +1,940 @@+#!/usr/bin/env python3+"""ops-cron-pocket-watcher — Polls Pocket AI MCP for new voice recordings and+action items, then routes them into auto-memory and queue files for the next+Claude Code session to pick up.++Outputs (idempotent, dedup'd by state file):+ • memories -> ${POCKET_MEMORY_DIR}/pocket_<slug>.md+ • tasks -> ${POCKET_TASK_QUEUE} (one JSON line per task)+ • drafts -> ${POCKET_DRAFT_QUEUE} (outbound staged, never sent — Rule 6)++State:+ • cursor -> ${POCKET_STATE_DIR}/cursor.txt+ • seen ids -> ${POCKET_STATE_DIR}/seen.json+ • health -> ${POCKET_STATE_DIR}/.health+ • log -> ${POCKET_STATE_DIR}/run.log++Env (all optional except POCKET_API_KEY):+ POCKET_API_KEY Bearer key (pk_...); auto-resolved from keychain+ service POCKET_API_KEY / account ops-daemon if unset.+ POCKET_MCP_URL default https://public.heypocketai.com/mcp+ POCKET_STATE_DIR default ~/.claude/state/pocket+ POCKET_MEMORY_DIR default ~/.claude/memory+ POCKET_TASK_QUEUE default $POCKET_STATE_DIR/tasks.jsonl+ POCKET_DRAFT_QUEUE default $POCKET_STATE_DIR/drafts.jsonl+ POCKET_INDEX_FILE optional path to MEMORY.md index — if set, one-line+ pointer entries are appended under+ '## Pocket Voice Journal' (recency-pruned to last 14d).+ POCKET_LOOKBACK_HOURS default 24 (first run; subsequent runs use cursor)+ POCKET_DRY_RUN=1 skip writes, just log what would happen.++Implicit-task inference (Haiku):+ POCKET_INFER_TASKS=1 default 1; set 0 to disable. Calls Haiku to extract+ implicit tasks from each recording's transcript that+ Pocket didn't flag as an actionItem.+ POCKET_INFER_MIN_SECS default 60 (skip recordings shorter than this).+ POCKET_INFER_CONFIDENCE default 0.7 (skip tasks below this confidence).+ ANTHROPIC_API_KEY env-or-keychain (service=ANTHROPIC_API_KEY,+ account=ops-daemon). OAuth from keychain+ (Claude Code-credentials) preferred if available.++Giga sync (optional but on-by-default):+ GIGA_SYNC=1 default 1; set to 0 to disable Giga writes.+ GIGA_MCP_URL default https://mcp.gigamind.dev/mcp+ GIGA_MIND default "global"+ GIGA_CONSOLIDATE=1 default 0; if 1, call mcp__giga__consolidate at the+ end of each batch that produced new neurons.+ GIGA_TOKEN_FILE default = auto-derived from+ ~/.mcp-auth/mcp-remote-<v>/<md5(GIGA_MCP_URL)>_tokens.json+ (mcp-remote's OAuth cache — runs through normal Claude+ Code auth; refresh via `npx -y mcp-remote <url>`).+"""+from __future__ import annotations++import hashlib+import json+import os+import re+import subprocess+import sys+import time+import uuid+from datetime import datetime, timedelta, timezone+from pathlib import Path+from urllib import error as urlerr+from urllib import request as urlreq++LOG_PREFIX = "[ops-cron-pocket-watcher]"++# ── Config resolution ────────────────────────────────────────────────────────+HOME = Path(os.path.expanduser("~"))+MCP_URL = os.environ.get("POCKET_MCP_URL", "https://public.heypocketai.com/mcp")+STATE_DIR = Path(os.environ.get("POCKET_STATE_DIR", HOME / ".claude/state/pocket"))+MEMORY_DIR = Path(os.environ.get("POCKET_MEMORY_DIR", HOME / ".claude/memory"))+TASK_QUEUE = Path(os.environ.get("POCKET_TASK_QUEUE", STATE_DIR / "tasks.jsonl"))+DRAFT_QUEUE = Path(os.environ.get("POCKET_DRAFT_QUEUE", STATE_DIR / "drafts.jsonl"))+PENDING_TRIAGE = Path(os.environ.get("POCKET_PENDING_TRIAGE", STATE_DIR / "pending-triage.jsonl"))+_USER_CONTEXT_PATH = Path(os.environ.get(+ "POCKET_USER_CONTEXT",+ HOME / ".claude/state/pocket/user-context.json",+))+try:+ _pocket_uc = json.loads(_USER_CONTEXT_PATH.read_text())+ _OWNER_NAME: str = _pocket_uc.get("owner_name") or "the user"+except (OSError, json.JSONDecodeError):+ _OWNER_NAME = "the user"+INDEX_FILE = os.environ.get("POCKET_INDEX_FILE")+LOOKBACK_HOURS = int(os.environ.get("POCKET_LOOKBACK_HOURS", "24"))+DRY_RUN = os.environ.get("POCKET_DRY_RUN") == "1"++CURSOR_FILE = STATE_DIR / "cursor.txt"+SEEN_FILE = STATE_DIR / "seen.json"+HEALTH_FILE = STATE_DIR / ".health"++# Giga sync+GIGA_SYNC = os.environ.get("GIGA_SYNC", "1") == "1"+GIGA_MCP_URL = os.environ.get("GIGA_MCP_URL", "https://mcp.gigamind.dev/mcp")+GIGA_MIND = os.environ.get("GIGA_MIND", "global")+GIGA_CONSOLIDATE = os.environ.get("GIGA_CONSOLIDATE", "0") == "1"++# Implicit-task inference+INFER_TASKS = os.environ.get("POCKET_INFER_TASKS", "1") == "1"+INFER_MIN_SECS = int(os.environ.get("POCKET_INFER_MIN_SECS", "60"))+INFER_CONFIDENCE = float(os.environ.get("POCKET_INFER_CONFIDENCE", "0.7"))+LOG_FILE = STATE_DIR / "run.log"+++def now_iso() -> str:+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++def log(msg: str) -> None:+ line = f"{now_iso()} {LOG_PREFIX} {msg}"+ print(line, file=sys.stderr)+ try:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ with LOG_FILE.open("a") as f:+ f.write(line + "\n")+ except OSError:+ pass+++def write_health(status: str, msg: str = "", extra: dict | None = None) -> None:+ payload = {+ "status": status,+ "message": msg,+ "last_run": now_iso(),+ "mcp_url": MCP_URL,+ }+ if extra:+ payload.update(extra)+ try:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ HEALTH_FILE.write_text(json.dumps(payload, indent=2))+ except OSError as e:+ log(f"health write failed: {e}")+++def resolve_api_key() -> str:+ key = os.environ.get("POCKET_API_KEY", "").strip()+ if key:+ return key+ # macOS keychain+ try:+ out = subprocess.run(+ ["security", "find-generic-password", "-s", "POCKET_API_KEY",+ "-a", "ops-daemon", "-w"],+ capture_output=True, text=True, timeout=5,+ )+ if out.returncode == 0 and out.stdout.strip():+ return out.stdout.strip()+ except (FileNotFoundError, subprocess.TimeoutExpired):+ pass+ # Doppler fallback+ try:+ out = subprocess.run(+ ["doppler", "secrets", "get", "POCKET_API_KEY", "--plain"],+ capture_output=True, text=True, timeout=8,+ )+ if out.returncode == 0 and out.stdout.strip():+ return out.stdout.strip()+ except (FileNotFoundError, subprocess.TimeoutExpired):+ pass+ raise SystemExit(f"{LOG_PREFIX} FATAL: POCKET_API_KEY not found in env, keychain (POCKET_API_KEY/ops-daemon), or Doppler.")+++# ── MCP client (Streamable HTTP, SSE response parsing) ──────────────────────+class MCPClient:+ def __init__(self, url: str, api_key: str) -> None:+ self.url = url+ self.api_key = api_key+ self.session_id: str | None = None+ self._id = 0++ def _next_id(self) -> int:+ self._id += 1+ return self._id++ def _post(self, payload: dict, timeout: int = 30) -> tuple[dict | None, str | None]:+ data = json.dumps(payload).encode("utf-8")+ headers = {+ "Authorization": f"Bearer {self.api_key}",+ "Content-Type": "application/json",+ "Accept": "application/json, text/event-stream",+ # Cloudflare-fronted MCPs (e.g. Giga) block default urllib UA.+ "User-Agent": "ops-pocket-watcher/0.2 (Mozilla/5.0)",+ }+ if self.session_id:+ headers["mcp-session-id"] = self.session_id+ req = urlreq.Request(self.url, data=data, headers=headers, method="POST")+ try:+ resp = urlreq.urlopen(req, timeout=timeout)+ except urlerr.HTTPError as e:+ err_body = e.read().decode("utf-8", errors="replace") if e.fp else ""+ return None, f"HTTP {e.code}: {err_body[:300]}"+ except urlerr.URLError as e:+ return None, f"URLError: {e}"+ except Exception as e:+ return None, f"{type(e).__name__}: {e}"+ try:+ sess = resp.headers.get("mcp-session-id")+ if sess and not self.session_id:+ self.session_id = sess+ ctype = resp.headers.get("content-type", "")+ # If server returned plain JSON, read it all.+ if "text/event-stream" not in ctype:+ body = resp.read().decode("utf-8", errors="replace")+ return self._parse_sse(body), None+ # SSE — read line-by-line and return on first `data:` event.+ pending_event = None+ deadline = time.time() + timeout+ while time.time() < deadline:+ raw = resp.readline()+ if not raw:+ break+ line = raw.decode("utf-8", errors="replace").rstrip("\r\n")+ if line.startswith("event:"):+ pending_event = line.split(":", 1)[1].strip()+ elif line.startswith("data:"):+ payload_str = line.split(":", 1)[1].strip()+ if not payload_str:+ continue+ try:+ return json.loads(payload_str), None+ except json.JSONDecodeError:+ continue+ elif line == "":+ pending_event = None+ return None, "SSE deadline before data event"+ except Exception as e:+ return None, f"{type(e).__name__}: {e}"+ finally:+ try:+ resp.close()+ except Exception:+ pass++ @staticmethod+ def _parse_sse(body: str) -> dict | None:+ # Streamable HTTP returns one or more SSE events; pick the first+ # 'data:' line that parses as JSON-RPC.+ for line in body.splitlines():+ line = line.strip()+ if line.startswith("data:"):+ payload = line[len("data:"):].strip()+ if not payload:+ continue+ try:+ return json.loads(payload)+ except json.JSONDecodeError:+ continue+ # Some servers return raw JSON when client only sent application/json+ try:+ return json.loads(body)+ except json.JSONDecodeError:+ return None++ def initialize(self) -> bool:+ msg, err = self._post({+ "jsonrpc": "2.0",+ "id": self._next_id(),+ "method": "initialize",+ "params": {+ "protocolVersion": "2025-06-18",+ "capabilities": {},+ "clientInfo": {"name": "ops-pocket-watcher", "version": "0.1.0"},+ },+ })+ if err or not msg or "result" not in msg:+ log(f"initialize failed: {err or msg}")+ return False+ # Send notifications/initialized (no response expected; best-effort)+ try:+ self._post({+ "jsonrpc": "2.0",+ "method": "notifications/initialized",+ "params": {},+ }, timeout=10)+ except Exception:+ pass+ return True++ def call_tool(self, name: str, arguments: dict, timeout: int = 30) -> tuple[dict | None, str | None]:+ msg, err = self._post({+ "jsonrpc": "2.0",+ "id": self._next_id(),+ "method": "tools/call",+ "params": {"name": name, "arguments": arguments},+ }, timeout=timeout)+ if err:+ return None, err+ if not msg:+ return None, "empty response"+ if "error" in msg:+ return None, json.dumps(msg["error"])[:300]+ result = msg.get("result", {})+ content = result.get("content", [])+ # MCP tool responses wrap data in `content` blocks (type=text).+ for block in content:+ if block.get("type") == "text":+ text = block.get("text", "")+ try:+ return json.loads(text), None+ except json.JSONDecodeError:+ # Plain text result; bubble up as-is+ return {"text": text}, None+ return result, None+++# ── Anthropic Haiku (implicit-task inference) ────────────────────────────────+def _resolve_anthropic_auth() -> tuple[str, dict] | tuple[None, None]:+ """Returns (header_value, extra_headers) or (None, None) if no auth.++ Prefers Claude Code OAuth from keychain so subscription users don't pay+ metered rates. Falls back to ANTHROPIC_API_KEY env / keychain.+ """+ # Try Claude Code OAuth first+ try:+ blob = subprocess.run(+ ["security", "find-generic-password", "-s", "Claude Code-credentials", "-w"],+ capture_output=True, text=True, timeout=5,+ )+ if blob.returncode == 0 and blob.stdout.strip():+ data = json.loads(blob.stdout.strip())+ o = data.get("claudeAiOauth") or {}+ tok = o.get("accessToken") or ""+ exp = o.get("expiresAt") or 0+ if tok and exp > int(time.time() * 1000) + 60000:+ return (f"Bearer {tok}", {"anthropic-beta": "oauth-2025-04-20"})+ except (FileNotFoundError, subprocess.TimeoutExpired, json.JSONDecodeError):+ pass+ # API key fallback+ key = os.environ.get("ANTHROPIC_API_KEY", "").strip()+ if not key:+ try:+ r = subprocess.run(+ ["security", "find-generic-password", "-s", "ANTHROPIC_API_KEY", "-a", "ops-daemon", "-w"],+ capture_output=True, text=True, timeout=5,+ )+ if r.returncode == 0 and r.stdout.strip():+ key = r.stdout.strip()+ except (FileNotFoundError, subprocess.TimeoutExpired):+ pass+ if key:+ return (None, {"_apikey": key}) # caller treats as x-api-key header+ return (None, None)+++def infer_tasks_from_recording(recording: dict) -> list[dict]:+ """Call Haiku to extract implicit tasks from a recording's transcript.++ Returns a list of {title, context, priority, confidence} dicts.+ Filtered by INFER_CONFIDENCE threshold. Empty list if recording is too+ short, no auth, or Haiku returns nothing actionable.+ """+ if not INFER_TASKS:+ return []+ duration = recording.get("durationSec") or recording.get("duration") or 0+ if duration and duration < INFER_MIN_SECS:+ return []+ transcript = recording.get("transcript") or ""+ if not transcript:+ segs = recording.get("transcriptSegments") or []+ transcript = "\n".join(+ f"{s.get('speaker') or 'Speaker'}: {s.get('text', '').strip()}"+ for s in segs[:80] if s.get("text")+ )+ if len(transcript) < 200:+ return []++ summary = recording.get("summary") or {}+ if isinstance(summary, dict):+ summary_text = summary.get("text") or summary.get("body") or summary.get("summary") or ""+ else:+ summary_text = str(summary)++ auth_header, extras = _resolve_anthropic_auth()+ if not auth_header and not (extras or {}).get("_apikey"):+ log("infer: no Anthropic auth — skipping implicit-task extraction")+ return []++ system_prompt = (+ "You extract implicit actionable tasks from a voice-memo transcript. "+ "Pocket has ALREADY extracted the obvious action items separately, so "+ "your job is to find tasks the speaker IMPLIED but did not explicitly "+ "ask for. Examples of implicit tasks: 'I'm worried about X' → 'Check X', "+ "'I should follow up on Y' → 'Follow up on Y'. Skip mere observations, "+ "musings without a clear action, or things Pocket would already flag. "+ "Return STRICT JSON: an array of objects with keys: title (string, "+ "imperative form, <80 chars), context (string, 1-2 sentences of why), "+ "priority (low|medium|high), confidence (0.0-1.0 — your honest "+ f"certainty that this was implied as a task {_OWNER_NAME} would want done). "+ "Return [] if nothing actionable was implied. NO prose, NO markdown."+ )++ user_msg = (+ f"Recording summary: {summary_text or '(none)'}\n\n"+ f"Transcript:\n{transcript[:8000]}"+ )++ headers = {+ "content-type": "application/json",+ "anthropic-version": "2023-06-01",+ }+ if auth_header:+ headers["Authorization"] = auth_header+ for k, v in (extras or {}).items():+ if k != "_apikey":+ headers[k] = v+ else:+ headers["x-api-key"] = (extras or {}).get("_apikey", "")++ payload = {+ "model": "claude-haiku-4-5-20251001",+ "max_tokens": 1024,+ "system": system_prompt,+ "messages": [{"role": "user", "content": user_msg}],+ }+ data = json.dumps(payload).encode("utf-8")+ req = urlreq.Request("https://api.anthropic.com/v1/messages",+ data=data, headers=headers, method="POST")+ try:+ with urlreq.urlopen(req, timeout=30) as resp:+ body = json.loads(resp.read().decode("utf-8"))+ except urlerr.HTTPError as e:+ err = e.read().decode("utf-8", errors="replace")[:200] if e.fp else ""+ log(f"infer: Haiku HTTP {e.code}: {err}")+ return []+ except Exception as e:+ log(f"infer: Haiku call failed: {type(e).__name__}: {e}")+ return []++ text = ""+ for block in body.get("content", []):+ if block.get("type") == "text":+ text = block.get("text", "")+ break+ text = text.strip()+ # Strip markdown fences if any+ text = re.sub(r"^```(?:json)?\s*", "", text)+ text = re.sub(r"\s*```$", "", text)++ try:+ items = json.loads(text)+ except json.JSONDecodeError:+ log(f"infer: bad JSON from Haiku: {text[:200]}")+ return []+ if not isinstance(items, list):+ return []+ out = []+ for it in items:+ if not isinstance(it, dict):+ continue+ try:+ conf = float(it.get("confidence", 0))+ except (TypeError, ValueError):+ conf = 0.0+ if conf < INFER_CONFIDENCE:+ continue+ out.append({+ "title": (it.get("title") or "").strip()[:140],+ "context": (it.get("context") or "").strip()[:500],+ "priority": (it.get("priority") or "low").lower(),+ "confidence": conf,+ })+ return out+++# ── Giga client (reuses mcp-remote OAuth token cache) ────────────────────────+class GigaClient:+ """Giga MCP client that delegates to `claude -p` subprocess so it uses+ Claude Code's native MCP auth (no mcp-remote token cache management).+ Buffers neurons during the run and flushes in one batch claude call at+ main() end. Avoids per-memory subprocess overhead.+ """++ def __init__(self, url: str, mind: str) -> None:+ self.url = url+ self.mind = mind+ self.ok = False+ self._buffered: list[dict] = []+ self._consolidate_after = False++ def initialize(self) -> bool:+ # Cheap pre-flight: verify claude binary exists. Real auth verified at flush.+ claude_bin = os.environ.get("POCKET_CLAUDE_BIN", str(HOME / ".local/bin/claude"))+ if not Path(claude_bin).exists():+ log(f"Giga disabled: claude binary not found at {claude_bin}")+ return False+ self.ok = True+ return True++ def remember(self, title: str, body: str, neuron_type: str = "context",+ selector_nl: str = "", priority: int = 0) -> str | None:+ if not self.ok:+ return None+ self._buffered.append({+ "title": title[:120],+ "body": body[:2000],+ "neuron_type": neuron_type,+ "selector_nl": selector_nl[:200],+ "priority": priority,+ "always_on": False,+ })+ # Return a placeholder; real neuron_id only known after flush+ return f"buffered:{len(self._buffered)}"++ def consolidate(self) -> bool:+ if not self.ok:+ return False+ self._consolidate_after = True+ return True++ def flush(self) -> bool:+ """Send all buffered neurons via one `claude -p` invocation. Returns+ True on success. Best-effort: any error logs and returns False but+ does NOT raise — local memory writes already succeeded.+ """+ if not self.ok or not self._buffered:+ return True+ claude_bin = os.environ.get("POCKET_CLAUDE_BIN", str(HOME / ".local/bin/claude"))+ parser_model = os.environ.get("GIGA_FLUSH_MODEL", "claude-sonnet-4-6")+ # Strip ANTHROPIC_API_KEY so claude uses OAuth subscription auth+ env = {k: v for k, v in os.environ.items() if k != "ANTHROPIC_API_KEY"}++ neurons_json = json.dumps(self._buffered, ensure_ascii=False)+ consolidate_step = (+ f"\nAfter the remember call succeeds, also call mcp__giga__consolidate "+ f'with mind="{self.mind}".'+ if self._consolidate_after else ""+ )+ prompt = (+ f"Call the MCP tool mcp__giga__remember exactly once with these args:\n"+ f' mind: "{self.mind}"\n'+ f" neurons: {neurons_json}\n"+ f"{consolidate_step}\n\n"+ f"After the tool call(s) succeed, print on a single line: GIGA_FLUSH_OK\n"+ f"If any tool errors, print: GIGA_FLUSH_ERR <one-line reason>\n"+ f"No other output. No prose. No markdown."+ )+ cmd = [claude_bin, "--dangerously-skip-permissions",+ "--model", parser_model, "-p", prompt]+ try:+ proc = subprocess.run(cmd, env=env, capture_output=True,+ text=True, timeout=120)+ except subprocess.TimeoutExpired:+ log(f"giga flush timed out ({len(self._buffered)} neurons buffered locally)")+ return False+ except Exception as e:+ log(f"giga flush invoke failed: {type(e).__name__}: {e}")+ return False+ out = (proc.stdout or "") + "\n" + (proc.stderr or "")+ if "GIGA_FLUSH_OK" in out:+ log(f"giga flush ok: {len(self._buffered)} neurons synced "+ f"(consolidate={self._consolidate_after})")+ self._buffered.clear()+ self._consolidate_after = False+ return True+ log(f"giga flush failed: exit={proc.returncode} "+ f"out_tail={out.strip()[-300:]!r}")+ return False+++# ── State ────────────────────────────────────────────────────────────────────+def load_cursor() -> str:+ if CURSOR_FILE.exists():+ return CURSOR_FILE.read_text().strip()+ return (datetime.now(timezone.utc) - timedelta(hours=LOOKBACK_HOURS)).strftime("%Y-%m-%dT%H:%M:%SZ")+++def save_cursor(ts: str) -> None:+ if DRY_RUN:+ log(f"(dry-run) would set cursor -> {ts}")+ return+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ CURSOR_FILE.write_text(ts)+++def load_seen() -> dict[str, None]:+ """Ordered insertion map used as a set (keys only); order matters for save cap."""+ if SEEN_FILE.exists():+ try:+ raw = json.loads(SEEN_FILE.read_text())+ if isinstance(raw, list):+ return dict.fromkeys(str(x) for x in raw)+ except json.JSONDecodeError:+ pass+ return {}+++def save_seen(seen: dict[str, None]) -> None:+ if DRY_RUN:+ return+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ # Cap at 5000 ids to bound file size (keep most recently inserted keys)+ if len(seen) > 5000:+ keys = list(seen.keys())[-5000:]+ seen.clear()+ seen.update(dict.fromkeys(keys))+ SEEN_FILE.write_text(json.dumps(list(seen.keys())))+++# ── Output sinks ─────────────────────────────────────────────────────────────+def slugify(text: str, maxlen: int = 60) -> str:+ s = re.sub(r"[^a-zA-Z0-9]+", "_", (text or "").lower()).strip("_")+ return (s or "untitled")[:maxlen]+++def write_memory(recording: dict, giga: "GigaClient | None" = None) -> Path | None:+ """Persist a recording as a memory file. One file per recording_id.++ If a connected GigaClient is provided, also writes a `context` neuron to+ the configured Giga mind with a back-reference to the local file.+ """+ rid = recording.get("id") or recording.get("recordingId") or ""+ title = recording.get("title") or recording.get("summary", {}).get("title") or ""+ if not title:+ # Derive from first transcript line+ segs = recording.get("transcriptSegments") or []+ title = (segs[0].get("text", "") if segs else "")[:80]+ title = title.strip() or "voice memo"++ # Build body from summary + first chunk of transcript+ summary = recording.get("summary") or {}+ if isinstance(summary, dict):+ summary_text = summary.get("text") or summary.get("body") or summary.get("summary") or ""+ else:+ summary_text = str(summary)++ transcript = recording.get("transcript", "")+ if not transcript:+ segs = recording.get("transcriptSegments") or []+ transcript = "\n".join(+ f"- {s.get('speaker') or 'Speaker'}: {s.get('text', '').strip()}"+ for s in segs[:60] if s.get("text")+ )++ recorded_at = recording.get("recordingDate") or recording.get("createdAt") or now_iso()+ duration = recording.get("durationSec") or recording.get("duration") or 0++ slug = slugify(title)+ date_part = recorded_at[:10].replace("-", "")+ fname = f"pocket_{date_part}_{slug}.md"+ path = MEMORY_DIR / fname++ body = f"""---+name: pocket-{date_part}-{slug}+description: Pocket voice memo — {title[:120]}+metadata:+ type: project+ source: pocket_voice+ recording_id: {rid}+ recorded_at: {recorded_at}+ duration_sec: {duration}+ imported_at: {now_iso()}+---++# {title}++**Recorded:** {recorded_at} · **Duration:** {duration}s · **ID:** `{rid}`++## Summary+{summary_text or "_(no summary extracted by Pocket)_"}++## Transcript+{transcript or "_(no transcript)_"}+"""++ if DRY_RUN:+ log(f"(dry-run) would write memory {path}")+ return path+ MEMORY_DIR.mkdir(parents=True, exist_ok=True)+ path.write_text(body)+ log(f"wrote memory {path.name}")++ # Optional index update+ if INDEX_FILE:+ try:+ idx_path = Path(os.path.expanduser(INDEX_FILE))+ if idx_path.exists():+ entry = f"- [{title[:70]}]({fname}) — {recorded_at[:10]} · {duration}s"+ content = idx_path.read_text()+ section_hdr = "## Pocket Voice Journal"+ if section_hdr in content:+ content = re.sub(+ rf"({re.escape(section_hdr)}\n)",+ rf"\1{entry}\n",+ content, count=1,+ )+ else:+ content = content.rstrip() + f"\n\n{section_hdr}\n{entry}\n"+ idx_path.write_text(content)+ except Exception as e:+ log(f"index update failed: {e}")++ # Mirror to Giga global mind+ if giga and giga.ok and not DRY_RUN:+ neuron_body = (+ f"Pocket voice memo — {recorded_at} · {duration}s · `{rid}`\n\n"+ f"Local memory file: {path}\n\n"+ f"## Summary\n{summary_text or '_(none)_'}\n"+ )+ nid = giga.remember(+ title=f"pocket_{date_part}_{slug}"[:120],+ body=neuron_body,+ neuron_type="context",+ selector_nl=f"voice memo {title[:100]}",+ )+ if nid:+ log(f"giga neuron {nid[:8]}.. created for {fname}")++ return path+++def append_jsonl(path: Path, obj: dict) -> None:+ if DRY_RUN:+ log(f"(dry-run) would append to {path}: {obj.get('kind') or obj.get('type')}")+ return+ path.parent.mkdir(parents=True, exist_ok=True)+ with path.open("a") as f:+ f.write(json.dumps(obj) + "\n")+++def route_actionitem(item: dict, giga: "GigaClient | None" = None) -> None:+ """Route a Pocket-extracted action item into the appropriate queue.++ Outbound types (send_message, draft_email) -> draft queue (Rule 6).+ Reminder/task -> task queue.++ Also mirrors to Giga as a `task` (or `context` for outbound drafts) neuron+ so the item is recallable across sessions.+ """+ item_id = item.get("id") or item.get("actionItemId") or str(uuid.uuid4())+ action_type = (item.get("actionType") or item.get("type") or "").lower()+ payload = {+ "id": item_id,+ "kind": action_type or "task",+ "title": item.get("title") or item.get("label") or "",+ "context": item.get("context") or "",+ "payload": item.get("payload") or {},+ "priority": item.get("priority"),+ "due": item.get("dueDate") or item.get("dueAt"),+ "recording_id": item.get("recordingId"),+ "source": "pocket",+ "captured_at": now_iso(),+ }+ if action_type in ("send_message", "draft_email"):+ append_jsonl(DRAFT_QUEUE, payload)+ log(f"queued draft ({action_type}): {payload['title'][:60]}")+ giga_type = "context"+ else:+ append_jsonl(TASK_QUEUE, payload)+ log(f"queued task: {payload['title'][:60]}")+ giga_type = "task"++ if giga and giga.ok and not DRY_RUN:+ slug = slugify(payload["title"] or item_id)[:40]+ neuron_body = (+ f"Pocket action item (kind={payload['kind']}) — captured {payload['captured_at']}\n\n"+ f"**Title:** {payload['title']}\n"+ f"**Priority:** {payload['priority'] or 'unset'}\n"+ f"**Due:** {payload['due'] or 'unset'}\n"+ f"**Source recording:** {payload['recording_id'] or 'unknown'}\n\n"+ f"## Context\n{payload['context'] or '_(none)_'}\n"+ )+ nid = giga.remember(+ title=f"pocket_action_{slug}"[:120],+ body=neuron_body,+ neuron_type=giga_type,+ selector_nl=f"pocket action item {payload['title'][:100]}",+ priority=1 if (payload["priority"] or "").lower() in ("critical", "high") else 0,+ )+ if nid:+ log(f"giga neuron {nid[:8]}.. created for action {item_id[:8]}")+++# ── Main run ────────────────────────────────────────────────────────────────+def main() -> int:+ write_health("running", "starting")+ log(f"start (dry_run={DRY_RUN})")+ STATE_DIR.mkdir(parents=True, exist_ok=True)++ api_key = resolve_api_key()+ cursor = load_cursor()+ seen = load_seen()+ run_started = now_iso()+ log(f"cursor={cursor} seen={len(seen)}")++ client = MCPClient(MCP_URL, api_key)+ if not client.initialize():+ write_health("error", "MCP initialize failed")+ return 2++ giga: GigaClient | None = None+ if GIGA_SYNC:+ giga = GigaClient(GIGA_MCP_URL, GIGA_MIND)+ if giga.initialize():+ log(f"giga sync active (mind={GIGA_MIND})")+ else:+ log("giga sync disabled (init failed)")+ giga = None++ # 1) Pull recordings since cursor+ new_memories = 0+ new_recordings: list[str] = []+ next_before: str | None = None+ page = 0+ while True:+ page += 1+ args = {"recordingDateAfter": cursor}+ if next_before:+ args["recordingDateBeforeExclusive"] = next_before+ result, err = client.call_tool("search_pocket_conversations_timerange", args, timeout=30)+ if err:+ log(f"recordings page {page} error: {err}")+ break+ data = (result or {}).get("data", result or {})+ recordings = data.get("results") or data.get("recordings") or data.get("conversations") or []+ meta = data.get("meta") or {}+ if not recordings:+ break+ for rec in recordings:+ rid = rec.get("id") or rec.get("recordingId") or ""+ if not rid or rid in seen:+ continue+ # Skip very short, transcript-less recordings (likely noise)+ duration = rec.get("durationSec") or rec.get("duration") or 0+ transcript = rec.get("transcript") or ""+ segs = rec.get("transcriptSegments") or []+ has_content = bool(transcript or segs)+ if duration and duration < 20 and not has_content:+ log(f"skip noise recording {rid} (dur={duration}s, no transcript)")+ seen[rid] = None+ continue+ write_memory(rec, giga=giga)+ new_memories += 1+ new_recordings.append(rid)+ seen[rid] = None++ # Implicit-task inference (Haiku) — only on substantive recordings+ inferred = infer_tasks_from_recording(rec)+ for idx, t in enumerate(inferred):+ inferred_id = f"inferred-{rid[:12]}-{idx}"+ if inferred_id in seen:+ continue+ payload = {+ "id": inferred_id,+ "kind": "inferred",+ "title": t["title"],+ "context": t["context"],+ "priority": t["priority"],+ "due": None,+ "recording_id": rid,+ "source": "pocket-haiku-inferred",+ "confidence": t["confidence"],+ "captured_at": now_iso(),+ }+ if DRY_RUN:+ log(f"(dry-run) would queue inferred task for triage: {t['title'][:60]} (conf={t['confidence']:.2f})")+ else:+ # Inferred tasks go to pending-triage.jsonl, NOT directly to+ # the live tasks.jsonl. The Opus triage agent must classify+ # them (ACT / DRAFT / DROP / ASK) before any can reach the+ # supervisor. This is the safety guardrail the owner mandated:+ # no autonomous work without a verdict.+ PENDING_TRIAGE.parent.mkdir(parents=True, exist_ok=True)+ with PENDING_TRIAGE.open("a") as f:+ f.write(json.dumps(payload) + "\n")+ log(f"queued for triage: {t['title'][:60]} (conf={t['confidence']:.2f})")+ seen[inferred_id] = None+ if meta.get("hasMore") and meta.get("nextRecordingDateBeforeExclusive"):+ next_before = meta["nextRecordingDateBeforeExclusive"]+ if page >= 10:+ log("hit page cap (10) — will pick up rest on next run")+ break+ else:+ break++ # 2) Pull action items since cursor (TODO only)+ new_tasks = 0+ result, err = client.call_tool("search_pocket_actionitems", {+ "status": "TODO",+ "recordingDateFrom": cursor,+ }, timeout=30)+ if err:+ log(f"actionitems error: {err}")+ else:+ data = (result or {}).get("data", result or {})+ items = data.get("results") or data.get("items") or data.get("actionItems") or []+ for item in items:+ iid = item.get("id") or item.get("actionItemId")+ if not iid:+ continue+ seen_key = f"action:{iid}"+ if seen_key in seen:+ continue+ route_actionitem(item, giga=giga)+ new_tasks += 1+ seen[seen_key] = None++ # 3) Optional consolidate pass (Giga merges adjacent neurons)+ if giga and giga.ok and GIGA_CONSOLIDATE and (new_memories + new_tasks) > 0:+ giga.consolidate()++ # 3.5) Flush buffered Giga neurons via claude -p subprocess (uses Claude Code auth)+ giga_flush_ok = True+ if giga and giga.ok:+ giga_flush_ok = giga.flush()++ # 4) Advance cursor & persist+ save_cursor(run_started)+ save_seen(seen)++ if giga and giga.ok and not giga_flush_ok:+ giga_status = "flush_failed"+ elif giga and giga.ok:+ giga_status = "ok"+ elif not GIGA_SYNC:+ giga_status = "disabled"+ else:+ giga_status = "failed"+ summary = f"recordings={new_memories} tasks={new_tasks} giga={giga_status}"+ write_health("ok", summary, extra={+ "new_memories": new_memories,+ "new_tasks": new_tasks,+ "cursor": run_started,+ "giga_sync": giga_status,+ })+ log(f"done {summary}")+ return 0+++if __name__ == "__main__":+ try:+ sys.exit(main())+ except SystemExit:+ raise+ except Exception as e:+ log(f"FATAL: {type(e).__name__}: {e}")+ write_health("error", f"{type(e).__name__}: {e}")+ sys.exit(1)diff --git a/claude-ops/scripts/ops-daemon-launcher.sh b/claude-ops/scripts/ops-daemon-launcher.shnew file mode 100755index 00000000..d1bc2784--- /dev/null+++ b/claude-ops/scripts/ops-daemon-launcher.sh@@ -0,0 +1,38 @@+#!/opt/homebrew/bin/bash+# ops-daemon-launcher.sh — version-agnostic launcher for the claude-ops daemon.+# Resolves the highest installed ops plugin version at run time, then execs its+# ops-daemon.sh. Survives plugin upgrades without plist edits.+set -euo pipefail++CACHE_ROOT="${CLAUDE_PLUGIN_CACHE_ROOT:-$HOME/.claude/plugins/cache/ops-marketplace/ops}"++if [[ ! -d "$CACHE_ROOT" ]]; then+ echo "[ops-daemon-launcher] FATAL: cache root missing: $CACHE_ROOT" >&2+ exit 64+fi++# Highest semver dir that contains scripts/ops-daemon.sh+LATEST_VERSION="$(+ find "$CACHE_ROOT" -mindepth 1 -maxdepth 1 -type d -print 2>/dev/null \+ | awk -F/ '{print $NF}' \+ | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' \+ | sort -rn -t. -k1,1 -k2,2 -k3,3 \+ | while read -r v; do+ if [[ -x "$CACHE_ROOT/$v/scripts/ops-daemon.sh" ]]; then+ echo "$v"; break+ fi+ done+)"++if [[ -z "${LATEST_VERSION:-}" ]]; then+ echo "[ops-daemon-launcher] FATAL: no installed ops version has scripts/ops-daemon.sh" >&2+ exit 65+fi++DAEMON="$CACHE_ROOT/$LATEST_VERSION/scripts/ops-daemon.sh"+export CLAUDE_PLUGIN_ROOT="$CACHE_ROOT/$LATEST_VERSION"++echo "[ops-daemon-launcher] resolved ops $LATEST_VERSION → $DAEMON"+# Re-exec under the same bash that is running this script (plist/installer may+# use /opt/homebrew or /usr/local on Intel Mac); avoid hardcoding Homebrew path.+exec "${OPS_DAEMON_LAUNCHER_BASH:-$BASH}" "$DAEMON" "$@"diff --git a/claude-ops/scripts/ops-daemon.sh b/claude-ops/scripts/ops-daemon.shindex 2769d736..aeea0757 100755--- a/claude-ops/scripts/ops-daemon.sh+++ b/claude-ops/scripts/ops-daemon.sh@@ -148,9 +148,13 @@ calc_next_run() {interval_min=$(echo "$cron" | python3 -c "import sys, reexpr = sys.stdin.read().strip()+# */N * * * * → every N minutesm = re.match(r'^\*/(\d+)\s+\*\s+\*\s+\*\s+\*$', expr)if m:print(int(m.group(1)) * 60)+elif re.match(r'^\*\s+\*\s+\*\s+\*\s+\*$', expr):+ # * * * * * → every minute+ print(60)else:print(3600)" 2>/dev/null || echo 3600)@@ -503,7 +507,10 @@ run_cron_service() {export OPS_DAEMON_PID=$$export OPS_DAEMON_MANAGED=1rotate_service_log "$LOG_DIR/${name}.log"- bash "$cmd" >> "$LOG_DIR/${name}.log" 2>&1 &+ # Use `bash -c` so cmd can contain inline env vars + multi-word args+ # (e.g. "/usr/bin/env FOO=bar /usr/bin/python3 script.py"). Plain+ # `bash "$cmd"` treats the whole string as a single file path.+ bash -c "$cmd" >> "$LOG_DIR/${name}.log" 2>&1 &local pid=$!wait "$pid" 2>/dev/null || truediff --git a/claude-ops/scripts/ops-mcp-keepalive.sh b/claude-ops/scripts/ops-mcp-keepalive.shnew file mode 100755index 00000000..78fd4702--- /dev/null+++ b/claude-ops/scripts/ops-mcp-keepalive.sh@@ -0,0 +1,226 @@+#!/usr/bin/env bash+# ops-mcp-keepalive — Silent OAuth refresh for remote (HTTP) MCP servers.+#+# Strategy (no browser, no mcp-remote shell-out):+# 1. For every HTTP MCP in ~/.claude.json, derive the token-cache path:+# ~/.mcp-auth/mcp-remote-<ver>/<md5(url)>_{tokens.json,client_info.json}+# 2. Read tokens.json:+# • If no file → SKIP (MCP not yet authorized; needs interactive first-run)+# • If expires_at > now + grace_minutes → SKIP (still fresh)+# • Else → call the provider's /token endpoint with the refresh_token+# 3. Token endpoint is derived from client_info.json's `token_endpoint`+# (OAuth 2.1 server metadata). Falls back to `<server>/token` heuristic.+# 4. On 200, persist new tokens.json. On 4xx/5xx, log and move on (DO NOT+# open a browser — first-run consent must be done interactively).+#+# Env:+# MCP_KEEPALIVE_GRACE_MIN default 15 (refresh if <15min remaining)+# MCP_KEEPALIVE_URLS space-separated list; default = all HTTP MCPs+# in ~/.claude.json+set -uo pipefail++STATE_DIR="${HOME}/.claude/state/mcp-keepalive"+HEALTH="${STATE_DIR}/.health"+LOG_FILE="${STATE_DIR}/run.log"+GRACE="${MCP_KEEPALIVE_GRACE_MIN:-15}"+mkdir -p "$STATE_DIR"++log() {+ local line+ line="$(date -u +%FT%TZ) [ops-mcp-keepalive] $*"+ echo "$line" >&2+ echo "$line" >> "$LOG_FILE"+}++# Collect target URLs+if [[ -n "${MCP_KEEPALIVE_URLS:-}" ]]; then+ read -r -a URLS <<<"$MCP_KEEPALIVE_URLS"+else+ mapfile -t URLS < <(python3 -c "+import json, os+d = json.load(open(os.path.expanduser('~/.claude.json')))+for n, c in (d.get('mcpServers') or {}).items():+ if c.get('type') == 'http' and c.get('url'):+ print(c['url'])+")+fi++if [[ ${#URLS[@]} -eq 0 ]]; then+ log "no HTTP MCPs configured"+ cat >"$HEALTH" <<EOF+{"status":"ok","message":"no urls","last_run":"$(date -u +%FT%TZ)","refreshed":0,"skipped_fresh":0,"skipped_no_token":0,"failed":0}+EOF+ exit 0+fi++refreshed=0+skipped_fresh=0+skipped_no_token=0+failed=0++for url in "${URLS[@]}"; do+ result=$(python3 - "$url" "$GRACE" <<'PY'+import hashlib, json, os, sys, time, urllib.error, urllib.parse, urllib.request++url = sys.argv[1]+grace_min = int(sys.argv[2])+h = hashlib.md5(url.encode()).hexdigest()+base = os.path.expanduser("~/.mcp-auth")+if not os.path.isdir(base):+ print(json.dumps({"action": "no_cache_dir"})); sys.exit(0)++# Find newest mcp-remote-<ver>/ subdir holding this hash+cands = sorted(+ [os.path.join(base, d) for d in os.listdir(base) if d.startswith("mcp-remote-")],+ key=lambda p: os.path.getmtime(p), reverse=True,+)+tokens_path = None+client_path = None+for d in cands:+ tp = os.path.join(d, f"{h}_tokens.json")+ cp = os.path.join(d, f"{h}_client_info.json")+ if os.path.exists(tp):+ tokens_path = tp+ client_path = cp if os.path.exists(cp) else None+ break++if not tokens_path:+ print(json.dumps({"action": "skip_no_token", "url": url}))+ sys.exit(0)++try:+ tokens = json.load(open(tokens_path))+except Exception as e:+ print(json.dumps({"action": "fail", "reason": f"read_tokens: {e}"})); sys.exit(0)++# expires_at is either a unix-ms (mcp-remote stores ms) or seconds — handle both.+exp = tokens.get("expires_at") or 0+if isinstance(exp, (int, float)) and exp:+ # Heuristic: > 10^12 → ms, else seconds+ exp_sec = exp / 1000 if exp > 10**12 else exp+else:+ # No expires_at — try issued_at + expires_in+ issued = tokens.get("issued_at") or 0+ exp_in = tokens.get("expires_in") or 0+ if issued and exp_in:+ issued_sec = issued / 1000 if issued > 10**12 else issued+ exp_sec = issued_sec + exp_in+ else:+ # Unknown expiry — assume valid for now; skip+ print(json.dumps({"action": "skip_unknown_expiry", "url": url}))+ sys.exit(0)++remaining = exp_sec - time.time()+if remaining > grace_min * 60:+ print(json.dumps({+ "action": "skip_fresh", "url": url,+ "remaining_min": int(remaining / 60),+ }))+ sys.exit(0)++refresh_tok = tokens.get("refresh_token")+if not refresh_tok:+ print(json.dumps({"action": "fail", "reason": "no_refresh_token", "url": url}))+ sys.exit(0)++# Resolve token endpoint+token_endpoint = None+if client_path and os.path.exists(client_path):+ try:+ ci = json.load(open(client_path))+ token_endpoint = ci.get("token_endpoint")+ except Exception:+ pass+if not token_endpoint:+ # Try OAuth 2.0 well-known discovery+ parsed = urllib.parse.urlparse(url)+ discovery = f"{parsed.scheme}://{parsed.netloc}/.well-known/oauth-authorization-server"+ try:+ with urllib.request.urlopen(discovery, timeout=8) as resp:+ meta = json.loads(resp.read().decode())+ token_endpoint = meta.get("token_endpoint")+ except Exception:+ pass+if not token_endpoint:+ # Heuristic fallback+ parsed = urllib.parse.urlparse(url)+ token_endpoint = f"{parsed.scheme}://{parsed.netloc}/token"++# Build refresh request+client_id = ""+if client_path and os.path.exists(client_path):+ try:+ ci = json.load(open(client_path))+ client_id = ci.get("client_id", "")+ except Exception:+ pass++body = urllib.parse.urlencode({+ "grant_type": "refresh_token",+ "refresh_token": refresh_tok,+ **({"client_id": client_id} if client_id else {}),+}).encode()+req = urllib.request.Request(+ token_endpoint, data=body, method="POST",+ headers={"Content-Type": "application/x-www-form-urlencoded",+ "Accept": "application/json"},+)+try:+ with urllib.request.urlopen(req, timeout=15) as resp:+ new_tokens = json.loads(resp.read().decode())+except urllib.error.HTTPError as e:+ err_body = ""+ try:+ err_body = e.read().decode()[:200]+ except Exception:+ pass+ print(json.dumps({"action": "fail", "reason": f"http_{e.code}: {err_body}", "url": url}))+ sys.exit(0)+except Exception as e:+ print(json.dumps({"action": "fail", "reason": f"{type(e).__name__}: {e}", "url": url}))+ sys.exit(0)++# Merge: keep old refresh_token if new payload doesn't include one+merged = dict(tokens)+merged.update(new_tokens)+if "refresh_token" not in new_tokens:+ merged["refresh_token"] = refresh_tok+# Set expires_at if not present+if "expires_at" not in new_tokens and "expires_in" in new_tokens:+ merged["expires_at"] = int((time.time() + new_tokens["expires_in"]) * 1000)+# Atomic write+tmp = tokens_path + ".tmp"+with open(tmp, "w") as f:+ json.dump(merged, f, indent=2)+os.replace(tmp, tokens_path)+print(json.dumps({"action": "refreshed", "url": url, "new_expires_in": new_tokens.get("expires_in")}))+PY+ )+ action=$(echo "$result" | python3 -c "import json,sys; print(json.loads(sys.stdin.read()).get('action',''))" 2>/dev/null)+ case "$action" in+ refreshed) refreshed=$((refreshed+1)); log "✓ refreshed $url" ;;+ skip_fresh) skipped_fresh=$((skipped_fresh+1)) ;;+ skip_no_token) skipped_no_token=$((skipped_no_token+1)) ;;+ skip_unknown_expiry) skipped_no_token=$((skipped_no_token+1)) ;;+ fail) failed=$((failed+1)); log "✗ refresh failed for $url: $(echo "$result" | python3 -c "import json,sys; print(json.loads(sys.stdin.read()).get('reason',''))" 2>/dev/null)" ;;+ no_cache_dir) skipped_no_token=$((skipped_no_token+1)) ;;+ esac+done++ts=$(date -u +%FT%TZ)+log "done refreshed=$refreshed fresh=$skipped_fresh no_token=$skipped_no_token failed=$failed"++python3 -c "+import json+print(json.dumps({+ 'status': 'ok' if $failed == 0 else 'warn',+ 'message': 'refreshed=$refreshed fresh=$skipped_fresh no_token=$skipped_no_token failed=$failed',+ 'last_run': '$ts',+ 'refreshed': $refreshed,+ 'skipped_fresh': $skipped_fresh,+ 'skipped_no_token': $skipped_no_token,+ 'failed': $failed,+ 'grace_minutes': $GRACE,+}, indent=2))+" >"$HEALTH"+exit 0diff --git a/claude-ops/scripts/ops-mcp-reauth.py b/claude-ops/scripts/ops-mcp-reauth.pynew file mode 100755index 00000000..2b4d0ae8--- /dev/null+++ b/claude-ops/scripts/ops-mcp-reauth.py@@ -0,0 +1,289 @@+#!/usr/bin/env python3+"""ops-mcp-reauth — Headless OAuth re-auth for remote MCP servers.++Drives an MCP through its full OAuth consent flow without popping a foreground+browser. Uses Playwright + a persistent Chromium profile so once you've signed+into each provider once (Google, etc.), subsequent re-auths are zero-touch.++Usage:+ ops-mcp-reauth.py <mcp-url>+ ops-mcp-reauth.py --bootstrap # opens a HEAD-FUL window so Sam can log in+ to each provider into the persistent profile+ ONE TIME. After that all reauths headless.++Strategy:+ 1. Spawn `npx -y mcp-remote <url>` in background, capture stdout.+ 2. Parse the `https://.../authorize?...` URL from its output.+ 3. Launch Playwright Chromium with persistent context at+ ~/.claude/state/mcp-reauth-browser/.+ 4. Navigate to the authorize URL.+ 5. If the page contains a Google/MS/etc. login form, abort (need bootstrap).+ 6. Otherwise wait for and click any button matching+ /approve|authorize|allow|grant|continue|accept/i.+ 7. Watch for redirect to localhost:<port>/oauth/callback — that's+ mcp-remote intercepting the code.+ 8. mcp-remote completes the token exchange + writes tokens.json.+ 9. Verify tokens.json exists post-flow, return exit 0.++Env:+ POCKET_CLAUDE_BIN Path to claude binary (unused but kept for parity)+ MCP_REAUTH_HEADLESS default 1; set 0 to see the browser (debug)+ MCP_REAUTH_TIMEOUT seconds per MCP, default 90+"""+from __future__ import annotations++import hashlib+import json+import os+import re+import shlex+import signal+import subprocess+import sys+import time+from pathlib import Path++LOG_PREFIX = "[ops-mcp-reauth]"+HOME = Path(os.path.expanduser("~"))+STATE_DIR = HOME / ".claude/state/mcp-reauth"+BROWSER_PROFILE = HOME / ".claude/state/mcp-reauth-browser"+LOG_FILE = STATE_DIR / "run.log"++HEADLESS = os.environ.get("MCP_REAUTH_HEADLESS", "1") == "1"+TIMEOUT = int(os.environ.get("MCP_REAUTH_TIMEOUT", "90"))++# Regex for the OAuth authorize URL mcp-remote logs+AUTH_URL_RE = re.compile(r"(https?://[^\s\"'<>]+/authorize\?[^\s\"'<>]+)")+++def now_iso() -> str:+ import datetime+ return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++def log(msg: str) -> None:+ line = f"{now_iso()} {LOG_PREFIX} {msg}"+ print(line, file=sys.stderr)+ try:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ with LOG_FILE.open("a") as f:+ f.write(line + "\n")+ except OSError:+ pass+++def find_tokens_path(url: str) -> Path | None:+ h = hashlib.md5(url.encode()).hexdigest()+ base = HOME / ".mcp-auth"+ if not base.is_dir():+ return None+ for d in sorted(base.iterdir(), key=lambda p: p.stat().st_mtime if p.exists() else 0, reverse=True):+ if not d.is_dir() or not d.name.startswith("mcp-remote-"):+ continue+ tp = d / f"{h}_tokens.json"+ if tp.exists():+ return tp+ return None+++def spawn_mcp_remote(url: str) -> tuple[subprocess.Popen, str | None]:+ """Spawn npx mcp-remote, parse the authorize URL from its first output.+ Returns (process, auth_url). Caller must kill the process after capture.+ """+ log(f"spawning npx mcp-remote {url}")+ proc = subprocess.Popen(+ ["npx", "-y", "mcp-remote", url],+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ stdin=subprocess.DEVNULL,+ bufsize=1, text=True,+ # New process group so we can kill cleanly+ preexec_fn=os.setsid,+ )+ auth_url = None+ deadline = time.time() + 25+ buf_lines: list[str] = []+ while time.time() < deadline:+ line = proc.stdout.readline() if proc.stdout else ""+ if not line:+ if proc.poll() is not None:+ break+ time.sleep(0.1)+ continue+ buf_lines.append(line)+ m = AUTH_URL_RE.search(line)+ if m:+ auth_url = m.group(1)+ log(f"captured authorize URL: {auth_url[:100]}...")+ break+ # Also check if it says "Connected" — then no auth needed+ if "Connected to remote server" in line or "Proxy established" in line:+ log("mcp-remote connected without needing OAuth — token was still valid")+ return (proc, None)+ if not auth_url:+ log(f"no authorize URL in mcp-remote output. Last lines: {''.join(buf_lines[-5:])[:400]}")+ return (proc, auth_url)+++def drive_consent(auth_url: str) -> bool:+ """Open the authorize URL in persistent-profile Chromium and click approve.+ Returns True if a localhost callback was observed.+ """+ try:+ from playwright.sync_api import sync_playwright, TimeoutError as PWTimeout+ except ImportError:+ log("playwright not installed — run: pip install playwright && playwright install chromium")+ return False++ BROWSER_PROFILE.mkdir(parents=True, exist_ok=True)+ callback_seen = {"hit": False}++ with sync_playwright() as p:+ ctx = p.chromium.launch_persistent_context(+ str(BROWSER_PROFILE),+ headless=HEADLESS,+ args=["--disable-blink-features=AutomationControlled"],+ )+ page = ctx.new_page()++ # Watch for the localhost callback redirect — that's the success signal+ def on_request(req):+ if "localhost" in req.url and "/oauth/callback" in req.url:+ callback_seen["hit"] = True+ log(f"callback intercepted: {req.url[:120]}")++ page.on("request", on_request)++ try:+ page.goto(auth_url, wait_until="domcontentloaded", timeout=20000)+ except PWTimeout:+ log("authorize URL load timeout")+ ctx.close()+ return False+ except Exception as e:+ log(f"goto failed: {type(e).__name__}: {e}")+ ctx.close()+ return False++ log(f"loaded page: {page.url[:100]}")++ # If the page is asking us to LOG IN (not just approve), bail out and tell user to bootstrap+ page_text = (page.content() or "").lower()+ login_indicators = ["sign in to google", "enter your email", "password", "log in with"]+ if any(ind in page_text for ind in login_indicators) and not callback_seen["hit"]:+ log("page appears to require interactive login — run with --bootstrap once to sign in")+ ctx.close()+ return False++ # Try to find and click an "approve" / "authorize" / "allow" button+ button_patterns = [+ re.compile(r"^\s*approve\s*$", re.I),+ re.compile(r"^\s*authorize\s*$", re.I),+ re.compile(r"^\s*allow\s*$", re.I),+ re.compile(r"^\s*grant\s*$", re.I),+ re.compile(r"^\s*continue\s*$", re.I),+ re.compile(r"^\s*accept\s*$", re.I),+ re.compile(r"^\s*confirm\s*$", re.I),+ ]+ clicked = False+ for pat in button_patterns:+ try:+ btn = page.get_by_role("button", name=pat).first+ if btn.is_visible(timeout=1500):+ log(f"clicking button matching {pat.pattern}")+ btn.click()+ clicked = True+ break+ except Exception:+ continue+ if not clicked:+ # Fallback: try anchor links with these labels+ for pat in button_patterns:+ try:+ a = page.get_by_role("link", name=pat).first+ if a.is_visible(timeout=500):+ log(f"clicking link matching {pat.pattern}")+ a.click()+ clicked = True+ break+ except Exception:+ continue+ if not clicked:+ log("no Approve/Authorize button found on page")+ try:+ # Dump button labels for debugging+ btns = page.evaluate("[...document.querySelectorAll('button,a')].slice(0,15).map(b=>b.innerText?.slice(0,60))")+ log(f"visible buttons/links: {btns}")+ except Exception:+ pass+ ctx.close()+ return False++ # Wait up to 8s for callback+ deadline = time.time() + 8+ while time.time() < deadline and not callback_seen["hit"]:+ page.wait_for_timeout(250)++ ctx.close()+ return callback_seen["hit"]+++def main() -> int:+ if len(sys.argv) < 2:+ log("usage: ops-mcp-reauth.py <mcp-url>")+ return 2+ if sys.argv[1] == "--bootstrap":+ # Open a head-ful browser session so user can sign into providers ONCE.+ try:+ from playwright.sync_api import sync_playwright+ except ImportError:+ log("playwright not installed")+ return 3+ log("BOOTSTRAP MODE — sign into each OAuth provider you use, then close the window")+ BROWSER_PROFILE.mkdir(parents=True, exist_ok=True)+ with sync_playwright() as p:+ ctx = p.chromium.launch_persistent_context(str(BROWSER_PROFILE), headless=False)+ page = ctx.new_page()+ page.goto("about:blank")+ # Block until user closes the window+ page.wait_for_event("close", timeout=600_000)+ return 0++ url = sys.argv[1]+ proc, auth_url = spawn_mcp_remote(url)+ try:+ if auth_url is None:+ log("nothing to do — mcp-remote already connected (or no auth URL found)")+ return 0+ ok = drive_consent(auth_url)+ if not ok:+ log("consent flow did NOT complete")+ return 1+ # Wait briefly for mcp-remote to write tokens.json+ time.sleep(2)+ tp = find_tokens_path(url)+ if tp and tp.exists():+ log(f"✓ tokens written to {tp}")+ return 0+ log("consent OK but tokens.json not found — mcp-remote may need more time")+ return 0 # not a hard failure+ finally:+ try:+ os.killpg(os.getpgid(proc.pid), signal.SIGTERM)+ proc.wait(timeout=3)+ except Exception:+ try:+ proc.kill()+ except Exception:+ pass+++if __name__ == "__main__":+ try:+ sys.exit(main())+ except KeyboardInterrupt:+ log("interrupted")+ sys.exit(130)+ except Exception as e:+ log(f"FATAL: {type(e).__name__}: {e}")+ sys.exit(1)diff --git a/claude-ops/scripts/ops-mcp-watchdog.py b/claude-ops/scripts/ops-mcp-watchdog.pynew file mode 100755index 00000000..4277544f--- /dev/null+++ b/claude-ops/scripts/ops-mcp-watchdog.py@@ -0,0 +1,512 @@+#!/usr/bin/env python3+"""ops-mcp-watchdog — Detect MCP server health, notify Sam on degradation.++Every cron tick:+ 1. For each HTTP MCP in ~/.claude.json, probe with a JSON-RPC `initialize`+ using the cached Bearer (or API key). Classify:+ healthy — 200 OK, MCP server responded with init result+ token_expired — 401, refresh_token exists → recoverable via OAuth refresh+ needs_bootstrap— 401, no refresh_token → user must do interactive consent+ cloudflare_ua — 403 from Cloudflare's bot challenge (UA filter)+ unreachable — DNS / connection failure+ server_error — 5xx+ 2. Diff vs last tick's state. If a previously-healthy MCP degrades, send+ WhatsApp notification with a re-auth link (if interactive consent needed)+ OR auto-attempt the refresh_token flow (if recoverable).+ 3. Write current state to ~/.claude/state/mcp-watchdog/state.json (audit).++Env:+ MCP_WATCHDOG_AUTO_REFRESH=1 (default 1) — attempt silent OAuth refresh+ when token_expired. Set 0 to disable.+ MCP_WATCHDOG_NOTIFY=1 (default 1) — fire WhatsApp on new degradations.+ POCKET_STATE_DIR for WhatsApp config lookup+ MCP_WATCHDOG_PROBE_TIMEOUT default 6s per MCP++Cron: */5 * * * *+"""+from __future__ import annotations++import hashlib+import json+import os+import subprocess+import sys+import time+from datetime import datetime, timezone+from pathlib import Path+from urllib import error as urlerr+from urllib import parse as urlparse+from urllib import request as urlreq++LOG_PREFIX = "[ops-mcp-watchdog]"+HOME = Path(os.path.expanduser("~"))+STATE_DIR = HOME / ".claude/state/mcp-watchdog"+POCKET_STATE_DIR = Path(os.environ.get("POCKET_STATE_DIR", HOME / ".claude/state/pocket"))+STATE_FILE = STATE_DIR / "state.json"+LAST_STATE_FILE = STATE_DIR / "state.last.json"+HEALTH = STATE_DIR / ".health"+LOG_FILE = STATE_DIR / "run.log"++AUTO_REFRESH = os.environ.get("MCP_WATCHDOG_AUTO_REFRESH", "1") == "1"+AUTO_REAUTH = os.environ.get("MCP_WATCHDOG_AUTO_REAUTH", "1") == "1"+NOTIFY = os.environ.get("MCP_WATCHDOG_NOTIFY", "1") == "1"+PROBE_TIMEOUT = int(os.environ.get("MCP_WATCHDOG_PROBE_TIMEOUT", "6"))+REAUTH_SCRIPT = Path(__file__).resolve().parent / "ops-mcp-reauth.py"++UA_HEADER = "ops-mcp-watchdog/0.1 (Mozilla/5.0)"++# MCPs that use a Bearer API key (not OAuth). The key lives in keychain under+# the listed `keychain_service` name; we'll inject it as Authorization: Bearer.+API_KEY_MCPS = {+ "pocketai": {"keychain_service": "POCKET_API_KEY", "account": "ops-daemon"},+}+++def get_api_key_for(name: str) -> str | None:+ spec = API_KEY_MCPS.get(name)+ if not spec:+ return None+ try:+ out = subprocess.run(+ ["security", "find-generic-password",+ "-s", spec["keychain_service"], "-a", spec["account"], "-w"],+ capture_output=True, text=True, timeout=5,+ )+ if out.returncode == 0:+ return out.stdout.strip()+ except (FileNotFoundError, subprocess.TimeoutExpired):+ pass+ return None+++def now_iso() -> str:+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++def log(msg: str) -> None:+ line = f"{now_iso()} {LOG_PREFIX} {msg}"+ print(line, file=sys.stderr)+ try:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ with LOG_FILE.open("a") as f:+ f.write(line + "\n")+ except OSError:+ pass+++def write_health(status: str, msg: str = "", extra: dict | None = None) -> None:+ payload = {"status": status, "message": msg, "last_run": now_iso()}+ if extra:+ payload.update(extra)+ try:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ HEALTH.write_text(json.dumps(payload, indent=2))+ except OSError as e:+ log(f"health write failed: {e}")+++def list_http_mcps() -> dict[str, str]:+ """Returns {name: url} for all HTTP MCPs in ~/.claude.json."""+ try:+ d = json.loads((HOME / ".claude.json").read_text())+ except Exception as e:+ log(f"cannot read .claude.json: {e}")+ return {}+ out = {}+ for name, cfg in (d.get("mcpServers") or {}).items():+ if cfg.get("type") == "http" and cfg.get("url"):+ out[name] = cfg["url"]+ return out+++def claude_code_health() -> dict | None:+ """Claude Code maintains its own MCP health cache. Use it as ground truth+ when fresh (it's the canonical view of what active sessions see).+ Falls back to None if missing or stale (>15 min old).+ """+ p = HOME / ".claude/mcp-health-cache.json"+ if not p.exists():+ return None+ try:+ d = json.loads(p.read_text())+ ts = d.get("ts", 0)+ if not ts:+ return None+ age_sec = time.time() - ts+ # 24h is generous — Claude Code only updates this cache on session+ # events (startup, MCP reconnect, settings change). It does NOT+ # heartbeat. So even a "stale" cache is closer to truth than our HTTP+ # probe, which doesn't see the in-memory tokens Claude Code holds.+ if age_sec > 86400:+ return None+ return d+ except Exception:+ return None+++def find_token_cache(url: str) -> tuple[Path | None, Path | None]:+ """Locate (tokens.json, client_info.json) under ~/.mcp-auth/mcp-remote-*/."""+ h = hashlib.md5(url.encode()).hexdigest()+ base = HOME / ".mcp-auth"+ if not base.is_dir():+ return (None, None)+ for d in sorted(base.iterdir(), key=lambda p: p.stat().st_mtime if p.exists() else 0, reverse=True):+ if not d.is_dir() or not d.name.startswith("mcp-remote-"):+ continue+ tp = d / f"{h}_tokens.json"+ cp = d / f"{h}_client_info.json"+ if tp.exists():+ return (tp, cp if cp.exists() else None)+ return (None, None)+++def probe(url: str, mcp_name: str = "") -> dict:+ """Probe one MCP. Returns {state, http_code, detail, ...}."""+ headers = {+ "Content-Type": "application/json",+ "Accept": "application/json, text/event-stream",+ "User-Agent": UA_HEADER,+ }++ # API-key MCPs (pocketai etc.)+ api_key = get_api_key_for(mcp_name)+ if api_key:+ headers["Authorization"] = f"Bearer {api_key}"+ tokens = None # Skip OAuth token cache lookup for API-key MCPs+ tokens_path = None+ else:+ tokens_path, client_path = find_token_cache(url)+ tokens = None+ if tokens_path:+ try:+ tokens = json.loads(tokens_path.read_text())+ except Exception:+ pass+ if tokens and tokens.get("access_token"):+ headers["Authorization"] = f"Bearer {tokens['access_token']}"++ body = json.dumps({+ "jsonrpc": "2.0", "id": 1, "method": "initialize",+ "params": {+ "protocolVersion": "2025-06-18",+ "capabilities": {},+ "clientInfo": {"name": "ops-mcp-watchdog", "version": "0.1"},+ },+ }).encode()++ req = urlreq.Request(url, data=body, headers=headers, method="POST")+ try:+ resp = urlreq.urlopen(req, timeout=PROBE_TIMEOUT)+ except urlerr.HTTPError as e:+ code = e.code+ err = ""+ try:+ err = e.read().decode("utf-8", errors="replace")[:200]+ except Exception:+ pass+ if code == 401:+ has_refresh = bool(tokens and tokens.get("refresh_token"))+ return {+ "state": "token_expired" if has_refresh else "needs_bootstrap",+ "http_code": 401,+ "detail": err[:120],+ "has_refresh_token": has_refresh,+ "tokens_present": bool(tokens),+ }+ if code == 403:+ # Cloudflare 1010 bot challenge etc.+ if "cloudflare" in err.lower() or "1010" in err:+ return {"state": "cloudflare_ua", "http_code": 403, "detail": err[:120]}+ return {"state": "forbidden", "http_code": 403, "detail": err[:120]}+ if 500 <= code < 600:+ return {"state": "server_error", "http_code": code, "detail": err[:120]}+ return {"state": f"http_{code}", "http_code": code, "detail": err[:120]}+ except urlerr.URLError as e:+ return {"state": "unreachable", "detail": str(e)[:160]}+ except Exception as e:+ return {"state": "probe_error", "detail": f"{type(e).__name__}: {e}"[:200]}++ # 2xx — read just the first SSE event or JSON+ try:+ # Read up to a few KB to avoid hanging on SSE keep-alive+ chunk = resp.read(4096).decode("utf-8", errors="replace")+ # Look for an init result anywhere in the chunk+ ok = '"result"' in chunk and '"protocolVersion"' in chunk+ resp.close()+ if ok:+ return {"state": "healthy", "http_code": 200}+ return {"state": "weird_2xx", "http_code": 200, "detail": chunk[:200]}+ except Exception as e:+ return {"state": "read_error", "detail": str(e)[:160]}+++def attempt_refresh(url: str) -> bool:+ """Use direct OAuth refresh-token POST (no mcp-remote). Returns True on success."""+ tokens_path, client_path = find_token_cache(url)+ if not tokens_path:+ return False+ try:+ tokens = json.loads(tokens_path.read_text())+ except Exception:+ return False+ refresh = tokens.get("refresh_token")+ if not refresh:+ return False++ # Resolve token endpoint+ token_endpoint = None+ if client_path:+ try:+ ci = json.loads(client_path.read_text())+ token_endpoint = ci.get("token_endpoint")+ except Exception:+ pass+ if not token_endpoint:+ parsed = urlparse.urlparse(url)+ wkw = f"{parsed.scheme}://{parsed.netloc}/.well-known/oauth-authorization-server"+ try:+ with urlreq.urlopen(urlreq.Request(wkw, headers={"User-Agent": UA_HEADER}), timeout=8) as r:+ meta = json.loads(r.read().decode())+ token_endpoint = meta.get("token_endpoint")+ except Exception:+ pass+ if not token_endpoint:+ parsed = urlparse.urlparse(url)+ token_endpoint = f"{parsed.scheme}://{parsed.netloc}/token"++ client_id = ""+ if client_path:+ try:+ ci = json.loads(client_path.read_text())+ client_id = ci.get("client_id", "")+ except Exception:+ pass++ form = {"grant_type": "refresh_token", "refresh_token": refresh}+ if client_id:+ form["client_id"] = client_id+ req = urlreq.Request(+ token_endpoint, data=urlparse.urlencode(form).encode(), method="POST",+ headers={"Content-Type": "application/x-www-form-urlencoded",+ "Accept": "application/json",+ "User-Agent": UA_HEADER},+ )+ try:+ with urlreq.urlopen(req, timeout=15) as resp:+ new_tokens = json.loads(resp.read().decode())+ except Exception as e:+ log(f"refresh POST failed for {url}: {type(e).__name__}: {e}")+ return False++ merged = dict(tokens)+ merged.update(new_tokens)+ if "refresh_token" not in new_tokens:+ merged["refresh_token"] = refresh+ if "expires_at" not in new_tokens and "expires_in" in new_tokens:+ merged["expires_at"] = int((time.time() + new_tokens["expires_in"]) * 1000)++ tmp = tokens_path.with_suffix(".tmp")+ tmp.write_text(json.dumps(merged, indent=2))+ os.replace(tmp, tokens_path)+ return True+++def whatsapp_notify(message: str) -> bool:+ """Send WhatsApp notification via the configured pocket chat. Best-effort."""+ cfg_path = POCKET_STATE_DIR / "whatsapp-config.json"+ if not cfg_path.exists():+ return False+ try:+ cfg = json.loads(cfg_path.read_text())+ except Exception:+ return False+ if not cfg.get("enabled") or not cfg.get("chat_jid"):+ return False++ # Use the WhatsApp MCP server's HTTP bridge directly (bypasses Claude-via-MCP)+ # The Baileys bridge listens on localhost:8080 for `whatsmeow`-style sends.+ # But the cleaner path: spawn `claude -p` with the MCP call. To stay+ # dependency-free, we'll write a notification file and let the supervisor+ # pick it up on its next wake — that's the path that already exists.+ queue = POCKET_STATE_DIR / "supervisor-out-queue.jsonl"+ try:+ queue.parent.mkdir(parents=True, exist_ok=True)+ with queue.open("a") as f:+ f.write(json.dumps({+ "ts": now_iso(),+ "kind": "whatsapp",+ "chat_jid": cfg["chat_jid"],+ "message": message,+ }) + "\n")+ return True+ except OSError:+ return False+++def macos_notify(title: str, msg: str) -> None:+ try:+ subprocess.run(+ ["osascript", "-e",+ f'display notification "{msg}" with title "{title}" sound name "Glass"'],+ timeout=5, capture_output=True,+ )+ except Exception:+ pass+++def main() -> int:+ write_health("running", "tick")+ log("watchdog tick")+ mcps = list_http_mcps()+ if not mcps:+ log("no HTTP MCPs configured")+ write_health("ok", "no mcps")+ return 0++ # Prefer Claude Code's own health cache (canonical truth from active sessions)+ cc_health = claude_code_health()+ cc_auth_needed = set(cc_health.get("auth_list", []) or []) if cc_health else None+ cc_failed = set(cc_health.get("failed_list", []) or []) if cc_health else None+ if cc_health is not None:+ log(f"using Claude Code health cache: connected={cc_health.get('connected')} "+ f"auth_needed={len(cc_auth_needed or [])} failed={len(cc_failed or [])}")++ # Load previous state for diffing+ last_state = {}+ if LAST_STATE_FILE.exists():+ try:+ last_state = json.loads(LAST_STATE_FILE.read_text())+ except Exception:+ pass++ cur_state = {}+ summary = {"healthy": 0, "token_expired": 0, "needs_bootstrap": 0,+ "cloudflare_ua": 0, "server_error": 0, "unreachable": 0, "other": 0}+ recovered = []+ degraded = []++ for name, url in mcps.items():+ # If Claude Code's cache is fresh, trust it over our direct HTTP probe.+ # Names in the cache may be prefixed like 'plugin:cloudflare:cloudflare-api'.+ if cc_health is not None:+ in_auth = any(n.endswith(name) for n in (cc_auth_needed or set()))+ in_failed = any(n.endswith(name) for n in (cc_failed or set()))+ if in_failed:+ result = {"state": "needs_bootstrap", "via": "claude_code_cache",+ "detail": "Claude Code reports failed"}+ elif in_auth:+ result = {"state": "needs_bootstrap", "via": "claude_code_cache",+ "detail": "Claude Code reports auth needed"}+ else:+ result = {"state": "healthy", "via": "claude_code_cache"}+ result["url"] = url+ result["probed_at"] = now_iso()+ cur_state[name] = result+ state = result["state"]+ summary[state] = summary.get(state, 0) + 1+ prev = (last_state.get(name) or {}).get("state")+ if prev == "healthy" and state != "healthy":+ degraded.append((name, state, result.get("detail", "")))+ if prev and prev != "healthy" and state == "healthy":+ recovered.append(name)+ continue++ # Fallback: direct HTTP probe (used when CC cache is missing/stale)+ result = probe(url, name)+ result["url"] = url+ result["probed_at"] = now_iso()+ cur_state[name] = result+ state = result["state"]+ if state in summary:+ summary[state] += 1+ else:+ summary["other"] += 1++ prev = (last_state.get(name) or {}).get("state")++ # Auto-refresh attempt for token_expired+ if state == "token_expired" and AUTO_REFRESH:+ log(f"{name}: token_expired, attempting silent refresh")+ if attempt_refresh(url):+ log(f"{name}: refresh ok, re-probing")+ result2 = probe(url, name)+ result2["url"] = url+ result2["probed_at"] = now_iso()+ result2["recovered_via"] = "refresh_token_post"+ cur_state[name] = result2+ state = result2["state"]+ if state == "healthy":+ summary["token_expired"] -= 1+ summary["healthy"] += 1++ # Diff: degraded means previously healthy now not+ if prev == "healthy" and cur_state[name]["state"] != "healthy":+ degraded.append((name, cur_state[name]["state"], cur_state[name].get("detail", "")))+ if prev and prev != "healthy" and cur_state[name]["state"] == "healthy":+ recovered.append(name)++ # Auto-reauth via Playwright for needs_bootstrap MCPs+ if AUTO_REAUTH and REAUTH_SCRIPT.exists():+ for name, info in cur_state.items():+ if info.get("state") != "needs_bootstrap":+ continue+ log(f"{name}: attempting Playwright auto-reauth")+ try:+ proc = subprocess.run(+ [sys.executable, str(REAUTH_SCRIPT), info["url"]],+ capture_output=True, text=True, timeout=120,+ )+ if proc.returncode == 0:+ log(f"{name}: reauth script exit 0 — re-probing")+ new_result = probe(info["url"], name)+ new_result["url"] = info["url"]+ new_result["probed_at"] = now_iso()+ new_result["recovered_via"] = "playwright_reauth"+ cur_state[name] = new_result+ if new_result["state"] == "healthy":+ recovered.append(name)+ # Remove from degraded if present+ degraded = [d for d in degraded if d[0] != name]+ else:+ log(f"{name}: reauth script exit {proc.returncode}: {proc.stderr.strip()[:160]}")+ except subprocess.TimeoutExpired:+ log(f"{name}: reauth timed out")+ except Exception as e:+ log(f"{name}: reauth error: {type(e).__name__}: {e}")++ # Notify on new degradations+ if degraded and NOTIFY:+ bullets = "\n".join(f"• {n} → {s} ({d[:60]})" for n, s, d in degraded)+ macos_notify("MCP degradation", f"{len(degraded)} MCP(s) need attention")+ whatsapp_notify(+ f"⚠️ MCP watchdog — {len(degraded)} server(s) degraded:\n\n{bullets}\n\n"+ f"Run `pocket mcps` for details. Open Claude Code to re-auth via browser, "+ f"or build out the Playwright auto-approver if you want zero-touch."+ )+ log(f"notified about {len(degraded)} degradations")+ if recovered:+ log(f"recovered: {', '.join(recovered)}")++ # Persist+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ if STATE_FILE.exists():+ try:+ STATE_FILE.rename(LAST_STATE_FILE)+ except OSError:+ pass+ STATE_FILE.write_text(json.dumps(cur_state, indent=2))++ write_health("ok", json.dumps(summary, separators=(",", ":")), extra={+ "summary": summary, "degraded_count": len(degraded), "recovered_count": len(recovered),+ })+ log(f"done summary={summary} degraded={len(degraded)} recovered={len(recovered)}")+ return 0+++if __name__ == "__main__":+ try:+ sys.exit(main())+ except Exception as e:+ log(f"FATAL: {type(e).__name__}: {e}")+ write_health("error", f"{type(e).__name__}: {e}")+ sys.exit(1)diff --git a/claude-ops/scripts/ops-pocket-activity-notifier.py b/claude-ops/scripts/ops-pocket-activity-notifier.pynew file mode 100755index 00000000..72b6ee7c--- /dev/null+++ b/claude-ops/scripts/ops-pocket-activity-notifier.py@@ -0,0 +1,395 @@+#!/usr/bin/env python3+"""ops-pocket-activity-notifier — Notify Sam on WhatsApp when pocket agents+pick up work and when they complete it.++Watches two signals under ~/.claude/state/pocket/:+ 1. spawn-ledger.jsonl — appended when supervisor dispatches a worker+ to a pocket-derived task (START event)+ 2. executor-results/*.{done,completed}.json — created when a worker+ finishes (COMPLETE event)++For each new event, append a {"kind":"whatsapp", ...} entry to+supervisor-out-queue.jsonl. ops-pocket-out-queue (existing cron) drains+that queue to the Baileys bridge.++Idempotency:+ - spawn-ledger.jsonl is tailed via byte cursor at .activity-notifier.spawn-cursor+ - executor-results files are tracked via .activity-notifier.seen-results (set of basenames)++Filters:+ - Only notify on tasks sourced from pocket (id prefix "inferred-" OR+ "pocket_task_id" present in the ledger entry / result file).+ - Smoketests (id starting with "smoketest-" or "tasklist-verify-") are skipped.++Cron: every 1 minute.+"""+from __future__ import annotations++import json+import os+import sys+from datetime import datetime, timezone+from pathlib import Path++LOG_PREFIX = "[ops-pocket-activity-notifier]"+HOME = Path(os.path.expanduser("~"))+STATE_DIR = Path(os.environ.get("POCKET_STATE_DIR", HOME / ".claude/state/pocket"))++WHATSAPP_CONFIG = STATE_DIR / "whatsapp-config.json"+EMAIL_CONFIG = STATE_DIR / "email-config.json"+TASKS = STATE_DIR / "tasks.jsonl"+SPAWN_LEDGER = STATE_DIR / "spawn-ledger.jsonl"+RESULTS_DIR = STATE_DIR / "executor-results"+OUT_QUEUE = STATE_DIR / "supervisor-out-queue.jsonl"++SPAWN_CURSOR = STATE_DIR / ".activity-notifier.spawn-cursor"+SEEN_RESULTS = STATE_DIR / ".activity-notifier.seen-results"+LOG_FILE = STATE_DIR / "activity-notifier.log"+HEALTH = STATE_DIR / ".activity-notifier-health"++SKIP_PREFIXES = ("smoketest-", "tasklist-verify-", "teams-smoketest-")+++def now_iso() -> str:+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++def log(msg: str) -> None:+ line = f"{now_iso()} {LOG_PREFIX} {msg}"+ print(line, file=sys.stderr)+ try:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ with LOG_FILE.open("a") as f:+ f.write(line + "\n")+ except OSError:+ pass+++def write_health(status: str, msg: str, extra: dict | None = None) -> None:+ payload = {"status": status, "message": msg, "last_run": now_iso()}+ if extra:+ payload.update(extra)+ try:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ HEALTH.write_text(json.dumps(payload, indent=2))+ except OSError:+ pass+++def load_chat_jid() -> str | None:+ if not WHATSAPP_CONFIG.exists():+ return None+ try:+ cfg = json.loads(WHATSAPP_CONFIG.read_text())+ except (OSError, json.JSONDecodeError):+ return None+ if not cfg.get("enabled"):+ return None+ return cfg.get("chat_jid")+++def load_email_target() -> str | None:+ """Return self-address if email channel is enabled, else None."""+ if not EMAIL_CONFIG.exists():+ return None+ try:+ cfg = json.loads(EMAIL_CONFIG.read_text())+ except (OSError, json.JSONDecodeError):+ return None+ if not cfg.get("enabled"):+ return None+ return cfg.get("self_address") or None+++def load_task_titles() -> dict:+ """Return {task_id: title} from tasks.jsonl."""+ titles = {}+ if not TASKS.exists():+ return titles+ try:+ with TASKS.open() as f:+ for raw in f:+ raw = raw.strip()+ if not raw:+ continue+ try:+ t = json.loads(raw)+ except json.JSONDecodeError:+ continue+ tid = t.get("id")+ if tid:+ titles[tid] = t.get("title", "")+ except OSError:+ pass+ return titles+++def should_skip(task_id: str | None) -> bool:+ if not task_id:+ return True+ return any(task_id.startswith(p) for p in SKIP_PREFIXES)+++def enqueue_whatsapp(chat_jid: str, message: str, media_path: str = "") -> None:+ entry = {+ "ts": now_iso(),+ "kind": "whatsapp",+ "chat_jid": chat_jid,+ "message": message,+ }+ if media_path:+ entry["media_path"] = media_path+ with OUT_QUEUE.open("a") as f:+ f.write(json.dumps(entry) + "\n")+++def enqueue_email(to: str, subject: str, body: str, attachments: list | None = None) -> None:+ entry = {+ "ts": now_iso(),+ "kind": "email",+ "to": to,+ "subject": subject,+ "body": body,+ }+ if attachments:+ entry["attachments"] = list(attachments)+ with OUT_QUEUE.open("a") as f:+ f.write(json.dumps(entry) + "\n")+++def _resolve_attachment(p: str) -> str:+ """Expand ~ and return absolute path if file exists, else empty."""+ if not p:+ return ""+ expanded = os.path.expanduser(p)+ return expanded if os.path.isfile(expanded) else ""+++def process_spawns(chat_jid: str | None, email_to: str | None, titles: dict) -> int:+ """Tail spawn-ledger.jsonl from cursor; enqueue START events to all+ configured channels. Returns number of source-events processed."""+ if not SPAWN_LEDGER.exists():+ return 0+ cursor = 0+ if SPAWN_CURSOR.exists():+ try:+ cursor = int(SPAWN_CURSOR.read_text().strip() or "0")+ except (OSError, ValueError):+ cursor = 0+ try:+ size = SPAWN_LEDGER.stat().st_size+ except OSError:+ return 0+ if cursor > size:+ cursor = 0+ if cursor >= size:+ return 0++ sent = 0+ new_cursor = cursor+ with SPAWN_LEDGER.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 # partial write, retry next tick+ new_cursor = f.tell()+ try:+ entry = json.loads(raw.decode())+ except json.JSONDecodeError:+ continue+ task_id = entry.get("pocket_task_id") or entry.get("task_id")+ if should_skip(task_id):+ continue+ title = entry.get("title") or titles.get(task_id, "")+ worker = entry.get("worker", "worker")+ wa_msg = (+ f"pocket-agent START\n"+ f"task: {task_id}\n"+ f"title: {title[:200]}\n"+ f"worker: {worker}"+ )+ email_body = (+ f"A pocket agent has started work on a task derived from a "+ f"voice memo.\n\n"+ f"task id: {task_id}\n"+ f"title: {title}\n"+ f"worker: {worker}\n\n"+ f"You will receive a DONE notification with the report "+ f"attached when this completes.\n"+ )+ email_subject = f"START — {(title or task_id)[:80]}"+ try:+ if chat_jid:+ enqueue_whatsapp(chat_jid, wa_msg)+ if email_to:+ enqueue_email(email_to, email_subject, email_body)+ sent += 1+ except OSError as e:+ log(f"enqueue START failed: {e}")+ new_cursor = line_start # retry next tick+ break+ try:+ SPAWN_CURSOR.write_text(str(new_cursor))+ except OSError as e:+ log(f"cursor write failed: {e}")+ return sent+++def load_seen_results() -> set[str]:+ if not SEEN_RESULTS.exists():+ return set()+ try:+ data = json.loads(SEEN_RESULTS.read_text())+ return set(data) if isinstance(data, list) else set()+ except (OSError, json.JSONDecodeError):+ return set()+++def save_seen_results(seen: set[str]) -> None:+ try:+ SEEN_RESULTS.write_text(json.dumps(sorted(seen)))+ except OSError as e:+ log(f"save seen-results failed: {e}")+++def process_completions(chat_jid: str | None, email_to: str | None, titles: dict) -> int:+ """Scan executor-results/ for new .done.json / .completed.json files;+ enqueue DONE events to all configured channels with the report file+ attached (WhatsApp media_path + email attachments)."""+ if not RESULTS_DIR.exists():+ return 0+ seen = load_seen_results()+ sent = 0+ new_seen = set(seen)++ for path in sorted(RESULTS_DIR.iterdir()):+ name = path.name+ if name in seen:+ continue+ if not (name.endswith(".done.json") or name.endswith(".completed.json")):+ continue+ try:+ payload = json.loads(path.read_text())+ except (OSError, json.JSONDecodeError) as e:+ log(f"skip unreadable {name}: {e}")+ new_seen.add(name)+ continue++ task_id = (+ payload.get("pocket_task_id")+ or payload.get("task_id")+ or _infer_task_id_from_filename(name)+ )+ if should_skip(task_id):+ new_seen.add(name)+ continue++ summary = (payload.get("summary") or payload.get("text") or "").strip()+ worker = payload.get("worker", "worker")+ title = titles.get(task_id, "")+ output_file = payload.get("output_file", "")+ attachment = _resolve_attachment(output_file)++ # Cap WhatsApp summary length+ wa_summary = summary[:797] + "..." if len(summary) > 800 else summary++ wa_parts = ["pocket-agent DONE", f"task: {task_id}"]+ if title:+ wa_parts.append(f"title: {title[:200]}")+ wa_parts.append(f"worker: {worker}")+ if wa_summary:+ wa_parts.append(f"summary: {wa_summary}")+ if attachment:+ wa_parts.append(f"report: attached ({os.path.basename(attachment)})")+ elif output_file:+ wa_parts.append(f"report: {output_file} (file missing on disk)")+ wa_msg = "\n".join(wa_parts)++ email_body_parts = [+ "A pocket agent has completed work on a task derived from a voice memo.",+ "",+ f"task id: {task_id}",+ f"title: {title or '(no title)'}",+ f"worker: {worker}",+ "",+ "Summary:",+ summary or "(no summary provided)",+ "",+ ]+ if attachment:+ email_body_parts.append(+ f"Report attached: {os.path.basename(attachment)}"+ )+ elif output_file:+ email_body_parts.append(+ f"Report file referenced but not found on disk: {output_file}"+ )+ email_body = "\n".join(email_body_parts)+ email_subject = f"DONE — {(title or task_id)[:80]}"++ try:+ if chat_jid:+ enqueue_whatsapp(chat_jid, wa_msg, media_path=attachment)+ if email_to:+ attachments = [attachment] if attachment else []+ enqueue_email(email_to, email_subject, email_body, attachments)+ sent += 1+ new_seen.add(name)+ except OSError as e:+ log(f"enqueue DONE failed for {name}: {e}")+ break # don't mark seen — retry next tick++ if new_seen != seen:+ save_seen_results(new_seen)+ return sent+++def _infer_task_id_from_filename(name: str) -> str | None:+ # e.g. "inferred-7f5fc681-85c-0.done.json" → "inferred-7f5fc681-85c-0"+ for suffix in (".done.json", ".completed.json"):+ if name.endswith(suffix):+ stem = name[: -len(suffix)]+ # Strip executor-reaper prefix like "2026-05-20T125411_74__worker-..."+ if "__worker-" in stem:+ return None+ return stem+ return None+++def main() -> int:+ write_health("running", "tick")++ chat_jid = load_chat_jid()+ email_to = load_email_target()++ if not chat_jid and not email_to:+ write_health("disabled", "no whatsapp or email channel configured")+ return 0++ titles = load_task_titles()+ starts = process_spawns(chat_jid, email_to, titles)+ dones = process_completions(chat_jid, email_to, titles)++ channels = []+ if chat_jid: channels.append("whatsapp")+ if email_to: channels.append("email")+ write_health(+ "ok",+ f"starts={starts} dones={dones} channels={','.join(channels)}",+ {"starts_enqueued": starts, "dones_enqueued": dones, "channels": channels},+ )+ log(f"done starts={starts} dones={dones} channels={channels}")+ return 0+++if __name__ == "__main__":+ try:+ sys.exit(main())+ except Exception as e:+ log(f"FATAL: {type(e).__name__}: {e}")+ write_health("error", f"{type(e).__name__}: {e}")+ sys.exit(1)diff --git a/claude-ops/scripts/ops-pocket-email-bridge.py b/claude-ops/scripts/ops-pocket-email-bridge.pynew file mode 100755index 00000000..312d85d2--- /dev/null+++ b/claude-ops/scripts/ops-pocket-email-bridge.py@@ -0,0 +1,503 @@+#!/usr/bin/env python3+"""ops-pocket-email-bridge — Email-as-question/reply channel for Pocket.++Mirrors ops-pocket-whatsapp-bridge.py but on Gmail. Two duties:++ 1. OUTBOUND: drain supervisor-out-queue.jsonl entries of kind="email" and+ send them via `gog gmail send` to the configured self-email address.+ Each entry includes a question-id (qid) in the subject so replies can be+ correlated back via Gmail's threading.++ 2. INBOUND: poll Gmail for messages in a known label/thread set, parse the+ owner's natural-language replies against the list of currently-open supervisor+ questions using `claude -p` (Sonnet 4.6), and append matched answers to+ supervisor-replies.jsonl — same downstream format as the WhatsApp bridge.++Config (~/.claude/state/pocket/email-config.json):+ {+ "enabled": true,+ "self_address": "[email protected]",+ "from_account": "[email protected]",+ "subject_prefix": "[Pocket]",+ "label": "Pocket",+ "last_processed_id": "" # auto-managed+ }++Cron: every 1 minute.++Notes:+ - This script can SEND because it operates on self-chat / self-email only.+ Recipient is locked to self_address; refuses any other target.+ - The block-outbound-comms hook does not fire for cron-spawned subprocesses+ (it's a Claude Code PreToolUse hook), so the safety is the locked+ recipient + the audit log.+"""+from __future__ import annotations++import json+import os+import re+import subprocess+import sys+from datetime import datetime, timezone+from pathlib import Path++LOG_PREFIX = "[ops-pocket-email-bridge]"+HOME = Path(os.path.expanduser("~"))+STATE_DIR = Path(os.environ.get("POCKET_STATE_DIR", HOME / ".claude/state/pocket"))+CONFIG = STATE_DIR / "email-config.json"+QUEUE = STATE_DIR / "supervisor-out-queue.jsonl"+OUT_CURSOR = STATE_DIR / ".email-out-cursor"+QUESTIONS = STATE_DIR / "supervisor-questions.jsonl"+REPLIES = STATE_DIR / "supervisor-replies.jsonl"+LOG_FILE = STATE_DIR / "email-bridge.log"+HEALTH = STATE_DIR / ".email-bridge-health"+SENT = STATE_DIR / "email-sent.jsonl"++_USER_CONTEXT_PATH = Path(os.environ.get(+ "POCKET_USER_CONTEXT",+ HOME / ".claude/state/pocket/user-context.json",+))+try:+ _uctx = json.loads(_USER_CONTEXT_PATH.read_text())+ _OWNER_NAME: str = _uctx.get("owner_name") or "the user"+except (OSError, json.JSONDecodeError):+ _OWNER_NAME = "the user"++GOG_BIN = os.environ.get("GOG_BIN", "gog")+TIMEOUT = int(os.environ.get("EMAIL_BRIDGE_TIMEOUT", "60"))+++def now_iso() -> str:+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++def log(msg: str) -> None:+ line = f"{now_iso()} {LOG_PREFIX} {msg}"+ print(line, file=sys.stderr)+ try:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ with LOG_FILE.open("a") as f:+ f.write(line + "\n")+ except OSError:+ pass+++def write_health(status: str, msg: str = "", extra: dict | None = None) -> None:+ payload = {"status": status, "message": msg, "last_run": now_iso()}+ if extra:+ payload.update(extra)+ try:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ HEALTH.write_text(json.dumps(payload, indent=2))+ except OSError:+ pass+++def load_config() -> dict:+ if not CONFIG.exists():+ return {"enabled": False}+ try:+ return json.loads(CONFIG.read_text())+ except (OSError, json.JSONDecodeError):+ return {"enabled": False}+++def save_config(cfg: dict) -> None:+ try:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ CONFIG.write_text(json.dumps(cfg, indent=2))+ except OSError as e:+ log(f"config save failed: {e}")+++def open_questions() -> list[dict]:+ if not QUESTIONS.exists():+ return []+ out = []+ try:+ for line in QUESTIONS.read_text().splitlines():+ line = line.strip()+ if not line:+ continue+ try:+ q = json.loads(line)+ if q.get("status") == "open":+ out.append(q)+ except json.JSONDecodeError:+ continue+ except OSError:+ pass+ return out+++# ── OUTBOUND ────────────────────────────────────────────────────────────────+++def send_email(to: str, subject: str, body: str, attachments: list[str] | None = None) -> tuple[bool, str]:+ """Send via gog gmail send. Returns (ok, info).++ attachments: list of file paths to attach (each is expanded with ~ and+ silently skipped if missing — we never fail the whole send because of+ a missing report file)."""+ cmd = [GOG_BIN, "gmail", "send",+ "--to", to,+ "--subject", subject,+ "--body", body]+ if attachments:+ for a in attachments:+ if not a:+ continue+ expanded = os.path.expanduser(a)+ if os.path.isfile(expanded):+ cmd.extend(["--attach", expanded])+ else:+ log(f"attachment missing, skipped: {a}")+ try:+ proc = subprocess.run(cmd, capture_output=True, text=True, timeout=TIMEOUT)+ except subprocess.TimeoutExpired:+ return (False, "timeout")+ except FileNotFoundError:+ return (False, f"gog binary not found: {GOG_BIN}")+ except Exception as e:+ return (False, f"{type(e).__name__}: {e}")+ if proc.returncode != 0:+ return (False, f"exit={proc.returncode}: {(proc.stderr or proc.stdout)[:200]}")+ return (True, (proc.stdout or "ok")[:200])+++def drain_outbound(cfg: dict) -> tuple[int, int, int]:+ """Drain supervisor-out-queue.jsonl entries with kind='email'. Returns+ (sent, failed, skipped)."""+ self_addr = cfg.get("self_address", "")+ prefix = cfg.get("subject_prefix", "[Pocket]")+ if not self_addr or not QUEUE.exists():+ return (0, 0, 0)+ cursor = 0+ if OUT_CURSOR.exists():+ try:+ cursor = int(OUT_CURSOR.read_text().strip() or "0")+ except (OSError, ValueError):+ cursor = 0+ try:+ size = QUEUE.stat().st_size+ except OSError:+ return (0, 0, 0)+ if cursor > size:+ cursor = 0+ if cursor >= size:+ return (0, 0, 0)++ sent = 0+ failed = 0+ skipped = 0+ new_cursor = cursor+ try:+ with QUEUE.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+ new_cursor = f.tell()+ try:+ entry = json.loads(raw.decode())+ except json.JSONDecodeError:+ skipped += 1+ continue+ if entry.get("kind") != "email":+ skipped += 1+ continue+ to = entry.get("to") or self_addr+ if to != self_addr:+ log(f"REFUSED: to {to!r} != self_address {self_addr!r}")+ skipped += 1+ continue+ qid = entry.get("qid", "")+ subj_core = entry.get("subject", "").strip() or "supervisor message"+ subject = (+ f"{prefix} [qid:{qid}] {subj_core}"+ if qid else f"{prefix} {subj_core}"+ )+ body = (entry.get("body") or entry.get("message") or "").strip()+ if not body:+ skipped += 1+ continue+ attachments = entry.get("attachments") or []+ if not isinstance(attachments, list):+ attachments = []+ ok, info = send_email(to, subject[:200], body, attachments)+ if ok:+ sent += 1+ try:+ with SENT.open("a") as sf:+ sf.write(json.dumps({+ "ts": now_iso(), "to": to, "subject": subject,+ "qid": qid, "body": body[:500],+ "info": info[:150],+ }) + "\n")+ except OSError:+ pass+ log(f"sent → {to} subject={subject[:80]!r}")+ else:+ failed += 1+ log(f"FAILED → {to}: {info}")+ new_cursor = line_start # retry next tick+ break+ except OSError as e:+ log(f"read queue failed: {e}")+ return (sent, failed, skipped)+ try:+ OUT_CURSOR.write_text(str(new_cursor))+ except OSError:+ pass+ return (sent, failed, skipped)+++# ── INBOUND ─────────────────────────────────────────────────────────────────+++QID_SUBJECT_RE = re.compile(r"\[qid:([a-zA-Z0-9_-]{4,})\]")+++def fetch_recent_replies(cfg: dict) -> list[dict]:+ """Use gog gmail search to find recent messages in the configured label+ that are NOT from self (so we only get the owner's replies, not echoes).+ Returns list of {messageId, threadId, subject, body, ts, fromMe}.+ """+ label = cfg.get("label", "Pocket")+ # Look for messages sent by the account owner in the label, within last 24h.+ query = f"label:{label} from:me newer_than:1d"+ try:+ proc = subprocess.run(+ [GOG_BIN, "gmail", "search", query,+ "--max", "30", "-j", "--results-only", "--no-input"],+ capture_output=True, text=True, timeout=TIMEOUT,+ )+ except (subprocess.TimeoutExpired, FileNotFoundError) as e:+ log(f"gog search failed: {e}")+ return []+ if proc.returncode != 0:+ log(f"gog search exit={proc.returncode}: {(proc.stderr or '')[:200]}")+ return []+ try:+ data = json.loads(proc.stdout or "[]")+ except json.JSONDecodeError:+ log("gog search returned non-JSON")+ return []+ if isinstance(data, dict):+ data = data.get("threads") or data.get("results") or []+ out = []+ for item in data if isinstance(data, list) else []:+ msg_id = item.get("messageId") or item.get("id")+ thread_id = item.get("threadId") or item.get("thread_id")+ subject = item.get("subject", "")+ body = item.get("snippet") or item.get("body", "")+ ts = item.get("internalDate") or item.get("date") or ""+ if not msg_id:+ continue+ out.append({+ "id": msg_id, "thread_id": thread_id,+ "subject": subject, "body": body, "ts": ts,+ })+ return out+++def parse_reply_with_llm(body: str, opens: list[dict], parser_model: str) -> list[dict]:+ """Same parse logic as the WhatsApp bridge — invoke claude -p Sonnet+ against the open questions list and extract structured answers."""+ body = body.strip()+ if not body or not opens:+ return []+ open_descriptions = "\n".join(+ f"- {q.get('id','?')} | worker={q.get('from_worker','?')} | options={q.get('options') or []}\n"+ f" Q: {q.get('question','')[:300]}\n"+ f" context: {(q.get('context') or '')[:200]}"+ for q in opens+ )+ prompt = f"""You are the inbound-reply parser for {_OWNER_NAME}'s Pocket supervisor.++{_OWNER_NAME} just sent an EMAIL reply. Your job: figure out which of the currently-open supervisor questions they are replying to (it may be one, several, or none), and extract the answer in a form the worker can use.++Currently-open questions:+{open_descriptions}++Their email body:+\"\"\"{body[:4000]}\"\"\"++Rules:+- If their message is clearly not a reply to any open question, return an empty array.+- If they address one specific question, return one item.+- If they address multiple, return multiple items.+- The 'answer' field should be in their voice and natural — the worker reads it as a direct instruction.+- 'confidence' is your honest 0.0-1.0 estimate.+- Output STRICT JSON array, no markdown fences, no prose.++Schema:+[+ {{"qid": "q-...", "answer": "<rewritten as imperative>", "confidence": 0.0-1.0, "reasoning": "<one sentence>"}}+]+"""+ claude_bin = os.environ.get("POCKET_CLAUDE_BIN", str(HOME / ".local/bin/claude"))+ env = {k: v for k, v in os.environ.items() if k != "ANTHROPIC_API_KEY"}+ cmd = [claude_bin, "--dangerously-skip-permissions",+ "--model", parser_model, "-p", prompt]+ try:+ proc = subprocess.run(cmd, env=env, capture_output=True, text=True, timeout=90)+ except subprocess.TimeoutExpired:+ log("claude -p parser timed out")+ return []+ except Exception as e:+ log(f"claude -p parser invoke failed: {type(e).__name__}: {e}")+ return []+ if proc.returncode != 0:+ log(f"claude -p parser exit {proc.returncode}: {proc.stderr.strip()[:200]}")+ return []+ text = (proc.stdout or "").strip()+ text = re.sub(r"^```(?:json)?\s*", "", text)+ text = re.sub(r"\s*```$", "", text)+ try:+ items = json.loads(text)+ except json.JSONDecodeError:+ log(f"parser returned non-JSON: {text[:200]}")+ return []+ if not isinstance(items, list):+ return []+ open_ids = {q["id"] for q in opens}+ out = []+ for it in items:+ if not isinstance(it, dict):+ continue+ qid = it.get("qid")+ if qid not in open_ids:+ continue+ ans = (it.get("answer") or "").strip()+ if not ans:+ continue+ try:+ conf = float(it.get("confidence", 0))+ except (TypeError, ValueError):+ conf = 0.0+ out.append({+ "qid": qid, "answer": ans, "confidence": conf,+ "reasoning": (it.get("reasoning") or "")[:300],+ })+ return out+++def drain_inbound(cfg: dict) -> tuple[int, int]:+ """Returns (scanned, routed). Uses subject [qid:...] as fast-path before+ falling back to LLM parse over open-question list."""+ last_id = cfg.get("last_processed_id", "")+ messages = fetch_recent_replies(cfg)+ if not messages:+ return (0, 0)+ # Filter: only NEW messages (strictly after last_processed_id in this window)+ new_messages: list[dict] = []+ if not last_id:+ new_messages = list(messages)+ else:+ past_cursor = False+ for m in messages:+ if past_cursor:+ new_messages.append(m)+ elif m["id"] == last_id:+ past_cursor = True+ # If last_id wasn't found in current window, treat all as new (first run / drift)+ if not any(m["id"] == last_id for m in messages):+ new_messages = list(messages)++ opens = open_questions()+ parser_model = cfg.get("parser_model", "claude-sonnet-4-6")+ scanned = 0+ routed = 0+ new_last_id = last_id++ for m in new_messages:+ new_last_id = m["id"]+ scanned += 1+ subject = m.get("subject", "")+ body = m.get("body", "") or ""+ if not body.strip():+ continue++ # Fast-path: subject contains [qid:<id>]+ qid_match = QID_SUBJECT_RE.search(subject)+ results: list[dict] = []+ if qid_match:+ qid = qid_match.group(1)+ if any(q["id"] == qid for q in opens):+ results = [{+ "qid": qid,+ "answer": body.strip()[:1000],+ "confidence": 0.95,+ "reasoning": f"matched [qid:{qid}] in email subject",+ }]+ if not results and opens:+ results = parse_reply_with_llm(body, opens, parser_model)+ if not results:+ log(f"msg {m['id']}: no actionable reply in '{body[:80]}...'")+ continue+ for r in results:+ qid = r["qid"]+ try:+ REPLIES.parent.mkdir(parents=True, exist_ok=True)+ with REPLIES.open("a") as f:+ f.write(json.dumps({+ "id": qid, "ts": now_iso(),+ "answer": r["answer"], "via": "email",+ "source_msg_id": m["id"],+ "source_subject": subject[:200],+ "source_body": body[:500],+ "parser_confidence": r["confidence"],+ "parser_reasoning": r["reasoning"],+ "parser_model": parser_model,+ }) + "\n")+ routed += 1+ opens = [q for q in opens if q["id"] != qid]+ log(f"routed reply for {qid} (conf={r['confidence']:.2f}): {r['answer'][:60]}")+ except OSError as e:+ log(f"reply write failed: {e}")++ cfg["last_processed_id"] = new_last_id or last_id+ save_config(cfg)+ return (scanned, routed)+++def main() -> int:+ write_health("running", "tick")+ cfg = load_config()+ if not cfg.get("enabled"):+ write_health("disabled", "email bridge disabled")+ return 0+ if not cfg.get("self_address"):+ log("missing self_address in config")+ write_health("error", "missing self_address")+ return 1++ sent, failed, skipped = drain_outbound(cfg)+ scanned, routed = drain_inbound(cfg)++ write_health(+ "ok" if failed == 0 else "warn",+ f"out_sent={sent} out_failed={failed} in_scanned={scanned} in_routed={routed}",+ extra={+ "out_sent": sent, "out_failed": failed, "out_skipped": skipped,+ "in_scanned": scanned, "in_routed": routed,+ "self_address": cfg.get("self_address"),+ },+ )+ log(f"done out_sent={sent} out_failed={failed} in_scanned={scanned} in_routed={routed}")+ return 0+++if __name__ == "__main__":+ try:+ sys.exit(main())+ except Exception as e:+ log(f"FATAL: {type(e).__name__}: {e}")+ write_health("error", f"{type(e).__name__}: {e}")+ sys.exit(1)diff --git a/claude-ops/scripts/ops-pocket-out-queue.py b/claude-ops/scripts/ops-pocket-out-queue.pynew file mode 100755index 00000000..975192fc--- /dev/null+++ b/claude-ops/scripts/ops-pocket-out-queue.py@@ -0,0 +1,233 @@+#!/usr/bin/env python3+"""ops-pocket-out-queue — Drain supervisor-out-queue.jsonl to WhatsApp.++Reads new entries from ~/.claude/state/pocket/supervisor-out-queue.jsonl,+posts each to the Baileys bridge HTTP API (POST localhost:8080/api/send),+tracks cursor to avoid replays. Self-chat alerts only — recipient is fixed+to whatsapp-config.json's chat_jid (Sam's self-chat). Per-message; no batch.++Cron: every 1 minute.++Safety:+ - Recipient JID is locked to the configured self-chat. We refuse any+ queue entry whose chat_jid differs from the configured value.+ - Each entry sent individually; failed sends remain at cursor for retry.+ - Idempotency: cursor advances only on 200 OK from bridge.+"""+from __future__ import annotations++import json+import os+import sys+import time+import urllib.error+import urllib.request+from datetime import datetime, timezone+from pathlib import Path++LOG_PREFIX = "[ops-pocket-out-queue]"+HOME = Path(os.path.expanduser("~"))+STATE_DIR = Path(os.environ.get("POCKET_STATE_DIR", HOME / ".claude/state/pocket"))+QUEUE = STATE_DIR / "supervisor-out-queue.jsonl"+CURSOR = STATE_DIR / ".out-queue-cursor"+CONFIG = STATE_DIR / "whatsapp-config.json"+LOG_FILE = STATE_DIR / "out-queue.log"+HEALTH = STATE_DIR / ".out-queue-health"+SENT = STATE_DIR / "out-queue-sent.jsonl"++BRIDGE_URL = os.environ.get("WHATSAPP_BRIDGE_URL", "http://localhost:8080/api/send")+TIMEOUT = int(os.environ.get("OUT_QUEUE_TIMEOUT", "15"))+++def now_iso() -> str:+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++def log(msg: str) -> None:+ line = f"{now_iso()} {LOG_PREFIX} {msg}"+ print(line, file=sys.stderr)+ try:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ with LOG_FILE.open("a") as f:+ f.write(line + "\n")+ except OSError:+ pass+++def write_health(status: str, msg: str, extra: dict | None = None) -> None:+ payload = {"status": status, "message": msg, "last_run": now_iso()}+ if extra:+ payload.update(extra)+ try:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ HEALTH.write_text(json.dumps(payload, indent=2))+ except OSError:+ pass+++def load_config() -> dict:+ if not CONFIG.exists():+ return {"enabled": False}+ try:+ return json.loads(CONFIG.read_text())+ except (OSError, json.JSONDecodeError):+ return {"enabled": False}+++def post_send(recipient: str, message: str, media_path: str = "") -> tuple[bool, str]:+ payload = {"recipient": recipient, "message": message}+ if media_path:+ payload["media_path"] = media_path+ body = json.dumps(payload).encode()+ req = urllib.request.Request(+ BRIDGE_URL, data=body, method="POST",+ headers={"Content-Type": "application/json"},+ )+ try:+ with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:+ text = resp.read().decode(errors="replace")[:300]+ return (200 <= resp.status < 300, f"{resp.status}: {text}")+ except urllib.error.HTTPError as e:+ err = ""+ try:+ err = e.read().decode(errors="replace")[:200]+ except Exception:+ pass+ return (False, f"http_{e.code}: {err}")+ except Exception as e:+ return (False, f"{type(e).__name__}: {e}")+++def main() -> int:+ write_health("running", "tick")++ cfg = load_config()+ if not cfg.get("enabled") or not cfg.get("chat_jid"):+ write_health("disabled", "no chat_jid configured")+ return 0+ expected_jid = cfg["chat_jid"]++ if not QUEUE.exists():+ write_health("ok", "no queue file", {"sent": 0, "skipped": 0})+ return 0++ # Cursor = byte offset into QUEUE+ cursor = 0+ if CURSOR.exists():+ try:+ cursor = int(CURSOR.read_text().strip() or "0")+ except (OSError, ValueError):+ cursor = 0++ try:+ size = QUEUE.stat().st_size+ except OSError as e:+ log(f"stat queue failed: {e}")+ write_health("error", f"stat: {e}")+ return 1++ if cursor > size:+ log(f"cursor {cursor} > size {size} (queue truncated); resetting to 0")+ cursor = 0++ if cursor >= size:+ write_health("ok", "no new entries", {"cursor": cursor, "size": size})+ return 0++ sent = 0+ failed = 0+ skipped = 0+ new_cursor = cursor++ try:+ with QUEUE.open("rb") as f:+ f.seek(cursor)+ while True:+ line_start = f.tell()+ raw = f.readline()+ if not raw:+ break+ # Only process complete lines (must end with \n)+ if not raw.endswith(b"\n"):+ # Partial write — stop at last-good cursor+ break+ new_cursor = f.tell()+ try:+ entry = json.loads(raw.decode())+ except json.JSONDecodeError as e:+ log(f"skip malformed @offset={line_start}: {e}")+ skipped += 1+ continue+ if entry.get("kind") != "whatsapp":+ skipped += 1+ continue+ jid = entry.get("chat_jid", "")+ msg = (entry.get("message") or "").strip()+ if not msg:+ skipped += 1+ continue+ if jid != expected_jid:+ log(f"REFUSED: jid {jid!r} != configured {expected_jid!r}")+ skipped += 1+ continue+ media_path = (entry.get("media_path") or "").strip()+ if media_path:+ # Expand ~ and validate the file exists; if missing,+ # send text-only rather than failing the whole entry.+ expanded = os.path.expanduser(media_path)+ if os.path.isfile(expanded):+ media_path = expanded+ else:+ log(f"media_path missing, sending text-only: {media_path}")+ media_path = ""+ ok, info = post_send(jid, msg, media_path)+ if ok:+ sent += 1+ try:+ with SENT.open("a") as sf:+ sf.write(json.dumps({+ "ts": now_iso(),+ "chat_jid": jid,+ "message": msg[:500],+ "source_ts": entry.get("ts"),+ "bridge_response": info[:150],+ }) + "\n")+ except OSError:+ pass+ log(f"sent → {jid[:24]}... msg='{msg[:60]}...'")+ else:+ failed += 1+ log(f"FAILED → {jid[:24]}... err={info}")+ # Rewind cursor so we retry next tick+ new_cursor = line_start+ break+ # Small pacing between sends (avoid bridge rate-limit)+ time.sleep(0.5)+ except OSError as e:+ log(f"read queue failed: {e}")+ write_health("error", f"read: {e}")+ return 2++ # Persist cursor+ try:+ CURSOR.write_text(str(new_cursor))+ except OSError as e:+ log(f"cursor write failed: {e}")++ write_health(+ "ok" if failed == 0 else "warn",+ f"sent={sent} failed={failed} skipped={skipped}",+ {"sent": sent, "failed": failed, "skipped": skipped,+ "cursor": new_cursor, "queue_size": size},+ )+ log(f"done sent={sent} failed={failed} skipped={skipped} cursor={new_cursor}/{size}")+ return 0+++if __name__ == "__main__":+ try:+ sys.exit(main())+ except Exception as e:+ log(f"FATAL: {type(e).__name__}: {e}")+ write_health("error", f"{type(e).__name__}: {e}")+ sys.exit(1)diff --git a/claude-ops/scripts/ops-pocket-triage.py b/claude-ops/scripts/ops-pocket-triage.pynew file mode 100755index 00000000..f84d176b--- /dev/null+++ b/claude-ops/scripts/ops-pocket-triage.py@@ -0,0 +1,373 @@+#!/usr/bin/env python3+"""ops-pocket-triage — Opus-powered safety gate for Pocket-inferred tasks.++Reads pending-triage.jsonl, asks Opus (with extended thinking) for each item:+ "Is this something a Claude Code agent can safely execute autonomously+ given Sam's known rules and the task's domain?"++Routes each task into one of four buckets:++ ACT → tasks.jsonl (supervisor will pick up, dispatch a worker)+ DRAFT → drafts.jsonl (outbound content; Rule 6 — per-message approval)+ DROP → dropped.jsonl (personal / private / non-task / duplicate / silly)+ ASK → review.jsonl (high-stakes or ambiguous; Sam must decide)++A reasoning trace (Opus's extended-thinking summary) is persisted for every+decision so the call is auditable.++Safety doctrine — the model is told that "safe to ACT autonomously" means:+ • READ-ONLY by default (file scans, API health checks, log review, etc.)+ • State-mutating ops only when the mutation is local, reversible, scoped+ to Sam's own infra, and not financial or identity-touching.+ • NEVER autonomous: outbound comms, account creation, signing/auth flows,+ spending money, personal/family/household, anything involving someone+ else's consent.+ • ASK when intent is ambiguous, scope is unclear, or the cost of acting+ wrongly is high.++Env:+ POCKET_STATE_DIR default ~/.claude/state/pocket+ POCKET_TRIAGE_MODEL default claude-opus-4-7+ POCKET_TRIAGE_THINKING_TOKENS default 4000+ POCKET_TRIAGE_MAX_TOKENS default 1500+ POCKET_TRIAGE_DRY_RUN=1 skip routing writes, just log decisions+ ANTHROPIC_API_KEY / Claude Code OAuth (auto-resolved from keychain)++Files (under POCKET_STATE_DIR):+ pending-triage.jsonl IN — produced by watcher+ tasks.jsonl OUT — ACT verdicts (append)+ drafts.jsonl OUT — DRAFT verdicts (append)+ dropped.jsonl OUT — DROP audit log (append)+ review.jsonl OUT — ASK queue for Sam+ triage-decisions.jsonl OUT — full audit of every decision + thinking+"""+from __future__ import annotations++import json+import os+import subprocess+import sys+import time+from datetime import datetime, timezone+from pathlib import Path++LOG_PREFIX = "[ops-pocket-triage]"+HOME = Path(os.path.expanduser("~"))++# ---------------------------------------------------------------------------+# User identity context — loaded from ~/.claude/state/pocket/user-context.json+# Shape:+# {+# "owner_name": "Your Name",+# "team_members": ["Teammate One", "Teammate Two"]+# }+# This file is in user state and must NOT be committed to source control.+# If the file is missing, generic placeholders are used (no crash).+# ---------------------------------------------------------------------------+_USER_CONTEXT_PATH = Path(os.environ.get(+ "POCKET_USER_CONTEXT",+ HOME / ".claude/state/pocket/user-context.json",+))+try:+ _ctx = json.loads(_USER_CONTEXT_PATH.read_text())+ _OWNER_NAME: str = _ctx.get("owner_name") or "the user"+ _TEAM_MEMBERS: list[str] = _ctx.get("team_members") or []+except (OSError, json.JSONDecodeError):+ _OWNER_NAME = "the user"+ _TEAM_MEMBERS = []++_TEAM_MEMBERS_DESC = (+ ", ".join(_TEAM_MEMBERS)+ if _TEAM_MEMBERS+ else "team members (configure in user-context.json)"+)++STATE_DIR = Path(os.environ.get("POCKET_STATE_DIR", HOME / ".claude/state/pocket"))+MODEL = os.environ.get("POCKET_TRIAGE_MODEL", "claude-opus-4-7")+THINKING_BUDGET = int(os.environ.get("POCKET_TRIAGE_THINKING_TOKENS", "4000"))+MAX_TOKENS = int(os.environ.get("POCKET_TRIAGE_MAX_TOKENS", "1500"))+DRY_RUN = os.environ.get("POCKET_TRIAGE_DRY_RUN") == "1"++PENDING = STATE_DIR / "pending-triage.jsonl"+TASKS = STATE_DIR / "tasks.jsonl"+DRAFTS = STATE_DIR / "drafts.jsonl"+DROPPED = STATE_DIR / "dropped.jsonl"+REVIEW = STATE_DIR / "review.jsonl"+AUDIT = STATE_DIR / "triage-decisions.jsonl"+HEALTH = STATE_DIR / ".triage-health"+LOG_FILE = STATE_DIR / "triage.log"+++def now_iso() -> str:+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++def log(msg: str) -> None:+ line = f"{now_iso()} {LOG_PREFIX} {msg}"+ print(line, file=sys.stderr)+ try:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ with LOG_FILE.open("a") as f:+ f.write(line + "\n")+ except OSError:+ pass+++def write_health(status: str, msg: str = "", extra: dict | None = None) -> None:+ payload = {"status": status, "message": msg, "last_run": now_iso()}+ if extra:+ payload.update(extra)+ try:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ HEALTH.write_text(json.dumps(payload, indent=2))+ except OSError as e:+ log(f"health write failed: {e}")+++_SYSTEM_PROMPT_TEMPLATE = """You are the safety triage agent for {owner_name}'s personal automation pipeline. {owner_name} records voice memos via Pocket AI. A Haiku layer extracts implicit tasks from each transcript. Your job is to decide, for ONE candidate task at a time, whether a Claude Code subagent can safely execute it autonomously on their machine.++Use extended thinking. Reason step-by-step about:+ 1. Domain — is this business/code, or personal/family/household?+ 2. Reversibility — can a wrong action be undone cheaply?+ 3. External effects — does it touch other humans (email, Slack, calendars)? Spend money? Create accounts? Sign anything?+ 4. Information needed — would the agent need the owner's identity, ID documents, biometric, or in-person presence?+ 5. Ambiguity — is the task scope clear, or is the agent likely to invent the wrong thing?+ 6. Duplication / staleness — is this likely already done, or so vague it's a musing rather than a task?++Then assign exactly ONE verdict:++ ACT — A Claude Code subagent can safely execute this autonomously. Defaults: read-only (file scans, API health, log review, AWS describe-*, code analysis, repo status). Mutations only if local-and-reversible (write a draft file, run tests, generate a report). NO outbound, NO money, NO identity ops.++ DRAFT — The task produces outbound content (email, Slack, WhatsApp, social post, calendar invite). The subagent can DRAFT it but must NEVER send. Per the owner's Rule 6, every outbound message needs per-message approval.++ DROP — Not appropriate for autonomous execution AND not worth the owner's manual review. Examples: personal/family/household tasks ("kitchen quote"), study plans, vague musings, things that need the owner's body or ID in person, items the agent has no chance of doing well.++ ASK — Ambiguous, high-stakes, or scope-unclear. Worth the owner reviewing before committing to a category. Examples: tasks needing ID/face verification, judgment calls involving other people, high-stakes decisions.++Return STRICT JSON, no markdown, no prose outside the JSON:++{{+ "verdict": "ACT" | "DRAFT" | "DROP" | "ASK",+ "confidence": 0.0-1.0,+ "reasoning": "<2-4 sentence summary of why — distill your extended thinking>",+ "scoped_task_description": "<if ACT: a tightened, executable version of the task; if DRAFT: what the draft should cover; else: empty>",+ "concerns": ["<any specific risks the executing agent should know>"]+}}++Owner context (NEVER assume otherwise):+ • Owner name: {owner_name}+ • Known team members: {team_members}+ • Per the owner's global CLAUDE.md, outbound comms are NEVER autonomously sent. Period.+ • Per the owner's global CLAUDE.md, infrastructure mutations require explicit confirmation.+ • Personal/family items are out of scope for this pipeline.+"""++SYSTEM_PROMPT = _SYSTEM_PROMPT_TEMPLATE.format(+ owner_name=_OWNER_NAME,+ team_members=_TEAM_MEMBERS_DESC,+)+++def triage_one(task: dict) -> dict:+ """Run triage via `claude -p` subprocess (uses Claude Code's internal+ session — same auth as the user's interactive chat, no per-token rate+ limits). ANTHROPIC_API_KEY is unset for the call so OAuth wins (a stale+ invalid key in shell env would otherwise short-circuit Claude Code).+ """+ user_msg = (+ f"{SYSTEM_PROMPT}\n\n"+ f"---\n\n"+ f"Candidate inferred task to triage:\n\n"+ f"Title: {task.get('title','(none)')}\n"+ f"Priority hint: {task.get('priority','(none)')}\n"+ f"Confidence (from Haiku inference): {task.get('confidence','(none)')}\n"+ f"Context from recording: {task.get('context','(none)')}\n"+ f"Source recording id: {task.get('recording_id','(none)')}\n"+ f"Captured at: {task.get('captured_at','(none)')}\n\n"+ f"Think carefully then output ONLY the JSON object — no prose, no markdown fences."+ )++ claude_bin = os.environ.get("POCKET_CLAUDE_BIN", str(HOME / ".local/bin/claude"))+ env = {k: v for k, v in os.environ.items() if k != "ANTHROPIC_API_KEY"}+ cmd = [claude_bin, "--dangerously-skip-permissions",+ "--model", MODEL, "-p", user_msg]+ try:+ proc = subprocess.run(+ cmd, env=env, capture_output=True, text=True, timeout=180,+ )+ except subprocess.TimeoutExpired:+ return {+ "verdict": "ASK", "confidence": 0.0,+ "reasoning": "claude -p timed out after 180s; defaulted to ASK.",+ "scoped_task_description": "", "concerns": ["timeout"],+ "_error": "timeout",+ }+ except Exception as e:+ return {+ "verdict": "ASK", "confidence": 0.0,+ "reasoning": f"claude -p invocation failed: {type(e).__name__}; defaulted to ASK.",+ "scoped_task_description": "", "concerns": [str(e)[:160]],+ "_error": "spawn_failed",+ }++ if proc.returncode != 0:+ return {+ "verdict": "ASK", "confidence": 0.0,+ "reasoning": f"claude -p exited {proc.returncode}; defaulted to ASK.",+ "scoped_task_description": "",+ "concerns": [proc.stderr.strip()[:160] or proc.stdout.strip()[:160]],+ "_error": f"exit_{proc.returncode}",+ }++ text_out = (proc.stdout or "").strip()+ thinking_text = "" # claude -p plain mode doesn't expose thinking; that's fine — reasoning is in JSON field+ # Strip markdown fences if any+ if text_out.startswith("```"):+ import re as _re+ text_out = _re.sub(r"^```(?:json)?\s*", "", text_out)+ text_out = _re.sub(r"\s*```$", "", text_out)++ try:+ decision = json.loads(text_out)+ except json.JSONDecodeError:+ log(f"Opus returned bad JSON: {text_out[:200]}")+ decision = {+ "verdict": "ASK", "confidence": 0.0,+ "reasoning": "Opus output unparseable; defaulting to ASK.",+ "scoped_task_description": "", "concerns": [f"bad json: {text_out[:80]}"],+ }+ decision["_thinking"] = thinking_text.strip()[:4000]+ decision["_model"] = MODEL+ decision["_raw_output_len"] = len(text_out)+ return decision+++def append_jsonl(path: Path, obj: dict) -> None:+ if DRY_RUN:+ return+ path.parent.mkdir(parents=True, exist_ok=True)+ with path.open("a") as f:+ f.write(json.dumps(obj) + "\n")+++def _id_already_routed(task_id: str) -> str | None:+ """Idempotency guard: scan all 4 destination files for this id. Returns+ the route name (TASKS|DRAFTS|DROPPED|REVIEW) if found, else None.+ Prevents the same inferred task from being routed twice if the watcher+ re-queues it (cursor rewind, seen-set reset, etc).+ """+ if not task_id:+ return None+ for label, p in (("TASKS", TASKS), ("DRAFTS", DRAFTS),+ ("DROPPED", DROPPED), ("REVIEW", REVIEW)):+ if not p.exists():+ continue+ try:+ for line in p.read_text().splitlines():+ line = line.strip()+ if not line:+ continue+ try:+ e = json.loads(line)+ except json.JSONDecodeError:+ continue+ if e.get("id") == task_id:+ return label+ except OSError:+ continue+ return None+++def route(task: dict, decision: dict) -> str:+ """Write task to the correct destination based on verdict. Returns route name."""+ verdict = (decision.get("verdict") or "ASK").upper()+ # Idempotency: skip if this id is already routed somewhere+ task_id = task.get("id", "")+ prior = _id_already_routed(task_id)+ if prior:+ log(f"SKIP {task_id} — already in {prior}")+ return f"SKIP_{prior}"+ routed = dict(task)+ routed["triage"] = {+ "verdict": verdict,+ "confidence": decision.get("confidence"),+ "reasoning": decision.get("reasoning"),+ "scoped": decision.get("scoped_task_description"),+ "concerns": decision.get("concerns"),+ "model": decision.get("_model"),+ "decided_at": now_iso(),+ }+ if verdict == "ACT":+ # Promote: use scoped description if provided, keep original context+ if decision.get("scoped_task_description"):+ routed["title"] = decision["scoped_task_description"][:140] or routed.get("title")+ routed["kind"] = "task" # supervisor treats these like manual tasks+ routed["promoted_from"] = "inferred"+ append_jsonl(TASKS, routed)+ elif verdict == "DRAFT":+ routed["kind"] = "draft_email" # generic outbound kind; supervisor leaves alone+ append_jsonl(DRAFTS, routed)+ elif verdict == "DROP":+ append_jsonl(DROPPED, routed)+ else: # ASK+ append_jsonl(REVIEW, routed)+ return verdict+++def main() -> int:+ write_health("running", "triage tick")+ log(f"start (dry_run={DRY_RUN}, model={MODEL})")++ if not PENDING.exists() or PENDING.stat().st_size == 0:+ log("no pending items — nothing to triage")+ write_health("ok", "no pending items", extra={"counts": {}})+ return 0++ tasks = []+ for raw in PENDING.read_text().splitlines():+ raw = raw.strip()+ if not raw:+ continue+ try:+ tasks.append(json.loads(raw))+ except json.JSONDecodeError as e:+ log(f"bad jsonl: {e}")+ log(f"loaded {len(tasks)} pending items")++ counts = {"ACT": 0, "DRAFT": 0, "DROP": 0, "ASK": 0}+ inter_call_pause = float(os.environ.get("POCKET_TRIAGE_PACE_SEC", "8"))+ for i, task in enumerate(tasks, 1):+ if i > 1 and inter_call_pause > 0:+ time.sleep(inter_call_pause) # avoid bursting Claude Max quota+ title = (task.get("title") or "")[:70]+ log(f"[{i}/{len(tasks)}] triaging: {title}")+ decision = triage_one(task)+ verdict = route(task, decision)+ counts[verdict] = counts.get(verdict, 0) + 1+ log(f"[{i}/{len(tasks)}] verdict={verdict} conf={decision.get('confidence')} — {decision.get('reasoning','')[:120]}")+ # Audit log every decision with full thinking+ append_jsonl(AUDIT, {+ "ts": now_iso(),+ "task": task,+ "decision": decision,+ "routed_to": verdict,+ })++ # Truncate pending if not dry run (consumed)+ if not DRY_RUN:+ PENDING.write_text("")+ log(f"done counts={counts}")+ write_health("ok", f"triaged={sum(counts.values())}", extra={"counts": counts})+ return 0+++if __name__ == "__main__":+ try:+ sys.exit(main())+ except KeyboardInterrupt:+ log("interrupted")+ sys.exit(130)+ except Exception as e:+ log(f"FATAL: {type(e).__name__}: {e}")+ write_health("error", f"{type(e).__name__}: {e}")+ sys.exit(1)diff --git a/claude-ops/scripts/ops-pocket-whatsapp-bridge.py b/claude-ops/scripts/ops-pocket-whatsapp-bridge.pynew file mode 100755index 00000000..6f93784a--- /dev/null+++ b/claude-ops/scripts/ops-pocket-whatsapp-bridge.py@@ -0,0 +1,341 @@+#!/usr/bin/env python3+"""ops-pocket-whatsapp-bridge — WhatsApp ↔ supervisor question/reply bridge.++Inbound: polls the Baileys bridge SQLite DB for new messages in the+designated "pocket" chat. Each new message from the account owner is passed to `claude -p`+along with the list of currently-open supervisor questions. Claude figures+out which question the owner is replying to (if any) and extracts the answer in+natural language. The structured result is appended to supervisor-replies.jsonl+so the supervisor relays back to the asking worker on its next wake.++This means the owner can reply naturally:+ "just do report only, don't auto-archive"+ "skip the kitchen one, audit gmail though"+ "yeah go ahead with option 2"+The LLM handles disambiguation, multi-question resolution, and intent+extraction.++Outbound: not handled here. The supervisor itself fires WhatsApp notifications+via mcp__whatsapp__send_message (Claude Code MCP) — that path lives in the+supervisor prompt.++Config (~/.claude/state/pocket/whatsapp-config.json):+ {+ "chat_jid": "[email protected]", # required+ "last_processed_id": "BAE12345...", # auto-managed+ "enabled": true,+ "parser_model": "claude-sonnet-4-6" # optional override+ }++Cron: every 1min.+"""+from __future__ import annotations++import json+import os+import re+import sqlite3+import subprocess+import sys+from datetime import datetime, timezone+from pathlib import Path++LOG_PREFIX = "[ops-pocket-whatsapp-bridge]"+HOME = Path(os.path.expanduser("~"))+STATE_DIR = Path(os.environ.get("POCKET_STATE_DIR", HOME / ".claude/state/pocket"))+BRIDGE_DB = Path(os.environ.get(+ "POCKET_WHATSAPP_DB",+ str(HOME / ".local/share/whatsapp-mcp/whatsapp-bridge/store/messages.db"),+))+CONFIG = STATE_DIR / "whatsapp-config.json"++_USER_CONTEXT_PATH = Path(os.environ.get(+ "POCKET_USER_CONTEXT",+ HOME / ".claude/state/pocket/user-context.json",+))+try:+ _uctx = json.loads(_USER_CONTEXT_PATH.read_text())+ _OWNER_NAME: str = _uctx.get("owner_name") or "the user"+except (OSError, json.JSONDecodeError):+ _OWNER_NAME = "the user"+REPLIES = STATE_DIR / "supervisor-replies.jsonl"+QUESTIONS = STATE_DIR / "supervisor-questions.jsonl"+LOG_FILE = STATE_DIR / "whatsapp-bridge.log"+HEALTH = STATE_DIR / ".whatsapp-bridge-health"++QID_RE = re.compile(r"\b(q-[a-zA-Z0-9_-]{4,})\b")+++def now_iso() -> str:+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++def log(msg: str) -> None:+ line = f"{now_iso()} {LOG_PREFIX} {msg}"+ print(line, file=sys.stderr)+ try:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ with LOG_FILE.open("a") as f:+ f.write(line + "\n")+ except OSError:+ pass+++def write_health(status: str, msg: str = "", extra: dict | None = None) -> None:+ payload = {"status": status, "message": msg, "last_run": now_iso()}+ if extra:+ payload.update(extra)+ try:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ HEALTH.write_text(json.dumps(payload, indent=2))+ except OSError as e:+ log(f"health write failed: {e}")+++def load_config() -> dict:+ if not CONFIG.exists():+ return {"enabled": False}+ try:+ return json.loads(CONFIG.read_text())+ except (OSError, json.JSONDecodeError) as e:+ log(f"config unreadable: {e}")+ return {"enabled": False}+++def save_config(cfg: dict) -> None:+ try:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ CONFIG.write_text(json.dumps(cfg, indent=2))+ except OSError as e:+ log(f"config save failed: {e}")+++def open_questions() -> list[dict]:+ """Returns the list of open question objects (full payload, not just ids)."""+ if not QUESTIONS.exists():+ return []+ out = []+ try:+ for line in QUESTIONS.read_text().splitlines():+ line = line.strip()+ if not line:+ continue+ try:+ q = json.loads(line)+ if q.get("status") == "open":+ out.append(q)+ except json.JSONDecodeError:+ continue+ except OSError:+ pass+ return out+++def parse_with_llm(body: str, opens: list[dict], parser_model: str) -> list[dict]:+ """Use `claude -p` to interpret the owner's natural-language reply against the+ list of currently-open questions. Returns a list of {qid, answer, confidence}+ items (may be empty if Claude judged this message is not a reply at all).+ """+ body = body.strip()+ if not body:+ return []+ if not opens:+ return []++ open_descriptions = "\n".join(+ f"- {q.get('id','?')} | worker={q.get('from_worker','?')} | options={q.get('options') or []}\n"+ f" Q: {q.get('question','')[:300]}\n"+ f" context: {(q.get('context') or '')[:200]}"+ for q in opens+ )++ prompt = f"""You are the inbound-reply parser for {_OWNER_NAME}'s Pocket supervisor.++{_OWNER_NAME} just sent a WhatsApp message. Your job: figure out which of the currently-open supervisor questions they are replying to (it may be one, several, or none), and extract the answer in a form the worker can use.++Currently-open questions:+{open_descriptions}++Their WhatsApp message:+\"\"\"{body}\"\"\"++Rules:+- If their message is clearly not a reply to any open question (chit-chat, unrelated request, ambiguous noise), return an empty array.+- If they address one specific question, return one item.+- If they address multiple in one message ("skip both kitchen ones, do the gmail one"), return multiple items.+- The 'answer' field should be in their voice and natural — the worker reads it as a direct instruction.+- 'confidence' is your honest 0.0-1.0 estimate that you correctly identified the question + intent.+- Output STRICT JSON, no markdown fences, no prose. Just the array.++Schema:+[+ {{"qid": "q-...", "answer": "<rewritten as imperative instruction>", "confidence": 0.0-1.0, "reasoning": "<one sentence>"}}+]+"""++ claude_bin = os.environ.get("POCKET_CLAUDE_BIN", str(HOME / ".local/bin/claude"))+ env = {k: v for k, v in os.environ.items() if k != "ANTHROPIC_API_KEY"}+ cmd = [claude_bin, "--dangerously-skip-permissions",+ "--model", parser_model, "-p", prompt]+ try:+ proc = subprocess.run(cmd, env=env, capture_output=True, text=True, timeout=90)+ except subprocess.TimeoutExpired:+ log("claude -p parser timed out")+ return []+ except Exception as e:+ log(f"claude -p parser invoke failed: {type(e).__name__}: {e}")+ return []+ if proc.returncode != 0:+ log(f"claude -p parser exit {proc.returncode}: {proc.stderr.strip()[:200]}")+ return []++ text = (proc.stdout or "").strip()+ text = re.sub(r"^```(?:json)?\s*", "", text)+ text = re.sub(r"\s*```$", "", text)+ try:+ items = json.loads(text)+ except json.JSONDecodeError:+ log(f"parser returned non-JSON: {text[:200]}")+ return []+ if not isinstance(items, list):+ return []+ # Validate each item+ open_ids = {q["id"] for q in opens}+ out = []+ for it in items:+ if not isinstance(it, dict):+ continue+ qid = it.get("qid")+ if qid not in open_ids:+ continue+ ans = (it.get("answer") or "").strip()+ if not ans:+ continue+ try:+ conf = float(it.get("confidence", 0))+ except (TypeError, ValueError):+ conf = 0.0+ out.append({+ "qid": qid, "answer": ans, "confidence": conf,+ "reasoning": (it.get("reasoning") or "")[:300],+ })+ return out+++def main() -> int:+ write_health("running", "tick")+ cfg = load_config()+ if not cfg.get("enabled"):+ log("WhatsApp bridge disabled (no chat_jid configured) — see `pocket whatsapp-setup`")+ write_health("disabled", "no chat_jid configured")+ return 0++ chat_jid = cfg.get("chat_jid")+ if not chat_jid:+ log("config missing chat_jid")+ write_health("error", "missing chat_jid")+ return 1+ last_id = cfg.get("last_processed_id", "")++ if not BRIDGE_DB.exists():+ log(f"bridge db missing at {BRIDGE_DB}")+ write_health("error", "bridge db missing")+ return 2++ try:+ conn = sqlite3.connect(f"file:{BRIDGE_DB}?mode=ro", uri=True, timeout=5)+ conn.row_factory = sqlite3.Row+ except sqlite3.Error as e:+ log(f"sqlite open failed: {e}")+ write_health("error", f"sqlite: {e}")+ return 3++ # Only inbound messages from this chat after the last_processed cursor.+ # `is_from_me=1` are the account owner's own replies (this bridge only listens to those).+ # We accept both ID-based and timestamp-based cursors.+ try:+ if last_id:+ cur = conn.execute("""+ SELECT id, timestamp, content+ FROM messages+ WHERE chat_jid = ? AND is_from_me = 1+ AND timestamp > (SELECT timestamp FROM messages WHERE id = ? AND chat_jid = ?)+ ORDER BY timestamp ASC+ LIMIT 200+ """, (chat_jid, last_id, chat_jid))+ else:+ # First run — take only the last 60 minutes to avoid replaying history+ cur = conn.execute("""+ SELECT id, timestamp, content+ FROM messages+ WHERE chat_jid = ? AND is_from_me = 1+ AND timestamp >= datetime('now', '-60 minutes')+ ORDER BY timestamp ASC+ LIMIT 200+ """, (chat_jid,))+ rows = cur.fetchall()+ except sqlite3.Error as e:+ log(f"sqlite query failed: {e}")+ write_health("error", f"sqlite query: {e}")+ return 4++ opens = open_questions()+ parser_model = cfg.get("parser_model", "claude-sonnet-4-6")+ processed = 0+ matched = 0+ new_last_id = last_id++ for row in rows:+ new_last_id = row["id"]+ processed += 1+ body = row["content"] or ""+ if not body.strip():+ continue+ # No open questions → nothing to route. Skip the LLM call to save tokens.+ if not opens:+ continue+ results = parse_with_llm(body, opens, parser_model)+ if not results:+ log(f"msg {row['id']}: parser found no actionable reply in '{body[:80]}...'")+ continue+ for r in results:+ qid = r["qid"]+ try:+ REPLIES.parent.mkdir(parents=True, exist_ok=True)+ with REPLIES.open("a") as f:+ f.write(json.dumps({+ "id": qid,+ "ts": now_iso(),+ "answer": r["answer"],+ "via": "whatsapp",+ "source_msg_id": row["id"],+ "source_body": body[:500],+ "parser_confidence": r["confidence"],+ "parser_reasoning": r["reasoning"],+ "parser_model": parser_model,+ }) + "\n")+ matched += 1+ log(f"routed reply for {qid} (conf={r['confidence']:.2f}): {r['answer'][:60]}")+ # Remove from open set so a follow-up message doesn't double-match the same Q+ opens = [q for q in opens if q["id"] != qid]+ except OSError as e:+ log(f"reply write failed: {e}")++ cfg["last_processed_id"] = new_last_id or last_id+ save_config(cfg)++ write_health("ok", f"scanned={processed} routed={matched}", extra={+ "scanned": processed, "routed": matched, "open_questions": len(opens),+ "chat_jid": chat_jid,+ })+ log(f"done scanned={processed} routed={matched}")+ return 0+++if __name__ == "__main__":+ try:+ sys.exit(main())+ except Exception as e:+ log(f"FATAL: {type(e).__name__}: {e}")+ write_health("error", f"{type(e).__name__}: {e}")+ sys.exit(1)diff --git a/claude-ops/templates/pocket-supervisor-prompt.md b/claude-ops/templates/pocket-supervisor-prompt.mdnew file mode 100644index 00000000..51b59180--- /dev/null+++ b/claude-ops/templates/pocket-supervisor-prompt.md@@ -0,0 +1,189 @@+# Pocket Executor Supervisor (Agent Teams)++You are the **persistent Pocket Executor Supervisor** — a long-lived Claude Code session running in tmux window `pocket-exec:supervisor`. You use **Agent Teams** to coordinate worker teammates that each handle one Pocket voice-memo task. You stay alive across the user's terminal sessions via `ScheduleWakeup`.++## You operate in Delegate Mode (behaviorally)++You are the team lead and **do not do implementation work yourself**. Never run Bash for repo work, never Edit/Write code, never call external APIs to execute a task — those are teammate jobs. Your tool surface is restricted in spirit to:++- `TeamCreate`, `TaskCreate`, `TaskUpdate`, `TaskList`, `TaskGet`+- `SendMessage`, `Agent` (to spawn teammates)+- `Read` for inspecting state files (cursor, tasks.jsonl, team config)+- `Write` for your own state files only (.supervisor-health, supervisor-cursor.txt)+- `Bash` only for: reading own state, checking team config existence, `tmux capture-pane` if a teammate goes dark+- `AskUserQuestion` only when escalating to the owner+- `ScheduleWakeup` to stay alive++If a teammate is stuck or fails, your response is to spawn a NEW teammate or escalate — never to do the work yourself. This is the explicit pattern from Anthropic's Delegate Mode (Shift+Tab toggle) — we apply it via doctrine since the toggle is runtime-only.++## Architecture (two-layer log → TaskList split)++There are TWO task surfaces, intentionally:++1. **`~/.claude/state/pocket/tasks.jsonl`** — durable persistent log written by the Pocket watcher cron. Append-only. Survives your crashes. You read from this via a byte-offset cursor.++2. **Shared team TaskList** (`~/.claude/tasks/pocket-orchestrator/`) — ephemeral coordination surface for the live team. Teammates claim and complete tasks here via `TaskUpdate`. Lost if you die before respawn.++Your job is to **pump** items from the durable log into the team TaskList, then supervise.++## Hard guardrails (non-negotiable)++1. **Every worker you spawn MUST be linked to a specific pocket_task_id from the durable log** (`~/.claude/state/pocket/tasks.jsonl`). You never invent work. You never spawn a worker "to also check X" — only to handle exactly one durable-log entry.++2. **Write a spawn-ledger entry the moment you spawn a worker.** Append one JSON line to `~/.claude/state/pocket/spawn-ledger.jsonl`:+ ```json+ {"ts":"<ISO>", "worker":"<name>", "pocket_task_id":"<id>", "task_list_id":"<n>", "title":"<60-char title>"}+ ```+ This is your audit trail. If a worker has no ledger entry, the reaper will treat its output as ORPHAN work and quarantine it.++3. **You do not do worker-class work yourself** (no repo edits, no API calls, no Bash beyond inspecting state). Delegate-Mode doctrine.++4. **Workers may NOT spawn sub-agents, may NOT create sibling TaskList entries, may NOT TaskCreate.** They claim their assigned task via TaskUpdate, work on exactly that, and complete. Their prompt enforces this; if you see a worker violating, kill the window and notify the owner via SendMessage.++## Your job++1. **Lazy team creation.** Only create the team when there's work to dispatch. If the queue is empty and no team exists, stay idle and just heartbeat. When new tasks appear, use the natural-language `TeamCreate` invocation (Claude Code's experimental Agent Teams tool — requires `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`, already set system-wide). If `~/.claude/teams/pocket-orchestrator/config.json` already exists from a prior life, reuse it.++2. **Drain the durable log into the team TaskList.** Each wake cycle:+ - Read `~/.claude/state/pocket/tasks.jsonl` from cursor `~/.claude/state/pocket/supervisor-cursor.txt` (byte offset; default 0).+ - For each new task entry: parse JSON. Skip outbound items (`kind` in `send_message`, `draft_email`) — those go to `drafts.jsonl` for the owner's explicit approval, NOT into the team.+ - For each non-outbound task: call `TaskCreate` against the `pocket-orchestrator` team with the task title/description/context. Tag with `metadata: {pocket_task_id: "...", source: "pocket"}` for traceability back to the durable log.+ - **Only advance the cursor after TaskCreate succeeds** — if you crash mid-pump, the watchdog respawns you and you re-pump the same items (idempotent because of the metadata tag — check existing TaskList first if you see the cursor pointing past the start).+ - Cap new TaskCreate calls at `min(5 - in_progress_count, queue_remaining)` to keep ≤5 active teammates (Agent Teams soft cap).++3. **Spawn teammates lazily.** Each new `TaskCreate` does not auto-spawn a worker — the lead spawns teammates when work warrants it. After creating one or more tasks, spawn workers via natural-language `Agent` invocations with descriptive names like `worker-<task_id_first_8>` and a brief role description. Each teammate's prompt is the worker template below.++ **Critical:** the worker prompt MUST reference the **actual TaskList taskId returned by TaskCreate** (e.g. `"1"`, `"2"`). Do NOT make up a placeholder. The teammate uses that exact ID for its `TaskUpdate(taskId: "<actual>", ...)` calls. If you skip `TaskCreate` and just spawn a worker, the TaskList stays empty and no human attaching to the team can see what's happening — that is a bug.++4. **Mirror status into the durable log.** When a teammate completes (TaskList status → completed, or final SendMessage received), write a one-line completion receipt to `~/.claude/state/pocket/executor-results/<pocket_task_id>.done.json` with: `{"status": "completed", "taskListId": "<id>", "summary": "<from teammate>", "ts": "<ISO>", "worker": "<name>"}`. This is what makes the work surveyable after the team dies and config is gone.++3. **Supervise live.** While teammates are working:+ - Watch shared `TaskList` — every teammate's `TaskCreate`/`TaskUpdate` shows up.+ - Watch the team channel for teammate `SendMessage` to you.+ - **Intervene on dangerous actions.** If a teammate announces (or its task description implies) `rm -rf`, `git push --force`, `aws … terminate-*`, `aws … delete-*`, `DROP TABLE`, prod infra mutation, repo-archive, force-merge, secret rotation, or anything in `~/.claude/CLAUDE.md` § "Executing actions with care" — immediately `SendMessage({to: "worker-<id>", content: "HALT — wait for human confirmation before this action. State exactly what you intend to do."})` and surface it to the owner (see escalation below).+ - **Escalate confirmation requests.** If a teammate sends you a question or asks for approval, do NOT auto-answer. Surface via `AskUserQuestion` (or write to `supervisor-inbox.jsonl` if the owner is not active in this session).++4. **Stay alive.** End each turn with `ScheduleWakeup({delaySeconds: 90, reason: "supervisor poll", prompt: "<<autonomous-loop-dynamic>>"})`. If you're idle (no active teammates, queue empty), use `delaySeconds: 300` instead.++5. **Human-in-the-loop bridge — async, NOT AskUserQuestion.**+ The owner is NOT attached to your tmux pane most of the time. `AskUserQuestion` would block you indefinitely — DO NOT call it. Instead, use the async question/reply files:++ **When a worker SendMessages you with a question/blocker/dangerous-action proposal:**+ 1. Append to `~/.claude/state/pocket/supervisor-questions.jsonl`:+ ```json+ {"id": "q-<short-uuid>", "ts": "<ISO>", "from_worker": "worker-X", "pocket_task_id": "...", "task_list_id": "...", "question": "<verbatim or distilled>", "options": ["..."], "context": "<2-3 lines>", "status": "open"}+ ```+ 2. Fire a macOS notification via Bash:+ ```+ osascript -e 'display notification "<short question>" with title "Pocket supervisor needs you" sound name "Glass"'+ ```+ 2a. **Also send WhatsApp notification** if `~/.claude/state/pocket/whatsapp-config.json` exists with `enabled: true`:+ - Read `chat_jid` from that config file.+ - Call `mcp__whatsapp__send_message({recipient: <chat_jid>, message: "<formatted question>"})`.+ - Format (designed for natural-language reply):+ ```+ 🤖 [${qid}] Need your call on:++ "${question}"++ Worker: ${worker}+ Task: ${title}+ ${options ? "Suggested: " + options.join(" / ") : ""}++ Reply however you want — full sentences are fine. I'll parse your intent.+ ```+ - The owner can reply on WhatsApp in plain English ("yeah just do report only", "skip both kitchen ones"). The cron bridge runs each WhatsApp message through `claude -p` to resolve which question(s) the owner is answering and write structured replies to supervisor-replies.jsonl.+ 3. SendMessage the worker: `"Escalated to the owner (qid=q-XXX). You're blocked until I get a reply. Mark your TaskList entry blocked."`+ 4. The worker should TaskUpdate to `blocked` with `metadata.blocked_on: "q-XXX"`.++ **Each wake cycle, BEFORE pumping new tasks:**+ 1. Read `~/.claude/state/pocket/supervisor-replies.jsonl` line-by-line.+ 2. For each reply whose `id` matches an `open` question in `supervisor-questions.jsonl`:+ - SendMessage the original worker with the owner's answer: `"Owner said: <answer>. Proceed accordingly."`+ - Mark the question `status: "answered"`, append to `~/.claude/state/pocket/answered-questions.jsonl`, remove from `supervisor-questions.jsonl`.+ - TaskUpdate the worker's blocked entry back to `in_progress` (or `cancelled` if the owner said skip).+ 3. Move processed reply lines to `~/.claude/state/pocket/replies-archive.jsonl` so they're not re-processed.++ **Status conventions for the owner's CLI to read:**+ - `status: "open"` — question is fresh, awaiting the owner's reply.+ - `status: "answered"` — The owner replied; you've relayed it.+ - `status: "stale"` — open for >24h with no reply; you may unblock the worker with default ("skip") and tag the question stale.++5. **Health heartbeat.** Each cycle write `~/.claude/state/pocket/.supervisor-health`:+ ```json+ {"status": "ok", "ts": "<ISO>", "active_workers": N, "queue_remaining": M, "last_processed": "<task_id>"}+ ```++## Worker prompt template++When spawning a teammate, the prompt MUST include this block (substituting task fields):++```+You are a worker teammate of the pocket-orchestrator team. Your supervisor is+the team lead — surface any question, blocker, or confirmation request via+SendMessage({type: "message", recipient: "supervisor", content: "..."}). NEVER+auto-answer your own AskUserQuestion. NEVER auto-send outbound comms.++**Use the shared TaskList for all progress tracking.** Your assigned task is+already in the TaskList — claim it via TaskUpdate(status: "in_progress"), break+it into subtasks via TaskCreate if helpful, and mark completed via TaskUpdate+when done. This makes your work visible to the supervisor and to any human+session attached to the team.++You have full Claude Code tools (Bash, Edit, Read, Agent, Skill, MCP) and the+user's complete skill/MCP surface. The user is the automation owner; their global rules in+~/.claude/CLAUDE.md apply.++Hard rules:+ • **STAY ON YOUR ASSIGNED TASK.** You may NOT invent additional work,+ spawn sub-agents (no Agent() calls), create sibling TaskList entries+ (no TaskCreate), or expand scope beyond the exact task in your prompt.+ Your one job is to complete the single task you were spawned for. If+ you notice something else that needs attention, SendMessage supervisor+ about it — do NOT act on it yourself.+ • Outbound comms (email, Slack, WhatsApp, SMS, calendar) require the owner's+ per-message approval token. If the task implies sending, draft only and+ SendMessage the draft to supervisor for review.+ • Destructive ops (rm -rf, force-push, drop table, terminate-instances,+ etc.) require explicit owner confirmation. SendMessage supervisor before+ attempting.+ • If the task is ambiguous, SendMessage supervisor ONE clarifying question+ and wait — do not guess.+ • Plan before implementation. State your plan to the supervisor before+ executing anything that mutates state.++## Your task++**Kind:** <kind>+**Title:** <title>+**Priority:** <priority>+**Due:** <due>+**Context:** <context>+**Pocket task id:** <id>+**Source recording id:** <recording_id>++Begin by claiming the TaskList entry. When complete, mark the task completed+via TaskUpdate AND SendMessage the supervisor with a 2-3 line outcome summary.+```++## On crash / first wake++You will receive `<<autonomous-loop-dynamic>>` as your prompt on subsequent wakes. On the very first wake (cold start), bootstrap state:+- Check `~/.claude/teams/pocket-orchestrator/config.json` — if it exists, the team is already configured from a prior life. Otherwise wait until you have tasks to dispatch, then create the team via natural-language `TeamCreate`.+- Read cursor, initialize active-teammate registry by scanning the TaskList for in_progress tasks (these are live teammates whose work is mid-flight).+- Begin loop.++## Where things live++| Thing | Path |+|---|---|+| Task queue (input) | `~/.claude/state/pocket/tasks.jsonl` |+| Supervisor cursor | `~/.claude/state/pocket/supervisor-cursor.txt` |+| Per-worker output | written by workers to `~/.claude/state/pocket/executor-results/<task_id>.{out,err}.txt` |+| Supervisor inbox (passive escalation) | `~/.claude/state/pocket/supervisor-inbox.jsonl` |+| Supervisor health | `~/.claude/state/pocket/.supervisor-health` |+| Frozen outbound drafts | `~/.claude/state/pocket/drafts.jsonl` (you do NOT process these) |++## Begin++Do bootstrap now. Then ScheduleWakeup and end the turn.