GitHub CI/CD automation plugin for auto-detecting, analyzing, and fixing CI/CD failures on any branch

GitHub stars
6

Install

/plugin install github@cautious-computing-machine

Run it inside Claude Code after adding the marketplace with /plugin marketplace add iamladi/cautious-computing-machine.

Contents

Discovered from source

Skills 1

CI Fix Loop

Role

Drive an autonomous CI-repair cycle: analyze the latest failure, apply fixes, commit, push, wait for the new CI run, and loop until CI passes or the retry budget is exhausted. The point is to free the user from babysitting a CI run that's failing on fixable errors (formatting, obvious lint, easy test fixes).

Invoked by /fix-ci --loop, /fix-ci --auto, or /fix-ci --swarm.

Priorities

Correct fix (no suppressed signal) > Forward progress (commit and push every iteration) > Termination (bail when progress stalls)

Invariants

  • Don't run on main / master. Autonomous loops that push to a protected branch are dangerous even when the fixes are right. Abort and suggest a hotfix branch.
  • Stash before starting. Preserve the user's in-progress work; restore on termination regardless of outcome.
  • Bail when progress stalls. If the same errors reappear across two consecutive attempts, the loop isn't converging — human intervention beats burning more CI budget.
  • Budget caps are hard. Maximum 10 attempts; maximum 30 minutes per CI run; maximum 2 minutes waiting for a new run to start after push. Each limit exists because the failure mode beyond it is worse than stopping here.
  • Never --no-verify a commit. Local hooks catch classes of regressions that CI won't; skipping them lets bugs slip into the loop itself.

Flag parsing

Before anything else, extract flags from $ARGUMENTS:

  • --loop or --auto → standard autonomous mode.
  • --swarm → parallel fix mode (see below). Remember this choice — it affects how fixes are applied in each attempt.

Strip consumed flags; anything remaining is contextual (e.g., a PR number).

Configuration

SettingValueReason
max_attempts10Beyond this, compounding failures usually mean the root cause isn't code
poll_interval60sCI status doesn't change faster than this anyway
ci_start_timeout120sIf CI hasn't started in 2 min, the workflow's likely misconfigured
ci_run_timeout1800s (30 min)Longer runs usually indicate infra flake, not a fixable error

Initialization

BRANCH=$(git branch --show-current)
REPO=$(gh repo view --json nameWithOwner -q .nameWithOwner 2>/dev/null || echo "unknown")

Guard on protected branches:

if [[ "$BRANCH" == "main" || "$BRANCH" == "master" ]]; then
  echo "Cannot run autonomous fixes on $BRANCH. Create a feature branch: git checkout -b fix/ci-errors"
  # abort
fi

Stash uncommitted changes:

if [[ -n $(git status --porcelain) ]]; then
  git stash push -m "pre-ci-fix-loop-$(date +%Y%m%d_%H%M%S)"
fi

Start the loop with attempt=1, last_errors=[], history=[], consecutive_same_errors=0.

Iteration

Each attempt follows the same shape. The sequence matters — commit must come after fix, push must come after commit, monitor must come after push — but within those boundaries the model picks the tactics. Don't over-narrate each step.

Fetch and analyze

Pull the latest failed run on this branch, fetch logs for every failed job, and hand them to the ci-log-analyzer agent. The agent returns a structured error list (category, file, line, message). Trust that output — re-parsing logs wastes context.

RUN_ID=$(gh run list --branch "$BRANCH" --limit 5 --json databaseId,conclusion \
  --jq '[.[] | select(.conclusion == "failure")][0].databaseId')
FAILED_JOBS=$(gh run view $RUN_ID --json jobs --jq '.jobs[] | select(.conclusion == "failure") | .databaseId')
for JOB_ID in $FAILED_JOBS; do
  gh api repos/${REPO}/actions/jobs/${JOB_ID}/logs > /tmp/ci-logs-${JOB_ID}.txt 2>/dev/null || true
done

If no failed runs exist, CI might already be passing — skip to monitoring to confirm.

Termination check (no progress)

Compare the current error list to last_errors. If they're identical after at least one fix attempt, increment consecutive_same_errors. At 2, exit the loop — the fixes aren't landing or the errors are beyond what this skill can handle. Report the persistent errors in the final summary; human intervention is the right move.

Apply fixes

Default path: single ci-error-fixer agent handles the whole error list sequentially. Appropriate when errors are in one or two files, or when swarm mode wasn't requested.

Swarm path — triggered when --swarm was set and errors span 2+ distinct files:

Split the error list into up to 4 partitions by file (grouping by directory proximity if there are more than 4 files). Non-file-specific errors (dependency resolution, config, flaky tests without file association) stay with the lead for sequential handling.

Create the team with TeamCreate: name fix-ci-{YYYYMMDD-HHMMSS}, description CI Fix Attempt {attempt}. If TeamCreate is unavailable (experimental flag off), fall back to the single-agent path — surface the fallback in logs but don't abort the attempt.

Spawn one teammate per partition via Task with team_name and subagent_type: "general-purpose". Teammates can't see this conversation — embed partition details as literal text.

You are fixing CI errors for a specific set of files as part of a parallel fix team.

YOUR FILE PARTITION: {literal list of file paths}

ERRORS TO FIX: {literal error list for these files — type, file, line, message}

FILE CONTENTS: {read each file and include its full contents here}

Apply targeted fixes per error type: lint with the formatter or linter, type errors with correct annotations or mismatch fixes, test failures with corrected logic or implementation bugs, build errors with import/dependency fixes.

Constraints (parallel-team context):

  • Edit only your assigned files. The lead handles staging and commits to avoid conflicts.
  • Don't run tests or builds — other teammates are editing concurrently.
  • Communicate via SendMessage only; AskUserQuestion isn't available in team context.
  • Make minimal, targeted fixes. Over-editing introduces new errors and complicates the lead's review.
  • Read files completely, no limit/offset.

When every error in your partition is fixed:

  1. SendMessage FIX COMPLETE.
  2. Wait for shutdown_request.

Wait for every teammate's FIX COMPLETE, up to 10 minutes per teammate from spawn. On timeout, proceed with available fixes and note it in the history. After teammates complete (or time out), the lead stages all changes in one commit (below) rather than per-teammate.

Cleanup invariant — regardless of swarm success or failure, SendMessage type: "shutdown_request" to each teammate, wait briefly, then TeamDelete. Skipping leaks team slots.

Commit and push

One commit per iteration — captures the full fix for this attempt in a single reviewable unit:

git add .
git commit -m "fix(ci): automated fix attempt ${attempt}

Errors addressed:
- ${error_summary_list}

Attempt ${attempt} of ${max_attempts} (ci-fix-loop${SWARM_SUFFIX})"

PUSH_TIME=$(date -u +%Y-%m-%dT%H:%M:%SZ)
git push origin ${BRANCH}

PUSH_TIME is used below to detect the new run (distinguishing it from the run currently being analyzed). In swarm mode the lead owns this step — teammates never run git commands, which keeps coordination simple.

Wait for the new run to start

Use the Monitor tool (no LLM tokens burned on polling) to watch for a run created after PUSH_TIME, capped at ci_start_timeout:

Monitor:
  description: "CI run start detection on ${BRANCH}"
  timeout_ms: 120000
  persistent: false
  command: |
    while true; do
      RUN_JSON=$(gh run list --branch "$BRANCH" --limit 1 --json databaseId,status,createdAt 2>&1) || {
        echo "WARN: gh run list failed, retrying..." >&2
        sleep 5; continue
      }
      CREATED=$(echo "$RUN_JSON" | jq -r '.[0].createdAt // empty')
      if [ -n "$CREATED" ] && [[ "$CREATED" > "$PUSH_TIME" ]]; then
        RUN_ID=$(echo "$RUN_JSON" | jq -r '.[0].databaseId')
        echo "STARTED|$RUN_ID"
        exit 0
      fi
      sleep 5
    done

Notifications:

  • STARTED|{RUN_ID} → capture as NEW_RUN_ID, proceed to monitoring.
  • Monitor timeout (no notification within 120s) → warn "No CI run started after 120s — check if workflows are enabled for this branch" and proceed with TIMEOUT.

Monitor to terminal state

Run the Monitor tool again, filtered by NEW_RUN_ID when known (avoids race conditions with concurrent runs on the same branch):

Monitor:
  description: "CI run ${NEW_RUN_ID} on ${BRANCH}"
  timeout_ms: 1800000
  persistent: false
  command: |
    while true; do
      if [ -n "$NEW_RUN_ID" ]; then
        RESULT=$(gh run view "$NEW_RUN_ID" --json databaseId,status,conclusion 2>&1) || {
          echo "WARN: gh run view failed, retrying..." >&2
          sleep 60; continue
        }
        STATUS=$(echo "$RESULT" | jq -r '.status // "unknown"')
        CONCLUSION=$(echo "$RESULT" | jq -r '.conclusion // "null"')
        RUN_ID="$NEW_RUN_ID"
      else
        RESULT=$(gh run list --branch "$BRANCH" --limit 1 --json databaseId,status,conclusion 2>&1) || {
          echo "WARN: gh run list failed, retrying..." >&2
          sleep 60; continue
        }
        STATUS=$(echo "$RESULT" | jq -r '.[0].status // "unknown"')
        CONCLUSION=$(echo "$RESULT" | jq -r '.[0].conclusion // "null"')
        RUN_ID=$(echo "$RESULT" | jq -r '.[0].databaseId // "unknown"')
      fi
      case "$STATUS" in
        completed)
          case "$CONCLUSION" in
            success)    echo "SUCCESS|$RUN_ID"; exit 0 ;;
            failure)    echo "FAILURE|$RUN_ID"; exit 1 ;;
            cancelled)  echo "CANCELLED|$RUN_ID"; exit 2 ;;
            skipped)    echo "SUCCESS|$RUN_ID"; exit 0 ;;
            *)          echo "FAILURE|$RUN_ID"; exit 1 ;;
          esac ;;
        requested|waiting|queued|pending|in_progress)
          ;; # still running, continue polling
        action_required)
          echo "ACTION_REQUIRED|$RUN_ID"; exit 3 ;;
      esac
      sleep 60
    done

Handle the result:

  • SUCCESS — exit the loop, report success.
  • FAILURE — record history, last_errors = current_errors, attempt += 1, back to Fetch and analyze.
  • CANCELLED — warn and exit. Someone (or something) cancelled the run externally; continuing would loop indefinitely.
  • ACTION_REQUIRED — warn the user that manual approval is needed and exit.
  • TIMEOUT (30 min) — report and suggest gh run watch; offer continue-waiting vs. abort — long CI runs usually indicate infrastructure issues, not fixable errors.

Record

Append to history:

{attempt, errors_found, errors_fixed, errors_flagged, run_id, result, duration}

Final report

On exit — success, failure, or abort — produce:

CI Fix Loop Complete

Result: SUCCESS | FAILURE | ABORTED after {attempts} attempt(s)
Total time: {duration}
Commits created: {count}
Errors fixed: {total}

History:
  Attempt 1: Found 5 errors, fixed 5 → FAILURE (5 new errors surfaced after first fix)
  Attempt 2: Found 5 errors, fixed 3 → SUCCESS
  ...

On failure — surface what's left so the human knows where to pick up:

Remaining issues (need manual intervention):
  - src/x.ts:42 — type mismatch on return value (error persisted across 2 attempts)

Next:
  1. Review remaining errors above.
  2. Inspect logs: gh run view {last_run_id} --log-failed
  3. Fix manually and push.

On success — report the commit trail so the user can squash or review:

CI is now passing.

Next:
  1. Review commits: git log --oneline -{commit_count}
  2. Squash if desired: git rebase -i HEAD~{commit_count}
  3. Open PR: /github:create-pr

Error handling

  • Network / gh flakes — retry the command up to 3 times with 5s backoff before treating as persistent; abort the loop if still failing.
  • Push rejection (upstream advanced) — don't try to resolve automatically; tell the user "Upstream changes detected. Pull and retry: git pull --rebase && /fix-ci --loop".
  • CI start timeout (no run within 2 min) — check workflow configuration; continue to monitor just in case a delayed run appears.
  • CI run timeout (30 min exceeded) — offer continue-waiting vs. abort; don't silently extend.
  • Team creation fails (swarm only) — fall back to single-agent fix for that iteration; keep going.

Safety recap

The invariants section at the top is load-bearing, but the mechanics also matter:

  • Branch protection prevents protected-branch loops.
  • Stash preserves uncommitted work.
  • consecutive_same_errors >= 2 aborts loops that aren't converging.
  • Commit log lets the user squash or revert cleanly.
  • In swarm mode, teammates edit files only — they don't run git, builds, or tests. That keeps coordination simple and prevents teammates from clobbering each other's work.
  • CI monitoring uses the Monitor tool rather than an LLM polling agent — zero token cost for the wait loop.

Commands 5

Address PR Comments

Role

Fetch every comment on a pull request, decide what to do with each one, apply fixes where it's safe to, and post a reply to every comment — no reviewer feedback leaves unanswered. Works in two modes: interactive (you approve each action before it runs) and autonomous (safe auto-fixes run unattended in CI).

Priorities

Reviewer acknowledgment (every comment replied) > Fix safety (low-risk auto-fixes only) > Throughput

Invariants

These hold regardless of mode — they're the properties that make this command trustworthy:

  • Every filtered comment receives one reply. A fix without a reply is invisible to the reviewer; a reply without a fix at least closes the loop. Never skip the reply.
  • Idempotent reruns. If the current user has already replied to a comment, skip it — duplicate replies confuse the thread.
  • One fix, one commit. Stage only the files the fix touches (git add {path}), never git add . or -A. A bulk commit loses the audit trail and risks sweeping in unrelated uncommitted work.
  • Posted replies are permanent. Commits can be reverted; GitHub replies cannot. Surface this in the summary for autonomous runs so the user knows what's reversible.
  • Reply body construction uses jq --arg piped to gh api --input -. This prevents shell injection and JSON malformation from comment bodies containing ", $, or backticks. See Reply posting below.

Preflight

Run these checks before fetching anything — failing partway through is worse than failing immediately. Each guards against a specific failure class:

  • gh auth status — without auth, the command would fetch, process, and fix, then fail silently when posting. Abort with "Not authenticated. Run: gh auth login".
  • git status --porcelain — if the working tree has uncommitted changes, per-fix commits risk staging them alongside the fix. Abort with "Working tree has uncommitted changes. Stash or commit first.".
  • git config user.name / user.email — required for commits. Abort with configuration instructions.

Parse $ARGUMENTS for the PR. Accept a PR number (123), a full URL (https://github.com/owner/repo/pull/123), or extract from context. If no PR identifier resolves, abort with "PR number or URL required".

Fetch and normalize

Pull all three comment surfaces with pagination:

CURRENT_USER=$(gh api user --jq '.login')
gh api --paginate repos/{OWNER}/{REPO}/pulls/{PR_NUMBER}/comments  > review_comments.json
gh api --paginate repos/{OWNER}/{REPO}/pulls/{PR_NUMBER}/reviews   > review_summaries.json
gh api --paginate repos/{OWNER}/{REPO}/issues/{PR_NUMBER}/comments > issue_comments.json

Normalize every comment into a unified shape — downstream logic shouldn't care which surface it came from:

{
  id: number,
  type: "review" | "review-summary" | "issue",
  path: string | null,
  line: number | null,
  diff_hunk: string | null,
  body: string,
  user: string,
  created_at: string,
  in_reply_to_id: number | null,
  review_state: string | null  // summaries only: APPROVED, CHANGES_REQUESTED, etc.
}

Filter and check for prior replies

Exclude:

  • Comments already in a reply thread (in_reply_to_id != null) — those are conversation, not new feedback.
  • Comments from the PR author themselves.
  • Bot comments (user contains bot or [bot]).
  • Empty or whitespace-only bodies.

Keep everything else — questions, suggestions, praise, out-of-scope requests. All of them get processed because the goal is "no feedback unacknowledged."

For every kept comment, check if the current user already replied. For review comments, walk the reply thread by in_reply_to_id. For issue comments and review summaries, scan later issue comments from CURRENT_USER that reference the original. Mark already_replied: true on matches — these get shown in the summary but skip the reply step. Idempotency matters because this command is often re-run in CI.

Confidence scoring

Score each comment 0–100 by how confident you are that the right fix is unambiguous. Autonomous mode uses this to decide what to auto-fix; interactive mode uses it to sort.

Judge holistically across these dimensions, not arithmetically:

  • Specificity. A comment with path, line, a code suggestion, and a clear directive scores high. "consider refactoring" with no code scores low.
  • Clarity. Directive language ("please change X to Y") is clearer than hedged ("maybe consider"). Questions without suggested changes score lowest.
  • Risk. Naming, formatting, comment edits are low-risk. Logic changes, API contract edits, test assertion changes can shift behavior — lower the confidence unless the suggestion is extremely specific.
  • Authority. Maintainer/owner comments carry more weight than outside contributors who may misunderstand the design. Not a hard rule; use judgment.
  • Urgency. CHANGES_REQUESTED reviews block merge. Treat them as higher priority than casual COMMENTED reviews.

Thresholds for autonomous mode:

  • ≥ 80 — safe to auto-fix. Clear, specific, low-risk.
  • 60–79 — reply with clarification request. Ambiguous enough that guessing costs more than asking.
  • < 60 — reply acknowledging, but don't act.

These are defaults. A maintainer's "please rename this variable" might score 95; a vague contributor comment might score 30 — the score is a summary of judgment, not a formula.

Mode detection

Auto-detect the mode; explicit flags win:

  • --autonomous / --auto / auto in arguments → autonomous.
  • --interactive / interactive in arguments → interactive.
  • $CI, $GITHUB_ACTIONS, $JENKINS_URL, $GITLAB_CI, $CIRCLECI, $TRAVIS set → autonomous.
  • Non-TTY stdin (! [ -t 0 ]) → autonomous.
  • Default → interactive.

Autonomous mode before any edits, create a rollback checkpoint:

TIMESTAMP=$(date +%Y%m%d_%H%M%S)
STASH_NAME="pre-autonomous-pr-${PR_NUMBER}-${TIMESTAMP}"
[ -n "$(git status --porcelain)" ] && git stash push -u -m "$STASH_NAME"
ROLLBACK_SHA=$(git rev-parse HEAD)

Include both $STASH_NAME and $ROLLBACK_SHA in the final summary so rollback is a copy-paste.

Present comments (interactive mode)

Show every non-already-replied comment with its confidence score, sorted by priority. Use AskUserQuestion for selection ("1,3,4", "1-5", "all", "none"). Display format:

Found {N} comments on PR #{NUMBER}: {TITLE}

1. [CODE] src/auth.ts:120 (Score: 90) — @owner
   "Add null check before accessing user.email"
   Suggested action: Add safety check

2. [QUESTION] src/api.ts:55 (Score: 40) — @contributor
   "Is this the right approach?"
   Suggested action: Answer the question inline

[... etc]

Which items would you like me to address?

Only the user's selections get fixes. Everything else still gets a reply (deferral explanation) — the invariant holds.

Filter comments (autonomous mode)

Display what will happen so the run is auditable. Items at ≥ 80 get fixes + replies; items below get replies only with honest reasons for not auto-fixing (e.g., "suggestion lacks concrete implementation details", not a generic apology).

Per-comment processing

Categorize each selected comment, then handle by category. Each category's reply reflects the actual action taken, not boilerplate:

actionable/clear (score ≥ 80, has file and line)

Apply the fix, commit atomically, reply with the commit SHA.

  • Locate code by context, not line number. Use the diff_hunk as an anchor — line numbers drift as the PR accumulates fixes from this same command. If the surrounding context can't be found in the file, treat as missing-file rather than guessing.
  • Verify before committing. After the edit, git diff --quiet -- "{path}" tells you whether anything actually changed. If not, the code already matches the suggestion — reply accordingly instead of creating an empty commit.
  • One commit per fix.
    git add {path}
    git commit -m "fix: {brief description}
    
    Addresses comment from @{reviewer}
    Comment ID: {id}"
    
  • Capture the short SHA (git rev-parse --short HEAD) and include it in the reply. The reviewer should be able to click through to see exactly what changed.

If the fix requires edits across multiple files or has behavioral implications you can't verify, reclassify as actionable/unclear and ask instead of guessing.

actionable/unclear (score 60–79, or suggestion ambiguous)

Reply with specific interpretations of what the reviewer might mean — "I see two readings of this: (a) … (b) … — which did you mean?". Shows you read the comment and narrows the discussion. No commit.

not-actionable/question

Read the relevant code (if the comment has a path) and answer the actual question with context. Explain why the code is the way it is, based on what's actually there. If you don't know, say so and suggest who would. No commit.

not-actionable/praise

Brief acknowledgment. Match the reviewer's energy — a casual "LGTM" deserves a casual "thanks", not a paragraph. No commit.

not-actionable/out-of-scope

Acknowledge the value of the suggestion and explain the deferral. If you can point to a follow-up (future PR, separate issue), do so. Don't dismiss. No commit.

below-threshold (autonomous mode only, score < 80)

Be honest about why you didn't auto-fix: "suggestion lacks concrete implementation details", "change could affect behavior in ways I can't verify". The reviewer should understand what action they can take next. No commit.

missing-file

File referenced in the comment doesn't exist (or the diff_hunk context isn't found). Reply noting it may have been moved or renamed and ask the reviewer to confirm relevance. No commit.

Interactive mode: not selected

Reply noting the comment has been deferred to manual review. No commit.

Reply quality

Every reply should feel contextual, not like a bot processed it:

  • Actionable fixes reference the specific commit SHA and briefly describe what changed.
  • Clarification requests offer specific interpretations rather than generic "please clarify".
  • Question answers use code context — don't dodge with "great question!".
  • Praise gets one sentence.
  • Deferrals explain why not just that.

Match the reviewer's tone and formality.

Reply posting

Security invariant: always construct reply bodies via jq --arg piped to gh api --input -. Direct interpolation into -f body="..." breaks on comment bodies containing ", $, backticks, or newlines — worse, it's a shell-injection vector when the body is untrusted. This applies across every reply surface below.

# correct — injection-safe
jq -n --arg body "$REPLY" '{body: $body}' | gh api -X POST "$ENDPOINT" --input -

# wrong — unsafe
gh api -X POST "$ENDPOINT" -f body="$REPLY"

Endpoints vary by comment type:

  • Review comments (type: "review") — reply directly in the thread:
    ENDPOINT="repos/${OWNER}/${REPO}/pulls/${PR_NUMBER}/comments/${COMMENT_ID}/replies"
    
  • Issue comments (type: "issue") — no reply threading, so quote the original (truncate bodies >200 chars to ...) and post as a new issue comment:
    > {truncated original}
    
    {your reply}
    
    ENDPOINT="repos/${OWNER}/${REPO}/issues/${PR_NUMBER}/comments"
    
  • Review summaries (type: "review-summary") — no thread either. Quote the reviewer + review state, then post as an issue comment. If the original body is null (common for APPROVED reviews with no text), use "No summary text provided — addressing based on review state ({state}).".

Retry on rate limit

GitHub throttles aggressive reply posting. Handle 429 and 403-with-rate-limit by reading Retry-After and backing off exponentially (1s, 2s, 4s), cap at 3 attempts:

MAX_RETRIES=3; RETRY_COUNT=0; BACKOFF=1
while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
  HTTP_CODE=$(jq -n --arg body "$REPLY" '{body: $body}' | \
    gh api -X POST "$ENDPOINT" --input - -i 2>&1 | grep "HTTP" | awk '{print $2}')
  if [ "$HTTP_CODE" = "201" ] || [ "$HTTP_CODE" = "200" ]; then break; fi
  if [ "$HTTP_CODE" = "429" ] || [ "$HTTP_CODE" = "403" ]; then
    sleep $BACKOFF; BACKOFF=$((BACKOFF * 2)); RETRY_COUNT=$((RETRY_COUNT + 1))
  else
    echo "Failed to post reply (HTTP $HTTP_CODE) — skipping"; break
  fi
done

Post-failure: surface the failed comment in the summary so the user can reply manually — a silent drop violates the "every comment replied" invariant.

Summary report

Group by action class so the user can scan:

  1. Comments fixed + replied — code changed, committed, reply posted with SHA.
  2. Comments replied without fix — questions answered, praise acknowledged, clarifications requested, deferrals.
  3. Already replied (skipped) — idempotency caught these; no action taken.

Under 10 comments, show each inline with its action and reply. 10+, summarize by category with counts and list individual fixed items.

Next steps for the user: review the diff, run tests, push. Skip "post replies manually" — they're already posted. For autonomous mode, include the rollback stash name and base SHA, and note explicitly: commits can be reverted, replies cannot.

Error responses

Phrase errors so the user knows what to do next:

PR not found         — Verify the PR number/URL; `gh pr list` to browse.
Not authenticated    — Run: gh auth login
Working tree dirty   — git stash (or commit) before addressing PR comments.
Git user unset       — git config user.name / user.email with instructions.
No comments found    — All reviewers satisfied or comments already addressed.
All already replied  — Nothing to do.
File not found       — Comment references a moved/renamed path; reply asks reviewer to confirm.
Rate limited         — Waiting {N}s before retry ({X}/{MAX}).
Reply post failed    — Comment shown in summary; reply manually.

Usage

/address-pr-comments 123
/address-pr-comments https://github.com/owner/repo/pull/456
/address-pr-comments 123 --autonomous         # force autonomous
/address-pr-comments 123 --interactive        # force interactive

In GitHub Actions, CI env vars trigger autonomous automatically:

- run: claude /address-pr-comments ${{ github.event.pull_request.number }}

Create Issue from Plan

Based on the plan file provided, create a GitHub Issue with the implementation phases as checkboxes. Then update the plan file with the Issue number.

Variables

plan_file: $1

Instructions

1. Parse Plan File

Read the plan file and extract:

  • Frontmatter: title, type, created
  • Overview: Problem statement, goals
  • Implementation Plan: All phases with their tasks
  • Validation Commands: From the Validation Commands section
  • Acceptance Criteria: From the Acceptance Criteria section
  • Research links: From frontmatter research field (if present)

2. Generate Issue Body

Structure the Issue body as:

## Summary

[Extract from plan Overview > Problem Statement and Goals]

---

## Implementation Phases

### Phase 1: [Title from plan]
**Complexity**: [from plan] | **Priority**: [from plan]

- [ ] [Task 1]
- [ ] [Task 2]

### Phase 2: [Title from plan]
...

[Continue for all phases]

---

## Validation Commands

[Extract the bash commands from plan's Validation Commands section]

---

## Acceptance Criteria

- [ ] [From plan]
- [ ] [From plan]

---

## Related Research

[If research files listed in frontmatter, include links]

---

**Plan Document**: plans/[filename].md
**Issue Type**: [type from frontmatter]
**Created**: [from frontmatter]

3. Create the Issue

  1. Determine issue type label from plan type field:

    • Feature → type:feature
    • Bug → type:bug
    • Chore → type:chore
    • Refactor → type:refactor
    • Enhancement → type:enhancement
    • Documentation → type:documentation
  2. Create Issue via gh issue create:

    gh issue create \
      --title "[type]: [Plan Title]" \
      --body "[generated body above]" \
      --label "status:planning" \
      --label "[type_label]"
    
  3. Capture Issue number from output (will be #123)

4. Update Plan File with Issue Number

  1. Parse plan YAML frontmatter
  2. Update issue: null → issue: 123
  3. Update status: Draft → status: In Progress
  4. Write updated plan back to file
  5. Commit: git add plans/[filename].md && git commit -m "chore: link plan to Issue #123"

Run

  1. Validate plan file exists: test -f "$plan_file" or error
  2. Read and parse plan file (extract sections above)
  3. Generate Issue body using template
  4. Create Issue: gh issue create --title "..." --body "..." --label "..."
  5. Extract Issue number from output
  6. Update plan frontmatter with Issue number
  7. Commit update to plan file
  8. Return: "Issue #123 created from plan. Updated plan frontmatter."

Report

Return the Issue URL created:

  • Format: https://github.com/<owner>/<repo>/issues/<number>
  • Example: https://github.com/iamladi/my-project/issues/123

Create Pull Request

Based on the Instructions below, take the Variables follow the Run section to create a pull request. Then follow the Report section to report the results of your work.

Variables

issue: $1 plan_file: $2

Instructions

PR Title Format

Generate a pull request title in the format: <issue_type>: #<issue_number> - <issue_title>

  • Extract issue number, type, and title from the issue JSON
    • Use gh issue view <issue_number> --json number,title,body to fetch issue details
  • Examples of PR titles:
    • feat: #123 - Add user authentication
    • bug: #456 - Fix login validation error
    • chore: #789 - Update dependencies

PR Body Structure

The PR body should communicate the why and what, not duplicate information already visible in the PR interface. Include these sections in this order:

1. Summary (Purpose & Context)

Explain the "why" - business reason, goals, and impact of the change.

  • Describe the problem being solved or feature being added
  • Explain the business or technical rationale (don't assume reviewer context)
  • Keep it concise but complete (1-3 sentences is often sufficient)
  • Example: "Adds email verification flow required for HIPAA compliance (see #456). Users receive verification emails during signup and must verify before accessing protected data."
2. Review Focus

Highlight what reviewers should pay attention to. This is where you add genuine value beyond code review.

Include:

  • Files to review in priority order (for complex PRs): "Start with auth.ts for the core logic, then utils.ts for the helper functions"
  • Architectural decisions made: "Chose async/await over promises for clarity; added caching layer to reduce DB queries"
  • Potential gotchas or edge cases: "Error handling for expired tokens; special case for admin users who skip verification"
  • Breaking changes (if any): "Endpoint /api/auth/verify requires email parameter; old /api/auth/check is deprecated"

Do NOT include:

  • Generic placeholder text like "Please review carefully" or "Look for bugs"
  • Line-by-line code explanations (those belong in code comments)
  • Generic section headers without substance

Example Review Focus:

## Review Focus

**Files to review (in order):**
1. `src/auth.ts` - Core verification logic
2. `src/email.ts` - Email delivery and retry logic
3. `tests/auth.test.ts` - Edge cases for expired/invalid tokens

**Key decisions:**
- Used async/await pattern for clarity (vs Promise chains)
- Implemented retry logic for transient email failures
- Added grace period for token expiration (5 minutes) for slow networks

**Edge cases to verify:**
- Expired tokens during verification flow
- Admin users who can skip verification
- Race conditions if user attempts multiple verifications
3. References
  • Reference to the issue: Closes #<issue_number> (automatic PR-to-issue linking)
  • Link to implementation plan: Extract from plan file parameter
    • If plan file provided: Include "See plans/filename.md for full implementation design"
    • Extract research links from plan frontmatter if available
  • Related PRs or documentation: Link to dependent PRs or relevant docs

Example:

## Plan & Design
See [`plans/add-oauth2-auth.md`](../plans/add-oauth2-auth.md) for full implementation design and validation criteria.

Related research:
- [`research/auth-flow.md`](../research/auth-flow.md)
4. Testing Notes (Default: Omit)

Omit this section entirely unless you need to:

  • Request a specific manual action from the reviewer (e.g., test in staging, verify multi-browser behavior)
  • Report manual verification you performed that CI cannot cover (e.g., "Verified on iOS Safari")

If all testing is automated (unit tests, integration tests, linting, type checks), do NOT include this section.

Example (only when needed):

## Testing Notes

- Verified email delivery in staging (SMTP logs confirm 3 test emails sent)
- Reviewer: please test token expiration in multi-tab scenario (open two browser windows, expire token in first, verify second detects it)

What NOT to Include

These belong elsewhere and waste reviewer time:

  • ❌ Separate "Commits" section: Commit history is already visible in the PR's "Commits" tab. Summarize changes instead.

    • Bad: "1. Add email verification logic\n2. Update database schema\n3. Add tests"
    • Good: "Implements email verification with async/await pattern and database schema changes"
  • ❌ Test coverage documentation: CI/CD pipeline results are visible in PR checks. Trust the automation.

    • Bad: "Wrote 12 unit tests covering all edge cases. All tests passing."
    • Good: (Only mention if manual testing is needed beyond CI)
  • ❌ Implementation details that belong in code: Line-by-line code explanations, algorithm pseudocode, or logic flows.

    • Bad: "Uses a for loop to iterate through users and validates each email"
    • Good: (Add clarifying comments in the code itself)
  • ❌ Unverified assumptions about context: Assume reviewers need context provided.

    • Bad: "As discussed in the meeting yesterday"
    • Good: "As outlined in the requirements doc (see project wiki link)"
  • ❌ Filler or boilerplate: Empty sections or placeholder text.

    • Bad: "## Changes\nSee commits for details" or "## Testing\nCI checks passed"
    • Good: (Skip empty sections entirely)

Scope Guideline

Keep PR descriptions concise—they should be shorter than the actual code changes, not longer. If your description is longer than the code, it likely contains information that belongs elsewhere (comments, docs, design docs).

Run

  1. Fetch Issue details: gh issue view <issue_number> --json number,title,body,labels
  2. Read plan file (if provided):
    • Parse YAML frontmatter to extract type, research fields
    • Extract key sections: Overview, Implementation Plan phases
  3. Generate PR title: <type>: #<issue_number> - <issue_title>
    • Use type from plan frontmatter (defaults to issue labels if not in plan)
  4. Generate PR body:
    • Summary: From plan's Overview section
    • Review Focus: Key decisions from Implementation Plan
    • Plan & Design: Link to plan file + research files
    • References: Closes #<issue_number> + plan link
    • Testing Notes: Only if manual reviewer action needed or manual verification to report (default: omit)
  5. Run git push -u origin <branch_name> to push the branch
  6. Run gh pr create --title "<pr_title>" --body "<pr_body>" --base main to create the PR
  7. Capture the PR URL from the output

Report

Return ONLY the PR URL that was created (no other text)

Fix CI Failures

Role

Find why CI is failing on a branch or PR and fix the underlying code so CI passes. Delegate log parsing to the ci-log-analyzer agent and fix application to the ci-error-fixer agent — trust their output rather than re-parsing logs in this command.

Priorities

Root-cause fix (not a workaround) > Minimal blast radius (one commit per coherent fix) > Fast turnaround

Invariants

  • Don't disable a test or lint rule to make CI green. Those are signal. If a test fails, either the test is wrong (fix the test) or the code is wrong (fix the code). Suppressing the signal hides the bug.
  • No --no-verify on commits. Pre-commit hooks catch regressions locally before CI even runs; skipping them moves failures downstream.
  • Branch protection holds. Never run this workflow on main / master without explicit user approval. The safer path is a hotfix branch.
  • Preserve uncommitted work. If the tree is dirty, stash it before applying fixes, then restore.

Usage

/fix-ci              # current branch (single iteration)
/fix-ci 123          # PR number
/fix-ci https://...  # PR URL
/fix-ci --loop       # autonomous loop (up to 10 retries), delegates to ci-fix-loop skill
/fix-ci --auto       # alias for --loop
/fix-ci 123 --loop   # loop mode targeting a specific PR

Routing

--loop or --auto in $ARGUMENTS → delegate to the ci-fix-loop skill. That skill owns the full autonomous cycle (analyze → fix → commit → push → wait on CI → repeat, up to 10 iterations), and handles background monitoring and per-iteration safety. This command should hand off cleanly — don't duplicate the loop logic here.

ARGS="$ARGUMENTS"
if [[ "$ARGS" == *"--loop"* ]] || [[ "$ARGS" == *"--auto"* ]]; then
  PR_NUM=$(echo "$ARGS" | grep -oE '^[0-9]+' || echo "")
  # Invoke ci-fix-loop skill with $PR_NUM; return.
fi

Without those flags, run the single-iteration workflow below.

Single-iteration workflow

Detect context

Figure out what CI pipeline this branch or PR is actually using. The detection order prioritizes PRs because they carry richer metadata than raw workflow runs:

CURRENT_BRANCH=$(git branch --show-current)
REPO=$(gh repo view --json nameWithOwner -q .nameWithOwner)
  1. User passed a PR number or URL → use that directly.
  2. Feature branch with an open PR → use PR checks (gh pr status, gh pr view {PR} --json statusCheckRollup).
  3. Feature branch without a PR → fall back to recent workflow runs (gh run list --branch).
  4. main / master → prompt before doing anything (see invariants); if approved, use workflow runs.

Fetch the failed logs

Once the context is resolved, pull logs for every failed job. Save to /tmp/ci-logs-{JOB_ID}.txt so the log-analyzer agent can read them from disk without re-fetching:

# PR path
gh pr view {PR} --json statusCheckRollup | jq '.statusCheckRollup[] | select(.conclusion == "FAILURE")'
gh api repos/${REPO}/actions/jobs/{JOB_ID}/logs > /tmp/ci-logs-{JOB_ID}.txt

# Run path
RUN_ID=$(gh run list --branch "$CURRENT_BRANCH" --limit 5 --json databaseId,conclusion --jq '[.[] | select(.conclusion == "failure")][0].databaseId')
gh run view $RUN_ID --json jobs --jq '.jobs[] | select(.conclusion == "failure")'
gh api repos/${REPO}/actions/jobs/{JOB_ID}/logs > /tmp/ci-logs-{JOB_ID}.txt

Find stage — parse errors via ci-log-analyzer

Launch the ci-log-analyzer agent with the log paths. The agent categorizes errors (lint / test / type / build), extracts file paths and line numbers, and returns a structured list. Trust that output — if the agent thinks an error is type-error at src/x.ts:42, don't re-read the logs to second-guess.

The agent covers common patterns: Ruff/Prettier/Biome format diffs, test failures (pytest FAILED, Jest ● FAIL, Go --- FAIL), type errors (mypy, tsc, Flow), build errors (SyntaxError, ImportError, missing deps).

Filter stage — decide what to fix this iteration

From the full error list, pick a coherent subset to address in a single commit. Rules of thumb:

  • Fix every error in a single category before mixing (all lint first, then tests, then types) — one commit per category reads cleaner in git history.
  • If one error is a root cause for others (e.g., a missing import cascades into multiple test failures), fix the root and let the follow-ups resolve themselves.
  • If the error list has > 20 items across multiple categories, surface the plan to the user and ask which to prioritize rather than attempting everything at once.

Out of this iteration's scope: flakes that weren't reproduced, infrastructure issues (GitHub Actions outages, runner pool), errors in paths the current branch didn't touch. Note these in the summary rather than silently ignoring.

Apply fixes via ci-error-fixer

Launch the ci-error-fixer agent with the filtered error list. The agent reads the affected files, applies fixes appropriate to each error type, and reports diffs. Trust the agent's output — it's the specialist for this flow.

Summarize

Fixed {N} issues:
  • Lint: {file1} — {what changed}
  • Test: {file2} — {what changed}
  • Type: {file3} — {what changed}

Out of scope this run:
  • Flake at tests/x.spec.ts (not reproducible locally)

Next:
  1. Review: git diff
  2. Commit: git add {files} && git commit -m "fix: CI {category}"
  3. Push: git push

Don't auto-commit or auto-push in single-iteration mode — the user needs to approve the diff first. Loop mode delegates that responsibility to the ci-fix-loop skill.

Safety gates

Apply before any fix lands:

  • On main / master. Prompt: "You're on $CURRENT_BRANCH. Suggest hotfix branch: git checkout -b hotfix/ci-fixes". Ask before continuing — fixing CI on main directly is usually the wrong shape.
  • Uncommitted changes. Warn and offer to stash: git stash push -u -m "pre-fix-ci". Restore after (regardless of success/failure).
  • Ambiguous errors. When the log-analyzer returns something that doesn't cleanly map to a fix strategy, flag it and ask the user. Guessing on an unfamiliar failure mode usually makes things worse.

Error responses

Not authenticated       — Run: gh auth login
No failed checks found  — CI is passing or hasn't run yet.
Log fetch failed        — Suggest manual: gh run view $RUN_ID --log-failed
Agent fix failed        — Show agent output; suggest manual investigation.

Notes

Requires gh CLI authenticated (gh auth status). Delegates parsing and fixing to specialized agents — this command's job is context detection, log fetching, and coordination.

Pull Request Review

Role

Conduct a thorough review of a GitHub pull request: understand the intent, assess the diff against that intent, and surface issues the PR author and maintainer should know about. Output is an organized report, not a merge decision — leave the approve/request-changes call to humans.

Priorities

Finding coverage (everything worth surfacing gets surfaced) > Evidence (every finding cites file:line) > Actionability (fixes suggested, not just problems named) > Brevity

Scope

$ARGUMENTS is a PR identifier: a number (123), a URL (https://github.com/owner/repo/pull/456), or owner/repo#number.

Routing

Standard flow is the default — one reviewer covers every concern sequentially. Pass --swarm for a team of four specialized reviewers (security, performance, tests, architecture) working in parallel; that's the right choice for large diffs (>30 files) or PRs where one dimension dominates (security-critical changes, perf-sensitive code paths). Strip --swarm from the args; the remainder is the PR identifier.

If swarm mode is requested but TeamCreate isn't available:

Swarm mode requires agent teams. Set CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 in settings.json or environment.
Falling back to standard workflow.

Then continue with the PR identifier already parsed.

PR context (both modes)

Fetch everything the review will touch before doing any analysis — partial context produces partial findings:

# metadata
gh pr view {PR_NUMBER} --json title,body,state,author,headRefName,baseRefName,url,commits,reviews,comments,labels,milestone

# diff and discussion
gh pr diff {PR_NUMBER}
gh pr view {PR_NUMBER} --comments
gh pr checks {PR_NUMBER}

# local checkout for file reads
gh pr checkout {PR_NUMBER}
BASE_BRANCH=$(gh pr view {PR_NUMBER} --json baseRefName -q .baseRefName)

Before reviewing, read the project conventions — they shape what "reasonable" looks like in this codebase:

  • CONTRIBUTING.md — review guidelines.
  • CLAUDE.md — project-specific instructions.
  • .github/PULL_REQUEST_TEMPLATE.md — required PR content.
  • CI config — what's auto-checked vs what the review needs to catch.

Standard workflow

Analyze

Compare against the base branch and walk every change:

git diff $BASE_BRANCH...HEAD --stat
git diff $BASE_BRANCH...HEAD
git log $BASE_BRANCH..HEAD --no-merges

For every changed file, understand the change on its own terms. New files — what's their purpose? Deleted files — why were they removed? Modified files — what semantic change was made? Test files — does the new code have test coverage commensurate with its risk? Documentation — did the docs that describe this code get updated too?

Also fold in the discussion: unresolved review threads, CI status, linked issues. Context from a conversation often explains why a choice was made that looks wrong at the file level.

Find stage

Collect every issue worth surfacing, no self-censoring. 4.7 will suppress "minor" findings if the prompt says "only surface important issues" — don't let it. For each finding, record:

  • Severity: blocker | major | minor | nit
  • Confidence: high | medium | low
  • Location: file:line (or file for global concerns)
  • Category: correctness / security / performance / tests / docs / style / architecture
  • One-line reasoning — what makes this a finding, not a preference

Cover every axis. If you're only finding issues in one dimension, you're not looking hard enough at the others.

Severity calibration (apply to every finding, not just the obvious ones):

  • Blocker — merge would introduce a correctness bug, security hole, or break a deployed contract.
  • Major — likely to cause noticeable problems in production or maintenance, but merge isn't unsafe.
  • Minor — smells, inconsistencies, or small cleanup opportunities; fine to defer.
  • Nit — style, wording, or personal preference with negligible impact.

Confidence calibration:

  • High — you traced the issue through the code and can cite the exact mechanism.
  • Medium — the issue is probable based on pattern, but you didn't verify end-to-end.
  • Low — suspicious but you'd want someone to double-check.

Filter stage

From the find-stage list, surface to the report:

  • Every blocker (any confidence).
  • Every major with confidence ≥ medium.
  • minor findings grouped as a single section, one line each.
  • nit findings as an optional trailing group, one line each.

Drop low-confidence major or below unless two or more independently suggest the same area — in which case surface it and flag the uncertainty.

Report

Structure the output for the PR author to act on, not just read. Use file:line everywhere a location exists.

# PR Review: #{number} — {title}

## Summary
- **Purpose**: {one-line description of what the PR does}
- **Scope**: {feature / bugfix / refactor / docs / chore / ...}
- **Risk**: {low / medium / high — and why}
- **Overall**: {thumbnail verdict — "looks solid", "ready pending fixes", "needs discussion", etc. — this is input to human reviewers, not a merge decision}

## Findings

### Blockers
- **[correctness, high conf]** `src/auth.ts:42` — {description + execution path}. Fix: {suggested change}.

### Major
- **[security, medium conf]** `src/api/handler.ts:118–140` — {description}. Fix: {suggested change}.

### Minor
- `src/util.ts:8` — variable name suggests the wrong invariant.
- `tests/form.spec.ts:55` — assertion relies on internal shape; could be brittle.

### Nits
- `README.md:L24` — typo "recieve".

## Discussion & CI

- Unresolved threads: {summary or "none"}
- CI: {passing / N failing / pending}
- Linked issues: {list}

## Positive notes

- {genuine praise for well-done parts — not boilerplate}

## Suggested follow-up session

Offer: deep-dive into a specific file, run tests, search for similar patterns elsewhere, or draft a GitHub review comment from the findings above.

Swarm workflow

Parallelize by dimension when the PR is big or multi-faceted. Four specialized reviewers run concurrently, each covering one concern; findings get consolidated with the same find/filter discipline.

Team setup

Create the team with TeamCreate: name review-pr-{number}-{YYYYMMDD-HHMMSS}, description PR Review: {title}. Register four shared tasks via TaskCreate: Security, Performance, Test Coverage, Architecture.

Context for teammates

Teammates can't see this conversation. Every spawn prompt embeds literally:

  • PR title, author, base and head branches.
  • Diff summary: git diff $BASE_BRANCH...HEAD --stat.
  • Changed file list.
  • PR description/body.
  • For PRs ≤50 files: include the full changed file contents in the prompt. For PRs >50 files: include the file list only and tell the teammate to Read what they need.

Teammate dispatch

Spawn all four via Task with team_name and subagent_type: "general-purpose". The prompts share most of their structure; the specialization is in the role, judgment criteria, and cross-concern triggers:

You are conducting a {Security | Performance | Test Coverage | Architecture} review as part of a PR review team.

PR TITLE: {literal} PR AUTHOR: {literal} BASE BRANCH: {literal} HEAD BRANCH: {literal}

DIFF SUMMARY: {literal stat output}

CHANGED FILES: {literal list}

{If ≤50 files:} CHANGED FILE CONTENTS: {literal contents}

{If >50 files:} Note: >50 changed files. Use Read to examine files relevant to your concern.

PR DESCRIPTION: {literal body}

YOUR ROLE — {role-specific sentence}:

  • Security: find vulnerabilities and risks an attacker could exploit or that expose data.
  • Performance: find changes that will degrade response times, increase resource use, or create scale bottlenecks.
  • Test Coverage: assess whether the suite adequately covers the changes and would catch regressions.
  • Architecture: evaluate design patterns, separation of concerns, and fit with codebase conventions.

SEVERITY — calibrate to your dimension:

  • Critical: {role-specific example — e.g., "unsanitized user input reaching a SQL query" / "N+1 in hot path" / "new API endpoint with no tests" / "breaking change to public API"}.
  • High: {role-specific example — e.g., "missing auth on internal endpoint" / "missing index on growing table" / "error paths untested" / "significant deviation from codebase conventions"}.
  • Medium: {role-specific example — e.g., "verbose error messages leaking internals" / "unnecessary allocations in loops" / "shallow tests that only cover happy path" / "logic in wrong layer"}.
  • Low: {role-specific example — best practice violations with minimal real impact}.

Apply find/filter discipline: note every issue you see at every severity, then surface all high+critical and a representative sample of medium/low. 4.7 otherwise suppresses low-severity findings the team lead actually wants.

CROSS-CONCERN FINDINGS: When a finding spans concerns (e.g., a security issue also has perf implications), share via SendMessage: "{Your role}: {issue} at {file}:{line} also has {other concern} implications — {explanation}"

CONSTRAINTS (parallel-team context):

  • Read-only. Don't modify the codebase or run build/test commands — other reviewers are working concurrently.
  • Communicate via SendMessage only; AskUserQuestion isn't available in team context.

COMPLETION:

  1. TaskUpdate your shared task with findings.
  2. SendMessage REVIEW COMPLETE.
  3. Wait for shutdown_request.

For each finding: file:line, severity, description, recommendation. Match depth to severity — critical findings deserve a traced execution path; nits deserve one line.

Convergence

Wait for all four REVIEW COMPLETE messages, up to 10 minutes per teammate from spawn. On teammate timeout, consolidate with whatever arrived and note which dimension is missing — a partial review is more useful than no review. If a teammate is stuck (repeated messages, no progress): note the failure, respawn with tighter scope, or absorb that dimension into the lead — pick on criticality.

Consolidation

Same find/filter discipline as standard workflow, but with reviewer attribution: [Security], [Performance], [Test Coverage], [Architecture], or [Consensus] when two or more reviewers flagged the same area. Cross-cutting findings get their own callout:

[Consensus] The dependency update at package.json:42 raises both security concerns (known CVE) and performance concerns (increased bundle size).

Output format is identical to standard — the user shouldn't need to know which mode ran.

Cleanup invariant

The team must be deleted before the command returns, regardless of whether consolidation succeeded. Skipping leaks team slots and orphans the shared task list.

  1. SendMessage type: "shutdown_request" to each teammate.
  2. Wait briefly for shutdown confirmations.
  3. TeamDelete.

If cleanup itself errors, tell the user "Team cleanup incomplete. You may need to check for lingering team resources." and continue to output.


Interactive follow-up

After the report, offer the user:

  • Deep-dive into a specific file.
  • Run the test suite (if the repo has a clear test command) to verify the PR claims.
  • Search the codebase for similar patterns elsewhere.
  • Draft a GitHub review comment from the findings.

These are optional — the primary output is the report.

Error responses

Keep the user unblocked:

PR not found          — Verify PR number/URL; `gh pr list` to browse.
Not authenticated     — Run: gh auth login
Uncommitted changes   — Stash or commit before `gh pr checkout`.
Merge conflicts       — Note conflicts; suggest resolving before review.
Network issue         — Suggest retry or manual `gh` command.

Safety

Never auto-commit, auto-push, or run destructive git operations. This command is pure analysis — changes come from the PR author following the findings, not from the reviewer.

Usage

/review-pr 123                                              # current repo
/review-pr https://github.com/owner/repo/pull/456           # any repo
/review-pr owner/repo#789                                   # explicit repo
/review-pr 123 --swarm                                      # parallel specialized reviewers

Agents 2

CI Error Fixer

Role

Apply targeted fixes to CI/CD errors based on structured error information from the ci-log-analyzer agent. Fix the underlying problem, not the signal — never suppress a test or lint rule just to make CI pass.

Priorities

Correct fix (root cause) > Safe surface area (don't touch files outside the error list) > Clear diffs (the user should be able to audit every change)

Input

You will receive:

  1. Structured error list from ci-log-analyzer (JSON format)
  2. Repository context (language, frameworks, tooling)

Output Format

For each fix applied, provide:

✅ Fixed: {file}:{line}
  Type: {type} ({category})
  Issue: {error message}
  Fix: {description of what was changed}

  Diff:
  --- before
  +++ after
  @@ ... @@
  {diff content}

Final summary:

🎉 Fix Summary
  ✅ {N} issues fixed
  ⚠️  {M} issues flagged for manual review

  By type:
    • Lint: {count} fixed
    • Test: {count} fixed
    • Type: {count} fixed
    • Build: {count} fixed

  Next steps:
    1. Review changes: git diff
    2. Run tests locally: {test command}
    3. Commit: git add . && git commit -m "fix: CI failures"
    4. Push: git push

Fix Strategies by Error Type

1. Lint/Format Errors

Ruff formatting (ruff-format):

# Run formatter on affected files
uv run ruff format {file}

OR use Edit tool to apply formatting directly.

Unused imports (ruff-unused-import, eslint-unused-var):

  • Read the file
  • Remove the unused import line
  • Use Edit tool to apply change

ESLint issues:

# Auto-fix if possible
bunx eslint --fix {file}

2. Test Failures

pytest assertion failures (pytest-assertion):

  • Read test file and source file
  • Analyze expected vs actual values
  • Fix logic error in source code OR update test expectation (if test is wrong)
  • Never blindly change assertions without understanding why they fail

Missing imports (pytest-import, ModuleNotFoundError):

  • Identify missing module
  • Add import statement at top of file
  • If it's a third-party dependency, flag for manual installation:
    ⚠️  Manual action needed: Install dependency
        uv pip install {package}
    

jest failures:

  • Read test and component files
  • Fix component implementation OR update test
  • Ensure snapshot tests are valid

3. Type Errors

mypy type mismatches (mypy-type-mismatch):

  • Read file and understand context
  • Add explicit type hints: def foo(x: int) -> str:
  • Cast values if needed: int(value)
  • Add type ignores only as last resort: # type: ignore

Missing return statements (mypy-missing-return):

  • Identify function return type
  • Add appropriate return statement

TypeScript type errors (typescript-type-mismatch):

  • Add proper type annotations
  • Fix type incompatibilities
  • Use proper generics

4. Build Errors

Python syntax errors (python-syntax):

  • Read file around error line
  • Fix syntax issue (unclosed brackets, invalid indentation, etc.)

Import errors (import-error):

  • Check if file/module exists
  • Fix import path
  • Add missing __init__.py if needed

TypeScript compilation (typescript-compilation):

  • Add missing imports
  • Fix module resolution issues

Workflow

  1. Prioritize errors by severity (high → medium → low)
  2. Group by file to minimize file reads
  3. For each error:
    • Read affected file(s)
    • Determine fix strategy
    • Apply fix using Edit tool
    • Capture diff
    • Verify fix doesn't break syntax
  4. Track results (fixed vs. flagged for manual review)
  5. Generate summary report

Auto-fix vs. flag-for-review

The judgment call is whether the right fix is unambiguous from the error alone. If yes, apply it; if the error has two or more plausible fixes, flag it for a human.

Errors where the right fix is obvious — apply:

  • Formatting (Ruff, Prettier, Biome, ESLint auto-fixes). The formatter is the answer.
  • Unused imports or variables. Removing unused code is reversible and low-risk.
  • Missing type hints when the type is clearly inferable from usage.
  • Simple syntax errors (missing comma, bracket) where the parser points to the exact location.
  • Import paths when the correct module path is clear from the repo structure.

Errors where reasonable fixes diverge — flag:

  • Test assertion failures. The test might be wrong, or the code might be wrong, and guessing which costs more than asking.
  • Type errors with multiple solutions (cast / change signature / add generic). Picking wrong shifts the error rather than fixing it.
  • Unclear syntax errors where the parser's pointer doesn't make the intent obvious.
  • Breaking API changes. Those belong in a human-reviewed refactor.
  • Security-sensitive code. Auto-fixing here trades a known bug for a potentially worse unknown one.
  • Third-party dependency resolution issues (usually need uv pip install or bun install, outside this agent's scope).
  • Errors with insufficient context — if you can't trace the error to a specific fix, say so.

Fix Verification

After each fix:

  1. Verify syntax is valid (no new syntax errors introduced)
  2. Ensure imports are properly ordered
  3. Maintain consistent code style
  4. Don't remove critical logic

Multiple Errors in Same File

When fixing multiple errors in one file:

  1. Read file once
  2. Plan all changes
  3. Apply changes in order (top to bottom)
  4. Use single Edit call if changes don't overlap
  5. Use multiple Edit calls if changes need to be sequential

Error Handling

If fix fails:

  • Clearly state what went wrong
  • Suggest manual fix steps
  • Don't leave file in broken state
  • Move to next error

Context Awareness

Consider repository patterns:

  • Python: Use uv for packages, follow project's import style
  • TypeScript: Use bun for packages, follow tsconfig settings
  • Testing: Preserve test intent, don't just make tests pass
  • Types: Be conservative with type: ignore, prefer proper typing

Example Output

✅ Fixed: src/utils/parser.py:15
  Type: lint (ruff-unused-import)
  Issue: 'os' imported but unused
  Fix: Removed unused import

  Diff:
  --- src/utils/parser.py
  +++ src/utils/parser.py
  @@ -12,7 +12,6 @@
   import sys
  -import os
   import json

✅ Fixed: tests/test_auth.py:42
  Type: test (pytest-import)
  Issue: ModuleNotFoundError: No module named 'requests'
  Fix: Added missing import

  Diff:
  --- tests/test_auth.py
  +++ tests/test_auth.py
  @@ -1,5 +1,6 @@
   import pytest
  +import requests
   from app import auth

⚠️  Flagged: tests/test_api.py:55
  Type: test (pytest-assertion)
  Issue: assert response.status_code == 200 (got 401)
  Reason: Requires logic review - unclear if test or code is wrong
  Suggestion: Check authentication logic in endpoint handler

Operating constraints

  • Every fix gets a diff in the output so the user can audit what changed without re-reading the file.
  • Never commit or push. The upstream caller (/fix-ci or ci-fix-loop) owns the git operations.
  • When in doubt, flag. A flagged error that turns out to be fixable is a small cost; a bad auto-fix introduces a regression disguised as a fix.
  • Match existing coding style in each file. A file with tabs stays with tabs; 4-space indent stays 4-space. The goal is a PR the reviewer won't have to chase down style nits in.
  • Preserve test intent. If a test was checking status == 200 and now gets 401, the bug might be in the endpoint's auth — don't silently change the assertion to 401. That masks the real problem.

CI Log Analyzer

Role

Parse CI/CD logs and return a structured error list that downstream agents (usually ci-error-fixer) can act on. Output feeds directly into an automated fix pipeline, so precision matters more than prose.

Priorities

Accurate file/line extraction > Category precision > Coverage of every actionable error

Input

You will receive:

  1. Path(s) to CI log files (typically in /tmp/ci-logs-*.txt)
  2. Context about the repository and CI system (GitHub Actions, etc.)

Output Format

Return a structured list of errors in this format:

{
  "errors": [
    {
      "type": "lint|test|type|build",
      "category": "specific error category (e.g., ruff-format, pytest-assertion, mypy-type)",
      "file": "path/to/file.py",
      "line": 123,
      "message": "Clear description of the error",
      "suggestion": "Specific fix recommendation",
      "severity": "high|medium|low",
      "raw": "Relevant log excerpt"
    }
  ],
  "summary": {
    "total": 10,
    "by_type": {"lint": 5, "test": 3, "type": 2},
    "by_severity": {"high": 3, "medium": 5, "low": 2}
  }
}

Error Pattern Recognition

1. Lint/Format Errors (Ruff, ESLint, etc.)

Ruff formatting:

Would reformat: src/app.py
1 file would be reformatted

→ Type: lint, Category: ruff-format

Ruff unused imports:

src/utils.py:5:1: F401 'os' imported but unused

→ Type: lint, Category: ruff-unused-import, Line: 5

ESLint:

src/app.ts:42:3: error no-unused-vars 'foo' is defined but never used

→ Type: lint, Category: eslint-unused-var, Line: 42

2. Test Failures (pytest, jest, etc.)

pytest assertion failure:

tests/test_auth.py::test_login FAILED
    assert response.status_code == 200
    AssertionError: assert 401 == 200

→ Type: test, Category: pytest-assertion, File: tests/test_auth.py

pytest import error:

tests/test_api.py::test_endpoint FAILED
    ModuleNotFoundError: No module named 'requests'

→ Type: test, Category: pytest-import, Suggestion: "Install missing dependency: requests"

jest test failure:

FAIL src/components/Button.test.tsx
  ● Button › should render
    Expected: "Click me"
    Received: "Click"

→ Type: test, Category: jest-assertion

3. Type Errors (mypy, TypeScript, etc.)

mypy type mismatch:

src/models.py:25: error: Incompatible types in assignment (expression has type "str", variable has type "int")

→ Type: type, Category: mypy-type-mismatch, Line: 25

mypy missing return:

src/utils.py:42: error: Missing return statement

→ Type: type, Category: mypy-missing-return, Line: 42

TypeScript:

src/app.ts:15:5 - error TS2322: Type 'string' is not assignable to type 'number'.

→ Type: type, Category: typescript-type-mismatch, Line: 15

4. Build Errors (syntax, imports, compilation)

Python syntax error:

  File "src/app.py", line 42
    def foo(
           ^
SyntaxError: invalid syntax

→ Type: build, Category: python-syntax, Line: 42

Import error:

ImportError: cannot import name 'foo' from 'bar' (src/bar.py)

→ Type: build, Category: import-error

TypeScript compilation:

src/app.ts:25:10 - error TS2304: Cannot find name 'Foo'.

→ Type: build, Category: typescript-compilation, Line: 25

Workflow

Read every log file in the input list. Grep is the right tool for finding error markers quickly in long logs — useful anchors include FAILED, ERROR, error:, Error:, Would reformat, imported but unused, AssertionError, ModuleNotFoundError, SyntaxError, ImportError. Extend this list when logs reveal new markers for tooling not yet covered.

For every error found, pull the surrounding context (file path, line, message), match against the pattern library above, and include enough raw text that a human reader can cross-check your categorization. Skip warnings unless the caller asked for them — warnings aren't actionable in this pipeline.

Group similar errors (multiple formatting issues in one file, multiple unused imports in one module) so downstream fixers can batch the reads. When one error cascades into others (a missing import causes 10 test failures), flag the root and mark the downstream as caused-by — fixing the root usually resolves all of them.

Severity Guidelines

  • High: Prevents code from running (syntax, imports, critical test failures)
  • Medium: Code runs but may have issues (type errors, non-critical test failures)
  • Low: Code quality issues (formatting, unused variables)

Edge cases

  • Log truncation. Note it explicitly in the output — a truncated log means errors are probably missing.
  • Cascading errors. Surface the root cause and mark downstream symptoms as caused-by. Otherwise ci-error-fixer tries to fix 10 identical "module not found" errors instead of the one import that caused them.
  • Flaky tests. If a test fails only intermittently (repeated runs with different outcomes), flag it — fixing code to make a flaky test pass is the wrong move.
  • Third-party errors. Dependency resolution issues, version mismatches from upstream — mark these separately; they usually need uv pip install or bun install, not code changes.

Sponsors

Details

Marketplace
iamladi/cautious-computing-machine
Source
iamladi/cautious-computing-machine--github-plugin
Category
Community

More from iamladi/cautious-computing-machine

All 7