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
Port Hermes ops lessons into ops-inbox, ops-comms, and plugin rules (#813)
Aurora Capitale9c971b83b74
diff --git a/.gitignore b/.gitignoreindex 9ad9c290..e17026eb 100644--- a/.gitignore+++ b/.gitignore@@ -11,9 +11,21 @@ node_modules/.pii-denylist# Local, owner-specific prefs/overrides — never commit (see docs/LOCAL-PREFS.md)+# Preferences belong in the plugin data dir ($PREFS_PATH) or $HOME/.config,+# never in the repo. tests/test-no-secrets.sh fails the build if any of these+# become tracked, so adding a pattern here is not on its own sufficient.ops.local.json*.local.json.ops-prefs.json+ops-prefs.json+preferences.json+contact-registry.json+daemon-health.json+daemon-services.json+pii-denylist.txt+registry.json+!scripts/registry.example.json+!claude-ops/scripts/registry.example.json# Runtime message/session stores written by local bridges (WhatsApp whatsmeow,# etc). These hold real conversation content and pairing state and must neverdiff --git a/claude-ops/.claude-plugin/plugin.json b/claude-ops/.claude-plugin/plugin.jsonindex 0147398b..464f0f8b 100644--- a/claude-ops/.claude-plugin/plugin.json+++ b/claude-ops/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "ops","version": "3.3.1",- "description": "Business operations command center for Claude Code — 62 skills, 21 agents, and a smart background daemon that manage communications (WhatsApp/Email/Slack/Telegram), projects, infrastructure (all AWS services), revenue (Stripe + RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4/GSC), monitoring (Datadog/New Relic/OTEL), and voice (Bland AI/ElevenLabs/Whisper). Includes /ops:ops-ar A&R (audio analysis + demo verdict cards), /gtm go-to-market planner, /ops:projects portfolio dashboard, /ops:ops-mac macOS diagnose-and-fix (bundles the macos-toolkit CLI suite — security, launchd, network, disk, system health), YOLO mode for autonomous operation with 4 parallel C-suite agents, /ops:ops-home smart home control via Homey Pro, /ops:ops-unifi UniFi network control (Site Manager + Network + Protect APIs), and /ops:ops-feature-dev overlay for the feature-dev companion plugin.",+ "description": "Business operations command center for Claude Code — 63 skills, 21 agents, and a smart background daemon that manage communications (WhatsApp/Email/Slack/Telegram), projects, infrastructure (all AWS services), revenue (Stripe + RevenueCat), e-commerce (Shopify), marketing (Klaviyo/Meta/GA4/GSC), monitoring (Datadog/New Relic/OTEL), and voice (Bland AI/ElevenLabs/Whisper). Includes /ops:ops-ar A&R (audio analysis + demo verdict cards), /gtm go-to-market planner, /ops:projects portfolio dashboard, /ops:ops-mac macOS diagnose-and-fix (bundles the macos-toolkit CLI suite — security, launchd, network, disk, system health), YOLO mode for autonomous operation with 4 parallel C-suite agents, /ops:ops-home smart home control via Homey Pro, /ops:ops-unifi UniFi network control (Site Manager + Network + Protect APIs), and /ops:ops-feature-dev overlay for the feature-dev companion plugin.","author": {"name": "Lifecycle Innovations Limited","url": "https://github.com/Lifecycle-Innovations-Limited"diff --git a/claude-ops/CLAUDE.md b/claude-ops/CLAUDE.mdindex 1e922bbe..6f7b368a 100644--- a/claude-ops/CLAUDE.md+++ b/claude-ops/CLAUDE.md@@ -18,9 +18,24 @@ These rules apply to ALL skills in this plugin. They are non-negotiable and over- `$PREFS_PATH` (preferences.json in plugin data dir — never committed)- `scripts/registry.json` (gitignored)-- Environment variables or Doppler secrets+- `$HOME/.config/claude-ops/` for anything machine-scoped (e.g. the PII denylist)+- Environment variables or a secrets manager-Run `tests/test-no-secrets.sh` before every commit to verify.+**Never write preferences into the repo tree.** A skill or script that writes+`preferences.json`, `registry.json`, or any prefs-shaped file next to its own+source will commit the operator's identity on the next `git add -A`. Resolve the+path from `$PREFS_PATH` or `$HOME`, never from `$PLUGIN_ROOT`/`$REPO_ROOT`.++This is enforced, not merely documented. `tests/test-no-secrets.sh` fails the+build when a prefs-shaped file is tracked in the git index (`.gitignore` does not+help once a file is already tracked, and `git add -f` bypasses it), and when a+write target resolves into the repo tree. Run it before every commit.++**Enable the operator identity denylist.** The scanner cannot hardcode your own+names, brands, or hostnames — that list would itself be the leak. Put one term+per line in `$HOME/.config/claude-ops/pii-denylist.txt` (or `.pii-denylist`,+gitignored) and the scanner will fail the build if any of them reach the repo.+Until you configure it, that check passes while verifying nothing.## Deploy-fix fleet contract@@ -199,6 +214,69 @@ silently stops firing the moment an account is renamed or added, which turns anwithout any error. Match on a pattern such as `mcp__whatsapp[a-z-]*__send_(message|audio_message|file)`so every present and future account stays gated.+## Rule 9 — Exhaust before concluding++Most confident-but-wrong answers share one shape: stopping at the first plausible+result. Before writing any of these sentences, run the matching check. If you have+not run it, do not write the sentence.++- "X was never sent" / "there is no email about Y"+- "service X is down / dead / needs re-auth"+- "the contract says Z"+- "this happened on `<date>`" / "A came after B"+- "nobody replied" / "it stalled because…"+- "this needs you" / "that's a human blocker"++**"It doesn't exist."** Search every configured account, not the default one, and+page past the first screen. Vary the query at least three ways: by topic keyword,+by the counterparty's exact address (`to:`/`from:`), and by their domain alone+plus likely misspellings of the name. A negative from one account, one query, or+page one is not evidence of absence.++**"Service X is down."** Enumerate every instance before declaring anything dead:+all processes, all listening ports, all service labels, all data stores. Probe+each listener individually. A single failed probe on an assumed port is not an+outage, and the same service often runs more than once under different names.++**"The contract says Z."** Confirm you have the operative version by searching the+thread for later drafts and the counterparty's own copy, and check for a clause+that supersedes an earlier letter of intent. Map the full structure before+quoting, since schedules routinely hold more than one table. Quote verbatim with+the clause number; never paraphrase from memory.++**"This happened on `<date>`."** Mail search returns the *thread's* latest date,+not the individual message's. Never build a chronology from search output; open+the thread and read per-message dates.++**"Nobody replied / it stalled."** Read every message in the chain, both+directions, before assigning fault. A stall is usually a condition nobody+satisfied rather than neglect.++**"This needs you."** The capability usually already exists and is simply+undocumented. Before escalating: grep the codebase for an existing path including+sibling repos, check the secret store by name, check the password manager for+anything account-shaped, then live-probe it so you know rather than believe. Also+question the framing — ask whether the dependency should exist at all before+asking the user how to fund or fix it.++**A counterparty asked a question.** Answer it yourself. Search the mailboxes,+open every attachment, read the contracts, check the web. Escalate to the user+only when the answer exists solely in their head or needs their physical presence.+Relaying a question the user pays you to answer is the failure this rule exists to+prevent.++**Attachments are primary sources.** `.eml`, `.pdf`, `.docx`, and `.xlsx`+attachments regularly hold the actual answer. "See the attachment" is an+instruction to open it, not a pointer to summarise around. Nested `.eml` files+parse with Python's `email` module.++**User corrections are research instructions, never hedges to be reassured.**+"I think I sent that" means the search was too narrow, so sweep again. "I don't+think that's true" means stop and re-verify from the primary source. "Isn't there+a better way" is a design review, so go and check before answering. "Maybe it's+running on a different port" means enumerate rather than politely dismiss. A+user's half-memory of their own estate routinely beats a first-pass search.+## Appendix: CLI Reference (EXACT SYNTAX — never guess)### gog (v0.12.0+)diff --git a/claude-ops/README.md b/claude-ops/README.mdindex 2a303bad..2e8917be 100644--- a/claude-ops/README.md+++ b/claude-ops/README.md@@ -60,8 +60,6 @@ Per-repo budget caps (default 3/hour), single-flight locks, content-hash dedup,| ------------------- | --------------------------------------------------------------------------------- || `/ops` | Interactive command center dashboard (visual HQ) || `/ops:dash` | Same as `/ops` — pixel-art dashboard with hotkey navigation |-| `ops-healify-dash` | Dedicated Healify.ai KPI, growth, App Store, reliability, infra, repo, agent, MCP, and plugin command center |-| `ops-healify-bi-refresh` | Warms the Healify BI cache used by `ops-healify-dash` from EAS, ASC, AppsFlyer, Amplitude, Sentry, BetterStack, Linear, QA, and ops-dashboard sources || `/ops:setup` | Interactive setup wizard — installs CLIs, configures channels, builds registry || `/ops:go` | Morning briefing — all systems in one dashboard || `/ops:next` | Priority-ordered next action (fires > comms > PRs > sprint > GSD) |@@ -142,7 +140,7 @@ The background memory extractor now prefers the Claude Code OAuth token stored i### Full Plugin Feature Adoption-- All 62 skills: `effort`, `maxTurns`, `disallowedTools`, `model` annotations+- All 63 skills: `effort`, `maxTurns`, `disallowedTools`, `model` annotations- All 21 agents: `memory` (cross-session learning), `initialPrompt`, `isolation`- PreToolUse hooks for WhatsApp health checks and MCP auto-reconnect- Runtime Context loading in every skill (preferences, daemon health, memories, secrets)diff --git a/claude-ops/agents/memory-extractor.md b/claude-ops/agents/memory-extractor.mdindex 90372abd..2c8d02bf 100644--- a/claude-ops/agents/memory-extractor.md+++ b/claude-ops/agents/memory-extractor.md@@ -44,7 +44,7 @@ Example usage in a skill:MEMORIES="${HOME}/.claude/plugins/data/ops-ops-marketplace/memories"# Load contact profile-CONTACT_FILE=$(ls "${MEMORIES}/contact_"*deeksha* 2>/dev/null | head -1)+CONTACT_FILE=$(ls "${MEMORIES}/contact_"*jane-doe* 2>/dev/null | head -1)[[ -f "${CONTACT_FILE}" ]] && cat "${CONTACT_FILE}"# Load user preferencesdiff --git a/claude-ops/bin/ops-dash b/claude-ops/bin/ops-dashindex 91a3bb88..4d378d10 100755--- a/claude-ops/bin/ops-dash+++ b/claude-ops/bin/ops-dash@@ -11,10 +11,6 @@ PLUGIN_ROOT="$(cd "$(dirname "$0")/.." && pwd)". "${PLUGIN_ROOT}/lib/registry-resolve.sh"PREFS="${OPS_DATA_DIR}/preferences.json"-if [[ "${OPS_HEALIFY_DASH:-0}" == "1" && -x "${PLUGIN_ROOT}/bin/ops-healify-dash" ]]; then- exec "${PLUGIN_ROOT}/bin/ops-healify-dash" "$@"-fi-# ── Mobile / SSH detection (Rule 7) ─────────────────────────────────────────MOBILE_MODE=0if [[ -n "${SSH_CONNECTION:-}${SSH_CLIENT:-}${SSH_TTY:-}" || "${OPS_MOBILE:-}" == "1" ]]; thendiff --git a/claude-ops/bin/ops-healify-bi-refresh b/claude-ops/bin/ops-healify-bi-refreshdeleted file mode 100755index 83d60e7e..00000000--- a/claude-ops/bin/ops-healify-bi-refresh+++ /dev/null@@ -1,150 +0,0 @@-#!/usr/bin/env bash-set -uo pipefail--CACHE_DIR="${HEALIFY_BI_CACHE_DIR:-$HOME/.cache/agent-hub}"-OUT="$CACHE_DIR/healify-bi.json"-TMP="$OUT.tmp"-HEALIFY_APP="${HEALIFY_APP_ROOT:-$HOME/Projects/healify-workspace/healify}"-OPDASH="${HEALIFY_OPDASH_ROOT:-$HOME/Projects/healify-workspace/healify-operating-dashboard}"--mkdir -p "$CACHE_DIR"--eas_json='{"ok":false,"note":"EAS CLI unavailable or not authenticated","builds":[]}'-if command -v eas >/dev/null 2>&1 && [[ -d "$HEALIFY_APP" ]]; then- eas_raw="$(cd "$HEALIFY_APP" && timeout 60 eas build:list --platform ios --limit 8 --json --non-interactive 2>/tmp/healify-eas.err || true)"- if printf '%s' "$eas_raw" | jq -e 'type=="array"' >/dev/null 2>&1; then- eas_json="$(printf '%s' "$eas_raw" | jq -c '{ok:true, builds:[.[] | {id,status,platform,profile,appVersion,appBuildVersion,createdAt,updatedAt,distribution}] }')"- else- eas_err="$(sed -n '1,4p' /tmp/healify-eas.err 2>/dev/null | tr '\n' ' ' | sed 's/"/'\''/g')"- eas_json="$(jq -nc --arg note "${eas_err:-EAS build list returned no JSON}" '{ok:false,note:$note,builds:[]}')"- fi-fi--sentry_json='{"ok":false,"note":"sentry-cli unavailable","projects":[]}'-SENTRY_ORG="${SENTRY_ORG:-}"-SENTRY_PROJECTS="${SENTRY_PROJECTS:-}"-if command -v sentry-cli >/dev/null 2>&1 && [[ -n "$SENTRY_ORG" && -n "$SENTRY_PROJECTS" ]]; then- sentry_json="$(- IFS=',' read -ra projects <<< "$SENTRY_PROJECTS"- for project in "${projects[@]}"; do- project="${project//[[:space:]]/}"- [[ -n "$project" ]] || continue- out="$(timeout 25 sentry-cli issues list --org "$SENTRY_ORG" --project "$project" --query 'is:unresolved' 2>&1 || true)"- if printf '%s' "$out" | grep -qi 'No issues found'; then- jq -nc --arg project "$project" '{project:$project,ok:true,unresolved:0,highPriority:0,note:"No unresolved issues"}'- elif printf '%s' "$out" | grep -Eqi '^error:|unauthorized|forbidden|not found'; then- note="$(printf '%s' "$out" | sed -n '1,2p' | tr '\n' ' ' | sed 's/"/'\''/g')"- jq -nc --arg project "$project" --arg note "$note" '{project:$project,ok:false,unresolved:null,highPriority:null,note:$note}'- else- rows="$(printf '%s\n' "$out" | sed '/^$/d' | grep -Ev '^(Issue|ID|\\-)' | wc -l | awk '{print $1}')"- jq -nc --arg project "$project" --argjson rows "${rows:-0}" '{project:$project,ok:true,unresolved:$rows,highPriority:null,note:"issues listed by sentry-cli"}'- fi- done | jq -sc '{ok:true,projects:.}'- )"-elif command -v sentry-cli >/dev/null 2>&1; then- sentry_json='{"ok":false,"note":"SENTRY_ORG and SENTRY_PROJECTS env vars required","projects":[]}'-fi--opdash_json='{"ok":false,"note":"operating dashboard source probe unavailable"}'-if [[ -d "$OPDASH" ]] && command -v npx >/dev/null 2>&1; then- opdash_raw="$(- cd "$OPDASH" && timeout 120 npx tsx -e '- import { fetchAppStoreConnect } from "./server/sources/appstore";- import { fetchAmplitude } from "./server/sources/amplitude";- import { fetchOpsIntegrations } from "./server/sources/ops-integrations";- async function main() {- const out = { ok: true, generatedAt: new Date().toISOString(), appstore: await fetchAppStoreConnect(), amplitude: await fetchAmplitude(), ops: await fetchOpsIntegrations() };- console.log(JSON.stringify(out));- }- main().catch((e) => {- console.log(JSON.stringify({ ok: false, note: String(e?.message || e).slice(0, 400) }));- });- ' 2>/tmp/healify-opdash.err || true- )"- if printf '%s' "$opdash_raw" | jq -e 'type=="object"' >/dev/null 2>&1; then- opdash_json="$opdash_raw"- else- opdash_err="$(sed -n '1,4p' /tmp/healify-opdash.err 2>/dev/null | tr '\n' ' ' | sed 's/"/'\''/g')"- opdash_json="$(jq -nc --arg note "${opdash_err:-operating dashboard source probe returned no JSON}" '{ok:false,note:$note}')"- fi-fi--asc_extra_json="$(-python3 - <<'PY'-import json, os, sys, time, urllib.parse, urllib.request, urllib.error, ssl-from datetime import datetime, timezone--try:- import jwt-except Exception as exc:- print(json.dumps({"ok": False, "note": f"PyJWT unavailable: {exc}", "apps": []}))- sys.exit(0)--APP_IDS = [a.strip() for a in os.environ.get("APP_STORE_CONNECT_APP_IDS", "").split(",") if a.strip()]-KEY_ID = os.environ.get("APP_STORE_CONNECT_API_KEY_ID") or os.environ.get("APP_STORE_CONNECT_KEY_ID") or ""-ISSUER_ID = os.environ.get("APP_STORE_CONNECT_ISSUER_ID") or ""-if not APP_IDS or not KEY_ID or not ISSUER_ID:- print(json.dumps({"ok": False, "note": "Set APP_STORE_CONNECT_APP_IDS, APP_STORE_CONNECT_API_KEY_ID, and APP_STORE_CONNECT_ISSUER_ID env vars", "apps": []}))- sys.exit(0)-KEY_PATH = os.environ.get("APP_STORE_CONNECT_API_KEY_PATH") or os.path.expanduser(f"~/.fastlane/app_store_connect/AuthKey_{KEY_ID}.p8")--def token():- if not os.path.exists(KEY_PATH):- raise FileNotFoundError("ASC key file missing")- with open(KEY_PATH) as f:- private_key = f.read()- now = int(time.time())- return jwt.encode({"iss": ISSUER_ID, "iat": now, "exp": now + 900, "aud": "appstoreconnect-v1"}, private_key, algorithm="ES256", headers={"kid": KEY_ID})--def get(path, tok):- req = urllib.request.Request("https://api.appstoreconnect.apple.com" + path, headers={"Authorization": f"Bearer {tok}", "Content-Type": "application/json"})- with urllib.request.urlopen(req, timeout=25, context=ssl.create_default_context()) as resp:- return json.loads(resp.read())--def app_payload(app_id, tok):- out = {"appId": app_id}- try:- qs = urllib.parse.urlencode({"filter[app]": app_id, "sort": "-uploadedDate", "limit": "8", "fields[builds]": "version,uploadedDate,processingState,expired,usesNonExemptEncryption"})- data = get("/v1/builds?" + qs, tok)- out["builds"] = [{"id": b.get("id"), **(b.get("attributes") or {})} for b in data.get("data", [])]- except Exception as exc:- out["buildError"] = str(exc)[:220]- try:- qs = urllib.parse.urlencode({"sort": "-createdDate", "limit": "50", "fields[customerReviews]": "rating,title,body,createdDate,territory"})- data = get(f"/v1/apps/{app_id}/customerReviews?" + qs, tok)- reviews = [{"id": r.get("id"), **(r.get("attributes") or {})} for r in data.get("data", [])]- ratings = [r.get("rating") for r in reviews if isinstance(r.get("rating"), int)]- out["reviews"] = {"count": len(reviews), "avgRating": round(sum(ratings) / len(ratings), 2) if ratings else None, "lowStars": len([r for r in ratings if r <= 3]), "latest": reviews[:5]}- except Exception as exc:- out["reviewError"] = str(exc)[:220]- return out--try:- tok = token()- print(json.dumps({"ok": True, "generatedAt": datetime.now(timezone.utc).isoformat(), "apps": [app_payload(a, tok) for a in APP_IDS]}))-except Exception as exc:- print(json.dumps({"ok": False, "note": str(exc)[:220], "apps": []}))-PY-)"--isjson() { printf '%s' "$1" | jq empty >/dev/null 2>&1; }-isjson "$eas_json" || eas_json='{"ok":false,"note":"invalid EAS JSON","builds":[]}'-isjson "$sentry_json" || sentry_json='{"ok":false,"note":"invalid Sentry JSON","projects":[]}'-isjson "$opdash_json" || opdash_json='{"ok":false,"note":"invalid opdash JSON"}'-isjson "$asc_extra_json" || asc_extra_json='{"ok":false,"note":"invalid ASC JSON","apps":[]}'---if jq -nc \- --arg generatedAt "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" \- --argjson eas "$eas_json" \- --argjson sentry "$sentry_json" \- --argjson opdash "$opdash_json" \- --argjson ascExtra "$asc_extra_json" \- '{generatedAt:$generatedAt,eas:$eas,sentry:$sentry,opdash:$opdash,ascExtra:$ascExtra}' >"$TMP"; then- mv "$TMP" "$OUT"- printf '%s\n' "$OUT"-else- rm -f "$TMP"- printf 'healify-bi refresh: merge failed; keeping existing cache at %s\n' "$OUT" >&2- exit 1-fidiff --git a/claude-ops/bin/ops-healify-dash b/claude-ops/bin/ops-healify-dashdeleted file mode 100755index 1cbfe0eb..00000000--- a/claude-ops/bin/ops-healify-dash+++ /dev/null@@ -1,647 +0,0 @@-#!/usr/bin/env bash-set -uo pipefail--MODE="${1:---once}"-SESSION="${AGENT_HUB_TMUX_SESSION:-agent-hub}"-OPS_DATA="${OPS_DATA_DIR:-${CLAUDE_PLUGIN_DATA_DIR:-$HOME/.claude/plugins/data/ops-ops-marketplace}}"-OPS_PROJECTS="$OPS_DATA/cache/projects_health.json"-KPI_CACHE="$HOME/.claude/state/statusline-kpi.json"-MARKETING_CACHE="$OPS_DATA/cache/marketing.json"-ECOM_CACHE="$OPS_DATA/cache/ecom.json"-INFRA_CACHE="$HOME/.cache/agent-hub/infra-health.json"-AWS_CACHE="$HOME/.cache/agent-hub/aws-ecs-health.json"-PLUGIN_CACHE="$HOME/.cache/agent-hub/plugin-inventory.json"-BI_CACHE="$HOME/.cache/agent-hub/healify-bi.json"-RUNTIME_CACHE="$HOME/.cache/agent-hub/fleet/runtime-health.txt"-FLEET_STATUS="$HOME/.claude/state/fleet-status.json"-FLEET_TUI="$HOME/.claude/state/fleet-tui.json"-HEALIFY_ROOT="${HEALIFY_ROOT:-$HOME/Projects/healify-workspace}"-ASC_PROD_APP_ID="${HEALIFY_ASC_PROD_APP_ID:-}"-ASC_STAGING_APP_ID="${HEALIFY_ASC_STAGING_APP_ID:-}"-SENTRY_MOBILE_PROJECT="${HEALIFY_SENTRY_MOBILE_PROJECT:-}"-MAX_ROWS="${HEALIFY_DASH_ROWS:-18}"-INTERVAL="${HEALIFY_DASH_INTERVAL:-15}"-REFRESH="${HEALIFY_DASH_REFRESH:-0}"-SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"--if [[ "$MODE" == "--refresh" ]]; then- REFRESH=1- MODE="--once"-fi--if [[ -t 1 ]]; then- BOLD=$'\033[1m'- DIM=$'\033[2m'- RESET=$'\033[0m'- ORANGE=$'\033[38;5;208m'- AMBER=$'\033[38;5;214m'- PEACH=$'\033[38;5;216m'- GREEN=$'\033[38;5;114m'- RED=$'\033[38;5;203m'- YELLOW=$'\033[38;5;220m'- BLUE=$'\033[38;5;75m'- BORDER=$'\033[38;5;238m'- TEXT=$'\033[38;5;252m'-else- BOLD= DIM= RESET= ORANGE= AMBER= PEACH= GREEN= RED= YELLOW= BLUE= BORDER= TEXT=-fi--usage() {- cat <<'EOF'-healify-dashboard [--once|--watch|--refresh|--json]--Dedicated Healify.ai command center. Read-only by default.-Sources: ops:projects, statusline KPI cache, live health endpoints, AWS ECS,-agent runtime health, Claude/OpenClaw/Codex/Cursor readiness, plugin inventory,-and local Healify git repos.-EOF-}--cols() {- local c- c="$(tput cols 2>/dev/null || echo 100)"- [[ "$c" =~ ^[0-9]+$ ]] || c=100- ((c < 72)) && c=72- ((c > 180)) && c=180- echo "$c"-}--raw_cols() {- local c- c="$(tput cols 2>/dev/null || echo 100)"- [[ "$c" =~ ^[0-9]+$ ]] || c=100- echo "$c"-}--raw_lines() {- local l- l="$(tput lines 2>/dev/null || echo 40)"- [[ "$l" =~ ^[0-9]+$ ]] || l=40- echo "$l"-}--clip_width() {- awk -v n="${1:-$(cols)}" '{ gsub(/[[:cntrl:]]/, " "); if (length($0) > n) print substr($0, 1, n-1) "..."; else print }'-}--safe_jq() {- local file="$1" fallback="$2" filter="${3:-.}"- if [[ -s "$file" ]] && command -v jq >/dev/null 2>&1; then- jq -c "$filter" "$file" 2>/dev/null || printf '%s\n' "$fallback"- elif command -v jq >/dev/null 2>&1; then- printf '%s\n' "$fallback" | jq -c "$filter" 2>/dev/null || printf '%s\n' "$fallback"- else- printf '%s\n' "$fallback"- fi-}--jq_file() {- local file="$1" fallback="$2"- shift 2- if [[ -s "$file" ]] && command -v jq >/dev/null 2>&1; then- jq "$@" "$file" 2>/dev/null || printf '%s\n' "$fallback"- elif command -v jq >/dev/null 2>&1; then- printf '%s\n' "$fallback" | jq "$@" 2>/dev/null || printf '%s\n' "$fallback"- else- printf '%s\n' "$fallback"- fi-}--mtime() {- stat -c %Y "$1" 2>/dev/null || stat -f %m "$1" 2>/dev/null || echo 0-}--age() {- local f="$1" now mt d- [[ -s "$f" ]] || { printf 'missing'; return; }- now="$(date +%s)"- mt="$(mtime "$f")"- [[ "$mt" =~ ^[0-9]+$ ]] || { printf 'unknown'; return; }- d=$((now - mt))- if ((d < 120)); then printf '%ss' "$d"- elif ((d < 7200)); then printf '%sm' "$((d / 60))"- elif ((d < 172800)); then printf '%sh' "$((d / 3600))"- else printf '%sd' "$((d / 86400))"; fi-}--rule() {- printf '%s' "$BORDER"- printf '%*s\n' "$(cols)" '' | tr ' ' '-'- printf '%s' "$RESET"-}--section() {- printf '\n%s%s%s%s\n' "$BOLD" "$ORANGE" "$1" "$RESET"- rule-}--tone() {- case "${1,,}" in- ok|ready|connected|configured|healthy|active|passing|running|success) printf '%s%s%s' "$GREEN" "$1" "$RESET" ;;- warn|warning|paused|degraded|auth|auth-needed|stale|waiting) printf '%s%s%s' "$YELLOW" "$1" "$RESET" ;;- down|failed|error|blocked|critical|missing|unauthorized) printf '%s%s%s' "$RED" "$1" "$RESET" ;;- *) printf '%s%s%s' "$BLUE" "$1" "$RESET" ;;- esac-}--pretty_table() {- column -t -s '|' 2>/dev/null | clip_width "$(cols)"-}--spinner() {- [[ -t 1 ]] || return 0- local msg="$1" pid="$2" frames=("◒" "◐" "◓" "◑") i=0- while kill -0 "$pid" 2>/dev/null; do- printf '\r%s%s %s%s' "$ORANGE" "${frames[$((i % 4))]}" "$msg" "$RESET" >&2- i=$((i + 1))- sleep 0.12- done- printf '\r%*s\r' 80 '' >&2-}--refresh_caches() {- if [[ -x "$HOME/.local/bin/agent-mcp-sync" ]]; then- timeout 20 "$HOME/.local/bin/agent-mcp-sync" >/dev/null 2>&1 || true- fi- if [[ -x "$HOME/.local/bin/agent-project-health" ]]; then- timeout 55 "$HOME/.local/bin/agent-project-health" --refresh-infra >/dev/null 2>&1 || true- fi- if [[ -x "$HOME/.local/bin/agent-plugin-insights" ]]; then- timeout 20 "$HOME/.local/bin/agent-plugin-insights" --refresh >/dev/null 2>&1 || true- fi- if [[ -x "$HOME/.local/bin/agent-hub-health" ]]; then- timeout 40 "$HOME/.local/bin/agent-hub-health" short >"$RUNTIME_CACHE" 2>/dev/null || true- fi- local bi_refresh="${HEALIFY_BI_REFRESH_CMD:-}"- if [[ -z "$bi_refresh" && -x "$SCRIPT_DIR/ops-healify-bi-refresh" ]]; then- bi_refresh="$SCRIPT_DIR/ops-healify-bi-refresh"- elif [[ -z "$bi_refresh" && -x "$HOME/.local/bin/healify-bi-refresh" ]]; then- bi_refresh="$HOME/.local/bin/healify-bi-refresh"- fi- if [[ -n "$bi_refresh" ]]; then- timeout 180 "$bi_refresh" >/dev/null 2>&1 || true- fi-}--repo_rows() {- local roots=(- "$HEALIFY_ROOT/healify"- "$HEALIFY_ROOT/healify-api"- "$HEALIFY_ROOT/healify-agentcore"- "$HEALIFY_ROOT/healify-api-mcp"- "$HEALIFY_ROOT/healify-web"- "$HEALIFY_ROOT/healify-operating-dashboard"- "$HEALIFY_ROOT/repos/meditation-service"- "$HOME/Projects/meditation-service"- )- local seen="" root name branch dirty ahead behind last- printf 'REPO|BRANCH|DIRTY|AHEAD/BEHIND|LAST COMMIT\n'- for root in "${roots[@]}"; do- [[ -d "$root/.git" ]] || continue- name="$(basename "$root")"- [[ "$seen" == *"|$name|"* ]] && continue- seen="${seen}|$name|"- branch="$(git -C "$root" branch --show-current 2>/dev/null || echo '-')"- dirty="$(git -C "$root" status --porcelain 2>/dev/null | wc -l | awk '{print $1}')"- ahead="$(git -C "$root" rev-list --count '@{u}..HEAD' 2>/dev/null || echo 0)"- behind="$(git -C "$root" rev-list --count 'HEAD..@{u}' 2>/dev/null || echo 0)"- last="$(git -C "$root" log -1 --format='%cr %s' 2>/dev/null || echo '-')"- printf '%s|%s|%s|%s/%s|%s\n' "$name" "${branch:--}" "$dirty" "$ahead" "$behind" "$last"- done-}--json_summary() {- local projects kpi infra aws plugins runtime- projects="$(safe_jq "$OPS_PROJECTS" '{"projects":[],"summary":{}}')"- kpi="$(safe_jq "$KPI_CACHE" '{"projects":[]}')"- infra="$(safe_jq "$INFRA_CACHE" '{"endpoints":[]}')"- aws="$(safe_jq "$AWS_CACHE" '{"services":[]}')"- plugins="$(safe_jq "$PLUGIN_CACHE" '{"claude_plugins":[],"codex_skills":[],"ops_kpi_caches":[]}')"- runtime="$(sed -n '1,40p' "$RUNTIME_CACHE" 2>/dev/null | jq -Rs '.')"- jq -nc \- --argjson projects "$projects" \- --argjson kpi "$kpi" \- --argjson infra "$infra" \- --argjson aws "$aws" \- --argjson plugins "$plugins" \- --argjson runtime "$runtime" \- '{projects:$projects,kpi:$kpi,infra:$infra,aws:$aws,plugins:$plugins,runtime:$runtime}'-}--pixel_logo() {- local o p w r- if [[ -t 1 ]]; then- o=$'\033[48;5;208m \033[0m'- p=$'\033[48;5;204m \033[0m'- w=$'\033[48;5;231m \033[0m'- r=$'\033[48;5;209m \033[0m'- else- o='OO'; p='PP'; w='WW'; r='RR'- fi- printf ' %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n' "$o" "$o" "$o" "$o" "$o" "$o" "$o" "$o" "$o" "$o" "$o" "$o" "$o" "$o" "$o" "$o"- printf ' %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n' "$o" "$o" "$o" "$o" "$o" "$o" "$o" "$o" "$o" "$o" "$o" "$o" "$o" "$o" "$o" "$o"- printf ' %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n' "$o" "$o" "$w" "$w" "$o" "$o" "$o" "$o" "$o" "$w" "$w" "$o" "$o" "$o" "$o" "$o"- printf ' %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n' "$o" "$w" "$w" "$w" "$w" "$o" "$o" "$o" "$w" "$w" "$w" "$w" "$o" "$o" "$o" "$o"- printf ' %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n' "$o" "$w" "$w" "$w" "$w" "$w" "$o" "$w" "$w" "$w" "$w" "$w" "$o" "$o" "$o" "$o"- printf ' %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n' "$p" "$w" "$w" "$w" "$w" "$w" "$w" "$w" "$w" "$w" "$w" "$w" "$w" "$o" "$o" "$o"- printf ' %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n' "$p" "$p" "$w" "$w" "$w" "$w" "$w" "$r" "$r" "$w" "$w" "$w" "$w" "$o" "$o" "$o"- printf ' %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n' "$p" "$p" "$p" "$w" "$w" "$w" "$r" "$r" "$r" "$r" "$w" "$w" "$o" "$o" "$o" "$o"- printf ' %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n' "$p" "$p" "$p" "$p" "$w" "$r" "$r" "$r" "$r" "$r" "$r" "$o" "$o" "$o" "$o" "$o"- printf ' %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n' "$p" "$p" "$p" "$p" "$p" "$w" "$r" "$r" "$r" "$r" "$o" "$o" "$o" "$o" "$o" "$o"- printf ' %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n' "$p" "$p" "$p" "$p" "$p" "$p" "$w" "$r" "$r" "$o" "$o" "$o" "$o" "$o" "$o" "$o"- printf ' %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n' "$p" "$p" "$p" "$p" "$p" "$p" "$p" "$w" "$o" "$o" "$o" "$o" "$o" "$o" "$o" "$o"- printf ' %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n' "$p" "$p" "$p" "$p" "$p" "$p" "$p" "$p" "$o" "$o" "$o" "$o" "$o" "$o" "$o" "$o"- printf ' %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n' "$p" "$p" "$p" "$p" "$p" "$p" "$p" "$p" "$p" "$o" "$o" "$o" "$o" "$o" "$o" "$o"- printf ' %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n' "$p" "$p" "$p" "$p" "$p" "$p" "$p" "$p" "$p" "$p" "$o" "$o" "$o" "$o" "$o" "$o"- printf ' %s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n' "$p" "$p" "$p" "$p" "$p" "$p" "$p" "$p" "$p" "$p" "$p" "$o" "$o" "$o" "$o" "$o"-}--hero() {- local now host load mem disk- now="$(date -u '+%Y-%m-%d %H:%M:%SZ')"- host="$(hostname -s 2>/dev/null || hostname)"- load="$(awk '{print $1","$2","$3}' /proc/loadavg 2>/dev/null || echo '-')"- mem="$(free -h 2>/dev/null | awk '/Mem:/ {print $3 "/" $2 " used"}' || echo '-')"- disk="$(df -h / 2>/dev/null | awk 'NR==2 {print $5 " used / " $4 " free"}' || echo '-')"- pixel_logo- printf '%s%sHEALIFY.AI COMMAND CENTER%s %sread-only / orange dark mode%s\n' "$BOLD" "$AMBER" "$RESET" "$DIM" "$RESET"- printf '%s%s%s host=%s load=%s ram=%s disk=%s\n' "$TEXT" "$now" "$RESET" "$host" "$load" "$mem" "$disk"- rule-}--cards() {- local infra aws projects blockers plugins skills kpis agents_down- infra="$(safe_jq "$INFRA_CACHE" '{"endpoints":[]}' '[.endpoints[]? | select((.project|ascii_downcase|test("healify|meditation")) and .status=="ok")] | length')"- aws="$(safe_jq "$AWS_CACHE" '{"services":[]}' '[.services[]? | select((.project|ascii_downcase|test("healify|meditation")) and .status=="ok")] | length')"- projects="$(safe_jq "$OPS_PROJECTS" '{"projects":[]}' '[.projects[]? | select(.name|ascii_downcase|test("healify|meditation"))] | length')"- blockers="$(safe_jq "$OPS_PROJECTS" '{"projects":[]}' '[.projects[]? | select((.name|ascii_downcase|test("healify|meditation")) and ((.blockers // "0"|tostring) != "0"))] | length')"- plugins="$(safe_jq "$PLUGIN_CACHE" '{"claude_plugins":[]}' '.claude_plugins | length')"- skills="$(safe_jq "$PLUGIN_CACHE" '{"codex_skills":[]}' '.codex_skills | length')"- kpis="$(safe_jq "$PLUGIN_CACHE" '{"ops_kpi_caches":[]}' '.ops_kpi_caches | length')"- agents_down="$(grep -Eci 'auth-needed|failed|missing|unauthorized|\berror\b' "$RUNTIME_CACHE" 2>/dev/null || true)"- agents_down="${agents_down:-0}"- {- printf 'METRIC|VALUE|SOURCE|AGE\n'- printf 'Healify endpoints OK|%s|infra health|%s\n' "$infra" "$(age "$INFRA_CACHE")"- printf 'Healify ECS OK|%s|AWS ECS|%s\n' "$aws" "$(age "$AWS_CACHE")"- printf 'Healify projects|%s|ops:projects|%s\n' "$projects" "$(age "$OPS_PROJECTS")"- printf 'Project blockers|%s|gsd/ops registry|%s\n' "$blockers" "$(age "$OPS_PROJECTS")"- printf 'Claude plugins|%s|plugin inventory|%s\n' "$plugins" "$(age "$PLUGIN_CACHE")"- printf 'Codex skills|%s|plugin inventory|%s\n' "$skills" "$(age "$PLUGIN_CACHE")"- printf 'KPI caches|%s|ops daemon|%s\n' "$kpis" "$(age "$PLUGIN_CACHE")"- printf 'Agent warnings|%s|runtime health|%s\n' "$agents_down" "$(age "$RUNTIME_CACHE")"- } | pretty_table-}--business_kpis() {- jq_file "$KPI_CACHE" '{"projects":[]}' -r '- def fmt:- if . == null then "-"- elif type=="number" then- if . >= 1000000 then ((./1000000*10|round/10|tostring)+"M")- elif . >= 1000 then ((./1000*10|round/10|tostring)+"K")- else (.|tostring) end- else tostring end;- "KPI|VALUE|STATUS|DETAIL",- ((.projects // []) | map(select((.key // .label // "" | ascii_downcase) == "healify")) | .[0] // {}) as $h |- [- "Instagram followers|" + (($h.social.ig_followers // null)|fmt) + "|" + (($h.social.verdict // "-")|tostring) + "|Healify audience",- "Instagram reach|" + (($h.social.ig_reach // null)|fmt) + "|" + (($h.social.verdict // "-")|tostring) + "|Recent reach cache",- "Save rate|" + (($h.social.save_rate // null)|fmt) + "|" + (($h.social.verdict // "-")|tostring) + "|Content quality signal",- "Active requests|" + (($h.social.active_req // null)|fmt) + "|" + (($h.dev.phase // "-")|tostring) + "|Demand / backlog",- "Ads health|" + (($h.ads.health // "-")|tostring) + "|" + (($h.ads.health // "-")|tostring) + "|Marketing spend efficiency",- "Dev phase|" + (($h.dev.phase // "-")|tostring) + "|" + (($h.dev.phase // "-")|tostring) + "|Execution state"- ][]' | pretty_table-}--marketing_table() {- {- printf 'METRIC|VALUE|STATUS|SOURCE\n'- jq_file "$MARKETING_CACHE" '{}' -r '- def s: if . == null then "-" else tostring end;- "GA4 users|" + (.ga4.users|s) + "|" + (.health_status // "-") + "|ops marketing cache",- "GA4 sessions|" + (.ga4.sessions|s) + "|" + (.health_status // "-") + "|ops marketing cache",- "GA4 conversions|" + (.ga4.conversions|s) + "|" + (.health_status // "-") + "|ops marketing cache",- "GSC clicks|" + (.gsc.clicks|s) + "|" + (.health_status // "-") + "|ops marketing cache",- "Meta spend|" + (.meta.spend|s) + "|" + (.health_status // "-") + "|ops marketing cache",- "Meta ROAS|" + (.meta.roas|s) + "|" + (.health_status // "-") + "|ops marketing cache",- "Blended ROAS|" + (.blended_roas|s) + "|" + (.health_status // "-") + "|ops marketing cache"'- jq_file "$ECOM_CACHE" '{}' -r '- def s: if . == null then "-" else tostring end;- "Orders today|" + (.orders_today|s) + "|cached|ecom cache",- "Revenue today|" + ((.currency // "") + " " + (.revenue_today|s)) + "|cached|ecom cache"'- jq_file "$BI_CACHE" '{}' -r '- def card($id): (.opdash.ops.cards // [] | map(select(.id==$id)) | .[0] // {});- def s: if . == null then "-" else tostring end;- (card("appsflyer")) as $af |- (card("appsflyer").metrics // {}) as $m |- "App installs 7d|" + ($m.installs|s) + "|" + ($af.status // "-") + "|AppsFlyer",- "Organic installs|" + ($m.organic|s) + "|" + ($af.status // "-") + "|AppsFlyer",- "Loyal users|" + ($m.loyalUsers|s) + "|" + ($af.status // "-") + "|AppsFlyer",- "UA cost|" + ($m.cost|s) + "|" + ($af.status // "-") + "|AppsFlyer",- (.opdash.amplitude // {}) as $amp |- ($amp.current // {}) as $cur |- "Amplitude active|" + ($cur.activeUsers|s) + "|" + (if ($amp.ok // false) then "ok" else "blocked" end) + "|Amplitude project " + ($amp.projectId // "-"),- "Amplitude new|" + ($cur.newUsers|s) + "|" + (if ($amp.ok // false) then "ok" else "blocked" end) + "|Amplitude project " + ($amp.projectId // "-")'- } | pretty_table-}--release_table() {- {- printf 'SURFACE|LATEST|STATE|DETAIL\n'- jq_file "$BI_CACHE" '{}' --arg prod "$ASC_PROD_APP_ID" --arg staging "$ASC_STAGING_APP_ID" -r '- def s: if . == null then "-" else tostring end;- (.eas.builds[0] // {}) as $e |- "EAS iOS|" + (($e.appVersion|s) + " (" + ($e.appBuildVersion|s) + ")") + "|" + ($e.status|s) + "|" + (($e.distribution|s) + " · " + ($e.updatedAt|s)),- (.ascExtra.apps[]? | select(.appId==$prod) | .builds[0] // {}) as $p |- "ASC prod build|" + ($p.version|s) + "|" + ($p.processingState|s) + "|" + ("expired=" + ($p.expired|s) + " · " + ($p.uploadedDate|s)),- (.ascExtra.apps[]? | select(.appId==$staging) | .builds[0] // {}) as $st |- "ASC staging build|" + ($st.version|s) + "|" + ($st.processingState|s) + "|" + ("expired=" + ($st.expired|s) + " · " + ($st.uploadedDate|s)),- (.opdash.appstore.appDetails[]? | select(.appId==$prod) | .appStoreVersions[0] // {}) as $v |- "App Store version|" + ($v.versionString|s) + "|" + ($v.appStoreState|s) + "|production app",- (.opdash.appstore.appDetails[]? | select(.appId==$staging) | .appStoreVersions[0] // {}) as $sv |- "Beta store version|" + ($sv.versionString|s) + "|" + ($sv.appStoreState|s) + "|staging app",- (.ascExtra.apps[]? | select(.appId==$prod) | .reviews // {}) as $r |- "Reviews prod|" + (($r.avgRating|s) + " avg / " + ($r.count|s) + " reviews") + "|" + (($r.lowStars|s) + " low") + "|ASC customerReviews",- (.opdash.appstore.metrics // {}) as $m |- "App downloads|" + ($m.downloads|s) + "|" + (if $m.downloads == null then "blocked" else "ok" end) + "|ASC sales vendor number required"'- } | pretty_table-}--reliability_table() {- {- printf 'SOURCE|STATUS|METRIC|DETAIL\n'- jq_file "$BI_CACHE" '{}' -r '- def s: if . == null then "-" else tostring end;- (.sentry.projects[]? | "Sentry " + .project + "|" + (if .ok then "ok" else "warn" end) + "|" + (.unresolved|s) + " unresolved|" + (.note // "-")),- ((.opdash.ops.cards // [])[]? | select(.id=="betterstack") | "BetterStack|" + (.status // "-") + "|" + ((.metrics.up|s) + "/" + (.metrics.monitors|s) + " up") + "|" + ((.metrics.activeIncidents|s) + " active incidents")),- ((.opdash.ops.cards // [])[]? | select(.id=="linear") | "Linear|" + (.status // "-") + "|" + ((.metrics.p1|s) + " P1 / " + (.metrics.p2|s) + " P2") + "|" + ((.metrics.blockers|s) + " priority issues")),- ((.opdash.ops.cards // [])[]? | select(.id=="qa") | "Mobile QA|" + (.status // "-") + "|" + ((.metrics.live|s) + "/" + (.metrics.services|s) + " live") + "|" + (.note // "-")),- ((.opdash.ops.cards // [])[]? | select(.id=="api") | "API / AgentCore|" + (.status // "-") + "|" + ((.metrics.healthy|s) + "/" + (.metrics.endpoints|s) + " healthy") + "|operating-dashboard source")'- } | pretty_table-}--projects_table() {- jq_file "$OPS_PROJECTS" '{"projects":[]}' --argjson max "$MAX_ROWS" -r '- def clip($n): tostring | gsub("[\r\n\t]+";" ") | if length>$n then .[0:$n-1]+"..." else . end;- "PROJECT|STATUS|BLOCKERS|PHASE|NEXT ACTION",- ((.projects // [])- | map(select(.name|ascii_downcase|test("healify|meditation")))- | sort_by((.blockers // "0"|tonumber? // 0) * -1, .name)- | .[:$max]- | .[]- | [(.name // "-"),(.status // "-"),(.blockers // "0"|tostring),(.phase // "-"|tostring),(.next_action // "-"|clip(70))]- | join("|"))' | pretty_table-}--infra_table() {- {- printf 'PROJECT|SERVICE|TIER|STATUS|HTTP/RUN|LAT|URL\n'- jq_file "$INFRA_CACHE" '{"endpoints":[]}' --argjson max "$MAX_ROWS" -r '- (.endpoints // [])- | map(select(.project|ascii_downcase|test("healify|meditation")))- | sort_by(if .status=="down" then 0 elif .status=="warn" then 1 else 2 end, .project, .service)- | .[:$max]- | .[]- | [.project,.service,.tier,.status,.http,((.ms|tostring)+"ms"),.url]- | @tsv' | awk -F'\t' '{printf "%s|%s|%s|%s|%s|%s|%s\n",$1,$2,$3,$4,$5,$6,$7}'- jq_file "$AWS_CACHE" '{"services":[]}' --argjson max "$MAX_ROWS" -r '- (.services // [])- | map(select(.project|ascii_downcase|test("healify|meditation")))- | sort_by(if .status=="down" then 0 elif .status=="warn" then 1 else 2 end, .tier, .project)- | .[:$max]- | .[]- | [.project,.service,.tier,.status,.http,"-",.url]- | @tsv' | awk -F'\t' '{printf "%s|%s|%s|%s|%s|%s|%s\n",$1,$2,$3,$4,$5,$6,$7}'- } | pretty_table-}--agents_table() {- {- printf 'SOURCE|STATUS|DETAIL\n'- if [[ -s "$RUNTIME_CACHE" ]]; then- sed -n '1,30p' "$RUNTIME_CACHE" | awk -F: '{status=$2; sub(/^/,"",status); printf "%s|%s|%s\n",$1,(status ~ /ready|configured|ok/ ? "ok" : "warn"),status}'- else- printf 'runtime-health|missing|run agent-hub-health short\n'- fi- printf 'tmux|ok|%s windows in %s\n' "$(tmux list-windows -t "$SESSION" 2>/dev/null | wc -l | awk '{print $1}')" "$SESSION"- if command -v claude >/dev/null 2>&1; then- local c_total c_bad- c_total="$(timeout 12 claude agents --json --all 2>/dev/null | jq '[.[]? | select(.kind=="background")] | length' 2>/dev/null || echo '-')"- c_bad="$(timeout 12 claude agents --json --all 2>/dev/null | jq '[.[]? | select(.kind=="background" and (.state=="failed" or .state=="blocked"))] | length' 2>/dev/null || echo '-')"- printf 'claude-agents|ok|%s background, %s failed/blocked\n' "$c_total" "$c_bad"- fi- } | pretty_table-}--plugin_table() {- {- printf 'SURFACE|COUNT|USE IN HEALIFY DASHBOARD\n'- safe_jq "$PLUGIN_CACHE" '{"claude_plugins":[],"codex_skills":[],"ops_kpi_caches":[]}' '- "Claude plugins|" + ((.claude_plugins|length)|tostring) + "|connectors, business context, MCP capability map",- "Codex skills|" + ((.codex_skills|length)|tostring) + "|engineering execution map and review surfaces",- "Ops KPI caches|" + ((.ops_kpi_caches|length)|tostring) + "|revenue, social, marketing, project status caches"- ' | tr -d '"'- } | pretty_table-}--logs_panel() {- local log- for log in \- "$OPS_DATA/logs/ops-daemon.log" \- "$OPS_DATA/logs/mcp-watchdog.log" \- "$HOME/.claude/logs/agent-hub-watchdog.log" \- "$HOME/.claude/logs/agent-hub-revive.log"; do- [[ -s "$log" ]] || continue- printf '%s\n' "${log/#$HOME/~}"- tail -5 "$log" 2>/dev/null | sed 's/^/ /' | clip_width "$(cols)"- done-}--metric_value() {- local key="$1"- case "$key" in- endpoints_ok) safe_jq "$INFRA_CACHE" '{"endpoints":[]}' '[.endpoints[]? | select((.project|ascii_downcase|test("healify|meditation")) and .status=="ok")] | length' ;;- endpoints_down) safe_jq "$INFRA_CACHE" '{"endpoints":[]}' '[.endpoints[]? | select((.project|ascii_downcase|test("healify|meditation")) and .status=="down")] | length' ;;- ecs_ok) safe_jq "$AWS_CACHE" '{"services":[]}' '[.services[]? | select((.project|ascii_downcase|test("healify|meditation")) and .status=="ok")] | length' ;;- blockers) safe_jq "$OPS_PROJECTS" '{"projects":[]}' '[.projects[]? | select((.name|ascii_downcase|test("healify|meditation")) and ((.blockers // "0"|tostring) != "0"))] | length' ;;- projects) safe_jq "$OPS_PROJECTS" '{"projects":[]}' '[.projects[]? | select(.name|ascii_downcase|test("healify|meditation"))] | length' ;;- plugins) safe_jq "$PLUGIN_CACHE" '{"claude_plugins":[]}' '.claude_plugins | length' ;;- skills) safe_jq "$PLUGIN_CACHE" '{"codex_skills":[]}' '.codex_skills | length' ;;- kpis) safe_jq "$PLUGIN_CACHE" '{"ops_kpi_caches":[]}' '.ops_kpi_caches | length' ;;- latest_build) jq_file "$BI_CACHE" '{}' --arg prod "$ASC_PROD_APP_ID" -r '(.ascExtra.apps[]? | select(.appId==$prod) | .builds[0].version) // (.eas.builds[0].appBuildVersion // "-")' ;;- app_version) jq_file "$BI_CACHE" '{}' --arg prod "$ASC_PROD_APP_ID" -r '(.opdash.appstore.appDetails[]? | select(.appId==$prod) | .appStoreVersions[0].versionString) // "-"' ;;- app_state) jq_file "$BI_CACHE" '{}' --arg prod "$ASC_PROD_APP_ID" -r '(.opdash.appstore.appDetails[]? | select(.appId==$prod) | .appStoreVersions[0].appStoreState) // "-"' ;;- installs) safe_jq "$BI_CACHE" '{}' '((.opdash.ops.cards // [])[]? | select(.id=="appsflyer") | .metrics.installs) // "-"' ;;- sentry_mobile) jq_file "$BI_CACHE" '{}' --arg project "$SENTRY_MOBILE_PROJECT" -r '(.sentry.projects[]? | select(.project==$project) | .unresolved) // "-"' ;;- linear_p1) safe_jq "$BI_CACHE" '{}' '((.opdash.ops.cards // [])[]? | select(.id=="linear") | .metrics.p1) // "-"' ;;- reviews) jq_file "$BI_CACHE" '{}' --arg prod "$ASC_PROD_APP_ID" -r '(.ascExtra.apps[]? | select(.appId==$prod) | .reviews.count) // "-"' ;;- esac-}--compact_box() {- local title="$1" value="$2" detail="$3" width="$4"- printf '%s+%*s+%s\n' "$BORDER" "$((width - 2))" '' "$RESET" | tr ' ' '-'- printf '| %s%-*s%s |\n' "$DIM" "$((width - 4))" "$title" "$RESET"- printf '| %s%s%-*s%s |\n' "$BOLD" "$ORANGE" "$((width - 4))" "$value" "$RESET"- printf '| %-*s |\n' "$((width - 4))" "$detail"- printf '%s+%*s+%s\n' "$BORDER" "$((width - 2))" '' "$RESET" | tr ' ' '-'-}--compact_pair() {- local w left_title left_value left_detail right_title right_value right_detail- w="$1"- left_title="$2"; left_value="$3"; left_detail="$4"- right_title="$5"; right_value="$6"; right_detail="$7"- if (( w < 82 )); then- compact_box "$left_title" "$left_value" "$left_detail" "$w"- compact_box "$right_title" "$right_value" "$right_detail" "$w"- return- fi- local bw=$(((w - 3) / 2))- paste -d' ' \- <(compact_box "$left_title" "$left_value" "$left_detail" "$bw") \- <(compact_box "$right_title" "$right_value" "$right_detail" "$bw")-}--compact_logo() {- printf '%s%s' "$ORANGE" "$BOLD"- printf '██╗ ██╗███████╗ █████╗ ██╗ ██╗███████╗██╗ ██╗\n'- printf '███████║█████╗ ███████║██║ ██║█████╗ ╚████╔╝ \n'- printf '██║ ██║███████╗██║ ██║███████╗██║██║ ██║ \n'- printf '%s' "$RESET"-}--compact_kpis() {- jq_file "$KPI_CACHE" '{"projects":[]}' -r '- def fmt:- if . == null then "-"- elif type=="number" then- if . >= 1000000 then ((./1000000*10|round/10|tostring)+"M")- elif . >= 1000 then ((./1000*10|round/10|tostring)+"K")- else (.|tostring) end- else tostring end;- ((.projects // []) | map(select((.key // .label // "" | ascii_downcase) == "healify")) | .[0] // {}) as $h |- [- "IG followers|" + (($h.social.ig_followers // null)|fmt),- "IG reach|" + (($h.social.ig_reach // null)|fmt),- "Requests|" + (($h.social.active_req // null)|fmt),- "Ads|" + (($h.ads.health // "-")|tostring),- "Dev|" + (($h.dev.phase // "-")|tostring)- ][]' | column -t -s '|' | sed 's/^/ /' | clip_width "$(raw_cols)"-}--compact_risks() {- {- jq_file "$INFRA_CACHE" '{"endpoints":[]}' -r '- (.endpoints // [])- | map(select((.project|ascii_downcase|test("healify|meditation")) and .status!="ok"))- | .[:5]- | .[]- | " " + .status + " " + .project + " / " + .service + " " + (.http|tostring)'- jq_file "$OPS_PROJECTS" '{"projects":[]}' -r '- (.projects // [])- | map(select((.name|ascii_downcase|test("healify|meditation")) and ((.blockers // "0"|tostring) != "0")))- | .[:4]- | .[]- | " blocked " + .name + " " + (.next_action // "-" | tostring | gsub("[\r\n\t]+";" ") | .[0:48])'- } | sed '/^$/d' | sed -n '1,8p' | clip_width "$(raw_cols)"-}--compact_agents() {- if [[ -s "$RUNTIME_CACHE" ]]; then- sed -n '1,8p' "$RUNTIME_CACHE" | awk -F: '{printf " %-10s %s\n",$1,$2}' | clip_width "$(raw_cols)"- else- printf ' runtime health cache missing\n'- fi-}--compact_bi() {- jq_file "$BI_CACHE" '{}' --arg prod "$ASC_PROD_APP_ID" --arg project "$SENTRY_MOBILE_PROJECT" -r '- def s: if . == null then "-" else tostring end;- def card($id): (.opdash.ops.cards // [] | map(select(.id==$id)) | .[0] // {});- [- "ASC prod|" + ((.ascExtra.apps[]? | select(.appId==$prod) | .builds[0].version) // "-") + " · " + ((.ascExtra.apps[]? | select(.appId==$prod) | .builds[0].processingState) // "-"),- "Store|" + ((.opdash.appstore.appDetails[]? | select(.appId==$prod) | .appStoreVersions[0].versionString) // "-") + " · " + ((.opdash.appstore.appDetails[]? | select(.appId==$prod) | .appStoreVersions[0].appStoreState) // "-"),- "Installs|" + ((card("appsflyer").metrics.installs)|s) + " organic " + ((card("appsflyer").metrics.organic)|s),- "Sentry mobile|" + ((.sentry.projects[]? | select(.project==$project) | .unresolved)|s) + " unresolved",- "Linear|" + ((card("linear").metrics.p1)|s) + " P1 / " + ((card("linear").metrics.p2)|s) + " P2",- "Downloads|" + ((.opdash.appstore.metrics.downloads)|s) + " · vendor no. needed"- ][]' | column -t -s '|' | sed 's/^/ /' | clip_width "$(raw_cols)"-}--render_compact() {- local w now host endpoints_ok endpoints_down ecs_ok blockers projects plugins skills kpis- w="$(raw_cols)"- now="$(date -u '+%H:%M:%SZ')"- host="$(hostname -s 2>/dev/null || hostname)"- endpoints_ok="$(metric_value endpoints_ok)"- endpoints_down="$(metric_value endpoints_down)"- ecs_ok="$(metric_value ecs_ok)"- blockers="$(metric_value blockers)"- projects="$(metric_value projects)"- plugins="$(metric_value plugins)"- skills="$(metric_value skills)"- kpis="$(metric_value kpis)"-- compact_logo- printf '%s%sHEALIFY.AI%s %s%s · %s · %s%s\n' "$BOLD" "$AMBER" "$RESET" "$DIM" "$now" "$host" "orange command center" "$RESET"- printf '%s' "$BORDER"; printf '%*s\n' "$w" '' | tr ' ' '-'; printf '%s' "$RESET"- compact_pair "$w" "App Store" "v$(metric_value app_version) / build $(metric_value latest_build)" "$(metric_value app_state) · $(metric_value reviews) reviews" "Growth" "$(metric_value installs) installs" "AppsFlyer 7d · downloads need vendor no."- compact_pair "$w" "Reliability" "$(metric_value sentry_mobile) mobile issues" "Sentry · $(metric_value linear_p1) Linear P1" "Infra" "$endpoints_ok OK / $endpoints_down down" "HTTP + health endpoints"- compact_pair "$w" "Execution" "$projects projects / $blockers blockers" "GSD + ops registry" "Intelligence" "$plugins plugins / $skills skills" "$kpis KPI caches"- printf '\n%s%sBI Snapshot%s\n' "$BOLD" "$ORANGE" "$RESET"- compact_bi- printf '\n%s%sBusiness KPIs%s\n' "$BOLD" "$ORANGE" "$RESET"- compact_kpis- printf '\n%s%sNeeds Attention%s\n' "$BOLD" "$ORANGE" "$RESET"- compact_risks- printf '\n%s%sAgents / MCPs%s\n' "$BOLD" "$ORANGE" "$RESET"- compact_agents- printf '\n%sKeys:%s Ctrl-a v Healify · Ctrl-a f Fleet · Ctrl-a d Doctor · hd --refresh\n' "$DIM" "$RESET"-}--render() {- [[ "$REFRESH" == "1" ]] && refresh_caches- [[ -t 1 ]] && clear- if (( $(raw_cols) < 100 || $(raw_lines) < 36 )); then- render_compact- return- fi- hero- cards- section "Business KPIs"- business_kpis- section "Marketing And Acquisition"- marketing_table- section "App Store, TestFlight, Reviews"- release_table- section "Reliability, QA, Work"- reliability_table- section "Execution Portfolio"- projects_table- section "Infra And Deployments"- infra_table- section "Repos"- repo_rows | pretty_table- section "Agents, MCPs, CLIs"- agents_table- section "Plugin Surface"- plugin_table- section "Important Logs"- logs_panel- printf '\n%sCommands:%s hd --watch | hd --refresh | fleet | agent-hub-doctor --fix | agent-hub-ops menu\n' "$DIM" "$RESET"-}--case "$MODE" in- --once|"") render ;;- --watch)- while true; do- render || true- sleep "$INTERVAL"- done- ;;- --json) json_summary ;;- -h|--help) usage ;;- *) usage >&2; exit 2 ;;-esacdiff --git a/claude-ops/bin/ops-launch-gate b/claude-ops/bin/ops-launch-gateindex f3252890..2a728fd8 100755--- a/claude-ops/bin/ops-launch-gate+++ b/claude-ops/bin/ops-launch-gate@@ -1,5 +1,5 @@#!/usr/bin/env bash-# ops-launch-gate — Healify marketing launch go/no-go scoreboard+# ops-launch-gate — marketing launch go/no-go scoreboard## Checks distribution, funnel, measurement, and API health for campaign readiness.# Exit 0 = all hard gates green; exit 1 = one or more hard gates red.@@ -9,9 +9,17 @@# ops-launch-gate --json # machine-readable# ops-launch-gate --quiet # exit code only#-# Env:-# DOPPLER_TOKEN / doppler CLI logged in (healify, healify-api projects)-# Optional: PLAY_DWD_SUBJECT (default [email protected])+# Config — nothing app-specific is baked in; set these in your environment:+# OPS_APP_BUNDLE_ID iOS bundle id and Play package (e.g. com.example.app)+# OPS_API_BASE_URL API origin; health probed at <base>/health+# OPS_TRY_URL funnel redirect URL to probe for a Location header+# OPS_LANDING_HOSTS space-separated landing hosts to probe+# OPS_DOPPLER_APP_PROJECT doppler project holding app/analytics secrets+# OPS_DOPPLER_API_PROJECT doppler project holding API secrets+# PLAY_DWD_SUBJECT Workspace subject for Play domain-wide delegation+# DOPPLER_TOKEN / doppler CLI logged in+#+# Gates whose config is unset report AMBER rather than failing the run.set -euo pipefailJSON=0@@ -21,15 +29,22 @@ for arg in "$@"; do--json) JSON=1 ;;--quiet) QUIET=1 ;;-h|--help)- sed -n '2,20p' "$0"+ sed -n '2,22p' "$0"exit 0;;esacdone-PLAY_SUBJECT="${PLAY_DWD_SUBJECT:[email protected]}"-PACKAGE="${PLAY_PACKAGE:-com.healify.healify}"-IOS_BUNDLE="${IOS_BUNDLE:-com.healify.healify}"+PLAY_SUBJECT="${PLAY_DWD_SUBJECT:-}"+PACKAGE="${PLAY_PACKAGE:-${OPS_APP_BUNDLE_ID:-}}"+IOS_BUNDLE="${IOS_BUNDLE:-${OPS_APP_BUNDLE_ID:-}}"+API_BASE="${OPS_API_BASE_URL:-}"+API_BASE="${API_BASE%/}"+TRY_URL="${OPS_TRY_URL:-}"+LANDING_HOSTS="${OPS_LANDING_HOSTS:-}"+DOPPLER_APP_PROJECT="${OPS_DOPPLER_APP_PROJECT:-}"+DOPPLER_API_PROJECT="${OPS_DOPPLER_API_PROJECT:-}"+export PLAY_SUBJECT PACKAGE DOPPLER_APP_PROJECTHARD_FAIL=0green() { printf 'GREEN'; }@@ -65,7 +80,12 @@ add_row() {}# ── G1 iOS public ───────────────────────────────────────────────────────────-ios_json=$(curl -gsS --max-time 12 "https://itunes.apple.com/lookup?bundleId=${IOS_BUNDLE}&country=us" 2>/dev/null || echo '{}')+if [[ -z "$IOS_BUNDLE" ]]; then+ add_row "G1_iOS_public" "AMBER" "OPS_APP_BUNDLE_ID unset"+ ios_json='{}'+else+ ios_json=$(curl -gsS --max-time 12 "https://itunes.apple.com/lookup?bundleId=${IOS_BUNDLE}&country=us" 2>/dev/null || echo '{}')+fiios_ver=$(printf '%s' "$ios_json" | python3 -c 'import sys,jsontry:d=json.load(sys.stdin); r=d.get("results") or []@@ -78,17 +98,21 @@ try:except: print("")' 2>/dev/null || true)if [[ -n "$ios_ver" ]]; thenadd_row "G1_iOS_public" "GREEN" "live ${ios_ver} released ${ios_date}"-else+elif [[ -n "$IOS_BUNDLE" ]]; thenadd_row "G1_iOS_public" "RED" "iTunes lookup empty for ${IOS_BUNDLE}"fi# ── G2 Play public URL ──────────────────────────────────────────────────────-play_http=$(curl -gsS -o /dev/null -w '%{http_code}' --max-time 12 \- -A 'Mozilla/5.0' "https://play.google.com/store/apps/details?id=${PACKAGE}" 2>/dev/null || echo '000')-if [[ "$play_http" == "200" ]]; then- add_row "G2_Play_public" "GREEN" "store page HTTP 200"+if [[ -z "$PACKAGE" ]]; then+ add_row "G2_Play_public" "AMBER" "OPS_APP_BUNDLE_ID unset"else- add_row "G2_Play_public" "RED" "store page HTTP ${play_http} (need Console first-publish visibility)"+ play_http=$(curl -gsS -o /dev/null -w '%{http_code}' --max-time 12 \+ -A 'Mozilla/5.0' "https://play.google.com/store/apps/details?id=${PACKAGE}" 2>/dev/null || echo '000')+ if [[ "$play_http" == "200" ]]; then+ add_row "G2_Play_public" "GREEN" "store page HTTP 200"+ else+ add_row "G2_Play_public" "RED" "store page HTTP ${play_http} (need Console first-publish visibility)"+ fifi# ── G2b Play tracks (DWD) ───────────────────────────────────────────────────@@ -98,7 +122,14 @@ from google.oauth2 import service_accountfrom google.auth.transport.requests import Requestfrom googleapiclient.discovery import build-def doppler(key, project="healify", config="prd"):+PROJECT = os.environ.get("DOPPLER_APP_PROJECT", "")+SUBJECT = os.environ.get("PLAY_SUBJECT", "")+PKG = os.environ.get("PACKAGE", "")+if not PROJECT or not SUBJECT or not PKG:+ print("NO_CONFIG"); raise SystemExit(0)+++def doppler(key, project=PROJECT, config="prd"):r = subprocess.run(["doppler", "secrets", "get", key, "--project", project, "--config", config, "--plain"],capture_output=True, text=True,@@ -109,13 +140,12 @@ raw = doppler("GOOGLE_PLAY_SERVICE_ACCOUNT_JSON") or doppler("PLAY_STORE_SERVICEif not raw:print("NO_SECRET"); raise SystemExit(0)sa = json.loads(raw)-subject = os.environ.get("PLAY_DWD_SUBJECT", "[email protected]")creds = service_account.Credentials.from_service_account_info(- sa, scopes=["https://www.googleapis.com/auth/androidpublisher"], subject=subject+ sa, scopes=["https://www.googleapis.com/auth/androidpublisher"], subject=SUBJECT)creds.refresh(Request())svc = build("androidpublisher", "v3", credentials=creds, cache_discovery=False)-pkg = os.environ.get("PLAY_PACKAGE", "com.healify.healify")+pkg = PKGedit = svc.edits().insert(packageName=pkg).execute()tracks = svc.edits().tracks().list(packageName=pkg, editId=edit["id"]).execute()parts = []@@ -126,7 +156,9 @@ svc.edits().delete(packageName=pkg, editId=edit["id"]).execute()print("; ".join(parts) if parts else "NO_TRACKS")PY)-if [[ "$play_tracks" == "NO_SECRET" || -z "$play_tracks" ]]; then+if [[ "$play_tracks" == "NO_CONFIG" ]]; then+ add_row "G2b_Play_tracks" "AMBER" "set OPS_DOPPLER_APP_PROJECT, PLAY_DWD_SUBJECT, OPS_APP_BUNDLE_ID"+elif [[ "$play_tracks" == "NO_SECRET" || -z "$play_tracks" ]]; thenadd_row "G2b_Play_tracks" "AMBER" "could not read tracks (doppler/DWD)"elif [[ "$play_tracks" == *"production=completed"* ]]; thenadd_row "G2b_Play_tracks" "GREEN" "$play_tracks"@@ -135,11 +167,14 @@ elsefi# ── G3 Attribution ──────────────────────────────────────────────────────────-attr_secret=$(doppler secrets get ATTRIBUTION_INGEST_SECRET --project healify-api --config prd --plain 2>/dev/null || true)+attr_secret=""+if [[ -n "$DOPPLER_API_PROJECT" ]]; then+ attr_secret=$(doppler secrets get ATTRIBUTION_INGEST_SECRET --project "$DOPPLER_API_PROJECT" --config prd --plain 2>/dev/null || true)+fitoken="launch-gate-$(date +%s)"-if [[ -n "$attr_secret" ]]; then+if [[ -n "$attr_secret" && -n "$API_BASE" ]]; thenattr_code=$(curl -gsS -o /dev/null -w '%{http_code}' --max-time 12 \- -X POST 'https://ai.healify.ai/api/analytics/attribution/click' \+ -X POST "${API_BASE}/api/analytics/attribution/click" \-H 'Content-Type: application/json' \-H "X-Attribution-Secret: ${attr_secret}" \-d "{\"clickToken\":\"${token}\",\"utm\":{\"utm_source\":\"launch_gate\",\"utm_medium\":\"qa\",\"utm_campaign\":\"scoreboard\"},\"destination\":\"app_store\",\"clickedAt\":\"$(date -u +%Y-%m-%dT%H:%M:%S.000Z)\"}" \@@ -147,34 +182,46 @@ if [[ -n "$attr_secret" ]]; thenelseattr_code='NOSEC'fi-tf_loc=$(curl -gsS -D - -o /dev/null --max-time 12 \- 'https://try.healify.ai/get?channel=waitlist&utm_source=launch_gate' 2>/dev/null \- | awk 'tolower($1)=="location:"{print $2}' | tr -d '\r' | head -1)+tf_loc=""+if [[ -n "$TRY_URL" ]]; then+ tf_loc=$(curl -gsS -D - -o /dev/null --max-time 12 \+ "$TRY_URL" 2>/dev/null \+ | awk 'tolower($1)=="location:"{print $2}' | tr -d '\r' | head -1)+fiif [[ "$attr_code" == "201" || "$attr_code" == "200" ]] && [[ -n "$tf_loc" ]]; then- add_row "G3_attribution" "GREEN" "click HTTP ${attr_code}; /get → ${tf_loc}"+ add_row "G3_attribution" "GREEN" "click HTTP ${attr_code}; redirect → ${tf_loc}"elif [[ "$attr_code" == "201" || "$attr_code" == "200" ]]; then- add_row "G3_attribution" "AMBER" "click HTTP ${attr_code}; /get location missing"+ add_row "G3_attribution" "AMBER" "click HTTP ${attr_code}; redirect location missing"+elif [[ -z "$API_BASE" || -z "$DOPPLER_API_PROJECT" ]]; then+ add_row "G3_attribution" "AMBER" "set OPS_API_BASE_URL, OPS_DOPPLER_API_PROJECT, OPS_TRY_URL"else- add_row "G3_attribution" "RED" "click HTTP ${attr_code}; /get=${tf_loc:-none}"+ add_row "G3_attribution" "RED" "click HTTP ${attr_code}; redirect=${tf_loc:-none}"fi# ── G4 API health ───────────────────────────────────────────────────────────-api_health=$(curl -gsS --max-time 12 'https://ai.healify.ai/health' 2>/dev/null || echo '{}')-api_ok=$(printf '%s' "$api_health" | python3 -c 'import sys,json+if [[ -z "$API_BASE" ]]; then+ add_row "G4_api_health" "AMBER" "OPS_API_BASE_URL unset"+else+ api_health=$(curl -gsS --max-time 12 "${API_BASE}/health" 2>/dev/null || echo '{}')+ api_ok=$(printf '%s' "$api_health" | python3 -c 'import sys,jsontry:d=json.load(sys.stdin); print("ok" if d.get("status")=="ok" or d.get("overall")=="healthy" else "bad")except: print("bad")' 2>/dev/null || echo bad)-if [[ "$api_ok" == "ok" ]]; then- add_row "G4_api_health" "GREEN" "ai.healify.ai healthy"-else- add_row "G4_api_health" "RED" "ai.healify.ai unhealthy"+ if [[ "$api_ok" == "ok" ]]; then+ add_row "G4_api_health" "GREEN" "${API_BASE} healthy"+ else+ add_row "G4_api_health" "RED" "${API_BASE} unhealthy"+ fifi# ── G5 Amplitude ────────────────────────────────────────────────────────────amp=$(python3 - <<'PY' 2>/dev/null || echo FAIL-import subprocess, base64, urllib.request+import os, subprocess, base64, urllib.request+PROJECT=os.environ.get("DOPPLER_APP_PROJECT","")+if not PROJECT:+ print("NO_CONFIG"); raise SystemExit(0)def g(k):- r=subprocess.run(["doppler","secrets","get",k,"--project","healify","--config","prd","--plain"],capture_output=True,text=True)+ r=subprocess.run(["doppler","secrets","get",k,"--project",PROJECT,"--config","prd","--plain"],capture_output=True,text=True)return r.stdout.strip() if r.returncode==0 else ""api,sec=g("AMPLITUDE_API_KEY"),g("AMPLITUDE_SECRET_KEY")if not api or not sec:@@ -190,19 +237,27 @@ PY)if [[ "$amp" == "200" ]]; thenadd_row "G5_amplitude" "GREEN" "EU taxonomy 200"+elif [[ "$amp" == "NO_CONFIG" ]]; then+ add_row "G5_amplitude" "AMBER" "OPS_DOPPLER_APP_PROJECT unset"+elif [[ "$amp" == "NO_SECRET" ]]; then+ add_row "G5_amplitude" "AMBER" "amplitude keys not in doppler"elseadd_row "G5_amplitude" "RED" "EU taxonomy ${amp}"fi# ── G6 Landing ──────────────────────────────────────────────────────────────-for host in try.healify.ai healify.ai; do- code=$(curl -gsS -o /dev/null -w '%{http_code}' --max-time 12 -A 'Mozilla/5.0' "https://${host}/" 2>/dev/null || echo '000')- if [[ "$code" == "200" ]]; then- add_row "G6_landing_${host//./_}" "GREEN" "HTTP 200"- else- add_row "G6_landing_${host//./_}" "AMBER" "HTTP ${code}"- fi-done+if [[ -z "$LANDING_HOSTS" ]]; then+ add_row "G6_landing" "AMBER" "OPS_LANDING_HOSTS unset"+else+ for host in $LANDING_HOSTS; do+ code=$(curl -gsS -o /dev/null -w '%{http_code}' --max-time 12 -A 'Mozilla/5.0' "https://${host}/" 2>/dev/null || echo '000')+ if [[ "$code" == "200" ]]; then+ add_row "G6_landing_${host//./_}" "GREEN" "HTTP 200"+ else+ add_row "G6_landing_${host//./_}" "AMBER" "HTTP ${code}"+ fi+ done+fi# ── Campaign rule summary ───────────────────────────────────────────────────if [[ "$JSON" == 1 ]]; thendiff --git a/claude-ops/bin/ops-marketing-dash b/claude-ops/bin/ops-marketing-dashindex 7c57cf61..0636d261 100755--- a/claude-ops/bin/ops-marketing-dash+++ b/claude-ops/bin/ops-marketing-dash@@ -140,7 +140,7 @@ fi# Amplitude (product analytics: signups / new + active users). Dashboard REST API# uses HTTP Basic (api_key:secret_key). EU data-residency projects MUST hit# analytics.eu.amplitude.com; US hits amplitude.com (server_zone selects host).-# Creds resolve from the project-scoped prefs tier first (doppler:healify/prd/…),+# Creds resolve from the project-scoped prefs tier first (doppler:<project>/prd/…),# then env, then owner-level channels.marketing.amplitude.*_key Doppler refs.AMPLITUDE_API_KEY="$(get_cred 'amplitude.api_key' AMPLITUDE_API_KEY amplitude_api_key AMPLITUDE_API_KEY amplitude api_key_key)"AMPLITUDE_SECRET_KEY="$(get_cred 'amplitude.secret_key' AMPLITUDE_SECRET_KEY amplitude_secret_key AMPLITUDE_SECRET_KEY amplitude secret_key_key)"@@ -160,7 +160,7 @@ APPSFLYER_APP_ID="$(get_cred 'appsflyer.app_id' APPSFLYER_APP_ID appsflyer_app_i# RevenueCat (GROUND-TRUTH real app users: customers/subscriptions/MRR). v2 secret# key (sk_…) + project id. This is the authoritative "real people" source — it# counts actual app identities with store receipts, unlike Amplitude event counts.-REVENUECAT_KEY="$(get_cred 'revenuecat.api_key' REVENUECAT_HEALIFY_API_KEY revenuecat_api_key REVENUECAT_HEALIFY_API_KEY revenuecat api_key_key)"+REVENUECAT_KEY="$(get_cred 'revenuecat.api_key' REVENUECAT_API_KEY revenuecat_api_key REVENUECAT_API_KEY revenuecat api_key_key)"REVENUECAT_PROJECT="$(get_cred 'revenuecat.project_id' REVENUECAT_PROJECT_ID revenuecat_project_id)"# Meta ad-account id: prefs carries only the Business Manager id (bm_id_key), not@@ -271,9 +271,10 @@ gather_meta() {APP_INSTALLS=$(echo "$INSIGHTS" | jq -r '[.data[0].actions[]? | select(.action_type | test("mobile_app_install|app_install|omni_app_install")) | .value] | map(tonumber) | add // 0 | tostring' 2>/dev/null || echo "0")REGISTRATIONS=$(echo "$INSIGHTS" | jq -r '[.data[0].actions[]? | select(.action_type | test("complete_registration")) | .value] | map(tonumber) | add // 0 | tostring' 2>/dev/null || echo "0")- # Account currency — Meta reports spend in the ad-account currency (Healify = USD,- # NOT EUR). Fetch once so the statusline labels spend with the real symbol instead- # of assuming €. Cheap single call; falls back to empty (renderer omits symbol).+ # Account currency — Meta reports spend in the ad-account currency, which is not+ # always the owner's local currency. Fetch once so the statusline labels spend with+ # the real symbol instead of assuming one. Cheap single call; falls back to empty+ # (renderer omits symbol).CURRENCY=$(curl -gsS --max-time 5 "https://graph.facebook.com/v21.0/${META_ACCOUNT}?fields=currency${META_PROOF_QS}" \-H "Authorization: Bearer ${META_TOKEN}" 2>/dev/null | jq -r '.currency // ""' 2>/dev/null || echo "")diff --git a/claude-ops/bin/ops-update-check b/claude-ops/bin/ops-update-checknew file mode 100755index 00000000..129ae7a9--- /dev/null+++ b/claude-ops/bin/ops-update-check@@ -0,0 +1,166 @@+#!/usr/bin/env bash+# ops-update-check — is a newer claude-ops published? Answer, record, change nothing.+#+# This is the detect half of the auto-updater. It NEVER installs, patches, prunes,+# or restarts anything; applying an update stays a deliberate act run through+# `ops-update`, which the operator confirms. Keeping detect and apply apart is the+# whole point: a background job that silently swaps the plugin out from under a+# running session is how a working install breaks at the worst moment.+#+# What it does:+# 1. Read the installed version from the plugin manifest.+# 2. Refresh the marketplace catalogue (read-only pull) unless --no-fetch.+# 3. Read the published version from the refreshed catalogue.+# 4. Write the verdict to a state file the daemon and skills can read.+#+# Usage:+# ops-update-check [--json] [--no-fetch] [--force] [--quiet]+#+# --json emit the verdict as JSON on stdout+# --no-fetch do not pull the catalogue; compare against whatever is on disk+# --force ignore the once-a-day throttle+# --quiet write the state file, print nothing+#+# Exit codes:+# 0 up to date, or check skipped by the throttle+# 3 an update is available (scriptable: `ops-update-check || [ $? -eq 3 ]`)+# 1 the check could not be completed (no manifest, no catalogue, bad JSON)+#+# Public repo: no personal data. All paths derive from $HOME / env. (Rule 0)++set -euo pipefail++MARKETPLACE="ops-marketplace"+PLUGIN="ops"+PLUGINS_DIR="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/plugins"+STATE_DIR="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/state/ops-update"+STATE_FILE="$STATE_DIR/update-available.json"+THROTTLE_SECONDS="${OPS_UPDATE_CHECK_INTERVAL:-86400}"++WANT_JSON=0+NO_FETCH=0+FORCE=0+QUIET=0+for arg in "$@"; do+ case "$arg" in+ --json) WANT_JSON=1 ;;+ --no-fetch) NO_FETCH=1 ;;+ --force) FORCE=1 ;;+ --quiet) QUIET=1 ;;+ -h|--help) sed -n '2,30p' "$0"; exit 0 ;;+ *) echo "ops-update-check: unknown argument: $arg" >&2; exit 1 ;;+ esac+done++say() { [ "$QUIET" -eq 1 ] || printf '%s\n' "$*"; }++mkdir -p "$STATE_DIR"++# --- throttle -------------------------------------------------------------+# The daily cadence lives here rather than only in cron so that a session-start+# probe and the daemon cannot together hammer the catalogue.+now=$(date +%s)+if [ "$FORCE" -eq 0 ] && [ -f "$STATE_FILE" ]; then+ last=$(python3 -c "+import json,sys+try:+ print(int(json.load(open('$STATE_FILE')).get('checked_at_epoch', 0)))+except Exception:+ print(0)+" 2>/dev/null || echo 0)+ if [ "$last" -gt 0 ] && [ $((now - last)) -lt "$THROTTLE_SECONDS" ]; then+ say "checked less than $((THROTTLE_SECONDS / 3600))h ago; use --force to recheck"+ exit 0+ fi+fi++# --- installed version ----------------------------------------------------+installed=""+for manifest in \+ "$PLUGINS_DIR/cache/$MARKETPLACE/$PLUGIN/current/.claude-plugin/plugin.json" \+ "$PLUGINS_DIR/marketplaces/$MARKETPLACE/$PLUGIN/.claude-plugin/plugin.json"; do+ if [ -f "$manifest" ]; then+ installed=$(python3 -c "+import json+try:+ print(json.load(open('$manifest')).get('version','') or '')+except Exception:+ pass+" 2>/dev/null || true)+ [ -n "$installed" ] && break+ fi+done++if [ -z "$installed" ]; then+ say "ops-update-check: no installed plugin manifest found; nothing to compare"+ exit 1+fi++# --- published version ----------------------------------------------------+if [ "$NO_FETCH" -eq 0 ] && command -v claude >/dev/null 2>&1; then+ claude plugin marketplace update "$MARKETPLACE" >/dev/null 2>&1 || true+fi++catalogue="$PLUGINS_DIR/marketplaces/$MARKETPLACE/.claude-plugin/marketplace.json"+published=""+if [ -f "$catalogue" ]; then+ published=$(python3 -c "+import json+try:+ d = json.load(open('$catalogue'))+except Exception:+ raise SystemExit+plugins = d.get('plugins')+if isinstance(plugins, dict):+ entry = plugins.get('$PLUGIN') or {}+elif isinstance(plugins, list):+ entry = next((p for p in plugins if p.get('name') == '$PLUGIN'), {})+else:+ entry = {}+print(entry.get('version','') or '')+" 2>/dev/null || true)+fi++if [ -z "$published" ]; then+ say "ops-update-check: could not read a published version from the catalogue"+ exit 1+fi++# --- compare --------------------------------------------------------------+# Pure version compare; no network, no side effects.+newer=$(python3 -c "+def parts(v):+ out = []+ for chunk in str(v).split('.'):+ digits = ''.join(c for c in chunk if c.isdigit())+ out.append(int(digits) if digits else 0)+ return out+a, b = parts('$installed'), parts('$published')+n = max(len(a), len(b))+a += [0] * (n - len(a))+b += [0] * (n - len(b))+print('yes' if b > a else 'no')+" 2>/dev/null || echo "no")++python3 - "$STATE_FILE" "$installed" "$published" "$newer" "$now" <<'PY'+import json, sys+state_file, installed, published, newer, now = sys.argv[1:6]+json.dump({+ "installed": installed,+ "published": published,+ "update_available": newer == "yes",+ "checked_at_epoch": int(now),+}, open(state_file, "w"), indent=2)+PY++if [ "$WANT_JSON" -eq 1 ]; then+ cat "$STATE_FILE"+fi++if [ "$newer" = "yes" ]; then+ [ "$WANT_JSON" -eq 1 ] || say "claude-ops $installed -> $published available. Apply with: ops-update"+ exit 3+fi++[ "$WANT_JSON" -eq 1 ] || say "claude-ops $installed is current"+exit 0diff --git a/claude-ops/docs/healify-dashboard.md b/claude-ops/docs/healify-dashboard.mddeleted file mode 100644index 7e3f633c..00000000--- a/claude-ops/docs/healify-dashboard.md+++ /dev/null@@ -1,69 +0,0 @@-# Healify Dashboard--`ops-healify-dash` is a dedicated Healify.ai command center for terminal and tmux workflows. It is read-only by default and designed for dark terminals with an orange Healify.ai brand treatment.--## Commands--```bash-ops-healify-dash --once-ops-healify-dash --watch-ops-healify-dash --refresh-ops-healify-dash --json-ops-healify-bi-refresh-```--`--refresh` refreshes bounded local caches first. `--watch` rerenders on an interval. Neither mode changes tmux focus or selects another window.--`ops-dash` can explicitly delegate to this surface:--```bash-OPS_HEALIFY_DASH=1 ops-dash-```--## Data Sources--The dashboard aggregates only local, already-configured sources:--- `ops:projects` cache: `$OPS_DATA_DIR/cache/projects_health.json`-- statusline KPI cache: `~/.claude/state/statusline-kpi.json`-- live endpoint health cache: `~/.cache/agent-hub/infra-health.json`-- AWS ECS health cache: `~/.cache/agent-hub/aws-ecs-health.json`-- plugin inventory: `~/.cache/agent-hub/plugin-inventory.json`-- Healify BI cache: `~/.cache/agent-hub/healify-bi.json`-- runtime health: `~/.cache/agent-hub/fleet/runtime-health.txt`-- local Healify git repos under `~/Projects/healify-workspace`-- important ops and agent-hub logs--`ops-healify-bi-refresh` warms the BI cache from authenticated local and ops-dashboard sources when available:--- EAS latest iOS builds-- App Store Connect app versions, build numbers, processing state, and reviews-- App Store Connect sales/download status, clearly marked blocked when the vendor number is missing-- AppsFlyer installs, organic split, loyal users, and cost-- Amplitude active/new-user status-- Sentry unresolved issue counts by Healify project-- BetterStack uptime/incidents-- Linear priority issue counts-- mobile QA and Pact/contract health from the operating dashboard integration source--It shows business KPIs, acquisition and marketing state, App Store/TestFlight release state, reviews, project execution state, service health, ECS deployment status, repo drift, agent/MCP/CLI readiness, plugin coverage, and recent important logs.--## Branding--The 1:1 pixel icon lives at:--```text-assets/healify-pixel-logo.svg-```--It follows the current Healify.ai app-icon direction: orange/pink rounded square, high contrast, and a white heart/pill health mark. The terminal dashboard renders the same concept as ANSI pixel blocks.--## Tmux Integration--Any tmux binding should open this dashboard only through explicit user action, for example:--```tmux-bind v display-popup -E -w 96% -h 92% "ops-healify-dash --watch"-```--Background watchdogs, prewarmers, doctors, and repair hooks must not call `select-window` or `switch-client`. While a user is working in a window, focus should remain there unless the user explicitly presses a navigation key.diff --git a/claude-ops/docs/pocket-ec2-deployment.md b/claude-ops/docs/pocket-ec2-deployment.mdindex 6bf131e9..51a60def 100644--- a/claude-ops/docs/pocket-ec2-deployment.md+++ b/claude-ops/docs/pocket-ec2-deployment.md@@ -1,18 +1,18 @@# Pocket pipeline — EC2 deployment on dev-sandbox-Pocket runs entirely on the dev-sandbox EC2 instance (i-0b207951a7dff925d,+Pocket runs entirely on a dedicated EC2 instance (`$POCKET_INSTANCE_ID`,m8g.2xlarge). This is an approved exception to the no-EC2 rule; pocketworkloads are too persistent for a laptop.## Access-Web UI: `https://dev-sandbox.tail6aeed8.ts.net` (Tailscale only — never+Web UI: `https://dev-sandbox.<your-tailnet>.ts.net` (Tailscale only — neverexposed via public DNS or Cloudflare). Auth is enforced by the`Tailscale-User-Login` header injected by `tailscale serve`; onlythe configured owner identity is admitted (set via `TAILSCALE_USER` env in the systemd unit).-SSH: `ssh dev-ts` (ec2-user, pem at `~/.ssh/dev-sandbox-2026-05-17.pem`,-Tailscale IP 100.109.217.31).+SSH: `ssh dev-ts` (ec2-user, pem at `~/.ssh/<your-key>.pem`, Tailscale IP+from `tailscale status`).## Systemd unitsdiff --git a/claude-ops/scripts/account-rotation/refresh-tokens.mjs b/claude-ops/scripts/account-rotation/refresh-tokens.mjsindex 57879638..b08deadb 100644--- a/claude-ops/scripts/account-rotation/refresh-tokens.mjs+++ b/claude-ops/scripts/account-rotation/refresh-tokens.mjs@@ -17,6 +17,7 @@import { appendFileSync, existsSync, readFileSync, writeFileSync, renameSync } from 'fs';import { join, dirname } from 'path';+import { userInfo } from 'os';import { fileURLToPath } from 'url';import { execFileSync, execSync } from 'child_process';import { fetchWithProxyFallback } from './proxy-helper.mjs';@@ -41,7 +42,7 @@ const LOG_PATH = join(__dirname, 'rotation.log');const NEEDS_REAUTH_PATH = join(__dirname, '.crs-token-refresher-state.json');const AUTOLOOP_STATE_PATH = join(__dirname, '.crs-magic-autoloop-state.json');const KEYCHAIN_SERVICE = 'Claude Code-credentials';-const KEYCHAIN_ACCOUNT = process.env.USER || '<USER>';+const KEYCHAIN_ACCOUNT = process.env.USER || process.env.LOGNAME || userInfo().username;const CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e';const TOKEN_ENDPOINT = 'https://platform.claude.com/v1/oauth/token';diff --git a/claude-ops/scripts/account-rotation/rotate.mjs b/claude-ops/scripts/account-rotation/rotate.mjsindex a20d720b..b454bf2d 100644--- a/claude-ops/scripts/account-rotation/rotate.mjs+++ b/claude-ops/scripts/account-rotation/rotate.mjs@@ -113,12 +113,12 @@ const KEYCHAIN_SERVICE = 'Claude Code-credentials';const ACTIVE_KEYCHAIN_ACCOUNT = 'unknown';const VAULT_KEYCHAIN_ACCOUNT = process.env.CLAUDE_ROTATOR_KEYCHAIN_ACCOUNT || process.env.USER || 'claude-ops';-// When Sam's canonical CLIProxyAPI checkout exists, browser reauth should write+// When a canonical CLIProxyAPI checkout exists, browser reauth should write// there directly. CLIProxyAPI owns the per-seat JSON schema and is the sole// refresh writer; translating Claude Code's keychain after OAuth creates a// second credential plane and was the source of "OAuth succeeded / rotation-// unverified" failures. All paths remain configurable for other installations.-const CLIPROXYAPI_DIR = process.env.CLIPROXYAPI_DIR || join(homedir(), 'Developer', 'active', 'cliproxyapi');+// unverified" failures. Set CLIPROXYAPI_DIR to point at your own checkout.+const CLIPROXYAPI_DIR = process.env.CLIPROXYAPI_DIR || join(homedir(), 'cliproxyapi');const CLIPROXYAPI_BINARY = process.env.CLIPROXYAPI_BINARY || join(CLIPROXYAPI_DIR, 'cli-proxy-api');const CLIPROXYAPI_CONFIG = process.env.CLIPROXYAPI_CONFIG || join(CLIPROXYAPI_DIR, 'config', 'config.yaml');const CLIPROXYAPI_AUTH_DIR =diff --git a/claude-ops/scripts/account-rotation/route-state.mjs b/claude-ops/scripts/account-rotation/route-state.mjsindex 4661facb..7e7519b8 100644--- a/claude-ops/scripts/account-rotation/route-state.mjs+++ b/claude-ops/scripts/account-rotation/route-state.mjs@@ -10,7 +10,19 @@ export const ROUTE_MODES = new Set(['crs-oauth', 'fail-closed']);// INVARIANT: ANTHROPIC_BASE_URL points at the CRS relay XNOR a cr_-prefixed// relay key in ANTHROPIC_API_KEY. Auth-token fields are reserved for the// launcher-created child environment and must not persist in settings.-const CRS_BASE_RE = /127\.0\.0\.1:(3000|3002|3005|8091|18091)|100\.87\.53\.96:8091|:(3000|3002|3005|8091|18091)\/api/;+// Extra hosts (e.g. a tailnet relay) can be added via OPS_RELAY_HOSTS as a+// comma-separated host:port list; nothing site-specific is hardcoded here.+const EXTRA_RELAY_HOSTS = (process.env.OPS_RELAY_HOSTS || '')+ .split(',')+ .map((h) => h.trim())+ .filter(Boolean)+ .map((h) => h.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));+const CRS_BASE_RE = new RegExp(+ ['127\\.0\\.0\\.1:(3000|3002|3005|8091|18091)']+ .concat(EXTRA_RELAY_HOSTS)+ .concat([':(3000|3002|3005|8091|18091)\\/api'])+ .join('|'),+);function currentCrsToken(env = {}) {return isCrsToken(env.ANTHROPIC_API_KEY) ? env.ANTHROPIC_API_KEY : '';diff --git a/claude-ops/scripts/crsproxy-reauth/bu_reauth.py b/claude-ops/scripts/crsproxy-reauth/bu_reauth.pyindex e0ecc2bb..f4537f4f 100644--- a/claude-ops/scripts/crsproxy-reauth/bu_reauth.py+++ b/claude-ops/scripts/crsproxy-reauth/bu_reauth.py@@ -2,7 +2,7 @@"""Browser Use Cloud Agent — OAuth re-auth for CRSProxy.Production-grade reauth script that uses Browser Use Cloud to automate-OAuth flows for Claude, xAI, and Codex providers on the healify-hub EC2.+OAuth flows for Claude, xAI, and Codex providers on the proxy host.Features:- Proper timeout handling on all Browser Use API calls (never hang).@@ -29,35 +29,35 @@ Features:Usage:# Full reauth for a Claude accountsudo -u crsproxy /opt/crsproxy/venv/bin/python /opt/crsproxy/bu_reauth.py \\- -provider claude -email [email protected] -gog-account [email protected]+ -provider claude -email [email protected] -gog-account [email protected]# Dry run (validates setup, no browser runs)sudo -u crsproxy /opt/crsproxy/venv/bin/python /opt/crsproxy/bu_reauth.py \\- -provider claude -email [email protected] -dry-run+ -provider claude -email [email protected] -dry-run# xAI reauthsudo -u crsproxy /opt/crsproxy/venv/bin/python /opt/crsproxy/bu_reauth.py \\- -provider xai -email <WORK_EMAIL> -gog-account <WORK_EMAIL>+ -provider xai -email [email protected] -gog-account [email protected]# Codex reauthsudo -u crsproxy /opt/crsproxy/venv/bin/python /opt/crsproxy/bu_reauth.py \\- -provider codex -email <WORK_EMAIL> -gog-account <WORK_EMAIL>+ -provider codex -email [email protected] -gog-account [email protected]# Validate an existing auth file (no reauth, no browser)sudo -u crsproxy /opt/crsproxy/venv/bin/python /opt/crsproxy/bu_reauth.py \\- -provider claude -email [email protected] -validate-only+ -provider claude -email [email protected] -validate-only# Validate and activate if validsudo -u crsproxy /opt/crsproxy/venv/bin/python /opt/crsproxy/bu_reauth.py \\- -provider claude -email [email protected] -validate-only -activate+ -provider claude -email [email protected] -validate-only -activate# Validate metadata only (skip canary request)sudo -u crsproxy /opt/crsproxy/venv/bin/python /opt/crsproxy/bu_reauth.py \\- -provider claude -email [email protected] -validate-only -skip-canary+ -provider claude -email [email protected] -validate-only -skip-canary- # Resume from a hCaptcha checkpoint (after Sam solved the captcha)+ # Resume from a hCaptcha checkpoint (after the operator solved the captcha)sudo -u crsproxy /opt/crsproxy/venv/bin/python /opt/crsproxy/bu_reauth.py \\- -provider claude -email [email protected] -checkpoint-resume+ -provider claude -email [email protected] -checkpoint-resume# When hCaptcha is detected, the script emits the live_view_url and waits.# After solving the captcha in the browser, create the trigger file:diff --git a/claude-ops/scripts/crsproxy-reauth/test_checkpoint.py b/claude-ops/scripts/crsproxy-reauth/test_checkpoint.pyindex c5f0f7fa..58070157 100644--- a/claude-ops/scripts/crsproxy-reauth/test_checkpoint.py+++ b/claude-ops/scripts/crsproxy-reauth/test_checkpoint.py@@ -37,8 +37,8 @@ def test_sanitize_url():def test_safe_email():"""safe_email redacts the local part of an email."""- result = bu_reauth.safe_email("[email protected]")- assert result == "i***@auroracapital.nl", f"Expected redacted email, got {result}"+ result = bu_reauth.safe_email("[email protected]")+ assert result == "i***@example.com", f"Expected redacted email, got {result}"result = bu_reauth.safe_email("[email protected]")assert result == "***@b.com", f"Expected redacted email, got {result}"print("PASS: safe_email redacts the local part of an email")diff --git a/claude-ops/scripts/daemon-services.default.json b/claude-ops/scripts/daemon-services.default.jsonindex 0a08202a..df9db38b 100644--- a/claude-ops/scripts/daemon-services.default.json+++ b/claude-ops/scripts/daemon-services.default.json@@ -20,7 +20,7 @@"pid_probe": "lsof -ti :8080 -sTCP:LISTEN 2>/dev/null | head -1","restart_delay": 60,"max_restarts": 10,- "_note": "Cross-platform bridge starter. Looks at uname: macOS → launchctl kickstart gui/$UID/com.${USER}.whatsapp-bridge ; Linux → systemctl --user restart whatsapp-bridge.service. Install via `bash scripts/install-whatsapp-bridge-linux.sh --wa-phone <E.164>` on Linux hosts; on macOS the legacy launchctl plist still applies. Bridge source: github.com/lharries/whatsapp-mcp (with claude-ops patches applied by install script — see scripts/whatsapp/apply-patches.py)."+ "_note": "Cross-platform bridge starter. Looks at uname: macOS \u2192 launchctl kickstart gui/$UID/com.${USER}.whatsapp-bridge ; Linux \u2192 systemctl --user restart whatsapp-bridge.service. Install via `bash scripts/install-whatsapp-bridge-linux.sh --wa-phone <E.164>` on Linux hosts; on macOS the legacy launchctl plist still applies. Bridge source: github.com/lharries/whatsapp-mcp (with claude-ops patches applied by install script \u2014 see scripts/whatsapp/apply-patches.py)."},"whatsapp-backfill": {"enabled": true,@@ -28,7 +28,7 @@"cron": "0 */2 * * *","restart_delay": 0,"max_restarts": 3,- "_note": "On-demand WhatsApp history backfill — POSTs to the bridge's /api/backfill endpoint added by claude-ops patches. Idempotent (whatsmeow dedups by message ID). On Linux installs the systemd timer `whatsapp-backfill.timer` (installed by the install script) is the primary trigger; this daemon entry is the fallback for hosts using the cron-driven claude-ops-daemon. Bridge auto-backfills 5s after every Connected event regardless."+ "_note": "On-demand WhatsApp history backfill \u2014 POSTs to the bridge's /api/backfill endpoint added by claude-ops patches. Idempotent (whatsmeow dedups by message ID). On Linux installs the systemd timer `whatsapp-backfill.timer` (installed by the install script) is the primary trigger; this daemon entry is the fallback for hosts using the cron-driven claude-ops-daemon. Bridge auto-backfills 5s after every Connected event regardless."},"memory-extractor": {"enabled": true,@@ -102,7 +102,7 @@"enabled": false,"command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-cron-marketing-autopilot.sh","cron": "0 8 * * *",- "_note": "Autonomous per-project daily ad optimization (Meta + Google Ads) — mandatory per-project daily_spend_cap_usd, cap pre-flight, deterministic pause of underperformers (keeps >= min_live_creatives), creative-fatigue -> regen, weekly synthesis. Disabled by default; first run is forced dry. Opt-in via /ops:setup marketing (autopilot block). Cron is UTC: 08:00 UTC ~= 10:00 Europe/Amsterdam."+ "_note": "Autonomous per-project daily ad optimization (Meta + Google Ads) \u2014 mandatory per-project daily_spend_cap_usd, cap pre-flight, deterministic pause of underperformers (keeps >= min_live_creatives), creative-fatigue -> regen, weekly synthesis. Disabled by default; first run is forced dry. Opt-in via /ops:setup marketing (autopilot block). Cron is UTC: 08:00 UTC ~= 10:00 Europe/Amsterdam."},"marketing-autopilot-calibrate": {"enabled": false,@@ -132,13 +132,19 @@"enabled": false,"cron": "0 10 * * 1","command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-cron-email-draft.sh",- "_note": "Weekly email draft generator (Monday 10:00 UTC). Drafts Klaviyo flow variants + next Resend broadcast via Claude. NEVER auto-sends — all drafts require per-message approval (Rule 6). Enable per project by setting marketing.projects.<key>.email_marketing.enabled=true + brand.voice in prefs."+ "_note": "Weekly email draft generator (Monday 10:00 UTC). Drafts Klaviyo flow variants + next Resend broadcast via Claude. NEVER auto-sends \u2014 all drafts require per-message approval (Rule 6). Enable per project by setting marketing.projects.<key>.email_marketing.enabled=true + brand.voice in prefs."},"content-social-calendar": {"enabled": false,"cron": "0 11 * * 1","command": "${CLAUDE_PLUGIN_ROOT}/scripts/ops-cron-social-calendar.sh",- "_note": "Weekly social post calendar generator (Monday 11:00 UTC). Generates 5 LinkedIn + 5 X + 5 Instagram posts per project. NEVER auto-publishes — drafts require per-message approval (Rule 6). Enable per project by setting marketing.projects.<key>.social.enabled=true + brand.voice in prefs."+ "_note": "Weekly social post calendar generator (Monday 11:00 UTC). Generates 5 LinkedIn + 5 X + 5 Instagram posts per project. NEVER auto-publishes \u2014 drafts require per-message approval (Rule 6). Enable per project by setting marketing.projects.<key>.social.enabled=true + brand.voice in prefs."+ },+ "update-check": {+ "enabled": true,+ "command": "${CLAUDE_PLUGIN_ROOT}/bin/ops-update-check --quiet",+ "cron": "17 9 * * *",+ "_note": "Detect-only daily check for a newer published plugin version. Writes ~/.claude/state/ops-update/update-available.json and exits 3 when an update exists. It never installs: applying stays a deliberate act via `ops-update`, so a background job can never swap the plugin out from under a running session. Off-hour minute avoids the :00 stampede."}}}diff --git a/claude-ops/scripts/hermes-linear/alignment_lib.py b/claude-ops/scripts/hermes-linear/alignment_lib.pyindex 5ccd739a..9022d6a9 100755--- a/claude-ops/scripts/hermes-linear/alignment_lib.py+++ b/claude-ops/scripts/hermes-linear/alignment_lib.py@@ -21,7 +21,7 @@ ENV_PATHS = ()DEFAULT_API = "http://127.0.0.1:18790"AURORA_COMPANY_ID = "c8435d96-f0c6-40c3-a6a0-53c0c5030707"-HEALIFY_COMPANY_ID = "32375bd0-2a89-4a27-ad4a-e2050459224b"+PRIMARY_COMPANY_ID = "32375bd0-2a89-4a27-ad4a-e2050459224b"CLAIM_TTL_SECONDS = 2 * 60 * 60META_RE = re.compile(diff --git a/claude-ops/scripts/hermes-linear/hea_linear_fix_all.py b/claude-ops/scripts/hermes-linear/hea_linear_fix_all.pyindex 17dcb281..26cce806 100755--- a/claude-ops/scripts/hermes-linear/hea_linear_fix_all.py+++ b/claude-ops/scripts/hermes-linear/hea_linear_fix_all.py@@ -94,7 +94,7 @@ MATERIAL_PREFIXES = (def personal_key() -> str:- return (os.environ.get("LINEAR_API_KEY") or os.environ.get("HEALIFY_LINEAR_API_KEY") or "").strip()+ return (os.environ.get("LINEAR_API_KEY") or os.environ.get("TEAM_LINEAR_API_KEY") or "").strip()def agent_token() -> str:diff --git a/claude-ops/scripts/hermes-linear/linear_paperclip_delegate_bridge.py b/claude-ops/scripts/hermes-linear/linear_paperclip_delegate_bridge.pyindex 9795f897..5918c7f2 100755--- a/claude-ops/scripts/hermes-linear/linear_paperclip_delegate_bridge.py+++ b/claude-ops/scripts/hermes-linear/linear_paperclip_delegate_bridge.py@@ -45,7 +45,7 @@ from typing import Any, Optionalsys.path.insert(0, str(Path(__file__).resolve().parent))from alignment_lib import ( # noqa: E402- HEALIFY_COMPANY_ID,+ PRIMARY_COMPANY_ID,PC_TO_LINEAR_STATE,add_comment,api_call,@@ -67,13 +67,13 @@ HOME = Path.home()STATE_PATH = HOME / ".hermes" / "state" / "linear_paperclip_delegate_bridge.json"LINEAR_GQL = "https://api.linear.app/graphql"DEFAULT_DELEGATE_USER_ID = "1972ae8f-ef08-422b-a172-1a728f86abf6"-HEALIFY_TEAM_ID = "7d9c9413-d41d-4226-a041-f935c8d492df"+PRIMARY_TEAM_ID = "7d9c9413-d41d-4226-a041-f935c8d492df"# HEA inbound Linear→Paperclip: Agent Qiubo routes/owns (Sam 2026-07-19)HEA_INBOUND_ASSIGNEE_AGENT_ID = "b33501c1-1cc6-4e44-810c-66cc1f684f2d"HEA_INBOUND_ASSIGNEE_NAME = "Agent Qiubo"TEAM_TO_COMPANY = {- "HEA": HEALIFY_COMPANY_ID,+ "HEA": PRIMARY_COMPANY_ID,"MES": "71380d2a-b29e-48fc-8f10-49a8df8b2e46","DUTCH": "c4e2ebdd-351c-4bf0-9d96-4c22147ad85d","INB": "6ef96e49-0728-4170-bd2f-13c6b8bdce25",@@ -83,12 +83,12 @@ TEAM_TO_COMPANY = {# Optional company → inbound router agent (only HEA for now)INBOUND_ROUTER_AGENT = {- HEALIFY_COMPANY_ID: HEA_INBOUND_ASSIGNEE_AGENT_ID,+ PRIMARY_COMPANY_ID: HEA_INBOUND_ASSIGNEE_AGENT_ID,}# Paperclip company → Linear teamCOMPANY_TO_TEAM = {- HEALIFY_COMPANY_ID: ("HEA", HEALIFY_TEAM_ID),+ PRIMARY_COMPANY_ID: ("HEA", PRIMARY_TEAM_ID),"71380d2a-b29e-48fc-8f10-49a8df8b2e46": ("MES", "4e5dd03a-1015-4506-b6d0-b408b02ed7c2"),"c4e2ebdd-351c-4bf0-9d96-4c22147ad85d": ("DUTCH", "dd6deb04-63ac-43ae-b90b-6a59cc22d8fd"),"6ef96e49-0728-4170-bd2f-13c6b8bdce25": ("INB", "58cd5b2c-fb32-4c65-9558-db0346094883"),@@ -126,7 +126,7 @@ def agent_user_id() -> str:def personal_key() -> str:return (os.environ.get("LINEAR_API_KEY", "").strip()- or os.environ.get("HEALIFY_LINEAR_API_KEY", "").strip()+ or os.environ.get("TEAM_LINEAR_API_KEY", "").strip())@@ -295,7 +295,7 @@ def desired_linear_label_ids(pc_ident: str, lin: dict) -> tuple[Optional[list[st"""Compute Linear labelIds: keep current + add mapped PC labels.Additive for product taxonomy. Exception: strip banned priority/security-noise- labels (Priority:*, P1, priority-*, Security - Healify) so they cannot return.+ labels (Priority:*, P1, priority-*, Security - <company>) so they cannot return.Returns (label_ids_or_None_if_no_change, note)."""try:@@ -795,7 +795,7 @@ SELECT json_agg(row_to_json(t)) FROM (continueif r.get("marked"):out.append(r)- elif include_unlinked_open and r.get("company_id") == HEALIFY_COMPANY_ID:+ elif include_unlinked_open and r.get("company_id") == PRIMARY_COMPANY_ID:out.append(r)if len(out) >= limit:break@@ -1191,7 +1191,7 @@ def sync_pair(return eventslin_uuid = lin["id"]team = (lin.get("team") or {})- team_id = team.get("id") or HEALIFY_TEAM_ID+ team_id = team.get("id") or PRIMARY_TEAM_IDteam_key = (team.get("key") or lin_ident.split("-")[0]).upper()cur_type = ((lin.get("state") or {}).get("type") or "").lower()cur = ((lin.get("state") or {}).get("name") or "")@@ -1563,7 +1563,7 @@ def main() -> int:created_ids.append(m.group(1))state.setdefault("seen", {})[n.get("identifier")] = {"at": now_iso(), "event": ev}# Cost guard: at most ONE Qiubo wakeup per full-sync tick after batch creates- if created_ids and not args.dry_run and HEALIFY_COMPANY_ID in INBOUND_ROUTER_AGENT:+ if created_ids and not args.dry_run and PRIMARY_COMPANY_ID in INBOUND_ROUTER_AGENT:wcode, wresp = wakeup_agent(HEA_INBOUND_ASSIGNEE_AGENT_ID,reason=f"inbound-linear-batch:{len(created_ids)}:{','.join(created_ids[:5])}",diff --git a/claude-ops/scripts/hermes-linear/paperclip_linear_mirror.py b/claude-ops/scripts/hermes-linear/paperclip_linear_mirror.pyindex 96f4ff0e..e77fdf7d 100755--- a/claude-ops/scripts/hermes-linear/paperclip_linear_mirror.py+++ b/claude-ops/scripts/hermes-linear/paperclip_linear_mirror.py@@ -21,7 +21,7 @@ from typing import Any, Optionalsys.path.insert(0, str(Path(__file__).resolve().parent))from alignment_lib import ( # noqa: E402- HEALIFY_COMPANY_ID,+ PRIMARY_COMPANY_ID,PC_TO_LINEAR_STATE,add_comment,canonical_paperclip_title,@@ -40,13 +40,13 @@ from alignment_lib import ( # noqa: E402HOME = Path.home()STATE_PATH = HOME / ".hermes" / "state" / "paperclip_linear_mirror.json"LINEAR_GQL = "https://api.linear.app/graphql"-HEALIFY_TEAM_ID = "7d9c9413-d41d-4226-a041-f935c8d492df"+PRIMARY_TEAM_ID = "7d9c9413-d41d-4226-a041-f935c8d492df"def linear_key() -> str:return (os.environ.get("LINEAR_API_KEY", "").strip()- or os.environ.get("HEALIFY_LINEAR_API_KEY", "").strip()+ or os.environ.get("TEAM_LINEAR_API_KEY", "").strip())@@ -248,7 +248,7 @@ def run_outbound(state: dict, dry_run: bool, limit: int) -> list[str]:# Cache Linear team workflow states per team key (HEA vs MES vs DUTCH …)states_by_team: dict[str, list[dict]] = {}# Always warm HEA as default- states_by_team["HEA"] = team_states(HEALIFY_TEAM_ID)+ states_by_team["HEA"] = team_states(PRIMARY_TEAM_ID)for row in rows:ident = row.get("identifier")code, issue = get_issue(ident)@@ -391,7 +391,7 @@ def inbound_agent_work(state: dict, dry_run: bool, limit: int) -> list[str]:}}"""- data = linear_gql(q, {"tid": HEALIFY_TEAM_ID, "n": limit})+ data = linear_gql(q, {"tid": PRIMARY_TEAM_ID, "n": limit})if data.get("errors"):# label may not exist yet — soft failevents.append(f"inbound: Linear query note: {data['errors']}")@@ -436,7 +436,7 @@ LIMIT 3;if dry_run:events.append(f"DRY inbound create Paperclip for {lin}: {title[:80]}")continue- code, resp = create_issue(HEALIFY_COMPANY_ID, title, desc, priority="medium", status="todo")+ code, resp = create_issue(PRIMARY_COMPANY_ID, title, desc, priority="medium", status="todo")if code in (200, 201) and isinstance(resp, dict):pc_id = resp.get("identifier") or resp.get("id")events.append(f"inbound created {pc_id} for {lin}")diff --git a/claude-ops/scripts/ops-accounts/providers/factory.mjs b/claude-ops/scripts/ops-accounts/providers/factory.mjsindex 8be07648..bce13c57 100644--- a/claude-ops/scripts/ops-accounts/providers/factory.mjs+++ b/claude-ops/scripts/ops-accounts/providers/factory.mjs@@ -42,7 +42,7 @@ export async function listAccounts(ctx) {lastError: blocked ? snap?.vendor_detail || 'HTTP 402 no active paid subscription' : snap?.error || null,billing: snap?.billing_mail_hint || null,http: snap?.http || null,- note: 'Two orgs in Gmail (GGDXNY Sam Org / DGPBWS Healify); feeder probes one FACTORY_API_KEY',+ note: 'Multiple orgs can share one mailbox; the feeder probes a single FACTORY_API_KEY',reauth: { status: 'unavailable', note: 'pay invoice / restore Factory billing; no OAuth cascade' },},];diff --git a/claude-ops/skills/humanizer/ATTRIBUTION.md b/claude-ops/skills/humanizer/ATTRIBUTION.mdnew file mode 100644index 00000000..83e07453--- /dev/null+++ b/claude-ops/skills/humanizer/ATTRIBUTION.md@@ -0,0 +1,29 @@+# Attribution for the humanizer skill++## What is borrowed++The taxonomy of AI writing tells in `SKILL.md` follows the categories and observations set out in+[Wikipedia:Signs of AI writing](https://en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing),+maintained by WikiProject AI Cleanup. Wikipedia text is licensed+[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/).++## What is not borrowed++No prose, no "words to watch" list, and no before/after example was copied from that page. Every+sentence and every example in `SKILL.md` was written for this repository. What carries over is the+set of ideas, which CC BY-SA does not restrict, together with the credit above, which it earns.++That distinction is deliberate. CC BY-SA 4.0 is a share-alike licence and this repository ships+under MIT. Copying Wikipedia prose into an MIT-licensed file would create a licence conflict. Using+the ideas and crediting the source does not.++## If you extend this skill++Do not paste Wikipedia text in. Describe the pattern in your own words, write your own example, and+leave the credit above intact.++## Related prior art++[blader/humanizer](https://github.com/blader/humanizer) (MIT) packages the same Wikipedia guidance+as a standalone agent skill and is where the idea of doing so came from. The file in this directory+is an independent implementation, not a fork or a copy of it.diff --git a/claude-ops/skills/humanizer/SKILL.md b/claude-ops/skills/humanizer/SKILL.mdnew file mode 100644index 00000000..49666152--- /dev/null+++ b/claude-ops/skills/humanizer/SKILL.md@@ -0,0 +1,498 @@+---+name: humanizer+description: Strip the tells of AI-generated writing out of a draft so it reads as if a person wrote it. Use before any text leaves the machine (email, PR body, commit message, doc, landing copy, release note), or when the owner says "humanize this", "this reads like ChatGPT", "make it sound human". Detects inflated significance, promotional tone, participle padding, vague attribution, em dashes, rule of three, AI vocabulary, negative parallelism, sycophancy, and filler, then rewrites without inventing facts.+argument-hint: '[pasted text | path/to/file.md]'+allowed-tools:+ - Read+ - Write+ - Edit+ - Grep+effort: low+maxTurns: 15+---++# /ops:humanizer++You are an editor. Your job is to take a draft that reads as machine-generated and make it read as+if a person wrote it, without changing what it says.++Two failure modes, equally bad. Leaving the tells in. And scrubbing so hard that the prose goes+flat, or that a fact gets invented to fill the hole where a vague phrase used to be.++## The rules that outrank everything else++1. **Never invent.** No name, number, date, quote, source, or claim may appear in the rewrite that+ was not in the input or supplied by the owner. Trading a vague sentence for a specific one is+ only allowed when the specific came from somewhere real. If a sentence needs a fact you do not+ have, cut the sentence or write the plain version. A fabrication is a defect even when it reads+ better. (Fiction is the exception; there, invention is the assignment.)+2. **Keep the information, drop the shape.** Every claim survives. Paragraph structure, ordering,+ and length do not have to. Compress the padding, linger where a person would linger, merge or+ split freely.+3. **A supplied writing sample beats every rule below, including the em dash rule.** See Voice+ calibration.+4. **Rule 6 still applies.** If the text is an outbound message, humanizing it does not approve it.+ Stage the full draft and get per-message approval before anything sends.++## Invocation modes++**Pasted text (default).** Return the draft rewrite, three or four audit bullets, then the final+rewrite.++**File mode.** The owner points at a path. Read it, run the loop internally, write the final+version back in place. Touch prose only: leave code blocks, frontmatter, YAML, data tables, and+link targets exactly as they are. In chat, report what changed, not the whole file.++**Embedded mode.** Another skill or agent is calling you as one step of a bigger job, such as a PR+body or a commit message. Output the final text and nothing else. No draft, no audit, no summary.+The caller wants prose, not ceremony.++## The loop++1. Read the input. Mark every hit against the pattern list.+2. Write a **draft rewrite**. Read it back aloud in your head. Sentence lengths should vary. Prefer+ the plain verb over the elaborate one, "is" over "serves as", the concrete noun over the+ abstraction.+3. Ask two questions and answer both in one line each:+ - What still reads as machine-written here?+ - Does the rewrite assert anything that was not in the source?+4. Produce the **final rewrite** that fixes both. Before you hand it over, search it for `—` and+ `–`. A hit means you are not finished.++## Voice calibration++If the owner supplies a sample of their own writing, read it before you rewrite anything. Note+sentence length, how paragraphs open, vocabulary level, punctuation habits, recurring phrases,+how transitions are handled. Then match those habits rather than merely deleting tells. Do not+upgrade their casual word choices. Do not regularise a quirk they clearly meant.++Without a sample, use the defaults below.++Register decides how much personality is correct. Blog posts, essays, and opinion pieces want a+person with views, hesitations, and uneven rhythm. Reference docs, legal text, and technical+writing want plain and neutral, because plain and neutral **is** the human voice there. Injecting+first person into an API reference is its own kind of tell.++## Content patterns++### 1. Manufactured significance++Watch for: stands as, serves as, is a testament to, played a crucial/pivotal/vital role, marks a+turning point, underscores the importance of, reflects a broader, part of a wider shift, cemented+its place, left a lasting mark, paved the way for.++The model inflates an ordinary fact by asserting that it represents something larger. Usually the+larger thing is unsourced.++> Before: The scheduler was rewritten in 2021, marking a pivotal moment in the platform's evolution+> and reflecting a broader industry shift toward event-driven design.+>+> After: The scheduler was rewritten in 2021 to be event-driven.++### 2. Notability padding++Watch for: widely recognised, has been featured in, garnered attention from, an active presence on,+praised by industry leaders, a leading voice in.++Lists of outlets and follower counts stand in for saying what the thing actually is. Keep one+mention if the source gives real context for it. Drop the list. Do not invent the context.++> Before: The tool has been covered by several major technology publications and maintains an+> active community of over 40,000 developers.+>+> After: The tool is used by about 40,000 developers.++### 3. Participle padding++Watch for clauses trailing off the end of a sentence: highlighting..., underscoring...,+reflecting..., ensuring..., fostering..., showcasing..., contributing to..., encompassing...++These add length and the appearance of analysis while asserting nothing checkable.++> Before: The cache sits between the API and the database, reducing latency and ensuring a smoother+> experience for end users, reflecting the team's focus on performance.+>+> After: The cache sits between the API and the database. Reads that hit it return in under 5ms.++### 4. Brochure voice++Watch for: boasts, vibrant, rich (figurative), seamless, robust, powerful, cutting-edge,+best-in-class, nestled, in the heart of, breathtaking, must-have, unlock, elevate, empower.++The model cannot hold a neutral tone when describing anything it has decided is good.++> Before: Nestled in a vibrant part of the stack, the router offers a seamless and powerful+> experience for developers of all levels.+>+> After: The router matches paths to handlers. It has no configuration file.++### 5. Attribution to nobody++Watch for: experts say, industry observers note, it is widely believed, critics argue, studies+suggest, many have pointed out.++An opinion gets hung on an authority that is never named. Name the real source or cut the claim.+Never invent a source to make a sentence look grounded.++> Before: Experts believe the approach offers significant advantages over polling.+>+> After: The approach avoids the fixed cost of a polling interval. (Say who found that, if the+> source says.)++### 6. The bolt-on challenges section++Watch for: Despite its success, X faces several challenges; Despite these challenges; Looking+ahead; Future outlook; Challenges and opportunities.++Formulaic sections that exist because the outline demanded one, not because there was content.++> Before: Despite its adoption, the format faces challenges common to open standards, including+> fragmentation and inconsistent tooling. Despite these challenges, it continues to see steady+> growth.+>+> After: Tooling support is inconsistent. Two of the four major parsers reject nested arrays.++## Language patterns++### 7. AI vocabulary++High-frequency giveaways: delve, leverage (verb), utilise, robust, seamless, crucial, pivotal, key+(adjective), landscape (abstract), tapestry, realm, testament, underscore (verb), foster,+facilitate, enhance, streamline, holistic, nuanced, intricate, myriad, plethora, comprehensive,+align with, resonate with.++Any one of these is nothing. Three in a paragraph is a signature. They travel in packs.++> Before: The framework leverages a robust plugin architecture to facilitate a seamless developer+> experience across a diverse landscape of use cases.+>+> After: Plugins are loaded from a directory at startup. The same plugin works in the CLI and the+> server.++### 8. Copula avoidance++Watch for: serves as, functions as, represents, constitutes, stands as, boasts, features, offers.++Elaborate substitutes for "is" and "has". Almost always the plain verb is better.++> Before: The config file serves as the single source of truth and features three top-level+> sections.+>+> After: The config file is the single source of truth. It has three top-level sections.++### 9. Negative parallelism and tailing negations++Watch for: not just X, but Y; it is not merely A, it is B; X is not about Y, it is about Z. Also+the clipped fragment tacked onto a sentence end: no guesswork, no surprises, no config needed.++> Before: This is not just a linter, it is a way of thinking about code. Errors point at the exact+> line, no guessing.+>+> After: The linter reports the exact line and column of each error.++### 10. Rule of three++Three items appear because three sounds complete, not because there are three things.++> Before: The release brings faster builds, better error messages, and improved documentation.+>+> After: Builds are about 40% faster. Error messages now include the failing file path.++### 11. Synonym cycling++The model's repetition penalty pushes it to rename the same thing every time it appears.++> Before: The parser reads the file. The reader then validates the structure. The component finally+> emits the tree.+>+> After: The parser reads the file, validates the structure, and emits the tree.++### 12. False ranges++"From X to Y" where X and Y are not endpoints of any actual scale.++> Before: The plugin handles everything from authentication to the subtleties of cache invalidation.+>+> After: The plugin handles authentication and cache invalidation.++### 13. Hidden actors++Passive voice and subjectless fragments that omit who does the thing.++> Before: No configuration is required. Results are persisted automatically.+>+> After: You do not need to configure anything. The daemon writes results to disk after each run.++## Style patterns++### 14. Em dashes and en dashes: cut all of them++The final rewrite contains no `—` and no `–`. This is a hard constraint, not a preference, because+the em dash is the single most reliable tell in circulation. Also catch the spaced variant ` — `+and the double hyphen ` -- ` used the same way.++Replace, in order of preference: a full stop, a comma, a colon, brackets, or restructure.++> Before: The migration ran overnight — nobody noticed — and the old table was dropped the next+> morning.+>+> After: The migration ran overnight. Nobody noticed, and the old table was dropped the next+> morning.++One exception: a supplied writing sample that uses em dashes. Match the sample.++### 15. Mechanical boldface++Bolding key phrases at a steady rate because emphasis looks thorough.++> Before: It combines **static analysis**, **runtime tracing**, and a **rules engine**.+>+> After: It combines static analysis, runtime tracing, and a rules engine.++### 16. Bold-header bullet lists++Every bullet opens with a bolded label and a colon, and the sentence after it restates the label.++> Before:+>+> - **Performance:** Performance has been improved through better caching.+> - **Security:** Security has been strengthened with encryption at rest.+>+> After: Caching cut median response time to 80ms, and data at rest is now encrypted.++### 17. Title case headings++`## Getting Started With Plugins` is chatbot formatting. `## Getting started with plugins` is how+people write headings.++### 18. Decorative emoji++Emoji as bullet markers, section icons, or status prefixes. Cut them. Keep an emoji only where it+carries meaning the words do not, which is almost never in written work.++### 19. Curly quotes++Straight quotes in anything destined for a terminal, a config, or a code block. Curly quotes alone+are weak evidence, because editors insert them automatically, but they are worth normalising.++## Chat artefacts++### 20. Assistant leftovers++Watch for: Certainly!, Of course!, Great question!, I hope this helps, Let me know if you would+like me to expand, Would you like me to, Here is a, Feel free to.++Correspondence with a chatbot pasted in as if it were content.++> Before: Here is an overview of the deployment process. I hope this helps! Let me know if you want+> me to go deeper on any step.+>+> After: Deployment runs in three stages: build, canary, and full rollout.++### 21. Cutoff disclaimers and speculative filling++Watch for: as of my last update, based on available information, while specific details are+limited, it is likely that, it is believed that, maintains a low profile, prefers to stay out of+the public eye.++Two related tells. The model states its own ignorance in the copy, then invents plausible filler to+cover the gap. Say what is not known, or cut the sentence. Do not dress a guess as a fact.++> Before: While specific details about the outage are limited, it likely stemmed from a+> configuration change during the maintenance window.+>+> After: The cause of the outage is not recorded in the incident notes.++### 22. Sycophancy++Watch for: Great question, You are absolutely right, That is an excellent point, Fantastic+observation.++> Before: Great question! You are absolutely right that caching is tricky here.+>+> After: Caching is tricky here because the key depends on request headers.++## Filler and hedging++### 23. Filler phrases++- in order to → to+- due to the fact that → because+- at this point in time → now+- in the event that → if+- has the ability to → can+- it is important to note that → (delete)+- it is worth mentioning that → (delete)+- a wide variety of → many, or a number++### 24. Stacked hedges++> Before: It could potentially be argued that the change may have had some impact on throughput.+>+> After: The change may have affected throughput. (Or state the measured number.)++### 25. Upbeat send-offs++Closing paragraphs that say nothing: the future looks bright, exciting times ahead, a major step in+the right direction, watch this space.++Cut them. End on the last concrete fact. If the source names real plans, use those instead.++### 26. Uniform hyphenation++The model hyphenates compounds everywhere. People hyphenate them before a noun and usually drop the+hyphen after one.++> Before: The team is cross-functional and the report is high-quality.+>+> After: The team is cross functional and the report is high quality. (A cross-functional team and+> a high-quality report keep their hyphens.)++### 27. Authority tropes++Watch for: the real question is, at its core, fundamentally, what really matters, the deeper issue,+the heart of the matter, in reality.++These promise a cut through the noise and then deliver an ordinary point with ceremony attached.++> Before: The real question is whether the team can adapt. At its core, what matters is readiness.+>+> After: Whether the team can adapt depends on how much of the old workflow they have to unlearn.++### 28. Signposting++Watch for: let us dive in, let us break this down, here is what you need to know, now let us look+at, without further ado, in this section we will.++Announcing the writing instead of doing the writing.++> Before: Let us dive into how retries work. Here is what you need to know.+>+> After: Retries use exponential backoff starting at 200ms, capped at five attempts.++### 29. Warm-up sentences under headings++A heading, then a one-line paragraph that restates the heading, then the actual content. Delete the+middle one.++> Before:+>+> ## Performance+>+> Speed matters.+>+> Pages over 400ms lose about a third of their visitors.+>+> After:+>+> ## Performance+>+> Pages over 400ms lose about a third of their visitors.++### 30. Diff-anchored prose++Documentation written as a narration of the change rather than a description of the thing. Unless+the document is version-scoped by nature (changelog, release note, migration guide), it should read+correctly to someone who has never seen the previous version.++> Before: This function replaces the old loop, which was O(n²).+>+> After: This function uses a hash map, so lookups are O(1).++### 31. Manufactured punchlines++Every sentence engineered to land, then short fragments stacked for drama. One short sentence for+emphasis is fine. Four in a row is a tell.++> Before: Then the new index landed. No more full scans. No more timeouts. The old assumptions were+> gone.+>+> After: The new index removed the full table scans, and the queries that used to time out now+> return in about 30ms.++### 32. Aphorism formulas++Watch for: X is the Y of Z, X is not a tool but a mirror, the language of, the currency of, the+architecture of, X becomes a trap.++An ordinary claim rewritten as a quotable line, losing precision on the way. Replace the formula+with the claim it was gesturing at.++> Before: Documentation is the currency of trust in an engineering team.+>+> After: People stop trusting a service when its docs are wrong twice.++### 33. Fake-candid openers++Watch for standalone: Honestly?, Look,, Here is the thing, The thing is, Let us be honest, Real+talk. The tell is the theatrical pause before an unremarkable point. Someone actually being candid+just says the thing.++> Before: Is it worth migrating? Honestly? It depends on how much custom middleware you have.+>+> After: Whether it is worth migrating depends on how much custom middleware you have.++## What not to flag++A careful human writer hits several of the patterns above with no machine involved. Before you+start cutting, check that you are not gutting real prose. None of these is evidence on its own:++- Clean grammar and consistent style. Editing exists.+- Mixed casual and formal register. That is a person in a technical field, not a chatbot.+- Dry, plain prose. Machine prose has specific tells. Dryness without them is just dry.+- Formal vocabulary in general. The model overuses a specific set of fancy words, not all of them.+ Leave "ostensibly" alone.+- One transition word. A single "however" is not a signature.+- Curly quotes on their own. Most editors insert them by default.+- One em dash on its own. Plenty of journalists use them heavily.+- One short emphatic sentence.+- Unsourced claims. Most writing is unsourced.+- Clean formatting. Templates produce that.+- A watched phrase inside a quotation, a title, a proper name, or an example where the phrase is+ being discussed rather than used. Never rewrite quoted material.++Look for clusters. One em dash means nothing. Em dashes plus rule of three plus "vibrant tapestry"+plus a Conclusion section is a confession.++## Signs a person wrote it++When these show up, lean toward leaving the text alone. Over-editing destroys exactly the things+that make writing sound human:++- Specific, odd, hard-to-fabricate detail. A real timestamp, a strange quote, the name of the+ script nobody remembers writing. Models round specifics off; people hoard them.+- Unresolved feelings. "I think this is right but it still bothers me and I cannot say why."+- Era-bound references. Slang and in-jokes that pin to a particular year and scene.+- Editorial choices the writer can defend. If they can say why they cut that paragraph, a person+ cut it.+- Sentence length that swings. Machine prose settles into an even mid-length cadence.+- Genuine asides and self-corrections. "(I keep wanting to write 'almost' here, but it was+ certain.)"++## Output contract++Pasted-text mode returns, in order: the draft rewrite, the audit bullets, the final rewrite, and+optionally a two-line summary of what changed.++File mode writes the final rewrite to the file and reports a short summary in chat.++Embedded mode returns the final text alone.++In every mode, before you return anything, grep the output for `—` and `–`.++## Attribution++The pattern taxonomy in this skill follows the structure and observations set out in+[Wikipedia:Signs of AI writing](https://en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing),+maintained by WikiProject AI Cleanup, which is published under+[CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/). That page is the origin of the+categories and of the underlying research across thousands of observed cases.++The wording, the examples, and the ordering here are original to this plugin and are covered by+the plugin's MIT licence. No prose or example text was copied from the Wikipedia page, so no+share-alike obligation attaches to this file. If you extend it, do not paste Wikipedia text in:+describe the pattern in your own words and keep the credit above.++The idea of packaging this as an agent skill comes from+[blader/humanizer](https://github.com/blader/humanizer) (MIT). This is an independent+implementation, not a copy of it.diff --git a/claude-ops/skills/ops-comms/SKILL.md b/claude-ops/skills/ops-comms/SKILL.mdindex 9db0f528..4594377a 100644--- a/claude-ops/skills/ops-comms/SKILL.md+++ b/claude-ops/skills/ops-comms/SKILL.md@@ -175,6 +175,164 @@ Draft created for [recipient]:---+## Outbound judgment: verify before you assert++Rule 6 governs *whether* a message may go out. This section governs *whether the+message is right*. Every item below is a failure mode seen on a real run, where+the approval gate held and the content was still wrong.++### Research every load-bearing claim++Never state a fact in someone else's inbox from memory. A price, a date, an+availability, a "who currently holds X" all get a cheap check first: a search, the+actual thread, the calendar, the invoice.++**Claims about the recipient's own access get probed, not inferred.** Telling a+colleague their access is broken is a claim about a system you can inspect. A+wrong diagnosis sends a competent person chasing a non-problem, and they will+believe you because you appear to hold the admin view. Sort each access item into+fixed, never broken, or theirs, and say which. Telling someone "that already+works" stops them building a workaround for a permission they already have.++### Verify the join, not just the endpoints++The hardest fabrications are not invented facts, they are invented *relationships*+between two real things that share a name, an entity, or a keyword. Each half is+true, the sentence joining them is not, and it reads as diligence rather than a+guess.++"X should be coordinated with Y" is itself a factual claim and needs its own+evidence. A company or person appearing in two matters is weak evidence they are+the same workstream and often strong evidence of a naming coincidence. Be+especially suspicious of an advisory clause nobody asked for: the recipient asked+a yes or no question, and a "let's just align with..." rider is exactly where+invented linkage hides. When challenged on such a clause, probe and delete it+rather than rewording it into something defensible.++### Do not absorb the other party's job++An inbound message that mentions a task is not automatically a task for the user.+When the sender owns the workstream, a heads-up about their own work in progress+is not an instruction transferring that work.++Before staging any reply containing a first-person commitment ("I'll pick that+up", "I'll clean that up"), check whose function it is, who has the access, and+whether the commitment is even wanted. A message that only needs acknowledging+gets acknowledgement. Volunteering labour reads as helpful and creates real+obligations nobody tracks. When the work does need doing and the counterparty+owns it, name it and hand it back rather than quietly taking it on.++### Do not route a decision the counterparty already made++A narrow A/B to the user is right for a real trade-off and wrong when the+counterparty already supplied the answer inside the message being triaged.+An identifier a person gives for their **own** account (login, email, phone,+handle, bank account) is authoritative. A conflict with the admin view means the+estate is misconfigured, not that they misremembered their own account. Use the+probing to shape the message, not to defer. Escalate only when the action is+irreversible and expensive; two systems disagreeing is neither.++The tell that this rule was broken is a closing question to the user whose answer+is already quoted verbatim in the inbound message.++### A staged draft goes stale++A queue of drafts is researched at one moment and sent over hours. Any draft+referencing a pending external process (a bank instruction, a signature, a+shipment, a filing) must have that process re-checked immediately before the+send, not just at research time. A draft that correctly said "still waiting, no+news" became wrong when the counterparty's reply landed mid-queue.++Two consequences are easy to miss: the draft's central claim can flip outright,+and new inbound often creates a *second* outbound that also needs drafting.+Search results encountered mid-queue get triaged, not skimmed past.++**A parallel session may have already sent it.** Multiple agents can work the+same inbox and send under the same identity. Treat any outbound from the user's+own identity that this session did not write as another agent's work: verify its+claims at the source, report the item closed with that evidence, and move on. Do+not re-send, and do not assume it was correct just because it exists.++### A counterparty's restatement of your position is not authoritative++When someone replies "which of these did you mean?" or summarises your position+back before proceeding, do not pick the more plausible reading. Open what the+user actually sent and read their own words. A partner who guesses wrong and+proceeds on that guess can commit the user, in writing, to a different deal than+the one they proposed. Their politeness is not evidence; a soft hedge from a+competent counterparty is exactly where an unnoticed inversion lives.++### When the user contradicts your draft, check before defending it++Low-confidence pushback ("check, I think we already signed", "I might have+credentials too") is a hard stop and a research instruction, not a hedge to be+reassured about. Re-probe the primary source and come back with what it says,+including "partly, the mechanism is X not Y". Never defend a draft against the+user's own recollection without checking first.++### Do not trust an audit's verdict over primary evidence++A subagent audit is a research artifact, not a finding. Before acting on a+cancel-or-delete verdict, open one paid invoice and read the SKU, quantity,+billing address, and payment history. "No API key in the environment" does not+mean "unused": no-code SaaS runs entirely in a web UI. A "paused" or free-tier+notice may belong to an entirely different account than the paid plan.++### Reply to their message, not your parallel checklist++When the user says "just reply", answer only the inbound ask. Do not bolt on+extra forms, address updates, or multi-item checklists they did not ask for in+that draft. Extra tracks get a separate message after the send if still needed.+When the user corrects a draft to be shorter or more spoken, rewrite against+*their* wording, not a re-packaged version of your own.++### A work handover must match the tracker exactly++When a message tells someone what to work on, do not paraphrase the tracker.+Re-run the query and enumerate every open item in board order with identifier,+priority, and state. Vagueness is how items get silently dropped and how the+recipient invents their own ordering. If something is deliberately excluded, say+so and why rather than omitting it silently.++### Sequencing irreversible actions: preserve, verify, then destroy++When an action destroys an asset (a contact list, a mailbox, a dataset), order+the work export, then verify the export is real, then destroy. "Verify" means row+count and headers inspected against an expectation stated up front, so the check+is falsifiable. An export returning a few hundred rows from a plan holding tens+of thousands is a failed export that looks like a successful one. Split it across+two approvals: the export can run autonomously, the destroy waits for the user.++### Verify the send actually landed++Do not treat a send tool returning without an error as delivery. Confirm on the+channel: the outbound row appears in the thread, or the message carries the+`SENT` label. A `DRAFT` is not a delivery, and a broken sender alias can bounce+seconds later. If verification fails, do not archive; an unverified send is an+unanswered thread.++### Post-reply disposition, in the same step as the send++Every thread you reply to gets a disposition immediately. There is no "leave it+and see".++- **Ball in their court** — archive once the send is verified.+- **User still owes something** — snooze with a dated reminder naming the owed+ action and the thread, then archive. An unfulfilled commitment must never stay+ visible as a substitute for tracking it.+- **Unactionable or already answered** — archive.++Only threads genuinely waiting on the user's own next action stay in the inbox.++### Auto-resume the next staged outbound++After one item is approved, sent, verified, and dispositioned, stage the next+queue item automatically without waiting for "go" or "next". Stop only for the+per-draft approval itself, a real decision that is the user's to make, or a+blocker only a human can clear.++---+## Read flow: `read [channel]`**WhatsApp:**diff --git a/claude-ops/skills/ops-inbox/SKILL.md b/claude-ops/skills/ops-inbox/SKILL.mdindex d1782fa6..43df4f8d 100644--- a/claude-ops/skills/ops-inbox/SKILL.md+++ b/claude-ops/skills/ops-inbox/SKILL.md@@ -681,7 +681,7 @@ All channel credentials come from env vars or CLI auth — no hardcoded secrets.> - **"Verified done"** = the protected label has been removed, OR the thread was moved to a completion label (e.g. `Actioned`), OR the user explicitly says it's handled. Only then may it be archived. Archiving a still-todo-labeled email is a defect, not cleanup — surface it as a kept actionable item instead.> - This applies on every channel that exposes labels/flags (email today; extend to any future labeled channel). For label-less channels (WhatsApp/iMessage), the equivalent is "never archive a thread with a live unresolved action item" per rule 1.-1. **Archive everything that isn't a live action item.** FYI/noise/newsletters/bot channels, concluded threads, courtesy closes, reaction-only tails — and **WAITING** (you-sent-last) too. Archiving is reversible and WhatsApp/email **auto-resurface a chat the instant a new message lands**, so archiving WAITING loses nothing. The only things left visible after a run are genuine open **NEEDS_REPLY** items — including finance, legal, and personal threads, which are handled exactly like any other thread: draft the appropriate reply or take the required action, investigate as needed, and archive once fully handled. Nothing with a live unresolved action item gets archived regardless of category — **and per the HARD GUARDRAIL above, nothing carrying a todo/action label is archived until that task is verified done, even if it would otherwise classify as FYI/noise/WAITING.** All outbound sends on any thread — including finance, legal, and personal — still require per-message approval via the outbound-comms gate (Rule 6).+1. **Archive everything that isn't a live action item.** FYI/noise/newsletters/bot channels, concluded threads, courtesy closes, reaction-only tails — and **WAITING** (you-sent-last) too. Archiving is reversible, so archiving WAITING is the right default. Do not lean on auto-resurface as the safety net: on WhatsApp a new inbound can land in an archived chat without flipping `chats.archived` back to 0. Protect anything time-sensitive with a scheduled reminder, and re-query the horizon at the end of the pass. The only things left visible after a run are genuine open **NEEDS_REPLY** items — including finance, legal, and personal threads, which are handled exactly like any other thread: draft the appropriate reply or take the required action, investigate as needed, and archive once fully handled. Nothing with a live unresolved action item gets archived regardless of category — **and per the HARD GUARDRAIL above, nothing carrying a todo/action label is archived until that task is verified done, even if it would otherwise classify as FYI/noise/WAITING.** All outbound sends on any thread — including finance, legal, and personal — still require per-message approval via the outbound-comms gate (Rule 6).2. **After you reply to anyone, IMMEDIATELY archive that chat** — reply→archive is one atomic step. Never leave a just-answered thread sitting in the list.3. **`include_context: true` is the HARD DEFAULT on every `list_messages` read.** Never pass `false` — you must always see the surrounding thread to understand what a message is about before classifying or drafting.4. **Verify the bridge is FULLY up before trusting any classification** — run `wa-inbox-fresh.sh`, confirm the systemd unit is `active` and `:8080` LISTEN, and do a real read. A stale store mis-classifies last-sender.@@ -959,14 +959,40 @@ If either exists: do **not** send. Rebuild or drop the draft. Never double-respoThis does not change Rule 6's underlying send gate (stage → show full draft → explicit approval → send → next) — it makes explicit exactly how that gate is implemented: full draft + reasoning printed inline in chat first, then one `AskUserQuestion` with a short `preview`, options `[Send]`/`[Edit]`/`[Skip]`.+## Core principle: TRIAGE IS NOT THE DELIVERABLE — WORK THE QUEUE++Archiving the noise and staging one draft is a fraction of the job. The remaining+drafts are still owed. The characteristic failure is a pass that archives most of+the inbox, stalls on its first approval, and leaves a stack of researched drafts+that were never presented. The inbox looks clean and almost nothing was answered.++- **Work the full draft queue**, one approval at a time, until it is empty or the+ user stops you. A staged draft that is never shown is the same as no draft.+- **Re-scan before declaring done.** A long triage pass takes real time and new+ mail lands during it, so the count at the end is not the count from the start.+ Re-run the scan and fold in anything newer than your working cutoff.+- **Answer "are you done?" with the real number**, including what was never+ staged. An honest partial beats a confident summary of the finished part.+- **Give each replied thread its disposition immediately.** Archive when the ball+ is in their court, snooze with a dated reminder when the user still owes+ something. Never leave an answered thread sitting in the inbox.+## Core principle: SNOOZE & FOLLOW-UP INTELLIGENCE (never let the user lose a thread)-Cleanup must never silently drop something the user still owes or is owed. Archiving WAITING is safe **only** because new inbound auto-resurfaces it — but a thread where the ball is in the user's court, or where the other side has gone quiet on something the user needs, must be **snoozed with a reminder**, not just archived-and-forgotten.+Cleanup must never silently drop something the user still owes or is owed. A thread where the ball is in the user's court, or where the other side has gone quiet on something the user needs, must be **snoozed with a reminder**, not just archived-and-forgotten.++**Do not treat "their reply will resurface it" as evidence.** On WhatsApp a new+inbound can land in an archived chat without flipping `chats.archived` back to 0,+so an archived thread is not guaranteed to reappear when they answer. Archiving+WAITING is still the right default, but the safety net is the reminder you+schedule, not the resurface behaviour. Re-query the source horizon before final+classification and inspect every message newer than your cutoff, including+messages in chats you already archived this pass.When cleaning up, classify each non-NEEDS_REPLY item one more level:- **USER-OWES (todo)** — the user promised an action ("ik pak het vanavond op", "I'll resend the env file", "stuur ik je"), or a meeting-note / email assigned the user a task. → **KEEP visible** and schedule a follow-up reminder. Never archive an unfulfilled user commitment.-- **AWAITING-OTHER, time-sensitive** — the user is waiting on a reply tied to a deadline/deal. → archive (auto-resurfaces) **but** set a nudge reminder if no response by a sensible horizon (default 3 days) so the user can chase.+- **AWAITING-OTHER, time-sensitive** — the user is waiting on a reply tied to a deadline/deal. → archive **but** set a nudge reminder if no response by a sensible horizon (default 3 days) so the user can chase. The reminder is what protects this item, not the archive behaviour.- **CONCLUDED** — courtesy close, social tail, fully-answered. → archive, no reminder.**Scheduling reminders (a safe, non-outbound chore — do autonomously):** use `CronCreate` (one-shot, `recurring:false`) for each USER-OWES / nudge item. The reminder prompt should name the contact, the owed action, and the source thread, e.g. *"Reminder: you told <contact-A> you'd handle <contact-B>'s email tonight — follow up (WhatsApp <number>)."* Pick a sensible fire time (same evening for "tonight", +3d for nudges). Reminders fire to the user; they are NOT outbound third-party comms, so no approval gate applies.@@ -1132,11 +1158,19 @@ Per thread, you MUST:2. **Read ≥20 messages in BOTH directions before classifying.** Fetch at least 20 messages including BOTH inbound AND the user's own outbound (`is_from_me` / SENT / `Me:`), INCLUDING any `[voice]` transcripts. Never read only the last message, the last-direction flag, or a shallow window. The `last_is_from_me` / last-sender first pass is ONLY a first pass — it does not satisfy this gate. On WhatsApp, fetch/read the merged thread from step 1 (both JIDs), not one chat alone.+ **Deduplicate the merged thread by message ID first.** The phone and `@lid` mirrors routinely store the same message twice, once per JID, with identical IDs and timestamps that may differ only by timezone rendering. Counting those duplicates toward the 20-message minimum reads half the history while looking complete, and picking the "last" row without deduplicating can invert who actually spoke last.++ **A short thread that you have read completely satisfies this rule.** If the verified merged thread holds fewer than 20 messages, say so explicitly and classify. A complete short thread is not a blocker.++ **Transcribe load-bearing outbound voice notes, not just inbound ones.** A newer voice note from the user can resolve several preceding text asks while its `content` is still empty in the store. Classify from the transcript rather than from the last visible text or a stale `last_message_time`.+3. **Reconcile outbound the store may be missing.** The user often replies from their phone or by voice, and historic sends weren't always persisted. Before trusting "they sent last", check:- **`[voice]` transcripts** — a `[voice] …` body is the sender's words; read it as a real message in both directions.- **The bridge send-log** — `journalctl --user -u whatsapp-bridge.service --no-pager | grep "Received request to send message"` surfaces outbound `/api/send` calls that pre-#404 were NOT written to `messages.db`. If the user sent there, the thread is answered.- **The SAME contact's sends in OTHER threads/groups and other channels** — the user may have answered the same person in a group, on a secondary number, or via email/iMessage. Search the contact/topic across threads and channels (`mcp__whatsapp__list_messages {query, limit: 25}`, cross-channel search).+3b. **Enrich load-bearing media without breaking read-only mode.** When a message's stored content is empty and the media is what the thread turns on, use a read-only download and inspect the artifact directly: extract the document, transcribe the audio locally, sample representative video frames. Bound every download and transcription with a per-item timeout so one stale media URL cannot stall the batch. During an analytical (read-only) pass, do not run enrichment jobs that write transcripts, metadata, or read state back into the message store; if load-bearing media cannot be read, report it as an explicit blocker rather than guessing at the content.+4. **Write a 2-sentence conversation-arc summary proving comprehension** — who said what, and what is actually pending right now. If you cannot write it, you have NOT read enough: read more messages; do NOT classify.5. **Mark NEEDS_REPLY ONLY if the last INBOUND message is genuinely unanswered** after steps 2–4. If the user already replied ANYWHERE — including phone-sent or voice messages that may be ABSENT from the companion store — it is WAITING or HANDLED, never NEEDS_REPLY. **Trust the user's word over the store**: if the user says they answered, they answered, even if the store doesn't show it.@@ -1749,6 +1783,35 @@ If `bin/ops-discord` exits 1 with `{"error":"no discord credential configured---+## Critical pitfalls++These are failure modes seen on real runs, not hypotheticals. Each one produced a+wrong classification or a wrong draft.++- **Preview text is often truncated.** Always re-read the full body before drafting. A scan preview that cuts at a few hundred characters hides the actual ask.+- **Phone JIDs and LIDs can be mispaired.** Merge two identities only when an authoritative mapping proves the pair. Never trust a provisional alternate-JID field on its own.+- **LID and phone mirrors duplicate rows.** The same message can appear once per JID with the same message ID. Deduplicate by message ID before counting toward any minimum-messages rule and before deciding which message is genuinely last.+- **Same-name searches conflate different people and companies.** Verify the recipient address, domain, and topic before demoting a candidate as already answered.+- **A meeting on the calendar does not resolve a different open question** from the same person. Match on the specific ask, not on the fact that you have contact with them.+- **An old time, price, or status is context, not proof** of the current fact. Re-verify anything load-bearing against its own source.+- **An unanswered message is not automatically NEEDS_REPLY.** It may be an action item you owe, a social close that needs nothing, or a request now owned by the other party.+- **Subagent triage output is a research artifact, not a finished report.** Read the JSON it actually returned before restating its conclusions, and check that it covered every item you gave it. A partial pass that reports confidently will carry its gaps into the user's reply verbatim.+- **"No contact on file" is only true after sweeping every configured account.** Run `gog auth list` and search the relevant mailboxes, not just the default one. Query the company or domain as well as the person's name.+- **A draft that hands the task back to the counterparty misreads ownership.** Before drafting, name who owns the task and who has the access. A message that says "I'll do X" when the other party owns X is worse than no reply. The same applies in reverse: do not hand back work the user can do themselves.+- **When the user says to research first, that means research, not a softer draft.** If a counterparty re-pitches something, check whether it is genuinely new before writing a polite "sounds interesting". A pitch that reads as fresh may be the same pack from weeks earlier with open questions still unanswered.+- **A blocked send is a precondition to satisfy, not an obstacle to route around.** When a send hook rejects a call, it returns the block message instead of sending. Satisfy what it asked for, then re-issue the same call. Never retry the send through a different wrapper or shell path to get past the gate; a hook that inspects the command text will simply stop seeing the send, which disables the guardrail rather than passing it.++## Output quality gate++Before reporting the pass complete, prove each of these:++- every thread in the baseline is accounted for exactly once;+- no archived JID or thread also appears in an active bucket;+- every direct contact carries all of its verified aliases;+- every staged draft addresses the complete latest inbound, not just its first line;+- every uncertain factual claim is labelled as a blocker rather than asserted;+- the report states plainly which mutations occurred (sends, archives, mark-read) and which did not.+## CompletionAfter all selected channels are processed, print:diff --git a/claude-ops/skills/ops-update/SKILL.md b/claude-ops/skills/ops-update/SKILL.mdindex 897b2d59..e97339d6 100644--- a/claude-ops/skills/ops-update/SKILL.md+++ b/claude-ops/skills/ops-update/SKILL.md@@ -14,6 +14,35 @@ Upgrades the local **claude-ops** plugin to the newest version published in the`ops-marketplace` catalogue, then leaves the box clean: no stale cache dirs, nodangling version-pinned paths.+## Automatic daily check (detect only, never auto-installs)++`bin/ops-update-check` runs daily from the ops daemon (`update-check` service)+and answers one question: is a newer version published? It writes the verdict to+`~/.claude/state/ops-update/update-available.json` and exits **3** when an+update exists, **0** when current.++**It never installs anything.** Detection and application are deliberately split:+a background job that swapped the plugin out mid-session would break a working+install at the worst possible moment. Applying is always `ops-update`, run on+the user's word.++When you see that an update is available — because the state file says so, or+because the user asks — surface it once and offer to apply it:++```bash+"${CLAUDE_PLUGIN_ROOT}/bin/ops-update-check" --json # current verdict, throttled to daily+"${CLAUDE_PLUGIN_ROOT}/bin/ops-update-check" --force # recheck now, ignoring the throttle+```++Then a single `AskUserQuestion`: `[Update now]` `[Show what changed]` `[Not now]`.+Only on `Update now` do you run `bin/ops-update`. Never chain the two, and never+apply an update the user has not just agreed to in that exchange.++Flags: `--json` (verdict on stdout), `--no-fetch` (compare against the catalogue+already on disk, no network), `--force` (ignore the once-a-day throttle),+`--quiet` (write state, print nothing — how the daemon runs it). Override the+cadence with `$OPS_UPDATE_CHECK_INTERVAL` in seconds.+The workhorse is **`${CLAUDE_PLUGIN_ROOT}/bin/ops-update`**. It runs a 9-step loop:1. **Refresh catalogue** — `claude plugin marketplace update ops-marketplace` (git-pulls the clone).diff --git a/claude-ops/tests/test-no-secrets.sh b/claude-ops/tests/test-no-secrets.shindex 6ff3021a..ea69cc55 100755--- a/claude-ops/tests/test-no-secrets.sh+++ b/claude-ops/tests/test-no-secrets.sh@@ -154,7 +154,7 @@ scan_pattern "App Store Connect issuer UUID literals" \'(example|placeholder|00000000-0000-0000-0000-000000000000|<)'scan_pattern "App Store Connect numeric app ID literals" \- '(APP_STORE_CONNECT_APP_IDS|HEALIFY_ASC_[A-Z_]*APP_ID|APP_IDS|appId).{0,80}["'\''][0-9]{9,12}["'\'']' \+ '(APP_STORE_CONNECT_APP_IDS|[A-Z][A-Z0-9_]*_ASC_[A-Z_]*APP_ID|APP_IDS|appId).{0,80}["'\''][0-9]{9,12}["'\'']' \'(example|placeholder|<)'scan_pattern "hardcoded sentry-cli org values" \@@ -194,6 +194,44 @@ scan_tests_literal "Stripe sk_live_" 'sk_live_[a-zA-Z0-9]{24,}'scan_tests_literal "GitHub ghp_" 'ghp_[a-zA-Z0-9]{36,}'scan_tests_literal "Slack xoxb-" 'xoxb-[0-9]{10,}-[0-9]{10,}-[a-zA-Z0-9]{20,}'+# --- User preferences must never be tracked ---+# Preferences hold the operator's own identity, contacts, and channel config.+# .gitignore alone is not a guard: a file already tracked stays tracked, and+# `git add -f` bypasses it. This asserts the actual git index, which is the+# thing that ends up public.+prefs_tracked_check() {+ local tracked+ tracked=$(git -C "$PLUGIN_ROOT" ls-files 2>/dev/null | grep -iE \+ '(^|/)(preferences|ops-prefs|ops\.local|contact-registry|daemon-health|daemon-services|pii-denylist)\.(json|txt)$|(^|/)registry\.json$|\.local\.json$' \+ | grep -vE '\.(example|template|sample)\.json$|/registry\.templates/' || true)+ if [[ -n "$tracked" ]]; then+ local count; count=$(echo "$tracked" | wc -l | tr -d ' ')+ err "user preference file(s) tracked in git" "$count file(s) — move to \$PREFS_PATH or \$HOME/.config and git rm --cached"+ echo "$tracked" | head -5 | sed 's/^/ /'+ else+ ok "no user preference files tracked in git"+ fi+}+prefs_tracked_check++# --- Skills must not write preferences into the repo ---+# A skill that writes prefs next to its own source will commit the operator's+# identity on the next `git add -A`. Preferences go to the plugin data dir.+prefs_write_target_check() {+ local bad+ bad=$(grep -rnE '>[[:space:]]*"?\$?\{?(PLUGIN_ROOT|CLAUDE_PLUGIN_ROOT|REPO_ROOT)\}?/[^"]*(preferences|prefs|registry)\.json' \+ $EXCLUDE_ARGS --include="*.sh" --include="*.mjs" --include="*.js" --include="*.py" \+ "$PLUGIN_ROOT" 2>/dev/null || true)+ if [[ -n "$bad" ]]; then+ local count; count=$(echo "$bad" | wc -l | tr -d ' ')+ err "preference written into the repo tree" "$count site(s) — write to \$PREFS_PATH instead"+ echo "$bad" | head -5 | sed 's/^/ /'+ else+ ok "no preference writes target the repo tree"+ fi+}+prefs_write_target_check+# --- Operator identity denylist (OUT-OF-REPO) ---# A public scanner cannot hardcode the operator's own brand names, personal# names, or private hostnames — that list would itself be the PII it's meant todiff --git a/docs/MERGE_GATES.md b/docs/MERGE_GATES.mdindex fa4e77e7..6e4d8011 100644--- a/docs/MERGE_GATES.md+++ b/docs/MERGE_GATES.md@@ -6,7 +6,7 @@| Typical required context | Notes ||--------------------------|--------|-| **`CI Summary`** (if present) | Only required context on many Healify `dev` branches |+| **`CI Summary`** (if present) | Often the only required context on a `dev` branch || Else: branch-protection required checks | `gh api repos/.../branches/<branch>/protection` |When required green + no conflicts:diff --git a/docs/PII-AUDIT.md b/docs/PII-AUDIT.mdindex ce34e606..f1edc9e6 100644--- a/docs/PII-AUDIT.md+++ b/docs/PII-AUDIT.md@@ -5,18 +5,24 @@ this branch scrubbed, and what remains for a dedicated follow-up pass.## Scrubbed on this branch (`chore/scrub-pii-to-local-prefs`)-Highest-sensitivity: real people + real phone + a real WhatsApp JID, all in+Highest-sensitivity: real people + a real phone number + a real WhatsApp JID, all in`skills/ops-inbox/SKILL.md` example / standing-rule prose (illustrative only — safe to-genericize, no logic depends on the literals):+genericize, no logic depended on the literals):-- Real contact names in dedup examples (Robert, Brittany, Twan, Dennis, JD) → generic- `<contact>` / `<contact-A>` / `<contact-B>`.-- Real phone number `31642218102` → `<number>`.-- Real deal/issue references (Betaalronde, Centurion, Ian comp, `AUR-880`, `AUR-696`,- `AUR-1004`, `AUR-920`, `SFB-172`) in the Paperclip SSOT example → generic wording+> **This section deliberately does not quote what it removed.** An audit that+> reprints the phone number, JID, and contact names it scrubbed leaves the repo+> exactly as exposed as before, just with the data moved to a different file.+> The original version of this document did precisely that; see "Round 3" below.+> Describe the *class* of value removed, never the value.++- Five real contact first names in dedup examples → generic `<contact>` /+ `<contact-A>` / `<contact-B>`.+- One real E.164 phone number → `<number>`.+- Real deal and issue references in the task-tracker example (four internal issue+ keys plus three counterparty/deal code names) → generic wording("resolve counterparty→issue mappings from your local prefs/board").-- LID format example `218030407741450@lid` in `scripts/whatsapp/apply-patches.py`- docstring → `100000000000000@lid`.+- A real WhatsApp LID used as a format example in a script docstring → a+ synthetic all-zeros LID.Mechanism added:- `~/.claude/ops-prefs.json` (OUTSIDE the repo, gitignored by location) — central prefs@@ -32,36 +38,58 @@ Raw grep counts (many are already example placeholders like `a[at]x[.]com`,| Category | Raw hits | Real (est.) | Notes ||---|---|---|---|| `Healify` company name | 149 | ~load-bearing | Integration target across Slack scoping, dashboards, skills. Genericizing to a config-driven company key is a real refactor — do not blind-scrub. |-| Emails | 155 | ~4 real | `info[at]lifecycleinnovations[.]limited` ×5, `support[at]healify[.]ai` ×3, `deeksha[at]browserstack[.]com` ×1; rest are examples. |+| Emails | 155 | ~4 real | The public maintainer contact ×5, a product support alias ×3, one vendor contact ×1; rest are examples. || WhatsApp JIDs | 79 | ~0 real left | Overwhelmingly format examples. |-| Issue keys AUR/HEA/SFB/HFT | 15 | ~11 | `HEA-4045/4047/4049/4246`, `SFB-172`, `AUR-*` — traceability comments in credit-rotation code + CHANGELOG. Low-harm, numerous. |+| Issue keys | 15 | ~11 | Internal tracker keys in traceability comments in credit-rotation code + CHANGELOG. Low-harm, numerous. || Phone E.164 | 7 | 1 (scrubbed) | Rest are `123456…` examples. || `Aurora` | 4 | 0 | All AWS RDS **Aurora**, not the company — false positive. |-| `Vinites` | 1 | scrubbed | — |+| One counterparty name | 1 | scrubbed | — |### Recommended follow-up-1. **Issue keys** (`HEA-####`, `SFB-172`, `AUR-*`) in code comments + CHANGELOG →- drop the ticket refs or replace with `<ISSUE>`; mechanical, low-risk, ~11 spots.-2. **Real emails** (`info[at]lifecycleinnovations[.]limited`, `support[at]healify[.]ai`,- `deeksha[at]browserstack[.]com`) → placeholders / read from prefs; ~9 spots.-3. **`Healify` (×149)** → a real refactor: introduce a company-key indirection- (`<company>` in prose; runtime value from `~/.claude/ops-prefs.json`), keeping the- Healify-specific Slack/dashboard integration working. Do as its own reviewed PR.+1. **Issue keys** in code comments + CHANGELOG → drop the ticket refs or replace+ with `<ISSUE>`; mechanical, low-risk, ~11 spots.+2. **Real emails** (the maintainer contact, a support alias, one vendor address) →+ placeholders / read from prefs; ~9 spots.+3. **Company name (×149)** → a real refactor: introduce a company-key indirection+ (`<company>` in prose; runtime value from prefs), keeping the product-specific+ Slack/dashboard integration working. Do as its own reviewed PR.Nothing here is pushed. Branch: `chore/scrub-pii-to-local-prefs`.## Round 2 (2026-07-22) — mechanical scrub done-- Internal issue keys (`HEA-####`, `SFB-172`, `AUR-*`) in code comments / tests / install- scripts / plist templates / one runbook → removed or genericized (`<ISSUE>` / `<TEAM>-123`),- plus the runbook `Owner:` line degenericized.+- Internal issue keys in code comments / tests / install scripts / plist templates /+ one runbook → removed or genericized (`<ISSUE>` / `<TEAM>-123`), plus the runbook+ `Owner:` line degenericized.- A person's example email in `agents/memory-extractor.md` → `example.user@example[.]com`.### Deliberately kept (NOT PII to scrub)-- `info[at]lifecycleinnovations[.]limited` — intentional PUBLIC maintainer contact- (marketplace.json / SECURITY.md; allowlisted in `tests/test-no-secrets.sh`).-- `Healify` (~149) — the product this plugin was built for; the maintainers keep it- Healify-specific (Slack `#healify-*` scoping, dashboards). Removing it is a multi-tenant- architecture change, not a scrub — out of scope, decide separately.-- `support[at]healify[.]ai` — functional config default (`PLAY_DWD_SUBJECT`), overridable- by env; left to avoid breaking the launch-gate default.+- The public maintainer contact address — intentional, published in+ `marketplace.json` / `SECURITY.md` and allowlisted in `tests/test-no-secrets.sh`.+- A product support alias — functional config default, overridable by env; left to+ avoid breaking the launch-gate default.++## Round 3 (2026-08-16) — this document was itself a leak++Two failures found by enabling the operator identity denylist, which had never been+configured and therefore reported PASS while checking nothing:++1. **This audit re-published what it scrubbed.** Rounds 1 and 2 quoted every removed+ literal verbatim: the phone number, the WhatsApp LID, contact first names, deal+ code names, and issue keys. One commit removed the phone number from a skill and+ added it to this file in the same change, so net exposure never dropped. All such+ literals are now described by class instead of quoted.+2. **Operator identifiers the earlier rounds missed** — real email addresses in+ script docstrings and a test assertion, hardcoded `/Users/<user>/…` paths, a+ username fallback, a Tailscale tailnet name, an EC2 instance id, a private+ Tailscale IP, a PEM filename, and account-pool labels naming the owner's brands.++Both are now guarded rather than merely documented: `tests/test-no-secrets.sh` gained+a tracked-preferences check and a prefs-write-target check, and the identity denylist+must be configured per machine (see `CLAUDE.md` Rule 0) or it verifies nothing.++**Scope limit, stated plainly:** everything above fixes the working tree only. Values+committed earlier remain readable in this repo's public git history, and the+maintainer identity is present in the author/committer trailers of most commits.+Neither is addressed by editing files. Treat any address or hostname that ever+appeared here as public.diff --git a/docs/plans/2026-08-16-crs-removal-plan.md b/docs/plans/2026-08-16-crs-removal-plan.mdnew file mode 100644index 00000000..c42fa5d8--- /dev/null+++ b/docs/plans/2026-08-16-crs-removal-plan.md@@ -0,0 +1,635 @@+# CRS removal plan++Date: 2026-08-16+Status: proposal. Nothing in this plan has been executed. No existing file was edited to produce it.+Scope: remove claude-relay-service (CRS) from this repo and re-offer it as an optional installable dependency.++All paths are repo-relative. Line numbers are from the tree at the time of writing.++---++## 1. What CRS is in this repo today++### 1.1 Headline counts++| Group | Tracked files | Lines | Bytes |+|---|---|---|---|+| `claude-ops/scripts/account-rotation/` | 106 | 34,210 | 1,360,958 |+| `claude-ops/scripts/crsproxy-reauth/` | 7 | 3,532 | 140,618 |+| Other CRS-named files (installers, units, plists, runbook) | 14 | 786 | not measured |+| **Total matched by the inventory grep** | **127** | **~38,528** | **~1.5 MB** |++The repo tracks 959 files in total, 850 of them under `claude-ops/`. So the inventory grep touches+about 13% of the tree by file count.++The grep used was:+`git ls-files | grep -iE 'crs|claude-relay|account-rotation|rotation'`++### 1.2 The important distinction: `account-rotation` is not CRS++`account-rotation/` is 106 files, but only **14** carry a `crs-` filename prefix. Of the 106,+**53 mention "CRS" somewhere** and **53 do not**. Treating `account-rotation/` as "the CRS directory"+and deleting it would remove a large amount of non-CRS functionality (keychain rotation, the credit+ledger, the captcha cascade, staged enrollment, seat state, the CLIProxyAPI writer inside+`rotate.mjs`).++Three tiers, by evidence:++**Tier A — CRS-only. Extractable with no functional loss to the rest of the plugin.**++14 files in `account-rotation/`:++```+crs-401-refresher.mjs crs-egress-failover.sh crs-priority-daemon.mjs+crs-429-cooldown.mjs crs-health-watch.mjs crs-priority-daemon.sh+crs-429-cooldown.sh crs-pool-config.mjs crs-reconciler-state.mjs+crs-bedrock-guard.mjs crs-pool-config.test.mjs crs-refresh-lock.mjs+ crs-token-feed.mjs+ crs-token-feed.sh+```++Plus, outside `account-rotation/`:++```+claude-ops/scripts/crsproxy-reauth/ (7 files, 3,532 lines — CRS reauth, Python)+claude-ops/scripts/install-crs-fra-tunnel.sh+claude-ops/scripts/install-crs-priority-agent.sh+claude-ops/scripts/install-crs-reconcilers-agent.sh+claude-ops/scripts/systemd/crs-bedrock-guard.service+claude-ops/scripts/systemd/crs-bedrock-guard.timer+claude-ops/scripts/systemd/crs-compose.service+claude-ops/scripts/systemd/crs-token-feed.service+claude-ops/scripts/systemd/crs-token-feed.timer+claude-ops/templates/com.claude-ops.crs-429-cooldown.plist+claude-ops/templates/com.claude-ops.crs-fra-tunnel.plist+claude-ops/templates/com.claude-ops.crs-priority.plist+claude-ops/templates/com.claude-ops.magic-link-autoloop.plist (installed only by install-crs-reconcilers-agent.sh)+docs/runbooks/crs-full-tuning-plan.md (269 lines, host-specific CRS tuning)+```++**Tier B — CRS-coupled but not CRS-only. Needs editing, not deleting.**++These are core rotation files that carry CRS logic inline. Counts are `git grep -c -i CRS`:++| File | CRS mentions | Why it matters |+|---|---|---|+| `claude-ops/scripts/account-rotation/bg-respawn.mjs` | 97 | highest CRS density in the tree; background respawn is CRS-aware throughout |+| `claude-ops/scripts/account-rotation/route-state.mjs` | 56 | exports `routeStatus()`, consumed by a **registered PreToolUse hook** |+| `claude-ops/scripts/account-rotation/claude-stack.mjs` | 35 | backs the `bin/claude-stack` wrapper; route modes are CRS-named |+| `claude-ops/scripts/account-rotation/session-router.mjs` | 25 | |+| `claude-ops/scripts/account-rotation/claude-settings-mode.mjs` | 20 | |+| `claude-ops/scripts/account-rotation/captcha-helper.mjs` | 18 | |+| `claude-ops/scripts/account-rotation/magic-link-autoloop.mjs` | 16 | **hard-imports two Tier-A modules** |+| `claude-ops/scripts/account-rotation/reauth-env.mjs` | 13 | |+| `claude-ops/scripts/account-rotation/launch-claude.mjs` | 11 | |+| `claude-ops/scripts/account-rotation/claude-harness-env.mjs` | 11 | |+| `claude-ops/scripts/account-rotation/config.example.json` | 11 | shipped config schema carries a `crs` block |+| `claude-ops/scripts/account-rotation/refresh-tokens.mjs` | 10 | **hard-imports one Tier-A module** |+| `claude-ops/scripts/account-rotation/ops-accounts-backend.mjs` | 9 | |+| `claude-ops/scripts/account-rotation/ops-accounts-gateway.mjs` | 5 | the declared CRS **replacement**; still speaks CRS in migration text |+| `claude-ops/scripts/account-rotation/README.md` | 14 | |+| `claude-ops/scripts/account-rotation/CAPTCHA-CASCADE.md` | 8 | |++Plus two test files that assert CRS behaviour:+`__tests__/claude-settings-mode-crs.test.mjs` (28 mentions),+`__tests__/production-recovery.test.mjs` (20).++**Tier C — not CRS.** The remaining ~53 files in `account-rotation/`: `rotate.mjs` (the largest+CLIProxyAPI consumer in the repo, 70 `cliproxy` hits), `ledger.mjs`, `claude-p-as.mjs`,+`seat-state.mjs`, `seat-policy-tick.mjs`, `staged-enrollment.mjs`, the captcha cascade+(`captcha-cascade.mjs`, `visual-captcha-solver.mjs`, `bright-data-cascade.mjs`), `rotate-magic.mjs`,+`kapture-claim-credits.mjs`, `daily-credit-digest.mjs`, `monthly-credit-reclaim.mjs`, the 23 files+under `__tests__/`, and the rest.++### 1.3 Hard code edges into Tier A++Only four `import` statements cross into CRS modules. This is the real coupling surface:++| Consumer | Line | Imports |+|---|---|---|+| `claude-ops/scripts/account-rotation/magic-link-autoloop.mjs` | 33 | `./crs-pool-config.mjs` (`loadRotationConfig`, `buildCrsNameMaps`, `crsFileVaultPath`) |+| `claude-ops/scripts/account-rotation/magic-link-autoloop.mjs` | 34 | `./crs-reconciler-state.mjs` (`loadJsonState`, `saveJsonStateAtomic`, `withOwnStateLock`) |+| `claude-ops/scripts/account-rotation/refresh-tokens.mjs` | 24 | `./crs-refresh-lock.mjs` (`acquireRefreshLock`, `claimRefreshPace`) |+| `claude-ops/scripts/account-rotation/crs-health-watch.mjs` | 33 | `./crs-heal-relay.mjs` — **this file does not exist** (not tracked, not on disk) |++Intra-Tier-A imports (`crs-429-cooldown.mjs:62,63`, `crs-pool-config.test.mjs:3`,+`crs-priority-daemon.mjs:73`, `crs-token-feed.mjs:22,29`) all resolve inside the group and move with it.++---++## 2. What depends on it — blast radius++### 2.1 Executable callers (code, not prose)++| File:line | What it does |+|---|---|+| `claude-ops/hooks/bedrock-fallback-guard.mjs:2` | `import { routeStatus } from '../scripts/account-rotation/route-state.mjs'` |+| `claude-ops/hooks/hooks.json:8` | registers `bedrock-fallback-guard.mjs` as a **PreToolUse hook** — this is a live safety gate |+| `claude-ops/hooks/hooks.json:73` | registers `bedrock-billing-guard.mjs` (PreToolUse); its user-facing text at `:111,112,127,129` tells the user CRS/OAuth will take over |+| `claude-ops/hooks/bedrock-fallback-guard.mjs:21,27,33` | error strings instruct `claude-stack route --mode crs-oauth` |+| `claude-ops/bin/claude-stack:5` | `exec node "$ROOT/scripts/account-rotation/claude-stack.mjs"` |+| `claude-ops/bin/ops-accounts:60` | `ROT="${ROOT}/scripts/account-rotation"` — the whole shell path hangs off this |+| `claude-ops/bin/ops-accounts:34` | `SHELL_CMDS="util setup crs crs-tick seats gateway grok-proxy help …"` |+| `claude-ops/bin/ops-accounts:62,94` | `CRS_GROK_BASE_URL` probe for the Grok hop |+| `claude-ops/bin/ops-accounts:298-311` | `crs` and `crs-tick` subcommands shell out to `crs-priority-daemon.sh` |+| `claude-ops/bin/ops-accounts:368` | prints the `CRS_BASE_URL` → `OPS_ACCOUNTS_GATEWAY_URL` migration hint |+| `claude-ops/bin/ops-accounts:395` | help text lists `crs \| crs-tick` |+| `claude-ops/bin/ops-bg:91-105` | injects a CRS session-settings overlay via `--settings`, gated on a host preflight script that lives outside the repo |+| `claude-ops/scripts/lib/claude-invoke.sh:15,25,34,83` | resolves and execs `scripts/account-rotation/claude-p-as.mjs` (Tier C, not CRS) |+| `claude-ops/scripts/install-account-rotator-linux.sh:19,20,37,66` | systemd installer for `daemon.mjs` + `provision-coordination.mjs` |+| `claude-ops/scripts/install-crs-priority-agent.sh:20,21,22` | wrapper/daemon/plist paths |+| `claude-ops/scripts/install-crs-reconcilers-agent.sh:52,53,89,99,106,107` | 429-cooldown + magic-link autoloop units |+| `claude-ops/scripts/install-daily-credit-digest.sh:23` | `account-rotation/daily-credit-digest.mjs` (Tier C) |+| `claude-ops/scripts/install-monthly-credit-reclaim.sh:23` | `account-rotation/monthly-credit-reclaim.mjs` (Tier C) |+| `claude-ops/scripts/ops-accounts/providers/claude.mjs:13,18` | resolves the `account-rotation` dir and a host config path |+| `claude-ops/scripts/ops-accounts/providers/claude.mjs:121` | returns `note: 'use crs-live-status / priority daemon'` |+| `claude-ops/scripts/ops-accounts/providers/cursor.mjs:11,55` | reads a quota snapshot under a `crs-keys/` host dir |+| `claude-ops/scripts/ops-accounts/providers/factory.mjs:12,60` | same `crs-keys/` host dir |+| `claude-ops/scripts/ops-cron-pocket-watcher.py:358,363` | falls back to a keychain item named `CRS_KEY` for a relay token |+| `claude-ops/scripts/ops-memory-extractor.sh:87,91` | same `CRS_KEY` keychain fallback |+| `claude-ops/templates/statusline/statusline-command.sh:262-275` | CRS-relay detection to suppress a false Bedrock warning |+| `claude-ops/templates/statusline/statusline-command.sh:301` | reads a host `account-rotation` dir for status |+| `claude-ops/templates/statusline/tests/run-tests.sh:88` | creates a fake `account-rotation` dir as fixture |+| `claude-ops/scripts/recap/cron.example.txt:12` | example crontab line running `account-rotation/kapture-claim-credits.mjs` |++### 2.2 Service definitions++| File:line | Note |+|---|---|+| `claude-ops/scripts/systemd/claude-account-rotation.service:3,4` | `After=`/`Wants= crs-compose.service` — the rotation daemon unit is ordered behind CRS |+| `claude-ops/scripts/systemd/claude-account-rotation.service:16,17` | ExecStart / WorkingDirectory into `account-rotation/daemon.mjs` |+| `claude-ops/scripts/systemd/crs-bedrock-guard.service:3,4,8` | depends on `crs-compose.service`, runs `crs-bedrock-guard.mjs` from a host path |+| `claude-ops/scripts/systemd/crs-token-feed.service:3,4,10,11` | depends on `crs-compose.service`, sets `CRS_BASE`, runs `crs-token-feed.sh` |+| `claude-ops/scripts/systemd/crs-bedrock-guard.timer:8`, `crs-token-feed.timer:8` | timers bound to the above |+| `claude-ops/templates/com.claude-ops.account-rotation.plist` | launchd unit for the rotation daemon (not CRS-specific) |+| `claude-ops/templates/com.claude-ops.crs-*.plist` (3 files) | launchd units for CRS reconcilers/tunnel/priority |+| `claude-ops/templates/com.claude-ops.magic-link-autoloop.plist:7,65` | installed by the CRS reconciler installer; sets `CRS_MAGIC_LINK_ROTATE_TIMEOUT_MS` |++`claude-ops/scripts/systemd/install-systemd-units.sh` does **not** reference any `crs-*` unit —+verified with a targeted grep that returned nothing. The CRS units are installed only by the three+`install-crs-*.sh` scripts, or by hand.++**No cron entries** ship in the repo other than the example at `claude-ops/scripts/recap/cron.example.txt:12`.++### 2.3 Configuration surfaces++| File:line | Note |+|---|---|+| `claude-ops/.claude-plugin/plugin.json:184-189` | userConfig `account_rotation_enabled` (default false) |+| `claude-ops/.claude-plugin/plugin.json:190-194` | userConfig `account_rotation_setup_oauth_each` (default true) |+| `claude-ops/.gitleaks.toml:179` | comment noting the scanner still runs against `scripts/account-rotation/` because it handles real auth tokens |+| `claude-ops/package.json` | **no** npm script references CRS or account-rotation. Verified by reading the file. |+| `claude-ops/plugin-dependencies.json:20` | companion `essentialFor` names "unattended captcha cascade (rotate-magic / magic-link-autoloop)" — magic-link-autoloop is Tier B |++### 2.4 Documentation++| File:line | Note |+|---|---|+| `claude-ops/README.md:3,7,8,10,32,93,94` | rotator is a headline feature; two commands listed |+| `claude-ops/CLAUDE.md:46-48` | the Credit-pool gate section (see §6) |+| `claude-ops/CHANGELOG.md` | 20+ hits across the history. Changelog entries are historical record and should not be rewritten. |+| `claude-ops/docs/ops/HOST-VS-PLUGIN-ROTATE-GAP.md:3,4,50,62,73-84,99,124-149` | the gap analysis between host tree and plugin tree; enumerates host-only CRS units |+| `claude-ops/docs/ops/OPS-ACCOUNTS-GATEWAY.md:3,7,32,42,54` | states the gateway's purpose is to work **without** installing claude-relay-service |+| `claude-ops/docs/ops/OPS-ACCOUNTS-VISION.md:52,102-106,120,153` | phase map with "CRS optional" and "gateway (no CRS)" as the end state |+| `claude-ops/docs/daemon-guide.md:10`, `claude-ops/docs/migrating-from-v1.md:37,56,90,113`, `claude-ops/docs/os-compatibility.md:182`, `claude-ops/docs/safety-hooks.md:124` | rotation references |+| `docs/runbooks/crs-full-tuning-plan.md` | 269 lines. Entirely CRS. Contains host-specific operational detail. |+| `docs/PII-AUDIT.md:37` | already flags issue keys in credit-rotation code |++---++## 3. What breaks if deleted, per skill++Read from the SKILL.md files themselves.++### `ops-accounts` — **breaks partially, degrades loudly**++- `SKILL.md:3,4` — description and `argument-hint` both advertise `crs` and `crs-tick` verbs.+- `SKILL.md:28` — router table row "Optional Claude LB (CRS or future gateway) → `crs`, `crs-tick`".+- `SKILL.md:37` — Claude provider engine is `scripts/account-rotation/rotate.mjs` (Tier C, survives).+- `SKILL.md:38,90-94` — Grok flows describe an optional CRS hop in front of a host OAuth proxy.+- `SKILL.md:43,66,78,101,102` — the skill **already** says CRS is optional and "Missing CRS is not a failure".+- `SKILL.md:83,86` — seat-state calls into `account-rotation/seat-state.mjs` (Tier C, survives).+- `SKILL.md:107,108` — the phase map already ends at "8 gateway (no CRS)".++Net: losing CRS costs this skill exactly two verbs. `bin/ops-accounts:298-311` already prints+"CRS priority script missing (optional)" when the script is absent, so the removal is+already handled at runtime for `crs`; `crs-tick` exits 1.++### `ops-rotate` — **breaks two documented verbs**++`SKILL.md:3,4,26` advertise `crs` / `crs-tick` and map them onto `ops-accounts`. The skill is a thin+alias; everything else routes to `bin/ops-accounts`. Fix is a doc edit.++### `ops-rotate-setup` — **does not break**++`SKILL.md:18,23` point at `account-rotation/staged-enrollment.mjs` (Tier C) and describe capturing a+**CLIProxyAPI** Claude auth candidate. This skill is already on the replacement path. It never+mentions CRS.++### `ops-fleet` — **does not break, already on CLI proxy**++`SKILL.md:3,17,23,32,48-66` are entirely CLIProxyAPI: `CLIPROXYAPI_BASE_URL`,+`fleet.cliproxy_base_url`, `CLIPROXY_API_KEY`, `CLIPROXYAPI_POOL_COMMAND`, `CLIPROXYAPI_SSH_HOST`,+`CLIPROXYAPI_REMOTE_HELPER`. A targeted grep for `crs` over `bin/ops-fleet` and+`bin/ops-fleet-pool-snapshot` returned nothing. This skill is the model for where the rest should land.++### `ops-credentials` — **does not break**++A targeted grep over `bin/ops-credentials` and `skills/ops-credentials/` found exactly one hit,+`SKILL.md:71`, about rotating an unrelated third-party token. No CRS coupling.++### Others that reference CRS in prose only++- `skills/ops-desk/SKILL.md:75` — one sentence about relay/CRS setups and batch sizing.+- `skills/ops-mac/SKILL.md:113` — names CRS in a "never kill a daemon the user relies on" warning list.+- `skills/setup/SKILL.md:1109,1487,1695` and `skills/setup/channels/claude-rotator.md:3,8,9,31,34` —+ the rotator setup channel. References `account-rotation/config.json`, not CRS.++### Not a skill, but the loudest break++`hooks/bedrock-fallback-guard.mjs` is a **registered PreToolUse hook** (`hooks/hooks.json:8`) that+imports `route-state.mjs`. `route-state.mjs:7` defines `ROUTE_MODES = new Set(['crs-oauth',+'fail-closed'])`. If `route-state.mjs` is deleted the hook throws on every tool call. If the mode name+`crs-oauth` is renamed without updating the hook's three message strings+(`bedrock-fallback-guard.mjs:21,27,33`), the guidance the user sees becomes wrong.++---++## 4. CI++Both CRS test paths run in CI today.++**Workflow:** `.github/workflows/ci.yml`++| Job | Step | Line | CRS relevance |+|---|---|---|---|+| `lint-and-check` | "Prettier check" | `ci.yml:71` | formats `**/*.{js,mjs,json}` — includes all of `account-rotation/` |+| `lint-and-check` | "Run gitleaks" | `ci.yml:78` | uses `claude-ops/.gitleaks.toml`, whose comment at `:179` exists specifically because of `account-rotation/` |+| `pii-gate` | "PII / personal-data scan" | `ci.yml:90` | `claude-ops/tests/test-no-secrets.sh` |+| `test-suite` | "Run full test suite" | `ci.yml:105` | `bash claude-ops/tests/run-all.sh` — this is the one that matters |++**Inside `claude-ops/tests/run-all.sh`**, six suites reach into the removal area:++| Line | Suite | Reaches |+|---|---|---|+| 42 | `test-rotate-cliproxy-integration.sh` | `account-rotation/auto-auth-policy.mjs` (:14), `refresh-tokens.mjs` (:42), `rotate.mjs` (:64); sets `CLAUDE_ROTATION_SKIP_CRS_SYNC: '1'` (:50) |+| 43 | `test-model-args.sh` | `account-rotation/__tests__/model-args.test.mjs` |+| 44 | `test-account-recovery.sh` | `__tests__/refresh-pacing.test.mjs`, `refresh-lock.test.mjs`, `production-recovery.test.mjs` |+| 45 | `../scripts/crsproxy-reauth/test-python-suites.sh` | **the only pure-CRS suite in CI.** Runs 4 Python files: `test_browser_cleanup.py`, `test_checkpoint.py`, `test_lease_cooldown.py`, `test_candidate_validation.py` |+| 46 | `test-staged-enrollment.sh` | `__tests__/staged-enrollment.test.mjs` |+| 47 | `test-coordination-provisioning.sh` | `__tests__/coordination-provisioning.test.mjs` |+| 63 | `../templates/statusline/tests/run-tests.sh` | creates an `account-rotation` fixture dir at `:88` |++Two test files exist but are **not** wired into `run-all.sh`, so they do not run in CI:+`account-rotation/crs-pool-config.test.mjs` and `claude-ops/tests/test-claude-invoke.sh`.+`account-rotation/__tests__/run-captcha-unit-tests.mjs` is likewise not in `run-all.sh`.++`claude-ops/.github/workflows/cross-os.yml` and `docker-build.yml` contain no CRS or+account-rotation references — verified by grep.++---++## 5. What already references "cliproxy" — how much of the replacement exists++The replacement is not hypothetical. It is roughly half-built.++| File | `cliproxy` hits | State |+|---|---|---|+| `claude-ops/scripts/account-rotation/rotate.mjs` | 70 | Writes CLIProxyAPI auth files directly (`cliproxyAuthSnapshot` :1691, `cliproxyAuthChanged` :1719, `clearCliProxyCooldown` :1729, `syncCliProxyReplica` :1753). Comment at `:117` states CLIProxyAPI "owns the per-seat JSON schema and is the sole" source. |+| `claude-ops/bin/ops-accounts` | 24 | Full CLIProxyAPI backend: `CLIPROXY_HOME` :102, `cliproxy_alive()` :106, `cliproxy_count()` :113, and `codex`/`gemini`/`xai`/`kimi` util paths :177-202 |+| `claude-ops/scripts/crsproxy-reauth/bu_reauth.py` | 17 | CRS-side reauth that already knows about cliproxy |+| `claude-ops/bin/ops-fleet` | 14 | fully CLIProxyAPI |+| `claude-ops/skills/ops-fleet/SKILL.md` | 12 | fully CLIProxyAPI |+| `claude-ops/scripts/ops-accounts/providers/cliproxy.mjs` | 10 | A complete provider adapter (91 lines): `listAccounts`, `utilization`, `reauth`. Note it still carries a vestigial `crs: null` field at `:41,61`. |+| `claude-ops/bin/ops-fleet-pool-snapshot` | 5 | |+| `claude-ops/scripts/account-rotation/README.md` | 3 | |+| `claude-ops/tests/test-rotate-cliproxy-integration.sh` | 2 | an existing CI-run integration test for the cliproxy path |+| `claude-ops/skills/ops-rotate-setup/SKILL.md` | 1 | already instructs a CLIProxyAPI auth candidate |+| `claude-ops/scripts/ops-accounts/cli.mjs` | 1 | |+| `claude-ops/scripts/account-rotation/staged-enrollment.mjs` | 1 | |+| `claude-ops/docs/ops/OPS-ACCOUNTS-VISION.md` | 1 | |++Also already built as the CRS replacement: `account-rotation/ops-accounts-gateway.mjs`, documented at+`claude-ops/docs/ops/OPS-ACCOUNTS-GATEWAY.md:3` ("skeleton shipped") and `:7` ("without installing+claude-relay-service"). `bin/ops-accounts:342-383` exposes it as `ops-accounts gateway+status|start|path|self-test|config` on the same default port CRS used.++Conclusion: `ops-fleet`, `ops-rotate-setup`, the cliproxy provider adapter, the cliproxy writer in+`rotate.mjs`, and the gateway all exist. What is missing is the pool-priority / cooldown / token-feed+control loop that the `crs-*` daemons currently provide.++---++## 6. The credit-pool gate — what actually needs rewiring++`claude-ops/CLAUDE.md:46-48` documents `CLAUDE_OPS_USE_CREDIT_POOL`. Verified against the code:++- `claude-ops/scripts/lib/claude-invoke.sh:80` — when `CLAUDE_OPS_USE_CREDIT_POOL=1`, `claude_invoke`+ execs `scripts/account-rotation/claude-p-as.mjs` (`:83,91`). Otherwise it calls `claude` directly+ (`:93`).+- `claude-p-as.mjs` imports **only** `./ledger.mjs` (`:38`) and reads a credit ledger JSON (`:41`).+ It contains **zero** references to CRS, cliproxy, or any relay. Confirmed by grep.++**So the credit-pool gate does not depend on CRS at all.** It depends on `account-rotation/` existing+as a directory, and on `ledger.mjs` + `claude-p-as.mjs` staying put.++What that means for the removal:++- If CRS is extracted (Tier A only), the gate needs **no rewiring**.+- If `account-rotation/` is moved or renamed wholesale, four call sites in+ `claude-ops/scripts/lib/claude-invoke.sh` (`:15` comment, `:25`, `:34`, `:83`) plus+ `claude-ops/tests/test-claude-invoke.sh:114` must be updated, and eleven downstream consumers of+ `claude_invoke` inherit the change:+ `bin/ops-creative-brief:206`, `bin/ops-marketing-autopilot:37`, `bin/ops-suggest-specialized-agent:92`,+ `scripts/lib/creative/analyze.sh:38`, `scripts/lib/creative/landing.sh:66`,+ `scripts/lib/deploy-fix-common.sh:296`, `scripts/ops-cron-competitor-intel.sh:263`,+ `scripts/ops-cron-email-draft.sh:30`, `scripts/ops-cron-seo-blog-gen.sh:26`,+ `scripts/ops-cron-social-calendar.sh:30`, `scripts/recap/digest.sh:12`.+- `claude-invoke.sh:87` already degrades to direct `claude` with a warning if the wrapper is missing,+ so a botched move fails soft rather than dropping daemon jobs.++---++## 7. Removal sequence++Seven steps. Each is independently verifiable and independently revertable. Steps 1-3 are pure+subtraction with no behaviour change; the risk starts at step 4.++### Step 1 — Fix the already-broken import, or delete the file that has it++`crs-health-watch.mjs:33` imports `./crs-heal-relay.mjs`, which does not exist in the repo or on disk.+That file is dead today. Decide: delete `crs-health-watch.mjs`, or carry the broken import into the+extracted package and fix it there.++**Verify:** `node --check claude-ops/scripts/account-rotation/crs-health-watch.mjs` passes (syntax+only, it will not catch the missing module); `git ls-files | grep crs-heal-relay` returns nothing.++### Step 2 — Cut the three code edges from Tier B into Tier A++Three imports, three fixes. Nothing else needs to move first.++1. `refresh-tokens.mjs:24` imports `acquireRefreshLock`, `claimRefreshPace` from `crs-refresh-lock.mjs`.+ These are generic lock/pacing primitives with a CRS-flavoured filename. Rename the module to a+ neutral name (e.g. `refresh-lock.mjs`) and keep it in `account-rotation/`. Update+ `crs-token-feed.mjs:22` to match — it moves out with Tier A but needs the new import path.+2. `magic-link-autoloop.mjs:34` imports `loadJsonState`, `saveJsonStateAtomic`, `withOwnStateLock`+ from `crs-reconciler-state.mjs`. Same treatment: neutral filename, stays.+ Update `crs-429-cooldown.mjs:62` to match.+3. `magic-link-autoloop.mjs:33` imports `loadRotationConfig`, `buildCrsNameMaps`, `crsFileVaultPath`+ from `crs-pool-config.mjs`. This one is genuinely mixed: `loadRotationConfig` is generic,+ `buildCrsNameMaps` and `crsFileVaultPath` are CRS pool concepts. Split it: generic config loading+ stays, the CRS pool mapping leaves. `magic-link-autoloop.mjs` then needs an alternative for the+ name map, or must lose the CRS branch.++**Verify:** `node --check` every changed `.mjs`. Then+`git grep -nE "from '\./crs-" -- claude-ops/scripts/account-rotation/` should list only files that+are themselves Tier A. Run `bash claude-ops/tests/run-all.sh` — the suites at lines 42-47 exercise+`refresh-tokens.mjs` and the `__tests__` tree.++### Step 3 — Extract Tier A to the new home++Move the 14 `crs-*` files (minus whatever was renamed in step 2), `scripts/crsproxy-reauth/`, the+three `install-crs-*.sh`, the five `crs-*` systemd units, the three `com.claude-ops.crs-*.plist`, and+`com.claude-ops.magic-link-autoloop.plist` into the separate installable package (§8). Do **not**+delete them from history; a plain `git rm` is enough, the history stays.++Do not move `docs/runbooks/crs-full-tuning-plan.md` verbatim. It carries host-specific operational+detail. Either rewrite it generically for the new package or drop it — see §9.++**Verify:** `git ls-files | grep -iE 'crs|claude-relay'` returns only intentional survivors.+`bash claude-ops/tests/run-all.sh` — expect line 45 to fail until step 4.++### Step 4 — Unwire CI++- Remove `claude-ops/tests/run-all.sh:45` (the `crsproxy-reauth` suite). This is the only line in+ `run-all.sh` that must go.+- Re-check `test-rotate-cliproxy-integration.sh:50` — it sets `CLAUDE_ROTATION_SKIP_CRS_SYNC: '1'`.+ If `rotate.mjs` no longer has a CRS sync path, that env var is dead and the line should go with it.+- `claude-ops/.gitleaks.toml:179` — update the comment; the reasoning ("account-rotation handles real+ auth tokens") still holds for Tier C, so the rule itself should stay.++**Verify:** `bash claude-ops/tests/run-all.sh` is green locally. Then confirm the `test-suite` job in+`.github/workflows/ci.yml:105` passes on both matrix OS entries.++### Step 5 — Unwire the daemons and units++- `claude-ops/scripts/systemd/claude-account-rotation.service:3,4` — drop+ `After=`/`Wants= crs-compose.service`. The rotation daemon has no real dependency on a relay+ container once CRS is gone, and leaving the ordering in means the unit waits on a unit that will+ never exist.+- Confirm `install-systemd-units.sh` still installs a coherent set (it never referenced the CRS units,+ so this should be a no-op).+- Decide the fate of `com.claude-ops.magic-link-autoloop.plist`: its only installer is+ `install-crs-reconcilers-agent.sh`. If magic-link autoloop survives without CRS, it needs a+ non-CRS installer.++**Verify:** `systemd-analyze verify` on the changed unit where a Linux box is available; otherwise+read the unit and confirm no `crs-` token remains:+`git grep -n crs -- claude-ops/scripts/systemd/`.++### Step 6 — Rewire the routing vocabulary and the safety hook++This is the step most likely to cause a user-visible regression.++- `route-state.mjs:7` — `ROUTE_MODES` contains `crs-oauth`. Renaming it to something like+ `proxy-oauth` requires updating `bedrock-fallback-guard.mjs:21,27,33` (three user-facing strings+ naming `--mode crs-oauth`), `claude-stack.mjs` (35 CRS hits), `claude-settings-mode.mjs` (20), and+ `__tests__/claude-settings-mode-crs.test.mjs` (28) which asserts the current names.+- `route-state.mjs:13` — the base-URL regex hardcodes specific ports **and one specific host IP**.+ That IP is operator-specific and should not be in a public repo regardless of this plan. Replace+ with a configured value.+- `route-state.mjs:46,48,49` — host state paths named `crs-session-settings.json`,+ `crs-fallback-active`, `crs-health-watch.state.json`. Renaming these breaks any live install that+ already has those files; needs a migration or a read-both-write-new shim.+- `hooks/bedrock-billing-guard.mjs:111,112,127,129` — four message strings promise "the rotation+ watchdog should swap you to CRS/OAuth". Reword.+- `bin/ops-bg:91-105` — the CRS overlay injection. It already defaults to a host file and can be+ opted out with `CRS_OVERLAY=""`. Either point it at the CLI proxy overlay or delete the block.++**Verify:** a session start with the PreToolUse hooks active does not throw; `bin/claude-stack route+--mode <new-name>` succeeds and `--mode crs-oauth` gives a clear deprecation message rather than an+opaque failure. Run the two `claude-settings-mode` test files.++### Step 7 — Documentation and the two skill verbs++- `bin/ops-accounts` — remove or deprecate `crs` / `crs-tick` (`:34,298-311,395`), remove the+ `CRS_GROK_BASE_URL` probe (`:62,94`) or rename it, keep the migration hint at `:368` but flip it to+ point at the gateway as the default rather than the migration target.+- `skills/ops-accounts/SKILL.md:3,4,28,38,43,65,66,90,101,102,107,108` — drop the two verbs, keep the+ Grok proxy path, retire the "CRS optional" phase-map language now that phase 8 is the state.+- `skills/ops-rotate/SKILL.md:3,4,26` — drop the two verbs.+- `skills/ops-desk/SKILL.md:75`, `skills/ops-mac/SKILL.md:113` — reword the one-line mentions.+- `claude-ops/README.md:32,93,94` — the rotator entry stays (it is Tier C), but should describe the+ CLI proxy backend, not a relay.+- `claude-ops/docs/ops/HOST-VS-PLUGIN-ROTATE-GAP.md`, `OPS-ACCOUNTS-GATEWAY.md`,+ `OPS-ACCOUNTS-VISION.md` — these three are the CRS-to-gateway migration story. They should be+ rewritten as a single "CLI proxy is the backend, CRS is an optional add-on" document, or archived.+- `claude-ops/CHANGELOG.md` — **do not edit**. It is a historical record. Add a new entry describing+ the removal instead.++**Verify:** `bash claude-ops/tests/run-all.sh` (the skills-lint suite at `run-all.sh:36` will catch+malformed frontmatter). `git grep -icE 'crs|claude-relay' -- claude-ops/skills/` should be zero or+only intentional deprecation notes.++---++## 8. What becomes the installable dependency++### 8.1 Shape++The repo already has the right mechanism: `claude-ops/plugin-dependencies.json` is the declared SSOT+for companions, read by `scripts/install-companions.sh` and `bin/ops-update`. It supports two kinds+today — `claude-plugin` and `skills-clone` — and each entry carries `required`, `coInstallDefault`,+`updateWithOps`, `userConfigGate`, `prefsKey`, `detect`, and `essentialFor`.++CRS should become a **fourth-party optional companion** with:++```+required: false+coInstallDefault: false+updateWithOps: "never" (or "on-request")+userConfigGate: "crs_backend_enabled" (new userConfig key, default false)+prefsKey: "backends.crs"+essentialFor: [] (nothing in the plugin requires it)+```++`essentialFor: []` is the honest value and it is the whole point of the change: after this plan,+no ops command depends on CRS.++The package itself needs to contain: the 14 `crs-*` scripts, the 7 `crsproxy-reauth` files, the three+`install-crs-*.sh` installers, the five systemd units, the four plists, and a config schema for the+`crs` block currently living in `account-rotation/config.example.json`.++### 8.2 Where it should live++Two options, and the owner should pick before step 3:++**(a) A separate repo under the same marketplace.** Matches the `desktop-act` pattern+(`plugin-dependencies.json:5-22`): a real plugin, installed with `claude plugin install`, detected+with a `find` glob. Cleanest boundary. Costs a new repo and a new release lane.++**(b) A `skills-clone`-style git clone.** Matches the `gstack` pattern+(`plugin-dependencies.json:39-57`): `installScript` + `detect.pathExists`, no marketplace entry.+Cheaper to set up, but `bin/ops-update` treats these as always-update, which is wrong for an opt-in+backend — so `updateWithOps` would need a value the installer currently may not honour. **This needs+checking against `scripts/install-companions.sh` before committing to it; I did not read that script.**++### 8.3 Install / opt-in path a user would follow++Assuming option (a):++1. User runs `/ops:accounts` and sees the Claude backend reported as CLI proxy. No CRS anywhere.+2. User who wants multiple Claude or other OAuth seats behind one relay opens plugin settings and+ flips `crs_backend_enabled` to true.+3. `/ops:setup` (or `bin/ops-update`) sees the gate, reads the companion entry, and runs+ `claude plugin install <crs-companion>@ops-marketplace`.+4. The companion's own installer prompts for the upstream relay: which container image, which admin+ credential source, which base URL. **The upstream project slug and image tag are not stated in+ this plan on purpose — this is a public repo. They are recorded today in+ `docs/runbooks/crs-full-tuning-plan.md:19-21` and the owner should decide what is safe to+ republish.**+5. The companion writes its own `crs` config block and registers only the units the user asked for+ (`install-crs-priority-agent.sh` for pool priority, `install-crs-reconcilers-agent.sh` for+ cooldown/magic-link, `install-crs-fra-tunnel.sh` for a remote relay over SSH).+6. `bin/ops-accounts crs` / `crs-tick` come back as verbs **provided by the companion**, not the core+ plugin. The core plugin's current behaviour at `bin/ops-accounts:301` — printing "CRS priority+ script missing (optional)" — is already the correct not-installed message.++### 8.4 What must NOT move into the companion++`claude-p-as.mjs`, `ledger.mjs`, `rotate.mjs`, `seat-state.mjs`, `staged-enrollment.mjs`, the captcha+cascade, and the `__tests__/` tree. These are Tier C, they back the credit-pool gate and the+CLIProxyAPI writer, and moving them would break `claude-invoke.sh` and eleven daemon callers (§6).++---++## 9. Risks and what cannot be cleanly removed++**R1 — The PreToolUse safety hook is the sharpest edge.** `hooks/hooks.json:8` registers+`bedrock-fallback-guard.mjs`, which imports `route-state.mjs` at module load. Any error in that+import path fires on **every tool call in every session**, not just when someone runs an accounts+command. This is the one change in the plan that can brick a working install. It is why step 6 is+last and why steps 1-5 must be green first.++**R2 — Live installs have on-disk state named after CRS.** `route-state.mjs:46,48,49` reference+`crs-session-settings.json`, `crs-fallback-active`, and `crs-health-watch.state.json` under the+user's home. `bin/ops-bg:92` defaults to the same session-settings file, and+`templates/statusline/statusline-command.sh:262-275` detects a CRS relay by base URL to suppress a+false Bedrock billing warning. Renaming these without a migration means: a user's routing silently+stops being recognised, and the statusline starts warning about metered Bedrock spend on a session+that is fine. Read-both-write-new, or leave the filenames alone and only change the code that reads+them.++**R3 — `bg-respawn.mjs` has 97 CRS references and no obvious seam.** It is the densest CRS file+outside the `crs-*` group and it is not named `crs-`. I did not read it in full, so I cannot say+whether it decomposes cleanly or whether the CRS logic is load-bearing for non-CRS respawn. **This is+the single largest unknown in the plan and should be scoped before step 6 is estimated.**++**R4 — Host-only dependencies that this repo cannot remove.** Several CRS touchpoints reference files+that live outside the repo entirely and will keep dangling: `bin/ops-bg:95` expects a preflight script+under the user's home; `rotate.mjs:127` defaults to a replica-sync script under the user's+`~/.local/bin`; `ops-accounts/providers/{cursor,factory}.mjs` read quota snapshots from a `crs-keys/`+host directory; `ops-cron-pocket-watcher.py:363` and `ops-memory-extractor.sh:91` fall back to a+keychain item named `CRS_KEY`. Removing CRS from the repo does not remove these from users' machines.+`docs/ops/HOST-VS-PLUGIN-ROTATE-GAP.md:50,62,73-81` already documents this host/plugin split.++**R5 — Two pre-existing public-repo hygiene problems sit inside the removal area.**+`rotate.mjs:116` contains a contributor's first name in a comment, and `rotate.mjs:121` defaults a+path into a specific personal directory layout. `route-state.mjs:13` hardcodes a specific host IP.+`docs/runbooks/crs-full-tuning-plan.md` contains host-specific operational detail throughout. None of+these were introduced by this plan, but step 3 and step 6 touch all of them, so they should be fixed+in the same pass rather than moved into a new package. `docs/PII-AUDIT.md:37` already tracks a related+class of issue.++**R6 — CHANGELOG cannot be cleaned.** 20+ CRS references across the release history. Rewriting them+would falsify the record. They stay, and any future "is CRS gone?" grep will keep hitting them.++**R7 — The `crs` config block ships in a tracked example.** `account-rotation/config.example.json` has+11 CRS references. Users who copied it have a `crs` block in their live config. Removing the block+from the example does not remove it from their file; readers should tolerate an unknown block rather+than fail.++**R8 — Two test files are dead weight and will hide regressions.**+`account-rotation/crs-pool-config.test.mjs` and `tests/test-claude-invoke.sh` are not referenced by+`run-all.sh`, so nothing verifies them in CI. `test-claude-invoke.sh` is the only test of the+credit-pool gate — the exact thing §6 says must not break. Wiring it into `run-all.sh` **before**+step 2 would be cheap insurance.++---++## 10. Open questions for the owner++1. **Scope.** Does "remove CRS" mean Tier A only (~35 files, low risk), or all of `account-rotation/`+ (106 files, breaks the credit-pool gate and eleven daemon callers)? This plan assumes Tier A.++2. **Companion shape.** Separate marketplace plugin (the `desktop-act` pattern) or git clone+ (the `gstack` pattern)? See §8.2. I did not read `scripts/install-companions.sh`, so I cannot say+ whether it honours `updateWithOps: "never"`.++3. **Republishing the upstream relay details.** The upstream project slug, container image tag, and+ port layout are currently recorded in `docs/runbooks/crs-full-tuning-plan.md`. That file also+ contains host-specific operational detail. What may be republished in a public companion package?++4. **Route-mode rename.** Is `crs-oauth` renamed (breaks `--mode crs-oauth` for existing users, needs+ the shim in R2), or kept as a legacy alias forever?++5. **On-disk state migration.** Rename the three `crs-*` state files under the user's home with a+ migration, or leave the filenames and only change the code? R2.++6. **`bg-respawn.mjs`.** Should it be scoped before this plan is scheduled? 97 CRS references, no read+ performed. R3.++7. **Magic-link autoloop.** Does it survive CRS removal? Today it hard-imports two CRS modules+ (`magic-link-autoloop.mjs:33,34`), its only installer is `install-crs-reconcilers-agent.sh`, and+ `plugin-dependencies.json:20` names it as something a required companion is essential for.++8. **`crs-heal-relay.mjs`.** It is imported at `crs-health-watch.mjs:33` and does not exist. Was it+ ever committed, or is `crs-health-watch.mjs` dead code that should just be deleted?++9. **Grok hop.** `bin/ops-accounts:62,94` and `skills/ops-accounts/SKILL.md:38,90` describe CRS as a+ thin hop in front of the Grok OAuth proxy. Does the CLI proxy replace that hop, or does the Grok+ path keep an optional CRS dependency?++10. **Timeline vs. the gateway.** `docs/ops/OPS-ACCOUNTS-GATEWAY.md:3` calls the gateway a "skeleton".+ Does CRS removal wait for the gateway to reach parity with the `crs-priority` / `crs-429-cooldown`+ / `crs-token-feed` control loop, or ship first and leave that gap to the optional companion?diff --git a/docs/runbooks/crs-full-tuning-plan.md b/docs/runbooks/crs-full-tuning-plan.mdindex 5fefb8aa..a7b9c3b6 100644--- a/docs/runbooks/crs-full-tuning-plan.md+++ b/docs/runbooks/crs-full-tuning-plan.md@@ -20,7 +20,7 @@| Live image | `weishaw/claude-relay-service:cve-fix-20260615` (the CVE-clean node:22-alpine rebuild). **NOT** a `loadbalance-fix-*` tag — see §1 gap || Redis | `crs-redis-1` (`redis:7-alpine`, :6379). Account state + concurrency counters + utilization live here || Aux containers | redis-commander, prometheus, grafana (compose-defined) |-| Account pool | ~10 Claude **Max OAuth** accounts: `pool-aurora/<OWNER_BRAND>/<USER>/chairman/foundation/<OWNER_BRAND>-personal/<OWNER_BRAND>-team` + `canary-lifecycle/support/sponsors`. Records: Redis hash `claude:account:<uuid>` |+| Account pool | ~10 Claude **Max OAuth** accounts, named `pool-<label>` per owner/brand plus a few `canary-<label>` entries. Records: Redis hash `claude:account:<uuid>` || Token refresh | `crs-token-feed.timer` (systemd `--user`, every 5 min) — FRA is the OAuth refresher-of-record || Coarse priority cron | `dynamic-priority.py` (every 5 min) writes CRS `priority` from the same util formula || Routing in | Fleet sessions route via overlay `~/.claude/crs-session-settings.json` (`ANTHROPIC_BASE_URL=…:3005/api` + `ANTHROPIC_AUTH_TOKEN=cr_…`). The `cr_` key MUST be `ANTHROPIC_AUTH_TOKEN`, never `ANTHROPIC_API_KEY` |@@ -120,7 +120,7 @@ This makes future tuning a `docker compose up -d` (env reload), not a code rebui- Confirm `dynamic-priority.py` cron is running and not erroring. **Known pre-existing bug:**`NoneType .get` traceback on accounts with no usage object — non-blocking but should beguarded so the cron doesn't half-update priorities.-- Verify the dead account: `pool-<USER>` (`a9f4806a…`) was the out_of_credits trigger;+- Verify the dead account: one `pool-<label>` entry was the out_of_credits trigger;it needs a **credit top-up** to truly rejoin (5h/7d windows are not the constraint).Until topped up, the credit-cooldown (§2.1) keeps it parked instead of hammered.@@ -266,4 +266,4 @@ time it, confirm < 2 min and health 200, then proceed with the tuning deploy.1. Agreed **fleet concurrent-dispatch ceiling** (relay-side cap is moot if the fleet over-dispatches).2. Whether the `loadbalance-fix-20260616` image/diff is recoverable on the box, or thecredit-cooldown must be re-implemented from §1 spec.-3. Top-up status of `pool-<USER>` (billing-dead account) — keep parked vs. top up vs. remove from pool.+3. Top-up status of the billing-dead `pool-<label>` account — keep parked vs. top up vs. remove from pool.diff --git a/scripts/batch-ship-approval-policies.py b/scripts/batch-ship-approval-policies.pyindex 685db17c..61d99db6 100644--- a/scripts/batch-ship-approval-policies.py+++ b/scripts/batch-ship-approval-policies.py@@ -7,9 +7,10 @@ import reimport subprocessimport sysfrom dataclasses import dataclass, field+import osfrom pathlib import Path-PROJECTS_ROOT = Path("/Users/<user>/Projects")+PROJECTS_ROOT = Path(os.environ.get("OPS_PROJECTS_ROOT", Path.home() / "Projects"))BRANCH = "chore/approval-agent-policies"COMMIT_MSG = """chore: add Cursor Approval Agent policy files@@ -17,13 +18,23 @@ Scaffold APPROVAL_POLICY.md and .cursor/approval-policies/ routingfor Cloud Approval Agents. Force-add routing under .cursor despitegitignore so Approval Agents can discover ROUTING.md."""-PREFER_NAMES = {- "claude-ops": 100,- "healify-api": 90,- "healify-web": 90,- "healify-agentcore": 90,- "healify": 90,-}+# When the same remote is checked out in several places, prefer these repo+# directory names. Override with OPS_PREFER_REPOS="repo-a=100,repo-b=90".+def _prefer_names() -> dict[str, int]:+ raw = os.environ.get("OPS_PREFER_REPOS", "claude-ops=100")+ out: dict[str, int] = {}+ for part in raw.split(","):+ part = part.strip()+ if not part:+ continue+ name, _, score = part.partition("=")+ name = name.strip()+ if name:+ out[name] = int(score) if score.strip().isdigit() else 90+ return out+++PREFER_NAMES = _prefer_names()@dataclassdiff --git a/scripts/scaffold-approval-policies.py b/scripts/scaffold-approval-policies.pyindex 5d070be6..bc08d531 100644--- a/scripts/scaffold-approval-policies.py+++ b/scripts/scaffold-approval-policies.py@@ -10,13 +10,13 @@ from pathlib import Pathfrom typing import LiteralProfile = Literal[- "healify-core",- "healify-api",- "healify-agentcore",- "healify-web",- "healify-mobile",- "healify-docs",- "healify-ops",+ "product-core",+ "product-api",+ "product-agent",+ "product-web",+ "product-mobile",+ "product-docs",+ "product-ops","claude-ops","infra","mcp",@@ -25,21 +25,27 @@ Profile = Literal["generic",]-PROJECTS_ROOT = Path("/Users/<user>/Projects")+PROJECTS_ROOT = Path(os.environ.get("OPS_PROJECTS_ROOT", Path.home() / "Projects"))SKIP_IF_EXISTS = True+# Repo-name patterns are matched against the full repo path. The product slug is+# the prefix your own repos share — set OPS_PRODUCT_SLUG=acme to classify+# acme-api, acme-web, acme-mobile, and so on. Repos that match nothing fall+# through to the "generic" profile.+PRODUCT_SLUG = re.escape(os.environ.get("OPS_PRODUCT_SLUG", "product"))+PROFILE_RULES: list[tuple[re.Pattern[str], Profile]] = [- (re.compile(r"healify-agentcore|healify-llm", re.I), "healify-agentcore"),- (re.compile(r"healify-api(-mcp|-work)?$|healify-api/", re.I), "healify-api"),- (re.compile(r"healify-web|healify\.ai$", re.I), "healify-web"),- (re.compile(r"^healify$|/healify$", re.I), "healify-mobile"),- (re.compile(r"meditation-service", re.I), "healify-core"),- (re.compile(r"healify-(docs|partner-docs|press|knowledge|dataroom)", re.I), "healify-docs"),- (re.compile(r"healify-(marketing|b2b-leadgen|blocks-automations|org|multiplatform)", re.I), "healify-docs"),- (re.compile(r"healify-(admin|operating-dashboard|grafana|storybook)|testflight", re.I), "healify-ops"),+ (re.compile(rf"{PRODUCT_SLUG}-(agentcore|agent|llm)", re.I), "product-agent"),+ (re.compile(rf"{PRODUCT_SLUG}-api(-mcp|-work)?$|{PRODUCT_SLUG}-api/", re.I), "product-api"),+ (re.compile(rf"{PRODUCT_SLUG}-web", re.I), "product-web"),+ (re.compile(rf"^{PRODUCT_SLUG}$|/{PRODUCT_SLUG}$|{PRODUCT_SLUG}-mobile", re.I), "product-mobile"),+ (re.compile(rf"{PRODUCT_SLUG}-(core|service)", re.I), "product-core"),+ (re.compile(rf"{PRODUCT_SLUG}-(docs|partner-docs|press|knowledge|dataroom)", re.I), "product-docs"),+ (re.compile(rf"{PRODUCT_SLUG}-(marketing|leadgen|automations|org|multiplatform)", re.I), "product-docs"),+ (re.compile(rf"{PRODUCT_SLUG}-(admin|operating-dashboard|grafana|storybook)|testflight", re.I), "product-ops"),(re.compile(r"claude-ops", re.I), "claude-ops"),(re.compile(r"network-operations|mcp-gateway|mcp-proxy", re.I), "infra"),- (re.compile(r"-mcp|api-mcp|esimmcp", re.I), "mcp"),+ (re.compile(r"-mcp|api-mcp", re.I), "mcp"),(re.compile(r"_shelved/", re.I), "shelved"),(re.compile(r"internal/", re.I), "infra"),]@@ -70,13 +76,13 @@ def root_policy(profile: Profile, name: str) -> str:- PRs labeled `security`, `breaking`, or `do-not-auto-approve`"""purposes = {- "healify-core": f"{name} is part of the Healify health platform. Treat health data, user safety, and production deploy paths as high sensitivity.",- "healify-api": f"{name} is a Healify backend API. Database schema, auth, and PHI-handling paths require strict review.",- "healify-agentcore": f"{name} hosts Healify AI agents (Anna). Crisis escalation, prompt safety, and model routing are P0.",- "healify-web": f"{name} is the Healify web app. Auth flows, subscription gates, and crisis UI paths are sensitive.",- "healify-mobile": f"{name} is the Healify mobile app (React Native/Expo). HealthKit, releases, and in-app safety flows are sensitive.",- "healify-docs": f"{name} holds Healify documentation or marketing content. Lower runtime risk; still avoid secrets and inaccurate health claims.",- "healify-ops": f"{name} is Healify internal ops/dashboard tooling. Production visibility and auth boundaries matter.",+ "product-core": f"{name} is part of the core health platform. Treat health data, user safety, and production deploy paths as high sensitivity.",+ "product-api": f"{name} is a backend API. Database schema, auth, and PHI-handling paths require strict review.",+ "product-agent": f"{name} hosts the product's AI agents. Crisis escalation, prompt safety, and model routing are P0.",+ "product-web": f"{name} is the web app. Auth flows, subscription gates, and crisis UI paths are sensitive.",+ "product-mobile": f"{name} is the mobile app (React Native/Expo). HealthKit, releases, and in-app safety flows are sensitive.",+ "product-docs": f"{name} holds documentation or marketing content. Lower runtime risk; still avoid secrets and inaccurate health claims.",+ "product-ops": f"{name} is internal ops/dashboard tooling. Production visibility and auth boundaries matter.","claude-ops": f"{name} is Claude Code ops infrastructure. Hooks, deploy automation, and credentials are high risk.","infra": f"{name} is infrastructure or platform code. Network, IAM, and secrets changes require human review.","mcp": f"{name} is an MCP server or integration. New tools, scopes, and outbound calls are medium–high risk.",@@ -86,25 +92,25 @@ def root_policy(profile: Profile, name: str) -> str:}extra_auto = {- "healify-core": "- Small scoped fixes with tests; no auth/PHI/crisis logic changes",- "healify-api": "- Docs and test-only changes with no schema or auth impact",- "healify-agentcore": "- Eval/test-only changes with no prompt, crisis, or tool-scope changes",- "healify-web": "- Docs, copy, and visual tweaks with no auth/subscription/crisis path changes",- "healify-mobile": "- Non-release test/docs changes with no HealthKit or native module changes",- "healify-docs": "- Markdown/copy-only PRs with no embedded secrets",- "healify-ops": "- Dashboard copy and read-only query tweaks with tests",+ "product-core": "- Small scoped fixes with tests; no auth/PHI/crisis logic changes",+ "product-api": "- Docs and test-only changes with no schema or auth impact",+ "product-agent": "- Eval/test-only changes with no prompt, crisis, or tool-scope changes",+ "product-web": "- Docs, copy, and visual tweaks with no auth/subscription/crisis path changes",+ "product-mobile": "- Non-release test/docs changes with no HealthKit or native module changes",+ "product-docs": "- Markdown/copy-only PRs with no embedded secrets",+ "product-ops": "- Dashboard copy and read-only query tweaks with tests","generic": "- Documentation-only or test-only PRs (≤ 300 lines excluding lockfiles)","shelved": "- Documentation-only changes",}extra_never = {- "healify-core": "- Any PHI logging, health data export, or HIPAA-sensitive log changes",- "healify-api": "- `prisma` migrations, auth middleware, or raw health data exposure\n- Never run or approve `prisma db pull` in PR descriptions as a fix",- "healify-agentcore": "- Crisis escalation paths, 988 routing, mental-health guardrails\n- Prompt changes that weaken scope or safety refusals\n- Production model ID or Bedrock guardrail changes without review",- "healify-web": "- Crisis support UI, subscription gates on safety features\n- Auth/session handling and magic-link flows",- "healify-mobile": "- App Store release config, HealthKit entitlements, production API endpoints\n- Fastlane/EAS production profile changes",- "healify-docs": "- Medical claims, HIPAA statements, or regulatory copy without review",- "healify-ops": "- Production dashboard auth or cross-tenant data access",+ "product-core": "- Any PHI logging, health data export, or HIPAA-sensitive log changes",+ "product-api": "- `prisma` migrations, auth middleware, or raw health data exposure\n- Never run or approve `prisma db pull` in PR descriptions as a fix",+ "product-agent": "- Crisis escalation paths, 988 routing, mental-health guardrails\n- Prompt changes that weaken scope or safety refusals\n- Production model ID or Bedrock guardrail changes without review",+ "product-web": "- Crisis support UI, subscription gates on safety features\n- Auth/session handling and magic-link flows",+ "product-mobile": "- App Store release config, HealthKit entitlements, production API endpoints\n- Fastlane/EAS production profile changes",+ "product-docs": "- Medical claims, HIPAA statements, or regulatory copy without review",+ "product-ops": "- Production dashboard auth or cross-tenant data access","infra": "- IAM policy broadening, public exposure, or secret handling changes","mcp": "- New MCP tools, expanded filesystem/network access, or auth bypass","web-saas": "- Payment/checkout, auth, and PII handling changes",@@ -169,7 +175,7 @@ def routing_yaml(profile: Profile) -> str:- .cursor/approval-policies/runtime-policy.md"""extras = {- "healify-api": """+ "product-api": """- product: Database and migrationsboundary: "{prisma/**,**/migrations/**,**/schema.prisma}"policies:@@ -180,8 +186,8 @@ def routing_yaml(profile: Profile) -> str:policies:- .cursor/approval-policies/auth-policy.md""",- "healify-agentcore": """-- product: Anna agent and prompts+ "product-agent": """+- product: AI agent and promptsboundary: "{agents/**,**/prompts/**,evals/**}"policies:- .cursor/approval-policies/agent-policy.md@@ -191,7 +197,7 @@ def routing_yaml(profile: Profile) -> str:policies:- .cursor/approval-policies/crisis-policy.md""",- "healify-web": """+ "product-web": """- product: Authenticationboundary: "{src/**/auth/**,e2e/**/auth/**}"policies:@@ -202,7 +208,7 @@ def routing_yaml(profile: Profile) -> str:policies:- .cursor/approval-policies/e2e-policy.md""",- "healify-mobile": """+ "product-mobile": """- product: Native and releaseboundary: "{ios/**,android/**,fastlane/**,eas.json,app.json}"policies:@@ -213,7 +219,7 @@ def routing_yaml(profile: Profile) -> str:policies:- .cursor/approval-policies/health-data-policy.md""",- "healify-core": """+ "product-core": """- product: Health data handlingboundary: "{**/health/**,**/hipaa/**,**/phi/**}"policies:@@ -309,7 +315,7 @@ Never auto-approve schema migrations.- TimescaleDB hypertable constraints include partition columns- No `prisma db pull` workflow introduced- Rollback plan exists for production deploy window-- Shared DATABASE_URL contract with healify-langgraphs preserved if applicable+- Shared DATABASE_URL contract with sibling services preserved if applicable""","agent-policy.md": """# AI agent approval policy@@ -394,11 +400,11 @@ def policies_for_profile(profile: Profile) -> dict[str, str]:"runtime-policy.md": POLICY_SNIPPETS["runtime-policy.md"],}extras = {- "healify-api": ["auth-policy.md", "migrations-policy.md"],- "healify-agentcore": ["agent-policy.md", "crisis-policy.md"],- "healify-web": ["auth-policy.md", "e2e-" + "policy.md"],- "healify-mobile": ["mobile-release-policy.md", "health-data-policy.md"],- "healify-core": ["health-data-policy.md"],+ "product-api": ["auth-policy.md", "migrations-policy.md"],+ "product-agent": ["agent-policy.md", "crisis-policy.md"],+ "product-web": ["auth-policy.md", "e2e-" + "policy.md"],+ "product-mobile": ["mobile-release-policy.md", "health-data-policy.md"],+ "product-core": ["health-data-policy.md"],"infra": ["infra-policy.md"],"mcp": ["mcp-policy.md"],"claude-ops": ["hooks-policy.md", "mcp-policy.md"],