Skip to content
Back to skills

Ci Queue Trim

ASecurity

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 be...

  • 6 stars
  • 0 votes
  • 0 copies
  • 3 views
  • Added November 26, 2026
devopspythongobashgitapi

Works with

  • terminal
  • cli
  • api

Security analysis

A100/100

Pro scans all 3 files and shows the line behind each finding

Scanned November 26, 2026

npx -y skills add jleechanorg/jleechan-skills --skill ci-queue-trim --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Ci Queue Trim?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Ci Queue Trim
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/jleechanorg-ci-queue-trim/badge)](https://www.skillsdirectory.com/skills/jleechanorg-ci-queue-trim)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: ci-queue-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.
type: skill
scope: global
owner: $USER
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"
allowed-tools:
  - Bash
  - Read
  - Write
---

# /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
  `updatedAt` of "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}` via
  `commit.committer.date`. NEVER substituted with `pushed_at`,
  `updated_at`, or run age.
- `PR.updated_at` is reported separately for operator visibility only
  (the `pr_updated_age` field); it is NOT used for cancellation decisions.
- `--max-age-hours` labels 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.sha` is the **head branch tip SHA** — NOT the merge ref.
  `merge_commit_sha` is a separate field and must NOT be used for
  supersede comparison.
- For `pull_request` events: comparison ref is `PR.head.sha`.
- For `pull_request_target`: base-side semantics. The run's `head_sha`
  is 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 `push` events: always KEEP with `audit_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_group` and 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 **numeric `repo.id`**. The live
  shape of `actions/runs/{id}.pull_requests[].head.repo` is
  `{id, name, url}` (no `full_name`); requiring `full_name` would mark
  every real run unknown. The `pulls/{n}.head.repo` record carries
  `{id, full_name, name, ...}` — match by `id`.
- 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.id` MUST equal the requested `run_id` (mismatched id ⇒ drop,
  even if the rest looks valid).
- `head_sha`, `head_branch`, `event`, `path`, and `status` must be nonempty
  strings; `status` must be
  `queued` before mutation.
- `repository` must contain a nonempty `id` and `full_name`;
  `full_name` must equal the requested `OWNER/REPO`. Missing or mismatched
  identity keeps the audit row incomplete and prevents cancellation.
- PR runs require exactly one structurally valid raw `pull_requests`
  association before normalization (malformed entries are never dropped), with matching
  PR number and numeric `head.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-workflow` enables cancellation; `--protect-workflow` protects
  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 via `partition('@')[0]` — refs containing slashes are
  preserved.
- Reusable workflows invoked via `workflow_call` are 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:

```bash
"${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:
```bash
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:
```bash
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.
```bash
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.
```bash
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`.
```bash
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:
```bash
python3 ~/.claude/skills/ci-queue-trim/scripts/ci_queue_trim.py --check-host
```
- **Colima Sockets:** Verifies `~/.colima/_lima/_networks/user-v2/user-v2_fd.sock`
  exists and is backed by exactly 1 active `limactl usernet` process.
- **Host Disk Space:** Checks `/System/Volumes/Data` against 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`:
```bash
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:
```bash
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_queue` fetches each run's record + the exact PR (via the run
  detail's `pull_requests` array),
  then calls `classify_run` once per run.
- `cancel_with_per_item_refresh` re-runs the same fetch + classifier
  pipeline per candidate immediately before each `gh run cancel`.

Because the same classifier is reused, audit-time verdicts and
pre-mutation verdicts cannot drift.

Files in this skill

  • SKILL.md13.6 KB
  • scripts/ci_queue_trim.py38.4 KB
  • tests/test_ci_queue_trim.py70.6 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in devops →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.