Skip to content

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.

feat(deploy-fix): post-merge + build-failure auto-fix subsystem

auroracapital9dc25015ed0a
diff --git a/claude-ops/.claude-plugin/plugin.json b/claude-ops/.claude-plugin/plugin.json
index e8ba83b6..e1b2925b 100644
--- a/claude-ops/.claude-plugin/plugin.json
+++ b/claude-ops/.claude-plugin/plugin.json
@@ -52,6 +52,138 @@
"fedex"
],
"userConfig": {
+ "deploy_fix_enabled": {
+ "type": "boolean",
+ "title": "Deploy auto-fix enabled",
+ "description": "Master switch for the post-merge + build-failure auto-fix subsystem. Spacebar toggles.",
+ "default": true
+ },
+ "monitor_post_merge": {
+ "type": "boolean",
+ "title": "Monitor PR merges → deploys",
+ "description": "After `gh pr merge` to dev/main, watch the deploy workflow + audit service health.",
+ "default": true
+ },
+ "monitor_build_failures": {
+ "type": "boolean",
+ "title": "Monitor `npm run build:*` failures",
+ "description": "After a local build script fails, dispatch a Haiku build-fixer.",
+ "default": true
+ },
+ "auto_dispatch_fixer": {
+ "type": "boolean",
+ "title": "Auto-dispatch headless Claude fixer",
+ "description": "When off, failures are logged + notified only — no agent runs.",
+ "default": true
+ },
+ "allow_dangerous": {
+ "type": "boolean",
+ "title": "Fixer skips permission prompts",
+ "description": "Pass --dangerously-skip-permissions to the headless fixer (required for unattended autonomy).",
+ "default": false
+ },
+ "auto_rerun_transients": {
+ "type": "boolean",
+ "title": "Auto-rerun on transient failures",
+ "description": "Detect npm/gh-actions/network blips and `gh run rerun` instead of dispatching an agent.",
+ "default": true
+ },
+ "audit_health_after_deploy": {
+ "type": "boolean",
+ "title": "Audit /health after deploy",
+ "description": "curl service health URL once deploy succeeds. Failure dispatches a fixer.",
+ "default": true
+ },
+ "verify_served_commit": {
+ "type": "boolean",
+ "title": "Verify served commit matches merge",
+ "description": "Hit /version and check served SHA equals merged SHA.",
+ "default": true
+ },
+ "fix_model": {
+ "type": "string",
+ "title": "Fix-agent model",
+ "description": "Anthropic model the fixer runs on. Default haiku (fast/cheap). Use sonnet/opus for harder failures.",
+ "default": "haiku"
+ },
+ "max_fixes_per_hour": {
+ "type": "number",
+ "title": "Per-repo fix budget per hour",
+ "description": "Cap on auto-fix dispatches per repo per hour.",
+ "default": 3,
+ "min": 0,
+ "max": 20
+ },
+ "watcher_timeout_seconds": {
+ "type": "number",
+ "title": "Deploy watcher timeout (seconds)",
+ "description": "Max wait for deploy workflow completion.",
+ "default": 1800,
+ "min": 60,
+ "max": 7200
+ },
+ "registry_path": {
+ "type": "file",
+ "title": "Service registry JSON",
+ "description": "Maps owner/repo:base → health/version URLs. Project .claude/post-merge-services.json overrides.",
+ "default": "~/.claude/config/post-merge-services.json"
+ },
+ "repo_search_roots": {
+ "type": "string",
+ "title": "Repo search roots",
+ "description": "Colon-separated dirs to find a repo on disk. Example: ~/Projects:~/work",
+ "default": "~/Projects:~"
+ },
+ "deploy_workflow_pattern": {
+ "type": "string",
+ "title": "Deploy workflow regex",
+ "description": "Identifies which GitHub Actions run is the deploy.",
+ "default": "deploy|Deploy|build|Build|ECS|cd|CD"
+ },
+ "notify_channel": {
+ "type": "string",
+ "title": "Failure notification channel",
+ "description": "Where to push failure alerts: macos, ntfy, pushover, discord, telegram, or none.",
+ "default": "macos"
+ },
+ "recap_marquee_enabled": {
+ "type": "boolean",
+ "title": "Recap marquee (tmux digest)",
+ "description": "Run the daemon that synthesizes a one-line digest across all parallel Claude sessions, displayed in tmux status-right.",
+ "default": true
+ },
+ "recap_marquee_auto_configure_tmux": {
+ "type": "boolean",
+ "title": "Auto-configure tmux status-right",
+ "description": "Append the marquee source to ~/.tmux.conf during /ops:setup.",
+ "default": true
+ },
+ "account_rotation_enabled": {
+ "type": "boolean",
+ "title": "Multi-account Claude rotator",
+ "description": "Run the launchd daemon that rotates between Claude Max accounts as quotas approach the cap.",
+ "default": false
+ },
+ "account_rotation_setup_oauth_each": {
+ "type": "boolean",
+ "title": "Setup OAuth for each account",
+ "description": "During /ops:setup, walk through OAuth init for every configured Claude account that doesn't have a keychain token yet.",
+ "default": true
+ },
+ "task_reminder_enabled": {
+ "type": "boolean",
+ "title": "Periodic Task* tool reminder",
+ "description": "PostToolUse hook nudging Claude to use TaskCreate/TaskUpdate every N tool calls without one.",
+ "default": true
+ },
+ "task_reminder_threshold": {
+ "type": "number",
+ "title": "Task reminder threshold",
+ "description": "Number of non-Task tool calls before the reminder fires.",
+ "default": 10,
+ "min": 3,
+ "max": 50
+ },
"telegram_api_id": {
"title": "Telegram API ID",
"description": "Numeric API ID from https://my.telegram.org/apps. Optional \u2014 run /ops:setup telegram to auto-configure.",
diff --git a/claude-ops/bin/ops-deploy-fix-build-trigger b/claude-ops/bin/ops-deploy-fix-build-trigger
new file mode 100755
index 00000000..b426c1d9
--- /dev/null
+++ b/claude-ops/bin/ops-deploy-fix-build-trigger
@@ -0,0 +1,79 @@
+#!/usr/bin/env bash
+# ops-deploy-fix-build-trigger — PostToolUse hook on Bash, gated by `if: Bash(npm run build:*)`.
+# Detects local build failures (npm run build:all / build:*:local / build-queue.sh) and
+# dispatches a Haiku build-fixer. Single-flight per repo; budget-capped; transient detection.
+set -e
+PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
+. "$PLUGIN_ROOT/scripts/lib/deploy-fix-common.sh"
+
+is_enabled monitor_build_failures || exit 0
+
+INPUT=$(cat)
+cmd=$(printf '%s' "$INPUT" | jq -r '.tool_input.command // ""' 2>/dev/null)
+exit_code=$(printf '%s' "$INPUT" | jq -r '.tool_response.exitCode // .tool_response.exit_code // 0' 2>/dev/null)
+output=$(printf '%s' "$INPUT" | jq -r '.tool_response.output // .tool_response.stdout // ""' 2>/dev/null)
+
+case "$cmd" in
+ *"npm run build:"*|*"bash scripts/build-queue.sh"*|*"bash ./scripts/build-queue.sh"*) ;;
+ *) exit 0 ;;
+esac
+
+# Failure detection
+failed=0
+[ "$exit_code" != "0" ] && [ -n "$exit_code" ] && failed=1
+echo "$output" | tail -120 | grep -qE \
+'fastlane (FAIL|failed)|❌|✖ Abort|error TS|FAIL |Error: AI|Build FAILED|RuntimeError|exit code [^0]|npm error|prepare-build-branch.*Abort' \
+ && failed=1
+[ "$failed" -ne 1 ] && exit 0
+
+last_lines=$(echo "$output" | tail -120)
+
+# Repo = my-project (mobile build hooks always operate against this)
+repo_slug="my-project"
+repo_path=$(locate_repo "your-org/my-project" 2>/dev/null)
+[ -z "$repo_path" ] && repo_path="$HOME/my-project"
+branch=$(git -C "$repo_path" branch --show-current 2>/dev/null || echo "unknown")
+
+# Transient → tell user to retry, no agent
+if [ "$(config auto_rerun_transients true)" = "true" ] && is_transient "$last_lines"; then
+ notify "Build transient" "Detected transient ($cmd) — recommend retry"
+ cat <<JSON
+{
+ "suppressOutput": true,
+ "hookSpecificOutput": {
+ "hookEventName": "PostToolUse",
+ "additionalContext": "[ops-deploy-fix] '${cmd:0:60}' failed with a transient signature (network/registry/runner blip). No fixer dispatched — retry the build."
+ }
+}
+JSON
+ exit 0
+fi
+
+# Dedup: same failure tail twice = skip
+if already_seen "$repo_slug-build" "$last_lines"; then
+ notify "Duplicate build failure" "$cmd same root cause — fixer NOT re-dispatched"
+ exit 0
+fi
+
+if [ "$(config auto_dispatch_fixer true)" != "true" ]; then
+ notify "Build failed" "$cmd — auto_dispatch_fixer=false, manual intervention"
+ exit 0
+fi
+
+fix_log=$(dispatch_fix_agent "build-fix.md" "$repo_slug-build" \
+ "COMMAND=$cmd" "REPO_PATH=$repo_path" "BRANCH=$branch" "LOGS=$last_lines")
+case $? in
+ 0)
+ cat <<JSON
+{
+ "suppressOutput": true,
+ "hookSpecificOutput": {
+ "hookEventName": "PostToolUse",
+ "additionalContext": "[ops-deploy-fix] Build failure detected in '${cmd:0:60}'. Haiku build-fixer dispatched (logs: $fix_log). Will open fix PR or report transient."
+ }
+}
+JSON
+ ;;
+ 2|3) notify "Auto-fix skipped" "$repo_slug — already in flight or budget exhausted" ;;
+esac
+exit 0
diff --git a/claude-ops/bin/ops-deploy-fix-merge-trigger b/claude-ops/bin/ops-deploy-fix-merge-trigger
new file mode 100755
index 00000000..a61825a4
--- /dev/null
+++ b/claude-ops/bin/ops-deploy-fix-merge-trigger
@@ -0,0 +1,38 @@
+#!/usr/bin/env bash
+# ops-deploy-fix-merge-trigger — PostToolUse hook on Bash, gated by `if: Bash(gh pr merge *)`.
+# Detects `gh pr merge <pr> --repo <owner/repo>` and spawns the deploy monitor in the background.
+# Single-flight per repo:base via lock; never duplicates.
+set -e
+PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
+. "$PLUGIN_ROOT/scripts/lib/deploy-fix-common.sh"
+
+is_enabled monitor_post_merge || exit 0
+
+INPUT=$(cat)
+cmd=$(printf '%s' "$INPUT" | jq -r '.tool_input.command // ""' 2>/dev/null)
+case "$cmd" in *"gh pr merge "*) ;; *) exit 0 ;; esac
+
+pr=$(printf '%s' "$cmd" | sed -E 's/.*gh pr merge[[:space:]]+([0-9]+).*/\1/' | head -c 10)
+repo=$(printf '%s' "$cmd" | sed -nE 's/.*--repo[[:space:]]+([^[:space:]]+).*/\1/p' | head -c 80)
+[ -z "$pr" ] || [ -z "$repo" ] && exit 0
+[[ "$pr" =~ ^[0-9]+$ ]] || exit 0
+
+# Single-flight: if a monitor is already in flight for this PR, no-op.
+slug=$(repo_slug_safe "$repo")
+monitor_lock="monitor-$slug-pr$pr"
+if [ -f "$STATE_DIR/lock-$monitor_lock" ] && kill -0 "$(cat "$STATE_DIR/lock-$monitor_lock" 2>/dev/null)" 2>/dev/null; then
+ exit 0
+fi
+
+nohup bash "$PLUGIN_ROOT/scripts/ops-deploy-monitor.sh" "$repo" "$pr" </dev/null >/dev/null 2>&1 &
+disown 2>/dev/null || true
+
+cat <<JSON
+{
+ "suppressOutput": true,
+ "hookSpecificOutput": {
+ "hookEventName": "PostToolUse",
+ "additionalContext": "[ops-deploy-fix] Background monitor watching deploy of ${repo}#${pr}. Logs: ~/.claude/logs/ops-deploy-fix/. Will dispatch a Haiku fixer on failure (per-hour budget enforced)."
+ }
+}
+JSON
diff --git a/claude-ops/bin/ops-task-reminder b/claude-ops/bin/ops-task-reminder
new file mode 100755
index 00000000..625b9e80
--- /dev/null
+++ b/claude-ops/bin/ops-task-reminder
@@ -0,0 +1,43 @@
+#!/usr/bin/env bash
+# ops-task-reminder — PostToolUse hook on every tool.
+# Per-session counter at $STATE_DIR/task-reminder-<sid>. When N non-Task tool calls
+# occur without any Task* call, injects a system-reminder via additionalContext.
+# Counter resets to 0 on any Task* tool use.
+set -e
+PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
+. "$PLUGIN_ROOT/scripts/lib/deploy-fix-common.sh" 2>/dev/null || {
+ STATE_DIR="$HOME/.claude/state/ops"
+ mkdir -p "$STATE_DIR" 2>/dev/null
+ config() { echo "${2:-}"; }
+}
+
+[ "$(config task_reminder_enabled true)" = "false" ] && exit 0
+THRESHOLD=$(config task_reminder_threshold 10)
+
+INPUT=$(cat)
+sid=$(printf '%s' "$INPUT" | jq -r '.session_id // "default"' 2>/dev/null)
+tool=$(printf '%s' "$INPUT" | jq -r '.tool_name // ""' 2>/dev/null)
+state_file="$STATE_DIR/task-reminder-${sid}"
+
+case "$tool" in
+ Task*) echo 0 > "$state_file"; exit 0 ;;
+esac
+
+count=$(cat "$state_file" 2>/dev/null || echo 0)
+count=$((count + 1))
+
+if [ "$count" -ge "$THRESHOLD" ]; then
+ echo 0 > "$state_file"
+ cat <<JSON
+{
+ "suppressOutput": true,
+ "hookSpecificOutput": {
+ "hookEventName": "PostToolUse",
+ "additionalContext": "[ops-task-reminder] No Task* tool used in the last $THRESHOLD calls. For multi-step work, consider TaskCreate to track open items, TaskUpdate to mark progress, TaskList to review status. Skip this reminder if your current work is a single quick action."
+ }
+}
+JSON
+else
+ echo "$count" > "$state_file"
+fi
+exit 0
diff --git a/claude-ops/config/post-merge-services.example.json b/claude-ops/config/post-merge-services.example.json
new file mode 100644
index 00000000..7cfe944f
--- /dev/null
+++ b/claude-ops/config/post-merge-services.example.json
@@ -0,0 +1,5 @@
+{
+ "_doc": "Service health registry for ops-deploy-monitor. Key = '<owner/repo>:<base_branch>'. Each entry: { health: <url>, version: <url> (optional, returns {commit/sha/gitSha}) }. Layered lookup: project .claude/post-merge-services.json (committed) → user ~/.claude/config/post-merge-services.json → this plugin default. Add your own services in user-level or per-project file.",
+ "your-org/your-api:dev": { "health": "https://api-dev.example.com/health", "version": "https://api-dev.example.com/version" },
+ "your-org/your-api:main": { "health": "https://api.example.com/health", "version": "https://api.example.com/version" }
+}
diff --git a/claude-ops/hooks/hooks.json b/claude-ops/hooks/hooks.json
index 44b636dd..69474485 100644
--- a/claude-ops/hooks/hooks.json
+++ b/claude-ops/hooks/hooks.json
@@ -29,6 +29,35 @@
]
}
],
+ "PostToolUse": [
+ {
+ "matcher": "Bash",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "bash ${CLAUDE_PLUGIN_ROOT}/bin/ops-deploy-fix-merge-trigger 2>/dev/null || true",
+ "timeout": 5,
+ "if": "Bash(gh pr merge *)"
+ },
+ {
+ "type": "command",
+ "command": "bash ${CLAUDE_PLUGIN_ROOT}/bin/ops-deploy-fix-build-trigger 2>/dev/null || true",
+ "timeout": 5,
+ "if": "Bash(npm run build:*)"
+ }
+ ]
+ },
+ {
+ "matcher": "*",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "bash ${CLAUDE_PLUGIN_ROOT}/bin/ops-task-reminder 2>/dev/null || true",
+ "timeout": 3
+ }
+ ]
+ }
+ ],
"Stop": [
{
"hooks": [
diff --git a/claude-ops/prompts/build-fix.md b/claude-ops/prompts/build-fix.md
new file mode 100644
index 00000000..c0994141
--- /dev/null
+++ b/claude-ops/prompts/build-fix.md
@@ -0,0 +1,86 @@
+# Persona
+
+You are **Build Fixer** — a focused mobile/native build engineer persona spawned by the `claude-ops` plugin to repair a SINGLE failed local build (`npm run build:*`). You are NOT a feature engineer. One repair, one PR, exit.
+
+# Awareness
+
+You are headless inside Claude Code with full claude-ops tooling:
+
+| Need | Use |
+|---|---|
+| Mobile / Expo / RN / iOS Fastlane | spawn the `Mobile App Specialist` subagent |
+| TypeScript / type errors | spawn the `typescript-reviewer` subagent |
+| My-Project cross-repo contract breakage | spawn the `fullstack-mobile-architect` subagent |
+| Sentry context for runtime crashes | `mcp__sentry__search_events` |
+| Apple Developer / TestFlight state | `python3 scripts/asc-manage-builds.py` (in my-project repo) |
+| Doppler secret resolution | `doppler secrets get <KEY> --project my-project --config <env> --plain` |
+| Library version drift | `npx expo install --check`, `npm ls <pkg>`, Context7 MCP for docs |
+
+Do NOT invent agent names. Fall back to `general-purpose` if unsure.
+
+# Failure context
+
+- **Failed command**: `{{COMMAND}}`
+- **Repo path**: {{REPO_PATH}}
+- **Current branch**: {{BRANCH}}
+
+**Last 120 lines of output:**
+
+```
+{{LOGS}}
+```
+
+# Diagnosis taxonomy
+
+Categorize the failure into ONE bucket — your fix flows from the bucket:
+
+| Bucket | Signals | Fix path |
+|---|---|---|
+| **type-check** | `error TS2`, `error TS7` | Patch the offending file(s); rerun `npm run type-check`. |
+| **lint** | `error Parsing error`, ESLint rule fails | Fix in code (no `eslint-disable` shortcut). |
+| **expo-doctor / version drift** | `expo-doctor`, `package versions mismatch` | `npx expo install --check --fix`. |
+| **fastlane signing** | `Match`, `provisioning profile`, `code signing` | Re-sync via `bundle exec fastlane match nuke + match` (CONFIRM with user before nuke). |
+| **fastlane archive** | `xcodebuild`, `gym`, `Build FAILED` | Locate Xcode error in logs, patch in iOS native or RN bridge code. |
+| **App Store Connect transient** | `503`, `timed out`, `Apple ID server.*temporarily unavailable` | Recommend retry; do NOT open PR. |
+| **Doppler missing** | `DOPPLER_TOKEN`, `secret not found` | Surface the missing key + its required Doppler path; do NOT auto-rotate. |
+| **Dirty working tree** | `prepare-build-branch.sh.*Abort`, `Stash or commit your changes` | Stash the variant artifacts (`app.config.js`, `credentials.json`); recommend retry. |
+| **patch-package mismatch** | `verify-runtime-patches.js`, patch did not apply | Restore the patch invariant; reference `~/my-project/CLAUDE.md` Runtime patches section. |
+
+# Workflow
+
+1. **Diagnose** → bucket above.
+2. **Locate the repo** at {{REPO_PATH}} (already known). Verify `git status` is clean enough to branch.
+3. **Worktree** off current branch: `git worktree add .worktrees/fix-build-<short-ts>`.
+4. **Apply minimal fix.**
+5. **Verify** by re-running the appropriate gate:
+ - type-check failure → `npm run type-check`
+ - lint → `npm run lint:check`
+ - expo drift → `npx expo install --check`
+ - patch → `node scripts/verify-runtime-patches.js`
+6. **Commit `--no-verify`** with co-author trailer for Haiku.
+7. **Push + open PR** to `dev` (or current base). Title: `fix(build): <bucket>: <one-line>`. Body links to the failed command + log excerpt.
+
+# Hard guardrails — NON-NEGOTIABLE
+
+- **NEVER re-run `npm run build:all` / `build:*:local` yourself.** That's the operator's call.
+- **NEVER bump major dep versions.** Patch only.
+- **NEVER add `eslint-disable` / `@ts-ignore` to mask errors.** Fix the cause.
+- **NEVER touch `app.config.js` directly** — edit `src/config/app.config.<variant>.js` (per `~/my-project/CLAUDE.md`).
+- **NEVER invalidate signing material** (`fastlane match nuke`) without explicit confirmation.
+- **NEVER ship dependency upgrades unrelated to the bucket.**
+- **MAX 8 files changed.** If more, STOP and report scope mismatch.
+- **NEVER spawn more than 2 subagents.**
+- **NEVER call `/ops:ops-yolo` or fan-out skills.**
+- **NEVER commit secrets** or echo Doppler values into PR bodies.
+
+# Scope
+
+Repair THIS build failure. Not adjacent code, not unrelated test improvements, not docs unless contract changed.
+
+# Output (final line)
+
+- `RESOLVED: <PR_URL>` — fix opened, ready for retry
+- `RETRY: <reason>` — transient, no fix needed
+- `BLOCKED: <reason>` — human needed (e.g. credentials, signing decision)
+
+Final line MUST be one of these — anything else violates contract.
diff --git a/claude-ops/prompts/deploy-fix.md b/claude-ops/prompts/deploy-fix.md
new file mode 100644
index 00000000..839c02ba
--- /dev/null
+++ b/claude-ops/prompts/deploy-fix.md
@@ -0,0 +1,89 @@
+# Persona
+
+You are **Deploy Fixer** — a focused infrastructure SRE persona spawned by the `claude-ops` plugin to diagnose and remediate a SINGLE failed post-merge deployment. You are NOT a general-purpose engineer. You execute one repair, open one PR, and exit.
+
+# Awareness
+
+You are running headless inside a Claude Code session with full claude-ops tooling. Use these proactively:
+
+| Need | Use |
+|---|---|
+| Fetch failed CI logs | `gh run view {{RUN_ID}} --repo {{REPO}} --log-failed` |
+| Inspect ECS / AWS state | `/ops:ops-fires`, `/ops:ops-monitor`, raw `aws` CLI |
+| Sentry context for related errors | `/ops:ops-triage` or `mcp__sentry__search_events` |
+| Find prior fixes for similar failures | `gh search prs --repo {{REPO}} 'fix(deploy)' --state merged` |
+| My-Project mobile crashes / iOS build issues | spawn the `Mobile App Specialist` subagent |
+| My-Project backend / NestJS issues | spawn the `Health Data Expert` subagent |
+| Database performance / migration | spawn the `database-reviewer` subagent |
+| AWS infra / IAM / Terraform | spawn the `DevOps Engineer` subagent |
+
+**Do NOT** invent skill names — if unsure, fall back to `general-purpose` subagent.
+
+# Failure context
+
+- **Repo**: `{{REPO}}`
+- **PR**: #{{PR}} (already merged to `{{BASE}}` at commit `{{SHA}}`)
+- **Workflow run**: https://github.com/{{REPO}}/actions/runs/{{RUN_ID}}
+- **Failure summary**: {{SUMMARY}}
+
+**Failing logs (last 120 lines):**
+
+```
+{{LOGS}}
+```
+
+# Workflow
+
+1. **Diagnose root cause** from the logs. Categorize as one of:
+ - **Code defect** — type error, missing import, runtime crash, bad migration → fix in code
+ - **Config drift** — Doppler secret missing/rotated, env var renamed → fix config
+ - **Infra issue** — IAM permission, security group, ECR rate limit → fix infra (Terraform if available)
+ - **Transient** — flaky test, runner outage, registry blip → recommend rerun, do NOT open PR
+
+2. **Locate the repo** on disk. Search `~/Projects`, `~/`, `~/work`, `~/gsd-workspaces`. If not found, `gh repo clone` into `~/Projects/`.
+
+3. **Create a worktree** off `{{BASE}}`: `git worktree add .worktrees/fix-deploy-<short-sha> {{BASE}}`. NEVER work directly on the base branch.
+
+4. **Apply the minimal fix.** Surgical changes only.
+
+5. **Run the per-repo quality gate** before committing (per `~/.claude/CLAUDE.md`):
+ - `my-project-api`: `npm run type-check && npm run lint && npm run test:unit`
+ - `my-project`: `npm run type-check`
+ - `my-project-langgraphs` / `my-project-agentcore` / `meditation-service`: `source .venv/bin/activate && pytest tests/ -x --ignore=tests/e2e`
+ - other Node repos: `npm run type-check && npm run lint && npm test`
+
+6. **Commit with `--no-verify`** (project hooks are bugged per Sam's CLAUDE.md). Co-author trailer: `Co-Authored-By: Claude Haiku 4.5 <[email protected]>`.
+
+7. **Push + open PR** targeting `{{BASE}}`:
+ - Title: `fix(deploy): <one-line root cause>`
+ - Body: link to the failed run, the diagnosed root cause, the change rationale, the gate results.
+
+# Hard guardrails — NON-NEGOTIABLE
+
+- **NEVER merge the PR yourself.** Leave that to the next `/ops:ops-merge` cycle.
+- **NEVER force-push** to `dev` or `main`.
+- **NEVER touch files outside the diagnosed root cause.** No "while I'm here" cleanups.
+- **NEVER skip CI hooks except via `--no-verify`** (already documented as bugged).
+- **NEVER commit secrets.** If you discover one in the logs, redact in the PR body and notify via `/ops:ops-comms`.
+- **MAX 10 files changed.** If the fix needs more, STOP and report — likely scope mismatch.
+- **NEVER spawn more than 2 subagents.** This session is already a subagent.
+- **NEVER call `/ops:ops-yolo`, `/ops:ops-orchestrate`, or anything that fans out parallel work.** You have one job.
+- **NEVER send outbound comms** (email, Slack, WhatsApp) — read-only on those surfaces.
+- **NEVER ship unrelated dependency upgrades.** If a transitive bump is needed, pin to the exact required version only.
+
+# Scope
+
+You are responsible for fixing **this one deploy failure**. You are NOT responsible for:
+- Refactoring adjacent code
+- Improving test coverage beyond the regression
+- Updating docs unless the fix changes a public contract
+- Other failing deploys on other repos
+
+# Output (final line of your run)
+
+Last line of your output MUST be one of:
+- `RESOLVED: <PR_URL>` — fix opened, ready for the merge cycle
+- `RERUN: <reason>` — transient, asked the user to retry
+- `BLOCKED: <reason>` — could not auto-fix; human needed
+
+Anything else is a violation of this contract.
diff --git a/claude-ops/scripts/lib/deploy-fix-common.sh b/claude-ops/scripts/lib/deploy-fix-common.sh
new file mode 100755
index 00000000..763b56c1
--- /dev/null
+++ b/claude-ops/scripts/lib/deploy-fix-common.sh
@@ -0,0 +1,202 @@
+#!/usr/bin/env bash
+# deploy-fix-common.sh — shared helpers for the deploy/build auto-fix subsystem.
+# Sourced by hook scripts and the background monitor. Uses ${CLAUDE_PLUGIN_ROOT}
+# when invoked from inside the plugin; falls back to inferred paths.
+
+set -u
+
+PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-}"
+[ -z "$PLUGIN_ROOT" ] && PLUGIN_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+export PLUGIN_ROOT
+
+PREFS_DIR="${HOME}/.claude/plugins/data/ops-ops-marketplace"
+PREFS_FILE="$PREFS_DIR/preferences.json"
+STATE_DIR="${OPS_DEPLOY_FIX_STATE:-${HOME}/.claude/state/ops-deploy-fix}"
+LOGS_DIR="${OPS_DEPLOY_FIX_LOGS:-${HOME}/.claude/logs/ops-deploy-fix}"
+mkdir -p "$STATE_DIR" "$LOGS_DIR" 2>/dev/null
+
+# config <key> <default> — reads CLAUDE_PLUGIN_OPTION_<KEY>, then plugin prefs, then default
+config() {
+ local key="$1" default="$2"
+ local env_var="CLAUDE_PLUGIN_OPTION_$(echo "$key" | tr '[:lower:]' '[:upper:]')"
+ if [ -n "${!env_var:-}" ]; then echo "${!env_var}"; return; fi
+ if [ -f "$PREFS_FILE" ]; then
+ local v=$(jq -r --arg k "$key" '.[$k] // .deploy_fix[$k] // empty' "$PREFS_FILE" 2>/dev/null)
+ [ -n "$v" ] && [ "$v" != "null" ] && { echo "$v"; return; }
+ fi
+ echo "$default"
+}
+
+is_enabled() {
+ [ "$(config deploy_fix_enabled true)" = "true" ] && [ "$(config "$1" true)" = "true" ]
+}
+
+repo_slug_safe() { echo "$1" | tr '/' '-'; }
+
+# Single-flight lock per repo+kind. Returns 0 if acquired, 1 if held.
+lock_acquire() {
+ local id="$1"
+ local f="$STATE_DIR/lock-$id"
+ if [ -f "$f" ]; then
+ local pid=$(cat "$f" 2>/dev/null)
+ if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
+ return 1 # alive
+ fi
+ rm -f "$f" # stale
+ fi
+ echo $$ > "$f"
+ return 0
+}
+lock_release() { rm -f "$STATE_DIR/lock-$1" 2>/dev/null; }
+
+# Hourly budget per repo. Returns 0 if under cap (and increments), 1 if over.
+budget_check_increment() {
+ local slug="$1"
+ local cap=$(config max_fixes_per_hour 3)
+ local hour=$(date +%Y%m%d-%H)
+ local f="$STATE_DIR/budget-$slug-$hour"
+ local n=$(cat "$f" 2>/dev/null || echo 0)
+ if [ "$n" -ge "$cap" ]; then return 1; fi
+ echo $((n + 1)) > "$f"
+ return 0
+}
+
+# Dedup by content hash — same failure tail twice in a row = skip second dispatch.
+already_seen() {
+ local slug="$1" content="$2"
+ local hash=$(printf '%s' "$content" | shasum | awk '{print $1}')
+ local f="$STATE_DIR/last-failure-$slug"
+ local last=$(cat "$f" 2>/dev/null || echo "")
+ if [ "$last" = "$hash" ]; then return 0; fi
+ echo "$hash" > "$f"
+ return 1
+}
+
+# Detect transient failure signatures. Returns 0 (transient) or 1.
+is_transient() {
+ printf '%s' "$1" | grep -qE \
+'ECONNRESET|ETIMEDOUT|EAI_AGAIN|EHOSTUNREACH|TLS handshake timeout|unexpected EOF while reading|Could not resolve host|network is unreachable|\
+npm error code E429|npm error 5(0[0-9]|2[0-9])|HTTP(S)?Error:? 429|HTTP(S)?Error:? 5[0-9]{2}|\
+The runner has received a shutdown signal|The hosted runner lost communication|The operation was canceled\.|GH001:|\
+TooManyRequestsException|ThrottlingException|RequestLimitExceeded|Service Unavailable Exception|\
+Apple ID server.*temporarily unavailable|App Store Connect.*timed out|ASC.*5[0-9]{2}|\
+Simulator failed to launch|ECR.*throttle'
+}
+
+notify() {
+ local title="$1" msg="$2"
+ local channel=$(config notify_channel macos)
+ case "$channel" in
+ macos)
+ command -v terminal-notifier >/dev/null && \
+ terminal-notifier -title "$title" -message "$msg" -sender com.apple.Terminal 2>/dev/null
+ ;;
+ ntfy)
+ local topic=$(config ntfy_topic "")
+ [ -n "$topic" ] && curl -sS -X POST "https://ntfy.sh/$topic" -H "Title: $title" -d "$msg" >/dev/null 2>&1
+ ;;
+ discord)
+ local hook=$(config discord_default_webhook_url "")
+ [ -n "$hook" ] && curl -sS -X POST "$hook" -H 'Content-Type: application/json' \
+ -d "$(jq -n --arg c "**$title** — $msg" '{content:$c}')" >/dev/null 2>&1
+ ;;
+ pushover)
+ local user=$(config pushover_user_key "") token=$(config pushover_app_token "")
+ [ -n "$user" ] && [ -n "$token" ] && \
+ curl -sS https://api.pushover.net/1/messages.json \
+ --form-string "token=$token" --form-string "user=$user" \
+ --form-string "title=$title" --form-string "message=$msg" >/dev/null 2>&1
+ ;;
+ none) : ;;
+ esac
+}
+
+# Locate repo on disk via configurable search roots.
+locate_repo() {
+ local slug="$1" repo_only="${1#*/}"
+ local roots="$(config repo_search_roots "$HOME/Projects:$HOME")"
+ IFS=':' read -ra arr <<< "$roots"
+ for root in "${arr[@]}"; do
+ root="${root/#\~/$HOME}"
+ [ -d "$root/$repo_only" ] && { echo "$root/$repo_only"; return 0; }
+ [ -d "$root/$slug" ] && { echo "$root/$slug"; return 0; }
+ done
+ return 1
+}
+
+# Resolve health URL via layered registry: project → user → plugin example.
+resolve_health_url() {
+ local slug="$1" base="$2" key="$slug:$base"
+ local proj=$(locate_repo "$slug" 2>/dev/null)
+ if [ -n "$proj" ] && [ -f "$proj/.claude/post-merge-services.json" ]; then
+ local v=$(jq -r --arg k "$key" '.[$k].health // ""' "$proj/.claude/post-merge-services.json" 2>/dev/null)
+ [ -n "$v" ] && { echo "$v"; return; }
+ fi
+ local user_path="$(config registry_path "$HOME/.claude/config/post-merge-services.json")"
+ user_path="${user_path/#\~/$HOME}"
+ if [ -f "$user_path" ]; then
+ local v=$(jq -r --arg k "$key" '.[$k].health // ""' "$user_path" 2>/dev/null)
+ [ -n "$v" ] && { echo "$v"; return; }
+ fi
+ if [ -f "$PLUGIN_ROOT/config/post-merge-services.example.json" ]; then
+ jq -r --arg k "$key" '.[$k].health // ""' "$PLUGIN_ROOT/config/post-merge-services.example.json" 2>/dev/null
+ fi
+}
+
+resolve_version_url() {
+ local slug="$1" base="$2" key="$slug:$base"
+ local proj=$(locate_repo "$slug" 2>/dev/null)
+ if [ -n "$proj" ] && [ -f "$proj/.claude/post-merge-services.json" ]; then
+ local v=$(jq -r --arg k "$key" '.[$k].version // ""' "$proj/.claude/post-merge-services.json" 2>/dev/null)
+ [ -n "$v" ] && { echo "$v"; return; }
+ fi
+ local user_path="$(config registry_path "$HOME/.claude/config/post-merge-services.json")"
+ user_path="${user_path/#\~/$HOME}"
+ if [ -f "$user_path" ]; then
+ local v=$(jq -r --arg k "$key" '.[$k].version // ""' "$user_path" 2>/dev/null)
+ [ -n "$v" ] && { echo "$v"; return; }
+ fi
+ if [ -f "$PLUGIN_ROOT/config/post-merge-services.example.json" ]; then
+ jq -r --arg k "$key" '.[$k].version // ""' "$PLUGIN_ROOT/config/post-merge-services.example.json" 2>/dev/null
+ fi
+}
+
+dispatch_fix_agent() {
+ # $1 = prompt template path (in $PLUGIN_ROOT/prompts/), $2 = lock_id, rest = template vars as KEY=VAL
+ local template="$1" lock_id="$2"; shift 2
+ if ! lock_acquire "$lock_id"; then
+ return 2 # already in flight
+ fi
+ local slug="${lock_id%%:*}"
+ if ! budget_check_increment "$slug"; then
+ notify "Auto-fix budget exhausted" "$slug hit hourly cap — manual intervention needed"
+ lock_release "$lock_id"
+ return 3
+ fi
+
+ local prompt_file="$PLUGIN_ROOT/prompts/$template"
+ if [ ! -f "$prompt_file" ]; then
+ lock_release "$lock_id"
+ return 4
+ fi
+ local prompt=$(cat "$prompt_file")
+ for kv in "$@"; do
+ local k="${kv%%=*}" v="${kv#*=}"
+ prompt="${prompt//\{\{${k}\}\}/$v}"
+ done
+
+ local fix_log="$LOGS_DIR/fix-${lock_id}-$(date +%s).log"
+ local model=$(config fix_model haiku)
+ local danger_flag="--permission-mode acceptEdits"
+ [ "$(config allow_dangerous false)" = "true" ] && danger_flag="--dangerously-skip-permissions"
+
+ command -v claude >/dev/null || { lock_release "$lock_id"; return 5; }
+
+ nohup bash -c "
+ printf '%s' \"\$1\" | claude -p --model $model $danger_flag --no-session-persistence > '$fix_log' 2>&1
+ rm -f '$STATE_DIR/lock-$lock_id'
+ " _ "$prompt" </dev/null >/dev/null 2>&1 &
+ disown 2>/dev/null || true
+ echo "$fix_log"
+ return 0
+}
diff --git a/claude-ops/scripts/ops-deploy-monitor.sh b/claude-ops/scripts/ops-deploy-monitor.sh
new file mode 100755
index 00000000..3624f454
--- /dev/null
+++ b/claude-ops/scripts/ops-deploy-monitor.sh
@@ -0,0 +1,135 @@
+#!/usr/bin/env bash
+# ops-deploy-monitor.sh <owner/repo> <pr_number>
+#
+# Spawned by ops-deploy-fix-merge-trigger after a PR merges. Watches the deploy
+# workflow, audits service health, dispatches Haiku fixer on failure.
+# Single-flight via lock; budget-capped per repo per hour; transient detection.
+set -u
+PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
+. "$PLUGIN_ROOT/scripts/lib/deploy-fix-common.sh"
+
+REPO="${1:?usage: $0 <owner/repo> <pr_number>}"
+PR="${2:?usage: $0 <owner/repo> <pr_number>}"
+SLUG=$(repo_slug_safe "$REPO")
+LOG="$LOGS_DIR/monitor-$SLUG-pr$PR.log"
+log() { printf '[%s] %s/#%s %s\n' "$(date '+%H:%M:%S')" "$REPO" "$PR" "$*" >> "$LOG"; }
+fire() { log "❌ $*"; printf '[%s] %s/#%s ❌ %s\n' "$(date '+%Y-%m-%dT%H:%M:%S')" "$REPO" "$PR" "$*" >> "$LOGS_DIR/fires.log"; }
+
+# Single-flight monitor lock
+MONITOR_LOCK="monitor-$SLUG-pr$PR"
+lock_acquire "$MONITOR_LOCK" || { log "monitor already running, exit"; exit 0; }
+trap 'lock_release "$MONITOR_LOCK"' EXIT
+
+log "monitor starting"
+
+sleep 5
+PR_INFO=$(gh pr view "$PR" --repo "$REPO" --json baseRefName,mergeCommit,state 2>/dev/null)
+BASE=$(echo "$PR_INFO" | jq -r '.baseRefName // ""')
+SHA=$(echo "$PR_INFO" | jq -r '.mergeCommit.oid // ""')
+STATE=$(echo "$PR_INFO" | jq -r '.state // ""')
+
+[ "$STATE" != "MERGED" ] && { log "not merged ($STATE) — exit"; exit 0; }
+[ "$BASE" != "dev" ] && [ "$BASE" != "main" ] && { log "base=$BASE, skip"; exit 0; }
+log "merged to $BASE @ $SHA"
+
+# Find deploy workflow run
+PATTERN=$(config deploy_workflow_pattern "deploy|Deploy|build|Build|ECS|cd|CD")
+RUN_ID=""
+for i in $(seq 1 12); do
+ RUN_ID=$(gh run list --repo "$REPO" --branch "$BASE" --limit 5 \
+ --json databaseId,headSha,name --jq \
+ ".[] | select(.headSha==\"$SHA\" and (.name | test(\"$PATTERN\"))) | .databaseId" 2>/dev/null | head -1)
+ [ -n "$RUN_ID" ] && break
+ sleep 15
+done
+if [ -z "$RUN_ID" ]; then
+ RUN_ID=$(gh run list --repo "$REPO" --branch "$BASE" --limit 5 \
+ --json databaseId,headSha --jq ".[] | select(.headSha==\"$SHA\") | .databaseId" 2>/dev/null | head -1)
+fi
+[ -z "$RUN_ID" ] && { log "no run found — exit"; exit 0; }
+log "tracking run #$RUN_ID"
+
+# Wait for completion (configurable timeout)
+TIMEOUT=$(config watcher_timeout_seconds 1800)
+gh run watch "$RUN_ID" --repo "$REPO" --exit-status >> "$LOG" 2>&1 &
+WATCH_PID=$!
+( sleep "$TIMEOUT"; kill -9 $WATCH_PID 2>/dev/null ) &
+TIMEOUT_PID=$!
+wait $WATCH_PID; RC=$?
+kill -9 $TIMEOUT_PID 2>/dev/null
+
+CONCLUSION=$(gh run view "$RUN_ID" --repo "$REPO" --json conclusion --jq .conclusion 2>/dev/null)
+log "conclusion=$CONCLUSION rc=$RC"
+
+if [ "$CONCLUSION" != "success" ]; then
+ failed_log=$(gh run view "$RUN_ID" --repo "$REPO" --log-failed 2>/dev/null | tail -120)
+
+ # Transient → rerun, no agent
+ if [ "$(config auto_rerun_transients true)" = "true" ] && is_transient "$failed_log"; then
+ log "transient detected → gh run rerun"
+ gh run rerun "$RUN_ID" --repo "$REPO" --failed >> "$LOG" 2>&1
+ notify "Auto-rerun: transient" "$REPO #$PR — workflow rerun on transient failure"
+ exit 0
+ fi
+
+ # Dedup — same failure tail twice in a row = skip
+ if already_seen "$SLUG-deploy" "$failed_log"; then
+ log "duplicate failure — already dispatched fixer for this signature, skipping"
+ notify "Duplicate failure" "$REPO #$PR same root cause as last run — fixer NOT re-dispatched"
+ exit 0
+ fi
+
+ fire "deploy #$RUN_ID concluded $CONCLUSION"
+ notify "Deploy failed" "$REPO #$PR → $BASE: $CONCLUSION"
+
+ if [ "$(config auto_dispatch_fixer true)" = "true" ]; then
+ fix_log=$(dispatch_fix_agent "deploy-fix.md" "$SLUG-deploy" \
+ "REPO=$REPO" "PR=$PR" "BASE=$BASE" "SHA=$SHA" "RUN_ID=$RUN_ID" \
+ "SUMMARY=deploy workflow #$RUN_ID concluded $CONCLUSION" \
+ "LOGS=$failed_log")
+ case $? in
+ 0) log "fixer dispatched → $fix_log" ;;
+ 2) log "fixer skipped — already in flight for $SLUG-deploy" ;;
+ 3) log "fixer skipped — hourly budget exhausted" ;;
+ *) log "fixer dispatch failed — exit code $?" ;;
+ esac
+ else
+ log "auto_dispatch_fixer=false — notification only"
+ fi
+ exit 1
+fi
+
+# Health audit
+[ "$(config audit_health_after_deploy true)" != "true" ] && { log "audit_health_after_deploy=false — done"; exit 0; }
+URL=$(resolve_health_url "$REPO" "$BASE")
+[ -z "$URL" ] && { log "no health URL registered for $REPO:$BASE — done"; exit 0; }
+
+sleep 10
+HTTP=$(curl -sS -o /dev/null -w '%{http_code}' --max-time 15 "$URL" 2>/dev/null || echo 000)
+if [ "$HTTP" != "200" ]; then
+ fire "service $URL → HTTP $HTTP after deploy"
+ notify "Service unhealthy" "$REPO $BASE: $URL → HTTP $HTTP"
+ if [ "$(config auto_dispatch_fixer true)" = "true" ]; then
+ dispatch_fix_agent "deploy-fix.md" "$SLUG-health" \
+ "REPO=$REPO" "PR=$PR" "BASE=$BASE" "SHA=$SHA" "RUN_ID=$RUN_ID" \
+ "SUMMARY=service health URL $URL returned HTTP $HTTP" \
+ "LOGS=(no workflow logs — health check failure)" >/dev/null
+ fi
+ exit 1
+fi
+log "health $URL → 200"
+
+# Verify served commit
+if [ "$(config verify_served_commit true)" = "true" ]; then
+ VERSION_URL=$(resolve_version_url "$REPO" "$BASE")
+ if [ -n "$VERSION_URL" ]; then
+ served=$(curl -sS --max-time 10 "$VERSION_URL" 2>/dev/null | jq -r '.commit // .sha // .gitSha // ""' 2>/dev/null)
+ if [ -n "$served" ] && [ "${served:0:7}" = "${SHA:0:7}" ]; then
+ log "served ${served:0:7} matches merge ✓"
+ elif [ -n "$served" ]; then
+ fire "version mismatch served=${served:0:7} expected=${SHA:0:7}"
+ notify "Version mismatch" "$REPO $BASE serving ${served:0:7}, expected ${SHA:0:7}"
+ fi
+ fi
+fi
+log "audit complete ✓"