diff --git a/.github/workflows/qwen-autofix.yml b/.github/workflows/qwen-autofix.yml index 177cbb9a231c..15082a15b19e 100644 --- a/.github/workflows/qwen-autofix.yml +++ b/.github/workflows/qwen-autofix.yml @@ -127,6 +127,12 @@ env: # Comment-command sugar over TAKEOVER_LABEL ('' applies it, ' # stop' removes it). Matched EXACTLY against the trimmed comment body. TAKEOVER_COMMAND: '@qwen-code /takeover' + # Re-arm sugar. Recovering a stranded PR previously meant DELETING the + # bot's autofix-eval marker comment by hand (undiscoverable, destructive, + # and it erases the audit trail). This command instead posts an + # 'autofix-rearm' marker that supersedes the earlier evaluation markers: + # the scan re-reads the feedback from scratch and the round counter resets. + RETRY_COMMAND: '@qwen-code /retry' # Round cap while TAKEOVER_LABEL is present. Large managed PRs routinely # need dozens of feedback rounds — that is the point of takeover — so the # unattended cap (MAX_ROUNDS) would strangle it. The circuit breaker stays @@ -147,8 +153,10 @@ jobs: # gates (exact body match, sender authorization) live in 'Decide phases'. # Nuance: a body with LEADING whitespace dies here even though the decide # branch would trim it — fail closed, command must start the comment. + # Both commands are prefiltered here (/takeover toggles the label, /retry + # re-arms a stranded PR); everything else never starts a job. if: |- - ${{ github.repository == 'QwenLM/qwen-code' && (github.event_name != 'issue_comment' || (github.event.issue.pull_request && startsWith(github.event.comment.body, '@qwen-code /takeover'))) && (github.event_name != 'pull_request' || github.event.label.name == 'autofix/takeover') }} + ${{ github.repository == 'QwenLM/qwen-code' && (github.event_name != 'issue_comment' || (github.event.issue.pull_request && (startsWith(github.event.comment.body, '@qwen-code /takeover') || startsWith(github.event.comment.body, '@qwen-code /retry')))) && (github.event_name != 'pull_request' || github.event.label.name == 'autofix/takeover') }} runs-on: 'ubuntu-latest' timeout-minutes: 5 concurrency: @@ -198,6 +206,7 @@ jobs: takeover_ack: '${{ steps.decide.outputs.takeover_ack }}' ack_pr: '${{ steps.decide.outputs.ack_pr }}' takeover_cmd: '${{ steps.decide.outputs.takeover_cmd }}' + retry_pr: '${{ steps.decide.outputs.retry_pr }}' cmd_pr: '${{ steps.decide.outputs.cmd_pr }}' steps: - name: 'Decide phases' @@ -235,6 +244,7 @@ jobs: TAKEOVER_ACK='' TAKEOVER_CMD='' CMD_PR='' + RETRY_PR='' DRY_RUN="${DRY_RUN_INPUT:-false}" sanitize_number() { local value="${1//$'\r'/}" @@ -323,14 +333,19 @@ jobs: CMD='' [[ "${BODY_TRIMMED}" == "${TAKEOVER_COMMAND}" ]] && CMD='add' [[ "${BODY_TRIMMED}" == "${TAKEOVER_COMMAND} stop" ]] && CMD='remove' + # Re-arm shares the takeover command's authorization exactly: + # both summon bot activity on a managed PR, so inventing a + # second policy would only add surface. + RETRY_REQ='' + [[ "${BODY_TRIMMED}" == "${RETRY_COMMAND}" ]] && RETRY_REQ='true' if [[ -z "${HAS_PR_URL}" ]]; then - echo "🧭 takeover command ignored: not a PR comment" - elif [[ -z "${CMD}" ]]; then - echo "🧭 takeover command ignored: body is not an exact command" + echo "🧭 command ignored: not a PR comment" + elif [[ -z "${CMD}" && -z "${RETRY_REQ}" ]]; then + echo "🧭 command ignored: body is not an exact command" elif [[ "${ISSUE_STATE}" != 'open' ]]; then - echo "🧭 takeover command ignored: PR is not open" + echo "🧭 command ignored: PR is not open" elif [[ -z "${SENDER_LOGIN}" || "${SENDER_LOGIN}" == "${AUTOFIX_BOT}" ]]; then - echo "🧭 takeover command ignored: sender '${SENDER_LOGIN:-n/a}'" + echo "🧭 command ignored: sender '${SENDER_LOGIN:-n/a}'" else sender_is_authorized=false sender_permission='' @@ -371,11 +386,16 @@ jobs: rm -f "${api_error_file}" fi if [[ "${sender_is_authorized}" == 'true' ]]; then - TAKEOVER_CMD="${CMD}" - CMD_PR="$(sanitize_number "${ISSUE_NUMBER}")" - echo "🧭 takeover command accepted: ${CMD} ${TAKEOVER_LABEL} on PR #${ISSUE_NUMBER} by ${SENDER_LOGIN} (${sender_permission})" + if [[ -n "${RETRY_REQ}" ]]; then + RETRY_PR="$(sanitize_number "${ISSUE_NUMBER}")" + echo "🧭 retry command accepted: re-arm PR #${ISSUE_NUMBER} by ${SENDER_LOGIN} (${sender_permission})" + else + TAKEOVER_CMD="${CMD}" + CMD_PR="$(sanitize_number "${ISSUE_NUMBER}")" + echo "🧭 takeover command accepted: ${CMD} ${TAKEOVER_LABEL} on PR #${ISSUE_NUMBER} by ${SENDER_LOGIN} (${sender_permission})" + fi else - echo "🧭 takeover command ignored: sender '${SENDER_LOGIN}' permission='${sender_permission:-none}' is not the PR author or write+" + echo "🧭 command ignored: sender '${SENDER_LOGIN}' permission='${sender_permission:-none}' is not the PR author or write+" fi fi fi @@ -480,6 +500,7 @@ jobs: echo "takeover_ack=${TAKEOVER_ACK}" >> "${GITHUB_OUTPUT}" echo "ack_pr=$(sanitize_number "${PR_NUMBER_EVENT}")" >> "${GITHUB_OUTPUT}" echo "takeover_cmd=${TAKEOVER_CMD}" >> "${GITHUB_OUTPUT}" + echo "retry_pr=${RETRY_PR}" >> "${GITHUB_OUTPUT}" echo "cmd_pr=${CMD_PR}" >> "${GITHUB_OUTPUT}" echo "🧭 phase='${PHASE:-auto}' event='${EVENT_NAME}' issue='#${ISSUE_NUMBER:-n/a}' pr='#${PR_NUMBER_EVENT:-n/a}' schedule='${SCHEDULE:-n/a}' dry_run=${DRY_RUN} → issue=${DO_ISSUE} review=${DO_REVIEW}" @@ -1330,6 +1351,51 @@ jobs: # a PR via the takeover label. Label events are explicit user actions, so # every toggle acks (no dedup wanted). In-repo PRs only reach this job. # =========================================================================== + # Re-arm a stranded PR without deleting anything. Recovery previously meant + # `gh api -X DELETE` on the bot's own autofix-eval marker comment: raw API + # access, an erased audit trail, and undiscoverable unless you had read the + # workflow. This posts ONE marker instead — the scan then re-reads the + # feedback (the marker releases the watermark those older markers held) and + # the round counter resets, because the marker also opens a fresh counting + # window exactly like an engage ack. + retry-command: + needs: 'route' + if: |- + ${{ needs.route.outputs.retry_pr != '' }} + # Queued (never cancelled) per PR so two quick /retry comments cannot + # interleave their marker writes. + concurrency: + group: 'qwen-autofix-retry-cmd-${{ needs.route.outputs.retry_pr }}' + cancel-in-progress: false + runs-on: 'ubuntu-latest' + timeout-minutes: 5 + permissions: + contents: 'read' + env: + REPO: '${{ github.repository }}' + PR: '${{ needs.route.outputs.retry_pr }}' + GITHUB_TOKEN: '${{ secrets.CI_DEV_BOT_PAT }}' + steps: + - name: 'Post re-arm marker' + run: |- + # The marker only counts when the AUTOFIX_BOT authored it (both the + # scan and the address-side recheck filter markers by that login), so + # a mis-scoped PAT would post a comment that silently does nothing. + api_error_file="$(mktemp)" + if ! bot_actor="$(GH_TOKEN="${GITHUB_TOKEN}" gh api user --jq '.login' 2>"${api_error_file}")"; then + api_error="$(tr '\r\n' ' ' < "${api_error_file}")" + rm -f "${api_error_file}" + echo "::error::Failed to verify CI_DEV_BOT_PAT identity with gh api user: ${api_error:-unknown error}." + exit 1 + fi + rm -f "${api_error_file}" + if [[ "${bot_actor}" != "${AUTOFIX_BOT}" ]]; then + echo "::error::CI_DEV_BOT_PAT authenticates as '${bot_actor:-unknown}'; expected ${AUTOFIX_BOT}." + exit 1 + fi + gh pr comment "${PR}" --repo "${REPO}" --body "$(printf '\U0001F504 AutoFix re-armed. The next scan re-reads this PR'"'"'s feedback from the start and the round counter resets. Nothing was deleted — this marker supersedes the evaluation markers above it.\n\n
\n中文说明\n\n\U0001F504 已重新武装 AutoFix。下一次扫描会从头重新读取本 PR 的反馈,轮次计数也已重置。未删除任何内容 —— 本标记使其上方的评估标记失效。\n\n
\n\n')" + echo "🔄 re-armed PR #${PR}" + takeover-ack: needs: 'route' if: |- @@ -1697,9 +1763,9 @@ jobs: # Inserting or reordering a field here or at any write site silently # corrupts round tracking; keep the `ts= acted= round=` order in lockstep. MARKERS="$(jq -c --arg ab "${AUTOFIX_BOT}" ' - [ .[] | select((.user.login // "") == $ab) | (.body // "") + [ .[] | select((.user.login // "") == $ab) | . as $c | ($c.body // "") | [ scan("") ] | .[] - | {ts: .[0], round: (.[2] | tonumber), win: (.[3] // "none")} ]' "${WORKDIR}/ic.json")" + | {ts: .[0], round: (.[2] | tonumber), win: (.[3] // "none"), at: ($c.created_at // "")} ]' "${WORKDIR}/ic.json")" # The watermark is GLOBAL across all markers — feedback already # evaluated stays evaluated, no matter how counting windows move. # The terminal-handoff SENTINEL ts is excluded: it is a flag, not @@ -1707,7 +1773,19 @@ jobs: # filter all future feedback forever — making a re-arm after a # terminal handoff dead on arrival (terminal skipping itself is # round-based and window-scoped, so re-arm properly clears it). - EVAL_WM="$(jq -r 'map(.ts) | map(select(. != "9999-12-31T23:59:59Z")) | max // ""' <<< "${MARKERS}")" + REARM_AT="$(jq -r --arg ab "${AUTOFIX_BOT}" ' + [ .[] | select((.user.login // "") == $ab) + | select((.body // "") | contains("")) + | .created_at ] | max // ""' "${WORKDIR}/ic.json")" + # A maintainer '@qwen-code /retry' posts that marker to say + # "evaluate this feedback again": markers written BEFORE it stop + # holding the watermark down. This is the sanctioned exception to + # the global rule above, and it replaces the old recovery - + # deleting the bot's marker comment by hand, which erased the + # audit trail and needed raw API access to do at all. + EVAL_WM="$(jq -r --arg rearm "${REARM_AT}" ' + map(select($rearm == "" or (.at > $rearm))) + | map(.ts) | map(select(. != "9999-12-31T23:59:59Z")) | max // ""' <<< "${MARKERS}")" # ROUND counting is windowed by KEY EQUALITY, not timestamps: the # current window key is the created_at of the latest # '' comment ('none' before any @@ -1721,7 +1799,8 @@ jobs: # scan skip regardless of order). REARM_KEY="$(jq -r --arg ab "${AUTOFIX_BOT}" ' [ .[] | select((.user.login // "") == $ab) - | select((.body // "") | contains("")) + | select(((.body // "") | contains("")) + or ((.body // "") | contains(""))) | .created_at ] | max // "none"' "${WORKDIR}/ic.json")" ROUND="$(jq -r --arg key "${REARM_KEY}" 'map(select(.win == $key)) | map(.round) | max // 0' <<< "${MARKERS}")" @@ -1821,7 +1900,7 @@ jobs: # bot's own eval markers, and known non-actionable bot comments # (triage stages, coverage reports, legacy suggestion summaries, # force-push reminders). - BOT_COMMENT_FILTER='") ] | .[] - | {ts: .[0], round: (.[2] | tonumber), win: (.[3] // "none")} ]' "${WORKDIR}/ic.json")" - LIVE_EVAL_WM="$(jq -r 'map(.ts) | map(select(. != "9999-12-31T23:59:59Z")) | max // ""' <<< "${LIVE_MARKS}")" + | {ts: .[0], round: (.[2] | tonumber), win: (.[3] // "none"), at: ($c.created_at // "")} ]' "${WORKDIR}/ic.json")" + LIVE_REARM_AT="$(jq -r --arg ab "${AUTOFIX_BOT}" ' + [ .[] | select((.user.login // "") == $ab) + | select((.body // "") | contains("")) + | .created_at ] | max // ""' "${WORKDIR}/ic.json")" + # Mirrors the scan: a /retry marker releases the watermark it holds. + LIVE_EVAL_WM="$(jq -r --arg rearm "${LIVE_REARM_AT}" ' + map(select($rearm == "" or (.at > $rearm))) + | map(.ts) | map(select(. != "9999-12-31T23:59:59Z")) | max // ""' <<< "${LIVE_MARKS}")" # Round counting mirrors the scan: keyed to the CURRENT window (the # latest engage ack's created_at, 'none' before any takeover), so # pre-re-arm markers can neither trip the cap nor inflate the live # round here. LIVE_REARM_KEY="$(jq -r --arg ab "${AUTOFIX_BOT}" ' [ .[] | select((.user.login // "") == $ab) - | select((.body // "") | contains("")) + | select(((.body // "") | contains("")) + or ((.body // "") | contains(""))) | .created_at ] | max // "none"' "${WORKDIR}/ic.json")" LIVE_MAX_ROUND="$(jq -r --arg key "${LIVE_REARM_KEY}" 'map(select(.win == $key)) | map(.round) | max // 0' <<< "${LIVE_MARKS}")" # A re-arm SUPERSEDES every job selected under the old window key: @@ -2248,7 +2335,7 @@ jobs: + (.[2] | map(select((.created_at // "") > $wm) | select((.user.login // "") != $ab) | select(((.author_association // "") | IN($trust[])) or (.user.login // "") == $rb) - | select((.body // "") | test("`, + }); + const run = (comments) => { + const dir = mkdtempSync(join(tmpdir(), 'rearm-')); + writeFileSync(join(dir, 'ic.json'), JSON.stringify(comments)); + const out = execFileSync( + 'bash', + [ + '-c', + `set -uo pipefail\n${block}\nprintf '%s|%s|%s' "$EVAL_WM" "$REARM_KEY" "$ROUND"`, + ], + { + env: { ...process.env, WORKDIR: dir, AUTOFIX_BOT: BOT }, + encoding: 'utf8', + }, + ); + rmSync(dir, { recursive: true, force: true }); + return out.split('|'); + }; + + const evaluated = [ + evalMarker('2026-07-20T08:00:00Z', '2026-07-20T07:00:00Z', 1), + evalMarker('2026-07-20T09:00:00Z', '2026-07-20T08:30:00Z', 2), + ]; + // Stranded: the watermark sits at the newest evaluated feedback and the + // round has climbed, so the scan reports "nothing new" forever. + const [wmBefore, keyBefore, roundBefore] = run(evaluated); + expect(wmBefore).toBe('2026-07-20T08:30:00Z'); + expect(keyBefore).toBe('none'); + expect(roundBefore).toBe('2'); + + // After /retry both halves clear: no marker holds the watermark, and the + // marker opens a fresh counting window so the round restarts at 0. + const [wmAfter, keyAfter, roundAfter] = run([ + ...evaluated, + { + user: { login: BOT }, + created_at: '2026-07-20T10:00:00Z', + body: '', + }, + ]); + expect(wmAfter).toBe(''); + expect(keyAfter).toBe('2026-07-20T10:00:00Z'); + expect(roundAfter).toBe('0'); + + // A marker written AFTER the re-arm counts again (the exception is scoped + // to the re-arm instant, it does not disable the watermark forever). + const [wmNext] = run([ + ...evaluated, + { + user: { login: BOT }, + created_at: '2026-07-20T10:00:00Z', + body: '', + }, + evalMarker('2026-07-20T11:00:00Z', '2026-07-20T10:30:00Z', 1), + ]); + expect(wmNext).toBe('2026-07-20T10:30:00Z'); + + // A re-arm posted by anyone other than the bot is ignored: both scanners + // filter markers by author, so a spoofed comment must not re-arm. + const [wmSpoof] = run([ + ...evaluated, + { + user: { login: 'someone-else' }, + created_at: '2026-07-20T10:00:00Z', + body: '', + }, + ]); + expect(wmSpoof).toBe('2026-07-20T08:30:00Z'); + }); + + it('address-side stale check mirrors the scan-side re-arm logic under bash', () => { + // The scan-side and address-side jq blocks are copy-pasted (~40 lines + // each, 4 jq expressions). Drift between them is the class of bug the + // re-arm feature prevents: a queued address job could stamp an + // old-sequence eval marker into a fresh window after /retry. This test + // runs the address-side block under bash with the same fixtures and + // asserts identical outputs. + const block = prepareBranchAndFeedbackStep.match( + /(LIVE_MARKS="\$\(jq[\s\S]*?LIVE_MAX_ROUND="\$\(jq[^\n]*\n)/, + )?.[1]; + expect(block).toBeTruthy(); + + const BOT = 'qwen-code-dev-bot'; + const evalMarker = (at, ts, round) => ({ + user: { login: BOT }, + created_at: at, + body: ``, + }); + const run = (comments) => { + const dir = mkdtempSync(join(tmpdir(), 'rearm-live-')); + writeFileSync(join(dir, 'ic.json'), JSON.stringify(comments)); + const out = execFileSync( + 'bash', + [ + '-c', + `set -uo pipefail\n${block}\nprintf '%s|%s|%s' "$LIVE_EVAL_WM" "$LIVE_REARM_KEY" "$LIVE_MAX_ROUND"`, + ], + { + env: { ...process.env, WORKDIR: dir, AUTOFIX_BOT: BOT }, + encoding: 'utf8', + }, + ); + rmSync(dir, { recursive: true, force: true }); + return out.split('|'); + }; + + const evaluated = [ + evalMarker('2026-07-20T08:00:00Z', '2026-07-20T07:00:00Z', 1), + evalMarker('2026-07-20T09:00:00Z', '2026-07-20T08:30:00Z', 2), + ]; + const [wmBefore, keyBefore, roundBefore] = run(evaluated); + expect(wmBefore).toBe('2026-07-20T08:30:00Z'); + expect(keyBefore).toBe('none'); + expect(roundBefore).toBe('2'); + + const [wmAfter, keyAfter, roundAfter] = run([ + ...evaluated, + { + user: { login: BOT }, + created_at: '2026-07-20T10:00:00Z', + body: '', + }, + ]); + expect(wmAfter).toBe(''); + expect(keyAfter).toBe('2026-07-20T10:00:00Z'); + expect(roundAfter).toBe('0'); + + const [wmNext] = run([ + ...evaluated, + { + user: { login: BOT }, + created_at: '2026-07-20T10:00:00Z', + body: '', + }, + evalMarker('2026-07-20T11:00:00Z', '2026-07-20T10:30:00Z', 1), + ]); + expect(wmNext).toBe('2026-07-20T10:30:00Z'); + + const [wmSpoof] = run([ + ...evaluated, + { + user: { login: 'someone-else' }, + created_at: '2026-07-20T10:00:00Z', + body: '', + }, + ]); + expect(wmSpoof).toBe('2026-07-20T08:30:00Z'); + }); + + it('routes @qwen-code /retry through the takeover command authorization', () => { + // Prefilter must let the command reach route at all, and the marker must + // be a CONTROL comment so the agent never sees it as feedback to address. + expect(workflow).toContain( + "startsWith(github.event.comment.body, '@qwen-code /retry')", + ); + expect(workflow).toContain("RETRY_COMMAND: '@qwen-code /retry'"); + expect(workflow).toContain(''); + expect(workflow).toContain('') check matches the + // marker at several workflow sites so it would not catch a typo in the body. + const BOT = 'qwen-code-dev-bot'; + const rearmStep = workflow.match( + /- name: 'Post re-arm marker'\n {8}run: \|-\n {10}([\s\S]*?)\n\n {2}takeover-ack:/, + )?.[1]; + expect(rearmStep).toBeTruthy(); + const block = rearmStep.replace(/\n {10}/g, '\n'); + + const runRearm = ({ actor = BOT, apiFail = false } = {}) => { + const dir = mkdtempSync(join(tmpdir(), 'autofix-rearm-')); + try { + writeFileSync( + join(dir, 'gh'), + [ + '#!/bin/bash', + `echo "$1 $2" >> '${join(dir, 'calls.log')}'`, + 'if [[ "$1" == "api" && "$2" == "user" ]]; then', + ` if [[ "${apiFail}" == "true" ]]; then echo "HTTP 401: Bad credentials" >&2; exit 1; fi`, + ` printf '%s' "${actor}"`, + 'elif [[ "$1" == "pr" && "$2" == "comment" ]]; then', + ` printf '%s' "$7" > '${join(dir, 'body.txt')}'`, + 'fi', + ].join('\n'), + ); + chmodSync(join(dir, 'gh'), 0o755); + writeFileSync(join(dir, 'calls.log'), ''); + const res = spawnSync('bash', ['-c', block], { + env: { + ...process.env, + PATH: `${dir}:${process.env.PATH}`, + GITHUB_TOKEN: 'x', + PR: '7354', + REPO: 'QwenLM/qwen-code', + AUTOFIX_BOT: BOT, + }, + encoding: 'utf8', + }); + return { + status: res.status, + stdout: res.stdout ?? '', + calls: readFileSync(join(dir, 'calls.log'), 'utf8'), + body: existsSync(join(dir, 'body.txt')) + ? readFileSync(join(dir, 'body.txt'), 'utf8') + : '', + }; + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }; + + // Happy path: identity verified via gh api user, then the marker is posted + // with the scanner marker line in the bilingual collapsed format. + const ok = runRearm({ actor: BOT }); + expect(ok.status).toBe(0); + expect(ok.calls).toContain('api user'); + expect(ok.calls).toContain('pr comment'); + expect(ok.stdout).toContain('re-armed PR #7354'); + expect(ok.body).toContain('AutoFix re-armed'); + expect(ok.body).toContain(''); + expect(ok.body).toContain('
'); + expect(ok.body).toContain('中文说明'); + // No line may be indented 4+ spaces, or the marker renders as a code block + // and the scanners' marker match silently fails. + expect(ok.body).not.toMatch(/^ {4,}/m); + + // Actor mismatch: the PAT authenticates as someone else -> the guard exits + // non-zero and posts nothing (a mis-scoped PAT must not leave a stranded PR + // behind a fake "re-armed" line). + const mismatch = runRearm({ actor: 'someone-else' }); + expect(mismatch.status).toBe(1); + expect(mismatch.calls).toContain('api user'); + expect(mismatch.calls).not.toContain('pr comment'); + expect(mismatch.body).toBe(''); + expect(mismatch.stdout).toContain(`expected ${BOT}`); + + // API failure: gh api user fails -> exits non-zero, posts nothing, and + // surfaces the captured gh stderr in the error message. + const failed = runRearm({ apiFail: true }); + expect(failed.status).toBe(1); + expect(failed.calls).not.toContain('pr comment'); + expect(failed.body).toBe(''); + expect(failed.stdout).toContain('Failed to verify CI_DEV_BOT_PAT identity'); + expect(failed.stdout).toContain('Bad credentials'); + }); + it('replays the handoff decision and terminal-round transitions under bash', () => { // The agent step is bounded below the 120-minute job timeout so a runaway // agent fails the STEP, not the job, leaving the always() report step time to