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(mcp): /ops:mcp skill + setup channel + doctor probe + daemon registration (#277)
Aurora Capitala10a3a62fcd0
diff --git a/claude-ops/bin/ops-doctor b/claude-ops/bin/ops-doctorindex 29fe64c3..7606e523 100755--- a/claude-ops/bin/ops-doctor+++ b/claude-ops/bin/ops-doctor@@ -317,6 +317,192 @@ if command -v jq >/dev/null 2>&1 && \fifi+# --- 5e. Pocket health probe ---+POCKET_STATE_DIR="$HOME/.claude/state/pocket"+POCKET_CONFIGURED=false+if [ -f "$PREFS" ] && command -v jq >/dev/null 2>&1; then+ jq -e '.pocket.enabled == true' "$PREFS" >/dev/null 2>&1 && POCKET_CONFIGURED=true+fi+# Also probe if any health/config file already exists (partial install)+for _pf in \+ "$POCKET_STATE_DIR/.activity-notifier-health" \+ "$POCKET_STATE_DIR/.out-queue-health" \+ "$POCKET_STATE_DIR/.email-bridge-health" \+ "$POCKET_STATE_DIR/.whatsapp-bridge-health" \+ "$POCKET_STATE_DIR/whatsapp-config.json" \+ "$POCKET_STATE_DIR/email-config.json"; do+ [ -f "$_pf" ] && POCKET_CONFIGURED=true && break+done++if [ "$POCKET_CONFIGURED" = true ]; then+ NOW=$(date +%s)+ MAX_HEALTH_AGE=300 # 5 minutes++ # Map service name -> health file+ _pocket_health_check() {+ local svc="$1" hf="$2"+ if [ ! -f "$hf" ]; then+ WARNINGS+=("pocket_health_missing_${svc}: $hf does not exist — service may not be running")+ return+ fi+ # Staleness check (macOS stat -f or GNU stat -c)+ if command -v stat >/dev/null 2>&1; then+ MTIME=$(stat -f '%m' "$hf" 2>/dev/null || stat -c '%Y' "$hf" 2>/dev/null || echo 0)+ AGE=$(( NOW - MTIME ))+ if [ "$AGE" -gt "$MAX_HEALTH_AGE" ]; then+ WARNINGS+=("pocket_health_stale_${svc}: $hf last written ${AGE}s ago (threshold: ${MAX_HEALTH_AGE}s)")+ fi+ fi+ # Status field+ if command -v jq >/dev/null 2>&1; then+ HF_STATUS=$(jq -r '.status // "unknown"' "$hf" 2>/dev/null || echo "unknown")+ if [ "$HF_STATUS" = "error" ]; then+ HF_MSG=$(jq -r '.message // ""' "$hf" 2>/dev/null || echo "")+ WARNINGS+=("pocket_health_error_${svc}: reports error — $HF_MSG")+ fi+ fi+ }++ _pocket_health_check "activity-notifier" "$POCKET_STATE_DIR/.activity-notifier-health"+ _pocket_health_check "out-queue" "$POCKET_STATE_DIR/.out-queue-health"++ # Email bridge — only if email is enabled+ if [ -f "$POCKET_STATE_DIR/email-config.json" ]; then+ EM_EN=$(jq -r '.enabled // "true"' "$POCKET_STATE_DIR/email-config.json" 2>/dev/null || echo "true")+ [ "$EM_EN" != "false" ] && _pocket_health_check "email-bridge" "$POCKET_STATE_DIR/.email-bridge-health"+ fi++ # WhatsApp bridge — only if whatsapp is enabled+ if [ -f "$POCKET_STATE_DIR/whatsapp-config.json" ]; then+ WA_EN=$(jq -r '.enabled // "true"' "$POCKET_STATE_DIR/whatsapp-config.json" 2>/dev/null || echo "true")+ [ "$WA_EN" != "false" ] && _pocket_health_check "whatsapp-bridge" "$POCKET_STATE_DIR/.whatsapp-bridge-health"+ fi++ # Validate JSON config files+ for _cfg in whatsapp-config email-config; do+ _cf="$POCKET_STATE_DIR/${_cfg}.json"+ if [ -f "$_cf" ] && command -v jq >/dev/null 2>&1; then+ if ! jq empty "$_cf" 2>/dev/null; then+ ERRORS+=("pocket_config_invalid_${_cfg}: $_cf is not valid JSON — re-run /ops:setup pocket")+ fi+ fi+ done++ # pocket-exec tmux session+ TMUX_SESSION="${POCKET_TMUX_SESSION:-pocket-exec}"+ if command -v tmux >/dev/null 2>&1; then+ if ! tmux has-session -t "$TMUX_SESSION" 2>/dev/null; then+ INFO+=("pocket_tmux_missing: tmux session '$TMUX_SESSION' not running — pocket executor inactive (expected if executor not in use)")+ fi+ fi++ # gog gmail auth (proxy for email send)+ if [ -f "$POCKET_STATE_DIR/email-config.json" ]; then+ EM_EN=$(jq -r '.enabled // "true"' "$POCKET_STATE_DIR/email-config.json" 2>/dev/null || echo "true")+ if [ "$EM_EN" != "false" ] && command -v gog >/dev/null 2>&1; then+ if ! gog auth status 2>&1 | grep -qi "authenticated\|logged in\|active"; then+ WARNINGS+=("pocket_email_auth: gog gmail not authenticated — email notifications will fail. Run: gog auth add <email> --services gmail")+ fi+ fi+ fi++ # Baileys bridge port 8080 (proxy for WhatsApp send)+ if [ -f "$POCKET_STATE_DIR/whatsapp-config.json" ]; then+ WA_EN=$(jq -r '.enabled // "true"' "$POCKET_STATE_DIR/whatsapp-config.json" 2>/dev/null || echo "true")+ if [ "$WA_EN" != "false" ]; then+ if ! lsof -i :8080 2>/dev/null | grep -q LISTEN; then+ WARNINGS+=("pocket_bridge_port: WhatsApp bridge not listening on :8080 — WhatsApp notifications will fail. Run: launchctl kickstart -k gui/$(id -u)/com.<user>.whatsapp-bridge")+ fi+ fi+ fi+fi++# --- 5f. MCP watchdog health probes ---+# 1. ~/.claude.json is valid JSON+if [ -f "$HOME/.claude.json" ]; then+ if command -v jq >/dev/null 2>&1; then+ if ! jq empty "$HOME/.claude.json" 2>/dev/null; then+ ERRORS+=("claude_json_invalid: ~/.claude.json is not valid JSON — MCP watchdog and Claude Code will fail to parse server list")+ fi+ fi+else+ WARNINGS+=("claude_json_missing: ~/.claude.json not found — no MCP servers configured")+fi++# 2. For each stdio MCP server, check its command resolves on PATH+if [ -f "$HOME/.claude.json" ] && command -v jq >/dev/null 2>&1 && jq empty "$HOME/.claude.json" 2>/dev/null; then+ STDIO_SERVERS=$(jq -r '+ .mcpServers // {} | to_entries[] |+ select(.value.type == null or .value.type == "stdio") |+ select(.value.command != null) |+ "\(.key)=\(.value.command)"+ ' "$HOME/.claude.json" 2>/dev/null || true)+ while IFS='=' read -r srv_name srv_cmd; do+ [ -z "$srv_name" ] && continue+ CMD_BIN="${srv_cmd%% *}"+ if [[ "$CMD_BIN" == /* ]]; then+ if [ ! -x "$CMD_BIN" ]; then+ WARNINGS+=("mcp_stdio_cmd_missing_${srv_name}: MCP server '${srv_name}' command '${CMD_BIN}' not found or not executable")+ fi+ else+ if ! command -v "$CMD_BIN" >/dev/null 2>&1; then+ WARNINGS+=("mcp_stdio_cmd_missing_${srv_name}: MCP server '${srv_name}' command '${CMD_BIN}' not on PATH")+ fi+ fi+ done <<< "$STDIO_SERVERS"+fi++# 3. Watchdog health file — check it exists and is not stale (>60 min = watchdog not running)+WATCHDOG_HEALTH_FILE="$HOME/.claude/state/mcp-watchdog/.health"+if [ -f "$WATCHDOG_HEALTH_FILE" ]; then+ if command -v python3 >/dev/null 2>&1; then+ WATCHDOG_AGE_STATUS=$(python3 -c "+import json, time, sys+try:+ h = json.load(open('$WATCHDOG_HEALTH_FILE'))+ last = h.get('last_run', '')+ if not last:+ print('unknown'); sys.exit(0)+ from datetime import datetime, timezone+ ts = datetime.fromisoformat(last.replace('Z','+00:00')).timestamp()+ print('stale' if (time.time()-ts) > 3600 else 'ok')+except Exception:+ print('error')+" 2>/dev/null || echo "unknown")+ if [ "$WATCHDOG_AGE_STATUS" = "stale" ]; then+ WARNINGS+=("mcp_watchdog_stale: MCP watchdog health not updated in >1h — cron may be unregistered. Run /ops:mcp restart")+ fi++ # 4. Warn on servers that have been degraded >1 hour+ WATCHDOG_STATE_FILE="$HOME/.claude/state/mcp-watchdog/state.json"+ if [ -f "$WATCHDOG_STATE_FILE" ] && [ "$WATCHDOG_AGE_STATUS" = "ok" ]; then+ DEGRADED_LONG=$(python3 -c "+import json, time+try:+ s = json.load(open('$WATCHDOG_STATE_FILE'))+ now = time.time()+ bad = []+ for name, info in s.items():+ if info.get('state') == 'healthy': continue+ probed = info.get('probed_at', '')+ if not probed: continue+ from datetime import datetime+ ts = datetime.fromisoformat(probed.replace('Z','+00:00')).timestamp()+ if now - ts > 3600:+ bad.append(name + ':' + info.get('state','?'))+ print(','.join(bad))+except Exception:+ print('')+" 2>/dev/null || echo "")+ if [ -n "$DEGRADED_LONG" ]; then+ WARNINGS+=("mcp_servers_degraded_long: MCP servers degraded >1h: $DEGRADED_LONG — run /ops:mcp status")+ fi+ fi+ fi+else+ WARNINGS+=("mcp_watchdog_no_health: MCP watchdog has never run (no health file). Run /ops:mcp restart to register cron")+fi+# --- 6. Registry ---REGISTRY_STATUS="missing"REGISTRY_COUNT=0@@ -373,7 +559,92 @@ ENV_JSON=$(cat <<ENVENV)-# --- 10. Cache copies vs source ---+# --- 10. Daemon services health ---+DAEMON_SERVICES_FILE="${CLAUDE_PLUGIN_ROOT:-$SCRIPT_DIR}/scripts/daemon-services.default.json"+DAEMON_HEALTH=()+if [ ! -f "$DAEMON_SERVICES_FILE" ]; then+ WARNINGS+=("daemon_services_missing: daemon-services.default.json not found at $DAEMON_SERVICES_FILE")+elif ! command -v jq >/dev/null 2>&1; then+ WARNINGS+=("daemon_services_no_jq: cannot check daemon health without jq")+else+ NOW_EPOCH=$(date +%s)+ SERVICE_NAMES=$(jq -r '.services | keys[]' "$DAEMON_SERVICES_FILE" 2>/dev/null || true)+ for svc in $SERVICE_NAMES; do+ ENABLED=$(jq -r ".services[\"$svc\"].enabled" "$DAEMON_SERVICES_FILE" 2>/dev/null || echo "false")+ [ "$ENABLED" = "true" ] || continue++ HEALTH_FILE_RAW=$(jq -r ".services[\"$svc\"].health_file // empty" "$DAEMON_SERVICES_FILE" 2>/dev/null || true)+ if [ -z "$HEALTH_FILE_RAW" ]; then+ DAEMON_HEALTH+=("? $svc: no health file declared")+ continue+ fi++ # Expand ~ to $HOME+ HEALTH_FILE="${HEALTH_FILE_RAW/#\~/$HOME}"++ if [ ! -f "$HEALTH_FILE" ]; then+ DAEMON_HEALTH+=("⚠ $svc: health file missing ($HEALTH_FILE_RAW)")+ WARNINGS+=("daemon_health_missing_${svc}: service '$svc' health file not found at $HEALTH_FILE_RAW")+ continue+ fi++ # Parse status and last_run from JSON health file+ SVC_STATUS=$(jq -r '.status // "unknown"' "$HEALTH_FILE" 2>/dev/null || echo "parse_error")+ LAST_RUN_RAW=$(jq -r '.last_run // empty' "$HEALTH_FILE" 2>/dev/null || true)++ if [ -z "$LAST_RUN_RAW" ]; then+ DAEMON_HEALTH+=("⚠ $svc: status=$SVC_STATUS last_run=unknown")+ WARNINGS+=("daemon_health_no_last_run_${svc}: service '$svc' health file has no last_run field")+ continue+ fi++ # Compute age in seconds; handle both epoch integers and ISO-8601 strings+ if echo "$LAST_RUN_RAW" | grep -qE '^[0-9]+$'; then+ LAST_RUN_EPOCH="$LAST_RUN_RAW"+ else+ # macOS date -jf is strict: strip fractional seconds and trailing Z (UTC).+ LAST_RUN_PARSE="${LAST_RUN_RAW%%.*}"+ LAST_RUN_PARSE="${LAST_RUN_PARSE%Z}"+ LAST_RUN_EPOCH=$(date -d "$LAST_RUN_RAW" +%s 2>/dev/null || date -jf "%Y-%m-%dT%H:%M:%S" "$LAST_RUN_PARSE" +%s 2>/dev/null || echo "0")+ fi++ AGE_SEC=$(( NOW_EPOCH - LAST_RUN_EPOCH ))+ AGE_MIN=$(( AGE_SEC / 60 ))++ # Determine staleness threshold: services with cron >= 30m use 15m warning, else 5m+ CRON_EXPR=$(jq -r ".services[\"$svc\"].cron // empty" "$DAEMON_SERVICES_FILE" 2>/dev/null || true)+ if [ -z "$CRON_EXPR" ]; then+ # continuous / no cron — use 15m threshold+ STALE_THRESHOLD=15+ else+ # Parse the minute field: if it's */N, use N; treat as frequent if N<=10+ MINUTE_FIELD=$(echo "$CRON_EXPR" | awk '{print $1}')+ if echo "$MINUTE_FIELD" | grep -qE '^\*/([0-9]+)$'; then+ CRON_INTERVAL=$(echo "$MINUTE_FIELD" | grep -oE '[0-9]+')+ if [ "$CRON_INTERVAL" -le 10 ]; then+ STALE_THRESHOLD=5+ else+ STALE_THRESHOLD=15+ fi+ else+ # Hourly or less frequent — 15m threshold+ STALE_THRESHOLD=15+ fi+ fi++ if [ "$SVC_STATUS" = "ok" ] && [ "$AGE_MIN" -le "$STALE_THRESHOLD" ]; then+ DAEMON_HEALTH+=("✓ $svc: status=ok last_run=${AGE_MIN}m ago")+ elif [ "$AGE_MIN" -gt "$STALE_THRESHOLD" ]; then+ DAEMON_HEALTH+=("✗ $svc: stale (last_run=${AGE_MIN}m ago, threshold=${STALE_THRESHOLD}m)")+ WARNINGS+=("daemon_health_stale_${svc}: service '$svc' last ran ${AGE_MIN}m ago (threshold ${STALE_THRESHOLD}m)")+ else+ DAEMON_HEALTH+=("⚠ $svc: status=$SVC_STATUS last_run=${AGE_MIN}m ago")+ WARNINGS+=("daemon_health_status_${svc}: service '$svc' reported status='$SVC_STATUS'")+ fi+ done+fi++# --- 10b. Cache copies vs source ---CACHE_DIR="$HOME/.claude/plugins/cache/ops-marketplace/ops"CACHE_VERSIONS=()if [ -d "$CACHE_DIR" ]; then@@ -388,6 +659,7 @@ err_json="[]"warn_json="[]"info_json="[]"cache_json="[]"+daemon_json="[]"if command -v jq >/dev/null 2>&1; thenif [ ${#ERRORS[@]} -gt 0 ]; thenerr_json=$(printf '%s\n' "${ERRORS[@]}" | jq -R . | jq -s . 2>/dev/null || echo "[]")@@ -401,6 +673,9 @@ if command -v jq >/dev/null 2>&1; thenif [ ${#CACHE_VERSIONS[@]} -gt 0 ]; thencache_json=$(printf '%s\n' "${CACHE_VERSIONS[@]}" | jq -R . | jq -s . 2>/dev/null || echo "[]")fi+ if [ ${#DAEMON_HEALTH[@]} -gt 0 ]; then+ daemon_json=$(printf '%s\n' "${DAEMON_HEALTH[@]}" | jq -R . | jq -s . 2>/dev/null || echo "[]")+ fificat <<EOF@@ -422,6 +697,7 @@ cat <<EOF"path": "$PREFS"},"cache_versions": $cache_json,+ "daemon_services_health": $daemon_json,"skill_count": $(find "$SCRIPT_DIR/skills" -name "SKILL.md" 2>/dev/null | wc -l | tr -d ' '),"agent_count": $(find "$SCRIPT_DIR/agents" -name "*.md" 2>/dev/null | wc -l | tr -d ' '),"bin_count": $(find "$SCRIPT_DIR/bin" -name "ops-*" 2>/dev/null | wc -l | tr -d ' ')diff --git a/claude-ops/bin/ops-marketing-link-prewarm b/claude-ops/bin/ops-marketing-link-prewarmindex 8046f0b3..01c35ccb 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" # gitleaks:allow — prefs path reference, not a literal secret+ echo "api_secret:ga4.api_secret" # gitleaks:allow;;analytics_amplitude)echo "api_key:amplitude.api_key"diff --git a/claude-ops/scripts/daemon-services.default.json b/claude-ops/scripts/daemon-services.default.jsonindex e203ea1a..2a8ac1f5 100644--- a/claude-ops/scripts/daemon-services.default.json+++ b/claude-ops/scripts/daemon-services.default.json@@ -1,5 +1,12 @@{"services": {+ "mcp-watchdog": {+ "enabled": true,+ "command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-mcp-watchdog.py",+ "cron": "*/5 * * * *",+ "health_file": "~/.claude/state/mcp-watchdog/.health",+ "_note": "MCP server connectivity watchdog. Auto-reconnects degraded servers, sends WhatsApp/email alert via supervisor-out-queue when manual reauth needed. Cron interval drives latency of degraded-state detection."+ },"briefing-pre-warm": {"enabled": true,"command": "${CLAUDE_PLUGIN_ROOT}/bin/ops-gather",@@ -46,7 +53,7 @@"enabled": false,"command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-cron-inbox-digest.sh","cron": "0 */4 * * *",- "_note": "Aggregates all configured channels (WhatsApp, Email, Telegram, Slack) every 4 hours. Script not yet landed — re-enable when ops-cron-inbox-digest.sh is added."+ "_note": "Aggregates all configured channels (WhatsApp, Email, Telegram, Slack) every 4 hours into a single digest. Enable after configuring at least one channel in /ops:settings."},"message-listener": {"enabled": false,@@ -55,13 +62,13 @@"health_file": "~/.claude/plugins/data/ops-ops-marketplace/listener-health.txt","restart_delay": 30,"max_restarts": 20,- "_note": "Persistent poller for WhatsApp and Telegram. Script not yet landed — re-enable when ops-message-listener.sh is added."+ "_note": "Persistent poller for WhatsApp and Telegram. Writes incoming messages to the ops inbox queue for /ops:inbox processing. Enable after configuring channel credentials in /ops:settings."},"competitor-intel": {"enabled": false,"command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-cron-competitor-intel.sh","cron": "0 10 * * 1",- "_note": "Weekly competitor intelligence report every Monday at 10am. Script not yet landed — re-enable when ops-cron-competitor-intel.sh is added."+ "_note": "Weekly competitor intelligence report every Monday at 10am. Fetches and summarises competitor activity across registered projects. Enable after configuring project registry."},"competitor-alert": {"enabled": true,diff --git a/claude-ops/skills/ops-doctor/SKILL.md b/claude-ops/skills/ops-doctor/SKILL.mdindex a21452b2..e8d9bd01 100644--- a/claude-ops/skills/ops-doctor/SKILL.md+++ b/claude-ops/skills/ops-doctor/SKILL.md@@ -124,6 +124,56 @@ If there are **no errors and no warnings**:Display: "All checks passed. Plugin is healthy."+## MCP watchdog health probe++After Phase 1 diagnostics, parse the `5f` block warnings from `bin/ops-doctor`. The bin script emits these MCP-specific keys:++- `claude_json_invalid` — `~/.claude.json` is not valid JSON (hard error — all MCP tooling breaks)+- `claude_json_missing` — no `~/.claude.json` (warning — no servers configured)+- `mcp_stdio_cmd_missing_<name>` — stdio server `command` binary not on PATH+- `mcp_watchdog_stale` — watchdog health not updated in >1h (cron not running)+- `mcp_watchdog_no_health` — watchdog has never run (never registered)+- `mcp_servers_degraded_long` — one or more HTTP MCP servers degraded >1h++For each warning, surface a one-line fix hint:++| Warning | Fix hint |+|---------|----------|+| `claude_json_invalid` | `python3 -c "import json; json.load(open('$HOME/.claude.json'))"` to find the syntax error |+| `mcp_stdio_cmd_missing_<name>` | Verify the command path and install the missing binary; update `~/.claude.json` if path changed |+| `mcp_watchdog_stale` or `mcp_watchdog_no_health` | `/ops:mcp restart` to register crontab entries |+| `mcp_servers_degraded_long` | `/ops:mcp status` for full detail, then `/ops:mcp reauth <name>` for each `needs_bootstrap` |++Include these warnings in the doctor-agent prompt for auto-fix where applicable (e.g., crontab registration is safe to do automatically).++## Pocket health probe++After Phase 1 diagnostics, run the pocket probe if the `pocket` section is configured in preferences or if `--verbose` was passed. The bin script already includes these checks (section 5e); this section describes what the SKILL layer adds on top.++Parse the `pocket` block from the `bin/ops-doctor` JSON output. Surface any pocket-specific warnings:++- `pocket_health_stale_*` — health file exists but mtime > 5 minutes+- `pocket_health_missing_*` — health file does not exist+- `pocket_health_error_*` — health file has `"status": "error"`+- `pocket_tmux_missing` — `pocket-exec` tmux session not found+- `pocket_config_invalid_*` — whatsapp-config.json or email-config.json not valid JSON+- `pocket_email_auth` — `gog gmail status` not authenticated+- `pocket_bridge_port` — Baileys bridge port 8080 not listening++For each warning, surface a one-line fix hint:++| Warning | Fix hint |+|---------|----------|+| `pocket_health_stale_activity-notifier` | `launchctl kickstart -k gui/$UID/com.claude-ops.pocket-activity-notifier` |+| `pocket_health_missing_*` | `bash $CLAUDE_PLUGIN_ROOT/scripts/install-pocket-notifier.sh` |+| `pocket_health_error_*` | `tail -30 ~/.claude/state/pocket/activity-notifier.stderr.log` |+| `pocket_tmux_missing` | Executor not running — start with `python3 $CLAUDE_PLUGIN_ROOT/scripts/ops-cron-pocket-executor.py` |+| `pocket_config_invalid_whatsapp` | Re-run `/ops:setup pocket` to write a valid whatsapp-config.json |+| `pocket_config_invalid_email` | Re-run `/ops:setup pocket` to write a valid email-config.json |+| `pocket_email_auth` | `gog auth add <your-email> --services gmail` |+| `pocket_bridge_port` | `launchctl kickstart -k gui/$UID/com.<user>.whatsapp-bridge` |++Include pocket warnings in the doctor-agent prompt so it can auto-fix where possible.## Phase 3 — Post-fix verificationAfter the agent completes, re-run diagnostics:diff --git a/claude-ops/skills/ops-mcp/SKILL.md b/claude-ops/skills/ops-mcp/SKILL.mdnew file mode 100644index 00000000..d933905e--- /dev/null+++ b/claude-ops/skills/ops-mcp/SKILL.md@@ -0,0 +1,279 @@+---+name: ops-mcp+description: MCP server health dashboard and reconnect control. Surfaces the watchdog + keepalive + reauth subsystem as a discoverable slash command. Routes — status, servers, reconnect, reauth, logs, restart, test.+argument-hint: "[status|servers|reconnect [server]|reauth [server]|logs [N]|restart|test [server]]"+allowed-tools:+ - Bash+ - Read+ - Grep+ - Glob+ - Skill+ - AskUserQuestion+effort: low+maxTurns: 20+---++# OPS ► MCP++Surfaces the MCP auto-reconnect subsystem (watchdog + keepalive + reauth) as a discoverable slash command. These three scripts were previously orphaned — no plugin-level entry point. This skill is the entry point.++For full architecture reference (state files, scripts, failure modes) see [`STATUS.md`](./STATUS.md).++## Runtime Context++Before any route runs, resolve:++1. **State dir**: `$HOME/.claude/state/mcp-watchdog` — watchdog state, health, and logs.+2. **Keepalive state dir**: `$HOME/.claude/state/mcp-keepalive` — keepalive logs and health.+3. **Reauth state dir**: `$HOME/.claude/state/mcp-reauth` — reauth logs.+4. **Plugin root**: `${CLAUDE_PLUGIN_ROOT}` — used to invoke scripts.+5. **Claude config**: `$HOME/.claude.json` — source of truth for configured MCP servers.++If the watchdog state dir does not exist, the watchdog has never run — surface a setup hint on the `status` route.++## Routing table++Parse `$ARGUMENTS` and route immediately. First token decides the route.++| First arg | Route |+| ----------------------- | ----------------------------------------------------------------------------- |+| (empty) / `status` | **Status dashboard** — watchdog health + per-server states + last tick |+| `servers` | List all MCP servers from `~/.claude.json` with current state |+| `reconnect [server]` | Manually trigger watchdog reconnect for one server or all |+| `reauth [server]` | Invoke `ops-mcp-reauth.py` for the named server (Playwright OAuth flow) |+| `logs [N]` | Tail N lines (default 50) of watchdog + keepalive logs |+| `restart` | Restart the watchdog (update crontab entry) |+| `test [server]` | Fire a no-op MCP probe against one server to verify reachability |++Anything else: print the routing table and exit.++---++## Route — `status` (default)++Read state files in parallel, render a compact dashboard.++```bash+WATCHDOG_STATE="$HOME/.claude/state/mcp-watchdog"+KEEPALIVE_STATE="$HOME/.claude/state/mcp-keepalive"++# Watchdog health file+cat "$WATCHDOG_STATE/.health" 2>/dev/null++# Current server states (last watchdog run)+cat "$WATCHDOG_STATE/state.json" 2>/dev/null++# Last run timestamp from log+tail -n 5 "$WATCHDOG_STATE/run.log" 2>/dev/null++# Keepalive health+cat "$KEEPALIVE_STATE/.health" 2>/dev/null++# Crontab entry (to confirm watchdog is scheduled)+crontab -l 2>/dev/null | grep -E "ops-mcp-(watchdog|keepalive)"+```++**Output format:**++```+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+ OPS ► MCP — [timestamp]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━++DAEMONS+ watchdog [running|never_run] last tick [Xs ago] cron [registered|missing]+ keepalive [ok|warn|never_run] last tick [Xs ago]++SERVERS ([N] configured)+ [name] [healthy|token_expired|needs_bootstrap|unreachable|server_error]+ url=[masked — scheme+host only] last_probed=[Xs ago]++SUMMARY+ healthy=[N] degraded=[N] needs_bootstrap=[N]++LAST RECONNECT ACTIVITY+ [last 3 lines from run.log showing recovered/degraded events]+━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━+```++**Mobile mode** (`$SSH_CONNECTION` set, `$OPS_MOBILE=1`, or `$COLUMNS<80`):++```+mcp: watchdog ok, keepalive ok, 5m ago+servers: 4 healthy, 1 needs_bootstrap (giga)+cron: registered+```++After dashboard: if any server is `needs_bootstrap`, surface a one-line hint: "Run `/ops:mcp reauth <name>` to restore OAuth." No `AskUserQuestion` unless something requires a binary choice.++---++## Route — `servers`++List every MCP server from `~/.claude.json` cross-referenced with the last watchdog `state.json`.++```bash+# Parse ~/.claude.json for all mcpServers entries+python3 -c "+import json, os+d = json.load(open(os.path.expanduser('~/.claude.json')))+servers = d.get('mcpServers') or {}+for name, cfg in servers.items():+ print(json.dumps({'name': name, 'type': cfg.get('type','stdio'), 'url': cfg.get('url',''), 'command': cfg.get('command','')}))+"++# Cross-reference with watchdog state+cat "$HOME/.claude/state/mcp-watchdog/state.json" 2>/dev/null+```++Format per server:++```+[name]+ type: [http|stdio]+ url/cmd: [masked url or command path]+ state: [healthy|token_expired|needs_bootstrap|unreachable|not_probed]+ probed: [ISO timestamp or "never"]+ detail: [detail field if not healthy]+```++---++## Route — `reconnect [server]`++Manually triggers the watchdog for one server or all. The watchdog already handles auto-refresh; this forces an immediate out-of-schedule run.++```bash+WATCHDOG="${CLAUDE_PLUGIN_ROOT}/scripts/ops-mcp-watchdog.py"++if [[ -n "$SERVER_ARG" ]]; then+ # Single server: set env to probe only that URL+ URL=$(python3 -c "+import json, os, sys+d = json.load(open(os.path.expanduser('~/.claude.json')))+s = (d.get('mcpServers') or {}).get(sys.argv[1], {})+print(s.get('url', ''))+" "$SERVER_ARG")+ MCP_KEEPALIVE_URLS="$URL" python3 "$WATCHDOG"+else+ # All servers+ python3 "$WATCHDOG"+fi+```++Print the exit code and last 5 lines of `run.log` on completion.++---++## Route — `reauth [server]`++Invokes `ops-mcp-reauth.py` (Playwright headless OAuth flow) for the named server. If no server is named, list `needs_bootstrap` servers and `AskUserQuestion` which to reauth.++```bash+REAUTH="${CLAUDE_PLUGIN_ROOT}/scripts/ops-mcp-reauth.py"++# Resolve URL for the named server+URL=$(python3 -c "+import json, os, sys+d = json.load(open(os.path.expanduser('~/.claude.json')))+s = (d.get('mcpServers') or {}).get(sys.argv[1], {})+print(s.get('url', ''))+" "$SERVER_ARG")++if [[ -z "$URL" ]]; then+ echo "Server '$SERVER_ARG' not found or has no URL (stdio servers cannot be reauthed this way)"+ exit 1+fi++python3 "$REAUTH" "$URL"+```++On exit 0: confirm tokens were written, suggest running `/ops:mcp test <server>` to verify.+On exit 1: the consent page required a login the browser profile didn't have. Surface the bootstrap hint: `python3 $REAUTH --bootstrap` opens a headed browser for one-time sign-in.++---++## Route — `logs [N]`++Tail the most recent N lines (default 50) from watchdog, keepalive, and reauth logs.++```bash+N="${LOG_N:-50}"+WATCHDOG_LOG="$HOME/.claude/state/mcp-watchdog/run.log"+KEEPALIVE_LOG="$HOME/.claude/state/mcp-keepalive/run.log"+REAUTH_LOG="$HOME/.claude/state/mcp-reauth/run.log"++echo "=== watchdog (last $N) ==="+tail -n "$N" "$WATCHDOG_LOG" 2>/dev/null || echo "(no log)"++echo ""+echo "=== keepalive (last $N) ==="+tail -n "$N" "$KEEPALIVE_LOG" 2>/dev/null || echo "(no log)"++echo ""+echo "=== reauth (last $N) ==="+tail -n "$N" "$REAUTH_LOG" 2>/dev/null || echo "(no log)"+```++---++## Route — `restart`++Ensures both `ops-mcp-watchdog.py` (cron `*/5`) and `ops-mcp-keepalive.sh` (cron `*/15`) are in the user's crontab. Does NOT remove existing entries — adds if missing.++```bash+WATCHDOG="${CLAUDE_PLUGIN_ROOT}/scripts/ops-mcp-watchdog.py"+KEEPALIVE="${CLAUDE_PLUGIN_ROOT}/scripts/ops-mcp-keepalive.sh"++# Idempotent crontab injection+TMPFILE=$(mktemp)+crontab -l 2>/dev/null > "$TMPFILE" || true++if ! grep -q "ops-mcp-watchdog" "$TMPFILE"; then+ echo "*/5 * * * * /opt/homebrew/bin/python3 $WATCHDOG >> $HOME/.claude/state/mcp-watchdog/run.log 2>&1" >> "$TMPFILE"+ echo "Added watchdog cron entry"+fi++if ! grep -q "ops-mcp-keepalive" "$TMPFILE"; then+ echo "*/15 * * * * bash $KEEPALIVE >> $HOME/.claude/state/mcp-keepalive/run.log 2>&1" >> "$TMPFILE"+ echo "Added keepalive cron entry"+fi++crontab "$TMPFILE"+rm "$TMPFILE"+echo "Crontab updated. Verify with: crontab -l | grep ops-mcp"+```++---++## Route — `test [server]`++Fire a direct JSON-RPC `initialize` probe at the named server (or all) using the same logic as the watchdog.++```bash+python3 - "$SERVER_ARG" <<'PY'+import json, os, sys+from pathlib import Path++# Import probe logic from watchdog+import importlib.util+wp = Path(os.environ.get("CLAUDE_PLUGIN_ROOT", "")) / "scripts/ops-mcp-watchdog.py"+spec = importlib.util.spec_from_file_location("watchdog", wp)+wdog = importlib.util.module_from_spec(spec)+spec.loader.exec_module(wdog)++target = sys.argv[1] if len(sys.argv) > 1 else None+mcps = wdog.list_http_mcps()+if not mcps:+ print("No HTTP MCPs configured")+ sys.exit(0)++for name, url in mcps.items():+ if target and name != target:+ continue+ r = wdog.probe(url, name)+ print(f"{name}: {r['state']}" + (f" — {r.get('detail','')}" if r.get('detail') else ""))+PY+```++Print result per server. On `healthy`: confirm reachable. On any other state: describe the failure and suggest the remediation route (`/ops:mcp reauth <name>` or `/ops:mcp reconnect <name>`).diff --git a/claude-ops/skills/ops-mcp/STATUS.md b/claude-ops/skills/ops-mcp/STATUS.mdnew file mode 100644index 00000000..438f0143--- /dev/null+++ b/claude-ops/skills/ops-mcp/STATUS.md@@ -0,0 +1,139 @@+# OPS ► MCP — Architecture Reference++Long-form architecture, state, and lifecycle reference for the MCP auto-reconnect subsystem. Cross-referenced from [`SKILL.md`](./SKILL.md).++The subsystem keeps HTTP MCP servers alive and authenticated without user intervention. Three scripts form the core: a watchdog that probes + diffs + notifies, a keepalive that proactively refreshes OAuth tokens before they expire, and a reauth script that drives a headless Playwright browser through the OAuth consent flow when a token cannot be silently refreshed.++## Subsystem overview++```+ ~/.claude.json (mcpServers)+ │+ ▼+ [1] ops-mcp-watchdog.py (cron */5 * * * *)+ │ probe each HTTP MCP via JSON-RPC initialize+ │ classify: healthy / token_expired / needs_bootstrap /+ │ cloudflare_ua / unreachable / server_error+ │ diff vs last tick (state.last.json)+ │ on token_expired → attempt_refresh() [direct OAuth POST]+ │ on needs_bootstrap → invoke ops-mcp-reauth.py (Playwright)+ │ on new degradations → WhatsApp notify (via supervisor-out-queue)+ │ on all paths → write_health() to .health+ │ write current state → state.json+ ▼+ [2] ops-mcp-keepalive.sh (cron */15 * * * *)+ │ for every HTTP MCP, find ~/.mcp-auth/mcp-remote-*/+ │ <md5(url)>_tokens.json+ │ if expires_at < now + grace_min → POST refresh_token+ │ token endpoint from client_info.json or .well-known discovery+ │ atomic write back to tokens.json+ │ write health JSON to ~/.claude/state/mcp-keepalive/.health+ ▼+ [3] ops-mcp-reauth.py (invoked by watchdog OR /ops:mcp reauth)+ │ spawn `npx -y mcp-remote <url>` in background+ │ capture the OAuth authorize URL from its stdout+ │ launch Playwright Chromium (persistent profile at+ │ ~/.claude/state/mcp-reauth-browser/)+ │ click Approve/Authorize/Allow button+ │ watch for localhost /oauth/callback intercept+ │ verify tokens.json was written by mcp-remote+ │ --bootstrap mode: headed window so user signs into each+ │ provider once; subsequent reauths headless+```++## Scripts++All paths relative to `$CLAUDE_PLUGIN_ROOT/scripts/`.++| # | Script | Role | Triggered by | Interval |+|---|---------------------------|--------------------------|-----------------------------------|------------|+| 1 | `ops-mcp-watchdog.py` | Probe + diff + notify | cron, `/ops:mcp reconnect` | */5 min |+| 2 | `ops-mcp-keepalive.sh` | Proactive token refresh | cron | */15 min |+| 3 | `ops-mcp-reauth.py` | Playwright OAuth consent | watchdog (auto), `/ops:mcp reauth`| on-demand |++## Hook flow (CLAUDE.md MCP auto-reconnect doctrine)++The MCP auto-reconnect behavior documented in `CLAUDE.md` has two layers:++1. **In-session layer** (`PreToolUse` hook on `mcp__*` tools): When a tool call fails due to disconnection, the hook kills the stale server process and Claude Code respawns it. Claude Code then waits 5 seconds and retries. This is handled by Claude Code itself.++2. **Background layer** (this subsystem): Runs out-of-band on cron. Detects HTTP MCP degradation before an active session hits it, attempts silent recovery (token refresh or Playwright reauth), and sends WhatsApp notification if manual intervention is required.++The two layers are complementary: the hook handles transient in-session crashes; the watchdog handles persistent auth failures and proactively prevents them via keepalive.++## State directory layout++```+~/.claude/state/mcp-watchdog/+├── state.json # current per-server probe results (canonical)+├── state.last.json # previous tick's results (for diff)+├── .health # watchdog health file (read by ops-doctor)+│ # fields: status, message, last_run, summary,+│ # degraded_count, recovered_count+└── run.log # watchdog log (appended each tick)++~/.claude/state/mcp-keepalive/+├── .health # keepalive health JSON+└── run.log # keepalive log++~/.claude/state/mcp-reauth/+├── run.log # reauth log (per OAuth flow attempt)+└── [mcp-reauth-browser/] # Playwright persistent Chromium profile+ # (actually at ~/.claude/state/mcp-reauth-browser/)+```++## Server state classification++| State | Meaning | Auto-recovery |+|--------------------|-------------------------------------------------------------------|---------------|+| `healthy` | JSON-RPC initialize returned valid result | N/A |+| `token_expired` | 401 + refresh_token exists in tokens.json | Silent refresh |+| `needs_bootstrap` | 401 + no refresh_token (first-time or refresh expired) | Playwright reauth |+| `cloudflare_ua` | 403 from Cloudflare bot challenge (change UA or use different path) | Manual |+| `unreachable` | DNS failure or connection refused | Wait / manual |+| `server_error` | 5xx from MCP server | Wait |+| `weird_2xx` | 200 but response was not a valid MCP init result | Check server |++## Token cache location++mcp-remote writes OAuth tokens under `~/.mcp-auth/mcp-remote-<version>/`. The watchdog and keepalive find tokens by taking `md5(url)` and looking for `<hash>_tokens.json` in the most recently modified `mcp-remote-*` subdirectory. Client metadata (OAuth endpoints, client_id) is in `<hash>_client_info.json` alongside.++The token cache is what Claude Code itself uses — the watchdog reads and writes to the same files, making token state consistent between the watchdog and active sessions.++## API-key MCPs vs OAuth MCPs++Servers listed in `API_KEY_MCPS` in `ops-mcp-watchdog.py` (currently: `pocketai`) use a static Bearer key retrieved from macOS Keychain via `security find-generic-password`. They do not use token refresh — the key is either valid or not. The watchdog skips the OAuth token-cache lookup for these servers.++## Notification behavior++On new degradations (server was healthy on previous tick, now not):+1. macOS notification via `osascript` (fires immediately, no config needed)+2. WhatsApp message via `supervisor-out-queue.jsonl` (same queue as pocket notifier)++On recovery (server was degraded, now healthy): logged only, no notification.++Notification can be suppressed with `MCP_WATCHDOG_NOTIFY=0`.++## Environment variables++| Variable | Default | Effect |+|-----------------------------|---------|-----------------------------------------------------|+| `MCP_WATCHDOG_AUTO_REFRESH` | `1` | Attempt silent OAuth refresh on token_expired |+| `MCP_WATCHDOG_AUTO_REAUTH` | `1` | Invoke Playwright reauth on needs_bootstrap |+| `MCP_WATCHDOG_NOTIFY` | `1` | Send WhatsApp + macOS notifications on degradation |+| `MCP_WATCHDOG_PROBE_TIMEOUT`| `6` | Per-server HTTP probe timeout in seconds |+| `MCP_KEEPALIVE_GRACE_MIN` | `15` | Refresh token if expiry < this many minutes away |+| `MCP_KEEPALIVE_URLS` | (all) | Space-separated URL list; overrides full scan |+| `MCP_REAUTH_HEADLESS` | `1` | Set to `0` to see the Playwright browser |+| `MCP_REAUTH_TIMEOUT` | `90` | Per-MCP consent flow timeout in seconds |++## Common failure modes++| Symptom | Likely cause | Remediation |+|---------|-------------|-------------|+| All servers `needs_bootstrap` after machine restart | mcp-remote token cache wiped or Keychain locked | `/ops:mcp reauth <name>` for each |+| Server `token_expired` but auto-refresh fails | Provider rotated signing key or revoked refresh | `/ops:mcp reauth <name>` |+| `cloudflare_ua` state | Cloudflare WAF blocking the watchdog's UA | Not auto-recoverable; use Claude Code directly |+| `unreachable` for remote server | Network change, server down, or DNS failure | Check server status; wait and run `/ops:mcp reconnect` |+| Playwright reauth exits 1 | Browser profile has no session for the OAuth provider | Run `python3 $CLAUDE_PLUGIN_ROOT/scripts/ops-mcp-reauth.py --bootstrap` once |+| Watchdog health file stale > 15 min | Cron not registered or Python binary path wrong | `/ops:mcp restart` to re-register crontab |diff --git a/claude-ops/skills/setup/channels/mcp.md b/claude-ops/skills/setup/channels/mcp.mdnew file mode 100644index 00000000..51174e83--- /dev/null+++ b/claude-ops/skills/setup/channels/mcp.md@@ -0,0 +1,92 @@+# Setup Channel — MCP Server Connectivity++This channel walks through first-time setup of the MCP auto-reconnect subsystem.++## 1. Verify installed servers++```bash+claude mcp list+```++This lists every server Claude Code knows about. Cross-check against `~/.claude.json` under `mcpServers`. HTTP servers (type `http`) are probed by the watchdog; stdio servers (type `stdio` or `command`) are not — they are managed by Claude Code's process lifecycle.++If `~/.claude.json` does not exist or has no `mcpServers` block, there is nothing to monitor. Add servers via `claude mcp add` or by editing the file directly.++## 2. Register the watchdog as a daemon service++The watchdog and keepalive run on cron. Register them with:++```bash+/usr/bin/env bash "${CLAUDE_PLUGIN_ROOT}/skills/ops-mcp/SKILL.md"+```++Or directly via the restart route:++```+/ops:mcp restart+```++This injects two crontab entries if not already present:++```+*/5 * * * * /opt/homebrew/bin/python3 ${CLAUDE_PLUGIN_ROOT}/scripts/ops-mcp-watchdog.py >> ~/.claude/state/mcp-watchdog/run.log 2>&1+*/15 * * * * bash ${CLAUDE_PLUGIN_ROOT}/scripts/ops-mcp-keepalive.sh >> ~/.claude/state/mcp-keepalive/run.log 2>&1+```++Verify:++```bash+crontab -l | grep ops-mcp+```++The `daemon-services.default.json` also carries an `mcp-watchdog` entry which the daemon installer reads. If you use the daemon installer, it will handle cron registration automatically.++## 3. OAuth bootstrap for servers that need browser auth++Remote MCP servers using OAuth (giga, linear, atlassian, etc.) require a one-time interactive sign-in before the headless reauth can work. The Playwright reauth stores session cookies in a persistent Chromium profile at `~/.claude/state/mcp-reauth-browser/`. Once a provider session is saved there, all subsequent reauths are zero-touch.++Bootstrap each provider you use:++```bash+python3 "${CLAUDE_PLUGIN_ROOT}/scripts/ops-mcp-reauth.py" --bootstrap+```++A headed Chromium window opens. Sign into each OAuth provider (Google, GitHub, etc.) that your MCP servers use. Close the window when done. After this, `/ops:mcp reauth <server>` runs headlessly.++Run this bootstrap once per machine, or after clearing the browser profile.++## 4. Verify API-key servers++Servers in `API_KEY_MCPS` (currently `pocketai`) use a static Bearer key from macOS Keychain under service name `POCKET_API_KEY`, account `ops-daemon`. Confirm:++```bash+security find-generic-password -s POCKET_API_KEY -a ops-daemon -w+```++If the key is missing, add it:++```bash+security add-generic-password -s POCKET_API_KEY -a ops-daemon -w "<key>"+```++## 5. First health check++After registration:++```+/ops:mcp status+```++All configured HTTP servers should show `healthy` or `token_expired` (which the watchdog will auto-resolve on the next tick). If any show `needs_bootstrap`, run `/ops:mcp reauth <name>`.++## 6. Notifications++The watchdog sends WhatsApp notifications on new degradations via the pocket `supervisor-out-queue.jsonl`. This requires the pocket WhatsApp config at `$POCKET_STATE_DIR/whatsapp-config.json` to be configured. If you have not set up the pocket channel, macOS notifications via `osascript` still fire — no extra config needed.++To silence watchdog notifications:++```bash+export MCP_WATCHDOG_NOTIFY=0+```++Add to your shell profile to persist.