orch-cli 0.103.0

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
//! Screenshots on the PR. The agent lists image paths in its final JSON, orch pushes the images
//! to a branch that never merges and comments on the PR with links pinned to that commit

use std::fmt::Write as _;
use std::fs::{self, File};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process;
use std::sync::atomic::{AtomicU64, Ordering};

use anyhow::{Context, bail};

use super::git_ops;
use crate::parser::Screenshot;

/// Branch that holds the images, used as no PR base or head, and cleanup deletes task branches only
pub const SCREENSHOTS_BRANCH: &str = "orch/screenshots";

const MAX_IMAGES: usize = 12;
const MAX_IMAGE_BYTES: u64 = 10 * 1024 * 1024;
const IMAGE_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp"];
const LOCAL_REF: &str = "refs/orch/screenshots";
const PUSH_ATTEMPTS: u32 = 5;
static INDEX_SEQ: AtomicU64 = AtomicU64::new(0);

/// An image checked and placed at its path on the screenshots branch
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Prepared {
    pub source: PathBuf,
    pub branch_path: String,
    pub caption: String,
}

/// Keep the file name safe for a URL and a git tree
fn safe_name(name: &str) -> String {
    let cleaned: String = name
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_' {
                c
            } else {
                '-'
            }
        })
        .collect();
    cleaned.trim_start_matches('.').to_string()
}

/// Check each listed image, and skip a bad entry with a reason so it does not drop the others
pub fn prepare(
    shots: &[Screenshot],
    base: &Path,
    roots: &[PathBuf],
    pr_number: u64,
) -> (Vec<Prepared>, Vec<String>) {
    let mut prepared = Vec::new();
    let mut skipped = Vec::new();

    for shot in shots {
        if prepared.len() >= MAX_IMAGES {
            skipped.push(format!("{}: more than {MAX_IMAGES} screenshots", shot.path));
            continue;
        }
        match check_image(&shot.path, base, roots) {
            Ok(source) => {
                let name = source
                    .file_name()
                    .map(|n| safe_name(&n.to_string_lossy()))
                    .unwrap_or_default();
                prepared.push(Prepared {
                    branch_path: format!("pr-{pr_number}/{}-{name}", prepared.len() + 1),
                    source,
                    caption: shot.caption.clone(),
                });
            }
            Err(e) => skipped.push(format!("{}: {e}", shot.path)),
        }
    }
    (prepared, skipped)
}

fn check_image(path: &str, base: &Path, roots: &[PathBuf]) -> anyhow::Result<PathBuf> {
    let joined = base.join(path.trim());
    let source = fs::canonicalize(&joined).context("file not found")?;
    if !roots.iter().any(|root| source.starts_with(root)) {
        bail!("outside the worktree");
    }
    let is_image = source
        .extension()
        .and_then(|e| e.to_str())
        .is_some_and(|e| IMAGE_EXTENSIONS.contains(&e.to_ascii_lowercase().as_str()));
    if !is_image {
        bail!("not an image file");
    }
    let meta = fs::metadata(&source).context("unreadable")?;
    if !meta.is_file() || meta.len() == 0 || meta.len() > MAX_IMAGE_BYTES {
        bail!("empty or larger than {} MB", MAX_IMAGE_BYTES / 1024 / 1024);
    }
    let mut head = [0u8; 12];
    let read = File::open(&source)
        .and_then(|mut f| f.read(&mut head))
        .context("unreadable")?;
    if !has_image_header(&head[..read]) {
        bail!("not an image file");
    }
    Ok(source)
}

fn has_image_header(head: &[u8]) -> bool {
    head.starts_with(b"\x89PNG\r\n\x1a\n")
        || head.starts_with(&[0xFF, 0xD8, 0xFF])
        || head.starts_with(b"GIF8")
        || (head.starts_with(b"RIFF") && head.get(8..12) == Some(b"WEBP"))
}

fn one_line(text: &str) -> String {
    text.split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
        .replace(['[', ']'], "")
}

/// The PR comment, with links pinned to `commit` so they render in a private repository
pub fn build_comment(
    repo: &str,
    commit: &str,
    images: &[Prepared],
    note: Option<&str>,
    skipped: &[String],
) -> String {
    let mut body = String::from("## Screenshots\n");
    for (i, image) in images.iter().enumerate() {
        let caption = one_line(&image.caption);
        let alt = if caption.is_empty() {
            format!("Screenshot {}", i + 1)
        } else {
            caption.clone()
        };
        let url = format!(
            "https://github.com/{repo}/blob/{commit}/{}?raw=true",
            image.branch_path
        );
        body.push('\n');
        if !caption.is_empty() {
            let _ = writeln!(body, "**{caption}**\n");
        }
        let _ = writeln!(body, "![{alt}]({url})");
    }
    if !skipped.is_empty() {
        body.push_str("\nSkipped:\n");
        for reason in skipped {
            let _ = writeln!(body, "- {}", one_line(reason));
        }
    }
    if let Some(note) = note.map(str::trim).filter(|n| !n.is_empty()) {
        let _ = write!(body, "\n> {}\n", one_line(note));
    }
    body
}

/// PR comment when the images never landed on the screenshots branch
pub fn build_unpublished_comment(note: Option<&str>, skipped: &[String]) -> String {
    let mut body = String::from("## Screenshots\n\nThe screenshots could not be published.\n");
    if !skipped.is_empty() {
        body.push_str("\nSkipped:\n");
        for reason in skipped {
            let _ = writeln!(body, "- {}", one_line(reason));
        }
    }
    if let Some(note) = note.map(str::trim).filter(|n| !n.is_empty()) {
        let _ = write!(body, "\n> {}\n", one_line(note));
    }
    body
}

async fn git_out(dir: &Path, index: Option<&Path>, args: &[&str]) -> anyhow::Result<String> {
    let mut cmd = git_ops::git().await;
    cmd.arg("-C").arg(dir).args(args);
    if let Some(index) = index {
        cmd.env("GIT_INDEX_FILE", index);
    }
    cmd.env("GIT_AUTHOR_NAME", "orch")
        .env("GIT_AUTHOR_EMAIL", "orch@localhost")
        .env("GIT_COMMITTER_NAME", "orch")
        .env("GIT_COMMITTER_EMAIL", "orch@localhost");
    let out = git_ops::sanitize_git_output(cmd.output_with_context().await?);
    if !out.status.success() {
        bail!(
            "git {} failed: {}",
            args.first().copied().unwrap_or(""),
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

/// Roots an image may live in: the worktree and its git dir, which stays out of the PR commit
pub async fn allowed_roots(worktree: &Path) -> Vec<PathBuf> {
    let mut roots = Vec::new();
    if let Ok(root) = fs::canonicalize(worktree) {
        roots.push(root);
    }
    if let Ok(dir) = git_out(worktree, None, &["rev-parse", "--absolute-git-dir"]).await
        && let Ok(dir) = fs::canonicalize(dir)
    {
        roots.push(dir);
    }
    roots
}

/// Push the images on top of the screenshots branch, with a throwaway index so the worktree stays
/// untouched, and return the commit the links point at
pub async fn publish(
    worktree: &Path,
    images: &[Prepared],
    pr_number: u64,
) -> anyhow::Result<String> {
    if images.is_empty() {
        bail!("no images to publish");
    }
    let git_dir = git_out(worktree, None, &["rev-parse", "--absolute-git-dir"]).await?;
    let index = PathBuf::from(git_dir).join(format!(
        "orch-screenshots-index-{}-{}-{pr_number}",
        process::id(),
        INDEX_SEQ.fetch_add(1, Ordering::Relaxed)
    ));
    let result = push_images(worktree, &index, images, pr_number).await;
    let _ = fs::remove_file(&index);
    result
}

async fn push_images(
    worktree: &Path,
    index: &Path,
    images: &[Prepared],
    pr_number: u64,
) -> anyhow::Result<String> {
    let mut blobs = Vec::with_capacity(images.len());
    for image in images {
        let source = image.source.to_string_lossy();
        let blob = git_out(worktree, None, &["hash-object", "-w", "--", &source]).await?;
        blobs.push((blob, image.branch_path.clone()));
    }

    let mut last_nff = None;
    for attempt in 1..=PUSH_ATTEMPTS {
        match push_once(worktree, index, &blobs, pr_number).await {
            Ok(commit) => return Ok(commit),
            Err(e) if push_lost_the_remote_tip(&e) => {
                tracing::warn!(
                    attempt,
                    err = %e,
                    "screenshot push was not a fast-forward, fetching again"
                );
                last_nff = Some(e);
            }
            Err(e) => return Err(e),
        }
    }
    Err(last_nff.unwrap_or_else(|| anyhow::anyhow!("screenshot push failed")))
}

async fn fetch_parent(worktree: &Path) -> anyhow::Result<Option<String>> {
    let fetch_spec = format!("+refs/heads/{SCREENSHOTS_BRANCH}:{LOCAL_REF}");
    match git_out(worktree, None, &["fetch", "origin", &fetch_spec]).await {
        Ok(_) => Ok(Some(
            git_out(worktree, None, &["rev-parse", "--verify", LOCAL_REF])
                .await
                .context("screenshots branch ref missing after a successful fetch")?,
        )),
        Err(e) if git_ops::is_missing_remote_ref_error(&e) => Ok(None),
        // A fetch error other than a missing branch must not become a root commit
        Err(e) => Err(e),
    }
}

fn push_lost_the_remote_tip(err: &anyhow::Error) -> bool {
    let s = err.to_string();
    let lower = s.to_ascii_lowercase();
    lower.contains("non-fast-forward")
        || s.contains("! [rejected]")
        || lower.contains("fetch first")
        || lower.contains("reference already exists")
        || lower.contains("cannot lock ref")
}

async fn push_once(
    worktree: &Path,
    index: &Path,
    blobs: &[(String, String)],
    pr_number: u64,
) -> anyhow::Result<String> {
    let parent = fetch_parent(worktree).await?;
    if let Some(parent) = &parent {
        git_out(worktree, Some(index), &["read-tree", parent]).await?;
    } else {
        git_out(worktree, Some(index), &["read-tree", "--empty"]).await?;
    }
    for (blob, path) in blobs {
        let entry = format!("100644,{blob},{path}");
        git_out(
            worktree,
            Some(index),
            &["update-index", "--add", "--cacheinfo", &entry],
        )
        .await?;
    }
    let tree = git_out(worktree, Some(index), &["write-tree"]).await?;
    let message = format!("Screenshots for PR #{pr_number}");
    let mut args = vec!["commit-tree", tree.as_str(), "-m", message.as_str()];
    if let Some(parent) = &parent {
        args.extend(["-p", parent.as_str()]);
    }
    let commit = git_out(worktree, None, &args).await?;
    let refspec = format!("{commit}:refs/heads/{SCREENSHOTS_BRANCH}");
    git_out(worktree, None, &["push", "origin", &refspec]).await?;
    Ok(commit)
}

#[cfg(test)]
mod tests {
    use std::process::Command as StdCommand;
    use std::slice;

    use super::git_ops;
    use super::*;

    const PNG_HEADER: &[u8] = b"\x89PNG\r\n\x1a\n";

    fn shot(path: &str, caption: &str) -> Screenshot {
        Screenshot {
            path: path.into(),
            caption: caption.into(),
        }
    }

    fn git_run(dir: &Path, args: &[&str]) -> String {
        let out = StdCommand::new("git")
            .arg("-C")
            .arg(dir)
            .args(args)
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .output()
            .unwrap();
        assert!(out.status.success(), "git {args:?}: {out:?}");
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    }

    #[test]
    fn git_error_strips_url_credentials() {
        let raw = "error: failed to push some refs to 'https://x-access-token:test-secret-1234567890abcdef@github.com/o/r.git'";
        let msg = format!("git push failed: {}", git_ops::sanitize_push_error(raw));
        assert!(!msg.contains("test-secret-1234567890abcdef"));
        assert!(msg.contains("://***@github.com"));
    }

    #[test]
    fn comment_links_images_to_the_commit() {
        let images = vec![
            Prepared {
                source: PathBuf::from("/x/home.png"),
                branch_path: "pr-7/1-home.png".into(),
                caption: "Home, desktop".into(),
            },
            Prepared {
                source: PathBuf::from("/x/phone.png"),
                branch_path: "pr-7/2-phone.png".into(),
                caption: String::new(),
            },
        ];
        let body = build_comment(
            "owner/repo",
            "abc123",
            &images,
            Some("ui-screenshot skill missing"),
            &[],
        );
        assert!(body.starts_with("## Screenshots"));
        assert!(body.contains("**Home, desktop**"));
        assert!(body.contains(
            "![Home, desktop](https://github.com/owner/repo/blob/abc123/pr-7/1-home.png?raw=true)"
        ));
        assert!(body.contains(
            "![Screenshot 2](https://github.com/owner/repo/blob/abc123/pr-7/2-phone.png?raw=true)"
        ));
        assert!(body.contains("> ui-screenshot skill missing"));
    }

    #[test]
    fn note_comment_has_no_images() {
        let body = build_comment(
            "owner/repo",
            "",
            &[],
            Some("no browser, the screenshot could not be taken"),
            &[],
        );
        assert!(!body.contains("!["));
        assert!(body.contains("> no browser"));
    }

    #[test]
    fn unpublished_comment_says_the_images_never_landed() {
        let body = build_unpublished_comment(
            Some("ui-screenshot skill missing"),
            &["shot.png: empty or larger than 10 MB".into()],
        );
        assert!(body.starts_with("## Screenshots"));
        assert!(body.contains("The screenshots could not be published."));
        assert!(!body.contains("!["));
        assert!(body.contains("Skipped:"));
        assert!(body.contains("shot.png: empty or larger than 10 MB"));
        assert!(body.contains("> ui-screenshot skill missing"));
    }

    #[test]
    fn push_lost_the_remote_tip_detects_a_diverged_or_raced_create() {
        let nff = anyhow::anyhow!("git push failed: ! [rejected] a -> a (non-fast-forward)");
        assert!(push_lost_the_remote_tip(&nff));
        assert!(push_lost_the_remote_tip(&anyhow::anyhow!(
            "git push failed: ! [rejected] a -> a (fetch first)"
        )));
        assert!(push_lost_the_remote_tip(&anyhow::anyhow!(
            "git push failed: remote: error: cannot lock ref 'refs/heads/orch/screenshots': reference already exists\n ! [remote rejected] a -> orch/screenshots (reference already exists)"
        )));
        assert!(!push_lost_the_remote_tip(&anyhow::anyhow!(
            "git push failed: remote: fatal error in commit_refs\n ! [remote rejected] a -> a (pre-receive hook declined)"
        )));
    }

    #[test]
    fn prepare_keeps_images_inside_the_roots_only() {
        let tmp = tempfile::tempdir().unwrap();
        let root = fs::canonicalize(tmp.path()).unwrap();
        fs::write(root.join("a b.png"), PNG_HEADER).unwrap();
        fs::write(root.join("notes.txt"), b"text").unwrap();
        fs::write(root.join("fake.png"), b"not an image at all").unwrap();
        let outside = tempfile::tempdir().unwrap();
        fs::write(outside.path().join("secret.png"), PNG_HEADER).unwrap();

        let shots = vec![
            shot("a b.png", "A"),
            shot("notes.txt", "B"),
            shot("fake.png", "F"),
            shot("missing.png", "C"),
            shot(&outside.path().join("secret.png").to_string_lossy(), "D"),
            shot("../secret.png", "E"),
        ];
        let (prepared, skipped) = prepare(&shots, &root, slice::from_ref(&root), 9);

        assert_eq!(prepared.len(), 1);
        assert_eq!(prepared[0].branch_path, "pr-9/1-a-b.png");
        assert_eq!(skipped.len(), 5);
    }

    #[tokio::test]
    async fn publish_pushes_a_branch_the_worktree_never_sees() {
        let tmp = tempfile::tempdir().unwrap();
        let origin = tmp.path().join("origin.git");
        let clone = tmp.path().join("clone");
        git_run(tmp.path(), &["init", "--bare", "-q", "origin.git"]);
        git_run(tmp.path(), &["init", "-q", "-b", "main", "clone"]);
        git_run(&clone, &["config", "user.email", "t@t"]);
        git_run(&clone, &["config", "user.name", "t"]);
        git_run(
            &clone,
            &["remote", "add", "origin", &origin.to_string_lossy()],
        );
        fs::write(clone.join("f"), "x").unwrap();
        git_run(&clone, &["add", "f"]);
        git_run(&clone, &["commit", "-qm", "init"]);
        let head_before = git_run(&clone, &["rev-parse", "HEAD"]);

        let shot_path = clone.join("home.png");
        fs::write(&shot_path, PNG_HEADER).unwrap();
        let roots = vec![fs::canonicalize(&clone).unwrap()];
        let (images, _) = prepare(&[shot("home.png", "Home")], &clone, &roots, 3);
        let first = publish(&clone, &images, 3).await.unwrap();

        fs::write(&shot_path, b"\x89PNG\r\n\x1a\nsecond").unwrap();
        let (images, _) = prepare(&[shot("home.png", "Home")], &clone, &roots, 4);
        let second = publish(&clone, &images, 4).await.unwrap();

        assert_ne!(first, second);
        let tip = format!("refs/heads/{SCREENSHOTS_BRANCH}");
        assert_eq!(git_run(&origin, &["rev-parse", &tip]), second);
        assert_eq!(
            git_run(&origin, &["rev-parse", &format!("{second}^")]),
            first
        );
        let files = git_run(&origin, &["ls-tree", "-r", "--name-only", &second]);
        assert!(files.contains("pr-3/1-home.png"), "{files}");
        assert!(files.contains("pr-4/1-home.png"), "{files}");
        assert_eq!(git_run(&clone, &["rev-parse", "HEAD"]), head_before);
        assert_eq!(
            git_run(&clone, &["branch", "--list", SCREENSHOTS_BRANCH]),
            ""
        );
    }

    fn init_origin_and_clone(tmp: &Path) -> (PathBuf, PathBuf) {
        let origin = tmp.join("origin.git");
        let clone = tmp.join("clone");
        git_run(tmp, &["init", "--bare", "-q", "origin.git"]);
        git_run(tmp, &["init", "-q", "-b", "main", "clone"]);
        git_run(&clone, &["config", "user.email", "t@t"]);
        git_run(&clone, &["config", "user.name", "t"]);
        git_run(
            &clone,
            &["remote", "add", "origin", &origin.to_string_lossy()],
        );
        fs::write(clone.join("f"), "x").unwrap();
        git_run(&clone, &["add", "f"]);
        git_run(&clone, &["commit", "-qm", "init"]);
        (origin, clone)
    }

    fn write_hook(origin: &Path, body: &str) {
        let hook = origin.join("hooks/pre-receive");
        fs::write(&hook, body).unwrap();
        let status = StdCommand::new("chmod")
            .arg("+x")
            .arg(&hook)
            .status()
            .unwrap();
        assert!(status.success(), "chmod +x {hook:?}");
    }

    fn screenshots_tip(origin: &Path) -> String {
        git_run(
            origin,
            &["rev-parse", &format!("refs/heads/{SCREENSHOTS_BRANCH}")],
        )
    }

    fn screenshots_files(origin: &Path, commit: &str) -> String {
        git_run(origin, &["ls-tree", "-r", "--name-only", commit])
    }

    fn screenshots_branch_exists(origin: &Path) -> bool {
        StdCommand::new("git")
            .arg("-C")
            .arg(origin)
            .args([
                "show-ref",
                "--verify",
                "--quiet",
                &format!("refs/heads/{SCREENSHOTS_BRANCH}"),
            ])
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .status()
            .unwrap()
            .success()
    }

    #[tokio::test]
    async fn publish_retries_when_two_worktrees_push_together() {
        let tmp = tempfile::tempdir().unwrap();
        let (origin, clone) = init_origin_and_clone(tmp.path());
        let other = tmp.path().join("other");
        git_run(
            &clone,
            &["worktree", "add", "-q", &other.to_string_lossy(), "HEAD"],
        );
        write_hook(&origin, "#!/bin/sh\nsleep 0.2\n");

        fs::write(clone.join("a.png"), PNG_HEADER).unwrap();
        fs::write(other.join("b.png"), PNG_HEADER).unwrap();
        let roots_a = allowed_roots(&clone).await;
        let roots_b = allowed_roots(&other).await;
        let (images_a, _) = prepare(&[shot("a.png", "A")], &clone, &roots_a, 3);
        let (images_b, _) = prepare(&[shot("b.png", "B")], &other, &roots_b, 4);

        let (first, second) =
            tokio::join!(publish(&clone, &images_a, 3), publish(&other, &images_b, 4),);
        let first = first.expect("first worktree publish");
        let second = second.expect("second worktree publish");
        assert_ne!(first, second);

        let tip = screenshots_tip(&origin);
        let files = screenshots_files(&origin, &tip);
        assert!(files.contains("pr-3/1-a.png"), "{files}");
        assert!(files.contains("pr-4/1-b.png"), "{files}");
        let log = git_run(
            &origin,
            &[
                "log",
                "--format=%H",
                &format!("refs/heads/{SCREENSHOTS_BRANCH}"),
            ],
        );
        assert!(log.contains(&first), "{log}");
        assert!(log.contains(&second), "{log}");
    }

    #[tokio::test]
    async fn publish_skips_a_root_commit_when_fetch_fails() {
        let tmp = tempfile::tempdir().unwrap();
        let (origin, clone) = init_origin_and_clone(tmp.path());
        let missing = tmp.path().join("missing.git");
        git_run(
            &clone,
            &["remote", "set-url", "origin", &missing.to_string_lossy()],
        );
        git_run(
            &clone,
            &[
                "remote",
                "set-url",
                "--push",
                "origin",
                &origin.to_string_lossy(),
            ],
        );

        fs::write(clone.join("home.png"), PNG_HEADER).unwrap();
        let roots = vec![fs::canonicalize(&clone).unwrap()];
        let (images, _) = prepare(&[shot("home.png", "Home")], &clone, &roots, 3);
        let err = publish(&clone, &images, 3).await.unwrap_err();
        assert!(
            !git_ops::is_missing_remote_ref_error(&err),
            "fetch failed for a reason other than a missing branch: {err}"
        );
        assert!(
            !screenshots_branch_exists(&origin),
            "a root commit must not be pushed when fetch failed"
        );
    }

    #[tokio::test]
    async fn publish_stops_after_non_fast_forward_retries() {
        let tmp = tempfile::tempdir().unwrap();
        let (origin, clone) = init_origin_and_clone(tmp.path());
        write_hook(
            &origin,
            "#!/bin/sh\necho 'error: non-fast-forward' >&2\nexit 1\n",
        );

        fs::write(clone.join("home.png"), PNG_HEADER).unwrap();
        let roots = vec![fs::canonicalize(&clone).unwrap()];
        let (images, _) = prepare(&[shot("home.png", "Home")], &clone, &roots, 3);
        let err = publish(&clone, &images, 3).await.unwrap_err();
        assert!(
            err.to_string()
                .to_ascii_lowercase()
                .contains("non-fast-forward"),
            "{err}"
        );
        assert!(!screenshots_branch_exists(&origin));
    }
}