diff --git a/GLOSSARY.md b/GLOSSARY.md index 008b1c0bf..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. diff --git a/docs/guide.md b/docs/guide.md index a2c43b261..121edfb6e 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -4509,6 +4509,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 313de0b2d..399325746 100644 --- a/site/docs/index.html +++ b/site/docs/index.html @@ -4202,6 +4202,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/site/how-it-works/index.html b/site/how-it-works/index.html index 7727fd5c1..ce7978a5f 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 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..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. 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 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 b9ebf4c8e..18dad1664 100644 --- a/src/branch.rs +++ b/src/branch.rs @@ -279,6 +279,13 @@ impl History { }) } + 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/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/fix/selection.rs b/src/fix/selection.rs index fe1c2f6a2..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; @@ -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; @@ -17,28 +18,24 @@ 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 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, + 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) = - github.observe_fix_candidate(pr, base, author, false, sign_off_hold)? - else { + let Some(candidate) = pass.observe(pr, false, holds.as_ref())? else { continue; }; if candidate.needs_repair { @@ -59,12 +56,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 +76,7 @@ struct Pass<'a> { github: &'a GitHub, author: Option<&'a str>, sign_off_hold: Option<&'a SignOffHold>, + hold_logs: Option<&'a Path>, passed_over: &'a mut Vec, } @@ -95,6 +87,28 @@ enum Recheck { } impl Pass<'_> { + 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, + holds.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 +138,8 @@ 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 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/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..c7a800944 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; @@ -715,9 +716,9 @@ pub(crate) fn record_for_pull_request(root: &Path, url: &str) -> 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)) + 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/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.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 cc362690b..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 } @@ -93,11 +98,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 0013e59b9..658121659 100644 --- a/src/pass.rs +++ b/src/pass.rs @@ -258,7 +258,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, @@ -281,12 +281,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 4dffc3b40..a16dcc04b 100644 --- a/src/pickup.rs +++ b/src/pickup.rs @@ -192,14 +192,10 @@ 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, - first_pr_bodies, - )? - .map(|ready| (ready, reservation))) + Ok( + crate::ready::refresh(directory.git(), ready, config, &authors, first_pr_bodies)? + .map(|ready| (ready, reservation)), + ) }, ) } diff --git a/src/pull_request.rs b/src/pull_request.rs index 1444c61b4..fbd089ec5 100644 --- a/src/pull_request.rs +++ b/src/pull_request.rs @@ -138,9 +138,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> { @@ -518,8 +518,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/src/ready.rs b/src/ready.rs index ef939b522..c0d69e537 100644 --- a/src/ready.rs +++ b/src/ready.rs @@ -6,6 +6,7 @@ //! Ready issue condition except settling. use std::cell::RefCell; +use std::path::Path; use anyhow::Result; use chrono::{DateTime, TimeDelta, Utc}; @@ -13,10 +14,12 @@ use chrono::{DateTime, TimeDelta, Utc}; use crate::base_fix; use crate::branch::{self, FirstPrBodies, 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, PullRequestAttribution}; use crate::progress; use crate::spec_run::{self, Unstartable}; use crate::trust::{self, UntrustedIssue}; @@ -102,7 +105,7 @@ enum Settling { pub fn first( launch: &Git, repo: &Repo, - wait: TimeDelta, + config: &UserConfig, order: PickupOrder, past: Option, authors: &[String], @@ -110,9 +113,9 @@ pub fn first( ) -> Result> { Ok( match search( - &GitHubAndOrigin::new(launch, authors, first_pr_bodies), + &GitHubAndOrigin::new(launch, authors, &config.logs_dir, first_pr_bodies), repo, - wait, + config.pickup_wait, Settling::Wait, order, past, @@ -128,13 +131,13 @@ pub fn first( pub fn before_architect( launch: &Git, repo: &Repo, - wait: TimeDelta, + config: &UserConfig, authors: &[String], ) -> Result> { search( - &GitHubAndOrigin::new(launch, authors, &mut FirstPrBodies::new()), + &GitHubAndOrigin::new(launch, authors, &config.logs_dir, &mut FirstPrBodies::new()), repo, - wait, + config.pickup_wait, Settling::Include, PickupOrder::LowestFirst, None, @@ -174,11 +177,11 @@ fn search( pub fn refresh( launch: &Git, selected: ReadyIssue, - wait: TimeDelta, + config: &UserConfig, authors: &[String], first_pr_bodies: &mut FirstPrBodies, ) -> Result> { - let reads = GitHubAndOrigin::new(launch, authors, first_pr_bodies); + let reads = GitHubAndOrigin::new(launch, authors, &config.logs_dir, first_pr_bodies); let issue = selected.listed.issue; let current = reads.github.issue(&issue)?; if !current.is_open || !current.labels.has(READY_FOR_AGENT) { @@ -189,7 +192,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,29 +219,44 @@ trait Reads { fn candidate(&self, issue: &IssueUrl) -> Result; /// What shows `issue` was ever started, if it was. fn started(&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, github: GitHub, authors: &'a [String], + logs_dir: &'a Path, first_pr_bodies: RefCell<&'a mut FirstPrBodies>, + holds: RefCell>, } impl<'a> GitHubAndOrigin<'a> { - fn new(launch: &'a Git, authors: &'a [String], first_pr_bodies: &'a mut FirstPrBodies) -> Self { + fn new( + launch: &'a Git, + authors: &'a [String], + logs_dir: &'a Path, + first_pr_bodies: &'a mut FirstPrBodies, + ) -> Self { Self { launch, github: GitHub::new(), authors, + logs_dir, first_pr_bodies: RefCell::new(first_pr_bodies), + holds: RefCell::new(None), } } @@ -241,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<'_> { @@ -259,8 +293,18 @@ impl Reads for GitHubAndOrigin<'_> { Ok(self.branch_history(issue)?.started(issue)) } - fn can_continue(&self, issue: &IssueUrl) -> Result { - Ok(self.branch_history(issue)?.can_continue()) + fn continuation(&self, issue: &IssueUrl) -> Result { + 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 history.can_continue() { + Continuation::Available + } else { + Continuation::Unavailable + }) } fn tickets(&self, spec: &IssueUrl) -> Result> { @@ -302,6 +346,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, @@ -480,6 +525,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; @@ -590,8 +638,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, @@ -601,33 +649,41 @@ fn standing_of( if read.claimed { return passed_over(Reason::Claimed); } - 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 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, + Continuation::Unavailable => false, + Continuation::Held(pr) => return passed_over(Reason::HeldBySelfMergeCheck(pr)), } - true } else { false }; - let unsettled = read - .last_shaped - .filter(|shaped| wait > TimeDelta::zero() && now - shaped.at < wait); + if !can_continue && known_closed_spec { + return passed_over(Reason::TicketsClosed); + } // 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() - || !(continuing_closed_spec || reads.can_continue(&candidate.issue)?) - { + if tickets.is_empty() || !can_continue { return passed_over(Reason::TicketsClosed); } } else if tickets @@ -737,8 +793,8 @@ mod tests { Ok(self.facts(issue).and_then(|facts| facts.started.clone())) } - 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/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 823a7b21b..9b128ecac 100644 --- a/tests/fix_pass.rs +++ b/tests/fix_pass.rs @@ -189,6 +189,183 @@ 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 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 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 record = held_command_record(&scenario); + let staged = scenario.path("late-hold.json"); + std::fs::rename(&record, &staged).unwrap(); + 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 = 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"); + 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(); + 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..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(); @@ -4157,6 +4206,156 @@ fn a_handed_back_open_pr_is_continued_using_its_base() { ); } +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"); + 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), + ], + ); + 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(); + 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")); + + 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(), 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 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 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();