CI 队列任务清理
ci-queue-trim
审计并清理队列中 head SHA 已被证实过时的 GitHub Actions CI 工作流运行。PR 关联来自 `actions/runs/{id}.pull_requests`(唯一权威指针);在 fork 之间重名的分支不得将运行交叉绑定到某个 PR。事件语义区分 pull_request 与 pull_request_target(后者使用 base 侧 SHA,因此 tip 前进不是被取代的信号),而 merge_group / 未知事件跳过通用的 stale-head 比较。在每次 `gh run cancel` 前逐项重新验证,以捕捉并发状态变更。工作流的重要性由显式配置的允许列表决定(默认为空),绝不采用模糊的子串启发式判断。
- License 许可
- MIT
- 最近更新
- 2026-11-14
- Stars
- ★ 6
- Forks
- 0
01 前言 Front Matter
- name
- ci-queue-trim
- type
- skill
- owner
- $USER
- scope
- global
- version
- 1.2.0
- triggers
- [ "ci queue trim", "trim ci queue", "cancel dormant ci runs", "clean up ci queue", "trim queued jobs", "ci backlog cleanup", "pr inactivity trim" ]
- description
- Audit and trim queued GitHub Actions CI workflow runs whose head SHA is proven obsolete. PR association comes from `actions/runs/{id}.pull_requests` (the only authoritative pointer); branch names that collide between forks MUST NOT cross-bind runs to a PR. Event semantics split pull_request from pull_request_target (the latter uses base-side SHA, so a tip advance is NOT a supersede signal) and merge_group / unknown events skip the generic stale-head comparison. Per-item re-validation right before each `gh run cancel` catches concurrent state advances. Workflow importance is decided by an explicit configured allowlist (empty by default), never by fuzzy substring heuristics.
- allowed-tools
- [ "Bash", "Read", "Write" ]
02 资源文件 2
- 脚本scripts/ci_queue_trim.py38.4 KB
- 脚本tests/test_ci_queue_trim.py70.6 KB
03 SKILL.md 正文
/ci-queue-trim — CI Queue Inactivity Triage & Trimming
Use this skill when GitHub Actions self-hosted or cloud runner queues become backlogged with queued runs whose head SHA is no longer current. PR closure and commit age alone never authorize cancellation.
The Pitfalls Resolved at Audit Time
1. Deceptive PR.updatedAt (bots touch it constantly)
When filtering PRs by activity, PR.updatedAt is fundamentally deceptive:
- Automated bots (merge queues, label synchronizers, automated status
comments, rebase checks) constantly touch
updatedAt. - A PR whose code has not been touched in 10–30 days frequently shows
updatedAtof "2 minutes ago". - The script uses the immutable head-commit committer timestamp as
the reporting source — fetched from
GET repos/{head.repo.full_name}/commits/{head.sha}viacommit.committer.date. NEVER substituted withpushed_at,updated_at, or run age. PR.updated_atis reported separately for operator visibility only (thepr_updated_agefield); it is NOT used for cancellation decisions.--max-age-hourslabels matching-head commit age in the report only. Exceeding it never authorizes cancellation. If commit age is unknown, matching-head runs are KEEP incomplete; proven obsolete heads do not require a timestamp.
2. Superseded runs (run.head_sha ≠ PR/branch current head)
A run can be queued against an older SHA even though the PR has since
advanced. The script compares run.head_sha against the current head SHA
to detect this without false-positive dormancy cancellations.
PR.head.shais the head branch tip SHA — NOT the merge ref.merge_commit_shais a separate field and must NOT be used for supersede comparison.- For
pull_requestevents: comparison ref isPR.head.sha. - For
pull_request_target: base-side semantics. The run'shead_shais the BASE branch SHA, not the PR head SHA. Tip advances on the PR are NOT proven supersede — always keep, including MERGED/CLOSED PRs. - For
pushevents: always KEEP withaudit_incomplete=True. The run record does not prove the original branch/tag namespace. Current tag absence cannot exclude a deleted tag; same-name branch/tag collisions are ambiguous. No branch or tag lookup authorizes cancellation. - For
merge_groupand any unsupported event: never apply the generic stale-head comparison.
3. Lookup failure (PR / commit / run detail unknown)
If the audit cannot verify the PR or run detail, the run is
kept with audit_incomplete=True. A missing head-commit date marks
matching-head age reporting incomplete; it does not block proven
supersession. Run age never substitutes for head-commit age.
A failed gh run list (queue fetch) is propagated as
stats["queue_fetch_failed"]=True, NOT silently turned into a healthy
empty success. The CLI exits nonzero on queue fetch failure.
4. PR association — branch names that collide between forks
Branch-name lookup is never used to bind a run to a PR. The script
reads actions/runs/{id}.pull_requests (the only authoritative pointer).
Two forks pushing a branch named feature/x will not cross-bind the run
to the wrong PR.
- The audit requires exactly one PR association (0 or >1 ⇒ UNKNOWN,
audit_incomplete=True). There is no "pick the first" fallback. - Identity between the run's PR pointer and the fetched
pulls/{n}record is verified by the stable numericrepo.id. The live shape ofactions/runs/{id}.pull_requests[].head.repois{id, name, url}(nofull_name); requiringfull_namewould mark every real run unknown. Thepulls/{n}.head.reporecord carries{id, full_name, name, ...}— match byid. - Absent or mismatched
repo.id⇒ UNKNOWN. The association base repo ID, run repository ID, and fetched PR base repo ID must all be present and equal. PR number plus base repository identifies the PR; head ref is not used as an alternative identity. Historical association head SHA may differ from the current tip and is not required to equal it.
5. Per-item refresh before cancellation
Before every individual gh run cancel, the script re-fetches the run
record and the exact PR for PR events, re-runs the
same pure classifier the audit used, and only cancels if the verdict
is still CANCEL. If state moved on between audit time and mutation
time, the candidate is dropped.
Both audit and refresh use the same run-response validation:
- Run IDs, PR numbers, and repository IDs must be positive JSON integers; strings, booleans, floats, zero, and negative values are rejected.
data.idMUST equal the requestedrun_id(mismatched id ⇒ drop, even if the rest looks valid).head_sha,head_branch,event,path, andstatusmust be nonempty strings;statusmust bequeuedbefore mutation.repositorymust contain a nonemptyidandfull_name;full_namemust equal the requestedOWNER/REPO. Missing or mismatched identity keeps the audit row incomplete and prevents cancellation.- PR runs require exactly one structurally valid raw
pull_requestsassociation before normalization (malformed entries are never dropped), with matching PR number and numerichead.repo.id, plus equal association/run/fetched-PR base repository IDs. Incomplete identity or lookups keep the run. Push events remain ambiguous and are never cancellation candidates.
Every mode requires superseded=True before cancellation. Neither old
commits nor MERGED/CLOSED state authorizes cancellation of current-head
work, which may include legitimate cleanup or deployment after closure.
The same classifier is reused at mutation time.
Protected Branches and Workflows
- Protected branches (never cancelled automatically):
main,master,production,staging,release,deploy. - Workflow cancellation is opted-in via
--allow-workflow PATH(repeatable). The default is an empty allowlist, which keeps every workflow — i.e. no workflow is cancellable out of the box. Operators must explicitly enumerate the exact normalized workflow paths they consider safe to cancel. - Workflow protection is opt-in via
--protect-workflow PATH(repeatable).--allow-workflowenables cancellation;--protect-workflowprotects even if the same path is in--allow-workflow. The two flags are independent. - The
@<ref>suffix on a workflow path (e.g.release.yml@refs/heads/feature/x,deploy.yml@v2) is stripped before matching viapartition('@')[0]— refs containing slashes are preserved. - Reusable workflows invoked via
workflow_callare protected by event semantics, not by fuzzy name matching.
Tooling & Command Syntax
The skill includes a pre-built, standalone Python helper. Resolve the skill root via the standard Claude home convention and substitute in the commands below:
"${CLAUDE_HOME:-$HOME/.claude}/skills/ci-queue-trim/scripts/ci_queue_trim.py"
This resolves the helper under the active Claude home on both Linux and macOS.
1. Dry-Run Audit (Default)
Inspects the queue, classifies each run via the pure classifier, and
prints cancel candidates without cancelling anything. Explicit --dry-run
also overrides --cancel if both flags are supplied:
python3 ~/.claude/skills/ci-queue-trim/scripts/ci_queue_trim.py
2. Execute Cancellations
Each candidate is re-fetched and re-classified immediately before its
gh run cancel call:
python3 ~/.claude/skills/ci-queue-trim/scripts/ci_queue_trim.py \
--allow-workflow .github/workflows/ci.yml --cancel
3. Superseded-Only Compatibility Flag
--superseded-only remains accepted for existing callers. The default now
has the same cancellation rule: only proven obsolete heads are eligible.
Matching heads remain queued regardless of PR state or commit age.
pull_request_target runs are always kept because their SHA is base-side.
python3 ~/.claude/skills/ci-queue-trim/scripts/ci_queue_trim.py \
--allow-workflow .github/workflows/ci.yml --superseded-only --cancel
4. Enable Cancellation for Specific Workflows
--allow-workflow PATH (repeatable) opts a workflow INTO cancellation.
Default is empty (no workflow cancellable). Use --protect-workflow PATH
to also keep a path safe even if it was added to the allowlist.
python3 ~/.claude/skills/ci-queue-trim/scripts/ci_queue_trim.py \
--allow-workflow .github/workflows/ci.yml \
--allow-workflow .github/workflows/lint.yml@v2 \
--protect-workflow .github/workflows/ci.yml \
--cancel
5. Customize Report Age Threshold and Target Repo
The age threshold affects reporting only; cancellation still requires proven
supersession and an explicitly allowed workflow. Without --repo, the target is
$GITHUB_REPOSITORY, else the repository gh repo view resolves from the current
directory; with neither, the script exits non-zero naming GITHUB_REPOSITORY.
python3 ~/.claude/skills/ci-queue-trim/scripts/ci_queue_trim.py \
--repo <owner>/<repo> --max-age-hours 4 \
--allow-workflow .github/workflows/ci.yml --cancel
6. Host & Colima Preflight (--check-host)
Checks local macOS host conditions that cause runner starvation or admission lockouts:
python3 ~/.claude/skills/ci-queue-trim/scripts/ci_queue_trim.py --check-host
- Colima Sockets: Verifies
~/.colima/_lima/_networks/user-v2/user-v2_fd.sockexists and is backed by exactly 1 activelimactl usernetprocess. - Host Disk Space: Checks
/System/Volumes/Dataagainst the 7.0 GB admission safety floor.
7. Structured JSON Output (--json)
Stdout contains exactly one JSON object with stats and runs, including
for empty queues and queue-fetch errors. Human audit, host, dry-run, and
cancellation messages go to stderr. Queue-fetch errors still exit nonzero;
cancellation acceptance is reported on stderr and is not terminal-state proof.
This contract also applies with --cancel, --dry-run, and --check-host:
python3 ~/.claude/skills/ci-queue-trim/scripts/ci_queue_trim.py --json
Each row carries:
run_id, name, branch, event, pr_number, pr_state, head_commit_age, pr_updated_age, deceptive_delta, superseded, audit_incomplete, verdict, reason. head_commit_age is the actual immutable committer-timestamp
age (reporting only). pr_updated_age is the PR
updated_at age, reported for visibility only — not used for
decisions.
Diagnostic Follow-up
1. Colima Networking
Host-health observations are diagnostic hints, not proof that a process or socket is orphaned. Resolve the host Colima installation and its owning configuration; inspect exact process arguments, socket ownership, and active VM connections using that installation's read-only status tools. Any repair must follow the owning service instructions and normal authorization boundary with exact validated targets. This skill does not authorize termination, socket removal, or service restart.
2. Host Disk Floor
A low-space observation does not identify safe deletion targets. Follow the host's disk-diagnosis owner instructions, attribute usage to exact paths, and check their owners and active users. Cleanup requires a separate authorized scope with validated targets; this portable queue skill provides no deletion recipe.
3. Self-Hosted Runner Capacity
Runner health belongs to the runner installation. Resolve the actual
ez-gh-actions repository path and read its instructions before invoking its
doctor-runner checker. That checker is not included in this portable skill;
there is no working-directory-relative command here. Report observed worker
execution per configured slot using the owning fleet contract; cycling alone
is not execution proof.
4. Audit-Incomplete Runs
If a run is reported with audit_incomplete=True, the script could not
verify its PR/branch/commit at audit time. To investigate:
gh api repos/<owner>/<repo>/actions/runs/<run_id> | jq '.event, .head_sha, .pull_requests'
gh api repos/<owner>/<repo>/pulls/<pr_number> | jq '.head.sha, .state'
Do not manually cancel an audit_incomplete run unless you have
independently confirmed the head SHA mismatch.
Architecture
The script is structured around one pure classifier (classify_run)
that consumes pre-fetched facts and returns a Classification namedtuple
(verdict, superseded, audit_incomplete, reason, pr_state):
audit_queuefetches each run's record + the exact PR (via the run detail'spull_requestsarray), then callsclassify_runonce per run.cancel_with_per_item_refreshre-runs the same fetch + classifier pipeline per candidate immediately before eachgh run cancel.
Because the same classifier is reused, audit-time verdicts and pre-mutation verdicts cannot drift.
04 同仓库更多 Skills
disk-reclaim-playbook
Use Disk Magician to diagnose disk growth or qualify cleanup on macOS or Linux.
claudea-bench
Compare `claudea` and normal `claude` on a fair split of comparable work by default; use `--strict` for duplicate runs of the exact same task.
pr
Alias for the canonical pr-lifecycle PR workflow skill (/pr-workflow, /prw).
whisper
OpenAI's general-purpose speech recognition model. Supports 99 languages, transcription, translation to English, and language identification. Six model sizes from tiny (39M params) to large (1550M params). Use for speech-to-text, podcast transcription, or multilingual audio processing. Best for robust, multilingual ASR.
webapp-testing
Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.
pr-report
This skill should be used when the user asks for a PR report, PR audit, PR delta analysis, /pr-report, or wants per-PR summary with delta files/lines. Generates a structured report for one or more open PRs covering purpose, files changed, +/− line counts, /code-standards + /thermo review findings, /ponytail simplification opportunities, file-overlap combination candidates, and /green status per pr-green-definition. Output: machine-readable JSONL + human-readable markdown. Read-only by default; can apply simplifications if user opts in.