1use std::ffi::OsStr;
2use std::io::Read;
3use std::path::{Path, PathBuf};
4use std::process::{Command, Stdio};
5use std::sync::Arc;
6
7use blyte_agent::approval::{Approval, Approver, LandDetails};
8
9use crate::publish::{output_detail, run_gh, run_git};
10use crate::requests::{
11 check_request_ownership, load_published_record, write_published_record, RequestOwnership,
12 RequestOwnershipError,
13};
14use crate::serve::Surface;
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct PullRequestInfo {
18 pub number: u64,
19 pub state: String,
20 pub is_draft: bool,
21 pub title: String,
22 pub head_ref_name: String,
23 pub head_ref_oid: String,
24 pub base_ref_name: String,
25 pub mergeable: String,
26}
27
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct CheckReport {
30 pub passed: bool,
31 pub exit_code: Option<i32>,
32 pub output_tail: String,
33}
34
35pub const CHECK_OUTPUT_TAIL_BYTES: usize = 4000;
36
37const PR_VIEW_JSON_FIELDS: &str =
38 "number,state,isDraft,title,headRefName,headRefOid,baseRefName,mergeable";
39
40pub fn view_pull_request(root: &Path, url: &str) -> Result<PullRequestInfo, String> {
41 view_pull_request_with_gh(root, "gh", url)
42}
43
44pub fn view_pull_request_with_gh(
45 root: &Path,
46 gh: &str,
47 url: &str,
48) -> Result<PullRequestInfo, String> {
49 let out = run_gh(
50 root,
51 OsStr::new(gh),
52 &["pr", "view", url, "--json", PR_VIEW_JSON_FIELDS],
53 "gh pr view",
54 )?;
55
56 let value: serde_json::Value = serde_json::from_slice(&out.stdout)
57 .map_err(|e| format!("gh pr view returned invalid JSON: {e}"))?;
58 let obj = value
59 .as_object()
60 .ok_or_else(|| "gh pr view did not return a JSON object".to_string())?;
61
62 Ok(PullRequestInfo {
63 number: required_u64(obj, "number")?,
64 state: required_string(obj, "state")?,
65 is_draft: required_bool(obj, "isDraft")?,
66 title: required_string(obj, "title")?,
67 head_ref_name: required_string(obj, "headRefName")?,
68 head_ref_oid: required_string(obj, "headRefOid")?,
69 base_ref_name: required_string(obj, "baseRefName")?,
70 mergeable: required_string(obj, "mergeable")?,
71 })
72}
73
74fn required_u64(
75 obj: &serde_json::Map<String, serde_json::Value>,
76 field: &str,
77) -> Result<u64, String> {
78 match obj.get(field) {
79 None | Some(serde_json::Value::Null) => Err(format!("gh pr view returned no {field}")),
80 Some(v) => v
81 .as_u64()
82 .ok_or_else(|| format!("gh pr view returned invalid {field}")),
83 }
84}
85
86fn required_bool(
87 obj: &serde_json::Map<String, serde_json::Value>,
88 field: &str,
89) -> Result<bool, String> {
90 match obj.get(field) {
91 None | Some(serde_json::Value::Null) => Err(format!("gh pr view returned no {field}")),
92 Some(v) => v
93 .as_bool()
94 .ok_or_else(|| format!("gh pr view returned invalid {field}")),
95 }
96}
97
98fn required_string(
99 obj: &serde_json::Map<String, serde_json::Value>,
100 field: &str,
101) -> Result<String, String> {
102 match obj.get(field) {
103 None | Some(serde_json::Value::Null) => Err(format!("gh pr view returned no {field}")),
104 Some(v) => v
105 .as_str()
106 .map(String::from)
107 .ok_or_else(|| format!("gh pr view returned invalid {field}")),
108 }
109}
110
111pub fn check_landable(info: &PullRequestInfo, published_commit: &str) -> Result<(), String> {
112 if info.state != "OPEN" {
113 return Err(format!(
114 "pull request #{} is not open (state: {})",
115 info.number, info.state
116 ));
117 }
118 if info.is_draft {
119 return Err(format!("pull request #{} is a draft", info.number));
120 }
121 if info.mergeable == "CONFLICTING" {
122 return Err(format!(
123 "pull request #{} conflicts with {}",
124 info.number, info.base_ref_name
125 ));
126 }
127 if info.head_ref_oid != published_commit {
128 return Err(format!(
129 "pull request #{} head {} is not the published commit {published_commit}",
130 info.number, info.head_ref_oid
131 ));
132 }
133 Ok(())
134}
135
136fn land_worktree_rel_path(number: u64) -> PathBuf {
137 Path::new(".wt").join(format!("land-{number}"))
138}
139
140pub fn land_worktree_path(root: &Path, number: u64) -> PathBuf {
141 root.join(land_worktree_rel_path(number))
142}
143
144pub fn expand_check_command(command: &str, number: u64) -> String {
145 command.replace("{pr}", &number.to_string())
146}
147
148pub fn run_land_check(
149 root: &Path,
150 command: &str,
151 number: u64,
152 commit: &str,
153) -> Result<CheckReport, String> {
154 let wt_rel = land_worktree_rel_path(number);
155 let wt_path = root.join(&wt_rel);
156 if wt_path.exists() || wt_path.symlink_metadata().is_ok() {
157 let display = wt_path.display();
158 return Err(format!(
159 "{display} already exists: another landing check is running, or one was interrupted; remove it with git worktree remove --force {display}"
160 ));
161 }
162
163 let add_out = Command::new("git")
164 .args(["worktree", "add", "--detach"])
165 .arg(&wt_rel)
166 .arg(commit)
167 .current_dir(root)
168 .env("GIT_TERMINAL_PROMPT", "0")
169 .output()
170 .map_err(|e| format!("failed to run git worktree add: {e}"))?;
171 if !add_out.status.success() {
172 let detail = output_detail(&add_out);
173 return Err(format!("git worktree add failed: {detail}"));
174 }
175
176 let expanded = expand_check_command(command, number);
177 let check_res = execute_check(&wt_path, &expanded);
178 let remove_res = remove_land_worktree(root, &wt_rel, &wt_path);
179 match (check_res, remove_res) {
180 (Ok(report), Ok(())) => Ok(report),
181 (Ok(_), Err(remove_err)) => Err(remove_err),
182 (Err(check_err), Ok(())) => Err(check_err),
183 (Err(check_err), Err(remove_err)) => Err(format!("{check_err}; {remove_err}")),
184 }
185}
186
187fn execute_check(wt_path: &Path, expanded: &str) -> Result<CheckReport, String> {
188 let (mut reader, writer) =
189 std::io::pipe().map_err(|e| format!("could not run the land check: {e}"))?;
190 let writer_err = writer
191 .try_clone()
192 .map_err(|e| format!("could not run the land check: {e}"))?;
193
194 let mut child = Command::new("sh")
195 .args(["-c", expanded])
196 .current_dir(wt_path)
197 .stdin(Stdio::null())
198 .stdout(Stdio::from(writer))
199 .stderr(Stdio::from(writer_err))
200 .spawn()
201 .map_err(|e| format!("could not run the land check: {e}"))?;
202
203 let mut output_bytes = Vec::new();
204 let read_res = reader.read_to_end(&mut output_bytes);
205 let status = child
206 .wait()
207 .map_err(|e| format!("could not run the land check: {e}"))?;
208 read_res.map_err(|e| format!("could not run the land check: {e}"))?;
209
210 let exit_code = status.code();
211 let passed = exit_code == Some(0);
212 let output_tail = tail_utf8(&output_bytes, CHECK_OUTPUT_TAIL_BYTES);
213 Ok(CheckReport {
214 passed,
215 exit_code,
216 output_tail,
217 })
218}
219
220fn remove_land_worktree(root: &Path, wt_rel: &Path, wt_path: &Path) -> Result<(), String> {
221 let out = Command::new("git")
222 .args(["worktree", "remove", "--force"])
223 .arg(wt_rel)
224 .current_dir(root)
225 .env("GIT_TERMINAL_PROMPT", "0")
226 .output()
227 .map_err(|e| format!("failed to remove worktree {}: {e}", wt_path.display()))?;
228 if !out.status.success() {
229 let detail = output_detail(&out);
230 return Err(format!(
231 "failed to remove worktree {}: {detail}",
232 wt_path.display()
233 ));
234 }
235 Ok(())
236}
237
238fn tail_utf8(bytes: &[u8], max_bytes: usize) -> String {
239 let text = String::from_utf8_lossy(bytes);
240 if text.len() <= max_bytes {
241 return text.into_owned();
242 }
243 let mut start = text.len() - max_bytes;
244 while !text.is_char_boundary(start) {
245 start += 1;
246 }
247 text[start..].to_string()
248}
249
250pub fn merge_pull_request(root: &Path, url: &str, commit: &str) -> Result<(), String> {
251 merge_pull_request_with_gh(root, "gh", url, commit)
252}
253
254pub fn merge_pull_request_with_gh(
255 root: &Path,
256 gh: &str,
257 url: &str,
258 commit: &str,
259) -> Result<(), String> {
260 run_gh(
261 root,
262 OsStr::new(gh),
263 &[
264 "pr",
265 "merge",
266 url,
267 "--squash",
268 "--match-head-commit",
269 commit,
270 ],
271 "gh pr merge",
272 )?;
273 Ok(())
274}
275
276pub fn update_default_branch(root: &Path, base: &str) -> Result<String, String> {
277 let fetch = run_git(root, &["fetch", "--quiet", "origin", base])?;
278 if !fetch.status.success() {
279 let detail = output_detail(&fetch);
280 return Err(format!("git fetch origin {base} failed: {detail}"));
281 }
282
283 let head = run_git(root, &["rev-parse", "--abbrev-ref", "HEAD"])?;
284 if !head.status.success() {
285 let detail = output_detail(&head);
286 return Err(format!(
287 "could not read current branch in {}: {detail}",
288 root.display()
289 ));
290 }
291 let branch = String::from_utf8_lossy(&head.stdout).trim().to_string();
292 if branch != base {
293 return Ok(format!(
294 "fetched origin/{base}; {} is on {branch}, left as it was",
295 root.display()
296 ));
297 }
298
299 let status = run_git(root, &["status", "--porcelain"])?;
300 if !status.status.success() {
301 let detail = output_detail(&status);
302 return Err(format!(
303 "could not read git status in {}: {detail}",
304 root.display()
305 ));
306 }
307 if !String::from_utf8_lossy(&status.stdout).trim().is_empty() {
308 return Ok(format!(
309 "fetched origin/{base}; {} has uncommitted changes, left as it was",
310 root.display()
311 ));
312 }
313
314 let remote_ref = format!("origin/{base}");
315 let merge = run_git(root, &["merge", "--ff-only", &remote_ref])?;
316 if !merge.status.success() {
317 let detail = output_detail(&merge);
318 return Err(format!("git merge --ff-only {remote_ref} failed: {detail}"));
319 }
320 Ok(format!(
321 "fetched origin/{base} and fast-forwarded {base} in {}",
322 root.display()
323 ))
324}
325
326pub trait Lander: Send + Sync {
327 fn view(&self, root: &Path, url: &str) -> Result<PullRequestInfo, String>;
328 fn check(
329 &self,
330 root: &Path,
331 command: &str,
332 number: u64,
333 commit: &str,
334 ) -> Result<CheckReport, String>;
335 fn merge(&self, root: &Path, url: &str, commit: &str) -> Result<(), String>;
336 fn update(&self, root: &Path, base: &str) -> Result<String, String>;
337}
338
339pub struct RealLander;
340
341impl Lander for RealLander {
342 fn view(&self, root: &Path, url: &str) -> Result<PullRequestInfo, String> {
343 view_pull_request(root, url)
344 }
345
346 fn check(
347 &self,
348 root: &Path,
349 command: &str,
350 number: u64,
351 commit: &str,
352 ) -> Result<CheckReport, String> {
353 run_land_check(root, command, number, commit)
354 }
355
356 fn merge(&self, root: &Path, url: &str, commit: &str) -> Result<(), String> {
357 merge_pull_request(root, url, commit)
358 }
359
360 fn update(&self, root: &Path, base: &str) -> Result<String, String> {
361 update_default_branch(root, base)
362 }
363}
364
365pub struct SurfaceLandTool {
366 surface: Arc<Surface>,
367 approver: Arc<dyn Approver>,
368 lander: Arc<dyn Lander>,
369}
370
371impl SurfaceLandTool {
372 pub fn new(surface: Arc<Surface>) -> Self {
373 let approver: Arc<dyn Approver> = surface.session.approver();
374 Self {
375 surface,
376 approver,
377 lander: Arc::new(RealLander),
378 }
379 }
380
381 pub fn with_lander(
382 surface: Arc<Surface>,
383 approver: Arc<dyn Approver>,
384 lander: Arc<dyn Lander>,
385 ) -> Self {
386 Self {
387 surface,
388 approver,
389 lander,
390 }
391 }
392}
393
394impl blyte_agent::tools::LandTool for SurfaceLandTool {
395 fn land(&self, request: &str) -> Result<String, String> {
396 land_request(
397 &self.surface,
398 self.approver.as_ref(),
399 self.lander.as_ref(),
400 request,
401 )
402 }
403}
404
405pub fn land_request(
406 surface: &Surface,
407 approver: &dyn Approver,
408 lander: &dyn Lander,
409 request: &str,
410) -> Result<String, String> {
411 if let Some(started_by) = blyte_agent::tools::blyte_started_by() {
412 return Err(format!(
413 "cannot land during a turn started by another surface ({started_by})"
414 ));
415 }
416
417 crate::dispatch::validate_request_id(request)?;
418 match check_request_ownership(surface, request) {
419 Ok(RequestOwnership::Owned) => {}
420 Ok(RequestOwnership::OtherSurface) => {
421 return Err(format!("request {request} belongs to another surface"));
422 }
423 Ok(RequestOwnership::Unowned) => {
424 return Err(format!("request {request} was not started by this surface"));
425 }
426 Ok(RequestOwnership::NotFound) => {
427 return Err(format!("unknown request {request}"));
428 }
429 Err(RequestOwnershipError::Mixed(msg)) | Err(RequestOwnershipError::IoOrParse(msg)) => {
430 return Err(msg);
431 }
432 }
433
434 let mut published = load_published_record(&surface.root, request)?;
435 let (Some(url), Some(pushed_commit)) = (
436 published.pull_request_url.clone(),
437 published.pushed_commit.clone(),
438 ) else {
439 return Err(format!(
440 "request {request} has no pull request: publish it first"
441 ));
442 };
443 if published.landed_head.is_some() {
444 return Err(format!("request {request} is already landed ({url})"));
445 }
446
447 let land_check = match crate::config::load_with_fallback(&surface.root)? {
448 Some((cfg, _)) => match cfg.surface.land_check {
449 Some(cmd) => cmd,
450 None => {
451 return Err(
452 "no landing check is set: add land_check to [surface] in blyte.toml, the command that must pass before a merge ({pr} is replaced by the pull request number)"
453 .to_string(),
454 );
455 }
456 },
457 None => {
458 return Err(
459 "no landing check is set: add land_check to [surface] in blyte.toml, the command that must pass before a merge ({pr} is replaced by the pull request number)"
460 .to_string(),
461 );
462 }
463 };
464
465 let _in_flight = surface
466 .requests
467 .try_begin_publish(request)
468 .ok_or_else(|| format!("request {request} is already being published or landed"))?;
469
470 let info = lander.view(&surface.root, &url)?;
471 check_landable(&info, &pushed_commit)?;
472
473 let expanded = expand_check_command(&land_check, info.number);
474 let report = lander.check(&surface.root, &land_check, info.number, &pushed_commit)?;
475 if !report.passed {
476 let code = match report.exit_code {
477 Some(c) => c.to_string(),
478 None => "signal".to_string(),
479 };
480 return Err(format!(
481 "the landing check failed (exit {code}): {expanded}\n{}",
482 report.output_tail
483 ));
484 }
485
486 let details = LandDetails {
487 request: request.to_string(),
488 pull_request_url: url.clone(),
489 number: info.number,
490 title: info.title.clone(),
491 branch: info.head_ref_name.clone(),
492 base: info.base_ref_name.clone(),
493 commit: pushed_commit.clone(),
494 check_command: expanded,
495 };
496 match approver.ask_land(&details) {
497 Approval::Approved => {}
498 Approval::Denied => {
499 return Err("the user declined".to_string());
500 }
501 Approval::Unavailable => {
502 return Err("merge approval is not available here".to_string());
503 }
504 }
505
506 lander.merge(&surface.root, &url, &pushed_commit)?;
507
508 published.landed_head = Some(pushed_commit.clone());
509 write_published_record(&surface.root, request, &published)?;
510
511 let notice = format!(
512 "Merged pull request #{} ({url}) into {} at {pushed_commit}",
513 info.number, info.base_ref_name
514 );
515 if let Err(e) = surface
516 .session
517 .record_decision(request, "land", Some(¬ice), None)
518 {
519 surface.session.record_error(&format!(
520 "failed to record land decision for {request}: {e}"
521 ));
522 }
523
524 let update_line = match lander.update(&surface.root, &info.base_ref_name) {
525 Ok(msg) => msg,
526 Err(err) => format!("could not update {}: {err}", surface.root.display()),
527 };
528
529 Ok(format!("{notice}\n{update_line}"))
530}