From ad03dcf7ff72a54bc5903ea5a359b542d9d252e8 Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:49:11 -0500 Subject: [PATCH 1/2] feat(pr-merge): read the merge sweep through the lanes App token Owner decision D398 (2026-11-18): the scheduled merge sweep reads through the lanes App's own installation allowance instead of the repository's shared GITHUB_TOKEN pool. - lane-rules.json gives the merge-pr grant actions read, which the token broker already allows to that activity alone. - The merge job's candidate listing, carried artifact reads, post-merge check, skip filter, gate verdict and review-evidence reads and sweep-count read use the lane token, named lanes-app to the rate guard. - babysit_gh sends check-run, check-suite, annotation and commit-status reads under BABYSIT_JOB_GH_TOKEN (the job's GITHUB_TOKEN) when set, since the lane grant holds neither permission, and names a call whose GH_TOKEN equals the process's own as API_BUDGET_TOKEN. - Whole-review reads its job bucket with BABYSIT_JOB_GH_TOKEN when set. Enable Auto Merge stays on GITHUB_TOKEN: the broker refuses actions to the enable-auto-merge activity. Co-Authored-By: Claude Opus 5.5 --- .../feat-pr-merge-app-token-reads-7a68786b.md | 7 ++ .../feat-pr-merge-app-token-reads-69d513d8.md | 12 +++ .../actions/resolve-config/lane-rules.json | 3 +- .../resolve-config/live-config.test.mjs | 12 ++- .github/scripts/pr-merge/carry-run-cache.mjs | 2 +- .github/scripts/pr-merge/head-ref-map.mjs | 2 +- .github/scripts/pr-merge/lane-records.mjs | 2 +- .github/scripts/pr-merge/merge-job.test.mjs | 58 ++++++++++--- .github/scripts/pr-merge/rotation.mjs | 2 +- .github/scripts/pr-merge/workflow.test.mjs | 4 +- .github/scripts/pr-verify/workflow.test.mjs | 11 +-- .github/workflows/pr-merge.yml | 86 ++++++++++--------- docs/conventions/pr-pipeline/README.md | 26 ++++-- .../skills/babysit-prs/scripts/babysit_gh.py | 36 +++++++- .../babysit-prs/scripts/babysit_merge.py | 7 +- .../scripts/babysit_whole_review.py | 5 +- .../tests/test_babysit_gh_api_budget.py | 64 +++++++++++++- .../tests/test_babysit_merge_unattended.py | 4 +- .../tests/test_babysit_verify_evidence.py | 8 +- .../tests/test_babysit_whole_review.py | 25 +++++- 20 files changed, 278 insertions(+), 98 deletions(-) create mode 100644 .changes/pr-pipeline/feat-pr-merge-app-token-reads-7a68786b.md create mode 100644 .changes/source-control/feat-pr-merge-app-token-reads-69d513d8.md diff --git a/.changes/pr-pipeline/feat-pr-merge-app-token-reads-7a68786b.md b/.changes/pr-pipeline/feat-pr-merge-app-token-reads-7a68786b.md new file mode 100644 index 00000000000..cc20cddf554 --- /dev/null +++ b/.changes/pr-pipeline/feat-pr-merge-app-token-reads-7a68786b.md @@ -0,0 +1,7 @@ +--- +bump: minor +--- + +### Changed + +- pr-merge's merge job reads through the lanes App's installation allowance instead of the repository's shared `GITHUB_TOKEN` pool (owner decision D398). `lane-rules.json` gives the `merge-pr` grant `actions: read`, which the token broker allows to that activity alone. The candidate listing, the carried artifact reads (cursor, head-ref map, verdict reads, lane records), the post-merge check, the skip filter, the gate's verdict and review-evidence reads and the sweep-count read use the lane token, named `lanes-app` to the rate guard. Check-run, check-suite, annotation and commit-status reads, the who and superseded reads before the mint, and the re-fire and escalation-clear steps stay on `GITHUB_TOKEN`. No read moves to the other token when its own pool runs low. diff --git a/.changes/source-control/feat-pr-merge-app-token-reads-69d513d8.md b/.changes/source-control/feat-pr-merge-app-token-reads-69d513d8.md new file mode 100644 index 00000000000..95b70b02c14 --- /dev/null +++ b/.changes/source-control/feat-pr-merge-app-token-reads-69d513d8.md @@ -0,0 +1,12 @@ +--- +bump: minor +--- + +### Added + +- The babysit scripts' gh seam sends a REST read of check runs, check suites, annotations or commit statuses under `BABYSIT_JOB_GH_TOKEN` when a job sets it (`babysit_gh.job_token_env`), so a job whose process and verdict-reader token is an App token without the Checks or Commit statuses permission reads those with its own `GITHUB_TOKEN`. Writes and every other read keep their token. + +### Changed + +- A call whose `GH_TOKEN` override equals the process's own `GH_TOKEN` is named to the rate guard as `API_BUDGET_TOKEN`, not `API_BUDGET_OVERRIDE_TOKEN`, so a verdict reader set to the process token budgets against that token's pool. +- The whole-review request reads the job bucket and the running jobs with `BABYSIT_JOB_GH_TOKEN` when it is set, else with `BABYSIT_VERIFY_GH_TOKEN` as before. diff --git a/.github/actions/resolve-config/lane-rules.json b/.github/actions/resolve-config/lane-rules.json index 8bc5efb5e81..81516b504f4 100644 --- a/.github/actions/resolve-config/lane-rules.json +++ b/.github/actions/resolve-config/lane-rules.json @@ -64,7 +64,8 @@ "pr-merge": { "stage": "merge", "forbidden-effects": [], - "never": "Merges above the rung, past a hold, or a PR that touches a denied path" + "never": "Merges above the rung, past a hold, or a PR that touches a denied path", + "activity-grants": { "merge-pr": { "actions": "read" } } }, "post-merge-verify": { "stage": "post-merge", diff --git a/.github/actions/resolve-config/live-config.test.mjs b/.github/actions/resolve-config/live-config.test.mjs index ed1a03c8752..357cd7d7a6b 100644 --- a/.github/actions/resolve-config/live-config.test.mjs +++ b/.github/actions/resolve-config/live-config.test.mjs @@ -860,16 +860,22 @@ test("live config: the shipped patch rules pass against the live activities", () assert.equal(checkPatchRules(rules, json("./patch-rules.schema.json"), parse(FILES.config).activities), rules); }); -test("live config: no live slot resolves an actions permission", () => { +test("live config: only pr-merge's merge-pr grant carries actions, and only read", () => { const doc = parse(FILES.config); + const holders = []; for (const lane of Object.keys(doc.lanes)) { const { lane: resolved } = resolve(FILES, { lane, configPath: CONFIG_PATH, basePath: ".base", facts: FACTS }); for (const slot of resolved.slots) { - assert.equal(slot.grant.actions, undefined, `${lane}/${slot.name}`); + if (slot.grant.actions !== undefined) holders.push(`${lane}/${slot.name}`); } } + assert.ok(holders.every((holder) => holder.startsWith("pr-merge/")), JSON.stringify(holders)); + assert.deepEqual(resolveGrant(FILES, { lane: "pr-merge", activity: "merge-pr", configPath: CONFIG_PATH }), { + effect: "merge", + grant: { contents: "write", "pull-requests": "write", issues: "write", actions: "read" }, + }); assert.equal( - resolveGrant(FILES, { lane: "pr-merge", activity: "merge-pr", configPath: CONFIG_PATH }).grant.actions, + resolveGrant(FILES, { lane: "pr-merge", activity: "enable-auto-merge", configPath: CONFIG_PATH }).grant.actions, undefined, ); }); diff --git a/.github/scripts/pr-merge/carry-run-cache.mjs b/.github/scripts/pr-merge/carry-run-cache.mjs index 975c6de8b57..bea06e2207b 100755 --- a/.github/scripts/pr-merge/carry-run-cache.mjs +++ b/.github/scripts/pr-merge/carry-run-cache.mjs @@ -53,7 +53,7 @@ // CARRY_BRANCH the branch the verdicts are judged on (main) // GITHUB_OUTPUT gets carried=true once CARRY_TO is written, and // kept=true when it holds a read -// ACTIONS_TOKEN read: the job's GITHUB_TOKEN (actions: read) +// ACTIONS_TOKEN read: a token with Actions read (https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps) // GITHUB_RUN_ID read: this run, which has no file yet // RUNNER_TEMP read: where the artifact is downloaded // PR_MERGE_READS_PATH read: the job's shared GET answers diff --git a/.github/scripts/pr-merge/head-ref-map.mjs b/.github/scripts/pr-merge/head-ref-map.mjs index 8535972e56b..66f371ab0c4 100755 --- a/.github/scripts/pr-merge/head-ref-map.mjs +++ b/.github/scripts/pr-merge/head-ref-map.mjs @@ -31,7 +31,7 @@ // untied FAIL, which costs requests, never a decision. // // Environment: -// ACTIONS_TOKEN read: the job's GITHUB_TOKEN (actions: read) +// ACTIONS_TOKEN read: a token with Actions read (https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps) // GITHUB_REPOSITORY owner/repo // GITHUB_RUN_ID read: this run, which has no map yet // RUNNER_TEMP read: where the artifact is downloaded diff --git a/.github/scripts/pr-merge/lane-records.mjs b/.github/scripts/pr-merge/lane-records.mjs index e3c87ec9c2c..6e5b8eedf8a 100755 --- a/.github/scripts/pr-merge/lane-records.mjs +++ b/.github/scripts/pr-merge/lane-records.mjs @@ -34,7 +34,7 @@ // check then reads every record, which costs requests, never a decision. // // Environment: -// ACTIONS_TOKEN read: the job's GITHUB_TOKEN (actions: read) +// ACTIONS_TOKEN read: a token with Actions read (https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps) // GITHUB_REPOSITORY owner/repo // GITHUB_RUN_ID read: this run, which has no file yet // RUNNER_TEMP read: where the artifact is downloaded diff --git a/.github/scripts/pr-merge/merge-job.test.mjs b/.github/scripts/pr-merge/merge-job.test.mjs index 329ed26aad6..9da33adb95c 100644 --- a/.github/scripts/pr-merge/merge-job.test.mjs +++ b/.github/scripts/pr-merge/merge-job.test.mjs @@ -26,6 +26,8 @@ const stepsOf = (block) => .map((b) => ({ name: /^ - name: (.*)$/m.exec(b)[1], block: b })); const job = jobBlock("merge"); const steps = stepsOf(job); +const LANE_ACTIONS_READ = "ACTIONS_TOKEN: ${{ steps.lane-token.outputs.token }}\n"; +const JOB_ACTIONS_READ = "ACTIONS_TOKEN: ${{ github.token }}\n"; const step = (name, list = steps) => { const found = list.find((s) => s.name === name); assert.ok(found, `step ${name}`); @@ -497,7 +499,13 @@ test("a held listing files no failed lane merge; a run that listed goes by its o }); test("a held listing writes a sweep summary with no read, and a monitor can tell it held", () => { - const skipped = { gate: { outcome: "skipped" }, candidates: { outputs: {} }, "scan-upload-5": { outputs: { clean: "true" } } }; + const skipped = { + gate: { outcome: "skipped" }, + candidates: { outputs: {} }, + "scan-upload-5": { outputs: { clean: "true" } }, + "lane-token": { outputs: { token: "t" } }, + }; + assert.equal(runsOn("Count the sweep's refusals", { ...skipped, candidates: { outputs: { held: "true" } }, "lane-token": { outputs: { token: "" } } }), false); for (const name of ["Count the sweep's refusals", "Upload the sweep's verdicts", "Write the sweep cost"]) { assert.equal(runsOn(name, { ...skipped, candidates: { outputs: { held: "true" } } }), true, name); assert.equal(runsOn(name, skipped), false, name); @@ -670,12 +678,15 @@ test("both token-holding jobs read the carried reads from the last trusted run's const carried = "${{ runner.temp }}/pr-merge-carried.json"; const runCache = "${{ runner.temp }}/babysit-run-cache.json"; const read = "Read the verdict reads the last run kept"; - for (const list of [steps, stepsOf(jobBlock("enable-auto-merge"))]) { + for (const [list, token] of [ + [steps, LANE_ACTIONS_READ], + [stepsOf(jobBlock("enable-auto-merge")), JOB_ACTIONS_READ], + ]) { const names = list.map((s) => s.name); assert.ok(names.indexOf(read) >= 0 && names.indexOf(read) < names.indexOf("Start the run cache from them")); const block = step(read, list); assert.match(block, /run: node \.base\/\.github\/scripts\/pr-merge\/carry-run-cache\.mjs read\n/); - assert.ok(block.includes(`CARRY_TO: ${carried}\n`) && block.includes("ACTIONS_TOKEN: ${{ github.token }}\n")); + assert.ok(block.includes(`CARRY_TO: ${carried}\n`) && block.includes(token), block); assert.match(block, /\n {8}timeout-minutes: 2\n/); const start = step("Start the run cache from them", list); assert.ok(start.includes(`CARRY_FROM: ${carried}\n`) && start.includes(`CARRY_TO: ${runCache}\n`)); @@ -759,7 +770,7 @@ test("the gate reads the head-ref map the last run uploaded and uploads the next const mapOut = "${{ runner.temp }}/head-refs/head-refs.json"; const read = step("Read the head refs the last run kept"); assert.match(read, /run: node \.base\/\.github\/scripts\/pr-merge\/head-ref-map\.mjs read\n/); - assert.ok(read.includes(`HEAD_REFS_PATH: ${mapIn}\n`) && read.includes("ACTIONS_TOKEN: ${{ github.token }}\n")); + assert.ok(read.includes(`HEAD_REFS_PATH: ${mapIn}\n`) && read.includes(LANE_ACTIONS_READ)); const gate = step("Run the merge gate on each candidate"); assert.ok(gate.includes(`BABYSIT_VERIFY_HEAD_REFS: ${mapIn}\n`)); const keep = step("Keep the head refs the gate read"); @@ -796,12 +807,15 @@ test("every post-merge check reads the lane records, and only the merge job uplo const file = "${{ runner.temp }}/lane-records.json"; const out = "${{ runner.temp }}/lane-records/lane-records.json"; const early = stepsOf(jobBlock("dispatch-post-merge-runs")); - for (const list of [steps, early]) { + for (const [list, token] of [ + [steps, LANE_ACTIONS_READ], + [early, JOB_ACTIONS_READ], + ]) { const names = list.map((s) => s.name); const read = step("Read the lane records the last run kept", list); assert.ok(names.indexOf("Read the lane records the last run kept") < names.indexOf("Check earlier lane merges")); assert.match(read, /run: node \.base\/\.github\/scripts\/pr-merge\/lane-records\.mjs read\n/); - assert.ok(read.includes(`LANE_RECORDS_PATH: ${file}\n`) && read.includes("ACTIONS_TOKEN: ${{ github.token }}\n")); + assert.ok(read.includes(`LANE_RECORDS_PATH: ${file}\n`) && read.includes(token), read); assert.match(read, /\n {8}continue-on-error: true\n/); assert.ok(step("Check earlier lane merges", list).includes(`BABYSIT_POSTMERGE_LANE_RECORDS: ${file}\n`)); } @@ -1282,16 +1296,32 @@ test("a failed lane merge reruns the check with --remediate under the lane token assert.match(runScript("Check earlier lane merges"), /^echo "code=\$code" >>"\$GITHUB_OUTPUT"$/m); }); -// Only --remediate writes, so it alone takes the lane token. The read-only -// check and the gate's evidence reads spend the job's own token, which this -// job grants no write. -test("the read-only post-merge check and the gate's reads use the job's read-only token", () => { - assert.match(step("Check earlier lane merges"), /\n {10}GH_TOKEN: \$\{\{ github\.token \}\}\n/); +test("the post-merge check and the gate read with the lane token, checks with the job's", () => { + for (const name of ["Check earlier lane merges", "Skip refusals whose inputs have not changed", "Run the merge gate on each candidate"]) { + const block = step(name); + assert.match(block, /\n {10}GH_TOKEN: \$\{\{ steps\.lane-token\.outputs\.token \}\}\n/, name); + assert.match(block, /\n {10}API_BUDGET_TOKEN: lanes-app\n/, name); + assert.match(block, /\n {10}BABYSIT_JOB_GH_TOKEN: \$\{\{ github\.token \}\}\n/, name); + assert.match(block, /\n {10}API_BUDGET_OVERRIDE_TOKEN: github-token\n/, name); + assert.doesNotMatch(block, /BABYSIT_VERIFY_GH_TOKEN: \$\{\{ github\.token \}\}/, name); + } assert.doesNotMatch(runScript("Check earlier lane merges"), /--remediate/); assert.match(step("Record a failed lane merge"), /\n {10}GH_TOKEN: \$\{\{ steps\.lane-token\.outputs\.token \}\}\n/); const gate = step("Run the merge gate on each candidate"); - assert.match(gate, /\n {10}GH_TOKEN: \$\{\{ steps\.lane-token\.outputs\.token \}\}\n/); - assert.match(gate, /\n {10}BABYSIT_VERIFY_GH_TOKEN: \$\{\{ github\.token \}\}\n/); + assert.match(gate, /\n {10}BABYSIT_VERIFY_GH_TOKEN: \$\{\{ steps\.lane-token\.outputs\.token \}\}\n/); + const listing = step("List the candidate PRs"); + assert.match(listing, /\n {10}GH_TOKEN: \$\{\{ steps\.lane-token\.outputs\.token \}\}\n/); + assert.match(listing, /\n {10}API_BUDGET_TOKEN: lanes-app\n/); + assert.match(runScript("List the candidate PRs"), /^api_budget_wrap_gh lanes-app$/m); + for (const name of [ + "Start after the candidate the last run reached", + "Read the head refs the last run kept", + "Read the verdict reads the last run kept", + "Read the lane records the last run kept", + ]) { + assert.ok(step(name).includes(LANE_ACTIONS_READ), name); + assert.match(step(name), /\n {10}API_BUDGET_TOKEN: lanes-app\n/, name); + } const permissions = /\n permissions:\n([\s\S]*?)\n [a-z-]+:/.exec(job)[1]; const grants = [...permissions.matchAll(/^ {6}([a-z-]+): ([a-z]+)/gm)].map((m) => `${m[1]}: ${m[2]}`); assert.deepEqual(grants.filter((g) => g.endsWith(": write")), ["id-token: write"]); @@ -1636,7 +1666,7 @@ test("the skip step runs just before the gate and its record between the carry a assert.match(filter, /\n {8}continue-on-error: true\n/); assert.match(filter, /\n {8}if: steps\.lane-token\.outputs\.token != '' && steps\.candidates\.outputs\.listed == 'true'\n/); assert.match(filter, /GH_TOKEN: \$\{\{ steps\.lane-token\.outputs\.token \}\}/); - assert.match(filter, /BABYSIT_VERIFY_GH_TOKEN: \$\{\{ github\.token \}\}/); + assert.match(filter, /BABYSIT_VERIFY_GH_TOKEN: \$\{\{ steps\.lane-token\.outputs\.token \}\}/); // The listing it reads is saved where the gate's first candidate looks. const listing = "BABYSIT_VERIFY_LISTING: ${{ runner.temp }}/verify-listing.json\n"; assert.ok(filter.includes(listing) && step("Run the merge gate on each candidate").includes(listing)); diff --git a/.github/scripts/pr-merge/rotation.mjs b/.github/scripts/pr-merge/rotation.mjs index b8a1dc9c8f5..e655855842e 100755 --- a/.github/scripts/pr-merge/rotation.mjs +++ b/.github/scripts/pr-merge/rotation.mjs @@ -18,7 +18,7 @@ // leaves the listing order (ascending PR number) and warns. // // Environment: -// ACTIONS_TOKEN the job's GITHUB_TOKEN (actions: read) +// ACTIONS_TOKEN a token with Actions read (https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps) // GITHUB_REPOSITORY owner/repo // GITHUB_RUN_ID this run, which has no cursor yet // CANDIDATES_PATH candidates.json, rewritten in rotated order diff --git a/.github/scripts/pr-merge/workflow.test.mjs b/.github/scripts/pr-merge/workflow.test.mjs index c202bb9fd48..38641202239 100644 --- a/.github/scripts/pr-merge/workflow.test.mjs +++ b/.github/scripts/pr-merge/workflow.test.mjs @@ -1271,7 +1271,7 @@ test("every createGitHub step that calls GitHub with the job token names the buc // The sweep-count step's one read, the run's start, goes through the wrapped // gh, so the job-end notice counts it; sweep-summary.mjs calls nothing. -test("the merge job's sweep-count read leaves one github-token reading", () => { +test("the merge job's sweep-count read leaves one lanes-app reading", () => { const step = /- name: Count the sweep's refusals\n([\s\S]*?)(?=\n {6}- name: )/.exec(job("merge"))[1]; const run = /\n {8}run: \|\n((?: {10}.*\n|\s*\n)+)/.exec(step)[1].replace(/^ {10}/gm, ""); const dir = tempDir("pr-merge-sweep-count-"); @@ -1296,7 +1296,7 @@ while [ $# -gt 0 ]; do if [ "$1" = --jq ]; then echo '{"run_started_at":"2026-10 }); assert.equal(r.status, 0, r.stdout + r.stderr); assert.equal(readFileSync(join(dir, "started"), "utf8"), "2026-10-28T00:00:00Z\n"); - assert.equal(readFileSync(join(dir, "api-budget", "github-token"), "utf8"), "200 5000 4000 1000 9999999999 core repos/{repo}/actions/runs/{n}\n"); + assert.equal(readFileSync(join(dir, "api-budget", "lanes-app"), "utf8"), "200 5000 4000 1000 9999999999 core repos/{repo}/actions/runs/{n}\n"); } finally { rmSync(dir, { recursive: true, force: true }); } diff --git a/.github/scripts/pr-verify/workflow.test.mjs b/.github/scripts/pr-verify/workflow.test.mjs index dae7c90af31..64cde9dcdba 100644 --- a/.github/scripts/pr-verify/workflow.test.mjs +++ b/.github/scripts/pr-verify/workflow.test.mjs @@ -269,15 +269,16 @@ test("the resolver runs before the trigger gate, and the agree step only after t } }); -test("pr-merge.yml gives the gate an Actions token for the verdict reads only", () => { - // babysit_verify_evidence.py reads BABYSIT_VERIFY_GH_TOKEN; the lane token - // the gate runs gh with holds no Actions permission. +test("pr-merge.yml's gate reads its verdicts with the lane token and checks with the job's", () => { const merge = readFileSync(new URL("../../workflows/pr-merge.yml", import.meta.url), "utf8"); const job = /\n merge:\n([\s\S]*?)\n [a-z-]+:\n/.exec(merge)[1]; - assert.match(job, /\n {6}actions: read\n/); + assert.match(job, /\n {6}checks: read\n/); const gate = /- name: Run the merge gate on each candidate\n([\s\S]*?)\n {6}- name: /.exec(job)[1]; assert.match(gate, /\n {10}GH_TOKEN: \$\{\{ steps\.lane-token\.outputs\.token \}\}\n/); - assert.match(gate, /\n {10}BABYSIT_VERIFY_GH_TOKEN: \$\{\{ github\.token \}\}\n/); + assert.match(gate, /\n {10}BABYSIT_VERIFY_GH_TOKEN: \$\{\{ steps\.lane-token\.outputs\.token \}\}\n/); + assert.match(gate, /\n {10}BABYSIT_JOB_GH_TOKEN: \$\{\{ github\.token \}\}\n/); + assert.match(gate, /\n {10}API_BUDGET_TOKEN: lanes-app\n/); + assert.match(gate, /\n {10}API_BUDGET_OVERRIDE_TOKEN: github-token\n/); }); test("the concurrency group is per PR and head and never cancels a running judgment", () => { diff --git a/.github/workflows/pr-merge.yml b/.github/workflows/pr-merge.yml index cfbf985d115..faca52579cd 100644 --- a/.github/workflows/pr-merge.yml +++ b/.github/workflows/pr-merge.yml @@ -662,7 +662,8 @@ jobs: if-no-files-found: error # A red attempt 1 of a full run this workflow dispatched waits for its - # one re-run, and the lanes App holds no Actions permission to start it. + # one re-run, and the lanes App holds no Actions write to start it + # (https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps). # This job starts it with its own token, one run per job, and records it # as pr-merge-rerun--attempt-2, which the post-merge check needs # before it counts a github-actions[bot] attempt 2 of a lane-dispatched @@ -988,13 +989,15 @@ jobs: timeout-minutes: 48 permissions: contents: read # check out main - pull-requests: read # list the open PRs - # The gate's pr-verify verdict reads (artifact listing, run records, - # download) and its review-evidence reads, which stay on this token; - # the lane token holds no Actions permission. + pull-requests: read + # The who and superseded reads before the lane token is minted, and the + # re-fire and escalation steps' run reads beside their checks reads; + # the job's other Actions reads use the lane token's actions read + # (owner decision D398; https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps). actions: read - # Read a refused lane run's annotations and its PR head's checks. Never - # write: the report-gate-checks job below writes the check runs. + # Check runs, check suites and annotations, which the lane token's grant + # cannot read (https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps). Never write: the + # report-gate-checks job below writes the check runs. checks: read issues: read # the post-merge check's demotion records, read with this job's token statuses: read # a lane stop's pr-unblock status (the lanes App holds no statuses permission) @@ -1096,7 +1099,6 @@ jobs: if: steps.kill.outputs.proceed == 'true' env: API_BUDGET_TOKEN: github-token - # The lane token holds no Actions permission. ACTIONS_TOKEN: ${{ github.token }} ACTOR_ID: ${{ github.actor_id }} TRUSTED_ACTORS_PATH: .base/.github/standards/trusted-actors/trusted-actors.json @@ -1115,7 +1117,6 @@ jobs: continue-on-error: true env: API_BUDGET_TOKEN: github-token - # The lane token holds no Actions permission. ACTIONS_TOKEN: ${{ github.token }} TRUSTED_ACTORS_PATH: .base/.github/standards/trusted-actors/trusted-actors.json run: node .base/.github/scripts/pr-merge/superseded.mjs @@ -1222,13 +1223,13 @@ jobs: # the tracker binding in docs/conventions/work-items.yaml, `needs-human` # by default, or a hold in the body) is set aside here before it costs # lane-token calls (babysit_merge_prefilter.py); the summary still - # reports it. Read with the job's own read-only token. + # reports it. Read with the lane token (https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps). - name: List the candidate PRs id: candidates if: steps.lane-token.outputs.token != '' env: - GH_TOKEN: ${{ github.token }} - API_BUDGET_TOKEN: github-token + GH_TOKEN: ${{ steps.lane-token.outputs.token }} + API_BUDGET_TOKEN: lanes-app # A rate limit past the guard's budget refuses the listing with a # notice, not an error (api-budget.bash), and retry_call's unknown # holds the step green with `held`. @@ -1286,7 +1287,7 @@ jobs: . .base/.github/actions/log-api-budget/api-budget.bash . .base/.github/scripts/pr-merge/rate-stop.bash . .base/.github/scripts/pr-merge/retry-call.bash - api_budget_wrap_gh github-token + api_budget_wrap_gh lanes-app listing="$RUNNER_TEMP/listing.json" page_file="$RUNNER_TEMP/listing-page.json" # One GraphQL list of every open pull request into main, 100 a page @@ -1400,11 +1401,11 @@ jobs: # PR_MERGE_READS_PATH (rotation.mjs sharedReads); each still picks and # checks its own run and file. - name: Start after the candidate the last run reached - if: steps.candidates.outputs.listed == 'true' + if: steps.lane-token.outputs.token != '' && steps.candidates.outputs.listed == 'true' continue-on-error: true env: - API_BUDGET_TOKEN: github-token - ACTIONS_TOKEN: ${{ github.token }} + API_BUDGET_TOKEN: lanes-app + ACTIONS_TOKEN: ${{ steps.lane-token.outputs.token }} CANDIDATES_PATH: ${{ runner.temp }}/candidates.json PR_MERGE_READS_PATH: ${{ runner.temp }}/pr-merge-reads.json run: node .base/.github/scripts/pr-merge/rotation.mjs @@ -1416,11 +1417,11 @@ jobs: # steps could upload it. Any error leaves no map, and the gate downloads # each untied FAIL. Rules: .github/scripts/pr-merge/head-ref-map.mjs. - name: Read the head refs the last run kept - if: steps.candidates.outputs.listed == 'true' + if: steps.lane-token.outputs.token != '' && steps.candidates.outputs.listed == 'true' continue-on-error: true env: - API_BUDGET_TOKEN: github-token - ACTIONS_TOKEN: ${{ github.token }} + API_BUDGET_TOKEN: lanes-app + ACTIONS_TOKEN: ${{ steps.lane-token.outputs.token }} HEAD_REFS_PATH: ${{ runner.temp }}/head-refs-in.json PR_MERGE_READS_PATH: ${{ runner.temp }}/pr-merge-reads.json run: node .base/.github/scripts/pr-merge/head-ref-map.mjs read @@ -1439,12 +1440,12 @@ jobs: # listing still matches. Any error leaves the run cache empty, and the # gate reads GitHub. Rules: .github/scripts/pr-merge/carry-run-cache.mjs. - name: Read the verdict reads the last run kept - if: steps.candidates.outputs.listed == 'true' + if: steps.lane-token.outputs.token != '' && steps.candidates.outputs.listed == 'true' continue-on-error: true timeout-minutes: 2 env: - API_BUDGET_TOKEN: github-token - ACTIONS_TOKEN: ${{ github.token }} + API_BUDGET_TOKEN: lanes-app + ACTIONS_TOKEN: ${{ steps.lane-token.outputs.token }} CARRY_TO: ${{ runner.temp }}/pr-merge-carried.json PR_MERGE_READS_PATH: ${{ runner.temp }}/pr-merge-reads.json run: node .base/.github/scripts/pr-merge/carry-run-cache.mjs read @@ -1466,8 +1467,8 @@ jobs: if: steps.lane-token.outputs.token != '' && steps.candidates.outputs.listed == 'true' continue-on-error: true env: - API_BUDGET_TOKEN: github-token - ACTIONS_TOKEN: ${{ github.token }} + API_BUDGET_TOKEN: lanes-app + ACTIONS_TOKEN: ${{ steps.lane-token.outputs.token }} LANE_RECORDS_PATH: ${{ runner.temp }}/lane-records.json PR_MERGE_READS_PATH: ${{ runner.temp }}/pr-merge-reads.json run: node .base/.github/scripts/pr-merge/lane-records.mjs read @@ -1486,8 +1487,8 @@ jobs: # failed listing nor a long gate loop holds that run back. A held # listing skips this step and the record below: that job's check of # this run stands, and the next run that lists files any record. - # Read-only, so it reads with this job's own token, off the lane App's - # quota; only --remediate below needs the lane token. + # Read-only; it reads with the lane token, and its check-run and + # annotation reads with the job's own token (https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps). # The same check of this run's dispatch-post-merge-runs job, with the same # inputs, is reused instead when it judged (exit 0, 1 or 5), the check's # code here reads as at the commit it ran, and the lane room's reuse @@ -1514,8 +1515,10 @@ jobs: if: steps.lane-token.outputs.token != '' && steps.candidates.outputs.listed == 'true' env: MAIN_TIP_SHA: ${{ steps.tip.outputs.sha }} - GH_TOKEN: ${{ github.token }} - API_BUDGET_TOKEN: github-token + GH_TOKEN: ${{ steps.lane-token.outputs.token }} + API_BUDGET_TOKEN: lanes-app + BABYSIT_JOB_GH_TOKEN: ${{ github.token }} + API_BUDGET_OVERRIDE_TOKEN: github-token BABYSIT_POSTMERGE_LANE_RECORDS: ${{ runner.temp }}/lane-records.json # The completed attempts kept beside dispatch-post-merge-runs's report, # which the fresh check answers with no read (ATTEMPTS_ENV). @@ -1574,7 +1577,7 @@ jobs: # under the lane token, which disarms the lane's armed pull requests, # dequeues the lane's merge-queue entries and files the record (or # comments on it, reopening it on a new sighting). The lane token holds - # no Actions permission, so the re-run and dispatch --remediate also + # no Actions write (https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps), so the re-run and dispatch --remediate also # attempts fail here and are reported as a write failure (exit 4); the # dispatch-post-merge-runs job starts those. Live mode only. A held listing # skips it, as it skips the check above: the job files and dequeues @@ -1608,7 +1611,7 @@ jobs: elif jq -e '[.remediation.errors[] | select(startswith("demotion issue:") or startswith("dequeue:") or startswith("disarm:"))] | length > 0' "$report" >/dev/null; then echo "::error::the post-merge remediation could not file the demotion record, dequeue the lane's entries or disarm its pull requests; see its report above" elif [ "$code" -eq 4 ]; then - echo "::warning::the post-merge remediation exited $code (re-run or dispatch refused: the lane token has no Actions permission)" + echo "::warning::the post-merge remediation exited $code (re-run or dispatch refused: the lane token has no Actions write)" fi # Each lane merge the check above judged verified from a readable read, @@ -1687,7 +1690,8 @@ jobs: GH_TOKEN: ${{ steps.lane-token.outputs.token }} API_BUDGET_TOKEN: lanes-app API_BUDGET_OVERRIDE_TOKEN: github-token - BABYSIT_VERIFY_GH_TOKEN: ${{ github.token }} + BABYSIT_VERIFY_GH_TOKEN: ${{ steps.lane-token.outputs.token }} + BABYSIT_JOB_GH_TOKEN: ${{ github.token }} BABYSIT_VERIFY_LISTING: ${{ runner.temp }}/verify-listing.json REPO: ${{ github.repository }} RUNG_CAP: ${{ vars.CLAUDE_LANES_MERGE_RUNG_CAP }} @@ -1732,13 +1736,13 @@ jobs: if: steps.lane-token.outputs.token != '' && steps.candidates.outputs.listed == 'true' env: GH_TOKEN: ${{ steps.lane-token.outputs.token }} - # The verdict reader's Actions calls, the review-evidence reads - # (timeline, comments, lane runs, attempts, jobs, annotations) and - # the whole-review request's limit reads use this, as their own - # GH_TOKEN (babysit_verify_evidence.py, babysit_merge.py - # _lane_evidence, babysit_whole_review.py); every write keeps the - # lane token. The job runs main's code alone, never a PR's. - BABYSIT_VERIFY_GH_TOKEN: ${{ github.token }} + # The verdict and review-evidence reads use the lane token (owner + # decision D398); check-run, check-suite, annotation and status reads, + # which its grant cannot make (https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps), + # and the whole-review job-bucket reads use BABYSIT_JOB_GH_TOKEN. + # The job runs main's code alone, never a PR's. + BABYSIT_VERIFY_GH_TOKEN: ${{ steps.lane-token.outputs.token }} + BABYSIT_JOB_GH_TOKEN: ${{ github.token }} # Name the two tokens' rate-limit readings (api-budget.bash). API_BUDGET_TOKEN: lanes-app API_BUDGET_OVERRIDE_TOKEN: github-token @@ -2078,11 +2082,11 @@ jobs: # is split here so this script, which the log echoes, never matches a # grep for it. Rules: .github/scripts/pr-merge/sweep-summary.mjs. - name: Count the sweep's refusals - if: always() && (steps.gate.outcome != 'skipped' || steps.candidates.outputs.held == 'true') + if: always() && steps.lane-token.outputs.token != '' && (steps.gate.outcome != 'skipped' || steps.candidates.outputs.held == 'true') continue-on-error: true timeout-minutes: 1 env: - GH_TOKEN: ${{ github.token }} + GH_TOKEN: ${{ steps.lane-token.outputs.token }} REPO: ${{ github.repository }} EVENT: ${{ github.event_name }} LIVE: ${{ steps.mode.outputs.live }} @@ -2099,7 +2103,7 @@ jobs: set -euo pipefail # The read goes through the wrapped gh, so the job-end notice counts it. . .base/.github/actions/log-api-budget/api-budget.bash - api_budget_wrap_gh github-token + api_budget_wrap_gh lanes-app # After the gate's rate-limit stop or a held listing, no read: the # start stays unknown. RUN_STARTED_AT= diff --git a/docs/conventions/pr-pipeline/README.md b/docs/conventions/pr-pipeline/README.md index ba98deac865..683a648daed 100644 --- a/docs/conventions/pr-pipeline/README.md +++ b/docs/conventions/pr-pipeline/README.md @@ -3199,18 +3199,26 @@ one whole listing an over-count takes starts paging, a later reader in the job w over-count refuses without another, even when that listing failed transiently or on a caller's limit (then with the caller-limit prefix). A refusal before paging leaves that listing to the next reader. -The lane token holds no Actions permission, so pr-merge.yml grants its job `actions: read` and passes the job's `GITHUB_TOKEN` as +The merge job's lane token carries `actions: read` (`lane-rules.json` gives the `merge-pr` grant +alone that scope, and the broker refuses it to any other activity), and pr-merge.yml passes it as `BABYSIT_VERIFY_GH_TOKEN`; the reader uses it as `GH_TOKEN` for the artifact listing, the run records, the download of a verdict.json (by the listed artifact's id, one request where `gh run download` lists the run's artifacts first) and the compare of a run's head to main (a `contents: read` call). The gate's -review-evidence reads use it too: the timeline, the comments, and the lane runs with their attempts, -jobs and annotations. All of these reads stay on `GITHUB_TOKEN`: none switches to the lane token, -whatever `GITHUB_TOKEN`'s budget, since GitHub's Terms of Service bar sharing tokens to exceed its -rate limits ([owner decision](https://github.com/melodic-software/claude-code-plugins/issues/9297#issuecomment-6368281689)). -A read refused for a rate limit is not retried: the candidate's lanes read `evidence-missing`, it -holds, and the next run reads again. An untied FAIL whose record cannot be read refuses the run's later candidates through `BABYSIT_RUN_CACHE` without another -download; the next run reads it again. `GITHUB_TOKEN`'s pool is shared with the full-run dispatch and the post-merge checks. Every other call, every write -included, keeps the lane token. That job checks out only main and runs no pull request code. +review-evidence reads use it too: the timeline, the comments, and the lane runs with their attempts +and jobs. Every read that needs the Checks or Commit statuses permission, which the lane grant +lacks (check runs, check suites, annotations, commit statuses), goes under the job's own +`GITHUB_TOKEN`, passed as `BABYSIT_JOB_GH_TOKEN` (`babysit_gh.py` `job_token_env`), as do the +whole-review request's job-bucket and running-job reads. Each read has one designed token, named to +the rate guard as `lanes-app` or `github-token`, and none moves to the other token when its own pool +runs low. Owner decision D398 (2026-11-18) moved these reads to the lanes App's allowance, +replacing the [earlier decision](https://github.com/melodic-software/claude-code-plugins/issues/9297#issuecomment-6368281689) +that kept them on `GITHUB_TOKEN`. A read refused for a rate +limit is not retried: the candidate's lanes read `evidence-missing`, it holds, and the next run +reads again. An untied FAIL whose record cannot be read refuses the run's later candidates through `BABYSIT_RUN_CACHE` without another +download; the next run reads it again. The candidate listing, the carried artifacts and the +post-merge check read with the lane token too; the who and superseded reads before the mint, the +re-fire and escalation-clear steps' run and check reads, and every write the lane token cannot make +stay on `GITHUB_TOKEN`. That job checks out only main and runs no pull request code. The post-merge check's lane records (`pr-merge-dispatched-`, `pr-merge-rerun--attempt-2`) carry from run to run as the `pr-merge-lane-records` artifact diff --git a/plugins/source-control/skills/babysit-prs/scripts/babysit_gh.py b/plugins/source-control/skills/babysit-prs/scripts/babysit_gh.py index 4e37608b3d4..701ba2b81a3 100755 --- a/plugins/source-control/skills/babysit-prs/scripts/babysit_gh.py +++ b/plugins/source-control/skills/babysit-prs/scripts/babysit_gh.py @@ -366,6 +366,7 @@ def _send( one whose headers hold a Retry-After: `_guard_response` stops the process on a value in seconds, and any other form returns as the failed read.""" global _read_retries_sent + env_overrides = job_token_env(args, env_overrides) left = _default_timeout_seconds if timeout_seconds is None else timeout_seconds deadline = _retry_clock() + left for attempt in range(1, READ_ATTEMPTS): @@ -400,6 +401,32 @@ def _send( return proc, headers +# The job's own token (GITHUB_TOKEN), for the reads an App token granted no +# Checks or Commit statuses permission cannot make: https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps +JOB_TOKEN_ENV = "BABYSIT_JOB_GH_TOKEN" +_JOB_TOKEN_ROUTE = re.compile( + r"^/?repos/[^/?]+/[^/?]+/(?:check-runs|check-suites" + r"|commits/[^/?]+/(?:check-runs|check-suites|statuses|status))(?:[/?]|$)" +) + + +def job_token_env( + args: list[str], env_overrides: Mapping[str, str] | None +) -> Mapping[str, str] | None: + """`env_overrides` with GH_TOKEN set to JOB_TOKEN_ENV's token for a REST + read of check runs, check suites or commit statuses, when the job sets + one; unchanged for every other call.""" + token = os.environ.get(JOB_TOKEN_ENV) + if ( + not token + or args[:1] != ["api"] + or _is_write(args) + or not _JOB_TOKEN_ROUTE.match(_endpoint(args)) + ): + return env_overrides + return {**(env_overrides or {}), "GH_TOKEN": token} + + def _send_once( args: list[str], *, @@ -901,8 +928,13 @@ def _limits_pool(args: list[str], env_overrides: Mapping[str, str] | None) -> st def _budget_token_name(env_overrides: Mapping[str, str] | None) -> str: """The token name the job gives for a call: API_BUDGET_OVERRIDE_TOKEN for a - call carrying its own GH_TOKEN, else API_BUDGET_TOKEN; empty when unset.""" - own = bool(env_overrides and "GH_TOKEN" in env_overrides) + call carrying a GH_TOKEN other than the process's, else API_BUDGET_TOKEN; + empty when unset.""" + own = bool( + env_overrides + and "GH_TOKEN" in env_overrides + and env_overrides["GH_TOKEN"] != os.environ.get("GH_TOKEN") + ) return os.environ.get( "API_BUDGET_OVERRIDE_TOKEN" if own else "API_BUDGET_TOKEN", "" ) diff --git a/plugins/source-control/skills/babysit-prs/scripts/babysit_merge.py b/plugins/source-control/skills/babysit-prs/scripts/babysit_merge.py index 0f35e58caaa..e9eb2a03425 100755 --- a/plugins/source-control/skills/babysit-prs/scripts/babysit_merge.py +++ b/plugins/source-control/skills/babysit-prs/scripts/babysit_merge.py @@ -3229,10 +3229,9 @@ def _lane_evidence( more commits than the list returns, raises `HeadPusherUnproven`. A retargeted base unbinds every lane. The timeline, the comments and the lane runs are read under the verdict - reader's token when one is set, keeping them off the lane App's quota; - every read here is a GET. A refused read, a rate limit included, raises - and is never made again with the lane token: GitHub's Terms of Service - bar sharing tokens to exceed its rate limits, so the candidate holds.""" + reader's token when one is set; every read here is a GET. A refused + read, a rate limit included, raises and is never made again with + another token, so the candidate holds.""" head = json_object(pr.get("head")) token = os.environ.get(verify_evidence.TOKEN_ENV) read_env = {"GH_TOKEN": token} if token else None diff --git a/plugins/source-control/skills/babysit-prs/scripts/babysit_whole_review.py b/plugins/source-control/skills/babysit-prs/scripts/babysit_whole_review.py index a44285692a8..131f078d01d 100755 --- a/plugins/source-control/skills/babysit-prs/scripts/babysit_whole_review.py +++ b/plugins/source-control/skills/babysit-prs/scripts/babysit_whole_review.py @@ -39,6 +39,7 @@ from collections.abc import Mapping, Sequence from typing import Any +import babysit_gh import babysit_risk from babysit_gh import fetch_paginated_api, gh_capture @@ -57,7 +58,7 @@ CONVERT_SKEW = timedelta(minutes=1) SPENT_ENV = "BABYSIT_WHOLE_REVIEW_SPENT" # The job's own token (GITHUB_TOKEN), which also reads the runs. -JOB_TOKEN_ENV = "BABYSIT_VERIFY_GH_TOKEN" +JOB_TOKEN_ENVS = (babysit_gh.JOB_TOKEN_ENV, "BABYSIT_VERIFY_GH_TOKEN") MAX_RUNNING_JOBS = 35 # The share of each rate-limit bucket that must be left: 1,500 of 5,000, 300 # of GITHUB_TOKEN's 1,000 outside GitHub Enterprise Cloud. @@ -254,7 +255,7 @@ def limits(repo: str) -> str | None: return "sweep-limit" except OSError as exc: return f"sweep-claim: {exc}" - token = os.environ.get(JOB_TOKEN_ENV) + token = next((t for name in JOB_TOKEN_ENVS if (t := os.environ.get(name))), None) if not token: return "job-token-missing" job = {"GH_TOKEN": token} diff --git a/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_gh_api_budget.py b/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_gh_api_budget.py index 4117e862475..336709df63c 100644 --- a/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_gh_api_budget.py +++ b/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_gh_api_budget.py @@ -43,6 +43,7 @@ def setUp(self) -> None: self.dir = tempfile.mkdtemp() self.addCleanup(lambda: subprocess.run(["rm", "-rf", self.dir], check=False)) self.calls: list[list[str]] = [] + self.tokens: list[str | None] = [] def run_gh( self, @@ -55,8 +56,9 @@ def run_gh( check: bool = False, overrides: dict[str, str] | None = None, ) -> subprocess.CompletedProcess[Any]: - def fake(argv: list[str], **_kwargs: Any) -> subprocess.CompletedProcess[str]: + def fake(argv: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]: self.calls.append(argv) + self.tokens.append((kwargs.get("env_overrides") or {}).get("GH_TOKEN")) return subprocess.CompletedProcess(argv, code, stdout, stderr) with ( @@ -155,6 +157,66 @@ def test_a_call_with_its_own_token_reads_into_the_override_name(self) -> None: ) self.assertFalse(pathlib.Path(self.dir, "api-budget", "lanes-app").exists()) + def test_a_call_carrying_the_process_token_reads_into_the_token_name( + self, + ) -> None: + env = { + "RUNNER_TEMP": self.dir, + "GH_TOKEN": "lane", + "API_BUDGET_TOKEN": "lanes-app", + "API_BUDGET_OVERRIDE_TOKEN": "github-token", + } + self.run_gh( + HEAD.format(status=200, remaining=4100, used=900) + "{}", + ["api", "repos/o/r/actions/artifacts"], + env=env, + overrides={"GH_TOKEN": "lane"}, + ) + self.assertEqual( + self.readings("lanes-app"), + "200 5000 4100 900 1792748042 core repos/{repo}/actions/artifacts\n", + ) + self.assertFalse(pathlib.Path(self.dir, "api-budget", "github-token").exists()) + + def test_with_a_job_token_only_check_and_status_reads_go_under_it(self) -> None: + env = { + "RUNNER_TEMP": self.dir, + "GH_TOKEN": "lane", + gh.JOB_TOKEN_ENV: "job", + "API_BUDGET_TOKEN": "lanes-app", + "API_BUDGET_OVERRIDE_TOKEN": "github-token", + } + cases = [ + (["api", "repos/o/r/check-runs/5/annotations?per_page=100"], "job"), + (["api", "/repos/o/r/commits/abc/check-runs?filter=all"], "job"), + (["api", "repos/o/r/commits/abc/check-suites?app_id=15368"], "job"), + (["api", "repos/o/r/commits/abc/statuses?per_page=100"], "job"), + (["api", "repos/o/r/commits/abc/status"], "job"), + (["api", "repos/o/r/actions/runs/7/jobs"], None), + (["api", "repos/o/r/issues/3/timeline"], None), + (["api", "repos/o/r/commits/abc"], None), + (["api", "repos/o/r/check-runs", "-X", "POST", "-f", "name=x"], None), + (["api", "repos/o/r/statuses/abc", "-f", "state=success"], None), + ] + for args, token in cases: + self.run_gh( + HEAD.format(status=200, remaining=4100, used=900) + "{}", + args, + env=env, + ) + self.assertEqual(self.tokens, [token for _, token in cases]) + self.assertEqual(len(self.readings("github-token").splitlines()), 5) + self.assertEqual(len(self.readings("lanes-app").splitlines()), 5) + + def test_without_a_job_token_a_check_read_keeps_its_token(self) -> None: + self.run_gh( + "{}", + ["api", "repos/o/r/check-runs/5/annotations"], + env={"RUNNER_TEMP": self.dir, gh.JOB_TOKEN_ENV: ""}, + overrides={"GH_TOKEN": "verify"}, + ) + self.assertEqual(self.tokens, ["verify"]) + def test_without_a_token_name_or_for_a_non_api_call_no_reading_is_written( self, ) -> None: diff --git a/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_merge_unattended.py b/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_merge_unattended.py index eaea187fcd1..12181baf5e5 100644 --- a/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_merge_unattended.py +++ b/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_merge_unattended.py @@ -5086,8 +5086,8 @@ def test_linked_commits_bind_as_before(self) -> None: class LaneEvidenceReadToken(unittest.TestCase): """The gate's review-evidence reads (timeline, comments, lane runs and - their attempts, jobs and annotations) run under the job's read-only token - (`BABYSIT_VERIFY_GH_TOKEN`), off the lane App's quota; each is a GET.""" + their attempts, jobs and annotations) run under the verdict reader's + token (`BABYSIT_VERIFY_GH_TOKEN`) when one is set; each is a GET.""" RUN = 11 JOB = 21 diff --git a/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_verify_evidence.py b/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_verify_evidence.py index c0723b7d472..ee52ed1901d 100644 --- a/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_verify_evidence.py +++ b/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_verify_evidence.py @@ -3356,11 +3356,9 @@ def test_anyone_elses_entry_is_judged(self) -> None: class ActionsReadsUseTheActionsToken(unittest.TestCase): - """The lane token holds no Actions permission, so the artifact listing, - the run records and the download run under `BABYSIT_VERIFY_GH_TOKEN`, as - do the run heads' compares to the branch (a contents read the job token - serves, kept off the lane App's quota); every other read keeps the - process token.""" + """The artifact listing, the run records and the download run under + `BABYSIT_VERIFY_GH_TOKEN` when one is set, as do the run heads' compares + to the branch; every other read keeps the process token.""" ACTIONS = ("actions/artifacts?", "actions/runs/", "/zip", "/compare/") diff --git a/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_whole_review.py b/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_whole_review.py index 30511261c45..21d78dc044c 100644 --- a/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_whole_review.py +++ b/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_whole_review.py @@ -22,6 +22,7 @@ import babysit_whole_review as wr HEAD = "a" * 40 +VERIFY_TOKEN_ENV = "BABYSIT_VERIFY_GH_TOKEN" MED = risk.Reason("findings:claude-review", risk.Risk.MED, "1 open") HIGH = risk.Reason("security-finding", risk.Risk.HIGH, "1 open") CLEARS = risk.LaneEvidence("claude-security-review", True, None, 1, True) @@ -356,7 +357,7 @@ def _capture(self, args: list[str], env_overrides: Any = None) -> Any: def limits(self, env: dict[str, str] | None = None) -> str | None: env = ( - {wr.SPENT_ENV: self.spent, wr.JOB_TOKEN_ENV: "job"} if env is None else env + {wr.SPENT_ENV: self.spent, VERIFY_TOKEN_ENV: "job"} if env is None else env ) with ( mock.patch.dict(os.environ, env, clear=False), @@ -407,10 +408,28 @@ def test_outside_pr_merge_nothing_is_requested(self) -> None: def test_no_job_token(self) -> None: self.assertEqual( - self.limits({wr.SPENT_ENV: self.spent, wr.JOB_TOKEN_ENV: ""}), + self.limits({wr.SPENT_ENV: self.spent, VERIFY_TOKEN_ENV: ""}), "job-token-missing", ) + def test_the_job_token_reads_the_job_bucket_over_the_verdict_readers( + self, + ) -> None: + tokens: list[Any] = [] + + def capture(args: list[str], env_overrides: Any = None) -> Any: + tokens.append((env_overrides or {}).get("GH_TOKEN")) + return self._capture(args, env_overrides) + + env = {wr.SPENT_ENV: self.spent, VERIFY_TOKEN_ENV: "lane", "BABYSIT_JOB_GH_TOKEN": "job"} + with ( + mock.patch.dict(os.environ, env, clear=False), + mock.patch.object(wr, "gh_capture", side_effect=capture), + ): + self.assertIsNone(wr.limits("o/r")) + self.assertEqual(tokens[:2], [None, "job"]) + self.assertTrue(all(token == "job" for token in tokens[1:])) + def test_a_zero_limit_refuses(self) -> None: self.job_limit, self.job_left = 0, 0 self.assertEqual(self.limits(), "rate-limit:job:core:0/0") @@ -418,7 +437,7 @@ def test_a_zero_limit_refuses(self) -> None: def test_an_unreadable_limit_refuses(self) -> None: with ( mock.patch.dict( - os.environ, {wr.SPENT_ENV: self.spent, wr.JOB_TOKEN_ENV: "j"} + os.environ, {wr.SPENT_ENV: self.spent, VERIFY_TOKEN_ENV: "j"} ), mock.patch.object(wr, "gh_capture", return_value=done(code=1)), ): From c0c2aa89069b6541502dc21ee519bdc229a5c73c Mon Sep 17 00:00:00 2001 From: Kyle Sexton <153232337+kyle-sexton@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:00:42 -0500 Subject: [PATCH 2/2] fix(pr-merge): keep check reads on the lane token, route statuses only The gate already read check suites, check runs and annotations with the lane token on this public repository (run 44399528272: 5 check-suite reads under lanes-app, no unreadable refusal). Routing those reads to GITHUB_TOKEN moved calls back onto the pool this change drains, so BABYSIT_JOB_GH_TOKEN now carries commit-status reads only, which need the Commit statuses permission the lane grant lacks. Co-Authored-By: Claude Opus 5.5 --- .../feat-pr-merge-app-token-reads-7a68786b.md | 2 +- .../feat-pr-merge-app-token-reads-69d513d8.md | 2 +- .github/workflows/pr-merge.yml | 12 +++++----- docs/conventions/pr-pipeline/README.md | 10 ++++----- .../skills/babysit-prs/scripts/babysit_gh.py | 11 +++++----- .../tests/test_babysit_gh_api_budget.py | 22 +++++++++---------- 6 files changed, 29 insertions(+), 30 deletions(-) diff --git a/.changes/pr-pipeline/feat-pr-merge-app-token-reads-7a68786b.md b/.changes/pr-pipeline/feat-pr-merge-app-token-reads-7a68786b.md index cc20cddf554..daafe846ade 100644 --- a/.changes/pr-pipeline/feat-pr-merge-app-token-reads-7a68786b.md +++ b/.changes/pr-pipeline/feat-pr-merge-app-token-reads-7a68786b.md @@ -4,4 +4,4 @@ bump: minor ### Changed -- pr-merge's merge job reads through the lanes App's installation allowance instead of the repository's shared `GITHUB_TOKEN` pool (owner decision D398). `lane-rules.json` gives the `merge-pr` grant `actions: read`, which the token broker allows to that activity alone. The candidate listing, the carried artifact reads (cursor, head-ref map, verdict reads, lane records), the post-merge check, the skip filter, the gate's verdict and review-evidence reads and the sweep-count read use the lane token, named `lanes-app` to the rate guard. Check-run, check-suite, annotation and commit-status reads, the who and superseded reads before the mint, and the re-fire and escalation-clear steps stay on `GITHUB_TOKEN`. No read moves to the other token when its own pool runs low. +- pr-merge's merge job reads through the lanes App's installation allowance instead of the repository's shared `GITHUB_TOKEN` pool (owner decision D398). `lane-rules.json` gives the `merge-pr` grant `actions: read`, which the token broker allows to that activity alone. The candidate listing, the carried artifact reads (cursor, head-ref map, verdict reads, lane records), the post-merge check, the skip filter, the gate's verdict and review-evidence reads and the sweep-count read use the lane token, named `lanes-app` to the rate guard. Commit-status reads, the who and superseded reads before the mint, and the re-fire and escalation-clear steps stay on `GITHUB_TOKEN`. No read moves to the other token when its own pool runs low. diff --git a/.changes/source-control/feat-pr-merge-app-token-reads-69d513d8.md b/.changes/source-control/feat-pr-merge-app-token-reads-69d513d8.md index 95b70b02c14..5de656fbbad 100644 --- a/.changes/source-control/feat-pr-merge-app-token-reads-69d513d8.md +++ b/.changes/source-control/feat-pr-merge-app-token-reads-69d513d8.md @@ -4,7 +4,7 @@ bump: minor ### Added -- The babysit scripts' gh seam sends a REST read of check runs, check suites, annotations or commit statuses under `BABYSIT_JOB_GH_TOKEN` when a job sets it (`babysit_gh.job_token_env`), so a job whose process and verdict-reader token is an App token without the Checks or Commit statuses permission reads those with its own `GITHUB_TOKEN`. Writes and every other read keep their token. +- The babysit scripts' gh seam sends a REST read of a commit's statuses under `BABYSIT_JOB_GH_TOKEN` when a job sets it (`babysit_gh.job_token_env`), so a job whose process and verdict-reader token is an App token without the Commit statuses permission reads them with its own `GITHUB_TOKEN`. Writes and every other read keep their token. ### Changed diff --git a/.github/workflows/pr-merge.yml b/.github/workflows/pr-merge.yml index faca52579cd..ba2dd59cf42 100644 --- a/.github/workflows/pr-merge.yml +++ b/.github/workflows/pr-merge.yml @@ -995,8 +995,8 @@ jobs: # the job's other Actions reads use the lane token's actions read # (owner decision D398; https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps). actions: read - # Check runs, check suites and annotations, which the lane token's grant - # cannot read (https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps). Never write: the + # The re-fire and escalation-clear steps read check runs and annotations + # with this token (https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps). Never write: the # report-gate-checks job below writes the check runs. checks: read issues: read # the post-merge check's demotion records, read with this job's token @@ -1487,8 +1487,8 @@ jobs: # failed listing nor a long gate loop holds that run back. A held # listing skips this step and the record below: that job's check of # this run stands, and the next run that lists files any record. - # Read-only; it reads with the lane token, and its check-run and - # annotation reads with the job's own token (https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps). + # Read-only; it reads with the lane token, and any commit-status read + # with the job's own token (https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps). # The same check of this run's dispatch-post-merge-runs job, with the same # inputs, is reused instead when it judged (exit 0, 1 or 5), the check's # code here reads as at the commit it ran, and the lane room's reuse @@ -1737,8 +1737,8 @@ jobs: env: GH_TOKEN: ${{ steps.lane-token.outputs.token }} # The verdict and review-evidence reads use the lane token (owner - # decision D398); check-run, check-suite, annotation and status reads, - # which its grant cannot make (https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps), + # decision D398); commit-status reads, which its grant cannot make + # (https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps), # and the whole-review job-bucket reads use BABYSIT_JOB_GH_TOKEN. # The job runs main's code alone, never a PR's. BABYSIT_VERIFY_GH_TOKEN: ${{ steps.lane-token.outputs.token }} diff --git a/docs/conventions/pr-pipeline/README.md b/docs/conventions/pr-pipeline/README.md index 683a648daed..946b6268f1d 100644 --- a/docs/conventions/pr-pipeline/README.md +++ b/docs/conventions/pr-pipeline/README.md @@ -3204,11 +3204,11 @@ alone that scope, and the broker refuses it to any other activity), and pr-merge `BABYSIT_VERIFY_GH_TOKEN`; the reader uses it as `GH_TOKEN` for the artifact listing, the run records, the download of a verdict.json (by the listed artifact's id, one request where `gh run download` lists the run's artifacts first) and the compare of a run's head to main (a `contents: read` call). The gate's -review-evidence reads use it too: the timeline, the comments, and the lane runs with their attempts -and jobs. Every read that needs the Checks or Commit statuses permission, which the lane grant -lacks (check runs, check suites, annotations, commit statuses), goes under the job's own -`GITHUB_TOKEN`, passed as `BABYSIT_JOB_GH_TOKEN` (`babysit_gh.py` `job_token_env`), as do the -whole-review request's job-bucket and running-job reads. Each read has one designed token, named to +review-evidence reads use it too: the timeline, the comments, and the lane runs with their attempts, +jobs and annotations (the gate already read check runs and check suites with the lane token on +this public repository). A commit-status read, which needs the Commit statuses permission the lane grant lacks, +goes under the job's own `GITHUB_TOKEN`, passed as `BABYSIT_JOB_GH_TOKEN` (`babysit_gh.py` +`job_token_env`), as do the whole-review request's job-bucket and running-job reads. Each read has one designed token, named to the rate guard as `lanes-app` or `github-token`, and none moves to the other token when its own pool runs low. Owner decision D398 (2026-11-18) moved these reads to the lanes App's allowance, replacing the [earlier decision](https://github.com/melodic-software/claude-code-plugins/issues/9297#issuecomment-6368281689) diff --git a/plugins/source-control/skills/babysit-prs/scripts/babysit_gh.py b/plugins/source-control/skills/babysit-prs/scripts/babysit_gh.py index 701ba2b81a3..4b50e1318b4 100755 --- a/plugins/source-control/skills/babysit-prs/scripts/babysit_gh.py +++ b/plugins/source-control/skills/babysit-prs/scripts/babysit_gh.py @@ -401,12 +401,11 @@ def _send( return proc, headers -# The job's own token (GITHUB_TOKEN), for the reads an App token granted no -# Checks or Commit statuses permission cannot make: https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps +# The job's own token (GITHUB_TOKEN), for the commit-status reads an App token +# granted no Commit statuses permission cannot make: https://docs.github.com/en/rest/authentication/permissions-required-for-github-apps JOB_TOKEN_ENV = "BABYSIT_JOB_GH_TOKEN" _JOB_TOKEN_ROUTE = re.compile( - r"^/?repos/[^/?]+/[^/?]+/(?:check-runs|check-suites" - r"|commits/[^/?]+/(?:check-runs|check-suites|statuses|status))(?:[/?]|$)" + r"^/?repos/[^/?]+/[^/?]+/commits/[^/?]+/(?:statuses|status)(?:[/?]|$)" ) @@ -414,8 +413,8 @@ def job_token_env( args: list[str], env_overrides: Mapping[str, str] | None ) -> Mapping[str, str] | None: """`env_overrides` with GH_TOKEN set to JOB_TOKEN_ENV's token for a REST - read of check runs, check suites or commit statuses, when the job sets - one; unchanged for every other call.""" + read of a commit's statuses, when the job sets one; unchanged for every + other call.""" token = os.environ.get(JOB_TOKEN_ENV) if ( not token diff --git a/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_gh_api_budget.py b/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_gh_api_budget.py index 336709df63c..8d122c20896 100644 --- a/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_gh_api_budget.py +++ b/plugins/source-control/skills/babysit-prs/scripts/tests/test_babysit_gh_api_budget.py @@ -178,7 +178,7 @@ def test_a_call_carrying_the_process_token_reads_into_the_token_name( ) self.assertFalse(pathlib.Path(self.dir, "api-budget", "github-token").exists()) - def test_with_a_job_token_only_check_and_status_reads_go_under_it(self) -> None: + def test_with_a_job_token_only_commit_status_reads_go_under_it(self) -> None: env = { "RUNNER_TEMP": self.dir, "GH_TOKEN": "lane", @@ -187,16 +187,16 @@ def test_with_a_job_token_only_check_and_status_reads_go_under_it(self) -> None: "API_BUDGET_OVERRIDE_TOKEN": "github-token", } cases = [ - (["api", "repos/o/r/check-runs/5/annotations?per_page=100"], "job"), - (["api", "/repos/o/r/commits/abc/check-runs?filter=all"], "job"), - (["api", "repos/o/r/commits/abc/check-suites?app_id=15368"], "job"), (["api", "repos/o/r/commits/abc/statuses?per_page=100"], "job"), - (["api", "repos/o/r/commits/abc/status"], "job"), + (["api", "/repos/o/r/commits/abc/status"], "job"), + (["api", "repos/o/r/commits/abc/status?per_page=1"], "job"), + (["api", "repos/o/r/check-runs/5/annotations?per_page=100"], None), + (["api", "repos/o/r/commits/abc/check-suites?app_id=15368"], None), (["api", "repos/o/r/actions/runs/7/jobs"], None), - (["api", "repos/o/r/issues/3/timeline"], None), (["api", "repos/o/r/commits/abc"], None), - (["api", "repos/o/r/check-runs", "-X", "POST", "-f", "name=x"], None), + (["api", "repos/o/r/commits/abc/statusesx"], None), (["api", "repos/o/r/statuses/abc", "-f", "state=success"], None), + (["api", "repos/o/r/commits/abc/statuses", "-X", "POST"], None), ] for args, token in cases: self.run_gh( @@ -205,13 +205,13 @@ def test_with_a_job_token_only_check_and_status_reads_go_under_it(self) -> None: env=env, ) self.assertEqual(self.tokens, [token for _, token in cases]) - self.assertEqual(len(self.readings("github-token").splitlines()), 5) - self.assertEqual(len(self.readings("lanes-app").splitlines()), 5) + self.assertEqual(len(self.readings("github-token").splitlines()), 3) + self.assertEqual(len(self.readings("lanes-app").splitlines()), 7) - def test_without_a_job_token_a_check_read_keeps_its_token(self) -> None: + def test_without_a_job_token_a_status_read_keeps_its_token(self) -> None: self.run_gh( "{}", - ["api", "repos/o/r/check-runs/5/annotations"], + ["api", "repos/o/r/commits/abc/statuses"], env={"RUNNER_TEMP": self.dir, gh.JOB_TOKEN_ENV: ""}, overrides={"GH_TOKEN": "verify"}, )