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.

fix(deploy-fix): replace gh run watch with bounded REST polling (#886)

Aurora Capital596d9ce6bb58
diff --git a/claude-ops/CHANGELOG.md b/claude-ops/CHANGELOG.md
index 868810f8..21878012 100644
--- a/claude-ops/CHANGELOG.md
+++ b/claude-ops/CHANGELOG.md
@@ -1,5 +1,20 @@
## Unreleased
+- fix(deploy-fix): `scripts/ops-deploy-monitor.sh` no longer calls `gh run watch`.
+ That call blocks, polls every 2-5s with no tick cap, and is the exact pattern
+ `hooks/gh-watch-guard.sh` denies for every other caller. The monitor is spawned
+ by a PostToolUse hook on any `gh pr merge`, so one merge could arm an uncapped
+ poller. It now polls `gh api repos/{owner}/{repo}/actions/runs/{id}` on a 30s
+ sleep floor, capped at 60 ticks and a 1800s wall-clock deadline. PR and run
+ lookups moved from `gh pr view --json` / `gh run list --json` (GraphQL-backed)
+ to `gh api repos/...` (REST). `gh api rate_limit` — which spends no quota —
+ gates every polling phase and bails out with a log line below 200 remaining.
+ The same banned patterns were removed from `skills/ops-deploy/SKILL.md`,
+ `skills/ops-merge/SKILL.md` and `skills/ops-merge/references/cli.md`, which
+ had been telling agents to run them. `tests/mocks/gh` now serves the REST
+ endpoints and exits 90 if anything invokes `gh run watch`; test case 12 in
+ `tests/test-deploy-fix-hooks.sh` guards the script against regression.
+
- Slim `ops-inbox` SKILL.md (~6k → ~2k words): runtime, Workflow JS, and Agent Teams moved to `references/`. Rewrite remaining skill descriptions with real NL triggers (Claude / Grok / Hermes share the same `skills/` tree).
- Sync harness ports: `hermes-plugin/plugin.yaml` version matches `plugin.json`; installer default ref tracks the latest tag; `ops-release` bumps both. Grok still loads the Claude plugin (no `.grok-plugin`). Docs: `.mcp.json` is empty on purpose.
diff --git a/claude-ops/scripts/ops-deploy-monitor.sh b/claude-ops/scripts/ops-deploy-monitor.sh
index 1a3c7865..3d3412e5 100755
--- a/claude-ops/scripts/ops-deploy-monitor.sh
+++ b/claude-ops/scripts/ops-deploy-monitor.sh
@@ -4,6 +4,15 @@
# 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.
+#
+# Rate discipline (matches ~/.claude/scripts/gh-pr-watch.sh):
+# * NO `gh run watch` / `gh pr checks --watch` — those poll every 2-5s with no
+# cap and are denied by hooks/gh-watch-guard.sh.
+# * Every GitHub read is one-shot `gh api repos/...` (REST bucket), never
+# `gh pr view --json` / `gh run list --json` (GraphQL-backed).
+# * `gh api rate_limit` gates each phase. That endpoint is free — it does not
+# consume quota — so it is safe to call before every poll phase.
+# * Bounded polling: hard tick cap + sleep floor + wall-clock deadline.
set -u
PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
@@ -22,6 +31,45 @@ 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"; }
+# ── Rate discipline ────────────────────────────────────────────────────────
+# Bounded-poll parameters. Every one is overridable via `config`, but the
+# defaults are deliberate:
+# POLL_SLEEP=30 — floor, never below the 25s house minimum. A deploy that
+# finishes between ticks is still caught on the next tick.
+# RUN_LOOKUP_TICKS=8 / RUN_LOOKUP_SLEEP=15 — a workflow run is registered by
+# GitHub within ~2min of a merge; 8 x 15s = 2min covers it.
+# TIMEOUT=1800 — unchanged from the old `watcher_timeout_seconds` default,
+# so the outward behaviour of a slow deploy is the same.
+# With a 30s floor, 1800s of wall clock is 60 ticks, so MAX_TICKS=60 and the
+# deadline bind at the same moment. Whichever trips first, the loop stops:
+# there is no configuration in which this can spin indefinitely.
+POLL_SLEEP=$(config deploy_poll_sleep_seconds 30)
+[ "$POLL_SLEEP" -lt 25 ] 2>/dev/null && POLL_SLEEP=25
+TIMEOUT=$(config watcher_timeout_seconds 1800)
+MAX_TICKS=$(config deploy_poll_max_ticks 60)
+RUN_LOOKUP_TICKS=$(config deploy_run_lookup_ticks 8)
+RUN_LOOKUP_SLEEP=$(config deploy_run_lookup_sleep_seconds 15)
+RATE_FLOOR=$(config gh_rate_floor 200)
+
+# rate_ok — pre-flight gate. `gh api rate_limit` is itself quota-free, so this
+# costs nothing. Returns 1 when the REST (core) bucket is below the floor.
+rate_ok() {
+ local rem
+ rem=$(gh api rate_limit --jq '.resources.core.remaining' 2>/dev/null)
+ case "$rem" in
+ ''|*[!0-9]*) return 0 ;; # unreadable → do not block the monitor
+ esac
+ if [ "$rem" -lt "$RATE_FLOOR" ]; then
+ log "rate gate: REST core bucket at $rem (floor $RATE_FLOOR) — bailing out, no polling"
+ return 1
+ fi
+ return 0
+}
+
+# One-shot REST reads. All of these land in the core (REST) bucket.
+api() { gh api -H 'Accept: application/vnd.github+json' "repos/$REPO/$1" 2>/dev/null; }
+
+
# Single-flight monitor lock
MONITOR_LOCK="monitor-$SLUG-pr$PR"
lock_acquire "$MONITOR_LOCK" || { log "monitor already running, exit"; exit 0; }
@@ -29,11 +77,19 @@ trap 'lock_release "$MONITOR_LOCK"' EXIT
log "monitor starting"
+rate_ok || exit 0
+
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 // ""')
+# REST pulls/{n}: base.ref, merge_commit_sha, merged. Same three facts the old
+# `gh pr view --json baseRefName,mergeCommit,state` returned, off the REST bucket.
+PR_INFO=$(api "pulls/$PR")
+BASE=$(echo "$PR_INFO" | jq -r '.base.ref // ""')
+SHA=$(echo "$PR_INFO" | jq -r '.merge_commit_sha // ""')
+if [ "$(echo "$PR_INFO" | jq -r '.merged // false')" = "true" ]; then
+ STATE=MERGED
+else
+ STATE=$(echo "$PR_INFO" | jq -r '(.state // "") | ascii_upcase')
+fi
[ "$STATE" != "MERGED" ] && { log "not merged ($STATE) — exit"; exit 0; }
[ "$BASE" != "dev" ] && [ "$BASE" != "main" ] && { log "base=$BASE, skip"; exit 0; }
@@ -41,32 +97,55 @@ log "merged to $BASE @ $SHA"
# Find deploy workflow run
PATTERN=$(config deploy_workflow_pattern "deploy|Deploy|build|Build|ECS|cd|CD")
+RUNS_PATH="actions/runs?branch=$BASE&head_sha=$SHA&per_page=10"
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)
+for _ in $(seq 1 "$RUN_LOOKUP_TICKS"); do
+ rate_ok || exit 0
+ RUN_ID=$(api "$RUNS_PATH" \
+ | jq -r --arg p "$PATTERN" \
+ '(.workflow_runs // [])[] | select((.name // "") | test($p)) | .id' 2>/dev/null | head -1)
[ -n "$RUN_ID" ] && break
- sleep 15
+ sleep "$RUN_LOOKUP_SLEEP"
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)
+ # No name match — fall back to any run for this SHA.
+ RUN_ID=$(api "$RUNS_PATH" | jq -r '(.workflow_runs // [])[0].id // ""' 2>/dev/null)
fi
+[ "$RUN_ID" = "null" ] && RUN_ID=""
[ -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"
+# ── Wait for completion: bounded REST polling ─────────────────────────────
+# Replaces `gh run watch`, which blocks, polls every 2-5s internally, and has no
+# tick cap. Three independent stops: MAX_TICKS, the wall-clock DEADLINE, and the
+# rate gate. RC keeps the old contract (0 = success, 1 = anything else).
+DEADLINE=$(( $(date +%s) + TIMEOUT ))
+CONCLUSION=""
+STATUS=""
+RC=1
+for tick in $(seq 1 "$MAX_TICKS"); do
+ if [ "$(date +%s)" -ge "$DEADLINE" ]; then
+ log "poll deadline reached after ${TIMEOUT}s (tick $tick) — no verdict on run #$RUN_ID"
+ exit 0
+ fi
+ if ! rate_ok; then
+ # Quota floor is an OBSERVABILITY stop, not a deploy verdict. Falling through
+ # to the failure path here would dispatch a fixer against a run we never read.
+ log "rate floor reached at tick $tick — stopping polling, no verdict on run #$RUN_ID"
+ exit 0
+ fi
+ RUN_JSON=$(api "actions/runs/$RUN_ID")
+ STATUS=$(echo "$RUN_JSON" | jq -r '.status // ""')
+ CONCLUSION=$(echo "$RUN_JSON" | jq -r '.conclusion // ""')
+ [ "$CONCLUSION" = "null" ] && CONCLUSION=""
+ log "tick $tick/$MAX_TICKS status=${STATUS:-?} conclusion=${CONCLUSION:-pending}"
+ if [ "$STATUS" = "completed" ] || [ -n "$CONCLUSION" ]; then
+ break
+ fi
+ sleep "$POLL_SLEEP"
+done
+[ "$CONCLUSION" = "success" ] && RC=0
+log "conclusion=${CONCLUSION:-unknown} rc=$RC"
if [ "$CONCLUSION" != "success" ]; then
failed_log=$(gh run view "$RUN_ID" --repo "$REPO" --log-failed 2>/dev/null | tail -120)
diff --git a/claude-ops/skills/ops-deploy/SKILL.md b/claude-ops/skills/ops-deploy/SKILL.md
index a63dd26e..e09410b2 100644
--- a/claude-ops/skills/ops-deploy/SKILL.md
+++ b/claude-ops/skills/ops-deploy/SKILL.md
@@ -65,7 +65,11 @@ Before executing, load available context:
| --------------------------------------------------------------------------------------------------------- | -------------- | ------------------------------ |
| `gh run list --repo <owner/repo> --limit 5 --json status,conclusion,name,headBranch,createdAt,databaseId` | CI runs | JSON array |
| `gh run view <id> --repo <repo> --log-failed` | Failed CI logs | Log output |
-| `gh run watch <run-id> --repo <repo>` | Stream CI run | Live output (use with Monitor) |
+| `gh api repos/<repo>/actions/runs/<run-id> --jq .status,.conclusion` | Poll one CI run | JSON fields (REST bucket) |
+
+`gh run watch` and `gh pr checks --watch` are banned — they poll every 2-5s with no
+cap. `hooks/gh-watch-guard.sh` denies them. Poll the REST endpoint above on a `sleep
+30` floor with a finite tick count instead.
---
@@ -209,11 +213,23 @@ Trigger deploy for [project]:
### Monitor — live deploy streaming
-When watching a deploy in progress, use `Monitor` to stream logs:
+When watching a deploy in progress, call the approved monitor script. Do NOT
+hand-roll a `gh api` polling loop: `hooks/gh-watch-guard.sh` denies any
+for/while/until loop containing a quota-spending `gh` verb, so a hand-rolled
+loop is rejected before it ever polls. `gh run watch` is denied for the same
+reason (it polls every 2-5s with no cap).
+```bash
+${CLAUDE_PLUGIN_ROOT}/scripts/ops-deploy-monitor.sh <owner/repo> <pr-number>
```
-Monitor(command: "gh run watch <run-id> --repo <repo>")
-```
+
+That script owns the bounded poll: a tick cap, a wall-clock deadline, a 25s
+sleep floor and a REST rate gate, all in one place. It is also what the
+`bin/ops-deploy-fix-merge-trigger` PostToolUse hook spawns, so the interactive
+path and the automatic path share one implementation and one set of limits.
+
+Only a `/rate_limit`-only loop is exempt from the guard (that endpoint is
+quota-free) — useful for blocking until quota recovers, not for watching a run.
For ECS deploys: `Monitor(command: "aws ecs wait services-stable --cluster <cluster> --services <service>")`
diff --git a/claude-ops/skills/ops-merge/SKILL.md b/claude-ops/skills/ops-merge/SKILL.md
index 05b67158..f4eb6b9d 100644
--- a/claude-ops/skills/ops-merge/SKILL.md
+++ b/claude-ops/skills/ops-merge/SKILL.md
@@ -430,7 +430,9 @@ For each repo that has separate `dev` and `main` branches:
```
3. If confirmed: create sync PR: `gh pr create --repo <repo> --base main --head dev --title "chore: sync dev → main"`
-4. Wait for CI: `gh pr checks <sync-pr-number> --repo <repo> --watch` (background, max 10 min)
+4. Wait for CI via the approved monitor, never a hand-rolled loop and never
+ `--watch`. `hooks/gh-watch-guard.sh` denies both:
+ `${CLAUDE_PLUGIN_ROOT}/scripts/ops-deploy-monitor.sh <repo> <sync-pr-number>`
5. If CI green: `gh pr merge <sync-pr-number> --repo <repo> --merge` (merge commit, not squash; never `--admin`)
6. Pull main back into dev: `git -C <path> fetch origin && git -C <path> checkout dev && git -C <path> merge origin/main --no-edit`
@@ -560,13 +562,17 @@ the commit, and say which gate it skipped.
### Monitor — live CI watching
-When waiting for CI after a fixer pushes (Phase 3-4), use `Monitor` to stream the GitHub Actions run output instead of polling:
+When waiting for CI after a fixer pushes (Phase 3-4), call the approved monitor
+script. A hand-rolled `gh api` polling loop is denied by
+`hooks/gh-watch-guard.sh` before it runs, and `gh run watch` is banned outright
+(polls every 2-5s, no tick cap):
-```
-Monitor(command: "gh run watch <run-id> --repo <repo>")
+```bash
+${CLAUDE_PLUGIN_ROOT}/scripts/ops-deploy-monitor.sh <owner/repo> <pr-number>
```
-This avoids sleep loops and gives real-time feedback on CI progress.
+Tick cap, wall-clock deadline, 25s sleep floor and REST rate gate all live in
+that one script, so the interactive and hook-spawned paths cannot drift apart.
### Tasks — progress tracking
diff --git a/claude-ops/skills/ops-merge/references/cli.md b/claude-ops/skills/ops-merge/references/cli.md
index 12c1dcf3..11865e6c 100644
--- a/claude-ops/skills/ops-merge/references/cli.md
+++ b/claude-ops/skills/ops-merge/references/cli.md
@@ -13,7 +13,7 @@
| `gh pr create --repo <repo> --title "<t>" --body "<b>" --base dev` | Create PR | PR URL |
| `gh run list --repo <repo> --limit 5 --json conclusion,name,headBranch` | CI runs | JSON array |
| `gh run view <id> --repo <repo> --log-failed` | Failed CI logs | Log output |
-| `gh run watch <run-id> --repo <repo>` | Stream CI run | Live output (use with Monitor) |
+| `gh api repos/<repo>/actions/runs/<run-id> --jq .status,.conclusion` | Poll one CI run | JSON fields (REST bucket) |
| `gh api repos/<repo>/pulls/<n>/comments --jq '.[].body'` | PR review comments | Comment text |
---
diff --git a/claude-ops/tests/mocks/gh b/claude-ops/tests/mocks/gh
index da4d3f68..2abfa176 100755
--- a/claude-ops/tests/mocks/gh
+++ b/claude-ops/tests/mocks/gh
@@ -3,8 +3,15 @@
# MOCK_GH_PR_VIEW_JSON — JSON returned by `gh pr view ... --json ...`
# MOCK_GH_RUN_LIST_JSON — JSON array returned by `gh run list ... --json ...`
# (script will run --jq filter against it)
-# MOCK_GH_RUN_WATCH_RC — exit code from `gh run watch` (default 0)
+# MOCK_GH_RUN_WATCH_RC — legacy, accepted but unused (gh run watch is banned)
# MOCK_GH_RUN_VIEW_CONCLUSION — string conclusion ("success"/"failure"/...)
+# MOCK_GH_RUN_STATUS — run status for REST actions/runs/{id} (default "completed")
+# MOCK_GH_RATE_CORE — REST core remaining for `gh api rate_limit` (default 5000)
+# MOCK_GH_RATE_GRAPHQL — GraphQL remaining for `gh api rate_limit` (default 5000)
+#
+# REST translation: the monitor now reads GitHub over `gh api repos/...`. The
+# MOCK_GH_PR_VIEW_JSON / MOCK_GH_RUN_LIST_JSON fixtures stay in their original
+# (gh --json) shape and are translated here, so existing test cases keep working.
# MOCK_GH_RUN_VIEW_LOG_FAILED — stdout for `gh run view ... --log-failed`
# MOCK_GH_LOG_FILE — append every invocation (argv) to this file
set -u
@@ -17,6 +24,83 @@ shift || true
sub2="${1:-}"
case "$sub" in
+ api)
+ # Collect the endpoint path (first non-flag arg) and any --jq filter.
+ path=""; api_jq=""
+ while [ $# -gt 0 ]; do
+ case "$1" in
+ --jq|-q) shift; api_jq="${1:-}" ;;
+ -H|--header|-f|-F|--method|-X) shift ;;
+ -*) : ;;
+ *) [ -z "$path" ] && path="$1" ;;
+ esac
+ shift || break
+ done
+
+ emit() {
+ if [ -n "$api_jq" ] && command -v jq >/dev/null 2>&1; then
+ printf '%s' "$1" | jq -r "$api_jq" 2>/dev/null
+ else
+ printf '%s' "$1"
+ fi
+ }
+
+ case "$path" in
+ rate_limit|/rate_limit)
+ # MOCK_GH_RATE_DROP_AFTER lets a test keep the bucket healthy for the
+ # pre-flight gate and drop it mid-loop, which is the only way to exercise
+ # the in-loop rate gate. Call count persists in a temp file.
+ _core="${MOCK_GH_RATE_CORE:-5000}"
+ if [ -n "${MOCK_GH_RATE_DROP_AFTER:-}" ]; then
+ _cf="${MOCK_GH_RATE_COUNTER_FILE:-${TMPDIR:-/tmp}/mock-gh-rate-calls-${MOCK_GH_RATE_COUNTER_ID:-default}}"
+ _n=$(cat "$_cf" 2>/dev/null || echo 0); _n=$((_n+1)); printf '%s' "$_n" > "$_cf"
+ [ "$_n" -gt "$MOCK_GH_RATE_DROP_AFTER" ] && _core="${MOCK_GH_RATE_DROPPED:-3}"
+ fi
+ emit "{\"resources\":{\"core\":{\"remaining\":${_core},\"limit\":5000},\"graphql\":{\"remaining\":${MOCK_GH_RATE_GRAPHQL:-5000},\"limit\":5000}}}"
+ exit 0
+ ;;
+ */pulls/*)
+ # Translate the gh --json PR shape into the REST pulls/{n} shape.
+ _default='{"baseRefName":"dev","mergeCommit":{"oid":"abcdef1234567890"},"state":"MERGED"}'
+ src="${MOCK_GH_PR_VIEW_JSON:-$_default}"
+ emit "$(printf '%s' "$src" | jq -c '{
+ base: {ref: (.baseRefName // "")},
+ merge_commit_sha: (.mergeCommit.oid // ""),
+ merged: ((.state // "") == "MERGED"),
+ state: (if (.state // "") == "MERGED" then "closed" else ((.state // "") | ascii_downcase) end)
+ }' 2>/dev/null)"
+ exit 0
+ ;;
+ */actions/runs/[0-9]*)
+ rid="${path##*/}"; rid="${rid%%\?*}"
+ rstatus="${MOCK_GH_RUN_STATUS:-completed}"
+ # A run that is not completed has no conclusion yet. Defaulting it to
+ # "success" made every in_progress fixture terminate the monitor on tick 1.
+ if [ -n "${MOCK_GH_RUN_VIEW_CONCLUSION:-}" ]; then
+ rconcl="\"${MOCK_GH_RUN_VIEW_CONCLUSION}\""
+ elif [ "$rstatus" = "completed" ]; then
+ rconcl='"success"'
+ else
+ rconcl='null'
+ fi
+ emit "{\"id\":${rid},\"status\":\"${rstatus}\",\"conclusion\":${rconcl}}"
+ exit 0
+ ;;
+ */actions/runs*)
+ # Translate the gh --json run-list array into REST {workflow_runs:[...]}.
+ src="${MOCK_GH_RUN_LIST_JSON:-[]}"
+ emit "$(printf '%s' "$src" | jq -c '{workflow_runs: [ .[] | {
+ id: (.databaseId // .id),
+ head_sha: (.headSha // .head_sha // ""),
+ name: (.name // ""),
+ status: "completed"
+ } ]}' 2>/dev/null)"
+ exit 0
+ ;;
+ esac
+ emit "{}"
+ exit 0
+ ;;
pr)
case "$sub2" in
view)
@@ -59,8 +143,10 @@ case "$sub" in
exit 0
;;
watch)
- echo "[mock-gh] watching run"
- exit "${MOCK_GH_RUN_WATCH_RC:-0}"
+ # `gh run watch` is a banned pattern (hooks/gh-watch-guard.sh denies it).
+ # Fail loudly so a regression cannot pass the suite silently.
+ echo "[mock-gh] FORBIDDEN: gh run watch was invoked" >&2
+ exit 90
;;
view)
# Detect --log-failed
diff --git a/claude-ops/tests/test-deploy-fix-hooks.sh b/claude-ops/tests/test-deploy-fix-hooks.sh
index 42d136c0..a1d8ae67 100755
--- a/claude-ops/tests/test-deploy-fix-hooks.sh
+++ b/claude-ops/tests/test-deploy-fix-hooks.sh
@@ -573,6 +573,103 @@ test_monitor_real_failure() {
}
test_monitor_real_failure
+# ===========================================================================
+# CASE 12 — rate discipline: no banned patterns, quota gate bails out
+# ===========================================================================
+echo ""
+echo "── Case 12: rate discipline ──────────────────────────────────────"
+test_monitor_rate_discipline() {
+ new_isolated_env "case12-rate"
+
+ # 12a — the monitor must not contain any banned polling pattern.
+ # Comment lines are stripped first: the header explains WHY those calls are
+ # banned and naming them there must not trip this guard.
+ monitor_code=$(grep -v '^[[:space:]]*#' "$PLUGIN_ROOT/scripts/ops-deploy-monitor.sh")
+ if printf '%s' "$monitor_code" \
+ | grep -qE 'gh[[:space:]]+run[[:space:]]+watch|gh[[:space:]]+pr[[:space:]]+checks[^|]*--watch'; then
+ fail "12a.no-banned-watch" "ops-deploy-monitor.sh still contains a banned gh watch call"
+ else
+ pass "12a.no-banned-watch"
+ fi
+
+ # 12b — status reads go through `gh api repos/...` (REST), not `--json` (GraphQL).
+ if printf '%s' "$monitor_code" \
+ | grep -qE 'gh[[:space:]]+(pr|run)[[:space:]]+(view|list)[^|]*--json'; then
+ fail "12b.rest-not-graphql" "monitor still uses a GraphQL-backed --json read"
+ else
+ pass "12b.rest-not-graphql"
+ fi
+
+ # 12c — an exhausted REST bucket makes the monitor bail out cleanly (rc 0,
+ # log line, no fixer dispatched).
+ export MOCK_GH_RATE_CORE=3
+ export MOCK_GH_PR_VIEW_JSON='{"baseRefName":"dev","mergeCommit":{"oid":"abcdef1234567890"},"state":"MERGED"}'
+ export MOCK_GH_RUN_LIST_JSON='[{"databaseId":42,"headSha":"abcdef1234567890","name":"deploy"}]'
+ export MOCK_GH_RUN_VIEW_CONCLUSION="failure"
+ ln -sf /usr/bin/true "$TEST_BIN/sleep" 2>/dev/null || true
+
+ bash "$PLUGIN_ROOT/scripts/ops-deploy-monitor.sh" "owner/repo12" "12" >/dev/null 2>&1
+ rc=$?
+ assert_eq "12c.rate-gate-exit-zero" "0" "$rc"
+ monitor_log="$TEST_LOGS/monitor-owner-repo12-pr12.log"
+ if grep -q "rate gate" "$monitor_log" 2>/dev/null; then
+ pass "12d.rate-gate-logged"
+ else
+ fail "12d.rate-gate-logged" "no rate gate line in $monitor_log"
+ fi
+ if [ ! -s "$TEST_LOGS/claude.log" ]; then
+ pass "12e.no-fixer-when-rate-limited"
+ else
+ fail "12e.no-fixer-when-rate-limited" "claude was invoked while rate-limited"
+ fi
+ unset MOCK_GH_RATE_CORE
+}
+test_monitor_rate_discipline
+
+echo ""
+echo "── Case 13: mid-loop rate gate is not a deploy verdict ───────────"
+# Regression guard. The in-loop rate gate used to be `rate_ok || break`, which
+# left CONCLUSION empty and RC=1, so the script fell through to the FAILURE
+# path and dispatched a fixer against a run it had never successfully read.
+# Case 12 cannot catch this: it starves the bucket before the pre-flight gate,
+# so the loop is never entered. Here the bucket is healthy for the pre-flight
+# read and drops afterwards, which is the only way to reach the in-loop gate.
+test_monitor_midloop_rate_gate() {
+ new_isolated_env "case13-midloop-rate"
+
+ export MOCK_GH_PR_VIEW_JSON='{"baseRefName":"dev","mergeCommit":{"oid":"abcdef1234567890"},"state":"MERGED"}'
+ export MOCK_GH_RUN_LIST_JSON='[{"databaseId":77,"headSha":"abcdef1234567890","name":"deploy"}]'
+ export MOCK_GH_RUN_STATUS="in_progress"
+ export MOCK_GH_RATE_COUNTER_FILE="$TEST_STATE/rate-calls"
+ export MOCK_GH_RATE_DROP_AFTER=2
+ export MOCK_GH_RATE_DROPPED=3
+ ln -sf /usr/bin/true "$TEST_BIN/sleep" 2>/dev/null || true
+
+ bash "$PLUGIN_ROOT/scripts/ops-deploy-monitor.sh" "owner/repo13" "13" >/dev/null 2>&1
+ rc=$?
+ assert_eq "13a.midloop-rate-exit-zero" "0" "$rc"
+
+ monitor_log="$TEST_LOGS/monitor-owner-repo13-pr13.log"
+
+ # The decisive assertion: a quota stop must NOT be reported as a conclusion.
+ if grep -qE 'conclusion=(unknown|) rc=1' "$monitor_log" 2>/dev/null; then
+ fail "13b.no-failure-verdict-on-rate-stop" \
+ "monitor turned a rate stop into a failure verdict in $monitor_log"
+ else
+ pass "13b.no-failure-verdict-on-rate-stop"
+ fi
+
+ if [ ! -s "$TEST_LOGS/claude.log" ]; then
+ pass "13c.no-fixer-on-midloop-rate-stop"
+ else
+ fail "13c.no-fixer-on-midloop-rate-stop" "a fixer was dispatched on a rate stop"
+ fi
+
+ unset MOCK_GH_RUN_STATUS MOCK_GH_RATE_DROP_AFTER MOCK_GH_RATE_DROPPED
+ unset MOCK_GH_RATE_COUNTER_FILE
+}
+test_monitor_midloop_rate_gate
+
# ===========================================================================
# SUMMARY
# ===========================================================================