diff --git a/GLOSSARY.md b/GLOSSARY.md index d1a869311..a20be9b48 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -28,9 +28,9 @@ _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. -_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. +_Avoid_: queued issue, backlog item **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 121edfb6e..322c4047a 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -4492,6 +4492,8 @@ 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 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. Add `skip-author ` (or `--skip-author `) 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 ` still runs the named issue under the usual trust checks. The word never makes an untrusted author eligible. diff --git a/site/docs/index.html b/site/docs/index.html index 399325746..79c36e83c 100644 --- a/site/docs/index.html +++ b/site/docs/index.html @@ -4188,6 +4188,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 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 ce7978a5f..e9485d670 100644 --- a/site/how-it-works/index.html +++ b/site/how-it-works/index.html @@ -270,7 +270,6 @@

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.

@@ -318,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 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 795d7ba27..57771bd20 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 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.

+

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. 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, then looks for the next Ready issue. 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/selection.rs b/src/fix/selection.rs index cd20632d6..deb7ed3aa 100644 --- a/src/fix/selection.rs +++ b/src/fix/selection.rs @@ -8,7 +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::logs::{self, SelfMergeCheckHolds}; use crate::review::{PullRequestUrl, Reservation}; use crate::worktree::Worktree; @@ -87,7 +87,7 @@ enum Recheck { } impl Pass<'_> { - fn read_holds(&self) -> Result> { + fn read_holds(&self) -> Result> { self.hold_logs .map(|logs_dir| logs::self_merge_check_holds(logs_dir, &self.launch.repo)) .transpose() @@ -97,7 +97,7 @@ impl Pass<'_> { &self, pr: &PullRequestUrl, reserved: bool, - holds: Option<&PullRequestAttribution>, + holds: Option<&SelfMergeCheckHolds>, ) -> Result> { self.github.observe_fix_candidate( pr, @@ -105,7 +105,7 @@ impl Pass<'_> { self.author, reserved, self.sign_off_hold, - holds.is_some_and(|holds| holds.self_merge_check_held(&pr.url)), + holds.is_some_and(|holds| holds.reason(&pr.url).is_some()), ) } diff --git a/src/logs.rs b/src/logs.rs index c7a800944..a0440d4da 100644 --- a/src/logs.rs +++ b/src/logs.rs @@ -28,7 +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::SelfMergeCheckHolds; pub(crate) use reading::catalog; pub(crate) use reading::run_for_pull_request; mod recording; @@ -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, @@ -717,8 +721,8 @@ pub(crate) fn record_for_pull_request(root: &Path, url: &str) -> anyhow::Result< pub(crate) fn self_merge_check_holds( logs_dir: &Path, repo: &Repo, -) -> anyhow::Result { - reading::repository_hold_attribution(logs_dir, 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 ee1c1ed3c..5602386ae 100644 --- a/src/logs/command_record.rs +++ b/src/logs/command_record.rs @@ -425,14 +425,6 @@ 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> { @@ -482,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 c5462aba4..646d4f0e1 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}; @@ -538,45 +538,29 @@ 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) } -/// 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( +pub(super) fn self_merge_check_holds( 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) - }; +) -> Result { + let inventory = Arc::new(Inventory::capture_repository(logs_dir, repo)?); 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)?); - } + 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)) -} - -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) + Ok(PullRequestAttribution::from_commands(&commands).self_merge_check_holds()) } fn read_records( diff --git a/src/logs/reading/attribution.rs b/src/logs/reading/attribution.rs index d6ebbde9e..2d32fe625 100644 --- a/src/logs/reading/attribution.rs +++ b/src/logs/reading/attribution.rs @@ -30,7 +30,16 @@ 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 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. @@ -69,9 +78,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. @@ -98,7 +114,10 @@ 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.held_by_self_merge_check(), + self_merge_check_hold: command + .record + .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 67e4a99dc..7db760007 100644 --- a/src/logs/reading/inbox.rs +++ b/src/logs/reading/inbox.rs @@ -334,24 +334,21 @@ 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( + /// 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>, - rows: &mut Vec, + held: &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() + if child.record.pull_request.is_some() && child.record.self_merge_check_hold().is_some() { - rows.push(Self::new(Observation::Record(child), local)); + held.push(Self::new(Observation::Record(child), local)); } - Self::collect_held_base_fixes(child, local, rows); + Self::collect_held_children(child, local, held); } - for child in &command.dispatched { - Self::collect_held_base_fixes(child, local, rows); + for run in &command.dispatched { + Self::collect_held_children(run, local, held); } } @@ -494,18 +491,20 @@ 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 mut held_children = Vec::new(); let captured: Vec<_> = entries .iter() .map(|entry| { - 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) + Captured::new( + match entry { + Entry::Record(command) => { + Captured::collect_held_children(command, &mut local, &mut held_children); + Observation::Record(command) + } + Entry::History(command) => Observation::History(command), + }, + &mut local, + ) }) .collect(); let observations: Vec<_> = captured @@ -524,7 +523,7 @@ pub(super) fn evaluate<'a>( && (carried.is_none() || record_pull_request(&run.command) != carried) })) }) - .chain(&held_base_fixes) + .chain(&held_children) .collect(); let starts: Vec<_> = observations .iter() 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 c0d69e537..428cfb4d8 100644 --- a/src/ready.rs +++ b/src/ready.rs @@ -5,7 +5,7 @@ //! definition. An Architect run also waits for an issue that meets every //! Ready issue condition except settling. -use std::cell::RefCell; +use std::cell::{OnceCell, RefCell}; use std::path::Path; use anyhow::Result; @@ -19,7 +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::logs::{self, SelfMergeCheckHolds}; use crate::progress; use crate::spec_run::{self, Unstartable}; use crate::trust::{self, UntrustedIssue}; @@ -98,7 +98,7 @@ 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. @@ -230,7 +230,7 @@ trait Reads { enum Continuation { Available, Unavailable, - Held(String), + Held { pr_url: String, reason: String }, } /// The reads of GitHub and of the Launch directory `launch`'s origin. @@ -240,7 +240,7 @@ struct GitHubAndOrigin<'a> { authors: &'a [String], logs_dir: &'a Path, first_pr_bodies: RefCell<&'a mut FirstPrBodies>, - holds: RefCell>, + holds: OnceCell, } impl<'a> GitHubAndOrigin<'a> { @@ -256,7 +256,7 @@ impl<'a> GitHubAndOrigin<'a> { authors, logs_dir, first_pr_bodies: RefCell::new(first_pr_bodies), - holds: RefCell::new(None), + holds: OnceCell::new(), } } @@ -266,14 +266,15 @@ impl<'a> GitHubAndOrigin<'a> { 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))) + fn hold_reason(&self, issue: &IssueUrl, pr: &str) -> Result> { + let holds = match self.holds.get() { + Some(holds) => holds, + None => { + let holds = logs::self_merge_check_holds(self.logs_dir, &issue.repo())?; + self.holds.get_or_init(|| holds) + } + }; + Ok(holds.reason(pr)) } } @@ -296,8 +297,11 @@ impl Reads for GitHubAndOrigin<'_> { 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())); + if let Some(reason) = self.hold_reason(issue, &pr.url)? { + return Ok(Continuation::Held { + pr_url: pr.url.clone(), + reason: reason.to_owned(), + }); } } Ok(if history.can_continue() { @@ -346,7 +350,10 @@ enum Reason { evidence: Started, never_claimed: bool, }, - HeldBySelfMergeCheck(String), + 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, @@ -525,8 +532,8 @@ 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::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) => { @@ -603,7 +610,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 local Run +/// 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 @@ -665,7 +673,9 @@ fn standing_of( match reads.continuation(&candidate.issue)? { Continuation::Available => true, Continuation::Unavailable => false, - Continuation::Held(pr) => return passed_over(Reason::HeldBySelfMergeCheck(pr)), + Continuation::Held { pr_url, reason } => { + return passed_over(Reason::SelfMergeCheckHold { pr_url, reason }); + } } } else { false 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/base_fix.rs b/tests/base_fix.rs index ff99b8ea3..6e60a6a7a 100644 --- a/tests/base_fix.rs +++ b/tests/base_fix.rs @@ -329,6 +329,24 @@ fn a_base_fix_obeys_the_self_merge_check() { result.stderr ); if check_exit == 1 { + 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 + .lines() + .any(|line| { line.trim() == "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/fix_pass.rs b/tests/fix_pass.rs index 9b128ecac..aa312e4bd 100644 --- a/tests/fix_pass.rs +++ b/tests/fix_pass.rs @@ -129,16 +129,21 @@ fn fix_pass_skips_a_self_merge_check_hold_until_the_pr_has_red_ci() { let head = scenario.origin_git(&["rev-parse", "issue-7"]); 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); + } let mut state = scenario.gh_state(); state["checks"][head.trim()] = json!([{"name": "test", "conclusion": "failure"}]); @@ -388,6 +393,52 @@ fn a_fix_pass_can_self_merge_after_a_previous_self_merge_check_hold() { ); } +#[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 aee3c6228..cfdc338d8 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] @@ -2336,6 +2344,67 @@ 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")); + + 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); + 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"); + assert_eq!(pr_lists_for_held_issue() - prior_pr_lists, 1); +} + const RED: &str = r#"[{"name": "test", "conclusion": "failure"}]"#; const GREEN: &str = r#"[{"name": "test", "conclusion": "success"}]"#; @@ -4281,7 +4350,7 @@ fn pickup_leaves_an_open_pull_request_held_by_the_self_merge_check() { assert_eq!(next.code, Some(0), "{}", next.stderr); assert!( next.stderr.contains(&format!( - "{} is held by the Self-merge check", + "waits for the Day shift on PR {}: Self-merge check held: Day shift decides", pr["url"].as_str().unwrap() )), "{}", @@ -4299,7 +4368,9 @@ fn pickup_reports_the_hold_as_the_reason_no_issue_was_taken() { 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 + .contains("Self-merge check held: Day shift decides"), "{}", waiting.stderr ); 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();