From bc98875fdfe9e2a8f648779490de7278d59c8108 Mon Sep 17 00:00:00 2001 From: Jordan Ritter Date: Tue, 20 Oct 2026 12:06:10 -0700 Subject: [PATCH] fix(drift-sync): keep one rolling needs-human PR instead of a sibling per changeset The changeset key dedups an identical family set only. While a decision waited, every new or vanished family minted a new key, and the needs-human step opened a new PR beside the one still open: #406/#409/#411/#412 were open together (2026-09-02..09-08), and #475/#477/#481/#483/#484 (2026-09-22..10-02). Now a run whose set differs is written onto the open rolling PR: its commit is force-pushed (leased to the head that was inspected) onto that PR's branch, and the body is rewritten with this run's markers and notes. A new rolling PR lives on drift-needs-human/rolling--, a branch with no changeset key, because a key there would go stale once later runs rewrite the content. The rolling PR is rewritten only when it is still open, was opened by the drift bot (app/copilotkit-bot), and every commit on it is the bot's own. A human's commit leaves it alone and opens no sibling. A PR that cannot be read fails closed. The tests replay two runs through the real step body: run 1's pushed branch and created body become run 2's open PR. --- .github/workflows/fix-drift.yml | 206 ++++++++++++++++------ src/__tests__/fix-drift-workflow.test.ts | 212 ++++++++++++++++++++--- 2 files changed, 349 insertions(+), 69 deletions(-) diff --git a/.github/workflows/fix-drift.yml b/.github/workflows/fix-drift.yml index 5cd1ca30..eec7b1fa 100644 --- a/.github/workflows/fix-drift.yml +++ b/.github/workflows/fix-drift.yml @@ -949,6 +949,15 @@ jobs: # SECONDARY — skip when an open PR already proposes one of this run's note # files, matched by the per-note body marker. The Slack alert below still # fires either way. + # + # ONE ROLLING PR. The changeset key dedups an IDENTICAL family set only, so + # while a decision waited, every new or vanished family minted a new key and + # a new sibling PR beside the open one (#406..#412 and #475..#484 were each + # open together). So a run whose set differs is written onto the open + # ROLLING PR (force-push with lease, then a body rewrite) instead of opening + # another. That PR lives on `drift-needs-human/rolling--`, a + # branch with NO changeset key: its content changes, so a key in its name + # would go stale. - name: Persist needs-human note + open PR id: needs_human_pr if: steps.sync.outputs.reason == 'needs-human' && success() @@ -957,6 +966,9 @@ jobs: BASE_SHA: ${{ steps.gitcfg.outputs.base_sha }} RUN_ID: ${{ github.run_id }} CHANGESET_KEY: ${{ steps.sync.outputs.changeset_key }} + # The login gh reports for every PR the app token above opens (app slug + # `copilotkit-bot`; checked on #337..#541). The rolling-PR guard reads it. + DRIFT_BOT_LOGIN: app/copilotkit-bot run: | set -euo pipefail # ---- RECORD WHAT ACTUALLY HAPPENS IN HERE ---------------------------- @@ -1515,6 +1527,144 @@ jobs: exit 0 fi + # ---- THE ONE BODY WRITER ------------------------------------------------ + # Used to OPEN the rolling PR and to REWRITE it in place, so both carry + # exactly this run's markers and notes. + PR_BODY_FILE="${RUNNER_TEMP}/drift-needs-human-pr-body.md" + PR_TITLE="chore(drift-sync): needs-human model-family decision ($(date +%Y-%m-%d))" + write_nh_body() { + { + echo "## Needs a human decision (drift-sync)" + echo "" + echo "The deterministic, zero-LLM drift-sync found a model-family change it must" + echo "NOT auto-apply (a genuinely new/unclassified family, or a registry" + echo "structural mismatch). It wrote the note file(s) below and opened this PR so" + echo "the decision is REACHABLE in the repo." + echo "" + echo "This is the ONE open needs-human PR. A later run whose family set differs" + echo "rewrites this PR's branch and this body in place instead of opening another." + echo "A commit by anyone but the drift bot on this branch stops those rewrites." + echo "" + echo "> **Not auto-merged — a human decides, and applies it by hand.**" + echo "> For a *new-family* note, DO NOT expect merging this PR to apply anything:" + echo "> \`includeFamilies\` is checksum-pinned, and adding a family moves that pin," + echo "> which reds the freeze test gate-2 re-runs. drift-sync cannot re-pin — the" + echo "> gate-1 allowlist permits only \`model-registry.ts\` and \`drift-proposals/\`." + echo "> So a follow-up run would report \`gate-failed\`, not \`ok-applied\`." + echo ">" + echo "> The procedure that actually works, in ONE commit: add the family to" + echo "> \`includeFamilies\` (or \`excludeFamilies\` to reject), re-pin BOTH checksums," + echo "> resolve the note file(s) below, and update the offline \`/models\` wave." + echo "> Then close this PR. Prior examples: 72f85f8, 936b59c." + echo "" + echo "### Note file(s) in this PR" + echo "" + for note in "${NOTES[@]:-}"; do + [ -n "$note" ] || continue + echo "- \`${note}\`" + done + echo "" + # Emitted from the SINGLE MARKERS array built at the top of this step + # (the PRIMARY changeset marker plus one per note), so the set written + # here is by construction the set the marker self-heal re-asserts and + # the set the guards above match. + for m in "${MARKERS[@]}"; do + echo "" + done + echo "" + echo "### drift-sync outcome" + echo "" + echo '```' + cat "${RUNNER_TEMP}/drift-sync.log" 2>/dev/null || echo "(see drift-sync-log artifact)" + echo '```' + } > "$1" + } + + # ---- THE ROLLING PR: UPDATE IT, DO NOT OPEN A SIBLING -------------------- + # Reached only after DUP (no open PR carries this key), REJECTED (no human + # closed this key) and the no-new-commit return have all declined, so this + # run's set is un-proposed. If the bot's rolling PR is open, this run's + # commit goes onto ITS branch and its body is rewritten. Read from UNMERGED: + # the listing audited complete above, which holds every OPEN PR. The OLDEST + # open rolling PR opened by DRIFT_BOT_LOGIN is the one. + if [ -z "${DRIFT_BOT_LOGIN:-}" ]; then + echo "::error::DRIFT_BOT_LOGIN is not set, so this run cannot tell the drift bot's rolling PR from a human's — refusing to either rewrite one or open a sibling beside it." + exit 1 + fi + ROLLING_ERR="${RUNNER_TEMP}/drift-rolling-select.err" + if ! ROLLING="$(printf '%s' "$UNMERGED" | jq -c ' + [ .[] + | select(.state == "OPEN" + and ((.headRefName // "") | test("^drift-needs-human/rolling-[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]+$")) + and (((.author.login // "") | ascii_downcase) == ($ENV.DRIFT_BOT_LOGIN | ascii_downcase))) ] + | sort_by(.number) | .[0] // empty' 2>"$ROLLING_ERR")"; then + echo "::error::selecting the open rolling needs-human PR FAILED, so this run cannot tell whether to update it instead of opening another — refusing to risk a duplicate: $(cat "$ROLLING_ERR" 2>/dev/null)" + exit 1 + fi + if [ -n "$ROLLING" ]; then + R_NUMBER="$(printf '%s' "$ROLLING" | jq -r '.number')" + R_URL="$(printf '%s' "$ROLLING" | jq -r '.url')" + R_BRANCH="$(printf '%s' "$ROLLING" | jq -r '.headRefName')" + # THE GUARD, read LIVE: still OPEN, opened by the drift bot, on its rolling + # branch, and EVERY commit on it made by the bot's own git identity (the + # gitcfg step's). A commit by anyone else means a human is working on it, + # and force-pushing would destroy that work. Anything this run cannot read + # fails CLOSED: neither a force-push nor a sibling. + BOT_EMAIL="$(git config user.email || true)" + if [ -z "$BOT_EMAIL" ]; then + echo "::error::no git user.email is configured, so the drift bot's commits on PR #${R_NUMBER} cannot be told from a human's — refusing to rewrite it or open a sibling." + exit 1 + fi + if ! R_VIEW="$(gh pr view "$R_NUMBER" --json number,state,author,headRefName,headRefOid,commits 2>&1)"; then + echo "::error::open rolling PR #${R_NUMBER} could not be read (${R_VIEW}), so this run neither force-pushes over it nor opens a sibling beside it — refusing." + exit 1 + fi + if ! R_VERDICT="$(printf '%s' "$R_VIEW" | jq -r --arg e "$BOT_EMAIL" --arg b "$R_BRANCH" ' + if ((.commits | type) != "array") or ((.commits | length) == 0) + or ((.headRefOid // "") == "") + then "unknown:it came back with no commit list or no head commit" + elif .state != "OPEN" then "refuse:it is \(.state), not OPEN" + elif ((.author.login // "") | ascii_downcase) != ($ENV.DRIFT_BOT_LOGIN | ascii_downcase) + then "refuse:it was opened by \(.author.login // "nobody"), not by the drift bot" + elif (.headRefName // "") != $b then "refuse:its branch is now \(.headRefName // "")" + elif any(.commits[]; ((.authors // []) | length) == 0 + or any((.authors // [])[]; (.email // "") != $e)) + then "refuse:it carries a commit NOT made by the drift bot, so a human is working on it" + else "ok" end' 2>&1)"; then + echo "::error::open rolling PR #${R_NUMBER} came back unusable (${R_VERDICT}) — refusing to rewrite it or open a sibling." + exit 1 + fi + case "$R_VERDICT" in + ok) ;; + refuse:*) + # No sibling either: that is the duplicate this exists to prevent. The + # decision waits until a human merges or closes that PR, so the alert + # names it: resolving it is the action that unblocks this changeset. + echo "::warning::open needs-human PR #${R_NUMBER} is not the bot's to rewrite: ${R_VERDICT#refuse:}. So changeset ${CHANGESET_KEY} is NOT proposed this run — that PR is left alone and no sibling is opened. Merge or close #${R_NUMBER} and the next run proposes it." + emit_pr "$R_NUMBER" "$R_URL" + exit 0 + ;; + *) + echo "::error::open rolling PR #${R_NUMBER} cannot be proven safe to rewrite (${R_VERDICT#unknown:}) — refusing to rewrite it or open a sibling." + exit 1 + ;; + esac + R_HEAD="$(printf '%s' "$R_VIEW" | jq -r '.headRefOid')" + write_nh_body "$PR_BODY_FILE" + # Leased to the head the guard inspected: a push that landed after the + # check is rejected instead of overwritten. + git push --force-with-lease="refs/heads/${R_BRANCH}:${R_HEAD}" \ + origin "HEAD:refs/heads/${R_BRANCH}" + echo "Pushed ${HEAD_SHA} onto rolling needs-human PR #${R_NUMBER}'s branch ${R_BRANCH}" + if ! EDIT_ERR="$(gh pr edit "$R_NUMBER" --title "$PR_TITLE" --body-file "$PR_BODY_FILE" 2>&1)"; then + echo "::error::pushed changeset ${CHANGESET_KEY} onto PR #${R_NUMBER}, but rewriting its body FAILED, so its markers still name the OLD changeset (the next run rewrites it again): ${EDIT_ERR}" + exit 1 + fi + echo "needs-human: updated rolling PR #${R_NUMBER} IN PLACE to changeset ${CHANGESET_KEY} — not opening a sibling" + emit_pr "$R_NUMBER" "$R_URL" + exit 0 + fi + # A PER-NOTE OVERLAP IS REPORTED. IT DOES NOT DECIDE THE RUN. # # This loop used to `exit 0` the whole step on the FIRST note that some @@ -1550,61 +1700,19 @@ jobs: fi done - # Distinct branch (never collides with the ok-applied fix/drift-* branch). - # The changeset key is the LAST segment on purpose: it is the - # body-INDEPENDENT anchor the marker self-heal above uses to recognise this - # PR again if a human ever deletes its body markers. Keep it last — the - # self-heal matches on `endswith("-")`. - BRANCH="drift-needs-human/$(date +%Y-%m-%d)-${RUN_ID}-${CHANGESET_KEY}" + # No rolling PR is open: open it. Distinct from the ok-applied fix/drift-* + # branch, unique per run (a closed rolling PR is never reused, so reopening + # it stays a way out of a suppression), and with NO changeset key in it, + # because later runs rewrite its content. + BRANCH="drift-needs-human/rolling-$(date +%Y-%m-%d)-${RUN_ID}" git checkout -B "$BRANCH" git push -u origin "$BRANCH" echo "Pushed needs-human branch ${BRANCH} at ${HEAD_SHA}" - PR_BODY_FILE="${RUNNER_TEMP}/drift-needs-human-pr-body.md" - { - echo "## Needs a human decision (drift-sync)" - echo "" - echo "The deterministic, zero-LLM drift-sync found a model-family change it must" - echo "NOT auto-apply (a genuinely new/unclassified family, or a registry" - echo "structural mismatch). It wrote the note file(s) below and opened this PR so" - echo "the decision is REACHABLE in the repo." - echo "" - echo "> **Not auto-merged — a human decides, and applies it by hand.**" - echo "> For a *new-family* note, DO NOT expect merging this PR to apply anything:" - echo "> \`includeFamilies\` is checksum-pinned, and adding a family moves that pin," - echo "> which reds the freeze test gate-2 re-runs. drift-sync cannot re-pin — the" - echo "> gate-1 allowlist permits only \`model-registry.ts\` and \`drift-proposals/\`." - echo "> So a follow-up run would report \`gate-failed\`, not \`ok-applied\`." - echo ">" - echo "> The procedure that actually works, in ONE commit: add the family to" - echo "> \`includeFamilies\` (or \`excludeFamilies\` to reject), re-pin BOTH checksums," - echo "> resolve the note file(s) below, and update the offline \`/models\` wave." - echo "> Then close this PR. Prior examples: 72f85f8, 936b59c." - echo "" - echo "### Note file(s) in this PR" - echo "" - for note in "${NOTES[@]:-}"; do - [ -n "$note" ] || continue - echo "- \`${note}\`" - done - echo "" - # Emitted from the SINGLE MARKERS array built at the top of this step - # (the PRIMARY changeset marker plus one per note), so the set written - # here is by construction the set the marker self-heal re-asserts and - # the set the guards above match. - for m in "${MARKERS[@]}"; do - echo "" - done - echo "" - echo "### drift-sync outcome" - echo "" - echo '```' - cat "${RUNNER_TEMP}/drift-sync.log" 2>/dev/null || echo "(see drift-sync-log artifact)" - echo '```' - } > "$PR_BODY_FILE" + write_nh_body "$PR_BODY_FILE" gh pr create \ - --title "chore(drift-sync): needs-human model-family decision ($(date +%Y-%m-%d))" \ + --title "$PR_TITLE" \ --assignee jpr5 \ --body-file "$PR_BODY_FILE" diff --git a/src/__tests__/fix-drift-workflow.test.ts b/src/__tests__/fix-drift-workflow.test.ts index c67a6482..0fe917c1 100644 --- a/src/__tests__/fix-drift-workflow.test.ts +++ b/src/__tests__/fix-drift-workflow.test.ts @@ -1039,6 +1039,8 @@ interface PrStepRun { created: boolean; /** Did the step get as far as pushing a branch? */ pushed: boolean; + /** The body `gh pr create --body-file` was handed, or "" when none was created. */ + createdBody: string; } /** A PR in the scenario's repository, in `gh pr list --json`'s own shape. */ @@ -1050,6 +1052,9 @@ interface PrFixture { body: string; files?: { path: string }[]; author?: { login: string }; + /** `gh pr view`-only fields: the head commit and every commit on the PR. */ + headRefOid?: string; + commits?: { authors: { email: string; login: string }[] }[]; } interface PrStepScenario { @@ -1070,6 +1075,10 @@ interface PrStepScenario { matchOut?: string; } +/** The commit identity the gitcfg step configures for the drift bot. */ +const DRIFT_BOT_EMAIL = + /git config user\.email "([^"]+)"/.exec(codeOf(stepById("gitcfg")))?.[1] ?? ""; + const REAL_GIT = (() => { const r = spawnSync("/usr/bin/env", ["which", "git"], { encoding: "utf-8" }); const p = (r.stdout ?? "").trim(); @@ -1099,8 +1108,9 @@ function observePrStep( if (r.status !== 0) throw new Error(`git ${argv.join(" ")} failed: ${r.stderr}`); }; git("init", "-q", "-b", "main"); - git("config", "user.email", "t@t.test"); - git("config", "user.name", "t"); + // The gitcfg step's own identity, so "is this commit the bot's" can be asked here. + git("config", "user.email", DRIFT_BOT_EMAIL); + git("config", "user.name", "aimock-drift-bot"); writeFileSync(join(repo, "seed.txt"), "seed\n"); git("add", "-A"); git("commit", "-q", "-m", "base"); @@ -1186,7 +1196,14 @@ function observePrStep( ' while [ $# -gt 0 ]; do case "$1" in --body-file) BF="$2"; shift;; esac; shift; done', ` [ -n "$BF" ] && cp "$BF" ${JSON.stringify(edits)}/"$N".md`, " exit 0;;", - ' "pr create"*) exit 0;;', + // `pr view `: the one PR, from the same population, with its view-only fields. + ' "pr view"*)', + ` jq -c --argjson n "$3" '.[] | select(.number == $n)' ${JSON.stringify(join(fix, "all.json"))} | grep . || { echo "no PR $3" >&2; exit 1; }`, + " exit 0;;", + ' "pr create"*)', + ' BF=""; while [ $# -gt 0 ]; do case "$1" in --body-file) BF="$2"; shift;; esac; shift; done', + ` [ -n "$BF" ] && cp "$BF" ${JSON.stringify(join(dir, "created.md"))}`, + " exit 0;;", "esac", 'echo "gh stub: unhandled invocation: $ARGS" >&2', "exit 64", @@ -1215,6 +1232,8 @@ function observePrStep( CHANGESET_KEY: sc.changesetKey, GITHUB_OUTPUT: outFile, RUNNER_TEMP: dir, + // Step-level env the runner would inject, read off the step itself. + ...(step.env.DRIFT_BOT_LOGIN ? { DRIFT_BOT_LOGIN: step.env.DRIFT_BOT_LOGIN } : {}), }, }); const outputs: Record = {}; @@ -1235,6 +1254,9 @@ function observePrStep( edits: editBodies, created: ghCalls.some((c) => c.startsWith("pr create")), pushed: ghCalls.some((c) => c.startsWith("PUSH ")), + createdBody: existsSync(join(dir, "created.md")) + ? readFileSync(join(dir, "created.md"), "utf-8") + : "", }; } finally { rmSync(dir, { recursive: true, force: true }); @@ -3266,8 +3288,8 @@ describe("fix-drift.yml — bot_managed decides candidacy, and is pinned to both */ const builtBranches = (): { okApplied: string; needsHuman: string } => { const checkout = /git checkout -B "([^"]+)"/.exec(codeOf(stepById("gitcfg")))?.[1]; - const prBranch = /BRANCH="([^"]+)"/.exec(codeOf(stepById("pr")))?.[1]; - const nhBranch = /BRANCH="([^"]+)"/.exec(codeOf(stepById("needs_human_pr")))?.[1]; + const prBranch = /^\s*BRANCH="([^"]+)"/m.exec(codeOf(stepById("pr")))?.[1]; + const nhBranch = /^\s*BRANCH="([^"]+)"/m.exec(codeOf(stepById("needs_human_pr")))?.[1]; if (!checkout || !prBranch || !nhBranch) throw new Error("a BRANCH= builder moved"); const res = runFragment( [ @@ -3287,20 +3309,27 @@ describe("fix-drift.yml — bot_managed decides candidacy, and is pinned to both return { okApplied, needsHuman }; }; - it("keyed_branch accepts what BOTH branch builders actually produce", () => { - const { okApplied, needsHuman } = builtBranches(); - for (const branch of [okApplied, needsHuman]) { - expect(branch, "a branch builder produced nothing").toBeTruthy(); - expect( - def("keyed_branch", { headRefName: branch }), - `keyed_branch does not match the branch this workflow actually pushes (${branch}), so ` + - "the marker self-heal will not recognise its own PR and silently selects nothing", - ).toBe(true); - } - // Both must therefore be bot-managed without needing the author signal. - for (const branch of [okApplied, needsHuman]) { - expect(def("bot_managed", { headRefName: branch, author: { login: "jpr5" } })).toBe(true); - } + it("keyed_branch accepts what the ok-applied branch builder actually produces", () => { + const { okApplied } = builtBranches(); + expect(okApplied, "a branch builder produced nothing").toBeTruthy(); + expect( + def("keyed_branch", { headRefName: okApplied }), + `keyed_branch does not match the branch this workflow actually pushes (${okApplied}), so ` + + "the marker self-heal will not recognise its own PR and silently selects nothing", + ).toBe(true); + // It must therefore be bot-managed without needing the author signal. + expect(def("bot_managed", { headRefName: okApplied, author: { login: "jpr5" } })).toBe(true); + }); + + it("the ROLLING needs-human branch is deliberately NOT key-anchored", () => { + // Later runs rewrite the rolling PR with a different changeset, so a key in its + // branch name would go stale, and the key-anchored self-heal would re-stamp that + // stale key onto a PR that no longer proposes it (a false dedup). Its markers are + // instead rewritten by every update. + const { needsHuman } = builtBranches(); + expect(needsHuman).toMatch(/^drift-needs-human\/rolling-\d{4}-\d{2}-\d{2}-\d+$/); + expect(needsHuman).not.toContain(KEY); + expect(def("keyed_branch", { headRefName: needsHuman })).toBe(false); }); it("a bot PR on a PRE-KEY-ERA drift branch is still a candidate (that is what bot_author is for)", () => { @@ -3428,7 +3457,10 @@ describe("fix-drift.yml — dedup survives a human body edit and a CLOSED PR", ( "dedup blind and the next run opens a duplicate", ).toMatch(/gh pr edit .*--body-file/); - // (f) Identity is body-INDEPENDENT: the pushed branch carries the key. + // (f) Identity is body-INDEPENDENT: the pushed branch carries the key. Not + // for the needs-human step: its ROLLING branch is rewritten with later + // changesets, so a key there would go stale (pinned key-free elsewhere). + if (st.id === "needs_human_pr") continue; expect( code, `${st.name}: the pushed branch does not end in the changeset key, so the marker ` + @@ -5891,3 +5923,143 @@ describe("fix-drift.yml — the gate-failure alert reports the real exit code an } }); }); + +// --------------------------------------------------------------------------- +// ONE ROLLING needs-human PR, not a sibling per changeset. +// +// The changeset key dedups an IDENTICAL family set only. While a decision waits, +// each newly-appearing (or vanishing) family mints a new key, and the needs-human +// step opened a new PR for it beside the one still open: #406/#409/#411/#412 were +// open together (2026-09-02..09-08), and #475/#477/#481/#483/#484 (2026-09-22.. +// 10-02). These replay that sequence through the REAL step body, run after run: +// run 1's pushed branch and created body become run 2's open PR. +// --------------------------------------------------------------------------- +describe("fix-drift.yml — needs-human keeps ONE rolling PR across changesets", () => { + const BOT_LOGIN = "app/copilotkit-bot"; + const NOTE_A = "drift-proposals/openai-alpha-1.new-family.md"; + const NOTE_B = "drift-proposals/gemini-beta-2.new-family.md"; + const KEY_1 = "aaaa1111bbbb2222"; + const KEY_2 = "cccc3333dddd4444"; + const BOT_COMMIT = { authors: [{ email: DRIFT_BOT_EMAIL, login: "" }] }; + + /** The branch a run pushed, read off its `git push` call. */ + const pushedBranch = (r: PrStepRun): string => { + const push = r.ghCalls.find((c) => c.startsWith("PUSH ")); + if (!push) throw new Error(`no push: ${r.stdio}`); + const ref = push.split(" ").pop() ?? ""; + return ref.replace(/^HEAD:refs\/heads\//, ""); + }; + + /** Run 1: nothing open, so it opens the PR the later runs must reuse. */ + const firstRun = (): { run: PrStepRun; pr: PrFixture } => { + const run = observePrStep("needs_human_pr", { + changesetKey: KEY_1, + committed: { [NOTE_A]: "note A\n" }, + matchOut: '{"url":"https://x/pr/475","number":475}', + }); + expect(run.created, `run 1 opened no PR: ${run.stdio}`).toBe(true); + const pr: PrFixture = { + number: 475, + url: "https://x/pr/475", + state: "OPEN", + headRefName: pushedBranch(run), + body: run.createdBody, + files: [{ path: NOTE_A }], + author: { login: BOT_LOGIN }, + headRefOid: "0123456789abcdef0123456789abcdef01234567", + commits: [BOT_COMMIT], + }; + return { run, pr }; + }; + + const secondRun = (pr: PrFixture): PrStepRun => + observePrStep("needs_human_pr", { + changesetKey: KEY_2, + committed: { [NOTE_A]: "note A\n", [NOTE_B]: "note B\n" }, + prs: [pr], + matchOut: '{"url":"https://x/pr/477","number":477}', + }); + + it("a second run with a DIFFERENT changeset updates the open PR instead of opening a sibling", () => { + const { pr } = firstRun(); + const r = secondRun(pr); + expect( + r.created, + "a run whose family set merely GREW opened a second needs-human PR beside the one " + + `still open (#475 -> #477). stdio: ${r.stdio}`, + ).toBe(false); + expect(r.stepExit, r.stdio).toBe(0); + // It went onto THAT PR's branch, with a lease on the head it inspected. + const push = r.ghCalls.find((c) => c.startsWith("PUSH ")) ?? ""; + expect(push, r.stdio).toContain(`HEAD:refs/heads/${pr.headRefName}`); + expect(push).toContain(`--force-with-lease=refs/heads/${pr.headRefName}:${pr.headRefOid}`); + // The body now names THIS changeset and both notes, and not the old key. + const body = r.edits["475"] ?? ""; + expect(body, `PR #475's body was not rewritten. stdio: ${r.stdio}`).toContain( + ``, + ); + expect(body).not.toContain(`drift-changeset: ${KEY_1}`); + expect(body).toContain(NOTE_B); + expect(r.outputs.number).toBe("475"); + expect(r.outputs.url).toBe("https://x/pr/475"); + }); + + it("the rolling PR's branch carries NO changeset key, so its identity never goes stale", () => { + // A branch ending in KEY_1 that now carries KEY_2's content would be re-claimed + // by KEY_1's marker self-heal, which then dedups KEY_1 against the wrong content. + const { pr } = firstRun(); + expect(pr.headRefName).toMatch(/^drift-needs-human\/rolling-\d{4}-\d{2}-\d{2}-\d+$/); + expect(pr.headRefName).not.toContain(KEY_1); + }); + + it("NEGATIVE CONTROL: the same changeset again is still a no-op (no push, no edit)", () => { + const { pr } = firstRun(); + const r = observePrStep("needs_human_pr", { + changesetKey: KEY_1, + committed: { [NOTE_A]: "note A\n" }, + prs: [pr], + }); + expect(r.created, r.stdio).toBe(false); + expect(r.pushed, r.stdio).toBe(false); + expect(Object.keys(r.edits)).toEqual([]); + expect(r.outputs.number).toBe("475"); + }); + + it("a rolling PR a HUMAN has committed to is never force-pushed, and no sibling is opened", () => { + const { pr } = firstRun(); + const r = secondRun({ + ...pr, + commits: [BOT_COMMIT, { authors: [{ email: "someone@example.com", login: "someone" }] }], + }); + expect(r.pushed, `a human's work on #475 was force-pushed over. stdio: ${r.stdio}`).toBe(false); + expect(r.created, r.stdio).toBe(false); + expect(Object.keys(r.edits)).toEqual([]); + expect(r.stdio).toContain("::warning::"); + expect(r.stdio).toContain("#475"); + // The alert names the PR whose resolution unblocks this changeset. + expect(r.outputs.number).toBe("475"); + expect(r.stepExit, r.stdio).toBe(0); + }); + + it("a rolling-shaped PR NOT opened by the drift bot is not reused", () => { + const { pr } = firstRun(); + const r = secondRun({ + ...pr, + headRefName: "drift-needs-human/rolling-2026-10-14-1234", + author: { login: "jpr5" }, + }); + expect(Object.keys(r.edits), r.stdio).toEqual([]); + expect( + r.ghCalls.some((c) => c.startsWith("PUSH ") && c.includes("rolling-2026-10-14-1234")), + `a human's rolling-shaped branch was force-pushed. stdio: ${r.stdio}`, + ).toBe(false); + }); + + it("a rolling PR whose commits cannot be read FAILS CLOSED (no push, no sibling)", () => { + const { pr } = firstRun(); + const r = secondRun({ ...pr, commits: undefined }); + expect(r.stepExit, r.stdio).not.toBe(0); + expect(r.pushed, r.stdio).toBe(false); + expect(r.created, r.stdio).toBe(false); + }); +});