Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions .github/workflows/pr-self-report-label.yml
Original file line number Diff line number Diff line change
Expand Up @@ -73,18 +73,37 @@ jobs:
HAS_LABEL="$(gh pr view "${PR}" --repo "${REPO}" --json labels \
--jq "[.labels[].name] | index(\"${LABEL}\") != null" 2> /dev/null || echo 'false')"

# Label mutations go through REST, NOT `gh pr edit`: that command's
# GraphQL lookup requests repository.pullRequest.projectCards, and
# GitHub answers the Projects (classic) deprecation as an ERROR on
# the gh builds that still send that query — this job's runner
# image does, so `gh pr edit` exits 1 before mutating anything.
# Every add/remove path of this job failed that way from
# 2026-08-04 on (43 runs); the green runs were all the no-change
# arm. REST never touches that query.
if [[ "${SELF}" == 'true' && "${HAS_LABEL}" != 'true' ]]; then
# Create the label on first use (idempotent), then apply it.
gh label create "${LABEL}" --repo "${REPO}" --color 'BFD4F2' \
--description 'The linked issue was opened by the PR author (self-reported)' \
2> /dev/null || true
gh pr edit "${PR}" --repo "${REPO}" --add-label "${LABEL}"
gh api -X POST "repos/${REPO}/issues/${PR}/labels" -f "labels[]=${LABEL}" > /dev/null
Comment thread
wenshao marked this conversation as resolved.
Resolved
echo "🏷️ #${PR}: added ${LABEL} — a closed issue was opened by ${PR_AUTHOR}"
elif [[ "${SELF}" != 'true' && "${HAS_LABEL}" == 'true' && "${API_OK}" == 'true' ]]; then
# The link was removed or re-pointed to someone else's issue — clear
# the now-stale label so it never lies. Only when the query itself
# succeeded: an API failure must not look like "no self-reported link".
gh pr edit "${PR}" --repo "${REPO}" --remove-label "${LABEL}"
# The label name is a PATH SEGMENT here, and it contains a slash —
# unencoded, the request hits …/labels/review/self-reported (404).
# The presence check above is not atomic with this DELETE: if the
# label was removed in the gap, the 404 only says the desired end
# state already holds and must not fail the step. Any other
# failure (403 rate limit, 5xx, network) also keeps the step
# green — the job only re-runs on the next PR event — but must
# not disappear: without the warning, the log claims "removed"
# while the label stays on the PR.
if ! REMOVE_ERR="$(gh api -X DELETE "repos/${REPO}/issues/${PR}/labels/$(jq -rn --arg l "${LABEL}" '$l|@uri')" 2>&1)"; then
[[ "${REMOVE_ERR}" == *404* ]] || echo "::warning::#${PR}: ${LABEL} removal failed — ${REMOVE_ERR}"
fi
echo "🏷️ #${PR}: removed ${LABEL} — no self-reported linked issue"
else
echo "#${PR}: no change (self=${SELF}, labeled=${HAS_LABEL}, api=${API_OK})"
Expand Down
22 changes: 20 additions & 2 deletions .github/workflows/qwen-autofix.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1733,7 +1733,14 @@ jobs:
gh pr comment "${PR}" --repo "${REPO}" --body "$(printf '🔄 Takeover re-armed: the round counter starts a fresh window (previous rounds no longer count toward the cap); management continues.\n\n<details>\n<summary>中文说明</summary>\n\n🔄 已重新武装:轮次计数开启新窗口(此前轮次不再计入上限),托管继续。\n\n</details>\n\n<!-- takeover-ack engaged -->')"
echo "🔄 re-armed ${TAKEOVER_LABEL} window on #${PR}"
else
gh pr edit "${PR}" --repo "${REPO}" --add-label "${TAKEOVER_LABEL}"
# REST for consistency and runner-version independence: `gh pr
# edit`'s GraphQL lookup requests
# repository.pullRequest.projectCards, which GitHub rejects on
# the gh builds that still send that query (demonstrated on the
# ECS pool — see pr-self-report-label.yml). This job runs on
# ubuntu-latest, where the command still worked; REST behaves
# the same on every runner image.
gh api -X POST "repos/${REPO}/issues/${PR}/labels" -f "labels[]=${TAKEOVER_LABEL}" > /dev/null
Comment thread
wenshao marked this conversation as resolved.
Resolved
echo "🏷️ applied ${TAKEOVER_LABEL} to #${PR}"
# Ack HERE, not via the pull_request:labeled round-trip: that
# event has been observed to simply not fire (#7999 — the
Expand All @@ -1759,7 +1766,18 @@ jobs:
if [[ "${HAS}" != 'true' ]]; then
echo "ℹ️ #${PR} does not carry ${TAKEOVER_LABEL} — nothing to do"
else
gh pr edit "${PR}" --repo "${REPO}" --remove-label "${TAKEOVER_LABEL}"
# REST for the same reason as the add above; the label name is a
# path segment and contains a slash, so it must be URI-encoded.
# A concurrent removal between the presence check and this
# DELETE already reached the end state — the 404 must not abort
# the step and drop the release ack below. Other failures (403,
# 5xx, network) also must not drop the ack — a later
# `/takeover stop` retries the removal — but must not disappear
# silently either: masked, the ack reads "released" while the
# loop keeps managing the PR.
if ! REMOVE_ERR="$(gh api -X DELETE "repos/${REPO}/issues/${PR}/labels/$(jq -rn --arg l "${TAKEOVER_LABEL}" '$l|@uri')" 2>&1)"; then
[[ "${REMOVE_ERR}" == *404* ]] || echo "::warning::#${PR}: ${TAKEOVER_LABEL} removal failed — ${REMOVE_ERR}"
fi
echo "🏷️ removed ${TAKEOVER_LABEL} from #${PR}"
# Release ack, direct from the command — the exact mirror of
# the engage side above, for the same reason: the unlabeled
Expand Down
17 changes: 15 additions & 2 deletions .github/workflows/repo-hygiene.yml
Original file line number Diff line number Diff line change
Expand Up @@ -842,8 +842,21 @@ jobs:

# Label requested by issue #7383. Non-fatal: never create labels,
# and a repo without it should not fail the run.
gh pr edit "${PR_URL}" --add-label 'autofix/repo-hygiene' \
|| echo '⚠️ Could not add label autofix/repo-hygiene (missing in this repo?)'
# REST, not `gh pr edit`: its GraphQL lookup requests
# repository.pullRequest.projectCards, which GitHub rejects on the
# gh builds that still send that query (see
# pr-self-report-label.yml). The label autofix/repo-hygiene has
# never been created in this repo, and the existence probe
# preserves the no-create promise: the REST add alone would create
# a missing label. The probe cannot tell a 404 from any other API
# failure, so the skip message claims neither.
if gh api "repos/${GITHUB_REPOSITORY}/labels/autofix%2Frepo-hygiene" > /dev/null 2>&1; then
Comment thread
wenshao marked this conversation as resolved.
Resolved
gh api -X POST "repos/${GITHUB_REPOSITORY}/issues/${PR_URL##*/}/labels" \
Comment thread
wenshao marked this conversation as resolved.
Resolved
-f 'labels[]=autofix/repo-hygiene' > /dev/null \
|| echo '⚠️ Could not add label autofix/repo-hygiene'
else
echo '⚠️ Could not verify label autofix/repo-hygiene; skipping'
fi

if [[ -s "${WORKDIR}/report-only.md" ]]; then
{
Expand Down
166 changes: 163 additions & 3 deletions scripts/tests/pr-self-report-label.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
existsSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
writeFileSync,
Expand All @@ -26,31 +27,64 @@ const runBlock = workflow.jobs.label.steps[0].run;

// The step decides label state from two inputs: the logins that opened the PR's
// closed issues (gh api graphql) and whether the label is already present (gh pr
// view). Stub both and record which mutation, if any, it makes.
// view). Stub both and record which mutation, if any, it makes. The
// GH_DELETE_FAILS / GH_POST_FAILS knobs make the matching REST call exit 1
// with the knob value on stderr (shaped like a real gh HTTP error), so BOTH
// failure policies the workflow introduces are pinned — DELETE tolerance and
// POST loudness — instead of the catch-all silently exiting 0.
const GH_STUB = [
'#!/usr/bin/env bash',
'echo "gh $*" >> "${CALLS_LOG}"',
'case "$*" in',
" *'api graphql'*) [ \"${GH_API_FAILS:-false}\" = true ] && exit 1; printf '%s\\n' ${GH_ISSUE_AUTHORS:-} ;;",
" *'pr view'*labels*) { [ \"${GH_HAS_LABEL:-false}\" = true ] && printf 'true' || printf 'false'; } ;;",
' *\'api -X DELETE\'*) [ -z "${GH_DELETE_FAILS:-}" ] || { printf \'%s\' "${GH_DELETE_FAILS}" >&2; exit 1; } ;;',
' *\'api -X POST\'*) [ -z "${GH_POST_FAILS:-}" ] || { printf \'%s\' "${GH_POST_FAILS}" >&2; exit 1; } ;;',
' *) : ;;',
'esac',
'exit 0',
].join('\n');

// The replayed DELETE URI-encodes the slashed label with a REAL jq — stub it
// on PATH like gh so the suite never depends on the host having jq (a fresh
// macOS has none, and the %2F assertion would fail opaquely). Supports only
// the one form the workflow executes — and ENFORCES it, program included:
// jq -rn --arg NAME VALUE '$NAME|@uri'. Any other program exits 1, so a
// mutation of the workflow's filter (e.g. dropping `|@uri`) fails the suite
// instead of riding the stub's unconditional percent-encoding.
const JQ_STUB = [
'#!/usr/bin/env bash',
'value=""',
'prog=""',
'while [[ $# -gt 0 ]]; do',
' if [[ "$1" == "--arg" ]]; then value="$3"; shift 3; else prog="$1"; shift; fi',
'done',
'[[ "$prog" == \'$l|@uri\' ]] || exit 1',
Comment thread
wenshao marked this conversation as resolved.
Resolved
'out=""',
'for ((i = 0; i < ${#value}; i++)); do',
' c="${value:i:1}"',
' if [[ "$c" =~ [A-Za-z0-9._~-] ]]; then out+="$c"; else printf -v hex \'%02X\' "\'$c"; out+="%$hex"; fi',
'done',
'printf \'%s\' "$out"',
].join('\n');

describe('pr-self-report-label', () => {
const run = ({
prAuthor = 'alice',
issueAuthors = '',
hasLabel = false,
apiFails = false,
deleteFails = '',
postFails = '',
}) => {
const dir = mkdtempSync(join(tmpdir(), 'lbl-'));
const bin = join(dir, 'bin');
mkdirSync(bin);
const callsLog = join(dir, 'calls.log');
writeFileSync(join(bin, 'gh'), GH_STUB);
chmodSync(join(bin, 'gh'), 0o755);
writeFileSync(join(bin, 'jq'), JQ_STUB);
chmodSync(join(bin, 'jq'), 0o755);
const out = execFileSync('bash', ['-c', runBlock], {
env: {
...process.env,
Expand All @@ -63,14 +97,29 @@ describe('pr-self-report-label', () => {
GH_ISSUE_AUTHORS: issueAuthors,
GH_HAS_LABEL: String(hasLabel),
GH_API_FAILS: String(apiFails),
GH_DELETE_FAILS: deleteFails,
GH_POST_FAILS: postFails,
},
encoding: 'utf8',
});
const calls = existsSync(callsLog) ? readFileSync(callsLog, 'utf8') : '';
rmSync(dir, { recursive: true, force: true });
return {
added: /add-label/.test(calls),
removed: /remove-label/.test(calls),
// Label mutations are REST — `gh pr edit`'s GraphQL lookup requests
// repository.pullRequest.projectCards, which GitHub rejects on the gh
// builds that still send it (this job's runner image does), so it
// exits 1 before mutating (43 straight CI failures of the add/remove
// arms, 2026-08-04..08). The full method + path is asserted,
// including the %2F: the label is a PATH SEGMENT in the DELETE and
// contains a slash, so an unencoded call 404s.
added:
/api -X POST repos\/o\/r\/issues\/1\/labels -f labels\[\]=review\/self-reported/.test(
calls,
),
Comment thread
wenshao marked this conversation as resolved.
Resolved
removed:
/api -X DELETE repos\/o\/r\/issues\/1\/labels\/review%2Fself-reported/.test(
Comment thread
wenshao marked this conversation as resolved.
Resolved
calls,
),
labelCreated: /label create/.test(calls),
out: out.trim(),
};
Expand Down Expand Up @@ -124,9 +173,120 @@ describe('pr-self-report-label', () => {
).toMatchObject({ added: false, removed: false });
});

it('pins the REST failure policies: 404 race silent, other DELETEs warned, POST loud', () => {
// DELETE: the presence check is not atomic with the DELETE — a 404 race
// means the desired end state already holds: green, no warning, and the
// removal is logged.
const race = run({
prAuthor: 'alice',
issueAuthors: 'bob',
hasLabel: true,
deleteFails: 'HTTP 404: Not Found (https://api.github.com/…)',
});
expect(race.removed).toBe(true);
expect(race.out).not.toContain('::warning::');
// Any other DELETE failure keeps the step green (the job only re-runs
// on the next PR event) but MUST surface — a silent run would claim
// "removed" while the label stays on the PR.
const failed = run({
prAuthor: 'alice',
issueAuthors: 'bob',
hasLabel: true,
deleteFails: 'HTTP 500',
});
expect(failed.removed).toBe(true);
expect(failed.out).toContain('::warning::');
expect(failed.out).toContain('removal failed');
expect(failed.out).toContain('HTTP 500');
// POST carries NO tolerance: a label that fails to apply must fail the
// step (the runBlock sets -e), not leave the PR unlabeled behind green.
expect(() =>
run({ prAuthor: 'alice', issueAuthors: 'alice', postFails: 'HTTP 500' }),
).toThrow();
});

it('never interpolates PR-controlled data into the run body (env only)', () => {
// pull_request_target hardening: the author/number/label reach the script
// only through env, so a crafted title or body cannot inject shell.
expect(runBlock).not.toMatch(/\$\{\{/);
});
});

// Scans one workflow file for `gh pr edit` label mutations. Comments are
// stripped before matching — a comment QUOTING the banned pattern documents
// the ban, it does not run it. Backslash continuations are joined so a
// wrapped flag still counts, and the reported line is the PHYSICAL line
// where the command starts: indices into the joined text no longer
// correspond to file lines (every benign join above an offender shifts
// them).
function ghPrEditLabelOffenders(file, raw) {
const banned = /gh pr edit .*(--add-label|--remove-label)/;
const offenders = [];
let joined = '';
let start = 0;
for (const [i, line] of raw.split('\n').entries()) {
if (joined === '') start = i + 1;
const text = line.replace(/#.*$/, '');
joined += ` ${text}`;
if (text.endsWith('\\')) continue;
Comment thread
wenshao marked this conversation as resolved.
Resolved
if (banned.test(joined)) offenders.push(`${file}:${start}`);
joined = '';
}
return offenders;
}

describe('gh pr edit label mutations are banned in workflow files', () => {
// `gh pr edit` label mutations fail wherever the gh build still requests
// repository.pullRequest.projectCards: GitHub answers the Projects
// (classic) deprecation as an error and the command exits 1 before
// applying the change. Three workflows carried label mutations through it
// and every such arm failed silently-green (the runs only passed when
// there was nothing to do) or warned with a misdiagnosis. Labels go
// through the REST issues/labels endpoints, which never touch that query.
// Scope is workflow YAML: .github/scripts/classify-release-notes.mjs still
// toggles skip-changelog-auto through `gh pr edit` on the release path and
// needs its own conversion.
it('ignores comments and reports the command start line', () => {
// A comment quoting the banned pattern documents the ban — it must not
// fail CI (the house style is dense why-comments; two of the guarded
// workflows name `gh pr edit` in comments already).
expect(
ghPrEditLabelOffenders(
'w.yml',
'# do not revert to gh pr edit --add-label here\n',
),
).toEqual([]);
// An executable violation is still caught…
expect(
ghPrEditLabelOffenders(
'w.yml',
'gh pr edit "${PR}" --add-label "${LABEL}"\n',
),
).toEqual(['w.yml:1']);
// …even wrapped across continuations, and at the PHYSICAL line where
// the command starts: line 5 here, where the two benign joins above
// would shift any index computed from the joined text.
const wrapped = [
'gh label create x \\',
' --color BFD4F2',
'echo hi \\',
' there',
'gh pr edit "${PR}" \\',
' --add-label "${LABEL}"',
].join('\n');
expect(ghPrEditLabelOffenders('w.yml', wrapped)).toEqual(['w.yml:5']);
});

it('no workflow mutates labels through gh pr edit', () => {
const dir = '.github/workflows';
const files = readdirSync(dir).filter((f) => /\.ya?ml$/.test(f));
expect(files.length).toBeGreaterThan(0);
const offenders = [];
for (const file of files) {
offenders.push(
...ghPrEditLabelOffenders(file, readFileSync(join(dir, file), 'utf8')),
);
}
expect(offenders).toEqual([]);
});
});
Loading
Loading