Business operating system for Claude Code — 57 skills, 21 agents, smart daemon. Unified inbox (WhatsApp/Email/Slack/Telegram), autonomous PR merge, full-AWS monitoring, revenue (Stripe+RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4), voice (Bland/ElevenLabs), APM (Datadog/NewRelic/OTEL), YOLO mode.
Shell agent-teamsai-agentai-automationanthropicautonomous-agentawsbusiness-operationsclaudeclaude-codeclaude-code-plugindevopsecommerceinbox-zeroklaviyomarketingmcpmorning-briefingpr-automationshopifyterminal
feat(pocket): /ops:pocket skill + STATUS reference (#272)
Aurora Capital9bffe546ee2f
diff --git a/claude-ops/bin/ops-marketing-portfolio b/claude-ops/bin/ops-marketing-portfolioindex 405af796..927fc377 100755--- a/claude-ops/bin/ops-marketing-portfolio+++ b/claude-ops/bin/ops-marketing-portfolio@@ -31,7 +31,7 @@ for ((i=1; i<=$#; i++)); do--json) JSON_OUT=1 ;;--project)j=$((i+1)); FILTER_PROJECT="${!j:-}"- i=$((i+1)) # skip value so it is not parsed as a flag on the next iteration+ i=$j;;esacdonediff --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/ops-cron-pocket-watcher.py b/claude-ops/scripts/ops-cron-pocket-watcher.pyindex a07508b7..a048bfa5 100755--- a/claude-ops/scripts/ops-cron-pocket-watcher.py+++ b/claude-ops/scripts/ops-cron-pocket-watcher.py@@ -74,15 +74,6 @@ 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"@@ -388,7 +379,7 @@ def infer_tasks_from_recording(recording: dict) -> list[dict]:"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). "+ "certainty that this was implied as a task Sam would want done). ""Return [] if nothing actionable was implied. NO prose, NO markdown.")@@ -575,28 +566,23 @@ def save_cursor(ts: str) -> None: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."""+def load_seen() -> set[str]: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)+ return set(json.loads(SEEN_FILE.read_text()))except json.JSONDecodeError:- pass- return {}+ return set()+ return set()-def save_seen(seen: dict[str, None]) -> None:+def save_seen(seen: set[str]) -> None:if DRY_RUN:returnSTATE_DIR.mkdir(parents=True, exist_ok=True)- # Cap at 5000 ids to bound file size (keep most recently inserted keys)+ # Cap at 5000 ids to bound file sizeif len(seen) > 5000:- keys = list(seen.keys())[-5000:]- seen.clear()- seen.update(dict.fromkeys(keys))- SEEN_FILE.write_text(json.dumps(list(seen.keys())))+ seen = set(list(seen)[-5000:])+ SEEN_FILE.write_text(json.dumps(sorted(seen)))# ── Output sinks ─────────────────────────────────────────────────────────────@@ -829,12 +815,12 @@ def main() -> int: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+ seen.add(rid)continuewrite_memory(rec, giga=giga)new_memories += 1new_recordings.append(rid)- seen[rid] = None+ seen.add(rid)# Implicit-task inference (Haiku) — only on substantive recordingsinferred = infer_tasks_from_recording(rec)@@ -860,13 +846,13 @@ def main() -> int:# 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:+ # supervisor. This is the safety guardrail Sam 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+ seen.add(inferred_id)if meta.get("hasMore") and meta.get("nextRecordingDateBeforeExclusive"):next_before = meta["nextRecordingDateBeforeExclusive"]if page >= 10:@@ -895,7 +881,7 @@ def main() -> int:continueroute_actionitem(item, giga=giga)new_tasks += 1- seen[seen_key] = None+ seen.add(seen_key)# 3) Optional consolidate pass (Giga merges adjacent neurons)if giga and giga.ok and GIGA_CONSOLIDATE and (new_memories + new_tasks) > 0:diff --git a/claude-ops/scripts/ops-daemon-launcher.sh b/claude-ops/scripts/ops-daemon-launcher.shindex d7eca206..b0243a7c 100755--- a/claude-ops/scripts/ops-daemon-launcher.sh+++ b/claude-ops/scripts/ops-daemon-launcher.sh@@ -15,7 +15,7 @@ fiLATEST_VERSION="$(find "$CACHE_ROOT" -mindepth 1 -maxdepth 1 -type d -print 2>/dev/null \| awk -F/ '{print $NF}' \- | awk '/^[0-9]+\.[0-9]+\.[0-9]+$/ { print }' \+ | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' \| sort -V \| tac \| while read -r v; do@@ -34,11 +34,4 @@ 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"-# Match install-ops-daemon.sh: Apple Silicon Homebrew → Intel Homebrew → system bash-BASH_PATH="/bin/bash"-if [[ -x /opt/homebrew/bin/bash ]]; then- BASH_PATH="/opt/homebrew/bin/bash"-elif [[ -x /usr/local/bin/bash ]]; then- BASH_PATH="/usr/local/bin/bash"-fi-exec "$BASH_PATH" "$DAEMON" "$@"+exec "${BASH:-/bin/bash}" "$DAEMON" "$@"diff --git a/claude-ops/scripts/ops-pocket-activity-notifier.py b/claude-ops/scripts/ops-pocket-activity-notifier.pyindex 1fc8ca90..72b6ee7c 100755--- a/claude-ops/scripts/ops-pocket-activity-notifier.py+++ b/claude-ops/scripts/ops-pocket-activity-notifier.py@@ -222,25 +222,16 @@ def process_spawns(chat_jid: str | None, email_to: str | None, titles: dict) ->f"attached when this completes.\n")email_subject = f"START — {(title or task_id)[:80]}"- enqueue_errors: list[str] = []- if chat_jid:- try:+ try:+ if chat_jid:enqueue_whatsapp(chat_jid, wa_msg)- except OSError as e:- log(f"enqueue START whatsapp failed: {e}")- enqueue_errors.append("whatsapp")- if email_to:- try:+ if email_to:enqueue_email(email_to, email_subject, email_body)- except OSError as e:- log(f"enqueue START email failed: {e}")- enqueue_errors.append("email")- channels_configured = (1 if chat_jid else 0) + (1 if email_to else 0)- if channels_configured and len(enqueue_errors) == channels_configured:- log("enqueue START all channels failed; retry next tick")- new_cursor = line_start+ sent += 1+ except OSError as e:+ log(f"enqueue START failed: {e}")+ new_cursor = line_start # retry next tickbreak- sent += 1try:SPAWN_CURSOR.write_text(str(new_cursor))except OSError as e:@@ -340,26 +331,17 @@ def process_completions(chat_jid: str | None, email_to: str | None, titles: dictemail_body = "\n".join(email_body_parts)email_subject = f"DONE — {(title or task_id)[:80]}"- enqueue_errors: list[str] = []- if chat_jid:- try:+ try:+ if chat_jid:enqueue_whatsapp(chat_jid, wa_msg, media_path=attachment)- except OSError as e:- log(f"enqueue DONE whatsapp failed for {name}: {e}")- enqueue_errors.append("whatsapp")- if email_to:- try:+ if email_to:attachments = [attachment] if attachment else []enqueue_email(email_to, email_subject, email_body, attachments)- except OSError as e:- log(f"enqueue DONE email failed for {name}: {e}")- enqueue_errors.append("email")- channels_configured = (1 if chat_jid else 0) + (1 if email_to else 0)- if channels_configured and len(enqueue_errors) == channels_configured:- log(f"enqueue DONE all channels failed for {name}; retry next tick")- break- sent += 1- new_seen.add(name)+ 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 tickif new_seen != seen:save_seen_results(new_seen)diff --git a/claude-ops/scripts/ops-pocket-email-bridge.py b/claude-ops/scripts/ops-pocket-email-bridge.pyindex 5926988b..38909d83 100755--- a/claude-ops/scripts/ops-pocket-email-bridge.py+++ b/claude-ops/scripts/ops-pocket-email-bridge.py@@ -385,19 +385,30 @@ def drain_inbound(cfg: dict) -> tuple[int, int]:messages = fetch_recent_replies(cfg)if not messages:return (0, 0)- # Filter: only NEW messages after last_processed_id (skip through cursor, then take rest)- new_messages: list[dict] = []++ def _internal_ts_rank(m: dict) -> int:+ """Gmail internalDate as int for ordering (matches WhatsApp strict > cursor)."""+ t = m.get("ts")+ try:+ if isinstance(t, (int, float)):+ return int(t)+ s = str(t)+ if s.isdigit():+ return int(s)+ except (TypeError, ValueError):+ pass+ return 0++ # Filter: only NEW messages after last_processed_id (strictly newer internalDate).if not last_id:- new_messages = list(messages)+ new_messages = messageselse:- past_cursor = False- for m in messages:- if past_cursor:- new_messages.append(m)- elif m["id"] == last_id:- past_cursor = True- if not past_cursor:- new_messages = list(messages)+ cur = next((m for m in messages if m["id"] == last_id), None)+ if cur is None:+ new_messages = messages+ else:+ t0 = _internal_ts_rank(cur)+ new_messages = [m for m in messages if _internal_ts_rank(m) > t0]opens = open_questions()parser_model = cfg.get("parser_model", "claude-sonnet-4-6")diff --git a/claude-ops/scripts/ops-pocket-triage.py b/claude-ops/scripts/ops-pocket-triage.pyindex 9cb28f3c..c5255658 100755--- a/claude-ops/scripts/ops-pocket-triage.py+++ b/claude-ops/scripts/ops-pocket-triage.py@@ -50,6 +50,8 @@ import sysimport timefrom datetime import datetime, timezonefrom pathlib import Path+from urllib import error as urlerr+from urllib import request as urlreqLOG_PREFIX = "[ops-pocket-triage]"HOME = Path(os.path.expanduser("~"))@@ -323,16 +325,9 @@ def main() -> int:write_health("ok", "no pending items", extra={"counts": {}})return 0- # Claim file atomically so the watcher can append to a fresh pending-triage.jsonl- claim = PENDING.with_name("pending-triage.processing")- if not DRY_RUN:- PENDING.rename(claim)- pending_src = claim- else:- pending_src = PENDING-+ pending_snapshot = PENDING.read_text()tasks = []- for raw in pending_src.read_text().splitlines():+ for raw in pending_snapshot.splitlines():raw = raw.strip()if not raw:continue@@ -345,13 +340,27 @@ def main() -> int: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 quotatitle = (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+ task_id = task.get("id", "")+ prior = _id_already_routed(task_id)+ if prior:+ verdict = f"SKIP_{prior}"+ log(f"SKIP {task_id} — already in {prior}")+ decision = {+ "verdict": "ASK",+ "confidence": 0.0,+ "reasoning": f"skipped Opus triage — already present in {prior}",+ "scoped_task_description": "",+ "concerns": [],+ }+ else:+ if i > 1 and inter_call_pause > 0:+ time.sleep(inter_call_pause) # avoid bursting Claude Max quota+ log(f"[{i}/{len(tasks)}] triaging: {title}")+ decision = triage_one(task)+ verdict = route(task, decision)+ if not verdict.startswith("SKIP_"):+ counts[verdict] = counts.get(verdict, 0) + 1log(f"[{i}/{len(tasks)}] verdict={verdict} conf={decision.get('confidence')} — {decision.get('reasoning','')[:120]}")# Audit log every decision with full thinkingappend_jsonl(AUDIT, {@@ -361,9 +370,16 @@ def main() -> int:"routed_to": verdict,})- # Drop claimed batch if not dry run (watcher recreated PENDING as needed)+ # Drop only the snapshot we consumed; preserve any lines appended during triage.if not DRY_RUN:- claim.unlink(missing_ok=True)+ try:+ current = PENDING.read_text()+ if current.startswith(pending_snapshot):+ PENDING.write_text(current[len(pending_snapshot):])+ else:+ log("pending-triage prefix changed during triage — not rewriting file")+ except OSError as e:+ log(f"pending rewrite failed: {e}")log(f"done counts={counts}")write_health("ok", f"triaged={sum(counts.values())}", extra={"counts": counts})return 0diff --git a/claude-ops/scripts/ops-pocket-whatsapp-bridge.py b/claude-ops/scripts/ops-pocket-whatsapp-bridge.pyindex 6f93784a..2b8b3a93 100755--- a/claude-ops/scripts/ops-pocket-whatsapp-bridge.py+++ b/claude-ops/scripts/ops-pocket-whatsapp-bridge.py@@ -2,13 +2,13 @@"""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`+designated "pocket" chat. Each new message from Sam 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+out which question Sam is replying to (if any) and extracts the answer innatural language. The structured result is appended to supervisor-replies.jsonlso the supervisor relays back to the asking worker on its next wake.-This means the owner can reply naturally:+This means Sam can reply naturally:"just do report only, don't auto-archive""skip the kitchen one, audit gmail though""yeah go ahead with option 2"@@ -48,16 +48,6 @@ BRIDGE_DB = Path(os.environ.get(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"@@ -132,7 +122,7 @@ def open_questions() -> list[dict]: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+ """Use `claude -p` to interpret Sam's natural-language reply against thelist 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)."""@@ -149,21 +139,21 @@ def parse_with_llm(body: str, opens: list[dict], parser_model: str) -> list[dictfor q in opens)- prompt = f"""You are the inbound-reply parser for {_OWNER_NAME}'s Pocket supervisor.+ prompt = f"""You are the inbound-reply parser for Account A' 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.+Sam just sent a WhatsApp message. Your job: figure out which of the currently-open supervisor questions he's 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:+Sam's 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.+- If Sam's message is clearly not a reply to any open question (chit-chat, unrelated request, ambiguous noise), return an empty array.+- If Sam addresses one specific question, return one item.+- If Sam addresses multiple in one message ("skip both kitchen ones, do the gmail one"), return multiple items.+- The 'answer' field should be in Sam's 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.@@ -251,7 +241,7 @@ def main() -> int: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).+ # `is_from_me=1` are Sam's own replies (this bridge only listens to those).# We accept both ID-based and timestamp-based cursors.try:if last_id:diff --git a/claude-ops/skills/ops-pocket/SKILL.md b/claude-ops/skills/ops-pocket/SKILL.mdnew file mode 100644index 00000000..1b1be7aa--- /dev/null+++ b/claude-ops/skills/ops-pocket/SKILL.md@@ -0,0 +1,335 @@+---+name: ops-pocket+description: Pocket voice-memo pipeline command center. Surfaces the watcher → triage → executor → notifier → bridges chain that turns Pocket-recorded voice memos into running Claude tasks, with WhatsApp + email notifications. Routes — status, setup, tasks, test, logs, restart, whatsapp on|off, email on|off.+argument-hint: "[status|setup|tasks|test|logs [N]|restart|whatsapp on|off|email on|off]"+allowed-tools:+ - Bash+ - Read+ - Grep+ - Glob+ - Skill+ - AskUserQuestion+effort: low+maxTurns: 25+---++# OPS ► POCKET++Surfaces the Pocket voice-memo pipeline as a discoverable slash command. The pipeline was previously orphaned — 7 scripts, no entry point. This skill is the entry point.++For the full architecture reference (every state file, every script, every failure mode) see [`STATUS.md`](./STATUS.md) sibling to this file.++## Runtime Context++Before any route runs, resolve:++1. **State dir**: `${POCKET_STATE_DIR:-$HOME/.claude/state/pocket}`. Every file mentioned below is relative to this dir.+2. **Plugin root**: `${CLAUDE_PLUGIN_ROOT}` — used to invoke pipeline scripts under `scripts/`.+3. **Daemon health snapshot**: `${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}/daemon-health.json` — surface its `pocket-*` service status if present.++If `$POCKET_STATE_DIR` does not exist on disk, the pipeline has never been bootstrapped — route to `setup` automatically (no autoroute on `status` if the user explicitly asked for status).++## Routing table++Parse `$ARGUMENTS` and route immediately. First token decides the route.++| First arg | Route |+| ---------------------- | --------------------------------------------------------------------------- |+| (empty) / `status` | **Status dashboard** — daemon health + queue depths + cursors + counts |+| `setup` | Delegate to `skills/setup/channels/pocket.md` if present; else inline steps |+| `tasks` | Pending + in-progress + recently-completed task list |+| `test` | End-to-end synthetic completion test (covered below) |+| `logs [N]` | Tail N lines (default 50) of notifier + run + executor logs |+| `restart` | Kickstart launchd notifier + (re)spawn `pocket-exec` tmux supervisor |+| `whatsapp on` / `off` | Toggle WhatsApp self-chat sink |+| `email on` / `off` | Toggle email self-mail sink |++Anything else: print the routing table and exit.++---++## Route — `status` (default)++The default route. Read state files, render a compact dashboard.++**Read these — in parallel where possible:**++```bash+STATE_DIR="${POCKET_STATE_DIR:-$HOME/.claude/state/pocket}"++# Daemon plist liveness+launchctl list com.claude-ops.pocket-activity-notifier 2>/dev/null \+ | awk '/PID/{print "pid="$3} /LastExitStatus/{print "exit="$3}'++# Supervisor tmux session+tmux has-session -t pocket-exec 2>/dev/null && echo "tmux=up" || echo "tmux=down"+tmux list-windows -t pocket-exec 2>/dev/null | wc -l++# Queue depths (line counts)+wc -l < "$STATE_DIR/pending-triage.jsonl" 2>/dev/null+wc -l < "$STATE_DIR/tasks.jsonl" 2>/dev/null+wc -l < "$STATE_DIR/spawn-ledger.jsonl" 2>/dev/null+wc -l < "$STATE_DIR/supervisor-out-queue.jsonl" 2>/dev/null++# Completed reports+ls "$STATE_DIR/executor-results/"*.done.json 2>/dev/null | wc -l++# Last pull cursor+cat "$STATE_DIR/cursor.txt" 2>/dev/null++# Last 3 notifications (from out-queue-sent.jsonl)+tail -n 3 "$STATE_DIR/out-queue-sent.jsonl" 2>/dev/null++# Per-component health+for h in .activity-notifier-health .out-queue-health .email-bridge-health .health; do+ cat "$STATE_DIR/$h" 2>/dev/null+done+```++**Output format (desktop):**++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► POCKET — [timestamp]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++DAEMONS+ watcher [running|stalled] last tick [Xs ago]+ triage [running|idle]+ executor watchdog [running|stalled] tmux pocket-exec=[up|down] (N windows)+ activity-notifier [running|stalled] pid [N]+ out-queue [running|disabled|error]+ email-bridge [running|disabled|error]++QUEUES+ pending-triage [N items] (awaiting ACT/SKIP decision)+ tasks.jsonl [N items] (canonical task store)+ spawn-ledger [N spawns]+ out-queue [N pending]+ executor-results [N .done.json]++CURSORS+ watcher last pull [ISO timestamp from cursor.txt]+ last completion [latest .done.json mtime]++CHANNELS+ whatsapp [on|off|misconfigured] chat_jid=[masked tail]+ email [on|off|misconfigured] to=[masked]++LAST 3 NOTIFICATIONS+ [N. kind type | task_id | sent_at]+──────────────────────────────────────────────────────+```++**Mobile mode** (Rule 7 — `$SSH_CONNECTION`/`$SSH_CLIENT`/`$SSH_TTY` set OR `$OPS_MOBILE=1` OR `$COLUMNS<80`): plain text lines, no boxes, no emoji prefixes:++```+pocket: watcher running, exec tmux=up, notifier pid=N+queues: triage 0, tasks 12 (3 active), out 0+last pull: 5m ago. last done: 12m ago.+channels: whatsapp on, email off.+```++After the dashboard, use `AskUserQuestion` (max 4 — Rule 1) ONLY if there is something actionable (stalled daemon, pending-triage > 0, etc.). On a clean board, exit silently.++---++## Route — `setup`++Delegate to the setup channel doc when it exists:++```bash+SETUP_DOC="$CLAUDE_PLUGIN_ROOT/skills/setup/channels/pocket.md"+[[ -f "$SETUP_DOC" ]] && cat "$SETUP_DOC"+```++If `pocket.md` does not exist, print the inline onboarding sequence:++1. Confirm `pocket-cli` (or equivalent Pocket API auth) is on PATH.+2. Drop a `whatsapp-config.json` and/or `email-config.json` under `$STATE_DIR` (see STATUS.md for schemas).+3. Run `bash $CLAUDE_PLUGIN_ROOT/scripts/install-pocket-notifier.sh` to register the launchd LaunchAgent.+4. Verify with `/ops:pocket status`.++Per Rule 4 (background by default during setup) and Rule 2 (never delegate commands to the user) — run the install script via Bash with `run_in_background: true`. Per Rule 3, never auto-skip channel selection — if `whatsapp-config.json` and `email-config.json` are both missing, ask via `AskUserQuestion` which to configure first (`[WhatsApp]` / `[Email]` / `[Both]` / `[Skip]`).++---++## Route — `tasks`++Render a single combined list. No `AskUserQuestion` — read-only by default.++```bash+STATE_DIR="${POCKET_STATE_DIR:-$HOME/.claude/state/pocket}"++# Pending triage (awaiting ACT/SKIP)+tail -n 50 "$STATE_DIR/pending-triage.jsonl" 2>/dev/null++# Live tasks (canonical store)+tail -n 50 "$STATE_DIR/tasks.jsonl" 2>/dev/null++# In-flight workers (windows in pocket-exec tmux, excluding _idle + supervisor)+tmux list-windows -t pocket-exec -F '#{window_name}' 2>/dev/null \+ | grep -vE '^(_idle|supervisor)$'++# Recently completed (.done.json sorted by mtime, last 10)+ls -t "$STATE_DIR/executor-results/"*.done.json 2>/dev/null | head -10+```++Format:++```+PENDING TRIAGE (N)+ [id] [created] [title]++ACTIVE TASKS (N)+ [task_id] [status] [title] [started]++IN-FLIGHT WORKERS (N)+ [tmux window name] [up since]++RECENTLY COMPLETED (last 10)+ [task_id] [duration] [report file]+```++---++## Route — `test` (synthetic end-to-end)++Smoke-tests the full notifier → out-queue → both bridges path **without** going through the watcher or triage. Same flow as the manual session-level test that was run when the notifier shipped.++**Steps:**++1. **Pre-flight**: verify `$STATE_DIR/whatsapp-config.json` OR `email-config.json` has `enabled: true`. If neither: print `not configured — run /ops:pocket setup` and exit.+2. **Generate a synthetic task_id** like `test-$(date +%s)`.+3. **Append a tasks.jsonl entry** for the synthetic task (so the notifier can title-resolve it):+ ```bash+ echo "{\"task_id\":\"$TID\",\"title\":\"synthetic pocket test\",\"created_at\":\"$(date -u +%FT%TZ)\",\"verdict\":\"ACT\"}" \+ >> "$STATE_DIR/tasks.jsonl"+ ```+4. **Drop a synthetic `.done.json`** into `executor-results/`:+ ```bash+ cat > "$STATE_DIR/executor-results/$TID.done.json" <<EOF+ {"task_id":"$TID","status":"done","completed_at":"$(date -u +%FT%TZ)","report_file":"$TID.out.md"}+ EOF+ echo "# Synthetic test report\n\nThis is a test artifact from /ops:pocket test." \+ > "$STATE_DIR/executor-results/$TID.out.md"+ ```+5. **Manually invoke the notifier once** (don't wait 60s for launchd):+ ```bash+ "$CLAUDE_PLUGIN_ROOT/scripts/ops-pocket-activity-notifier.py" --once 2>&1 | tail -20+ ```+ (If `--once` is not supported, run the script with `POCKET_NOTIFIER_ONESHOT=1` env var, or just `python3 ops-pocket-activity-notifier.py`.)+6. **Drain both bridges** in parallel:+ ```bash+ "$CLAUDE_PLUGIN_ROOT/scripts/ops-pocket-out-queue.py" 2>&1 | tail -10+ "$CLAUDE_PLUGIN_ROOT/scripts/ops-pocket-email-bridge.py" 2>&1 | tail -10+ ```+7. **Verify delivery** — for each enabled channel:+ - **WhatsApp**: tail `$STATE_DIR/out-queue-sent.jsonl` for an entry with the synthetic task_id. (Do NOT use `mcp__whatsapp__list_messages` — the bridge's own sent ledger is the source of truth.)+ - **Email**: tail `$STATE_DIR/email-bridge.log` for `SENT` on the synthetic task_id.+8. **Cleanup**:+ ```bash+ rm -f "$STATE_DIR/executor-results/$TID.done.json" \+ "$STATE_DIR/executor-results/$TID.out.md"+ ```+ Leave the `tasks.jsonl` line (append-only log; harmless).++**Report:**++```+POCKET ► TEST+ task_id: [tid]+ whatsapp: [SENT|SKIPPED-disabled|FAIL: reason]+ email: [SENT|SKIPPED-disabled|FAIL: reason]+ duration: [Xs]+```++If any channel fails, surface the last error line from the corresponding `*.log` and `.health` file.++---++## Route — `logs [N]`++```bash+N="${ARG_2:-50}"+STATE_DIR="${POCKET_STATE_DIR:-$HOME/.claude/state/pocket}"++for f in activity-notifier.log run.log executor.log out-queue.log email-bridge.log; do+ echo "==> $f <=="+ tail -n "$N" "$STATE_DIR/$f" 2>/dev/null || echo "(missing)"+done+```++For Rule 7 mobile mode, default `N=20` and skip per-file headers.++---++## Route — `restart`++```bash+# 1. Kickstart the launchd activity-notifier+launchctl kickstart -k "gui/$(id -u)/com.claude-ops.pocket-activity-notifier" 2>&1++# 2. (Re)spawn the pocket-exec supervisor via the executor watchdog cron script+"$CLAUDE_PLUGIN_ROOT/scripts/ops-cron-pocket-executor.py" 2>&1 | tail -10+```++If the launchd label is missing (notifier never installed), prompt via `AskUserQuestion`: `[Install notifier now]` / `[Skip]`. On install: run `scripts/install-pocket-notifier.sh` (Rule 4: `run_in_background: true`).++---++## Route — `whatsapp on|off` and `email on|off`++Both routes mutate a small JSON config file. Never overwrite the whole file — patch in place.++```bash+STATE_DIR="${POCKET_STATE_DIR:-$HOME/.claude/state/pocket}"+CFG="$STATE_DIR/whatsapp-config.json" # or email-config.json+ACTION="${ARG_2}" # on | off+mkdir -p "$STATE_DIR"++if [[ ! -f "$CFG" ]]; then+ # Bootstrap empty config with enabled=false so subsequent `on` is meaningful.+ echo '{"enabled":false}' > "$CFG"+fi++case "$ACTION" in+ on) python3 -c "import json,sys,pathlib; p=pathlib.Path('$CFG'); d=json.loads(p.read_text()); d['enabled']=True; p.write_text(json.dumps(d,indent=2))" ;;+ off) python3 -c "import json,sys,pathlib; p=pathlib.Path('$CFG'); d=json.loads(p.read_text()); d['enabled']=False; p.write_text(json.dumps(d,indent=2))" ;;+ *) echo "usage: /ops:pocket {whatsapp|email} {on|off}"; exit 2 ;;+esac++# Echo new state+cat "$CFG"+```++**Required keys per channel** (validated by `status`):++- `whatsapp-config.json` — `chat_jid` (WhatsApp JID of the self-chat, e.g. `<digits>@s.whatsapp.net`).+- `email-config.json` — `to` (self-email address).++If `on` is requested but the required key is missing, switch state to `enabled: false` and route the user to `setup` via `AskUserQuestion`.++---++## Rule reminders++- **Rule 1**: Max 4 options per `AskUserQuestion`. None of the routes above need more.+- **Rule 2**: Never delegate commands to the user — every command runs through Bash.+- **Rule 3**: Never auto-skip channels in `setup` — always ask explicitly.+- **Rule 4**: Background by default in `setup` (`run_in_background: true`).+- **Rule 5**: This skill performs NO destructive ops — no deletes, no terminates, no force-kills beyond `launchctl kickstart -k` (which is a graceful restart, not a wipe).+- **Rule 6**: No outbound comms staged from this skill except the synthetic test message in `test`, which goes to the operator's OWN self-chat / self-email (already enabled by the user) — not to third parties. Per-message approval rule is satisfied by the test being a no-args opt-in.+- **Rule 7**: Mobile mode renders plain text only — see `status` example.++## Native tool usage++- `AskUserQuestion`: only when there is a real choice to make (stalled daemon → restart? missing channel config → bootstrap?). Never required on a green status.+- `Skill`: `setup` route may delegate to the setup channel doc.++## See also++- [`STATUS.md`](./STATUS.md) — full architecture: 8 scripts, every state file, lifecycle, troubleshooting.+- `scripts/ops-cron-pocket-watcher.py`, `scripts/ops-pocket-triage.py`, `scripts/ops-cron-pocket-executor.py`, `scripts/ops-pocket-activity-notifier.py`, `scripts/ops-pocket-out-queue.py`, `scripts/ops-pocket-email-bridge.py`, `scripts/ops-pocket-whatsapp-bridge.py`.+- `scripts/install-pocket-notifier.sh`, `scripts/com.claude-ops.pocket-activity-notifier.plist`.+- `templates/pocket-supervisor-prompt.md` — the prompt the long-lived supervisor runs under.diff --git a/claude-ops/skills/ops-pocket/STATUS.md b/claude-ops/skills/ops-pocket/STATUS.mdnew file mode 100644index 00000000..539a195a--- /dev/null+++ b/claude-ops/skills/ops-pocket/STATUS.md@@ -0,0 +1,208 @@+# OPS ► POCKET — Architecture Reference++Long-form architecture, state, and lifecycle reference for the Pocket voice-memo pipeline. Cross-referenced from [`SKILL.md`](./SKILL.md).++The pipeline turns voice memos recorded into Pocket (or any external memo source the watcher is wired to) into running Claude tasks, then notifies the operator on WhatsApp + email when each task starts and completes.++## Pipeline overview++```+ ┌─────────────────────────┐+ │ Pocket API │+ └─────────┬───────────────┘+ │ poll (cron)+ ▼+ [1] ops-cron-pocket-watcher.py+ │ writes pending-triage.jsonl+ ▼+ [2] ops-pocket-triage.py (Opus + extended thinking)+ │ ACT ⇒ tasks.jsonl+ │ SKIP ⇒ logged, discarded+ ▼+ [3] ops-cron-pocket-executor.py (watchdog cron)+ │ ensures tmux session `pocket-exec` is alive+ │ respawns supervisor window if missing+ ▼+ SUPERVISOR (long-lived Claude Code in tmux)+ │ reads tasks.jsonl via cursor+ │ spawns workers in new tmux windows+ │ appends to spawn-ledger.jsonl+ ▼+ WORKER teammates+ │ run the task to completion+ │ write executor-results/<task_id>.done.json + .out.md|.out.txt+ ▼+ [4] ops-pocket-activity-notifier.py (60s launchd LaunchAgent)+ │ tails spawn-ledger (START events)+ │ scans executor-results dir (DONE events)+ │ enqueues kind=whatsapp + kind=email rows+ ▼+ supervisor-out-queue.jsonl+ │+ ├─► [5] ops-pocket-out-queue.py (kind=whatsapp)+ │ └─► WhatsApp self-chat (whatsmeow bridge, port 8080)+ │+ └─► [6] ops-pocket-email-bridge.py (kind=email)+ └─► gog gmail send --attach (Gmail OAuth)+```++`ops-pocket-whatsapp-bridge.py` is the **inbound** counterpart in the 7-script set — it polls the operator's own self-chat for replies that should be threaded back into the supervisor's async question/reply protocol. The notifier handles **outbound**; this script handles **inbound** (user replying to a question the supervisor asked).++## Scripts (eight, including the install helper)++All paths relative to `$CLAUDE_PLUGIN_ROOT/scripts/`.++| # | Script | Role | Runs as | Interval |+|---|---------------------------------------|---------------|-------------------------------|----------|+| 1 | `ops-cron-pocket-watcher.py` | Watcher | cron (user crontab) | ~5 min |+| 2 | `ops-pocket-triage.py` | Triage | cron / on-demand | ~5 min |+| 3 | `ops-cron-pocket-executor.py` | Exec watchdog | cron | ~1 min |+| 3a | (supervisor) | Long-lived | tmux window `pocket-exec:supervisor` | always |+| 4 | `ops-pocket-activity-notifier.py` | Notifier | launchd LaunchAgent | 60s |+| 5 | `ops-pocket-out-queue.py` | WA bridge out | cron | 60s |+| 6 | `ops-pocket-email-bridge.py` | Email bridge | cron | 60s |+| 7 | `ops-pocket-whatsapp-bridge.py` | WA bridge in | cron | 60s |+| | `install-pocket-notifier.sh` | Installer | one-shot | — |++The 7-script set the SKILL.md is built around is: watcher, triage, executor, notifier, out-queue, email-bridge, whatsapp-bridge. The install helper is supporting infrastructure.++## State directory layout++Default: `$HOME/.claude/state/pocket/` — override via `POCKET_STATE_DIR`.++```+~/.claude/state/pocket/+├── cursor.txt # watcher: last polled timestamp+├── seen.json # watcher: dedup set of pocket item IDs+├── pending-triage.jsonl # awaiting triage decision (watcher → triage)+├── tasks.jsonl # canonical task store (triage → supervisor)+├── drafts.jsonl # watcher-inferred low-confidence items+├── spawn-ledger.jsonl # every worker spawn (supervisor → notifier)+├── supervisor-cursor.txt # supervisor's read cursor into tasks.jsonl+├── supervisor-out-queue.jsonl # outbound notification queue+├── out-queue-sent.jsonl # delivered WhatsApp notifications ledger+├── executor-results/+│ ├── <task_id>.done.json # worker completion marker (canonical)+│ ├── <task_id>.completed.json # legacy completion marker (also handled)+│ ├── <task_id>.out.md # worker report (markdown)+│ └── <task_id>.out.txt # worker report (plain text)+├── whatsapp-config.json # outbound WhatsApp sink config+├── email-config.json # outbound email sink config+│+├── .health # watcher health+├── .activity-notifier-health # notifier health (read by ops-doctor)+├── .activity-notifier.spawn-cursor # notifier: byte cursor into spawn-ledger+├── .activity-notifier.seen-results # notifier: set of seen .done basenames+├── .out-queue-health # WA out-queue health+├── .out-queue-cursor # WA out-queue: byte cursor+├── .email-bridge-health # email bridge health+│+├── run.log # watcher log+├── executor.log # executor watchdog log+├── activity-notifier.log # notifier log+├── activity-notifier.stdout.log # launchd stdout+├── activity-notifier.stderr.log # launchd stderr+├── out-queue.log # WA bridge out log+└── email-bridge.log # email bridge log+```++## Lifecycle — a single voice memo++1. **Recording** — user records a voice memo into Pocket.+2. **Watcher tick** (cron, ~5 min later) — `ops-cron-pocket-watcher.py` reads `cursor.txt`, hits the Pocket API for items newer than the cursor, dedupes against `seen.json`, transcribes if needed, writes a row to `pending-triage.jsonl`, advances cursor, writes `.health`.+3. **Triage tick** — `ops-pocket-triage.py` reads new rows from `pending-triage.jsonl`, asks Opus (extended thinking) for an ACT or SKIP verdict per item. ACT rows are appended to `tasks.jsonl` with a structured verdict. SKIP rows are logged and discarded.+4. **Executor watchdog tick** (cron, ~60s) — `ops-cron-pocket-executor.py` ensures the tmux session `pocket-exec` exists with an `_idle` keepalive window. If the supervisor window died, respawns it from `templates/pocket-supervisor-prompt.md`. Detects orphan worker windows (running but not in the spawn-ledger — supervisor crashed mid-spawn).+5. **Supervisor wake** — long-lived Claude session in `pocket-exec:supervisor` reads from `tasks.jsonl` via its own `supervisor-cursor.txt`. For each new ACT task, creates an Agent Teams teammate in a new tmux window, appends a START row to `spawn-ledger.jsonl`.+6. **Worker run** — the teammate completes the task. On exit it writes `executor-results/<task_id>.done.json` + a report file (`.out.md` or `.out.txt`).+7. **Notifier tick** (launchd, every 60s) — `ops-pocket-activity-notifier.py`:+ - tails `spawn-ledger.jsonl` from `.activity-notifier.spawn-cursor` → emits START events.+ - scans `executor-results/` against `.activity-notifier.seen-results` → emits DONE events.+ - for each event, writes one row per enabled channel (`kind: whatsapp` and/or `kind: email`) to `supervisor-out-queue.jsonl`.+8. **WhatsApp drain** (cron, 60s) — `ops-pocket-out-queue.py` reads `supervisor-out-queue.jsonl` from `.out-queue-cursor`, filters `kind=whatsapp`, validates `chat_jid` matches the configured self-chat (refuses to send to anything else — defense in depth against a poisoned queue row), posts to the whatsmeow bridge at `localhost:8080`, appends to `out-queue-sent.jsonl`.+9. **Email drain** (cron, 60s) — `ops-pocket-email-bridge.py` reads the same queue, filters `kind=email`, calls `gog gmail send --to <self_email> --subject ... --body ... --attach <report_file>`.+10. **Inbound** (cron, 60s) — `ops-pocket-whatsapp-bridge.py` polls the WhatsApp bridge's sqlite for new `is_from_me=1` messages in the configured `chat_jid` since the last seen message id. These are surfaced to the supervisor as async answers to pending questions (the supervisor uses file-based question/reply, not `AskUserQuestion`, since it has no attached terminal).++## Config file schemas++### `whatsapp-config.json`++```json+{+ "enabled": true,+ "chat_jid": "<digits>@s.whatsapp.net",+ "include_attachments": true+}+```++`chat_jid` is the JID of the user's **self-chat** (where they can send messages to themselves on WhatsApp). The bridge validates outbound rows match this JID before sending.++### `email-config.json`++```json+{+ "enabled": true,+ "to": "[email protected]",+ "from_account": "[email protected]",+ "subject_prefix": ""+}+```++`from_account` is the gog/Gmail OAuth account to send through. `subject_prefix` is empty by default (the `[Pocket]` prefix was stripped in commit `739b29b` of `feat/pocket-notifier-templatize`).++## Out-queue row schema++```json+{+ "id": "<uuid>",+ "kind": "whatsapp",+ "task_id": "<task_id>",+ "event": "START",+ "title": "<task title from tasks.jsonl>",+ "chat_jid": "<digits>@s.whatsapp.net",+ "body": "<rendered message>",+ "attachments": ["<absolute path to report file>"],+ "enqueued_at": "2026-05-20T08:00:00Z"+}+```++`kind` is one of `whatsapp` or `email`. `event` is `START` or `DONE`. The notifier emits one row per enabled channel per event.++## Health surface (read by `ops-doctor` and `/ops:pocket status`)++Every long-running component writes a one-line JSON health file each tick:++```json+{+ "status": "running",+ "msg": "tick",+ "extra": { "sent": 0, "skipped": 0, "cursor": 12345 },+ "updated_at": "2026-05-20T08:00:00Z"+}+```++`status` is one of:++- `running` — last tick succeeded.+- `ok` — alias for `running` (notifier uses `ok` for no-work ticks).+- `disabled` — component is enabled in code but channel config is missing or `enabled: false`.+- `error` — last tick failed; `msg` carries the error.+- `stalled` — derived in the status dashboard when `updated_at` is older than 3× the expected tick interval.++## Common failure modes++| Symptom | Most likely cause | Fix |+|------------------------------------------|----------------------------------------------------------|-----------------------------------------------------------------|+| `whatsapp: disabled` in status | `whatsapp-config.json` missing or `enabled: false` | `/ops:pocket whatsapp on` (after `setup`) |+| Notifier `error: tmux not found` | tmux not on PATH for the launchd LaunchAgent | Re-run `install-pocket-notifier.sh` after `brew install tmux` |+| out-queue `error: refusing — JID mismatch` | Queue row has a different `chat_jid` than config | Inspect queue with `tail supervisor-out-queue.jsonl` — bad enqueue |+| WA messages delivered, email not | gog Gmail OAuth expired | `gog auth status` then `gog auth add <addr> --services gmail` |+| `tmux=down` after `restart` | `_idle` keepalive window died, supervisor never spawned | `tmux kill-session -t pocket-exec` then re-run `restart` |+| Pending-triage growing, tasks not | Triage cron never running, or Opus quota hit | Check `run.log` for triage errors; manually run `ops-pocket-triage.py` |+| Notifier never fires after worker done | Worker wrote `.completed.json` but not `.done.json` | Notifier handles both; check `.activity-notifier.seen-results` |+| Duplicate notifications | `.activity-notifier.seen-results` was wiped | Don't delete it; rebuild via `--once` won't re-emit if cursor intact |++## Why this skill exists++The pipeline shipped in commit `d64bf16` with 7 scripts but no entry point. Operators had to remember which `tail -f` to run, which launchd label to kickstart, which JSON to edit. This skill is the front door.++It is intentionally read-mostly: every command is reversible, no destructive operations, no outbound comms beyond the synthetic test that goes to the operator's own self-channels.diff --git a/claude-ops/templates/pocket-supervisor-prompt.md b/claude-ops/templates/pocket-supervisor-prompt.mdindex 51b59180..2b1eb42b 100644--- a/claude-ops/templates/pocket-supervisor-prompt.md+++ b/claude-ops/templates/pocket-supervisor-prompt.md@@ -11,7 +11,7 @@ You are the team lead and **do not do implementation work yourself**. Never run- `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+- `AskUserQuestion` only when escalating to Sam- `ScheduleWakeup` to stay aliveIf 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.@@ -38,7 +38,7 @@ Your job is to **pump** items from the durable log into the team TaskList, then3. **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.+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 SendMessage Sam.## Your job@@ -46,7 +46,7 @@ Your job is to **pump** items from the durable log into the team TaskList, then2. **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 new task entry: parse JSON. Skip outbound items (`kind` in `send_message`, `draft_email`) — those go to `drafts.jsonl` for Sam'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).@@ -60,13 +60,13 @@ Your job is to **pump** items from the durable log into the team TaskList, then3. **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).+ - **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 Sam (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 Sam 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:+ Sam 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`:@@ -92,21 +92,21 @@ Your job is to **pump** items from the durable log into the team TaskList, thenReply 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."`+ - Sam 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) Sam is answering and write structured replies to supervisor-replies.jsonl.+ 3. SendMessage the worker: `"Escalated to Sam (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."`+ - SendMessage the original worker with Sam's answer: `"Sam 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).+ - TaskUpdate the worker's blocked entry back to `in_progress` (or `cancelled` if Sam 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 conventions for Sam's CLI to read:**+ - `status: "open"` — question is fresh, awaiting Sam's reply.+ - `status: "answered"` — Sam 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`:@@ -131,7 +131,7 @@ when done. This makes your work visible to the supervisor and to any humansession 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+user's complete skill/MCP surface. The user is Sam; all his global rules in~/.claude/CLAUDE.md apply.Hard rules:@@ -141,11 +141,11 @@ Hard rules:Your one job is to complete the single task you were spawned for. Ifyou notice something else that needs attention, SendMessage supervisorabout it — do NOT act on it yourself.- • Outbound comms (email, Slack, WhatsApp, SMS, calendar) require the owner's+ • Outbound comms (email, Slack, WhatsApp, SMS, calendar) require Sam'sper-message approval token. If the task implies sending, draft only andSendMessage the draft to supervisor for review.• Destructive ops (rm -rf, force-push, drop table, terminate-instances,- etc.) require explicit owner confirmation. SendMessage supervisor before+ etc.) require explicit Sam confirmation. SendMessage supervisor beforeattempting.• If the task is ambiguous, SendMessage supervisor ONE clarifying questionand wait — do not guess.