gate4agent-node 0.4.8

Native gate4agent node server: wraps providers and owns PTY/inline sessions, the file browser, local git, and worktrees for its machine
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
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
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
use std::ffi::OsString;
use std::io;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::{Duration, Instant};
use tokio::io::{AsyncRead, AsyncReadExt};
use tokio::time::timeout;

#[cfg(windows)]
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
#[cfg(windows)]
const CREATE_SUSPENDED: u32 = 0x0000_0004;
const GIT_STDERR_MAX_BYTES: usize = 4 * 1_024;
const GIT_LIST_MAX_BYTES: usize = 256 * 1_024;
const GIT_WORKTREE_MAX_ENTRIES: usize = 512;
const GIT_READ_TIMEOUT_MS: u64 = 5_000;
const GIT_REMOVE_PREFLIGHT_TIMEOUT_MS: u64 = 30_000;
const GIT_MUTATION_TIMEOUT_MS: u64 = 180_000;

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct NativeGitWorktreeSnapshot {
    pub path: String,
    pub head: String,
    pub branch: Option<String>,
    pub is_bare: bool,
    pub is_main: bool,
    pub locked: bool,
    pub lock_reason: Option<String>,
    pub prunable: bool,
    pub prunable_reason: Option<String>,
    pub workspace_id: Option<crate::protocol::WorkspaceId>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum GitWorktreeErrorKind {
    Invalid,
    NotRepository,
    Conflict,
    Protected,
    Dirty,
    Locked,
    Failed,
}

#[derive(Debug)]
pub(crate) struct GitWorktreeError {
    pub kind: GitWorktreeErrorKind,
    pub message: String,
}

impl GitWorktreeError {
    fn new(kind: GitWorktreeErrorKind, message: impl Into<String>) -> Self {
        Self { kind, message: message.into() }
    }
}

pub(crate) struct GitCommandOutput {
    pub success: bool,
    pub stdout: Vec<u8>,
    pub stderr: Vec<u8>,
    pub truncated: bool,
    pub timed_out: bool,
}

pub(crate) async fn run_git_read_bounded(
    root: &str,
    arguments: &[&str],
    output_limit: usize,
    timeout_ms: u64,
) -> io::Result<GitCommandOutput> {
    run_git_bounded(root, arguments, output_limit, timeout_ms, true).await
}

async fn run_git_mutation_bounded(
    root: &str,
    arguments: &[OsString],
    output_limit: usize,
    timeout_ms: u64,
) -> io::Result<GitCommandOutput> {
    let mut command = tokio::process::Command::new("git");
    command
        .arg("--no-pager")
        .arg("-c")
        .arg("core.fsmonitor=false")
        .arg("-c")
        .arg("core.quotepath=false")
        .arg("-C")
        .arg(root)
        .args(arguments)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;

        command.as_std_mut().creation_flags(CREATE_NO_WINDOW);
    }
    collect_child_output(command, output_limit, timeout_ms).await
}

async fn run_git_bounded(
    root: &str,
    arguments: &[&str],
    output_limit: usize,
    timeout_ms: u64,
    read_only: bool,
) -> io::Result<GitCommandOutput> {
    let mut command = tokio::process::Command::new("git");
    command
        .arg("--no-pager")
        .arg("-c")
        .arg("core.fsmonitor=false")
        .arg("-c")
        .arg("core.quotepath=false")
        .arg("-C")
        .arg(root)
        .args(arguments)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    if read_only {
        command.env("GIT_OPTIONAL_LOCKS", "0");
    }
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;

        command.as_std_mut().creation_flags(CREATE_NO_WINDOW);
    }
    collect_child_output(command, output_limit, timeout_ms).await
}

async fn collect_child_output(
    mut command: tokio::process::Command,
    output_limit: usize,
    timeout_ms: u64,
) -> io::Result<GitCommandOutput> {
    command.kill_on_drop(true);
    #[cfg(windows)]
    let (mut child, job) = windows_job::spawn_contained(&mut command)?;
    #[cfg(not(windows))]
    let mut child = command.spawn()?;
    let stdout = child.stdout.take().ok_or_else(|| {
        io::Error::new(io::ErrorKind::Other, "git stdout pipe is unavailable")
    })?;
    let stderr = child.stderr.take().ok_or_else(|| {
        io::Error::new(io::ErrorKind::Other, "git stderr pipe is unavailable")
    })?;
    let stdout_task = tokio::spawn(read_process_output(stdout, output_limit));
    let stderr_task = tokio::spawn(read_process_output(stderr, GIT_STDERR_MAX_BYTES));
    #[cfg(windows)]
    let mut child = ChildGuard::new(child, job);
    #[cfg(not(windows))]
    let mut child = ChildGuard::new(child);
    let (status, timed_out) = match timeout(
        Duration::from_millis(timeout_ms),
        child.child_mut().wait(),
    ).await {
        Ok(status) => (status?, false),
        Err(_) => {
            child.terminate_tree();
            (child.child_mut().wait().await?, true)
        }
    };
    child.disarm();
    let (stdout, stdout_truncated) = stdout_task
        .await
        .map_err(|error| io::Error::new(io::ErrorKind::Other, error.to_string()))??;
    let (stderr, stderr_truncated) = stderr_task
        .await
        .map_err(|error| io::Error::new(io::ErrorKind::Other, error.to_string()))??;
    Ok(GitCommandOutput {
        success: status.success(),
        stdout,
        stderr,
        truncated: stdout_truncated || stderr_truncated,
        timed_out,
    })
}

struct ChildGuard {
    child: Option<tokio::process::Child>,
    #[cfg(windows)]
    job: Option<windows_job::WindowsJob>,
}

impl ChildGuard {
    #[cfg(not(windows))]
    fn new(child: tokio::process::Child) -> Self {
        Self { child: Some(child) }
    }

    #[cfg(windows)]
    fn new(child: tokio::process::Child, job: windows_job::WindowsJob) -> Self {
        Self { child: Some(child), job: Some(job) }
    }

    fn child_mut(&mut self) -> &mut tokio::process::Child {
        self.child.as_mut().expect("Git child guard is armed")
    }

    fn terminate_tree(&mut self) {
        #[cfg(windows)]
        self.job.take();
        if let Some(child) = self.child.as_mut() {
            let _ = child.start_kill();
        }
    }

    fn disarm(&mut self) {
        #[cfg(windows)]
        self.job.take();
        self.child.take();
    }
}

impl Drop for ChildGuard {
    fn drop(&mut self) {
        self.terminate_tree();
        let Some(mut child) = self.child.take() else { return };
        if let Ok(handle) = tokio::runtime::Handle::try_current() {
            handle.spawn(async move {
                let _ = timeout(Duration::from_secs(5), child.wait()).await;
            });
        }
    }
}

#[cfg(windows)]
mod windows_job {
    use std::ffi::c_void;
    use std::io;
    use std::mem::{size_of, zeroed};
    use std::os::windows::process::CommandExt;
    use std::ptr::null;
    use std::time::{Duration, Instant};

    type Bool = i32;
    type Dword = u32;
    type Handle = *mut c_void;

    const JOB_OBJECT_EXTENDED_LIMIT_INFORMATION: Dword = 9;
    const JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE: Dword = 0x0000_2000;
    const TH32CS_SNAPTHREAD: Dword = 0x0000_0004;
    const THREAD_SUSPEND_RESUME: Dword = 0x0002;
    const INVALID_HANDLE_VALUE: Handle = -1isize as Handle;
    const THREAD_DISCOVERY_TIMEOUT: Duration = Duration::from_secs(2);
    const THREAD_DISCOVERY_POLL: Duration = Duration::from_millis(10);

    #[repr(C)]
    struct JobObjectBasicLimitInformation {
        per_process_user_time_limit: i64,
        per_job_user_time_limit: i64,
        limit_flags: Dword,
        minimum_working_set_size: usize,
        maximum_working_set_size: usize,
        active_process_limit: Dword,
        affinity: usize,
        priority_class: Dword,
        scheduling_class: Dword,
    }

    #[repr(C)]
    struct IoCounters {
        read_operation_count: u64,
        write_operation_count: u64,
        other_operation_count: u64,
        read_transfer_count: u64,
        write_transfer_count: u64,
        other_transfer_count: u64,
    }

    #[repr(C)]
    struct JobObjectExtendedLimitInformation {
        basic_limit_information: JobObjectBasicLimitInformation,
        io_info: IoCounters,
        process_memory_limit: usize,
        job_memory_limit: usize,
        peak_process_memory_used: usize,
        peak_job_memory_used: usize,
    }

    #[repr(C)]
    struct ThreadEntry32 {
        size: Dword,
        usage_count: Dword,
        thread_id: Dword,
        owner_process_id: Dword,
        base_priority: i32,
        delta_priority: i32,
        flags: Dword,
    }

    #[link(name = "kernel32")]
    extern "system" {
        fn AssignProcessToJobObject(job: Handle, process: Handle) -> Bool;
        fn CloseHandle(handle: Handle) -> Bool;
        fn CreateJobObjectW(attributes: *const c_void, name: *const u16) -> Handle;
        fn CreateToolhelp32Snapshot(flags: Dword, process_id: Dword) -> Handle;
        fn OpenThread(desired_access: Dword, inherit_handle: Bool, thread_id: Dword) -> Handle;
        fn ResumeThread(thread: Handle) -> Dword;
        fn SetInformationJobObject(
            job: Handle,
            information_class: Dword,
            information: *const c_void,
            information_length: Dword,
        ) -> Bool;
        fn Thread32First(snapshot: Handle, entry: *mut ThreadEntry32) -> Bool;
        fn Thread32Next(snapshot: Handle, entry: *mut ThreadEntry32) -> Bool;
    }

    struct OwnedHandle(Handle);

    unsafe impl Send for OwnedHandle {}

    impl OwnedHandle {
        fn new(handle: Handle) -> io::Result<Self> {
            if handle.is_null() || handle == INVALID_HANDLE_VALUE {
                Err(io::Error::last_os_error())
            } else {
                Ok(Self(handle))
            }
        }

        fn raw(&self) -> Handle {
            self.0
        }
    }

    impl Drop for OwnedHandle {
        fn drop(&mut self) {
            unsafe {
                CloseHandle(self.0);
            }
        }
    }

    pub(super) struct WindowsJob {
        handle: OwnedHandle,
    }

    impl WindowsJob {
        fn new() -> io::Result<Self> {
            let handle = OwnedHandle::new(unsafe { CreateJobObjectW(null(), null()) })?;
            let mut limits: JobObjectExtendedLimitInformation = unsafe { zeroed() };
            limits.basic_limit_information.limit_flags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
            let configured = unsafe {
                SetInformationJobObject(
                    handle.raw(),
                    JOB_OBJECT_EXTENDED_LIMIT_INFORMATION,
                    &limits as *const _ as *const c_void,
                    size_of::<JobObjectExtendedLimitInformation>() as Dword,
                )
            };
            if configured == 0 {
                return Err(io::Error::last_os_error());
            }
            Ok(Self { handle })
        }

        fn assign(&self, child: &tokio::process::Child) -> io::Result<()> {
            let process = child.raw_handle().ok_or_else(|| {
                io::Error::new(io::ErrorKind::Other, "suspended Git process has no process handle")
            })?;
            let assigned = unsafe {
                AssignProcessToJobObject(self.handle.raw(), process as Handle)
            };
            if assigned == 0 {
                Err(io::Error::last_os_error())
            } else {
                Ok(())
            }
        }
    }

    fn open_primary_thread(process_id: Dword) -> io::Result<OwnedHandle> {
        let deadline = Instant::now() + THREAD_DISCOVERY_TIMEOUT;
        loop {
            let snapshot = OwnedHandle::new(unsafe {
                CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0)
            })?;
            let mut entry: ThreadEntry32 = unsafe { zeroed() };
            entry.size = size_of::<ThreadEntry32>() as Dword;
            let mut has_entry = unsafe { Thread32First(snapshot.raw(), &mut entry) } != 0;
            while has_entry {
                if entry.owner_process_id == process_id {
                    return OwnedHandle::new(unsafe {
                        OpenThread(THREAD_SUSPEND_RESUME, 0, entry.thread_id)
                    });
                }
                has_entry = unsafe { Thread32Next(snapshot.raw(), &mut entry) } != 0;
            }
            if Instant::now() >= deadline {
                return Err(io::Error::new(
                    io::ErrorKind::TimedOut,
                    "suspended Git process primary thread was not found",
                ));
            }
            std::thread::sleep(THREAD_DISCOVERY_POLL);
        }
    }

    fn resume_primary_thread(child: &tokio::process::Child) -> io::Result<()> {
        let thread = open_primary_thread(child.id().ok_or_else(|| {
            io::Error::new(io::ErrorKind::Other, "suspended Git process has no process ID")
        })?)?;
        let previous_suspend_count = unsafe { ResumeThread(thread.raw()) };
        if previous_suspend_count == Dword::MAX {
            Err(io::Error::last_os_error())
        } else if previous_suspend_count != 1 {
            Err(io::Error::new(
                io::ErrorKind::Other,
                format!("unexpected Git primary thread suspend count: {previous_suspend_count}"),
            ))
        } else {
            Ok(())
        }
    }

    pub(super) fn spawn_contained(
        command: &mut tokio::process::Command,
    ) -> io::Result<(tokio::process::Child, WindowsJob)> {
        let job = WindowsJob::new()?;
        command
            .as_std_mut()
            .creation_flags(super::CREATE_SUSPENDED | super::CREATE_NO_WINDOW);
        let mut child = command.spawn()?;
        if let Err(error) = job.assign(&child) {
            let _ = child.start_kill();
            return Err(error);
        }
        if let Err(error) = resume_primary_thread(&child) {
            drop(job);
            let _ = child.start_kill();
            return Err(error);
        }
        Ok((child, job))
    }
}

async fn read_process_output<R>(reader: R, max_bytes: usize) -> io::Result<(Vec<u8>, bool)>
where
    R: AsyncRead + Unpin,
{
    let mut reader = reader.take((max_bytes + 1) as u64);
    let mut output = Vec::with_capacity(max_bytes.min(8 * 1_024));
    reader.read_to_end(&mut output).await?;
    let truncated = output.len() > max_bytes;
    output.truncate(max_bytes);
    Ok((output, truncated))
}

pub(crate) async fn list_worktrees(
    root: &str,
) -> Result<Vec<NativeGitWorktreeSnapshot>, GitWorktreeError> {
    list_worktrees_with_deadline(root, Instant::now() + Duration::from_millis(GIT_READ_TIMEOUT_MS * 2)).await
}

pub(crate) async fn list_worktrees_with_deadline(
    root: &str,
    deadline: Instant,
) -> Result<Vec<NativeGitWorktreeSnapshot>, GitWorktreeError> {
    let nul = run_git_read_bounded(
        root,
        &["worktree", "list", "--porcelain", "-z"],
        GIT_LIST_MAX_BYTES,
        remaining_timeout_ms(deadline)?,
    )
    .await
    .map_err(io_error)?;
    if nul.timed_out {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Failed,
            "git worktree list timed out",
        ));
    }
    if nul.success {
        if nul.truncated {
            return Err(GitWorktreeError::new(
                GitWorktreeErrorKind::Failed,
                "git worktree list exceeded its bounded output",
            ));
        }
        return bounded_worktree_list(parse_worktree_list_nul(&nul.stdout));
    }

    let fallback = run_git_read_bounded(
        root,
        &["worktree", "list", "--porcelain"],
        GIT_LIST_MAX_BYTES,
        remaining_timeout_ms(deadline)?,
    )
    .await
    .map_err(io_error)?;
    let output = command_result("git worktree list", fallback)?;
    bounded_worktree_list(parse_worktree_list_lines(&output))
}

pub(crate) async fn create_worktree(
    source_root: &str,
    target_root: &str,
    branch: &str,
    base: Option<&str>,
) -> Result<NativeGitWorktreeSnapshot, GitWorktreeError> {
    create_worktree_with_timeout(
        source_root,
        target_root,
        branch,
        base,
        GIT_MUTATION_TIMEOUT_MS,
    ).await
}

pub(crate) async fn create_worktree_with_timeout(
    source_root: &str,
    target_root: &str,
    branch: &str,
    base: Option<&str>,
    mutation_timeout_ms: u64,
) -> Result<NativeGitWorktreeSnapshot, GitWorktreeError> {
    let deadline = Instant::now()
        + Duration::from_millis(mutation_timeout_ms.max(1).min(GIT_MUTATION_TIMEOUT_MS));
    let worktrees = list_worktrees_with_deadline(source_root, deadline).await?;
    let repository_root = repository_root(&worktrees)?;
    let target = normalized_absent_target(target_root)?;
    let target_text = path_to_string(&target)?;
    if worktrees.iter().any(|worktree| paths_equal(&worktree.path, &target_text)) {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Conflict,
            "target is already registered as a Git worktree",
        ));
    }
    validate_branch_with_timeout(
        &repository_root,
        branch,
        remaining_timeout_ms(deadline)?,
    ).await?;
    let base_commit = match base {
        Some(base) => Some(resolve_base_commit_with_timeout(
            &repository_root,
            base,
            remaining_timeout_ms(deadline)?,
        ).await?),
        None => None,
    };

    let mut arguments = vec![
        OsString::from("worktree"),
        OsString::from("add"),
        OsString::from("--no-track"),
        OsString::from("-b"),
        OsString::from(branch),
        OsString::from("--"),
        target.as_os_str().to_owned(),
    ];
    if let Some(base_commit) = base_commit {
        arguments.push(OsString::from(base_commit));
    }
    let output = run_git_mutation_bounded(
        &repository_root,
        &arguments,
        GIT_STDERR_MAX_BYTES,
        remaining_timeout_ms(deadline)?,
    )
    .await
    .map_err(io_error)?;
    command_result("git worktree add", output)?;

    let created = list_worktrees_with_deadline(&repository_root, deadline)
        .await?
        .into_iter()
        .find(|worktree| paths_equal(&worktree.path, &target_text))
        .ok_or_else(|| GitWorktreeError::new(
            GitWorktreeErrorKind::Failed,
            "Git created the worktree but it was not present in the authoritative listing",
        ))?;
    Ok(created)
}

pub(crate) async fn remove_worktree(
    source_root: &str,
    requested_target: &str,
) -> Result<NativeGitWorktreeSnapshot, GitWorktreeError> {
    let requested_target = removal_lookup_path(requested_target)?;
    let worktrees = list_worktrees(source_root).await?;
    let repository_root = repository_root(&worktrees)?;
    let target = worktrees
        .iter()
        .find(|worktree| paths_equal(&worktree.path, &requested_target))
        .cloned()
        .ok_or_else(|| GitWorktreeError::new(
            GitWorktreeErrorKind::Protected,
            "refusing to remove a path that is not in Git's worktree listing",
        ))?;
    validate_removal_target(&repository_root, &target, &worktrees)?;
    ensure_clean(&target.path).await?;

    let arguments = vec![
        OsString::from("worktree"),
        OsString::from("remove"),
        OsString::from("--"),
        OsString::from(&target.path),
    ];
    let output = run_git_mutation_bounded(
        &repository_root,
        &arguments,
        GIT_STDERR_MAX_BYTES,
        GIT_MUTATION_TIMEOUT_MS,
    )
    .await
    .map_err(io_error)?;
    command_result("git worktree remove", output)?;
    if list_worktrees(&repository_root)
        .await?
        .iter()
        .any(|worktree| paths_equal(&worktree.path, &target.path))
    {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Failed,
            "Git reported success but the worktree remains registered",
        ));
    }
    Ok(target)
}

pub(crate) fn removal_lookup_path(value: &str) -> Result<String, GitWorktreeError> {
    if value.is_empty() || value.len() > crate::protocol::MAX_WORKSPACE_ROOT_BYTES {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Invalid,
            "worktree target is empty or exceeds the path limit",
        ));
    }
    let target = Path::new(value);
    if !target.is_absolute() {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Invalid,
            "worktree target must be an absolute path",
        ));
    }
    match std::fs::canonicalize(target) {
        Ok(canonical) => path_to_string(&normalize_windows_verbatim_path(canonical)),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(value.to_owned()),
        Err(error) => Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Protected,
            format!("worktree target cannot be resolved safely: {error}"),
        )),
    }
}

fn repository_root(worktrees: &[NativeGitWorktreeSnapshot]) -> Result<String, GitWorktreeError> {
    worktrees
        .iter()
        .find(|worktree| worktree.is_main && !worktree.is_bare)
        .map(|worktree| worktree.path.clone())
        .ok_or_else(|| GitWorktreeError::new(
            GitWorktreeErrorKind::NotRepository,
            "Git did not report a non-bare main worktree",
        ))
}

async fn validate_branch_with_timeout(
    root: &str,
    branch: &str,
    timeout_ms: u64,
) -> Result<(), GitWorktreeError> {
    if branch.is_empty() || branch.len() > 1_024 || branch.chars().any(char::is_control) {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Invalid,
            "worktree branch is empty, too long, or contains control characters",
        ));
    }
    let output = run_git_read_bounded(
        root,
        &["check-ref-format", "--branch", branch],
        GIT_STDERR_MAX_BYTES,
        timeout_ms.max(1),
    )
    .await
    .map_err(io_error)?;
    if output.timed_out {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Failed,
            "git check-ref-format timed out",
        ));
    }
    if !output.success {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Invalid,
            "worktree branch is not a valid Git branch name",
        ));
    }
    Ok(())
}

pub(crate) async fn resolve_base_commit_with_timeout(
    root: &str,
    base: &str,
    timeout_ms: u64,
) -> Result<String, GitWorktreeError> {
    if base.is_empty() || base.len() > 1_024 || base.chars().any(char::is_control) {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Invalid,
            "worktree base is empty, too long, or contains control characters",
        ));
    }
    let peeled = format!("{base}^{{commit}}");
    let output = run_git_read_bounded(
        root,
        &["rev-parse", "--verify", "--quiet", "--end-of-options", &peeled],
        GIT_STDERR_MAX_BYTES,
        timeout_ms.max(1),
    )
    .await
    .map_err(io_error)?;
    if output.timed_out {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Failed,
            "git worktree base resolution timed out",
        ));
    }
    if output.truncated {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Failed,
            "git worktree base resolution exceeded its bounded output",
        ));
    }
    if !output.success {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Conflict,
            "worktree base does not resolve to a commit",
        ));
    }
    let commit = String::from_utf8_lossy(&output.stdout).trim().to_owned();
    if commit.is_empty() || !commit.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Failed,
            "git worktree base resolution returned an invalid object ID",
        ));
    }
    Ok(commit)
}

fn remaining_timeout_ms(deadline: Instant) -> Result<u64, GitWorktreeError> {
    let remaining = deadline.checked_duration_since(Instant::now()).ok_or_else(|| {
        GitWorktreeError::new(
            GitWorktreeErrorKind::Failed,
            "managed Git operation exceeded its bounded deadline",
        )
    })?;
    let millis = u64::try_from(remaining.as_millis()).unwrap_or(u64::MAX);
    if millis == 0 {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Failed,
            "managed Git operation exceeded its bounded deadline",
        ));
    }
    Ok(millis)
}

async fn ensure_clean(target: &str) -> Result<(), GitWorktreeError> {
    let output = run_git_read_bounded(
        target,
        &["status", "--porcelain=v1", "-z", "--untracked-files=all"],
        GIT_LIST_MAX_BYTES,
        GIT_REMOVE_PREFLIGHT_TIMEOUT_MS,
    )
    .await
    .map_err(io_error)?;
    let output = command_result("git status", output)?;
    if !output.is_empty() {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Dirty,
            "worktree has modified or untracked files",
        ));
    }
    Ok(())
}

fn validate_removal_target(
    repository_root: &str,
    target: &NativeGitWorktreeSnapshot,
    worktrees: &[NativeGitWorktreeSnapshot],
) -> Result<(), GitWorktreeError> {
    if target.is_main || target.is_bare || dangerous_path(&target.path, repository_root) {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Protected,
            "refusing to remove the main, bare, or protected worktree path",
        ));
    }
    if target.locked {
        let reason = target.lock_reason.as_deref().unwrap_or("no reason reported");
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Locked,
            format!("worktree is locked by Git: {reason}"),
        ));
    }
    if target.prunable {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Protected,
            "refusing to remove a prunable worktree through the clean removal path",
        ));
    }
    if let Some(nested) = worktrees.iter().find(|worktree| {
        !paths_equal(&worktree.path, &target.path)
            && path_contains(&target.path, &worktree.path)
    }) {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Protected,
            format!("worktree contains another registered worktree: {}", nested.path),
        ));
    }
    Ok(())
}

fn normalized_absent_target(value: &str) -> Result<PathBuf, GitWorktreeError> {
    if value.is_empty() || value.len() > crate::protocol::MAX_WORKSPACE_ROOT_BYTES {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Invalid,
            "worktree target is empty or exceeds the path limit",
        ));
    }
    let target = Path::new(value);
    if !target.is_absolute() {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Invalid,
            "worktree target must be an absolute path",
        ));
    }
    match std::fs::symlink_metadata(target) {
        Ok(_) => return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Conflict,
            "worktree target already exists",
        )),
        Err(error) if error.kind() == io::ErrorKind::NotFound => {}
        Err(error) => return Err(io_error(error)),
    }
    let file_name = target.file_name().ok_or_else(|| GitWorktreeError::new(
        GitWorktreeErrorKind::Invalid,
        "worktree target must name a directory below an existing parent",
    ))?;
    let parent = target.parent().ok_or_else(|| GitWorktreeError::new(
        GitWorktreeErrorKind::Invalid,
        "worktree target has no parent directory",
    ))?;
    let canonical_parent = std::fs::canonicalize(parent).map_err(|error| {
        GitWorktreeError::new(
            GitWorktreeErrorKind::Invalid,
            format!("worktree target parent is unavailable: {error}"),
        )
    })?;
    if !canonical_parent.is_dir() {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Invalid,
            "worktree target parent is not a directory",
        ));
    }
    Ok(normalize_windows_verbatim_path(canonical_parent).join(file_name))
}

#[cfg(windows)]
fn normalize_windows_verbatim_path(path: PathBuf) -> PathBuf {
    let Some(value) = path.to_str() else {
        return path;
    };
    if let Some(rest) = value.strip_prefix(r"\\?\UNC\") {
        PathBuf::from(format!(r"\\{rest}"))
    } else if let Some(rest) = value.strip_prefix(r"\\?\") {
        PathBuf::from(rest)
    } else {
        path
    }
}

#[cfg(not(windows))]
fn normalize_windows_verbatim_path(path: PathBuf) -> PathBuf {
    path
}

fn path_to_string(path: &Path) -> Result<String, GitWorktreeError> {
    path.as_os_str().to_str().map(str::to_owned).ok_or_else(|| GitWorktreeError::new(
        GitWorktreeErrorKind::Invalid,
        "worktree target is not valid Unicode",
    ))
}

fn dangerous_path(target: &str, repository_root: &str) -> bool {
    let target_path = Path::new(target);
    let repository_root = Path::new(repository_root);
    let home = configured_home_directory();
    dangerous_path_with_home(target_path, repository_root, home.as_deref())
}

pub(crate) fn validate_managed_allocation_root(
    repository_root: &str,
    allocation_root: &str,
) -> Result<(), GitWorktreeError> {
    let allocation = Path::new(allocation_root);
    let repository = Path::new(repository_root);
    let home = configured_home_directory();
    if dangerous_path_with_home(allocation, repository, home.as_deref())
        || native_path_contains(repository, allocation)
    {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Protected,
            "managed worktree allocation root overlaps a protected path",
        ));
    }
    Ok(())
}

fn dangerous_path_with_home(
    target: &Path,
    repository_root: &Path,
    home: Option<&Path>,
) -> bool {
    if native_paths_equal(target, repository_root) {
        return true;
    }
    if target.parent().is_none() || native_path_contains(target, repository_root) {
        return true;
    }
    home.is_some_and(|home| {
        native_paths_equal(target, home) || native_path_contains(target, home)
    })
}

#[cfg(windows)]
fn configured_home_directory() -> Option<PathBuf> {
    std::env::var_os("USERPROFILE").map(PathBuf::from)
}

#[cfg(not(windows))]
fn configured_home_directory() -> Option<PathBuf> {
    std::env::var_os("HOME").map(PathBuf::from)
}

fn path_contains(parent: &str, child: &str) -> bool {
    native_path_contains(Path::new(parent), Path::new(child))
}

pub(crate) fn paths_equal(left: &str, right: &str) -> bool {
    native_paths_equal(Path::new(left), Path::new(right))
}

#[cfg(windows)]
fn native_path_contains(parent: &Path, child: &Path) -> bool {
    let (Some(normalized_parent), Some(normalized_child)) = (
        normalized_path_for_compare(parent),
        normalized_path_for_compare(child),
    ) else {
        return parent != child && child.starts_with(parent);
    };
    normalized_child.len() > normalized_parent.len()
        && normalized_child.starts_with(&normalized_parent)
        && normalized_child.as_bytes().get(normalized_parent.len()) == Some(&b'/')
}

#[cfg(not(windows))]
fn native_path_contains(parent: &Path, child: &Path) -> bool {
    parent != child && child.starts_with(parent)
}

#[cfg(windows)]
fn native_paths_equal(left: &Path, right: &Path) -> bool {
    match (
        normalized_path_for_compare(left),
        normalized_path_for_compare(right),
    ) {
        (Some(left), Some(right)) => left == right,
        _ => left == right,
    }
}

#[cfg(not(windows))]
fn native_paths_equal(left: &Path, right: &Path) -> bool {
    left == right
}

#[cfg(windows)]
fn normalized_path_for_compare(value: &Path) -> Option<String> {
    Some(
        value
            .to_str()?
            .trim_end_matches(['/', '\\'])
            .replace('\\', "/")
            .to_ascii_lowercase(),
    )
}

fn command_result(
    operation: &'static str,
    output: GitCommandOutput,
) -> Result<Vec<u8>, GitWorktreeError> {
    if output.timed_out {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Failed,
            format!("{operation} timed out"),
        ));
    }
    if output.truncated {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Failed,
            format!("{operation} exceeded its bounded output"),
        ));
    }
    if !output.success {
        let stderr = sanitize_diagnostic(&output.stderr);
        let lower = stderr.to_ascii_lowercase();
        let kind = if lower.contains("not a git repository") {
            GitWorktreeErrorKind::NotRepository
        } else if lower.contains("already exists")
            || lower.contains("already checked out")
            || lower.contains("is already used by worktree")
        {
            GitWorktreeErrorKind::Conflict
        } else if lower.contains("locked working tree") {
            GitWorktreeErrorKind::Locked
        } else {
            GitWorktreeErrorKind::Failed
        };
        let message = if stderr.is_empty() {
            format!("{operation} failed")
        } else {
            format!("{operation} failed: {stderr}")
        };
        return Err(GitWorktreeError::new(kind, message));
    }
    Ok(output.stdout)
}

fn bounded_worktree_list(
    worktrees: Vec<NativeGitWorktreeSnapshot>,
) -> Result<Vec<NativeGitWorktreeSnapshot>, GitWorktreeError> {
    if worktrees.len() > GIT_WORKTREE_MAX_ENTRIES {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Failed,
            format!(
                "git worktree list exceeds the {GIT_WORKTREE_MAX_ENTRIES}-entry safety limit",
            ),
        ));
    }
    if worktrees.iter().any(|worktree| {
        worktree.path.is_empty()
            || worktree.path.len() > crate::protocol::MAX_WORKSPACE_ROOT_BYTES
            || worktree.path.as_bytes().contains(&0)
    }) {
        return Err(GitWorktreeError::new(
            GitWorktreeErrorKind::Failed,
            "git worktree list contains an invalid or oversized host path",
        ));
    }
    Ok(worktrees)
}

fn sanitize_diagnostic(output: &[u8]) -> String {
    String::from_utf8_lossy(output)
        .chars()
        .map(|character| if character.is_control() { ' ' } else { character })
        .collect::<String>()
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
}

fn io_error(error: io::Error) -> GitWorktreeError {
    GitWorktreeError::new(
        GitWorktreeErrorKind::Failed,
        format!("Git process failed: {error}"),
    )
}

fn parse_worktree_list_nul(output: &[u8]) -> Vec<NativeGitWorktreeSnapshot> {
    let mut records = Vec::new();
    let mut fields = Vec::new();
    for field in output.split(|byte| *byte == 0) {
        if field.is_empty() {
            if !fields.is_empty() {
                records.push(parse_worktree_record(&fields, records.is_empty(), false));
                fields.clear();
                if records.len() > GIT_WORKTREE_MAX_ENTRIES {
                    break;
                }
            }
        } else {
            fields.push(String::from_utf8_lossy(field).into_owned());
        }
    }
    if !fields.is_empty() {
        records.push(parse_worktree_record(&fields, records.is_empty(), false));
    }
    records.into_iter().flatten().collect()
}

fn parse_worktree_list_lines(output: &[u8]) -> Vec<NativeGitWorktreeSnapshot> {
    let text = String::from_utf8_lossy(output).replace("\r\n", "\n");
    text.split("\n\n")
        .take(GIT_WORKTREE_MAX_ENTRIES + 1)
        .filter_map(|block| {
            let fields = block
                .lines()
                .filter(|line| !line.is_empty())
                .map(str::to_owned)
                .collect::<Vec<_>>();
            parse_worktree_record(&fields, false, true)
        })
        .enumerate()
        .map(|(index, mut worktree)| {
            worktree.is_main = index == 0;
            worktree
        })
        .collect()
}

fn parse_worktree_record(
    fields: &[String],
    is_main: bool,
    decode_paths: bool,
) -> Option<NativeGitWorktreeSnapshot> {
    let mut path = None;
    let mut head = String::new();
    let mut branch = None;
    let mut is_bare = false;
    let mut locked = false;
    let mut lock_reason = None;
    let mut prunable = false;
    let mut prunable_reason = None;
    for field in fields {
        if let Some(value) = field.strip_prefix("worktree ") {
            path = Some(if decode_paths { decode_git_path(value) } else { value.to_owned() });
        } else if let Some(value) = field.strip_prefix("HEAD ") {
            head = value.to_owned();
        } else if let Some(value) = field.strip_prefix("branch ") {
            branch = Some(value.strip_prefix("refs/heads/").unwrap_or(value).to_owned());
        } else if field == "bare" {
            is_bare = true;
        } else if field == "locked" || field.starts_with("locked ") {
            locked = true;
            lock_reason = field.strip_prefix("locked ").map(|value| {
                if decode_paths { decode_git_path(value) } else { value.to_owned() }
            });
        } else if field == "prunable" || field.starts_with("prunable ") {
            prunable = true;
            prunable_reason = field.strip_prefix("prunable ").map(|value| {
                if decode_paths { decode_git_path(value) } else { value.to_owned() }
            });
        }
    }
    Some(NativeGitWorktreeSnapshot {
        path: path?,
        head,
        branch,
        is_bare,
        is_main,
        locked,
        lock_reason,
        prunable,
        prunable_reason,
        workspace_id: None,
    })
}

fn decode_git_path(value: &str) -> String {
    if !(value.starts_with('"') && value.ends_with('"') && value.len() >= 2) {
        return value.to_owned();
    }
    let bytes = value.as_bytes();
    let mut decoded = Vec::with_capacity(value.len() - 2);
    let mut index = 1;
    while index + 1 < bytes.len() {
        let byte = bytes[index];
        index += 1;
        if byte != b'\\' || index + 1 > bytes.len() {
            decoded.push(byte);
            continue;
        }
        let escaped = bytes[index];
        index += 1;
        match escaped {
            b'\\' | b'"' => decoded.push(escaped),
            b'n' => decoded.push(b'\n'),
            b'r' => decoded.push(b'\r'),
            b't' => decoded.push(b'\t'),
            b'b' => decoded.push(8),
            b'f' => decoded.push(12),
            b'v' => decoded.push(11),
            b'0'..=b'7' => {
                let mut value = (escaped - b'0') as u16;
                for _ in 0..2 {
                    let Some(next @ b'0'..=b'7') = bytes.get(index).copied() else { break };
                    value = value * 8 + (next - b'0') as u16;
                    index += 1;
                }
                decoded.push(value.min(255) as u8);
            }
            other => decoded.push(other),
        }
    }
    String::from_utf8_lossy(&decoded).into_owned()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU64, Ordering};

    static NEXT_GIT_TEMP: AtomicU64 = AtomicU64::new(1);

    #[test]
    fn nul_worktree_parser_preserves_paths_and_git_safety_flags() {
        let output = b"worktree C:/repo\0HEAD abc\0branch refs/heads/main\0\0worktree C:/trees/feature one\0HEAD def\0branch refs/heads/feature/one\0locked owner request\0\0worktree C:/gone\0HEAD 000\0detached\0prunable gitdir file points to non-existent location\0\0";
        let parsed = parse_worktree_list_nul(output);

        assert_eq!(parsed.len(), 3);
        assert!(parsed[0].is_main);
        assert_eq!(parsed[0].branch.as_deref(), Some("main"));
        assert_eq!(parsed[1].path, "C:/trees/feature one");
        assert_eq!(parsed[1].branch.as_deref(), Some("feature/one"));
        assert!(parsed[1].locked);
        assert_eq!(parsed[1].lock_reason.as_deref(), Some("owner request"));
        assert!(parsed[2].prunable);
        assert!(parsed[2].branch.is_none());
    }

    #[test]
    fn fallback_parser_decodes_c_quoted_paths_and_marks_only_first_main() {
        let output = b"worktree \"C:/repo/line\\nfeed\"\nHEAD abc\nbranch refs/heads/main\n\nworktree C:/tree\nHEAD def\nbranch refs/heads/topic\n\n";
        let parsed = parse_worktree_list_lines(output);

        assert_eq!(parsed.len(), 2);
        assert_eq!(parsed[0].path, "C:/repo/line\nfeed");
        assert!(parsed[0].is_main);
        assert!(!parsed[1].is_main);
    }

    #[cfg(windows)]
    #[test]
    fn windows_path_comparison_is_case_insensitive_and_separator_agnostic() {
        assert!(paths_equal(r"C:\Repo\Tree", "c:/repo/tree/"));
        assert!(path_contains(r"C:\Repo", "c:/repo/tree"));
    }

    #[cfg(unix)]
    #[test]
    fn unix_path_comparison_is_case_sensitive_and_treats_backslash_as_a_name_byte() {
        assert!(!paths_equal("/srv/Repo", "/srv/repo"));
        assert!(path_contains("/srv/Repo", "/srv/Repo/tree"));
        assert!(!path_contains("/srv/repo", "/srv/repo\\tree"));
    }

    #[test]
    fn removal_safety_protects_home_and_ancestors_but_not_home_children() {
        let repository_root = Path::new("D:/repository");
        let home = Path::new("C:/Users/operator");

        assert!(dangerous_path_with_home(home, repository_root, Some(home)));
        assert!(dangerous_path_with_home(
            Path::new("C:/Users"),
            repository_root,
            Some(home),
        ));
        assert!(!dangerous_path_with_home(
            Path::new("C:/Users/operator/worktree"),
            repository_root,
            Some(home),
        ));
    }

    #[test]
    fn oversized_worktree_path_is_rejected_before_wire_conversion() {
        let oversized = "x".repeat(crate::protocol::MAX_WORKSPACE_ROOT_BYTES + 1);
        let error = bounded_worktree_list(vec![worktree(&oversized, true)]).unwrap_err();
        assert_eq!(error.kind, GitWorktreeErrorKind::Failed);
        assert_eq!(
            error.message,
            "git worktree list contains an invalid or oversized host path",
        );
    }

    #[test]
    fn removal_safety_rejects_main_locked_prunable_and_nested_worktrees() {
        let main = worktree("C:/repo", true);
        let mut locked = worktree("C:/trees/locked", false);
        locked.locked = true;
        let mut prunable = worktree("C:/trees/gone", false);
        prunable.prunable = true;
        let parent = worktree("C:/trees/parent", false);
        let nested = worktree("C:/trees/parent/nested", false);

        assert_eq!(
            validate_removal_target("C:/repo", &main, &[main.clone()]).unwrap_err().kind,
            GitWorktreeErrorKind::Protected,
        );
        assert_eq!(
            validate_removal_target("C:/repo", &locked, &[main.clone(), locked.clone()]).unwrap_err().kind,
            GitWorktreeErrorKind::Locked,
        );
        assert_eq!(
            validate_removal_target("C:/repo", &prunable, &[main.clone(), prunable.clone()]).unwrap_err().kind,
            GitWorktreeErrorKind::Protected,
        );
        assert_eq!(
            validate_removal_target("C:/repo", &parent, &[main, parent.clone(), nested]).unwrap_err().kind,
            GitWorktreeErrorKind::Protected,
        );
    }

    fn worktree(path: &str, is_main: bool) -> NativeGitWorktreeSnapshot {
        NativeGitWorktreeSnapshot {
            path: path.to_owned(),
            head: "abc".to_owned(),
            branch: Some("topic".to_owned()),
            is_bare: false,
            is_main,
            locked: false,
            lock_reason: None,
            prunable: false,
            prunable_reason: None,
            workspace_id: None,
        }
    }

    #[tokio::test]
    async fn managed_git_roundtrip_removes_clean_advanced_worktree_without_deleting_branch() {
        let sequence = NEXT_GIT_TEMP.fetch_add(1, Ordering::Relaxed);
        let parent = std::env::temp_dir().join(format!(
            "gate4agent-managed-git-{}-{sequence}",
            std::process::id(),
        ));
        if parent.exists() {
            std::fs::remove_dir_all(&parent).unwrap();
        }
        let source = parent.join("source");
        let allocation = parent.join("allocation");
        let target = allocation.join("mw-test");
        std::fs::create_dir_all(&source).unwrap();
        std::fs::create_dir_all(&allocation).unwrap();
        run_git(&source, &["init"]);
        run_git(&source, &["config", "user.email", "gate4agent@example.invalid"]);
        run_git(&source, &["config", "user.name", "Gate4Agent Test"]);
        std::fs::write(source.join("seed.txt"), "seed\n").unwrap();
        run_git(&source, &["add", "seed.txt"]);
        run_git(&source, &["commit", "-m", "seed"]);
        let source_text = source.to_string_lossy().into_owned();
        let target_text = target.to_string_lossy().into_owned();
        let created = create_worktree(
            &source_text,
            &target_text,
            "gate4agent/mw-test",
            Some("HEAD"),
        ).await.unwrap();
        let created_target = PathBuf::from(&created.path);
        assert!(created_target.is_dir());
        std::fs::write(created_target.join("advanced.txt"), "advanced\n").unwrap();
        run_git(&created_target, &["add", "advanced.txt"]);
        run_git(&created_target, &["commit", "-m", "advanced"]);
        remove_worktree(&source_text, &created.path).await.unwrap();
        assert!(!created_target.exists());
        let status = std::process::Command::new("git")
            .arg("-C").arg(&source)
            .args(["show-ref", "--verify", "--quiet", "refs/heads/gate4agent/mw-test"])
            .status().unwrap();
        assert!(status.success(), "cleanup must not delete the managed branch");
        std::fs::remove_dir_all(parent).unwrap();
    }

    #[tokio::test]
    async fn aborting_bounded_child_prevents_late_mutation() {
        let sequence = NEXT_GIT_TEMP.fetch_add(1, Ordering::Relaxed);
        let parent = std::env::temp_dir().join(format!(
            "gate4agent-child-cancel-{}-{sequence}",
            std::process::id(),
        ));
        if parent.exists() {
            std::fs::remove_dir_all(&parent).unwrap();
        }
        std::fs::create_dir_all(&parent).unwrap();
        let marker = parent.join("late-mutation");

        #[cfg(windows)]
        let mut command = {
            let escaped = marker.to_string_lossy().replace('\'', "''");
            let mut command = tokio::process::Command::new("powershell.exe");
            command.args([
                "-NoLogo",
                "-NoProfile",
                "-NonInteractive",
                "-Command",
                &format!("Start-Sleep -Milliseconds 750; Set-Content -LiteralPath '{escaped}' -Value late"),
            ]);
            command
        };
        #[cfg(unix)]
        let mut command = {
            let escaped = marker.to_string_lossy().replace('\'', "'\\''");
            let mut command = tokio::process::Command::new("sh");
            command.args(["-c", &format!("sleep 0.75; printf late > '{escaped}'")]);
            command
        };
        command
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        let task = tokio::spawn(collect_child_output(command, 1_024, 5_000));
        tokio::time::sleep(Duration::from_millis(100)).await;
        task.abort();
        let _ = task.await;
        tokio::time::sleep(Duration::from_millis(1_000)).await;

        assert!(!marker.exists(), "cancelled child performed a late mutation");
        std::fs::remove_dir_all(parent).unwrap();
    }

    fn run_git(root: &Path, arguments: &[&str]) {
        let output = std::process::Command::new("git")
            .arg("-C").arg(root).args(arguments).output().unwrap();
        assert!(
            output.status.success(),
            "git {:?} failed: {}",
            arguments,
            String::from_utf8_lossy(&output.stderr),
        );
    }
}