diff --git a/services/common/contract/worker_messages.json b/services/common/contract/worker_messages.json index a547be183..c54bc22cd 100644 --- a/services/common/contract/worker_messages.json +++ b/services/common/contract/worker_messages.json @@ -18,6 +18,7 @@ "await_merge": {"type":"await_merge","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","pr_number":2,"head_sha":"abc","base_branch":"main","self_authored":true,"attempts":1,"chain_id":"c","error_retries":0}, "graph_index": {"type":"graph_index","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","branch":"main","changed_files":["a.rs"]}, "release_notes": {"type":"release_notes","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","tag":"v1.0.0","sha":"abc","resend":"","check_branch":true}, + "restack": {"type":"restack","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","branch":"coderhelm/feature-a","before":"abc","after":"def"}, "tag_sweep": {"type":"tag_sweep","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","base_branch":"main","pr_number":2,"delay_remaining_secs":0,"sweep_id":"s","manual":true,"claimed":false,"attempt":0}, "test_ingest": {"type":"test_ingest","team_id":"TEAM#team-a","installation_id":1,"repo_owner":"acme","repo_name":"widgets","repo_id":9,"default_branch":"main","workflow":"e2e","workflow_path":".github/workflows/e2e.yml","run_id":10,"run_attempt":1,"head_sha":"abc","head_branch":"main","event":"push","pr_numbers":[2],"conclusion":"success","html_url":"https://example.test/run/10","started_at":"2026-01-01T00:00:00Z","updated_at":"2026-01-01T00:10:00Z","upload_key":null}, "test_action": {"type":"test_action","team_id":"TEAM#team-a","repo":"acme/widgets","action":"fix","target_id":"t1","actor":"someone"}, diff --git a/services/common/src/dlq.rs b/services/common/src/dlq.rs index 6467a28e6..acdb897cc 100644 --- a/services/common/src/dlq.rs +++ b/services/common/src/dlq.rs @@ -43,6 +43,8 @@ pub const WORKER_MESSAGE_TYPES: &[&str] = &[ "await_merge", "release_steps", "tag_sweep", + // A force push: the pull requests stacked on that branch are rebuilt. + "restack", "release_notes", "graph_index", "test_ingest", diff --git a/services/common/src/messages.rs b/services/common/src/messages.rs index 17bc7fe70..dda7763fe 100644 --- a/services/common/src/messages.rs +++ b/services/common/src/messages.rs @@ -85,6 +85,11 @@ pub enum WorkerMessage { /// branch's current HEAD — skipping if that commit is already tagged. #[serde(rename = "tag_sweep")] TagSweep(TagSweepMessage), + /// A branch was force-pushed (rebased): CoderHelm's open pull requests + /// stacked on it get their own change rebuilt on its new head, one at + /// a time (`worker::passes::restack`). + #[serde(rename = "restack")] + Restack(RestackMessage), /// Release notes for a release tag CoderHelm just cut (or a re-send from the /// dashboard): GitHub Release + Confluence changelog entry + IT email. #[serde(rename = "release_notes")] @@ -345,9 +350,10 @@ impl WorkerMessage { use crate::usage::feature as f; match self { WorkerMessage::Ticket(t) if matches!(t.source, TicketSource::Alert) => f::ALERT, - WorkerMessage::Ticket(_) | WorkerMessage::Resume(_) | WorkerMessage::MarkReady(_) => { - f::RUN - } + WorkerMessage::Ticket(_) + | WorkerMessage::Resume(_) + | WorkerMessage::MarkReady(_) + | WorkerMessage::Restack(_) => f::RUN, WorkerMessage::Feedback(_) | WorkerMessage::JiraComment(_) => f::FEEDBACK, WorkerMessage::Lesson(_) | WorkerMessage::RewardOutcome(_) => f::MEMORY, WorkerMessage::Onboard(_) => f::ONBOARD, @@ -727,6 +733,20 @@ pub struct MarkReadyMessage { pub pr_number: u64, } +/// A force push to `branch` (from `before` to `after`). +#[derive(Serialize, Deserialize, Debug, Default, Clone)] +pub struct RestackMessage { + pub team_id: String, + pub installation_id: u64, + pub repo_owner: String, + pub repo_name: String, + pub branch: String, + /// The branch's head before the push: where the stacked branches' + /// own work starts. + pub before: String, + pub after: String, +} + #[derive(Serialize, Deserialize, Debug, Default)] pub struct PlanExecuteMessage { pub team_id: String, diff --git a/services/gateway/src/routes/github_webhook.rs b/services/gateway/src/routes/github_webhook.rs index 8065342c5..a21798177 100644 --- a/services/gateway/src/routes/github_webhook.rs +++ b/services/gateway/src/routes/github_webhook.rs @@ -3623,6 +3623,38 @@ fn tool_definition_paths(payload: &Value) -> Vec { paths } +/// The rebuild a push asks for: a force push (not a deletion or a new +/// branch) to a branch other than the default one. +fn restack_message( + payload: &Value, + installation_id: u64, + team_id: &str, + owner: &str, + name: &str, +) -> Option { + let flag = |k: &str| payload[k].as_bool().unwrap_or(false); + if !flag("forced") || flag("deleted") || flag("created") { + return None; + } + let branch = payload["ref"].as_str()?.strip_prefix("refs/heads/")?; + let default_branch = payload["repository"]["default_branch"] + .as_str() + .unwrap_or("main"); + let before = payload["before"].as_str().unwrap_or(""); + if branch == default_branch || before.is_empty() || before.chars().all(|c| c == '0') { + return None; + } + Some(crate::models::RestackMessage { + team_id: team_id.to_string(), + installation_id, + repo_owner: owner.to_string(), + repo_name: name.to_string(), + branch: branch.to_string(), + before: before.to_string(), + after: payload["after"].as_str().unwrap_or("").to_string(), + }) +} + async fn handle_push( state: &AppState, payload: &Value, @@ -3648,6 +3680,16 @@ async fn handle_push( if let Some(tag) = git_ref.strip_prefix("refs/tags/") { return handle_tag_push(state, payload, installation_id, team_id, owner, name, tag).await; } + // A force push (a rebase) to a branch other pull requests may stack on: + // CoderHelm's stacked pull requests get rebuilt on its new head. + if let Some(m) = restack_message(payload, installation_id, team_id, owner, name) { + let _ = send_to_queue( + state, + &state.config.ticket_queue_url, + &WorkerMessage::Restack(m), + ) + .await; + } // Only the branch the graph tracks. if git_ref != format!("refs/heads/{default_branch}") { return Ok(StatusCode::OK); @@ -5012,3 +5054,47 @@ mod close_reason_tests { assert!(!is_own_actor(&serde_json::json!({}))); } } + +#[cfg(test)] +mod restack_tests { + use super::*; + + #[test] + fn only_a_force_push_to_another_branch_rebuilds_its_stack() { + let push = |forced: bool, r: &str, before: &str| { + serde_json::json!({ + "ref": r, + "forced": forced, + "before": before, + "after": "b2", + "repository": {"default_branch": "main"}, + }) + }; + let m = restack_message( + &push(true, "refs/heads/coderhelm/feature-a", "a1"), + 7, + "t1", + "acme", + "web", + ) + .unwrap(); + assert_eq!( + (m.branch.as_str(), m.before.as_str(), m.after.as_str()), + ("coderhelm/feature-a", "a1", "b2") + ); + assert_eq!((m.installation_id, m.repo_owner.as_str()), (7, "acme")); + // A plain push, the default branch, a tag, a new branch: nothing. + for p in [ + push(false, "refs/heads/coderhelm/feature-a", "a1"), + push(true, "refs/heads/main", "a1"), + push(true, "refs/tags/v1", "a1"), + push( + true, + "refs/heads/x", + "0000000000000000000000000000000000000000", + ), + ] { + assert!(restack_message(&p, 7, "t1", "acme", "web").is_none()); + } + } +} diff --git a/services/worker/src/clients/github.rs b/services/worker/src/clients/github.rs index 9dd8fd024..8cf46f183 100644 --- a/services/worker/src/clients/github.rs +++ b/services/worker/src/clients/github.rs @@ -1706,137 +1706,222 @@ impl GitHubClient { Ok(RebaseResult::Rebased(tip)) } - /// `git rebase --onto`: moves `branch` onto `onto` replaying only its - /// own commits, leaving out `drop` (copies of `onto`'s commits under - /// other hashes, which `onto` already has) and merge commits. The result - /// must hold the code the branch would have with `onto` merged in - /// ([`onto_holds`]), and the branch moves with a lease, as in - /// [`Self::rebase_branch`]. - pub async fn rebase_onto( + // ─── Building a change on another branch, file by file ───── + + /// Every commit in `base...head`, oldest first, following GitHub's + /// pages until the compare's `total_commits` are all listed. An error + /// when they can't all be read: a partial list would leave work out. + pub async fn compare_all_commits( &self, owner: &str, repo: &str, - branch: &str, - onto: &str, - drop: &[String], - lease: &str, - ) -> Result> { - let onto_sha = self.get_ref(owner, repo, onto).await?; - let cmp = self - .get(&format!( - "{API_BASE}/repos/{owner}/{repo}/compare/{onto_sha}...{lease}" - )) - .await?; - let onto_in_branch = cmp["behind_by"].as_u64() == Some(0); - if onto_in_branch && drop.is_empty() { - return Ok(RebaseResult::UpToDate); + base: &str, + head: &str, + ) -> Result, Box> { + let mut out = Vec::new(); + let mut total = 0usize; + for page in 1..=200u32 { + let data = self + .get(&format!( + "{API_BASE}/repos/{owner}/{repo}/compare/{base}...{head}?per_page=100&page={page}" + )) + .await?; + total = data["total_commits"].as_u64().unwrap_or(0) as usize; + let batch = data["commits"].as_array().cloned().unwrap_or_default(); + let empty = batch.is_empty(); + out.extend(batch); + if out.len() >= total || empty { + break; + } } - let Some((steps, merges_dropped)) = onto_steps(&cmp, drop) else { - return Ok(RebaseResult::NotClean( - "too many commits to replay".to_string(), - )); - }; - if steps.is_empty() { - return Ok(RebaseResult::NotClean( - "the branch has no commits of its own".to_string(), - )); + if out.len() < total { + return Err(format!( + "GitHub listed {} of the {total} commits in {base}...{head}", + out.len() + ) + .into()); } - let scratch = format!( - "coderhelm-rebase/{branch}-{}", - chrono::Utc::now().timestamp_millis() - ); - self.create_branch(owner, repo, &scratch, &onto_sha).await?; - let result = self - .replay(owner, repo, &scratch, &onto_sha, lease, &steps) - .await; - let _ = self.delete_branch(owner, repo, &scratch).await; - let (tip, tip_tree) = match result? { - Ok(t) => t, - Err(why) => return Ok(RebaseResult::NotClean(why)), - }; - let branch_tree = self.git_commit(owner, repo, lease).await?["tree"]["sha"] + Ok(out) + } + + /// A commit's tree and parents (the git data API). + pub async fn commit_tree_parents( + &self, + owner: &str, + repo: &str, + sha: &str, + ) -> Result<(String, Vec), Box> { + let c = self.git_commit(owner, repo, sha).await?; + let tree = c["tree"]["sha"] .as_str() - .unwrap_or("") + .ok_or("Missing tree sha in commit")? .to_string(); - let merged_tree = if onto_in_branch { - None - } else { - let check = format!("{scratch}-check"); - self.create_branch(owner, repo, &check, lease).await?; - let merged = self - .merge_returning(owner, repo, &check, &onto_sha, "rebase check") - .await; - let _ = self.delete_branch(owner, repo, &check).await; - merged?.and_then(|c| { - c.pointer("/commit/tree/sha") - .and_then(|v| v.as_str()) - .map(String::from) - }) - }; - if let Err(why) = onto_holds( - onto_in_branch, - &branch_tree, - merged_tree.as_deref(), - merges_dropped, - &tip_tree, - ) { - return Ok(RebaseResult::NotClean(why)); - } - if self.get_ref(owner, repo, branch).await? != lease { - return Ok(RebaseResult::Moved); + let parents = c["parents"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| p["sha"].as_str().map(String::from)) + .collect(); + Ok((tree, parents)) + } + + /// A tree's entries by path: the whole tree in one read when GitHub + /// returns it complete, else `None` (the caller walks it level by level + /// with [`Self::tree_level`]). + pub async fn tree_all( + &self, + owner: &str, + repo: &str, + tree: &str, + ) -> Result>, Box> { + let data = self + .get(&format!( + "{API_BASE}/repos/{owner}/{repo}/git/trees/{tree}?recursive=1" + )) + .await?; + if data["truncated"].as_bool().unwrap_or(false) { + return Ok(None); } - self.move_scratch_ref(owner, repo, branch, &tip).await?; - self.invalidate_snapshot(owner, repo, branch).await; - Ok(RebaseResult::Rebased(tip)) + Ok(Some( + data["tree"] + .as_array() + .into_iter() + .flatten() + .filter_map(|e| Some((e["path"].as_str()?.to_string(), GitEntry::from_json(e)?))) + .collect(), + )) } - /// Moves `branch`, which already has `onto` merged in, to one new commit - /// on `onto` holding exactly the branch's code: what a rebase that drops - /// copies of `onto`'s commits gives when its own commits don't replay - /// one by one. Nothing of the code changes (same tree); the branch moves - /// with a lease. - pub async fn flatten_onto( + /// One level of a tree: each name and its entry, directories (`tree`) + /// included. + pub async fn tree_level( &self, owner: &str, repo: &str, - branch: &str, - onto: &str, - message: &str, - lease: &str, - ) -> Result> { - let onto_sha = self.get_ref(owner, repo, onto).await?; - let status = self.compare_status(owner, repo, &onto_sha, lease).await?; - if status != "ahead" && status != "identical" { - return Ok(RebaseResult::NotClean(format!( - "`{onto}` isn't merged into the branch yet" - ))); + tree: &str, + ) -> Result, Box> { + let data = self + .get(&format!("{API_BASE}/repos/{owner}/{repo}/git/trees/{tree}")) + .await?; + Ok(data["tree"] + .as_array() + .into_iter() + .flatten() + .filter_map(|e| { + Some(( + e["path"].as_str()?.to_string(), + GitEntry { + mode: e["mode"].as_str().unwrap_or("").to_string(), + kind: e["type"].as_str()?.to_string(), + sha: e["sha"].as_str()?.to_string(), + }, + )) + }) + .collect()) + } + + /// A blob's bytes. + pub async fn blob_bytes( + &self, + owner: &str, + repo: &str, + sha: &str, + ) -> Result, Box> { + let b = self + .get(&format!("{API_BASE}/repos/{owner}/{repo}/git/blobs/{sha}")) + .await?; + let content = b["content"].as_str().ok_or("Missing blob content")?; + if b["encoding"].as_str() == Some("utf-8") { + return Ok(content.as_bytes().to_vec()); } - let tree = self.git_commit(owner, repo, lease).await?["tree"]["sha"] - .as_str() - .ok_or("Missing tree sha in branch commit")? - .to_string(); - let onto_tree = self.git_commit(owner, repo, &onto_sha).await?["tree"]["sha"] + let clean: String = content.chars().filter(|c| !c.is_whitespace()).collect(); + Ok(B64.decode(clean)?) + } + + /// Writes a blob and returns its sha. + pub async fn put_blob( + &self, + owner: &str, + repo: &str, + bytes: &[u8], + ) -> Result> { + let b = self + .post( + &format!("{API_BASE}/repos/{owner}/{repo}/git/blobs"), + &serde_json::json!({"content": B64.encode(bytes), "encoding": "base64"}), + ) + .await?; + b["sha"] .as_str() - .unwrap_or("") - .to_string(); - if tree == onto_tree { - return Ok(RebaseResult::NotClean( - "the branch has no change of its own".to_string(), - )); - } - let tip = self - .new_commit( - owner, - repo, - serde_json::json!({"message": message, "tree": tree, "parents": [onto_sha]}), + .map(String::from) + .ok_or_else(|| "Missing blob sha".into()) + } + + /// Writes the tree `base_tree` with `changes` laid over it (`None` + /// removes the path) and returns its sha. + pub async fn put_tree( + &self, + owner: &str, + repo: &str, + base_tree: &str, + changes: &[(String, Option)], + ) -> Result> { + let entries: Vec = changes + .iter() + .map(|(path, e)| match e { + Some(e) => serde_json::json!({ + "path": path, "mode": e.mode, "type": e.kind, "sha": e.sha, + }), + None => serde_json::json!({ + "path": path, "mode": "100644", "type": "blob", "sha": null, + }), + }) + .collect(); + let t = self + .post( + &format!("{API_BASE}/repos/{owner}/{repo}/git/trees"), + &serde_json::json!({"base_tree": base_tree, "tree": entries}), ) .await?; + t["sha"] + .as_str() + .map(String::from) + .ok_or_else(|| "Missing tree sha".into()) + } + + /// Writes a commit of `tree` on `parents` and returns its sha. + pub async fn put_commit( + &self, + owner: &str, + repo: &str, + message: &str, + tree: &str, + parents: &[String], + ) -> Result> { + self.new_commit( + owner, + repo, + serde_json::json!({"message": message, "tree": tree, "parents": parents}), + ) + .await + } + + /// Moves `branch` to `to` only if it still points at `lease`: `false` + /// (nothing moved) when someone pushed since. + pub async fn move_with_lease( + &self, + owner: &str, + repo: &str, + branch: &str, + lease: &str, + to: &str, + ) -> Result> { if self.get_ref(owner, repo, branch).await? != lease { - return Ok(RebaseResult::Moved); + return Ok(false); } - self.move_scratch_ref(owner, repo, branch, &tip).await?; + self.move_scratch_ref(owner, repo, branch, to).await?; self.invalidate_snapshot(owner, repo, branch).await; - Ok(RebaseResult::Rebased(tip)) + Ok(true) } /// Replays `steps` on the scratch ref starting at `base_sha`. The new @@ -2509,27 +2594,33 @@ impl GitHubClient { Ok(v.as_array().cloned().unwrap_or_default()) } - /// The files one commit changes, as (path, patch), first 300. - pub async fn commit_patches( + /// A commit's changed files, every page of them (GitHub lists 300 a + /// page, up to 3000): each path, the path it was renamed from, its patch. + pub async fn commit_changes( &self, owner: &str, repo: &str, sha: &str, - ) -> Result, Box> { - let v = self - .get(&format!("{API_BASE}/repos/{owner}/{repo}/commits/{sha}")) - .await?; - Ok(v["files"] - .as_array() - .into_iter() - .flatten() - .map(|f| { - ( - f["filename"].as_str().unwrap_or("").to_string(), - f["patch"].as_str().unwrap_or("").to_string(), - ) - }) - .collect()) + ) -> Result, Box> { + let mut out = Vec::new(); + for page in 1..=10u32 { + let v = self + .get(&format!( + "{API_BASE}/repos/{owner}/{repo}/commits/{sha}?page={page}" + )) + .await?; + let files = v["files"].as_array().cloned().unwrap_or_default(); + let n = files.len(); + out.extend(files.iter().map(|f| CommitFile { + path: f["filename"].as_str().unwrap_or("").to_string(), + previous: f["previous_filename"].as_str().map(String::from), + patch: f["patch"].as_str().unwrap_or("").to_string(), + })); + if n < 300 { + break; + } + } + Ok(out) } /// An issue (title, body, author), as the issues endpoint returns it. @@ -4042,6 +4133,36 @@ pub struct DirEntry { pub path: String, } +/// A path's entry in a git tree: its mode, type (`blob`, `commit` for a +/// submodule) and object sha. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GitEntry { + pub mode: String, + pub kind: String, + pub sha: String, +} + +impl GitEntry { + /// A tree listing's entry; `None` for a directory (a `tree`). + pub fn from_json(e: &serde_json::Value) -> Option { + let kind = e["type"].as_str()?; + (kind != "tree").then(|| GitEntry { + mode: e["mode"].as_str().unwrap_or("100644").to_string(), + kind: kind.to_string(), + sha: e["sha"].as_str().unwrap_or("").to_string(), + }) + } +} + +/// One file a commit changed: its path, the path it was renamed from, its +/// patch (empty for a binary or very large file). +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct CommitFile { + pub path: String, + pub previous: Option, + pub patch: String, +} + /// File operation for batch_write. pub enum FileOp { Write { path: String, content: String }, @@ -4109,48 +4230,6 @@ pub fn replay_steps(compare: &serde_json::Value) -> Option> { (steps.len() <= MAX_REPLAY).then_some(steps) } -/// The branch's own commits for `git rebase --onto`: [`replay_steps`] -/// without the commits in `drop`, and whether merge commits were left out -/// (their conflict resolutions aren't replayed). -pub fn onto_steps(compare: &serde_json::Value, drop: &[String]) -> Option<(Vec, bool)> { - let steps = replay_steps(compare)?; - let merges = compare["commits"].as_array().is_some_and(|c| { - c.iter() - .any(|c| c["parents"].as_array().is_some_and(|p| p.len() > 1)) - }); - let own = steps - .into_iter() - .filter(|s| !drop.contains(&s.sha)) - .collect(); - Some((own, merges)) -} - -/// Whether a rebase onto another branch kept the branch's code. With that -/// branch already merged in, the result must hold the branch's code -/// exactly. Otherwise it must hold what merging it in gives; when that -/// merge conflicts (the copies are older versions of its commits) the -/// replayed commits are trusted only if no merge commit was left out. -pub fn onto_holds( - onto_in_branch: bool, - branch_tree: &str, - merged_tree: Option<&str>, - merges_dropped: bool, - tip_tree: &str, -) -> Result<(), String> { - let same = if onto_in_branch { - tip_tree == branch_tree - } else if let Some(m) = merged_tree { - tip_tree == m - } else { - !merges_dropped - }; - if same { - Ok(()) - } else { - Err("the rebased code differs from the branch with that branch merged in".to_string()) - } -} - /// Whether a compare's commits (merge commits aside) were all committed by /// `login`. A truncated list is `false`: an unseen commit may be someone's. pub fn commits_all_by(compare: &serde_json::Value, login: &str) -> bool { @@ -4254,41 +4333,6 @@ mod rebase_tests { assert!(!commits_all_by(&truncated, "app[bot]")); assert!(replay_steps(&truncated).is_none()); } - - #[test] - fn a_rebase_onto_replays_only_the_branch_s_own_commits() { - // acme/web: c1 and c2 copy the dependency's commits, o1 is the run's. - let cmp = json!({ - "total_commits": 4, - "commits": [ - commit("c1", &["b0"], "app[bot]"), - commit("c2", &["c1"], "app[bot]"), - commit("m1", &["c2", "d9"], "app[bot]"), - commit("o1", &["m1"], "app[bot]"), - ], - }); - let (steps, merges) = onto_steps(&cmp, &["c1".into(), "c2".into()]).unwrap(); - assert_eq!( - steps.iter().map(|s| s.sha.as_str()).collect::>(), - vec!["o1"] - ); - assert!(merges); - let plain = json!({"total_commits": 1, "commits": [commit("o1", &["b0"], "x")]}); - assert!(!onto_steps(&plain, &[]).unwrap().1); - } - - #[test] - fn a_rebase_onto_keeps_the_branch_s_code_or_is_refused() { - // Already merged in: exactly the branch's code. - assert!(onto_holds(true, "t1", None, true, "t1").is_ok()); - assert!(onto_holds(true, "t1", None, false, "t2").is_err()); - // Not merged in: what merging it in gives. - assert!(onto_holds(false, "t1", Some("t3"), false, "t3").is_ok()); - assert!(onto_holds(false, "t1", Some("t3"), false, "t2").is_err()); - // The merge conflicts (older copies): trusted without dropped merges. - assert!(onto_holds(false, "t1", None, false, "t2").is_ok()); - assert!(onto_holds(false, "t1", None, true, "t2").is_err()); - } } /// Result of a SHA-guarded merge attempt. diff --git a/services/worker/src/main.rs b/services/worker/src/main.rs index c37adfe03..388ad886f 100644 --- a/services/worker/src/main.rs +++ b/services/worker/src/main.rs @@ -559,6 +559,12 @@ async fn handle_message(state: Arc, message: models::WorkerMessage) error!("Team agent try failed: {e:?}"); } } + models::WorkerMessage::Restack(msg) => { + info!(team_id = %msg.team_id, repo = %format!("{}/{}", msg.repo_owner, msg.repo_name), branch = %msg.branch, "Force push: rebuilding the pull requests stacked on it"); + if let Err(e) = passes::restack::after_forced_push(&state, msg).await { + error!("Rebuilding stacked pull requests failed: {e:?}"); + } + } models::WorkerMessage::HealthCheck(msg) => { info!(team_id = %msg.team_id, pr = msg.pr_number, attempt = msg.attempts, "Post-merge health check"); if let Err(e) = passes::health_check::run(&state, msg).await { @@ -729,6 +735,10 @@ async fn mark_pr_ready( } // CoderHelm's own review still lists findings it hasn't fixed: the PR // stays a draft until its fix rounds clear them (`own_review`). + if let Some(why) = pr["body"].as_str().and_then(passes::stack::hold) { + info!(pr_number = msg.pr_number, why = %why, "PR stays a draft"); + return Ok(()); + } if let Some(why) = pr["body"].as_str().and_then(passes::own_review::hold) { info!(pr_number = msg.pr_number, why = %why, "PR stays a draft"); return Ok(()); diff --git a/services/worker/src/passes/mod.rs b/services/worker/src/passes/mod.rs index 44eaeec79..73a0e3ecd 100644 --- a/services/worker/src/passes/mod.rs +++ b/services/worker/src/passes/mod.rs @@ -847,6 +847,7 @@ pub mod remote_mcp; pub(crate) mod repo_pick; mod resolve; mod resolved; +pub mod restack; pub mod resume; mod review; pub mod review_actions; @@ -3537,19 +3538,21 @@ async fn run_passes( } } - // A branch kept from an earlier attempt can carry copies of another - // open pull request's commits (that branch was rebased since): they - // are dropped now, before any implementation, and the run stacks on - // it. A branch with its own open pull request keeps its history. - if existing_pr.is_none() && !pr_lookup_failed && !is_internal_ticket(&msg.ticket_id) { - if let Some(d) = stack::at_start(&github, msg, &branch_name).await { + // A branch kept from an earlier attempt (or a retry) can carry + // copies of another open pull request's commits (that branch was + // rebased since): its own change is rebuilt on that branch now, + // file by file, before any implementation, and the run stacks on it. + if !pr_lookup_failed && !is_internal_ticket(&msg.ticket_id) { + if let Some(d) = + stack::at_start(state, &github, msg, &branch_name, &provider, usage).await + { add_progress_note( state, &msg.team_id, run_id, &format!( - "Dropped this branch's copies of #{}'s commits; it now builds on `{}`", - d.number, d.branch + "Rebuilt this branch's own change on #{}'s branch `{}` without its copies of #{}'s commits", + d.number, d.branch, d.number ), ) .await; @@ -5291,6 +5294,9 @@ async fn run_passes( links: &links, test_fix: test_pr.as_ref(), feature: feature_pr.as_ref(), + keep_commits: stacked_on + .as_ref() + .is_some_and(|d| !d.unresolved.is_empty()), }, &provider, usage, @@ -6217,6 +6223,7 @@ async fn run_repo_pipeline( test_fix: test_pr.as_ref(), // Multi-repo runs: the new-feature rules check single-repo runs. feature: None, + keep_commits: false, }, provider, usage, diff --git a/services/worker/src/passes/pr.rs b/services/worker/src/passes/pr.rs index 376622a44..d6c847a76 100644 --- a/services/worker/src/passes/pr.rs +++ b/services/worker/src/passes/pr.rs @@ -49,6 +49,10 @@ pub struct Proof<'a> { /// content, the verification checklist and open product questions (see /// `feature`). pub feature: Option<&'a super::feature::PrFacts>, + /// The branch's commits stay as they are (no squash): a stacked change + /// was rebuilt with a labelled follow-up commit people should see (see + /// `stack`). + pub keep_commits: bool, } /// What the writer is told about the checks CI runs on the PR: never a @@ -657,7 +661,12 @@ Return ONLY the markdown body text."#, // the noisier history. Skipped for existing/reopened PRs above to avoid // rewriting a PR a human may already be reviewing. let squash_msg = squash_message(&conventions, &tokens, msg); - if let Err(e) = github + if proof.keep_commits { + info!( + branch, + "Keeping the branch's commits: it carries a labelled follow-up commit" + ); + } else if let Err(e) = github .squash_branch( &msg.repo_owner, &msg.repo_name, @@ -1087,109 +1096,20 @@ pub async fn resolve_conflicts( (None, None) => continue, }; - let cap = |s: &str, limit: usize| -> String { - if s.len() > limit { - let head = common::truncate_str(s, limit); - let cut = head.rfind('\n').unwrap_or(head.len()); - format!("{}... (truncated, {} bytes total)", &head[..cut], s.len()) - } else { - s.to_string() - } - }; - - // Build a 3-way merge prompt - let system = "You are a precise merge conflict resolver. You will be given three versions of a file: the common ancestor, the main branch version, and the feature branch version. Produce the correctly merged file that incorporates changes from BOTH sides. When changes conflict directly, prefer the feature branch version. Return ONLY the file content — no explanations, no markdown fences, no commentary.".to_string(); - - let mut prompt = format!("Merge these versions of `{path}`.\n\n"); - - if let Some(ref anc) = ancestor { - prompt.push_str(&format!( - "## Common ancestor\n```\n{}\n```\n\n", - cap(anc, 12_000) - )); - } - - prompt.push_str(&format!( - "## main branch version (their changes)\n```\n{}\n```\n\n", - cap(&main_content, 16_000) - )); - prompt.push_str(&format!( - "## feature branch version (our changes — prefer when conflicting)\n```\n{}\n```\n\n", - cap(&branch_content, 16_000) - )); - - if ancestor.is_some() { - prompt.push_str( - "Use the common ancestor to understand what each side changed. \ - Include changes from BOTH sides. Only prefer the feature branch \ - when both sides modified the exact same lines.", - ); - } else { - prompt.push_str( - "Include changes from BOTH sides. Only prefer the feature branch \ - when both sides modified the exact same lines.", - ); - } - - let mut messages = vec![( - "user".to_string(), - vec![serde_json::json!({"type": "text", "text": prompt})], - )]; - - let model_id = provider.primary_model_id(); - let merged_content = provider::converse( + let Some(merged_content) = merge_file( state, provider, - common::agent_policy::Agent::Coder, - model_id, - &system, - &mut messages, - &[], - &super::triage::NoOpExecutor, usage, - llm::ConverseOptions { - max_turns: 40, - max_tokens: 16384, - deadline: None, - effort: None, - }, - None, - None, + path, + ancestor.as_deref(), + "main branch", + &main_content, + &branch_content, ) - .await?; - - // Validate the model's merge before it becomes a commit — the output - // used to be committed verbatim (dropped hunks, stray fences, - // truncation all landed as file corruption). Any invalid file aborts - // the whole resolution: an unresolved conflict GitHub can display is - // strictly safer than a silently corrupted merge. - let merged_content = strip_code_fences(&merged_content); - let min_side = branch_content.len().min(main_content.len()); - if merged_content.trim().is_empty() && min_side > 0 { - warn!( - path, - "LLM merge produced empty output — aborting conflict resolution" - ); - return Ok(false); - } - if min_side > 200 && merged_content.len() < min_side * 3 / 10 { - warn!( - path, - merged = merged_content.len(), - min_side, - "LLM merge dropped most of the file — aborting conflict resolution" - ); - return Ok(false); - } - if let Err(problem) = - syntax_check::validate_change(path, Some(&branch_content), &merged_content) - { - warn!( - path, - problem, "LLM merge is syntactically broken — aborting conflict resolution" - ); + .await? + else { return Ok(false); - } + }; resolved_files.push(FileOp::Write { path: path.to_string(), @@ -1239,6 +1159,128 @@ pub async fn resolve_conflicts( Ok(true) } +/// Merges two versions of `path` with the model, keeping both sides' work: +/// `main_content` (the `their_label` version) and `branch_content` (the +/// change's, preferred only where both changed the same lines), read from +/// `ancestor` when known. `None` when the model's file fails the checks +/// (empty, most of the file dropped, broken syntax): an unresolved conflict +/// is safer than a corrupted file. +#[allow(clippy::too_many_arguments)] +pub async fn merge_file( + state: &WorkerState, + provider: &ModelProvider, + usage: &mut TokenUsage, + path: &str, + ancestor: Option<&str>, + their_label: &str, + main_content: &str, + branch_content: &str, +) -> Result, Box> { + let cap = |s: &str, limit: usize| -> String { + if s.len() > limit { + let head = common::truncate_str(s, limit); + let cut = head.rfind('\n').unwrap_or(head.len()); + format!("{}... (truncated, {} bytes total)", &head[..cut], s.len()) + } else { + s.to_string() + } + }; + + // Build a 3-way merge prompt + let system = format!("You are a precise merge conflict resolver. You will be given three versions of a file: the common ancestor, the {their_label} version, and the feature branch version. Produce the correctly merged file that incorporates changes from BOTH sides. When changes conflict directly, prefer the feature branch version. Return ONLY the file content — no explanations, no markdown fences, no commentary."); + + let mut prompt = format!("Merge these versions of `{path}`.\n\n"); + + if let Some(anc) = ancestor { + prompt.push_str(&format!( + "## Common ancestor\n```\n{}\n```\n\n", + cap(anc, 12_000) + )); + } + + prompt.push_str(&format!( + "## {their_label} version (their changes)\n```\n{}\n```\n\n", + cap(main_content, 16_000) + )); + prompt.push_str(&format!( + "## feature branch version (our changes — prefer when conflicting)\n```\n{}\n```\n\n", + cap(branch_content, 16_000) + )); + + if ancestor.is_some() { + prompt.push_str( + "Use the common ancestor to understand what each side changed. \ + Include changes from BOTH sides. Only prefer the feature branch \ + when both sides modified the exact same lines.", + ); + } else { + prompt.push_str( + "Include changes from BOTH sides. Only prefer the feature branch \ + when both sides modified the exact same lines.", + ); + } + + let mut messages = vec![( + "user".to_string(), + vec![serde_json::json!({"type": "text", "text": prompt})], + )]; + + let model_id = provider.primary_model_id(); + let merged_content = provider::converse( + state, + provider, + common::agent_policy::Agent::Coder, + model_id, + &system, + &mut messages, + &[], + &super::triage::NoOpExecutor, + usage, + llm::ConverseOptions { + max_turns: 40, + max_tokens: 16384, + deadline: None, + effort: None, + }, + None, + None, + ) + .await?; + + // Validate the model's merge before it becomes a commit — the output + // used to be committed verbatim (dropped hunks, stray fences, + // truncation all landed as file corruption). Any invalid file aborts + // the whole resolution: an unresolved conflict GitHub can display is + // strictly safer than a silently corrupted merge. + let merged_content = strip_code_fences(&merged_content); + let min_side = branch_content.len().min(main_content.len()); + if merged_content.trim().is_empty() && min_side > 0 { + warn!( + path, + "LLM merge produced empty output — aborting conflict resolution" + ); + return Ok(None); + } + if min_side > 200 && merged_content.len() < min_side * 3 / 10 { + warn!( + path, + merged = merged_content.len(), + min_side, + "LLM merge dropped most of the file — aborting conflict resolution" + ); + return Ok(None); + } + if let Err(problem) = syntax_check::validate_change(path, Some(branch_content), &merged_content) + { + warn!( + path, + problem, "LLM merge is syntactically broken — aborting conflict resolution" + ); + return Ok(None); + } + Ok(Some(merged_content)) +} + /// Strip a wrapping markdown code fence the model may have added despite /// instructions ("```lang\n…\n```"). Inner fences are left untouched. fn strip_code_fences(s: &str) -> String { @@ -2024,6 +2066,7 @@ mod refresh_tests { links: "", test_fix: None, feature: None, + keep_commits: false, }; let owned = super::owned_sections(&plan, &proof, "acme/infra"); let body = assemble( diff --git a/services/worker/src/passes/restack.rs b/services/worker/src/passes/restack.rs new file mode 100644 index 000000000..13051a2ce --- /dev/null +++ b/services/worker/src/passes/restack.rs @@ -0,0 +1,1851 @@ +//! A branch's own change rebuilt on another branch, file by file. +//! +//! A run stacked on an open pull request has to move when that pull +//! request's branch is rebased: its branch still holds the old commits, +//! which now read as copies under other hashes. Replaying the branch's own +//! commits one by one stopped at a commit count, and merging the other +//! branch in first needed a merge that could fail; both stopped the run. +//! +//! Here no commit is replayed. The change is what the branch's own commits +//! (not the copies, not merge commits) touched, as files: each path with its +//! final content on the branch, or its removal (a rename is both). One new +//! commit on the other branch's head holds that branch's tree with those +//! paths laid over it, so the commit count never matters and nothing has to +//! be merged first. +//! +//! A path the other branch also changed since the point the run copied +//! from is a conflict: the model merges the two versions (both sides' work +//! kept). When it can't, the commit keeps the other branch's version and a +//! labelled follow-up commit puts this change's back, so the pull request +//! still opens, as a draft that names the path. +//! +//! Before the branch moves, the result is checked: every path of the change +//! holds the change's (or the merged) content and every other path equals +//! the other branch's head. It moves with a lease (only if nobody pushed +//! since; when someone did, it is rebuilt from the new head). GitHub errors +//! are retried with backoff; only a missing permission stops, naming it. + +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::future::Future; +use std::time::Duration; + +use serde_json::Value; +use tracing::{info, warn}; + +use crate::clients::github::{CommitFile, GitEntry, GitHubClient}; + +pub type Error = Box; + +/// A path's entry in a tree; `None` when the path isn't there. +pub type Slot = Option; + +/// A commit of a compare's list. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Listed { + pub sha: String, + pub parents: Vec, + pub message: String, +} + +impl Listed { + pub fn from_json(c: &Value) -> Option { + Some(Listed { + sha: c["sha"].as_str()?.to_string(), + parents: c["parents"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| p["sha"].as_str().map(String::from)) + .collect(), + message: c + .pointer("/commit/message") + .and_then(|m| m.as_str()) + .unwrap_or("") + .to_string(), + }) + } +} + +/// What the rebuild reads and writes on the repository. +#[async_trait::async_trait] +pub trait Repo: Sync { + async fn head(&self, branch: &str) -> Result; + /// A commit's tree and parents. + async fn commit(&self, sha: &str) -> Result<(String, Vec), Error>; + /// Every commit in `base...head`, oldest first. + async fn between(&self, base: &str, head: &str) -> Result, Error>; + /// The files a (non-merge) commit changed. + async fn files(&self, sha: &str) -> Result, Error>; + /// Each path's entry at a commit. + async fn slots( + &self, + commit: &str, + paths: &BTreeSet, + ) -> Result, Error>; + async fn blob(&self, sha: &str) -> Result, Error>; + async fn put_blob(&self, bytes: &[u8]) -> Result; + async fn put_tree(&self, base_tree: &str, changes: &[(String, Slot)]) -> Result; + async fn put_commit( + &self, + message: &str, + tree: &str, + parents: &[String], + ) -> Result; + /// Moves the branch to `to` only if it still points at `lease`. + async fn move_branch(&self, branch: &str, lease: &str, to: &str) -> Result; + /// The paths that differ between two commits; `None` when there are + /// more than GitHub lists. + async fn changed(&self, from: &str, to: &str) -> Result>, Error>; +} + +/// Merges two versions of a file, keeping both sides' work. +#[async_trait::async_trait] +pub trait Merger: Send { + /// `theirs` is the other branch's version, `ours` the change's; `None` + /// when they can't be merged safely. + async fn merge( + &mut self, + path: &str, + ancestor: Option<&str>, + theirs: &str, + ours: &str, + ) -> Option; +} + +/// No model at hand: every conflict is kept as a follow-up commit. +pub struct NoMerger; + +#[async_trait::async_trait] +impl Merger for NoMerger { + async fn merge(&mut self, _: &str, _: Option<&str>, _: &str, _: &str) -> Option { + None + } +} + +/// The model merges a conflicting path (`pr::merge_file`: validated, an +/// invalid merge is `None`). +pub struct ModelMerger<'a> { + pub state: &'a crate::WorkerState, + pub provider: &'a crate::agent::provider::ModelProvider, + pub usage: &'a mut crate::models::TokenUsage, + /// What the other branch is, for the prompt ("pull request #42's branch"). + pub theirs: String, +} + +#[async_trait::async_trait] +impl Merger for ModelMerger<'_> { + async fn merge( + &mut self, + path: &str, + ancestor: Option<&str>, + theirs: &str, + ours: &str, + ) -> Option { + match super::pr::merge_file( + self.state, + self.provider, + self.usage, + path, + ancestor, + &self.theirs, + theirs, + ours, + ) + .await + { + Ok(m) => m, + Err(e) => { + warn!(path, error = %e, "The model couldn't merge the two versions"); + None + } + } + } +} + +/// Which of the branch's commits are its own change. +#[derive(Debug, Clone, Copy)] +pub enum Own<'a> { + /// Its commits past `base`, the copies of the other branch's commits + /// left out. + NotCopies { base: &'a str, copies: &'a [String] }, + /// Its commits past `from`, the other branch's old head it was built on + /// (that branch was force-pushed since). + After { from: &'a str }, +} + +/// One rebuild: `branch`'s own change onto `onto`'s head. +pub struct Job<'a> { + pub branch: &'a str, + pub onto: &'a str, + pub own: Own<'a>, + /// The new commit's message. + pub message: &'a str, + /// The other branch's pull request, for the follow-up commit's message. + pub onto_pr: u64, +} + +/// What a rebuild did. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Rebuilt { + /// The branch's new head. + pub tip: String, + /// The branch's own commits the change came from. + pub own_commits: usize, + /// The paths of the change. + pub paths: usize, + /// Paths both changed, merged by the model. + pub merged: Vec, + /// Paths both changed that couldn't be merged: the other branch's + /// version, then this change's in a labelled follow-up commit. + pub unresolved: Vec, + /// How many times it was built (more than one when the branch moved). + pub tries: u32, +} + +/// Why a rebuild didn't move the branch. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Halt { + /// The GitHub App lacks a permission: the only reason a run stops. + Permission { permission: String, doing: String }, + /// Anything else (after retries); the pull request still opens. + Failed(String), +} + +impl Halt { + /// In plain words, with what to do for a missing permission. + pub fn say(&self, repo: &str) -> String { + match self { + Halt::Permission { permission, doing } => format!( + "CoderHelm's GitHub App needs the \"{permission}\" permission on {repo} for \ + {doing}. An organization owner can grant it in the GitHub App's settings \ + (Permissions); run the ticket again after that." + ), + Halt::Failed(why) => why.clone(), + } + } +} + +const READ: &str = "Contents: read"; +const WRITE: &str = "Contents: read and write"; + +/// Tries per GitHub call; the waits between double from [`BACKOFF_MS`]. +const TRIES: u32 = 4; +#[cfg(not(test))] +const BACKOFF_MS: u64 = 1_000; +#[cfg(test)] +const BACKOFF_MS: u64 = 0; +/// Builds of one rebuild when the branch keeps moving under it. +pub const LEASE_TRIES: u32 = 3; + +/// The permission a failed call lacked, from GitHub's answer: a workflow +/// file needs "Workflows: read and write"; any other refusal for a missing +/// permission needs `step`'s. A rate limit is not a permission. +pub fn permission_needed(err: &str, step: &str) -> Option { + let l = err.to_ascii_lowercase(); + if l.contains("rate limit") { + return None; + } + if l.contains("workflow") && (l.contains("permission") || l.contains("scope")) { + return Some("Workflows: read and write".to_string()); + } + let forbidden = l.contains("(403") || l.contains(" 403 "); + if forbidden && (l.contains("resource not accessible") || l.contains("permission")) { + return Some(step.to_string()); + } + None +} + +/// One GitHub call, retried with backoff; a missing permission stops at +/// once. +pub async fn retry(permission: &str, doing: &str, mut call: F) -> Result +where + F: FnMut() -> Fut, + Fut: Future>, +{ + let mut last = String::new(); + for i in 0..TRIES { + match call().await { + Ok(v) => return Ok(v), + Err(e) => { + last = e.to_string(); + if let Some(p) = permission_needed(&last, permission) { + return Err(Halt::Permission { + permission: p, + doing: doing.to_string(), + }); + } + if i + 1 < TRIES { + tokio::time::sleep(Duration::from_millis(BACKOFF_MS << i)).await; + } + } + } + } + Err(Halt::Failed(format!( + "{doing} kept failing on GitHub ({})", + common::truncate_str(&last, 300) + ))) +} + +/// The branch's own commits: neither merge commits nor copies. +pub fn own_commits<'a>(listed: &'a [Listed], copies: &[String]) -> Vec<&'a Listed> { + listed + .iter() + .filter(|c| c.parents.len() <= 1 && !copies.contains(&c.sha)) + .collect() +} + +/// The paths a commit's files touch: a rename is its new path (added) and +/// its old one (removed). +pub fn touched(files: &[CommitFile]) -> BTreeSet { + let mut out = BTreeSet::new(); + for f in files { + if !f.path.is_empty() { + out.insert(f.path.clone()); + } + if let Some(p) = f.previous.as_ref().filter(|p| !p.is_empty()) { + out.insert(p.clone()); + } + } + out +} + +/// What each path of the change becomes on the other branch. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Plan { + /// Paths whose version is the change's (`None` removes the path). + pub take: Vec<(String, Slot)>, + /// Paths both changed since the point the change was copied from. + pub conflicts: Vec, +} + +fn at(m: &BTreeMap, p: &str) -> Slot { + m.get(p).cloned().flatten() +} + +/// Per path: the same on both is nothing to do; the other branch left it +/// as it was at `base` (the point the run copied from), so the change's +/// version wins; the change's net result is `base`'s, so the other +/// branch's stays; both changed it: a conflict. +pub fn plan( + paths: &BTreeSet, + ours: &BTreeMap, + theirs: &BTreeMap, + base: &BTreeMap, +) -> Plan { + let mut out = Plan::default(); + for p in paths { + let (o, t, b) = (at(ours, p), at(theirs, p), at(base, p)); + if o == t || o == b { + continue; + } + if t == b { + out.take.push((p.clone(), o)); + } else { + out.conflicts.push(p.clone()); + } + } + out +} + +/// The check before the branch moves: each path of the change holds what +/// it should, and nothing else differs from the other branch's head +/// (`changed`, when GitHub could list it all). +pub fn holds( + expect: &BTreeMap, + got: &BTreeMap, + changed: Option<&[String]>, + paths: &BTreeSet, +) -> Result<(), String> { + for (p, e) in expect { + if at(got, p) != *e { + return Err(format!("`{p}` doesn't hold the expected version")); + } + } + if let Some(x) = changed.and_then(|c| c.iter().find(|f| !paths.contains(*f))) { + return Err(format!( + "`{x}` differs from the other branch though this change never touched it" + )); + } + Ok(()) +} + +/// The follow-up commit's message: the paths this change's version comes +/// back to, for review. +pub fn follow_up_message(paths: &[String], onto_pr: u64) -> String { + let mut m = format!( + "Follow-up: this change's version of {} file(s) #{onto_pr} also changed\n\n\ + These couldn't be merged with #{onto_pr}'s version: the commit before this one keeps \ + #{onto_pr}'s, this one puts this change's back. Review them before merging:\n", + paths.len() + ); + for p in paths { + m.push_str(&format!("- {p}\n")); + } + m.trim_end().to_string() +} + +enum Attempt { + Done(Rebuilt), + Moved, +} + +/// Rebuilds `job.branch`'s own change on `job.onto`'s head and moves the +/// branch there; built again from the new head when the branch moves +/// meanwhile, at most [`LEASE_TRIES`] times. +pub async fn rebuild( + repo: &R, + merger: &mut M, + job: &Job<'_>, +) -> Result { + for n in 1..=LEASE_TRIES { + match attempt(repo, merger, job).await? { + Attempt::Done(mut r) => { + r.tries = n; + return Ok(r); + } + Attempt::Moved => { + info!( + branch = job.branch, + n, "The branch moved while it was rebuilt; building again" + ); + } + } + } + Err(Halt::Failed(format!( + "`{}` kept moving while it was being rebuilt ({LEASE_TRIES} tries)", + job.branch + ))) +} + +async fn attempt( + repo: &R, + merger: &mut M, + job: &Job<'_>, +) -> Result { + let lease = retry(READ, "reading the branch's head", || repo.head(job.branch)).await?; + let dep = retry(READ, "reading the other branch's head", || { + repo.head(job.onto) + }) + .await?; + let (dep_tree, _) = retry(READ, "reading the other branch's head", || { + repo.commit(&dep) + }) + .await?; + let (from, copies): (&str, &[String]) = match job.own { + Own::NotCopies { base, copies } => (base, copies), + Own::After { from } => (from, &[]), + }; + let listed = retry(READ, "listing the branch's commits", || { + repo.between(from, &lease) + }) + .await?; + let own = own_commits(&listed, copies); + let Some(first) = own.first() else { + return Err(Halt::Failed( + "the branch has no commits of its own".to_string(), + )); + }; + // The point the change was copied from: the other branch's old head, + // or the parent of the branch's first own commit. + let start = match job.own { + Own::After { from } => from.to_string(), + Own::NotCopies { .. } => match first.parents.first() { + Some(p) => p.clone(), + None => from.to_string(), + }, + }; + let mut paths = BTreeSet::new(); + for c in &own { + let files = retry(READ, "reading a commit's files", || repo.files(&c.sha)).await?; + paths.extend(touched(&files)); + } + let ours = retry(READ, "reading the branch's files", || { + repo.slots(&lease, &paths) + }) + .await?; + let theirs = retry(READ, "reading the other branch's files", || { + repo.slots(&dep, &paths) + }) + .await?; + let base = retry(READ, "reading the files the change started from", || { + repo.slots(&start, &paths) + }) + .await?; + let planned = plan(&paths, &ours, &theirs, &base); + + let mut overlay = planned.take.clone(); + let mut merged = Vec::new(); + let mut unresolved = Vec::new(); + for p in &planned.conflicts { + let entry = resolve( + repo, + merger, + p, + &at(&base, p), + &at(&theirs, p), + &at(&ours, p), + ) + .await?; + match entry { + Some(e) => { + overlay.push((p.clone(), Some(e))); + merged.push(p.clone()); + } + None => unresolved.push(p.clone()), + } + } + + let tree = if overlay.is_empty() { + dep_tree.clone() + } else { + retry(WRITE, "writing the rebuilt files", || { + repo.put_tree(&dep_tree, &overlay) + }) + .await? + }; + let parents = vec![dep.clone()]; + let mut tip = retry(WRITE, "writing the rebuilt commit", || { + repo.put_commit(job.message, &tree, &parents) + }) + .await?; + if !unresolved.is_empty() { + let back: Vec<(String, Slot)> = unresolved + .iter() + .map(|p| (p.clone(), at(&ours, p))) + .collect(); + let tree2 = retry(WRITE, "writing the follow-up files", || { + repo.put_tree(&tree, &back) + }) + .await?; + let message = follow_up_message(&unresolved, job.onto_pr); + let parents = vec![tip.clone()]; + tip = retry(WRITE, "writing the follow-up commit", || { + repo.put_commit(&message, &tree2, &parents) + }) + .await?; + } + + // The check: what each path should hold now. + let set: BTreeMap = overlay.iter().cloned().collect(); + let expect: BTreeMap = paths + .iter() + .map(|p| { + let e = if unresolved.contains(p) { + at(&ours, p) + } else if let Some(e) = set.get(p) { + e.clone() + } else { + at(&theirs, p) + }; + (p.clone(), e) + }) + .collect(); + let got = retry(READ, "reading the rebuilt files", || { + repo.slots(&tip, &paths) + }) + .await?; + let changed = retry(READ, "comparing the rebuilt branch", || { + repo.changed(&dep, &tip) + }) + .await?; + if let Err(why) = holds(&expect, &got, changed.as_deref(), &paths) { + return Err(Halt::Failed(format!( + "the rebuilt branch failed its check ({why}); the branch wasn't moved" + ))); + } + let moved = retry(WRITE, "moving the branch", || { + repo.move_branch(job.branch, &lease, &tip) + }) + .await?; + if !moved { + return Ok(Attempt::Moved); + } + Ok(Attempt::Done(Rebuilt { + tip, + own_commits: own.len(), + paths: paths.len(), + merged, + unresolved, + tries: 0, + })) +} + +/// A conflicting path merged by the model: both versions must be text +/// files (a removal, a binary file or a submodule can't be merged). +async fn resolve( + repo: &R, + merger: &mut M, + path: &str, + base: &Slot, + theirs: &Slot, + ours: &Slot, +) -> Result, Halt> { + let (Some(t), Some(o)) = (theirs, ours) else { + return Ok(None); + }; + if t.kind != "blob" || o.kind != "blob" { + return Ok(None); + } + let text = |b: Vec| String::from_utf8(b).ok(); + let Some(their_text) = text(retry(READ, "reading a file", || repo.blob(&t.sha)).await?) else { + return Ok(None); + }; + let Some(our_text) = text(retry(READ, "reading a file", || repo.blob(&o.sha)).await?) else { + return Ok(None); + }; + let ancestor = match base { + Some(b) if b.kind == "blob" => { + text(retry(READ, "reading a file", || repo.blob(&b.sha)).await?) + } + _ => None, + }; + let Some(m) = merger + .merge(path, ancestor.as_deref(), &their_text, &our_text) + .await + else { + return Ok(None); + }; + let sha = retry(WRITE, "writing a merged file", || { + repo.put_blob(m.as_bytes()) + }) + .await?; + Ok(Some(GitEntry { + mode: o.mode.clone(), + kind: "blob".to_string(), + sha, + })) +} + +// ── Pull requests stacked on a force-pushed branch ───────────────────────── + +/// Most stacked pull requests one force push rebuilds (one at a time). +pub const MAX_DEPENDENTS: usize = 5; + +fn same_repo(p: &Value, owner: &str, repo: &str) -> bool { + p["head"]["repo"]["full_name"] + .as_str() + .is_some_and(|f| f.eq_ignore_ascii_case(&format!("{owner}/{repo}"))) +} + +/// CoderHelm's open pull requests (from this repository) whose base is +/// `branch`, at most [`MAX_DEPENDENTS`]. +pub fn dependents<'a>(open: &'a [Value], owner: &str, repo: &str, branch: &str) -> Vec<&'a Value> { + open.iter() + .filter(|p| p["base"]["ref"].as_str() == Some(branch) && same_repo(p, owner, repo)) + .filter(|p| { + p["user"]["login"] + .as_str() + .is_some_and(|l| l.to_ascii_lowercase().contains("coderhelm")) + || p["head"]["ref"] + .as_str() + .is_some_and(|b| b.starts_with("coderhelm/")) + }) + .take(MAX_DEPENDENTS) + .collect() +} + +/// The rebuilt commit's message: the stacked pull request's first own +/// commit's subject (already in the team's convention), else its title. +pub fn restacked_message(subject: &str, dep: u64, branch: &str) -> String { + format!( + "{}\n\nRebuilt on #{dep} (`{branch}`) file by file after it was force-pushed.", + subject.trim() + ) +} + +/// A force push to `msg.branch`: each of CoderHelm's open pull requests +/// stacked on it gets its own change (its commits past `msg.before`, the +/// old head) rebuilt on the new head, one at a time, and its stack section +/// says what happened. One that can't be rebuilt now says so and is +/// rebuilt when its ticket runs again (`stack::at_start`). +pub async fn after_forced_push( + state: &crate::WorkerState, + msg: crate::models::RestackMessage, +) -> Result<(), Error> { + let github = GitHubClient::new( + &state.secrets.github_app_id, + &state.secrets.github_private_key, + msg.installation_id, + &state.http, + )?; + let (owner, repo) = (msg.repo_owner.as_str(), msg.repo_name.as_str()); + let open = github.list_open_pulls(owner, repo).await?; + let open = open.as_array().cloned().unwrap_or_default(); + let stacked = dependents(&open, owner, repo, &msg.branch); + // Only an open pull request's branch is something to stack on. + let Some(dep) = open.iter().find(|p| { + p["head"]["ref"].as_str() == Some(msg.branch.as_str()) && same_repo(p, owner, repo) + }) else { + return Ok(()); + }; + if stacked.is_empty() { + return Ok(()); + } + let dep_number = dep["number"].as_u64().unwrap_or(0); + let dep_title = dep["title"].as_str().unwrap_or("").to_string(); + let provider = crate::agent::provider::ModelProvider::load_for_team( + &state.dynamo, + &state.config.settings_table_name, + &msg.team_id, + ) + .await + .ok(); + let mut usage = crate::models::TokenUsage::default(); + let known = BTreeMap::new(); + let gh = Gh { + github: &github, + owner, + repo, + known: &known, + }; + for p in stacked { + let (Some(number), Some(head)) = (p["number"].as_u64(), p["head"]["ref"].as_str()) else { + continue; + }; + // Already built on the new head. + if matches!( + github + .compare_status(owner, repo, &msg.branch, head) + .await + .as_deref(), + Ok("ahead") | Ok("identical") + ) { + continue; + } + let subject = github + .compare_all_commits(owner, repo, &msg.before, head) + .await + .ok() + .and_then(|c| { + c.iter() + .filter_map(Listed::from_json) + .find(|l| l.parents.len() <= 1) + .and_then(|l| l.message.lines().next().map(String::from)) + }) + .unwrap_or_else(|| { + p["title"] + .as_str() + .unwrap_or("Rebuild this change") + .to_string() + }); + let message = restacked_message(&subject, dep_number, &msg.branch); + let job = Job { + branch: head, + onto: &msg.branch, + own: Own::After { from: &msg.before }, + message: &message, + onto_pr: dep_number, + }; + let result = match &provider { + Some(pv) => { + let mut m = ModelMerger { + state, + provider: pv, + usage: &mut usage, + theirs: format!("pull request #{dep_number}'s branch"), + }; + rebuild(&gh, &mut m, &job).await + } + None => rebuild(&gh, &mut NoMerger, &job).await, + }; + let base = super::stack::Dependency { + number: dep_number, + branch: msg.branch.clone(), + title: dep_title.clone(), + ..Default::default() + }; + let stated = match result { + Ok(r) => { + info!( + pr = number, + dep = dep_number, + tries = r.tries, + "Rebuilt a stacked pull request on its base's new head" + ); + let mut why = format!( + "#{dep_number} was force-pushed; this pull request's own change ({} commit(s), \ + {} file(s)) was rebuilt on its new head file by file.", + r.own_commits, r.paths + ); + if !r.merged.is_empty() { + let list: Vec = r.merged.iter().map(|p| format!("`{p}`")).collect(); + why.push_str(&format!( + " #{dep_number} had also changed {}; the two versions were merged, keeping both.", + list.join(", ") + )); + } + super::stack::Dependency { + why, + unresolved: r.unresolved, + ..base + } + } + Err(h) => { + warn!(pr = number, dep = dep_number, why = %h.say(&format!("{owner}/{repo}")), "Couldn't rebuild a stacked pull request"); + super::stack::Dependency { + why: format!( + "#{dep_number} was force-pushed and this pull request's change couldn't be \ + rebuilt on its new head yet ({}).", + h.say(&format!("{owner}/{repo}")) + ), + not_stacked: true, + ..base + } + } + }; + super::stack::note_pr(&github, owner, repo, number, &stated).await; + } + Ok(()) +} + +// ── The repository on GitHub ──────────────────────────────────────────────── + +/// [`Repo`] on GitHub. `known` holds commits' files already read (the +/// copy check reads every commit's). +pub struct Gh<'a> { + pub github: &'a GitHubClient, + pub owner: &'a str, + pub repo: &'a str, + pub known: &'a BTreeMap>, +} + +#[async_trait::async_trait] +impl Repo for Gh<'_> { + async fn head(&self, branch: &str) -> Result { + self.github.get_ref(self.owner, self.repo, branch).await + } + + async fn commit(&self, sha: &str) -> Result<(String, Vec), Error> { + self.github + .commit_tree_parents(self.owner, self.repo, sha) + .await + } + + async fn between(&self, base: &str, head: &str) -> Result, Error> { + Ok(self + .github + .compare_all_commits(self.owner, self.repo, base, head) + .await? + .iter() + .filter_map(Listed::from_json) + .collect()) + } + + async fn files(&self, sha: &str) -> Result, Error> { + if let Some(f) = self.known.get(sha) { + return Ok(f.clone()); + } + self.github.commit_changes(self.owner, self.repo, sha).await + } + + async fn slots( + &self, + commit: &str, + paths: &BTreeSet, + ) -> Result, Error> { + let (root, _) = self.commit(commit).await?; + if let Some(all) = self.github.tree_all(self.owner, self.repo, &root).await? { + return Ok(paths + .iter() + .map(|p| (p.clone(), all.get(p).cloned())) + .collect()); + } + // A tree too big to list at once: walk it, one directory a read. + let mut levels: HashMap> = HashMap::new(); + let mut dirs: HashMap> = HashMap::new(); + dirs.insert(String::new(), Some(root)); + let mut out = BTreeMap::new(); + for p in paths { + let (dir, name) = p.rsplit_once('/').unwrap_or(("", p.as_str())); + let tree = self.dir_tree(dir, &mut dirs, &mut levels).await?; + let slot = match tree { + Some(t) => self + .level(&t, &mut levels) + .await? + .iter() + .find(|(n, e)| n == name && e.kind != "tree") + .map(|(_, e)| e.clone()), + None => None, + }; + out.insert(p.clone(), slot); + } + Ok(out) + } + + async fn blob(&self, sha: &str) -> Result, Error> { + self.github.blob_bytes(self.owner, self.repo, sha).await + } + + async fn put_blob(&self, bytes: &[u8]) -> Result { + self.github.put_blob(self.owner, self.repo, bytes).await + } + + async fn put_tree(&self, base_tree: &str, changes: &[(String, Slot)]) -> Result { + self.github + .put_tree(self.owner, self.repo, base_tree, changes) + .await + } + + async fn put_commit( + &self, + message: &str, + tree: &str, + parents: &[String], + ) -> Result { + self.github + .put_commit(self.owner, self.repo, message, tree, parents) + .await + } + + async fn move_branch(&self, branch: &str, lease: &str, to: &str) -> Result { + self.github + .move_with_lease(self.owner, self.repo, branch, lease, to) + .await + } + + async fn changed(&self, from: &str, to: &str) -> Result>, Error> { + let files = self + .github + .compare_changed_files(self.owner, self.repo, from, to) + .await?; + // The compare lists at most 300 files: past that it isn't the list. + Ok((files.len() < 300).then_some(files)) + } +} + +impl Gh<'_> { + async fn level<'m>( + &self, + tree: &str, + levels: &'m mut HashMap>, + ) -> Result<&'m Vec<(String, GitEntry)>, Error> { + if !levels.contains_key(tree) { + let l = self.github.tree_level(self.owner, self.repo, tree).await?; + levels.insert(tree.to_string(), l); + } + Ok(&levels[tree]) + } + + /// The tree sha of directory `dir` (`""` is the root), `None` when it + /// isn't there. + async fn dir_tree( + &self, + dir: &str, + dirs: &mut HashMap>, + levels: &mut HashMap>, + ) -> Result, Error> { + if let Some(t) = dirs.get(dir) { + return Ok(t.clone()); + } + let mut cur = dirs.get("").cloned().flatten(); + let mut walked = String::new(); + for part in dir.split('/') { + if !walked.is_empty() { + walked.push('/'); + } + walked.push_str(part); + if let Some(t) = dirs.get(&walked) { + cur = t.clone(); + continue; + } + cur = match cur { + Some(t) => self + .level(&t, levels) + .await? + .iter() + .find(|(n, e)| n == part && e.kind == "tree") + .map(|(_, e)| e.sha.clone()), + None => None, + }; + dirs.insert(walked.clone(), cur.clone()); + } + Ok(cur) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Mutex; + + fn blob(sha: &str) -> GitEntry { + GitEntry { + mode: "100644".into(), + kind: "blob".into(), + sha: sha.into(), + } + } + + /// A repository in memory: commits hold whole trees (path to entry), + /// blobs are their text, trees are named by their content. + #[derive(Default)] + struct Fake { + inner: Mutex, + } + + /// A commit's whole tree, parents, message and order. + type FakeCommit = (BTreeMap, Vec, String, usize); + + #[derive(Default)] + struct FakeInner { + commits: BTreeMap, + trees: BTreeMap>, + blobs: BTreeMap>, + branches: BTreeMap, + seq: usize, + /// Someone pushes this file to the branch the next time it moves. + push_on_move: Option<(String, String, String)>, + /// The next calls to read a head fail with a server error. + head_failures: u32, + /// Writing a tree is refused for a missing permission. + forbid_trees: bool, + moves: u32, + } + + fn text_sha(t: &[u8]) -> String { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + t.hash(&mut h); + format!("b{:015x}", h.finish()) + } + + fn tree_sha(t: &BTreeMap) -> String { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + for (p, e) in t { + (p, &e.mode, &e.kind, &e.sha).hash(&mut h); + } + format!("t{:015x}", h.finish()) + } + + impl Fake { + fn put_text(&self, text: &str) -> GitEntry { + let mut i = self.inner.lock().unwrap(); + let sha = text_sha(text.as_bytes()); + i.blobs.insert(sha.clone(), text.as_bytes().to_vec()); + blob(&sha) + } + + /// A commit on `parents` whose tree is the first parent's with + /// `files` laid over it (`None` removes). + fn commit_on(&self, parents: &[&str], files: &[(&str, Option<&str>)], msg: &str) -> String { + let entries: Vec<(String, Slot)> = files + .iter() + .map(|(p, t)| (p.to_string(), t.map(|t| self.put_text(t)))) + .collect(); + let mut i = self.inner.lock().unwrap(); + let mut tree = parents + .first() + .map(|p| i.commits[*p].0.clone()) + .unwrap_or_default(); + for (p, e) in entries { + match e { + Some(e) => tree.insert(p, e), + None => tree.remove(&p), + }; + } + i.seq += 1; + let sha = format!("c{:04}", i.seq); + let seq = i.seq; + i.commits.insert( + sha.clone(), + ( + tree, + parents.iter().map(|p| p.to_string()).collect(), + msg.to_string(), + seq, + ), + ); + sha + } + + /// A merge commit of two parents holding `files` over the first's. + fn merge_of(&self, a: &str, b: &str, files: &[(&str, Option<&str>)]) -> String { + self.commit_on(&[a, b], files, "Merge") + } + + fn set(&self, branch: &str, sha: &str) { + self.inner + .lock() + .unwrap() + .branches + .insert(branch.into(), sha.into()); + } + + fn file(&self, branch: &str, path: &str) -> Option { + let i = self.inner.lock().unwrap(); + let c = &i.branches[branch]; + i.commits[c] + .0 + .get(path) + .map(|e| String::from_utf8(i.blobs[&e.sha].clone()).unwrap()) + } + + fn tree_of(&self, sha: &str) -> BTreeMap { + self.inner.lock().unwrap().commits[sha].0.clone() + } + + /// A branch name or a commit. + fn sha(i: &FakeInner, name: &str) -> String { + i.branches + .get(name) + .cloned() + .unwrap_or_else(|| name.to_string()) + } + + fn ancestors(i: &FakeInner, sha: &str) -> BTreeSet { + let mut out = BTreeSet::new(); + let mut todo = vec![Fake::sha(i, sha)]; + while let Some(s) = todo.pop() { + if out.insert(s.clone()) { + todo.extend(i.commits[&s].1.iter().cloned()); + } + } + out + } + } + + fn diff(a: &BTreeMap, b: &BTreeMap) -> Vec { + let keys: BTreeSet<&String> = a.keys().chain(b.keys()).collect(); + keys.into_iter() + .filter(|k| a.get(*k) != b.get(*k)) + .cloned() + .collect() + } + + #[async_trait::async_trait] + impl Repo for Fake { + async fn head(&self, branch: &str) -> Result { + let mut i = self.inner.lock().unwrap(); + if i.head_failures > 0 { + i.head_failures -= 1; + return Err("HTTP status server error (502 Bad Gateway) for url (x)".into()); + } + i.branches + .get(branch) + .cloned() + .ok_or_else(|| "HTTP status client error (404 Not Found) for url (x)".into()) + } + + async fn commit(&self, sha: &str) -> Result<(String, Vec), Error> { + let mut i = self.inner.lock().unwrap(); + let (tree, parents, _, _) = i.commits.get(sha).cloned().ok_or("no commit")?; + let t = tree_sha(&tree); + i.trees.insert(t.clone(), tree); + Ok((t, parents)) + } + + async fn between(&self, base: &str, head: &str) -> Result, Error> { + let i = self.inner.lock().unwrap(); + let skip = Fake::ancestors(&i, base); + let mut out: Vec<(usize, Listed)> = Fake::ancestors(&i, head) + .into_iter() + .filter(|s| !skip.contains(s)) + .map(|s| { + let (_, parents, message, seq) = i.commits[&s].clone(); + ( + seq, + Listed { + sha: s, + parents, + message, + }, + ) + }) + .collect(); + out.sort_by_key(|(n, _)| *n); + Ok(out.into_iter().map(|(_, l)| l).collect()) + } + + async fn files(&self, sha: &str) -> Result, Error> { + let i = self.inner.lock().unwrap(); + let (tree, parents, _, _) = &i.commits[sha]; + let before = parents + .first() + .map(|p| i.commits[p].0.clone()) + .unwrap_or_default(); + let changed = diff(&before, tree); + let added: Vec<&String> = changed + .iter() + .filter(|p| !before.contains_key(*p)) + .collect(); + let removed: Vec<&String> = changed.iter().filter(|p| !tree.contains_key(*p)).collect(); + let mut out = Vec::new(); + let mut renamed_from = BTreeSet::new(); + for p in &changed { + let mut previous = None; + if added.contains(&p) { + // GitHub reports a moved file as one renamed file. + previous = removed + .iter() + .find(|r| before[**r].sha == tree[p].sha && !renamed_from.contains(**r)) + .map(|r| r.to_string()); + if let Some(r) = &previous { + renamed_from.insert(r.clone()); + } + } + out.push(CommitFile { + path: p.clone(), + previous, + patch: String::new(), + }); + } + out.retain(|f| !renamed_from.contains(&f.path)); + Ok(out) + } + + async fn slots( + &self, + commit: &str, + paths: &BTreeSet, + ) -> Result, Error> { + let i = self.inner.lock().unwrap(); + let tree = &i.commits.get(&Fake::sha(&i, commit)).ok_or("no commit")?.0; + Ok(paths + .iter() + .map(|p| (p.clone(), tree.get(p).cloned())) + .collect()) + } + + async fn blob(&self, sha: &str) -> Result, Error> { + Ok(self.inner.lock().unwrap().blobs[sha].clone()) + } + + async fn put_blob(&self, bytes: &[u8]) -> Result { + let sha = text_sha(bytes); + self.inner + .lock() + .unwrap() + .blobs + .insert(sha.clone(), bytes.to_vec()); + Ok(sha) + } + + async fn put_tree( + &self, + base_tree: &str, + changes: &[(String, Slot)], + ) -> Result { + let mut i = self.inner.lock().unwrap(); + if i.forbid_trees { + return Err("HTTP status client error (403 Forbidden) for url (x): \ + {\"message\":\"Resource not accessible by integration\"}" + .into()); + } + let mut tree = i.trees[base_tree].clone(); + for (p, e) in changes { + match e { + Some(e) => { + tree.insert(p.clone(), e.clone()); + } + None => { + // GitHub refuses to remove a path the tree lacks. + tree.remove(p) + .ok_or("HTTP status client error (422) no such path")?; + } + } + } + let t = tree_sha(&tree); + i.trees.insert(t.clone(), tree); + Ok(t) + } + + async fn put_commit( + &self, + message: &str, + tree: &str, + parents: &[String], + ) -> Result { + let mut i = self.inner.lock().unwrap(); + let t = i.trees[tree].clone(); + i.seq += 1; + let sha = format!("n{:04}", i.seq); + let seq = i.seq; + i.commits + .insert(sha.clone(), (t, parents.to_vec(), message.to_string(), seq)); + Ok(sha) + } + + async fn move_branch(&self, branch: &str, lease: &str, to: &str) -> Result { + let pushed = { + let mut i = self.inner.lock().unwrap(); + i.moves += 1; + i.push_on_move.take() + }; + if let Some((b, path, text)) = pushed { + let head = self.inner.lock().unwrap().branches[&b].clone(); + let c = self.commit_on(&[&head], &[(&path, Some(&text))], "A person's push"); + self.set(&b, &c); + } + let mut i = self.inner.lock().unwrap(); + if i.branches[branch] != lease { + return Ok(false); + } + i.branches.insert(branch.into(), to.into()); + Ok(true) + } + + async fn changed(&self, from: &str, to: &str) -> Result>, Error> { + let i = self.inner.lock().unwrap(); + Ok(Some(diff(&i.commits[from].0, &i.commits[to].0))) + } + } + + /// Merges by keeping both versions' lines (theirs, then ours' new ones). + #[derive(Default)] + struct Both { + calls: Vec<(String, Option)>, + } + + #[async_trait::async_trait] + impl Merger for Both { + async fn merge( + &mut self, + path: &str, + ancestor: Option<&str>, + theirs: &str, + ours: &str, + ) -> Option { + self.calls + .push((path.to_string(), ancestor.map(String::from))); + let mut out: Vec<&str> = theirs.lines().collect(); + for l in ours.lines() { + if !out.contains(&l) { + out.push(l); + } + } + Some(out.join("\n")) + } + } + + /// acme/web: `main` at m0; the dependency `coderhelm/feature-a` (#42) + /// had commits a1, a2 on it; the run's branch `coderhelm/feature-b` + /// started from a2 and made its own commits; then #42's branch was + /// rebased on a newer main (same changes, new hashes a1', a2'). + struct Stack { + repo: Fake, + copies: Vec, + } + + fn stack(own: usize) -> Stack { + let repo = Fake::default(); + let m0 = repo.commit_on( + &[], + &[ + ("web/app.ts", Some("app 1")), + ("web/old.ts", Some("old")), + ("README.md", Some("readme")), + ], + "main", + ); + let a1 = repo.commit_on( + &[&m0], + &[("web/schema.ts", Some("schema 1"))], + "ABC-12: schema", + ); + let a2 = repo.commit_on(&[&a1], &[("web/rows.ts", Some("rows 1"))], "ABC-12: rows"); + let mut tip = a2.clone(); + for n in 0..own { + tip = repo.commit_on( + &[&tip], + &[(&format!("web/b/f{}.ts", n % 7), Some(&format!("b {n}")))], + &format!("ABC-99: step {n}"), + ); + } + repo.set("coderhelm/feature-b", &tip); + // #42 rebased onto a newer main. + let m1 = repo.commit_on(&[&m0], &[("README.md", Some("readme 2"))], "main moved"); + let n1 = repo.commit_on( + &[&m1], + &[("web/schema.ts", Some("schema 1"))], + "ABC-12: schema", + ); + let n2 = repo.commit_on(&[&n1], &[("web/rows.ts", Some("rows 1"))], "ABC-12: rows"); + repo.set("coderhelm/feature-a", &n2); + repo.set("main", &m1); + Stack { + repo, + copies: vec![a1, a2], + } + } + + fn job<'a>(own: Own<'a>) -> Job<'a> { + Job { + branch: "coderhelm/feature-b", + onto: "coderhelm/feature-a", + own, + message: "ABC-99: one field for the two flags", + onto_pr: 42, + } + } + + /// The branch now: one commit (or two) on the dependency's head, and + /// every path is the dependency's except the change's. + fn assert_stacked(s: &Stack, r: &Rebuilt, commits: usize) { + let i = s.repo.inner.lock().unwrap(); + let dep = i.branches["coderhelm/feature-a"].clone(); + let mut c = i.branches["coderhelm/feature-b"].clone(); + assert_eq!(c, r.tip); + for _ in 0..commits { + c = i.commits[&c].1[0].clone(); + } + assert_eq!(c, dep, "the change sits right on the dependency's head"); + } + + #[tokio::test] + async fn a_branch_with_more_commits_than_any_replay_allowed_stacks() { + // 150 own commits: past the old 100-commit replay limit. + let s = stack(150); + let r = rebuild( + &s.repo, + &mut NoMerger, + &job(Own::NotCopies { + base: "main", + copies: &s.copies, + }), + ) + .await + .unwrap(); + assert_eq!(r.own_commits, 150); + assert_eq!(r.paths, 7); + assert!(r.unresolved.is_empty() && r.merged.is_empty()); + assert_stacked(&s, &r, 1); + // The change's files, and the dependency's (and main's) everything else. + assert_eq!( + s.repo.file("coderhelm/feature-b", "web/b/f3.ts").as_deref(), + Some("b 143") + ); + assert_eq!( + s.repo.file("coderhelm/feature-b", "README.md").as_deref(), + Some("readme 2") + ); + assert_eq!( + s.repo.file("coderhelm/feature-b", "web/rows.ts").as_deref(), + Some("rows 1") + ); + } + + #[tokio::test] + async fn a_dependency_never_merged_into_the_branch_stacks() { + // The dependency moved on after the rebase and the branch never had + // it merged in: nothing has to be merged first. + let s = stack(3); + let dep = s.repo.inner.lock().unwrap().branches["coderhelm/feature-a"].clone(); + let d3 = s + .repo + .commit_on(&[&dep], &[("web/extra.ts", Some("more"))], "ABC-12: more"); + s.repo.set("coderhelm/feature-a", &d3); + // A merge of main into the branch is no part of the change. + let tip = s.repo.inner.lock().unwrap().branches["coderhelm/feature-b"].clone(); + let main = s.repo.inner.lock().unwrap().branches["main"].clone(); + let mg = s + .repo + .merge_of(&tip, &main, &[("README.md", Some("readme 2"))]); + s.repo.set("coderhelm/feature-b", &mg); + let r = rebuild( + &s.repo, + &mut NoMerger, + &job(Own::NotCopies { + base: "main", + copies: &s.copies, + }), + ) + .await + .unwrap(); + assert_eq!((r.own_commits, r.paths), (3, 3)); + assert_stacked(&s, &r, 1); + assert_eq!( + s.repo + .file("coderhelm/feature-b", "web/extra.ts") + .as_deref(), + Some("more") + ); + let i = s.repo.inner.lock().unwrap(); + assert_eq!(i.commits[&r.tip].2, "ABC-99: one field for the two flags"); + } + + #[tokio::test] + async fn a_path_both_changed_is_merged_keeping_both_sides() { + let s = stack(0); + let tip = s.repo.inner.lock().unwrap().branches["coderhelm/feature-b"].clone(); + let o = s.repo.commit_on( + &[&tip], + &[("web/rows.ts", Some("rows 1\nours"))], + "ABC-99: rows", + ); + s.repo.set("coderhelm/feature-b", &o); + let dep = s.repo.inner.lock().unwrap().branches["coderhelm/feature-a"].clone(); + let d = s.repo.commit_on( + &[&dep], + &[("web/rows.ts", Some("rows 1\ntheirs"))], + "ABC-12: fix", + ); + s.repo.set("coderhelm/feature-a", &d); + let mut m = Both::default(); + let r = rebuild( + &s.repo, + &mut m, + &job(Own::NotCopies { + base: "main", + copies: &s.copies, + }), + ) + .await + .unwrap(); + assert_eq!(r.merged, vec!["web/rows.ts".to_string()]); + assert!(r.unresolved.is_empty()); + // The model saw the version the change was copied from. + assert_eq!( + m.calls, + vec![("web/rows.ts".to_string(), Some("rows 1".to_string()))] + ); + assert_eq!( + s.repo.file("coderhelm/feature-b", "web/rows.ts").as_deref(), + Some("rows 1\ntheirs\nours") + ); + assert_stacked(&s, &r, 1); + } + + #[tokio::test] + async fn a_conflict_that_can_t_be_merged_becomes_a_labelled_follow_up() { + let s = stack(1); + let tip = s.repo.inner.lock().unwrap().branches["coderhelm/feature-b"].clone(); + let o = s + .repo + .commit_on(&[&tip], &[("web/rows.ts", Some("ours"))], "ABC-99: rows"); + s.repo.set("coderhelm/feature-b", &o); + let dep = s.repo.inner.lock().unwrap().branches["coderhelm/feature-a"].clone(); + let d = s + .repo + .commit_on(&[&dep], &[("web/rows.ts", Some("theirs"))], "ABC-12: fix"); + s.repo.set("coderhelm/feature-a", &d); + let r = rebuild( + &s.repo, + &mut NoMerger, + &job(Own::NotCopies { + base: "main", + copies: &s.copies, + }), + ) + .await + .unwrap(); + assert_eq!(r.unresolved, vec!["web/rows.ts".to_string()]); + assert_stacked(&s, &r, 2); + // The first commit keeps #42's version; the follow-up puts ours back + // and says so. + let (first, msg) = { + let i = s.repo.inner.lock().unwrap(); + (i.commits[&r.tip].1[0].clone(), i.commits[&r.tip].2.clone()) + }; + let first_tree = s.repo.tree_of(&first); + let i = s.repo.inner.lock().unwrap(); + assert_eq!(i.blobs[&first_tree["web/rows.ts"].sha], b"theirs"); + drop(i); + assert_eq!( + s.repo.file("coderhelm/feature-b", "web/rows.ts").as_deref(), + Some("ours") + ); + assert!(msg.starts_with("Follow-up: this change's version of 1 file(s) #42 also changed")); + assert!(msg.contains("- web/rows.ts")); + } + + #[tokio::test] + async fn removed_and_renamed_files_come_along() { + let s = stack(0); + let tip = s.repo.inner.lock().unwrap().branches["coderhelm/feature-b"].clone(); + // A rename (old.ts to new.ts, same content) and a removal. + let o = s.repo.commit_on( + &[&tip], + &[("web/old.ts", None), ("web/new.ts", Some("old"))], + "ABC-99: rename", + ); + let o2 = s + .repo + .commit_on(&[&o], &[("web/app.ts", None)], "ABC-99: remove app"); + s.repo.set("coderhelm/feature-b", &o2); + let renamed = s.repo.files(&o).await.unwrap(); + assert_eq!( + renamed, + vec![CommitFile { + path: "web/new.ts".into(), + previous: Some("web/old.ts".into()), + patch: String::new() + }] + ); + let r = rebuild( + &s.repo, + &mut NoMerger, + &job(Own::NotCopies { + base: "main", + copies: &s.copies, + }), + ) + .await + .unwrap(); + assert_eq!(r.paths, 3); + assert_stacked(&s, &r, 1); + let b = "coderhelm/feature-b"; + assert_eq!(s.repo.file(b, "web/new.ts").as_deref(), Some("old")); + assert_eq!(s.repo.file(b, "web/old.ts"), None); + assert_eq!(s.repo.file(b, "web/app.ts"), None); + assert_eq!(s.repo.file(b, "README.md").as_deref(), Some("readme 2")); + } + + #[tokio::test] + async fn a_kept_branch_rebuilt_at_start_carries_no_copies_into_the_work() { + // A retry starts on the branch an earlier attempt left: it is rebuilt + // before any implementation, so the new work lands on #42's head and + // the pull request step finds nothing left to drop. + let s = stack(4); + let r = rebuild( + &s.repo, + &mut NoMerger, + &job(Own::NotCopies { + base: "main", + copies: &s.copies, + }), + ) + .await + .unwrap(); + let w = s.repo.commit_on( + &[&r.tip], + &[("web/b/f1.ts", Some("implemented"))], + "ABC-99: work", + ); + s.repo.set("coderhelm/feature-b", &w); + let ahead = s + .repo + .between("coderhelm/feature-a", "coderhelm/feature-b") + .await + .unwrap(); + assert_eq!(ahead.len(), 2); + assert!(ahead.iter().all(|c| !s.copies.contains(&c.sha))); + // Built again (a second retry): one commit again, same files. + let again = rebuild( + &s.repo, + &mut NoMerger, + &job(Own::NotCopies { + base: "coderhelm/feature-a", + copies: &[], + }), + ) + .await + .unwrap(); + assert_stacked(&s, &again, 1); + assert_eq!( + s.repo.file("coderhelm/feature-b", "web/b/f1.ts").as_deref(), + Some("implemented") + ); + } + + #[tokio::test] + async fn a_force_pushed_dependency_rebuilds_from_its_old_head() { + // The dependency's commits were reworded and squashed (no patch id + // matches): the old head says where the branch's own work starts. + let s = stack(2); + let old = s.copies[1].clone(); + let r = rebuild(&s.repo, &mut NoMerger, &job(Own::After { from: &old })) + .await + .unwrap(); + assert_eq!(r.own_commits, 2); + assert_stacked(&s, &r, 1); + } + + #[tokio::test] + async fn the_branch_moving_meanwhile_is_built_again_with_the_push() { + let s = stack(2); + s.repo.inner.lock().unwrap().push_on_move = Some(( + "coderhelm/feature-b".into(), + "web/late.ts".into(), + "pushed meanwhile".into(), + )); + let r = rebuild( + &s.repo, + &mut NoMerger, + &job(Own::NotCopies { + base: "main", + copies: &s.copies, + }), + ) + .await + .unwrap(); + assert_eq!(r.tries, 2); + assert_eq!(r.own_commits, 3); + assert_stacked(&s, &r, 1); + assert_eq!( + s.repo.file("coderhelm/feature-b", "web/late.ts").as_deref(), + Some("pushed meanwhile") + ); + } + + #[tokio::test] + async fn github_errors_are_retried_and_only_a_permission_stops() { + let s = stack(1); + s.repo.inner.lock().unwrap().head_failures = 3; + let own = Own::NotCopies { + base: "main", + copies: &s.copies, + }; + assert!(rebuild(&s.repo, &mut NoMerger, &job(own)).await.is_ok()); + + let s = stack(1); + s.repo.inner.lock().unwrap().forbid_trees = true; + let own = Own::NotCopies { + base: "main", + copies: &s.copies, + }; + let h = rebuild(&s.repo, &mut NoMerger, &job(own)) + .await + .unwrap_err(); + assert_eq!( + h, + Halt::Permission { + permission: "Contents: read and write".into(), + doing: "writing the rebuilt files".into() + } + ); + assert!(h.say("acme/web").starts_with( + "CoderHelm's GitHub App needs the \"Contents: read and write\" permission on acme/web" + )); + // Nothing moved. + assert_eq!(s.repo.inner.lock().unwrap().moves, 0); + } + + #[test] + fn a_force_push_rebuilds_only_coderhelm_s_pull_requests_stacked_on_it() { + let pr = |n: u64, head: &str, base: &str, user: &str, repo: &str| { + serde_json::json!({ + "number": n, + "head": {"ref": head, "repo": {"full_name": repo}}, + "base": {"ref": base}, + "user": {"login": user}, + }) + }; + let open = vec![ + pr( + 42, + "coderhelm/feature-a", + "main", + "acme-coderhelm[bot]", + "acme/web", + ), + pr( + 43, + "coderhelm/feature-b", + "coderhelm/feature-a", + "acme-coderhelm[bot]", + "acme/web", + ), + pr(44, "pat/tweak", "coderhelm/feature-a", "pat", "acme/web"), + pr( + 45, + "coderhelm/feature-c", + "coderhelm/feature-a", + "acme-coderhelm[bot]", + "someone/web", + ), + pr( + 46, + "coderhelm/feature-d", + "main", + "acme-coderhelm[bot]", + "acme/web", + ), + ]; + let d: Vec = dependents(&open, "acme", "web", "coderhelm/feature-a") + .iter() + .map(|p| p["number"].as_u64().unwrap()) + .collect(); + assert_eq!(d, vec![43]); + let many: Vec = (0..9) + .map(|n| { + pr( + n, + &format!("coderhelm/x-{n}"), + "b", + "coderhelm[bot]", + "acme/web", + ) + }) + .collect(); + assert_eq!(dependents(&many, "acme", "web", "b").len(), MAX_DEPENDENTS); + let m = restacked_message("ABC-99: one field ", 42, "coderhelm/feature-a"); + assert!(m.starts_with("ABC-99: one field\n\nRebuilt on #42")); + } + + #[test] + fn which_permission_a_refusal_names() { + let e = "HTTP status client error (403 Forbidden) for url (u): Resource not accessible by integration"; + assert_eq!(permission_needed(e, WRITE).as_deref(), Some(WRITE)); + let w = + "HTTP status client error (422 Unprocessable Entity) for url (u): refusing to allow \ + a GitHub App to create or update workflow `.github/workflows/ci.yml` without \ + `workflows` permission"; + assert_eq!( + permission_needed(w, WRITE).as_deref(), + Some("Workflows: read and write") + ); + let rl = "HTTP status client error (403 Forbidden) for url (u): API rate limit exceeded"; + assert_eq!(permission_needed(rl, WRITE), None); + assert_eq!( + permission_needed("HTTP status server error (502)", WRITE), + None + ); + } + + #[test] + fn the_plan_takes_the_change_keeps_theirs_or_names_a_conflict() { + let paths: BTreeSet = ["a", "b", "c", "d", "e"] + .iter() + .map(|s| s.to_string()) + .collect(); + let m = |v: &[(&str, Option<&str>)]| -> BTreeMap { + v.iter() + .map(|(p, s)| (p.to_string(), s.map(blob))) + .collect() + }; + let base = m(&[ + ("a", Some("1")), + ("b", Some("1")), + ("c", Some("1")), + ("d", Some("1")), + ("e", None), + ]); + let ours = m(&[ + ("a", Some("2")), + ("b", Some("1")), + ("c", Some("2")), + ("d", None), + ("e", Some("9")), + ]); + let theirs = m(&[ + ("a", Some("1")), + ("b", Some("3")), + ("c", Some("3")), + ("d", Some("1")), + ("e", Some("9")), + ]); + let p = plan(&paths, &ours, &theirs, &base); + // a: only ours changed; d: ours removed it; b: ours net nothing, + // theirs stays; c: both changed; e: the same on both. + assert_eq!( + p.take, + vec![("a".to_string(), Some(blob("2"))), ("d".to_string(), None)] + ); + assert_eq!(p.conflicts, vec!["c".to_string()]); + } + + #[test] + fn the_check_refuses_a_wrong_path_or_a_stray_change() { + let paths: BTreeSet = ["a".to_string()].into(); + let e: BTreeMap = [("a".to_string(), Some(blob("2")))].into(); + assert!(holds(&e, &e, Some(&["a".to_string()]), &paths).is_ok()); + let wrong: BTreeMap = [("a".to_string(), Some(blob("1")))].into(); + assert!(holds(&e, &wrong, None, &paths).is_err()); + assert!( + holds(&e, &e, Some(&["a".to_string(), "z".to_string()]), &paths) + .unwrap_err() + .contains("`z`") + ); + } +} diff --git a/services/worker/src/passes/resume.rs b/services/worker/src/passes/resume.rs index 1384cfc43..3588481f3 100644 --- a/services/worker/src/passes/resume.rs +++ b/services/worker/src/passes/resume.rs @@ -4547,6 +4547,9 @@ pub(crate) fn draft_hold(body: &str, title: &str, proven: bool) -> Option<&'stat if super::own_review::hold(body).is_some() { return Some("CoderHelm's own review findings are open in the description"); } + if super::stack::hold(body).is_some() { + return Some("the stacked change asks for a look first"); + } if !proven && is_e2e_proof_pr(title) { return Some("an end-to-end proof PR waits for its repeat runs"); } diff --git a/services/worker/src/passes/stack.rs b/services/worker/src/passes/stack.rs index b17ecdf58..ba33f3a41 100644 --- a/services/worker/src/passes/stack.rs +++ b/services/worker/src/passes/stack.rs @@ -22,14 +22,16 @@ //! re-created another pull request's commits (any open pull request of //! the repository, CoderHelm's or a person's) is moved onto that pull //! request's branch without the copies and stacks on it ([`before_pr`]): -//! its own commits are replayed with the copies left out, or, when they -//! don't replay cleanly, that branch is merged in (the model resolves -//! conflicts) and the change becomes one commit on top of it. Copies -//! usually come from the dependency's branch being rebased after the run -//! started on it: its commits got new hashes and the run's branch still -//! holds the old ones. A branch kept from an earlier attempt is checked -//! before any implementation ([`at_start`]). The run stops only when -//! neither way works, saying what the person can do. +//! its own change is rebuilt there file by file as one commit +//! ([`super::restack`]), however many commits it has and without merging +//! anything first. Copies usually come from the dependency's branch being +//! rebased after the run started on it: its commits got new hashes and +//! the run's branch still holds the old ones. A branch kept from an +//! earlier attempt is rebuilt the same way before any implementation +//! ([`at_start`]), and a force push to a branch CoderHelm's open pull +//! requests stack on rebuilds them ([`super::restack::after_forced_push`]). +//! The pull request always opens; only a missing GitHub App permission +//! stops the run, naming it. use std::collections::{BTreeMap, BTreeSet}; use std::hash::{Hash, Hasher}; @@ -37,7 +39,9 @@ use std::hash::{Hash, Hasher}; use regex::Regex; use serde_json::Value; -use crate::clients::github::{GitHubClient, RebaseResult}; +use crate::clients::github::{CommitFile, GitHubClient}; + +use super::restack; /// The open pull request a branch builds on. #[derive(Debug, Clone, Default, PartialEq, Eq)] @@ -47,26 +51,70 @@ pub struct Dependency { pub title: String, /// How it was found (the ticket's line, or the commits it copied). pub why: String, + /// Files both changed whose two versions couldn't be merged: the + /// rebuilt commit keeps the dependency's, a labelled follow-up commit + /// puts this change's back. The pull request stays a draft. + pub unresolved: Vec, + /// The branch repeats the dependency's commits and couldn't be rebuilt + /// on it: the pull request targets the original base, as a draft. + pub not_stacked: bool, } impl Dependency { /// The pull request section: what it builds on and the merge order. pub fn section(&self) -> String { - format!( - "{SECTION_START}\n## Builds on #{n}\n\nThis pull request is stacked on #{n} (`{b}`, \ - \"{t}\"): its base is that branch, so its diff shows only this ticket's change. {why}\n\n\ - Merge order: #{n} first, then this one. When #{n} merges, GitHub moves this pull \ - request's base to #{n}'s base; CoderHelm rebases it if needed.\n{SECTION_END}", - n = self.number, - b = self.branch, - t = self.title.replace('"', "'"), - why = self.why.trim(), - ) + let (n, b) = (self.number, &self.branch); + let t = self.title.replace('"', "'"); + let why = self.why.trim(); + let mut out = if self.not_stacked { + format!( + "## Repeats #{n}\n\nThis pull request carries commits of #{n} (`{b}`, \"{t}\") \ + under other hashes, so its diff shows them too. {why}\n\n\ + Merge order: #{n} first, then this one. It stays a draft until it is rebuilt on \ + `{b}`: running the ticket again does that." + ) + } else { + format!( + "## Builds on #{n}\n\nThis pull request is stacked on #{n} (`{b}`, \"{t}\"): its \ + base is that branch, so its diff shows only this ticket's change. {why}\n\n\ + Merge order: #{n} first, then this one. When #{n} merges, GitHub moves this pull \ + request's base to #{n}'s base; CoderHelm rebases it if needed." + ) + }; + if !self.unresolved.is_empty() { + out.push_str(&format!( + "\n\n### Needs a look\n\n#{n} also changed these files, and the two versions \ + couldn't be merged. The rebuilt commit keeps #{n}'s version; the commit after it, \ + labelled \"Follow-up\", puts this change's back. Check that each keeps #{n}'s \ + work before merging; the pull request stays a draft until then.\n" + )); + for p in &self.unresolved { + out.push_str(&format!("\n- `{p}`")); + } + } + let hold = if self.not_stacked || !self.unresolved.is_empty() { + format!("\n{HOLD}") + } else { + String::new() + }; + format!("{SECTION_START}\n{out}{hold}\n{SECTION_END}") } } pub const SECTION_START: &str = ""; pub const SECTION_END: &str = ""; +/// In the stack section when a person has to look before it merges. +const HOLD: &str = ""; + +/// Why a pull request stays a draft: its stack section asks a person to +/// look first (files both pull requests changed, or a branch that still +/// repeats the other pull request's commits). +pub fn hold(body: &str) -> Option { + let (a, b) = (body.find(SECTION_START)?, body.find(SECTION_END)?); + (b > a && body[a..b].contains(HOLD)).then(|| { + "the stacked change asks for a look first (see its \"Builds on\" section)".to_string() + }) +} /// Words that make a line say the ticket depends on what it names. const DEPENDS: &[&str] = &[ @@ -160,6 +208,7 @@ pub fn pick( branch: p["head"]["ref"].as_str().unwrap_or("").to_string(), title: p["title"].as_str().unwrap_or("").to_string(), why, + ..Default::default() }; for n in prs { if let Some(p) = open @@ -348,6 +397,7 @@ pub fn pick_series( branch: p["head"]["ref"].as_str().unwrap_or("").to_string(), title: p["title"].as_str().unwrap_or("").to_string(), why: format!("This ticket is part {n} of {m}; part {k}'s pull request is still open."), + ..Default::default() }) } @@ -409,6 +459,7 @@ pub fn by_files(missing: &[String], changes: &[(Value, Vec)]) -> Option< why: format!( "The ticket names `{path}`, which the base branch doesn't have yet; this pull request adds it." ), + ..Default::default() }) } @@ -530,37 +581,51 @@ pub async fn for_ticket( } /// Right after the run's branch is ready, before any implementation: a -/// branch kept from an earlier attempt may carry copies of another open -/// pull request's commits (that pull request's branch was rebased since). -/// When the branch's own commits replay cleanly onto that pull request's -/// branch, the copies are dropped now and the run stacks on it; otherwise -/// the pull request step deals with them. +/// branch kept from an earlier attempt (or retried) may carry copies of +/// another open pull request's commits (that pull request's branch was +/// rebased since). Its own change is rebuilt on that branch file by file +/// now, so the run builds on it; when that can't be done the pull request +/// step tries again. pub async fn at_start( + state: &crate::WorkerState, github: &GitHubClient, msg: &mut crate::models::TicketMessage, branch: &str, + provider: &crate::agent::provider::ModelProvider, + usage: &mut crate::models::TokenUsage, ) -> Option { - let c = copied( + let (owner, repo) = (msg.repo_owner.clone(), msg.repo_name.clone()); + let c = copied(github, &owner, &repo, &msg.base_branch, branch).await?; + let mut merger = restack::ModelMerger { + state, + provider, + usage, + theirs: format!("pull request #{}'s branch", c.dep.number), + }; + match rebuild_on( github, - &msg.repo_owner, - &msg.repo_name, + &owner, + &repo, &msg.base_branch, branch, + &c, + &mut merger, ) - .await?; - match drop_copies(github, &msg.repo_owner, &msg.repo_name, branch, &c).await { - Ok(()) => { + .await + { + Ok(r) => { msg.base_branch = c.dep.branch.clone(); Some(Dependency { - why: dropped_why(&c), + why: rebuilt_why(&c, &r), + unresolved: r.unresolved, ..c.dep }) } - Err(why) => { + Err(h) => { tracing::info!( branch, dep = c.dep.number, - why, + why = %h.say(&format!("{owner}/{repo}")), "Copies of an open pull request's commits stay until the pull request step" ); None @@ -569,15 +634,16 @@ pub async fn at_start( } /// Right before the pull request opens: a branch that copied another open -/// pull request's commits is moved onto that pull request's branch without -/// the copies, and the pull request is stacked on it. First the branch's -/// own commits are replayed onto it (`git rebase --onto`, copies left -/// out); when they don't replay cleanly, that branch is merged into the -/// run's branch (conflicts are resolved by the model, the head is never -/// reset) and the merged code becomes one commit on top of it. Only when -/// both fail does the run stop, saying what the person can do. Returns the -/// dependency the pull request states (the ticket's, or the one found by -/// its commits). +/// pull request's commits gets its own change rebuilt on that pull +/// request's branch, file by file, as one commit (`restack`): no commit is +/// replayed and nothing has to be merged first, so neither the number of +/// commits nor a merge can stop it. Files both changed are merged by the +/// model; one it can't merge keeps the other pull request's version plus a +/// labelled follow-up commit with this change's, and the pull request +/// opens as a draft naming it. When the rebuild fails anyway (GitHub kept +/// failing), the pull request still opens against the original base, as a +/// draft that says so. Only a missing permission stops the run. Returns the +/// dependency the pull request states. pub async fn before_pr( state: &crate::WorkerState, github: &GitHubClient, @@ -591,146 +657,120 @@ pub async fn before_pr( let Some(c) = copied(github, &owner, &repo, &msg.base_branch, branch).await else { return Ok(from_ticket.filter(|d| d.branch == msg.base_branch)); }; - // Both ways build on the dependency's branch: the merge resolves - // conflicts against it. - let base = std::mem::replace(&mut msg.base_branch, c.dep.branch.clone()); - let msg_ref: &crate::models::TicketMessage = msg; - let outcome = recover(drop_copies(github, &owner, &repo, branch, &c), || { - tracing::info!( - branch, - dep = c.dep.number, - "Own commits don't replay onto the open pull request's branch; merging it in" - ); - merge_and_flatten(state, github, msg_ref, branch, &c, provider, usage) - }) - .await; - match outcome { - Ok(how) => Ok(Some(Dependency { - why: how.why(&c), - ..c.dep - })), - Err((replayed, merged)) => { - msg.base_branch = base; - Err(Refused(refusal(&c, branch, &replayed, &merged))) + let mut merger = restack::ModelMerger { + state, + provider, + usage, + theirs: format!("pull request #{}'s branch", c.dep.number), + }; + match rebuild_on( + github, + &owner, + &repo, + &msg.base_branch, + branch, + &c, + &mut merger, + ) + .await + { + Ok(r) => { + msg.base_branch = c.dep.branch.clone(); + Ok(Some(Dependency { + why: rebuilt_why(&c, &r), + unresolved: r.unresolved, + ..c.dep + })) } - } -} - -/// How a branch's copies of another pull request's commits were dropped. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Recovered { - /// Its own commits replayed onto that pull request's branch. - Replayed, - /// That branch merged in, the change rebuilt as one commit on it. - Rebuilt, -} - -impl Recovered { - fn why(self, c: &Copy) -> String { - match self { - Recovered::Replayed => dropped_why(c), - Recovered::Rebuilt => format!( - "The branch had re-created {} of its commits; #{n}'s branch was merged in and \ - this change rebuilt as one commit on top of it, so those commits come from #{n} \ - itself.", - c.commits.len(), - n = c.dep.number - ), + Err(h @ restack::Halt::Permission { .. }) => Err(Refused(format!( + "{} The work is kept on branch `{branch}`.", + h.say(&format!("{owner}/{repo}")) + ))), + Err(restack::Halt::Failed(why)) => { + tracing::warn!( + branch, + dep = c.dep.number, + why, + "Couldn't rebuild the change on the open pull request's branch; opening it as a draft" + ); + Ok(Some(Dependency { + why: not_rebuilt_why(&c, &why), + not_stacked: true, + ..c.dep + })) } } } -/// The order of the recovery: replaying the branch's own commits first; -/// merging the dependency in (the model resolves conflicts) only when that -/// fails. Both reasons when neither works. -pub async fn recover( - replay: impl std::future::Future>, - merge: M, -) -> Result -where - M: FnOnce() -> F, - F: std::future::Future>, -{ - let replayed = match replay.await { - Ok(()) => return Ok(Recovered::Replayed), - Err(why) => why, - }; - match merge().await { - Ok(()) => Ok(Recovered::Rebuilt), - Err(merged) => Err((replayed, merged)), - } -} - -fn dropped_why(c: &Copy) -> String { - format!( - "The branch had re-created {} of its commits; they were dropped and its own commits \ - replayed onto `{}`, so those commits come from #{} itself.", - c.commits.len(), - c.dep.branch, - c.dep.number - ) -} - -/// The branch's own commits replayed onto the dependency's branch, the -/// copies left out; why not when that can't be done. -async fn drop_copies( +/// The branch's own change rebuilt on the dependency's head ([`restack`]). +async fn rebuild_on( github: &GitHubClient, owner: &str, repo: &str, + base: &str, branch: &str, c: &Copy, -) -> Result<(), String> { - let lease = github - .get_ref(owner, repo, branch) - .await - .map_err(|e| format!("its head couldn't be read ({e})"))?; - match github - .rebase_onto(owner, repo, branch, &c.dep.branch, &c.commits, &lease) - .await - { - Ok(RebaseResult::Rebased(_)) | Ok(RebaseResult::UpToDate) => Ok(()), - Ok(RebaseResult::NotClean(why)) => Err(why), - Ok(RebaseResult::Moved) => Err("the branch moved while it was being rebased".to_string()), - Err(e) => Err(format!("the rebase failed ({e})")), - } + merger: &mut M, +) -> Result { + let gh = restack::Gh { + github, + owner, + repo, + known: &c.files, + }; + let message = flat_message(c); + restack::rebuild( + &gh, + merger, + &restack::Job { + branch, + onto: &c.dep.branch, + own: restack::Own::NotCopies { + base, + copies: &c.commits, + }, + message: &message, + onto_pr: c.dep.number, + }, + ) + .await } -/// The dependency's branch (`msg.base_branch` by now) merged into the -/// run's branch, conflicts resolved by the model, then the merged code as -/// one commit on top of the dependency's branch. -async fn merge_and_flatten( - state: &crate::WorkerState, - github: &GitHubClient, - msg: &crate::models::TicketMessage, - branch: &str, - c: &Copy, - provider: &crate::agent::provider::ModelProvider, - usage: &mut crate::models::TokenUsage, -) -> Result<(), String> { - if let Err(e) = super::pr::resolve_conflicts(state, msg, github, branch, provider, usage).await - { - return Err(format!("merging it in failed ({e})")); - } - let lease = github - .get_ref(&msg.repo_owner, &msg.repo_name, branch) - .await - .map_err(|e| format!("its head couldn't be read ({e})"))?; - match github - .flatten_onto( - &msg.repo_owner, - &msg.repo_name, - branch, - &c.dep.branch, - &flat_message(c), - &lease, - ) - .await - { - Ok(RebaseResult::Rebased(_)) | Ok(RebaseResult::UpToDate) => Ok(()), - Ok(RebaseResult::NotClean(why)) => Err(why), - Ok(RebaseResult::Moved) => Err("the branch moved while it was being rebuilt".to_string()), - Err(e) => Err(format!("rebuilding it failed ({e})")), +/// What happened, for the stack section: the copies dropped, the change +/// rebuilt on the dependency, the files merged. +pub fn rebuilt_why(c: &Copy, r: &restack::Rebuilt) -> String { + let n = c.dep.number; + let mut out = format!( + "The branch had re-created {} of #{n}'s commits under other hashes; its own change \ + ({} commit(s), {} file(s)) was rebuilt as one commit on `{}`, so those commits come from \ + #{n} itself.", + c.commits.len(), + r.own_commits, + r.paths, + c.dep.branch, + ); + if !r.merged.is_empty() { + let list: Vec = r.merged.iter().map(|p| format!("`{p}`")).collect(); + out.push_str(&format!( + " #{n} had also changed {}; the two versions were merged, keeping both.", + list.join(", ") + )); } + out +} + +/// Why the pull request isn't stacked, for its section: the copies, and +/// why rebuilding failed. +pub fn not_rebuilt_why(c: &Copy, why: &str) -> String { + let short: Vec<&str> = c.commits.iter().map(|s| &s[..7.min(s.len())]).collect(); + format!( + "The branch repeats {} of #{}'s commits ({}); rebuilding its own change on `{}` didn't \ + work this time ({why}).", + c.commits.len(), + c.dep.number, + short.join(", "), + c.dep.branch, + ) } /// The messages of `listed`'s commits (a compare's, oldest first) that @@ -761,7 +801,7 @@ pub fn flat_message(c: &Copy) -> String { .unwrap_or("Rebuild this change") .to_string(); let mut out = format!( - "{head}\n\nRebuilt on #{} (`{}`) without the {} commit(s) copied from it.", + "{head}\n\nRebuilt on #{} (`{}`) file by file, without the {} commit(s) copied from it.", c.dep.number, c.dep.branch, c.commits.len() @@ -775,24 +815,6 @@ pub fn flat_message(c: &Copy) -> String { out.trim_end().to_string() } -/// Why the run stops, in plain words with what the person can do: both -/// ways of building on the dependency failed. -pub fn refusal(c: &Copy, branch: &str, replayed: &str, merged: &str) -> String { - let short: Vec<&str> = c.commits.iter().map(|s| &s[..7.min(s.len())]).collect(); - format!( - "the branch repeats {k} commit(s) of open pull request #{n} (`{b}`) under other hashes \ - ({shas}). Dropping them didn't work ({replayed}), and neither did merging #{n}'s branch \ - in and rebuilding this change on it ({merged}). The work is kept on branch `{branch}`. \ - To finish it: merge or close #{n} and run the ticket again, or move `{branch}` onto \ - `{b}` yourself (`git rebase --onto {b}`, keeping only this change's commits) and open \ - the pull request against `{b}`.", - k = c.commits.len(), - n = c.dep.number, - b = c.dep.branch, - shas = short.join(", "), - ) -} - // ── Patch ids ─────────────────────────────────────────────────────────────── /// A commit's patch id: the same for the same change whatever its hash, @@ -836,6 +858,8 @@ pub struct Copy { /// The messages of the branch's other commits (merge commits aside): /// its own work. pub own: Vec, + /// The files of the branch's commits, as read for their patch ids. + pub files: BTreeMap>, } /// The branch's commits that match another pull request's, by patch id: @@ -848,24 +872,30 @@ pub fn matches(ours: &[(String, u64)], theirs: &[(String, u64)]) -> Vec .collect() } -const MAX_COMMITS: usize = 60; const MAX_PRS: usize = 40; +/// Each commit's patch id, and its files as read. async fn ids( github: &GitHubClient, owner: &str, repo: &str, shas: &[String], -) -> Vec<(String, u64)> { +) -> (Vec<(String, u64)>, BTreeMap>) { let mut out = Vec::new(); - for sha in shas.iter().take(MAX_COMMITS) { - if let Ok(files) = github.commit_patches(owner, repo, sha).await { - if let Some(id) = patch_id(&files) { + let mut read = BTreeMap::new(); + for sha in shas { + if let Ok(files) = github.commit_changes(owner, repo, sha).await { + let patches: Vec<(String, String)> = files + .iter() + .map(|f| (f.path.clone(), f.patch.clone())) + .collect(); + if let Some(id) = patch_id(&patches) { out.push((sha.clone(), id)); } + read.insert(sha.clone(), files); } } - out + (out, read) } /// The open pull request whose commits the branch re-created the most of, @@ -878,8 +908,10 @@ pub async fn copied( base: &str, branch: &str, ) -> Option { + // Every commit, however many: a copy past a cut-off would read as the + // branch's own work. let listed = github - .compare_commits(owner, repo, base, branch, MAX_COMMITS) + .compare_all_commits(owner, repo, base, branch) .await .ok()?; let ours_shas: Vec = listed @@ -889,7 +921,7 @@ pub async fn copied( if ours_shas.is_empty() { return None; } - let ours = ids(github, owner, repo, &ours_shas).await; + let (ours, files) = ids(github, owner, repo, &ours_shas).await; let our_files: BTreeSet = github .compare_changed_files(owner, repo, base, branch) .await @@ -923,7 +955,7 @@ pub async fn copied( .iter() .filter_map(|c| c["sha"].as_str().map(String::from)) .collect(); - let theirs = ids(github, owner, repo, &their_shas).await; + let (theirs, _) = ids(github, owner, repo, &their_shas).await; let m = matches(&ours, &theirs); if !m.is_empty() && best.as_ref().is_none_or(|b| m.len() > b.commits.len()) { best = Some(Copy { @@ -931,14 +963,15 @@ pub async fn copied( number: n, branch: head.to_string(), title: p["title"].as_str().unwrap_or("").to_string(), - why: String::new(), + ..Default::default() }, own: own_messages(&listed, &m), commits: m, + files: BTreeMap::new(), }); } } - best + best.map(|c| Copy { files, ..c }) } /// The body with the stack section replaced (or added after the first @@ -1284,10 +1317,11 @@ mod tests { number: 42, branch: "abc-12-schema".into(), title: "ABC-12 schema work".into(), - why: String::new(), + ..Default::default() }, own: own_messages(&listed, &commits), commits, + files: BTreeMap::new(), } } @@ -1304,7 +1338,9 @@ mod tests { // Rebuilt as one commit: the first own subject, then each one's. let m = flat_message(&c); assert!(m.starts_with("ABC-99: one field for the two flags\n\n")); - assert!(m.contains("Rebuilt on #42 (`abc-12-schema`) without the 2 commit(s)")); + assert!( + m.contains("Rebuilt on #42 (`abc-12-schema`) file by file, without the 2 commit(s)") + ); assert!(m.contains("- ABC-99: tests")); assert!(!m.contains("Body.")); // One own commit: no list. @@ -1314,61 +1350,74 @@ mod tests { } #[test] - fn a_stacked_dependency_says_its_copies_were_dropped() { + fn a_rebuilt_branch_says_what_happened_and_stacks() { let c = copy_of_42(); - let why = dropped_why(&c); - assert!(why.contains("re-created 2 of its commits")); - assert!(why.contains("replayed onto `abc-12-schema`")); + let r = restack::Rebuilt { + own_commits: 140, + paths: 9, + merged: vec!["web/rows.ts".into()], + ..Default::default() + }; + let why = rebuilt_why(&c, &r); + assert!(why.contains("re-created 2 of #42's commits")); + assert!( + why.contains("(140 commit(s), 9 file(s)) was rebuilt as one commit on `abc-12-schema`") + ); + assert!(why.contains("#42 had also changed `web/rows.ts`; the two versions were merged")); let d = Dependency { why, ..c.dep }; - assert!(d.section().contains("stacked on #42 (`abc-12-schema`")); + let s = d.section(); + assert!(s.contains("stacked on #42 (`abc-12-schema`")); + assert!(!s.contains("Needs a look")); + // Nothing to look at: it may leave draft. + assert_eq!(hold(&put_section("Body", &s)), None); } - #[tokio::test] - async fn copies_are_dropped_by_replaying_first_and_merging_only_on_a_conflict() { - // The own commits replay onto the dependency: no merge, no model. - let merged = std::cell::Cell::new(false); - let how = recover(async { Ok(()) }, || async { - merged.set(true); - Ok(()) - }) - .await; - assert_eq!(how, Ok(Recovered::Replayed)); - assert!(!merged.get()); - // A commit conflicts with the dependency's head: merged in instead. - let how = recover( - async { Err("commit o1 conflicts with the base".to_string()) }, - || async { Ok(()) }, - ) - .await; - assert_eq!(how, Ok(Recovered::Rebuilt)); + #[test] + fn files_that_couldn_t_be_merged_keep_the_pull_request_a_draft() { let c = copy_of_42(); - assert!(Recovered::Rebuilt - .why(&c) - .contains("#42's branch was merged in")); - // Neither works: both reasons, for the message. - let how = recover(async { Err("a".to_string()) }, || async { - Err("b".to_string()) - }) - .await; - assert_eq!(how, Err(("a".to_string(), "b".to_string()))); + let d = Dependency { + why: "w".into(), + unresolved: vec!["web/rows.ts".into()], + ..c.dep.clone() + }; + let s = d.section(); + assert!(s.contains("### Needs a look")); + assert!(s.contains("- `web/rows.ts`")); + assert!(s.contains("labelled \"Follow-up\"")); + let body = put_section("## Summary\n\nOne field.", &s); + assert!(hold(&body).is_some()); + // A branch that couldn't be rebuilt opens anyway, as a draft that + // says why, against the original base. + let d = Dependency { + why: not_rebuilt_why(&c, "reading the branch's head kept failing on GitHub (502)"), + not_stacked: true, + ..c.dep + }; + let s = d.section(); + assert!(s.starts_with(&format!("{SECTION_START}\n## Repeats #42"))); + assert!(s.contains("repeats 2 of #42's commits (c1aaaaa, c2bbbbb)")); + assert!(s.contains("running the ticket again does that")); + assert!(hold(&put_section("Body", &s)).is_some()); + // A hold marker outside the section is no hold. + assert_eq!(hold("Body "), None); } #[test] - fn stopping_says_what_the_person_can_do() { - let c = copy_of_42(); - let r = Refused(refusal( - &c, - "coderhelm/abc-99", - "commit o1 conflicts with the base", - "`abc-12-schema` isn't merged into the branch yet", + fn stopping_names_the_missing_permission_and_where_the_work_is() { + let h = restack::Halt::Permission { + permission: "Contents: read and write".into(), + doing: "moving the branch".into(), + }; + let r = Refused(format!( + "{} The work is kept on branch `coderhelm/feature-b`.", + h.say("acme/web") )) .to_string(); - assert!(r.starts_with("Stopped before opening a pull request: the branch repeats 2")); - assert!(r.contains("(c1aaaaa, c2bbbbb)")); - assert!(r.contains("commit o1 conflicts with the base")); - assert!(r.contains("The work is kept on branch `coderhelm/abc-99`.")); - assert!(r.contains("merge or close #42 and run the ticket again")); - assert!(r.contains("open the pull request against `abc-12-schema`")); + assert!(r.starts_with( + "Stopped before opening a pull request: CoderHelm's GitHub App needs the \"Contents: \ + read and write\" permission on acme/web for moving the branch." + )); + assert!(r.ends_with("The work is kept on branch `coderhelm/feature-b`.")); } #[test] @@ -1378,6 +1427,7 @@ mod tests { branch: "b".into(), title: "t".into(), why: "w".into(), + ..Default::default() }; let once = put_section("Body", &d.section()); let twice = put_section(&once, &d.section());