diff --git a/plugins/pr-tools/README.md b/plugins/pr-tools/README.md index c76459d..2cf89e7 100644 --- a/plugins/pr-tools/README.md +++ b/plugins/pr-tools/README.md @@ -16,6 +16,14 @@ Part of the [`fin-2x`](../../README.md) marketplace. - **[attach-github-assets](./skills/attach-github-assets/)** — Upload local files (screenshots, screen recordings, images, videos) to GitHub as user-attachment assets and return markdown-ready URLs for PR descriptions, issue bodies, or PR/issue comments. - **[create-pr](./skills/create-pr/)** — Open or update a well-formed GitHub pull request for the current branch: gathers intent, validates the diff against it, applies public-repo safeguards, and writes a clean Why/How description. +## Watchers + +`create-pr` launches these three scripts in the background once a PR is created or updated, so the session never polls `gh pr view` / `gh pr checks` in a loop. Each blocks until something changes (or times out at ~9.5 minutes and prints a cursor to resume from): + +- **watch-pr-comments.sh** — blocks until a new comment, review, or inline review comment lands. +- **watch-pr-merged.sh** — blocks until the PR is merged or closed unmerged. +- **pr-check-watcher.sh** — blocks until all CI checks (check-runs and commit statuses) reach a terminal state. + ## Hooks `pr-tools` installs a `PreToolUse` hook that intercepts direct `gh pr create` calls and redirects you to the `create-pr` skill, so PRs go through its intent-gathering and public-repo safeguards. Once `create-pr` is loaded in the session, `gh pr create` runs normally. The hook only matches real invocations (not `gh pr create` mentioned inside a quoted string or heredoc), fails open on any ambiguity, and clears its per-session state on context compaction. diff --git a/plugins/pr-tools/scripts/pr-check-watcher.sh b/plugins/pr-tools/scripts/pr-check-watcher.sh new file mode 100755 index 0000000..4e83a2f --- /dev/null +++ b/plugins/pr-tools/scripts/pr-check-watcher.sh @@ -0,0 +1,192 @@ +#!/bin/bash +# pr-check-watcher.sh - ETag-based fast polling for GitHub PR checks +# +# Uses conditional HTTP requests (If-None-Match) to poll every 3 seconds +# with zero rate-limit cost for unchanged responses. Only 200 responses +# (where something actually changed) count against the API quota. +# +# Polls BOTH the check-runs API (GitHub Actions, etc.) and the commit +# statuses API (Buildkite, Jenkins, etc.) to match `gh pr checks` semantics. +# +# This is the generic CI-green watcher (any PR, any CI, fastest polling). +# Buildkite and Jenkins above are just examples of commit-status-based CI — +# any provider that posts to the commit statuses or check-runs API works. +# +# Usage: +# pr-check-watcher.sh [last-etags] +# +# Arguments: +# pr-url - Full GitHub PR URL (e.g., https://github.com/org/repo/pull/123) +# last-etags - Optional ETags from a previous run to resume polling +# (format: |||) +# +# Exit codes: +# 0 - All checks completed successfully +# 1 - One or more checks failed +# 2 - Error (invalid args, API failure) +# 3 - Timed out, caller should re-run with the RESUME_ETAGS printed on last line + +set -euo pipefail + +pr_url="${1:-}" +resume_etags="${2:-}" + +if [[ -z "$pr_url" ]]; then + echo "Usage: pr-check-watcher.sh [last-etags]" >&2 + exit 2 +fi + +# Extract owner/repo/pr_number from URL +if [[ "$pr_url" =~ github\.com/([^/]+)/([^/]+)/pull/([0-9]+) ]]; then + owner="${BASH_REMATCH[1]}" + repo="${BASH_REMATCH[2]}" + pr_number="${BASH_REMATCH[3]}" +else + echo "Error: Invalid PR URL: $pr_url" >&2 + exit 2 +fi + +# Get the HEAD commit SHA for the PR +head_sha=$(gh api "repos/$owner/$repo/pulls/$pr_number" --jq '.head.sha' 2>/dev/null) +if [[ -z "$head_sha" ]]; then + echo "Error: Could not get HEAD SHA for PR #$pr_number" >&2 + exit 2 +fi + +echo "Monitoring checks for PR #$pr_number (commit ${head_sha:0:7})..." + +# Parse resume ETags (format: |||) +runs_etag="" +status_etag="" +if [[ -n "$resume_etags" ]]; then + runs_etag="${resume_etags%%|||*}" + status_etag="${resume_etags#*|||}" + # If no ||| separator was present, status_etag equals the full string — clear it + if [[ "$status_etag" == "$resume_etags" ]]; then + status_etag="" + fi +fi + +last_summary="" +last_runs_body="" +last_status_body="" +poll_interval=3 +max_wait=570 # 9.5 minutes (leaves 30s buffer within Bash tool's 10-min timeout) +start_time=$(date +%s) + +# Helper: fetch an API endpoint with optional ETag, sets $fetch_code, $fetch_etag, $fetch_body +fetch_with_etag() { + local endpoint="$1" + local etag="$2" + local response + + if [[ -n "$etag" ]]; then + response=$(gh api "$endpoint" -i -H "If-None-Match: $etag" 2>&1) || true + else + response=$(gh api "$endpoint" -i 2>&1) || true + fi + + fetch_code=$(echo "$response" | head -1 | grep -oE '[0-9]{3}' | head -1) + fetch_etag=$(echo "$response" | grep -i '^etag:' | sed 's/^[Ee][Tt][Aa][Gg]: *//' | tr -d '\r') + fetch_body=$(echo "$response" | sed '1,/^\r*$/d') +} + +while true; do + elapsed=$(( $(date +%s) - start_time )) + if (( elapsed > max_wait )); then + echo "" + echo "Polling window expired after $(( max_wait / 60 )) minutes. Checks still running." + echo "Last status: $last_summary" + echo "RESUME_ETAGS=${runs_etag}|||${status_etag}" + exit 3 + fi + + runs_changed=false + status_changed=false + + # Poll check-runs API + fetch_with_etag "repos/$owner/$repo/commits/$head_sha/check-runs" "$runs_etag" + if [[ "$fetch_code" == "200" ]]; then + [[ -n "$fetch_etag" ]] && runs_etag="$fetch_etag" + last_runs_body="$fetch_body" + runs_changed=true + elif [[ "$fetch_code" != "304" ]]; then + echo "Warning: check-runs returned HTTP $fetch_code, retrying..." >&2 + fi + + # Poll commit statuses API + fetch_with_etag "repos/$owner/$repo/commits/$head_sha/status" "$status_etag" + if [[ "$fetch_code" == "200" ]]; then + [[ -n "$fetch_etag" ]] && status_etag="$fetch_etag" + last_status_body="$fetch_body" + status_changed=true + elif [[ "$fetch_code" != "304" ]]; then + echo "Warning: statuses returned HTTP $fetch_code, retrying..." >&2 + fi + + # If neither changed, skip processing + if [[ "$runs_changed" == "false" && "$status_changed" == "false" ]]; then + sleep "$poll_interval" + continue + fi + + # Count check runs + runs_total=$(echo "$last_runs_body" | jq '.total_count // 0') + runs_completed=$(echo "$last_runs_body" | jq '[.check_runs[] | select(.status == "completed")] | length') + runs_in_progress=$(echo "$last_runs_body" | jq '[.check_runs[] | select(.status == "in_progress")] | length') + runs_queued=$(echo "$last_runs_body" | jq '[.check_runs[] | select(.status == "queued")] | length') + runs_success=$(echo "$last_runs_body" | jq '[.check_runs[] | select(.conclusion == "success" or .conclusion == "skipped" or .conclusion == "neutral")] | length') + runs_failure=$(echo "$last_runs_body" | jq '[.check_runs[] | select(.conclusion == "failure" or .conclusion == "timed_out" or .conclusion == "cancelled")] | length') + + # Count commit statuses (from combined status endpoint, already deduplicated) + statuses_total=$(echo "$last_status_body" | jq '[.statuses // [] | .[]] | length') + statuses_success=$(echo "$last_status_body" | jq '[.statuses // [] | .[] | select(.state == "success")] | length') + statuses_failure=$(echo "$last_status_body" | jq '[.statuses // [] | .[] | select(.state == "failure" or .state == "error")] | length') + statuses_pending=$(echo "$last_status_body" | jq '[.statuses // [] | .[] | select(.state == "pending")] | length') + statuses_completed=$(( statuses_success + statuses_failure )) + + # Merge totals + total=$(( runs_total + statuses_total )) + completed=$(( runs_completed + statuses_completed )) + in_progress=$(( runs_in_progress + statuses_pending )) + queued=$runs_queued + success=$(( runs_success + statuses_success )) + failure=$(( runs_failure + statuses_failure )) + + if (( total == 0 )); then + if [[ "no_checks" != "$last_summary" ]]; then + echo "No checks found yet, waiting..." + last_summary="no_checks" + fi + sleep "$poll_interval" + continue + fi + + # Build summary string for change detection + summary="total=$total completed=$completed in_progress=$in_progress queued=$queued success=$success failure=$failure" + + # Only print when something changes + if [[ "$summary" != "$last_summary" ]]; then + echo "[$((elapsed))s] $completed/$total complete ($success passed, $failure failed, $in_progress pending, $queued queued)" + last_summary="$summary" + fi + + # Check terminal conditions + if (( completed == total && total > 0 )); then + if (( failure > 0 )); then + echo "" + echo "FAILED checks:" + # Failed check runs + echo "$last_runs_body" | jq -r '.check_runs[] | select(.conclusion == "failure" or .conclusion == "timed_out" or .conclusion == "cancelled") | " - \(.name): \(.conclusion) (\(.html_url))"' + # Failed commit statuses + echo "$last_status_body" | jq -r '.statuses // [] | .[] | select(.state == "failure" or .state == "error") | " - \(.context): \(.state) (\(.target_url))"' + exit 1 + else + echo "" + echo "All $total checks completed successfully." + exit 0 + fi + fi + + sleep "$poll_interval" +done diff --git a/plugins/pr-tools/scripts/tests/watch-pr-comments.bats b/plugins/pr-tools/scripts/tests/watch-pr-comments.bats new file mode 100644 index 0000000..ad9e068 --- /dev/null +++ b/plugins/pr-tools/scripts/tests/watch-pr-comments.bats @@ -0,0 +1,225 @@ +#!/usr/bin/env bats +# Tests for ../watch-pr-comments.sh +# +# Runs the whole script end-to-end against a mock `gh` on PATH. The mock +# dispatches on the requested endpoint (issue comments / reviews / review +# comments, page 1 vs page 2) and returns fixture JSON. When called with -i +# it wraps the body in an HTTP-response shape (status line, etag header, +# blank line, body) matching what fetch_with_etag expects; without -i it +# returns the bare body, matching the pagination fetches. +# WATCH_INTERVAL/WATCH_MAX_WAIT are zeroed so the suite runs in well under a +# second. + +setup() { + SCRIPT="$(cd "$(dirname "$BATS_TEST_FILENAME")/.." && pwd)/watch-pr-comments.sh" + + MOCK_BIN="$(mktemp -d)" + FIXTURES="$(mktemp -d)" + export FIXTURES + + export WATCH_INTERVAL=0 + export WATCH_MAX_WAIT=2 + + PR_URL="https://github.com/acme/widgets/pull/42" + SINCE="2025-01-01T00:00:00Z" + + printf '[]' > "$FIXTURES/issue_comments.json" + printf '[]' > "$FIXTURES/issue_comments_page2.json" + printf '[]' > "$FIXTURES/reviews.json" + printf '[]' > "$FIXTURES/review_comments.json" + printf '[]' > "$FIXTURES/review_comments_page2.json" + + _write_mock_gh + export PATH="$MOCK_BIN:$PATH" +} + +teardown() { + rm -rf "$MOCK_BIN" "$FIXTURES" +} + +_write_mock_gh() { + cat > "$MOCK_BIN/gh" <<'MOCK' +#!/usr/bin/env bash +# Mock gh. Dispatches on the api endpoint; reads fixtures from $FIXTURES. +set -uo pipefail +F="$FIXTURES" + +sub="${1:-}"; shift || true +if [[ "$sub" != "api" ]]; then + echo "gh: unexpected subcommand: $sub" >&2 + exit 1 +fi + +endpoint="" +with_headers=false +for a in "$@"; do + case "$a" in + -i) with_headers=true ;; + -*) ;; + *) [[ -z "$endpoint" ]] && endpoint="$a" ;; + esac +done + +case "$endpoint" in + *issues/*/comments\?*page=2*) + body="$(cat "$F/issue_comments_page2.json")" + ;; + *issues/*/comments\?*) + body="$(cat "$F/issue_comments.json")" + ;; + *pulls/*/reviews\?*) + body="$(cat "$F/reviews.json")" + ;; + *pulls/*/comments\?*page=2*) + body="$(cat "$F/review_comments_page2.json")" + ;; + *pulls/*/comments\?*) + body="$(cat "$F/review_comments.json")" + ;; + *) + echo "gh: unexpected endpoint: $endpoint" >&2 + exit 1 + ;; +esac + +if [[ "$with_headers" == "true" ]]; then + printf 'HTTP/2.0 200\n' + printf 'etag: "mock-etag"\n' + printf '\n' +fi +printf '%s\n' "$body" +MOCK + chmod +x "$MOCK_BIN/gh" +} + +run_watch() { + run "$SCRIPT" "$@" +} + +# The cursor for the next run is the poll-round start time (see the script +# header), so tests assert its ISO-8601 shape rather than an exact value. +assert_next_since_is_timestamp() { + [[ "$output" =~ NEXT_SINCE=2[0-9]{3}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z ]] +} + +# ============================================================ +# Usage +# ============================================================ + +@test "invalid PR URL exits 2" { + run_watch "not-a-pr-url" + [ "$status" -eq 2 ] + [[ "$output" == *"Usage: watch-pr-comments.sh"* || "$output" == *"Invalid PR or issue URL"* ]] +} + +@test "issue URL is accepted and PR-only endpoints are skipped" { + printf '[{"id":1,"user":{"login":"octocat"},"created_at":"2025-01-02T00:00:00Z","updated_at":"2025-01-02T00:00:00Z","body":"issue-hello"}]' > "$FIXTURES/issue_comments.json" + # A review that WOULD emit if reviews were polled — in issue mode the pulls/* + # endpoints must be skipped, so this sentinel must not appear in the output. + printf '[{"id":9,"user":{"login":"reviewer"},"submitted_at":"2025-01-02T00:00:00Z","state":"APPROVED","body":"SHOULD-NOT-APPEAR"}]' > "$FIXTURES/reviews.json" + + run_watch "https://github.com/acme/widgets/issues/42" "$SINCE" + [ "$status" -eq 0 ] + [[ "$output" == *"issue-hello"* ]] + [[ "$output" != *"SHOULD-NOT-APPEAR"* ]] +} + +# ============================================================ +# New issue comment +# ============================================================ + +@test "a new issue comment is printed and NEXT_SINCE advances" { + printf '[{"id":101,"user":{"login":"alice"},"created_at":"2025-06-01T12:00:00Z","updated_at":"2025-06-01T12:00:00Z","body":"Looks good, one nit: fix the typo"}]' > "$FIXTURES/issue_comments.json" + + run_watch "$PR_URL" "$SINCE" + [ "$status" -eq 0 ] + [[ "$output" == *"comment alice 2025-06-01T12:00:00Z: Looks good, one nit: fix the typo"* ]] + assert_next_since_is_timestamp +} + +@test "an edited old comment is reported with its edit time" { + # `since=` filters on updated_at, so an old comment edited after the cursor + # comes back — it must be reported under its edit time, not silently + # re-served on every subsequent run under its (pre-cursor) creation time. + printf '[{"id":102,"user":{"login":"alice"},"created_at":"2024-06-01T00:00:00Z","updated_at":"2025-06-02T09:00:00Z","body":"edited: actually use the other helper"}]' > "$FIXTURES/issue_comments.json" + + run_watch "$PR_URL" "$SINCE" + [ "$status" -eq 0 ] + [[ "$output" == *"comment alice 2025-06-02T09:00:00Z: edited: actually use the other helper"* ]] +} + +@test "an empty-body comment keeps its columns aligned" { + # Comments carry an empty state column; the delimiter must not collapse + # around empty fields (tab-IFS would shift the body into state). + printf '[{"id":103,"user":{"login":"carol"},"created_at":"2025-06-03T00:00:00Z","updated_at":"2025-06-03T00:00:00Z","body":""}]' > "$FIXTURES/issue_comments.json" + + run_watch "$PR_URL" "$SINCE" + [ "$status" -eq 0 ] + [[ "$output" == *"comment carol 2025-06-03T00:00:00Z:"* ]] +} + +# ============================================================ +# Pagination — a full first page means there is more to fetch +# ============================================================ + +@test "a full 100-item first page triggers a page-2 fetch" { + jq -n '[range(100) | {id: ., user: {login: "gen"}, created_at: "2025-06-01T00:00:00Z", updated_at: "2025-06-01T00:00:00Z", body: ("c" + (. | tostring))}]' > "$FIXTURES/issue_comments.json" + printf '[{"id":200,"user":{"login":"dave"},"created_at":"2025-06-01T00:01:00Z","updated_at":"2025-06-01T00:01:00Z","body":"second page comment"}]' > "$FIXTURES/issue_comments_page2.json" + + run_watch "$PR_URL" "$SINCE" + [ "$status" -eq 0 ] + [[ "$output" == *"c99"* ]] + [[ "$output" == *"second page comment"* ]] +} + +# ============================================================ +# Reviews — client-side cursor filtering (no since= support) +# ============================================================ + +@test "an older review is not emitted while a newer one is" { + cat > "$FIXTURES/reviews.json" < "$MOCK_BIN/gh" <<'BROKEN' +#!/usr/bin/env bash +echo "gh: Could not resolve host: api.github.com" >&2 +exit 1 +BROKEN + chmod +x "$MOCK_BIN/gh" + + run_watch "$PR_URL" "$SINCE" + [ "$status" -eq 2 ] + [[ "$output" == *"Error: gh api"* ]] +} diff --git a/plugins/pr-tools/scripts/tests/watch-pr-merged.bats b/plugins/pr-tools/scripts/tests/watch-pr-merged.bats new file mode 100644 index 0000000..f2e2cfe --- /dev/null +++ b/plugins/pr-tools/scripts/tests/watch-pr-merged.bats @@ -0,0 +1,152 @@ +#!/usr/bin/env bats +# Tests for ../watch-pr-merged.sh +# +# Runs the whole script end-to-end against a mock `gh` on PATH. The mock +# serves a small pre-scripted "plan" of responses (one per poll, sequenced +# via a poll counter fixture), so each test only has to describe what the PR +# endpoint returns on each successive call. WATCH_INTERVAL/WATCH_MAX_WAIT are +# zeroed so the whole suite runs in well under a second. + +setup() { + SCRIPT="$(cd "$(dirname "$BATS_TEST_FILENAME")/.." && pwd)/watch-pr-merged.sh" + + MOCK_BIN="$(mktemp -d)" + FIXTURES="$(mktemp -d)" + # FIXTURES must be exported so the mock gh subprocess can read it. + export FIXTURES + + # Generous window by default — tests that expect a terminal state must not + # race the clock; the timeout test overrides this down itself. + export WATCH_INTERVAL=0 + export WATCH_MAX_WAIT=30 + + _write_mock_gh + export PATH="$MOCK_BIN:$PATH" +} + +teardown() { + rm -rf "$MOCK_BIN" "$FIXTURES" +} + +# Writes the response plan the mock will serve. One line per poll number +# (1-indexed); polls beyond the last line keep repeating that last line, so a +# single line is enough to simulate "stays this way forever" (the timeout case). +_set_plan() { + printf '%s\n' "$@" > "$FIXTURES/plan.jsonl" + printf '0' > "$FIXTURES/poll_count" +} + +_write_mock_gh() { + cat > "$MOCK_BIN/gh" <<'MOCK' +#!/usr/bin/env bash +# Mock gh. Serves the FIXTURES/plan.jsonl response plan for `gh api -i [...]`. +set -uo pipefail +F="$FIXTURES" + +sub="${1:-}"; shift || true +[[ "$sub" == "api" ]] || { echo "gh: unexpected subcommand: $sub" >&2; exit 1; } + +n=$(( $(cat "$F/poll_count") + 1 )) +printf '%s' "$n" > "$F/poll_count" + +total_lines=$(wc -l < "$F/plan.jsonl") +line_num=$n +(( line_num > total_lines )) && line_num=$total_lines +line=$(sed -n "${line_num}p" "$F/plan.jsonl") + +code=$(echo "$line" | jq -r '.code') +etag=$(echo "$line" | jq -r '.etag') +body=$(echo "$line" | jq -c '.body') + +if [[ "$code" == "error" ]]; then + echo "gh: Could not resolve host: api.github.com" >&2 + exit 1 +elif [[ "$code" == "304" ]]; then + printf 'HTTP/2.0 304 Not Modified\r\n' + printf 'etag: "%s"\r\n' "$etag" + printf '\r\n' +else + printf 'HTTP/2.0 200 OK\r\n' + printf 'etag: "%s"\r\n' "$etag" + printf '\r\n' + printf '%s\n' "$body" +fi +MOCK + chmod +x "$MOCK_BIN/gh" +} + +# ============================================================ +# Usage errors +# ============================================================ + +@test "invalid PR URL exits 2" { + run "$SCRIPT" "https://example.com/not-a-pr-url" + [ "$status" -eq 2 ] + [[ "$output" == *"Invalid PR URL"* ]] +} + +@test "missing PR URL exits 2 with usage message" { + run "$SCRIPT" + [ "$status" -eq 2 ] + [[ "$output" == *"Usage:"* ]] +} + +# ============================================================ +# Terminal states reached on the very first poll +# ============================================================ + +@test "merged on the first poll exits 0 with MERGED " { + _set_plan '{"code":200,"etag":"e1","body":{"merged":true,"state":"closed","merge_commit_sha":"deadbeef"}}' + run "$SCRIPT" "https://github.com/acme/widgets/pull/1" + [ "$status" -eq 0 ] + [[ "$output" == *"MERGED deadbeef"* ]] +} + +@test "closed without merging exits 1 with CLOSED_UNMERGED" { + _set_plan '{"code":200,"etag":"e1","body":{"merged":false,"state":"closed","merge_commit_sha":null}}' + run "$SCRIPT" "https://github.com/acme/widgets/pull/2" + [ "$status" -eq 1 ] + [[ "$output" == *"CLOSED_UNMERGED"* ]] +} + +# ============================================================ +# ETag / 304 path +# ============================================================ + +@test "a 304 no-change poll is skipped, then a later 200 merge is caught" { + # Poll 1 returns 304 (resuming from a prior etag, nothing changed yet); + # poll 2 returns 200 with merged=true. Proves the loop keeps polling past + # a no-change response instead of misreading it as a terminal state. + _set_plan \ + '{"code":304,"etag":"priorEtag","body":{}}' \ + '{"code":200,"etag":"e2","body":{"merged":true,"state":"closed","merge_commit_sha":"cafebabe"}}' + run "$SCRIPT" "https://github.com/acme/widgets/pull/3" "priorEtag" + [ "$status" -eq 0 ] + [[ "$output" == *"MERGED cafebabe"* ]] +} + +# ============================================================ +# Timeout / resume path +# ============================================================ + +@test "gh api failures retry then exit 2 after repeated errors" { + # A failed gh call has no HTTP status line — the parse must yield an empty + # code for the error-streak handling to see, not abort under set -e with an + # exit 1 that reads as CLOSED_UNMERGED. + export WATCH_MAX_WAIT=30 + _set_plan '{"code":"error","etag":"","body":{}}' + run "$SCRIPT" "https://github.com/acme/widgets/pull/5" + [ "$status" -eq 2 ] + [[ "$output" == *"repeated failures"* ]] + [[ "$output" != *"CLOSED_UNMERGED"* ]] +} + +@test "PR stays open through the whole window: exits 3 with RESUME_ETAG" { + export WATCH_MAX_WAIT=1 + _set_plan '{"code":200,"etag":"eOpen","body":{"merged":false,"state":"open","merge_commit_sha":null}}' + run "$SCRIPT" "https://github.com/acme/widgets/pull/4" + [ "$status" -eq 3 ] + # The mock's etag header carries real HTTP-style quotes (as GitHub's do); + # the script passes them through unstripped, same as pr-check-watcher.sh. + [[ "$output" == *'RESUME_ETAG="eOpen"'* ]] +} diff --git a/plugins/pr-tools/scripts/watch-pr-comments.sh b/plugins/pr-tools/scripts/watch-pr-comments.sh new file mode 100755 index 0000000..6430999 --- /dev/null +++ b/plugins/pr-tools/scripts/watch-pr-comments.sh @@ -0,0 +1,212 @@ +#!/bin/bash +# watch-pr-comments.sh - blocking watcher for NEW PR or issue activity +# +# Blocks until a NEW comment, review, or inline review comment lands on the PR +# (or a new comment lands on the issue), then prints only the new items plus a +# resumable cursor. Replaces repeated `gh pr view --json comments,reviews` or +# `gh issue view --json comments` full-payload polling. +# +# Accepts a PR URL (.../pull/N) or an issue URL (.../issues/N). Reviews and +# inline review comments are PR-only; in issue mode only the issue's comment +# thread is watched (the pulls/* endpoints 404 for a plain issue). +# +# Usage: +# watch-pr-comments.sh [since-iso8601] +# +# Env overrides: +# WATCH_INTERVAL - poll interval seconds (default 20) +# WATCH_MAX_WAIT - max wait seconds (default 570) +# +# Exit codes: +# 0 - new activity found; prints items then NEXT_SINCE= +# 2 - usage or API error +# 3 - timed out with no new activity; NEXT_SINCE= unchanged +# +# NEXT_SINCE is the poll-round START time, not the newest item timestamp — an +# item landing on an already-polled endpoint mid-round is re-served on the +# next run instead of being skipped. Cross-run duplicates are possible and +# benign; silently losing feedback is not. + +set -euo pipefail + +pr_url="${1:-}" +since="${2:-}" + +if [[ -z "$pr_url" ]]; then + echo "Usage: watch-pr-comments.sh [since-iso8601]" >&2 + exit 2 +fi + +if [[ "$pr_url" =~ github\.com/([^/]+)/([^/]+)/(pull|issues)/([0-9]+) ]]; then + owner="${BASH_REMATCH[1]}" + repo="${BASH_REMATCH[2]}" + pr_number="${BASH_REMATCH[4]}" + [[ "${BASH_REMATCH[3]}" == "pull" ]] && is_pr=true || is_pr=false +else + echo "Error: Invalid PR or issue URL: $pr_url" >&2 + exit 2 +fi + +if [[ -n "$since" ]]; then + cursor="$since" +else + # Same 1s back-off as NEXT_SINCE (see the round cursor below): an item + # landing in the startup second would otherwise sit exactly on the + # whole-second boundary and be skipped by after-cursor filtering. + startup_epoch=$(( $(date +%s) - 1 )) + cursor=$(date -u -r "$startup_epoch" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null \ + || date -u -d "@$startup_epoch" +%Y-%m-%dT%H:%M:%SZ) +fi +poll_interval="${WATCH_INTERVAL:-20}" +max_wait="${WATCH_MAX_WAIT:-570}" +start_time=$(date +%s) + +comments_etag="" +review_comments_etag="" + +seen_ids_file=$(mktemp) +trap 'rm -f "$seen_ids_file"' EXIT + +found_new=false + +# Helper: fetch an API endpoint with optional ETag, sets $fetch_code, $fetch_etag, $fetch_body +fetch_with_etag() { + local endpoint="$1" + local etag="$2" + local response + + if [[ -n "$etag" ]]; then + response=$(gh api "$endpoint" -i -H "If-None-Match: $etag" 2>&1) || true + else + response=$(gh api "$endpoint" -i 2>&1) || true + fi + + # `|| true` keeps set -e/pipefail from killing the script when a failed + # gh call has no status line or etag header — the non-200/304 check below + # must see the empty value and report the error instead. + fetch_code=$(echo "$response" | head -1 | grep -oE '[0-9]{3}' | head -1 || true) + fetch_etag=$(echo "$response" | grep -i '^etag:' | sed 's/^[Ee][Tt][Aa][Gg]: *//' | tr -d '\r' || true) + fetch_body=$(echo "$response" | sed '1,/^\r*$/d') + + if [[ "$fetch_code" != "200" && "$fetch_code" != "304" ]]; then + echo "Error: gh api $endpoint failed: $response" >&2 + exit 2 + fi +} + +# GitHub list endpoints cap at one page per request — after a full (100-item) +# first page, keep appending pages until a short one. Sets $all_body; "" on 304. +read_endpoint() { + local endpoint="$1" etag="$2" page=2 body count + all_body="" + fetch_with_etag "$endpoint" "$etag" + [[ "$fetch_code" == "304" ]] && return 0 + + all_body="$fetch_body" + count=$(jq 'length' <<<"$all_body" 2>/dev/null || echo 0) + while (( ${count:-0} == 100 )); do + body=$(gh api "${endpoint}&page=${page}" 2>&1) || { + echo "Error: gh api ${endpoint}&page=${page} failed: $body" >&2 + exit 2 + } + # Merge via stdin, not --argjson — a full page of large comment + # bodies can exceed the OS argv size limit. + all_body=$(printf '%s\n%s\n' "$all_body" "$body" | jq -c -s '.[0] + .[1]' 2>/dev/null) || { + echo "Error: unexpected JSON from ${endpoint}&page=${page}" >&2 + exit 2 + } + count=$(jq 'length' <<<"$body" 2>/dev/null || echo 0) + page=$((page + 1)) + done +} + +# `since=` is re-sent unchanged on every poll of this run, so a fresh 200 can +# re-include items already printed by an earlier poll — de-dupe by id. +already_seen() { + local key="$1" + if grep -qxF "$key" "$seen_ids_file" 2>/dev/null; then + return 0 + fi + echo "$key" >> "$seen_ids_file" + return 1 +} + +# Prints newly-seen rows (id, author, timestamp, state-or-empty, body) and +# tracks found_new as a global. Rows are US-delimited (\x1f): a non-whitespace +# IFS preserves empty fields, where consecutive tabs would collapse and shift +# the body into the state column. +emit_rows() { + local prefix="$1" rows="$2" + [[ -z "$rows" ]] && return 0 + while IFS=$'\x1f' read -r id author ts state body; do + [[ -z "$id" ]] && continue + if already_seen "$prefix-$id"; then + continue + fi + if [[ "$prefix" == "review" ]]; then + echo "review($state) $author $ts: $body" + else + echo "$prefix $author $ts: $body" + fi + found_new=true + done <<< "$rows" +} + +# Comments use updated_at to match the `since` filter's semantics — an edited +# old comment is served with its edit time, so it's reported once instead of +# on every subsequent run. +comment_rows_jq='.[] | [(.id|tostring), .user.login, (.updated_at // .created_at), "", (.body // "" | gsub("[\r\n\t\u001f]+";" ") | if length > 2000 then .[0:2000] + "…(truncated)" else . end)] | join("\u001f")' + +while true; do + # Back-date the round cursor by one second: timestamps are whole-second, + # so an item landing in the same second as the cursor would otherwise sit + # exactly ON the boundary and be skipped by the next run's after-cursor + # filtering. The overlap can re-serve a boundary item (dup-over-loss). + round_start_epoch=$(( $(date +%s) - 1 )) + round_start=$(date -u -r "$round_start_epoch" +%Y-%m-%dT%H:%M:%SZ 2>/dev/null \ + || date -u -d "@$round_start_epoch" +%Y-%m-%dT%H:%M:%SZ) + + read_endpoint "repos/$owner/$repo/issues/$pr_number/comments?since=$cursor&per_page=100" "$comments_etag" + if [[ -n "$all_body" ]]; then + [[ -n "$fetch_etag" ]] && comments_etag="$fetch_etag" + rows="$(jq -r "$comment_rows_jq" <<<"$all_body" 2>/dev/null)" || rows="" + emit_rows "comment" "$rows" + fi + + # No since= support and ascending order on the reviews endpoint: a new + # review appends past page 1, leaving page 1's ETag unchanged — so no + # conditional requests here; fetch all pages and filter on submitted_at. + # Reviews are PR-only — the pulls/* endpoint 404s for a plain issue. + [[ "$is_pr" == true ]] && read_endpoint "repos/$owner/$repo/pulls/$pr_number/reviews?per_page=100" "" || all_body="" + if [[ -n "$all_body" ]]; then + rows="$(jq -r --arg cursor "$cursor" '.[] | select(.submitted_at != null and .submitted_at > $cursor) | [(.id|tostring), .user.login, .submitted_at, .state, (.body // "" | gsub("[\r\n\t\u001f]+";" ") | if length > 2000 then .[0:2000] + "…(truncated)" else . end)] | join("\u001f")' <<<"$all_body" 2>/dev/null)" || rows="" + emit_rows "review" "$rows" + fi + + # Inline review comments are PR-only too — skip in issue mode. + [[ "$is_pr" == true ]] && read_endpoint "repos/$owner/$repo/pulls/$pr_number/comments?since=$cursor&per_page=100" "$review_comments_etag" || all_body="" + if [[ -n "$all_body" ]]; then + [[ -n "$fetch_etag" ]] && review_comments_etag="$fetch_etag" + rows="$(jq -r "$comment_rows_jq" <<<"$all_body" 2>/dev/null)" || rows="" + emit_rows "review-comment" "$rows" + fi + + if [[ "$found_new" == "true" ]]; then + echo "NEXT_SINCE=$round_start" + exit 0 + fi + + # Deadline check runs AFTER each poll round, not before, so at least one + # round always happens (even with WATCH_MAX_WAIT < WATCH_INTERVAL). When + # the remaining window is shorter than a full interval, sleep just the + # remainder and run one final round AT the deadline — activity landing + # late in the window is still caught. Exit is ~max_wait + one round. + elapsed=$(( $(date +%s) - start_time )) + if (( elapsed >= max_wait )); then + echo "Timed out after ${max_wait}s with no new PR activity." + echo "NEXT_SINCE=$cursor" + exit 3 + fi + remaining=$(( max_wait - elapsed )) + sleep $(( remaining < poll_interval ? remaining : poll_interval )) +done diff --git a/plugins/pr-tools/scripts/watch-pr-merged.sh b/plugins/pr-tools/scripts/watch-pr-merged.sh new file mode 100755 index 0000000..3f6655b --- /dev/null +++ b/plugins/pr-tools/scripts/watch-pr-merged.sh @@ -0,0 +1,129 @@ +#!/bin/bash +# watch-pr-merged.sh - ETag-based polling for a GitHub PR's merged state +# +# Uses conditional HTTP requests (If-None-Match) to poll the PR resource with +# zero rate-limit cost for unchanged responses. Only 200 responses (where +# something actually changed) get reprocessed; 304 just means "keep waiting". +# +# Usage: +# watch-pr-merged.sh [resume-etag] +# +# Arguments: +# pr-url - Full GitHub PR URL (e.g., https://github.com/org/repo/pull/123) +# resume-etag - Optional ETag from a previous run, to resume without re-fetching +# +# Environment (overridable so tests run near-instantly): +# WATCH_INTERVAL - poll interval in seconds (default 15) +# WATCH_MAX_WAIT - max wait in seconds before giving up (default 570) +# +# Exit codes: +# 0 - PR merged; prints "MERGED " +# 1 - PR closed without merging; prints "CLOSED_UNMERGED" +# 2 - Usage error or unrecoverable API error +# 3 - Timed out; prints last known state, then "RESUME_ETAG=" to resume +set -euo pipefail + +pr_url="${1:-}" +etag="${2:-}" + +if [[ -z "$pr_url" ]]; then + echo "Usage: watch-pr-merged.sh [resume-etag]" >&2 + exit 2 +fi + +if [[ "$pr_url" =~ github\.com/([^/]+)/([^/]+)/pull/([0-9]+) ]]; then + owner="${BASH_REMATCH[1]}" + repo="${BASH_REMATCH[2]}" + pr_number="${BASH_REMATCH[3]}" +else + echo "Error: Invalid PR URL: $pr_url" >&2 + exit 2 +fi + +endpoint="repos/$owner/$repo/pulls/$pr_number" +poll_interval="${WATCH_INTERVAL:-15}" +max_wait="${WATCH_MAX_WAIT:-570}" +start_time=$(date +%s) +last_summary="" +last_body="" +error_streak=0 + +# Helper: fetch the PR endpoint with optional ETag, sets $fetch_code, $fetch_etag, $fetch_body +fetch_with_etag() { + local response + if [[ -n "$etag" ]]; then + response=$(gh api "$endpoint" -i -H "If-None-Match: $etag" 2>&1) || true + else + response=$(gh api "$endpoint" -i 2>&1) || true + fi + # `|| true` keeps set -e/pipefail from killing the script when a failed + # gh call has no status line or etag header — the caller's error-streak + # handling must see the empty value instead. + fetch_code=$(echo "$response" | head -1 | grep -oE '[0-9]{3}' | head -1 || true) + fetch_etag=$(echo "$response" | grep -i '^etag:' | sed 's/^[Ee][Tt][Aa][Gg]: *//' | tr -d '\r' || true) + fetch_body=$(echo "$response" | sed '1,/^\r*$/d') +} + +echo "Watching PR #$pr_number ($owner/$repo) for merge..." + +# Deadline check runs AFTER each poll, not before: a terminal state landing in +# the final interval is still caught, at least one poll always happens (even +# with WATCH_MAX_WAIT < WATCH_INTERVAL), and the exit stays ~max_wait because +# the check runs before the sleep that would overshoot it. +deadline_then_sleep() { + local elapsed=$(( $(date +%s) - start_time )) + if (( elapsed + poll_interval > max_wait )); then + echo "" + echo "Polling window expired after ${max_wait}s. Last status: $last_summary" + echo "RESUME_ETAG=${etag}" + exit 3 + fi + sleep "$poll_interval" +} + +while true; do + fetch_with_etag + + if [[ "$fetch_code" == "304" ]]; then + error_streak=0 + deadline_then_sleep + continue + elif [[ "$fetch_code" == "200" ]]; then + error_streak=0 + [[ -n "$fetch_etag" ]] && etag="$fetch_etag" + last_body="$fetch_body" + else + error_streak=$(( error_streak + 1 )) + echo "Warning: PR fetch returned HTTP ${fetch_code:-unknown}, retrying..." >&2 + # A handful of consecutive non-200/304 responses means something is + # broken (auth, network), not a transient blip — stop retrying forever. + if (( error_streak >= 5 )); then + echo "Error: repeated failures fetching PR state" >&2 + exit 2 + fi + deadline_then_sleep + continue + fi + + merged=$(echo "$last_body" | jq -r '.merged // false') + state=$(echo "$last_body" | jq -r '.state // "unknown"') + merge_sha=$(echo "$last_body" | jq -r '.merge_commit_sha // ""') + + summary="merged=$merged state=$state" + if [[ "$summary" != "$last_summary" ]]; then + echo "[$(( $(date +%s) - start_time ))s] state=$state merged=$merged" + last_summary="$summary" + fi + + if [[ "$merged" == "true" ]]; then + echo "MERGED $merge_sha" + exit 0 + fi + + if [[ "$state" == "closed" ]]; then + echo "CLOSED_UNMERGED" + exit 1 + fi + + deadline_then_sleep +done diff --git a/plugins/pr-tools/skills/create-pr/SKILL.md b/plugins/pr-tools/skills/create-pr/SKILL.md index 92af370..ce412b9 100644 --- a/plugins/pr-tools/skills/create-pr/SKILL.md +++ b/plugins/pr-tools/skills/create-pr/SKILL.md @@ -232,6 +232,25 @@ The footer is the only attribution outside the collapsed `
` block (Core - `### Risks` - ONLY if user mentioned specific concerns - `
Notes for reviewers` collapsible (after `How?`) - ONLY when there is scope rationale a reviewer genuinely needs beyond the diff (e.g. why files beyond the obvious were touched, or why the change spans more than one area — Core Rule 9). Never add it empty or as filler, and never for merge-reassurance boilerplate ("safe to merge", "purely additive") — that is always omitted, never collapsed. +### 5. Launch the watchers + +Once the PR URL is known, launch all three watchers in the background — one Bash tool call per watcher, `run_in_background: true` on each: + +```bash +bash "${CLAUDE_PLUGIN_ROOT}/scripts/watch-pr-comments.sh" +bash "${CLAUDE_PLUGIN_ROOT}/scripts/watch-pr-merged.sh" +bash "${CLAUDE_PLUGIN_ROOT}/scripts/pr-check-watcher.sh" +``` + +Do NOT poll `gh pr view` or `gh pr checks` for comments, merge state, or CI — that is what these watchers replace. + +Exit codes: +- `watch-pr-merged.sh`: 0 = merged (prints `MERGED `), 1 = closed unmerged, 2 = error, 3 = timed out (prints `RESUME_ETAG=`) +- `watch-pr-comments.sh`: 0 = new activity (prints items then `NEXT_SINCE=`), 2 = error, 3 = timed out (prints `NEXT_SINCE=`) +- `pr-check-watcher.sh`: 0 = all checks passed, 1 = one or more failed (prints the failing check names and URLs), 2 = error, 3 = timed out (prints `RESUME_ETAGS=|||`) + +**Exit 3 is not "give up" — it is "resume".** All three cap out at `WATCH_MAX_WAIT=570` seconds (~9.5 min) and exit 3 rather than block forever. On exit 3, immediately re-launch the same script in the background, passing the printed cursor as the second argument: `RESUME_ETAG` for `watch-pr-merged.sh`, `NEXT_SINCE` for `watch-pr-comments.sh`, `RESUME_ETAGS` for `pr-check-watcher.sh`. Skipping this means a PR that merges or gets reviewed hours later is silently missed. + ## Response Style Output only what the user needs to act: