[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M75XAMXX2RHK5AMDNNZ2WKXW":3,"skill-same:01M75XAMXX2RHK5AMDNNZ2WKXW":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":30,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M75XAMXX2RHK5AMDNNZ2WKXW","pr-automation",null,"PR Automation Orchestrator: poll open PRs, check CI, run review, fix, and merge eligible PRs.\nUse when: (1) Invoked by daemon via scripts\u002Fpr-automation.sh, (2) User says \"\u002Fpr-automation\".","oliverhees\u002FLokkyWork","oliverhees","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F38748506?v=4","01M75X9T66RT9877CBYZK4MCBZ","Oliver Hees","01M75X9T6VRS2NWRCVC7SKKZSQ",1,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Foliverhees\u002FLokkyWork\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fpr-automation\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: pr-automation\ndescription: |\n  PR Automation Orchestrator: poll open PRs, check CI, run review, fix, and merge eligible PRs.\n  Use when: (1) Invoked by daemon via scripts\u002Fpr-automation.sh, (2) User says \"\u002Fpr-automation\".\n---\n\n# PR Automation\n\nOrchestrate the full PR automation lifecycle using a label-based state machine.\nEach invocation performs at most one \"heavy\" action (review or fix), then exits.\nPure skips continue within the same session to find the next eligible PR.\n\n**Announce at start:** \"I'm using pr-automation skill to process PRs.\"\n\n## Usage\n\n```\n\u002Fpr-automation\n```\n\nNo arguments required. The daemon script `scripts\u002Fpr-automation.sh` manages the automation loop.\n\n## Configuration\n\n```\nTRUSTED_CONTRIBUTORS_TEAM: detected from REPO org (e.g. iOfficeAI\u002Ftrusted-contributors)\nCRITICAL_PATH_PATTERN: env var, default in scripts\u002Fpr-automation.conf\nLARGE_PR_FILE_THRESHOLD: env var (default: 50), also in scripts\u002Fpr-automation.conf\nPR_DAYS_LOOKBACK: env var (default: 7), also in scripts\u002Fpr-automation.conf\n```\n\n**REPO** is detected automatically at runtime — do not hardcode it:\n\n```bash\nREPO=$(gh repo view --json nameWithOwner --jq '.nameWithOwner')\nORG=$(echo \"$REPO\" | cut -d'\u002F' -f1)\n```\n\n## Label State Machine\n\n| Label                    | Meaning                                                                 | Terminal? |\n| ------------------------ | ----------------------------------------------------------------------- | --------- |\n| `bot:reviewing`          | Review in progress (mutex)                                              | No        |\n| `bot:ready-to-fix`       | CONDITIONAL review done, waiting for bot to fix next session            | No        |\n| `bot:fixing`             | Fix in progress (mutex)                                                 | No        |\n| `bot:ci-waiting`         | CI failed and author notified — snoozed until author pushes new commits | No        |\n| `bot:needs-rebase`       | Merge conflict that bot cannot auto-resolve — author must rebase        | No        |\n| `bot:needs-human-review` | Blocking issues — human must intervene                                  | Yes       |\n| `bot:ready-to-merge`     | Bot done, code is clean — human just needs to confirm and merge         | Yes       |\n\n## Exit Rules\n\n- **Any substantive action** (approve workflow, post comment, run review, run fix) → EXIT after completing\n- **Pure skip** (WIP, draft, terminal label, CI running, mergeability unknown, `bot:ci-waiting`) → continue to find next PR in same session\n\n---\n\n## Steps\n\n### Step 1 — Fetch Candidate PRs\n\nRead the lookback window from the environment (default 7 days):\n\n```bash\nDAYS=${PR_DAYS_LOOKBACK:-7}\ngh pr list \\\n  --state open \\\n  --search \"created:>=$(date -v-${DAYS}d '+%Y-%m-%d' 2>\u002Fdev\u002Fnull || date -d \"${DAYS} days ago\" '+%Y-%m-%d') -is:draft\" \\\n  --json number,title,labels,createdAt,author \\\n  --limit 50\n```\n\nSave the result as `candidate_prs`.\n\nIf `candidate_prs` is empty: log `[pr-automation] No open PRs found. Exiting.` then log `[pr-automation:exit] action=no_prs reason=\"no open PRs\"` and EXIT.\n\n### Step 2 — Get Trusted Contributors\n\n```bash\ngh api orgs\u002F${ORG}\u002Fteams\u002Ftrusted-contributors\u002Fmembers --jq '[.[].login]'\n```\n\nSave as `trusted_logins`. If API call fails, treat as empty array.\n\n### Step 3 — Select Target PR\n\nSort `candidate_prs` using this **three-key** order:\n\n1. **Primary**: has label `bot:ready-to-fix` → these PRs first\n2. **Secondary**: author.login in `trusted_logins` → trusted PRs next\n3. **Tertiary**: createdAt ascending (oldest first \u002F FIFO)\n\nIterate through sorted list to find the **first eligible PR**.\n\n**Skip conditions** (skip this PR, try next — stay in session):\n\n| Condition                               | Check                                                                       |\n| --------------------------------------- | --------------------------------------------------------------------------- |\n| Title contains `WIP` (case-insensitive) | `title.toLowerCase().includes('wip')`                                       |\n| Has label `bot:needs-rebase`            | check labels array                                                          |\n| Has label `bot:needs-human-review`      | check labels array                                                          |\n| Has label `bot:ready-to-merge`          | check labels array                                                          |\n| Has label `bot:done`                    | check labels array                                                          |\n| Has label `bot:reviewing`               | check labels array                                                          |\n| Has label `bot:fixing`                  | check labels array                                                          |\n| Has label `bot:ci-waiting`              | check labels array — wake-up check runs as fallback if no eligible PR found |\n\n**When eligible PR found:**\n\nFor **fresh PRs** (no bot: label): add `bot:reviewing` to claim it:\n\n```bash\ngh pr edit \u003CPR_NUMBER> --add-label \"bot:reviewing\"\n```\n\nFor **`bot:ready-to-fix` PRs**: swap label atomically:\n\n```bash\ngh pr edit \u003CPR_NUMBER> --remove-label \"bot:ready-to-fix\" --add-label \"bot:fixing\"\n```\n\nSave this PR as `target_pr` (number, title, author.login, is_ready_to_fix).\n\n**If no eligible PR found after full iteration:** run the snoozed PR wake-up checks as a fallback before giving up.\n\n**Fallback: Wake Up Snoozed PRs**\n\nCheck both `bot:ci-waiting` and `bot:needs-rebase` PRs for new commits.\n\n**1. Wake up `bot:ci-waiting` PRs:**\n\nFetch all open PRs with `bot:ci-waiting` and check if the author has pushed new commits since the last CI failure comment:\n\n```bash\nWAITING_PRS=$(gh pr list --state open --label \"bot:ci-waiting\" \\\n  --json number,createdAt,author --limit 50)\n```\n\nFor each PR in `WAITING_PRS` (sorted by createdAt ascending, oldest first):\n\n```bash\nPR_NUMBER=\u003Cnumber>\n\nLAST_CI_COMMENT_TIME=$(gh pr view $PR_NUMBER --json comments \\\n  --jq '[.comments[] | select(.body | test(\"\u003C!-- pr-review-bot -->\") and test(\"CI 检查未通过\"))] | last | .createdAt \u002F\u002F \"\"')\n\nLATEST_COMMIT_TIME=$(gh pr view $PR_NUMBER --json commits \\\n  --jq '.commits | last | .committedDate')\n```\n\nIf `LATEST_COMMIT_TIME > LAST_CI_COMMENT_TIME` (author pushed new commits since the CI failure comment):\n\n```bash\ngh pr edit $PR_NUMBER --remove-label \"bot:ci-waiting\" --add-label \"bot:reviewing\"\n```\n\nLog: `[pr-automation] PR #\u003CPR_NUMBER> woke up from ci-waiting: new commits detected. Claiming as target.`\n\nSave this PR as `target_pr` and **continue to Step 4** (treat it as a freshly claimed PR).\n\n**2. Wake up `bot:needs-rebase` PRs:**\n\nIf no `bot:ci-waiting` PR was woken up, check `bot:needs-rebase` PRs:\n\n```bash\nREBASE_PRS=$(gh pr list --state open --label \"bot:needs-rebase\" \\\n  --json number,createdAt,author --limit 50)\n```\n\nFor each PR in `REBASE_PRS` (sorted by createdAt ascending, oldest first):\n\n```bash\nPR_NUMBER=\u003Cnumber>\n\nLAST_CONFLICT_COMMENT_TIME=$(gh pr view $PR_NUMBER --json comments \\\n  --jq '[.comments[] | select(.body | test(\"\u003C!-- pr-review-bot -->\") and test(\"合并冲突\"))] | last | .createdAt \u002F\u002F \"\"')\n\nLATEST_COMMIT_TIME=$(gh pr view $PR_NUMBER --json commits \\\n  --jq '.commits | last | .committedDate')\n```\n\nIf `LATEST_COMMIT_TIME > LAST_CONFLICT_COMMENT_TIME` (author pushed new commits since the conflict comment):\n\n```bash\ngh pr edit $PR_NUMBER --remove-label \"bot:needs-rebase\" --add-label \"bot:reviewing\"\n```\n\nLog: `[pr-automation] PR #\u003CPR_NUMBER> woke up from needs-rebase: new commits detected. Claiming as target.`\n\nSave this PR as `target_pr` and **continue to Step 4** (treat it as a freshly claimed PR).\n\nIf no PRs were woken up: log `[pr-automation] No eligible PR found this round.` then log `[pr-automation:exit] action=no_eligible_pr reason=\"all PRs skipped, no snoozed PRs woken up\"` and EXIT.\n\n### Step 3b — Handle bot:ready-to-fix PR\n\nTaken when selected PR had `bot:ready-to-fix` (CONDITIONAL review already done in a previous session).\n\n**First: check for new commits since the review** (author may have pushed fixes):\n\n```bash\nLAST_REVIEW_TIME=$(gh pr view \u003CPR_NUMBER> --json comments \\\n  --jq '[.comments[] | select(.body | startswith(\"\u003C!-- pr-review-bot -->\"))] | last | .createdAt \u002F\u002F \"\"')\n\nLATEST_COMMIT_TIME=$(gh pr view \u003CPR_NUMBER> --json commits \\\n  --jq '.commits | last | .committedDate')\n```\n\nIf `LATEST_COMMIT_TIME > LAST_REVIEW_TIME` (author pushed new commits since review):\n\n```bash\ngh pr edit \u003CPR_NUMBER> --remove-label \"bot:fixing\"\n```\n\nLog: `[pr-automation] PR #\u003CPR_NUMBER> has new commits since review — re-queuing for fresh review.`\nLog: `[pr-automation:exit] action=requeue pr=#\u003CPR_NUMBER> reason=\"new commits since review\"`\n\n**EXIT.** (PR re-enters normal queue with no bot: label → will be fully re-reviewed next round)\n\nIf no new commits, continue below.\n\n**Re-check CI** (new commits may have been pushed since review):\n\n```bash\ngh pr view \u003CPR_NUMBER> --json statusCheckRollup \\\n  --jq '.statusCheckRollup[] | {name: .name, status: .status, conclusion: .conclusion}'\n```\n\nRequired jobs: `Code Quality`, `Unit Tests (ubuntu-latest)`, `Unit Tests (macos-14)`, `Unit Tests (windows-2022)`, `Coverage Test`, `i18n-check`\n\n| Condition                                                          | Action                                                              |\n| ------------------------------------------------------------------ | ------------------------------------------------------------------- |\n| All required jobs SUCCESS                                          | Continue to pr-fix below                                            |\n| Any job QUEUED or IN_PROGRESS                                      | Remove `bot:fixing` → log \"CI still running for PR #N\" → EXIT       |\n| Any **non-informational** job FAILURE or CANCELLED (excl. codecov) | Remove `bot:fixing` → log \"CI failed for PR #N, re-queueing\" → EXIT |\n\n**Load the existing review report into the current session** (pr-fix requires it to be present):\n\n```bash\ngh pr view \u003CPR_NUMBER> --json comments \\\n  --jq '.comments[] | select(.body | startswith(\"\u003C!-- pr-review-bot -->\")) | .body' \\\n  | tail -1\n```\n\nOutput the fetched review report in the conversation so pr-fix can find it. If no review comment is found, abort:\n\n```bash\ngh pr edit \u003CPR_NUMBER> --remove-label \"bot:fixing\" --add-label \"bot:needs-human-review\"\n```\n\nLog: `[pr-automation] PR #\u003CPR_NUMBER> no review report found — cannot fix. Transferred to human review.`\nLog: `[pr-automation:exit] action=needs_human pr=#\u003CPR_NUMBER> reason=\"no review report found\"`\n\n**EXIT.**\n\n**Run pr-fix:**\n\n```\n\u002Fpr-fix \u003CPR_NUMBER> --automation\n```\n\nAfter pr-fix completes, check if pr-fix already handled everything (fork fallback path):\n\n```bash\nPR_STATE=$(gh pr view \u003CPR_NUMBER> --json state --jq '.state')\n```\n\nIf `PR_STATE` is `CLOSED` (pr-fix used fork fallback — closed the original PR and created a replacement):\n\nLog: `[pr-automation] PR #\u003CPR_NUMBER> fork fallback handled by pr-fix — original closed, replacement PR created.`\nLog: `[pr-automation:exit] action=fork_fallback pr=#\u003CPR_NUMBER> reason=\"pr-fix closed original and created replacement PR\"`\n\n**EXIT.**\n\nOtherwise, post comment and mark ready to merge:\n\n```bash\ngh pr edit \u003CPR_NUMBER> --remove-label \"bot:fixing\" --add-label \"bot:ready-to-merge\"\ngh pr comment \u003CPR_NUMBER> --body \"\u003C!-- pr-automation-bot -->\n✅ 已自动修复，代码无阻塞性问题，请人工确认后合并。\"\n```\n\nLog: `[pr-automation] PR #\u003CPR_NUMBER> fix complete — marked bot:ready-to-merge.`\nLog: `[pr-automation:exit] action=ready_to_merge pr=#\u003CPR_NUMBER> reason=\"fix complete, needs human confirmation to merge\"`\n\n**EXIT.**\n\n### Step 4 — Check CI Status\n\n```bash\ngh pr view \u003CPR_NUMBER> --json statusCheckRollup \\\n  --jq '.statusCheckRollup[] | {name: .name, status: .status, conclusion: .conclusion}'\n```\n\nRequired jobs: `Code Quality`, `Unit Tests (ubuntu-latest)`, `Unit Tests (macos-14)`, `Unit Tests (windows-2022)`, `Coverage Test`, `i18n-check`\n\n| Condition                                                                                | Action                                                                                                                             |\n| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |\n| All required jobs SUCCESS **and** no non-informational jobs FAILURE\u002FCANCELLED            | Continue to Step 4.5                                                                                                               |\n| Any **required** job QUEUED or IN_PROGRESS                                               | Remove `bot:reviewing` → log `[pr-automation:skip] action=ci_running pr=#\u003CPR_NUMBER> reason=\"CI still running\"` → **find next PR** |\n| `statusCheckRollup` empty (CI never triggered)                                           | Approve workflow (see below) → remove `bot:reviewing` → **EXIT**                                                                   |\n| Any **non-informational** job (required or not) FAILURE or CANCELLED (excl. `codecov\u002F*`) | Check dedup (see below) → **find next PR** or post comment → **EXIT**                                                              |\n\n**Workflow approval** (CI never triggered):\n\nUse the PR's head commit SHA to precisely find `action_required` runs for this PR\n(avoids missing fork PRs that `gh run list` may not return in default pagination):\n\n```bash\nHEAD_SHA=$(gh pr view \u003CPR_NUMBER> --json headRefOid --jq '.headRefOid')\nRUN_IDS=$(gh api \"repos\u002F$REPO\u002Factions\u002Fruns?head_sha=$HEAD_SHA&status=action_required\" \\\n  --jq '.workflow_runs[].id')\nfor RUN_ID in $RUN_IDS; do\n  gh run approve \"$RUN_ID\" --repo \"$REPO\"\ndone\n```\n\nLog: `[pr-automation] Approved workflow runs for PR #\u003CPR_NUMBER>.`\nLog: `[pr-automation:exit] action=workflow_approved pr=#\u003CPR_NUMBER> reason=\"CI not triggered, approved workflow runs\"`\n\nRemove `bot:reviewing`:\n\n```bash\ngh pr edit \u003CPR_NUMBER> --remove-label \"bot:reviewing\"\n```\n\n**EXIT.**\n\n**CI failure dedup check:**\n\n```bash\n# Last CI failure bot comment time\nLAST_CI_COMMENT_TIME=$(gh pr view \u003CPR_NUMBER> --json comments \\\n  --jq '[.comments[] | select(.body | test(\"\u003C!-- pr-review-bot -->\") and test(\"CI 检查未通过\"))] | last | .createdAt \u002F\u002F \"\"')\n\n# Latest commit time\nLATEST_COMMIT_TIME=$(gh pr view \u003CPR_NUMBER> --json commits \\\n  --jq '.commits | last | .committedDate')\n```\n\n- If `LAST_CI_COMMENT_TIME` is non-empty AND `LATEST_COMMIT_TIME \u003C= LAST_CI_COMMENT_TIME`:\n  No new commits since last CI failure comment — swap labels and find next PR:\n\n  ```bash\n  gh pr edit \u003CPR_NUMBER> --remove-label \"bot:reviewing\" --add-label \"bot:ci-waiting\"\n  ```\n\n  Log `[pr-automation:skip] action=ci_failure_dedup pr=#\u003CPR_NUMBER> reason=\"CI failed, no new commits since last comment\"` → **find next PR**\n\n- Otherwise: post CI failure comment below → log `[pr-automation:exit] action=ci_failed pr=#\u003CPR_NUMBER> reason=\"CI failure, commented\"` → remove `bot:reviewing` → **EXIT**\n\n**CI failure comment:**\n\n```bash\ngh pr comment \u003CPR_NUMBER> --body \"\u003C!-- pr-review-bot -->\n\n## CI 检查未通过\n\n以下 job 在本次自动化 review 时未通过，请修复：\n\n| Job | 结论 |\n|-----|------|\n| \u003C失败的 job 名称> | ❌ \u003CFAILURE 或 CANCELLED> |\n\n本次自动化 review 暂缓，待 CI 全部通过后将重新处理。\"\n```\n\n### Step 4.5 — Resolve Merge Conflicts\n\n```bash\ngh pr view \u003CPR_NUMBER> --json mergeable,mergeStateStatus,headRefName,baseRefName \\\n  --jq '{mergeable, mergeStateStatus, head: .headRefName, base: .baseRefName}'\n```\n\n| `mergeable`   | `mergeStateStatus` | Action                                                                                                                                                |\n| ------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `MERGEABLE`   | any                | Continue to Step 5                                                                                                                                    |\n| `UNKNOWN`     | any                | Remove `bot:reviewing` → log `[pr-automation:skip] action=merge_unknown pr=#\u003CPR_NUMBER> reason=\"mergeability unknown, will retry\"` → **find next PR** |\n| `CONFLICTING` | any                | Run conflict dedup check (see below)                                                                                                                  |\n\n**Merge conflict dedup check:**\n\n```bash\n# Last conflict bot comment time\nLAST_CONFLICT_COMMENT_TIME=$(gh pr view \u003CPR_NUMBER> --json comments \\\n  --jq '[.comments[] | select(.body | test(\"\u003C!-- pr-review-bot -->\") and test(\"合并冲突\"))] | last | .createdAt \u002F\u002F \"\"')\n\nLATEST_COMMIT_TIME=$(gh pr view \u003CPR_NUMBER> --json commits \\\n  --jq '.commits | last | .committedDate')\n```\n\n- If `LAST_CONFLICT_COMMENT_TIME` is non-empty AND `LATEST_COMMIT_TIME \u003C= LAST_CONFLICT_COMMENT_TIME`:\n  No new commits — remove `bot:reviewing` → log `[pr-automation:skip] action=conflict_dedup pr=#\u003CPR_NUMBER> reason=\"conflict already notified, no new commits\"` → **find next PR** (no new action)\n\n- Otherwise: attempt auto-rebase below.\n\n**Auto-rebase attempt (in worktree):**\n\n```bash\nREPO_ROOT=$(git rev-parse --show-toplevel)\nWORKTREE_DIR=\"\u002Ftmp\u002Faionui-pr-${PR_NUMBER}\"\n\n# Clean up any stale worktree\ngit worktree remove \"$WORKTREE_DIR\" --force 2>\u002Fdev\u002Fnull || true\n\n# Create worktree in detached HEAD mode (no local branch created)\ngit fetch origin \u003Chead_branch>\ngit fetch origin \u003Cbase_branch>\ngit worktree add \"$WORKTREE_DIR\" origin\u002F\u003Chead_branch> --detach\n\n# Symlink node_modules so tsc\u002Flint can run in the worktree\nln -s \"$REPO_ROOT\u002Fnode_modules\" \"$WORKTREE_DIR\u002Fnode_modules\"\n\ncd \"$WORKTREE_DIR\"\ngit rebase origin\u002F\u003Cbase_branch>\n```\n\nIf rebase succeeds, run quality check:\n\n```bash\ncd \"$WORKTREE_DIR\"\nbunx tsc --noEmit\nbun run lint:fix\n```\n\nIf quality check passes:\n\n```bash\ncd \"$WORKTREE_DIR\"\ngit push --force-with-lease origin HEAD:\u003Chead_branch>\ncd \"$REPO_ROOT\"\ngit worktree remove \"$WORKTREE_DIR\" --force 2>\u002Fdev\u002Fnull || true\ngh pr edit \u003CPR_NUMBER> --remove-label \"bot:reviewing\"\n```\n\nLog: `[pr-automation] Resolved merge conflicts for PR #\u003CPR_NUMBER>, pushed rebase.`\n\n**EXIT** (CI re-triggers automatically).\n\n**Fallback** — if rebase fails OR quality check fails:\n\n```bash\ncd \"$REPO_ROOT\"\ngit worktree remove \"$WORKTREE_DIR\" --force 2>\u002Fdev\u002Fnull || true\n```\n\nPost comment:\n\n```bash\ngh pr comment \u003CPR_NUMBER> --body \"\u003C!-- pr-review-bot -->\n\n## 合并冲突（无法自动解决）\n\n本 PR 与目标分支存在冲突，自动 rebase 未能干净解决。请手动 rebase 后重新 push：\n\n\\`\\`\\`bash\ngit fetch origin\ngit rebase origin\u002F\u003Cbase_branch>\n# 解决冲突后\ngit push --force-with-lease\n\\`\\`\\`\"\n```\n\n```bash\ngh pr edit \u003CPR_NUMBER> --remove-label \"bot:reviewing\" --add-label \"bot:needs-rebase\"\n```\n\nLog: `[pr-automation:exit] action=conflict_unresolved pr=#\u003CPR_NUMBER> reason=\"merge conflict, needs human rebase\"`\n\n**EXIT.**\n\n### Step 5 — Assess PR Scale and Critical Path\n\nNo checkout needed — use remote refs to check the diff:\n\n```bash\ngit fetch origin pull\u002F${PR_NUMBER}\u002Fhead\nBASE_REF=$(gh pr view \u003CPR_NUMBER> --json baseRefName --jq '.baseRefName')\ngit fetch origin \"$BASE_REF\"\n\nFILES_CHANGED=$(git diff origin\u002F${BASE_REF}...FETCH_HEAD --name-only | wc -l | tr -d ' ')\n\n# CRITICAL_PATH_PATTERN: defined in Configuration section above\nCRITICAL_FILES=\"\"\nif [ -n \"$CRITICAL_PATH_PATTERN\" ]; then\n  CRITICAL_FILES=$(git diff origin\u002F${BASE_REF}...FETCH_HEAD --name-only \\\n    | grep -E \"$CRITICAL_PATH_PATTERN\")\n  [ -n \"$CRITICAL_FILES\" ] && HAS_CRITICAL=true || HAS_CRITICAL=false\nelse\n  HAS_CRITICAL=false\nfi\n```\n\nSave `FILES_CHANGED`, `HAS_CRITICAL`, and `CRITICAL_FILES` for later steps.\n\n### Step 6 — Run pr-review (automation mode)\n\n**Before running a new review, check if a valid cached review already exists:**\n\n```bash\nLAST_REVIEW_TIME=$(gh pr view \u003CPR_NUMBER> --json comments \\\n  --jq '[.comments[] | select(.body | startswith(\"\u003C!-- pr-review-bot -->\"))] | last | .createdAt \u002F\u002F \"\"')\n\n# Exclude update-branch merge commits — these are automatically generated by GitHub\n# when the PR branch is synced with base (e.g. via the update-branch API), and do\n# not represent new author code changes that would invalidate the cached review.\n# Such commits always have a messageHeadline of the form:\n#   \"Merge branch '\u003Cbase>' into \u003Chead>\"\nBASE_REF=$(gh pr view \u003CPR_NUMBER> --json baseRefName --jq '.baseRefName')\nLATEST_COMMIT_TIME=$(gh pr view \u003CPR_NUMBER> --json commits | \\\n  jq --arg base \"$BASE_REF\" \\\n  '.commits | map(select(.messageHeadline | test(\"^Merge branch '\\''\" + $base + \"'\\'' into \") | not)) | last | .committedDate \u002F\u002F (.commits | last | .committedDate)')\n```\n\nIf `LAST_REVIEW_TIME` is non-empty AND `LATEST_COMMIT_TIME \u003C= LAST_REVIEW_TIME`:\n\nThe existing review is still valid (no new commits since it was posted). Load the cached conclusion from the existing comment:\n\n```bash\ngh pr view \u003CPR_NUMBER> --json comments \\\n  --jq '[.comments[] | select(.body | startswith(\"\u003C!-- pr-review-bot -->\"))] | last | .body'\n```\n\nParse the `\u003C!-- automation-result -->` block from the cached comment. Set `CONCLUSION`, `IS_CRITICAL_PATH`, and `CRITICAL_PATH_FILES` from it, then **skip to Step 7** (do not run pr-review again).\n\nLog: `[pr-automation] PR #\u003CPR_NUMBER> has valid cached review (no new commits since review) — skipping re-review.`\n\nOtherwise (no existing review, or new commits have been pushed since the last review): run a fresh review:\n\n```\n\u002Fpr-review \u003CPR_NUMBER> --automation\n```\n\nAfter pr-review completes, parse the `\u003C!-- automation-result -->` block:\n\n```\n\u003C!-- automation-result -->\nCONCLUSION: APPROVED | CONDITIONAL | REJECTED | CI_FAILED | CI_NOT_READY\nIS_CRITICAL_PATH: true | false\nCRITICAL_PATH_FILES:\n- file1\n- file2\nPR_NUMBER: \u003Cnumber>\n\u003C!-- \u002Fautomation-result -->\n```\n\nWhen `IS_CRITICAL_PATH` is false, `CRITICAL_PATH_FILES` is `(none)`.\n\nSave `CONCLUSION`, `IS_CRITICAL_PATH`, and `CRITICAL_PATH_FILES` (override Step 5 values if different).\n\nIf block is missing: set `CONCLUSION=REJECTED`, log the error, continue to Step 7.\n\n### Step 7 — Execute Decision Matrix\n\n#### CONCLUSION = APPROVED\n\n1. Post comment:\n\n   When `IS_CRITICAL_PATH=true`, include the matched files in the comment:\n\n   ```bash\n   # Build critical path file list for the comment\n   if [ -n \"$CRITICAL_FILES\" ]; then\n     CRITICAL_LIST=$(echo \"$CRITICAL_FILES\" | sed 's\u002F^\u002F   - `\u002F' | sed 's\u002F$\u002F`\u002F')\n     CRITICAL_SECTION=\"\n   > 📂 **命中核心路径的文件：**\n   ${CRITICAL_LIST}\"\n   else\n     CRITICAL_SECTION=\"\"\n   fi\n\n   gh pr comment \u003CPR_NUMBER> --body \"\u003C!-- pr-automation-bot -->\n   ✅ 已自动 review，代码无阻塞性问题，请人工确认后合并。${CRITICAL_SECTION}\"\n   ```\n\n2. Update labels:\n   ```bash\n   gh pr edit \u003CPR_NUMBER> --remove-label \"bot:reviewing\" --add-label \"bot:ready-to-merge\"\n   ```\n3. Log: `[pr-automation] PR #\u003CPR_NUMBER> approved, marked bot:ready-to-merge.`\n4. Log: `[pr-automation:exit] action=ready_to_merge pr=#\u003CPR_NUMBER> reason=\"review passed, needs human confirmation to merge\"`\n5. **EXIT.**\n\n#### CONCLUSION = CONDITIONAL\n\n1. Update labels (defer pr-fix to next session):\n   ```bash\n   gh pr edit \u003CPR_NUMBER> --remove-label \"bot:reviewing\" --add-label \"bot:ready-to-fix\"\n   ```\n2. Log: `[pr-automation] PR #\u003CPR_NUMBER> CONDITIONAL — marked bot:ready-to-fix for next session.`\n3. Log: `[pr-automation:exit] action=conditional pr=#\u003CPR_NUMBER> reason=\"review conditional, deferred fix to next session\"`\n4. **EXIT.**\n\n#### CONCLUSION = REJECTED\n\n1. Post comment:\n   ```bash\n   gh pr comment \u003CPR_NUMBER> --body \"\u003C!-- pr-automation-bot -->\n   ❌ 本 PR 存在阻塞性问题，无法自动处理，已转交人工 review。详见上方 review 报告。\"\n   ```\n2. Update labels:\n   ```bash\n   gh pr edit \u003CPR_NUMBER> --remove-label \"bot:reviewing\" --add-label \"bot:needs-human-review\"\n   ```\n3. Log: `[pr-automation] PR #\u003CPR_NUMBER> rejected, transferred to human review.`\n4. Log: `[pr-automation:exit] action=rejected pr=#\u003CPR_NUMBER> reason=\"blocking issues, transferred to human review\"`\n5. **EXIT.**\n\n#### CONCLUSION = CI_FAILED or CI_NOT_READY\n\nSafety fallback (Step 4 should have caught these):\n\n1. Remove `bot:reviewing`:\n   ```bash\n   gh pr edit \u003CPR_NUMBER> --remove-label \"bot:reviewing\"\n   ```\n2. Log: `[pr-automation] PR #\u003CPR_NUMBER> CI not ready at pr-review stage. Skipping.`\n3. Log: `[pr-automation:exit] action=ci_not_ready pr=#\u003CPR_NUMBER> reason=\"CI not ready at review stage\"`\n4. **EXIT.**\n\n---\n\n## Mandatory Rules\n\n- **Single heavy action per session** — review OR fix, then EXIT\n- **bot:reviewing \u002F bot:fixing are mutexes** — always set immediately when claiming a PR\n- **Clean up on skip** — whenever skipping a PR mid-flow, always remove `bot:reviewing` first\n- **No AI signature** — no `Co-Authored-By`, no `Generated with` in any comment or commit\n- **Label atomicity** — when swapping labels, do both in a single `gh pr edit` call\n- **Comment dedup** — always check for existing bot comment before posting CI failure or conflict comments\n","# PR Automation\n\nOrchestrate the full PR automation lifecycle using a label-based state machine.\nEach invocation performs at most one \"heavy\" action (review or fix), then exits.\nPure skips continue within the same session to find the next eligible PR.\n\n**Announce at start:** \"I'm using pr-automation skill to process PRs.\"\n\n## Usage\n\n```\n\u002Fpr-automation\n```\n\nNo arguments required. The daemon script `scripts\u002Fpr-automation.sh` manages the automation loop.\n\n## Configuration\n\n```\nTRUSTED_CONTRIBUTORS_TEAM: detected from REPO org (e.g. iOfficeAI\u002Ftrusted-contributors)\nCRITICAL_PATH_PATTERN: env var, default in scripts\u002Fpr-automation.conf\nLARGE_PR_FILE_THRESHOLD: env var (default: 50), also in scripts\u002Fpr-automation.conf\nPR_DAYS_LOOKBACK: env var (default: 7), also in scripts\u002Fpr-automation.conf\n```\n\n**REPO** is detected automatically at runtime — do not hardcode it:\n\n```bash\nREPO=$(gh repo view --json nameWithOwner --jq '.nameWithOwner')\nORG=$(echo \"$REPO\" | cut -d'\u002F' -f1)\n```\n\n## Label State Machine\n\n| Label                    | Meaning                                                                 | Terminal? |\n| ------------------------ | ----------------------------------------------------------------------- | --------- |\n| `bot:reviewing`          | Review in progress (mutex)                                              | No        |\n| `bot:ready-to-fix`       | CONDITIONAL review done, waiting for bot to fix next session            | No        |\n| `bot:fixing`             | Fix in progress (mutex)                                                 | No        |\n| `bot:ci-waiting`         | CI failed and author notified — snoozed until author pushes new commits | No        |\n| `bot:needs-rebase`       | Merge conflict that bot cannot auto-resolve — author must rebase        | No        |\n| `bot:needs-human-review` | Blocking issues — human must intervene                                  | Yes       |\n| `bot:ready-to-merge`     | Bot done, code is clean — human just needs to confirm and merge         | Yes       |\n\n## Exit Rules\n\n- **Any substantive action** (approve workflow, post comment, run review, run fix) → EXIT after completing\n- **Pure skip** (WIP, draft, terminal label, CI running, mergeability unknown, `bot:ci-waiting`) → continue to find next PR in same session\n\n---\n\n## Steps\n\n### Step 1 — Fetch Candidate PRs\n\nRead the lookback window from the environment (default 7 days):\n\n```bash\nDAYS=${PR_DAYS_LOOKBACK:-7}\ngh pr list \\\n  --state open \\\n  --search \"created:>=$(date -v-${DAYS}d '+%Y-%m-%d' 2>\u002Fdev\u002Fnull || date -d \"${DAYS} days ago\" '+%Y-%m-%d') -is:draft\" \\\n  --json number,title,labels,createdAt,author \\\n  --limit 50\n```\n\nSave the result as `candidate_prs`.\n\nIf `candidate_prs` is empty: log `[pr-automation] No open PRs found. Exiting.` then log `[pr-automation:exit] action=no_prs reason=\"no open PRs\"` and EXIT.\n\n### Step 2 — Get Trusted Contributors\n\n```bash\ngh api orgs\u002F${ORG}\u002Fteams\u002Ftrusted-contributors\u002Fmembers --jq '[.[].login]'\n```\n\nSave as `trusted_logins`. If API call fails, treat as empty array.\n\n### Step 3 — Select Target PR\n\nSort `candidate_prs` using this **three-key** order:\n\n1. **Primary**: has label `bot:ready-to-fix` → these PRs first\n2. **Secondary**: author.login in `trusted_logins` → trusted PRs next\n3. **Tertiary**: createdAt ascending (oldest first \u002F FIFO)\n\nIterate through sorted list to find the **first eligible PR**.\n\n**Skip conditions** (skip this PR, try next — stay in session):\n\n| Condition                               | Check                                                                       |\n| --------------------------------------- | --------------------------------------------------------------------------- |\n| Title contains `WIP` (case-insensitive) | `title.toLowerCase().includes('wip')`                                       |\n| Has label `bot:needs-rebase`            | check labels array                                                          |\n| Has label `bot:needs-human-review`      | check labels array                                                          |\n| Has label `bot:ready-to-merge`          | check labels array                                                          |\n| Has label `bot:done`                    | check labels array                                                          |\n| Has label `bot:reviewing`               | check labels array                                                          |\n| Has label `bot:fixing`                  | check labels array                                                          |\n| Has label `bot:ci-waiting`              | check labels array — wake-up check runs as fallback if no eligible PR found |\n\n**When eligible PR found:**\n\nFor **fresh PRs** (no bot: label): add `bot:reviewing` to claim it:\n\n```bash\ngh pr edit \u003CPR_NUMBER> --add-label \"bot:reviewing\"\n```\n\nFor **`bot:ready-to-fix` PRs**: swap label atomically:\n\n```bash\ngh pr edit \u003CPR_NUMBER> --remove-label \"bot:ready-to-fix\" --add-label \"bot:fixing\"\n```\n\nSave this PR as `target_pr` (number, title, author.login, is_ready_to_fix).\n\n**If no eligible PR found after full iteration:** run the snoozed PR wake-up checks as a fallback before giving up.\n\n**Fallback: Wake Up Snoozed PRs**\n\nCheck both `bot:ci-waiting` and `bot:needs-rebase` PRs for new commits.\n\n**1. Wake up `bot:ci-waiting` PRs:**\n\nFetch all open PRs with `bot:ci-waiting` and check if the author has pushed new commits since the last CI failure comment:\n\n```bash\nWAITING_PRS=$(gh pr list --state open --label \"bot:ci-waiting\" \\\n  --json number,createdAt,author --limit 50)\n```\n\nFor each PR in `WAITING_PRS` (sorted by createdAt ascending, oldest first):\n\n```bash\nPR_NUMBER=\u003Cnumber>\n\nLAST_CI_COMMENT_TIME=$(gh pr view $PR_NUMBER --json comments \\\n  --jq '[.comments[] | select(.body | test(\"\u003C!-- pr-review-bot -->\") and test(\"CI 检查未通过\"))] | last | .createdAt \u002F\u002F \"\"')\n\nLATEST_COMMIT_TIME=$(gh pr view $PR_NUMBER --json commits \\\n  --jq '.commits | last | .committedDate')\n```\n\nIf `LATEST_COMMIT_TIME > LAST_CI_COMMENT_TIME` (author pushed new commits since the CI failure comment):\n\n```bash\ngh pr edit $PR_NUMBER --remove-label \"bot:ci-waiting\" --add-label \"bot:reviewing\"\n```\n\nLog: `[pr-automation] PR #\u003CPR_NUMBER> woke up from ci-waiting: new commits detected. Claiming as target.`\n\nSave this PR as `target_pr` and **continue to Step 4** (treat it as a freshly claimed PR).\n\n**2. Wake up `bot:needs-rebase` PRs:**\n\nIf no `bot:ci-waiting` PR was woken up, check `bot:needs-rebase` PRs:\n\n```bash\nREBASE_PRS=$(gh pr list --state open --label \"bot:needs-rebase\" \\\n  --json number,createdAt,author --limit 50)\n```\n\nFor each PR in `REBASE_PRS` (sorted by createdAt ascending, oldest first):\n\n```bash\nPR_NUMBER=\u003Cnumber>\n\nLAST_CONFLICT_COMMENT_TIME=$(gh pr view $PR_NUMBER --json comments \\\n  --jq '[.comments[] | select(.body | test(\"\u003C!-- pr-review-bot -->\") and test(\"合并冲突\"))] | last | .createdAt \u002F\u002F \"\"')\n\nLATEST_COMMIT_TIME=$(gh pr view $PR_NUMBER --json commits \\\n  --jq '.commits | last | .committedDate')\n```\n\nIf `LATEST_COMMIT_TIME > LAST_CONFLICT_COMMENT_TIME` (author pushed new commits since the conflict comment):\n\n```bash\ngh pr edit $PR_NUMBER --remove-label \"bot:needs-rebase\" --add-label \"bot:reviewing\"\n```\n\nLog: `[pr-automation] PR #\u003CPR_NUMBER> woke up from needs-rebase: new commits detected. Claiming as target.`\n\nSave this PR as `target_pr` and **continue to Step 4** (treat it as a freshly claimed PR).\n\nIf no PRs were woken up: log `[pr-automation] No eligible PR found this round.` then log `[pr-automation:exit] action=no_eligible_pr reason=\"all PRs skipped, no snoozed PRs woken up\"` and EXIT.\n\n### Step 3b — Handle bot:ready-to-fix PR\n\nTaken when selected PR had `bot:ready-to-fix` (CONDITIONAL review already done in a previous session).\n\n**First: check for new commits since the review** (author may have pushed fixes):\n\n```bash\nLAST_REVIEW_TIME=$(gh pr view \u003CPR_NUMBER> --json comments \\\n  --jq '[.comments[] | select(.body | startswith(\"\u003C!-- pr-review-bot -->\"))] | last | .createdAt \u002F\u002F \"\"')\n\nLATEST_COMMIT_TIME=$(gh pr view \u003CPR_NUMBER> --json commits \\\n  --jq '.commits | last | .committedDate')\n```\n\nIf `LATEST_COMMIT_TIME > LAST_REVIEW_TIME` (author pushed new commits since review):\n\n```bash\ngh pr edit \u003CPR_NUMBER> --remove-label \"bot:fixing\"\n```\n\nLog: `[pr-automation] PR #\u003CPR_NUMBER> has new commits since review — re-queuing for fresh review.`\nLog: `[pr-automation:exit] action=requeue pr=#\u003CPR_NUMBER> reason=\"new commits since review\"`\n\n**EXIT.** (PR re-enters normal queue with no bot: label → will be fully re-reviewed next round)\n\nIf no new commits, continue below.\n\n**Re-check CI** (new commits may have been pushed since review):\n\n```bash\ngh pr view \u003CPR_NUMBER> --json statusCheckRollup \\\n  --jq '.statusCheckRollup[] | {name: .name, status: .status, conclusion: .conclusion}'\n```\n\nRequired jobs: `Code Quality`, `Unit Tests (ubuntu-latest)`, `Unit Tests (macos-14)`, `Unit Tests (windows-2022)`, `Coverage Test`, `i18n-check`\n\n| Condition                                                          | Action                                                              |\n| ------------------------------------------------------------------ | ------------------------------------------------------------------- |\n| All required jobs SUCCESS                                          | Continue to pr-fix below                                            |\n| Any job QUEUED or IN_PROGRESS                                      | Remove `bot:fixing` → log \"CI still running for PR #N\" → EXIT       |\n| Any **non-informational** job FAILURE or CANCELLED (excl. codecov) | Remove `bot:fixing` → log \"CI failed for PR #N, re-queueing\" → EXIT |\n\n**Load the existing review report into the current session** (pr-fix requires it to be present):\n\n```bash\ngh pr view \u003CPR_NUMBER> --json comments \\\n  --jq '.comments[] | select(.body | startswith(\"\u003C!-- pr-review-bot -->\")) | .body' \\\n  | tail -1\n```\n\nOutput the fetched review report in the conversation so pr-fix can find it. If no review comment is found, abort:\n\n```bash\ngh pr edit \u003CPR_NUMBER> --remove-label \"bot:fixing\" --add-label \"bot:needs-human-review\"\n```\n\nLog: `[pr-automation] PR #\u003CPR_NUMBER> no review report found — cannot fix. Transferred to human review.`\nLog: `[pr-automation:exit] action=needs_human pr=#\u003CPR_NUMBER> reason=\"no review report found\"`\n\n**EXIT.**\n\n**Run pr-fix:**\n\n```\n\u002Fpr-fix \u003CPR_NUMBER> --automation\n```\n\nAfter pr-fix completes, check if pr-fix already handled everything (fork fallback path):\n\n```bash\nPR_STATE=$(gh pr view \u003CPR_NUMBER> --json state --jq '.state')\n```\n\nIf `PR_STATE` is `CLOSED` (pr-fix used fork fallback — closed the original PR and created a replacement):\n\nLog: `[pr-automation] PR #\u003CPR_NUMBER> fork fallback handled by pr-fix — original closed, replacement PR created.`\nLog: `[pr-automation:exit] action=fork_fallback pr=#\u003CPR_NUMBER> reason=\"pr-fix closed original and created replacement PR\"`\n\n**EXIT.**\n\nOtherwise, post comment and mark ready to merge:\n\n```bash\ngh pr edit \u003CPR_NUMBER> --remove-label \"bot:fixing\" --add-label \"bot:ready-to-merge\"\ngh pr comment \u003CPR_NUMBER> --body \"\u003C!-- pr-automation-bot -->\n✅ 已自动修复，代码无阻塞性问题，请人工确认后合并。\"\n```\n\nLog: `[pr-automation] PR #\u003CPR_NUMBER> fix complete — marked bot:ready-to-merge.`\nLog: `[pr-automation:exit] action=ready_to_merge pr=#\u003CPR_NUMBER> reason=\"fix complete, needs human confirmation to merge\"`\n\n**EXIT.**\n\n### Step 4 — Check CI Status\n\n```bash\ngh pr view \u003CPR_NUMBER> --json statusCheckRollup \\\n  --jq '.statusCheckRollup[] | {name: .name, status: .status, conclusion: .conclusion}'\n```\n\nRequired jobs: `Code Quality`, `Unit Tests (ubuntu-latest)`, `Unit Tests (macos-14)`, `Unit Tests (windows-2022)`, `Coverage Test`, `i18n-check`\n\n| Condition                                                                                | Action                                                                                                                             |\n| ---------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |\n| All required jobs SUCCESS **and** no non-informational jobs FAILURE\u002FCANCELLED            | Continue to Step 4.5                                                                                                               |\n| Any **required** job QUEUED or IN_PROGRESS                                               | Remove `bot:reviewing` → log `[pr-automation:skip] action=ci_running pr=#\u003CPR_NUMBER> reason=\"CI still running\"` → **find next PR** |\n| `statusCheckRollup` empty (CI never triggered)                                           | Approve workflow (see below) → remove `bot:reviewing` → **EXIT**                                                                   |\n| Any **non-informational** job (required or not) FAILURE or CANCELLED (excl. `codecov\u002F*`) | Check dedup (see below) → **find next PR** or post comment → **EXIT**                                                              |\n\n**Workflow approval** (CI never triggered):\n\nUse the PR's head commit SHA to precisely find `action_required` runs for this PR\n(avoids missing fork PRs that `gh run list` may not return in default pagination):\n\n```bash\nHEAD_SHA=$(gh pr view \u003CPR_NUMBER> --json headRefOid --jq '.headRefOid')\nRUN_IDS=$(gh api \"repos\u002F$REPO\u002Factions\u002Fruns?head_sha=$HEAD_SHA&status=action_required\" \\\n  --jq '.workflow_runs[].id')\nfor RUN_ID in $RUN_IDS; do\n  gh run approve \"$RUN_ID\" --repo \"$REPO\"\ndone\n```\n\nLog: `[pr-automation] Approved workflow runs for PR #\u003CPR_NUMBER>.`\nLog: `[pr-automation:exit] action=workflow_approved pr=#\u003CPR_NUMBER> reason=\"CI not triggered, approved workflow runs\"`\n\nRemove `bot:reviewing`:\n\n```bash\ngh pr edit \u003CPR_NUMBER> --remove-label \"bot:reviewing\"\n```\n\n**EXIT.**\n\n**CI failure dedup check:**\n\n```bash\n# Last CI failure bot comment time\nLAST_CI_COMMENT_TIME=$(gh pr view \u003CPR_NUMBER> --json comments \\\n  --jq '[.comments[] | select(.body | test(\"\u003C!-- pr-review-bot -->\") and test(\"CI 检查未通过\"))] | last | .createdAt \u002F\u002F \"\"')\n\n# Latest commit time\nLATEST_COMMIT_TIME=$(gh pr view \u003CPR_NUMBER> --json commits \\\n  --jq '.commits | last | .committedDate')\n```\n\n- If `LAST_CI_COMMENT_TIME` is non-empty AND `LATEST_COMMIT_TIME \u003C= LAST_CI_COMMENT_TIME`:\n  No new commits since last CI failure comment — swap labels and find next PR:\n\n  ```bash\n  gh pr edit \u003CPR_NUMBER> --remove-label \"bot:reviewing\" --add-label \"bot:ci-waiting\"\n  ```\n\n  Log `[pr-automation:skip] action=ci_failure_dedup pr=#\u003CPR_NUMBER> reason=\"CI failed, no new commits since last comment\"` → **find next PR**\n\n- Otherwise: post CI failure comment below → log `[pr-automation:exit] action=ci_failed pr=#\u003CPR_NUMBER> reason=\"CI failure, commented\"` → remove `bot:reviewing` → **EXIT**\n\n**CI failure comment:**\n\n```bash\ngh pr comment \u003CPR_NUMBER> --body \"\u003C!-- pr-review-bot -->\n\n## CI 检查未通过\n\n以下 job 在本次自动化 review 时未通过，请修复：\n\n| Job | 结论 |\n|-----|------|\n| \u003C失败的 job 名称> | ❌ \u003CFAILURE 或 CANCELLED> |\n\n本次自动化 review 暂缓，待 CI 全部通过后将重新处理。\"\n```\n\n### Step 4.5 — Resolve Merge Conflicts\n\n```bash\ngh pr view \u003CPR_NUMBER> --json mergeable,mergeStateStatus,headRefName,baseRefName \\\n  --jq '{mergeable, mergeStateStatus, head: .headRefName, base: .baseRefName}'\n```\n\n| `mergeable`   | `mergeStateStatus` | Action                                                                                                                                                |\n| ------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `MERGEABLE`   | any                | Continue to Step 5                                                                                                                                    |\n| `UNKNOWN`     | any                | Remove `bot:reviewing` → log `[pr-automation:skip] action=merge_unknown pr=#\u003CPR_NUMBER> reason=\"mergeability unknown, will retry\"` → **find next PR** |\n| `CONFLICTING` | any                | Run conflict dedup check (see below)                                                                                                                  |\n\n**Merge conflict dedup check:**\n\n```bash\n# Last conflict bot comment time\nLAST_CONFLICT_COMMENT_TIME=$(gh pr view \u003CPR_NUMBER> --json comments \\\n  --jq '[.comments[] | select(.body | test(\"\u003C!-- pr-review-bot -->\") and test(\"合并冲突\"))] | last | .createdAt \u002F\u002F \"\"')\n\nLATEST_COMMIT_TIME=$(gh pr view \u003CPR_NUMBER> --json commits \\\n  --jq '.commits | last | .committedDate')\n```\n\n- If `LAST_CONFLICT_COMMENT_TIME` is non-empty AND `LATEST_COMMIT_TIME \u003C= LAST_CONFLICT_COMMENT_TIME`:\n  No new commits — remove `bot:reviewing` → log `[pr-automation:skip] action=conflict_dedup pr=#\u003CPR_NUMBER> reason=\"conflict already notified, no new commits\"` → **find next PR** (no new action)\n\n- Otherwise: attempt auto-rebase below.\n\n**Auto-rebase attempt (in worktree):**\n\n```bash\nREPO_ROOT=$(git rev-parse --show-toplevel)\nWORKTREE_DIR=\"\u002Ftmp\u002Faionui-pr-${PR_NUMBER}\"\n\n# Clean up any stale worktree\ngit worktree remove \"$WORKTREE_DIR\" --force 2>\u002Fdev\u002Fnull || true\n\n# Create worktree in detached HEAD mode (no local branch created)\ngit fetch origin \u003Chead_branch>\ngit fetch origin \u003Cbase_branch>\ngit worktree add \"$WORKTREE_DIR\" origin\u002F\u003Chead_branch> --detach\n\n# Symlink node_modules so tsc\u002Flint can run in the worktree\nln -s \"$REPO_ROOT\u002Fnode_modules\" \"$WORKTREE_DIR\u002Fnode_modules\"\n\ncd \"$WORKTREE_DIR\"\ngit rebase origin\u002F\u003Cbase_branch>\n```\n\nIf rebase succeeds, run quality check:\n\n```bash\ncd \"$WORKTREE_DIR\"\nbunx tsc --noEmit\nbun run lint:fix\n```\n\nIf quality check passes:\n\n```bash\ncd \"$WORKTREE_DIR\"\ngit push --force-with-lease origin HEAD:\u003Chead_branch>\ncd \"$REPO_ROOT\"\ngit worktree remove \"$WORKTREE_DIR\" --force 2>\u002Fdev\u002Fnull || true\ngh pr edit \u003CPR_NUMBER> --remove-label \"bot:reviewing\"\n```\n\nLog: `[pr-automation] Resolved merge conflicts for PR #\u003CPR_NUMBER>, pushed rebase.`\n\n**EXIT** (CI re-triggers automatically).\n\n**Fallback** — if rebase fails OR quality check fails:\n\n```bash\ncd \"$REPO_ROOT\"\ngit worktree remove \"$WORKTREE_DIR\" --force 2>\u002Fdev\u002Fnull || true\n```\n\nPost comment:\n\n```bash\ngh pr comment \u003CPR_NUMBER> --body \"\u003C!-- pr-review-bot -->\n\n## 合并冲突（无法自动解决）\n\n本 PR 与目标分支存在冲突，自动 rebase 未能干净解决。请手动 rebase 后重新 push：\n\n\\`\\`\\`bash\ngit fetch origin\ngit rebase origin\u002F\u003Cbase_branch>\n# 解决冲突后\ngit push --force-with-lease\n\\`\\`\\`\"\n```\n\n```bash\ngh pr edit \u003CPR_NUMBER> --remove-label \"bot:reviewing\" --add-label \"bot:needs-rebase\"\n```\n\nLog: `[pr-automation:exit] action=conflict_unresolved pr=#\u003CPR_NUMBER> reason=\"merge conflict, needs human rebase\"`\n\n**EXIT.**\n\n### Step 5 — Assess PR Scale and Critical Path\n\nNo checkout needed — use remote refs to check the diff:\n\n```bash\ngit fetch origin pull\u002F${PR_NUMBER}\u002Fhead\nBASE_REF=$(gh pr view \u003CPR_NUMBER> --json baseRefName --jq '.baseRefName')\ngit fetch origin \"$BASE_REF\"\n\nFILES_CHANGED=$(git diff origin\u002F${BASE_REF}...FETCH_HEAD --name-only | wc -l | tr -d ' ')\n\n# CRITICAL_PATH_PATTERN: defined in Configuration section above\nCRITICAL_FILES=\"\"\nif [ -n \"$CRITICAL_PATH_PATTERN\" ]; then\n  CRITICAL_FILES=$(git diff origin\u002F${BASE_REF}...FETCH_HEAD --name-only \\\n    | grep -E \"$CRITICAL_PATH_PATTERN\")\n  [ -n \"$CRITICAL_FILES\" ] && HAS_CRITICAL=true || HAS_CRITICAL=false\nelse\n  HAS_CRITICAL=false\nfi\n```\n\nSave `FILES_CHANGED`, `HAS_CRITICAL`, and `CRITICAL_FILES` for later steps.\n\n### Step 6 — Run pr-review (automation mode)\n\n**Before running a new review, check if a valid cached review already exists:**\n\n```bash\nLAST_REVIEW_TIME=$(gh pr view \u003CPR_NUMBER> --json comments \\\n  --jq '[.comments[] | select(.body | startswith(\"\u003C!-- pr-review-bot -->\"))] | last | .createdAt \u002F\u002F \"\"')\n\n# Exclude update-branch merge commits — these are automatically generated by GitHub\n# when the PR branch is synced with base (e.g. via the update-branch API), and do\n# not represent new author code changes that would invalidate the cached review.\n# Such commits always have a messageHeadline of the form:\n#   \"Merge branch '\u003Cbase>' into \u003Chead>\"\nBASE_REF=$(gh pr view \u003CPR_NUMBER> --json baseRefName --jq '.baseRefName')\nLATEST_COMMIT_TIME=$(gh pr view \u003CPR_NUMBER> --json commits | \\\n  jq --arg base \"$BASE_REF\" \\\n  '.commits | map(select(.messageHeadline | test(\"^Merge branch '\\''\" + $base + \"'\\'' into \") | not)) | last | .committedDate \u002F\u002F (.commits | last | .committedDate)')\n```\n\nIf `LAST_REVIEW_TIME` is non-empty AND `LATEST_COMMIT_TIME \u003C= LAST_REVIEW_TIME`:\n\nThe existing review is still valid (no new commits since it was posted). Load the cached conclusion from the existing comment:\n\n```bash\ngh pr view \u003CPR_NUMBER> --json comments \\\n  --jq '[.comments[] | select(.body | startswith(\"\u003C!-- pr-review-bot -->\"))] | last | .body'\n```\n\nParse the `\u003C!-- automation-result -->` block from the cached comment. Set `CONCLUSION`, `IS_CRITICAL_PATH`, and `CRITICAL_PATH_FILES` from it, then **skip to Step 7** (do not run pr-review again).\n\nLog: `[pr-automation] PR #\u003CPR_NUMBER> has valid cached review (no new commits since review) — skipping re-review.`\n\nOtherwise (no existing review, or new commits have been pushed since the last review): run a fresh review:\n\n```\n\u002Fpr-review \u003CPR_NUMBER> --automation\n```\n\nAfter pr-review completes, parse the `\u003C!-- automation-result -->` block:\n\n```\n\u003C!-- automation-result -->\nCONCLUSION: APPROVED | CONDITIONAL | REJECTED | CI_FAILED | CI_NOT_READY\nIS_CRITICAL_PATH: true | false\nCRITICAL_PATH_FILES:\n- file1\n- file2\nPR_NUMBER: \u003Cnumber>\n\u003C!-- \u002Fautomation-result -->\n```\n\nWhen `IS_CRITICAL_PATH` is false, `CRITICAL_PATH_FILES` is `(none)`.\n\nSave `CONCLUSION`, `IS_CRITICAL_PATH`, and `CRITICAL_PATH_FILES` (override Step 5 values if different).\n\nIf block is missing: set `CONCLUSION=REJECTED`, log the error, continue to Step 7.\n\n### Step 7 — Execute Decision Matrix\n\n#### CONCLUSION = APPROVED\n\n1. Post comment:\n\n   When `IS_CRITICAL_PATH=true`, include the matched files in the comment:\n\n   ```bash\n   # Build critical path file list for the comment\n   if [ -n \"$CRITICAL_FILES\" ]; then\n     CRITICAL_LIST=$(echo \"$CRITICAL_FILES\" | sed 's\u002F^\u002F   - `\u002F' | sed 's\u002F$\u002F`\u002F')\n     CRITICAL_SECTION=\"\n   > 📂 **命中核心路径的文件：**\n   ${CRITICAL_LIST}\"\n   else\n     CRITICAL_SECTION=\"\"\n   fi\n\n   gh pr comment \u003CPR_NUMBER> --body \"\u003C!-- pr-automation-bot -->\n   ✅ 已自动 review，代码无阻塞性问题，请人工确认后合并。${CRITICAL_SECTION}\"\n   ```\n\n2. Update labels:\n   ```bash\n   gh pr edit \u003CPR_NUMBER> --remove-label \"bot:reviewing\" --add-label \"bot:ready-to-merge\"\n   ```\n3. Log: `[pr-automation] PR #\u003CPR_NUMBER> approved, marked bot:ready-to-merge.`\n4. Log: `[pr-automation:exit] action=ready_to_merge pr=#\u003CPR_NUMBER> reason=\"review passed, needs human confirmation to merge\"`\n5. **EXIT.**\n\n#### CONCLUSION = CONDITIONAL\n\n1. Update labels (defer pr-fix to next session):\n   ```bash\n   gh pr edit \u003CPR_NUMBER> --remove-label \"bot:reviewing\" --add-label \"bot:ready-to-fix\"\n   ```\n2. Log: `[pr-automation] PR #\u003CPR_NUMBER> CONDITIONAL — marked bot:ready-to-fix for next session.`\n3. Log: `[pr-automation:exit] action=conditional pr=#\u003CPR_NUMBER> reason=\"review conditional, deferred fix to next session\"`\n4. **EXIT.**\n\n#### CONCLUSION = REJECTED\n\n1. Post comment:\n   ```bash\n   gh pr comment \u003CPR_NUMBER> --body \"\u003C!-- pr-automation-bot -->\n   ❌ 本 PR 存在阻塞性问题，无法自动处理，已转交人工 review。详见上方 review 报告。\"\n   ```\n2. Update labels:\n   ```bash\n   gh pr edit \u003CPR_NUMBER> --remove-label \"bot:reviewing\" --add-label \"bot:needs-human-review\"\n   ```\n3. Log: `[pr-automation] PR #\u003CPR_NUMBER> rejected, transferred to human review.`\n4. Log: `[pr-automation:exit] action=rejected pr=#\u003CPR_NUMBER> reason=\"blocking issues, transferred to human review\"`\n5. **EXIT.**\n\n#### CONCLUSION = CI_FAILED or CI_NOT_READY\n\nSafety fallback (Step 4 should have caught these):\n\n1. Remove `bot:reviewing`:\n   ```bash\n   gh pr edit \u003CPR_NUMBER> --remove-label \"bot:reviewing\"\n   ```\n2. Log: `[pr-automation] PR #\u003CPR_NUMBER> CI not ready at pr-review stage. Skipping.`\n3. Log: `[pr-automation:exit] action=ci_not_ready pr=#\u003CPR_NUMBER> reason=\"CI not ready at review stage\"`\n4. **EXIT.**\n\n---\n\n## Mandatory Rules\n\n- **Single heavy action per session** — review OR fix, then EXIT\n- **bot:reviewing \u002F bot:fixing are mutexes** — always set immediately when claiming a PR\n- **Clean up on skip** — whenever skipping a PR mid-flow, always remove `bot:reviewing` first\n- **No AI signature** — no `Co-Authored-By`, no `Generated with` in any comment or commit\n- **Label atomicity** — when swapping labels, do both in a single `gh pr edit` call\n- **Comment dedup** — always check for existing bot comment before posting CI failure or conflict comments\n",{"name":5,"description":7},"main","e2ebc32375170a908421314e4490503fd6ae4b1b",".claude\u002Fskills\u002Fpr-automation",0,"https:\u002F\u002Fgithub.com\u002Foliverhees\u002FLokkyWork","https:\u002F\u002Fgithub.com\u002Foliverhees","https:\u002F\u002Fai-automation-engineers.com","Full Stack Software Developer Next.js and AI Prompt Engineer, AI Specialist \r\n","2026-06-23 22:14:58",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add oliverhees\u002FLokkyWork --skill pr-automation",{"tool":39,"command":40},"bunx","bunx skills add oliverhees\u002FLokkyWork --skill pr-automation",{"tool":42,"command":43},"pnpm","pnpm dlx skills add oliverhees\u002FLokkyWork --skill pr-automation","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Foliverhees\u002FLokkyWork\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fpr-automation\u002FSKILL.md",true,[],[48,55,62,69,76,83],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":19},"01M75XB5PNZR82QSYY87JRZSMT","testing","Testing workflow and quality standards for writing and running tests.\nUse when: (1) Writing new tests, (2) Adding a new feature that needs tests,\n(3) Modifying logic that has existing tests, (4) Before claiming a task is complete.","https:\u002F\u002Fgithub.com\u002Foliverhees\u002FLokkyWork\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Ftesting\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":19},"01M75XB2QRHG1J01988QW8XRP0","pr-verify","PR Verification & Merge: verify bot:ready-to-merge PRs with impact analysis, test supplementation, and one-click merge.\nUse when: (1) User says \"\u002Fpr-verify\", (2) User wants to verify and merge ready PRs.","https:\u002F\u002Fgithub.com\u002Foliverhees\u002FLokkyWork\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fpr-verify\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M75XAZW775V4YAZ41X965GMF","pr-ship","End-to-end PR lifecycle: create PR, wait for CI, review, fix issues, merge — all in one invocation.\nUse when: (1) User says \"\u002Fpr-ship\", (2) User wants to ship current changes as a complete PR lifecycle,\n(3) User wants to resume shepherding an existing PR.","https:\u002F\u002Fgithub.com\u002Foliverhees\u002FLokkyWork\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fpr-ship\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M75XAW7H1EBB5Q7T90TRPCT9","pr-review","PR Code Review (Local): perform a thorough local code review with full project context.\nUse when: (1) User asks to review a PR, (2) User says \"\u002Fpr-review\", (3) User wants to review code changes before merging.","https:\u002F\u002Fgithub.com\u002Foliverhees\u002FLokkyWork\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fpr-review\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M75XAR8Z8A5SXYKGRTQ6VPY7","pr-fix","PR Review Fix: automatically fix all issues identified in a pr-review report.\nUse when: (1) User says \"fix all review issues\", (2) User says \"\u002Fpr-fix\",\n(3) After pr-review skill has produced a report, (4) User wants to address PR review feedback.","https:\u002F\u002Fgithub.com\u002Foliverhees\u002FLokkyWork\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fpr-fix\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M75XAH05WQQE6FBDAH4J0RQG","oss-pr","Use when creating a pull request, after committing changes, or when user invokes \u002Foss-pr. Covers branch management, quality checks, commit, push, and PR creation.","https:\u002F\u002Fgithub.com\u002Foliverhees\u002FLokkyWork\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Foss-pr\u002FSKILL.md",[],[]]