From e491e707e79ce6767007b0625f953a2a5839da66 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Thu, 3 Dec 2026 16:02:42 -0500 Subject: [PATCH 01/27] Run repository Self-merge checks before requesting merges (#2421) --- GLOSSARY.md | 11 +- ...7-repositories-own-the-self-merge-check.md | 33 +++ docs/guide.md | 39 +++ site/architecture/index.html | 2 +- site/docs/index.html | 35 ++- site/how-it-works/index.html | 1 + src/architect.rs | 6 + src/args.rs | 44 ++- src/asks.rs | 54 ++++ src/base_fix.rs | 2 +- src/child_run.rs | 26 +- src/child_run/asks.rs | 2 + src/child_run/execution_tests.rs | 2 +- src/config.rs | 20 +- src/console/start.rs | 1 + src/delivery.rs | 30 +- src/delivery/repair_loop.rs | 7 +- src/fix.rs | 13 +- src/fix/selection.rs | 11 + src/github.rs | 4 +- src/logs.rs | 7 + src/logs/command_record.rs | 2 +- src/logs/reading.rs | 5 +- src/logs/reading/attribution.rs | 19 +- src/main.rs | 7 + src/notification.rs | 6 +- src/pickup.rs | 3 + src/processes.rs | 26 +- src/processes/review.rs | 23 +- src/processes/review/conflicts.rs | 2 +- src/processes/review/self_merge.rs | 6 + src/processes/source.rs | 11 +- src/processes/ticket.rs | 3 + src/pull_request.rs | 98 ++++++- src/run.rs | 37 ++- src/run_ending.rs | 47 +-- src/security.rs | 6 + src/self_merge_check.rs | 176 ++++++++++++ src/spec_run.rs | 2 +- src/spec_run/ticket_board.rs | 2 +- tests/ci.rs | 34 +++ tests/console/inbox.rs | 17 ++ tests/fix_base_ci.rs | 22 ++ tests/fix_pass.rs | 49 ++++ tests/merge_run.rs | 21 ++ tests/process.rs | 21 ++ tests/process/spec_review.rs | 22 ++ tests/process/spec_run.rs | 19 ++ tests/review_merge.rs | 33 +++ tests/self_merge_check.rs | 270 ++++++++++++++++++ 50 files changed, 1253 insertions(+), 86 deletions(-) create mode 100644 docs/adr/0037-repositories-own-the-self-merge-check.md create mode 100644 src/self_merge_check.rs create mode 100644 tests/self_merge_check.rs diff --git a/GLOSSARY.md b/GLOSSARY.md index 6b42d9d07..008b1c0bf 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -262,10 +262,12 @@ _Avoid_: computer use, video artifact, test skill, app harness **Self-merge**: The step at the end of a **Ticket run** asked to merge in which thirdshift itself merges Delivery's captured pull request by number in its repository, with a merge commit at the exact head whose CI it watched. A **Custom process** reaches that same step through a `self-merge` catalogue Step directly after `delivery`, and only when its command or the **User config** asks. A fresh observation validates its expected **Issue branch** and **Base branch**, open state, readiness and mergeability immediately before the request. GitHub guards the requested head, but offers no atomic expected-base guard against a retarget between that observation and the server merge. No human reviews it first. A failed or interrupted request counts as merged only when a completion observation of the same number confirms the requested head and expected branches. Completion then continues even after Command interruption. It ends with the **Issue branch** deleted, the issue closed by thirdshift, unless it is already closed, and the issue's **Claim** removed. A protected path in a Custom process holds it and leaves the pull request ready for review, as an unaddressed **Security finding** does. +Before a Self-merge into the Base branch, a configured **Self-merge check** can leave the pull request ready for review. + **Repair loop**: The rounds a **Delivery** goes through until the pull request's head is mergeable with the **Base branch** and its CI is green or absent. Each round merges the Base branch in (and, in a **Ticket run** asked to merge, any **Foreign commits**), pushes, watches CI, and starts a **Repair** for a conflict or for the branch's own red checks. When the Base branch moved while green or absent CI ran, a Ticket run asked to merge goes round again to merge it in. A Delivery that leaves the pull request ready for review stops on that head if GitHub reports the pull request mergeable, and the move is not counted; otherwise it goes round again. Repairs and upstream moves have fixed budgets. A **Custom process** may set a lower Repair cap. It cannot set a higher one. -A **Sign-off hold** can end the loop ready for review once the pull request is mergeable. +A **Sign-off hold** can end the loop ready for review once the pull request is mergeable. A **Self-merge check** can hold a requested **Self-merge** after the loop has settled CI. **Repair**: A follow-up agent session a **Ticket run** starts after the pull request exists, or a **Spec run** starts on its **Spec PR** after the **Spec review**: to resolve a merge conflict with the **Base branch** or the **Issue branch** on `origin`, to fix failing CI checks, or, in a **Ticket run** asked to merge, to review and fix **Foreign commits**. @@ -290,6 +292,11 @@ Settled CI with a failing check. **CI watch** identifies which failures belong t **Sign-off hold**: A named check and hold label for a repository in the **User config**. When **CI watch** sees that check red, the open pull request carries the label on the watched head, and every other check has settled green, a **Ticket run**, **Spec run** or **Fix run** ends ready for review. The run releases its **Claim** or pull request reservation, and a requested **Self-merge** waits for the **Day shift**. The check and label appear in the **Inbox**, **Run notification** and **Command log**. Each machine that runs on the repository needs its own entry. +CI watch handles the Sign-off hold independently of the **Self-merge check**. + +**Self-merge check**: +A command a repository or host provides, which thirdshift runs immediately before a **Self-merge**. A repository script runs as committed on the **Base branch**. A nonzero exit ends the Run ready for review with the command's first output line as the reason. The **Sign-off hold** handles its named red check earlier in Delivery. + **Check re-run**: The [one re-run](docs/guide.md#check-re-run-allowance) of a branch's own failed checks allowed per head commit within a **Delivery**, after a CI-fix **Repair** leaves that head unchanged and before a **Declined CI fix**. It gives a transient CI failure one chance to pass without another Repair. It is separate from the re-run of **Abandoned jobs**, which comes before any Repair. _Avoid_: retry, re-trigger, CI re-run @@ -397,7 +404,7 @@ Inbox, without adding to its count of active Commands. Ready for review shows one row per validated pull request across the visible **Commands**, including across the **Fleet**. A grouped pull request keeps its contributing Commands available individually. -An ending at a **Sign-off hold** appears in Ready for review with its check and label. +An ending at a **Sign-off hold** or a **Self-merge check** appears in Ready for review with the reason. _Avoid_: dashboard, feed, queue **Needs you**: diff --git a/docs/adr/0037-repositories-own-the-self-merge-check.md b/docs/adr/0037-repositories-own-the-self-merge-check.md new file mode 100644 index 000000000..b80726b53 --- /dev/null +++ b/docs/adr/0037-repositories-own-the-self-merge-check.md @@ -0,0 +1,33 @@ +# Repositories own the Self-merge check + +A repository can configure one command to run immediately before a Self-merge +into its Base branch. A successful exit allows the merge request. A nonzero +exit, start failure or timeout leaves the pull request ready for review. The +check receives the current and first-observed pull request bodies so the +repository can apply its own policy and recognize a changed declaration. + +The checkout for an Issue branch can change during a Run. Read a repository +command directly from the tip of the Base branch on origin, and execute the +copy in Command scratch. An operator can also name an absolute host path +outside worktrees and share it across repositories. The last readiness +observation binds the check to the head and body being considered. GitHub +guards the head at the merge request. A body edit detected in the final +observation holds the PR, and GitHub offers no atomic expected-body guard +after that observation. + +[ADR 0035](0035-a-sign-off-hold-is-ready-for-review-past-one-named-red-check.md) +still governs Sign-off holds. The Self-merge check runs once CI and the other +merge checks have cleared. Tickets landing in a Spec branch bypass it. The +Spec PR runs it before landing in the Base branch. + +## Considered options + +- Teach `thirdshift-pr` to write Release Lanes and thirdshift to parse them. + Repositories own what their declarations mean and how their rules evolve. +- Ship a built-in Door-only hold. Wait until several repositories run the same + check before promoting a lane or Door rule into thirdshift. +- Run the command from the Issue branch. That would let a Run change the + policy deciding whether its own branch may merge. +- Use a Custom process `command` Step. Delivery and Self-merge share a Repair + loop, and the catalogue puts no command Step between them. Built-in + processes also need the same check. diff --git a/docs/guide.md b/docs/guide.md index d2b9622c0..f07f75b36 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -2907,6 +2907,43 @@ label_from = { "owner/repo" = ["maintainer-login"] } Configure one **Sign-off hold** per repository with `delivery.sign_off_hold`. Repository keys and label names match without regard to case. Check names match exactly. Config validation rejects blank checks or labels, repository keys that differ only in case, and the factory's `in-progress` reservation label. Add the entry on each machine that runs on the repository. +Configure a **Self-merge check** with `merge.self_merge_check`. Add the entry +on every host that runs on the repository. Repository keys match without regard +to case. The same repository can also have a Sign-off hold. CI watch handles +the named red check and label first. The Self-merge check runs only when the +pull request is otherwise ready to Self-merge. + +```toml +[merge] +self_merge_check = { "owner/repo" = "scripts/self-merge-check 'release policy'" } +``` + +The first word is the executable and the remaining words are its arguments. +Use shell quoting to group words. A repository path is read from the current +Base branch on `origin` and copied to Command scratch before execution. An +absolute path names a host executable outside Git worktrees. Both run from +Command scratch with `PR_NUMBER`, `PR_BODY`, `PR_BODY_AT_START`, `REPOSITORY` +(`owner/repo`) and `BASE_BRANCH` in their environment. The current body comes +from the readiness observation for the head about to merge. The start body is +the first body observed by the Command, or the opening body when thirdshift +creates the pull request. The command can use both bodies to enforce its own +review policy. + +Exit `0` allows Self-merge. Any other exit, a missing or unstartable executable, +or a one-minute timeout leaves the pull request ready for review. The first +nonempty stdout line, trimmed and capped at 240 characters, becomes the +reason. Without a line, thirdshift reports the exit status, timeout, or start +failure. The reason appears on stderr, in the Command log, in the Run +notification and in the Inbox. The Run releases its Claim, keeps its open PR +and exits successfully. If the body changes during the check, the Run leaves +the pull request ready for review. + +Use `no-self-merge-check` or `--no-self-merge-check` to turn the check off for +one Command. Use `self-merge-check` or `--self-merge-check` to require a +configured command for that run. Repositories with no entry have no check. +The check applies to each requested Self-merge, including the Spec PR into +the Base branch. Tickets land into the Spec branch without running the check. + After saving the User config and any entered Credentials, `thirdshift setup` checks the host tools for pull request **Visual evidence**: `gh >= 2.103.2`, `ffmpeg` on `PATH`, and an installed Playwright Chromium executable. It checks @@ -3866,6 +3903,8 @@ behind threshold, and continues to the next candidate. A Merge conflict or other settled CI red keeps the PR eligible, with the held check left out of the Repair's failure list. An explicit Fix run on a PR held only by a Sign-off hold succeeds ready for review and names the check and label it is waiting on. +A Fix Pass also passes over a PR whose latest Run on the machine ended at a +Self-merge check, unless the PR has a Merge conflict or settled CI red. The Pass skips `in-progress` PRs. It reserves and rechecks each candidate; if another machine reserved it first, it continues to the next candidate. diff --git a/site/architecture/index.html b/site/architecture/index.html index 6c093452e..852b42250 100644 --- a/site/architecture/index.html +++ b/site/architecture/index.html @@ -514,7 +514,7 @@

Architecture

-
Figure 3 A Ticket run that Self-merges. thirdshift merges code an agent wrote or reviewed, and leaves a pull request ready for review when CI confirms a Sign-off hold.
+
Figure 3 A Ticket run that Self-merges. CI can identify a Sign-off hold. Before the merge request, thirdshift runs any configured Self-merge check from the Base branch or host, then rechecks the PR and its body. A hold leaves the PR ready for review.
diff --git a/site/docs/index.html b/site/docs/index.html index deaec2f45..8082368b2 100644 --- a/site/docs/index.html +++ b/site/docs/index.html @@ -2880,6 +2880,37 @@ label_from = { "owner/repo" = ["maintainer-login"] }

Configure one Sign-off hold per repository with delivery.sign_off_hold. Repository keys and label names match without regard to case. Check names match exactly. Config validation rejects blank checks or labels, repository keys that differ only in case, and the factory's in-progress reservation label. Add the entry on each machine that runs on the repository.

+

Configure a Self-merge check with merge.self_merge_check. Add the entry +on every host that runs on the repository. Repository keys match without regard +to case. The same repository can also have a Sign-off hold. CI watch handles +the named red check and label first. The Self-merge check runs only when the +pull request is otherwise ready to Self-merge.

+
[merge]
+self_merge_check = { "owner/repo" = "scripts/self-merge-check 'release policy'" }
+
+

The first word is the executable and the remaining words are its arguments. +Use shell quoting to group words. A repository path is read from the current +Base branch on origin and copied to Command scratch before execution. An +absolute path names a host executable outside Git worktrees. Both run from +Command scratch with PR_NUMBER, PR_BODY, PR_BODY_AT_START, REPOSITORY +(owner/repo) and BASE_BRANCH in their environment. The current body comes +from the readiness observation for the head about to merge. The start body is +the first body observed by the Command, or the opening body when thirdshift +creates the pull request. The command can use both bodies to enforce its own +review policy.

+

Exit 0 allows Self-merge. Any other exit, a missing or unstartable executable, +or a one-minute timeout leaves the pull request ready for review. The first +nonempty stdout line, trimmed and capped at 240 characters, becomes the +reason. Without a line, thirdshift reports the exit status, timeout, or start +failure. The reason appears on stderr, in the Command log, in the Run +notification and in the Inbox. The Run releases its Claim, keeps its open PR +and exits successfully. If the body changes during the check, the Run leaves +the pull request ready for review.

+

Use no-self-merge-check or --no-self-merge-check to turn the check off for +one Command. Use self-merge-check or --self-merge-check to require a +configured command for that run. Repositories with no entry have no check. +The check applies to each requested Self-merge, including the Spec PR into +the Base branch. Tickets land into the Spec branch without running the check.

After saving the User config and any entered Credentials, thirdshift setup checks the host tools for pull request Visual evidence: gh >= 2.103.2, ffmpeg on PATH, and an installed Playwright Chromium executable. It checks @@ -3667,7 +3698,9 @@ behind threshold, and continues to the next candidate. A Merge conflict or other settled CI red keeps the PR eligible, with the held check left out of the Repair's failure list. An explicit Fix run on a PR held only by a Sign-off -hold succeeds ready for review and names the check and label it is waiting on.

+hold succeeds ready for review and names the check and label it is waiting on. +A Fix Pass also passes over a PR whose latest Run on the machine ended at a +Self-merge check, unless the PR has a Merge conflict or settled CI red.

The Pass skips in-progress PRs. It reserves and rechecks each candidate; if another machine reserved it first, it continues to the next candidate. Before and after reserving, it reads every linked closing issue and skips the diff --git a/site/how-it-works/index.html b/site/how-it-works/index.html index aa93bedb1..7236f0ba0 100644 --- a/site/how-it-works/index.html +++ b/site/how-it-works/index.html @@ -131,6 +131,7 @@

How thirdshift works

A running Command whose own GitHub call hits primary quota exhaustion waits until reset plus one minute and a random 0–60 seconds, then retries. If the quota has already reset, with at least 500 left, it records no wait and retries once, immediately. CI watch and Delivery share a two-hour total cap with child Ticket runs. A secondary limit gets up to five retries, 60 seconds apart. During a primary wait, status, show and the Console show Quota wait until <time>; Slow timing includes the wait. Stop interrupts ordinary waits; Claim ending and other completion work still finish within the cap. The Run notification totals primary waits in one Waited <duration> for the GitHub quota (<resource>) line. Waiting itself adds no agent-failed; agent sessions' own gh calls are unchanged.

A pull request existing is not the finish line. Delivery runs the opening session, then keeps the captured pull request mergeable and checks CI. This orchestration is thirdshift's code; a Repair is another agent session started when the branch needs work.

A configured Sign-off hold leaves a mergeable PR ready for review after a Ticket, Spec or Fix run when the named check is its only red check and the current PR carries the hold label. The Inbox names the check and label, and a requested Self-merge waits for the Day shift. User config

+

A Self-merge check runs a repository or host command after CI settles and the PR is otherwise ready to Self-merge. The command can hold it for the Day shift. The reason appears in Ready for review, the Run notification and the Command log.

For an existing open pull request, thirdshift fix <PR URL or number> starts a Fix run directly at Delivery. Ready and draft PRs by Trusted accounts are accepted, with or without closing issues. It uses the PR's own Base branch, reserves the PR while running and gives each Repair trusted PR and linked-issue context. It stops before using a linked closing issue, including when started as a Pass, unless that issue's author is a Trusted account and no account that is not one has edited its title or body. The usual merge, Base fix, Harness and email defaults apply; failure preserves work and offers thirdshift fix again.

Self-merge requires recorded agent authorship or review of the adopted head. Without it, a Fix Pass, even with merge, or a targeted Fix run asked to merge only by merge.always, still repairs the PR and checks CI, then finishes successfully Ready for review (exit 0) and logs the hold. An explicit thirdshift fix <PR> merge still fails with the hold and leaves the repaired PR ready for review.

With no PR target, thirdshift fix [base <branch>] [--author <login>] is a Pass. Without --author, it first checks the Base branch's origin tip: a failed first push attempt gets one failed-jobs re-run, then PR selection continues without waiting. Persistent or non-rerunnable failures get a CI-fix session on fix-<base>-<short-sha> and a repair PR targeting the Base branch, treating every red check as its own; that Fix run ends the Pass. Existing PRs from that branch prevent duplicates, failed drafts included. Merge and email policy apply, and Self-merge closes the Base branch's CI-red reports and Base fix issues.

diff --git a/src/architect.rs b/src/architect.rs index e16b26aea..e866f64b8 100644 --- a/src/architect.rs +++ b/src/architect.rs @@ -308,6 +308,12 @@ pub fn run( config: &UserConfig, harness: &mut Choice, ) -> Outcome { + if flags.self_merge_check == Some(true) + && let Err(error) = + launch::repo().and_then(|repo| flags.validate_merge_check(&repo, config)) + { + return failed(error.into()); + } let started = Utc::now(); let Launch { directory, diff --git a/src/args.rs b/src/args.rs index 9550e17a2..e8abf86ab 100644 --- a/src/args.rs +++ b/src/args.rs @@ -50,6 +50,7 @@ pub struct ProcessRun { pub email: Option, /// `merge` or `no-merge`. Absent leaves the choice to the User config. pub goal: Option, + pub self_merge_check: Option, /// Whether this Process's Security review Step is requested. pub security_review: Option, /// Whether Security finding Steps are allowed to fix findings. @@ -351,6 +352,7 @@ pub fn retry_with_base_fix(issue: &IssueUrl, flags: &Flags) -> String { pub fn continuation(issue: &IssueUrl, asks: &crate::asks::Asks, is_spec: bool) -> String { let flags = Flags { goal: asks.merge_label_from.is_empty().then_some(asks.goal), + self_merge_check: asks.self_merge_check_override, trust_authors: asks.trust_authors.clone(), parallel: is_spec.then_some(asks.tickets_at_once), base_fix: Some(asks.base_fix.clone()), @@ -407,6 +409,16 @@ pub(crate) fn public_flag_words(flags: &Flags, words: &mut Vec) { Some(Goal::ReadyForReview) => words.push("--no-merge".into()), None => {} } + if let Some(enabled) = flags.self_merge_check { + words.push( + if enabled { + "--self-merge-check" + } else { + "--no-self-merge-check" + } + .into(), + ); + } match &flags.email { Some(NotificationAsk::Send(to)) => { words.push("--email".into()); @@ -1323,7 +1335,7 @@ fn parse_remote_details(args: &[String]) -> Result { Ok(Command::RemoteDetails { machine, route }) } -const PROCESS_USAGE: &str = "usage: thirdshift process list | show | [check] [issue | pull-request ] [harness ] [model ] [effort ] [email [address] | email-unless-merged [address] | no-email] [merge | no-merge] [security-review | no-security-review] [security-fix | no-security-fix] [security-close | no-security-close] [--plan-only]"; +const PROCESS_USAGE: &str = "usage: thirdshift process list | show | [check] [issue | pull-request ] [harness ] [model ] [effort ] [email [address] | email-unless-merged [address] | no-email] [merge | no-merge] [self-merge-check | no-self-merge-check] [security-review | no-security-review] [security-fix | no-security-fix] [security-close | no-security-close] [--plan-only]"; fn parse_review(args: &[String]) -> Result { let mut pull_request = None; @@ -1345,6 +1357,7 @@ fn parse_review(args: &[String]) -> Result { || take_email_flag(&mut flags.email, arg, &mut words)? || take_security_review_flag(&mut flags, arg)? || take_merge_flag(&mut flags.goal, arg)? + || take_self_merge_check_flag(&mut flags.self_merge_check, arg)? { } else if pull_request.is_none() { pull_request = Some(crate::review::PullRequestUrl::parse(arg)?); @@ -1488,6 +1501,9 @@ fn parse_process(args: &[String]) -> Result { if take_merge_flag(&mut goal, arg)? { continue; } + if take_self_merge_check_flag(&mut review_flags.self_merge_check, arg)? { + continue; + } if matches!( arg.as_str(), "security-review" @@ -1548,6 +1564,7 @@ fn parse_process(args: &[String]) -> Result { if expect_issue || ((email.is_some() || goal.is_some() + || review_flags.self_merge_check.is_some() || review_flags.security_review.is_some() || review_flags.security_fix.is_some() || review_flags.security_close.is_some() @@ -1566,6 +1583,7 @@ fn parse_process(args: &[String]) -> Result { asked, email, goal, + self_merge_check: review_flags.self_merge_check, security_review: review_flags.security_review, security_fix: review_flags.security_fix, security_close: review_flags.security_close, @@ -1589,6 +1607,21 @@ fn take_merge_flag(goal: &mut Option, arg: &str) -> Result { Ok(true) } +fn take_self_merge_check_flag(flag: &mut Option, arg: &str) -> Result { + let enabled = match arg { + "self-merge-check" | "--self-merge-check" => true, + "no-self-merge-check" | "--no-self-merge-check" => false, + _ => return Ok(false), + }; + ask_once( + flag, + enabled, + arg, + "self-merge-check and no-self-merge-check", + )?; + Ok(true) +} + /// Record an email flag in `email`. False, taking nothing, when `arg` is not one. fn take_email_flag<'a>( email: &mut Option, @@ -1902,7 +1935,9 @@ fn take_flag<'a>( if take_email_flag(&mut flags.email, arg, rest)? { return Ok(true); } - if take_merge_flag(&mut flags.goal, arg)? { + if take_merge_flag(&mut flags.goal, arg)? + || take_self_merge_check_flag(&mut flags.self_merge_check, arg)? + { return Ok(true); } if take_security_review_flag(flags, arg)? { @@ -2127,6 +2162,8 @@ mod tests { merge_label_from: Vec::new(), delivery_limits: crate::delivery::Limits::default(), sign_off_hold: None, + self_merge_check: None, + self_merge_check_override: None, security_review_harness: None, security_review_default: None, goal, @@ -2215,6 +2252,7 @@ mod tests { Flags { trust_authors: vec![], goal: Some(Goal::Merged), + self_merge_check: None, email: Some(NotificationAsk::Send(Some("day@example.com".into()))), parallel: NonZeroUsize::new(2), base_fix: Some(BaseFixAsk::Forbid), @@ -2900,6 +2938,7 @@ mod tests { security_close: None, security_review: None, goal: Some(Goal::Merged), + self_merge_check: None, email: Some(NotificationAsk::Send(Some("me@example.com".to_string()))), parallel: NonZeroUsize::new(2), base_fix: Some(BaseFixAsk::Allow), @@ -2960,6 +2999,7 @@ mod tests { security_close: None, security_review: None, goal: Some(Goal::ReadyForReview), + self_merge_check: None, email: Some(NotificationAsk::Skip), parallel: None, base_fix: Some(BaseFixAsk::Forbid), diff --git a/src/asks.rs b/src/asks.rs index ba73fa90f..4cb9d5afd 100644 --- a/src/asks.rs +++ b/src/asks.rs @@ -20,6 +20,7 @@ use crate::run::Goal; pub struct Flags { /// The goal `merge` or `no-merge` asked for. pub goal: Option, + pub self_merge_check: Option, /// What `email`, `email-unless-merged` or `no-email` asked for. pub email: Option, /// How many Tickets a Spec run runs at once, as `parallel ` gave it. @@ -45,6 +46,8 @@ pub struct Asks { /// Explicit named authors for an Issue URL run or a Pickup Pass. pub trust_authors: Vec, pub sign_off_hold: Option, + pub self_merge_check: Option, + pub self_merge_check_override: Option, /// Whether it is a Merge run. pub goal: Goal, /// The logins that may supply a merge request when none was given. @@ -108,6 +111,8 @@ impl Asks { delivery_limits: crate::delivery::Limits::default(), trust_authors: flags.trust_authors.clone(), sign_off_hold: config.sign_off_hold(&issue.repo()).cloned(), + self_merge_check: flags.merge_check_for(&issue.repo(), config).cloned(), + self_merge_check_override: flags.self_merge_check, notification: flags.notification(config), tickets_at_once: flags.parallel.unwrap_or(config.spec_parallel), parallel_asked: flags.parallel.is_some(), @@ -142,6 +147,11 @@ impl Asks { child_run::Kind::Ticket { .. } => None, child_run::Kind::BaseFix { .. } => config.sign_off_hold(&issue.repo()).cloned(), }, + self_merge_check: match &given.kind { + child_run::Kind::Ticket { .. } => None, + child_run::Kind::BaseFix { .. } => given.asks.self_merge_check.clone(), + }, + self_merge_check_override: None, notification: NotificationAsk::Skip, tickets_at_once: config.spec_parallel, parallel_asked: false, @@ -199,6 +209,31 @@ impl Asks { } } +impl Flags { + pub(crate) fn merge_check_for<'a>( + &self, + repo: &crate::issue::Repo, + config: &'a UserConfig, + ) -> Option<&'a crate::self_merge_check::Check> { + config + .self_merge_check(repo) + .filter(|_| self.self_merge_check != Some(false)) + } + + pub(crate) fn validate_merge_check( + &self, + repo: &crate::issue::Repo, + config: &UserConfig, + ) -> anyhow::Result<()> { + anyhow::ensure!( + self.self_merge_check != Some(true) || self.merge_check_for(repo, config).is_some(), + "self-merge-check requires merge.self_merge_check for {}", + repo.slug(), + ); + Ok(()) + } +} + impl Flags { /// Whether a Run with these flags runs a Security review: as /// `security-review` or `no-security-review` asked, else as `config` @@ -455,6 +490,8 @@ mod tests { merge_label_from: Vec::new(), delivery_limits: crate::delivery::Limits::default(), sign_off_hold: None, + self_merge_check: None, + self_merge_check_override: None, security_review_harness: None, security_review_default: None, security_fix: false, @@ -482,6 +519,8 @@ mod tests { merge_label_from: Vec::new(), delivery_limits: crate::delivery::Limits::default(), sign_off_hold: None, + self_merge_check: None, + self_merge_check_override: None, security_review_harness: None, security_review_default: None, security_fix: false, @@ -506,6 +545,7 @@ mod tests { security_close: None, security_review: None, goal: Some(Goal::ReadyForReview), + self_merge_check: None, email: Some(NotificationAsk::Skip), parallel: Some(n(2)), base_fix: Some(BaseFixAsk::Forbid), @@ -519,6 +559,8 @@ mod tests { merge_label_from: Vec::new(), delivery_limits: crate::delivery::Limits::default(), sign_off_hold: None, + self_merge_check: None, + self_merge_check_override: None, security_review_harness: None, security_review_default: None, security_fix: false, @@ -541,6 +583,7 @@ mod tests { security_close: None, security_review: None, goal: Some(Goal::Merged), + self_merge_check: None, email: Some(to("flag@example.com")), parallel: Some(n(2)), base_fix: Some(BaseFixAsk::Allow), @@ -554,6 +597,8 @@ mod tests { merge_label_from: Vec::new(), delivery_limits: crate::delivery::Limits::default(), sign_off_hold: None, + self_merge_check: None, + self_merge_check_override: None, security_review_harness: None, security_review_default: None, security_fix: false, @@ -719,6 +764,7 @@ mod tests { security_close: None, security_review: None, goal: Some(Goal::Merged), + self_merge_check: None, email: Some(to("flag@example.com")), parallel: Some(n(2)), base_fix: None, @@ -736,6 +782,8 @@ mod tests { merge_label_from: Vec::new(), delivery_limits: crate::delivery::Limits::default(), sign_off_hold: None, + self_merge_check: None, + self_merge_check_override: None, security_review_harness: None, security_review_default: None, security_fix: false, @@ -761,6 +809,8 @@ mod tests { merge_label_from: Vec::new(), delivery_limits: crate::delivery::Limits::default(), sign_off_hold: None, + self_merge_check: None, + self_merge_check_override: None, security_review_harness: None, security_review_default: None, security_fix: false, @@ -788,6 +838,8 @@ mod tests { merge_label_from: Vec::new(), delivery_limits: crate::delivery::Limits::default(), sign_off_hold: None, + self_merge_check: None, + self_merge_check_override: None, security_review_harness: None, security_review_default: None, security_fix: false, @@ -813,6 +865,8 @@ mod tests { merge_label_from: Vec::new(), delivery_limits: crate::delivery::Limits::default(), sign_off_hold: None, + self_merge_check: None, + self_merge_check_override: None, security_review_harness: None, security_review_default: None, security_fix: false, diff --git a/src/base_fix.rs b/src/base_fix.rs index 86bb9450b..4f2b2870d 100644 --- a/src/base_fix.rs +++ b/src/base_fix.rs @@ -303,7 +303,7 @@ impl BaseFix { "Base fix #{number} ended before Delivery: {reason}" )) .into()), - Ended::SignOffHeld { pr_url, hold } => Err(ChildEnded(format!( + Ended::Held { pr_url, hold } => Err(ChildEnded(format!( "Base fix #{number} is ready for review waiting for {hold} on {pr_url}" )) .into()), diff --git a/src/child_run.rs b/src/child_run.rs index ef0e53581..16906eb58 100644 --- a/src/child_run.rs +++ b/src/child_run.rs @@ -146,6 +146,7 @@ const SECURITY_REVIEW_DEFAULT_EFFORT: &str = "--security-review-default-effort"; const ALLOW_SECURITY_FIX: &str = "--allow-security-fix"; const ALLOW_SECURITY_CLOSE: &str = "--allow-security-close"; const DELIVERY_LIMITS: &str = "--delivery-limits"; +const CHILD_SELF_MERGE_CHECK: &str = "--child-self-merge-check"; const TICKET_PROCESS: &str = "--ticket-process"; const NAMED_TICKET_AUTHOR: &str = "--named-ticket-author"; @@ -244,6 +245,14 @@ impl Given { .expect("Delivery limits serialize"), ]); } + if matches!(self.kind, Kind::BaseFix { .. }) + && let Some(check) = &self.asks.self_merge_check + { + args.extend([ + CHILD_SELF_MERGE_CHECK.to_string(), + serde_json::to_string(check).expect("Self-merge check serializes"), + ]); + } args } } @@ -333,6 +342,7 @@ pub struct Reader { process: Option, named_author: Option, delivery_limits: Option, + self_merge_check: Option, kind: Option, spec_pr: Option, stamp: Option, @@ -389,6 +399,10 @@ impl Reader { } self.delivery_limits = Some(limits); } + CHILD_SELF_MERGE_CHECK => { + not_yet_given(&self.self_merge_check, arg)?; + self.self_merge_check = Some(serde_json::from_str(&value("Self-merge check")?)?); + } SECURITY_REVIEW => { if self.security_review { bail!("repeated argument: {arg}"); @@ -555,6 +569,7 @@ impl Reader { asks: ChildAsks { delivery_limits: self.delivery_limits.unwrap_or_default(), sign_off_hold: None, + self_merge_check: self.self_merge_check, harness, security_review_harness, security_review_default, @@ -582,7 +597,7 @@ pub enum Ended { /// A Custom Ticket Process ended successfully without delivering its Ticket. ArchitectureReview { reason: String }, /// Self-merge waits for sign-off on this ready pull request. - SignOffHeld { pr_url: String, hold: String }, + Held { pr_url: String, hold: String }, /// It reached its goal, with its PR as it printed it, and what became /// of the Base fix it took, if any, as it reported it. Reached { @@ -946,10 +961,10 @@ impl Handle { let reader = self.stderr.as_mut().unwrap().value.take().unwrap(); let not_reproduced = reader.not_reproduced().map(String::from); let architecture_end = reader.architecture_end().map(String::from); - let sign_off_hold = stdout + let review_hold = stdout .lines() .last() - .and_then(|pr_url| reader.sign_off_hold(pr_url)) + .and_then(|pr_url| reader.review_hold(pr_url)) .map(String::from); let ending = reader.finish(&stdout, status.success()); Ok(match ending.outcome { @@ -959,8 +974,8 @@ impl Handle { Ok(_) if architecture_end.is_some() => Ended::ArchitectureReview { reason: architecture_end.unwrap(), }, - Ok(pr_url) => match (pr_url, sign_off_hold) { - (Some(pr_url), Some(hold)) => Ended::SignOffHeld { pr_url, hold }, + Ok(pr_url) => match (pr_url, review_hold) { + (Some(pr_url), Some(hold)) => Ended::Held { pr_url, hold }, (pr_url, _) => Ended::Reached { pr_url, base_fix: ending.base_fix, @@ -1178,6 +1193,7 @@ mod tests { asks: ChildAsks { delivery_limits: crate::delivery::Limits::default(), sign_off_hold: None, + self_merge_check: None, harness: harness.clone(), security_review_harness: security_review_harness.clone(), security_review_default: security_review.then(|| Choice { diff --git a/src/child_run/asks.rs b/src/child_run/asks.rs index 07ca62560..042011f03 100644 --- a/src/child_run/asks.rs +++ b/src/child_run/asks.rs @@ -11,6 +11,7 @@ use crate::harness::Choice; pub struct ChildAsks { pub delivery_limits: crate::delivery::Limits, pub sign_off_hold: Option, + pub self_merge_check: Option, /// The Harness, Model and Effort a child Run's sessions run on, as the /// Command's checks settled them. pub harness: Choice, @@ -37,6 +38,7 @@ impl ChildAsks { ChildAsks { delivery_limits: asks.delivery_limits.clone(), sign_off_hold: asks.sign_off_hold.clone(), + self_merge_check: asks.self_merge_check.clone(), harness: asks.harness.clone(), security_review_harness: asks.security_review_harness.clone(), security_review_default: asks.security_review_default.clone(), diff --git a/src/child_run/execution_tests.rs b/src/child_run/execution_tests.rs index 8c5b23eff..6cb63e664 100644 --- a/src/child_run/execution_tests.rs +++ b/src/child_run/execution_tests.rs @@ -260,7 +260,7 @@ fn malformed_stderr_preserves_a_successful_ending_and_base_fix_account() { } Ended::NotReproduced { .. } | Ended::ArchitectureReview { .. } - | Ended::SignOffHeld { .. } + | Ended::Held { .. } | Ended::Failed { .. } | Ended::Paused { .. } | Ended::Interrupted { .. } => { diff --git a/src/config.rs b/src/config.rs index d53885733..26516e9d9 100644 --- a/src/config.rs +++ b/src/config.rs @@ -41,6 +41,8 @@ pub struct UserConfig { pub merge_always: bool, /// `merge.label_from`: logins allowed to request Self-merge per repository. pub merge_label_from: BTreeMap>, + /// `merge.self_merge_check` keyed by lowercase owner/repo. + pub self_merge_checks: BTreeMap, /// `base.fix`: every Run may start a Base fix unless told `no-base-fix`. pub base_fix: bool, /// `delivery.sign_off_hold` keyed by lowercase owner/repo. @@ -189,6 +191,11 @@ impl UserConfig { self.sign_off_holds.get(&repo.slug().to_ascii_lowercase()) } + pub(crate) fn self_merge_check(&self, repo: &Repo) -> Option<&crate::self_merge_check::Check> { + self.self_merge_checks + .get(&repo.slug().to_ascii_lowercase()) + } + pub(crate) fn fix_behind(&self, repo: &Repo) -> Option { self.fix_behind .get(&repo.slug().to_ascii_lowercase()) @@ -249,6 +256,7 @@ impl UserConfig { console: ConsoleSettings::default(), merge_always: false, merge_label_from: BTreeMap::new(), + self_merge_checks: BTreeMap::new(), base_fix: false, sign_off_holds: BTreeMap::new(), launch_pull: false, @@ -393,6 +401,14 @@ impl UserConfig { ("merge", "label_from", value) => { config.merge_label_from = merge_label_logins(value, &file)?; } + ("merge", "self_merge_check", value) => { + let checks: BTreeMap = value + .clone() + .try_into() + .with_context(|| format!("invalid merge.self_merge_check in {file}"))?; + config.self_merge_checks = + repository_keys(checks, "merge.self_merge_check")?; + } ("triage", "allow_ready_for_agent", Value::Boolean(allow)) => { config.triage_allow_ready_for_agent = *allow } @@ -1316,6 +1332,7 @@ pub const DEFAULTS: &str = r#"launch_directories = [] # additional known Launch [merge] always = false # every Ticket run Self-merges, without the merge word; default false label_from = {} # GitHub logins allowed to request Self-merge with an issue label, keyed by "owner/repo"; default empty +self_merge_check = {} # command before Self-merge, keyed by "owner/repo"; default empty [base] fix = false # every Ticket run may start a Base fix, without the base-fix word; default false @@ -1738,6 +1755,7 @@ mod tests { "launch_directories", "merge.always", "merge.label_from", + "merge.self_merge_check", "base.fix", "delivery.sign_off_hold", "launch.pull", @@ -2692,7 +2710,7 @@ mod tests { assert!( rendered.lines().any(|line| { line.starts_with("merge = { always = true") - && line.ends_with("label_from = {} }") + && line.ends_with("label_from = {}, self_merge_check = {} }") }), "{rendered}" ); diff --git a/src/console/start.rs b/src/console/start.rs index 64fa66a07..2606f886f 100644 --- a/src/console/start.rs +++ b/src/console/start.rs @@ -448,6 +448,7 @@ impl Request { fn flags(&self) -> Result { Ok(Flags { trust_authors: vec![], + self_merge_check: None, goal: self.merge.map(|merge| { if merge { Goal::Merged diff --git a/src/delivery.rs b/src/delivery.rs index fb7b7780d..383759d73 100644 --- a/src/delivery.rs +++ b/src/delivery.rs @@ -302,7 +302,11 @@ impl Delivery<'_> { outside.stage(Stage::PullRequestReadiness); let pr = outside.mark_pr_ready(None)?; if check_existing_hold && let Some(hold) = outside.existing_sign_off_hold()? { - return Ok(Resolution::delivered(pr.url, goal, Some(hold))); + return Ok(Resolution::delivered( + pr.url, + goal, + Some(crate::run::ReviewHold::SignOff(hold)), + )); } let resolution = outside.take_to_goal(&pr.url, goal)?; if resolution.goal() == Some(Goal::Merged) { @@ -1502,6 +1506,9 @@ impl Outside for InWorktree<'_> { ) -> Result> { let base = self.base; let pull_request = &mut *self.pull_request; + if self.child_asks.self_merge_check.is_some() { + pull_request.observe_start_body()?; + } let mut continue_with = |committed: bool| { crate::implement::continue_with(continuation, committed, base, pull_request) }; @@ -1584,9 +1591,9 @@ impl Outside for InWorktree<'_> { scope: self.scope, context: self.context, }; - let (goal, sign_off_hold) = + let (goal, hold) = match repair_loop::take_to_goal(&mut outside, self.base, goal, self.repair_cap) { - Ok(sign_off_hold) => (goal, sign_off_hold), + Ok(hold) => (goal, hold), Err(hold) if hold.is::() => { match self.check_merge_label() { Ok(()) => return Err(hold), @@ -1602,7 +1609,7 @@ impl Outside for InWorktree<'_> { // Ticket/Spec and Base CI Deliveries began with agent-authored or // reviewed work. Preserve exact-head evidence for a later Fix run. // An adopted PR cannot acquire that authority merely by passing CI. - if (goal == Goal::ReadyForReview || sign_off_hold.is_some()) + if (goal == Goal::ReadyForReview || hold.is_some()) && !matches!(self.context, RepairContext::PullRequest { .. }) && let Err(error) = self.record_delivered_head(pr_url) { @@ -1611,11 +1618,7 @@ impl Outside for InWorktree<'_> { format_args!("could not record the delivered agent head"), ); } - Ok(Resolution::delivered( - pr_url.to_owned(), - goal, - sign_off_hold, - )) + Ok(Resolution::delivered(pr_url.to_owned(), goal, hold)) } fn check_merge_label(&self) -> Result<()> { @@ -1885,7 +1888,12 @@ impl repair_loop::Outside for RunOutside<'_> { fn merge(&mut self, watched: &repair_loop::WatchedHead) -> Result { self.check_closing_issues()?; - self.pull_request.merge(&watched.commit, || { + let check = self + .child_asks + .self_merge_check + .as_ref() + .map(|check| (check, self.worktree.launch())); + self.pull_request.merge_with_check(&watched.commit, || { use crate::worktree::BaseRelationship; use repair_loop::WatchedCi; let relationship = self.worktree.relationship_to_base( @@ -1925,7 +1933,7 @@ impl repair_loop::Outside for RunOutside<'_> { )) } } - }) + }, check) } fn merge_hold(&mut self) -> Result> { diff --git a/src/delivery/repair_loop.rs b/src/delivery/repair_loop.rs index 77600e0bd..82934ee1d 100644 --- a/src/delivery/repair_loop.rs +++ b/src/delivery/repair_loop.rs @@ -120,7 +120,7 @@ pub(super) fn take_to_goal( base: &str, goal: Goal, repair_cap: usize, -) -> Result> { +) -> Result> { let mut repair_loop = RepairLoop { outside, base, @@ -150,7 +150,7 @@ pub(super) fn take_to_goal( if goal == Goal::Merged { outside.progress(format!("{hold} holds the Self-merge")); } - return Ok(Some(hold)); + return Ok(Some(crate::run::ReviewHold::SignOff(hold))); } outside.stage(if goal == Goal::Merged { Stage::SelfMerge @@ -171,6 +171,9 @@ pub(super) fn take_to_goal( outside.stage(Stage::SelfMerge); let error = match outside.merge(&watched)? { MergeAttempt::Merged => return Ok(None), + MergeAttempt::Held(reason) => { + return Ok(Some(crate::run::ReviewHold::SelfMergeCheck(reason))); + } MergeAttempt::BaseMoved => { repair_loop.count_base_move("before Self-merge")?; watched = repair_loop.rounds()?; diff --git a/src/fix.rs b/src/fix.rs index 19228a824..6860f7420 100644 --- a/src/fix.rs +++ b/src/fix.rs @@ -41,6 +41,11 @@ pub(crate) fn run( started: &mut crate::command::Started, ) -> crate::command::Ending { let result = (|| -> anyhow::Result<_> { + if command.flags.self_merge_check == Some(true) { + command + .flags + .validate_merge_check(&crate::launch::repo()?, config)?; + } if let Target::Pass { base, author } = &command.target { let launch = match crate::launch::start( base.as_deref(), @@ -78,6 +83,9 @@ pub(crate) fn run( author.as_deref(), behind, sign_off_hold, + config + .self_merge_check(&launch.repo) + .map(|_| config.logs_dir.as_path()), &mut passed_over, )? { let selected = FixArgs { @@ -209,8 +217,8 @@ fn targeted_at( return Err(anyhow::anyhow!("origin mismatch: {} is not in {origin}", pr.url).into()); } let github = GitHub::new(); - let snapshot = github.fix_pull_request(&pr)?; - started_command.pull_request(&pr, &snapshot.title); + let initial = github.fix_pull_request(&pr)?; + started_command.pull_request(&pr, &initial.title); let pass = reservation.is_some(); let _reservation = match reservation { Some(held) => held, @@ -258,6 +266,7 @@ fn targeted_at( asks.goal != Goal::Merged || github.authored_or_reviewed_head(&pr, &adopted_head)?; let mut target = PullRequest::on_pull_request(&pr, &snapshot.branch, &snapshot.base, github); + target.remember_body(pr.issue.number, &initial.body); if !reviewed { let reason = format!( "PR {} stays ready for review: adopted head {} has no recorded agent review; run thirdshift review {} before retrying Self-merge", diff --git a/src/fix/selection.rs b/src/fix/selection.rs index 9984382fa..023b3342f 100644 --- a/src/fix/selection.rs +++ b/src/fix/selection.rs @@ -17,8 +17,13 @@ pub(super) fn take( author: Option<&str>, behind: Option, sign_off_hold: Option<&SignOffHold>, + hold_logs: Option<&std::path::Path>, passed_over: &mut Vec, ) -> Result> { + let holds = hold_logs + .filter(|_| behind.is_some()) + .map(crate::logs::self_merge_check_holds) + .transpose()?; let mut pass = Pass { launch, github, @@ -53,6 +58,12 @@ pub(super) fn take( }; let mut further_behind = Vec::new(); for (pr, candidate) in without_repairs { + if holds + .as_ref() + .is_some_and(|holds| holds.self_merge_check_held(&pr.url)) + { + continue; + } let distance = github.fix_commits_behind(&pr, &candidate)?; if distance >= behind.get() { further_behind.push((distance, pr, candidate.branch)); diff --git a/src/github.rs b/src/github.rs index 5f2f3acd8..3c23617c0 100644 --- a/src/github.rs +++ b/src/github.rs @@ -910,6 +910,7 @@ impl GitHub { }; Ok(Some(PrSnapshot { pr: PullRequest::from_json(&json)?, + body: json["body"].as_str().map(String::from), mergeable, has_required_label, head_commit: json["headRefOid"] @@ -1940,12 +1941,13 @@ query($owner: String!, $repo: String!, $number: Int!, $after: String) { const PR_FIELDS: &str = "number,url,state,headRefName,baseRefName,isDraft"; const SNAPSHOT_FIELDS: &str = - "number,url,state,headRefName,baseRefName,isDraft,mergeable,headRefOid,isCrossRepository"; + "number,url,state,headRefName,baseRefName,isDraft,mergeable,headRefOid,isCrossRepository,body"; /// The fields needed for one pull request observation, read together. #[derive(Debug, Clone)] pub struct PrSnapshot { pub pr: PullRequest, + pub body: Option, pub mergeable: Mergeable, pub head_commit: String, pub from_fork: bool, diff --git a/src/logs.rs b/src/logs.rs index 3f814e03f..9b89aa4a6 100644 --- a/src/logs.rs +++ b/src/logs.rs @@ -713,6 +713,13 @@ pub(crate) fn record_for_pull_request(root: &Path, url: &str) -> anyhow::Result< Ok(run_for_pull_request(root, url)?.map(|(path, _)| path)) } +pub(crate) fn self_merge_check_holds( + logs_dir: &Path, +) -> anyhow::Result { + let snapshot = reading::Snapshot::load(logs_dir, chrono::Local::now())?; + Ok(reading::PullRequestAttribution::new(&snapshot)) +} + /// Where this command and all its child Runs keep Session traces on `repo`. pub fn session_dir(repo: &Repo) -> PathBuf { let record = record(); diff --git a/src/logs/command_record.rs b/src/logs/command_record.rs index f1501660c..226d3559e 100644 --- a/src/logs/command_record.rs +++ b/src/logs/command_record.rs @@ -499,7 +499,7 @@ impl CommandRecord { .err() .map(|cause| cause.full().to_owned()) }) - .or_else(|| account.sign_off_hold.map(ToString::to_string)); + .or_else(|| account.review_hold.map(ToString::to_string)); // A plan limit pauses work; it is not a failure to attribute. let failure = account .ended diff --git a/src/logs/reading.rs b/src/logs/reading.rs index e05fa251d..b32a251f5 100644 --- a/src/logs/reading.rs +++ b/src/logs/reading.rs @@ -27,9 +27,8 @@ use super::effects::OnMachine; use super::pass_starts::{self, PassStart}; pub(super) use super::usual_range::UsualRange; use super::{Pass, activity}; -pub(super) use attribution::{ - CommandIdentity, PullRequestAttribution, identity as pull_request_key, -}; +pub(crate) use attribution::PullRequestAttribution; +pub(super) use attribution::{CommandIdentity, identity as pull_request_key}; pub(super) use health::Health; pub(super) use history::Command as HistoricalCommand; pub(super) use inbox::{Departure, Group, InboxItem, NeedsYouKind, RowOrder}; diff --git a/src/logs/reading/attribution.rs b/src/logs/reading/attribution.rs index f3a6d1738..cc362690b 100644 --- a/src/logs/reading/attribution.rs +++ b/src/logs/reading/attribution.rs @@ -30,10 +30,11 @@ impl CommandIdentity { struct Candidate { identity: CommandIdentity, started_at: Option>, + held_by_self_merge_check: bool, } /// One matching and ordering rule for Scoring, Bug origins and Run metrics. -pub(in crate::logs) struct PullRequestAttribution { +pub(crate) struct PullRequestAttribution { candidates: BTreeMap>, } @@ -52,11 +53,20 @@ impl PullRequestAttribution { /// Invalid starts precede valid instants; lexical path/name break ties. pub(in crate::logs) fn latest(&self, url: &str) -> Option<&CommandIdentity> { + self.latest_candidate(url) + .map(|candidate| &candidate.identity) + } + + fn latest_candidate(&self, url: &str) -> Option<&Candidate> { self.candidates .get(&identity(url))? .iter() .max_by_key(|candidate| (candidate.started_at, &candidate.identity)) - .map(|candidate| &candidate.identity) + } + + pub(crate) fn self_merge_check_held(&self, url: &str) -> bool { + self.latest_candidate(url) + .is_some_and(|candidate| candidate.held_by_self_merge_check) } /// A saved local identity is authoritative, including its PR membership. @@ -83,6 +93,11 @@ impl PullRequestAttribution { .push(Candidate { identity: CommandIdentity::of(command), started_at: DateTime::parse_from_rfc3339(&command.record.started_at).ok(), + held_by_self_merge_check: command.record.outcome.as_deref() + == Some("ready for review") + && command.record.cause.as_deref().is_some_and(|cause| { + cause.starts_with(crate::self_merge_check::HOLD_PREFIX) + }), }); } // Snapshot has already excluded orphaned and unmatched child records. diff --git a/src/main.rs b/src/main.rs index 274a8b15b..f63d41535 100644 --- a/src/main.rs +++ b/src/main.rs @@ -125,6 +125,7 @@ mod scoring; mod scratch; #[cfg(target_os = "linux")] mod security; +mod self_merge_check; #[cfg(target_os = "linux")] mod session; #[cfg(target_os = "linux")] @@ -239,6 +240,7 @@ Start from the issue's clone. The Base branch is the branch checked out; positiv An issue with sub-issues starts a Spec run: its Tickets merge into a Spec branch; merge on a Spec merges the Spec PR. is one quoted free-text argument. Shared options (before or after the Issue URL or number, or after a Pass command; -- prefixes accepted, once each, without opposites): merge / no-merge Merge the pull request / leave it for review + self-merge-check / no-self-merge-check Enable / disable the repository's Self-merge check for this Command email [
] / no-email Send a Run notification / skip it (email-unless-merged [
]: unless merged) base-fix / no-base-fix Allow / forbid fixing inherited CI failures parallel Run up to Tickets at once (Spec runs; default 3) @@ -555,6 +557,11 @@ fn main() -> ExitCode { Ok(started) => started, Err(failure) => return failure, }; + if given.is_none() + && let Err(error) = flags.validate_merge_check(&issue.repo(), &config) + { + return argument_error(format_args!("{error}")); + } let mut asks = asks_of(&config); let authors = config.implementation_authors(&issue.repo(), &flags.trust_authors); let started_by = given diff --git a/src/notification.rs b/src/notification.rs index 5ad46b3ae..e505798c2 100644 --- a/src/notification.rs +++ b/src/notification.rs @@ -406,7 +406,7 @@ fn body( took: Duration, ) -> String { let mut text = format!("Result: {}\n", account.outcome); - if let Some(hold) = account.sign_off_hold { + if let Some(hold) = account.review_hold { text += &format!("Waiting for: {hold}\n"); } if let Subject::Issue { @@ -785,7 +785,7 @@ mod tests { security_fix: None, security_close: None, failed_reproduction: None, - sign_off_hold: None, + review_hold: None, pre_audit_failure: None, recovery: None, urls: vec![PR], @@ -813,7 +813,7 @@ mod tests { security_fix: None, security_close: None, failed_reproduction: None, - sign_off_hold: None, + review_hold: None, pre_audit_failure: None, recovery: None, urls: Vec::new(), diff --git a/src/pickup.rs b/src/pickup.rs index ebc73aeb5..bb9653602 100644 --- a/src/pickup.rs +++ b/src/pickup.rs @@ -153,6 +153,9 @@ pub fn run( order: PickupOrder, skip_authors: &crate::skip_authors::SkipAuthors, ) -> Result { + if flags.self_merge_check == Some(true) { + flags.validate_merge_check(&launch::repo()?, config)?; + } let Launch { directory, repo, diff --git a/src/processes.rs b/src/processes.rs index b663a4762..c975f0fdd 100644 --- a/src/processes.rs +++ b/src/processes.rs @@ -689,6 +689,7 @@ fn run(command: &ProcessRun) -> Result { security_fix: command.security_fix, security_close: command.security_close, security_review: command.security_review, + self_merge_check: command.self_merge_check, ..Flags::default() }; file.security_fix = file.security_flags.security_fix_allowed(&config); @@ -701,6 +702,15 @@ fn run(command: &ProcessRun) -> Result { Ok(issue) => issue, Err(error) => return Err(failed_before_steps(notification, error)), }; + if command.self_merge_check == Some(true) { + let validation = issue + .as_ref() + .map_or_else(launch::repo, |issue| Ok(issue.repo())) + .and_then(|repo| file.security_flags.validate_merge_check(&repo, &config)); + if let Err(error) = validation { + return Err(failed_before_steps(notification, error)); + } + } if let Some(issue) = &issue { // Issue validation, branch selection and Claim creation all use // GitHub before the first Step. They share the Command's wait budget @@ -857,14 +867,14 @@ fn notify( .all(|resolution| resolution.goal() == Some(Goal::Merged)); let not_reproduced = completed.unreproduced_bug.as_ref(); let delivered = completed.last_delivery(); - let sign_off_hold = delivered - .and_then(crate::run::Resolution::sign_off_hold) + let review_hold = delivered + .and_then(crate::run::Resolution::review_hold) .filter(|_| outcome == "succeeded"); let account_outcome = if outcome == "succeeded" && not_reproduced.is_some() { "bug not reproduced" } else if merged { Goal::Merged.outcome() - } else if sign_off_hold.is_some() { + } else if review_hold.is_some() { Goal::ReadyForReview.outcome() } else { outcome @@ -901,7 +911,7 @@ fn notify( .as_deref() .map(crate::run_ending::Review::OutcomeLine), failed_reproduction: None, - sign_off_hold, + review_hold, pre_audit_failure: None, security_findings: completed.security_findings.as_deref(), security_findings_waiting: false, @@ -1166,6 +1176,12 @@ fn execute_groups( if let Some((name, error)) = group_error { return Err(skip_remaining(&prepared.steps[range.end..], name, error)); } + if let Some(run) = issue_run.as_deref_mut() + && run.child_asks.self_merge_check.is_some() + && !run.delivered + { + run.pull_request.observe_start_body()?; + } let completed = prepared.completed.lock().expect("completed Runs"); let early_end = completed .architecture_end @@ -1439,6 +1455,7 @@ fn run_land_tickets( crate::security::FixAsk::Forbid }), security_close: prepared.security_flags.security_close, + self_merge_check: prepared.security_flags.self_merge_check, ..Flags::default() }; let mut asks = Asks::of_run(run.issue, &flags, &config); @@ -1680,6 +1697,7 @@ fn run_published( crate::security::FixAsk::Forbid }), security_close: run.security_flags.security_close, + self_merge_check: run.security_flags.self_merge_check, ..Flags::default() }; let mut asks = Asks::of_run(&issue, &flags, &config); diff --git a/src/processes/review.rs b/src/processes/review.rs index c6ff65f64..c4f2a63e1 100644 --- a/src/processes/review.rs +++ b/src/processes/review.rs @@ -26,6 +26,7 @@ pub(crate) fn run(command: ReviewArgs) -> Result { let repo = crate::issue::Repo::of_origin(&launch.run(&["config", "remote.origin.url"])?) .context("review --author needs a GitHub origin")?; + command.flags.validate_merge_check(&repo, &config)?; logs::pass_fired(&repo); let skip = |reason: &dyn std::fmt::Display| { logs::skipped(logs::Pass::Review, &repo, reason); @@ -109,6 +110,7 @@ pub(super) fn custom(command: &ProcessRun, checking: bool) -> Result { email: command.email.clone(), security_review: command.security_review, goal: command.goal, + self_merge_check: command.self_merge_check, ..Flags::default() }, Mode::Address, @@ -176,6 +178,8 @@ impl ReviewProcess { pr.url ); let repo = pr.issue.repo(); + flags.validate_merge_check(&repo, &config)?; + let check = flags.merge_check_for(&repo, &config); let mut command = CommandChoice::of(&flags.harness, &config); if checking { let snapshot = GitHub::new().review_pull_request(pr)?; @@ -250,6 +254,7 @@ impl ReviewProcess { let mut last_log = None; let mut delivered = false; let mut merged = false; + let mut review_hold = None; let mut recovery = None; let pass = reservation.is_some(); let run_started = Utc::now() - crate::run::STARTED_MARGIN; @@ -257,8 +262,8 @@ impl ReviewProcess { let github = GitHub::new(); // Validate before reserving, so an ineligible explicit PR changes // no label. Capture again after reservation for the actual run. - let snapshot = github.review_pull_request(pr)?; - notification.pull_request(pr, &snapshot.title); + let initial = github.review_pull_request(pr)?; + notification.pull_request(pr, &initial.title); let _reservation = match reservation { Some(held) => held, None => Reservation::take(&launch, &github, pr)? @@ -622,6 +627,8 @@ impl ReviewProcess { match (self_merge::SelfMerge { pr, snapshot: &snapshot, + start_body: &initial.body, + check, closing_issues: &closing_issues, choice: &step.choice, logs: &logs, @@ -633,7 +640,15 @@ impl ReviewProcess { { Ok(reached) => { last_log = reached.log.or(last_log.take()); - merged = true; + merged = reached.resolution.goal() == Some(Goal::Merged); + if let crate::run::Resolution::Held { hold, .. } = + reached.resolution + { + progress::step(crate::run_ending::held_ready( + &pr.url, &hold, + )); + review_hold = Some(hold); + } pr.url.clone() } Err(failed) => { @@ -702,7 +717,7 @@ impl ReviewProcess { review: None, triage: None, failed_reproduction: None, - sign_off_hold: None, + review_hold: review_hold.as_deref(), pre_audit_failure: None, security_findings: None, security_findings_waiting: false, diff --git a/src/processes/review/conflicts.rs b/src/processes/review/conflicts.rs index e79c48b03..6ec3b4dc3 100644 --- a/src/processes/review/conflicts.rs +++ b/src/processes/review/conflicts.rs @@ -80,7 +80,7 @@ pub(super) fn eligible( temporary.persist(&path)?; progress::step(format_args!("{}: {:#}", pr.url, conflict.error)); notification.finish(&Account { - sign_off_hold: None, + review_hold: None, recovery: None, outcome: "failed", ended: Err(Cause::of(&conflict.error)), diff --git a/src/processes/review/self_merge.rs b/src/processes/review/self_merge.rs index ac6ec417b..7f204bc6b 100644 --- a/src/processes/review/self_merge.rs +++ b/src/processes/review/self_merge.rs @@ -8,6 +8,8 @@ use crate::worktree::Worktree; pub(super) struct SelfMerge<'a> { pub pr: &'a PullRequestUrl, pub snapshot: &'a ReviewPullRequest, + pub start_body: &'a str, + pub check: Option<&'a crate::self_merge_check::Check>, pub closing_issues: &'a crate::delivery::ClosingIssues, pub choice: &'a Choice, pub logs: &'a session::Logs, @@ -22,6 +24,8 @@ impl SelfMerge<'_> { let Self { pr, snapshot, + start_body, + check, closing_issues, choice, logs, @@ -31,11 +35,13 @@ impl SelfMerge<'_> { } = *self; let child_asks = ChildAsks { harness: choice.clone(), + self_merge_check: check.cloned(), ..ChildAsks::default() }; let mut base_fix = BaseFix::new(None, crate::base_fix::BaseFixAsk::Forbid); let mut target = PullRequest::on_pull_request(pr, &snapshot.branch, &snapshot.base, GitHub::new()); + target.remember_body(pr.issue.number, start_body); target.require_unstacked_base(); crate::delivery::Delivery { security_review: false, diff --git a/src/processes/source.rs b/src/processes/source.rs index 887c1fe0a..75f6e117d 100644 --- a/src/processes/source.rs +++ b/src/processes/source.rs @@ -14,6 +14,9 @@ pub(super) fn execute_issue_steps( prepared: &Prepared, issue_run: &mut IssueRun<'_>, ) -> Result { + if issue_run.child_asks.self_merge_check.is_some() { + issue_run.pull_request.observe_start_body()?; + } if prepared.spec_branch && let Some(checkout) = issue_run.checkout.as_mut() { @@ -954,6 +957,10 @@ pub(super) fn run_issue_branch( spec_tickets: None, child_asks: ChildAsks { sign_off_hold: config.sign_off_hold(&repo).cloned(), + self_merge_check: prepared + .security_flags + .merge_check_for(&repo, config) + .cloned(), ..ChildAsks::default() }, failure: None, @@ -1011,9 +1018,9 @@ pub(super) fn run_issue_branch( drop(held); if result.is_ok() && let Some(delivered) = completed.last_delivery() - && let Some(hold) = delivered.sign_off_hold() + && let Some(hold) = delivered.review_hold() { - let line = crate::run_ending::sign_off_ready(delivered.url(), hold); + let line = crate::run_ending::held_ready(delivered.url(), hold); progress::step(&line); logs::ended(&line); logs::complete(Goal::ReadyForReview.outcome(), Some(&hold.to_string())); diff --git a/src/processes/ticket.rs b/src/processes/ticket.rs index 59818048f..5e3b5a07d 100644 --- a/src/processes/ticket.rs +++ b/src/processes/ticket.rs @@ -28,6 +28,9 @@ pub(crate) fn run_custom( }); file.security_review = delivery.security_review; file.security_fix = delivery.child_asks.security_fix; + if delivery.child_asks.self_merge_check.is_none() { + file.security_flags.self_merge_check = Some(false); + } file.security_flags.security_fix = Some(if file.security_fix { crate::security::FixAsk::Allow } else { diff --git a/src/pull_request.rs b/src/pull_request.rs index 50571c8c8..3f2b8456c 100644 --- a/src/pull_request.rs +++ b/src/pull_request.rs @@ -90,6 +90,7 @@ impl std::error::Error for SpecPrChanged {} /// to the Repair loop. A successful guarded command needs no additional read. pub(crate) enum MergeAttempt { Merged, + Held(String), BaseMoved, Refused(anyhow::Error), } @@ -111,6 +112,7 @@ pub(crate) struct PullRequest { branch: String, base: String, identified: Option, + start_body: Option<(u64, String)>, scope: CaptureScope, security_review_count: Option, /// The Spec PR a Ticket's Self-merge into its Spec branch depends on. @@ -173,6 +175,7 @@ impl PullRequest { branch: branch.to_string(), base: base.to_string(), identified: None, + start_body: None, scope: CaptureScope::Delivery, security_review_count: None, spec_pr: None, @@ -203,6 +206,34 @@ impl PullRequest { self.merge_hold = Some(reason); } + pub(crate) fn remember_body(&mut self, number: u64, body: &str) { + if self + .start_body + .as_ref() + .is_none_or(|(seen, _)| *seen != number) + { + self.start_body = Some((number, body.to_owned())); + } + } + + /// Record a PR already present before an agent session, without binding + /// Delivery's identity before it normally takes ownership. + pub(crate) fn observe_start_body(&mut self) -> Result<()> { + let selector = self.selector(); + if let Some(snapshot) = self.adapter.observe(&self.issue, &selector, false, None)? + && snapshot.pr.is_open() + && let Some(body) = &snapshot.body + { + self.check_ownership( + &snapshot, + &self.branch, + self.identified.as_ref().map(|pr| pr.number), + )?; + self.remember_body(snapshot.pr.number, body); + } + Ok(()) + } + pub(crate) fn use_merge_label(&mut self, label: Option) { self.merge_label = label.map(Box::new); } @@ -555,6 +586,7 @@ impl PullRequest { .create_draft(&self.issue, &self.branch, &self.base, title, body)?; let url = url.trim().to_string(); let number = self.number_from_url(&url)?; + self.remember_body(number, body); self.identified = Some(Identified { number, url }); let snapshot = self .observe(completion)? @@ -599,10 +631,14 @@ impl PullRequest { /// coherent numbered observation. Waiting remains interruptible. pub fn ensure_ready_and_mergeable(&mut self) -> Result<()> { progress::step("checking the PR is open, ready and mergeable"); + self.mergeable_snapshot().map(drop) + } + + fn mergeable_snapshot(&mut self) -> Result { let snapshot = self.settled_ready_snapshot(Readiness::Delivery)?; let url = &snapshot.pr.url; match snapshot.mergeable { - Mergeable::Yes => Ok(()), + Mergeable::Yes => Ok(snapshot), Mergeable::No => bail!("PR {url} is not mergeable"), Mergeable::Unknown => { bail!("GitHub has not worked out whether PR {url} is mergeable") @@ -737,10 +773,20 @@ impl PullRequest { /// request. A blocking review is a terminal policy refusal. GitHub guards /// its head; a retarget between the gate and server merge remains a remote /// race because the request has no expected-base precondition. - pub fn merge( + #[cfg(test)] + fn merge( + &mut self, + watched: &str, + base_current: impl FnMut() -> Result, + ) -> Result { + self.merge_with_check(watched, base_current, None) + } + + pub fn merge_with_check( &mut self, watched: &str, mut base_current: impl FnMut() -> Result, + check: Option<(&crate::self_merge_check::Check, &crate::git::Git)>, ) -> Result { self.ensure_ready_and_mergeable()?; let number = self @@ -757,6 +803,7 @@ impl PullRequest { // handle so the gate can re-observe the captured PR before a retry. let mut transport = self.adapter.clone(); let mut first_attempt = true; + let mut stopped = None; let error = match transport.merge(&issue, number, watched, &mut || { let mut gate = || -> Result { self.check_merge_label()?; @@ -772,12 +819,53 @@ impl PullRequest { // untrusted edit during it still cancels the request. self.check_merge_label()?; } + if current && let Some((check, git)) = check { + let snapshot = self.mergeable_snapshot()?; + if snapshot.head_commit != watched { + stopped = Some(MergeAttempt::Refused(anyhow::anyhow!( + "the PR head changed before the Self-merge check" + ))); + return Ok(false); + } + let Some((_, start_body)) = + self.start_body.as_ref().filter(|(seen, _)| *seen == number) + else { + stopped = + Some(MergeAttempt::Held("PR body at start is unavailable".into())); + return Ok(false); + }; + if let Some(reason) = + check.run(git, &issue.repo_slug(), &self.base, &snapshot, start_body)? + { + stopped = Some(MergeAttempt::Held(reason)); + return Ok(false); + } + self.check_merge_label()?; + self.check_merge_policy(number)?; + if !base_current()? { + return Ok(false); + } + self.check_merge_label()?; + let rechecked = self.mergeable_snapshot()?; + if rechecked.head_commit != watched { + stopped = Some(MergeAttempt::Refused(anyhow::anyhow!( + "the PR head changed during the Self-merge check" + ))); + return Ok(false); + } + if rechecked.body != snapshot.body { + stopped = Some(MergeAttempt::Held( + "PR body changed during the Self-merge check".into(), + )); + return Ok(false); + } + } Ok(current) }; gate().context(SelfMergeGate) }) { Ok(true) => return Ok(self.confirm_self_merge()), - Ok(false) => return Ok(MergeAttempt::BaseMoved), + Ok(false) => return Ok(stopped.unwrap_or(MergeAttempt::BaseMoved)), Err(error) if error.is::() => return Err(error), Err(error) => error, }; @@ -884,6 +972,9 @@ impl PullRequest { fn capture(&mut self, snapshot: &PrSnapshot) -> Result<()> { let number = self.identified.as_ref().map(|pr| pr.number); self.check_ownership(snapshot, &self.branch, number)?; + if let Some(body) = &snapshot.body { + self.remember_body(snapshot.pr.number, body); + } if self.identified.is_none() { self.identified = Some(Identified { number: snapshot.pr.number, @@ -1180,6 +1271,7 @@ mod tests { fn snapshot() -> PrSnapshot { PrSnapshot { + body: Some(String::new()), pr: Record { number: 12, url: URL.to_string(), diff --git a/src/run.rs b/src/run.rs index 4f41e5e78..5d31ae68b 100644 --- a/src/run.rs +++ b/src/run.rs @@ -66,9 +66,9 @@ pub enum Resolution { url: String, goal: Goal, }, - SignOffHeld { + Held { url: String, - hold: Box, + hold: Box, }, NotReproduced { comment_url: String, @@ -84,10 +84,27 @@ pub enum Resolution { }, } +#[derive(Debug, PartialEq, Eq)] +pub enum ReviewHold { + SignOff(crate::config::SignOffHold), + SelfMergeCheck(String), +} + +impl std::fmt::Display for ReviewHold { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::SignOff(hold) => hold.fmt(f), + Self::SelfMergeCheck(reason) => { + write!(f, "{}{reason}", crate::self_merge_check::HOLD_PREFIX) + } + } + } +} + impl Resolution { - pub fn delivered(url: String, goal: Goal, hold: Option) -> Self { + pub fn delivered(url: String, goal: Goal, hold: Option) -> Self { match hold { - Some(hold) => Self::SignOffHeld { + Some(hold) => Self::Held { url, hold: Box::new(hold), }, @@ -98,16 +115,16 @@ impl Resolution { pub fn goal(&self) -> Option { match self { Self::PullRequest { goal, .. } => Some(*goal), - Self::SignOffHeld { .. } => Some(Goal::ReadyForReview), + Self::Held { .. } => Some(Goal::ReadyForReview), Self::NotReproduced { .. } | Self::ArchitectureReview { .. } | Self::BaseCiUnchanged { .. } => None, } } - pub fn sign_off_hold(&self) -> Option<&crate::config::SignOffHold> { + pub fn review_hold(&self) -> Option<&ReviewHold> { match self { - Self::SignOffHeld { hold, .. } => Some(hold), + Self::Held { hold, .. } => Some(hold), Self::PullRequest { .. } | Self::NotReproduced { .. } | Self::ArchitectureReview { .. } @@ -118,7 +135,7 @@ impl Resolution { /// The PR, triage comment, review issue or unchanged Base branch commit. pub fn url(&self) -> &str { match self { - Self::PullRequest { url, .. } | Self::SignOffHeld { url, .. } => url, + Self::PullRequest { url, .. } | Self::Held { url, .. } => url, Self::NotReproduced { comment_url } => comment_url, Self::ArchitectureReview { url, .. } => url, Self::BaseCiUnchanged { url, .. } => url, @@ -487,7 +504,7 @@ fn claim_ending(outcome: &Result) -> claim::Ending { match outcome { Ok(reached) => match &reached.resolution { Resolution::PullRequest { goal, .. } => claim::Ending::Reached(*goal), - Resolution::SignOffHeld { .. } => claim::Ending::Reached(Goal::ReadyForReview), + Resolution::Held { .. } => claim::Ending::Reached(Goal::ReadyForReview), Resolution::NotReproduced { .. } => claim::Ending::NotReproduced, Resolution::ArchitectureReview { .. } | Resolution::BaseCiUnchanged { .. } => { claim::Ending::BeforeDelivery @@ -1084,6 +1101,8 @@ mod tests { merge_label_from: Vec::new(), delivery_limits: crate::delivery::Limits::default(), sign_off_hold: None, + self_merge_check: None, + self_merge_check_override: None, security_review_harness: None, security_review_default: None, security_fix: false, diff --git a/src/run_ending.rs b/src/run_ending.rs index 94369234e..0d97af7cf 100644 --- a/src/run_ending.rs +++ b/src/run_ending.rs @@ -56,7 +56,7 @@ pub fn read(ending: &Ending) -> Result, &Skip> { security_fix: None, security_close: None, failed_reproduction: None, - sign_off_hold: None, + review_hold: None, pre_audit_failure: None, recovery: None, urls: vec![&ended.pr_url], @@ -82,7 +82,7 @@ pub fn read(ending: &Ending) -> Result, &Skip> { security_fix: None, security_close: None, failed_reproduction: None, - sign_off_hold: None, + review_hold: None, pre_audit_failure: None, recovery: None, urls: Vec::new(), @@ -113,7 +113,7 @@ pub fn read(ending: &Ending) -> Result, &Skip> { security_fix: None, security_close: None, failed_reproduction: None, - sign_off_hold: None, + review_hold: None, pre_audit_failure: None, recovery: None, urls: Vec::new(), @@ -197,7 +197,7 @@ pub fn read(ending: &Ending) -> Result, &Skip> { security_fix: None, security_close: None, failed_reproduction: None, - sign_off_hold: None, + review_hold: None, pre_audit_failure: None, recovery: None, urls: Vec::new(), @@ -214,7 +214,7 @@ pub fn read(ending: &Ending) -> Result, &Skip> { ), }; Ok(Account { - sign_off_hold: None, + review_hold: None, pre_audit_failure: if !audited.audit_started { audited.outcome.as_ref().err().map(|failed| { crate::github::operational_cause(&failed.error) @@ -262,8 +262,8 @@ pub struct Account<'a> { pub interrupted: bool, /// Its pull request's URL, if it has one. pub pr_url: Option<&'a str>, - /// The check and label that held a successful Run for sign-off. - pub sign_off_hold: Option<&'a crate::config::SignOffHold>, + /// The reason a successful Run held Self-merge or waited for sign-off. + pub review_hold: Option<&'a crate::run::ReviewHold>, /// Its published GitHub Release URL, if a Release run published one. pub release_url: Option<&'a str>, /// What a failed Run says after its cause, if Inherited failures failed @@ -474,7 +474,7 @@ impl<'a> Account<'a> { .unwrap_or(match &reached.resolution { crate::run::Resolution::NotReproduced { .. } => "bug not reproduced", crate::run::Resolution::PullRequest { .. } - | crate::run::Resolution::SignOffHeld { .. } + | crate::run::Resolution::Held { .. } | crate::run::Resolution::ArchitectureReview { .. } | crate::run::Resolution::BaseCiUnchanged { .. } => "succeeded", }), @@ -482,7 +482,7 @@ impl<'a> Account<'a> { crate::run::Resolution::PullRequest { url, goal } => { format!("PR {url} is {}", goal.outcome()) } - crate::run::Resolution::SignOffHeld { url, hold } => sign_off_ready(url, hold), + crate::run::Resolution::Held { url, hold } => held_ready(url, hold), crate::run::Resolution::NotReproduced { comment_url } => { format!("bug not reproduced: {comment_url}") } @@ -510,7 +510,7 @@ impl<'a> Account<'a> { Some(Review::OutcomeLine(reason)) } crate::run::Resolution::PullRequest { .. } - | crate::run::Resolution::SignOffHeld { .. } + | crate::run::Resolution::Held { .. } | crate::run::Resolution::NotReproduced { .. } | crate::run::Resolution::BaseCiUnchanged { .. } => None, }, @@ -519,7 +519,7 @@ impl<'a> Account<'a> { security_fix: None, security_close: None, failed_reproduction: None, - sign_off_hold: reached.resolution.sign_off_hold(), + review_hold: reached.resolution.review_hold(), pre_audit_failure: None, recovery: None, urls: vec![reached.resolution.url()], @@ -553,7 +553,7 @@ impl<'a> Account<'a> { security_fix: None, security_close: None, failed_reproduction: None, - sign_off_hold: None, + review_hold: None, pre_audit_failure: None, recovery: failed.recovery.as_deref(), urls: failed.pr_url.as_deref().into_iter().collect(), @@ -594,7 +594,7 @@ impl<'a> Account<'a> { security_fix: None, security_close: None, failed_reproduction: None, - sign_off_hold: None, + review_hold: None, pre_audit_failure: None, recovery: None, urls: vec![reviewed.url()], @@ -789,10 +789,10 @@ impl Shown { } } -const SIGN_OFF_WAITING: &str = " is ready for review waiting for "; +const REVIEW_WAITING: &str = " is ready for review waiting for "; -pub(crate) fn sign_off_ready(url: &str, hold: &crate::config::SignOffHold) -> String { - format!("PR {url}{SIGN_OFF_WAITING}{hold}") +pub(crate) fn held_ready(url: &str, hold: &crate::run::ReviewHold) -> String { + format!("PR {url}{REVIEW_WAITING}{hold}") } /// The ending of a child Run, as read back from what it showed. @@ -844,13 +844,16 @@ impl Reader { } /// A child requested to merge can instead leave its printed PR held. - pub fn sign_off_hold(&self, pr_url: &str) -> Option<&str> { + pub fn review_hold(&self, pr_url: &str) -> Option<&str> { let (url, hold) = self .cause .as_deref()? .strip_prefix("PR ")? - .split_once(SIGN_OFF_WAITING)?; - (url == pr_url && hold.starts_with("Sign-off hold for ")).then_some(hold) + .split_once(REVIEW_WAITING)?; + (url == pr_url + && (hold.starts_with("Sign-off hold for ") + || hold.starts_with(crate::self_merge_check::HOLD_PREFIX))) + .then_some(hold) } /// Read the next line of the child's stderr. @@ -975,7 +978,7 @@ mod tests { security_fix: None, security_close: None, failed_reproduction: None, - sign_off_hold: None, + review_hold: None, pre_audit_failure: None, recovery: None, urls: vec![PR], @@ -1003,7 +1006,7 @@ mod tests { security_fix: None, security_close: None, failed_reproduction: None, - sign_off_hold: None, + review_hold: None, pre_audit_failure: None, recovery: None, urls: Vec::new(), @@ -1198,7 +1201,7 @@ mod tests { security_fix: None, security_close: None, failed_reproduction: None, - sign_off_hold: None, + review_hold: None, pre_audit_failure: None, recovery: None, urls: vec![PLAN], diff --git a/src/security.rs b/src/security.rs index a93dc1bd8..1ff9cbf4f 100644 --- a/src/security.rs +++ b/src/security.rs @@ -172,6 +172,12 @@ pub fn run( config: &UserConfig, harness: &mut Choice, ) -> Outcome { + if flags.self_merge_check == Some(true) + && let Err(error) = + launch::repo().and_then(|repo| flags.validate_merge_check(&repo, config)) + { + return Outcome::Audited(error.into()); + } let offer_command = (flags.security_fix.is_none() && config.security_fix.is_none()) .then(|| crate::args::retry_with_security_fix(base, flags)); let Launch { diff --git a/src/self_merge_check.rs b/src/self_merge_check.rs new file mode 100644 index 000000000..b8772745f --- /dev/null +++ b/src/self_merge_check.rs @@ -0,0 +1,176 @@ +//! Run the repository's last decision before a guarded Self-merge request. + +use std::io::Write; +use std::os::unix::fs::PermissionsExt; +use std::path::{Component, Path}; +use std::process::Command; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result, ensure}; + +use crate::git::Git; +use crate::github::PrSnapshot; +use crate::process; + +const TIMEOUT: Duration = Duration::from_secs(60); +const REASON_LIMIT: usize = 240; +pub(crate) const HOLD_PREFIX: &str = "Self-merge check held: "; + +#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize)] +#[serde(try_from = "String", into = "String")] +pub(crate) struct Check { + source: String, + words: Vec, +} + +impl TryFrom for Check { + type Error = anyhow::Error; + + fn try_from(source: String) -> Result { + let words = shlex::split(&source).context("expected a quoted command and arguments")?; + let program = words + .first() + .filter(|word| !word.is_empty()) + .context("expected a nonblank command")?; + let path = Path::new(program); + ensure!( + path.is_absolute() + || path + .components() + .all(|part| { matches!(part, Component::Normal(_) | Component::CurDir) }), + "repository commands must be paths inside the repository" + ); + ensure!( + !words.iter().any(|word| word.contains('\0')), + "command contains a NUL" + ); + Ok(Self { source, words }) + } +} + +impl From for String { + fn from(check: Check) -> Self { + check.source + } +} + +impl Check { + pub(crate) fn run( + &self, + git: &Git, + repo: &str, + base: &str, + pr: &PrSnapshot, + start_body: &str, + ) -> Result> { + let result = self.execute(git, repo, base, pr, start_body); + if crate::interrupt::requested() { + anyhow::bail!("interrupted"); + } + let reason = match result { + Ok(output) if output.status.success() => { + crate::progress::step(format!("Self-merge check {:?} exited 0", self.source)); + return Ok(None); + } + Ok(output) => { + let status = output + .status + .code() + .map_or_else(|| output.status.to_string(), |code| code.to_string()); + let stdout = String::from_utf8_lossy(&output.stdout); + let reason = stdout.lines().map(str::trim).find(|line| !line.is_empty()); + let reason = reason.map_or_else( + || format!("Self-merge check exited {status}"), + |line| line.chars().take(REASON_LIMIT).collect(), + ); + crate::progress::step(format!( + "Self-merge check {:?} exited {status}: {reason}", + self.source + )); + reason + } + Err(error) if error.is::() => { + crate::progress::step(format!("Self-merge check {:?} timed out", self.source)); + "Self-merge check timed out".into() + } + Err(error) => { + crate::progress::step(format!( + "Self-merge check {:?} could not start: {error:#}", + self.source + )); + "Self-merge check could not start".into() + } + }; + Ok(Some(reason)) + } + + fn execute( + &self, + git: &Git, + repo: &str, + base: &str, + pr: &PrSnapshot, + start_body: &str, + ) -> Result { + let scratch = crate::scratch::temp_dir().context("Command scratch is unavailable")?; + let program = Path::new(&self.words[0]); + let script; + let executable = if program.is_absolute() { + let resolved = program.canonicalize()?; + for path in [program, &resolved] { + ensure!( + !path + .ancestors() + .skip(1) + .any(|dir| dir.join(".git").symlink_metadata().is_ok()), + "absolute Self-merge check paths must be outside Git worktrees" + ); + } + program + } else { + // Read the blob directly, without checking out the ref or applying + // filters from an Issue branch. The explicit refspec names origin's + // head even if this clone limits its usual fetch refspec. + let reference = format!("refs/remotes/origin/{base}"); + git.fetch(&[&format!("+refs/heads/{base}:{reference}")])?; + let commit = git.run(&["rev-parse", "--verify", &format!("{reference}^{{commit}}")])?; + let path = program + .components() + .filter_map(|component| match component { + Component::Normal(word) => word.to_str(), + Component::CurDir + | Component::ParentDir + | Component::RootDir + | Component::Prefix(_) => None, + }) + .collect::>() + .join("/"); + let blob = git.run_bytes(&["cat-file", "blob", &format!("{commit}:{path}")])?; + let mut file = tempfile::Builder::new() + .prefix("self-merge-check-") + .tempfile_in(&scratch)?; + file.write_all(&blob)?; + file.as_file() + .set_permissions(std::fs::Permissions::from_mode(0o700))?; + // Close the writable descriptor before exec (ETXTBSY on Linux). + script = file.into_temp_path(); + script.as_ref() + }; + process::one_shot( + Command::new(executable) + .args(&self.words[1..]) + .current_dir(scratch) + .env("PR_NUMBER", pr.pr.number.to_string()) + .env( + "PR_BODY", + pr.body.as_deref().context("PR body is unavailable")?, + ) + .env("PR_BODY_AT_START", start_body) + .env("REPOSITORY", repo) + .env("BASE_BRANCH", base), + "Self-merge check", + process::Stdout::Capture, + Instant::now() + TIMEOUT, + ) + } +} diff --git a/src/spec_run.rs b/src/spec_run.rs index ad02910bc..4bc27c445 100644 --- a/src/spec_run.rs +++ b/src/spec_run.rs @@ -400,7 +400,7 @@ impl Outside for ChildRunsAndGitHub<'_> { Ended::ArchitectureReview { reason } => { format!("#{number} Architecture review ended: {reason}") } - Ended::SignOffHeld { pr_url, hold } => { + Ended::Held { pr_url, hold } => { format!("#{number} did not land: {hold} on {pr_url}") } Ended::Reached { .. } => format!("#{number} landed"), diff --git a/src/spec_run/ticket_board.rs b/src/spec_run/ticket_board.rs index b2943d468..dd1d787a3 100644 --- a/src/spec_run/ticket_board.rs +++ b/src/spec_run/ticket_board.rs @@ -383,7 +383,7 @@ impl TicketBoard { Some(Standing::Ended(Ended::ArchitectureReview { reason })) => { return format!("Architecture review ended: {reason}"); } - Some(Standing::Ended(Ended::SignOffHeld { pr_url, hold })) => { + Some(Standing::Ended(Ended::Held { pr_url, hold })) => { return format!("did not land: {hold} on {pr_url}"); } Some(Standing::Running) => return "running".to_string(), diff --git a/tests/ci.rs b/tests/ci.rs index a06f79850..41ec5054e 100644 --- a/tests/ci.rs +++ b/tests/ci.rs @@ -60,6 +60,40 @@ sign_off_hold = { "Acme/Widgets" = { check = "Visual sign-off", label = "needs-s const SIGN_OFF_LABEL: &str = "gh fake labels 1 '[\"Needs-Sign-Off\"]'\n"; const SIGN_OFF_RED: &str = r#"[{"name":"Visual sign-off","conclusion":"failure"}]"#; +#[test] +fn a_self_merge_check_and_sign_off_hold_apply_independently() { + for (checks, reason) in [ + (SIGN_OFF_RED, "Sign-off hold for"), + (GREEN, "repository policy holds"), + ] { + let scenario = Scenario::new(); + let check = scenario.path("check"); + support::write_executable(&check, "#!/bin/sh\necho repository policy holds\nexit 1\n"); + scenario.user_config_is(&format!( + "{SIGN_OFF_CONFIG}\n[merge]\nself_merge_check = {{ \"acme/widgets\" = {:?} }}\n", + check.to_str().unwrap() + )); + scenario.agent_does(&format!( + "{AGENT_OPENS_PR}{SIGN_OFF_LABEL}{}", + checks_on_head(checks) + )); + + let result = scenario.run(&["merge", &scenario.issue_url(7)]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!(result.stderr.contains(reason), "{}", result.stderr); + assert_eq!( + result.stderr.contains("repository policy holds"), + checks == GREEN, + "{}", + result.stderr + ); + assert_eq!(scenario.claude_calls().len(), 1); + assert!(scenario.gh_calls_of("pr", "merge").is_empty()); + assert!(rerun_requests(&scenario).is_empty()); + } +} + fn install_sign_off_gh_wrapper(scenario: &Scenario, body: &str) { use std::fs; use std::os::unix::fs::PermissionsExt; diff --git a/tests/console/inbox.rs b/tests/console/inbox.rs index cc248d5d4..0cd019887 100644 --- a/tests/console/inbox.rs +++ b/tests/console/inbox.rs @@ -3,6 +3,23 @@ use serde_json::Value; use std::path::Path; use std::{fs, process::Command}; +#[test] +fn a_self_merge_check_reason_appears_in_the_ready_for_review_row() { + let home = tempfile::tempdir().unwrap(); + configure(home.path()); + let mut command = record(home.path(), 7, Some("ready for review"), 0); + command["cause"] = "Self-merge check held: Day shift decides".into(); + super::write_record(home.path(), 7, &command); + let console = Console::start(Path::new(env!("CARGO_BIN_EXE_thirdshift")), home.path()); + + let page = console.get("/").error_for_status().unwrap().text().unwrap(); + + assert!( + section(&page, "ready for review").contains("Self-merge check held: Day shift decides") + ); + assert!(!section(&page, "needs you").contains("Self-merge check held: Day shift decides")); +} + #[test] fn link_only_fleet_entry_has_no_copyable_status_command() { let home = tempfile::tempdir().unwrap(); diff --git a/tests/fix_base_ci.rs b/tests/fix_base_ci.rs index 30f52bf88..9ca1e02da 100644 --- a/tests/fix_base_ci.rs +++ b/tests/fix_base_ci.rs @@ -412,6 +412,28 @@ fn merge_base_fix_self_merges_only_the_new_base_repair() { } } +#[test] +fn a_self_merge_check_can_hold_a_base_ci_repair() { + let scenario = Scenario::new(); + scenario.origin_has_commit( + "main", + "check", + "#!/bin/sh\necho base hold\nexit 1\n", + "Add check", + ); + scenario.user_config_is("[merge]\nself_merge_check = { \"acme/widgets\" = \"check\" }\n"); + failed_base(&scenario, 2); + scenario.agent_does(FIX); + + let result = scenario.run(&["fix", "base", "main", "merge-base-fix", "no-email"]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!(result.stderr.contains("base hold"), "{}", result.stderr); + assert!(scenario.gh_calls_of("pr", "merge").is_empty()); + assert_eq!(scenario.gh_state()["prs"][0]["state"], "OPEN"); + assert_eq!(scenario.gh_state()["prs"][0]["isDraft"], false); +} + fn recorded_review(scenario: &Scenario, branch: &str) { let head = scenario.origin_git(&["rev-parse", branch]); let mut state = scenario.gh_state(); diff --git a/tests/fix_pass.rs b/tests/fix_pass.rs index 3f448a463..bdb99042f 100644 --- a/tests/fix_pass.rs +++ b/tests/fix_pass.rs @@ -17,6 +17,55 @@ const SIGN_OFF_CONFIG: &str = r#" sign_off_hold = { "Acme/Widgets" = { check = "Visual sign-off", label = "needs-sign-off" } } "#; +#[test] +fn fix_pass_skips_a_self_merge_check_hold_until_the_pr_has_red_ci() { + let scenario = Scenario::new(); + let check = scenario.path("hold-check"); + support::write_executable(&check, "#!/bin/sh\necho Day shift decides\nexit 1\n"); + scenario.user_config_is(&format!( + "[merge]\nalways = true\nself_merge_check = {{ \"acme/widgets\" = {:?} }}\n", + check.to_str().unwrap() + )); + scenario.agent_does( + "echo feature > feature.txt; git add feature.txt; git commit -qm 'Add feature'", + ); + let held = scenario.run(&[&scenario.issue_url(7)]); + assert_eq!(held.code, Some(0), "{}", held.stderr); + assert!(held.stderr.contains("Day shift decides"), "{}", held.stderr); + advance_base(&scenario, 2); + let head = scenario.origin_git(&["rev-parse", "issue-7"]); + let base = scenario.origin_git(&["rev-parse", "main"]); + let mut state = scenario.gh_state(); + record_behind(&mut state, head.trim(), base.trim(), 2); + scenario.write_gh_state(&state); + scenario.agent_does(REPAIR_CI); + + let skipped = fix_pass(&scenario, &["behind", "2"]); + + assert_eq!(skipped.code, Some(0), "{}", skipped.stderr); + assert!( + skipped.stderr.contains("no eligible pull request"), + "{}", + skipped.stderr + ); + assert_eq!(scenario.origin_git(&["rev-parse", "issue-7"]), head); + assert_eq!(scenario.claude_calls().len(), 1); + + state = scenario.gh_state(); + state["checks"][head.trim()] = json!([{"name": "test", "conclusion": "failure"}]); + scenario.write_gh_state(&state); + let repaired = fix_pass(&scenario, &["behind", "2"]); + + assert_eq!(repaired.code, Some(0), "{}", repaired.stderr); + assert_eq!( + scenario.origin_file("issue-7", "ci-fix.txt").as_deref(), + Some("repaired\n"), + "{}", + repaired.stderr + ); + assert_eq!(scenario.claude_calls().len(), 2); +} + #[test] fn pass_skips_a_sign_off_hold_and_repairs_the_next_pull_request() { let scenario = Scenario::new(); diff --git a/tests/merge_run.rs b/tests/merge_run.rs index f23c3576c..9d96229a1 100644 --- a/tests/merge_run.rs +++ b/tests/merge_run.rs @@ -49,6 +49,27 @@ fn a_merge_label_from_a_listed_login_requests_self_merge() { assert!(saved.contains(attribution), "{saved}"); } +#[test] +fn a_merge_label_still_obeys_the_self_merge_check() { + let scenario = Scenario::new(); + scenario.user_config_is(&format!( + "{MERGE_LABEL_CONFIG}self_merge_check = {{ \"acme/widgets\" = \"check\" }}\n" + )); + scenario.origin_has_commit( + "main", + "check", + "#!/bin/sh\necho label hold\nexit 1\n", + "Add check", + ); + label_issue_for_merge(&scenario); + scenario.agent_does(AGENT_OPENS_PR); + + let result = scenario.run(&[&scenario.issue_url(7)]); + + assert_merge_label_leaves_pr_ready(&scenario, &result); + assert!(result.stderr.contains("label hold"), "{}", result.stderr); +} + fn assert_merge_label_leaves_pr_ready(scenario: &Scenario, result: &support::RunResult) { assert_eq!(result.code, Some(0), "{}", result.stderr); assert!( diff --git a/tests/process.rs b/tests/process.rs index 9d3e572eb..4002b3adc 100644 --- a/tests/process.rs +++ b/tests/process.rs @@ -5401,6 +5401,27 @@ fn prepare_ship(body: &str) -> Scenario { scenario } +#[test] +fn a_custom_self_merge_step_obeys_the_self_merge_check() { + let scenario = prepare_ship(LAND); + scenario.origin_has_commit( + "main", + "check", + "#!/bin/sh\necho process hold\nexit 1\n", + "Add check", + ); + scenario.user_config_is("[merge]\nself_merge_check = { \"acme/widgets\" = \"check\" }\n"); + + let result = scenario.run(&["process", "ship", "issue", "7", "merge"]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!(result.stderr.contains("process hold"), "{}", result.stderr); + assert_eq!(scenario.gh_state()["prs"][0]["state"], "OPEN"); + assert_eq!(scenario.gh_state()["prs"][0]["isDraft"], false); + assert!(scenario.issue_labels(7).is_empty()); + assert!(scenario.gh_calls_of("pr", "merge").is_empty()); +} + #[test] fn a_concurrent_merge_does_not_keep_the_claim_of_a_delivery_only_process() { let scenario = prepare_ship(DELIVER); diff --git a/tests/process/spec_review.rs b/tests/process/spec_review.rs index e87babd00..de2221a3e 100644 --- a/tests/process/spec_review.rs +++ b/tests/process/spec_review.rs @@ -46,6 +46,28 @@ fn prepare_spec(source: &str) -> Scenario { scenario } +#[test] +fn the_self_merge_check_runs_on_the_spec_pr_but_not_its_tickets() { + let scenario = prepare_spec(SPEC_DELIVERY); + scenario.origin_has_commit( + "main", + "check", + "#!/bin/sh\necho spec hold\nexit 1\n", + "Add check", + ); + scenario.user_config_is("[merge]\nself_merge_check = { \"acme/widgets\" = \"check\" }\n"); + + let result = scenario.run(&["process", "complete-spec", "issue", "7", "merge"]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!(result.stderr.contains("spec hold"), "{}", result.stderr); + assert_eq!(pr_from(&scenario, "issue-8")["state"], "MERGED"); + let spec = pr_from(&scenario, "issue-7"); + assert_eq!(spec["state"], "OPEN"); + assert_eq!(spec["isDraft"], false); + assert_eq!(scenario.gh_calls_of("pr", "merge").len(), 1); +} + #[test] fn spec_self_merge_obeys_command_and_user_config_gates() { for (always, flag, merged) in [ diff --git a/tests/process/spec_run.rs b/tests/process/spec_run.rs index 3f790c67c..803615217 100644 --- a/tests/process/spec_run.rs +++ b/tests/process/spec_run.rs @@ -18,3 +18,22 @@ fn the_compiled_spec_run_is_listed_shown_and_passes_check() { ); assert!(source.contains("kind = \"spec-branch\"")); } + +#[test] +fn the_built_in_spec_run_checks_its_final_self_merge_only() { + let scenario = Scenario::new(); + scenario.spec_has_tickets(7, &[(8, &[])]); + scenario.agent_does_for(8, &agent_lands_ticket(8, "issue-7")); + scenario.agent_does_for(7, "true"); + scenario.origin_has_commit("main", "check", "#!/bin/sh\necho built-in spec hold\nexit 1\n", "Add check"); + scenario.user_config_is("[merge]\nself_merge_check = { \"acme/widgets\" = \"check\" }\n"); + + let result = scenario.run(&["merge", &scenario.issue_url(7)]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!(result.stderr.contains("built-in spec hold"), "{}", result.stderr); + assert_eq!(pr_from(&scenario, "issue-8")["state"], "MERGED"); + assert_eq!(pr_from(&scenario, "issue-7")["state"], "OPEN"); + assert_eq!(pr_from(&scenario, "issue-7")["isDraft"], false); + assert!(scenario.issue_labels(7).is_empty()); +} diff --git a/tests/review_merge.rs b/tests/review_merge.rs index 8b4c550cf..1a8a86182 100644 --- a/tests/review_merge.rs +++ b/tests/review_merge.rs @@ -13,6 +13,39 @@ fn pull_request(scenario: &Scenario) -> String { scenario.github_has_pr("colleague", "main", "OPEN") } +#[test] +fn a_review_self_merge_check_keeps_the_review_ready_for_review() { + let scenario = Scenario::new(); + scenario.origin_has_commit( + "main", + "check", + "#!/bin/sh\necho review hold\nexit 1\n", + "Add check", + ); + let url = pull_request(&scenario); + scenario.user_config_is("[merge]\nself_merge_check = { \"acme/widgets\" = \"check\" }\n"); + scenario.agent_does(NO_FINDINGS); + + let result = scenario.run(&["review", &url, "merge"]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert_eq!(scenario.gh_state()["prs"][0]["state"], "OPEN"); + assert_eq!(scenario.gh_state()["prs"][0]["isDraft"], false); + assert!(scenario.gh_calls_of("pr", "merge").is_empty()); + assert!( + !scenario + .issue_labels(1) + .iter() + .any(|label| label == "in-progress") + ); + let record = scenario.command_record("home/.thirdshift/logs/acme/widgets/commands/review"); + assert_eq!(record["outcome"], "ready for review", "{record}"); + assert_eq!( + record["cause"], "Self-merge check held: review hold", + "{record}" + ); +} + #[test] fn review_merge_requires_a_complete_clean_security_review() { for pass in [false, true] { diff --git a/tests/self_merge_check.rs b/tests/self_merge_check.rs new file mode 100644 index 000000000..295705fb3 --- /dev/null +++ b/tests/self_merge_check.rs @@ -0,0 +1,270 @@ +mod support; + +use support::{Scenario, write_executable}; + +const OPEN_PR: &str = r#" +echo feature > feature.txt +git add feature.txt +git commit -qm 'Add feature' +gh pr create --base main --head issue-7 --title 'Add feature' --body 'Closes #7' +"#; + +fn configure(scenario: &Scenario, command: &str) { + scenario.user_config_is(&format!( + "[merge]\nalways = true\nself_merge_check = {{ \"Acme/Widgets\" = {command:?} }}\n" + )); +} + +fn host_check(scenario: &Scenario, script: &str) { + let path = scenario.path("self merge check"); + write_executable(&path, script); + configure(scenario, &format!("'{}' 'one argument'", path.display())); +} + +#[test] +fn a_self_merge_check_hold_leaves_the_pull_request_ready() { + let scenario = Scenario::new(); + host_check( + &scenario, + "#!/bin/sh\nprintf '\\n Day shift decides \\nignored\\n'\nexit 7\n", + ); + scenario.issue_labelled(7, &["ready-for-agent"]); + scenario.agent_does(OPEN_PR); + + let result = scenario.run(&[&scenario.issue_url(7)]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!(result.stdout.contains("/pull/1"), "{}", result.stderr); + let state = scenario.gh_state(); + assert_eq!(state["prs"][0]["state"], "OPEN"); + assert_eq!(state["prs"][0]["isDraft"], false); + assert!(scenario.issue_labels(7).is_empty()); + assert_eq!(scenario.claude_calls().len(), 1); + assert!(scenario.gh_calls_of("pr", "merge").is_empty()); + assert!(scenario.origin_log("issue-7").is_some()); + + let (log, notification) = support::resend::saved_notification(&scenario, "issue"); + let inbox = scenario.run(&["status"]); + assert!( + inbox.stdout.contains("Ready for review"), + "{}", + inbox.stdout + ); + for text in [ + result.stderr, + std::fs::read_to_string(log).unwrap(), + notification, + inbox.stdout, + ] { + assert!(text.contains("Day shift decides"), "{text}"); + assert!(!text.contains("ignored"), "{text}"); + } +} + +#[test] +fn a_passing_host_check_receives_the_opening_body_and_current_body() { + let scenario = Scenario::new(); + host_check( + &scenario, + r#"#!/bin/sh +set -eu +test "$#" = 1 && test "$1" = 'one argument' || exit 2 +test "$PR_NUMBER" = 1 && test "$REPOSITORY" = acme/widgets && test "$BASE_BRANCH" = main || exit 3 +test "$PR_BODY_AT_START" = 'Closes #7' || exit 4 +case "$PR_BODY" in *'Closes #7'*'Built with'*) exit 0 ;; *) exit 5 ;; esac +"#, + ); + scenario.agent_does(OPEN_PR); + + let result = scenario.run(&[&scenario.issue_url(7), "--self-merge-check"]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert_eq!( + scenario.gh_state()["prs"][0]["state"], + "MERGED", + "{}", + result.stderr + ); + assert!(result.stderr.contains("exited 0"), "{}", result.stderr); +} + +#[test] +fn a_repair_can_change_the_current_body_without_replacing_the_opening_body() { + let scenario = Scenario::new(); + host_check( + &scenario, + r#"#!/bin/sh +test "$PR_BODY_AT_START" = 'Closes #7' || exit 2 +case "$PR_BODY" in *'Updated by Repair'*) echo observed both bodies; exit 1 ;; *) exit 3 ;; esac +"#, + ); + scenario.agent_does(&format!( + r#"{OPEN_PR} +gh fake checks "$(git rev-parse HEAD)" '[{{"name":"test","conclusion":"failure"}}]' +"# + )); + scenario.agent_does_in_session( + 2, + r#" +git commit --allow-empty -qm Repair +gh fake pr issue-7 body '"Updated by Repair"' +gh fake checks "$(git rev-parse HEAD)" '[{"name":"test","conclusion":"success"}]' +"#, + ); + + let result = scenario.run(&[&scenario.issue_url(7)]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!( + result.stderr.contains("observed both bodies"), + "{}", + result.stderr + ); + assert_eq!(scenario.claude_calls().len(), 2); + assert!(scenario.gh_calls_of("pr", "merge").is_empty()); +} + +#[test] +fn a_check_from_origin_base_ignores_the_issue_branch_copy() { + let scenario = Scenario::new(); + configure(&scenario, "./check"); + scenario.origin_has_commit( + "main", + "check", + "#!/bin/sh\necho Base policy\nexit 1\n", + "Add policy", + ); + scenario.agent_does(&format!( + "printf '#!/bin/sh\\nexit 0\\n' > check\ngit add check\n{OPEN_PR}" + )); + + let result = scenario.run(&[&scenario.issue_url(7)]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!(result.stderr.contains("Base policy"), "{}", result.stderr); + assert_eq!(scenario.gh_state()["prs"][0]["state"], "OPEN"); +} + +#[test] +fn a_missing_or_unstartable_check_holds_and_a_silent_exit_has_a_reason() { + for (command, reason) in [ + ("check", "Self-merge check could not start"), + ( + "/no/such/self-merge-check", + "Self-merge check could not start", + ), + ("silent", "Self-merge check exited 9"), + ("bad-interpreter", "Self-merge check could not start"), + ] { + let scenario = Scenario::new(); + match command { + "silent" => host_check(&scenario, "#!/bin/sh\nexit 9\n"), + "bad-interpreter" => host_check(&scenario, "#!/no/such/interpreter\n"), + _ => configure(&scenario, command), + } + scenario.agent_does(&format!( + "printf '#!/bin/sh\\nexit 0\\n' > check\ngit add check\n{OPEN_PR}" + )); + + let result = scenario.run(&[&scenario.issue_url(7)]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!(result.stderr.contains(reason), "{}", result.stderr); + assert_eq!(scenario.gh_state()["prs"][0]["state"], "OPEN"); + } +} + +#[test] +fn a_timed_out_check_leaves_the_pull_request_ready() { + let scenario = Scenario::new(); + host_check(&scenario, "#!/bin/sh\nsleep 120\n"); + scenario.agent_does(OPEN_PR); + + let result = scenario.run(&[&scenario.issue_url(7)]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!( + result.stderr.contains("Self-merge check timed out"), + "{}", + result.stderr + ); + assert!(scenario.gh_calls_of("pr", "merge").is_empty()); + assert_eq!(scenario.gh_state()["prs"][0]["isDraft"], false); + assert!(scenario.issue_labels(7).is_empty()); +} + +#[test] +fn a_passing_check_cannot_authorize_a_changed_body() { + let scenario = Scenario::new(); + host_check( + &scenario, + r#"#!/bin/sh +set -eu +gh pr edit "$PR_NUMBER" --repo "$REPOSITORY" --body 'Edited during check' +"#, + ); + scenario.agent_does(OPEN_PR); + + let result = scenario.run(&[&scenario.issue_url(7)]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!( + result + .stderr + .contains("PR body changed during the Self-merge check"), + "{}", + result.stderr + ); + assert!(scenario.gh_calls_of("pr", "merge").is_empty()); + assert_eq!(scenario.gh_state()["prs"][0]["body"], "Edited during check"); +} + +#[test] +fn a_command_can_turn_the_check_off_and_needs_an_entry_to_turn_it_on() { + let scenario = Scenario::new(); + scenario.agent_does(OPEN_PR); + + let result = scenario.run(&["merge", "self-merge-check", &scenario.issue_url(7)]); + assert_eq!(result.code, Some(2), "{}", result.stderr); + assert!( + result + .stderr + .contains("requires merge.self_merge_check for acme/widgets"), + "{}", + result.stderr + ); + assert!(scenario.claude_calls().is_empty()); + + host_check(&scenario, "#!/bin/sh\necho unexpected check\nexit 1\n"); + let result = scenario.run(&["--no-self-merge-check", &scenario.issue_url(7)]); + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert_eq!( + scenario.gh_state()["prs"][0]["state"], + "MERGED", + "{}", + result.stderr + ); + assert!( + !result.stderr.contains("unexpected check"), + "{}", + result.stderr + ); +} + +#[test] +fn a_check_hold_from_pickup_does_not_take_a_failure_slot() { + let scenario = Scenario::new(); + host_check(&scenario, "#!/bin/sh\necho Day shift decides\nexit 1\n"); + scenario.issue_labelled(7, &["ready-for-agent"]); + scenario.agent_does(OPEN_PR); + + let result = scenario.run(&["pickup"]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert_eq!(scenario.gh_state()["prs"][0]["state"], "OPEN"); + assert!(scenario.issue_labels(7).is_empty()); + let again = scenario.run(&["pickup"]); + assert_eq!(again.code, Some(0), "{}", again.stderr); + assert_eq!(scenario.claude_calls().len(), 1, "{}", again.stderr); + assert!(!again.stderr.contains("Failure limit"), "{}", again.stderr); +} From c57035cacf93ebfbcfc661a03de1dd7d49b49ae6 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Thu, 3 Dec 2026 16:12:27 -0500 Subject: [PATCH 02/27] Preserve original PR bodies and review hold outcomes (#2421) --- docs/guide.md | 8 ++- site/architecture/index.html | 2 +- site/docs/index.html | 8 ++- site/how-it-works/index.html | 2 +- site/index.html | 4 +- src/fix.rs | 23 ++++--- src/fix/selection.rs | 36 ++++++----- src/github/review.rs | 24 +++++-- src/process.rs | 33 ++++++++-- src/processes.rs | 26 ++++---- src/processes/findings.rs | 8 +-- src/processes/review.rs | 37 +++++++---- src/processes/source.rs | 5 +- src/processes/ticket.rs | 6 +- src/pull_request.rs | 1 + src/self_merge_check.rs | 78 +++++++++++++---------- tests/fix_pass.rs | 117 +++++++++++++++++++++++++++++++++++ tests/process/spec_run.rs | 61 +++++++++++++++++- tests/review_merge.rs | 55 +++++++++++++++- tests/self_merge_check.rs | 38 +++++++++++- 20 files changed, 450 insertions(+), 122 deletions(-) diff --git a/docs/guide.md b/docs/guide.md index f07f75b36..53e5555c2 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -2934,9 +2934,11 @@ or a one-minute timeout leaves the pull request ready for review. The first nonempty stdout line, trimmed and capped at 240 characters, becomes the reason. Without a line, thirdshift reports the exit status, timeout, or start failure. The reason appears on stderr, in the Command log, in the Run -notification and in the Inbox. The Run releases its Claim, keeps its open PR -and exits successfully. If the body changes during the check, the Run leaves -the pull request ready for review. +notification and in the Inbox. The Run releases its Claim or PR reservation +and keeps the open PR. A targeted Review that asked to Self-merge exits with +status `1` when held. Ticket, Spec and Fix runs and author Review Passes +exit successfully. If the body changes during the check, the Run leaves the +pull request ready for review. Use `no-self-merge-check` or `--no-self-merge-check` to turn the check off for one Command. Use `self-merge-check` or `--self-merge-check` to require a diff --git a/site/architecture/index.html b/site/architecture/index.html index 852b42250..00533f80b 100644 --- a/site/architecture/index.html +++ b/site/architecture/index.html @@ -586,7 +586,7 @@

Architecture

Once a Pickup run, an Architect run or a Security run knows its repository, it replaces that kind's last-fired time under the repository's log folder, before launch checks or the Command limit. Repeated skips update the time without adding Activity log lines. thirdshift status, thirdshift cronjobs and their Console views read the same per-repository times; no reader starts work. A Custom process started with no issue, and neither an Issue-branch nor a Spec-branch worktree, counts toward the Command limit, runs beside other Passes up to it, takes no lock of a kind, and does not record a last-fired time. A file that declares either branch worktree is refused when no issue is given, before the Command limit.

A Pass takes no Issue URL, so your operating system's scheduler can start it; thirdshift never schedules itself. A Pass is skipped while its repository is at its Command limit, [pass] command_limit, 1 by default: every live Command on the repository on the machine counts, a Ticket run started on an Issue URL included, but only a Pass is skipped. Passes of different kinds share a repository up to the limit, but never two Architect runs or two Security runs at once: each of those holds a lock of its kind and a review worktree of its own, and reserves the plan or fix it dispatches on origin, as a Pickup run reserves its Ready issue. A Pass with nothing to do is skipped, not failed. Architect and Security runs wait while a Ready issue is open, so work you shaped goes first. A Custom process started with no issue is a Pass for that rule and does not wait on a Ready issue or an Architect idea, unless the file declares either branch worktree: that is refused before any session, rather than skipped. One started with an issue is not a Pass. Your scheduler can start Architect runs every few minutes and Security runs on a schedule, with fixing allowed.

A Fix run, thirdshift fix <PR URL or number>, targets an explicit PR; with no PR target it is a Pass sharing the repository up to its Command limit. Without --author, it first checks the Base branch's origin tip. A failed first push attempt gets one failed-jobs re-run, then PR selection continues without waiting. Persistent or non-rerunnable failures get a CI-fix session on fix-<base>-<short-sha> and a repair PR targeting the Base branch; that Fix run ends the Pass. All red checks are its own, existing repair PRs prevent duplicates, and merge and email policy apply. Self-merge closes the Base branch's CI-red reports and Base fix issues.

-

The Pass otherwise searches open, non-draft, same-repository PRs by Trusted accounts, giving Merge conflicts and current-head CI red priority in ascending PR number. behind <n> or the repository’s fix.behind setting adds PRs at least that many commits behind, furthest behind first. The Pass skips a PR held only by a Sign-off hold even when it meets the behind threshold. An explicit Fix run leaves that PR ready for review and names the check and label. Optional base <branch> and --author <login> scope that search. Selection skips in-progress PRs and passes over head branches checked out locally, naming the PR and occupying path on stderr. When none can be taken, the Activity log skip includes those reasons without recording a failed Fix run. Occupied checkouts remain intact; an explicit PR target still fails and names the occupying path. Selection reserves and rechecks candidates before dispatch. Busy reservations pass through to the next candidate. Its fix-run Built-in process is delivery → self-merge, using the existing PR's head branch and Base branch without implementation or initial code review. It holds an origin reservation and in-progress through Repair and failure preservation, and records its own Command log and Run notification. Self-merge requires recorded agent authorship or review of the exact adopted head by thirdshift's GitHub account; completed Ticket, Spec and Base CI Deliveries record their delivered heads too. Absent that evidence, the repaired PR stays ready for review, preserving ADR 0004. Skips record an Activity log reason when it changes and send no notification. Later Passes skip PRs left as drafts. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state.

+

The Pass otherwise searches open, non-draft, same-repository PRs by Trusted accounts, giving Merge conflicts and current-head CI red priority in ascending PR number. behind <n> or the repository’s fix.behind setting adds PRs at least that many commits behind, furthest behind first. The Pass skips a PR held only by a Sign-off hold or left waiting by its latest Self-merge check on this machine, even when it meets the behind threshold. A Merge conflict or settled CI red apart from the Sign-off hold keeps the PR eligible. An explicit Fix run leaves that PR ready for review and names the check and label. Optional base <branch> and --author <login> scope that search. Selection skips in-progress PRs and passes over head branches checked out locally, naming the PR and occupying path on stderr. When none can be taken, the Activity log skip includes those reasons without recording a failed Fix run. Occupied checkouts remain intact; an explicit PR target still fails and names the occupying path. Selection reserves and rechecks candidates before dispatch. Busy reservations pass through to the next candidate. Its fix-run Built-in process is delivery → self-merge, using the existing PR's head branch and Base branch without implementation or initial code review. It holds an origin reservation and in-progress through Repair and failure preservation, and records its own Command log and Run notification. Self-merge requires recorded agent authorship or review of the exact adopted head by thirdshift's GitHub account; completed Ticket, Spec and Base CI Deliveries record their delivered heads too. Absent that evidence, the repaired PR stays ready for review, preserving ADR 0004. Skips record an Activity log reason when it changes and send no notification. Later Passes skip PRs left as drafts. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state.

The Fix-Pass-only word merge-base-fix grants Self-merge only to a repair newly authored by the Base branch CI step, through the usual Delivery and Self-merge gates. Selected PRs keep the ordinary merge / no-merge and merge.always policy. Thus thirdshift fix base master no-merge merge-base-fix merges a new Base branch repair and leaves selected feature PRs ready for review even when merge.always = true. Existing repair PRs selected later or retried gain no permission from this word or their branch name; merging one requires the usual merge policy, such as targeted fix <PR> merge. Omission, --author scoping and Ticket-run base-fix behavior are unchanged.

A Fix Pass checks every linked closing issue before and after reserving the PR. An in-progress Claim on a Spec or standalone Ticket run's issue, including on another host, makes it skip the PR and name the claimed issue on stderr. It can adopt the PR on a later Pass after the Claim ends. Unreadable links or labels fail closed; explicit PR targets keep their existing behavior. Once the Pass has selected a pull request, an untrusted author of a linked closing issue, or any title or body edit by an account that is not a Trusted account, stops the Fix run before the issue is used and does not take the next candidate.

Pending or re-running Base branch checks, an occupied CI reservation, or an existing repair branch or PR skip only Base branch maintenance and leave PR selection available. Stderr and the Activity log record the reason, including when no eligible PR is found. Failed opening Base CI sessions publish preserved work as draft repair PRs with a Fix Recovery command. An existing repair branch prevents another attempt if PR creation failed.

diff --git a/site/docs/index.html b/site/docs/index.html index 8082368b2..e37157551 100644 --- a/site/docs/index.html +++ b/site/docs/index.html @@ -2903,9 +2903,11 @@ nonempty stdout line, trimmed and capped at 240 characters, becomes the reason. Without a line, thirdshift reports the exit status, timeout, or start failure. The reason appears on stderr, in the Command log, in the Run -notification and in the Inbox. The Run releases its Claim, keeps its open PR -and exits successfully. If the body changes during the check, the Run leaves -the pull request ready for review.

+notification and in the Inbox. The Run releases its Claim or PR reservation +and keeps the open PR. A targeted Review that asked to Self-merge exits with +status 1 when held. Ticket, Spec and Fix runs and author Review Passes +exit successfully. If the body changes during the check, the Run leaves the +pull request ready for review.

Use no-self-merge-check or --no-self-merge-check to turn the check off for one Command. Use self-merge-check or --self-merge-check to require a configured command for that run. Repositories with no entry have no check. diff --git a/site/how-it-works/index.html b/site/how-it-works/index.html index 7236f0ba0..b2d7ec820 100644 --- a/site/how-it-works/index.html +++ b/site/how-it-works/index.html @@ -136,7 +136,7 @@

How thirdshift works

Self-merge requires recorded agent authorship or review of the adopted head. Without it, a Fix Pass, even with merge, or a targeted Fix run asked to merge only by merge.always, still repairs the PR and checks CI, then finishes successfully Ready for review (exit 0) and logs the hold. An explicit thirdshift fix <PR> merge still fails with the hold and leaves the repaired PR ready for review.

With no PR target, thirdshift fix [base <branch>] [--author <login>] is a Pass. Without --author, it first checks the Base branch's origin tip: a failed first push attempt gets one failed-jobs re-run, then PR selection continues without waiting. Persistent or non-rerunnable failures get a CI-fix session on fix-<base>-<short-sha> and a repair PR targeting the Base branch, treating every red check as its own; that Fix run ends the Pass. Existing PRs from that branch prevent duplicates, failed drafts included. Merge and email policy apply, and Self-merge closes the Base branch's CI-red reports and Base fix issues.

Use thirdshift fix base master no-merge merge-base-fix to Self-merge only a newly authored Base branch CI repair and leave selected PRs ready for review, even with merge.always = true. merge-base-fix (also --merge-base-fix) changes that new repair's merge permission alone; the usual Delivery and Self-merge gates still apply. Selected PRs follow merge, no-merge and the User config. An existing repair PR selected later or retried gains no permission from its branch name or this word; request fix <PR> merge explicitly. The word is rejected outside a Fix Pass. Omission preserves existing behavior, --author still skips Base branch maintenance, and a Ticket run's base-fix still always merges.

-

Otherwise the Pass selects an eligible open, non-draft, same-repository PR targeting the selected Base branch. A Merge conflict or CI red on the current head comes first, lowest PR number first. With behind <n> or the repository’s fix.behind setting, PRs at least that many commits behind also qualify, furthest behind first. The Pass skips a PR held only by a Sign-off hold even when it meets the behind threshold. A Merge conflict or other settled CI red keeps it eligible, and the held check stays out of the Repair's failure list. It skips untrusted authors and in-progress PRs, passing over busy reservations and head branches already checked out locally. Local occupancy reasons name the PR and occupying path on stderr and, when no candidate can be taken, in the Activity log. The check preserves occupied worktrees; an explicit PR target still fails and names the occupying path. At the Command limit or with no eligible PR left, it records a skip, exits successfully and sends no Run notification. Later Passes skip PRs left as drafts. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state.

+

Otherwise the Pass selects an eligible open, non-draft, same-repository PR targeting the selected Base branch. A Merge conflict or CI red on the current head comes first, lowest PR number first. With behind <n> or the repository’s fix.behind setting, PRs at least that many commits behind also qualify, furthest behind first. The Pass skips a PR held only by a Sign-off hold or left waiting by its latest Self-merge check on this machine, even when it meets the behind threshold. A Merge conflict or other settled CI red keeps it eligible, and the held check stays out of the Repair's failure list. It skips untrusted authors and in-progress PRs, passing over busy reservations and head branches already checked out locally. Local occupancy reasons name the PR and occupying path on stderr and, when no candidate can be taken, in the Activity log. The check preserves occupied worktrees; an explicit PR target still fails and names the occupying path. At the Command limit or with no eligible PR left, it records a skip, exits successfully and sends no Run notification. Later Passes skip PRs left as drafts. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state.

A Fix Pass checks every linked closing issue before and after reserving the PR. An in-progress Claim on a Spec or standalone Ticket run's issue, including on another host, makes it skip the PR and name the claimed issue on stderr. It can adopt the PR on a later Pass after the Claim ends. Unreadable links or labels fail closed; explicit PR targets keep their existing behavior. Once the Pass has selected a pull request, an untrusted author of a linked closing issue, or any title or body edit by an account that is not a Trusted account, stops the Fix run before the issue is used and does not take the next candidate.

A Fix run's Self-merge needs recorded agent authorship or review covering the exact adopted head, written by the GitHub account thirdshift acts as. Completed Ticket, Spec and Base CI Deliveries record their delivered heads for later Fix runs. Without that evidence the repaired PR stays ready for review; run thirdshift review <PR URL> before retrying Self-merge.

Pending or re-running Base branch checks, an occupied CI reservation, or an existing repair branch or PR skip only Base branch maintenance and leave PR selection available. Stderr and the Activity log record the reason, including when no eligible PR is found. Failed opening Base CI sessions publish preserved work as draft repair PRs with a Fix Recovery command; an existing repair branch also prevents another attempt if PR creation failed.

diff --git a/site/index.html b/site/index.html index 717a1dfa2..dc60c7dff 100644 --- a/site/index.html +++ b/site/index.html @@ -123,7 +123,7 @@

Your issues become pull requests overnight.

Review Passes (review --author) and Fix Passes skip release-* pull requests targeting main, leaving their version-only heads to the Release run. Explicit thirdshift fix <pr-url> --no-merge --no-base-fix still repairs those pull requests.

Review retries recover clean retained worktrees with verified ownership and committed fixes above the same captured PR head. Author Passes skip other local conflicts, notify once per state and continue to later waiting pull requests. An explicit PR URL still fails with preservation advice.

Review runs and pull-request Custom processes record their target PR URL and title before the first session starts. It appears in thirdshift status and the Command log while the run is live, and Command log and Session trace pages show the selected Command's GitHub issue or pull request link and title below the page heading (including a Pickup or Pass run's opened pull requests). Compact Working rows, including Overview, show live Fix and Review targets as clickable PR #number links beside the repository and run type, on desktop and phone, locally and across the Fleet. Explicit and Pass-selected targets appear alike. A Base branch CI repair shows its exact Base branch before publication and keeps it beside the PR link afterwards; older records without a target keep their Command label.

-

thirdshift fix <PR URL or number> takes an open pull request by a Trusted account, ready or draft, straight through Delivery and the Repair loop against its own Base branch. With no PR target, thirdshift fix [base <branch>] [--author <login>] [behind <n>] is a Pass taking eligible ready PRs with a Merge conflict or CI red first, lowest number first. behind <n> or the repository’s fix.behind setting also admits PRs at least that many commits behind, furthest behind first. A Fix Pass skips a PR held only by a Sign-off hold even when it meets the behind threshold. An explicit Fix run leaves that PR ready for review and names the check and label. The Pass skips head branches checked out locally, passing over them with the PR URL and occupying path on stderr. It skips cleanly at the Command limit or when none can be taken, recording occupancy reasons in the Activity log. An explicit PR target still fails and names the occupying worktree. A Fix run skips implementation and initial code review, reserves the PR until it ends, and supplies Repairs with trusted PR and linked closing-issue context. It stops before using a linked closing issue, including when started as a Pass, unless that issue's author is a Trusted account and no account that is not one has edited its title or body. Add merge for Self-merge or base-fix for inherited failures; the usual User config defaults apply. Self-merge needs recorded agent review of the adopted head; without it a Fix Pass, or a targeted Fix run asked to merge only by merge.always, repairs the PR and finishes successfully Ready for review, logging the hold. An explicit thirdshift fix <PR> merge still fails with the hold and leaves the repaired PR ready. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state. Other Delivery failures preserve work, draft the PR and offer a Fix run retry. Fix runs

+

thirdshift fix <PR URL or number> takes an open pull request by a Trusted account, ready or draft, straight through Delivery and the Repair loop against its own Base branch. With no PR target, thirdshift fix [base <branch>] [--author <login>] [behind <n>] is a Pass taking eligible ready PRs with a Merge conflict or CI red first, lowest number first. behind <n> or the repository’s fix.behind setting also admits PRs at least that many commits behind, furthest behind first. A Fix Pass skips a PR held only by a Sign-off hold or left waiting by its latest Self-merge check on this machine, even when it meets the behind threshold. A Merge conflict or settled CI red apart from the Sign-off hold keeps the PR eligible. An explicit Fix run leaves that PR ready for review and names the check and label. The Pass skips head branches checked out locally, passing over them with the PR URL and occupying path on stderr. It skips cleanly at the Command limit or when none can be taken, recording occupancy reasons in the Activity log. An explicit PR target still fails and names the occupying worktree. A Fix run skips implementation and initial code review, reserves the PR until it ends, and supplies Repairs with trusted PR and linked closing-issue context. It stops before using a linked closing issue, including when started as a Pass, unless that issue's author is a Trusted account and no account that is not one has edited its title or body. Add merge for Self-merge or base-fix for inherited failures; the usual User config defaults apply. Self-merge needs recorded agent review of the adopted head; without it a Fix Pass, or a targeted Fix run asked to merge only by merge.always, repairs the PR and finishes successfully Ready for review, logging the hold. An explicit thirdshift fix <PR> merge still fails with the hold and leaves the repaired PR ready. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state. Other Delivery failures preserve work, draft the PR and offer a Fix run retry. Fix runs

A Fix Pass checks every linked closing issue before and after reserving the PR. An in-progress Claim on a Spec or standalone Ticket run's issue, including on another host, makes it skip the PR and name the claimed issue on stderr. It can adopt the PR on a later Pass after the Claim ends. Unreadable links or labels fail closed; explicit PR targets keep their existing behavior. Once the Pass has selected a pull request, an untrusted author of a linked closing issue, or any title or body edit by an account that is not a Trusted account, stops the Fix run before the issue is used and does not take the next candidate.

thirdshift fix base master no-merge merge-base-fix lets a newly authored Base branch CI repair Self-merge through the usual gates while leaving selected PRs ready for review, even with merge.always = true. The Fix-Pass-only merge-base-fix word changes only that new repair's merge permission; selected PRs keep following merge, no-merge and the User config. Existing repair PRs gain no permission from their branch names or this word; use an explicit targeted fix <PR> merge to merge one. Omission keeps the existing policy, --author still skips Base branch CI, and a Ticket run's own base-fix still always merges. Fix Pass merge policy.

Without --author, a Fix Pass first checks Base branch CI on origin. A failed first push attempt gets one failed-jobs re-run, then PR selection continues without waiting. Pending or re-running Base checks, an occupied CI reservation, or an existing repair branch or PR skip only Base branch maintenance; stderr and the Activity log record the reason. Persistent or non-rerunnable failures get a CI-fix session on fix-<base>-<short-sha> and a repair PR targeting the Base branch, with every red check its own to fix; that Fix run ends the Pass. Failed opening sessions publish preserved work as draft repair PRs with a Fix Recovery command. An existing repair branch or PR prevents duplicates, including failed drafts. Completed Ticket, Spec and Base CI Deliveries record their exact agent-authored or reviewed heads for later Fix Self-merge. Merge and email flags and User config apply; Self-merge also closes the Base branch's CI-red reports and Base fix issues.

@@ -417,7 +417,7 @@

Seven workflows

Ticket runOne Issue URL becomes one reviewed pull request.

With run, open Start work in the Console's Pages navigation to choose a known repository labelled by its Fleet machine, an issue number or URL and shared options. Review the request and Harness, then confirm Start now. On Cron jobs, choose a machine and use Run now to confirm a Pass with its configured arguments. User config and Update also select a Fleet machine with admin there. Each machine's live scopes decide its controls, and the owning machine executes and records the action. The CLI offers start <owner/repo> <issue>, config and update with --machine <name>.

-

A Ticket run takes one Issue URL and delivers one pull request, ready for review. A Ticket run that Self-merges merges its own reviewed, green pull request when you ask.

+

A Ticket run takes one Issue URL and delivers one pull request, ready for review. A Ticket run can Self-merge its reviewed, green pull request when you ask. A configured Self-merge check can hold it for the Day shift.

A configured Sign-off hold leaves a PR ready for review after a Ticket, Spec or Fix run while its one deliberate red check waits for a person. User config

diff --git a/src/fix.rs b/src/fix.rs index 6860f7420..6924082bc 100644 --- a/src/fix.rs +++ b/src/fix.rs @@ -77,7 +77,7 @@ pub(crate) fn run( .or_else(|| config.fix_behind(&launch.repo)) .and_then(NonZeroU64::new); let mut passed_over = Vec::new(); - if let Some((pr, held)) = selection::take( + if let Some((listed, held)) = selection::take( &launch, &github, author.as_deref(), @@ -89,7 +89,7 @@ pub(crate) fn run( &mut passed_over, )? { let selected = FixArgs { - target: Target::PullRequest(crate::review::PullRequestInput::Url(pr)), + target: Target::PullRequest(crate::review::PullRequestInput::Url(listed.pr)), flags: command.flags.clone(), merge_base_fix: false, behind: None, @@ -99,7 +99,7 @@ pub(crate) fn run( config, harness, started, - Some(held), + Some((held, listed.body)), ))); } let mut reason = format!( @@ -137,7 +137,7 @@ fn targeted( config: &UserConfig, harness: &mut Choice, started_command: &mut crate::command::Started, - reservation: Option, + reservation: Option<(Reservation, String)>, ) -> Ended { let launch = std::env::current_dir() .map(Git::new) @@ -199,7 +199,7 @@ fn targeted_at( config: &UserConfig, harness: &mut Choice, started_command: &mut crate::command::Started, - reservation: Option, + reservation: Option<(Reservation, String)>, launch: anyhow::Result, occupy_slot: bool, ) -> Ended { @@ -220,10 +220,13 @@ fn targeted_at( let initial = github.fix_pull_request(&pr)?; started_command.pull_request(&pr, &initial.title); let pass = reservation.is_some(); - let _reservation = match reservation { - Some(held) => held, - None => Reservation::take(&launch, &github, &pr)? - .context("pull request is already reserved or labelled in-progress")?, + let (_reservation, start_body) = match reservation { + Some((held, body)) => (held, body), + None => ( + Reservation::take(&launch, &github, &pr)? + .context("pull request is already reserved or labelled in-progress")?, + initial.body, + ), }; let snapshot = github.fix_pull_request(&pr)?; started_command.pull_request(&pr, &snapshot.title); @@ -266,7 +269,7 @@ fn targeted_at( asks.goal != Goal::Merged || github.authored_or_reviewed_head(&pr, &adopted_head)?; let mut target = PullRequest::on_pull_request(&pr, &snapshot.branch, &snapshot.base, github); - target.remember_body(pr.issue.number, &initial.body); + target.remember_body(pr.issue.number, &start_body); if !reviewed { let reason = format!( "PR {} stays ready for review: adopted head {} has no recorded agent review; run thirdshift review {} before retrying Self-merge", diff --git a/src/fix/selection.rs b/src/fix/selection.rs index 023b3342f..fe1c2f6a2 100644 --- a/src/fix/selection.rs +++ b/src/fix/selection.rs @@ -6,7 +6,7 @@ use anyhow::Result; use crate::config::SignOffHold; use crate::github::GitHub; -use crate::github::review::FixCandidate; +use crate::github::review::{FixCandidate, ListedPullRequest}; use crate::launch::Launch; use crate::review::{PullRequestUrl, Reservation}; use crate::worktree::Worktree; @@ -19,7 +19,7 @@ pub(super) fn take( sign_off_hold: Option<&SignOffHold>, hold_logs: Option<&std::path::Path>, passed_over: &mut Vec, -) -> Result> { +) -> Result> { let holds = hold_logs .filter(|_| behind.is_some()) .map(crate::logs::self_merge_check_holds) @@ -34,22 +34,23 @@ pub(super) fn take( let mut without_repairs = Vec::new(); let base = launch.base.name(); - for pr in github.fix_candidates(&launch.repo, base, author)? { + for listed in github.fix_candidates(&launch.repo, base, author)? { + let pr = &listed.pr; let Some(candidate) = - github.observe_fix_candidate(&pr, base, author, false, sign_off_hold)? + github.observe_fix_candidate(pr, base, author, false, sign_off_hold)? else { continue; }; if candidate.needs_repair { - match pass.reserve(&pr, &candidate.branch, None)? { - Recheck::Held(held) => return Ok(Some((pr, held))), + match pass.reserve(pr, &candidate.branch, None)? { + Recheck::Held(held) => return Ok(Some((listed, held))), Recheck::Recovered(current) if behind.is_some() => { - without_repairs.push((pr, current)); + without_repairs.push((listed, current)); } Recheck::Recovered(_) | Recheck::Unavailable => {} } - } else if behind.is_some() && pass.checkout_is_free(&pr, &candidate.branch)? { - without_repairs.push((pr, candidate)); + } else if behind.is_some() && pass.checkout_is_free(pr, &candidate.branch)? { + without_repairs.push((listed, candidate)); } } @@ -57,22 +58,23 @@ pub(super) fn take( return Ok(None); }; let mut further_behind = Vec::new(); - for (pr, candidate) in without_repairs { + for (listed, candidate) in without_repairs { if holds .as_ref() - .is_some_and(|holds| holds.self_merge_check_held(&pr.url)) + .is_some_and(|holds| holds.self_merge_check_held(&listed.pr.url)) { continue; } - let distance = github.fix_commits_behind(&pr, &candidate)?; + let distance = github.fix_commits_behind(&listed.pr, &candidate)?; if distance >= behind.get() { - further_behind.push((distance, pr, candidate.branch)); + further_behind.push((distance, listed, candidate.branch)); } } - further_behind.sort_by_key(|(distance, pr, _)| (Reverse(*distance), pr.issue.number)); - for (_, pr, branch) in further_behind { - if let Recheck::Held(held) = pass.reserve(&pr, &branch, Some(behind))? { - return Ok(Some((pr, held))); + further_behind + .sort_by_key(|(distance, listed, _)| (Reverse(*distance), listed.pr.issue.number)); + for (_, listed, branch) in further_behind { + if let Recheck::Held(held) = pass.reserve(&listed.pr, &branch, Some(behind))? { + return Ok(Some((listed, held))); } } Ok(None) diff --git a/src/github/review.rs b/src/github/review.rs index 186e3b950..d819fb92b 100644 --- a/src/github/review.rs +++ b/src/github/review.rs @@ -33,6 +33,12 @@ pub(crate) struct FixCandidate { base: Option, } +/// The pull request and its body when a Pass first lists it. +pub(crate) struct ListedPullRequest { + pub pr: PullRequestUrl, + pub body: String, +} + #[derive(serde::Deserialize)] struct ReviewMarker { reviewed_head: Option, @@ -54,7 +60,7 @@ impl GitHub { repo: &crate::issue::Repo, base: &str, author: Option<&str>, - ) -> Result> { + ) -> Result> { if let Some(author) = author { ensure!( self.trusted_login(repo, author)?, @@ -74,10 +80,13 @@ impl GitHub { .context("pull request has no URL")?, )?; if fix_candidate(self, &pr, &node, base, author, false)? { - candidates.push(pr); + candidates.push(ListedPullRequest { + pr, + body: node["body"].as_str().unwrap_or_default().into(), + }); } } - candidates.sort_by_key(|pr| pr.issue.number); + candidates.sort_by_key(|candidate| candidate.pr.issue.number); Ok(candidates) } @@ -182,7 +191,7 @@ impl GitHub { repo: &crate::issue::Repo, author: &str, reserved: Option, - ) -> Result> { + ) -> Result> { let nodes = self.gh_api_items( &format!("repos/{}/pulls?state=open&per_page=100", repo.slug()), "", @@ -237,9 +246,12 @@ impl GitHub { if base_waiting { continue; } - candidates.push(pr); + candidates.push(ListedPullRequest { + pr, + body: node["body"].as_str().unwrap_or_default().into(), + }); } - candidates.sort_by_key(|pr| pr.issue.number); + candidates.sort_by_key(|candidate| candidate.pr.issue.number); Ok(candidates) } diff --git a/src/process.rs b/src/process.rs index c80b14ba5..48ca776ed 100644 --- a/src/process.rs +++ b/src/process.rs @@ -141,6 +141,31 @@ pub(crate) fn one_shot( stdout: Stdout, deadline: Instant, ) -> Result { + let output = one_shot_with(command, name, stdout, deadline, |pipe| read(pipe))?; + Ok(OneShot { + status: output.status, + stdout: output.stdout.unwrap_or_default(), + }) +} + +/// Consume a command's stdout as it arrives, so the reader can keep useful +/// output even when execution is stopped before stdout reaches EOF. +pub(crate) fn one_shot_reading( + command: &mut Command, + name: &str, + deadline: Instant, + consume: impl FnOnce(&mut dyn Read) -> io::Result<()> + Send + 'static, +) -> Result { + Ok(one_shot_with(command, name, Stdout::Capture, deadline, consume)?.status) +} + +fn one_shot_with( + command: &mut Command, + name: &str, + stdout: Stdout, + deadline: Instant, + consume: impl FnOnce(&mut dyn Read) -> io::Result + Send + 'static, +) -> Result> { let cancelled = Arc::new(AtomicBool::new(false)); let reader_cancelled = Arc::clone(&cancelled); let cli = name.to_owned(); @@ -155,18 +180,14 @@ pub(crate) fn one_shot( Some(deadline), &|| Ok(()), move |pipe| { - read(CancellableStdout { + consume(&mut CancellableStdout { pipe, cancelled: reader_cancelled, }) .with_context(|| format!("could not read {cli}'s stdout")) }, ); - let output = execution?; - Ok(OneShot { - status: output.status, - stdout: output.stdout.unwrap_or_default(), - }) + execution } #[derive(Debug)] diff --git a/src/processes.rs b/src/processes.rs index c975f0fdd..affd29564 100644 --- a/src/processes.rs +++ b/src/processes.rs @@ -100,7 +100,7 @@ struct ProcessFile { /// The merge choice inherited by a published issue, if already decided. dispatched_goal: Option, security_review: bool, - security_flags: Flags, + run_flags: Flags, security_fix: bool, plan_only: bool, } @@ -442,7 +442,7 @@ struct Prepared { goal: Goal, dispatched_goal: Option, security_review: bool, - security_flags: Flags, + run_flags: Flags, security_fix: bool, security_findings: Mutex>, plan_only: bool, @@ -507,7 +507,7 @@ struct StepRun<'a> { source: &'a source::TicketSource, process: &'a str, plan_only: bool, - security_flags: &'a Flags, + run_flags: &'a Flags, security_fix: bool, goal: Goal, dispatched_goal: Option, @@ -550,7 +550,7 @@ impl Prepared { source: &self.source, process, plan_only: self.plan_only, - security_flags: &self.security_flags, + run_flags: &self.run_flags, security_fix: self.security_fix, goal: self.goal, dispatched_goal: self.dispatched_goal, @@ -685,14 +685,14 @@ fn run(command: &ProcessRun) -> Result { ..Flags::default() } .security_review(&config); - file.security_flags = Flags { + file.run_flags = Flags { security_fix: command.security_fix, security_close: command.security_close, security_review: command.security_review, self_merge_check: command.self_merge_check, ..Flags::default() }; - file.security_fix = file.security_flags.security_fix_allowed(&config); + file.security_fix = file.run_flags.security_fix_allowed(&config); // Before any worktree: a foreign Issue URL is an origin mismatch, and a // number that cannot be resolved stops the same way. An Issue-branch // worktree with no issue is refused before the Pass log. A failure here @@ -706,7 +706,7 @@ fn run(command: &ProcessRun) -> Result { let validation = issue .as_ref() .map_or_else(launch::repo, |issue| Ok(issue.repo())) - .and_then(|repo| file.security_flags.validate_merge_check(&repo, &config)); + .and_then(|repo| file.run_flags.validate_merge_check(&repo, &config)); if let Err(error) = validation { return Err(failed_before_steps(notification, error)); } @@ -1454,8 +1454,8 @@ fn run_land_tickets( } else { crate::security::FixAsk::Forbid }), - security_close: prepared.security_flags.security_close, - self_merge_check: prepared.security_flags.self_merge_check, + security_close: prepared.run_flags.security_close, + self_merge_check: prepared.run_flags.self_merge_check, ..Flags::default() }; let mut asks = Asks::of_run(run.issue, &flags, &config); @@ -1696,8 +1696,8 @@ fn run_published( } else { crate::security::FixAsk::Forbid }), - security_close: run.security_flags.security_close, - self_merge_check: run.security_flags.self_merge_check, + security_close: run.run_flags.security_close, + self_merge_check: run.run_flags.self_merge_check, ..Flags::default() }; let mut asks = Asks::of_run(&issue, &flags, &config); @@ -2123,7 +2123,7 @@ fn prepare_from( goal: file.goal, dispatched_goal: file.dispatched_goal, security_review: file.security_review, - security_flags: file.security_flags, + run_flags: file.run_flags, security_fix: file.security_fix, security_findings: Mutex::default(), plan_only: file.plan_only, @@ -2766,7 +2766,7 @@ fn parse(path: &Path, text: &str) -> Result { security_review: false, security_fix: false, plan_only: false, - security_flags: Flags::default(), + run_flags: Flags::default(), }) } diff --git a/src/processes/findings.rs b/src/processes/findings.rs index 8ff5c5c17..e17ee905c 100644 --- a/src/processes/findings.rs +++ b/src/processes/findings.rs @@ -13,7 +13,7 @@ pub(super) fn private_failure(error: anyhow::Error) -> anyhow::Error { pub(super) fn fix(run: &StepRun<'_>, process: &str) -> Result { let config = UserConfig::load()?; - if !run.security_flags.security_fix_allowed(&config) { + if !run.run_flags.security_fix_allowed(&config) { return Ok("Security fixing is not allowed".into()); } // Held for publication, the Ticket run and every child it starts. @@ -32,7 +32,7 @@ pub(super) fn fix(run: &StepRun<'_>, process: &str) -> Result { } else { run.goal }), - ..run.security_flags.clone() + ..run.run_flags.clone() }; let mut choice = run.choice.clone(); let mut outside = LaunchAndGitHub { @@ -128,7 +128,7 @@ pub(super) fn fix(run: &StepRun<'_>, process: &str) -> Result { pub(super) fn close(run: &StepRun<'_>) -> Result { let config = UserConfig::load()?; - if !run.security_flags.security_close_allowed(&config) { + if !run.run_flags.security_close_allowed(&config) { return Ok("Security closing is not allowed".into()); } // The close check's prompt contains the private record. @@ -149,7 +149,7 @@ pub(super) fn close(run: &StepRun<'_>) -> Result { base: &base, repo: &repo, harness: &mut choice, - flags: run.security_flags, + flags: run.run_flags, config: &config, security_review_harness: None, }; diff --git a/src/processes/review.rs b/src/processes/review.rs index c4f2a63e1..0158983df 100644 --- a/src/processes/review.rs +++ b/src/processes/review.rs @@ -49,18 +49,20 @@ pub(crate) fn run(command: ReviewArgs) -> Result { crate::reservation::recover(&launch, &repo); let github = GitHub::new(); let mut selected = None; - for pr in github.waiting_review_pull_requests(&repo, &author, None)? { - if !admission::eligible(&launch, &github, &pr)? { + for listed in github.waiting_review_pull_requests(&repo, &author, None)? { + let pr = &listed.pr; + if !admission::eligible(&launch, &github, pr)? { continue; } - if let Some(held) = Reservation::take(&launch, &github, &pr)? + if let Some(held) = Reservation::take(&launch, &github, pr)? && github .waiting_review_pull_requests(&repo, &author, Some(pr.issue.number))? - .contains(&pr) - && admission::eligible(&launch, &github, &pr)? - && conflicts::eligible(&launch, &github, &pr, &command.flags, &config)? + .iter() + .any(|candidate| candidate.pr == *pr) + && admission::eligible(&launch, &github, pr)? + && conflicts::eligible(&launch, &github, pr, &command.flags, &config)? { - selected = Some((pr, Some(held))); + selected = Some((listed.pr, Some((held, listed.body)))); break; } } @@ -153,7 +155,7 @@ impl ReviewProcess { flags: &Flags, mode: Mode, checking: bool, - reservation: Option, + reservation: Option<(Reservation, String)>, ) -> Result { interrupt::install()?; let config = UserConfig::load()?; @@ -264,10 +266,13 @@ impl ReviewProcess { // no label. Capture again after reservation for the actual run. let initial = github.review_pull_request(pr)?; notification.pull_request(pr, &initial.title); - let _reservation = match reservation { - Some(held) => held, - None => Reservation::take(&launch, &github, pr)? - .context("pull request is already reserved or labelled in-progress")?, + let (_reservation, start_body) = match reservation { + Some((held, body)) => (held, body), + None => ( + Reservation::take(&launch, &github, pr)? + .context("pull request is already reserved or labelled in-progress")?, + initial.body, + ), }; let snapshot = github.review_pull_request(pr)?; notification.pull_request(pr, &snapshot.title); @@ -627,7 +632,7 @@ impl ReviewProcess { match (self_merge::SelfMerge { pr, snapshot: &snapshot, - start_body: &initial.body, + start_body: &start_body, check, closing_issues: &closing_issues, choice: &step.choice, @@ -728,6 +733,12 @@ impl ReviewProcess { logs::finished(&account); logs::ended(outcome); notification.finish(&account); + if !pass && let Some(hold) = &review_hold { + return Err(crate::failed_run::MergeHold { + reason: hold.to_string(), + } + .into()); + } if result.is_err() && !held && resumable { progress::step(format_args!("Recovery: {retry}")); } diff --git a/src/processes/source.rs b/src/processes/source.rs index 75f6e117d..8b2978282 100644 --- a/src/processes/source.rs +++ b/src/processes/source.rs @@ -957,10 +957,7 @@ pub(super) fn run_issue_branch( spec_tickets: None, child_asks: ChildAsks { sign_off_hold: config.sign_off_hold(&repo).cloned(), - self_merge_check: prepared - .security_flags - .merge_check_for(&repo, config) - .cloned(), + self_merge_check: prepared.run_flags.merge_check_for(&repo, config).cloned(), ..ChildAsks::default() }, failure: None, diff --git a/src/processes/ticket.rs b/src/processes/ticket.rs index 5e3b5a07d..23ad3f384 100644 --- a/src/processes/ticket.rs +++ b/src/processes/ticket.rs @@ -29,14 +29,14 @@ pub(crate) fn run_custom( file.security_review = delivery.security_review; file.security_fix = delivery.child_asks.security_fix; if delivery.child_asks.self_merge_check.is_none() { - file.security_flags.self_merge_check = Some(false); + file.run_flags.self_merge_check = Some(false); } - file.security_flags.security_fix = Some(if file.security_fix { + file.run_flags.security_fix = Some(if file.security_fix { crate::security::FixAsk::Allow } else { crate::security::FixAsk::Forbid }); - file.security_flags.security_close = Some(if delivery.child_asks.security_close { + file.run_flags.security_close = Some(if delivery.child_asks.security_close { crate::security::CloseAsk::Allow } else { crate::security::CloseAsk::Forbid diff --git a/src/pull_request.rs b/src/pull_request.rs index 3f2b8456c..ab3edd9bb 100644 --- a/src/pull_request.rs +++ b/src/pull_request.rs @@ -362,6 +362,7 @@ impl PullRequest { .create_draft(&self.issue, &self.branch, &self.base, &title, &body)?; let url = url.trim().to_string(); let number = self.number_from_url(&url)?; + self.remember_body(number, &body); self.identified = Some(Identified { number, url }); let snapshot = self.accounting_snapshot(true)?; if !snapshot.pr.is_draft { diff --git a/src/self_merge_check.rs b/src/self_merge_check.rs index b8772745f..1bf782462 100644 --- a/src/self_merge_check.rs +++ b/src/self_merge_check.rs @@ -1,9 +1,10 @@ //! Run the repository's last decision before a guarded Self-merge request. -use std::io::Write; +use std::io::{self, BufRead, BufReader, Read, Write}; use std::os::unix::fs::PermissionsExt; use std::path::{Component, Path}; -use std::process::Command; +use std::process::{Command, ExitStatus}; +use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use anyhow::{Context, Result, ensure}; @@ -63,44 +64,39 @@ impl Check { pr: &PrSnapshot, start_body: &str, ) -> Result> { - let result = self.execute(git, repo, base, pr, start_body); + let reason = Arc::new(Mutex::new(None)); + let result = self.execute(git, repo, base, pr, start_body, Arc::clone(&reason)); if crate::interrupt::requested() { anyhow::bail!("interrupted"); } - let reason = match result { - Ok(output) if output.status.success() => { + let printed = reason.lock().expect("check stdout").take(); + let (status, fallback) = match result { + Ok(status) if status.success() => { crate::progress::step(format!("Self-merge check {:?} exited 0", self.source)); return Ok(None); } - Ok(output) => { - let status = output - .status + Ok(status) => { + let code = status .code() - .map_or_else(|| output.status.to_string(), |code| code.to_string()); - let stdout = String::from_utf8_lossy(&output.stdout); - let reason = stdout.lines().map(str::trim).find(|line| !line.is_empty()); - let reason = reason.map_or_else( - || format!("Self-merge check exited {status}"), - |line| line.chars().take(REASON_LIMIT).collect(), - ); - crate::progress::step(format!( - "Self-merge check {:?} exited {status}: {reason}", - self.source - )); - reason + .map_or_else(|| status.to_string(), |code| code.to_string()); + ( + format!("exited {code}"), + format!("Self-merge check exited {code}"), + ) } Err(error) if error.is::() => { - crate::progress::step(format!("Self-merge check {:?} timed out", self.source)); - "Self-merge check timed out".into() - } - Err(error) => { - crate::progress::step(format!( - "Self-merge check {:?} could not start: {error:#}", - self.source - )); - "Self-merge check could not start".into() + ("timed out".into(), "Self-merge check timed out".into()) } + Err(error) => ( + format!("could not start: {error:#}"), + "Self-merge check could not start".into(), + ), }; + let reason = printed.unwrap_or(fallback); + crate::progress::step(format!( + "Self-merge check {:?} {status}: {reason}", + self.source + )); Ok(Some(reason)) } @@ -111,7 +107,8 @@ impl Check { base: &str, pr: &PrSnapshot, start_body: &str, - ) -> Result { + reason: Arc>>, + ) -> Result { let scratch = crate::scratch::temp_dir().context("Command scratch is unavailable")?; let program = Path::new(&self.words[0]); let script; @@ -156,7 +153,7 @@ impl Check { script = file.into_temp_path(); script.as_ref() }; - process::one_shot( + process::one_shot_reading( Command::new(executable) .args(&self.words[1..]) .current_dir(scratch) @@ -169,8 +166,25 @@ impl Check { .env("REPOSITORY", repo) .env("BASE_BRANCH", base), "Self-merge check", - process::Stdout::Capture, Instant::now() + TIMEOUT, + move |stdout| read_reason(stdout, &reason), ) } } + +fn read_reason(stdout: &mut dyn Read, reason: &Mutex>) -> io::Result<()> { + let mut stdout = BufReader::new(stdout); + let mut bytes = Vec::new(); + while stdout.read_until(b'\n', &mut bytes)? != 0 { + let line = String::from_utf8_lossy(&bytes); + let line = line.trim(); + if !line.is_empty() { + *reason.lock().expect("check stdout") = Some(line.chars().take(REASON_LIMIT).collect()); + break; + } + bytes.clear(); + } + // Keep draining stdout so a verbose check can finish before its deadline. + io::copy(&mut stdout, &mut io::sink())?; + Ok(()) +} diff --git a/tests/fix_pass.rs b/tests/fix_pass.rs index bdb99042f..d00563b64 100644 --- a/tests/fix_pass.rs +++ b/tests/fix_pass.rs @@ -17,6 +17,112 @@ const SIGN_OFF_CONFIG: &str = r#" sign_off_hold = { "Acme/Widgets" = { check = "Visual sign-off", label = "needs-sign-off" } } "#; +#[test] +fn fix_pass_keeps_the_body_observed_before_selection_finishes() { + let scenario = Scenario::new(); + scenario.origin_has_branch("feature", "main", &["Feature"]); + scenario.github_has_pr("feature", "main", "OPEN"); + let check = scenario.path("hold-check"); + support::write_executable( + &check, + r#"#!/bin/sh +if [ "$PR_BODY_AT_START" = 'Original policy' ]; then + echo original policy retained + exit 1 +fi +exit 0 +"#, + ); + scenario.user_config_is(&format!( + "[merge]\nself_merge_check = {{ \"acme/widgets\" = {:?} }}\n", + check.to_str().unwrap() + )); + let head = scenario.origin_git(&["rev-parse", "feature"]); + let mut state = scenario.gh_state(); + state["prs"][0]["body"] = "Original policy".into(); + state["collaborators"] = json!(["colleague"]); + state["prs"][0]["comments"] = json!([{ + "body": format!("", json!({"reviewed_head": head.trim()})), + "author_association": "COLLABORATOR", "user": {"login": "runner"} + }]); + state["checks"][head.trim()] = json!([{"name":"test","conclusion":"failure"}]); + state["on_ci_read"] = json!({ + "times": 1, "seen": [], + "script": "gh fake pr feature body '\"Edited policy\"'" + }); + scenario.write_gh_state(&state); + scenario.agent_does(REPAIR_CI); + let result = scenario.run(&["fix", "--author", "colleague", "merge", "no-email"]); + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!( + result.stderr.contains("original policy retained"), + "{}", + result.stderr + ); + assert_eq!(scenario.gh_state()["prs"][0]["state"], "OPEN"); +} + +#[test] +fn fix_pass_keeps_the_body_observed_during_selection() { + let scenario = Scenario::new(); + scenario.agent_does( + "echo feature > feature.txt; git add feature.txt; git commit -qm Feature\n\ + gh pr create --base main --head issue-7 --title Feature --body 'Original declaration'", + ); + let opened = scenario.run(&["no-merge", &scenario.issue_url(7)]); + assert_eq!(opened.code, Some(0), "{}", opened.stderr); + advance_base(&scenario, 2); + let head = scenario.origin_git(&["rev-parse", "issue-7"]); + let base = scenario.origin_git(&["rev-parse", "main"]); + let mut state = scenario.gh_state(); + record_behind(&mut state, head.trim(), base.trim(), 2); + scenario.write_gh_state(&state); + let check = scenario.path("check"); + support::write_executable( + &check, + r#"#!/bin/sh +case "$PR_BODY_AT_START" in + *'Original declaration'*) ;; + *) echo 'Wrong start body'; exit 1 ;; +esac +case "$PR_BODY" in + *'Edited during selection'*) echo 'Observed both bodies'; exit 1 ;; + *) echo 'Wrong current body'; exit 1 ;; +esac +"#, + ); + scenario.user_config_is(&format!( + "[merge]\nalways = true\nself_merge_check = {{ \"acme/widgets\" = {:?} }}\n", + check.to_str().unwrap() + )); + let wrapper = scenario.path("bin/gh"); + let original = scenario.path("bin/original/gh"); + std::fs::create_dir_all(original.parent().unwrap()).unwrap(); + std::fs::rename(&wrapper, original).unwrap(); + support::write_executable( + &wrapper, + r#"#!/bin/sh +set -eu +delegate="$(dirname "$0")/original/gh" +marker="${FAKE_GH_STATE%/*}/body-edited" +if [ "${1-} ${2-} ${3-}" = 'pr view 1' ] && [ ! -e "$marker" ]; then + "$delegate" "$@" + "$delegate" fake pr issue-7 body '"Edited during selection"' >&2 + touch "$marker" + exit 0 +fi +exec "$delegate" "$@" +"#, + ); + let result = scenario.run(&["fix", "base", "main", "behind", "2", "no-email"]); + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!( + result.stderr.contains("Observed both bodies"), + "{}", + result.stderr + ); +} + #[test] fn fix_pass_skips_a_self_merge_check_hold_until_the_pr_has_red_ci() { let scenario = Scenario::new(); @@ -53,6 +159,17 @@ fn fix_pass_skips_a_self_merge_check_hold_until_the_pr_has_red_ci() { state = scenario.gh_state(); state["checks"][head.trim()] = json!([{"name": "test", "conclusion": "failure"}]); + state["on_ci_read"] = json!({ + "times": 20, + "seen": [], + "script": r#" +case "$(git show -s --format=%s "$FAKE_CI_SHA")" in + "Merge remote-tracking branch 'origin/main' into issue-7") + gh fake checks "$FAKE_CI_SHA" '[{"name":"test","conclusion":"failure"}]' + ;; +esac +"# + }); scenario.write_gh_state(&state); let repaired = fix_pass(&scenario, &["behind", "2"]); diff --git a/tests/process/spec_run.rs b/tests/process/spec_run.rs index 803615217..5ef96e981 100644 --- a/tests/process/spec_run.rs +++ b/tests/process/spec_run.rs @@ -25,15 +25,72 @@ fn the_built_in_spec_run_checks_its_final_self_merge_only() { scenario.spec_has_tickets(7, &[(8, &[])]); scenario.agent_does_for(8, &agent_lands_ticket(8, "issue-7")); scenario.agent_does_for(7, "true"); - scenario.origin_has_commit("main", "check", "#!/bin/sh\necho built-in spec hold\nexit 1\n", "Add check"); + scenario.origin_has_commit( + "main", + "check", + "#!/bin/sh\necho built-in spec hold\nexit 1\n", + "Add check", + ); scenario.user_config_is("[merge]\nself_merge_check = { \"acme/widgets\" = \"check\" }\n"); let result = scenario.run(&["merge", &scenario.issue_url(7)]); assert_eq!(result.code, Some(0), "{}", result.stderr); - assert!(result.stderr.contains("built-in spec hold"), "{}", result.stderr); + assert!( + result.stderr.contains("built-in spec hold"), + "{}", + result.stderr + ); assert_eq!(pr_from(&scenario, "issue-8")["state"], "MERGED"); assert_eq!(pr_from(&scenario, "issue-7")["state"], "OPEN"); assert_eq!(pr_from(&scenario, "issue-7")["isDraft"], false); assert!(scenario.issue_labels(7).is_empty()); } + +#[test] +fn the_spec_check_receives_the_opening_body() { + let scenario = Scenario::new(); + scenario.spec_has_tickets(7, &[(8, &[])]); + scenario.agent_does_for(8, &agent_lands_ticket(8, "issue-7")); + scenario.agent_does_for(7, "true"); + let original = scenario.path("original/gh"); + std::fs::create_dir_all(original.parent().unwrap()).unwrap(); + std::fs::rename(scenario.path("bin/gh"), &original).unwrap(); + support::write_executable( + &scenario.path("bin/gh"), + &format!( + r#"#!/bin/sh +set -eu +original='{}' +case " $* " in + ' pr create '*" --head issue-7 "*) + url=$("$original" "$@") + "$original" fake pr issue-7 body '"Edited after creation"' >&2 + printf '%s\n' "$url" + ;; + *) exec "$original" "$@" ;; +esac +"#, + original.display() + ), + ); + scenario.origin_has_commit( + "main", + "check", + r#"#!/bin/sh +case "$PR_BODY_AT_START" in *'Edited after creation'*) exit 0 ;; esac +case "$PR_BODY" in *'Edited after creation'*) echo original body retained; exit 1 ;; esac +exit 2 +"#, + "Add check", + ); + scenario.user_config_is("[merge]\nself_merge_check = { \"acme/widgets\" = \"check\" }\n"); + let result = scenario.run(&["merge", &scenario.issue_url(7)]); + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!( + result.stderr.contains("original body retained"), + "{}", + result.stderr + ); + assert_eq!(pr_from(&scenario, "issue-7")["state"], "OPEN"); +} diff --git a/tests/review_merge.rs b/tests/review_merge.rs index 1a8a86182..abea2d68b 100644 --- a/tests/review_merge.rs +++ b/tests/review_merge.rs @@ -13,6 +13,59 @@ fn pull_request(scenario: &Scenario) -> String { scenario.github_has_pr("colleague", "main", "OPEN") } +#[test] +fn an_author_pass_keeps_the_first_observed_body() { + let scenario = Scenario::new(); + pull_request(&scenario); + let mut state = scenario.gh_state(); + state["prs"][0]["body"] = "Original policy".into(); + scenario.write_gh_state(&state); + scenario.agent_does(NO_FINDINGS); + let original = scenario.path("original/gh"); + std::fs::create_dir_all(original.parent().unwrap()).unwrap(); + std::fs::rename(scenario.path("bin/gh"), &original).unwrap(); + support::write_executable( + &scenario.path("bin/gh"), + &format!( + r#"#!/bin/sh +set -eu +original='{}' +marker='{}' +if [ "${{1-}}" = api ] && [ "${{2-}}" = repos/acme/widgets/pulls/1 ] && [ ! -e "$marker" ]; then + "$original" "$@" + "$original" fake pr colleague body '"Edited policy"' >&2 + touch "$marker" +else + exec "$original" "$@" +fi +"#, + original.display(), + scenario.path("edited").display() + ), + ); + scenario.origin_has_commit( + "main", + "check", + r#"#!/bin/sh +if [ "$PR_BODY_AT_START" = 'Original policy' ]; then + echo original policy retained + exit 1 +fi +exit 0 +"#, + "Add check", + ); + scenario.user_config_is("[merge]\nself_merge_check = { \"acme/widgets\" = \"check\" }\n"); + let result = scenario.run(&["review", "--author", "colleague", "merge", "no-email"]); + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!( + result.stderr.contains("original policy retained"), + "{}", + result.stderr + ); + assert_eq!(scenario.gh_state()["prs"][0]["state"], "OPEN"); +} + #[test] fn a_review_self_merge_check_keeps_the_review_ready_for_review() { let scenario = Scenario::new(); @@ -28,7 +81,7 @@ fn a_review_self_merge_check_keeps_the_review_ready_for_review() { let result = scenario.run(&["review", &url, "merge"]); - assert_eq!(result.code, Some(0), "{}", result.stderr); + assert_eq!(result.code, Some(1), "{}", result.stderr); assert_eq!(scenario.gh_state()["prs"][0]["state"], "OPEN"); assert_eq!(scenario.gh_state()["prs"][0]["isDraft"], false); assert!(scenario.gh_calls_of("pr", "merge").is_empty()); diff --git a/tests/self_merge_check.rs b/tests/self_merge_check.rs index 295705fb3..51c890bef 100644 --- a/tests/self_merge_check.rs +++ b/tests/self_merge_check.rs @@ -31,7 +31,18 @@ fn a_self_merge_check_hold_leaves_the_pull_request_ready() { scenario.issue_labelled(7, &["ready-for-agent"]); scenario.agent_does(OPEN_PR); - let result = scenario.run(&[&scenario.issue_url(7)]); + let resend = support::resend::ResendStandIn::replying(200, r#"{"id":"accepted"}"#); + let result = scenario.run_with_env( + &[ + &scenario.issue_url(7), + "email-unless-merged", + "day-shift@example.test", + ], + &[ + ("THIRDSHIFT_RESEND_URL", resend.url()), + ("RESEND_API_KEY", "re_test_hold"), + ], + ); assert_eq!(result.code, Some(0), "{}", result.stderr); assert!(result.stdout.contains("/pull/1"), "{}", result.stderr); @@ -44,6 +55,14 @@ fn a_self_merge_check_hold_leaves_the_pull_request_ready() { assert!(scenario.origin_log("issue-7").is_some()); let (log, notification) = support::resend::saved_notification(&scenario, "issue"); + let requests = resend.requests(); + assert_eq!(requests.len(), 1, "{requests:?}"); + assert!( + requests[0].body["text"] + .as_str() + .unwrap() + .contains("Day shift decides") + ); let inbox = scenario.run(&["status"]); assert!( inbox.stdout.contains("Ready for review"), @@ -193,6 +212,23 @@ fn a_timed_out_check_leaves_the_pull_request_ready() { assert!(scenario.issue_labels(7).is_empty()); } +#[test] +fn a_timed_out_check_keeps_its_printed_reason() { + let scenario = Scenario::new(); + host_check(&scenario, "#!/bin/sh\necho Day shift decides\nsleep 120\n"); + scenario.agent_does(OPEN_PR); + let result = scenario.run(&[&scenario.issue_url(7)]); + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!( + result + .stderr + .contains("Self-merge check held: Day shift decides"), + "{}", + result.stderr + ); + assert!(scenario.gh_calls_of("pr", "merge").is_empty()); +} + #[test] fn a_passing_check_cannot_authorize_a_changed_body() { let scenario = Scenario::new(); From 73d5912e4d4ba94e4602c1923b160a837d0cb7bf Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Thu, 3 Dec 2026 16:13:44 -0500 Subject: [PATCH 03/27] Clarify Fix Pass holds in the site summaries (#2421) --- site/architecture/index.html | 2 +- site/how-it-works/index.html | 2 +- site/index.html | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/site/architecture/index.html b/site/architecture/index.html index 00533f80b..814ac82c0 100644 --- a/site/architecture/index.html +++ b/site/architecture/index.html @@ -586,7 +586,7 @@

Architecture

Once a Pickup run, an Architect run or a Security run knows its repository, it replaces that kind's last-fired time under the repository's log folder, before launch checks or the Command limit. Repeated skips update the time without adding Activity log lines. thirdshift status, thirdshift cronjobs and their Console views read the same per-repository times; no reader starts work. A Custom process started with no issue, and neither an Issue-branch nor a Spec-branch worktree, counts toward the Command limit, runs beside other Passes up to it, takes no lock of a kind, and does not record a last-fired time. A file that declares either branch worktree is refused when no issue is given, before the Command limit.

A Pass takes no Issue URL, so your operating system's scheduler can start it; thirdshift never schedules itself. A Pass is skipped while its repository is at its Command limit, [pass] command_limit, 1 by default: every live Command on the repository on the machine counts, a Ticket run started on an Issue URL included, but only a Pass is skipped. Passes of different kinds share a repository up to the limit, but never two Architect runs or two Security runs at once: each of those holds a lock of its kind and a review worktree of its own, and reserves the plan or fix it dispatches on origin, as a Pickup run reserves its Ready issue. A Pass with nothing to do is skipped, not failed. Architect and Security runs wait while a Ready issue is open, so work you shaped goes first. A Custom process started with no issue is a Pass for that rule and does not wait on a Ready issue or an Architect idea, unless the file declares either branch worktree: that is refused before any session, rather than skipped. One started with an issue is not a Pass. Your scheduler can start Architect runs every few minutes and Security runs on a schedule, with fixing allowed.

A Fix run, thirdshift fix <PR URL or number>, targets an explicit PR; with no PR target it is a Pass sharing the repository up to its Command limit. Without --author, it first checks the Base branch's origin tip. A failed first push attempt gets one failed-jobs re-run, then PR selection continues without waiting. Persistent or non-rerunnable failures get a CI-fix session on fix-<base>-<short-sha> and a repair PR targeting the Base branch; that Fix run ends the Pass. All red checks are its own, existing repair PRs prevent duplicates, and merge and email policy apply. Self-merge closes the Base branch's CI-red reports and Base fix issues.

-

The Pass otherwise searches open, non-draft, same-repository PRs by Trusted accounts, giving Merge conflicts and current-head CI red priority in ascending PR number. behind <n> or the repository’s fix.behind setting adds PRs at least that many commits behind, furthest behind first. The Pass skips a PR held only by a Sign-off hold or left waiting by its latest Self-merge check on this machine, even when it meets the behind threshold. A Merge conflict or settled CI red apart from the Sign-off hold keeps the PR eligible. An explicit Fix run leaves that PR ready for review and names the check and label. Optional base <branch> and --author <login> scope that search. Selection skips in-progress PRs and passes over head branches checked out locally, naming the PR and occupying path on stderr. When none can be taken, the Activity log skip includes those reasons without recording a failed Fix run. Occupied checkouts remain intact; an explicit PR target still fails and names the occupying path. Selection reserves and rechecks candidates before dispatch. Busy reservations pass through to the next candidate. Its fix-run Built-in process is delivery → self-merge, using the existing PR's head branch and Base branch without implementation or initial code review. It holds an origin reservation and in-progress through Repair and failure preservation, and records its own Command log and Run notification. Self-merge requires recorded agent authorship or review of the exact adopted head by thirdshift's GitHub account; completed Ticket, Spec and Base CI Deliveries record their delivered heads too. Absent that evidence, the repaired PR stays ready for review, preserving ADR 0004. Skips record an Activity log reason when it changes and send no notification. Later Passes skip PRs left as drafts. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state.

+

The Pass otherwise searches open, non-draft, same-repository PRs by Trusted accounts, giving Merge conflicts and current-head CI red priority in ascending PR number. behind <n> or the repository’s fix.behind setting adds PRs at least that many commits behind, furthest behind first. The Pass skips a PR held only by a Sign-off hold or whose latest Run on this machine ended at a Self-merge check hold, even when it meets the behind threshold. A Merge conflict or settled CI red apart from the Sign-off hold keeps the PR eligible. An explicit Fix run facing a Sign-off hold leaves the PR ready for review and names the check and label. Optional base <branch> and --author <login> scope that search. Selection skips in-progress PRs and passes over head branches checked out locally, naming the PR and occupying path on stderr. When none can be taken, the Activity log skip includes those reasons without recording a failed Fix run. Occupied checkouts remain intact; an explicit PR target still fails and names the occupying path. Selection reserves and rechecks candidates before dispatch. Busy reservations pass through to the next candidate. Its fix-run Built-in process is delivery → self-merge, using the existing PR's head branch and Base branch without implementation or initial code review. It holds an origin reservation and in-progress through Repair and failure preservation, and records its own Command log and Run notification. Self-merge requires recorded agent authorship or review of the exact adopted head by thirdshift's GitHub account; completed Ticket, Spec and Base CI Deliveries record their delivered heads too. Absent that evidence, the repaired PR stays ready for review, preserving ADR 0004. Skips record an Activity log reason when it changes and send no notification. Later Passes skip PRs left as drafts. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state.

The Fix-Pass-only word merge-base-fix grants Self-merge only to a repair newly authored by the Base branch CI step, through the usual Delivery and Self-merge gates. Selected PRs keep the ordinary merge / no-merge and merge.always policy. Thus thirdshift fix base master no-merge merge-base-fix merges a new Base branch repair and leaves selected feature PRs ready for review even when merge.always = true. Existing repair PRs selected later or retried gain no permission from this word or their branch name; merging one requires the usual merge policy, such as targeted fix <PR> merge. Omission, --author scoping and Ticket-run base-fix behavior are unchanged.

A Fix Pass checks every linked closing issue before and after reserving the PR. An in-progress Claim on a Spec or standalone Ticket run's issue, including on another host, makes it skip the PR and name the claimed issue on stderr. It can adopt the PR on a later Pass after the Claim ends. Unreadable links or labels fail closed; explicit PR targets keep their existing behavior. Once the Pass has selected a pull request, an untrusted author of a linked closing issue, or any title or body edit by an account that is not a Trusted account, stops the Fix run before the issue is used and does not take the next candidate.

Pending or re-running Base branch checks, an occupied CI reservation, or an existing repair branch or PR skip only Base branch maintenance and leave PR selection available. Stderr and the Activity log record the reason, including when no eligible PR is found. Failed opening Base CI sessions publish preserved work as draft repair PRs with a Fix Recovery command. An existing repair branch prevents another attempt if PR creation failed.

diff --git a/site/how-it-works/index.html b/site/how-it-works/index.html index b2d7ec820..d7eb6f811 100644 --- a/site/how-it-works/index.html +++ b/site/how-it-works/index.html @@ -136,7 +136,7 @@

How thirdshift works

Self-merge requires recorded agent authorship or review of the adopted head. Without it, a Fix Pass, even with merge, or a targeted Fix run asked to merge only by merge.always, still repairs the PR and checks CI, then finishes successfully Ready for review (exit 0) and logs the hold. An explicit thirdshift fix <PR> merge still fails with the hold and leaves the repaired PR ready for review.

With no PR target, thirdshift fix [base <branch>] [--author <login>] is a Pass. Without --author, it first checks the Base branch's origin tip: a failed first push attempt gets one failed-jobs re-run, then PR selection continues without waiting. Persistent or non-rerunnable failures get a CI-fix session on fix-<base>-<short-sha> and a repair PR targeting the Base branch, treating every red check as its own; that Fix run ends the Pass. Existing PRs from that branch prevent duplicates, failed drafts included. Merge and email policy apply, and Self-merge closes the Base branch's CI-red reports and Base fix issues.

Use thirdshift fix base master no-merge merge-base-fix to Self-merge only a newly authored Base branch CI repair and leave selected PRs ready for review, even with merge.always = true. merge-base-fix (also --merge-base-fix) changes that new repair's merge permission alone; the usual Delivery and Self-merge gates still apply. Selected PRs follow merge, no-merge and the User config. An existing repair PR selected later or retried gains no permission from its branch name or this word; request fix <PR> merge explicitly. The word is rejected outside a Fix Pass. Omission preserves existing behavior, --author still skips Base branch maintenance, and a Ticket run's base-fix still always merges.

-

Otherwise the Pass selects an eligible open, non-draft, same-repository PR targeting the selected Base branch. A Merge conflict or CI red on the current head comes first, lowest PR number first. With behind <n> or the repository’s fix.behind setting, PRs at least that many commits behind also qualify, furthest behind first. The Pass skips a PR held only by a Sign-off hold or left waiting by its latest Self-merge check on this machine, even when it meets the behind threshold. A Merge conflict or other settled CI red keeps it eligible, and the held check stays out of the Repair's failure list. It skips untrusted authors and in-progress PRs, passing over busy reservations and head branches already checked out locally. Local occupancy reasons name the PR and occupying path on stderr and, when no candidate can be taken, in the Activity log. The check preserves occupied worktrees; an explicit PR target still fails and names the occupying path. At the Command limit or with no eligible PR left, it records a skip, exits successfully and sends no Run notification. Later Passes skip PRs left as drafts. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state.

+

Otherwise the Pass selects an eligible open, non-draft, same-repository PR targeting the selected Base branch. A Merge conflict or CI red on the current head comes first, lowest PR number first. With behind <n> or the repository’s fix.behind setting, PRs at least that many commits behind also qualify, furthest behind first. The Pass skips a PR held only by a Sign-off hold or whose latest Run on this machine ended at a Self-merge check hold, even when it meets the behind threshold. A Merge conflict or other settled CI red keeps it eligible, and the held check stays out of the Repair's failure list. It skips untrusted authors and in-progress PRs, passing over busy reservations and head branches already checked out locally. Local occupancy reasons name the PR and occupying path on stderr and, when no candidate can be taken, in the Activity log. The check preserves occupied worktrees; an explicit PR target still fails and names the occupying path. At the Command limit or with no eligible PR left, it records a skip, exits successfully and sends no Run notification. Later Passes skip PRs left as drafts. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state.

A Fix Pass checks every linked closing issue before and after reserving the PR. An in-progress Claim on a Spec or standalone Ticket run's issue, including on another host, makes it skip the PR and name the claimed issue on stderr. It can adopt the PR on a later Pass after the Claim ends. Unreadable links or labels fail closed; explicit PR targets keep their existing behavior. Once the Pass has selected a pull request, an untrusted author of a linked closing issue, or any title or body edit by an account that is not a Trusted account, stops the Fix run before the issue is used and does not take the next candidate.

A Fix run's Self-merge needs recorded agent authorship or review covering the exact adopted head, written by the GitHub account thirdshift acts as. Completed Ticket, Spec and Base CI Deliveries record their delivered heads for later Fix runs. Without that evidence the repaired PR stays ready for review; run thirdshift review <PR URL> before retrying Self-merge.

Pending or re-running Base branch checks, an occupied CI reservation, or an existing repair branch or PR skip only Base branch maintenance and leave PR selection available. Stderr and the Activity log record the reason, including when no eligible PR is found. Failed opening Base CI sessions publish preserved work as draft repair PRs with a Fix Recovery command; an existing repair branch also prevents another attempt if PR creation failed.

diff --git a/site/index.html b/site/index.html index dc60c7dff..cf43821b9 100644 --- a/site/index.html +++ b/site/index.html @@ -123,7 +123,7 @@

Your issues become pull requests overnight.

Review Passes (review --author) and Fix Passes skip release-* pull requests targeting main, leaving their version-only heads to the Release run. Explicit thirdshift fix <pr-url> --no-merge --no-base-fix still repairs those pull requests.

Review retries recover clean retained worktrees with verified ownership and committed fixes above the same captured PR head. Author Passes skip other local conflicts, notify once per state and continue to later waiting pull requests. An explicit PR URL still fails with preservation advice.

Review runs and pull-request Custom processes record their target PR URL and title before the first session starts. It appears in thirdshift status and the Command log while the run is live, and Command log and Session trace pages show the selected Command's GitHub issue or pull request link and title below the page heading (including a Pickup or Pass run's opened pull requests). Compact Working rows, including Overview, show live Fix and Review targets as clickable PR #number links beside the repository and run type, on desktop and phone, locally and across the Fleet. Explicit and Pass-selected targets appear alike. A Base branch CI repair shows its exact Base branch before publication and keeps it beside the PR link afterwards; older records without a target keep their Command label.

-

thirdshift fix <PR URL or number> takes an open pull request by a Trusted account, ready or draft, straight through Delivery and the Repair loop against its own Base branch. With no PR target, thirdshift fix [base <branch>] [--author <login>] [behind <n>] is a Pass taking eligible ready PRs with a Merge conflict or CI red first, lowest number first. behind <n> or the repository’s fix.behind setting also admits PRs at least that many commits behind, furthest behind first. A Fix Pass skips a PR held only by a Sign-off hold or left waiting by its latest Self-merge check on this machine, even when it meets the behind threshold. A Merge conflict or settled CI red apart from the Sign-off hold keeps the PR eligible. An explicit Fix run leaves that PR ready for review and names the check and label. The Pass skips head branches checked out locally, passing over them with the PR URL and occupying path on stderr. It skips cleanly at the Command limit or when none can be taken, recording occupancy reasons in the Activity log. An explicit PR target still fails and names the occupying worktree. A Fix run skips implementation and initial code review, reserves the PR until it ends, and supplies Repairs with trusted PR and linked closing-issue context. It stops before using a linked closing issue, including when started as a Pass, unless that issue's author is a Trusted account and no account that is not one has edited its title or body. Add merge for Self-merge or base-fix for inherited failures; the usual User config defaults apply. Self-merge needs recorded agent review of the adopted head; without it a Fix Pass, or a targeted Fix run asked to merge only by merge.always, repairs the PR and finishes successfully Ready for review, logging the hold. An explicit thirdshift fix <PR> merge still fails with the hold and leaves the repaired PR ready. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state. Other Delivery failures preserve work, draft the PR and offer a Fix run retry. Fix runs

+

thirdshift fix <PR URL or number> takes an open pull request by a Trusted account, ready or draft, straight through Delivery and the Repair loop against its own Base branch. With no PR target, thirdshift fix [base <branch>] [--author <login>] [behind <n>] is a Pass taking eligible ready PRs with a Merge conflict or CI red first, lowest number first. behind <n> or the repository’s fix.behind setting also admits PRs at least that many commits behind, furthest behind first. A Fix Pass skips a PR held only by a Sign-off hold or whose latest Run on this machine ended at a Self-merge check hold, even when it meets the behind threshold. A Merge conflict or settled CI red apart from the Sign-off hold keeps the PR eligible. An explicit Fix run facing a Sign-off hold leaves the PR ready for review and names the check and label. The Pass skips head branches checked out locally, passing over them with the PR URL and occupying path on stderr. It skips cleanly at the Command limit or when none can be taken, recording occupancy reasons in the Activity log. An explicit PR target still fails and names the occupying worktree. A Fix run skips implementation and initial code review, reserves the PR until it ends, and supplies Repairs with trusted PR and linked closing-issue context. It stops before using a linked closing issue, including when started as a Pass, unless that issue's author is a Trusted account and no account that is not one has edited its title or body. Add merge for Self-merge or base-fix for inherited failures; the usual User config defaults apply. Self-merge needs recorded agent review of the adopted head; without it a Fix Pass, or a targeted Fix run asked to merge only by merge.always, repairs the PR and finishes successfully Ready for review, logging the hold. An explicit thirdshift fix <PR> merge still fails with the hold and leaves the repaired PR ready. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state. Other Delivery failures preserve work, draft the PR and offer a Fix run retry. Fix runs

A Fix Pass checks every linked closing issue before and after reserving the PR. An in-progress Claim on a Spec or standalone Ticket run's issue, including on another host, makes it skip the PR and name the claimed issue on stderr. It can adopt the PR on a later Pass after the Claim ends. Unreadable links or labels fail closed; explicit PR targets keep their existing behavior. Once the Pass has selected a pull request, an untrusted author of a linked closing issue, or any title or body edit by an account that is not a Trusted account, stops the Fix run before the issue is used and does not take the next candidate.

thirdshift fix base master no-merge merge-base-fix lets a newly authored Base branch CI repair Self-merge through the usual gates while leaving selected PRs ready for review, even with merge.always = true. The Fix-Pass-only merge-base-fix word changes only that new repair's merge permission; selected PRs keep following merge, no-merge and the User config. Existing repair PRs gain no permission from their branch names or this word; use an explicit targeted fix <PR> merge to merge one. Omission keeps the existing policy, --author still skips Base branch CI, and a Ticket run's own base-fix still always merges. Fix Pass merge policy.

Without --author, a Fix Pass first checks Base branch CI on origin. A failed first push attempt gets one failed-jobs re-run, then PR selection continues without waiting. Pending or re-running Base checks, an occupied CI reservation, or an existing repair branch or PR skip only Base branch maintenance; stderr and the Activity log record the reason. Persistent or non-rerunnable failures get a CI-fix session on fix-<base>-<short-sha> and a repair PR targeting the Base branch, with every red check its own to fix; that Fix run ends the Pass. Failed opening sessions publish preserved work as draft repair PRs with a Fix Recovery command. An existing repair branch or PR prevents duplicates, including failed drafts. Completed Ticket, Spec and Base CI Deliveries record their exact agent-authored or reviewed heads for later Fix Self-merge. Merge and email flags and User config apply; Self-merge also closes the Base branch's CI-red reports and Base fix issues.

From 7541aa1e5d1c721b956614cc2a17d8fe374aac70 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Thu, 3 Dec 2026 16:14:39 -0500 Subject: [PATCH 04/27] thirdshift: failed ticket run (interrupted) 2026-12-03T21:14:39Z, host factory.etadventures.com. Uncommitted work at the time of failure is included in this commit. From 6e738fc57aa163c4e98895cf1fd9c4ceb8788f78 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Thu, 3 Dec 2026 17:15:07 -0500 Subject: [PATCH 05/27] Name missing Base branch Self-merge scripts in holds (#2423) --- docs/guide.md | 24 ++++++++++++------ site/docs/index.html | 22 ++++++++++------ src/self_merge_check.rs | 36 ++++++++++++++++++++++++++ tests/self_merge_check.rs | 53 ++++++++++++++++++++++++++++++++------- 4 files changed, 110 insertions(+), 25 deletions(-) diff --git a/docs/guide.md b/docs/guide.md index 53e5555c2..5eab1b63e 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -2919,11 +2919,19 @@ self_merge_check = { "owner/repo" = "scripts/self-merge-check 'release policy'" ``` The first word is the executable and the remaining words are its arguments. -Use shell quoting to group words. A repository path is read from the current -Base branch on `origin` and copied to Command scratch before execution. An -absolute path names a host executable outside Git worktrees. Both run from -Command scratch with `PR_NUMBER`, `PR_BODY`, `PR_BODY_AT_START`, `REPOSITORY` -(`owner/repo`) and `BASE_BRANCH` in their environment. The current body comes +Use shell quoting to group words. A relative path names a repository script. +Immediately before the check, thirdshift reads the committed script at the tip +of the Base branch on `origin`, copies it to Command scratch and runs that copy. +To change the rule, merge a pull request that updates the script. Edits on the +Issue branch have no effect on the check judging that branch. If the script is +absent from the Base branch, the hold reason reports the missing path. + +An absolute path such as `/usr/local/bin/self-merge-check` names a host +executable outside Git worktrees. + +Both forms run from Command scratch with `PR_NUMBER`, `PR_BODY`, +`PR_BODY_AT_START`, `REPOSITORY` (`owner/repo`) and `BASE_BRANCH` in their +environment. The current body comes from the readiness observation for the head about to merge. The start body is the first body observed by the Command, or the opening body when thirdshift creates the pull request. The command can use both bodies to enforce its own @@ -2932,9 +2940,9 @@ review policy. Exit `0` allows Self-merge. Any other exit, a missing or unstartable executable, or a one-minute timeout leaves the pull request ready for review. The first nonempty stdout line, trimmed and capped at 240 characters, becomes the -reason. Without a line, thirdshift reports the exit status, timeout, or start -failure. The reason appears on stderr, in the Command log, in the Run -notification and in the Inbox. The Run releases its Claim or PR reservation +reason. Without a line, thirdshift reports the exit status, timeout, missing +path or start failure. The reason appears on stderr, in the Command log, in +the Run notification and in the Inbox. The Run releases its Claim or PR reservation and keeps the open PR. A targeted Review that asked to Self-merge exits with status `1` when held. Ticket, Spec and Fix runs and author Review Passes exit successfully. If the body changes during the check, the Run leaves the diff --git a/site/docs/index.html b/site/docs/index.html index e37157551..5b671ebee 100644 --- a/site/docs/index.html +++ b/site/docs/index.html @@ -2889,11 +2889,17 @@ self_merge_check = { "owner/repo" = "scripts/self-merge-check 'release policy'" }

The first word is the executable and the remaining words are its arguments. -Use shell quoting to group words. A repository path is read from the current -Base branch on origin and copied to Command scratch before execution. An -absolute path names a host executable outside Git worktrees. Both run from -Command scratch with PR_NUMBER, PR_BODY, PR_BODY_AT_START, REPOSITORY -(owner/repo) and BASE_BRANCH in their environment. The current body comes +Use shell quoting to group words. A relative path names a repository script. +Immediately before the check, thirdshift reads the committed script at the tip +of the Base branch on origin, copies it to Command scratch and runs that copy. +To change the rule, merge a pull request that updates the script. Edits on the +Issue branch have no effect on the check judging that branch. If the script is +absent from the Base branch, the hold reason reports the missing path.

+

An absolute path such as /usr/local/bin/self-merge-check names a host +executable outside Git worktrees.

+

Both forms run from Command scratch with PR_NUMBER, PR_BODY, +PR_BODY_AT_START, REPOSITORY (owner/repo) and BASE_BRANCH in their +environment. The current body comes from the readiness observation for the head about to merge. The start body is the first body observed by the Command, or the opening body when thirdshift creates the pull request. The command can use both bodies to enforce its own @@ -2901,9 +2907,9 @@

Exit 0 allows Self-merge. Any other exit, a missing or unstartable executable, or a one-minute timeout leaves the pull request ready for review. The first nonempty stdout line, trimmed and capped at 240 characters, becomes the -reason. Without a line, thirdshift reports the exit status, timeout, or start -failure. The reason appears on stderr, in the Command log, in the Run -notification and in the Inbox. The Run releases its Claim or PR reservation +reason. Without a line, thirdshift reports the exit status, timeout, missing +path or start failure. The reason appears on stderr, in the Command log, in +the Run notification and in the Inbox. The Run releases its Claim or PR reservation and keeps the open PR. A targeted Review that asked to Self-merge exits with status 1 when held. Ticket, Spec and Fix runs and author Review Passes exit successfully. If the body changes during the check, the Run leaves the diff --git a/src/self_merge_check.rs b/src/self_merge_check.rs index 1bf782462..868b4a743 100644 --- a/src/self_merge_check.rs +++ b/src/self_merge_check.rs @@ -1,5 +1,6 @@ //! Run the repository's last decision before a guarded Self-merge request. +use std::fmt; use std::io::{self, BufRead, BufReader, Read, Write}; use std::os::unix::fs::PermissionsExt; use std::path::{Component, Path}; @@ -87,6 +88,9 @@ impl Check { Err(error) if error.is::() => { ("timed out".into(), "Self-merge check timed out".into()) } + Err(error) if error.is::() => { + ("could not start".into(), error.to_string()) + } Err(error) => ( format!("could not start: {error:#}"), "Self-merge check could not start".into(), @@ -142,6 +146,20 @@ impl Check { }) .collect::>() .join("/"); + let entry = git.run(&[ + "ls-tree", + "--full-tree", + &commit, + "--", + &format!(":(literal){path}"), + ])?; + if entry.is_empty() { + return Err(MissingRepositoryScript { + path, + base: base.into(), + } + .into()); + } let blob = git.run_bytes(&["cat-file", "blob", &format!("{commit}:{path}")])?; let mut file = tempfile::Builder::new() .prefix("self-merge-check-") @@ -172,6 +190,24 @@ impl Check { } } +#[derive(Debug)] +struct MissingRepositoryScript { + path: String, + base: String, +} + +impl fmt::Display for MissingRepositoryScript { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "Repository script {:?} is missing from origin/{}", + self.path, self.base + ) + } +} + +impl std::error::Error for MissingRepositoryScript {} + fn read_reason(stdout: &mut dyn Read, reason: &Mutex>) -> io::Result<()> { let mut stdout = BufReader::new(stdout); let mut bytes = Vec::new(); diff --git a/tests/self_merge_check.rs b/tests/self_merge_check.rs index 51c890bef..201637139 100644 --- a/tests/self_merge_check.rs +++ b/tests/self_merge_check.rs @@ -144,13 +144,17 @@ gh fake checks "$(git rev-parse HEAD)" '[{"name":"test","conclusion":"success"}] } #[test] -fn a_check_from_origin_base_ignores_the_issue_branch_copy() { +fn a_check_from_origin_base_receives_arguments_and_ignores_the_issue_branch_copy() { let scenario = Scenario::new(); - configure(&scenario, "./check"); + configure(&scenario, "./check 'release policy' review"); scenario.origin_has_commit( "main", "check", - "#!/bin/sh\necho Base policy\nexit 1\n", + r#"#!/bin/sh +test "$#" = 2 && test "$1" = 'release policy' && test "$2" = review || exit 2 +echo Base policy +exit 1 +"#, "Add policy", ); scenario.agent_does(&format!( @@ -161,13 +165,46 @@ fn a_check_from_origin_base_ignores_the_issue_branch_copy() { assert_eq!(result.code, Some(0), "{}", result.stderr); assert!(result.stderr.contains("Base policy"), "{}", result.stderr); - assert_eq!(scenario.gh_state()["prs"][0]["state"], "OPEN"); + let state = scenario.gh_state(); + assert_eq!(state["prs"][0]["state"], "OPEN"); + assert_eq!(state["prs"][0]["isDraft"], false); + assert!(scenario.gh_calls_of("pr", "merge").is_empty()); +} + +#[test] +fn a_missing_repository_check_names_the_path_in_the_hold() { + let scenario = Scenario::new(); + configure(&scenario, "policy/check"); + scenario.agent_does(&format!( + r#" +mkdir policy +printf '#!/bin/sh\nexit 0\n' > policy/check +git add policy/check +{OPEN_PR} +"# + )); + + let result = scenario.run(&[&scenario.issue_url(7)]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + let inbox = scenario.run(&["status"]); + assert!( + inbox.stdout.contains( + "Self-merge check held: Repository script \"policy/check\" is missing from origin/main" + ), + "{}\n{}", + inbox.stdout, + result.stderr + ); + let state = scenario.gh_state(); + assert_eq!(state["prs"][0]["state"], "OPEN"); + assert_eq!(state["prs"][0]["isDraft"], false); + assert!(scenario.gh_calls_of("pr", "merge").is_empty()); } #[test] -fn a_missing_or_unstartable_check_holds_and_a_silent_exit_has_a_reason() { +fn an_unstartable_check_holds_and_a_silent_exit_has_a_reason() { for (command, reason) in [ - ("check", "Self-merge check could not start"), ( "/no/such/self-merge-check", "Self-merge check could not start", @@ -181,9 +218,7 @@ fn a_missing_or_unstartable_check_holds_and_a_silent_exit_has_a_reason() { "bad-interpreter" => host_check(&scenario, "#!/no/such/interpreter\n"), _ => configure(&scenario, command), } - scenario.agent_does(&format!( - "printf '#!/bin/sh\\nexit 0\\n' > check\ngit add check\n{OPEN_PR}" - )); + scenario.agent_does(OPEN_PR); let result = scenario.run(&[&scenario.issue_url(7)]); From 5e0e790eb22c40e96bdc1e68ac28355477d49e12 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Thu, 3 Dec 2026 17:21:05 -0500 Subject: [PATCH 06/27] Report repository script read errors without pathspecs (#2423) --- src/self_merge_check.rs | 39 +++++++++++++------------------- tests/self_merge_check.rs | 47 ++++++++++++++++++++++++++++++++++++++- 2 files changed, 61 insertions(+), 25 deletions(-) diff --git a/src/self_merge_check.rs b/src/self_merge_check.rs index 868b4a743..84782ce33 100644 --- a/src/self_merge_check.rs +++ b/src/self_merge_check.rs @@ -88,13 +88,15 @@ impl Check { Err(error) if error.is::() => { ("timed out".into(), "Self-merge check timed out".into()) } - Err(error) if error.is::() => { - ("could not start".into(), error.to_string()) + Err(error) => { + let fallback = error + .downcast_ref::() + .map_or_else( + || "Self-merge check could not start".into(), + ToString::to_string, + ); + (format!("could not start: {error:#}"), fallback) } - Err(error) => ( - format!("could not start: {error:#}"), - "Self-merge check could not start".into(), - ), }; let reason = printed.unwrap_or(fallback); crate::progress::step(format!( @@ -146,21 +148,12 @@ impl Check { }) .collect::>() .join("/"); - let entry = git.run(&[ - "ls-tree", - "--full-tree", - &commit, - "--", - &format!(":(literal){path}"), - ])?; - if entry.is_empty() { - return Err(MissingRepositoryScript { + let blob = git + .run_bytes(&["cat-file", "blob", &format!("{commit}:{path}")]) + .with_context(|| RepositoryScriptReadFailed { path, base: base.into(), - } - .into()); - } - let blob = git.run_bytes(&["cat-file", "blob", &format!("{commit}:{path}")])?; + })?; let mut file = tempfile::Builder::new() .prefix("self-merge-check-") .tempfile_in(&scratch)?; @@ -191,23 +184,21 @@ impl Check { } #[derive(Debug)] -struct MissingRepositoryScript { +struct RepositoryScriptReadFailed { path: String, base: String, } -impl fmt::Display for MissingRepositoryScript { +impl fmt::Display for RepositoryScriptReadFailed { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, - "Repository script {:?} is missing from origin/{}", + "Could not read repository script {:?} from origin/{}", self.path, self.base ) } } -impl std::error::Error for MissingRepositoryScript {} - fn read_reason(stdout: &mut dyn Read, reason: &Mutex>) -> io::Result<()> { let mut stdout = BufReader::new(stdout); let mut bytes = Vec::new(); diff --git a/tests/self_merge_check.rs b/tests/self_merge_check.rs index 201637139..c921e6a33 100644 --- a/tests/self_merge_check.rs +++ b/tests/self_merge_check.rs @@ -190,7 +190,7 @@ git add policy/check let inbox = scenario.run(&["status"]); assert!( inbox.stdout.contains( - "Self-merge check held: Repository script \"policy/check\" is missing from origin/main" + "Self-merge check held: Could not read repository script \"policy/check\" from origin/main" ), "{}\n{}", inbox.stdout, @@ -202,6 +202,51 @@ git add policy/check assert!(scenario.gh_calls_of("pr", "merge").is_empty()); } +#[test] +fn a_base_branch_check_runs_with_literal_pathspecs_enabled() { + let scenario = Scenario::new(); + configure(&scenario, "policy/check"); + scenario.origin_has_commit("main", "policy/check", "#!/bin/sh\nexit 0\n", "Add policy"); + scenario.agent_does(OPEN_PR); + + let result = + scenario.run_with_env(&[&scenario.issue_url(7)], &[("GIT_LITERAL_PATHSPECS", "1")]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert_eq!( + scenario.gh_state()["prs"][0]["state"], + "MERGED", + "{}", + result.stderr + ); +} + +#[test] +fn a_repository_check_path_occupied_by_a_directory_names_the_path_in_the_hold() { + let scenario = Scenario::new(); + configure(&scenario, "policy/check"); + scenario.origin_has_commit( + "main", + "policy/check/README.md", + "Policy directory\n", + "Add policy directory", + ); + scenario.agent_does(OPEN_PR); + + let result = scenario.run(&[&scenario.issue_url(7)]); + assert_eq!(result.code, Some(0), "{}", result.stderr); + + let inbox = scenario.run(&["status"]); + assert!( + inbox.stdout.lines().any(|line| { + line.contains("Self-merge check held: ") && line.contains("policy/check") + }), + "{}\n{}", + inbox.stdout, + result.stderr + ); +} + #[test] fn an_unstartable_check_holds_and_a_silent_exit_has_a_reason() { for (command, reason) in [ From db4f69e6733818e1689db50ceb1b1b772d4c0eb4 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Thu, 3 Dec 2026 18:14:04 -0500 Subject: [PATCH 07/27] thirdshift: failed ticket run (CI red on 5e0e790 and the Repair found nothing to fix on the branch) 2026-12-03T23:14:04Z, host factory.etadventures.com. Uncommitted work at the time of failure is included in this commit. From 83fb0b7a242fb56857c3297cf54d4ff1d69a62aa Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Fri, 4 Dec 2026 11:20:09 -0500 Subject: [PATCH 08/27] Fix CI failures inherited from the interrupted Self-merge check work (#2423) The partial #2421 work kept on the Spec branch left tests red: - gate the self_merge_check module to Linux - keep the help text within its line limit - say "run", not "Run", on the hand-written site pages - watch the snapshot query's new body field in the sign-off CI test - list merge.self_merge_check in the complete User config test fixtures Co-Authored-By: Claude Sonnet 5.5 --- site/architecture/index.html | 2 +- site/how-it-works/index.html | 2 +- site/index.html | 2 +- src/main.rs | 4 ++-- src/setup.rs | 1 + tests/ci.rs | 2 +- tests/setup.rs | 1 + 7 files changed, 8 insertions(+), 6 deletions(-) diff --git a/site/architecture/index.html b/site/architecture/index.html index 814ac82c0..3a0ef0add 100644 --- a/site/architecture/index.html +++ b/site/architecture/index.html @@ -586,7 +586,7 @@

Architecture

Once a Pickup run, an Architect run or a Security run knows its repository, it replaces that kind's last-fired time under the repository's log folder, before launch checks or the Command limit. Repeated skips update the time without adding Activity log lines. thirdshift status, thirdshift cronjobs and their Console views read the same per-repository times; no reader starts work. A Custom process started with no issue, and neither an Issue-branch nor a Spec-branch worktree, counts toward the Command limit, runs beside other Passes up to it, takes no lock of a kind, and does not record a last-fired time. A file that declares either branch worktree is refused when no issue is given, before the Command limit.

A Pass takes no Issue URL, so your operating system's scheduler can start it; thirdshift never schedules itself. A Pass is skipped while its repository is at its Command limit, [pass] command_limit, 1 by default: every live Command on the repository on the machine counts, a Ticket run started on an Issue URL included, but only a Pass is skipped. Passes of different kinds share a repository up to the limit, but never two Architect runs or two Security runs at once: each of those holds a lock of its kind and a review worktree of its own, and reserves the plan or fix it dispatches on origin, as a Pickup run reserves its Ready issue. A Pass with nothing to do is skipped, not failed. Architect and Security runs wait while a Ready issue is open, so work you shaped goes first. A Custom process started with no issue is a Pass for that rule and does not wait on a Ready issue or an Architect idea, unless the file declares either branch worktree: that is refused before any session, rather than skipped. One started with an issue is not a Pass. Your scheduler can start Architect runs every few minutes and Security runs on a schedule, with fixing allowed.

A Fix run, thirdshift fix <PR URL or number>, targets an explicit PR; with no PR target it is a Pass sharing the repository up to its Command limit. Without --author, it first checks the Base branch's origin tip. A failed first push attempt gets one failed-jobs re-run, then PR selection continues without waiting. Persistent or non-rerunnable failures get a CI-fix session on fix-<base>-<short-sha> and a repair PR targeting the Base branch; that Fix run ends the Pass. All red checks are its own, existing repair PRs prevent duplicates, and merge and email policy apply. Self-merge closes the Base branch's CI-red reports and Base fix issues.

-

The Pass otherwise searches open, non-draft, same-repository PRs by Trusted accounts, giving Merge conflicts and current-head CI red priority in ascending PR number. behind <n> or the repository’s fix.behind setting adds PRs at least that many commits behind, furthest behind first. The Pass skips a PR held only by a Sign-off hold or whose latest Run on this machine ended at a Self-merge check hold, even when it meets the behind threshold. A Merge conflict or settled CI red apart from the Sign-off hold keeps the PR eligible. An explicit Fix run facing a Sign-off hold leaves the PR ready for review and names the check and label. Optional base <branch> and --author <login> scope that search. Selection skips in-progress PRs and passes over head branches checked out locally, naming the PR and occupying path on stderr. When none can be taken, the Activity log skip includes those reasons without recording a failed Fix run. Occupied checkouts remain intact; an explicit PR target still fails and names the occupying path. Selection reserves and rechecks candidates before dispatch. Busy reservations pass through to the next candidate. Its fix-run Built-in process is delivery → self-merge, using the existing PR's head branch and Base branch without implementation or initial code review. It holds an origin reservation and in-progress through Repair and failure preservation, and records its own Command log and Run notification. Self-merge requires recorded agent authorship or review of the exact adopted head by thirdshift's GitHub account; completed Ticket, Spec and Base CI Deliveries record their delivered heads too. Absent that evidence, the repaired PR stays ready for review, preserving ADR 0004. Skips record an Activity log reason when it changes and send no notification. Later Passes skip PRs left as drafts. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state.

+

The Pass otherwise searches open, non-draft, same-repository PRs by Trusted accounts, giving Merge conflicts and current-head CI red priority in ascending PR number. behind <n> or the repository’s fix.behind setting adds PRs at least that many commits behind, furthest behind first. The Pass skips a PR held only by a Sign-off hold or whose latest run on this machine ended at a Self-merge check hold, even when it meets the behind threshold. A Merge conflict or settled CI red apart from the Sign-off hold keeps the PR eligible. An explicit Fix run facing a Sign-off hold leaves the PR ready for review and names the check and label. Optional base <branch> and --author <login> scope that search. Selection skips in-progress PRs and passes over head branches checked out locally, naming the PR and occupying path on stderr. When none can be taken, the Activity log skip includes those reasons without recording a failed Fix run. Occupied checkouts remain intact; an explicit PR target still fails and names the occupying path. Selection reserves and rechecks candidates before dispatch. Busy reservations pass through to the next candidate. Its fix-run Built-in process is delivery → self-merge, using the existing PR's head branch and Base branch without implementation or initial code review. It holds an origin reservation and in-progress through Repair and failure preservation, and records its own Command log and Run notification. Self-merge requires recorded agent authorship or review of the exact adopted head by thirdshift's GitHub account; completed Ticket, Spec and Base CI Deliveries record their delivered heads too. Absent that evidence, the repaired PR stays ready for review, preserving ADR 0004. Skips record an Activity log reason when it changes and send no notification. Later Passes skip PRs left as drafts. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state.

The Fix-Pass-only word merge-base-fix grants Self-merge only to a repair newly authored by the Base branch CI step, through the usual Delivery and Self-merge gates. Selected PRs keep the ordinary merge / no-merge and merge.always policy. Thus thirdshift fix base master no-merge merge-base-fix merges a new Base branch repair and leaves selected feature PRs ready for review even when merge.always = true. Existing repair PRs selected later or retried gain no permission from this word or their branch name; merging one requires the usual merge policy, such as targeted fix <PR> merge. Omission, --author scoping and Ticket-run base-fix behavior are unchanged.

A Fix Pass checks every linked closing issue before and after reserving the PR. An in-progress Claim on a Spec or standalone Ticket run's issue, including on another host, makes it skip the PR and name the claimed issue on stderr. It can adopt the PR on a later Pass after the Claim ends. Unreadable links or labels fail closed; explicit PR targets keep their existing behavior. Once the Pass has selected a pull request, an untrusted author of a linked closing issue, or any title or body edit by an account that is not a Trusted account, stops the Fix run before the issue is used and does not take the next candidate.

Pending or re-running Base branch checks, an occupied CI reservation, or an existing repair branch or PR skip only Base branch maintenance and leave PR selection available. Stderr and the Activity log record the reason, including when no eligible PR is found. Failed opening Base CI sessions publish preserved work as draft repair PRs with a Fix Recovery command. An existing repair branch prevents another attempt if PR creation failed.

diff --git a/site/how-it-works/index.html b/site/how-it-works/index.html index d7eb6f811..0641b5110 100644 --- a/site/how-it-works/index.html +++ b/site/how-it-works/index.html @@ -136,7 +136,7 @@

How thirdshift works

Self-merge requires recorded agent authorship or review of the adopted head. Without it, a Fix Pass, even with merge, or a targeted Fix run asked to merge only by merge.always, still repairs the PR and checks CI, then finishes successfully Ready for review (exit 0) and logs the hold. An explicit thirdshift fix <PR> merge still fails with the hold and leaves the repaired PR ready for review.

With no PR target, thirdshift fix [base <branch>] [--author <login>] is a Pass. Without --author, it first checks the Base branch's origin tip: a failed first push attempt gets one failed-jobs re-run, then PR selection continues without waiting. Persistent or non-rerunnable failures get a CI-fix session on fix-<base>-<short-sha> and a repair PR targeting the Base branch, treating every red check as its own; that Fix run ends the Pass. Existing PRs from that branch prevent duplicates, failed drafts included. Merge and email policy apply, and Self-merge closes the Base branch's CI-red reports and Base fix issues.

Use thirdshift fix base master no-merge merge-base-fix to Self-merge only a newly authored Base branch CI repair and leave selected PRs ready for review, even with merge.always = true. merge-base-fix (also --merge-base-fix) changes that new repair's merge permission alone; the usual Delivery and Self-merge gates still apply. Selected PRs follow merge, no-merge and the User config. An existing repair PR selected later or retried gains no permission from its branch name or this word; request fix <PR> merge explicitly. The word is rejected outside a Fix Pass. Omission preserves existing behavior, --author still skips Base branch maintenance, and a Ticket run's base-fix still always merges.

-

Otherwise the Pass selects an eligible open, non-draft, same-repository PR targeting the selected Base branch. A Merge conflict or CI red on the current head comes first, lowest PR number first. With behind <n> or the repository’s fix.behind setting, PRs at least that many commits behind also qualify, furthest behind first. The Pass skips a PR held only by a Sign-off hold or whose latest Run on this machine ended at a Self-merge check hold, even when it meets the behind threshold. A Merge conflict or other settled CI red keeps it eligible, and the held check stays out of the Repair's failure list. It skips untrusted authors and in-progress PRs, passing over busy reservations and head branches already checked out locally. Local occupancy reasons name the PR and occupying path on stderr and, when no candidate can be taken, in the Activity log. The check preserves occupied worktrees; an explicit PR target still fails and names the occupying path. At the Command limit or with no eligible PR left, it records a skip, exits successfully and sends no Run notification. Later Passes skip PRs left as drafts. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state.

+

Otherwise the Pass selects an eligible open, non-draft, same-repository PR targeting the selected Base branch. A Merge conflict or CI red on the current head comes first, lowest PR number first. With behind <n> or the repository’s fix.behind setting, PRs at least that many commits behind also qualify, furthest behind first. The Pass skips a PR held only by a Sign-off hold or whose latest run on this machine ended at a Self-merge check hold, even when it meets the behind threshold. A Merge conflict or other settled CI red keeps it eligible, and the held check stays out of the Repair's failure list. It skips untrusted authors and in-progress PRs, passing over busy reservations and head branches already checked out locally. Local occupancy reasons name the PR and occupying path on stderr and, when no candidate can be taken, in the Activity log. The check preserves occupied worktrees; an explicit PR target still fails and names the occupying path. At the Command limit or with no eligible PR left, it records a skip, exits successfully and sends no Run notification. Later Passes skip PRs left as drafts. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state.

A Fix Pass checks every linked closing issue before and after reserving the PR. An in-progress Claim on a Spec or standalone Ticket run's issue, including on another host, makes it skip the PR and name the claimed issue on stderr. It can adopt the PR on a later Pass after the Claim ends. Unreadable links or labels fail closed; explicit PR targets keep their existing behavior. Once the Pass has selected a pull request, an untrusted author of a linked closing issue, or any title or body edit by an account that is not a Trusted account, stops the Fix run before the issue is used and does not take the next candidate.

A Fix run's Self-merge needs recorded agent authorship or review covering the exact adopted head, written by the GitHub account thirdshift acts as. Completed Ticket, Spec and Base CI Deliveries record their delivered heads for later Fix runs. Without that evidence the repaired PR stays ready for review; run thirdshift review <PR URL> before retrying Self-merge.

Pending or re-running Base branch checks, an occupied CI reservation, or an existing repair branch or PR skip only Base branch maintenance and leave PR selection available. Stderr and the Activity log record the reason, including when no eligible PR is found. Failed opening Base CI sessions publish preserved work as draft repair PRs with a Fix Recovery command; an existing repair branch also prevents another attempt if PR creation failed.

diff --git a/site/index.html b/site/index.html index cf43821b9..60d3d2009 100644 --- a/site/index.html +++ b/site/index.html @@ -123,7 +123,7 @@

Your issues become pull requests overnight.

Review Passes (review --author) and Fix Passes skip release-* pull requests targeting main, leaving their version-only heads to the Release run. Explicit thirdshift fix <pr-url> --no-merge --no-base-fix still repairs those pull requests.

Review retries recover clean retained worktrees with verified ownership and committed fixes above the same captured PR head. Author Passes skip other local conflicts, notify once per state and continue to later waiting pull requests. An explicit PR URL still fails with preservation advice.

Review runs and pull-request Custom processes record their target PR URL and title before the first session starts. It appears in thirdshift status and the Command log while the run is live, and Command log and Session trace pages show the selected Command's GitHub issue or pull request link and title below the page heading (including a Pickup or Pass run's opened pull requests). Compact Working rows, including Overview, show live Fix and Review targets as clickable PR #number links beside the repository and run type, on desktop and phone, locally and across the Fleet. Explicit and Pass-selected targets appear alike. A Base branch CI repair shows its exact Base branch before publication and keeps it beside the PR link afterwards; older records without a target keep their Command label.

-

thirdshift fix <PR URL or number> takes an open pull request by a Trusted account, ready or draft, straight through Delivery and the Repair loop against its own Base branch. With no PR target, thirdshift fix [base <branch>] [--author <login>] [behind <n>] is a Pass taking eligible ready PRs with a Merge conflict or CI red first, lowest number first. behind <n> or the repository’s fix.behind setting also admits PRs at least that many commits behind, furthest behind first. A Fix Pass skips a PR held only by a Sign-off hold or whose latest Run on this machine ended at a Self-merge check hold, even when it meets the behind threshold. A Merge conflict or settled CI red apart from the Sign-off hold keeps the PR eligible. An explicit Fix run facing a Sign-off hold leaves the PR ready for review and names the check and label. The Pass skips head branches checked out locally, passing over them with the PR URL and occupying path on stderr. It skips cleanly at the Command limit or when none can be taken, recording occupancy reasons in the Activity log. An explicit PR target still fails and names the occupying worktree. A Fix run skips implementation and initial code review, reserves the PR until it ends, and supplies Repairs with trusted PR and linked closing-issue context. It stops before using a linked closing issue, including when started as a Pass, unless that issue's author is a Trusted account and no account that is not one has edited its title or body. Add merge for Self-merge or base-fix for inherited failures; the usual User config defaults apply. Self-merge needs recorded agent review of the adopted head; without it a Fix Pass, or a targeted Fix run asked to merge only by merge.always, repairs the PR and finishes successfully Ready for review, logging the hold. An explicit thirdshift fix <PR> merge still fails with the hold and leaves the repaired PR ready. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state. Other Delivery failures preserve work, draft the PR and offer a Fix run retry. Fix runs

+

thirdshift fix <PR URL or number> takes an open pull request by a Trusted account, ready or draft, straight through Delivery and the Repair loop against its own Base branch. With no PR target, thirdshift fix [base <branch>] [--author <login>] [behind <n>] is a Pass taking eligible ready PRs with a Merge conflict or CI red first, lowest number first. behind <n> or the repository’s fix.behind setting also admits PRs at least that many commits behind, furthest behind first. A Fix Pass skips a PR held only by a Sign-off hold or whose latest run on this machine ended at a Self-merge check hold, even when it meets the behind threshold. A Merge conflict or settled CI red apart from the Sign-off hold keeps the PR eligible. An explicit Fix run facing a Sign-off hold leaves the PR ready for review and names the check and label. The Pass skips head branches checked out locally, passing over them with the PR URL and occupying path on stderr. It skips cleanly at the Command limit or when none can be taken, recording occupancy reasons in the Activity log. An explicit PR target still fails and names the occupying worktree. A Fix run skips implementation and initial code review, reserves the PR until it ends, and supplies Repairs with trusted PR and linked closing-issue context. It stops before using a linked closing issue, including when started as a Pass, unless that issue's author is a Trusted account and no account that is not one has edited its title or body. Add merge for Self-merge or base-fix for inherited failures; the usual User config defaults apply. Self-merge needs recorded agent review of the adopted head; without it a Fix Pass, or a targeted Fix run asked to merge only by merge.always, repairs the PR and finishes successfully Ready for review, logging the hold. An explicit thirdshift fix <PR> merge still fails with the hold and leaves the repaired PR ready. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state. Other Delivery failures preserve work, draft the PR and offer a Fix run retry. Fix runs

A Fix Pass checks every linked closing issue before and after reserving the PR. An in-progress Claim on a Spec or standalone Ticket run's issue, including on another host, makes it skip the PR and name the claimed issue on stderr. It can adopt the PR on a later Pass after the Claim ends. Unreadable links or labels fail closed; explicit PR targets keep their existing behavior. Once the Pass has selected a pull request, an untrusted author of a linked closing issue, or any title or body edit by an account that is not a Trusted account, stops the Fix run before the issue is used and does not take the next candidate.

thirdshift fix base master no-merge merge-base-fix lets a newly authored Base branch CI repair Self-merge through the usual gates while leaving selected PRs ready for review, even with merge.always = true. The Fix-Pass-only merge-base-fix word changes only that new repair's merge permission; selected PRs keep following merge, no-merge and the User config. Existing repair PRs gain no permission from their branch names or this word; use an explicit targeted fix <PR> merge to merge one. Omission keeps the existing policy, --author still skips Base branch CI, and a Ticket run's own base-fix still always merges. Fix Pass merge policy.

Without --author, a Fix Pass first checks Base branch CI on origin. A failed first push attempt gets one failed-jobs re-run, then PR selection continues without waiting. Pending or re-running Base checks, an occupied CI reservation, or an existing repair branch or PR skip only Base branch maintenance; stderr and the Activity log record the reason. Persistent or non-rerunnable failures get a CI-fix session on fix-<base>-<short-sha> and a repair PR targeting the Base branch, with every red check its own to fix; that Fix run ends the Pass. Failed opening sessions publish preserved work as draft repair PRs with a Fix Recovery command. An existing repair branch or PR prevents duplicates, including failed drafts. Completed Ticket, Spec and Base CI Deliveries record their exact agent-authored or reviewed heads for later Fix Self-merge. Merge and email flags and User config apply; Self-merge also closes the Base branch's CI-red reports and Base fix issues.

diff --git a/src/main.rs b/src/main.rs index f63d41535..44aaf2a83 100644 --- a/src/main.rs +++ b/src/main.rs @@ -125,6 +125,7 @@ mod scoring; mod scratch; #[cfg(target_os = "linux")] mod security; +#[cfg(target_os = "linux")] mod self_merge_check; #[cfg(target_os = "linux")] mod session; @@ -239,8 +240,7 @@ usage: thirdshift [--trust-author ] Run the factory on the is Start from the issue's clone. The Base branch is the branch checked out; positive issue numbers use origin, even in nested directories. An issue with sub-issues starts a Spec run: its Tickets merge into a Spec branch; merge on a Spec merges the Spec PR. is one quoted free-text argument. Shared options (before or after the Issue URL or number, or after a Pass command; -- prefixes accepted, once each, without opposites): - merge / no-merge Merge the pull request / leave it for review - self-merge-check / no-self-merge-check Enable / disable the repository's Self-merge check for this Command + merge / no-merge Merge the pull request / leave it for review (self-merge-check / no-self-merge-check: use the repository's check) email [
] / no-email Send a Run notification / skip it (email-unless-merged [
]: unless merged) base-fix / no-base-fix Allow / forbid fixing inherited CI failures parallel Run up to Tickets at once (Spec runs; default 3) diff --git a/src/setup.rs b/src/setup.rs index f7ef13463..412d7a458 100644 --- a/src/setup.rs +++ b/src/setup.rs @@ -1457,6 +1457,7 @@ launch_directories = [] [merge] always = true label_from = { \"Acme/Widgets\" = [\"maintainer\"] } +self_merge_check = {} [base] fix = true diff --git a/tests/ci.rs b/tests/ci.rs index 41ec5054e..da94b5fc3 100644 --- a/tests/ci.rs +++ b/tests/ci.rs @@ -162,7 +162,7 @@ if [[ "${1-} ${2-}" == "pr view" && "$*" == *",headRefOid,isCrossRepository"* ]] if [[ -f "$marker" && ! -f "$marker.removed" ]]; then "$delegate" fake labels 1 '[]' : > "$marker.removed" - elif [[ " $* " == *",headRefOid,isCrossRepository,labels "* ]]; then + elif [[ " $* " == *",headRefOid,isCrossRepository,body,labels "* ]]; then : > "$marker" fi fi diff --git a/tests/setup.rs b/tests/setup.rs index 66837b43c..247596687 100644 --- a/tests/setup.rs +++ b/tests/setup.rs @@ -594,6 +594,7 @@ fn completing_an_existing_file_replaces_it_atomically_keeps_permissions_and_then waiting_line_minutes = 2 # waiting\n\ [merge]\nalways = true # merge\n\ label_from = { 'Acme/Widgets' = ['maintainer'] } # merge-label approval\n\ + self_merge_check = {} # no check\n\ [pickup]\nwait_minutes = 60 # time to attach Tickets\n"; let path = scenario.user_config_is(original); fs::set_permissions(&path, fs::Permissions::from_mode(0o640)).unwrap(); From d17f1275f33242de300f5f63a58070d243778f87 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Fri, 4 Dec 2026 11:39:40 -0500 Subject: [PATCH 09/27] Resolve Base branch Self-merge policy links and clarify overrides (#2423) --- docs/guide.md | 1 + site/docs/index.html | 1 + src/git.rs | 29 +++++++++++++++++++++- src/main.rs | 2 +- src/self_merge_check.rs | 12 ++++----- tests/ci.rs | 15 +++++++++-- tests/command_surface.rs | 15 +++++++++++ tests/self_merge_check.rs | 52 +++++++++++++++++++++++++++++++++++++++ 8 files changed, 117 insertions(+), 10 deletions(-) diff --git a/docs/guide.md b/docs/guide.md index 5eab1b63e..6c3650848 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -2922,6 +2922,7 @@ The first word is the executable and the remaining words are its arguments. Use shell quoting to group words. A relative path names a repository script. Immediately before the check, thirdshift reads the committed script at the tip of the Base branch on `origin`, copies it to Command scratch and runs that copy. +A symbolic link must resolve to a file in that same commit. To change the rule, merge a pull request that updates the script. Edits on the Issue branch have no effect on the check judging that branch. If the script is absent from the Base branch, the hold reason reports the missing path. diff --git a/site/docs/index.html b/site/docs/index.html index 5b671ebee..8688cba9d 100644 --- a/site/docs/index.html +++ b/site/docs/index.html @@ -2892,6 +2892,7 @@ Use shell quoting to group words. A relative path names a repository script. Immediately before the check, thirdshift reads the committed script at the tip of the Base branch on origin, copies it to Command scratch and runs that copy. +A symbolic link must resolve to a file in that same commit. To change the rule, merge a pull request that updates the script. Edits on the Issue branch have no effect on the check judging that branch. If the script is absent from the Base branch, the hold reason reports the missing path.

diff --git a/src/git.rs b/src/git.rs index 3d2ebc425..0ace656c6 100644 --- a/src/git.rs +++ b/src/git.rs @@ -63,6 +63,29 @@ impl Git { command_result(args, &output).map(|_| output.stdout) } + /// Read a file from a commit tree, resolving symlinks within that tree. + pub(crate) fn committed_file(&self, commit: &str, path: &str) -> Result> { + let args = [ + "cat-file", + "--batch=%(objecttype)", + "--follow-symlinks", + "-z", + ]; + let object = format!("{commit}:{path}\0"); + let output = self.output_with_input(&args, Some(object.as_bytes()))?; + if !output.status.success() { + command_result(&args, &output)?; + } + // For our single request, only a resolved blob has this header. + // Missing objects and links outside the tree have separate records. + let contents = output + .stdout + .strip_prefix(b"blob\n") + .and_then(|record| record.strip_suffix(b"\n")) + .context("path does not resolve to a file in the commit")?; + Ok(contents.to_vec()) + } + /// Keep a caller's authority check around every subprocess, including /// retries. A completed helper cannot authorize its next command attempt. pub(crate) fn run_checked( @@ -312,13 +335,17 @@ impl Git { } fn output(&self, args: &[&str]) -> Result { + self.output_with_input(args, None) + } + + fn output_with_input(&self, args: &[&str], input: Option<&[u8]>) -> Result { #[cfg(not(test))] let mut command = std::process::Command::new("git"); #[cfg(test)] let mut command = crate::test_support::git_command(); process::output( command.args(args).current_dir(&self.dir), - None, + input, Control { name: &format!("git {}", args.join(" ")), interruption: self.interruption, diff --git a/src/main.rs b/src/main.rs index 44aaf2a83..c37b1c801 100644 --- a/src/main.rs +++ b/src/main.rs @@ -240,7 +240,7 @@ usage: thirdshift [--trust-author ] Run the factory on the is Start from the issue's clone. The Base branch is the branch checked out; positive issue numbers use origin, even in nested directories. An issue with sub-issues starts a Spec run: its Tickets merge into a Spec branch; merge on a Spec merges the Spec PR. is one quoted free-text argument. Shared options (before or after the Issue URL or number, or after a Pass command; -- prefixes accepted, once each, without opposites): - merge / no-merge Merge the pull request / leave it for review (self-merge-check / no-self-merge-check: use the repository's check) + merge / no-merge Merge / leave for review (self-merge-check / no-self-merge-check: require / skip the configured check) email [
] / no-email Send a Run notification / skip it (email-unless-merged [
]: unless merged) base-fix / no-base-fix Allow / forbid fixing inherited CI failures parallel Run up to Tickets at once (Spec runs; default 3) diff --git a/src/self_merge_check.rs b/src/self_merge_check.rs index 84782ce33..fb69f6225 100644 --- a/src/self_merge_check.rs +++ b/src/self_merge_check.rs @@ -148,12 +148,12 @@ impl Check { }) .collect::>() .join("/"); - let blob = git - .run_bytes(&["cat-file", "blob", &format!("{commit}:{path}")]) - .with_context(|| RepositoryScriptReadFailed { - path, - base: base.into(), - })?; + let blob = + git.committed_file(&commit, &path) + .with_context(|| RepositoryScriptReadFailed { + path, + base: base.into(), + })?; let mut file = tempfile::Builder::new() .prefix("self-merge-check-") .tempfile_in(&scratch)?; diff --git a/tests/ci.rs b/tests/ci.rs index da94b5fc3..8ab7f6f5f 100644 --- a/tests/ci.rs +++ b/tests/ci.rs @@ -157,12 +157,23 @@ fn removing_the_sign_off_label_before_final_readiness_restores_ci_repair() { install_sign_off_gh_wrapper( &scenario, r#" -if [[ "${1-} ${2-}" == "pr view" && "$*" == *",headRefOid,isCrossRepository"* ]]; then +fields='' +if [[ "${1-} ${2-}" == "pr view" ]]; then + previous='' + for arg in "$@"; do + if [[ "$previous" == --json ]]; then + fields=",$arg," + break + fi + previous="$arg" + done +fi +if [[ "$fields" == *,headRefOid,* && "$fields" == *,isCrossRepository,* ]]; then marker="${FAKE_GH_STATE}.sign-off-observed" if [[ -f "$marker" && ! -f "$marker.removed" ]]; then "$delegate" fake labels 1 '[]' : > "$marker.removed" - elif [[ " $* " == *",headRefOid,isCrossRepository,body,labels "* ]]; then + elif [[ "$fields" == *,labels,* ]]; then : > "$marker" fi fi diff --git a/tests/command_surface.rs b/tests/command_surface.rs index 7c4bdfdb0..d078b1e68 100644 --- a/tests/command_surface.rs +++ b/tests/command_surface.rs @@ -95,6 +95,21 @@ fn help_does_not_mention_the_flag_aliases() { } } +#[test] +fn help_explains_both_self_merge_check_overrides() { + let scenario = Scenario::new(); + + let help = scenario.run(&["help"]); + + assert!( + help.stdout.contains( + "self-merge-check / no-self-merge-check: require / skip the configured check" + ), + "help should explain how to require or skip a configured check: {}", + help.stdout + ); +} + #[test] fn help_is_a_compact_reference_with_a_link_to_the_details() { let scenario = Scenario::new(); diff --git a/tests/self_merge_check.rs b/tests/self_merge_check.rs index c921e6a33..63b6916c0 100644 --- a/tests/self_merge_check.rs +++ b/tests/self_merge_check.rs @@ -171,6 +171,58 @@ exit 1 assert!(scenario.gh_calls_of("pr", "merge").is_empty()); } +#[test] +fn a_relative_policy_symlink_runs_the_script_committed_on_base() { + let scenario = Scenario::new(); + configure(&scenario, "policy/check"); + scenario.origin_has_commit( + "main", + "policy/real-check", + "#!/bin/sh\nexit 0\n", + "Add policy", + ); + scenario.launch_git(&["fetch", "origin", "main"]); + scenario.launch_git(&["merge", "--ff-only", "origin/main"]); + std::os::unix::fs::symlink("real-check", scenario.launch_dir().join("policy/check")).unwrap(); + scenario.launch_git(&["add", "policy/check"]); + scenario.launch_git(&["commit", "-qm", "Add policy link"]); + scenario.launch_git(&["push", "origin", "main"]); + scenario.agent_does(OPEN_PR); + + let result = scenario.run(&[&scenario.issue_url(7)]); + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert_eq!( + scenario.gh_state()["prs"][0]["state"], + "MERGED", + "{}", + result.stderr, + ); +} + +#[test] +fn a_repository_check_link_outside_the_commit_holds_with_its_path() { + let scenario = Scenario::new(); + configure(&scenario, "check-link"); + write_executable(&scenario.path("work/host-check"), "#!/bin/sh\nexit 0\n"); + std::os::unix::fs::symlink("../host-check", scenario.launch_dir().join("check-link")).unwrap(); + scenario.launch_git(&["add", "check-link"]); + scenario.launch_git(&["commit", "-qm", "Add policy link"]); + scenario.launch_git(&["push", "origin", "main"]); + scenario.agent_does(OPEN_PR); + + let result = scenario.run(&[&scenario.issue_url(7)]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!( + result.stderr.contains( + "Self-merge check held: Could not read repository script \"check-link\" from origin/main" + ), + "{}", + result.stderr + ); + assert!(scenario.gh_calls_of("pr", "merge").is_empty()); +} + #[test] fn a_missing_repository_check_names_the_path_in_the_hold() { let scenario = Scenario::new(); From 7abd10c6981558b058f9ce6775db83c38d1997a1 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Fri, 4 Dec 2026 12:05:35 -0500 Subject: [PATCH 10/27] Cover Self-merge checks across Delivery paths (#2426) --- docs/guide.md | 5 ++-- site/docs/index.html | 5 ++-- site/how-it-works/index.html | 4 +-- site/index.html | 2 +- tests/base_fix.rs | 37 +++++++++++++++++++++++++++ tests/fix_base_ci.rs | 49 +++++++++++++++++++++++------------- tests/pickup_run.rs | 41 ++++++++++++++++++++++++++++++ tests/process.rs | 39 +++++++++++++++++----------- tests/process/spec_run.rs | 24 ++++++++++++++---- tests/review_merge.rs | 22 ++++++++++++++++ 10 files changed, 184 insertions(+), 44 deletions(-) diff --git a/docs/guide.md b/docs/guide.md index 6c3650848..b22b59d30 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -3882,8 +3882,9 @@ The word applies only to a Fix Pass: targeted Fix runs and other commands reject it. An existing `fix--` PR selected later gets no merge permission from its branch name or this word; use a targeted `thirdshift fix merge` to request its Self-merge explicitly. `--author` still skips Base branch CI -maintenance. A Ticket run's own `base-fix` still always merges, as -[ADR 0008](adr/0008-inherited-failures-fail-the-run.md) requires. +maintenance. A Ticket run's own `base-fix` still requests Self-merge under +[ADR 0008](adr/0008-inherited-failures-fail-the-run.md). A configured Self-merge +check can hold the Base fix for review. For a crontab line that repairs the Base branch unattended while leaving feature PRs for review, whatever the User config's merge default: diff --git a/site/docs/index.html b/site/docs/index.html index 8688cba9d..34c6ea022 100644 --- a/site/docs/index.html +++ b/site/docs/index.html @@ -3681,8 +3681,9 @@ it. An existing fix-<base>-<sha> PR selected later gets no merge permission from its branch name or this word; use a targeted thirdshift fix <PR> merge to request its Self-merge explicitly. --author still skips Base branch CI -maintenance. A Ticket run's own base-fix still always merges, as -ADR 0008 requires.

+maintenance. A Ticket run's own base-fix still requests Self-merge under +ADR 0008. A configured Self-merge +check can hold the Base fix for review.

For a crontab line that repairs the Base branch unattended while leaving feature PRs for review, whatever the User config's merge default:

*/10 * * * * cd ~/repos/widgets && thirdshift fix base master no-merge merge-base-fix
diff --git a/site/how-it-works/index.html b/site/how-it-works/index.html
index 0641b5110..080bab316 100644
--- a/site/how-it-works/index.html
+++ b/site/how-it-works/index.html
@@ -135,7 +135,7 @@ 

How thirdshift works

For an existing open pull request, thirdshift fix <PR URL or number> starts a Fix run directly at Delivery. Ready and draft PRs by Trusted accounts are accepted, with or without closing issues. It uses the PR's own Base branch, reserves the PR while running and gives each Repair trusted PR and linked-issue context. It stops before using a linked closing issue, including when started as a Pass, unless that issue's author is a Trusted account and no account that is not one has edited its title or body. The usual merge, Base fix, Harness and email defaults apply; failure preserves work and offers thirdshift fix again.

Self-merge requires recorded agent authorship or review of the adopted head. Without it, a Fix Pass, even with merge, or a targeted Fix run asked to merge only by merge.always, still repairs the PR and checks CI, then finishes successfully Ready for review (exit 0) and logs the hold. An explicit thirdshift fix <PR> merge still fails with the hold and leaves the repaired PR ready for review.

With no PR target, thirdshift fix [base <branch>] [--author <login>] is a Pass. Without --author, it first checks the Base branch's origin tip: a failed first push attempt gets one failed-jobs re-run, then PR selection continues without waiting. Persistent or non-rerunnable failures get a CI-fix session on fix-<base>-<short-sha> and a repair PR targeting the Base branch, treating every red check as its own; that Fix run ends the Pass. Existing PRs from that branch prevent duplicates, failed drafts included. Merge and email policy apply, and Self-merge closes the Base branch's CI-red reports and Base fix issues.

-

Use thirdshift fix base master no-merge merge-base-fix to Self-merge only a newly authored Base branch CI repair and leave selected PRs ready for review, even with merge.always = true. merge-base-fix (also --merge-base-fix) changes that new repair's merge permission alone; the usual Delivery and Self-merge gates still apply. Selected PRs follow merge, no-merge and the User config. An existing repair PR selected later or retried gains no permission from its branch name or this word; request fix <PR> merge explicitly. The word is rejected outside a Fix Pass. Omission preserves existing behavior, --author still skips Base branch maintenance, and a Ticket run's base-fix still always merges.

+

Use thirdshift fix base master no-merge merge-base-fix to Self-merge only a newly authored Base branch CI repair and leave selected PRs ready for review, even with merge.always = true. merge-base-fix (also --merge-base-fix) changes that new repair's merge permission alone; the usual Delivery and Self-merge gates still apply. Selected PRs follow merge, no-merge and the User config. An existing repair PR selected later or retried gains no permission from its branch name or this word; request fix <PR> merge explicitly. The word is rejected outside a Fix Pass. Omission preserves existing behavior, --author still skips Base branch maintenance, and a Ticket run's base-fix still requests Self-merge. A configured Self-merge check can hold the Base fix for review.

Otherwise the Pass selects an eligible open, non-draft, same-repository PR targeting the selected Base branch. A Merge conflict or CI red on the current head comes first, lowest PR number first. With behind <n> or the repository’s fix.behind setting, PRs at least that many commits behind also qualify, furthest behind first. The Pass skips a PR held only by a Sign-off hold or whose latest run on this machine ended at a Self-merge check hold, even when it meets the behind threshold. A Merge conflict or other settled CI red keeps it eligible, and the held check stays out of the Repair's failure list. It skips untrusted authors and in-progress PRs, passing over busy reservations and head branches already checked out locally. Local occupancy reasons name the PR and occupying path on stderr and, when no candidate can be taken, in the Activity log. The check preserves occupied worktrees; an explicit PR target still fails and names the occupying path. At the Command limit or with no eligible PR left, it records a skip, exits successfully and sends no Run notification. Later Passes skip PRs left as drafts. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state.

A Fix Pass checks every linked closing issue before and after reserving the PR. An in-progress Claim on a Spec or standalone Ticket run's issue, including on another host, makes it skip the PR and name the claimed issue on stderr. It can adopt the PR on a later Pass after the Claim ends. Unreadable links or labels fail closed; explicit PR targets keep their existing behavior. Once the Pass has selected a pull request, an untrusted author of a linked closing issue, or any title or body edit by an account that is not a Trusted account, stops the Fix run before the issue is used and does not take the next candidate.

A Fix run's Self-merge needs recorded agent authorship or review covering the exact adopted head, written by the GitHub account thirdshift acts as. Completed Ticket, Spec and Base CI Deliveries record their delivered heads for later Fix runs. Without that evidence the repaired PR stays ready for review; run thirdshift review <PR URL> before retrying Self-merge.

@@ -259,7 +259,7 @@

How thirdshift works

  • Spec PR → Base branchOne combined pull request for you to review, or to merge when requested
  • -

    Each Ticket gets a Ticket run that Self-merges into the Spec branch, not directly into main. The Spec PR gathers the result into the Base branch. Child Ticket runs verify any rendered UI changes locally in their Worktree without calling gh or uploading attachments, while the combined Spec review captures and attaches unified Before and After Visual evidence when writing the Spec PR body. A Ticket closing means its work landed on the Spec branch; the whole Spec has not shipped yet.

    +

    Each Ticket gets a Ticket run that Self-merges into the Spec branch. The configured Self-merge check runs only on the Spec PR, when it is ready to Self-merge into the Base branch. Child Ticket runs verify any rendered UI changes locally in their Worktree without calling gh or uploading attachments, while the combined Spec review captures and attaches unified Before and After Visual evidence when writing the Spec PR body. A Ticket closing means its work landed on the Spec branch; the whole Spec has not shipped yet.

    A failed Ticket stops only its dependents; other reachable Tickets can still run. Tickets marked for human work or triage also hold their dependents. An incomplete Spec leaves a draft Spec PR with a Tickets checklist. A Spec run that is only waiting, with no failed or interrupted Ticket and every undone Ticket gated, blocked behind gated Tickets or outside work, or outside the Spec's repository, puts ready-for-agent back on its Spec instead of agent-failed, unless someone other than a Trusted account or the Spec's authorized author edited it since its last Trusted labelling, which leaves needs-triage, and comments on the Spec naming each undone Ticket and what it waits on. Pickup continues it once a Ticket can start; a blocking cycle is a failure. A handed-back Spec with every Ticket closed can also be taken when its latest Spec branch is on origin, with no PR or an open PR: it goes straight to Spec review and Delivery without running a Ticket again. Its usual Ready issue gates still apply; Architect gives it priority even while it settles. A Spec PR closed, merged or retargeted mid-run starts no further Ticket, holds the Self-merge of a running Ticket started after it opened, and ends the Spec run without a Recovery command. An Unready Ticket's checklist and Command log line name its open blockers, marking those outside the Spec and those labelled ready-for-agent; outside blockers are reported but never run. Rerunning continues existing branches. Spec run controls and limits.

    diff --git a/site/index.html b/site/index.html index 60d3d2009..6503af0e8 100644 --- a/site/index.html +++ b/site/index.html @@ -125,7 +125,7 @@

    Your issues become pull requests overnight.

    Review runs and pull-request Custom processes record their target PR URL and title before the first session starts. It appears in thirdshift status and the Command log while the run is live, and Command log and Session trace pages show the selected Command's GitHub issue or pull request link and title below the page heading (including a Pickup or Pass run's opened pull requests). Compact Working rows, including Overview, show live Fix and Review targets as clickable PR #number links beside the repository and run type, on desktop and phone, locally and across the Fleet. Explicit and Pass-selected targets appear alike. A Base branch CI repair shows its exact Base branch before publication and keeps it beside the PR link afterwards; older records without a target keep their Command label.

    thirdshift fix <PR URL or number> takes an open pull request by a Trusted account, ready or draft, straight through Delivery and the Repair loop against its own Base branch. With no PR target, thirdshift fix [base <branch>] [--author <login>] [behind <n>] is a Pass taking eligible ready PRs with a Merge conflict or CI red first, lowest number first. behind <n> or the repository’s fix.behind setting also admits PRs at least that many commits behind, furthest behind first. A Fix Pass skips a PR held only by a Sign-off hold or whose latest run on this machine ended at a Self-merge check hold, even when it meets the behind threshold. A Merge conflict or settled CI red apart from the Sign-off hold keeps the PR eligible. An explicit Fix run facing a Sign-off hold leaves the PR ready for review and names the check and label. The Pass skips head branches checked out locally, passing over them with the PR URL and occupying path on stderr. It skips cleanly at the Command limit or when none can be taken, recording occupancy reasons in the Activity log. An explicit PR target still fails and names the occupying worktree. A Fix run skips implementation and initial code review, reserves the PR until it ends, and supplies Repairs with trusted PR and linked closing-issue context. It stops before using a linked closing issue, including when started as a Pass, unless that issue's author is a Trusted account and no account that is not one has edited its title or body. Add merge for Self-merge or base-fix for inherited failures; the usual User config defaults apply. Self-merge needs recorded agent review of the adopted head; without it a Fix Pass, or a targeted Fix run asked to merge only by merge.always, repairs the PR and finishes successfully Ready for review, logging the hold. An explicit thirdshift fix <PR> merge still fails with the hold and leaves the repaired PR ready. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state. Other Delivery failures preserve work, draft the PR and offer a Fix run retry. Fix runs

    A Fix Pass checks every linked closing issue before and after reserving the PR. An in-progress Claim on a Spec or standalone Ticket run's issue, including on another host, makes it skip the PR and name the claimed issue on stderr. It can adopt the PR on a later Pass after the Claim ends. Unreadable links or labels fail closed; explicit PR targets keep their existing behavior. Once the Pass has selected a pull request, an untrusted author of a linked closing issue, or any title or body edit by an account that is not a Trusted account, stops the Fix run before the issue is used and does not take the next candidate.

    -

    thirdshift fix base master no-merge merge-base-fix lets a newly authored Base branch CI repair Self-merge through the usual gates while leaving selected PRs ready for review, even with merge.always = true. The Fix-Pass-only merge-base-fix word changes only that new repair's merge permission; selected PRs keep following merge, no-merge and the User config. Existing repair PRs gain no permission from their branch names or this word; use an explicit targeted fix <PR> merge to merge one. Omission keeps the existing policy, --author still skips Base branch CI, and a Ticket run's own base-fix still always merges. Fix Pass merge policy.

    +

    thirdshift fix base master no-merge merge-base-fix lets a newly authored Base branch CI repair Self-merge through the usual gates while leaving selected PRs ready for review, even with merge.always = true. The Fix-Pass-only merge-base-fix word changes only that new repair's merge permission; selected PRs keep following merge, no-merge and the User config. Existing repair PRs gain no permission from their branch names or this word; use an explicit targeted fix <PR> merge to merge one. Omission keeps the existing policy, --author still skips Base branch CI, and a Ticket run's own base-fix still requests Self-merge. A configured Self-merge check can hold the Base fix for review. Fix Pass merge policy.

    Without --author, a Fix Pass first checks Base branch CI on origin. A failed first push attempt gets one failed-jobs re-run, then PR selection continues without waiting. Pending or re-running Base checks, an occupied CI reservation, or an existing repair branch or PR skip only Base branch maintenance; stderr and the Activity log record the reason. Persistent or non-rerunnable failures get a CI-fix session on fix-<base>-<short-sha> and a repair PR targeting the Base branch, with every red check its own to fix; that Fix run ends the Pass. Failed opening sessions publish preserved work as draft repair PRs with a Fix Recovery command. An existing repair branch or PR prevents duplicates, including failed drafts. Completed Ticket, Spec and Base CI Deliveries record their exact agent-authored or reviewed heads for later Fix Self-merge. Merge and email flags and User config apply; Self-merge also closes the Base branch's CI-red reports and Base fix issues.

    If the Base branch CI-fix session commits nothing, the Fix run pushes no repair branch, opens no PR and exits successfully, with the reason on stderr and in the Activity log. A local Git ref remembers that Base branch and full commit in the Launch repository, so later Passes there skip that CI-fix and can select another PR. No further Check re-run is requested.

    Fix CI sessions keep command and test logs in the worktree's Git-excluded .validation-logs/ directory, which cleanup discards. They reproduce with the failing test file or filter before a full suite, without full-suite debug output or sleep-and-tail polling loops. Review sessions check whether the PR is open at most once, immediately before a multi-minute validation suite; thirdshift also checks its state around the session and before Delivery.

    diff --git a/tests/base_fix.rs b/tests/base_fix.rs index d86f57c13..295704f7c 100644 --- a/tests/base_fix.rs +++ b/tests/base_fix.rs @@ -301,6 +301,43 @@ fn a_merge_run_self_merges_once_its_base_fix_has_merged() { } } +#[test] +fn a_base_fix_obeys_the_self_merge_check() { + for (check_exit, fix_state) in [(1, "OPEN"), (0, "MERGED")] { + let scenario = Scenario::new(); + scenario.origin_has_commit( + "main", + "check", + &format!("#!/bin/sh\necho base fix hold\nexit {check_exit}\n"), + "Add check", + ); + scenario.user_config_is("[merge]\nself_merge_check = { \"acme/widgets\" = \"check\" }\n"); + scenario.agent_does(RUN_OPENS_PR_WITH_INHERITED_FAILURE); + scenario.agent_does_for(8, &format!("{BASE_FIX_OPENS_PR}{GREEN_ON_HEAD}")); + + let result = scenario.run(&[&scenario.issue_url(7), "base-fix"]); + + let fix = &scenario.gh_state()["prs"][1]; + assert_eq!(fix["head"], "issue-8"); + assert_eq!(fix["state"], fix_state, "{}", result.stderr); + assert_eq!(fix["isDraft"], false, "{}", result.stderr); + assert!( + result + .stderr + .contains(&format!("Self-merge check \"check\" exited {check_exit}")), + "{}", + result.stderr + ); + if check_exit == 1 { + assert!(result.stderr.contains("base fix hold"), "{}", result.stderr); + assert!(scenario.gh_calls_of("pr", "merge").is_empty()); + } else { + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!(scenario.origin_file("main", "ci-fix.txt").is_some()); + } + } +} + #[test] fn the_base_fix_merges_into_the_runs_base_branch_whatever_the_launch_directory_has_checked_out() { let scenario = Scenario::new(); diff --git a/tests/fix_base_ci.rs b/tests/fix_base_ci.rs index 9ca1e02da..66623ebef 100644 --- a/tests/fix_base_ci.rs +++ b/tests/fix_base_ci.rs @@ -413,25 +413,40 @@ fn merge_base_fix_self_merges_only_the_new_base_repair() { } #[test] -fn a_self_merge_check_can_hold_a_base_ci_repair() { - let scenario = Scenario::new(); - scenario.origin_has_commit( - "main", - "check", - "#!/bin/sh\necho base hold\nexit 1\n", - "Add check", - ); - scenario.user_config_is("[merge]\nself_merge_check = { \"acme/widgets\" = \"check\" }\n"); - failed_base(&scenario, 2); - scenario.agent_does(FIX); +fn a_base_ci_repair_obeys_the_self_merge_check() { + for (check_exit, state) in [(1, "OPEN"), (0, "MERGED")] { + let scenario = Scenario::new(); + scenario.origin_has_commit( + "main", + "check", + &format!("#!/bin/sh\necho base hold\nexit {check_exit}\n"), + "Add check", + ); + scenario.user_config_is("[merge]\nself_merge_check = { \"acme/widgets\" = \"check\" }\n"); + failed_base(&scenario, 2); + scenario.agent_does(FIX); - let result = scenario.run(&["fix", "base", "main", "merge-base-fix", "no-email"]); + let result = scenario.run(&["fix", "base", "main", "merge-base-fix", "no-email"]); - assert_eq!(result.code, Some(0), "{}", result.stderr); - assert!(result.stderr.contains("base hold"), "{}", result.stderr); - assert!(scenario.gh_calls_of("pr", "merge").is_empty()); - assert_eq!(scenario.gh_state()["prs"][0]["state"], "OPEN"); - assert_eq!(scenario.gh_state()["prs"][0]["isDraft"], false); + assert_eq!(result.code, Some(0), "{}", result.stderr); + let pr = &scenario.gh_state()["prs"][0]; + assert_eq!(pr["state"], state, "{}", result.stderr); + assert_eq!(pr["isDraft"], false); + assert!( + result + .stderr + .contains(&format!("Self-merge check \"check\" exited {check_exit}")), + "{}", + result.stderr + ); + assert_eq!( + scenario.gh_calls_of("pr", "merge").len(), + usize::from(check_exit == 0) + ); + if check_exit == 1 { + assert!(result.stderr.contains("base hold"), "{}", result.stderr); + } + } } fn recorded_review(scenario: &Scenario, branch: &str) { diff --git a/tests/pickup_run.rs b/tests/pickup_run.rs index 2eacdfc4a..7fe949509 100644 --- a/tests/pickup_run.rs +++ b/tests/pickup_run.rs @@ -2246,6 +2246,47 @@ fn merge_reaches_the_dispatched_run() { assert_eq!(pr["state"], "MERGED"); } +#[test] +fn pickup_merge_always_obeys_the_self_merge_check_without_a_merge_label() { + for (check_exit, state, outcome) in [ + ( + 1, + "OPEN", + "ready for review waiting for Self-merge check held: pickup hold", + ), + (0, "MERGED", "merged"), + ] { + let scenario = ready_ticket(); + scenario.origin_has_commit( + "main", + "check", + &format!("#!/bin/sh\necho pickup hold\nexit {check_exit}\n"), + "Add check", + ); + scenario.user_config_is( + "[merge]\nalways = true\nself_merge_check = { \"acme/widgets\" = \"check\" }\n", + ); + + let result = scenario.run(&["pickup"]); + + let pr = pr_from(&scenario, "issue-7"); + assert_ended_with_pr(&result, &pr, outcome); + assert_eq!(pr["state"], state, "{}", result.stderr); + assert_eq!(pr["isDraft"], false); + assert!( + result + .stderr + .contains(&format!("Self-merge check \"check\" exited {check_exit}")), + "{}", + result.stderr + ); + assert_eq!( + scenario.gh_calls_of("pr", "merge").len(), + usize::from(check_exit == 0) + ); + } +} + const RED: &str = r#"[{"name": "test", "conclusion": "failure"}]"#; const GREEN: &str = r#"[{"name": "test", "conclusion": "success"}]"#; diff --git a/tests/process.rs b/tests/process.rs index 4002b3adc..3f6787fb9 100644 --- a/tests/process.rs +++ b/tests/process.rs @@ -5403,23 +5403,32 @@ fn prepare_ship(body: &str) -> Scenario { #[test] fn a_custom_self_merge_step_obeys_the_self_merge_check() { - let scenario = prepare_ship(LAND); - scenario.origin_has_commit( - "main", - "check", - "#!/bin/sh\necho process hold\nexit 1\n", - "Add check", - ); - scenario.user_config_is("[merge]\nself_merge_check = { \"acme/widgets\" = \"check\" }\n"); + for check_exit in [1, 0] { + let scenario = prepare_ship(LAND); + scenario.origin_has_commit( + "main", + "check", + &format!("#!/bin/sh\necho process hold\nexit {check_exit}\n"), + "Add check", + ); + scenario.user_config_is("[merge]\nself_merge_check = { \"acme/widgets\" = \"check\" }\n"); - let result = scenario.run(&["process", "ship", "issue", "7", "merge"]); + let result = scenario.run(&["process", "ship", "issue", "7", "merge"]); - assert_eq!(result.code, Some(0), "{}", result.stderr); - assert!(result.stderr.contains("process hold"), "{}", result.stderr); - assert_eq!(scenario.gh_state()["prs"][0]["state"], "OPEN"); - assert_eq!(scenario.gh_state()["prs"][0]["isDraft"], false); - assert!(scenario.issue_labels(7).is_empty()); - assert!(scenario.gh_calls_of("pr", "merge").is_empty()); + assert!( + result + .stderr + .contains(&format!("Self-merge check \"check\" exited {check_exit}")), + "{}", + result.stderr + ); + if check_exit == 1 { + assert!(result.stderr.contains("process hold"), "{}", result.stderr); + assert_left_ready(&scenario, &result); + } else { + assert_merged(&scenario, &result); + } + } } #[test] diff --git a/tests/process/spec_run.rs b/tests/process/spec_run.rs index 5ef96e981..dad6f18ab 100644 --- a/tests/process/spec_run.rs +++ b/tests/process/spec_run.rs @@ -22,13 +22,18 @@ fn the_compiled_spec_run_is_listed_shown_and_passes_check() { #[test] fn the_built_in_spec_run_checks_its_final_self_merge_only() { let scenario = Scenario::new(); - scenario.spec_has_tickets(7, &[(8, &[])]); + scenario.spec_has_tickets(7, &[(8, &[]), (9, &[8])]); scenario.agent_does_for(8, &agent_lands_ticket(8, "issue-7")); + scenario.agent_does_for(9, &agent_lands_ticket(9, "issue-7")); scenario.agent_does_for(7, "true"); + let calls = scenario.path("check-calls"); scenario.origin_has_commit( "main", "check", - "#!/bin/sh\necho built-in spec hold\nexit 1\n", + &format!( + "#!/bin/sh\nprintf '%s %s\\n' \"$PR_NUMBER\" \"$BASE_BRANCH\" >> '{}'\necho built-in spec hold\nexit 1\n", + calls.display() + ), "Add check", ); scenario.user_config_is("[merge]\nself_merge_check = { \"acme/widgets\" = \"check\" }\n"); @@ -41,9 +46,18 @@ fn the_built_in_spec_run_checks_its_final_self_merge_only() { "{}", result.stderr ); - assert_eq!(pr_from(&scenario, "issue-8")["state"], "MERGED"); - assert_eq!(pr_from(&scenario, "issue-7")["state"], "OPEN"); - assert_eq!(pr_from(&scenario, "issue-7")["isDraft"], false); + for branch in ["issue-8", "issue-9"] { + let ticket = pr_from(&scenario, branch); + assert_eq!(ticket["base"], "issue-7"); + assert_eq!(ticket["state"], "MERGED"); + } + let spec = pr_from(&scenario, "issue-7"); + assert_eq!(spec["state"], "OPEN"); + assert_eq!(spec["isDraft"], false); + assert_eq!( + std::fs::read_to_string(calls).unwrap(), + format!("{} main\n", spec["number"]) + ); assert!(scenario.issue_labels(7).is_empty()); } diff --git a/tests/review_merge.rs b/tests/review_merge.rs index abea2d68b..99e7694b0 100644 --- a/tests/review_merge.rs +++ b/tests/review_merge.rs @@ -99,6 +99,28 @@ fn a_review_self_merge_check_keeps_the_review_ready_for_review() { ); } +#[test] +fn a_review_self_merges_after_the_check_passes() { + let scenario = Scenario::new(); + scenario.origin_has_commit("main", "check", "#!/bin/sh\nexit 0\n", "Add check"); + let url = pull_request(&scenario); + scenario.user_config_is("[merge]\nself_merge_check = { \"acme/widgets\" = \"check\" }\n"); + scenario.agent_does(NO_FINDINGS); + + let result = scenario.run(&["review", &url, "merge"]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!( + result + .stderr + .contains("Self-merge check \"check\" exited 0"), + "{}", + result.stderr + ); + assert_eq!(scenario.gh_state()["prs"][0]["state"], "MERGED"); + assert_eq!(scenario.gh_calls_of("pr", "merge").len(), 1); +} + #[test] fn review_merge_requires_a_complete_clean_security_review() { for pass in [false, true] { From 0c1e0ecd815d8412f4da048b28599d846e59a6c4 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Fri, 4 Dec 2026 12:06:02 -0500 Subject: [PATCH 11/27] Preserve first-observed PR bodies for Self-merge checks (#2424) --- docs/guide.md | 18 ++++--- site/docs/index.html | 18 ++++--- src/branch.rs | 1 + src/github.rs | 6 +-- src/processes/source.rs | 2 +- src/processes/ticket.rs | 4 +- src/pull_request.rs | 35 +++++++++--- src/run.rs | 9 +++- src/self_merge_check.rs | 8 +-- src/spec_run.rs | 6 +-- tests/self_merge_check.rs | 108 ++++++++++++++++++++++++++++++-------- 11 files changed, 157 insertions(+), 58 deletions(-) diff --git a/docs/guide.md b/docs/guide.md index 6c3650848..55308b9a1 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -2930,13 +2930,17 @@ absent from the Base branch, the hold reason reports the missing path. An absolute path such as `/usr/local/bin/self-merge-check` names a host executable outside Git worktrees. -Both forms run from Command scratch with `PR_NUMBER`, `PR_BODY`, -`PR_BODY_AT_START`, `REPOSITORY` (`owner/repo`) and `BASE_BRANCH` in their -environment. The current body comes -from the readiness observation for the head about to merge. The start body is -the first body observed by the Command, or the opening body when thirdshift -creates the pull request. The command can use both bodies to enforce its own -review policy. +Both forms run from Command scratch with `PR_NUMBER`, `REPOSITORY` +(`owner/repo`), `BASE_BRANCH` and two pull request bodies in their environment. + +- `PR_BODY` comes from the readiness observation of the head about to merge. +- `PR_BODY_AT_START` contains the opening body for a pull request created by + the Command. For an existing pull request, including a Fix run or + Continuation, it contains the body at the Command's first observation. + +A Repair can change `PR_BODY` while `PR_BODY_AT_START` keeps the starting text. +The repository's check can allow a declaration where the starting body had +none and hold a Repair that changes an existing declaration. Exit `0` allows Self-merge. Any other exit, a missing or unstartable executable, or a one-minute timeout leaves the pull request ready for review. The first diff --git a/site/docs/index.html b/site/docs/index.html index 8688cba9d..3eff49297 100644 --- a/site/docs/index.html +++ b/site/docs/index.html @@ -2898,13 +2898,17 @@ absent from the Base branch, the hold reason reports the missing path.

    An absolute path such as /usr/local/bin/self-merge-check names a host executable outside Git worktrees.

    -

    Both forms run from Command scratch with PR_NUMBER, PR_BODY, -PR_BODY_AT_START, REPOSITORY (owner/repo) and BASE_BRANCH in their -environment. The current body comes -from the readiness observation for the head about to merge. The start body is -the first body observed by the Command, or the opening body when thirdshift -creates the pull request. The command can use both bodies to enforce its own -review policy.

    +

    Both forms run from Command scratch with PR_NUMBER, REPOSITORY +(owner/repo), BASE_BRANCH and two pull request bodies in their environment.

    +
      +
    • PR_BODY comes from the readiness observation of the head about to merge.
    • +
    • PR_BODY_AT_START contains the opening body for a pull request created by +the Command. For an existing pull request, including a Fix run or +Continuation, it contains the body at the Command's first observation.
    • +
    +

    A Repair can change PR_BODY while PR_BODY_AT_START keeps the starting text. +The repository's check can allow a declaration where the starting body had +none and hold a Repair that changes an existing declaration.

    Exit 0 allows Self-merge. Any other exit, a missing or unstartable executable, or a one-minute timeout leaves the pull request ready for review. The first nonempty stdout line, trimmed and capped at 240 characters, becomes the diff --git a/src/branch.rs b/src/branch.rs index d78a7ab7d..93305fc2d 100644 --- a/src/branch.rs +++ b/src/branch.rs @@ -377,6 +377,7 @@ mod tests { head: pr.head.to_string(), base: pr.base.to_string(), is_draft: false, + body: None, }) .collect()) } diff --git a/src/github.rs b/src/github.rs index 3c23617c0..3e82a70b1 100644 --- a/src/github.rs +++ b/src/github.rs @@ -910,7 +910,6 @@ impl GitHub { }; Ok(Some(PrSnapshot { pr: PullRequest::from_json(&json)?, - body: json["body"].as_str().map(String::from), mergeable, has_required_label, head_commit: json["headRefOid"] @@ -1938,7 +1937,7 @@ query($owner: String!, $repo: String!, $number: Int!, $after: String) { } }"; -const PR_FIELDS: &str = "number,url,state,headRefName,baseRefName,isDraft"; +const PR_FIELDS: &str = "number,url,state,headRefName,baseRefName,isDraft,body"; const SNAPSHOT_FIELDS: &str = "number,url,state,headRefName,baseRefName,isDraft,mergeable,headRefOid,isCrossRepository,body"; @@ -1947,7 +1946,6 @@ const SNAPSHOT_FIELDS: &str = #[derive(Debug, Clone)] pub struct PrSnapshot { pub pr: PullRequest, - pub body: Option, pub mergeable: Mergeable, pub head_commit: String, pub from_fork: bool, @@ -2014,6 +2012,7 @@ pub struct PullRequest { pub head: String, pub base: String, pub is_draft: bool, + pub body: Option, } impl PullRequest { @@ -2050,6 +2049,7 @@ impl PullRequest { .context(CommandFailure::InvalidResponse( "gh output has no isDraft".into(), ))?, + body: json["body"].as_str().map(String::from), }) } } diff --git a/src/processes/source.rs b/src/processes/source.rs index 8b2978282..dade85bd2 100644 --- a/src/processes/source.rs +++ b/src/processes/source.rs @@ -952,7 +952,7 @@ pub(super) fn run_issue_branch( process: name, delivered: false, merged: false, - pull_request: PullRequest::new(&issue, &branch, &base, GitHub::new()), + pull_request: PullRequest::for_selection(&issue, &selection, &base, GitHub::new()), reviews: Vec::new(), spec_tickets: None, child_asks: ChildAsks { diff --git a/src/processes/ticket.rs b/src/processes/ticket.rs index 23ad3f384..4178987c3 100644 --- a/src/processes/ticket.rs +++ b/src/processes/ticket.rs @@ -93,9 +93,9 @@ pub(crate) fn run_custom( delivered: false, merged: false, pull_request: { - let mut pull_request = PullRequest::new( + let mut pull_request = PullRequest::for_selection( delivery.issue.issue(), - &branch, + selection, delivery.base, GitHub::new(), ); diff --git a/src/pull_request.rs b/src/pull_request.rs index ab3edd9bb..068dd355f 100644 --- a/src/pull_request.rs +++ b/src/pull_request.rs @@ -187,6 +187,23 @@ impl PullRequest { } } + /// Retain the body read during branch selection. Delivery still captures + /// the PR identity at its normal observation. + pub(crate) fn for_selection( + issue: &IssueUrl, + selection: &crate::branch::Selection, + base: &str, + adapter: A, + ) -> Self { + let mut target = Self::new(issue, selection.branch(), base, adapter); + if let crate::branch::Selection::Continuation { pr: Some(pr), .. } = selection + && let Some(body) = &pr.body + { + target.remember_body(pr.number, body); + } + target + } + /// Capture an explicit pull request before any publication or Repair. pub fn on_pull_request( pr: &crate::review::PullRequestUrl, @@ -222,7 +239,7 @@ impl PullRequest { let selector = self.selector(); if let Some(snapshot) = self.adapter.observe(&self.issue, &selector, false, None)? && snapshot.pr.is_open() - && let Some(body) = &snapshot.body + && let Some(body) = &snapshot.pr.body { self.check_ownership( &snapshot, @@ -835,9 +852,13 @@ impl PullRequest { Some(MergeAttempt::Held("PR body at start is unavailable".into())); return Ok(false); }; - if let Some(reason) = - check.run(git, &issue.repo_slug(), &self.base, &snapshot, start_body)? - { + if let Some(reason) = check.run( + git, + &issue.repo_slug(), + &self.base, + &snapshot.pr, + start_body, + )? { stopped = Some(MergeAttempt::Held(reason)); return Ok(false); } @@ -854,7 +875,7 @@ impl PullRequest { ))); return Ok(false); } - if rechecked.body != snapshot.body { + if rechecked.pr.body != snapshot.pr.body { stopped = Some(MergeAttempt::Held( "PR body changed during the Self-merge check".into(), )); @@ -973,7 +994,7 @@ impl PullRequest { fn capture(&mut self, snapshot: &PrSnapshot) -> Result<()> { let number = self.identified.as_ref().map(|pr| pr.number); self.check_ownership(snapshot, &self.branch, number)?; - if let Some(body) = &snapshot.body { + if let Some(body) = &snapshot.pr.body { self.remember_body(snapshot.pr.number, body); } if self.identified.is_none() { @@ -1272,7 +1293,6 @@ mod tests { fn snapshot() -> PrSnapshot { PrSnapshot { - body: Some(String::new()), pr: Record { number: 12, url: URL.to_string(), @@ -1280,6 +1300,7 @@ mod tests { head: "issue-7".to_string(), base: "main".to_string(), is_draft: false, + body: Some(String::new()), }, mergeable: Mergeable::Yes, head_commit: "watched".to_string(), diff --git a/src/run.rs b/src/run.rs index 5d31ae68b..43bbad790 100644 --- a/src/run.rs +++ b/src/run.rs @@ -536,7 +536,7 @@ fn start_in_worktree( let opening = crate::implement::opening(issue, base, selection, scope); let worktree = outside.worktree(checkout, branch, base)?; if !tickets.is_empty() { - return outside.spec_run(tickets, worktree, base, parallel); + return outside.spec_run(tickets, worktree, selection, base, parallel); } outside.deliver(worktree, base, opening, selection) } @@ -586,6 +586,7 @@ trait Outside { &mut self, tickets: Vec, worktree: Self::Worktree, + selection: &Selection, base: &str, parallel: NonZeroUsize, ) -> Result; @@ -773,6 +774,7 @@ impl<'a> Outside for LaunchAndGitHub<'a> { &mut self, tickets: Vec, worktree: Worktree, + selection: &Selection, base: &str, parallel: NonZeroUsize, ) -> Result { @@ -781,6 +783,7 @@ impl<'a> Outside for LaunchAndGitHub<'a> { spec_run::run( tickets, worktree, + selection, self.delivery(base), parallel, skip_authors, @@ -813,7 +816,7 @@ impl<'a> Outside for LaunchAndGitHub<'a> { .transpose()?; let opening = crate::implement::prepare(issue, base, &worktree, opening, labels.as_ref())?; let mut pull_request = - crate::pull_request::PullRequest::new(issue, worktree.branch(), base, GitHub::new()); + crate::pull_request::PullRequest::for_selection(issue, selection, base, GitHub::new()); if let Some(spec_pr) = self.spec_pr.clone() { pull_request.gate_self_merge_on(spec_pr); } @@ -1021,6 +1024,7 @@ mod tests { &mut self, tickets: Vec, worktree: Checkout, + _selection: &Selection, base: &str, parallel: NonZeroUsize, ) -> Result { @@ -1090,6 +1094,7 @@ mod tests { head: "issue-7".to_string(), base: base.to_string(), is_draft: false, + body: None, }), } } diff --git a/src/self_merge_check.rs b/src/self_merge_check.rs index fb69f6225..01dcfc66b 100644 --- a/src/self_merge_check.rs +++ b/src/self_merge_check.rs @@ -11,7 +11,7 @@ use std::time::{Duration, Instant}; use anyhow::{Context, Result, ensure}; use crate::git::Git; -use crate::github::PrSnapshot; +use crate::github::PullRequest; use crate::process; const TIMEOUT: Duration = Duration::from_secs(60); @@ -62,7 +62,7 @@ impl Check { git: &Git, repo: &str, base: &str, - pr: &PrSnapshot, + pr: &PullRequest, start_body: &str, ) -> Result> { let reason = Arc::new(Mutex::new(None)); @@ -111,7 +111,7 @@ impl Check { git: &Git, repo: &str, base: &str, - pr: &PrSnapshot, + pr: &PullRequest, start_body: &str, reason: Arc>>, ) -> Result { @@ -168,7 +168,7 @@ impl Check { Command::new(executable) .args(&self.words[1..]) .current_dir(scratch) - .env("PR_NUMBER", pr.pr.number.to_string()) + .env("PR_NUMBER", pr.number.to_string()) .env( "PR_BODY", pr.body.as_deref().context("PR body is unavailable")?, diff --git a/src/spec_run.rs b/src/spec_run.rs index 4bc27c445..419bfc7ab 100644 --- a/src/spec_run.rs +++ b/src/spec_run.rs @@ -86,6 +86,7 @@ pub fn unstartable(spec: &IssueUrl, ticket: &Ticket) -> Option { pub fn run( tickets: Vec, worktree: Worktree, + selection: &crate::branch::Selection, delivery: Delivery, parallel: NonZeroUsize, skip_authors: &crate::skip_authors::SkipAuthors, @@ -93,8 +94,7 @@ pub fn run( ) -> Result { let sequence = crate::processes::spec::sequence()?; let (spec, base) = (delivery.issue.issue(), delivery.base); - let branch = worktree.branch().to_string(); - let mut spec_pr = PullRequest::new(spec, &branch, base, GitHub::new()); + let mut spec_pr = PullRequest::for_selection(spec, selection, base, GitHub::new()); spec_pr.resume_spec()?; let mut held = Some(worktree); let mut outside = ChildRunsAndGitHub::new( @@ -109,7 +109,7 @@ pub fn run( &mut outside, spec, base, - &branch, + selection.branch(), tickets, parallel, sequence.delivery, diff --git a/tests/self_merge_check.rs b/tests/self_merge_check.rs index 63b6916c0..9a4e6af0c 100644 --- a/tests/self_merge_check.rs +++ b/tests/self_merge_check.rs @@ -6,7 +6,17 @@ const OPEN_PR: &str = r#" echo feature > feature.txt git add feature.txt git commit -qm 'Add feature' -gh pr create --base main --head issue-7 --title 'Add feature' --body 'Closes #7' +gh pr create --base main --head issue-7 --title 'Add feature' --body "${OPENING_PR_BODY:-Closes #7}" +"#; + +const RELEASE_POLICY: &str = r#"#!/bin/sh +set -eu +start_lane=$(printf '%s\n' "$PR_BODY_AT_START" | sed -n '/^Release Lane: /p') +current_lane=$(printf '%s\n' "$PR_BODY" | sed -n '/^Release Lane: /p') +if [ -n "$start_lane" ] && [ "$start_lane" != "$current_lane" ]; then + echo 'Release Lane changed during this Command' + exit 1 +fi "#; fn configure(scenario: &Scenario, command: &str) { @@ -108,38 +118,92 @@ case "$PR_BODY" in *'Closes #7'*'Built with'*) exit 0 ;; *) exit 5 ;; esac } #[test] -fn a_repair_can_change_the_current_body_without_replacing_the_opening_body() { - let scenario = Scenario::new(); - host_check( - &scenario, - r#"#!/bin/sh -test "$PR_BODY_AT_START" = 'Closes #7' || exit 2 -case "$PR_BODY" in *'Updated by Repair'*) echo observed both bodies; exit 1 ;; *) exit 3 ;; esac -"#, - ); - scenario.agent_does(&format!( - r#"{OPEN_PR} +fn a_base_branch_policy_checks_release_lanes_after_a_repair() { + let review = "Release Lane: stakeholder-review"; + let ship = "Release Lane: auto-ship"; + for (opening_lane, repaired_lane, held) in [ + (review, ship, true), + (review, review, false), + ("", ship, false), + ] { + let scenario = Scenario::new(); + configure(&scenario, "check"); + scenario.origin_has_commit("main", "check", RELEASE_POLICY, "Add policy"); + scenario.agent_does(&format!( + r#"OPENING_PR_BODY='Closes #7 + +{opening_lane}' +{OPEN_PR} gh fake checks "$(git rev-parse HEAD)" '[{{"name":"test","conclusion":"failure"}}]' "# - )); - scenario.agent_does_in_session( - 2, - r#" + )); + scenario.agent_does_in_session( + 2, + &format!( + r#" git commit --allow-empty -qm Repair -gh fake pr issue-7 body '"Updated by Repair"' -gh fake checks "$(git rev-parse HEAD)" '[{"name":"test","conclusion":"success"}]' -"#, - ); +gh pr edit 1 --body 'Closes #7 + +{repaired_lane}' +gh fake checks "$(git rev-parse HEAD)" '[{{"name":"test","conclusion":"success"}}]' +"# + ), + ); + + let result = scenario.run(&[&scenario.issue_url(7)]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert_eq!(scenario.claude_calls().len(), 2, "{}", result.stderr); + assert_eq!( + result + .stderr + .contains("Release Lane changed during this Command"), + held, + "{opening_lane:?} to {repaired_lane:?}: {}", + result.stderr + ); + assert_eq!( + scenario.gh_state()["prs"][0]["state"], + if held { "OPEN" } else { "MERGED" }, + "{}", + result.stderr + ); + assert_eq!( + scenario.gh_calls_of("pr", "merge").len(), + usize::from(!held) + ); + } +} + +#[test] +fn a_continuation_keeps_the_body_from_branch_selection() { + let scenario = Scenario::new(); + configure(&scenario, "check"); + scenario.origin_has_commit("main", "check", RELEASE_POLICY, "Add policy"); + scenario.origin_has_branch("issue-7", "main", &["Earlier work"]); + scenario.github_has_pr("issue-7", "main", "OPEN"); + scenario.issue_labelled(7, &["ready-for-agent"]); + let mut state = scenario.gh_state(); + state["prs"][0]["body"] = "Release Lane: stakeholder-review".into(); + // The Claim reads labels after the Continuation has selected the open PR. + state["on_issue_view"]["7"] = serde_json::json!({ + "fields": "labels", + "script": "gh fake pr issue-7 body '\"Release Lane: auto-ship\"'" + }); + scenario.write_gh_state(&state); + scenario.agent_does(""); let result = scenario.run(&[&scenario.issue_url(7)]); assert_eq!(result.code, Some(0), "{}", result.stderr); assert!( - result.stderr.contains("observed both bodies"), + result + .stderr + .contains("Release Lane changed during this Command"), "{}", result.stderr ); - assert_eq!(scenario.claude_calls().len(), 2); + assert_eq!(scenario.gh_state()["prs"][0]["state"], "OPEN"); assert!(scenario.gh_calls_of("pr", "merge").is_empty()); } From 97760477a1bf33fb4435cf227c4d5024b922afc8 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Fri, 4 Dec 2026 12:06:57 -0500 Subject: [PATCH 12/27] Honor Self-merge check overrides before dispatch and selection (#2425) --- docs/guide.md | 12 ++++++---- site/architecture/index.html | 2 +- site/docs/index.html | 12 ++++++---- site/how-it-works/index.html | 2 +- site/index.html | 2 +- src/architect.rs | 6 ----- src/args.rs | 11 ++++----- src/asks.rs | 30 ++++++++++++++++++++---- src/command.rs | 37 ++++++++++++++++++++++++++--- src/fix.rs | 10 +++----- src/main.rs | 33 +++++++++++++++++--------- src/pickup.rs | 3 --- src/processes.rs | 31 ++++++++----------------- src/processes/review.rs | 4 ++-- src/security.rs | 6 ----- tests/command_surface.rs | 45 ++++++++++++++++++++++++++++++++++++ tests/fix_pass.rs | 40 ++++++++++++++++++++++++++++++++ tests/spec_run.rs | 11 +++++++-- 18 files changed, 214 insertions(+), 83 deletions(-) diff --git a/docs/guide.md b/docs/guide.md index 6c3650848..db944d136 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -2951,9 +2951,11 @@ pull request ready for review. Use `no-self-merge-check` or `--no-self-merge-check` to turn the check off for one Command. Use `self-merge-check` or `--self-merge-check` to require a -configured command for that run. Repositories with no entry have no check. -The check applies to each requested Self-merge, including the Spec PR into -the Base branch. Tickets land into the Spec branch without running the check. +configured command. If the repository has no entry, this is a usage error +before work starts. Give at most one of these options per Command. The +choice carries through to Runs dispatched by a Pass and to Base fixes. It +applies to requested Self-merges into the Base branch, including the Spec PR. +Tickets land into the Spec branch without running the check. After saving the User config and any entered Credentials, `thirdshift setup` checks the host tools for pull request **Visual evidence**: `gh >= 2.103.2`, @@ -3915,7 +3917,9 @@ other settled CI red keeps the PR eligible, with the held check left out of the Repair's failure list. An explicit Fix run on a PR held only by a Sign-off hold succeeds ready for review and names the check and label it is waiting on. A Fix Pass also passes over a PR whose latest Run on the machine ended at a -Self-merge check, unless the PR has a Merge conflict or settled CI red. +Self-merge check, unless the PR has a Merge conflict or settled CI red. Use +`no-self-merge-check` to let a Fix Pass consider such a PR under its usual +eligibility rules and skip the check if it Self-merges. The Pass skips `in-progress` PRs. It reserves and rechecks each candidate; if another machine reserved it first, it continues to the next candidate. diff --git a/site/architecture/index.html b/site/architecture/index.html index 3a0ef0add..3e41eed25 100644 --- a/site/architecture/index.html +++ b/site/architecture/index.html @@ -586,7 +586,7 @@

    Architecture

    Once a Pickup run, an Architect run or a Security run knows its repository, it replaces that kind's last-fired time under the repository's log folder, before launch checks or the Command limit. Repeated skips update the time without adding Activity log lines. thirdshift status, thirdshift cronjobs and their Console views read the same per-repository times; no reader starts work. A Custom process started with no issue, and neither an Issue-branch nor a Spec-branch worktree, counts toward the Command limit, runs beside other Passes up to it, takes no lock of a kind, and does not record a last-fired time. A file that declares either branch worktree is refused when no issue is given, before the Command limit.

    A Pass takes no Issue URL, so your operating system's scheduler can start it; thirdshift never schedules itself. A Pass is skipped while its repository is at its Command limit, [pass] command_limit, 1 by default: every live Command on the repository on the machine counts, a Ticket run started on an Issue URL included, but only a Pass is skipped. Passes of different kinds share a repository up to the limit, but never two Architect runs or two Security runs at once: each of those holds a lock of its kind and a review worktree of its own, and reserves the plan or fix it dispatches on origin, as a Pickup run reserves its Ready issue. A Pass with nothing to do is skipped, not failed. Architect and Security runs wait while a Ready issue is open, so work you shaped goes first. A Custom process started with no issue is a Pass for that rule and does not wait on a Ready issue or an Architect idea, unless the file declares either branch worktree: that is refused before any session, rather than skipped. One started with an issue is not a Pass. Your scheduler can start Architect runs every few minutes and Security runs on a schedule, with fixing allowed.

    A Fix run, thirdshift fix <PR URL or number>, targets an explicit PR; with no PR target it is a Pass sharing the repository up to its Command limit. Without --author, it first checks the Base branch's origin tip. A failed first push attempt gets one failed-jobs re-run, then PR selection continues without waiting. Persistent or non-rerunnable failures get a CI-fix session on fix-<base>-<short-sha> and a repair PR targeting the Base branch; that Fix run ends the Pass. All red checks are its own, existing repair PRs prevent duplicates, and merge and email policy apply. Self-merge closes the Base branch's CI-red reports and Base fix issues.

    -

    The Pass otherwise searches open, non-draft, same-repository PRs by Trusted accounts, giving Merge conflicts and current-head CI red priority in ascending PR number. behind <n> or the repository’s fix.behind setting adds PRs at least that many commits behind, furthest behind first. The Pass skips a PR held only by a Sign-off hold or whose latest run on this machine ended at a Self-merge check hold, even when it meets the behind threshold. A Merge conflict or settled CI red apart from the Sign-off hold keeps the PR eligible. An explicit Fix run facing a Sign-off hold leaves the PR ready for review and names the check and label. Optional base <branch> and --author <login> scope that search. Selection skips in-progress PRs and passes over head branches checked out locally, naming the PR and occupying path on stderr. When none can be taken, the Activity log skip includes those reasons without recording a failed Fix run. Occupied checkouts remain intact; an explicit PR target still fails and names the occupying path. Selection reserves and rechecks candidates before dispatch. Busy reservations pass through to the next candidate. Its fix-run Built-in process is delivery → self-merge, using the existing PR's head branch and Base branch without implementation or initial code review. It holds an origin reservation and in-progress through Repair and failure preservation, and records its own Command log and Run notification. Self-merge requires recorded agent authorship or review of the exact adopted head by thirdshift's GitHub account; completed Ticket, Spec and Base CI Deliveries record their delivered heads too. Absent that evidence, the repaired PR stays ready for review, preserving ADR 0004. Skips record an Activity log reason when it changes and send no notification. Later Passes skip PRs left as drafts. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state.

    +

    The Pass otherwise searches open, non-draft, same-repository PRs by Trusted accounts, giving Merge conflicts and current-head CI red priority in ascending PR number. behind <n> or the repository’s fix.behind setting adds PRs at least that many commits behind, furthest behind first. The Pass skips a PR held only by a Sign-off hold or whose latest run on this machine ended at a Self-merge check hold, even when it meets the behind threshold. With no-self-merge-check, a PR held by the Self-merge check can qualify under the usual rules. A Merge conflict or settled CI red apart from the Sign-off hold keeps the PR eligible. An explicit Fix run facing a Sign-off hold leaves the PR ready for review and names the check and label. Optional base <branch> and --author <login> scope that search. Selection skips in-progress PRs and passes over head branches checked out locally, naming the PR and occupying path on stderr. When none can be taken, the Activity log skip includes those reasons without recording a failed Fix run. Occupied checkouts remain intact; an explicit PR target still fails and names the occupying path. Selection reserves and rechecks candidates before dispatch. Busy reservations pass through to the next candidate. Its fix-run Built-in process is delivery → self-merge, using the existing PR's head branch and Base branch without implementation or initial code review. It holds an origin reservation and in-progress through Repair and failure preservation, and records its own Command log and Run notification. Self-merge requires recorded agent authorship or review of the exact adopted head by thirdshift's GitHub account; completed Ticket, Spec and Base CI Deliveries record their delivered heads too. Absent that evidence, the repaired PR stays ready for review, preserving ADR 0004. Skips record an Activity log reason when it changes and send no notification. Later Passes skip PRs left as drafts. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state.

    The Fix-Pass-only word merge-base-fix grants Self-merge only to a repair newly authored by the Base branch CI step, through the usual Delivery and Self-merge gates. Selected PRs keep the ordinary merge / no-merge and merge.always policy. Thus thirdshift fix base master no-merge merge-base-fix merges a new Base branch repair and leaves selected feature PRs ready for review even when merge.always = true. Existing repair PRs selected later or retried gain no permission from this word or their branch name; merging one requires the usual merge policy, such as targeted fix <PR> merge. Omission, --author scoping and Ticket-run base-fix behavior are unchanged.

    A Fix Pass checks every linked closing issue before and after reserving the PR. An in-progress Claim on a Spec or standalone Ticket run's issue, including on another host, makes it skip the PR and name the claimed issue on stderr. It can adopt the PR on a later Pass after the Claim ends. Unreadable links or labels fail closed; explicit PR targets keep their existing behavior. Once the Pass has selected a pull request, an untrusted author of a linked closing issue, or any title or body edit by an account that is not a Trusted account, stops the Fix run before the issue is used and does not take the next candidate.

    Pending or re-running Base branch checks, an occupied CI reservation, or an existing repair branch or PR skip only Base branch maintenance and leave PR selection available. Stderr and the Activity log record the reason, including when no eligible PR is found. Failed opening Base CI sessions publish preserved work as draft repair PRs with a Fix Recovery command. An existing repair branch prevents another attempt if PR creation failed.

    diff --git a/site/docs/index.html b/site/docs/index.html index 8688cba9d..0fe64d015 100644 --- a/site/docs/index.html +++ b/site/docs/index.html @@ -2917,9 +2917,11 @@ pull request ready for review.

    Use no-self-merge-check or --no-self-merge-check to turn the check off for one Command. Use self-merge-check or --self-merge-check to require a -configured command for that run. Repositories with no entry have no check. -The check applies to each requested Self-merge, including the Spec PR into -the Base branch. Tickets land into the Spec branch without running the check.

    +configured command. If the repository has no entry, this is a usage error +before work starts. Give at most one of these options per Command. The +choice carries through to Runs dispatched by a Pass and to Base fixes. It +applies to requested Self-merges into the Base branch, including the Spec PR. +Tickets land into the Spec branch without running the check.

    After saving the User config and any entered Credentials, thirdshift setup checks the host tools for pull request Visual evidence: gh >= 2.103.2, ffmpeg on PATH, and an installed Playwright Chromium executable. It checks @@ -3709,7 +3711,9 @@ the Repair's failure list. An explicit Fix run on a PR held only by a Sign-off hold succeeds ready for review and names the check and label it is waiting on. A Fix Pass also passes over a PR whose latest Run on the machine ended at a -Self-merge check, unless the PR has a Merge conflict or settled CI red.

    +Self-merge check, unless the PR has a Merge conflict or settled CI red. Use +no-self-merge-check to let a Fix Pass consider such a PR under its usual +eligibility rules and skip the check if it Self-merges.

    The Pass skips in-progress PRs. It reserves and rechecks each candidate; if another machine reserved it first, it continues to the next candidate. Before and after reserving, it reads every linked closing issue and skips the diff --git a/site/how-it-works/index.html b/site/how-it-works/index.html index 0641b5110..9ca45a9fd 100644 --- a/site/how-it-works/index.html +++ b/site/how-it-works/index.html @@ -136,7 +136,7 @@

    How thirdshift works

    Self-merge requires recorded agent authorship or review of the adopted head. Without it, a Fix Pass, even with merge, or a targeted Fix run asked to merge only by merge.always, still repairs the PR and checks CI, then finishes successfully Ready for review (exit 0) and logs the hold. An explicit thirdshift fix <PR> merge still fails with the hold and leaves the repaired PR ready for review.

    With no PR target, thirdshift fix [base <branch>] [--author <login>] is a Pass. Without --author, it first checks the Base branch's origin tip: a failed first push attempt gets one failed-jobs re-run, then PR selection continues without waiting. Persistent or non-rerunnable failures get a CI-fix session on fix-<base>-<short-sha> and a repair PR targeting the Base branch, treating every red check as its own; that Fix run ends the Pass. Existing PRs from that branch prevent duplicates, failed drafts included. Merge and email policy apply, and Self-merge closes the Base branch's CI-red reports and Base fix issues.

    Use thirdshift fix base master no-merge merge-base-fix to Self-merge only a newly authored Base branch CI repair and leave selected PRs ready for review, even with merge.always = true. merge-base-fix (also --merge-base-fix) changes that new repair's merge permission alone; the usual Delivery and Self-merge gates still apply. Selected PRs follow merge, no-merge and the User config. An existing repair PR selected later or retried gains no permission from its branch name or this word; request fix <PR> merge explicitly. The word is rejected outside a Fix Pass. Omission preserves existing behavior, --author still skips Base branch maintenance, and a Ticket run's base-fix still always merges.

    -

    Otherwise the Pass selects an eligible open, non-draft, same-repository PR targeting the selected Base branch. A Merge conflict or CI red on the current head comes first, lowest PR number first. With behind <n> or the repository’s fix.behind setting, PRs at least that many commits behind also qualify, furthest behind first. The Pass skips a PR held only by a Sign-off hold or whose latest run on this machine ended at a Self-merge check hold, even when it meets the behind threshold. A Merge conflict or other settled CI red keeps it eligible, and the held check stays out of the Repair's failure list. It skips untrusted authors and in-progress PRs, passing over busy reservations and head branches already checked out locally. Local occupancy reasons name the PR and occupying path on stderr and, when no candidate can be taken, in the Activity log. The check preserves occupied worktrees; an explicit PR target still fails and names the occupying path. At the Command limit or with no eligible PR left, it records a skip, exits successfully and sends no Run notification. Later Passes skip PRs left as drafts. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state.

    +

    Otherwise the Pass selects an eligible open, non-draft, same-repository PR targeting the selected Base branch. A Merge conflict or CI red on the current head comes first, lowest PR number first. With behind <n> or the repository’s fix.behind setting, PRs at least that many commits behind also qualify, furthest behind first. The Pass skips a PR held only by a Sign-off hold or whose latest run on this machine ended at a Self-merge check hold, even when it meets the behind threshold. With no-self-merge-check, a PR held by the Self-merge check can qualify under the usual rules. A Merge conflict or other settled CI red keeps it eligible, and the held check stays out of the Repair's failure list. It skips untrusted authors and in-progress PRs, passing over busy reservations and head branches already checked out locally. Local occupancy reasons name the PR and occupying path on stderr and, when no candidate can be taken, in the Activity log. The check preserves occupied worktrees; an explicit PR target still fails and names the occupying path. At the Command limit or with no eligible PR left, it records a skip, exits successfully and sends no Run notification. Later Passes skip PRs left as drafts. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state.

    A Fix Pass checks every linked closing issue before and after reserving the PR. An in-progress Claim on a Spec or standalone Ticket run's issue, including on another host, makes it skip the PR and name the claimed issue on stderr. It can adopt the PR on a later Pass after the Claim ends. Unreadable links or labels fail closed; explicit PR targets keep their existing behavior. Once the Pass has selected a pull request, an untrusted author of a linked closing issue, or any title or body edit by an account that is not a Trusted account, stops the Fix run before the issue is used and does not take the next candidate.

    A Fix run's Self-merge needs recorded agent authorship or review covering the exact adopted head, written by the GitHub account thirdshift acts as. Completed Ticket, Spec and Base CI Deliveries record their delivered heads for later Fix runs. Without that evidence the repaired PR stays ready for review; run thirdshift review <PR URL> before retrying Self-merge.

    Pending or re-running Base branch checks, an occupied CI reservation, or an existing repair branch or PR skip only Base branch maintenance and leave PR selection available. Stderr and the Activity log record the reason, including when no eligible PR is found. Failed opening Base CI sessions publish preserved work as draft repair PRs with a Fix Recovery command; an existing repair branch also prevents another attempt if PR creation failed.

    diff --git a/site/index.html b/site/index.html index 60d3d2009..5048fab76 100644 --- a/site/index.html +++ b/site/index.html @@ -123,7 +123,7 @@

    Your issues become pull requests overnight.

    Review Passes (review --author) and Fix Passes skip release-* pull requests targeting main, leaving their version-only heads to the Release run. Explicit thirdshift fix <pr-url> --no-merge --no-base-fix still repairs those pull requests.

    Review retries recover clean retained worktrees with verified ownership and committed fixes above the same captured PR head. Author Passes skip other local conflicts, notify once per state and continue to later waiting pull requests. An explicit PR URL still fails with preservation advice.

    Review runs and pull-request Custom processes record their target PR URL and title before the first session starts. It appears in thirdshift status and the Command log while the run is live, and Command log and Session trace pages show the selected Command's GitHub issue or pull request link and title below the page heading (including a Pickup or Pass run's opened pull requests). Compact Working rows, including Overview, show live Fix and Review targets as clickable PR #number links beside the repository and run type, on desktop and phone, locally and across the Fleet. Explicit and Pass-selected targets appear alike. A Base branch CI repair shows its exact Base branch before publication and keeps it beside the PR link afterwards; older records without a target keep their Command label.

    -

    thirdshift fix <PR URL or number> takes an open pull request by a Trusted account, ready or draft, straight through Delivery and the Repair loop against its own Base branch. With no PR target, thirdshift fix [base <branch>] [--author <login>] [behind <n>] is a Pass taking eligible ready PRs with a Merge conflict or CI red first, lowest number first. behind <n> or the repository’s fix.behind setting also admits PRs at least that many commits behind, furthest behind first. A Fix Pass skips a PR held only by a Sign-off hold or whose latest run on this machine ended at a Self-merge check hold, even when it meets the behind threshold. A Merge conflict or settled CI red apart from the Sign-off hold keeps the PR eligible. An explicit Fix run facing a Sign-off hold leaves the PR ready for review and names the check and label. The Pass skips head branches checked out locally, passing over them with the PR URL and occupying path on stderr. It skips cleanly at the Command limit or when none can be taken, recording occupancy reasons in the Activity log. An explicit PR target still fails and names the occupying worktree. A Fix run skips implementation and initial code review, reserves the PR until it ends, and supplies Repairs with trusted PR and linked closing-issue context. It stops before using a linked closing issue, including when started as a Pass, unless that issue's author is a Trusted account and no account that is not one has edited its title or body. Add merge for Self-merge or base-fix for inherited failures; the usual User config defaults apply. Self-merge needs recorded agent review of the adopted head; without it a Fix Pass, or a targeted Fix run asked to merge only by merge.always, repairs the PR and finishes successfully Ready for review, logging the hold. An explicit thirdshift fix <PR> merge still fails with the hold and leaves the repaired PR ready. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state. Other Delivery failures preserve work, draft the PR and offer a Fix run retry. Fix runs

    +

    thirdshift fix <PR URL or number> takes an open pull request by a Trusted account, ready or draft, straight through Delivery and the Repair loop against its own Base branch. With no PR target, thirdshift fix [base <branch>] [--author <login>] [behind <n>] is a Pass taking eligible ready PRs with a Merge conflict or CI red first, lowest number first. behind <n> or the repository’s fix.behind setting also admits PRs at least that many commits behind, furthest behind first. A Fix Pass skips a PR held only by a Sign-off hold or whose latest run on this machine ended at a Self-merge check hold, even when it meets the behind threshold. With no-self-merge-check, a PR held by the Self-merge check can qualify under the usual rules. A Merge conflict or settled CI red apart from the Sign-off hold keeps the PR eligible. An explicit Fix run facing a Sign-off hold leaves the PR ready for review and names the check and label. The Pass skips head branches checked out locally, passing over them with the PR URL and occupying path on stderr. It skips cleanly at the Command limit or when none can be taken, recording occupancy reasons in the Activity log. An explicit PR target still fails and names the occupying worktree. A Fix run skips implementation and initial code review, reserves the PR until it ends, and supplies Repairs with trusted PR and linked closing-issue context. It stops before using a linked closing issue, including when started as a Pass, unless that issue's author is a Trusted account and no account that is not one has edited its title or body. Add merge for Self-merge or base-fix for inherited failures; the usual User config defaults apply. Self-merge needs recorded agent review of the adopted head; without it a Fix Pass, or a targeted Fix run asked to merge only by merge.always, repairs the PR and finishes successfully Ready for review, logging the hold. An explicit thirdshift fix <PR> merge still fails with the hold and leaves the repaired PR ready. A closing-issue trust stop keeps unpublished Repair work local and leaves the PR in its current state. Other Delivery failures preserve work, draft the PR and offer a Fix run retry. Fix runs

    A Fix Pass checks every linked closing issue before and after reserving the PR. An in-progress Claim on a Spec or standalone Ticket run's issue, including on another host, makes it skip the PR and name the claimed issue on stderr. It can adopt the PR on a later Pass after the Claim ends. Unreadable links or labels fail closed; explicit PR targets keep their existing behavior. Once the Pass has selected a pull request, an untrusted author of a linked closing issue, or any title or body edit by an account that is not a Trusted account, stops the Fix run before the issue is used and does not take the next candidate.

    thirdshift fix base master no-merge merge-base-fix lets a newly authored Base branch CI repair Self-merge through the usual gates while leaving selected PRs ready for review, even with merge.always = true. The Fix-Pass-only merge-base-fix word changes only that new repair's merge permission; selected PRs keep following merge, no-merge and the User config. Existing repair PRs gain no permission from their branch names or this word; use an explicit targeted fix <PR> merge to merge one. Omission keeps the existing policy, --author still skips Base branch CI, and a Ticket run's own base-fix still always merges. Fix Pass merge policy.

    Without --author, a Fix Pass first checks Base branch CI on origin. A failed first push attempt gets one failed-jobs re-run, then PR selection continues without waiting. Pending or re-running Base checks, an occupied CI reservation, or an existing repair branch or PR skip only Base branch maintenance; stderr and the Activity log record the reason. Persistent or non-rerunnable failures get a CI-fix session on fix-<base>-<short-sha> and a repair PR targeting the Base branch, with every red check its own to fix; that Fix run ends the Pass. Failed opening sessions publish preserved work as draft repair PRs with a Fix Recovery command. An existing repair branch or PR prevents duplicates, including failed drafts. Completed Ticket, Spec and Base CI Deliveries record their exact agent-authored or reviewed heads for later Fix Self-merge. Merge and email flags and User config apply; Self-merge also closes the Base branch's CI-red reports and Base fix issues.

    diff --git a/src/architect.rs b/src/architect.rs index e866f64b8..e16b26aea 100644 --- a/src/architect.rs +++ b/src/architect.rs @@ -308,12 +308,6 @@ pub fn run( config: &UserConfig, harness: &mut Choice, ) -> Outcome { - if flags.self_merge_check == Some(true) - && let Err(error) = - launch::repo().and_then(|repo| flags.validate_merge_check(&repo, config)) - { - return failed(error.into()); - } let started = Utc::now(); let Launch { directory, diff --git a/src/args.rs b/src/args.rs index e8abf86ab..91b5cc584 100644 --- a/src/args.rs +++ b/src/args.rs @@ -1613,12 +1613,11 @@ fn take_self_merge_check_flag(flag: &mut Option, arg: &str) -> Result false, _ => return Ok(false), }; - ask_once( - flag, - enabled, - arg, - "self-merge-check and no-self-merge-check", - )?; + match *flag { + None => *flag = Some(enabled), + Some(given) if given == enabled => bail!("repeated argument: {arg}"), + Some(_) => bail!("self-merge-check and no-self-merge-check can't be used together"), + } Ok(true) } diff --git a/src/asks.rs b/src/asks.rs index 4cb9d5afd..80ca74fcc 100644 --- a/src/asks.rs +++ b/src/asks.rs @@ -225,15 +225,35 @@ impl Flags { repo: &crate::issue::Repo, config: &UserConfig, ) -> anyhow::Result<()> { - anyhow::ensure!( - self.self_merge_check != Some(true) || self.merge_check_for(repo, config).is_some(), - "self-merge-check requires merge.self_merge_check for {}", - repo.slug(), - ); + if self.self_merge_check == Some(true) && self.merge_check_for(repo, config).is_none() { + return Err(MissingSelfMergeCheck(repo.slug()).into()); + } + Ok(()) + } + + pub(crate) fn validate_launch_merge_check(&self, config: &UserConfig) -> anyhow::Result<()> { + if self.self_merge_check == Some(true) { + self.validate_merge_check(&crate::launch::repo()?, config)?; + } Ok(()) } } +#[derive(Debug)] +pub(crate) struct MissingSelfMergeCheck(String); + +impl std::fmt::Display for MissingSelfMergeCheck { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "self-merge-check requires merge.self_merge_check for {}", + self.0 + ) + } +} + +impl std::error::Error for MissingSelfMergeCheck {} + impl Flags { /// Whether a Run with these flags runs a Security review: as /// `security-review` or `no-security-review` asked, else as `config` diff --git a/src/command.rs b/src/command.rs index 28666b0e0..fceb28258 100644 --- a/src/command.rs +++ b/src/command.rs @@ -16,6 +16,7 @@ use std::process::ExitCode; use std::time::Instant; use crate::architect::{self, Reviewed}; +use crate::asks::{Flags, MissingSelfMergeCheck}; use crate::config::UserConfig; use crate::failed_run::FailedRun; use crate::harness::Choice; @@ -108,12 +109,39 @@ pub fn start( begin: Begin, ask: impl FnOnce(&UserConfig) -> NotificationAsk, about: About, +) -> Result<(UserConfig, Started), ExitCode> { + start_with_merge_check(begin, ask, about, None) +} + +/// Validate an explicitly required Self-merge check before announcing work +/// or gathering the Run notification's GitHub context. +pub fn start_with_merge_check( + begin: Begin, + ask: impl FnOnce(&UserConfig) -> NotificationAsk, + about: About, + flags: Option<&Flags>, ) -> Result<(UserConfig, Started), ExitCode> { let started = (!matches!(begin, Begin::ChildRun(..))).then(Instant::now); + let preflight_config = + if let Some(flags) = flags.filter(|flags| flags.self_merge_check == Some(true)) { + let config = UserConfig::load().map_err(|error| failure(&error))?; + if let About::Issue(issue) = &about { + flags.validate_merge_check(&issue.repo(), &config) + } else { + flags.validate_launch_merge_check(&config) + } + .map_err(|error| failure(&error))?; + Some(config) + } else { + None + }; logs::begin(begin); - let config = setup::offer() - .and_then(|()| UserConfig::load()) - .map_err(|error| failure(&error))?; + let config = match preflight_config { + Some(config) => config, + None => setup::offer() + .and_then(|()| UserConfig::load()) + .map_err(|error| failure(&error))?, + }; logs::configured(&config); // First, so no interrupt can end the command once its notification is // checked. @@ -229,6 +257,9 @@ impl Started { /// what to do when the host running out of disk space caused it, and the exit /// code of a failure. pub fn failure(error: &anyhow::Error) -> ExitCode { + if let Some(error) = error.downcast_ref::() { + return crate::argument_error(format_args!("{error}")); + } logs::show_held(); progress::step(format_args!("{error:#}")); if crate::failed_run::out_of_disk(error) { diff --git a/src/fix.rs b/src/fix.rs index 6924082bc..5200833e7 100644 --- a/src/fix.rs +++ b/src/fix.rs @@ -41,11 +41,6 @@ pub(crate) fn run( started: &mut crate::command::Started, ) -> crate::command::Ending { let result = (|| -> anyhow::Result<_> { - if command.flags.self_merge_check == Some(true) { - command - .flags - .validate_merge_check(&crate::launch::repo()?, config)?; - } if let Target::Pass { base, author } = &command.target { let launch = match crate::launch::start( base.as_deref(), @@ -83,8 +78,9 @@ pub(crate) fn run( author.as_deref(), behind, sign_off_hold, - config - .self_merge_check(&launch.repo) + command + .flags + .merge_check_for(&launch.repo, config) .map(|_| config.logs_dir.as_path()), &mut passed_over, )? { diff --git a/src/main.rs b/src/main.rs index c37b1c801..6f12b7a2c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -553,15 +553,15 @@ fn main() -> ExitCode { None => Asks::of_run(&issue, &flags, config), }; let ask = |config: &UserConfig| asks_of(config).notification; - let (config, mut started) = match command::start(begin, ask, About::Issue(&issue)) { + let (config, mut started) = match command::start_with_merge_check( + begin, + ask, + About::Issue(&issue), + given.is_none().then_some(&flags), + ) { Ok(started) => started, Err(failure) => return failure, }; - if given.is_none() - && let Err(error) = flags.validate_merge_check(&issue.repo(), &config) - { - return argument_error(format_args!("{error}")); - } let mut asks = asks_of(&config); let authors = config.implementation_authors(&issue.repo(), &flags.trust_authors); let started_by = given @@ -581,12 +581,13 @@ fn main() -> ExitCode { #[cfg(target_os = "linux")] fn fix(args: args::FixArgs) -> ExitCode { - let (config, mut started) = match command::start( + let (config, mut started) = match command::start_with_merge_check( Begin::FixRun { pass: matches!(args.target, fix::Target::Pass { .. }), }, |config| args.flags.notification(config), About::FixRun, + Some(&args.flags), ) { Ok(started) => started, Err(failure) => return failure, @@ -622,8 +623,12 @@ fn fix(args: args::FixArgs) -> ExitCode { #[cfg(target_os = "linux")] fn architect(args: ArchitectArgs) -> ExitCode { let ask = |config: &UserConfig| args.flags.notification(config); - let (config, mut started) = match command::start(Begin::ArchitectRun, ask, About::ArchitectRun) - { + let (config, mut started) = match command::start_with_merge_check( + Begin::ArchitectRun, + ask, + About::ArchitectRun, + Some(&args.flags), + ) { Ok(started) => started, Err(failure) => return failure, }; @@ -776,7 +781,12 @@ fn triage(args: args::TriageArgs) -> ExitCode { #[cfg(target_os = "linux")] fn pickup(args: PassArgs) -> ExitCode { let ask = |config: &UserConfig| args.flags.notification(config); - let (config, mut started) = match command::start(Begin::PickupRun, ask, About::PickupRun) { + let (config, mut started) = match command::start_with_merge_check( + Begin::PickupRun, + ask, + About::PickupRun, + Some(&args.flags), + ) { Ok(started) => started, Err(failure) => return failure, }; @@ -809,10 +819,11 @@ fn pickup(args: PassArgs) -> ExitCode { /// A Security run, with one notification when asked, unless skipped. #[cfg(target_os = "linux")] fn secure(args: PassArgs) -> ExitCode { - let (config, mut started) = match command::start( + let (config, mut started) = match command::start_with_merge_check( Begin::SecurityRun, |config| args.flags.notification(config), About::SecurityRun, + Some(&args.flags), ) { Ok(started) => started, Err(failure) => return failure, diff --git a/src/pickup.rs b/src/pickup.rs index bb9653602..ebc73aeb5 100644 --- a/src/pickup.rs +++ b/src/pickup.rs @@ -153,9 +153,6 @@ pub fn run( order: PickupOrder, skip_authors: &crate::skip_authors::SkipAuthors, ) -> Result { - if flags.self_merge_check == Some(true) { - flags.validate_merge_check(&launch::repo()?, config)?; - } let Launch { directory, repo, diff --git a/src/processes.rs b/src/processes.rs index affd29564..7cc0ff3fc 100644 --- a/src/processes.rs +++ b/src/processes.rs @@ -647,6 +647,14 @@ fn run(command: &ProcessRun) -> Result { let name = &command.name; interrupt::install()?; let config = UserConfig::load()?; + let run_flags = Flags { + security_fix: command.security_fix, + security_close: command.security_close, + security_review: command.security_review, + self_merge_check: command.self_merge_check, + ..Flags::default() + }; + run_flags.validate_launch_merge_check(&config)?; // The same check as a Ticket run, before any worktree or Step: a missing // address or Resend key fails the Process before it starts. As for the // other Passes, the check is before a skip, so a Process that would be @@ -680,18 +688,8 @@ fn run(command: &ProcessRun) -> Result { file.goal = goal; file.dispatched_goal = command.goal.or((goal == Goal::Merged).then_some(goal)); file.plan_only = command.plan_only; - file.security_review = Flags { - security_review: command.security_review, - ..Flags::default() - } - .security_review(&config); - file.run_flags = Flags { - security_fix: command.security_fix, - security_close: command.security_close, - security_review: command.security_review, - self_merge_check: command.self_merge_check, - ..Flags::default() - }; + file.security_review = run_flags.security_review(&config); + file.run_flags = run_flags; file.security_fix = file.run_flags.security_fix_allowed(&config); // Before any worktree: a foreign Issue URL is an origin mismatch, and a // number that cannot be resolved stops the same way. An Issue-branch @@ -702,15 +700,6 @@ fn run(command: &ProcessRun) -> Result { Ok(issue) => issue, Err(error) => return Err(failed_before_steps(notification, error)), }; - if command.self_merge_check == Some(true) { - let validation = issue - .as_ref() - .map_or_else(launch::repo, |issue| Ok(issue.repo())) - .and_then(|repo| file.run_flags.validate_merge_check(&repo, &config)); - if let Err(error) = validation { - return Err(failed_before_steps(notification, error)); - } - } if let Some(issue) = &issue { // Issue validation, branch selection and Claim creation all use // GitHub before the first Step. They share the Command's wait budget diff --git a/src/processes/review.rs b/src/processes/review.rs index 0158983df..73127f3a5 100644 --- a/src/processes/review.rs +++ b/src/processes/review.rs @@ -20,13 +20,13 @@ pub(crate) fn run(command: ReviewArgs) -> Result { crate::review::Target::Author(author) => { interrupt::install()?; let config = UserConfig::load()?; - logs::begin(Begin::ReviewRun { pass: true }); - logs::configured(&config); let launch = Git::new(std::env::current_dir()?); let repo = crate::issue::Repo::of_origin(&launch.run(&["config", "remote.origin.url"])?) .context("review --author needs a GitHub origin")?; command.flags.validate_merge_check(&repo, &config)?; + logs::begin(Begin::ReviewRun { pass: true }); + logs::configured(&config); logs::pass_fired(&repo); let skip = |reason: &dyn std::fmt::Display| { logs::skipped(logs::Pass::Review, &repo, reason); diff --git a/src/security.rs b/src/security.rs index 1ff9cbf4f..a93dc1bd8 100644 --- a/src/security.rs +++ b/src/security.rs @@ -172,12 +172,6 @@ pub fn run( config: &UserConfig, harness: &mut Choice, ) -> Outcome { - if flags.self_merge_check == Some(true) - && let Err(error) = - launch::repo().and_then(|repo| flags.validate_merge_check(&repo, config)) - { - return Outcome::Audited(error.into()); - } let offer_command = (flags.security_fix.is_none() && config.security_fix.is_none()) .then(|| crate::args::retry_with_security_fix(base, flags)); let Launch { diff --git a/tests/command_surface.rs b/tests/command_surface.rs index d078b1e68..4c0e7c67b 100644 --- a/tests/command_surface.rs +++ b/tests/command_surface.rs @@ -110,6 +110,39 @@ fn help_explains_both_self_merge_check_overrides() { ); } +#[test] +fn requiring_a_missing_self_merge_check_is_a_usage_error_before_work() { + let scenario = Scenario::new(); + let issue = scenario.issue_url(7); + let pull_request = "https://github.com/acme/widgets/pull/7"; + + for args in [ + vec![issue.as_str(), "self-merge-check"], + vec!["pickup", "--self-merge-check"], + vec!["architect", "self-merge-check"], + vec!["secure", "self-merge-check"], + vec!["fix", "self-merge-check"], + vec!["fix", "7", "self-merge-check"], + vec!["review", "--author", "colleague", "self-merge-check"], + vec!["review", pull_request, "self-merge-check"], + vec!["process", "ticket-run", "issue", "7", "self-merge-check"], + vec!["process", "ticket-run", "self-merge-check"], + ] { + let result = scenario.run(&args); + + assert_argument_error( + &scenario, + &result, + "self-merge-check requires merge.self_merge_check for acme/widgets", + ); + assert!(scenario.gh_calls().is_empty(), "{args:?} contacted GitHub"); + assert!( + scenario.claude_calls().is_empty(), + "{args:?} started a session" + ); + } +} + #[test] fn help_is_a_compact_reference_with_a_link_to_the_details() { let scenario = Scenario::new(); @@ -239,6 +272,18 @@ fn pickup_with_arguments_it_cant_use_prints_an_error_and_the_help_to_stderr() { vec!["pickup", "merge", "no-merge"], "merge and no-merge can't be used together", ), + ( + vec!["pickup", "self-merge-check", "--self-merge-check"], + "repeated argument: --self-merge-check", + ), + ( + vec!["pickup", "no-self-merge-check", "--no-self-merge-check"], + "repeated argument: --no-self-merge-check", + ), + ( + vec!["pickup", "no-self-merge-check", "--self-merge-check"], + "self-merge-check and no-self-merge-check can't be used together", + ), ( vec!["pickup", "base-fix", "--no-base-fix"], "base-fix and no-base-fix can't be used together", diff --git a/tests/fix_pass.rs b/tests/fix_pass.rs index d00563b64..fa0bb6357 100644 --- a/tests/fix_pass.rs +++ b/tests/fix_pass.rs @@ -183,6 +183,46 @@ esac assert_eq!(scenario.claude_calls().len(), 2); } +#[test] +fn a_fix_pass_can_self_merge_after_a_previous_self_merge_check_hold() { + let scenario = Scenario::new(); + let check = scenario.path("hold-check"); + support::write_executable(&check, "#!/bin/sh\necho Day shift decides\nexit 1\n"); + scenario.user_config_is(&format!( + "[merge]\nalways = true\nself_merge_check = {{ \"acme/widgets\" = {:?} }}\n", + check.to_str().unwrap() + )); + scenario.agent_does( + "echo feature > feature.txt; git add feature.txt; git commit -qm 'Add feature'", + ); + let held = scenario.run(&[&scenario.issue_url(7)]); + assert_eq!(held.code, Some(0), "{}", held.stderr); + assert!(held.stderr.contains("Day shift decides"), "{}", held.stderr); + advance_base(&scenario, 2); + let head = scenario.origin_git(&["rev-parse", "issue-7"]); + let base = scenario.origin_git(&["rev-parse", "main"]); + let mut state = scenario.gh_state(); + record_behind(&mut state, head.trim(), base.trim(), 2); + scenario.write_gh_state(&state); + + let result = scenario.run(&[ + "fix", + "behind", + "2", + "no-self-merge-check", + "no-base-fix", + "no-email", + ]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert_eq!( + scenario.gh_state()["prs"][0]["state"], + "MERGED", + "{}", + result.stderr + ); +} + #[test] fn pass_skips_a_sign_off_hold_and_repairs_the_next_pull_request() { let scenario = Scenario::new(); diff --git a/tests/spec_run.rs b/tests/spec_run.rs index 88e3c253d..b3f8f4e51 100644 --- a/tests/spec_run.rs +++ b/tests/spec_run.rs @@ -1386,8 +1386,15 @@ fn a_spec_pr_whose_red_check_also_fails_on_the_base_branch_commit_gets_no_repair } #[test] -fn with_base_fix_the_spec_prs_inherited_failure_gets_a_base_fix_into_the_base_branch() { +fn a_specs_base_fix_inherits_the_command_to_skip_the_self_merge_check() { let scenario = linear_spec(); + scenario.origin_has_commit( + "main", + "check", + "#!/bin/sh\necho Base fix needs sign-off\nexit 1\n", + "Add Self-merge check", + ); + scenario.user_config_is("[merge]\nself_merge_check = { \"acme/widgets\" = \"check\" }\n"); scenario.agent_does_for( SPEC, &format!("{}{}", checks_on_head(RED), checks_on_origin("main", RED)), @@ -1406,7 +1413,7 @@ gh pr create --base main --head issue-24 --title "Fix CI on main" --body "Closes ), ); - let result = scenario.run(&[&spec_url(&scenario), "base-fix"]); + let result = scenario.run(&[&spec_url(&scenario), "base-fix", "no-self-merge-check"]); assert_eq!(result.code, Some(0), "stderr: {}", result.stderr); assert_contains( From 3b3bda4440c127cdcd52a5991c8cad96ce9cbf8d Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Fri, 4 Dec 2026 12:10:59 -0500 Subject: [PATCH 13/27] Address Self-merge check review findings (#2426) --- site/how-it-works/index.html | 2 +- tests/process/spec_run.rs | 11 ++++++----- tests/spec_run.rs | 31 +++++++++++++++++++++++++++++-- 3 files changed, 36 insertions(+), 8 deletions(-) diff --git a/site/how-it-works/index.html b/site/how-it-works/index.html index 080bab316..213d4d5fe 100644 --- a/site/how-it-works/index.html +++ b/site/how-it-works/index.html @@ -259,7 +259,7 @@

    How thirdshift works

  • Spec PR → Base branchOne combined pull request for you to review, or to merge when requested
  • -

    Each Ticket gets a Ticket run that Self-merges into the Spec branch. The configured Self-merge check runs only on the Spec PR, when it is ready to Self-merge into the Base branch. Child Ticket runs verify any rendered UI changes locally in their Worktree without calling gh or uploading attachments, while the combined Spec review captures and attaches unified Before and After Visual evidence when writing the Spec PR body. A Ticket closing means its work landed on the Spec branch; the whole Spec has not shipped yet.

    +

    Each Ticket Self-merges into the Spec branch and skips the Self-merge check. A configured check runs before the Spec PR Self-merges into the Base branch. A Base fix into the Base branch also runs the check. Child Ticket runs verify any rendered UI changes locally in their Worktree without calling gh or uploading attachments, while the combined Spec review captures and attaches unified Before and After Visual evidence when writing the Spec PR body. A Ticket closing means its work landed on the Spec branch; the whole Spec has not shipped yet.

    A failed Ticket stops only its dependents; other reachable Tickets can still run. Tickets marked for human work or triage also hold their dependents. An incomplete Spec leaves a draft Spec PR with a Tickets checklist. A Spec run that is only waiting, with no failed or interrupted Ticket and every undone Ticket gated, blocked behind gated Tickets or outside work, or outside the Spec's repository, puts ready-for-agent back on its Spec instead of agent-failed, unless someone other than a Trusted account or the Spec's authorized author edited it since its last Trusted labelling, which leaves needs-triage, and comments on the Spec naming each undone Ticket and what it waits on. Pickup continues it once a Ticket can start; a blocking cycle is a failure. A handed-back Spec with every Ticket closed can also be taken when its latest Spec branch is on origin, with no PR or an open PR: it goes straight to Spec review and Delivery without running a Ticket again. Its usual Ready issue gates still apply; Architect gives it priority even while it settles. A Spec PR closed, merged or retargeted mid-run starts no further Ticket, holds the Self-merge of a running Ticket started after it opened, and ends the Spec run without a Recovery command. An Unready Ticket's checklist and Command log line name its open blockers, marking those outside the Spec and those labelled ready-for-agent; outside blockers are reported but never run. Rerunning continues existing branches. Spec run controls and limits.

    diff --git a/tests/process/spec_run.rs b/tests/process/spec_run.rs index dad6f18ab..dc986a61c 100644 --- a/tests/process/spec_run.rs +++ b/tests/process/spec_run.rs @@ -26,14 +26,15 @@ fn the_built_in_spec_run_checks_its_final_self_merge_only() { scenario.agent_does_for(8, &agent_lands_ticket(8, "issue-7")); scenario.agent_does_for(9, &agent_lands_ticket(9, "issue-7")); scenario.agent_does_for(7, "true"); - let calls = scenario.path("check-calls"); + let calls = scenario.path("home/check-calls"); scenario.origin_has_commit( "main", "check", - &format!( - "#!/bin/sh\nprintf '%s %s\\n' \"$PR_NUMBER\" \"$BASE_BRANCH\" >> '{}'\necho built-in spec hold\nexit 1\n", - calls.display() - ), + r#"#!/bin/sh +printf '%s %s\n' "$PR_NUMBER" "$BASE_BRANCH" >> "$HOME/check-calls" +echo built-in spec hold +exit 1 +"#, "Add check", ); scenario.user_config_is("[merge]\nself_merge_check = { \"acme/widgets\" = \"check\" }\n"); diff --git a/tests/spec_run.rs b/tests/spec_run.rs index 88e3c253d..bb1c368d4 100644 --- a/tests/spec_run.rs +++ b/tests/spec_run.rs @@ -1385,8 +1385,7 @@ fn a_spec_pr_whose_red_check_also_fails_on_the_base_branch_commit_gets_no_repair assert_eq!(spec["isDraft"], true); } -#[test] -fn with_base_fix_the_spec_prs_inherited_failure_gets_a_base_fix_into_the_base_branch() { +fn spec_with_a_base_fix_for_inherited_ci() -> Scenario { let scenario = linear_spec(); scenario.agent_does_for( SPEC, @@ -1405,7 +1404,12 @@ gh pr create --base main --head issue-24 --title "Fix CI on main" --body "Closes checks_on_head(GREEN) ), ); + scenario +} +#[test] +fn with_base_fix_the_spec_prs_inherited_failure_gets_a_base_fix_into_the_base_branch() { + let scenario = spec_with_a_base_fix_for_inherited_ci(); let result = scenario.run(&[&spec_url(&scenario), "base-fix"]); assert_eq!(result.code, Some(0), "stderr: {}", result.stderr); @@ -1424,6 +1428,29 @@ gh pr create --base main --head issue-24 --title "Fix CI on main" --body "Closes assert!(scenario.origin_file("issue-20", "ci-fix.txt").is_some()); } +#[test] +fn a_specs_base_fix_into_the_base_branch_obeys_the_self_merge_check() { + let scenario = spec_with_a_base_fix_for_inherited_ci(); + scenario.origin_has_commit( + "main", + "check", + "#!/bin/sh\necho Spec Base fix hold\nexit 1\n", + "Add check", + ); + scenario.user_config_is("[merge]\nself_merge_check = { \"acme/widgets\" = \"check\" }\n"); + + let result = scenario.run(&["merge", &spec_url(&scenario), "base-fix"]); + + assert_eq!(result.code, Some(1), "{}", result.stderr); + assert_contains(&result.stderr, "Self-merge check held: Spec Base fix hold"); + let fix = pr_from(&scenario, "issue-24").expect("the Base fix's PR"); + assert_eq!(fix["base"], "main"); + assert_eq!(fix["state"], "OPEN", "{}", result.stderr); + assert_eq!(fix["isDraft"], false); + assert_eq!(spec_pr(&scenario)["state"], "OPEN"); + assert!(scenario.origin_file("main", "ci-fix.txt").is_none()); +} + /// The agent for Ticket `ticket` lands `file` with `test` red on its head /// and on the Spec branch: an Inherited failure. fn agent_lands_with_an_inherited_failure(ticket: u32, file: &str) -> String { From 6a7fcdd7d7ad69c6dd88cdbea0563fc484e6eaec Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Fri, 4 Dec 2026 12:14:02 -0500 Subject: [PATCH 14/27] Preserve required checks through Custom Process dispatch --- src/args.rs | 27 +++++++++++-------------- src/asks.rs | 44 +++++++++++++++++++++++++++++------------ src/command.rs | 23 +++++++++++---------- src/processes.rs | 13 +++++++++++- src/processes/review.rs | 7 ++++--- src/processes/ticket.rs | 2 +- tests/fix_pass.rs | 30 +++++++++------------------- tests/process.rs | 40 +++++++++++++++++++++++++++++++++++++ 8 files changed, 119 insertions(+), 67 deletions(-) diff --git a/src/args.rs b/src/args.rs index 91b5cc584..9f863bfc5 100644 --- a/src/args.rs +++ b/src/args.rs @@ -8,7 +8,7 @@ use std::num::NonZeroUsize; use anyhow::{Context, Result, bail, ensure}; -use crate::asks::Flags; +use crate::asks::{Flags, SelfMergeCheckAsk}; use crate::base_fix::BaseFixAsk; use crate::child_run::{self, Given}; use crate::harness::{self, Harness}; @@ -50,7 +50,7 @@ pub struct ProcessRun { pub email: Option, /// `merge` or `no-merge`. Absent leaves the choice to the User config. pub goal: Option, - pub self_merge_check: Option, + pub self_merge_check: Option, /// Whether this Process's Security review Step is requested. pub security_review: Option, /// Whether Security finding Steps are allowed to fix findings. @@ -409,12 +409,11 @@ pub(crate) fn public_flag_words(flags: &Flags, words: &mut Vec) { Some(Goal::ReadyForReview) => words.push("--no-merge".into()), None => {} } - if let Some(enabled) = flags.self_merge_check { + if let Some(check) = flags.self_merge_check { words.push( - if enabled { - "--self-merge-check" - } else { - "--no-self-merge-check" + match check { + SelfMergeCheckAsk::Require => "--self-merge-check", + SelfMergeCheckAsk::Skip => "--no-self-merge-check", } .into(), ); @@ -1607,17 +1606,13 @@ fn take_merge_flag(goal: &mut Option, arg: &str) -> Result { Ok(true) } -fn take_self_merge_check_flag(flag: &mut Option, arg: &str) -> Result { - let enabled = match arg { - "self-merge-check" | "--self-merge-check" => true, - "no-self-merge-check" | "--no-self-merge-check" => false, +fn take_self_merge_check_flag(flag: &mut Option, arg: &str) -> Result { + let check = match arg { + "self-merge-check" | "--self-merge-check" => SelfMergeCheckAsk::Require, + "no-self-merge-check" | "--no-self-merge-check" => SelfMergeCheckAsk::Skip, _ => return Ok(false), }; - match *flag { - None => *flag = Some(enabled), - Some(given) if given == enabled => bail!("repeated argument: {arg}"), - Some(_) => bail!("self-merge-check and no-self-merge-check can't be used together"), - } + ask_once(flag, check, arg, "self-merge-check and no-self-merge-check")?; Ok(true) } diff --git a/src/asks.rs b/src/asks.rs index 80ca74fcc..0044bb2b4 100644 --- a/src/asks.rs +++ b/src/asks.rs @@ -14,13 +14,20 @@ use crate::issue::IssueUrl; use crate::notification::NotificationAsk; use crate::run::Goal; +/// An explicit Command choice about the repository's Self-merge check. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SelfMergeCheckAsk { + Require, + Skip, +} + /// The flags a Run and a Pass share, as the command /// gave them: each is none if the command said nothing about it. #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct Flags { /// The goal `merge` or `no-merge` asked for. pub goal: Option, - pub self_merge_check: Option, + pub self_merge_check: Option, /// What `email`, `email-unless-merged` or `no-email` asked for. pub email: Option, /// How many Tickets a Spec run runs at once, as `parallel ` gave it. @@ -47,7 +54,7 @@ pub struct Asks { pub trust_authors: Vec, pub sign_off_hold: Option, pub self_merge_check: Option, - pub self_merge_check_override: Option, + pub self_merge_check_override: Option, /// Whether it is a Merge run. pub goal: Goal, /// The logins that may supply a merge request when none was given. @@ -217,25 +224,36 @@ impl Flags { ) -> Option<&'a crate::self_merge_check::Check> { config .self_merge_check(repo) - .filter(|_| self.self_merge_check != Some(false)) + .filter(|_| self.self_merge_check != Some(SelfMergeCheckAsk::Skip)) + } + + pub(crate) fn requires_merge_check(&self) -> bool { + self.self_merge_check == Some(SelfMergeCheckAsk::Require) } - pub(crate) fn validate_merge_check( + pub(crate) fn required_merge_check<'a>( &self, repo: &crate::issue::Repo, - config: &UserConfig, - ) -> anyhow::Result<()> { - if self.self_merge_check == Some(true) && self.merge_check_for(repo, config).is_none() { - return Err(MissingSelfMergeCheck(repo.slug()).into()); + config: &'a UserConfig, + ) -> anyhow::Result> { + if !self.requires_merge_check() { + return Ok(None); } - Ok(()) + config + .self_merge_check(repo) + .map(Some) + .ok_or_else(|| MissingSelfMergeCheck(repo.slug()).into()) } - pub(crate) fn validate_launch_merge_check(&self, config: &UserConfig) -> anyhow::Result<()> { - if self.self_merge_check == Some(true) { - self.validate_merge_check(&crate::launch::repo()?, config)?; + pub(crate) fn required_launch_merge_check<'a>( + &self, + config: &'a UserConfig, + ) -> anyhow::Result> { + if self.requires_merge_check() { + self.required_merge_check(&crate::launch::repo()?, config) + } else { + Ok(None) } - Ok(()) } } diff --git a/src/command.rs b/src/command.rs index fceb28258..9fc92da63 100644 --- a/src/command.rs +++ b/src/command.rs @@ -122,19 +122,18 @@ pub fn start_with_merge_check( flags: Option<&Flags>, ) -> Result<(UserConfig, Started), ExitCode> { let started = (!matches!(begin, Begin::ChildRun(..))).then(Instant::now); - let preflight_config = - if let Some(flags) = flags.filter(|flags| flags.self_merge_check == Some(true)) { - let config = UserConfig::load().map_err(|error| failure(&error))?; - if let About::Issue(issue) = &about { - flags.validate_merge_check(&issue.repo(), &config) - } else { - flags.validate_launch_merge_check(&config) - } - .map_err(|error| failure(&error))?; - Some(config) + let preflight_config = if let Some(flags) = flags.filter(|flags| flags.requires_merge_check()) { + let config = UserConfig::load().map_err(|error| failure(&error))?; + if let About::Issue(issue) = &about { + flags.required_merge_check(&issue.repo(), &config) } else { - None - }; + flags.required_launch_merge_check(&config) + } + .map_err(|error| failure(&error))?; + Some(config) + } else { + None + }; logs::begin(begin); let config = match preflight_config { Some(config) => config, diff --git a/src/processes.rs b/src/processes.rs index 7cc0ff3fc..7f5d69ccc 100644 --- a/src/processes.rs +++ b/src/processes.rs @@ -99,6 +99,8 @@ struct ProcessFile { goal: Goal, /// The merge choice inherited by a published issue, if already decided. dispatched_goal: Option, + /// The Self-merge check explicitly required when this Command started. + required_merge_check: Option, security_review: bool, run_flags: Flags, security_fix: bool, @@ -441,6 +443,7 @@ struct Prepared { /// `Merged` only when this run was asked to Self-merge. goal: Goal, dispatched_goal: Option, + required_merge_check: Option, security_review: bool, run_flags: Flags, security_fix: bool, @@ -511,6 +514,7 @@ struct StepRun<'a> { security_fix: bool, goal: Goal, dispatched_goal: Option, + required_merge_check: Option<&'a crate::self_merge_check::Check>, limits: &'a Limits, completed: &'a Mutex, killed_work: &'a Mutex>>, @@ -554,6 +558,7 @@ impl Prepared { security_fix: self.security_fix, goal: self.goal, dispatched_goal: self.dispatched_goal, + required_merge_check: self.required_merge_check.as_ref(), limits: &self.limits, completed: &self.completed, killed_work: &self.killed_work, @@ -654,7 +659,7 @@ fn run(command: &ProcessRun) -> Result { self_merge_check: command.self_merge_check, ..Flags::default() }; - run_flags.validate_launch_merge_check(&config)?; + let required_merge_check = run_flags.required_launch_merge_check(&config)?.cloned(); // The same check as a Ticket run, before any worktree or Step: a missing // address or Resend key fails the Process before it starts. As for the // other Passes, the check is before a skip, so a Process that would be @@ -687,6 +692,7 @@ fn run(command: &ProcessRun) -> Result { } file.goal = goal; file.dispatched_goal = command.goal.or((goal == Goal::Merged).then_some(goal)); + file.required_merge_check = required_merge_check; file.plan_only = command.plan_only; file.security_review = run_flags.security_review(&config); file.run_flags = run_flags; @@ -1690,6 +1696,9 @@ fn run_published( ..Flags::default() }; let mut asks = Asks::of_run(&issue, &flags, &config); + if let Some(check) = run.required_merge_check { + asks.self_merge_check = Some(check.clone()); + } asks.delivery_limits = delivery::Limits { repair_cap: run.limits.repair_cap, protected_paths: run.limits.protected_paths.clone(), @@ -2111,6 +2120,7 @@ fn prepare_from( limits: file.limits, goal: file.goal, dispatched_goal: file.dispatched_goal, + required_merge_check: file.required_merge_check, security_review: file.security_review, run_flags: file.run_flags, security_fix: file.security_fix, @@ -2752,6 +2762,7 @@ fn parse(path: &Path, text: &str) -> Result { limits, goal: Goal::ReadyForReview, dispatched_goal: None, + required_merge_check: None, security_review: false, security_fix: false, plan_only: false, diff --git a/src/processes/review.rs b/src/processes/review.rs index 73127f3a5..d82a34c2f 100644 --- a/src/processes/review.rs +++ b/src/processes/review.rs @@ -24,7 +24,7 @@ pub(crate) fn run(command: ReviewArgs) -> Result { let repo = crate::issue::Repo::of_origin(&launch.run(&["config", "remote.origin.url"])?) .context("review --author needs a GitHub origin")?; - command.flags.validate_merge_check(&repo, &config)?; + command.flags.required_merge_check(&repo, &config)?; logs::begin(Begin::ReviewRun { pass: true }); logs::configured(&config); logs::pass_fired(&repo); @@ -180,8 +180,9 @@ impl ReviewProcess { pr.url ); let repo = pr.issue.repo(); - flags.validate_merge_check(&repo, &config)?; - let check = flags.merge_check_for(&repo, &config); + let check = flags + .required_merge_check(&repo, &config)? + .or_else(|| flags.merge_check_for(&repo, &config)); let mut command = CommandChoice::of(&flags.harness, &config); if checking { let snapshot = GitHub::new().review_pull_request(pr)?; diff --git a/src/processes/ticket.rs b/src/processes/ticket.rs index 23ad3f384..e908a7a9f 100644 --- a/src/processes/ticket.rs +++ b/src/processes/ticket.rs @@ -29,7 +29,7 @@ pub(crate) fn run_custom( file.security_review = delivery.security_review; file.security_fix = delivery.child_asks.security_fix; if delivery.child_asks.self_merge_check.is_none() { - file.run_flags.self_merge_check = Some(false); + file.run_flags.self_merge_check = Some(crate::asks::SelfMergeCheckAsk::Skip); } file.run_flags.security_fix = Some(if file.security_fix { crate::security::FixAsk::Allow diff --git a/tests/fix_pass.rs b/tests/fix_pass.rs index fa0bb6357..823a7b21b 100644 --- a/tests/fix_pass.rs +++ b/tests/fix_pass.rs @@ -125,25 +125,8 @@ exec "$delegate" "$@" #[test] fn fix_pass_skips_a_self_merge_check_hold_until_the_pr_has_red_ci() { - let scenario = Scenario::new(); - let check = scenario.path("hold-check"); - support::write_executable(&check, "#!/bin/sh\necho Day shift decides\nexit 1\n"); - scenario.user_config_is(&format!( - "[merge]\nalways = true\nself_merge_check = {{ \"acme/widgets\" = {:?} }}\n", - check.to_str().unwrap() - )); - scenario.agent_does( - "echo feature > feature.txt; git add feature.txt; git commit -qm 'Add feature'", - ); - let held = scenario.run(&[&scenario.issue_url(7)]); - assert_eq!(held.code, Some(0), "{}", held.stderr); - assert!(held.stderr.contains("Day shift decides"), "{}", held.stderr); - advance_base(&scenario, 2); + let scenario = pull_request_held_by_self_merge_check(); let head = scenario.origin_git(&["rev-parse", "issue-7"]); - let base = scenario.origin_git(&["rev-parse", "main"]); - let mut state = scenario.gh_state(); - record_behind(&mut state, head.trim(), base.trim(), 2); - scenario.write_gh_state(&state); scenario.agent_does(REPAIR_CI); let skipped = fix_pass(&scenario, &["behind", "2"]); @@ -157,7 +140,7 @@ fn fix_pass_skips_a_self_merge_check_hold_until_the_pr_has_red_ci() { assert_eq!(scenario.origin_git(&["rev-parse", "issue-7"]), head); assert_eq!(scenario.claude_calls().len(), 1); - state = scenario.gh_state(); + let mut state = scenario.gh_state(); state["checks"][head.trim()] = json!([{"name": "test", "conclusion": "failure"}]); state["on_ci_read"] = json!({ "times": 20, @@ -183,8 +166,7 @@ esac assert_eq!(scenario.claude_calls().len(), 2); } -#[test] -fn a_fix_pass_can_self_merge_after_a_previous_self_merge_check_hold() { +fn pull_request_held_by_self_merge_check() -> Scenario { let scenario = Scenario::new(); let check = scenario.path("hold-check"); support::write_executable(&check, "#!/bin/sh\necho Day shift decides\nexit 1\n"); @@ -204,6 +186,12 @@ fn a_fix_pass_can_self_merge_after_a_previous_self_merge_check_hold() { let mut state = scenario.gh_state(); record_behind(&mut state, head.trim(), base.trim(), 2); scenario.write_gh_state(&state); + scenario +} + +#[test] +fn a_fix_pass_can_self_merge_after_a_previous_self_merge_check_hold() { + let scenario = pull_request_held_by_self_merge_check(); let result = scenario.run(&[ "fix", diff --git a/tests/process.rs b/tests/process.rs index 4002b3adc..62b775062 100644 --- a/tests/process.rs +++ b/tests/process.rs @@ -4521,6 +4521,46 @@ printf '%s\\n' \"$url\" > \"$FAKE_CLAUDE_FINAL_MESSAGE\" } } +#[test] +fn a_pass_dispatch_preserves_its_explicit_check_if_config_changes() { + let scenario = Scenario::new(); + scenario.origin_has_commit( + "main", + "check", + "#!/bin/sh\necho original check held the merge\nexit 1\n", + "Add check", + ); + let config = + scenario.user_config_is("[merge]\nself_merge_check = { \"acme/widgets\" = \"check\" }\n"); + write_process(&scenario, "publish", PUBLISH_THEN_RUN); + scenario.agent_does_in_session( + 1, + &format!( + r#" +printf '[merge]\n' > '{}' +url=$(gh issue create --title Ticket --body 'Do the thing') +printf '%s\n' "$url" > "$FAKE_CLAUDE_FINAL_MESSAGE" +"#, + config.display() + ), + ); + scenario.agent_does_for(8, &agent_lands_ticket(8, "main")); + + let result = scenario.run(&["process", "publish", "merge", "self-merge-check"]); + + assert_eq!( + pr_from(&scenario, "issue-8")["state"], + "OPEN", + "{}", + result.stderr + ); + assert!( + result.stderr.contains("original check held the merge"), + "{}", + result.stderr + ); +} + fn agent_lands_ticket(issue: u32, base: &str) -> String { format!( r#" From e5c66ac5149a1ad307e24844da7938bf961765a9 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Fri, 4 Dec 2026 12:16:33 -0500 Subject: [PATCH 15/27] Keep starting PR bodies across Pickup and opening sessions --- docs/guide.md | 1 + site/docs/index.html | 3 +- src/branch.rs | 125 +++++++++++++++++++++++------------- src/github.rs | 54 +++++++++++++++- src/pass.rs | 13 ++-- src/pickup.rs | 2 + src/pull_request.rs | 86 ++++++++++++++++--------- src/ready.rs | 27 ++++++-- src/run.rs | 14 ++++- tests/fakes/gh.rs | 41 ++++++++++++ tests/self_merge_check.rs | 129 ++++++++++++++++++++++++++++++++++++++ 11 files changed, 407 insertions(+), 88 deletions(-) diff --git a/docs/guide.md b/docs/guide.md index 55308b9a1..d885aa937 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -2941,6 +2941,7 @@ Both forms run from Command scratch with `PR_NUMBER`, `REPOSITORY` A Repair can change `PR_BODY` while `PR_BODY_AT_START` keeps the starting text. The repository's check can allow a declaration where the starting body had none and hold a Repair that changes an existing declaration. +If the starting body is unavailable, the Run leaves the PR ready for review. Exit `0` allows Self-merge. Any other exit, a missing or unstartable executable, or a one-minute timeout leaves the pull request ready for review. The first diff --git a/site/docs/index.html b/site/docs/index.html index 3eff49297..71b514692 100644 --- a/site/docs/index.html +++ b/site/docs/index.html @@ -2908,7 +2908,8 @@

    A Repair can change PR_BODY while PR_BODY_AT_START keeps the starting text. The repository's check can allow a declaration where the starting body had -none and hold a Repair that changes an existing declaration.

    +none and hold a Repair that changes an existing declaration. +If the starting body is unavailable, the Run leaves the PR ready for review.

    Exit 0 allows Self-merge. Any other exit, a missing or unstartable executable, or a one-minute timeout leaves the pull request ready for review. The first nonempty stdout line, trimmed and capped at 240 characters, becomes the diff --git a/src/branch.rs b/src/branch.rs index 93305fc2d..b9ebf4c8e 100644 --- a/src/branch.rs +++ b/src/branch.rs @@ -1,6 +1,8 @@ //! Issue branch selection: start a fresh Issue branch, or continue the one //! already on origin (ADR-0002). +use std::collections::BTreeMap; + use anyhow::{Result, bail}; use crate::git::Git; @@ -8,6 +10,8 @@ use crate::github::{GitHub, PrState, PullRequest}; use crate::issue::IssueUrl; use crate::worktree; +pub(crate) type FirstPrBodies = BTreeMap; + pub enum Selection { /// No Issue branch has been used yet, or the highest-numbered one's PR is /// merged or closed: start `branch` from the Base branch. @@ -16,6 +20,7 @@ pub enum Selection { Continuation { branch: String, pr: Option, + first_bodies: FirstPrBodies, }, } @@ -26,6 +31,14 @@ impl Selection { } } + pub(crate) fn retain_earlier_bodies(&mut self, earlier: &FirstPrBodies) { + if let Self::Continuation { first_bodies, .. } = self { + for (number, body) in earlier { + first_bodies.insert(*number, body.clone()); + } + } + } + /// The open PR's base in a Continuation that has one, which names the /// Base branch whatever else would. `given` is the Base branch the Run was /// given by what started it, if any, and `checked_out` the branch @@ -41,6 +54,7 @@ impl Selection { let Selection::Continuation { branch, pr: Some(pr), + .. } = self else { return None; @@ -94,15 +108,9 @@ pub fn started(launch: &Git, github: &GitHub, issue: &IssueUrl) -> Result

    Pickup has no Built-in process file. It selects and reserves the Ready issue, then starts ticket-run or spec-run as a command on that Issue URL would.

    +

    Pickup passes over an open pull request whose latest local Run ended at a Self-merge check hold, even if the issue has been handed back. It prints the hold reason and looks for the next Ready issue.

    Which end of the issue numbers the pass takes is its order: lowest-first by default, highest-first with pickup.order = "highest-first" in the User config, or for one pass with lowest-first or highest-first on the command, which wins over the User config. Two schedules working through the same queue from opposite ends, one with each order, collide less often; the reservation below still protects either choice.

    Add skip-author <login> (or --skip-author <login>) on each cron line to pass over issues written by that account, even a Trusted account. Repeat it for several accounts; logins match case-insensitively. The Pass logs #947 passed over: written by alice, whom this Pass skips and searches for the next Ready issue. A skipped Spec author excludes the whole Spec. A Spec run dispatched by this Pass also stops before a Ticket written by a skipped account, with the same failure handling as an untrusted Ticket author. These choices belong to this Pass, with no User config setting; explicitly running thirdshift <Issue URL> still runs the named issue under the usual trust checks. The word never makes an untrusted author eligible.

    Pickup uses trust.authors for its repository. Add diff --git a/site/how-it-works/index.html b/site/how-it-works/index.html index 213d4d5fe..7dba307ee 100644 --- a/site/how-it-works/index.html +++ b/site/how-it-works/index.html @@ -317,6 +317,7 @@

    How thirdshift works

    Eligible work ↓ Ticket run or Spec run ↓ reviewed pull request

    +

    Pickup passes over an open pull request whose latest local Run ended at a Self-merge check hold, even if the issue has been handed back. It prints the hold reason and looks for the next Ready issue.

    Pickup respects issue readiness, open blockers and the Failure limit: it takes nothing while three open issues, or pickup.failure_limit, carry agent-failed from a failed run, and pull requests waiting for review never count. A run that failed because the host ran out of disk space is no failure of its issue: it puts ready-for-agent back without agent-failed, even with work on origin, and says to free disk space. A Paused Command, which no route had Plan usage left for, is none either: it puts ready-for-agent back the same way, unless an untrusted edit leaves needs-triage or it is a Security fix. Any other failed run with work on origin, or a failed Security fix, swaps in-progress for agent-failed and, unless it is a Security fix, posts its Recovery on the issue as a generated comment without local paths or the continue command; putting ready-for-agent back, taking agent-failed off or closing the issue ends the failure, and the Sweep takes in-progress off any open issue that still carries both. Before choosing work, it re-runs failed jobs of the Base branch's latest push CI once, immediately. Green on re-run files a Flaky-test Ticket using the recorded failure as evidence, without requiring reproduction on demand. Red again files an ordinary bug Ticket after 30 minutes from the re-run's completion. Its title, body and later comments leave job names and log lines out, and it waits until you write the task and apply ready-for-agent. An open CI-red Ticket in needs-info does not block a new report; another open CI-red Ticket receives new failing commits as comments. CI read failures warn and let Pickup continue; red Base CI does not hold Self-merges. Architect and Security runs yield to ready human-shaped work. Gates can skip a pass without failure, and unresolved plans, ideas or findings can leave the next decision with the Day shift. This is scheduled CLI work on your machine, using your authenticated tools.

    When a Security run fails before its audit starts, its requested Run notification names a fixed Cause for Base branch preparation failures, such as Base branch not found, and points to stderr on the host at the command's start time for diagnostics. Security run notifications.

    Before dispatch, Pickup reserves its selected issue on origin and checks that it is still Ready. Competing Pickup runs on two machines cannot take the same issue: only the reservation's owner can dispatch it, and the other moves on to the next Ready issue in its order. An Architect run takes the same reservation for the plan it dispatches, and a Security run for its fix, before marking it ready, so a Pickup run beside either never takes it. The reservation's commit message records its host, launch path, process and start time. Before choosing work, every scheduled Pass releases its own orphaned origin reservations only on local proof of death: a missing PID, a process started after the reservation, or a host boot after it. Failed probes count as alive, and an exact observed-SHA lease protects a new owner. Stderr and Activity record the release. A reservation no host can test that blocked work and has been held over a day appears in Needs you with owner, age, blocked work and a release command. The Day shift confirms death before releasing it by hand; no reservation expires on a timer. Pickup's reservation and readiness checks.

    diff --git a/src/branch.rs b/src/branch.rs index d78a7ab7d..61b06fd7d 100644 --- a/src/branch.rs +++ b/src/branch.rs @@ -105,6 +105,17 @@ pub fn can_continue(launch: &Git, github: &GitHub, issue: &IssueUrl) -> Result Result> { + Ok(latest(&GitHubAndOrigin { launch, github }, issue)? + .and_then(|latest| latest.pr) + .filter(|pr| pr.state == PrState::Open)) +} + /// What selection reads of origin, GitHub and the Launch directory. Each /// listing is by prefix, as git and GitHub answer it, so it can hold another /// issue's Issue branches. diff --git a/src/fix.rs b/src/fix.rs index 6924082bc..5cf15adf0 100644 --- a/src/fix.rs +++ b/src/fix.rs @@ -83,9 +83,7 @@ pub(crate) fn run( author.as_deref(), behind, sign_off_hold, - config - .self_merge_check(&launch.repo) - .map(|_| config.logs_dir.as_path()), + &config.logs_dir, &mut passed_over, )? { let selected = FixArgs { diff --git a/src/fix/selection.rs b/src/fix/selection.rs index fe1c2f6a2..3ddc52ca0 100644 --- a/src/fix/selection.rs +++ b/src/fix/selection.rs @@ -17,13 +17,9 @@ pub(super) fn take( author: Option<&str>, behind: Option, sign_off_hold: Option<&SignOffHold>, - hold_logs: Option<&std::path::Path>, + logs_dir: &std::path::Path, passed_over: &mut Vec, ) -> Result> { - let holds = hold_logs - .filter(|_| behind.is_some()) - .map(crate::logs::self_merge_check_holds) - .transpose()?; let mut pass = Pass { launch, github, @@ -54,15 +50,13 @@ pub(super) fn take( } } - let Some(behind) = behind else { + let Some(behind) = behind.filter(|_| !without_repairs.is_empty()) else { return Ok(None); }; + let holds = crate::logs::self_merge_check_holds(logs_dir)?; let mut further_behind = Vec::new(); for (listed, candidate) in without_repairs { - if holds - .as_ref() - .is_some_and(|holds| holds.self_merge_check_held(&listed.pr.url)) - { + if holds.reason(&listed.pr.url).is_some() { continue; } let distance = github.fix_commits_behind(&listed.pr, &candidate)?; diff --git a/src/logs.rs b/src/logs.rs index 9b89aa4a6..e12a6a368 100644 --- a/src/logs.rs +++ b/src/logs.rs @@ -28,6 +28,7 @@ pub(crate) mod pass_starts; mod process_identity; mod reading; pub(crate) use reading::Framing; +pub(crate) use reading::SelfMergeCheckHolds; pub(crate) use reading::catalog; pub(crate) use reading::run_for_pull_request; mod recording; @@ -713,11 +714,9 @@ pub(crate) fn record_for_pull_request(root: &Path, url: &str) -> anyhow::Result< Ok(run_for_pull_request(root, url)?.map(|(path, _)| path)) } -pub(crate) fn self_merge_check_holds( - logs_dir: &Path, -) -> anyhow::Result { +pub(crate) fn self_merge_check_holds(logs_dir: &Path) -> anyhow::Result { let snapshot = reading::Snapshot::load(logs_dir, chrono::Local::now())?; - Ok(reading::PullRequestAttribution::new(&snapshot)) + Ok(reading::PullRequestAttribution::new(&snapshot).self_merge_check_holds()) } /// Where this command and all its child Runs keep Session traces on `repo`. diff --git a/src/logs/reading.rs b/src/logs/reading.rs index b32a251f5..17368de22 100644 --- a/src/logs/reading.rs +++ b/src/logs/reading.rs @@ -27,8 +27,8 @@ use super::effects::OnMachine; use super::pass_starts::{self, PassStart}; pub(super) use super::usual_range::UsualRange; use super::{Pass, activity}; -pub(crate) use attribution::PullRequestAttribution; pub(super) use attribution::{CommandIdentity, identity as pull_request_key}; +pub(crate) use attribution::{PullRequestAttribution, SelfMergeCheckHolds}; pub(super) use health::Health; pub(super) use history::Command as HistoricalCommand; pub(super) use inbox::{Departure, Group, InboxItem, NeedsYouKind, RowOrder}; diff --git a/src/logs/reading/attribution.rs b/src/logs/reading/attribution.rs index cc362690b..c924907db 100644 --- a/src/logs/reading/attribution.rs +++ b/src/logs/reading/attribution.rs @@ -30,7 +30,20 @@ impl CommandIdentity { struct Candidate { identity: CommandIdentity, started_at: Option>, - held_by_self_merge_check: bool, + self_merge_check_hold: Option, +} + +/// Self-merge check reasons from the latest retained Command for each PR. +pub(crate) struct SelfMergeCheckHolds(BTreeMap); + +impl SelfMergeCheckHolds { + pub(crate) fn is_empty(&self) -> bool { + self.0.is_empty() + } + + pub(crate) fn reason(&self, url: &str) -> Option<&str> { + self.0.get(&identity(url)).map(String::as_str) + } } /// One matching and ordering rule for Scoring, Bug origins and Run metrics. @@ -64,9 +77,16 @@ impl PullRequestAttribution { .max_by_key(|candidate| (candidate.started_at, &candidate.identity)) } - pub(crate) fn self_merge_check_held(&self, url: &str) -> bool { - self.latest_candidate(url) - .is_some_and(|candidate| candidate.held_by_self_merge_check) + pub(in crate::logs) fn self_merge_check_holds(&self) -> SelfMergeCheckHolds { + SelfMergeCheckHolds( + self.candidates + .keys() + .filter_map(|url| { + let reason = self.latest_candidate(url)?.self_merge_check_hold.as_ref()?; + Some((url.clone(), reason.clone())) + }) + .collect(), + ) } /// A saved local identity is authoritative, including its PR membership. @@ -93,11 +113,15 @@ impl PullRequestAttribution { .push(Candidate { identity: CommandIdentity::of(command), started_at: DateTime::parse_from_rfc3339(&command.record.started_at).ok(), - held_by_self_merge_check: command.record.outcome.as_deref() - == Some("ready for review") - && command.record.cause.as_deref().is_some_and(|cause| { - cause.starts_with(crate::self_merge_check::HOLD_PREFIX) - }), + self_merge_check_hold: command + .record + .cause + .as_ref() + .filter(|cause| { + command.record.outcome.as_deref() == Some("ready for review") + && cause.starts_with(crate::self_merge_check::HOLD_PREFIX) + }) + .cloned(), }); } // Snapshot has already excluded orphaned and unmatched child records. diff --git a/src/pass.rs b/src/pass.rs index 4a9ebbb86..f624b0d18 100644 --- a/src/pass.rs +++ b/src/pass.rs @@ -246,7 +246,7 @@ impl Outside for LaunchAndGitHub<'_> { while let Some(ready) = ready::first( self.launch, self.repo, - self.config.pickup_wait, + self.config, order, past, self.authors, @@ -268,12 +268,7 @@ impl Outside for LaunchAndGitHub<'_> { } fn before_architect(&mut self) -> Result> { - ready::before_architect( - self.launch, - self.repo, - self.config.pickup_wait, - self.authors, - ) + ready::before_architect(self.launch, self.repo, self.config, self.authors) } fn step(&mut self, line: String) { diff --git a/src/pickup.rs b/src/pickup.rs index bb9653602..7f48ed227 100644 --- a/src/pickup.rs +++ b/src/pickup.rs @@ -195,7 +195,7 @@ pub fn run( return Ok(None); }; Ok( - crate::ready::refresh(directory.git(), ready, config.pickup_wait, &authors)? + crate::ready::refresh(directory.git(), ready, config, &authors)? .map(|ready| (ready, reservation)), ) }, diff --git a/src/ready.rs b/src/ready.rs index 23a832911..b6a6a6285 100644 --- a/src/ready.rs +++ b/src/ready.rs @@ -5,16 +5,20 @@ //! definition. An Architect run also waits for an issue that meets every //! Ready issue condition except settling. +use std::cell::OnceCell; + use anyhow::Result; use chrono::{DateTime, TimeDelta, Utc}; use crate::base_fix; use crate::branch::{self, Started}; use crate::claim; +use crate::config::UserConfig; use crate::git::Git; use crate::github::{Candidate, GitHub, ListedIssue, Shaping, Ticket}; use crate::issue::{IssueUrl, Repo}; use crate::labels::{Label, READY_FOR_AGENT}; +use crate::logs::{self, SelfMergeCheckHolds}; use crate::progress; use crate::spec_run::{self, Unstartable}; use crate::trust::{self, UntrustedIssue}; @@ -93,20 +97,20 @@ enum Settling { /// Launch directory `launch`'s repository, if there is one, with a line on /// stderr for each issue labelled `ready-for-agent` passed over before it, /// with why. Nothing is changed, on GitHub or in `launch`. -/// `wait` is the User config's settling window since the latest shaping +/// `config` gives the settling window since the latest shaping /// event. With `past`, the number of an issue already tried, only the issues /// after it in `order` are considered, so a Pickup run that could not /// reserve one moves on to the next. pub fn first( launch: &Git, repo: &Repo, - wait: TimeDelta, + config: &UserConfig, order: PickupOrder, past: Option, authors: &[String], ) -> Result> { Ok( - match search(launch, repo, wait, Settling::Wait, order, past, authors)? { + match search(launch, repo, config, Settling::Wait, order, past, authors)? { Some(PriorityIssue::Ready(ready)) => Some(ready), _ => None, }, @@ -118,13 +122,13 @@ pub fn first( pub fn before_architect( launch: &Git, repo: &Repo, - wait: TimeDelta, + config: &UserConfig, authors: &[String], ) -> Result> { search( launch, repo, - wait, + config, Settling::Include, PickupOrder::LowestFirst, None, @@ -135,7 +139,7 @@ pub fn before_architect( fn search( launch: &Git, repo: &Repo, - wait: TimeDelta, + config: &UserConfig, settling: Settling, order: PickupOrder, past: Option, @@ -145,6 +149,8 @@ fn search( launch, github: GitHub::new(), authors, + config, + holds: OnceCell::new(), }; let listed = reads .github @@ -154,7 +160,7 @@ fn search( &reads, listed.issues, Utc::now(), - wait, + config.pickup_wait, order, progress::step, ) @@ -171,13 +177,15 @@ fn search( pub fn refresh( launch: &Git, selected: ReadyIssue, - wait: TimeDelta, + config: &UserConfig, authors: &[String], ) -> Result> { let reads = GitHubAndOrigin { launch, github: GitHub::new(), authors, + config, + holds: OnceCell::new(), }; let issue = selected.listed.issue; let current = reads.github.issue(&issue)?; @@ -189,7 +197,13 @@ pub fn refresh( title: current.title.unwrap_or_default(), labels: current.labels, }; - match standing_of(&reads, &listed, Utc::now(), wait, Settling::Wait)? { + match standing_of( + &reads, + &listed, + Utc::now(), + config.pickup_wait, + Settling::Wait, + )? { Standing::Ready { is_spec, claim_generation, @@ -210,6 +224,8 @@ trait Reads { fn candidate(&self, issue: &IssueUrl) -> Result; /// What shows `issue` was ever started, if it was. fn started(&self, issue: &IssueUrl) -> Result>; + /// The open PR and its reason when the latest local Run left a Self-merge check hold. + fn self_merge_check_hold(&self, issue: &IssueUrl) -> Result>; /// Whether the latest Issue branch can be continued under ADR-0002. fn can_continue(&self, issue: &IssueUrl) -> Result; /// The Tickets of `spec`, an issue with sub-issues, as a Spec run reads @@ -223,6 +239,8 @@ struct GitHubAndOrigin<'a> { launch: &'a Git, github: GitHub, authors: &'a [String], + config: &'a UserConfig, + holds: OnceCell, } impl Reads for GitHubAndOrigin<'_> { @@ -241,6 +259,25 @@ impl Reads for GitHubAndOrigin<'_> { branch::started(self.launch, &self.github, issue) } + fn self_merge_check_hold(&self, issue: &IssueUrl) -> Result> { + let holds = match self.holds.get() { + Some(holds) => holds, + None => { + let holds = logs::self_merge_check_holds(&self.config.logs_dir)?; + self.holds.get_or_init(|| holds) + } + }; + if holds.is_empty() { + return Ok(None); + } + let Some(pr) = branch::current_open_pr(self.launch, &self.github, issue)? else { + return Ok(None); + }; + Ok(holds + .reason(&pr.url) + .map(|reason| (pr.url, reason.to_owned()))) + } + fn can_continue(&self, issue: &IssueUrl) -> Result { branch::can_continue(self.launch, &self.github, issue) } @@ -284,6 +321,10 @@ enum Reason { evidence: Started, never_claimed: bool, }, + SelfMergeCheckHold { + pr_url: String, + reason: String, + }, /// It is a Spec whose Tickets are all closed: the Spec run it would be /// dispatched as refuses it, having nothing to do. TicketsClosed, @@ -462,6 +503,9 @@ impl<'a, R: Reads, P: FnMut(String)> Search<'a, R, P> { ) } } + Reason::SelfMergeCheckHold { pr_url, reason } => { + format!("waits for the Day shift on PR {pr_url}: {reason}") + } Reason::TicketsClosed => "every Ticket is closed".to_string(), Reason::NoStartableTicket(tickets) => { let spec = &self.candidates[at].issue; @@ -572,13 +616,16 @@ fn standing_of( if let Some(check) = reads.issue_trust(&candidate.issue)? { return passed_over(Reason::Untrusted(check)); } - if let Some(started) = reads.started(&candidate.issue)? - && !read.handed_back - { - return passed_over(Reason::Started { - evidence: started, - never_claimed: read.claim_generation == 0, - }); + if let Some(started) = reads.started(&candidate.issue)? { + if !read.handed_back { + return passed_over(Reason::Started { + evidence: started, + never_claimed: read.claim_generation == 0, + }); + } + if let Some((pr_url, reason)) = reads.self_merge_check_hold(&candidate.issue)? { + return passed_over(Reason::SelfMergeCheckHold { pr_url, reason }); + } } if read.claimed { return passed_over(Reason::Claimed); @@ -719,6 +766,10 @@ mod tests { Ok(self.facts(issue).and_then(|facts| facts.started.clone())) } + fn self_merge_check_hold(&self, _issue: &IssueUrl) -> Result> { + Ok(None) + } + fn can_continue(&self, _issue: &IssueUrl) -> Result { Ok(false) } diff --git a/tests/fix_pass.rs b/tests/fix_pass.rs index d00563b64..8aa62fb5f 100644 --- a/tests/fix_pass.rs +++ b/tests/fix_pass.rs @@ -146,16 +146,21 @@ fn fix_pass_skips_a_self_merge_check_hold_until_the_pr_has_red_ci() { scenario.write_gh_state(&state); scenario.agent_does(REPAIR_CI); - let skipped = fix_pass(&scenario, &["behind", "2"]); + for remove_check in [false, true] { + if remove_check { + scenario.user_config_is(""); + } + let skipped = fix_pass(&scenario, &["behind", "2"]); - assert_eq!(skipped.code, Some(0), "{}", skipped.stderr); - assert!( - skipped.stderr.contains("no eligible pull request"), - "{}", - skipped.stderr - ); - assert_eq!(scenario.origin_git(&["rev-parse", "issue-7"]), head); - assert_eq!(scenario.claude_calls().len(), 1); + assert_eq!(skipped.code, Some(0), "{}", skipped.stderr); + assert!( + skipped.stderr.contains("no eligible pull request"), + "{}", + skipped.stderr + ); + assert_eq!(scenario.origin_git(&["rev-parse", "issue-7"]), head); + assert_eq!(scenario.claude_calls().len(), 1); + } state = scenario.gh_state(); state["checks"][head.trim()] = json!([{"name": "test", "conclusion": "failure"}]); @@ -183,6 +188,52 @@ esac assert_eq!(scenario.claude_calls().len(), 2); } +#[test] +fn fix_pass_repairs_a_merge_conflict_alongside_a_self_merge_check_hold() { + let scenario = Scenario::new(); + scenario.origin_has_commit( + "main", + "check", + "#!/bin/sh\necho Day shift decides\nexit 1\n", + "Add check", + ); + scenario.user_config_is( + "[merge]\nalways = true\nself_merge_check = { \"acme/widgets\" = \"check\" }\n", + ); + scenario + .agent_does("echo feature > shared.txt; git add shared.txt; git commit -qm 'Add feature'"); + let held = scenario.run(&[&scenario.issue_url(7)]); + assert_eq!(held.code, Some(0), "{}", held.stderr); + assert!( + held.stderr + .contains("Self-merge check held: Day shift decides") + ); + + scenario.origin_has_commit("main", "shared.txt", "base", "Base content"); + let mut state = scenario.gh_state(); + state["prs"][0]["mergeable"] = "CONFLICTING".into(); + scenario.write_gh_state(&state); + scenario.agent_does( + r#" +echo resolved > shared.txt +git add shared.txt +git commit -qm 'Resolve base conflict' +gh fake pr issue-7 mergeable '"MERGEABLE"' +"#, + ); + + let result = fix_pass(&scenario, &[]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert_eq!( + scenario.origin_file("issue-7", "shared.txt").as_deref(), + Some("resolved\n"), + "{}", + result.stderr + ); + assert_eq!(scenario.claude_calls().len(), 2); +} + #[test] fn pass_skips_a_sign_off_hold_and_repairs_the_next_pull_request() { let scenario = Scenario::new(); diff --git a/tests/pickup_run.rs b/tests/pickup_run.rs index 7fe949509..3d763a894 100644 --- a/tests/pickup_run.rs +++ b/tests/pickup_run.rs @@ -2287,6 +2287,56 @@ fn pickup_merge_always_obeys_the_self_merge_check_without_a_merge_label() { } } +#[test] +fn pickup_leaves_an_open_self_merge_check_hold_for_the_day_shift() { + let scenario = ready_ticket(); + scenario.origin_has_commit( + "main", + "check", + "#!/bin/sh\necho Day shift decides\nexit 1\n", + "Add check", + ); + scenario.user_config_is( + "[merge]\nalways = true\nself_merge_check = { \"acme/widgets\" = \"check\" }\n", + ); + let held = scenario.run(&["pickup"]); + let pr = pr_from(&scenario, "issue-7"); + assert_ended_with_pr( + &held, + &pr, + "ready for review waiting for Self-merge check held: Day shift decides", + ); + let held_url = pr["url"].as_str().unwrap(); + let held_head = scenario.origin_git(&["rev-parse", "issue-7"]); + + ready_issue(&scenario, 7, &[]); + scenario.issue_timeline( + 7, + &[ + (TimelineEvent::Labelled(IN_PROGRESS), 90), + (TimelineEvent::Unlabelled(IN_PROGRESS), 61), + (TimelineEvent::Labelled(READY_FOR_AGENT), 60), + ], + ); + ready_issue(&scenario, 8, &[]); + scenario.agent_does_for(8, &agent_opens_pr(8, "main")); + + let later = scenario.run(&["pickup", "no-merge"]); + + assert_eq!(later.code, Some(0), "{}", later.stderr); + assert!( + later.stderr.contains(&format!( + "#7 waits for the Day shift on PR {held_url}: Self-merge check held: Day shift decides" + )), + "{}", + later.stderr + ); + assert_eq!(sessions(&scenario), ["7", "8"], "{}", later.stderr); + assert_eq!(scenario.issue_labels(7), [READY_FOR_AGENT]); + assert_eq!(scenario.origin_git(&["rev-parse", "issue-7"]), held_head); + assert_eq!(pr_from(&scenario, "issue-7")["state"], "OPEN"); +} + const RED: &str = r#"[{"name": "test", "conclusion": "failure"}]"#; const GREEN: &str = r#"[{"name": "test", "conclusion": "success"}]"#; From 0f2f75bbb577c7fc13074975f8bc0e799f126850 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Fri, 4 Dec 2026 12:51:51 -0500 Subject: [PATCH 20/27] Address hold attribution and Inbox review findings (#2427) --- GLOSSARY.md | 2 +- docs/guide.md | 2 +- site/docs/index.html | 2 +- site/how-it-works/index.html | 2 +- site/index.html | 2 +- src/branch.rs | 92 +++++++++++++++++++++------------ src/fix/selection.rs | 2 +- src/logs.rs | 8 +-- src/logs/command_record.rs | 7 +++ src/logs/reading.rs | 36 ++++++++++++- src/logs/reading/attribution.rs | 26 ++++------ src/logs/reading/inbox.rs | 25 ++++++++- src/ready.rs | 65 ++++++++++++----------- tests/base_fix.rs | 10 ++++ tests/pickup_run.rs | 11 ++++ 15 files changed, 200 insertions(+), 92 deletions(-) diff --git a/GLOSSARY.md b/GLOSSARY.md index 008b1c0bf..7a6608a02 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -27,7 +27,7 @@ An issue scoping one session of work, standing alone or as a sub-issue of a **Sp _Avoid_: task, sub-task **Ready issue**: -An open issue a **Pickup run** may take: labelled `ready-for-agent`, written by a **Trusted account** or a named author, with its most recent `ready-for-agent` labelling made by a Trusted account and with later title and body edits only by Trusted accounts or the authorized author, with no label that makes an **Unready Ticket** and no **Claim**, not a sub-issue, not a **Base fix**'s or a **Security run**'s fix issue, with no open blocker, either never started (no **Issue branch** and no pull request) or handed back at or after the last **Claim** ended, as recorded in its label history: by the **Day shift** applying `ready-for-agent`, or by thirdshift putting it back on a Spec whose Spec run ended only waiting, which it does only when only Trusted accounts or the authorized author have edited the Spec since its last Trusted `ready-for-agent` labelling, and otherwise labels the Spec `needs-triage`, and only when each of its open Tickets in its repository passes the Trusted account check for Tickets, and otherwise labels it `agent-failed`, left untouched long enough that whoever is shaping it has finished, and, if it is a **Spec**, with a **Startable Ticket** or with every Ticket closed and a resumable **Spec branch** on `origin` (the latest numbered branch, with no PR or an open PR). A hand-back made in the same edit as the Claim's removal counts in either listed order at that timestamp; a Claim applied at the same timestamp leaves the issue Claimed. On a Spec, the label says its Tickets are published. A `ready-for-agent` Ticket inside a Spec is not one: it is reached through its Spec, when the Spec is itself a Ready issue. +An open issue a **Pickup run** may take: labelled `ready-for-agent`, written by a **Trusted account** or a named author, with its most recent `ready-for-agent` labelling made by a Trusted account and with later title and body edits only by Trusted accounts or the authorized author, with no label that makes an **Unready Ticket** and no **Claim**, not a sub-issue, not a **Base fix**'s or a **Security run**'s fix issue, with no open blocker, either never started (no **Issue branch** and no pull request) or handed back at or after the last **Claim** ended, as recorded in its label history: by the **Day shift** applying `ready-for-agent`, or by thirdshift putting it back on a Spec whose Spec run ended only waiting, which it does only when only Trusted accounts or the authorized author have edited the Spec since its last Trusted `ready-for-agent` labelling, and otherwise labels the Spec `needs-triage`, and only when each of its open Tickets in its repository passes the Trusted account check for Tickets, and otherwise labels it `agent-failed`, left untouched long enough that whoever is shaping it has finished, and, if it is a **Spec**, with a **Startable Ticket** or with every Ticket closed and a resumable **Spec branch** on `origin` (the latest numbered branch, with no PR or an open PR). A hand-back made in the same edit as the Claim's removal counts in either listed order at that timestamp; a Claim applied at the same timestamp leaves the issue Claimed. An open pull request whose latest run on this machine ended at a **Self-merge check** hold keeps its issue waiting for the Day shift. On a Spec, the label says its Tickets are published. A `ready-for-agent` Ticket inside a Spec is not one: it is reached through its Spec, when the Spec is itself a Ready issue. _Avoid_: queued issue, backlog item **Trusted account**: diff --git a/docs/guide.md b/docs/guide.md index 81c727e7a..8563ede63 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -4483,7 +4483,7 @@ thirdshift pickup trust-author 'intake[bot]' # approve this author for one Pass Pickup has no Built-in process file. It selects and reserves the Ready issue, then starts `ticket-run` or `spec-run` as a command on that Issue URL would. -Pickup passes over an open pull request whose latest local Run ended at a Self-merge check hold, even if the issue has been handed back. It prints the hold reason and looks for the next Ready issue. +Pickup passes over an open pull request whose latest run on this machine ended at a Self-merge check hold, even if the issue has been handed back. It prints the hold reason and looks for the next Ready issue. Which end of the issue numbers the pass takes is its order: `lowest-first` by default, `highest-first` with `pickup.order = "highest-first"` in the [User config](#user-config), or for one pass with `lowest-first` or `highest-first` on the command, which wins over the User config. Two schedules working through the same queue from opposite ends, one with each order, collide less often; the reservation below still protects either choice. diff --git a/site/docs/index.html b/site/docs/index.html index 6c7be5e66..82d23ea93 100644 --- a/site/docs/index.html +++ b/site/docs/index.html @@ -4179,7 +4179,7 @@

    Pickup has no Built-in process file. It selects and reserves the Ready issue, then starts ticket-run or spec-run as a command on that Issue URL would.

    -

    Pickup passes over an open pull request whose latest local Run ended at a Self-merge check hold, even if the issue has been handed back. It prints the hold reason and looks for the next Ready issue.

    +

    Pickup passes over an open pull request whose latest run on this machine ended at a Self-merge check hold, even if the issue has been handed back. It prints the hold reason and looks for the next Ready issue.

    Which end of the issue numbers the pass takes is its order: lowest-first by default, highest-first with pickup.order = "highest-first" in the User config, or for one pass with lowest-first or highest-first on the command, which wins over the User config. Two schedules working through the same queue from opposite ends, one with each order, collide less often; the reservation below still protects either choice.

    Add skip-author <login> (or --skip-author <login>) on each cron line to pass over issues written by that account, even a Trusted account. Repeat it for several accounts; logins match case-insensitively. The Pass logs #947 passed over: written by alice, whom this Pass skips and searches for the next Ready issue. A skipped Spec author excludes the whole Spec. A Spec run dispatched by this Pass also stops before a Ticket written by a skipped account, with the same failure handling as an untrusted Ticket author. These choices belong to this Pass, with no User config setting; explicitly running thirdshift <Issue URL> still runs the named issue under the usual trust checks. The word never makes an untrusted author eligible.

    Pickup uses trust.authors for its repository. Add diff --git a/site/how-it-works/index.html b/site/how-it-works/index.html index 7dba307ee..7e3850ebe 100644 --- a/site/how-it-works/index.html +++ b/site/how-it-works/index.html @@ -317,7 +317,7 @@

    How thirdshift works

    Eligible work ↓ Ticket run or Spec run ↓ reviewed pull request

    -

    Pickup passes over an open pull request whose latest local Run ended at a Self-merge check hold, even if the issue has been handed back. It prints the hold reason and looks for the next Ready issue.

    +

    Pickup passes over an open pull request whose latest run on this machine ended at a Self-merge check hold, even if the issue has been handed back. It prints the hold reason and looks for the next Ready issue.

    Pickup respects issue readiness, open blockers and the Failure limit: it takes nothing while three open issues, or pickup.failure_limit, carry agent-failed from a failed run, and pull requests waiting for review never count. A run that failed because the host ran out of disk space is no failure of its issue: it puts ready-for-agent back without agent-failed, even with work on origin, and says to free disk space. A Paused Command, which no route had Plan usage left for, is none either: it puts ready-for-agent back the same way, unless an untrusted edit leaves needs-triage or it is a Security fix. Any other failed run with work on origin, or a failed Security fix, swaps in-progress for agent-failed and, unless it is a Security fix, posts its Recovery on the issue as a generated comment without local paths or the continue command; putting ready-for-agent back, taking agent-failed off or closing the issue ends the failure, and the Sweep takes in-progress off any open issue that still carries both. Before choosing work, it re-runs failed jobs of the Base branch's latest push CI once, immediately. Green on re-run files a Flaky-test Ticket using the recorded failure as evidence, without requiring reproduction on demand. Red again files an ordinary bug Ticket after 30 minutes from the re-run's completion. Its title, body and later comments leave job names and log lines out, and it waits until you write the task and apply ready-for-agent. An open CI-red Ticket in needs-info does not block a new report; another open CI-red Ticket receives new failing commits as comments. CI read failures warn and let Pickup continue; red Base CI does not hold Self-merges. Architect and Security runs yield to ready human-shaped work. Gates can skip a pass without failure, and unresolved plans, ideas or findings can leave the next decision with the Day shift. This is scheduled CLI work on your machine, using your authenticated tools.

    When a Security run fails before its audit starts, its requested Run notification names a fixed Cause for Base branch preparation failures, such as Base branch not found, and points to stderr on the host at the command's start time for diagnostics. Security run notifications.

    Before dispatch, Pickup reserves its selected issue on origin and checks that it is still Ready. Competing Pickup runs on two machines cannot take the same issue: only the reservation's owner can dispatch it, and the other moves on to the next Ready issue in its order. An Architect run takes the same reservation for the plan it dispatches, and a Security run for its fix, before marking it ready, so a Pickup run beside either never takes it. The reservation's commit message records its host, launch path, process and start time. Before choosing work, every scheduled Pass releases its own orphaned origin reservations only on local proof of death: a missing PID, a process started after the reservation, or a host boot after it. Failed probes count as alive, and an exact observed-SHA lease protects a new owner. Stderr and Activity record the release. A reservation no host can test that blocked work and has been held over a day appears in Needs you with owner, age, blocked work and a release command. The Day shift confirms death before releasing it by hand; no reservation expires on a timer. Pickup's reservation and readiness checks.

    diff --git a/site/index.html b/site/index.html index 6503af0e8..bbbdc35c3 100644 --- a/site/index.html +++ b/site/index.html @@ -437,7 +437,7 @@

    Seven workflows

    Pickup runTake a Ready issue and put the factory to work.

    Add skip-author <login> or --skip-author <login> to a Pickup or Triage cron line to leave that author's issues alone, even for a Trusted account. Repeat it for several logins; matching ignores case. Pickup passes over the whole Spec when its author is skipped, and its dispatched Spec run stops before a skipped author's Ticket. Each exclusion logs why. Explicit Issue URL runs keep their usual trust checks.

    -

    A Pickup run takes the lowest-numbered Ready issue by default, the highest-numbered with pickup.order = "highest-first" or highest-first, after it has settled and while the repository is below its Failure limit: fewer open issues labelled agent-failed than pickup.failure_limit, 3 by default. A pull request waiting for review never holds it back. It immediately re-runs failed Base branch push CI once: green on re-run files a Flaky-test Ticket, and red again files an ordinary bug Ticket after 30 minutes. That CI-red Ticket leaves job names and log lines out of its title, body and later comments, and waits until you write the task and apply ready-for-agent. New failing commits are added to an open CI-red Ticket; one in needs-info does not block a new report. A run the host ran out of disk space under gets ready-for-agent back instead, as a host problem, not the issue's, and so does a Paused Command that no route had Plan usage left for, unless an untrusted edit leaves needs-triage or it is a Security fix. Other failed work stays with the Day shift, labelled agent-failed in place of in-progress, with a generated comment giving its cause, where it stopped, what was preserved and the machine, until you hand it back by applying ready-for-agent again, take agent-failed off, or close the issue. A Spec run only waiting on gated, blocked or out-of-repository Tickets is no failure: its Spec gets ready-for-agent back and a comment naming each undone Ticket and what it waits on, and a later Pickup run continues it once a Ticket can start. A run that leaves its pull request ready for review takes in-progress off and puts nothing back.

    +

    A Pickup run takes the lowest-numbered Ready issue by default, the highest-numbered with pickup.order = "highest-first" or highest-first, after it has settled and while the repository is below its Failure limit: fewer open issues labelled agent-failed than pickup.failure_limit, 3 by default. Pull requests waiting for review do not count toward the Failure limit. It immediately re-runs failed Base branch push CI once: green on re-run files a Flaky-test Ticket, and red again files an ordinary bug Ticket after 30 minutes. That CI-red Ticket leaves job names and log lines out of its title, body and later comments, and waits until you write the task and apply ready-for-agent. New failing commits are added to an open CI-red Ticket; one in needs-info does not block a new report. A run the host ran out of disk space under gets ready-for-agent back instead, as a host problem, not the issue's, and so does a Paused Command that no route had Plan usage left for, unless an untrusted edit leaves needs-triage or it is a Security fix. Other failed work stays with the Day shift, labelled agent-failed in place of in-progress, with a generated comment giving its cause, where it stopped, what was preserved and the machine, until you hand it back by applying ready-for-agent again, take agent-failed off, or close the issue. A Spec run only waiting on gated, blocked or out-of-repository Tickets is no failure: its Spec gets ready-for-agent back and a comment naming each undone Ticket and what it waits on, and a later Pickup run continues it once a Ticket can start. A run that leaves its pull request ready for review takes in-progress off and puts nothing back.

    diff --git a/src/branch.rs b/src/branch.rs index 61b06fd7d..56ad1c787 100644 --- a/src/branch.rs +++ b/src/branch.rs @@ -105,15 +105,24 @@ pub fn can_continue(launch: &Git, github: &GitHub, issue: &IssueUrl) -> Result Result> { - Ok(latest(&GitHubAndOrigin { launch, github }, issue)? +pub struct Readiness { + pub started: Option, + pub open_pr_url: Option, +} + +/// Started evidence and the current open PR from the same branch observation. +pub fn readiness(launch: &Git, github: &GitHub, issue: &IssueUrl) -> Result { + let used = used(&GitHubAndOrigin { launch, github }, issue)?; + let started = used.started(issue); + let open_pr_url = used + .latest() .and_then(|latest| latest.pr) - .filter(|pr| pr.state == PrState::Open)) + .filter(|pr| pr.state == PrState::Open) + .map(|pr| pr.url); + Ok(Readiness { + started, + open_pr_url, + }) } /// What selection reads of origin, GitHub and the Launch directory. Each @@ -222,36 +231,12 @@ struct Latest { } fn latest(reads: &impl Reads, issue: &IssueUrl) -> Result> { - let Used { on_origin, prs } = used(reads, issue)?; - let Some(highest) = on_origin - .iter() - .map(|(number, _)| *number) - .chain(prs.iter().map(|(number, _)| *number)) - .max() - else { - return Ok(None); - }; - Ok(Some(Latest { - number: highest, - origin_sha: on_origin - .into_iter() - .find_map(|(number, sha)| (number == highest).then_some(sha)), - // A branch can have had several PRs; the newest one decides. - pr: prs - .into_iter() - .filter_map(|(number, pr)| (number == highest).then_some(pr)) - .max_by_key(|pr| pr.number), - })) + Ok(used(reads, issue)?.latest()) } /// [`started`], reading through `reads`. fn started_through(reads: &impl Reads, issue: &IssueUrl) -> Result> { - let Used { on_origin, prs } = used(reads, issue)?; - let branch = on_origin.iter().map(|(number, _)| *number).min(); - let pr = prs.into_iter().map(|(_, pr)| pr).max_by_key(|pr| pr.number); - Ok(branch - .map(|number| Started::Branch(branch_name(issue, number))) - .or(pr.map(|pr| Started::PullRequest(pr.url)))) + Ok(used(reads, issue)?.started(issue)) } /// What has been used of an issue's Issue branches. @@ -263,6 +248,45 @@ struct Used { prs: Vec<(u64, PullRequest)>, } +impl Used { + fn started(&self, issue: &IssueUrl) -> Option { + self.on_origin + .iter() + .map(|(number, _)| *number) + .min() + .map(|number| Started::Branch(branch_name(issue, number))) + .or_else(|| { + self.prs + .iter() + .map(|(_, pr)| pr) + .max_by_key(|pr| pr.number) + .map(|pr| Started::PullRequest(pr.url.clone())) + }) + } + + fn latest(self) -> Option { + let highest = self + .on_origin + .iter() + .map(|(number, _)| *number) + .chain(self.prs.iter().map(|(number, _)| *number)) + .max()?; + Some(Latest { + number: highest, + origin_sha: self + .on_origin + .into_iter() + .find_map(|(number, sha)| (number == highest).then_some(sha)), + // A branch can have had several PRs; the newest one decides. + pr: self + .prs + .into_iter() + .filter_map(|(number, pr)| (number == highest).then_some(pr)) + .max_by_key(|pr| pr.number), + }) + } +} + /// What has been used of `issue`'s Issue branches: those on origin and the /// pull requests from them, one listing of each, with another issue's that /// the listings' prefix lets through dropped. diff --git a/src/fix/selection.rs b/src/fix/selection.rs index 3ddc52ca0..1b28339b8 100644 --- a/src/fix/selection.rs +++ b/src/fix/selection.rs @@ -53,7 +53,7 @@ pub(super) fn take( let Some(behind) = behind.filter(|_| !without_repairs.is_empty()) else { return Ok(None); }; - let holds = crate::logs::self_merge_check_holds(logs_dir)?; + let holds = crate::logs::self_merge_check_holds(logs_dir, &launch.repo)?; let mut further_behind = Vec::new(); for (listed, candidate) in without_repairs { if holds.reason(&listed.pr.url).is_some() { diff --git a/src/logs.rs b/src/logs.rs index e12a6a368..2d12c15e5 100644 --- a/src/logs.rs +++ b/src/logs.rs @@ -714,9 +714,11 @@ pub(crate) fn record_for_pull_request(root: &Path, url: &str) -> anyhow::Result< Ok(run_for_pull_request(root, url)?.map(|(path, _)| path)) } -pub(crate) fn self_merge_check_holds(logs_dir: &Path) -> anyhow::Result { - let snapshot = reading::Snapshot::load(logs_dir, chrono::Local::now())?; - Ok(reading::PullRequestAttribution::new(&snapshot).self_merge_check_holds()) +pub(crate) fn self_merge_check_holds( + logs_dir: &Path, + repo: &Repo, +) -> anyhow::Result { + reading::self_merge_check_holds(logs_dir, repo) } /// Where this command and all its child Runs keep Session traces on `repo`. diff --git a/src/logs/command_record.rs b/src/logs/command_record.rs index 226d3559e..5602386ae 100644 --- a/src/logs/command_record.rs +++ b/src/logs/command_record.rs @@ -474,6 +474,13 @@ impl CommandRecord { .chain(self.session_log.as_ref()) } + pub(super) fn self_merge_check_hold(&self) -> Option<&str> { + self.cause.as_deref().filter(|cause| { + self.outcome.as_deref() == Some("ready for review") + && cause.starts_with(crate::self_merge_check::HOLD_PREFIX) + }) + } + pub fn finish( &mut self, account: &crate::run_ending::Account<'_>, diff --git a/src/logs/reading.rs b/src/logs/reading.rs index 17368de22..b217971b4 100644 --- a/src/logs/reading.rs +++ b/src/logs/reading.rs @@ -538,11 +538,43 @@ impl Command { } pub(super) fn repository_records(root: &Path) -> Result> { - let inventory = Inventory::on_demand(); + read_repository_records(&Inventory::on_demand(), root) +} + +pub(super) fn self_merge_check_holds( + logs_dir: &Path, + repo: &crate::issue::Repo, +) -> Result { + let inventory = Arc::new(Inventory::on_demand()); + let mut records = BTreeMap::new(); + for owner in inventory.directories(logs_dir)? { + if !owner + .file_name() + .is_some_and(|name| name.eq_ignore_ascii_case(&repo.owner)) + { + continue; + } + for path in inventory.directories(&owner)? { + if path + .file_name() + .is_some_and(|name| name.eq_ignore_ascii_case(&repo.name)) + { + records.extend(read_repository_records(&inventory, &path)?); + } + } + } + let commands = command_trees(&inventory, &mut records, &Local::now()); + Ok(PullRequestAttribution::from_commands(&commands).self_merge_check_holds()) +} + +fn read_repository_records( + inventory: &Inventory, + root: &Path, +) -> Result> { let mut records = BTreeMap::new(); for folder in inventory.directories(&root.join("commands"))? { let folder = inventory.folder(&folder)?; - records.extend(read_records(&inventory, &folder, false)?); + records.extend(read_records(inventory, &folder, false)?); } Ok(records) } diff --git a/src/logs/reading/attribution.rs b/src/logs/reading/attribution.rs index c924907db..2d32fe625 100644 --- a/src/logs/reading/attribution.rs +++ b/src/logs/reading/attribution.rs @@ -37,10 +37,6 @@ struct Candidate { pub(crate) struct SelfMergeCheckHolds(BTreeMap); impl SelfMergeCheckHolds { - pub(crate) fn is_empty(&self) -> bool { - self.0.is_empty() - } - pub(crate) fn reason(&self, url: &str) -> Option<&str> { self.0.get(&identity(url)).map(String::as_str) } @@ -53,13 +49,18 @@ pub(crate) struct PullRequestAttribution { impl PullRequestAttribution { pub(in crate::logs) fn new(snapshot: &Snapshot) -> Self { + Self::from_commands(snapshot.entries().iter().filter_map(|entry| match entry { + Entry::Record(command) => Some(command.as_ref()), + Entry::History(_) => None, + })) + } + + pub(super) fn from_commands<'a>(commands: impl IntoIterator) -> Self { let mut attribution = Self { candidates: BTreeMap::new(), }; - for entry in snapshot.entries() { - if let Entry::Record(command) = entry { - attribution.collect(command); - } + for command in commands { + attribution.collect(command); } attribution } @@ -115,13 +116,8 @@ impl PullRequestAttribution { started_at: DateTime::parse_from_rfc3339(&command.record.started_at).ok(), self_merge_check_hold: command .record - .cause - .as_ref() - .filter(|cause| { - command.record.outcome.as_deref() == Some("ready for review") - && cause.starts_with(crate::self_merge_check::HOLD_PREFIX) - }) - .cloned(), + .self_merge_check_hold() + .map(str::to_owned), }); } // Snapshot has already excluded orphaned and unmatched child records. diff --git a/src/logs/reading/inbox.rs b/src/logs/reading/inbox.rs index 22c6b80fa..7db760007 100644 --- a/src/logs/reading/inbox.rs +++ b/src/logs/reading/inbox.rs @@ -334,6 +334,24 @@ impl<'a> Captured<'a> { } } + /// A held child has its own PR for the Day shift, even if its outer Command failed. + fn collect_held_children( + command: &'a Command, + local: &mut BTreeMap<&'a Path, LocalFacts>, + held: &mut Vec, + ) { + for child in &command.children { + if child.record.pull_request.is_some() && child.record.self_merge_check_hold().is_some() + { + held.push(Self::new(Observation::Record(child), local)); + } + Self::collect_held_children(child, local, held); + } + for run in &command.dispatched { + Self::collect_held_children(run, local, held); + } + } + /// A failed Pass is answered by its failed dispatched work; a Finding /// waits for its own private records rather than a successful fix. fn github_records(&self) -> Vec<&'a crate::logs::command_record::CommandRecord> { @@ -473,12 +491,16 @@ pub(super) fn evaluate<'a>( // representable timestamp is inside the requested retention period. let cutoff = now.checked_sub_signed(chrono::Duration::days(days)); let mut local = BTreeMap::new(); + let mut held_children = Vec::new(); let captured: Vec<_> = entries .iter() .map(|entry| { Captured::new( match entry { - Entry::Record(command) => Observation::Record(command), + Entry::Record(command) => { + Captured::collect_held_children(command, &mut local, &mut held_children); + Observation::Record(command) + } Entry::History(command) => Observation::History(command), }, &mut local, @@ -501,6 +523,7 @@ pub(super) fn evaluate<'a>( && (carried.is_none() || record_pull_request(&run.command) != carried) })) }) + .chain(&held_children) .collect(); let starts: Vec<_> = observations .iter() diff --git a/src/ready.rs b/src/ready.rs index b6a6a6285..745613b3b 100644 --- a/src/ready.rs +++ b/src/ready.rs @@ -222,10 +222,10 @@ trait Reads { /// `issue` as the search reads it: its parent, its sub-issues, its /// blockers and when it was last shaped. fn candidate(&self, issue: &IssueUrl) -> Result; - /// What shows `issue` was ever started, if it was. - fn started(&self, issue: &IssueUrl) -> Result>; - /// The open PR and its reason when the latest local Run left a Self-merge check hold. - fn self_merge_check_hold(&self, issue: &IssueUrl) -> Result>; + /// The issue's started evidence and current open PR from one listing. + fn branches(&self, issue: &IssueUrl) -> Result; + /// The reason when the latest local Run left a Self-merge check hold on this PR. + fn self_merge_check_hold(&self, issue: &IssueUrl, pr_url: &str) -> Result>; /// Whether the latest Issue branch can be continued under ADR-0002. fn can_continue(&self, issue: &IssueUrl) -> Result; /// The Tickets of `spec`, an issue with sub-issues, as a Spec run reads @@ -255,27 +255,19 @@ impl Reads for GitHubAndOrigin<'_> { self.github.candidate(issue, READY_FOR_AGENT) } - fn started(&self, issue: &IssueUrl) -> Result> { - branch::started(self.launch, &self.github, issue) + fn branches(&self, issue: &IssueUrl) -> Result { + branch::readiness(self.launch, &self.github, issue) } - fn self_merge_check_hold(&self, issue: &IssueUrl) -> Result> { + fn self_merge_check_hold(&self, issue: &IssueUrl, pr_url: &str) -> Result> { let holds = match self.holds.get() { Some(holds) => holds, None => { - let holds = logs::self_merge_check_holds(&self.config.logs_dir)?; + let holds = logs::self_merge_check_holds(&self.config.logs_dir, &issue.repo())?; self.holds.get_or_init(|| holds) } }; - if holds.is_empty() { - return Ok(None); - } - let Some(pr) = branch::current_open_pr(self.launch, &self.github, issue)? else { - return Ok(None); - }; - Ok(holds - .reason(&pr.url) - .map(|reason| (pr.url, reason.to_owned()))) + Ok(holds.reason(pr_url).map(str::to_owned)) } fn can_continue(&self, issue: &IssueUrl) -> Result { @@ -581,7 +573,8 @@ fn why_none_can_start(spec: &IssueUrl, tickets: &[Ticket]) -> String { /// Trusted accounts, it has no label that makes an Unready Ticket and no /// Claim, is not a sub-issue, has no `base-fix` or `security-fix` label and no /// open blocker, was never started or has a recorded ready-for-agent -/// hand-back after its last Claim ended, is settled: `wait` has passed since +/// hand-back after its last Claim ended, has no open PR whose latest run on +/// this machine ended at a Self-merge check hold, is settled: `wait` has passed since /// it was last labelled `ready-for-agent` and since a sub-issue or a "blocked by" link of its was /// last added or removed, and, if it is a Spec, has a Startable Ticket or /// every Ticket closed with a Spec branch that can be continued. Its @@ -616,20 +609,23 @@ fn standing_of( if let Some(check) = reads.issue_trust(&candidate.issue)? { return passed_over(Reason::Untrusted(check)); } - if let Some(started) = reads.started(&candidate.issue)? { - if !read.handed_back { - return passed_over(Reason::Started { - evidence: started, - never_claimed: read.claim_generation == 0, - }); - } - if let Some((pr_url, reason)) = reads.self_merge_check_hold(&candidate.issue)? { - return passed_over(Reason::SelfMergeCheckHold { pr_url, reason }); - } + let branches = reads.branches(&candidate.issue)?; + if let Some(evidence) = branches.started + && !read.handed_back + { + return passed_over(Reason::Started { + evidence, + never_claimed: read.claim_generation == 0, + }); } if read.claimed { return passed_over(Reason::Claimed); } + if let Some(pr_url) = branches.open_pr_url + && let Some(reason) = reads.self_merge_check_hold(&candidate.issue, &pr_url)? + { + return passed_over(Reason::SelfMergeCheckHold { pr_url, reason }); + } let continuing_closed_spec = if spec_run::all_closed(read.sub_issue_is_open.iter().copied()) { if !reads.can_continue(&candidate.issue)? { return passed_over(Reason::TicketsClosed); @@ -759,14 +755,21 @@ mod tests { }) } - fn started(&self, issue: &IssueUrl) -> Result> { + fn branches(&self, issue: &IssueUrl) -> Result { self.seen .borrow_mut() .push(Seen::StartedCheck(issue.number)); - Ok(self.facts(issue).and_then(|facts| facts.started.clone())) + Ok(branch::Readiness { + started: self.facts(issue).and_then(|facts| facts.started.clone()), + open_pr_url: None, + }) } - fn self_merge_check_hold(&self, _issue: &IssueUrl) -> Result> { + fn self_merge_check_hold( + &self, + _issue: &IssueUrl, + _pr_url: &str, + ) -> Result> { Ok(None) } diff --git a/tests/base_fix.rs b/tests/base_fix.rs index 295704f7c..0d0fc26ef 100644 --- a/tests/base_fix.rs +++ b/tests/base_fix.rs @@ -329,6 +329,16 @@ fn a_base_fix_obeys_the_self_merge_check() { result.stderr ); if check_exit == 1 { + let status = scenario.run(&["status"]); + assert!( + status + .stdout + .split("Ready for review") + .nth(1) + .is_some_and(|ready| ready.contains("Self-merge check held: base fix hold")), + "{}", + status.stdout + ); assert!(result.stderr.contains("base fix hold"), "{}", result.stderr); assert!(scenario.gh_calls_of("pr", "merge").is_empty()); } else { diff --git a/tests/pickup_run.rs b/tests/pickup_run.rs index 3d763a894..035b82eb1 100644 --- a/tests/pickup_run.rs +++ b/tests/pickup_run.rs @@ -2321,6 +2321,16 @@ fn pickup_leaves_an_open_self_merge_check_hold_for_the_day_shift() { ready_issue(&scenario, 8, &[]); scenario.agent_does_for(8, &agent_opens_pr(8, "main")); + fs::create_dir_all(scenario.path("home/.thirdshift/logs/acme/unrelated/activity.log")).unwrap(); + let pr_lists_for_held_issue = || { + scenario + .gh_calls_of("pr", "list") + .iter() + .filter(|args| args.iter().any(|arg| arg == "head:issue-7")) + .count() + }; + let prior_pr_lists = pr_lists_for_held_issue(); + let later = scenario.run(&["pickup", "no-merge"]); assert_eq!(later.code, Some(0), "{}", later.stderr); @@ -2335,6 +2345,7 @@ fn pickup_leaves_an_open_self_merge_check_hold_for_the_day_shift() { assert_eq!(scenario.issue_labels(7), [READY_FOR_AGENT]); assert_eq!(scenario.origin_git(&["rev-parse", "issue-7"]), held_head); assert_eq!(pr_from(&scenario, "issue-7")["state"], "OPEN"); + assert_eq!(pr_lists_for_held_issue() - prior_pr_lists, 1); } const RED: &str = r#"[{"name": "test", "conclusion": "failure"}]"#; From 75d1b5e3c0c9260cc53aef14e58cc1a8567c1e09 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Fri, 4 Dec 2026 12:53:57 -0500 Subject: [PATCH 21/27] Bind the Base fix assertion to its Ready for review PR --- tests/base_fix.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/tests/base_fix.rs b/tests/base_fix.rs index 0d0fc26ef..76e54be1c 100644 --- a/tests/base_fix.rs +++ b/tests/base_fix.rs @@ -329,13 +329,21 @@ fn a_base_fix_obeys_the_self_merge_check() { result.stderr ); if check_exit == 1 { - let status = scenario.run(&["status"]); + let status = scenario.run(&["status", "--group", "ready-for-review"]); + assert_eq!(status.code, Some(0), "{}", status.stderr); + let fix_url = fix["url"].as_str().unwrap(); + assert!( + status.stdout.lines().any(|line| { + line.contains("Base fix acme/widgets#8") && line.contains(fix_url) + }), + "{}", + status.stdout + ); assert!( status .stdout - .split("Ready for review") - .nth(1) - .is_some_and(|ready| ready.contains("Self-merge check held: base fix hold")), + .lines() + .any(|line| { line.trim() == "Self-merge check held: base fix hold" }), "{}", status.stdout ); From d4a462575a5887d5638803f859349d4897a05cc0 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Fri, 4 Dec 2026 13:02:24 -0500 Subject: [PATCH 22/27] Leave Self-merge check holds for the Day shift Skip held pull requests in Pickup and let Fix Pass repair conflicts after mergeability settles. Refs #2428. --- GLOSSARY.md | 2 ++ docs/guide.md | 3 +++ site/docs/index.html | 5 +++- site/how-it-works/index.html | 1 + src/branch.rs | 11 +++++++++ src/fix/selection.rs | 36 +++++++++++++-------------- src/github/review.rs | 17 ++++++++++--- src/logs.rs | 7 +++--- src/pickup.rs | 21 +++++++++++++--- src/pull_request.rs | 9 +++---- tests/fix_pass.rs | 29 ++++++++++++++++++++++ tests/pickup_run.rs | 48 ++++++++++++++++++++++++++++++++++++ 12 files changed, 154 insertions(+), 35 deletions(-) diff --git a/GLOSSARY.md b/GLOSSARY.md index 008b1c0bf..6d0e27239 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -163,6 +163,8 @@ _Avoid_: Weeding (former name), improve run, architecture run One invocation of the factory with no **Issue URL**: it takes the lowest-numbered **Ready issue** in the repository by default, the highest-numbered with `pickup.order` set to `highest-first` in the **User config** or `highest-first` on its command, and starts a **Spec run** or a **Ticket run** on it, as the command on that issue's URL would. It carries out no Process of its own: it selects the issue and dispatches its Built-in process. One issue per invocation, and thirdshift never schedules itself: the operating system's scheduler starts each one. Before dispatch, it reserves the issue across machines and rechecks that it is Ready with no intervening **Claim** since selection. The reservation lasts through the dispatched run's ending, then is released only by its owner; after a crash it waits for the **Day shift** to confirm the owner has stopped and release it. It is skipped, doing nothing, when the repository is at its **Command limit** on the machine, when there is no Ready issue, when the repository is at its **Failure limit**, or when no Ready issue it can reserve is left: an issue another Pickup run reserved, or whose selection went stale, is passed over for the next Ready issue in its order. Skipped is not a failure, and sends no **Run notification**. _Avoid_: watch, daemon, queue run, poll +Pickup passes over an issue whose open pull request's latest locally recorded Run ended at a **Self-merge check** hold, even after a hand-back. + **Security run**: One invocation of the factory with no **Issue URL**: a **Security audit** of the **Base branch**, then, for each **Security finding**, a session that tries to reproduce it with a proof-of-concept test in a throwaway worktree, and scores the severity of each one it reproduces. When a flag or the **User config** allows it, each reproduced finding is fixed by a **Ticket run**, or by a **Spec run** when one session isn't enough, on issues that say only what the fix changes. Its **Built-in process** owns the sequence of **Steps**, after the Pass has decided to go ahead. Every other finding waits for the **Day shift**, and one nothing reproduces is never fixed unattended. When closing is allowed too, a fix that merged closes the finding it fixed once its proof-of-concept test passes against the merged **Base branch**; anything else leaves the record for the Day shift. Like an **Architect run** with its plan, it reserves each fix across machines before marking it ready. It is skipped, like an Architect run, when the repository is at its **Command limit** on the machine or another Security run is running there, when the repository has a **Ready issue**, when a fix it dispatched failed and is still open, or when the Base branch hasn't changed since the last Security audit that finished. Past those, it fails at once, before any session, when the repository has Issues turned off. A finding still waiting for the Day shift holds off no audit, and an audit that finds it again keeps the outcome of its completed reproduction instead of reproducing it again. A failed fix is left for the Day shift; no later Security run or **Pickup run** retries it. _Avoid_: Fencing (former name), Secure run (it reads as a run that is secure), audit run, security pass diff --git a/docs/guide.md b/docs/guide.md index 401479d1e..185b16215 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -4486,6 +4486,9 @@ thirdshift pickup trust-author 'intake[bot]' # approve this author for one Pass Pickup has no Built-in process file. It selects and reserves the Ready issue, then starts `ticket-run` or `spec-run` as a command on that Issue URL would. +If its pull request is still open and the latest locally recorded Run on it +ended at a **Self-merge check** hold, Pickup leaves it for the Day shift and +looks for the next Ready issue, even after a hand-back. Which end of the issue numbers the pass takes is its order: `lowest-first` by default, `highest-first` with `pickup.order = "highest-first"` in the [User config](#user-config), or for one pass with `lowest-first` or `highest-first` on the command, which wins over the User config. Two schedules working through the same queue from opposite ends, one with each order, collide less often; the reservation below still protects either choice. diff --git a/site/docs/index.html b/site/docs/index.html index 07dedeb7c..8df119762 100644 --- a/site/docs/index.html +++ b/site/docs/index.html @@ -4182,7 +4182,10 @@ thirdshift pickup trust-author 'intake[bot]' # approve this author for one Pass

    Pickup has no Built-in process file. It selects and reserves the Ready issue, -then starts ticket-run or spec-run as a command on that Issue URL would.

    +then starts ticket-run or spec-run as a command on that Issue URL would. +If its pull request is still open and the latest locally recorded Run on it +ended at a Self-merge check hold, Pickup leaves it for the Day shift and +looks for the next Ready issue, even after a hand-back.

    Which end of the issue numbers the pass takes is its order: lowest-first by default, highest-first with pickup.order = "highest-first" in the User config, or for one pass with lowest-first or highest-first on the command, which wins over the User config. Two schedules working through the same queue from opposite ends, one with each order, collide less often; the reservation below still protects either choice.

    Add skip-author <login> (or --skip-author <login>) on each cron line to pass over issues written by that account, even a Trusted account. Repeat it for several accounts; logins match case-insensitively. The Pass logs #947 passed over: written by alice, whom this Pass skips and searches for the next Ready issue. A skipped Spec author excludes the whole Spec. A Spec run dispatched by this Pass also stops before a Ticket written by a skipped account, with the same failure handling as an untrusted Ticket author. These choices belong to this Pass, with no User config setting; explicitly running thirdshift <Issue URL> still runs the named issue under the usual trust checks. The word never makes an untrusted author eligible.

    Pickup uses trust.authors for its repository. Add diff --git a/site/how-it-works/index.html b/site/how-it-works/index.html index 7727fd5c1..d1e4f8632 100644 --- a/site/how-it-works/index.html +++ b/site/how-it-works/index.html @@ -270,6 +270,7 @@

    How thirdshift works

    07 / Where the next issue comes from

    Choose how the next work starts

    Every Pass checks the machine's GitHub Quota wait, then the quota, before other GitHub work or taking a Command-limit slot. It skips during a wait or below 500 REST requests or GraphQL points, with no stdout or Run notification. Pickup, Architect, Security, Triage without input, Review with --author, Fix without a pull request and issue-less Custom processes all follow this rule, from cron or by hand. The Activity log records each kind's changed reason; status and the Inbox show the wait beside last-fired Passes until reset. Budget Pass frequency per GitHub user across all hosts and repositories sharing that user's quota. After the quota, a Pass reads this machine's Plan usage, refreshing a stale Claude, Codex, Muse or agy snapshot with its non-billed read, and skips the same way when every route its sessions may take is held, with a banner in status and the Inbox naming the held routes and the earliest reset.

    +

    If an issue's pull request is still open and the latest locally recorded Run on it ended at a Self-merge check hold, Pickup leaves it for the Day shift and looks for the next Ready issue.

    Review Passes (review --author) and Fix Passes skip release-* pull requests targeting main, leaving their version-only heads to the Release run. Explicit thirdshift fix <pr-url> --no-merge --no-base-fix still repairs those pull requests.

    Review Passes recognize reviewed and pushed heads only in comments by the GitHub account thirdshift acts as. When an upper pull request lacks Review run fixes delivered to its base, its comment says it needs updating before merge; the author updates the stack.

    A Review Pass also checks the base Spec's issue when the PR targets an Issue branch, including numbered continuations. An in-progress Claim or issue reservation skips the PR with a line naming that Spec. When GitHub links no closing issue, local closing references in the body (Closes #7, Fixes #7, Resolves #7) get the same hold checks, so Ticket PRs into a non-default Spec branch stay with their Spec run.

    diff --git a/src/branch.rs b/src/branch.rs index d78a7ab7d..e1a52bdf7 100644 --- a/src/branch.rs +++ b/src/branch.rs @@ -105,6 +105,17 @@ pub fn can_continue(launch: &Git, github: &GitHub, issue: &IssueUrl) -> Result Result> { + Ok(latest(&GitHubAndOrigin { launch, github }, issue)? + .and_then(|latest| latest.pr) + .filter(|pr| pr.state == PrState::Open)) +} + /// What selection reads of origin, GitHub and the Launch directory. Each /// listing is by prefix, as git and GitHub answer it, so it can hold another /// issue's Issue branches. diff --git a/src/fix/selection.rs b/src/fix/selection.rs index fe1c2f6a2..c0a39074a 100644 --- a/src/fix/selection.rs +++ b/src/fix/selection.rs @@ -8,6 +8,7 @@ use crate::config::SignOffHold; use crate::github::GitHub; use crate::github::review::{FixCandidate, ListedPullRequest}; use crate::launch::Launch; +use crate::logs::{self, PullRequestAttribution}; use crate::review::{PullRequestUrl, Reservation}; use crate::worktree::Worktree; @@ -20,15 +21,12 @@ pub(super) fn take( hold_logs: Option<&std::path::Path>, passed_over: &mut Vec, ) -> Result> { - let holds = hold_logs - .filter(|_| behind.is_some()) - .map(crate::logs::self_merge_check_holds) - .transpose()?; let mut pass = Pass { launch, github, author, sign_off_hold, + self_merge_check_holds: hold_logs.map(logs::self_merge_check_holds).transpose()?, passed_over, }; @@ -36,9 +34,7 @@ pub(super) fn take( let base = launch.base.name(); for listed in github.fix_candidates(&launch.repo, base, author)? { let pr = &listed.pr; - let Some(candidate) = - github.observe_fix_candidate(pr, base, author, false, sign_off_hold)? - else { + let Some(candidate) = pass.observe(pr, false)? else { continue; }; if candidate.needs_repair { @@ -59,12 +55,6 @@ pub(super) fn take( }; let mut further_behind = Vec::new(); for (listed, candidate) in without_repairs { - if holds - .as_ref() - .is_some_and(|holds| holds.self_merge_check_held(&listed.pr.url)) - { - continue; - } let distance = github.fix_commits_behind(&listed.pr, &candidate)?; if distance >= behind.get() { further_behind.push((distance, listed, candidate.branch)); @@ -85,6 +75,7 @@ struct Pass<'a> { github: &'a GitHub, author: Option<&'a str>, sign_off_hold: Option<&'a SignOffHold>, + self_merge_check_holds: Option, passed_over: &'a mut Vec, } @@ -95,6 +86,19 @@ enum Recheck { } impl Pass<'_> { + fn observe(&self, pr: &PullRequestUrl, reserved: bool) -> Result> { + self.github.observe_fix_candidate( + pr, + self.launch.base.name(), + self.author, + reserved, + self.sign_off_hold, + self.self_merge_check_holds + .as_ref() + .is_some_and(|holds| holds.self_merge_check_held(&pr.url)), + ) + } + fn checkout_is_free(&mut self, pr: &PullRequestUrl, branch: &str) -> Result { let git = self.launch.directory.git(); let Some(path) = Worktree::occupying_checkout(git, branch)? else { @@ -124,11 +128,7 @@ impl Pass<'_> { let Some(held) = Reservation::take(git, self.github, pr)? else { return Ok(Recheck::Unavailable); }; - let base = self.launch.base.name(); - let Some(current) = - self.github - .observe_fix_candidate(pr, base, self.author, true, self.sign_off_hold)? - else { + let Some(current) = self.observe(pr, true)? else { return Ok(Recheck::Unavailable); }; if current.branch != branch { diff --git a/src/github/review.rs b/src/github/review.rs index d819fb92b..7915e6c5d 100644 --- a/src/github/review.rs +++ b/src/github/review.rs @@ -6,7 +6,7 @@ use super::{GitHub, Mergeable, PrSnapshot, PrState}; use crate::ci; use crate::config::SignOffHold; use crate::issue::IssueUrl; -use crate::pull_request::settled_sign_off_snapshot; +use crate::pull_request::settled_hold_snapshot; use crate::review::PullRequestUrl; #[derive(Clone)] @@ -99,6 +99,7 @@ impl GitHub { author: Option<&str>, reserved: bool, sign_off_hold: Option<&SignOffHold>, + self_merge_check_held: bool, ) -> Result> { let node = self.gh_json(&[ "api", @@ -123,7 +124,7 @@ impl GitHub { let Some(snapshot) = observe(None)? else { return Ok(None); }; - let needs_repair = if snapshot.mergeable == Mergeable::No { + let mut needs_repair = if snapshot.mergeable == Mergeable::No { true } else { let checks = self.checks_on(&pr.issue, &snapshot.head_commit)?; @@ -131,7 +132,7 @@ impl GitHub { { // Confirm the label after reading CI, on the same head. A // conflict still needs Repair, so let GitHub settle Unknown. - let current = settled_sign_off_snapshot(&snapshot.head_commit, || { + let current = settled_hold_snapshot(&snapshot.head_commit, || { observe(Some(hold.label.as_str())) })?; if current.is_none_or(|current| { @@ -142,6 +143,16 @@ impl GitHub { } ci::needs_repair(&checks) }; + if self_merge_check_held && !needs_repair { + // The recorded hold only rules out updates without a Repair. + // An unknown mergeability result can still settle as a conflict. + needs_repair = snapshot.mergeable == Mergeable::Unknown + && settled_hold_snapshot(&snapshot.head_commit, || observe(None))? + .is_some_and(|current| current.mergeable == Mergeable::No); + if !needs_repair { + return Ok(None); + } + } Ok(Some(FixCandidate { branch: snapshot.pr.head, needs_repair, diff --git a/src/logs.rs b/src/logs.rs index 9b89aa4a6..44ff8cace 100644 --- a/src/logs.rs +++ b/src/logs.rs @@ -28,6 +28,7 @@ pub(crate) mod pass_starts; mod process_identity; mod reading; pub(crate) use reading::Framing; +pub(crate) use reading::PullRequestAttribution; pub(crate) use reading::catalog; pub(crate) use reading::run_for_pull_request; mod recording; @@ -713,11 +714,9 @@ pub(crate) fn record_for_pull_request(root: &Path, url: &str) -> anyhow::Result< Ok(run_for_pull_request(root, url)?.map(|(path, _)| path)) } -pub(crate) fn self_merge_check_holds( - logs_dir: &Path, -) -> anyhow::Result { +pub(crate) fn self_merge_check_holds(logs_dir: &Path) -> anyhow::Result { let snapshot = reading::Snapshot::load(logs_dir, chrono::Local::now())?; - Ok(reading::PullRequestAttribution::new(&snapshot)) + Ok(PullRequestAttribution::new(&snapshot)) } /// Where this command and all its child Runs keep Session traces on `repo`. diff --git a/src/pickup.rs b/src/pickup.rs index ebc73aeb5..062e9ac63 100644 --- a/src/pickup.rs +++ b/src/pickup.rs @@ -191,10 +191,23 @@ pub fn run( let Some(reservation) = Reservation::take(directory.git(), &ready.listed.issue)? else { return Ok(None); }; - Ok( - crate::ready::refresh(directory.git(), ready, config.pickup_wait, &authors)? - .map(|ready| (ready, reservation)), - ) + let git = directory.git(); + let Some(ready) = crate::ready::refresh(git, ready, config.pickup_wait, &authors)? + else { + return Ok(None); + }; + let issue = &ready.listed.issue; + if ready.claim_generation > 0 + && let Some(pr) = crate::branch::open_pull_request(git, &GitHub::new(), issue)? + && logs::self_merge_check_holds(&config.logs_dir)?.self_merge_check_held(&pr.url) + { + crate::progress::step(format!( + "#{} passed over: PR {} is held by the Self-merge check", + issue.number, pr.url + )); + return Ok(None); + } + Ok(Some((ready, reservation))) }, ) } diff --git a/src/pull_request.rs b/src/pull_request.rs index ab3edd9bb..2c50a06e3 100644 --- a/src/pull_request.rs +++ b/src/pull_request.rs @@ -135,9 +135,9 @@ enum Readiness<'h> { Review { head: &'h str }, } -/// Settle mergeability while the same eligible head still carries the hold -/// label. The caller validates its own eligibility on every observation. -pub(crate) fn settled_sign_off_snapshot( +/// Settle mergeability on the same eligible head. When the caller requests a +/// hold label, stop waiting if it disappears. +pub(crate) fn settled_hold_snapshot( head: &str, mut observe: impl FnMut() -> Result>, ) -> Result> { @@ -469,8 +469,7 @@ impl PullRequest { /// Mergeability of the ready, watched head while it still has the label. pub fn sign_off_mergeability(&mut self, head: &str, label: &str) -> Result> { - let snapshot = - settled_sign_off_snapshot(head, || self.observe_ready(Some(label)).map(Some))?; + let snapshot = settled_hold_snapshot(head, || self.observe_ready(Some(label)).map(Some))?; Ok(snapshot .filter(|snapshot| snapshot.has_required_label) .map(|snapshot| snapshot.mergeable)) diff --git a/tests/fix_pass.rs b/tests/fix_pass.rs index 823a7b21b..2c1cd35fa 100644 --- a/tests/fix_pass.rs +++ b/tests/fix_pass.rs @@ -189,6 +189,35 @@ fn pull_request_held_by_self_merge_check() -> Scenario { scenario } +#[test] +fn fix_pass_repairs_a_conflict_after_mergeability_settles_on_a_self_merge_check_hold() { + let scenario = pull_request_held_by_self_merge_check(); + scenario.origin_has_commit("main", "feature.txt", "base", "Add base feature"); + let mut state = scenario.gh_state(); + state["prs"][0]["mergeable"] = "CONFLICTING".into(); + state["prs"][0]["unknown_polls"] = 1.into(); + scenario.write_gh_state(&state); + scenario.agent_does( + r#" +echo resolved > feature.txt +git add feature.txt +git commit -qm 'Resolve base conflict' +gh fake pr issue-7 mergeable '"MERGEABLE"' +"#, + ); + + let result = fix_pass(&scenario, &[]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert_eq!( + scenario.origin_file("issue-7", "feature.txt").as_deref(), + Some("resolved\n"), + "{}", + result.stderr + ); + assert_eq!(scenario.claude_calls().len(), 2); +} + #[test] fn a_fix_pass_can_self_merge_after_a_previous_self_merge_check_hold() { let scenario = pull_request_held_by_self_merge_check(); diff --git a/tests/pickup_run.rs b/tests/pickup_run.rs index 7fe949509..152674284 100644 --- a/tests/pickup_run.rs +++ b/tests/pickup_run.rs @@ -4157,6 +4157,54 @@ fn a_handed_back_open_pr_is_continued_using_its_base() { ); } +#[test] +fn pickup_leaves_an_open_pull_request_held_by_the_self_merge_check() { + let scenario = Scenario::new(); + let check = scenario.path("hold-check"); + support::write_executable(&check, "#!/bin/sh\necho Day shift decides\nexit 1\n"); + scenario.user_config_is(&format!( + "[merge]\nalways = true\nself_merge_check = {{ \"acme/widgets\" = {:?} }}\n", + check.to_str().unwrap() + )); + ready_issue(&scenario, 7, &[]); + scenario.agent_does_for(7, &agent_opens_pr(7, "main")); + let held = scenario.run(&["pickup"]); + let pr = pr_from(&scenario, "issue-7"); + assert_ended_with_pr( + &held, + &pr, + "ready for review waiting for Self-merge check held: Day shift decides", + ); + + // Even an issue back in the Ready search should leave this open PR waiting. + scenario.issue_labelled(7, &[READY_FOR_AGENT]); + scenario.issue_timeline( + 7, + &[ + (TimelineEvent::Labelled(IN_PROGRESS), 90), + (TimelineEvent::Unlabelled(IN_PROGRESS), 70), + (TimelineEvent::Labelled(READY_FOR_AGENT), 60), + ], + ); + ready_issue(&scenario, 8, &[]); + scenario.agent_does_for(8, &agent_opens_pr(8, "main")); + + let next = scenario.run(&["pickup", "no-merge"]); + + assert_eq!(next.code, Some(0), "{}", next.stderr); + assert!( + next.stderr.contains(&format!( + "{} is held by the Self-merge check", + pr["url"].as_str().unwrap() + )), + "{}", + next.stderr + ); + assert_ended_with_pr(&next, &pr_from(&scenario, "issue-8"), "ready for review"); + assert_eq!(scenario.claude_calls().len(), 2); + assert_eq!(scenario.issue_labels(7), [READY_FOR_AGENT]); +} + #[test] fn a_recent_hand_back_on_a_later_history_page_waits_for_settling() { let scenario = Scenario::new(); From 62d411a280264732176439b7b6b35101c069dac8 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Fri, 4 Dec 2026 13:12:55 -0500 Subject: [PATCH 23/27] Preserve and surface Self-merge check holds across Runs --- site/how-it-works/index.html | 2 +- site/index.html | 2 +- src/fix.rs | 8 ++-- src/logs/command_record.rs | 8 ++++ src/logs/reading/attribution.rs | 6 +-- src/logs/reading/inbox.rs | 38 +++++++++++++---- src/pass.rs | 2 + src/pickup.rs | 25 ++++-------- src/ready.rs | 72 ++++++++++++++++++++++++--------- tests/base_fix.rs | 34 ++++++++++++++++ tests/fix_pass.rs | 15 +++++++ tests/pickup_run.rs | 52 ++++++++++++++++++++++-- 12 files changed, 207 insertions(+), 57 deletions(-) diff --git a/site/how-it-works/index.html b/site/how-it-works/index.html index d1e4f8632..ce7978a5f 100644 --- a/site/how-it-works/index.html +++ b/site/how-it-works/index.html @@ -270,7 +270,7 @@

    How thirdshift works

    07 / Where the next issue comes from

    Choose how the next work starts

    Every Pass checks the machine's GitHub Quota wait, then the quota, before other GitHub work or taking a Command-limit slot. It skips during a wait or below 500 REST requests or GraphQL points, with no stdout or Run notification. Pickup, Architect, Security, Triage without input, Review with --author, Fix without a pull request and issue-less Custom processes all follow this rule, from cron or by hand. The Activity log records each kind's changed reason; status and the Inbox show the wait beside last-fired Passes until reset. Budget Pass frequency per GitHub user across all hosts and repositories sharing that user's quota. After the quota, a Pass reads this machine's Plan usage, refreshing a stale Claude, Codex, Muse or agy snapshot with its non-billed read, and skips the same way when every route its sessions may take is held, with a banner in status and the Inbox naming the held routes and the earliest reset.

    -

    If an issue's pull request is still open and the latest locally recorded Run on it ended at a Self-merge check hold, Pickup leaves it for the Day shift and looks for the next Ready issue.

    +

    If an issue's pull request is still open and the latest run recorded on this machine ended at a Self-merge check hold, Pickup leaves it for the Day shift and looks for the next Ready issue.

    Review Passes (review --author) and Fix Passes skip release-* pull requests targeting main, leaving their version-only heads to the Release run. Explicit thirdshift fix <pr-url> --no-merge --no-base-fix still repairs those pull requests.

    Review Passes recognize reviewed and pushed heads only in comments by the GitHub account thirdshift acts as. When an upper pull request lacks Review run fixes delivered to its base, its comment says it needs updating before merge; the author updates the stack.

    A Review Pass also checks the base Spec's issue when the PR targets an Issue branch, including numbered continuations. An in-progress Claim or issue reservation skips the PR with a line naming that Spec. When GitHub links no closing issue, local closing references in the body (Closes #7, Fixes #7, Resolves #7) get the same hold checks, so Ticket PRs into a non-default Spec branch stay with their Spec run.

    diff --git a/site/index.html b/site/index.html index fdc963fb6..f44facf9d 100644 --- a/site/index.html +++ b/site/index.html @@ -437,7 +437,7 @@

    Seven workflows

    Pickup runTake a Ready issue and put the factory to work.

    Add skip-author <login> or --skip-author <login> to a Pickup or Triage cron line to leave that author's issues alone, even for a Trusted account. Repeat it for several logins; matching ignores case. Pickup passes over the whole Spec when its author is skipped, and its dispatched Spec run stops before a skipped author's Ticket. Each exclusion logs why. Explicit Issue URL runs keep their usual trust checks.

    -

    A Pickup run takes the lowest-numbered Ready issue by default, the highest-numbered with pickup.order = "highest-first" or highest-first, after it has settled and while the repository is below its Failure limit: fewer open issues labelled agent-failed than pickup.failure_limit, 3 by default. A pull request waiting for review never holds it back. It immediately re-runs failed Base branch push CI once: green on re-run files a Flaky-test Ticket, and red again files an ordinary bug Ticket after 30 minutes. That CI-red Ticket leaves job names and log lines out of its title, body and later comments, and waits until you write the task and apply ready-for-agent. New failing commits are added to an open CI-red Ticket; one in needs-info does not block a new report. A run the host ran out of disk space under gets ready-for-agent back instead, as a host problem, not the issue's, and so does a Paused Command that no route had Plan usage left for, unless an untrusted edit leaves needs-triage or it is a Security fix. Other failed work stays with the Day shift, labelled agent-failed in place of in-progress, with a generated comment giving its cause, where it stopped, what was preserved and the machine, until you hand it back by applying ready-for-agent again, take agent-failed off, or close the issue. A Spec run only waiting on gated, blocked or out-of-repository Tickets is no failure: its Spec gets ready-for-agent back and a comment naming each undone Ticket and what it waits on, and a later Pickup run continues it once a Ticket can start. A run that leaves its pull request ready for review takes in-progress off and puts nothing back.

    +

    A Pickup run takes the lowest-numbered Ready issue by default, the highest-numbered with pickup.order = "highest-first" or highest-first, after it has settled and while the repository is below its Failure limit: fewer open issues labelled agent-failed than pickup.failure_limit, 3 by default. Pickup leaves an issue for the Day shift if its open pull request was held by the Self-merge check on this machine. Other Ready issues can still move ahead. It immediately re-runs failed Base branch push CI once: green on re-run files a Flaky-test Ticket, and red again files an ordinary bug Ticket after 30 minutes. That CI-red Ticket leaves job names and log lines out of its title, body and later comments, and waits until you write the task and apply ready-for-agent. New failing commits are added to an open CI-red Ticket; one in needs-info does not block a new report. A run the host ran out of disk space under gets ready-for-agent back instead, as a host problem, not the issue's, and so does a Paused Command that no route had Plan usage left for, unless an untrusted edit leaves needs-triage or it is a Security fix. Other failed work stays with the Day shift, labelled agent-failed in place of in-progress, with a generated comment giving its cause, where it stopped, what was preserved and the machine, until you hand it back by applying ready-for-agent again, take agent-failed off, or close the issue. A Spec run only waiting on gated, blocked or out-of-repository Tickets is no failure: its Spec gets ready-for-agent back and a comment naming each undone Ticket and what it waits on, and a later Pickup run continues it once a Ticket can start. A run that leaves its pull request ready for review takes in-progress off and puts nothing back.

    diff --git a/src/fix.rs b/src/fix.rs index 5200833e7..c0ca8cea5 100644 --- a/src/fix.rs +++ b/src/fix.rs @@ -6,7 +6,7 @@ use anyhow::Context; use chrono::Utc; use crate::args::{self, FixArgs}; -use crate::asks::{Asks, Flags}; +use crate::asks::{Asks, Flags, SelfMergeCheckAsk}; use crate::base_fix::{BaseFix, BaseFixAsk}; use crate::child_run::ChildAsks; use crate::config::UserConfig; @@ -78,10 +78,8 @@ pub(crate) fn run( author.as_deref(), behind, sign_off_hold, - command - .flags - .merge_check_for(&launch.repo, config) - .map(|_| config.logs_dir.as_path()), + (command.flags.self_merge_check != Some(SelfMergeCheckAsk::Skip)) + .then_some(config.logs_dir.as_path()), &mut passed_over, )? { let selected = FixArgs { diff --git a/src/logs/command_record.rs b/src/logs/command_record.rs index 226d3559e..ee1c1ed3c 100644 --- a/src/logs/command_record.rs +++ b/src/logs/command_record.rs @@ -425,6 +425,14 @@ impl StageName { } impl CommandRecord { + pub(super) fn held_by_self_merge_check(&self) -> bool { + self.outcome.as_deref() == Some("ready for review") + && self + .cause + .as_deref() + .is_some_and(|cause| cause.starts_with(crate::self_merge_check::HOLD_PREFIX)) + } + /// The Custom process's own name. An older record with no `process_name` /// falls back to the selector in `name`. pub(super) fn process_label(&self) -> Option<&str> { diff --git a/src/logs/reading/attribution.rs b/src/logs/reading/attribution.rs index cc362690b..94b2ccc03 100644 --- a/src/logs/reading/attribution.rs +++ b/src/logs/reading/attribution.rs @@ -93,11 +93,7 @@ impl PullRequestAttribution { .push(Candidate { identity: CommandIdentity::of(command), started_at: DateTime::parse_from_rfc3339(&command.record.started_at).ok(), - held_by_self_merge_check: command.record.outcome.as_deref() - == Some("ready for review") - && command.record.cause.as_deref().is_some_and(|cause| { - cause.starts_with(crate::self_merge_check::HOLD_PREFIX) - }), + held_by_self_merge_check: command.record.held_by_self_merge_check(), }); } // Snapshot has already excluded orphaned and unmatched child records. diff --git a/src/logs/reading/inbox.rs b/src/logs/reading/inbox.rs index 22c6b80fa..67e4a99dc 100644 --- a/src/logs/reading/inbox.rs +++ b/src/logs/reading/inbox.rs @@ -334,6 +334,27 @@ impl<'a> Captured<'a> { } } + /// A held Base fix needs its own pull request row even when the Run + /// waiting for that fix is itself in Needs you. + fn collect_held_base_fixes( + command: &'a Command, + local: &mut BTreeMap<&'a Path, LocalFacts>, + rows: &mut Vec, + ) { + for child in &command.children { + if child.record.kind == "Base fix" + && child.record.pull_request.is_some() + && child.record.held_by_self_merge_check() + { + rows.push(Self::new(Observation::Record(child), local)); + } + Self::collect_held_base_fixes(child, local, rows); + } + for child in &command.dispatched { + Self::collect_held_base_fixes(child, local, rows); + } + } + /// A failed Pass is answered by its failed dispatched work; a Finding /// waits for its own private records rather than a successful fix. fn github_records(&self) -> Vec<&'a crate::logs::command_record::CommandRecord> { @@ -473,16 +494,18 @@ pub(super) fn evaluate<'a>( // representable timestamp is inside the requested retention period. let cutoff = now.checked_sub_signed(chrono::Duration::days(days)); let mut local = BTreeMap::new(); + let mut held_base_fixes = Vec::new(); let captured: Vec<_> = entries .iter() .map(|entry| { - Captured::new( - match entry { - Entry::Record(command) => Observation::Record(command), - Entry::History(command) => Observation::History(command), - }, - &mut local, - ) + let observation = match entry { + Entry::Record(command) => { + Captured::collect_held_base_fixes(command, &mut local, &mut held_base_fixes); + Observation::Record(command) + } + Entry::History(command) => Observation::History(command), + }; + Captured::new(observation, &mut local) }) .collect(); let observations: Vec<_> = captured @@ -501,6 +524,7 @@ pub(super) fn evaluate<'a>( && (carried.is_none() || record_pull_request(&run.command) != carried) })) }) + .chain(&held_base_fixes) .collect(); let starts: Vec<_> = observations .iter() diff --git a/src/pass.rs b/src/pass.rs index 4a9ebbb86..f2c9e56be 100644 --- a/src/pass.rs +++ b/src/pass.rs @@ -250,6 +250,7 @@ impl Outside for LaunchAndGitHub<'_> { order, past, self.authors, + &self.config.logs_dir, )? { if let Some(reason) = self .skip_authors @@ -273,6 +274,7 @@ impl Outside for LaunchAndGitHub<'_> { self.repo, self.config.pickup_wait, self.authors, + &self.config.logs_dir, ) } diff --git a/src/pickup.rs b/src/pickup.rs index 062e9ac63..5bafe6abf 100644 --- a/src/pickup.rs +++ b/src/pickup.rs @@ -191,23 +191,14 @@ pub fn run( let Some(reservation) = Reservation::take(directory.git(), &ready.listed.issue)? else { return Ok(None); }; - let git = directory.git(); - let Some(ready) = crate::ready::refresh(git, ready, config.pickup_wait, &authors)? - else { - return Ok(None); - }; - let issue = &ready.listed.issue; - if ready.claim_generation > 0 - && let Some(pr) = crate::branch::open_pull_request(git, &GitHub::new(), issue)? - && logs::self_merge_check_holds(&config.logs_dir)?.self_merge_check_held(&pr.url) - { - crate::progress::step(format!( - "#{} passed over: PR {} is held by the Self-merge check", - issue.number, pr.url - )); - return Ok(None); - } - Ok(Some((ready, reservation))) + Ok(crate::ready::refresh( + directory.git(), + ready, + config.pickup_wait, + &authors, + &config.logs_dir, + )? + .map(|ready| (ready, reservation))) }, ) } diff --git a/src/ready.rs b/src/ready.rs index 23a832911..bc04d093f 100644 --- a/src/ready.rs +++ b/src/ready.rs @@ -5,6 +5,8 @@ //! definition. An Architect run also waits for an issue that meets every //! Ready issue condition except settling. +use std::path::Path; + use anyhow::Result; use chrono::{DateTime, TimeDelta, Utc}; @@ -104,9 +106,17 @@ pub fn first( order: PickupOrder, past: Option, authors: &[String], + logs_dir: &Path, ) -> Result> { Ok( - match search(launch, repo, wait, Settling::Wait, order, past, authors)? { + match search( + &GitHubAndOrigin::new(launch, authors, logs_dir), + repo, + wait, + Settling::Wait, + order, + past, + )? { Some(PriorityIssue::Ready(ready)) => Some(ready), _ => None, }, @@ -120,38 +130,32 @@ pub fn before_architect( repo: &Repo, wait: TimeDelta, authors: &[String], + logs_dir: &Path, ) -> Result> { search( - launch, + &GitHubAndOrigin::new(launch, authors, logs_dir), repo, wait, Settling::Include, PickupOrder::LowestFirst, None, - authors, ) } fn search( - launch: &Git, + reads: &GitHubAndOrigin<'_>, repo: &Repo, wait: TimeDelta, settling: Settling, order: PickupOrder, past: Option, - authors: &[String], ) -> Result> { - let reads = GitHubAndOrigin { - launch, - github: GitHub::new(), - authors, - }; let listed = reads .github .open_candidate_issues(&repo.slug(), READY_FOR_AGENT)?; crate::logs::listing_disagreement(repo, &listed); Search::new( - &reads, + reads, listed.issues, Utc::now(), wait, @@ -173,12 +177,9 @@ pub fn refresh( selected: ReadyIssue, wait: TimeDelta, authors: &[String], + logs_dir: &Path, ) -> Result> { - let reads = GitHubAndOrigin { - launch, - github: GitHub::new(), - authors, - }; + let reads = GitHubAndOrigin::new(launch, authors, logs_dir); let issue = selected.listed.issue; let current = reads.github.issue(&issue)?; if !current.is_open || !current.labels.has(READY_FOR_AGENT) { @@ -210,6 +211,8 @@ trait Reads { fn candidate(&self, issue: &IssueUrl) -> Result; /// What shows `issue` was ever started, if it was. fn started(&self, issue: &IssueUrl) -> Result>; + /// The open pull request waiting on a recorded Self-merge check hold. + fn held_pull_request(&self, issue: &IssueUrl) -> Result>; /// Whether the latest Issue branch can be continued under ADR-0002. fn can_continue(&self, issue: &IssueUrl) -> Result; /// The Tickets of `spec`, an issue with sub-issues, as a Spec run reads @@ -223,6 +226,18 @@ struct GitHubAndOrigin<'a> { launch: &'a Git, github: GitHub, authors: &'a [String], + logs_dir: &'a Path, +} + +impl<'a> GitHubAndOrigin<'a> { + fn new(launch: &'a Git, authors: &'a [String], logs_dir: &'a Path) -> Self { + Self { + launch, + github: GitHub::new(), + authors, + logs_dir, + } + } } impl Reads for GitHubAndOrigin<'_> { @@ -241,6 +256,14 @@ impl Reads for GitHubAndOrigin<'_> { branch::started(self.launch, &self.github, issue) } + fn held_pull_request(&self, issue: &IssueUrl) -> Result> { + let Some(pr) = branch::open_pull_request(self.launch, &self.github, issue)? else { + return Ok(None); + }; + let holds = crate::logs::self_merge_check_holds(self.logs_dir)?; + Ok(holds.self_merge_check_held(&pr.url).then_some(pr.url)) + } + fn can_continue(&self, issue: &IssueUrl) -> Result { branch::can_continue(self.launch, &self.github, issue) } @@ -284,6 +307,7 @@ enum Reason { evidence: Started, never_claimed: bool, }, + HeldBySelfMergeCheck(String), /// It is a Spec whose Tickets are all closed: the Spec run it would be /// dispatched as refuses it, having nothing to do. TicketsClosed, @@ -462,6 +486,9 @@ impl<'a, R: Reads, P: FnMut(String)> Search<'a, R, P> { ) } } + Reason::HeldBySelfMergeCheck(pr) => { + format!("passed over: PR {pr} is held by the Self-merge check") + } Reason::TicketsClosed => "every Ticket is closed".to_string(), Reason::NoStartableTicket(tickets) => { let spec = &self.candidates[at].issue; @@ -572,8 +599,8 @@ fn standing_of( if let Some(check) = reads.issue_trust(&candidate.issue)? { return passed_over(Reason::Untrusted(check)); } - if let Some(started) = reads.started(&candidate.issue)? - && !read.handed_back + if !read.handed_back + && let Some(started) = reads.started(&candidate.issue)? { return passed_over(Reason::Started { evidence: started, @@ -583,6 +610,11 @@ fn standing_of( if read.claimed { return passed_over(Reason::Claimed); } + if read.handed_back + && let Some(pr) = reads.held_pull_request(&candidate.issue)? + { + return passed_over(Reason::HeldBySelfMergeCheck(pr)); + } let continuing_closed_spec = if spec_run::all_closed(read.sub_issue_is_open.iter().copied()) { if !reads.can_continue(&candidate.issue)? { return passed_over(Reason::TicketsClosed); @@ -719,6 +751,10 @@ mod tests { Ok(self.facts(issue).and_then(|facts| facts.started.clone())) } + fn held_pull_request(&self, _issue: &IssueUrl) -> Result> { + Ok(None) + } + fn can_continue(&self, _issue: &IssueUrl) -> Result { Ok(false) } diff --git a/tests/base_fix.rs b/tests/base_fix.rs index 295704f7c..ff99b8ea3 100644 --- a/tests/base_fix.rs +++ b/tests/base_fix.rs @@ -338,6 +338,40 @@ fn a_base_fix_obeys_the_self_merge_check() { } } +#[test] +fn a_held_base_fix_has_its_own_ready_for_review_row() { + let scenario = Scenario::new(); + scenario.origin_has_commit( + "main", + "check", + "#!/bin/sh\necho base fix hold\nexit 1\n", + "Add check", + ); + scenario.user_config_is("[merge]\nself_merge_check = { \"acme/widgets\" = \"check\" }\n"); + scenario.agent_does(RUN_OPENS_PR_WITH_INHERITED_FAILURE); + scenario.agent_does_for(8, &format!("{BASE_FIX_OPENS_PR}{GREEN_ON_HEAD}")); + let held = scenario.run(&[&scenario.issue_url(7), "base-fix"]); + assert!(held.stderr.contains("base fix hold"), "{}", held.stderr); + let state = scenario.gh_state(); + let fix = &state["prs"][1]; + assert_eq!(fix["state"], "OPEN"); + assert_eq!(fix["isDraft"], false); + let output = scenario.run(&["status", "--local", "--json", "--group", "ready-for-review"]); + assert_eq!(output.code, Some(0), "{}", output.stderr); + let status: serde_json::Value = serde_json::from_str(&output.stdout).unwrap(); + assert!( + status["commands"] + .as_array() + .unwrap() + .iter() + .any(|row| row["pull_request"] == fix["url"] + && row["cause"] + .as_str() + .is_some_and(|cause| cause.contains("base fix hold"))), + "{status:#}" + ); +} + #[test] fn the_base_fix_merges_into_the_runs_base_branch_whatever_the_launch_directory_has_checked_out() { let scenario = Scenario::new(); diff --git a/tests/fix_pass.rs b/tests/fix_pass.rs index 2c1cd35fa..3d912c12d 100644 --- a/tests/fix_pass.rs +++ b/tests/fix_pass.rs @@ -189,6 +189,21 @@ fn pull_request_held_by_self_merge_check() -> Scenario { scenario } +#[test] +fn removing_check_config_does_not_release_a_recorded_hold() { + let scenario = pull_request_held_by_self_merge_check(); + let head = scenario.origin_git(&["rev-parse", "issue-7"]); + scenario.user_config_is(""); + let result = fix_pass(&scenario, &["behind", "2"]); + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!( + result.stderr.contains("no eligible pull request"), + "{}", + result.stderr + ); + assert_eq!(scenario.origin_git(&["rev-parse", "issue-7"]), head); +} + #[test] fn fix_pass_repairs_a_conflict_after_mergeability_settles_on_a_self_merge_check_hold() { let scenario = pull_request_held_by_self_merge_check(); diff --git a/tests/pickup_run.rs b/tests/pickup_run.rs index 152674284..3d2c509b1 100644 --- a/tests/pickup_run.rs +++ b/tests/pickup_run.rs @@ -4157,8 +4157,7 @@ fn a_handed_back_open_pr_is_continued_using_its_base() { ); } -#[test] -fn pickup_leaves_an_open_pull_request_held_by_the_self_merge_check() { +fn pickup_with_a_handed_back_self_merge_check_hold() -> Scenario { let scenario = Scenario::new(); let check = scenario.path("hold-check"); support::write_executable(&check, "#!/bin/sh\necho Day shift decides\nexit 1\n"); @@ -4186,6 +4185,24 @@ fn pickup_leaves_an_open_pull_request_held_by_the_self_merge_check() { (TimelineEvent::Labelled(READY_FOR_AGENT), 60), ], ); + scenario +} + +#[test] +fn pickup_leaves_an_open_pull_request_held_by_the_self_merge_check() { + let scenario = pickup_with_a_handed_back_self_merge_check_hold(); + let pr = pr_from(&scenario, "issue-7"); + let architect = scenario.run(&["architect"]); + let security = scenario.run(&["secure"]); + let activity = activity_log(&scenario); + assert!( + !activity.contains("Architect run skipped: Ready issue #7") + && !activity.contains("Security run skipped: Ready issue #7"), + "{activity}\nArchitect: {}\nSecurity: {}", + architect.stderr, + security.stderr + ); + let agent_calls = scenario.claude_calls().len(); ready_issue(&scenario, 8, &[]); scenario.agent_does_for(8, &agent_opens_pr(8, "main")); @@ -4201,10 +4218,39 @@ fn pickup_leaves_an_open_pull_request_held_by_the_self_merge_check() { next.stderr ); assert_ended_with_pr(&next, &pr_from(&scenario, "issue-8"), "ready for review"); - assert_eq!(scenario.claude_calls().len(), 2); + assert_eq!(scenario.claude_calls().len(), agent_calls + 1); assert_eq!(scenario.issue_labels(7), [READY_FOR_AGENT]); } +#[test] +fn pickup_reports_the_hold_as_the_reason_no_issue_was_taken() { + let scenario = pickup_with_a_handed_back_self_merge_check_hold(); + let waiting = scenario.run(&["pickup", "no-merge"]); + assert_eq!(waiting.code, Some(0), "{}", waiting.stderr); + assert!(waiting.stdout.is_empty(), "{}", waiting.stdout); + assert!( + waiting.stderr.contains("is held by the Self-merge check"), + "{}", + waiting.stderr + ); + assert!( + !waiting + .stderr + .contains("is reserved by another run or is no longer Ready"), + "{}", + waiting.stderr + ); + assert!( + !waiting + .stderr + .contains("check refs/heads/thirdshift/pickup/7"), + "{}", + waiting.stderr + ); + let activity = activity_log(&scenario); + assert!(!activity.contains("it can reserve"), "{activity}"); +} + #[test] fn a_recent_hand_back_on_a_later_history_page_waits_for_settling() { let scenario = Scenario::new(); From 349ea988c0c3ed84b9b2cb3b6df96ae6c6e7ba8f Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Fri, 4 Dec 2026 13:22:14 -0500 Subject: [PATCH 24/27] Read hold history from repository Command records --- GLOSSARY.md | 4 ++-- docs/guide.md | 4 +--- site/docs/index.html | 6 ++---- src/fix/selection.rs | 4 +++- src/logs.rs | 8 +++++--- src/logs/reading.rs | 36 +++++++++++++++++++++++++++++++-- src/logs/reading/attribution.rs | 13 ++++++++---- src/ready.rs | 2 +- tests/fix_pass.rs | 24 ++++++++++++++++++++++ tests/pickup_run.rs | 14 +++++++++++++ 10 files changed, 95 insertions(+), 20 deletions(-) diff --git a/GLOSSARY.md b/GLOSSARY.md index 6d0e27239..d1a869311 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -30,6 +30,8 @@ _Avoid_: task, sub-task An open issue a **Pickup run** may take: labelled `ready-for-agent`, written by a **Trusted account** or a named author, with its most recent `ready-for-agent` labelling made by a Trusted account and with later title and body edits only by Trusted accounts or the authorized author, with no label that makes an **Unready Ticket** and no **Claim**, not a sub-issue, not a **Base fix**'s or a **Security run**'s fix issue, with no open blocker, either never started (no **Issue branch** and no pull request) or handed back at or after the last **Claim** ended, as recorded in its label history: by the **Day shift** applying `ready-for-agent`, or by thirdshift putting it back on a Spec whose Spec run ended only waiting, which it does only when only Trusted accounts or the authorized author have edited the Spec since its last Trusted `ready-for-agent` labelling, and otherwise labels the Spec `needs-triage`, and only when each of its open Tickets in its repository passes the Trusted account check for Tickets, and otherwise labels it `agent-failed`, left untouched long enough that whoever is shaping it has finished, and, if it is a **Spec**, with a **Startable Ticket** or with every Ticket closed and a resumable **Spec branch** on `origin` (the latest numbered branch, with no PR or an open PR). A hand-back made in the same edit as the Claim's removal counts in either listed order at that timestamp; a Claim applied at the same timestamp leaves the issue Claimed. On a Spec, the label says its Tickets are published. A `ready-for-agent` Ticket inside a Spec is not one: it is reached through its Spec, when the Spec is itself a Ready issue. _Avoid_: queued issue, backlog item +An open pull request whose latest locally recorded Run ended at a **Self-merge check** hold keeps its issue waiting for the **Day shift**, even after a hand-back. + **Trusted account**: The repository's owner, a member of the organization that owns it, a collaborator on it, or the account thirdshift's own `gh` credentials act as, such as a GitHub App's `[bot]`: an issue author's `authorAssociation` of `OWNER`, `MEMBER` or `COLLABORATOR`, or that login; for an actor with no association field, and for an issue author with an untrusted one, equivalent repository membership or that login. The rule is fixed, with no **User config** setting. A **Spec run** stops before starting the Ticket run of a **Ticket** whose author is neither a Trusted account nor a named author, or whose title or body anyone else edited after the later of the Ticket's and its Spec's last `ready-for-agent` labellings by a Trusted account. A Ticket needs no `ready-for-agent` labelling of its own: the labelling that counts is its Spec's, checked when a **Pickup run** takes the Spec. **Ticket runs** and **Spec runs** check their issue again before a session, **Resume**, push or **Self-merge**. Title or body edits since a few minutes before the run started may come only from Trusted accounts or the issue's authorized author. A **Fix run** accepts only a Trusted account's edits on every linked closing issue (retaining previously linked ones during that run) around every **Repair**, **Resume**, push and **Self-merge**, and a **Review run** or pull-request **Custom process** accepts only a Trusted account's edits on every linked closing issue before writing `.thirdshift-review-input.md`, before and after each **Step**, session, **Repair** and **Resume**, before **Delivery** pushes fixes or posts its comment, and through any **Self-merge**, without drafting the pull request. The named-author exception does not apply to those pull-request checks. A **Review run**, a **Fix run**, or a pull-request **Custom process**, including one started as a **Pass**, also stops before using a linked closing issue unless that issue's author is a Trusted account and no account that is not one has edited its title or body. Each session that works on an issue gets the issue from thirdshift, written into its worktree again before the session starts: its title, its body, and only the comments by Trusted accounts and the issue's authorized author, each other comment replaced by a line saying it was left out. The **Session prompt** and **Factory skills** tell the session to work from that and not to fetch the issue's comments itself. @@ -163,8 +165,6 @@ _Avoid_: Weeding (former name), improve run, architecture run One invocation of the factory with no **Issue URL**: it takes the lowest-numbered **Ready issue** in the repository by default, the highest-numbered with `pickup.order` set to `highest-first` in the **User config** or `highest-first` on its command, and starts a **Spec run** or a **Ticket run** on it, as the command on that issue's URL would. It carries out no Process of its own: it selects the issue and dispatches its Built-in process. One issue per invocation, and thirdshift never schedules itself: the operating system's scheduler starts each one. Before dispatch, it reserves the issue across machines and rechecks that it is Ready with no intervening **Claim** since selection. The reservation lasts through the dispatched run's ending, then is released only by its owner; after a crash it waits for the **Day shift** to confirm the owner has stopped and release it. It is skipped, doing nothing, when the repository is at its **Command limit** on the machine, when there is no Ready issue, when the repository is at its **Failure limit**, or when no Ready issue it can reserve is left: an issue another Pickup run reserved, or whose selection went stale, is passed over for the next Ready issue in its order. Skipped is not a failure, and sends no **Run notification**. _Avoid_: watch, daemon, queue run, poll -Pickup passes over an issue whose open pull request's latest locally recorded Run ended at a **Self-merge check** hold, even after a hand-back. - **Security run**: One invocation of the factory with no **Issue URL**: a **Security audit** of the **Base branch**, then, for each **Security finding**, a session that tries to reproduce it with a proof-of-concept test in a throwaway worktree, and scores the severity of each one it reproduces. When a flag or the **User config** allows it, each reproduced finding is fixed by a **Ticket run**, or by a **Spec run** when one session isn't enough, on issues that say only what the fix changes. Its **Built-in process** owns the sequence of **Steps**, after the Pass has decided to go ahead. Every other finding waits for the **Day shift**, and one nothing reproduces is never fixed unattended. When closing is allowed too, a fix that merged closes the finding it fixed once its proof-of-concept test passes against the merged **Base branch**; anything else leaves the record for the Day shift. Like an **Architect run** with its plan, it reserves each fix across machines before marking it ready. It is skipped, like an Architect run, when the repository is at its **Command limit** on the machine or another Security run is running there, when the repository has a **Ready issue**, when a fix it dispatched failed and is still open, or when the Base branch hasn't changed since the last Security audit that finished. Past those, it fails at once, before any session, when the repository has Issues turned off. A finding still waiting for the Day shift holds off no audit, and an audit that finds it again keeps the outcome of its completed reproduction instead of reproducing it again. A failed fix is left for the Day shift; no later Security run or **Pickup run** retries it. _Avoid_: Fencing (former name), Secure run (it reads as a run that is secure), audit run, security pass diff --git a/docs/guide.md b/docs/guide.md index 185b16215..0e974c754 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -4486,9 +4486,6 @@ thirdshift pickup trust-author 'intake[bot]' # approve this author for one Pass Pickup has no Built-in process file. It selects and reserves the Ready issue, then starts `ticket-run` or `spec-run` as a command on that Issue URL would. -If its pull request is still open and the latest locally recorded Run on it -ended at a **Self-merge check** hold, Pickup leaves it for the Day shift and -looks for the next Ready issue, even after a hand-back. Which end of the issue numbers the pass takes is its order: `lowest-first` by default, `highest-first` with `pickup.order = "highest-first"` in the [User config](#user-config), or for one pass with `lowest-first` or `highest-first` on the command, which wins over the User config. Two schedules working through the same queue from opposite ends, one with each order, collide less often; the reservation below still protects either choice. @@ -4507,6 +4504,7 @@ A Ready issue is an open issue that: - is not a sub-issue. A sub-issue is a **Ticket** of a **Spec**, and is never run on its own, whatever the Spec's labels: it is reached through its Spec, when the Spec is itself a Ready issue, so its work always goes through the **Spec branch**. Labelling one Ticket never promotes its Spec, either; - is not labelled `base-fix` or `security-fix`: the Ticket run that opened a [Base fix](#base-fix)'s issue, or the Security run that dispatched a fix, owns it. A failed Security fix is still passed over if GitHub prevented its Claim from being made; - has no open blocker, by GitHub's "blocked by" links, never the text of its body. Once every blocker is closed, it can be taken; +- has no open pull request whose latest locally recorded Run ended at a **Self-merge check** hold. The hold keeps the issue with the Day shift even after a hand-back. Pickup looks for the next Ready issue. Architect and Security use the same readiness rule when deciding whether to defer to Ready work; - either was never started (no **Issue branch** on `origin` and no pull request from one, open, merged or closed), or you handed it back by applying `ready-for-agent` at or after its last [Claim](#the-claim) ended. A Spec whose Spec run ended only waiting is handed back by thirdshift the same way, unless someone other than a Trusted account or the Spec's authorized author edited its title or body after its last Trusted Ready labelling. For started work, the full label history must show an earlier `in-progress` application and its removal, with `ready-for-agent` applied at that removal's timestamp or later. A swap made in one edit counts in either listed order; a new Claim applied at the same timestamp leaves the issue Claimed. Work never Claimed, or without that hand-back, stays with you. An eligible branch with no PR or an open PR follows the existing [Continuation](#continuation) rule; merged or closed PRs follow ADR 0002 and start a fresh numbered branch. This is deliberate hand-back, not automatic retries; - if it is a **Spec** whose **Tickets** are all closed, its Spec run can continue its Spec branch on `origin` under [ADR-0002](adr/0002-existing-issue-branch-means-continue.md): the latest numbered branch is present, with no PR or an open PR. The dispatched Spec run goes straight to the Spec review and the Spec PR's Delivery and Repair loop, without running a Ticket again. A PR without its branch, or a retained branch whose latest PR is closed or merged, does not qualify. Without a resumable branch, waiting never makes it a Ready issue: close it, or take its `ready-for-agent` off; - is settled: by default, five minutes have passed since the latest of `ready-for-agent` being applied to it, a sub-issue being added to it or removed, and a "blocked by" link being added to it or removed. So a Spec is not taken while its Tickets are still being attached. These are read from the issue's timeline, since adding a sub-issue does not change the issue's update time, and `pickup.wait_minutes` in the [User config](#user-config) sets the window in whole minutes from 0 up, within the supported duration range; 0 disables waiting. An Architect run also waits for an issue that meets every other Ready issue condition while it is settling. A later pass takes the issue once it has settled; diff --git a/site/docs/index.html b/site/docs/index.html index 8df119762..1d778d36d 100644 --- a/site/docs/index.html +++ b/site/docs/index.html @@ -4182,10 +4182,7 @@ thirdshift pickup trust-author 'intake[bot]' # approve this author for one Pass

    Pickup has no Built-in process file. It selects and reserves the Ready issue, -then starts ticket-run or spec-run as a command on that Issue URL would. -If its pull request is still open and the latest locally recorded Run on it -ended at a Self-merge check hold, Pickup leaves it for the Day shift and -looks for the next Ready issue, even after a hand-back.

    +then starts ticket-run or spec-run as a command on that Issue URL would.

    Which end of the issue numbers the pass takes is its order: lowest-first by default, highest-first with pickup.order = "highest-first" in the User config, or for one pass with lowest-first or highest-first on the command, which wins over the User config. Two schedules working through the same queue from opposite ends, one with each order, collide less often; the reservation below still protects either choice.

    Add skip-author <login> (or --skip-author <login>) on each cron line to pass over issues written by that account, even a Trusted account. Repeat it for several accounts; logins match case-insensitively. The Pass logs #947 passed over: written by alice, whom this Pass skips and searches for the next Ready issue. A skipped Spec author excludes the whole Spec. A Spec run dispatched by this Pass also stops before a Ticket written by a skipped account, with the same failure handling as an untrusted Ticket author. These choices belong to this Pass, with no User config setting; explicitly running thirdshift <Issue URL> still runs the named issue under the usual trust checks. The word never makes an untrusted author eligible.

    Pickup uses trust.authors for its repository. Add @@ -4200,6 +4197,7 @@

  • is not a sub-issue. A sub-issue is a Ticket of a Spec, and is never run on its own, whatever the Spec's labels: it is reached through its Spec, when the Spec is itself a Ready issue, so its work always goes through the Spec branch. Labelling one Ticket never promotes its Spec, either;
  • is not labelled base-fix or security-fix: the Ticket run that opened a Base fix's issue, or the Security run that dispatched a fix, owns it. A failed Security fix is still passed over if GitHub prevented its Claim from being made;
  • has no open blocker, by GitHub's "blocked by" links, never the text of its body. Once every blocker is closed, it can be taken;
  • +
  • has no open pull request whose latest locally recorded Run ended at a Self-merge check hold. The hold keeps the issue with the Day shift even after a hand-back. Pickup looks for the next Ready issue. Architect and Security use the same readiness rule when deciding whether to defer to Ready work;
  • either was never started (no Issue branch on origin and no pull request from one, open, merged or closed), or you handed it back by applying ready-for-agent at or after its last Claim ended. A Spec whose Spec run ended only waiting is handed back by thirdshift the same way, unless someone other than a Trusted account or the Spec's authorized author edited its title or body after its last Trusted Ready labelling. For started work, the full label history must show an earlier in-progress application and its removal, with ready-for-agent applied at that removal's timestamp or later. A swap made in one edit counts in either listed order; a new Claim applied at the same timestamp leaves the issue Claimed. Work never Claimed, or without that hand-back, stays with you. An eligible branch with no PR or an open PR follows the existing Continuation rule; merged or closed PRs follow ADR 0002 and start a fresh numbered branch. This is deliberate hand-back, not automatic retries;
  • if it is a Spec whose Tickets are all closed, its Spec run can continue its Spec branch on origin under ADR-0002: the latest numbered branch is present, with no PR or an open PR. The dispatched Spec run goes straight to the Spec review and the Spec PR's Delivery and Repair loop, without running a Ticket again. A PR without its branch, or a retained branch whose latest PR is closed or merged, does not qualify. Without a resumable branch, waiting never makes it a Ready issue: close it, or take its ready-for-agent off;
  • is settled: by default, five minutes have passed since the latest of ready-for-agent being applied to it, a sub-issue being added to it or removed, and a "blocked by" link being added to it or removed. So a Spec is not taken while its Tickets are still being attached. These are read from the issue's timeline, since adding a sub-issue does not change the issue's update time, and pickup.wait_minutes in the User config sets the window in whole minutes from 0 up, within the supported duration range; 0 disables waiting. An Architect run also waits for an issue that meets every other Ready issue condition while it is settling. A later pass takes the issue once it has settled;
  • diff --git a/src/fix/selection.rs b/src/fix/selection.rs index c0a39074a..6233330db 100644 --- a/src/fix/selection.rs +++ b/src/fix/selection.rs @@ -26,7 +26,9 @@ pub(super) fn take( github, author, sign_off_hold, - self_merge_check_holds: hold_logs.map(logs::self_merge_check_holds).transpose()?, + self_merge_check_holds: hold_logs + .map(|logs_dir| logs::self_merge_check_holds(logs_dir, &launch.repo)) + .transpose()?, passed_over, }; diff --git a/src/logs.rs b/src/logs.rs index 44ff8cace..c7a800944 100644 --- a/src/logs.rs +++ b/src/logs.rs @@ -714,9 +714,11 @@ pub(crate) fn record_for_pull_request(root: &Path, url: &str) -> anyhow::Result< Ok(run_for_pull_request(root, url)?.map(|(path, _)| path)) } -pub(crate) fn self_merge_check_holds(logs_dir: &Path) -> anyhow::Result { - let snapshot = reading::Snapshot::load(logs_dir, chrono::Local::now())?; - Ok(PullRequestAttribution::new(&snapshot)) +pub(crate) fn self_merge_check_holds( + logs_dir: &Path, + repo: &Repo, +) -> anyhow::Result { + reading::repository_hold_attribution(logs_dir, repo) } /// Where this command and all its child Runs keep Session traces on `repo`. diff --git a/src/logs/reading.rs b/src/logs/reading.rs index b32a251f5..c5462aba4 100644 --- a/src/logs/reading.rs +++ b/src/logs/reading.rs @@ -538,11 +538,43 @@ impl Command { } pub(super) fn repository_records(root: &Path) -> Result> { - let inventory = Inventory::on_demand(); + read_repository_records(&Inventory::on_demand(), root) +} + +/// Hold selection needs the repository's Command records, including records +/// saved by a checkout that spelled the same repository with different case. +pub(super) fn repository_hold_attribution( + logs_dir: &Path, + repo: &crate::issue::Repo, +) -> Result { + let inventory = Arc::new(Inventory::on_demand()); + let matching_directories = |parent: &Path, name: &str| -> Result> { + let mut directories = inventory.directories(parent)?; + directories.retain(|path| { + path.file_name() + .and_then(|part| part.to_str()) + .is_some_and(|part| part.eq_ignore_ascii_case(name)) + }); + Ok(directories) + }; + let mut records = BTreeMap::new(); + for owner in matching_directories(logs_dir, &repo.owner)? { + for path in matching_directories(&owner, &repo.name)? { + records.extend(read_repository_records(&inventory, &path)?); + } + } + let commands = command_trees(&inventory, &mut records, &Local::now()); + Ok(PullRequestAttribution::from_commands(&commands)) +} + +fn read_repository_records( + inventory: &Inventory, + root: &Path, +) -> Result> { let mut records = BTreeMap::new(); for folder in inventory.directories(&root.join("commands"))? { let folder = inventory.folder(&folder)?; - records.extend(read_records(&inventory, &folder, false)?); + records.extend(read_records(inventory, &folder, false)?); } Ok(records) } diff --git a/src/logs/reading/attribution.rs b/src/logs/reading/attribution.rs index 94b2ccc03..d6ebbde9e 100644 --- a/src/logs/reading/attribution.rs +++ b/src/logs/reading/attribution.rs @@ -40,13 +40,18 @@ pub(crate) struct PullRequestAttribution { impl PullRequestAttribution { pub(in crate::logs) fn new(snapshot: &Snapshot) -> Self { + Self::from_commands(snapshot.entries().iter().filter_map(|entry| match entry { + Entry::Record(command) => Some(command.as_ref()), + Entry::History(_) => None, + })) + } + + pub(super) fn from_commands<'a>(commands: impl IntoIterator) -> Self { let mut attribution = Self { candidates: BTreeMap::new(), }; - for entry in snapshot.entries() { - if let Entry::Record(command) = entry { - attribution.collect(command); - } + for command in commands { + attribution.collect(command); } attribution } diff --git a/src/ready.rs b/src/ready.rs index bc04d093f..971837c23 100644 --- a/src/ready.rs +++ b/src/ready.rs @@ -260,7 +260,7 @@ impl Reads for GitHubAndOrigin<'_> { let Some(pr) = branch::open_pull_request(self.launch, &self.github, issue)? else { return Ok(None); }; - let holds = crate::logs::self_merge_check_holds(self.logs_dir)?; + let holds = crate::logs::self_merge_check_holds(self.logs_dir, &issue.repo())?; Ok(holds.self_merge_check_held(&pr.url).then_some(pr.url)) } diff --git a/tests/fix_pass.rs b/tests/fix_pass.rs index 3d912c12d..933486194 100644 --- a/tests/fix_pass.rs +++ b/tests/fix_pass.rs @@ -204,6 +204,30 @@ fn removing_check_config_does_not_release_a_recorded_hold() { assert_eq!(scenario.origin_git(&["rev-parse", "issue-7"]), head); } +#[test] +fn independent_activity_does_not_block_a_fix_pass() { + let scenario = Scenario::new(); + scenario.origin_has_branch("feature", "main", &["Feature"]); + scenario.github_has_pr("feature", "main", "OPEN"); + let head = scenario.origin_git(&["rev-parse", "feature"]); + let mut state = scenario.gh_state(); + state["checks"][head.trim()] = json!([{"name": "test", "conclusion": "failure"}]); + scenario.write_gh_state(&state); + scenario.agent_does(REPAIR_CI); + std::fs::create_dir_all(scenario.path("home/.thirdshift/logs/other/repo/activity.log")) + .unwrap(); + + let result = fix_pass(&scenario, &[]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert_eq!( + scenario.origin_file("feature", "ci-fix.txt").as_deref(), + Some("repaired\n"), + "{}", + result.stderr + ); +} + #[test] fn fix_pass_repairs_a_conflict_after_mergeability_settles_on_a_self_merge_check_hold() { let scenario = pull_request_held_by_self_merge_check(); diff --git a/tests/pickup_run.rs b/tests/pickup_run.rs index 3d2c509b1..c034e3e1c 100644 --- a/tests/pickup_run.rs +++ b/tests/pickup_run.rs @@ -4251,6 +4251,20 @@ fn pickup_reports_the_hold_as_the_reason_no_issue_was_taken() { assert!(!activity.contains("it can reserve"), "{activity}"); } +#[test] +fn independent_activity_does_not_block_pickup() { + let scenario = pickup_with_a_handed_back_self_merge_check_hold(); + ready_issue(&scenario, 8, &[]); + scenario.agent_does_for(8, &agent_opens_pr(8, "main")); + std::fs::create_dir_all(scenario.path("home/.thirdshift/logs/other/repo/activity.log")) + .unwrap(); + + let result = scenario.run(&["pickup", "no-merge"]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert_ended_with_pr(&result, &pr_from(&scenario, "issue-8"), "ready for review"); +} + #[test] fn a_recent_hand_back_on_a_later_history_page_waits_for_settling() { let scenario = Scenario::new(); From cc8dbab5aaa8e8016152456e192e390dcb2e8807 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Fri, 4 Dec 2026 13:32:58 -0500 Subject: [PATCH 25/27] Recheck holds under reservation and reuse readiness observations --- src/branch.rs | 27 ++++++++------ src/fix/selection.rs | 33 ++++++++++------ src/ready.rs | 76 ++++++++++++++++++++++--------------- tests/fix_pass.rs | 89 ++++++++++++++++++++++++++++++++++++++++++++ tests/pickup_run.rs | 21 +++++++++++ 5 files changed, 192 insertions(+), 54 deletions(-) diff --git a/src/branch.rs b/src/branch.rs index b30bc79f7..622965eda 100644 --- a/src/branch.rs +++ b/src/branch.rs @@ -239,6 +239,11 @@ pub(crate) struct History { prs: Vec<(u64, PullRequest)>, } +pub(crate) struct Continuation { + pub can_continue: bool, + pub open_pull_request: Option, +} + impl History { fn latest(self) -> Option { let Self { on_origin, prs } = self; @@ -272,20 +277,20 @@ impl History { .or(pr.map(|pr| Started::PullRequest(pr.url))) } - /// Whether ADR-0002 allows continuing the latest Issue branch. - pub(crate) fn can_continue(self) -> bool { - self.latest().is_some_and(|latest| { - latest.origin_sha.is_some() && latest.pr.is_none_or(|pr| pr.state == PrState::Open) + /// See whether ADR-0002 allows continuing the latest Issue branch and + /// whether its pull request is open, from the same observation. + pub(crate) fn continuation(self) -> Option { + let latest = self.latest()?; + Some(Continuation { + can_continue: latest.origin_sha.is_some() + && latest + .pr + .as_ref() + .is_none_or(|pr| pr.state == PrState::Open), + open_pull_request: latest.pr.filter(|pr| pr.state == PrState::Open), }) } - /// The open pull request on the latest Issue branch, if it has one. - pub(crate) fn open_pull_request(self) -> Option { - self.latest() - .and_then(|latest| latest.pr) - .filter(|pr| pr.state == PrState::Open) - } - pub(crate) fn remember_bodies(&self, bodies: &mut FirstPrBodies) { for (_, pr) in &self.prs { if let Some(body) = &pr.body { diff --git a/src/fix/selection.rs b/src/fix/selection.rs index 6233330db..cd20632d6 100644 --- a/src/fix/selection.rs +++ b/src/fix/selection.rs @@ -1,6 +1,6 @@ //! Fix Pass ordering and adoption under the pull request reservation. -use std::{cmp::Reverse, num::NonZeroU64}; +use std::{cmp::Reverse, num::NonZeroU64, path::Path}; use anyhow::Result; @@ -18,7 +18,7 @@ pub(super) fn take( author: Option<&str>, behind: Option, sign_off_hold: Option<&SignOffHold>, - hold_logs: Option<&std::path::Path>, + hold_logs: Option<&Path>, passed_over: &mut Vec, ) -> Result> { let mut pass = Pass { @@ -26,17 +26,16 @@ pub(super) fn take( github, author, sign_off_hold, - self_merge_check_holds: hold_logs - .map(|logs_dir| logs::self_merge_check_holds(logs_dir, &launch.repo)) - .transpose()?, + hold_logs, passed_over, }; + let holds = pass.read_holds()?; let mut without_repairs = Vec::new(); let base = launch.base.name(); for listed in github.fix_candidates(&launch.repo, base, author)? { let pr = &listed.pr; - let Some(candidate) = pass.observe(pr, false)? else { + let Some(candidate) = pass.observe(pr, false, holds.as_ref())? else { continue; }; if candidate.needs_repair { @@ -77,7 +76,7 @@ struct Pass<'a> { github: &'a GitHub, author: Option<&'a str>, sign_off_hold: Option<&'a SignOffHold>, - self_merge_check_holds: Option, + hold_logs: Option<&'a Path>, passed_over: &'a mut Vec, } @@ -88,16 +87,25 @@ enum Recheck { } impl Pass<'_> { - fn observe(&self, pr: &PullRequestUrl, reserved: bool) -> Result> { + fn read_holds(&self) -> Result> { + self.hold_logs + .map(|logs_dir| logs::self_merge_check_holds(logs_dir, &self.launch.repo)) + .transpose() + } + + fn observe( + &self, + pr: &PullRequestUrl, + reserved: bool, + holds: Option<&PullRequestAttribution>, + ) -> Result> { self.github.observe_fix_candidate( pr, self.launch.base.name(), self.author, reserved, self.sign_off_hold, - self.self_merge_check_holds - .as_ref() - .is_some_and(|holds| holds.self_merge_check_held(&pr.url)), + holds.is_some_and(|holds| holds.self_merge_check_held(&pr.url)), ) } @@ -130,7 +138,8 @@ impl Pass<'_> { let Some(held) = Reservation::take(git, self.github, pr)? else { return Ok(Recheck::Unavailable); }; - let Some(current) = self.observe(pr, true)? else { + let holds = self.read_holds()?; + let Some(current) = self.observe(pr, true, holds.as_ref())? else { return Ok(Recheck::Unavailable); }; if current.branch != branch { diff --git a/src/ready.rs b/src/ready.rs index c9bc9ed4f..4f1d284cc 100644 --- a/src/ready.rs +++ b/src/ready.rs @@ -19,6 +19,7 @@ use crate::git::Git; use crate::github::{Candidate, GitHub, ListedIssue, Shaping, Ticket}; use crate::issue::{IssueUrl, Repo}; use crate::labels::{Label, READY_FOR_AGENT}; +use crate::logs::{self, PullRequestAttribution}; use crate::progress; use crate::spec_run::{self, Unstartable}; use crate::trust::{self, UntrustedIssue}; @@ -218,16 +219,20 @@ trait Reads { fn candidate(&self, issue: &IssueUrl) -> Result; /// What shows `issue` was ever started, if it was. fn started(&self, issue: &IssueUrl) -> Result>; - /// The open pull request waiting on a recorded Self-merge check hold. - fn held_pull_request(&self, issue: &IssueUrl) -> Result>; - /// Whether the latest Issue branch can be continued under ADR-0002. - fn can_continue(&self, issue: &IssueUrl) -> Result; + /// Whether handed-back work can continue or its PR is already held. + fn continuation(&self, issue: &IssueUrl) -> Result; /// The Tickets of `spec`, an issue with sub-issues, as a Spec run reads /// them. fn tickets(&self, spec: &IssueUrl) -> Result>; fn issue_trust(&self, issue: &IssueUrl) -> Result>; } +enum Continuation { + Available, + Unavailable, + Held(String), +} + /// The reads of GitHub and of the Launch directory `launch`'s origin. struct GitHubAndOrigin<'a> { launch: &'a Git, @@ -235,6 +240,7 @@ struct GitHubAndOrigin<'a> { authors: &'a [String], logs_dir: &'a Path, first_pr_bodies: RefCell<&'a mut FirstPrBodies>, + holds: RefCell>, } impl<'a> GitHubAndOrigin<'a> { @@ -250,6 +256,7 @@ impl<'a> GitHubAndOrigin<'a> { authors, logs_dir, first_pr_bodies: RefCell::new(first_pr_bodies), + holds: RefCell::new(None), } } @@ -258,6 +265,16 @@ impl<'a> GitHubAndOrigin<'a> { history.remember_bodies(&mut self.first_pr_bodies.borrow_mut()); Ok(history) } + + fn has_hold(&self, issue: &IssueUrl, pr: &str) -> Result { + let mut holds = self.holds.borrow_mut(); + if holds.is_none() { + *holds = Some(logs::self_merge_check_holds(self.logs_dir, &issue.repo())?); + } + Ok(holds + .as_ref() + .is_some_and(|holds| holds.self_merge_check_held(pr))) + } } impl Reads for GitHubAndOrigin<'_> { @@ -276,16 +293,20 @@ impl Reads for GitHubAndOrigin<'_> { Ok(self.branch_history(issue)?.started(issue)) } - fn held_pull_request(&self, issue: &IssueUrl) -> Result> { - let Some(pr) = self.branch_history(issue)?.open_pull_request() else { - return Ok(None); + fn continuation(&self, issue: &IssueUrl) -> Result { + let Some(branch) = self.branch_history(issue)?.continuation() else { + return Ok(Continuation::Unavailable); }; - let holds = crate::logs::self_merge_check_holds(self.logs_dir, &issue.repo())?; - Ok(holds.self_merge_check_held(&pr.url).then_some(pr.url)) - } - - fn can_continue(&self, issue: &IssueUrl) -> Result { - Ok(self.branch_history(issue)?.can_continue()) + if let Some(pr) = branch.open_pull_request + && self.has_hold(issue, &pr.url)? + { + return Ok(Continuation::Held(pr.url)); + } + Ok(if branch.can_continue { + Continuation::Available + } else { + Continuation::Unavailable + }) } fn tickets(&self, spec: &IssueUrl) -> Result> { @@ -630,19 +651,18 @@ fn standing_of( if read.claimed { return passed_over(Reason::Claimed); } - if read.handed_back - && let Some(pr) = reads.held_pull_request(&candidate.issue)? - { - return passed_over(Reason::HeldBySelfMergeCheck(pr)); - } - let continuing_closed_spec = if spec_run::all_closed(read.sub_issue_is_open.iter().copied()) { - if !reads.can_continue(&candidate.issue)? { - return passed_over(Reason::TicketsClosed); + let can_continue = if read.handed_back { + match reads.continuation(&candidate.issue)? { + Continuation::Available => true, + Continuation::Unavailable => false, + Continuation::Held(pr) => return passed_over(Reason::HeldBySelfMergeCheck(pr)), } - true } else { false }; + if !can_continue && spec_run::all_closed(read.sub_issue_is_open.iter().copied()) { + return passed_over(Reason::TicketsClosed); + } let unsettled = read .last_shaped .filter(|shaped| wait > TimeDelta::zero() && now - shaped.at < wait); @@ -659,9 +679,7 @@ fn standing_of( let tickets = reads.tickets(&candidate.issue)?; // Read after the candidate: its Tickets may have closed since. if !tickets.iter().any(|ticket| ticket.is_open) { - if tickets.is_empty() - || !(continuing_closed_spec || reads.can_continue(&candidate.issue)?) - { + if tickets.is_empty() || !can_continue { return passed_over(Reason::TicketsClosed); } } else if tickets @@ -771,12 +789,8 @@ mod tests { Ok(self.facts(issue).and_then(|facts| facts.started.clone())) } - fn held_pull_request(&self, _issue: &IssueUrl) -> Result> { - Ok(None) - } - - fn can_continue(&self, _issue: &IssueUrl) -> Result { - Ok(false) + fn continuation(&self, _issue: &IssueUrl) -> Result { + Ok(Continuation::Unavailable) } fn tickets(&self, spec: &IssueUrl) -> Result> { diff --git a/tests/fix_pass.rs b/tests/fix_pass.rs index 933486194..ea2d964a1 100644 --- a/tests/fix_pass.rs +++ b/tests/fix_pass.rs @@ -228,6 +228,95 @@ fn independent_activity_does_not_block_a_fix_pass() { ); } +#[test] +fn a_hold_recorded_after_selection_still_stops_the_fix_on_reservation() { + let scenario = pull_request_held_by_self_merge_check(); + let head = scenario.origin_git(&["rev-parse", "issue-7"]); + let base = scenario.origin_git(&["rev-parse", "main"]); + let record = held_command_record(&scenario); + let staged = scenario.path("late-hold.json"); + std::fs::rename(&record, &staged).unwrap(); + let mut state = scenario.gh_state(); + state["on_ci_read"] = json!({ + "times": 1, + "seen": [base.trim()], + "script": format!("mv '{}' '{}'", staged.display(), record.display()) + }); + scenario.write_gh_state(&state); + + let result = fix_pass(&scenario, &["behind", "2"]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!(record.exists(), "hold must exist before recheck"); + assert_eq!( + scenario.origin_git(&["rev-parse", "issue-7"]), + head, + "Fix Pass adopted a PR with a newly recorded hold: {}", + result.stderr + ); +} + +#[test] +fn fix_pass_rechecks_a_hold_recorded_during_selection() { + let scenario = pull_request_held_by_self_merge_check(); + let head = scenario.origin_git(&["rev-parse", "issue-7"]); + let record = held_command_record(&scenario); + let pending = scenario.path("pending-hold.json"); + std::fs::rename(&record, &pending).unwrap(); + + let wrapper = scenario.path("bin/gh"); + std::fs::create_dir_all(scenario.path("bin/original")).unwrap(); + std::fs::rename(&wrapper, scenario.path("bin/original/gh")).unwrap(); + support::write_executable( + &wrapper, + r#"#!/bin/sh +set -eu +case "$*" in + *'repos/acme/widgets/pulls?state=open&per_page=100'*) + if [ -f "$PENDING_HOLD" ]; then mv "$PENDING_HOLD" "$HOLD_RECORD"; fi + ;; +esac +exec "$(dirname "$0")/original/gh" "$@" +"#, + ); + + let result = scenario.run_with_env( + &[ + "fix", + "base", + "main", + "behind", + "2", + "no-merge", + "no-base-fix", + "no-email", + ], + &[ + ("PENDING_HOLD", pending.to_str().unwrap()), + ("HOLD_RECORD", record.to_str().unwrap()), + ], + ); + + assert!(record.exists(), "{}", result.stderr); + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert_eq!( + scenario.origin_git(&["rev-parse", "issue-7"]), + head, + "{}", + result.stderr + ); +} + +fn held_command_record(scenario: &Scenario) -> std::path::PathBuf { + let folder = "home/.thirdshift/logs/acme/widgets/commands/issue"; + let name = scenario + .entries(folder) + .into_iter() + .find(|name| name.ends_with(".command.json")) + .unwrap(); + scenario.path(folder).join(name) +} + #[test] fn fix_pass_repairs_a_conflict_after_mergeability_settles_on_a_self_merge_check_hold() { let scenario = pull_request_held_by_self_merge_check(); diff --git a/tests/pickup_run.rs b/tests/pickup_run.rs index c034e3e1c..0f8655fe3 100644 --- a/tests/pickup_run.rs +++ b/tests/pickup_run.rs @@ -4265,6 +4265,27 @@ fn independent_activity_does_not_block_pickup() { assert_ended_with_pr(&result, &pr_from(&scenario, "issue-8"), "ready for review"); } +#[test] +fn closed_spec_standing_reads_branch_history_once() { + let scenario = spec_with_every_ticket_closed(); + scenario.origin_has_branch("issue-7", "main", &["Landed Tickets"]); + scenario.github_has_pr("issue-7", "main", "OPEN"); + hand_back_spec(&scenario); + + let result = scenario.run(&["architect"]); + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!(activity_log(&scenario).contains("Architect run skipped: Ready issue #7")); + let calls = scenario.gh_calls_of("pr", "list"); + let reads = calls + .iter() + .filter(|call| { + call.windows(2) + .any(|pair| pair == ["--search", "head:issue-7"]) + }) + .count(); + assert_eq!(reads, 1, "{calls:?}"); +} + #[test] fn a_recent_hand_back_on_a_later_history_page_waits_for_settling() { let scenario = Scenario::new(); From 448b4c599de1c76680783a002ed95a112879ae76 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Sat, 5 Dec 2026 08:54:05 -0500 Subject: [PATCH 26/27] Recheck held PRs and Spec branches before Pickup --- site/index.html | 2 +- src/branch.rs | 27 +++++++---------- src/ready.rs | 38 +++++++++++++----------- tests/fix_pass.rs | 40 +++++++++++++++++++------- tests/pickup_run.rs | 70 +++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 133 insertions(+), 44 deletions(-) diff --git a/site/index.html b/site/index.html index f44facf9d..795d7ba27 100644 --- a/site/index.html +++ b/site/index.html @@ -437,7 +437,7 @@

    Seven workflows

    Pickup runTake a Ready issue and put the factory to work.

    Add skip-author <login> or --skip-author <login> to a Pickup or Triage cron line to leave that author's issues alone, even for a Trusted account. Repeat it for several logins; matching ignores case. Pickup passes over the whole Spec when its author is skipped, and its dispatched Spec run stops before a skipped author's Ticket. Each exclusion logs why. Explicit Issue URL runs keep their usual trust checks.

    -

    A Pickup run takes the lowest-numbered Ready issue by default, the highest-numbered with pickup.order = "highest-first" or highest-first, after it has settled and while the repository is below its Failure limit: fewer open issues labelled agent-failed than pickup.failure_limit, 3 by default. Pickup leaves an issue for the Day shift if its open pull request was held by the Self-merge check on this machine. Other Ready issues can still move ahead. It immediately re-runs failed Base branch push CI once: green on re-run files a Flaky-test Ticket, and red again files an ordinary bug Ticket after 30 minutes. That CI-red Ticket leaves job names and log lines out of its title, body and later comments, and waits until you write the task and apply ready-for-agent. New failing commits are added to an open CI-red Ticket; one in needs-info does not block a new report. A run the host ran out of disk space under gets ready-for-agent back instead, as a host problem, not the issue's, and so does a Paused Command that no route had Plan usage left for, unless an untrusted edit leaves needs-triage or it is a Security fix. Other failed work stays with the Day shift, labelled agent-failed in place of in-progress, with a generated comment giving its cause, where it stopped, what was preserved and the machine, until you hand it back by applying ready-for-agent again, take agent-failed off, or close the issue. A Spec run only waiting on gated, blocked or out-of-repository Tickets is no failure: its Spec gets ready-for-agent back and a comment naming each undone Ticket and what it waits on, and a later Pickup run continues it once a Ticket can start. A run that leaves its pull request ready for review takes in-progress off and puts nothing back.

    +

    A Pickup run takes the lowest-numbered Ready issue by default, the highest-numbered with pickup.order = "highest-first" or highest-first, after it has settled and while the repository is below its Failure limit: fewer open issues labelled agent-failed than pickup.failure_limit, 3 by default. Pickup leaves an issue for the Day shift if the latest run this machine recorded for its open pull request ended at a Self-merge check hold. Other Ready issues can still move ahead. It immediately re-runs failed Base branch push CI once: green on re-run files a Flaky-test Ticket, and red again files an ordinary bug Ticket after 30 minutes. That CI-red Ticket leaves job names and log lines out of its title, body and later comments, and waits until you write the task and apply ready-for-agent. New failing commits are added to an open CI-red Ticket; one in needs-info does not block a new report. A run the host ran out of disk space under gets ready-for-agent back instead, as a host problem, not the issue's, and so does a Paused Command that no route had Plan usage left for, unless an untrusted edit leaves needs-triage or it is a Security fix. Other failed work stays with the Day shift, labelled agent-failed in place of in-progress, with a generated comment giving its cause, where it stopped, what was preserved and the machine, until you hand it back by applying ready-for-agent again, take agent-failed off, or close the issue. A Spec run only waiting on gated, blocked or out-of-repository Tickets is no failure: its Spec gets ready-for-agent back and a comment naming each undone Ticket and what it waits on, and a later Pickup run continues it once a Ticket can start. A run that leaves its pull request ready for review takes in-progress off and puts nothing back.

    diff --git a/src/branch.rs b/src/branch.rs index 622965eda..18dad1664 100644 --- a/src/branch.rs +++ b/src/branch.rs @@ -239,11 +239,6 @@ pub(crate) struct History { prs: Vec<(u64, PullRequest)>, } -pub(crate) struct Continuation { - pub can_continue: bool, - pub open_pull_request: Option, -} - impl History { fn latest(self) -> Option { let Self { on_origin, prs } = self; @@ -277,20 +272,20 @@ impl History { .or(pr.map(|pr| Started::PullRequest(pr.url))) } - /// See whether ADR-0002 allows continuing the latest Issue branch and - /// whether its pull request is open, from the same observation. - pub(crate) fn continuation(self) -> Option { - let latest = self.latest()?; - Some(Continuation { - can_continue: latest.origin_sha.is_some() - && latest - .pr - .as_ref() - .is_none_or(|pr| pr.state == PrState::Open), - open_pull_request: latest.pr.filter(|pr| pr.state == PrState::Open), + /// Whether ADR-0002 allows continuing the latest Issue branch. + pub(crate) fn can_continue(self) -> bool { + self.latest().is_some_and(|latest| { + latest.origin_sha.is_some() && latest.pr.is_none_or(|pr| pr.state == PrState::Open) }) } + pub(crate) fn open_pull_requests(&self) -> impl Iterator { + self.prs + .iter() + .map(|(_, pr)| pr) + .filter(|pr| pr.state == PrState::Open) + } + pub(crate) fn remember_bodies(&self, bodies: &mut FirstPrBodies) { for (_, pr) in &self.prs { if let Some(body) = &pr.body { diff --git a/src/ready.rs b/src/ready.rs index 4f1d284cc..c0d69e537 100644 --- a/src/ready.rs +++ b/src/ready.rs @@ -294,15 +294,13 @@ impl Reads for GitHubAndOrigin<'_> { } fn continuation(&self, issue: &IssueUrl) -> Result { - let Some(branch) = self.branch_history(issue)?.continuation() else { - return Ok(Continuation::Unavailable); - }; - if let Some(pr) = branch.open_pull_request - && self.has_hold(issue, &pr.url)? - { - return Ok(Continuation::Held(pr.url)); + let history = self.branch_history(issue)?; + for pr in history.open_pull_requests() { + if self.has_hold(issue, &pr.url)? { + return Ok(Continuation::Held(pr.url.clone())); + } } - Ok(if branch.can_continue { + Ok(if history.can_continue() { Continuation::Available } else { Continuation::Unavailable @@ -651,6 +649,18 @@ fn standing_of( if read.claimed { return passed_over(Reason::Claimed); } + let is_spec = read.has_sub_issues(); + let known_closed_spec = spec_run::all_closed(read.sub_issue_is_open.iter().copied()); + let unsettled = read + .last_shaped + .filter(|shaped| wait > TimeDelta::zero() && now - shaped.at < wait); + let waiting_to_settle = unsettled.as_ref().filter(|_| settling == Settling::Wait); + let read_tickets = || reads.tickets(&candidate.issue); + // If the last open Ticket closes during this read, confirm the Spec + // branch from an observation made after the Tickets closed. + let tickets = (is_spec && !known_closed_spec && waiting_to_settle.is_none()) + .then(read_tickets) + .transpose()?; let can_continue = if read.handed_back { match reads.continuation(&candidate.issue)? { Continuation::Available => true, @@ -660,23 +670,17 @@ fn standing_of( } else { false }; - if !can_continue && spec_run::all_closed(read.sub_issue_is_open.iter().copied()) { + if !can_continue && known_closed_spec { return passed_over(Reason::TicketsClosed); } - let unsettled = read - .last_shaped - .filter(|shaped| wait > TimeDelta::zero() && now - shaped.at < wait); // Pickup keeps its existing short circuit and passed-over reason. // Architect must check every other condition before treating settling // as the only reason an issue is not Ready. - if settling == Settling::Wait - && let Some(shaped) = &unsettled - { + if let Some(shaped) = waiting_to_settle { return passed_over(Reason::Unsettled(shaped.by)); } - let is_spec = read.has_sub_issues(); if is_spec { - let tickets = reads.tickets(&candidate.issue)?; + let tickets = tickets.map_or_else(read_tickets, Ok)?; // Read after the candidate: its Tickets may have closed since. if !tickets.iter().any(|ticket| ticket.is_open) { if tickets.is_empty() || !can_continue { diff --git a/tests/fix_pass.rs b/tests/fix_pass.rs index ea2d964a1..9b128ecac 100644 --- a/tests/fix_pass.rs +++ b/tests/fix_pass.rs @@ -229,22 +229,42 @@ fn independent_activity_does_not_block_a_fix_pass() { } #[test] -fn a_hold_recorded_after_selection_still_stops_the_fix_on_reservation() { +fn a_hold_recorded_on_reservation_stops_the_fix_pass() { let scenario = pull_request_held_by_self_merge_check(); let head = scenario.origin_git(&["rev-parse", "issue-7"]); - let base = scenario.origin_git(&["rev-parse", "main"]); let record = held_command_record(&scenario); let staged = scenario.path("late-hold.json"); std::fs::rename(&record, &staged).unwrap(); - let mut state = scenario.gh_state(); - state["on_ci_read"] = json!({ - "times": 1, - "seen": [base.trim()], - "script": format!("mv '{}' '{}'", staged.display(), record.display()) - }); - scenario.write_gh_state(&state); + scenario.repo_has_hook( + &scenario.origin_dir(), + "post-receive", + r#"#!/bin/sh +set -eu +while read old new reference; do + if [ "$reference" = refs/thirdshift/reservations/1 ] && + [ "$new" != 0000000000000000000000000000000000000000 ]; then + mv "$STAGED_HOLD" "$HOLD_RECORD" + fi +done +"#, + ); - let result = fix_pass(&scenario, &["behind", "2"]); + let result = scenario.run_with_env( + &[ + "fix", + "base", + "main", + "behind", + "2", + "no-merge", + "no-base-fix", + "no-email", + ], + &[ + ("STAGED_HOLD", staged.to_str().unwrap()), + ("HOLD_RECORD", record.to_str().unwrap()), + ], + ); assert_eq!(result.code, Some(0), "{}", result.stderr); assert!(record.exists(), "hold must exist before recheck"); diff --git a/tests/pickup_run.rs b/tests/pickup_run.rs index 0f8655fe3..aee3c6228 100644 --- a/tests/pickup_run.rs +++ b/tests/pickup_run.rs @@ -1928,6 +1928,55 @@ esac ); } +#[test] +fn pickup_rechecks_the_spec_branch_when_tickets_close_during_refresh() { + let scenario = spec_with_every_ticket_closed(); + scenario.issue_is(5, "OPEN"); + scenario.origin_has_branch("issue-7", "main", &["Landed Tickets"]); + hand_back_spec(&scenario); + let wrapper = scenario.path("bin/gh"); + let delegate = scenario.path("bin/real/gh"); + fs::create_dir_all(delegate.parent().unwrap()).unwrap(); + fs::rename(&wrapper, &delegate).unwrap(); + write_executable( + &wrapper, + r#"#!/bin/sh +set -eu +real="$(dirname "$0")/real/gh" +case "$*" in + 'api graphql '*"subIssues { totalCount }"*) + if [ -e "$TMPDIR/first-ticket-read" ] && [ ! -e "$TMPDIR/closed-on-refresh" ]; then + git --git-dir="$PICKUP_TEST_ORIGIN" update-ref -d refs/heads/issue-7 + "$real" fake issue 5 CLOSED + touch "$TMPDIR/closed-on-refresh" + else + touch "$TMPDIR/first-ticket-read" + fi + ;; +esac +exec "$real" "$@" +"#, + ); + let origin = scenario.origin_dir(); + let result = scenario.run_with_env( + &["pickup"], + &[("PICKUP_TEST_ORIGIN", origin.to_str().unwrap())], + ); + assert!( + scenario.path("tmp/closed-on-refresh").exists(), + "{}", + result.stderr + ); + assert!( + result.stderr.contains(&unreservable(7)), + "{}", + result.stderr + ); + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!(scenario.claude_calls().is_empty()); + assert_eq!(scenario.issue_labels(7), [READY_FOR_AGENT]); +} + #[test] fn a_spec_whose_tickets_are_all_closed_is_passed_over_and_the_next_ready_issue_is_taken() { let scenario = spec_with_every_ticket_closed(); @@ -4188,6 +4237,27 @@ fn pickup_with_a_handed_back_self_merge_check_hold() -> Scenario { scenario } +#[test] +fn pickup_leaves_older_held_pr_open_when_a_newer_issue_branch_exists() { + let scenario = pickup_with_a_handed_back_self_merge_check_hold(); + let branch = "issue-7-branch-2"; + scenario.origin_has_branch(branch, "main", &["Start another continuation"]); + let head = scenario.origin_git(&["rev-parse", branch]); + let calls = scenario.claude_calls().len(); + scenario.agent_does_for( + 7, + "touch retried.txt\ngit add retried.txt\ngit commit -qm 'Retry issue'", + ); + + let result = scenario.run(&["pickup", "no-merge"]); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert_eq!(scenario.claude_calls().len(), calls, "{}", result.stderr); + assert_eq!(scenario.origin_git(&["rev-parse", branch]), head); + assert_eq!(pr_from(&scenario, "issue-7")["state"], "OPEN"); + assert_eq!(scenario.issue_labels(7), [READY_FOR_AGENT]); +} + #[test] fn pickup_leaves_an_open_pull_request_held_by_the_self_merge_check() { let scenario = pickup_with_a_handed_back_self_merge_check_hold(); From 40922190d01884a559133125ad0a975259a86ce6 Mon Sep 17 00:00:00 2001 From: Jacob Stephens Date: Sat, 5 Dec 2026 08:57:31 -0500 Subject: [PATCH 27/27] Preserve held Run notifications through Custom processes (#2427) --- docs/guide.md | 1 + site/docs/index.html | 1 + src/branch.rs | 21 ++++---- src/logs.rs | 4 ++ src/logs/reading.rs | 42 +++++----------- src/logs/reading/inventory.rs | 31 ++++++++++-- src/logs/recording.rs | 18 +++++++ src/notification.rs | 29 ++++++++++- src/processes.rs | 18 ++++++- src/ready.rs | 57 ++++++++-------------- src/run_ending.rs | 2 +- tests/pickup_run.rs | 8 +++ tests/process.rs | 56 +++++++++++++++++++++ tests/process/published.rs | 92 +++++++++++++++++++++++++++++++++++ 14 files changed, 298 insertions(+), 82 deletions(-) diff --git a/docs/guide.md b/docs/guide.md index 2ad7576a0..76c36ea3a 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -4512,6 +4512,7 @@ A Ready issue is an open issue that: - is not labelled `base-fix` or `security-fix`: the Ticket run that opened a [Base fix](#base-fix)'s issue, or the Security run that dispatched a fix, owns it. A failed Security fix is still passed over if GitHub prevented its Claim from being made; - has no open blocker, by GitHub's "blocked by" links, never the text of its body. Once every blocker is closed, it can be taken; - either was never started (no **Issue branch** on `origin` and no pull request from one, open, merged or closed), or you handed it back by applying `ready-for-agent` at or after its last [Claim](#the-claim) ended. A Spec whose Spec run ended only waiting is handed back by thirdshift the same way, unless someone other than a Trusted account or the Spec's authorized author edited its title or body after its last Trusted Ready labelling. For started work, the full label history must show an earlier `in-progress` application and its removal, with `ready-for-agent` applied at that removal's timestamp or later. A swap made in one edit counts in either listed order; a new Claim applied at the same timestamp leaves the issue Claimed. Work never Claimed, or without that hand-back, stays with you. An eligible branch with no PR or an open PR follows the existing [Continuation](#continuation) rule; merged or closed PRs follow ADR 0002 and start a fresh numbered branch. This is deliberate hand-back, not automatic retries; +- has no open pull request whose latest Run on this machine ended at a Self-merge check hold, even after a hand-back; - if it is a **Spec** whose **Tickets** are all closed, its Spec run can continue its Spec branch on `origin` under [ADR-0002](adr/0002-existing-issue-branch-means-continue.md): the latest numbered branch is present, with no PR or an open PR. The dispatched Spec run goes straight to the Spec review and the Spec PR's Delivery and Repair loop, without running a Ticket again. A PR without its branch, or a retained branch whose latest PR is closed or merged, does not qualify. Without a resumable branch, waiting never makes it a Ready issue: close it, or take its `ready-for-agent` off; - is settled: by default, five minutes have passed since the latest of `ready-for-agent` being applied to it, a sub-issue being added to it or removed, and a "blocked by" link being added to it or removed. So a Spec is not taken while its Tickets are still being attached. These are read from the issue's timeline, since adding a sub-issue does not change the issue's update time, and `pickup.wait_minutes` in the [User config](#user-config) sets the window in whole minutes from 0 up, within the supported duration range; 0 disables waiting. An Architect run also waits for an issue that meets every other Ready issue condition while it is settling. A later pass takes the issue once it has settled; - if it is a **Spec** with open Tickets, has a **Startable Ticket**: an open Ticket in the Spec's repository, with no sub-issues, no open blocker and none of the labels that make an Unready Ticket. That is the rule a [Spec run](#spec-runs) picks its next Ticket by, as if nothing were running yet, so a Spec whose open Tickets all wait on you, such as one whose last open Ticket is `needs-info`, is passed over rather than Claimed for a Spec run that could start nothing and would fail. This applies to a Spec handed back with `ready-for-agent` too. A Spec with one Startable Ticket is taken, and the Spec run handles its other Tickets as usual. Once a Ticket becomes startable, because its Unready label comes off or its blocker closes, a later pass takes the Spec. Its Tickets are read only for a Spec that meets every other condition. diff --git a/site/docs/index.html b/site/docs/index.html index 5a064129e..294120299 100644 --- a/site/docs/index.html +++ b/site/docs/index.html @@ -4204,6 +4204,7 @@
  • is not labelled base-fix or security-fix: the Ticket run that opened a Base fix's issue, or the Security run that dispatched a fix, owns it. A failed Security fix is still passed over if GitHub prevented its Claim from being made;
  • has no open blocker, by GitHub's "blocked by" links, never the text of its body. Once every blocker is closed, it can be taken;
  • either was never started (no Issue branch on origin and no pull request from one, open, merged or closed), or you handed it back by applying ready-for-agent at or after its last Claim ended. A Spec whose Spec run ended only waiting is handed back by thirdshift the same way, unless someone other than a Trusted account or the Spec's authorized author edited its title or body after its last Trusted Ready labelling. For started work, the full label history must show an earlier in-progress application and its removal, with ready-for-agent applied at that removal's timestamp or later. A swap made in one edit counts in either listed order; a new Claim applied at the same timestamp leaves the issue Claimed. Work never Claimed, or without that hand-back, stays with you. An eligible branch with no PR or an open PR follows the existing Continuation rule; merged or closed PRs follow ADR 0002 and start a fresh numbered branch. This is deliberate hand-back, not automatic retries;
  • +
  • has no open pull request whose latest Run on this machine ended at a Self-merge check hold, even after a hand-back;
  • if it is a Spec whose Tickets are all closed, its Spec run can continue its Spec branch on origin under ADR-0002: the latest numbered branch is present, with no PR or an open PR. The dispatched Spec run goes straight to the Spec review and the Spec PR's Delivery and Repair loop, without running a Ticket again. A PR without its branch, or a retained branch whose latest PR is closed or merged, does not qualify. Without a resumable branch, waiting never makes it a Ready issue: close it, or take its ready-for-agent off;
  • is settled: by default, five minutes have passed since the latest of ready-for-agent being applied to it, a sub-issue being added to it or removed, and a "blocked by" link being added to it or removed. So a Spec is not taken while its Tickets are still being attached. These are read from the issue's timeline, since adding a sub-issue does not change the issue's update time, and pickup.wait_minutes in the User config sets the window in whole minutes from 0 up, within the supported duration range; 0 disables waiting. An Architect run also waits for an issue that meets every other Ready issue condition while it is settling. A later pass takes the issue once it has settled;
  • if it is a Spec with open Tickets, has a Startable Ticket: an open Ticket in the Spec's repository, with no sub-issues, no open blocker and none of the labels that make an Unready Ticket. That is the rule a Spec run picks its next Ticket by, as if nothing were running yet, so a Spec whose open Tickets all wait on you, such as one whose last open Ticket is needs-info, is passed over rather than Claimed for a Spec run that could start nothing and would fail. This applies to a Spec handed back with ready-for-agent too. A Spec with one Startable Ticket is taken, and the Spec run handles its other Tickets as usual. Once a Ticket becomes startable, because its Unready label comes off or its blocker closes, a later pass takes the Spec. Its Tickets are read only for a Spec that meets every other condition.
  • diff --git a/src/branch.rs b/src/branch.rs index 26effaf0c..a10410cc6 100644 --- a/src/branch.rs +++ b/src/branch.rs @@ -116,6 +116,7 @@ pub(crate) fn history(launch: &Git, github: &GitHub, issue: &IssueUrl) -> Result pub(crate) struct Readiness { pub(crate) started: Option, pub(crate) open_pr_url: Option, + pub(crate) can_continue: bool, } /// What selection reads of origin, GitHub and the Launch directory. Each @@ -283,24 +284,26 @@ impl History { /// Started evidence and the current open PR from the same observation. pub(crate) fn readiness(self, issue: &IssueUrl) -> Readiness { let started = self.started(issue); - let open_pr_url = self - .latest() + let latest = self.latest(); + // ADR-0002 permits proceeding with an existing branch and no closed or merged PR. + let can_continue = latest.as_ref().is_some_and(|latest| { + latest.origin_sha.is_some() + && latest + .pr + .as_ref() + .is_none_or(|pr| pr.state == PrState::Open) + }); + let open_pr_url = latest .and_then(|latest| latest.pr) .filter(|pr| pr.state == PrState::Open) .map(|pr| pr.url); Readiness { started, open_pr_url, + can_continue, } } - /// Whether ADR-0002 allows continuing the latest Issue branch. - pub(crate) fn can_continue(self) -> bool { - self.latest().is_some_and(|latest| { - latest.origin_sha.is_some() && latest.pr.is_none_or(|pr| pr.state == PrState::Open) - }) - } - pub(crate) fn remember_bodies(&self, bodies: &mut FirstPrBodies) { for (_, pr) in &self.prs { if let Some(body) = &pr.body { diff --git a/src/logs.rs b/src/logs.rs index 2d12c15e5..a0440d4da 100644 --- a/src/logs.rs +++ b/src/logs.rs @@ -672,6 +672,10 @@ pub fn dispatch_ended(ended: &crate::run::Ended) { record().dispatch_ended(&crate::run_ending::Account::of_run(ended)); } +pub(crate) fn dispatched_self_merge_check_holds() -> std::collections::BTreeMap { + record().dispatched_self_merge_check_holds() +} + /// Keep a Pass's dispatch before the Run's fallible launch checks. pub fn dispatching( work: Work, diff --git a/src/logs/reading.rs b/src/logs/reading.rs index b217971b4..646d4f0e1 100644 --- a/src/logs/reading.rs +++ b/src/logs/reading.rs @@ -538,47 +538,31 @@ impl Command { } pub(super) fn repository_records(root: &Path) -> Result> { - read_repository_records(&Inventory::on_demand(), root) + let inventory = Inventory::on_demand(); + let mut records = BTreeMap::new(); + for folder in inventory.command_folders(root)? { + records.extend(read_records(&inventory, &folder, false)?); + } + Ok(records) } pub(super) fn self_merge_check_holds( logs_dir: &Path, repo: &crate::issue::Repo, ) -> Result { - let inventory = Arc::new(Inventory::on_demand()); + let inventory = Arc::new(Inventory::capture_repository(logs_dir, repo)?); let mut records = BTreeMap::new(); - for owner in inventory.directories(logs_dir)? { - if !owner - .file_name() - .is_some_and(|name| name.eq_ignore_ascii_case(&repo.owner)) - { - continue; - } - for path in inventory.directories(&owner)? { - if path - .file_name() - .is_some_and(|name| name.eq_ignore_ascii_case(&repo.name)) - { - records.extend(read_repository_records(&inventory, &path)?); - } - } + for folder in inventory + .repositories() + .iter() + .flat_map(|repo| &repo.folders) + { + records.extend(read_records(&inventory, folder, false)?); } let commands = command_trees(&inventory, &mut records, &Local::now()); Ok(PullRequestAttribution::from_commands(&commands).self_merge_check_holds()) } -fn read_repository_records( - inventory: &Inventory, - root: &Path, -) -> Result> { - let mut records = BTreeMap::new(); - for folder in inventory.directories(&root.join("commands"))? { - let folder = inventory.folder(&folder)?; - records.extend(read_records(inventory, &folder, false)?); - } - Ok(records) -} - fn read_records( inventory: &Inventory, folder: &Folder, diff --git a/src/logs/reading/inventory.rs b/src/logs/reading/inventory.rs index b6cbc7b1d..0eee3f670 100644 --- a/src/logs/reading/inventory.rs +++ b/src/logs/reading/inventory.rs @@ -13,6 +13,7 @@ use std::time::SystemTime; use anyhow::{Context, Result}; use chrono::{DateTime, FixedOffset}; +use crate::issue::Repo; use crate::logs::owner::{self, SessionOwner}; /// The filesystem effects of discovery, separable so tests can count them. @@ -162,6 +163,11 @@ pub(super) fn name(repo: &Path) -> String { ) } +fn has_name(path: &Path, name: &str) -> bool { + path.file_name() + .is_some_and(|entry| entry.eq_ignore_ascii_case(name)) +} + pub(super) struct Folder { pub(super) path: PathBuf, /// Regular files only, never symlinks, in enumeration order. @@ -219,13 +225,25 @@ impl Inventory { /// Only the root and the literal `commands` folder may be aliases; owner, /// repository and kind entries must be real directories. pub(super) fn capture(files: Arc, root: &Path) -> Result { + Self::capture_matching(files, root, None) + } + + /// Discover only this repository's Command folders, matching GitHub's case-insensitive names. + pub(super) fn capture_repository(root: &Path, repo: &Repo) -> Result { + Self::capture_matching(Arc::new(Native), root, Some(repo)) + } + + fn capture_matching(files: Arc, root: &Path, repo: Option<&Repo>) -> Result { let mut inventory = Self::new(files); for owner in inventory.directories(root)? { + if repo.is_some_and(|repo| !has_name(&owner, &repo.owner)) { + continue; + } for path in inventory.directories(&owner)? { - let mut folders = Vec::new(); - for folder in inventory.directories(&path.join("commands"))? { - folders.push(inventory.folder(&folder)?); + if repo.is_some_and(|repo| !has_name(&path, &repo.name)) { + continue; } + let folders = inventory.command_folders(&path)?; inventory.repositories.push(Repository { path, folders }); } } @@ -242,6 +260,13 @@ impl Inventory { &self.repositories } + pub(super) fn command_folders(&self, repo_path: &Path) -> Result>> { + self.directories(&repo_path.join("commands"))? + .iter() + .map(|path| self.folder(path)) + .collect() + } + fn list(&self, path: &Path) -> Result> { match self.files.list(path) { Ok(entries) => Ok(entries), diff --git a/src/logs/recording.rs b/src/logs/recording.rs index 66cfe9391..37f7cb637 100644 --- a/src/logs/recording.rs +++ b/src/logs/recording.rs @@ -884,6 +884,24 @@ impl Record { } } + /// Nested dispatches share this Command's record and notification. + pub(super) fn dispatched_self_merge_check_holds(&self) -> BTreeMap { + let mut holds = BTreeMap::new(); + if let Some((_, tree)) = &self.command_record { + for run in &tree.dispatched { + let Some(url) = &run.pull_request else { + continue; + }; + if let Some(reason) = run.self_merge_check_hold() { + holds.insert(url.clone(), reason.to_owned()); + } else { + holds.remove(url); + } + } + } + holds + } + pub(super) fn dispatching( &mut self, work: Work, diff --git a/src/notification.rs b/src/notification.rs index e505798c2..00d3eea7c 100644 --- a/src/notification.rs +++ b/src/notification.rs @@ -19,6 +19,7 @@ use crate::launch; use crate::logs; use crate::progress; use crate::review::PullRequestUrl; +use crate::run::ReviewHold; use crate::run_ending::Account; /// Whether a Run or a Pass emails its Run notification, by its command or, @@ -251,6 +252,15 @@ impl RunNotification { /// either. A failed write or send is only a warning: it never changes /// the command's outcome. pub fn finish(self, account: &Account) { + self.finish_with_additional_holds(account, []); + } + + /// A Custom process can leave held deliveries alongside its own result. + pub(crate) fn finish_with_additional_holds<'a>( + self, + account: &Account, + holds: impl IntoIterator, + ) { let Some(subject) = subject_line(&self.subject, self.input.as_ref(), account.outcome) else { return; @@ -276,6 +286,20 @@ impl RunNotification { host.as_deref().unwrap_or("unknown host"), self.started.elapsed(), ); + let mut waiting = logs::dispatched_self_merge_check_holds(); + waiting.extend( + holds + .into_iter() + .map(|(url, hold)| (url.into(), hold.to_string())), + ); + if account.review_hold.is_some() + && let Some(url) = account.pr_url + { + waiting.remove(url); + } + for (url, hold) in &waiting { + text += &format!("\n{}\n", crate::run_ending::held_ready(url, hold)); + } match crate::github::quota::command::notification_line() { Ok(Some(line)) => text += &format!("\n{line}\n"), Ok(None) => {} @@ -313,8 +337,11 @@ impl RunNotification { // A Paused Command a later Pickup run retakes needs no one, so it // is saved but not emailed when only unmerged runs are. let retaken = account.outcome == "paused" && crate::logs::recorded_handed_back_for_pickup(); + let quiet = self.unless_merged + && waiting.is_empty() + && (account.merged_with_nothing_waiting() || retaken); if let Some(resend) = self.resend - && !(self.unless_merged && (account.merged_with_nothing_waiting() || retaken)) + && !quiet && let Err(error) = resend.send(&subject, &text) { progress::step(format_args!( diff --git a/src/processes.rs b/src/processes.rs index fe27396e9..99d97839a 100644 --- a/src/processes.rs +++ b/src/processes.rs @@ -928,7 +928,23 @@ fn notify( .map(|resolution| resolution.url()) .collect(), }; - notification.finish(&account); + // Dispatched Runs rely on this notification. Keep a check hold even if a + // later Step fails or delivers another PR. + let primary_hold_url = delivered + .filter(|_| review_hold.is_some()) + .map(|run| run.url()); + let mut seen = BTreeSet::new(); + let additional_holds = completed.resolutions.iter().rev().filter_map(|run| { + let url = run.url(); + if run.goal().is_none() || !seen.insert(url) || primary_hold_url == Some(url) { + return None; + } + match run.review_hold() { + Some(hold @ crate::run::ReviewHold::SelfMergeCheck(_)) => Some((url, hold)), + _ => None, + } + }); + notification.finish_with_additional_holds(&account, additional_holds); } fn finish_run( diff --git a/src/ready.rs b/src/ready.rs index 56f75e32f..205bb0168 100644 --- a/src/ready.rs +++ b/src/ready.rs @@ -112,8 +112,7 @@ pub fn first( ) -> Result> { Ok( match search( - &GitHubAndOrigin::new(launch, config, authors, first_pr_bodies), - repo, + &GitHubAndOrigin::new(launch, repo, config, authors, first_pr_bodies), Settling::Wait, order, past, @@ -133,8 +132,7 @@ pub fn before_architect( authors: &[String], ) -> Result> { search( - &GitHubAndOrigin::new(launch, config, authors, &mut FirstPrBodies::new()), - repo, + &GitHubAndOrigin::new(launch, repo, config, authors, &mut FirstPrBodies::new()), Settling::Include, PickupOrder::LowestFirst, None, @@ -143,15 +141,14 @@ pub fn before_architect( fn search( reads: &GitHubAndOrigin<'_>, - repo: &Repo, settling: Settling, order: PickupOrder, past: Option, ) -> Result> { let listed = reads .github - .open_candidate_issues(&repo.slug(), READY_FOR_AGENT)?; - crate::logs::listing_disagreement(repo, &listed); + .open_candidate_issues(&reads.repo.slug(), READY_FOR_AGENT)?; + crate::logs::listing_disagreement(reads.repo, &listed); Search::new( reads, listed.issues, @@ -177,8 +174,9 @@ pub fn refresh( authors: &[String], first_pr_bodies: &mut FirstPrBodies, ) -> Result> { - let reads = GitHubAndOrigin::new(launch, config, authors, first_pr_bodies); let issue = selected.listed.issue; + let repo = issue.repo(); + let reads = GitHubAndOrigin::new(launch, &repo, config, authors, first_pr_bodies); let current = reads.github.issue(&issue)?; if !current.is_open || !current.labels.has(READY_FOR_AGENT) { return Ok(None); @@ -216,9 +214,7 @@ trait Reads { /// The issue's started evidence and current open PR from one listing. fn branches(&self, issue: &IssueUrl) -> Result; /// The reason when the latest local Run left a Self-merge check hold on this PR. - fn self_merge_check_hold(&self, issue: &IssueUrl, pr_url: &str) -> Result>; - /// Whether the latest Issue branch can be continued under ADR-0002. - fn can_continue(&self, issue: &IssueUrl) -> Result; + fn self_merge_check_hold(&self, pr_url: &str) -> Result>; /// The Tickets of `spec`, an issue with sub-issues, as a Spec run reads /// them. fn tickets(&self, spec: &IssueUrl) -> Result>; @@ -229,6 +225,7 @@ trait Reads { struct GitHubAndOrigin<'a> { launch: &'a Git, github: GitHub, + repo: &'a Repo, authors: &'a [String], config: &'a UserConfig, holds: OnceCell, @@ -238,6 +235,7 @@ struct GitHubAndOrigin<'a> { impl<'a> GitHubAndOrigin<'a> { fn new( launch: &'a Git, + repo: &'a Repo, config: &'a UserConfig, authors: &'a [String], first_pr_bodies: &'a mut FirstPrBodies, @@ -245,6 +243,7 @@ impl<'a> GitHubAndOrigin<'a> { Self { launch, github: GitHub::new(), + repo, authors, config, holds: OnceCell::new(), @@ -275,21 +274,17 @@ impl Reads for GitHubAndOrigin<'_> { Ok(self.branch_history(issue)?.readiness(issue)) } - fn self_merge_check_hold(&self, issue: &IssueUrl, pr_url: &str) -> Result> { + fn self_merge_check_hold(&self, pr_url: &str) -> Result> { let holds = match self.holds.get() { Some(holds) => holds, None => { - let holds = logs::self_merge_check_holds(&self.config.logs_dir, &issue.repo())?; + let holds = logs::self_merge_check_holds(&self.config.logs_dir, self.repo)?; self.holds.get_or_init(|| holds) } }; Ok(holds.reason(pr_url).map(str::to_owned)) } - fn can_continue(&self, issue: &IssueUrl) -> Result { - Ok(self.branch_history(issue)?.can_continue()) - } - fn tickets(&self, spec: &IssueUrl) -> Result> { self.github.tickets(spec) } @@ -638,18 +633,13 @@ fn standing_of( return passed_over(Reason::Claimed); } if let Some(pr_url) = branches.open_pr_url - && let Some(reason) = reads.self_merge_check_hold(&candidate.issue, &pr_url)? + && let Some(reason) = reads.self_merge_check_hold(&pr_url)? { return passed_over(Reason::SelfMergeCheckHold { pr_url, reason }); } - let continuing_closed_spec = if spec_run::all_closed(read.sub_issue_is_open.iter().copied()) { - if !reads.can_continue(&candidate.issue)? { - return passed_over(Reason::TicketsClosed); - } - true - } else { - false - }; + if spec_run::all_closed(read.sub_issue_is_open.iter().copied()) && !branches.can_continue { + return passed_over(Reason::TicketsClosed); + } let unsettled = read .last_shaped .filter(|shaped| wait > TimeDelta::zero() && now - shaped.at < wait); @@ -666,9 +656,7 @@ fn standing_of( let tickets = reads.tickets(&candidate.issue)?; // Read after the candidate: its Tickets may have closed since. if !tickets.iter().any(|ticket| ticket.is_open) { - if tickets.is_empty() - || !(continuing_closed_spec || reads.can_continue(&candidate.issue)?) - { + if tickets.is_empty() || !branches.can_continue { return passed_over(Reason::TicketsClosed); } } else if tickets @@ -778,21 +766,14 @@ mod tests { Ok(branch::Readiness { started: self.facts(issue).and_then(|facts| facts.started.clone()), open_pr_url: None, + can_continue: false, }) } - fn self_merge_check_hold( - &self, - _issue: &IssueUrl, - _pr_url: &str, - ) -> Result> { + fn self_merge_check_hold(&self, _pr_url: &str) -> Result> { Ok(None) } - fn can_continue(&self, _issue: &IssueUrl) -> Result { - Ok(false) - } - fn tickets(&self, spec: &IssueUrl) -> Result> { self.seen.borrow_mut().push(Seen::TicketsRead(spec.number)); let facts = self.facts(spec).expect("only a Spec's Tickets are read"); diff --git a/src/run_ending.rs b/src/run_ending.rs index 0d97af7cf..bcac32b81 100644 --- a/src/run_ending.rs +++ b/src/run_ending.rs @@ -791,7 +791,7 @@ impl Shown { const REVIEW_WAITING: &str = " is ready for review waiting for "; -pub(crate) fn held_ready(url: &str, hold: &crate::run::ReviewHold) -> String { +pub(crate) fn held_ready(url: &str, hold: impl fmt::Display) -> String { format!("PR {url}{REVIEW_WAITING}{hold}") } diff --git a/tests/pickup_run.rs b/tests/pickup_run.rs index 035b82eb1..db9a1062b 100644 --- a/tests/pickup_run.rs +++ b/tests/pickup_run.rs @@ -1893,6 +1893,14 @@ fn an_all_closed_spec_with_an_empty_later_ticket_read_is_still_passed_over() { &no_ready_issue_after(&[EVERY_TICKET_CLOSED]), ); assert_eq!(scenario.issue_labels(7), [READY_FOR_AGENT]); + assert_eq!( + scenario + .gh_calls_of("pr", "list") + .iter() + .filter(|args| args.iter().any(|arg| arg == "head:issue-7")) + .count(), + 1 + ); } #[test] diff --git a/tests/process.rs b/tests/process.rs index 432b4bd87..362b2c742 100644 --- a/tests/process.rs +++ b/tests/process.rs @@ -4561,6 +4561,62 @@ printf '%s\n' "$url" > "$FAKE_CLAUDE_FINAL_MESSAGE" ); } +#[test] +fn a_later_process_failure_keeps_the_dispatched_self_merge_hold_in_email() { + let scenario = Scenario::new(); + scenario.origin_has_commit( + "main", + "check", + "#!/bin/sh\necho Day shift decides\nexit 1\n", + "Add check", + ); + scenario.user_config_is( + "[email]\nunless_merged = true\nto = 'me@example.com'\n\ + [merge]\nself_merge_check = { 'acme/widgets' = 'check' }\n", + ); + write_process( + &scenario, + "publish", + &format!("{PUBLISH_THEN_RUN}\n[[steps]]\nname = 'after'\ncommand = 'exit 1'\n"), + ); + scenario.agent_does_in_session( + 1, + r#" +url=$(gh issue create --title Ticket --body 'Do the thing') +printf '%s\n' "$url" > "$FAKE_CLAUDE_FINAL_MESSAGE" +"#, + ); + scenario.agent_does_for(8, &agent_lands_ticket(8, "main")); + let resend = ResendStandIn::replying(200, ACCEPTED); + + let result = scenario.run_with_env( + &["process", "publish", "merge"], + &[ + ("THIRDSHIFT_RESEND_URL", resend.url()), + ("RESEND_API_KEY", KEY), + ], + ); + + assert_eq!(result.code, Some(1), "{}", result.stderr); + assert!(result.stderr.contains("step after:"), "{}", result.stderr); + assert!( + result.stderr.contains("Day shift decides"), + "{}", + result.stderr + ); + let pr = pr_from(&scenario, "issue-8"); + assert_eq!(pr["state"], "OPEN"); + assert_eq!(pr["isDraft"], false); + let requests = resend.requests(); + assert_eq!(requests.len(), 1, "{requests:?}"); + let email = requests[0].body["text"].as_str().unwrap(); + assert!(email.contains("Result: failed"), "{email}"); + assert!( + email.contains("Self-merge check held: Day shift decides"), + "{email}" + ); +} + fn agent_lands_ticket(issue: u32, base: &str) -> String { format!( r#" diff --git a/tests/process/published.rs b/tests/process/published.rs index c093b9a3a..5fd5daf8e 100644 --- a/tests/process/published.rs +++ b/tests/process/published.rs @@ -708,6 +708,98 @@ printf 'parent skills retained' > "$FAKE_CLAUDE_FINAL_MESSAGE" assert_eq!(result.stdout.trim(), "parent skills retained"); } +#[test] +fn a_nested_published_ticket_hold_reaches_its_owning_process_email() { + let scenario = Scenario::new(); + scenario.origin_has_commit( + "main", + "check", + r#"#!/bin/sh +case "$PR_BODY" in + *'Closes #9'*) echo Day shift decides nested Ticket; exit 1 ;; +esac +"#, + "Add check", + ); + scenario.user_config_is( + "[email]\nunless_merged = true\nto = 'me@example.com'\n\ + [merge]\nself_merge_check = { 'acme/widgets' = 'check' }\n", + ); + write_process( + &scenario, + "publish", + &format!("{PUBLISH_THEN_RUN}process = \"contractor\"\n"), + ); + write_process( + &scenario, + "contractor", + r#"version = 1 +description = "Dispatch a nested Ticket and deliver the outer Ticket" +[worktrees.ticket] +kind = "issue-branch" +[[steps]] +name = "publish-nested" +skill = "to-spec" +worktree = "ticket" +[[steps]] +name = "run-nested" +catalogue = "run-published-issue" +worktree = "ticket" +[[steps]] +name = "change" +worktree = "ticket" +command = """ +echo contractor > contractor.txt +git add contractor.txt +git commit -qm contractor +gh pr create --base main --head issue-8 --title Contractor --body 'Closes #8' +""" +[[steps]] +name = "deliver" +catalogue = "delivery" +worktree = "ticket" +[[steps]] +name = "merge" +catalogue = "self-merge" +worktree = "ticket" +"#, + ); + let publish = r#"url=$(gh issue create --title Ticket --body 'Do the thing') +printf '%s\n' "$url" > "$FAKE_CLAUDE_FINAL_MESSAGE" +"#; + scenario.agent_does_in_session(1, publish); + scenario.agent_does_in_session(2, publish); + scenario.agent_does_for(9, &agent_lands_ticket(9, "main")); + let resend = ResendStandIn::replying(200, ACCEPTED); + + let result = scenario.run_with_env( + &["process", "publish", "merge"], + &[ + ("THIRDSHIFT_RESEND_URL", resend.url()), + ("RESEND_API_KEY", KEY), + ], + ); + + assert_eq!(result.code, Some(0), "{}", result.stderr); + assert!( + result.stderr.contains("Day shift decides nested Ticket"), + "{}", + result.stderr + ); + let nested = pr_from(&scenario, "issue-9"); + assert_eq!(nested["state"], "OPEN"); + assert_eq!(nested["isDraft"], false); + assert_eq!(pr_from(&scenario, "issue-8")["state"], "MERGED"); + let requests = resend.requests(); + assert_eq!(requests.len(), 1, "{requests:?}"); + let email = requests[0].body["text"].as_str().unwrap(); + assert!( + email.contains("Self-merge check held: Day shift decides nested Ticket"), + "{email}" + ); + assert!(email.contains(nested["url"].as_str().unwrap()), "{email}"); +} + #[test] fn a_base_fix_after_nested_dispatch_keeps_its_outer_ticket_parent() { let scenario = Scenario::new();