agengo 0.5.1

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
use anyhow::{anyhow, bail, Context, Result};
use std::{
    collections::BTreeSet,
    ffi::OsStr,
    fs,
    io::{self, Read, Write},
    path::{Path, PathBuf},
    process::{Command, Output, Stdio},
    sync::{
        atomic::{AtomicBool, Ordering},
        mpsc::{self, RecvTimeoutError, Sender},
    },
    thread,
    time::{Duration, Instant},
};

pub static INTERRUPTED: AtomicBool = AtomicBool::new(false);
pub static CANCEL_ASSIGNMENTS: AtomicBool = AtomicBool::new(false);

const OUTPUT_LIMIT: usize = 16 * 1024 * 1024;

/// How long a finished command's background processes may keep its output
/// pipes open before agengo stops them. Waiting twice as long gives up on
/// the pipes entirely, for processes that left the process group.
const EXIT_GRACE: Duration = Duration::from_secs(2);

/// A `git` command for agengo's own Git operations. Hooks and fsmonitor are
/// disabled: worktrees share hooks and configuration with the repository, so
/// an agent could otherwise make agengo run code outside its worktree.
pub fn git_command() -> Command {
    let mut command = Command::new("git");
    command.args([
        "-c",
        "core.hooksPath=/dev/null",
        "-c",
        "core.fsmonitor=false",
    ]);
    // Worktrees live below the user's cache directory, so checkouts with deep
    // trees (node_modules) pass the 260-character Windows path limit.
    #[cfg(windows)]
    command.args(["-c", "core.longpaths=true"]);
    command
}

pub fn run(command: &mut Command, input: Option<&[u8]>, timeout: Option<u64>) -> Result<Output> {
    run_with_limit(command, input, timeout, OUTPUT_LIMIT)
}

/// Which output pipe a chunk came from.
#[derive(Clone, Copy)]
enum Pipe {
    Stdout,
    Stderr,
}

impl Pipe {
    fn name(self) -> &'static str {
        match self {
            Self::Stdout => "stdout",
            Self::Stderr => "stderr",
        }
    }
}

/// What the pipe threads report to the coordinating loop.
enum Event {
    Data(Pipe, Vec<u8>),
    /// The pipe reached end of file, or failed.
    Closed(Pipe, Option<io::Error>),
    /// Writing the input failed for a reason other than the child closing it.
    InputFailed(io::Error),
}

/// Copy a pipe to the channel until end of file. Threads (rather than
/// polling) work the same way on every platform: Windows anonymous pipes
/// cannot be polled or made non-blocking.
fn pump(pipe: Pipe, mut reader: impl Read + Send + 'static, events: Sender<Event>) {
    thread::spawn(move || {
        let mut chunk = vec![0; 16 * 1024];
        loop {
            match reader.read(&mut chunk) {
                Ok(0) => {
                    let _ = events.send(Event::Closed(pipe, None));
                    return;
                }
                Ok(count) => {
                    if events
                        .send(Event::Data(pipe, chunk[..count].to_vec()))
                        .is_err()
                    {
                        return;
                    }
                }
                Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
                Err(error) => {
                    let _ = events.send(Event::Closed(pipe, Some(error)));
                    return;
                }
            }
        }
    });
}

fn feed(mut writer: impl Write + Send + 'static, input: Vec<u8>, events: Sender<Event>) {
    thread::spawn(move || {
        if let Err(error) = writer.write_all(&input) {
            if error.kind() != io::ErrorKind::BrokenPipe {
                let _ = events.send(Event::InputFailed(error));
            }
        }
    });
}

pub fn run_with_limit(
    command: &mut Command,
    input: Option<&[u8]>,
    timeout: Option<u64>,
    limit: usize,
) -> Result<Output> {
    command
        .stdin(if input.is_some() {
            Stdio::piped()
        } else {
            Stdio::null()
        })
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    group::prepare(command);
    let program = command.get_program().to_owned();
    let mut child = command
        .spawn()
        .with_context(|| format!("cannot launch {program:?}"))?;
    let group = match group::attach(&child) {
        Ok(group) => group,
        Err(error) => {
            let _ = child.kill();
            let _ = child.wait();
            return Err(error).with_context(|| format!("cannot start {program:?}"));
        }
    };

    let (events, received) = mpsc::channel();
    if let Some(stdin) = child.stdin.take() {
        // An empty input closes stdin at once, as before.
        if let Some(input) = input.filter(|input| !input.is_empty()) {
            feed(stdin, input.to_vec(), events.clone());
        }
    }
    let mut open = 0;
    if let Some(stdout) = child.stdout.take() {
        pump(Pipe::Stdout, stdout, events.clone());
        open += 1;
    }
    if let Some(stderr) = child.stderr.take() {
        pump(Pipe::Stderr, stderr, events.clone());
        open += 1;
    }
    drop(events);

    let result = (|| -> Result<Output> {
        let mut out = Vec::new();
        let mut err = Vec::new();
        let start = Instant::now();
        let mut status = None;
        let mut exited = None;
        let mut stopped = false;
        loop {
            if INTERRUPTED.load(Ordering::Relaxed) {
                bail!("run interrupted");
            }
            if CANCEL_ASSIGNMENTS.load(Ordering::Relaxed) {
                bail!("assignment cancelled");
            }
            if timeout.is_some_and(|seconds| start.elapsed().as_secs() >= seconds) {
                bail!("{program:?} exceeded the timeout");
            }
            if status.is_none() {
                status = child.try_wait()?;
                if status.is_some() {
                    exited = Some(Instant::now());
                }
            }
            if let Some(status) = status {
                // Background processes started by the command can inherit
                // its pipes and hold them open long after it exits.
                let lingering = exited.map_or(Duration::ZERO, |time| time.elapsed());
                if open == 0 || lingering >= EXIT_GRACE * 2 {
                    return Ok(Output {
                        status,
                        stdout: out,
                        stderr: err,
                    });
                }
                if lingering >= EXIT_GRACE && !stopped {
                    group.kill(&mut child);
                    stopped = true;
                }
            }
            match received.recv_timeout(Duration::from_millis(10)) {
                Ok(Event::Data(pipe, bytes)) => {
                    let output = match pipe {
                        Pipe::Stdout => &mut out,
                        Pipe::Stderr => &mut err,
                    };
                    if bytes.len() > limit - output.len() {
                        return Err(anyhow!("output exceeded the {limit}-byte limit"))
                            .with_context(|| format!("{program:?} {}", pipe.name()));
                    }
                    output.extend_from_slice(&bytes);
                }
                Ok(Event::Closed(pipe, error)) => {
                    open -= 1;
                    if let Some(error) = error {
                        return Err(error).with_context(|| format!("{program:?} {}", pipe.name()));
                    }
                }
                Ok(Event::InputFailed(error)) => {
                    return Err(error).with_context(|| format!("{program:?} stdin"));
                }
                Err(RecvTimeoutError::Timeout) => {}
                // Every pipe is closed; only the exit status is outstanding.
                Err(RecvTimeoutError::Disconnected) => thread::sleep(Duration::from_millis(2)),
            }
        }
    })();
    if result.is_err() {
        group.kill(&mut child);
        let _ = child.wait();
    }
    result
}

/// Stopping a command together with every process it started.
#[cfg(unix)]
mod group {
    use std::{
        io,
        os::unix::process::CommandExt,
        process::{Child, Command},
    };

    /// The child leads a new process group, so the terminal's Ctrl+C does not
    /// reach it and agengo can stop the whole group.
    pub fn prepare(command: &mut Command) {
        command.process_group(0);
    }

    pub struct Group(i32);

    pub fn attach(child: &Child) -> io::Result<Group> {
        Ok(Group(child.id() as i32))
    }

    impl Group {
        pub fn kill(&self, _child: &mut Child) {
            // The child was spawned with process_group(0), so its pid is the
            // group id.
            unsafe {
                libc::kill(-self.0, libc::SIGKILL);
            }
        }
    }
}

/// Stopping a command together with every process it started: the child
/// starts suspended, joins a Job Object, and only then runs, so none of its
/// descendants can start outside the job.
#[cfg(windows)]
mod group {
    use std::{
        io,
        os::windows::{io::AsRawHandle, process::CommandExt},
        process::{Child, Command},
        ptr,
    };
    use windows_sys::Win32::{
        Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE},
        System::{
            Diagnostics::ToolHelp::{
                CreateToolhelp32Snapshot, Thread32First, Thread32Next, TH32CS_SNAPTHREAD,
                THREADENTRY32,
            },
            JobObjects::{AssignProcessToJobObject, CreateJobObjectW, TerminateJobObject},
            Threading::{
                OpenThread, ResumeThread, CREATE_NEW_PROCESS_GROUP, CREATE_SUSPENDED,
                THREAD_SUSPEND_RESUME,
            },
        },
    };

    /// `CREATE_NEW_PROCESS_GROUP` keeps the console's Ctrl+C from reaching
    /// the child, as a new process group does on Unix.
    pub fn prepare(command: &mut Command) {
        command.creation_flags(CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP);
    }

    pub struct Group {
        /// `None` when the job could not be created; agengo then stops only
        /// the child itself.
        job: Option<HANDLE>,
    }

    // The job handle is only used through thread-safe Win32 calls.
    unsafe impl Send for Group {}

    pub fn attach(child: &Child) -> io::Result<Group> {
        let process = child.as_raw_handle() as HANDLE;
        // Owned by the returned Group, which closes it.
        let job = unsafe { CreateJobObjectW(ptr::null(), ptr::null()) };
        let job = if job.is_null() {
            None
        } else if unsafe { AssignProcessToJobObject(job, process) } == 0 {
            unsafe { CloseHandle(job) };
            None
        } else {
            Some(job)
        };
        resume(child.id())?;
        Ok(Group { job })
    }

    /// Resume the threads of a process created with `CREATE_SUSPENDED`.
    fn resume(pid: u32) -> io::Result<()> {
        let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };
        if snapshot == INVALID_HANDLE_VALUE {
            return Err(io::Error::last_os_error());
        }
        let mut entry: THREADENTRY32 = unsafe { std::mem::zeroed() };
        entry.dwSize = std::mem::size_of::<THREADENTRY32>() as u32;
        let mut resumed = 0;
        let mut more = unsafe { Thread32First(snapshot, &mut entry) } != 0;
        while more {
            if entry.th32OwnerProcessID == pid {
                let thread = unsafe { OpenThread(THREAD_SUSPEND_RESUME, 0, entry.th32ThreadID) };
                if !thread.is_null() {
                    if unsafe { ResumeThread(thread) } != u32::MAX {
                        resumed += 1;
                    }
                    unsafe { CloseHandle(thread) };
                }
            }
            more = unsafe { Thread32Next(snapshot, &mut entry) } != 0;
        }
        unsafe { CloseHandle(snapshot) };
        if resumed == 0 {
            return Err(io::Error::other("cannot resume the new process"));
        }
        Ok(())
    }

    impl Group {
        pub fn kill(&self, child: &mut Child) {
            match self.job {
                Some(job) => unsafe {
                    TerminateJobObject(job, 1);
                },
                None => {
                    let _ = child.kill();
                }
            }
        }
    }

    impl Drop for Group {
        fn drop(&mut self) {
            if let Some(job) = self.job {
                // Closing the job does not stop its processes.
                unsafe { CloseHandle(job) };
            }
        }
    }
}

/// Find an executable the way a shell would: a name with a directory part is
/// taken relative to `base`, a bare name is looked up on `PATH`. On Windows
/// the extensions in `PATHEXT` are tried too, because `Command` itself only
/// adds `.exe` and would not find `claude.cmd` or `npm.cmd`.
pub fn resolve(program: &OsStr, base: &Path) -> Option<PathBuf> {
    let path = Path::new(program);
    if path.components().count() > 1 || path.is_absolute() {
        return candidates(&base.join(path)).find(|candidate| executable(candidate));
    }
    std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())
        .flat_map(|directory| candidates(&base.join(directory).join(path)).collect::<Vec<_>>())
        .find(|candidate| executable(candidate))
}

#[cfg(unix)]
fn candidates(path: &Path) -> impl Iterator<Item = PathBuf> {
    std::iter::once(path.to_owned())
}

#[cfg(windows)]
fn candidates(path: &Path) -> impl Iterator<Item = PathBuf> {
    let extensions = std::env::var("PATHEXT")
        .ok()
        .filter(|value| !value.is_empty())
        .unwrap_or_else(|| ".COM;.EXE;.BAT;.CMD".into());
    let known = path.extension().is_some_and(|extension| {
        extensions.split(';').any(|known| {
            known
                .trim_start_matches('.')
                .eq_ignore_ascii_case(&extension.to_string_lossy())
        })
    });
    let mut found = Vec::new();
    if known {
        found.push(path.to_owned());
    } else {
        for extension in extensions.split(';').filter(|value| !value.is_empty()) {
            let mut name = path.as_os_str().to_owned();
            name.push(extension.to_ascii_lowercase());
            found.push(PathBuf::from(name));
        }
    }
    found.into_iter()
}

#[cfg(unix)]
fn executable(path: &Path) -> bool {
    use std::os::unix::fs::PermissionsExt;
    path.metadata()
        .is_ok_and(|info| info.is_file() && info.permissions().mode() & 0o111 != 0)
}

#[cfg(windows)]
fn executable(path: &Path) -> bool {
    path.is_file()
}

pub fn checked(output: Output, label: &str) -> Result<String> {
    if !output.status.success() {
        let error = String::from_utf8_lossy(&output.stderr);
        let detail = if error.trim().is_empty() {
            String::from_utf8_lossy(&output.stdout)
        } else {
            error
        };
        bail!("{label}: {}", detail.trim());
    }
    String::from_utf8(output.stdout).with_context(|| format!("{label}: invalid UTF-8 output"))
}

#[derive(Clone)]
pub struct Repo {
    pub root: PathBuf,
    pub data: PathBuf,
    /// Directory holding this repository's agent worktrees. It lives outside
    /// `.git` because coding agents refuse to write below `.git/`.
    pub worktrees: PathBuf,
}

/// Environment variable that overrides the base directory for worktrees.
/// Directories that hold only tool output: Python bytecode, tool caches and
/// installed npm packages.
const ARTIFACT_DIRS: &[&str] = &[
    "__pycache__",
    ".pytest_cache",
    ".mypy_cache",
    ".ruff_cache",
    "node_modules",
];
/// File names and suffixes of tool output (`*.py[cod]`, Finder and Explorer metadata).
const ARTIFACT_FILES: &[&str] = &[".DS_Store", "Thumbs.db"];
const ARTIFACT_SUFFIXES: &[&str] = &[".pyc", ".pyo", ".pyd"];

/// The leading part of the repository-relative `path` that makes it a
/// well-known build artifact, such as `pkg/__pycache__` for
/// `pkg/__pycache__/mod.cpython-312.pyc`, or `None` for ordinary files.
/// Agents create these when they run tests, and repositories without an
/// ignore file would otherwise see them as task output. agengo ignores them
/// on top of the repository's own ignore rules, without touching
/// `core.excludesFile` or `.git/info/exclude`.
pub fn artifact_root(path: &str) -> Option<&str> {
    let mut start = 0;
    for part in path.split('/') {
        let end = start + part.len();
        let artifact = if end == path.len() {
            ARTIFACT_FILES.contains(&part)
                || ARTIFACT_SUFFIXES
                    .iter()
                    .any(|suffix| part.ends_with(suffix))
        } else {
            ARTIFACT_DIRS.contains(&part)
        };
        if artifact {
            return Some(&path[..end]);
        }
        start = end + 1;
    }
    None
}

pub const WORKTREES_ENV: &str = "AGENGO_WORKTREES";

fn worktree_base() -> Result<PathBuf> {
    if let Some(base) = std::env::var_os(WORKTREES_ENV).filter(|value| !value.is_empty()) {
        return Ok(PathBuf::from(base));
    }
    if let Some(cache) = std::env::var_os("XDG_CACHE_HOME").filter(|value| !value.is_empty()) {
        return Ok(PathBuf::from(cache).join("agengo").join("worktrees"));
    }
    // Windows keeps per-user caches in %LOCALAPPDATA%, and PowerShell and
    // cmd do not set HOME.
    #[cfg(windows)]
    if let Some(local) = std::env::var_os("LOCALAPPDATA").filter(|value| !value.is_empty()) {
        return Ok(PathBuf::from(local).join("agengo").join("worktrees"));
    }
    let home = std::env::var_os("HOME")
        .filter(|value| !value.is_empty())
        .ok_or_else(|| anyhow!("set HOME, XDG_CACHE_HOME or {WORKTREES_ENV}"))?;
    Ok(PathBuf::from(home)
        .join(".cache")
        .join("agengo")
        .join("worktrees"))
}

/// Read the recorded worktree root, or choose and record a new one.
fn worktree_root(data: &Path, root: &Path) -> Result<PathBuf> {
    let record = data.join("worktree-root");
    if let Ok(saved) = fs::read_to_string(&record) {
        let saved = saved.trim_end_matches('\n');
        if !saved.is_empty() {
            return Ok(PathBuf::from(saved));
        }
    }
    let name: String = root
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("repo")
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '_'
            }
        })
        .take(40)
        .collect();
    let unique = uuid::Uuid::new_v4().simple().to_string();
    let chosen = worktree_base()?.join(format!("{name}-{}", &unique[..8]));
    let chosen = if chosen.is_absolute() {
        chosen
    } else {
        std::env::current_dir()?.join(chosen)
    };
    fs::create_dir_all(data)?;
    fs::write(&record, format!("{}\n", chosen.display()))?;
    Ok(chosen)
}

impl Repo {
    pub fn open(cwd: &Path) -> Result<Self> {
        let query = |args: &[&str]| {
            checked(
                run(git_command().current_dir(cwd).args(args), None, None)?,
                "git",
            )
            .map_err(|error| {
                if error.to_string().contains("not a git repository") {
                    anyhow!("{error}\nhint: agengo works inside a Git repository; run `git init` and make a first commit (`agengo doctor` checks the rest)")
                } else {
                    error
                }
            })
        };
        let root = PathBuf::from(query(&["rev-parse", "--show-toplevel"])?.trim_end_matches('\n'));
        let common = query(&["rev-parse", "--path-format=absolute", "--git-common-dir"])?;
        let data = Path::new(common.trim_end_matches('\n')).join("agent-flow");
        let worktrees = worktree_root(&data, &root)?;
        Ok(Self {
            root,
            data,
            worktrees,
        })
    }
    /// Worktree directories a run may own: the current location and the
    /// location used before 0.3.0.
    pub fn run_worktree_roots(&self, run: &str) -> [PathBuf; 2] {
        [
            self.worktrees.join(run),
            self.data.join("worktrees").join(run),
        ]
    }
    pub fn raw(&self, args: &[&str], cwd: &Path) -> Result<Output> {
        run(git_command().current_dir(cwd).args(args), None, None)
    }
    pub fn git_at(&self, args: &[&str], cwd: &Path) -> Result<String> {
        checked(
            self.raw(args, cwd)?,
            &format!("git {}", args.first().unwrap_or(&"")),
        )
    }
    pub fn git(&self, args: &[&str]) -> Result<String> {
        self.git_at(args, &self.root)
    }
    pub fn sha_at(&self, rev: &str, cwd: &Path) -> Result<String> {
        Ok(self
            .git_at(
                &[
                    "rev-parse",
                    "--verify",
                    "--end-of-options",
                    &format!("{rev}^{{commit}}"),
                ],
                cwd,
            )?
            .trim()
            .into())
    }
    pub fn sha(&self, rev: &str) -> Result<String> {
        self.sha_at(rev, &self.root)
    }
    pub fn current(&self, name: &str) -> Result<Option<String>> {
        let result = self.raw(
            &["rev-parse", "--verify", "--quiet", "--end-of-options", name],
            &self.root,
        )?;
        if result.status.code() == Some(1) {
            return Ok(None);
        }
        Ok(Some(checked(result, "read ref")?.trim().into()))
    }
    pub fn set_ref(&self, name: &str, sha: &str, expected: Option<&str>) -> Result<()> {
        let zero = "0".repeat(sha.len());
        self.git(&["update-ref", name, sha, expected.unwrap_or(&zero)])?;
        Ok(())
    }
    pub fn worktree(&self, path: &Path, sha: &str, branch: Option<&str>) -> Result<()> {
        fs::create_dir_all(path.parent().unwrap())?;
        let path = path
            .to_str()
            .ok_or_else(|| anyhow!("invalid worktree path"))?;
        let mut args = vec!["worktree", "add"];
        if let Some(branch) = branch {
            args.extend(["-b", branch]);
        } else {
            args.push("--detach");
        }
        args.extend([path, sha]);
        self.git(&args)?;
        Ok(())
    }
    /// Remove a worktree created by agengo. Missing worktrees are ignored.
    pub fn remove_worktree(&self, path: &Path) -> Result<()> {
        if !path.exists() {
            return Ok(());
        }
        let text = path
            .to_str()
            .ok_or_else(|| anyhow!("invalid worktree path"))?;
        if let Err(error) = self.git(&["worktree", "remove", "--force", "--force", text]) {
            // Git unregisters the worktree before deleting its files. On
            // Windows a file that another program holds open (an editor, a
            // dev server, a virus scanner) leaves the directory behind, and
            // Git no longer treats it as a worktree, so delete it directly.
            if path.exists() && fs::remove_dir_all(path).is_err() {
                return Err(error).with_context(|| {
                    format!(
                        "cannot delete {}; close programs that use files in it, then run agengo clean again",
                        path.display()
                    )
                });
            }
            self.git(&["worktree", "prune"])?;
        }
        Ok(())
    }
    /// Remove every registered worktree below `root`, then the directory itself.
    pub fn remove_worktrees_under(&self, root: &Path) -> Result<usize> {
        let mut removed = 0;
        // Git may report another spelling of the same directory: resolved
        // symlinks (/private/var on macOS), or on Windows the long form of an
        // 8.3 short name (C:\Users\RUNNER~1). Canonical paths agree on both.
        let resolved = fs::canonicalize(root).ok();
        for field in self
            .git(&["worktree", "list", "--porcelain", "-z"])?
            .split('\0')
        {
            if let Some(path) = field.strip_prefix("worktree ") {
                let path = Path::new(path);
                if path.starts_with(root)
                    || resolved.as_ref().is_some_and(|real| {
                        path.starts_with(real)
                            || fs::canonicalize(path).is_ok_and(|own| own.starts_with(real))
                    })
                {
                    self.remove_worktree(path)?;
                    removed += 1;
                }
            }
        }
        if root.exists() {
            fs::remove_dir_all(root)?;
        }
        self.git(&["worktree", "prune"])?;
        Ok(removed)
    }
    /// Delete every ref below the given prefixes. Returns the deleted names.
    pub fn delete_refs(&self, prefixes: &[&str]) -> Result<Vec<String>> {
        let mut args = vec!["for-each-ref", "--format=%(refname)"];
        args.extend(prefixes);
        let names: Vec<String> = self
            .git(&args)?
            .lines()
            .filter(|name| !name.is_empty())
            .map(str::to_owned)
            .collect();
        for name in &names {
            self.git(&["update-ref", "-d", name])?;
        }
        Ok(names)
    }
    pub fn checked_out(&self, reference: &str) -> Result<bool> {
        Ok(self
            .git(&["worktree", "list", "--porcelain", "-z"])?
            .split('\0')
            .any(|field| field.strip_prefix("branch ") == Some(reference)))
    }
    pub fn ancestor(&self, ancestor: &str, child: &str) -> Result<bool> {
        let output = self.raw(
            &["merge-base", "--is-ancestor", ancestor, child],
            &self.root,
        )?;
        if output.status.code() == Some(1) {
            return Ok(false);
        }
        checked(output, "git merge-base")?;
        Ok(true)
    }
    pub fn changed(&self, base: &str, head: &str) -> Result<Vec<String>> {
        Ok(self
            .git(&[
                "diff",
                "--no-renames",
                "--name-only",
                "-z",
                base,
                head,
                "--",
            ])?
            .split('\0')
            .filter(|path| !path.is_empty())
            .map(str::to_owned)
            .collect())
    }
    pub fn untracked(&self, path: &Path, respect_ignores: bool) -> Result<BTreeSet<String>> {
        let mut args = vec!["ls-files", "--others", "-z"];
        if respect_ignores {
            args.push("--exclude-standard");
        }
        Ok(self
            .git_at(&args, path)?
            .split('\0')
            .filter(|name| !name.is_empty())
            .map(str::to_owned)
            .collect())
    }

    /// HEAD of a worktree with no changes besides setup output and
    /// well-known build artifacts (see [`artifact_root`]).
    pub fn clean_head(&self, path: &Path, setup_artifacts: &BTreeSet<String>) -> Result<String> {
        // Compare contents with `git diff` rather than reading `git status`:
        // with core.autocrlf=true a file rewritten with other line endings
        // stays "modified" in status although it has nothing to commit.
        if self.differs(&["diff", "--quiet", "--cached", "HEAD", "--"], path)?
            || self.differs(&["diff", "--quiet", "HEAD", "--"], path)?
            || self
                .untracked(path, true)?
                .iter()
                .any(|name| !setup_artifacts.contains(name) && artifact_root(name).is_none())
        {
            bail!("worktree has uncommitted changes");
        }
        self.sha_at("HEAD", path)
    }
    /// Run a `git diff --quiet` command: exit code 1 means a difference.
    fn differs(&self, args: &[&str], path: &Path) -> Result<bool> {
        let output = self.raw(args, path)?;
        match output.status.code() {
            Some(0) => Ok(false),
            Some(1) => Ok(true),
            _ => checked(output, "git").map(|_| true),
        }
    }
    pub fn snapshot(&self, path: &Path, head: &str) -> Result<()> {
        if self.sha_at("HEAD", path)? != head {
            bail!("command changed the worktree HEAD");
        }
        if !self
            .raw(&["diff", "--quiet", head, "--"], path)?
            .status
            .success()
        {
            bail!("command modified tracked files");
        }
        Ok(())
    }
}

pub fn argv(command: &[String], cwd: &Path) -> Result<Command> {
    let (executable, arguments) = command
        .split_first()
        .ok_or_else(|| anyhow!("empty command"))?;
    // Windows: `npm` is `npm.cmd`, which `Command` does not find by itself.
    #[cfg(windows)]
    let executable = resolve(executable.as_ref(), cwd)
        .map_or_else(|| executable.into(), PathBuf::into_os_string);
    let mut result = Command::new(executable);
    result.current_dir(cwd).args(arguments);
    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A command that runs `script` with the platform's shell.
    fn shell(unix: &str, windows: &str) -> Command {
        if cfg!(windows) {
            let mut command = Command::new("cmd");
            command.args(["/d", "/c", windows]);
            command
        } else {
            let mut command = Command::new("sh");
            command.args(["-c", unix]);
            command
        }
    }

    #[test]
    fn process_passes_input_and_collects_both_pipes() -> Result<()> {
        let mut command = shell("cat; echo oops >&2", "findstr x & echo oops 1>&2");
        let output = run(&mut command, Some(b"x1\nx2\n"), Some(30))?;
        assert!(output.status.success());
        let stdout = String::from_utf8(output.stdout)?;
        assert_eq!(stdout.lines().collect::<Vec<_>>(), ["x1", "x2"]);
        assert_eq!(String::from_utf8(output.stderr)?.trim(), "oops");
        Ok(())
    }

    #[test]
    fn artifact_root_names_the_artifact_part() {
        for (path, root) in [
            (
                "pkg/__pycache__/mod.cpython-312.pyc",
                Some("pkg/__pycache__"),
            ),
            ("__pycache__/x.pyc", Some("__pycache__")),
            (
                "app/node_modules/left-pad/index.js",
                Some("app/node_modules"),
            ),
            (".pytest_cache/v/cache/nodeids", Some(".pytest_cache")),
            ("lib/fast.pyd", Some("lib/fast.pyd")),
            ("docs/.DS_Store", Some("docs/.DS_Store")),
            ("Thumbs.db", Some("Thumbs.db")),
            ("src/main.py", None),
            ("src/pyc", None),
            ("node_modules", None),
            ("build/out.o", None),
            ("target/debug/agengo", None),
        ] {
            assert_eq!(artifact_root(path), root, "{path}");
        }
    }

    #[test]
    fn process_reports_output_limit_instead_of_truncating() -> Result<()> {
        let mut command = shell(
            "printf 'more than eight bytes'",
            "echo more than eight bytes",
        );
        let error = run_with_limit(&mut command, None, Some(5), 8)
            .expect_err("output larger than the limit should fail");
        assert!(format!("{error:#}").contains("output exceeded the 8-byte limit"));
        Ok(())
    }

    #[test]
    fn background_processes_do_not_turn_success_into_a_timeout() -> Result<()> {
        let mut command = shell(
            "sleep 30 & echo $!",
            "start /b ping -n 30 127.0.0.1 & echo started",
        );
        let started = Instant::now();
        let output = run(&mut command, None, Some(30))?;
        assert!(output.status.success());
        assert!(started.elapsed() < Duration::from_secs(10));
        // The background process that held the pipe was stopped. It may stay
        // a zombie until whichever process adopted it reaps it.
        #[cfg(unix)]
        {
            let pid = String::from_utf8(output.stdout)?.trim().parse::<i32>()?;
            let state = Command::new("ps")
                .args(["-o", "stat=", "-p", &pid.to_string()])
                .output()?;
            let state = String::from_utf8_lossy(&state.stdout);
            assert!(state.trim().is_empty() || state.trim_start().starts_with('Z'));
        }
        Ok(())
    }

    /// With core.autocrlf=true (the Git for Windows default), a file checked
    /// out with CRLF and rewritten with LF stays "modified" in `git status`
    /// although adding it changes nothing. Formatters do this all the time.
    #[test]
    fn line_ending_rewrites_do_not_count_as_uncommitted_changes() -> Result<()> {
        let temp = tempfile::tempdir()?;
        let root = temp.path().to_owned();
        let git = |args: &[&str]| -> Result<String> {
            checked(
                run(
                    git_command()
                        .current_dir(&root)
                        .args(["-c", "user.name=t", "-c", "user.email=t@example.invalid"])
                        .args(args),
                    None,
                    Some(30),
                )?,
                "git",
            )
        };
        git(&["init", "-q", "-b", "main"])?;
        git(&["config", "core.autocrlf", "true"])?;
        fs::write(root.join("a.txt"), "one\ntwo\n")?;
        git(&["add", "a.txt"])?;
        git(&["commit", "-q", "-m", "base"])?;
        fs::remove_file(root.join("a.txt"))?;
        git(&["checkout", "--", "a.txt"])?;
        assert_eq!(fs::read(root.join("a.txt"))?, b"one\r\ntwo\r\n");
        let repo = Repo {
            root: root.clone(),
            data: root.join(".git/agent-flow"),
            worktrees: temp.path().join("worktrees"),
        };

        fs::write(root.join("a.txt"), "one\ntwo\n")?;
        assert!(!git(&["status", "--porcelain"])?.is_empty(), "Git's quirk");
        assert_eq!(
            repo.clean_head(&root, &BTreeSet::new())?,
            git(&["rev-parse", "HEAD"])?.trim()
        );

        fs::write(root.join("a.txt"), "one\nthree\n")?;
        assert!(repo.clean_head(&root, &BTreeSet::new()).is_err());
        git(&["checkout", "--", "a.txt"])?;
        fs::write(root.join("b.txt"), "new\n")?;
        assert!(repo.clean_head(&root, &BTreeSet::new()).is_err());
        git(&["add", "b.txt"])?;
        fs::remove_file(root.join("b.txt"))?;
        assert!(
            repo.clean_head(&root, &BTreeSet::new()).is_err(),
            "a staged change counts even when the worktree file is gone"
        );
        Ok(())
    }

    /// Windows refuses to delete a file another process holds open; Git then
    /// unregisters the worktree but leaves its directory behind.
    #[cfg(windows)]
    #[test]
    fn worktrees_with_open_files_are_removed_once_the_files_close() -> Result<()> {
        use std::os::windows::fs::OpenOptionsExt;
        let temp = tempfile::tempdir()?;
        let root = temp.path().join("repo");
        fs::create_dir(&root)?;
        let git = |args: &[&str]| -> Result<String> {
            checked(
                run(
                    git_command()
                        .current_dir(&root)
                        .env("GIT_CONFIG_GLOBAL", "/dev/null")
                        .env("GIT_CONFIG_NOSYSTEM", "1")
                        .args(["-c", "user.name=t", "-c", "user.email=t@example.invalid"])
                        .args(args),
                    None,
                    Some(30),
                )?,
                "git",
            )
        };
        git(&["init", "-q", "-b", "main"])?;
        fs::write(root.join("a.txt"), "a\n")?;
        git(&["add", "a.txt"])?;
        git(&["commit", "-q", "-m", "base"])?;
        let tree = temp.path().join("wt");
        git(&[
            "worktree",
            "add",
            "-q",
            "--detach",
            &tree.to_string_lossy(),
            "HEAD",
        ])?;
        let repo = Repo {
            root: root.clone(),
            data: root.join(".git/agent-flow"),
            worktrees: temp.path().join("worktrees"),
        };

        // Share reading only, as editors and indexers often do.
        let held = fs::OpenOptions::new()
            .read(true)
            .share_mode(1)
            .open(tree.join("a.txt"))?;
        let error = repo
            .remove_worktree(&tree)
            .expect_err("an open file blocks the removal");
        assert!(format!("{error:#}").contains("close programs that use files in it"));

        drop(held);
        repo.remove_worktree(&tree)?;
        assert!(!tree.exists());
        assert!(!git(&["worktree", "list"])?.contains("wt"));
        Ok(())
    }

    #[test]
    fn agengo_git_commands_ignore_hooks() -> Result<()> {
        let temp = tempfile::tempdir()?;
        let marker = temp.path().join("hook-ran");
        let git = |args: &[&str]| -> Result<String> {
            checked(
                run(
                    git_command()
                        .current_dir(temp.path())
                        .env("GIT_CONFIG_GLOBAL", "/dev/null")
                        .env("GIT_CONFIG_NOSYSTEM", "1")
                        .args(["-c", "user.name=t", "-c", "user.email=t@example.invalid"])
                        .args(args),
                    None,
                    Some(30),
                )?,
                "git",
            )
        };
        git(&["init", "-q", "-b", "main"])?;
        git(&["commit", "-q", "--allow-empty", "-m", "base"])?;
        let hook = temp.path().join(".git/hooks/post-checkout");
        let target = marker.to_string_lossy().replace('\\', "/");
        fs::write(&hook, format!("#!/bin/sh\ntouch '{target}'\n"))?;
        #[cfg(unix)]
        fs::set_permissions(&hook, std::os::unix::fs::PermissionsExt::from_mode(0o755))?;
        git(&["worktree", "add", "-q", "--detach", "wt", "HEAD"])?;
        assert!(temp.path().join("wt").exists());
        assert!(!marker.exists(), "agengo must not run repository hooks");
        Ok(())
    }

    #[test]
    fn process_reports_timeout() {
        let mut command = shell("sleep 10", "ping -n 10 127.0.0.1");
        let started = Instant::now();
        let error = run(&mut command, None, Some(1)).expect_err("the command must time out");
        assert!(format!("{error:#}").contains("exceeded the timeout"));
        assert!(started.elapsed() < Duration::from_secs(5));
    }

    #[test]
    fn timeouts_stop_every_process_the_command_started() -> Result<()> {
        let temp = tempfile::tempdir()?;
        let record = temp.path().join("pid");
        let target = record.to_string_lossy().into_owned();
        let mut command = if cfg!(windows) {
            let mut command = Command::new("powershell");
            command.args([
                "-NoProfile",
                "-Command",
                &format!(
                    "$p = Start-Process ping -ArgumentList '-n','60','127.0.0.1' -PassThru -WindowStyle Hidden; \
                     Set-Content -Path '{target}' -Value $p.Id; Start-Sleep 60"
                ),
            ]);
            command
        } else {
            shell(&format!("sleep 60 & echo $! > '{target}'; wait"), "")
        };
        // PowerShell can take many seconds to start on a busy CI runner; the
        // timeout must leave it time to record the child's PID, and stay
        // below the 60 seconds the child lives.
        let timeout = if cfg!(windows) { 30 } else { 8 };
        let error = run(&mut command, None, Some(timeout)).expect_err("the command must time out");
        assert!(format!("{error:#}").contains("exceeded the timeout"));
        let pid = fs::read_to_string(&record)?.trim().to_owned();
        thread::sleep(Duration::from_millis(500));
        let alive = if cfg!(windows) {
            let list = Command::new("tasklist")
                .args(["/FI", &format!("PID eq {pid}"), "/NH"])
                .output()?;
            String::from_utf8_lossy(&list.stdout).contains(&pid)
        } else {
            let state = Command::new("ps")
                .args(["-o", "stat=", "-p", &pid])
                .output()?;
            let state = String::from_utf8_lossy(&state.stdout).trim().to_owned();
            !state.is_empty() && !state.starts_with('Z')
        };
        assert!(!alive, "process {pid} outlived the timed-out command");
        Ok(())
    }

    #[test]
    fn executables_are_found_on_path_with_their_extension() -> Result<()> {
        let directory = tempfile::tempdir()?;
        let name = if cfg!(windows) { "tool.cmd" } else { "tool" };
        let path = directory.path().join(name);
        fs::write(&path, "")?;
        #[cfg(unix)]
        fs::set_permissions(&path, std::os::unix::fs::PermissionsExt::from_mode(0o755))?;
        let found = resolve(OsStr::new("tool"), directory.path());
        // A relative name with a directory part resolves against the base.
        let relative = resolve(OsStr::new("./tool"), directory.path());
        assert_eq!(found, None, "the directory is not on PATH");
        assert_eq!(
            relative.map(|path| path.file_name().map(ToOwned::to_owned)),
            Some(Some(name.into()))
        );
        Ok(())
    }

    #[test]
    fn checked_returns_stdout_and_explains_failures() -> Result<()> {
        let mut ok = shell("printf hi", "echo hi");
        let text = checked(run(&mut ok, None, Some(30))?, "say")?;
        assert_eq!(text.trim(), "hi");

        // The error stream explains a failure; stdout is the fallback.
        let mut bad = shell("echo boom >&2; exit 3", "echo boom 1>&2 & exit 3");
        let error = checked(run(&mut bad, None, Some(30))?, "build").unwrap_err();
        assert_eq!(error.to_string(), "build: boom");
        let mut quiet = shell("echo only; exit 1", "echo only& exit 1");
        let error = checked(run(&mut quiet, None, Some(30))?, "build").unwrap_err();
        assert_eq!(error.to_string(), "build: only");
        Ok(())
    }

    #[test]
    fn argv_splits_program_and_arguments_and_rejects_an_empty_command() -> Result<()> {
        let directory = tempfile::tempdir()?;
        assert!(argv(&[], directory.path()).is_err());
        let command = argv(
            &["git".into(), "--version".into(), "x y".into()],
            directory.path(),
        )?;
        assert_eq!(command.get_current_dir(), Some(directory.path()));
        let arguments: Vec<_> = command.get_args().collect();
        assert_eq!(
            arguments,
            ["--version", "x y"],
            "arguments are not re-split"
        );
        Ok(())
    }

    #[test]
    fn a_command_that_exits_nonzero_is_not_a_timeout() -> Result<()> {
        let mut command = shell("exit 7", "exit 7");
        let output = run(&mut command, None, Some(30))?;
        assert_eq!(output.status.code(), Some(7));
        Ok(())
    }
}