blyte 0.89.0

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
use std::ffi::OsStr;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::Arc;

use blyte_agent::approval::{Approval, Approver, LandDetails};

use crate::publish::{output_detail, run_gh, run_git};
use crate::requests::{
    check_request_ownership, load_published_record, write_published_record, RequestOwnership,
    RequestOwnershipError,
};
use crate::serve::Surface;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PullRequestInfo {
    pub number: u64,
    pub state: String,
    pub is_draft: bool,
    pub title: String,
    pub head_ref_name: String,
    pub head_ref_oid: String,
    pub base_ref_name: String,
    pub mergeable: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CheckReport {
    pub passed: bool,
    pub exit_code: Option<i32>,
    pub output_tail: String,
    pub output_log: PathBuf,
}

pub const CHECK_OUTPUT_TAIL_BYTES: usize = 4000;

const PR_VIEW_JSON_FIELDS: &str =
    "number,state,isDraft,title,headRefName,headRefOid,baseRefName,mergeable";

pub fn view_pull_request(root: &Path, url: &str) -> Result<PullRequestInfo, String> {
    view_pull_request_with_gh(root, "gh", url)
}

pub fn view_pull_request_with_gh(
    root: &Path,
    gh: &str,
    url: &str,
) -> Result<PullRequestInfo, String> {
    let out = run_gh(
        root,
        OsStr::new(gh),
        &["pr", "view", url, "--json", PR_VIEW_JSON_FIELDS],
        "gh pr view",
    )?;

    let value: serde_json::Value = serde_json::from_slice(&out.stdout)
        .map_err(|e| format!("gh pr view returned invalid JSON: {e}"))?;
    let obj = value
        .as_object()
        .ok_or_else(|| "gh pr view did not return a JSON object".to_string())?;

    Ok(PullRequestInfo {
        number: required_u64(obj, "number")?,
        state: required_string(obj, "state")?,
        is_draft: required_bool(obj, "isDraft")?,
        title: required_string(obj, "title")?,
        head_ref_name: required_string(obj, "headRefName")?,
        head_ref_oid: required_string(obj, "headRefOid")?,
        base_ref_name: required_string(obj, "baseRefName")?,
        mergeable: required_string(obj, "mergeable")?,
    })
}

fn required_u64(
    obj: &serde_json::Map<String, serde_json::Value>,
    field: &str,
) -> Result<u64, String> {
    match obj.get(field) {
        None | Some(serde_json::Value::Null) => Err(format!("gh pr view returned no {field}")),
        Some(v) => v
            .as_u64()
            .ok_or_else(|| format!("gh pr view returned invalid {field}")),
    }
}

fn required_bool(
    obj: &serde_json::Map<String, serde_json::Value>,
    field: &str,
) -> Result<bool, String> {
    match obj.get(field) {
        None | Some(serde_json::Value::Null) => Err(format!("gh pr view returned no {field}")),
        Some(v) => v
            .as_bool()
            .ok_or_else(|| format!("gh pr view returned invalid {field}")),
    }
}

fn required_string(
    obj: &serde_json::Map<String, serde_json::Value>,
    field: &str,
) -> Result<String, String> {
    match obj.get(field) {
        None | Some(serde_json::Value::Null) => Err(format!("gh pr view returned no {field}")),
        Some(v) => v
            .as_str()
            .map(String::from)
            .ok_or_else(|| format!("gh pr view returned invalid {field}")),
    }
}

pub fn check_landable(info: &PullRequestInfo, published_commit: &str) -> Result<(), String> {
    if info.state != "OPEN" {
        return Err(format!(
            "pull request #{} is not open (state: {})",
            info.number, info.state
        ));
    }
    if info.is_draft {
        return Err(format!("pull request #{} is a draft", info.number));
    }
    if info.mergeable == "CONFLICTING" {
        return Err(format!(
            "pull request #{} conflicts with {}",
            info.number, info.base_ref_name
        ));
    }
    if info.head_ref_oid != published_commit {
        return Err(format!(
            "pull request #{} head {} is not the published commit {published_commit}",
            info.number, info.head_ref_oid
        ));
    }
    Ok(())
}

fn land_worktree_rel_path(number: u64) -> PathBuf {
    Path::new(".wt").join(format!("land-{number}"))
}

pub fn land_worktree_path(root: &Path, number: u64) -> PathBuf {
    root.join(land_worktree_rel_path(number))
}

pub fn land_check_log_path(root: &Path, number: u64) -> PathBuf {
    root.join(".wt").join(format!("land-{number}.check.log"))
}

pub fn expand_check_command(command: &str, number: u64) -> String {
    command.replace("{pr}", &number.to_string())
}

pub fn run_land_check(
    root: &Path,
    command: &str,
    number: u64,
    commit: &str,
) -> Result<CheckReport, String> {
    let wt_rel = land_worktree_rel_path(number);
    let wt_path = root.join(&wt_rel);
    if wt_path.exists() || wt_path.symlink_metadata().is_ok() {
        let display = wt_path.display();
        return Err(format!(
            "{display} already exists: another landing check is running, or one was interrupted; remove it with git worktree remove --force {display}"
        ));
    }

    let add_out = Command::new("git")
        .args(["worktree", "add", "--detach"])
        .arg(&wt_rel)
        .arg(commit)
        .current_dir(root)
        .env("GIT_TERMINAL_PROMPT", "0")
        .output()
        .map_err(|e| format!("failed to run git worktree add: {e}"))?;
    if !add_out.status.success() {
        let detail = output_detail(&add_out);
        return Err(format!("git worktree add failed: {detail}"));
    }

    let expanded = expand_check_command(command, number);
    let output_log = land_check_log_path(root, number);
    let check_res = execute_check(&wt_path, &expanded, output_log);
    let remove_res = remove_land_worktree(root, &wt_rel, &wt_path);
    match (check_res, remove_res) {
        (Ok(report), Ok(())) => Ok(report),
        (Ok(_), Err(remove_err)) => Err(remove_err),
        (Err(check_err), Ok(())) => Err(check_err),
        (Err(check_err), Err(remove_err)) => Err(format!("{check_err}; {remove_err}")),
    }
}

fn execute_check(
    wt_path: &Path,
    expanded: &str,
    output_log: PathBuf,
) -> Result<CheckReport, String> {
    let (mut reader, writer) =
        std::io::pipe().map_err(|e| format!("could not run the land check: {e}"))?;
    let writer_err = writer
        .try_clone()
        .map_err(|e| format!("could not run the land check: {e}"))?;

    let mut command = Command::new("sh");
    command
        .args(["-c", expanded])
        .current_dir(wt_path)
        .stdin(Stdio::null())
        .stdout(Stdio::from(writer))
        .stderr(Stdio::from(writer_err));
    blyte_agent::shell::scrub_harness(&mut command);
    let mut child = command
        .spawn()
        .map_err(|e| format!("could not run the land check: {e}"))?;
    drop(command);

    let mut output_bytes = Vec::new();
    let read_res = reader.read_to_end(&mut output_bytes);
    let status = child
        .wait()
        .map_err(|e| format!("could not run the land check: {e}"))?;
    read_res.map_err(|e| format!("could not run the land check: {e}"))?;

    if let Some(parent) = output_log.parent() {
        std::fs::create_dir_all(parent).map_err(|e| {
            format!(
                "could not write the land check output to {}: {e}",
                output_log.display()
            )
        })?;
    }
    std::fs::write(&output_log, &output_bytes).map_err(|e| {
        format!(
            "could not write the land check output to {}: {e}",
            output_log.display()
        )
    })?;

    let exit_code = status.code();
    let passed = exit_code == Some(0);
    let output_tail = tail_utf8(&output_bytes, CHECK_OUTPUT_TAIL_BYTES);
    Ok(CheckReport {
        passed,
        exit_code,
        output_tail,
        output_log,
    })
}

fn remove_land_worktree(root: &Path, wt_rel: &Path, wt_path: &Path) -> Result<(), String> {
    let out = Command::new("git")
        .args(["worktree", "remove", "--force"])
        .arg(wt_rel)
        .current_dir(root)
        .env("GIT_TERMINAL_PROMPT", "0")
        .output()
        .map_err(|e| format!("failed to remove worktree {}: {e}", wt_path.display()))?;
    if !out.status.success() {
        let detail = output_detail(&out);
        return Err(format!(
            "failed to remove worktree {}: {detail}",
            wt_path.display()
        ));
    }
    Ok(())
}

fn tail_utf8(bytes: &[u8], max_bytes: usize) -> String {
    let text = String::from_utf8_lossy(bytes);
    if text.len() <= max_bytes {
        return text.into_owned();
    }
    let mut start = text.len() - max_bytes;
    while !text.is_char_boundary(start) {
        start += 1;
    }
    text[start..].to_string()
}

pub fn merge_pull_request(root: &Path, url: &str, commit: &str) -> Result<(), String> {
    merge_pull_request_with_gh(root, "gh", url, commit)
}

pub fn merge_pull_request_with_gh(
    root: &Path,
    gh: &str,
    url: &str,
    commit: &str,
) -> Result<(), String> {
    run_gh(
        root,
        OsStr::new(gh),
        &[
            "pr",
            "merge",
            url,
            "--squash",
            "--match-head-commit",
            commit,
        ],
        "gh pr merge",
    )?;
    Ok(())
}

pub fn update_default_branch(root: &Path, base: &str) -> Result<String, String> {
    let fetch = run_git(root, &["fetch", "--quiet", "origin", base])?;
    if !fetch.status.success() {
        let detail = output_detail(&fetch);
        return Err(format!("git fetch origin {base} failed: {detail}"));
    }

    let head = run_git(root, &["rev-parse", "--abbrev-ref", "HEAD"])?;
    if !head.status.success() {
        let detail = output_detail(&head);
        return Err(format!(
            "could not read current branch in {}: {detail}",
            root.display()
        ));
    }
    let branch = String::from_utf8_lossy(&head.stdout).trim().to_string();
    if branch != base {
        return Ok(format!(
            "fetched origin/{base}; {} is on {branch}, left as it was",
            root.display()
        ));
    }

    let status = run_git(root, &["status", "--porcelain"])?;
    if !status.status.success() {
        let detail = output_detail(&status);
        return Err(format!(
            "could not read git status in {}: {detail}",
            root.display()
        ));
    }
    if !String::from_utf8_lossy(&status.stdout).trim().is_empty() {
        return Ok(format!(
            "fetched origin/{base}; {} has uncommitted changes, left as it was",
            root.display()
        ));
    }

    let remote_ref = format!("origin/{base}");
    let merge = run_git(root, &["merge", "--ff-only", &remote_ref])?;
    if !merge.status.success() {
        let detail = output_detail(&merge);
        return Err(format!("git merge --ff-only {remote_ref} failed: {detail}"));
    }
    Ok(format!(
        "fetched origin/{base} and fast-forwarded {base} in {}",
        root.display()
    ))
}

pub trait Lander: Send + Sync {
    fn view(&self, root: &Path, url: &str) -> Result<PullRequestInfo, String>;
    fn check(
        &self,
        root: &Path,
        command: &str,
        number: u64,
        commit: &str,
    ) -> Result<CheckReport, String>;
    fn merge(&self, root: &Path, url: &str, commit: &str) -> Result<(), String>;
    fn update(&self, root: &Path, base: &str) -> Result<String, String>;
}

pub struct RealLander;

impl Lander for RealLander {
    fn view(&self, root: &Path, url: &str) -> Result<PullRequestInfo, String> {
        view_pull_request(root, url)
    }

    fn check(
        &self,
        root: &Path,
        command: &str,
        number: u64,
        commit: &str,
    ) -> Result<CheckReport, String> {
        run_land_check(root, command, number, commit)
    }

    fn merge(&self, root: &Path, url: &str, commit: &str) -> Result<(), String> {
        merge_pull_request(root, url, commit)
    }

    fn update(&self, root: &Path, base: &str) -> Result<String, String> {
        update_default_branch(root, base)
    }
}

pub struct SurfaceLandTool {
    surface: Arc<Surface>,
    approver: Arc<dyn Approver>,
    lander: Arc<dyn Lander>,
}

impl SurfaceLandTool {
    pub fn new(surface: Arc<Surface>) -> Self {
        let approver: Arc<dyn Approver> = surface.session.approver();
        Self {
            surface,
            approver,
            lander: Arc::new(RealLander),
        }
    }

    pub fn with_lander(
        surface: Arc<Surface>,
        approver: Arc<dyn Approver>,
        lander: Arc<dyn Lander>,
    ) -> Self {
        Self {
            surface,
            approver,
            lander,
        }
    }
}

impl blyte_agent::tools::LandTool for SurfaceLandTool {
    fn land(&self, request: &str) -> Result<String, String> {
        land_request(
            &self.surface,
            self.approver.as_ref(),
            self.lander.as_ref(),
            request,
        )
    }
}

pub fn land_request(
    surface: &Surface,
    approver: &dyn Approver,
    lander: &dyn Lander,
    request: &str,
) -> Result<String, String> {
    if let Some(started_by) = blyte_agent::tools::blyte_started_by() {
        return Err(format!(
            "cannot land during a turn started by another surface ({started_by})"
        ));
    }

    crate::dispatch::validate_request_id(request)?;
    match check_request_ownership(surface, request) {
        Ok(RequestOwnership::Owned) => {}
        Ok(RequestOwnership::OtherSurface) => {
            return Err(format!("request {request} belongs to another surface"));
        }
        Ok(RequestOwnership::Unowned) => {
            return Err(format!("request {request} was not started by this surface"));
        }
        Ok(RequestOwnership::NotFound) => {
            return Err(format!("unknown request {request}"));
        }
        Err(RequestOwnershipError::Mixed(msg)) | Err(RequestOwnershipError::IoOrParse(msg)) => {
            return Err(msg);
        }
    }

    let mut published = load_published_record(&surface.root, request)?;
    let (Some(url), Some(pushed_commit)) = (
        published.pull_request_url.clone(),
        published.pushed_commit.clone(),
    ) else {
        return Err(format!(
            "request {request} has no pull request: publish it first"
        ));
    };
    if published.landed_head.is_some() {
        return Err(format!("request {request} is already landed ({url})"));
    }

    let land_check = match crate::config::load_with_fallback(&surface.root)? {
        Some((cfg, _)) => match cfg.surface.land_check {
            Some(cmd) => cmd,
            None => {
                return Err(
                    "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)"
                        .to_string(),
                );
            }
        },
        None => {
            return Err(
                "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)"
                    .to_string(),
            );
        }
    };

    let _in_flight = surface
        .requests
        .try_begin_publish(request)
        .ok_or_else(|| format!("request {request} is already being published or landed"))?;

    let info = lander.view(&surface.root, &url)?;
    check_landable(&info, &pushed_commit)?;

    let expanded = expand_check_command(&land_check, info.number);
    let report = lander.check(&surface.root, &land_check, info.number, &pushed_commit)?;
    if !report.passed {
        let code = match report.exit_code {
            Some(c) => c.to_string(),
            None => "signal".to_string(),
        };
        return Err(format!(
            "the landing check failed (exit {code}): {expanded}\nfull output: {}\n{}",
            report.output_log.display(),
            report.output_tail
        ));
    }

    let details = LandDetails {
        request: request.to_string(),
        pull_request_url: url.clone(),
        number: info.number,
        title: info.title.clone(),
        branch: info.head_ref_name.clone(),
        base: info.base_ref_name.clone(),
        commit: pushed_commit.clone(),
        check_command: expanded,
    };
    match approver.ask_land(&details) {
        Approval::Approved => {}
        Approval::Denied => {
            return Err("the user declined".to_string());
        }
        Approval::Unavailable => {
            return Err("merge approval is not available here".to_string());
        }
    }

    lander.merge(&surface.root, &url, &pushed_commit)?;

    published.landed_head = Some(pushed_commit.clone());
    write_published_record(&surface.root, request, &published)?;

    let notice = format!(
        "Merged pull request #{} ({url}) into {} at {pushed_commit}",
        info.number, info.base_ref_name
    );
    if let Err(e) = surface
        .session
        .record_decision(request, "land", Some(&notice), None)
    {
        surface.session.record_error(&format!(
            "failed to record land decision for {request}: {e}"
        ));
    }

    let update_line = match lander.update(&surface.root, &info.base_ref_name) {
        Ok(msg) => msg,
        Err(err) => format!("could not update {}: {err}", surface.root.display()),
    };

    Ok(format!("{notice}\n{update_line}"))
}