orch-cli 0.88.1

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
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
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
//! Git worktree management for task execution.
//!
//! Each task runs in an isolated worktree to prevent conflicts.
//! Worktrees are stored at `~/.orch/worktrees/<project>/<branch>/`.

use crate::cmd::CommandErrorContext;
use crate::store;
use crate::store::TaskStore;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use tokio::process::Command;

/// Result of worktree setup.
pub struct WorktreeSetup {
    /// The directory where the agent will work
    pub work_dir: PathBuf,
    /// The branch name
    pub branch: String,
    /// The default branch of the repository
    pub default_branch: String,
    /// The main project directory (original, not worktree)
    pub main_project_dir: PathBuf,
}

/// Canonical project name used under `~/.orch/worktrees/`.
pub fn project_name(project_dir: &Path) -> String {
    project_dir
        .file_name()
        .map(|s| s.to_string_lossy().to_string())
        .unwrap_or_else(|| "project".to_string())
        .trim_end_matches(".git")
        .to_string()
}

/// Base worktrees directory for a project.
pub fn project_worktrees_dir(project_dir: &Path) -> PathBuf {
    crate::home::worktrees_dir()
        .unwrap_or_default()
        .join(project_name(project_dir))
}

/// List all worktree directories for a project.
pub async fn list_project_worktrees(project_dir: &Path) -> anyhow::Result<Vec<PathBuf>> {
    let base = project_worktrees_dir(project_dir);
    let mut worktrees = Vec::new();

    if tokio::fs::metadata(&base).await.is_err() {
        return Ok(worktrees);
    }

    let mut entries = tokio::fs::read_dir(&base).await?;
    while let Some(entry) = entries.next_entry().await? {
        if entry.metadata().await.map(|m| m.is_dir()).unwrap_or(false) {
            worktrees.push(entry.path());
        }
    }

    Ok(worktrees)
}

/// Extract a task ID from a worktree directory name.
pub fn task_id_from_worktree_name(name: &str) -> Option<String> {
    if let Some(rest) = name.strip_prefix("internal-") {
        let num = rest.split('-').next()?;
        return num.parse::<u64>().ok().map(|n| format!("internal:{n}"));
    }

    for prefix in ["gh-issue-", "gh-task-"] {
        if let Some(rest) = name.strip_prefix(prefix) {
            let task_part = rest.split('-').next()?;
            if task_part == "internal" {
                let num = rest.split('-').nth(1)?;
                return num.parse::<u64>().ok().map(|n| format!("internal:{n}"));
            }
            return Some(task_part.to_string());
        }
    }

    None
}

/// Abort any rebase in progress for a worktree.
pub async fn abort_worktree_rebase(worktree_dir: &Path) {
    let _ = Command::new("git")
        .args(["rebase", "--abort"])
        .current_dir(worktree_dir)
        .output_with_context()
        .await;
}

/// Rebase a worktree on top of `origin/{default_branch}`.
///
/// Stashes any uncommitted changes before rebasing to avoid failing the
/// rebase due to "You have unstaged changes".  The stash is restored after
/// the rebase succeeds; on failure the stash is preserved for manual recovery.
pub async fn rebase_worktree_on_origin_main(
    worktree_dir: &Path,
    default_branch: &str,
) -> anyhow::Result<()> {
    let origin_branch = format!("origin/{default_branch}");

    match crate::engine::runner::git_ops::stash_rebase_restore(
        worktree_dir,
        &origin_branch,
        crate::engine::runner::git_ops::StashRebaseOpts::default(),
    )
    .await?
    {
        crate::engine::runner::git_ops::RebaseOutcome::Succeeded => Ok(()),
        crate::engine::runner::git_ops::RebaseOutcome::Failed(e) => {
            anyhow::bail!("git rebase {} failed: {}", origin_branch, e)
        }
        crate::engine::runner::git_ops::RebaseOutcome::Skipped(_) => Ok(()),
    }
}

/// Generate a branch name from task ID and title.
///
/// Format: `internal-{id}-{slug}` for internal tasks, `gh-issue-{id}-{slug}` for external.
/// Slug is lowercase, non-alphanum→`-`, max 40 chars.
pub fn branch_name(task_id: &str, title: &str) -> String {
    let (prefix, sanitized_id) = if let Some(num) = task_id.strip_prefix("internal:") {
        ("internal", num.to_string())
    } else {
        ("gh-issue", sanitize_task_id(task_id))
    };

    let raw: String = title
        .to_lowercase()
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
        .collect();

    // Collapse consecutive dashes and trim
    let mut slug = String::with_capacity(raw.len());
    let mut prev_dash = false;
    for c in raw.chars() {
        if c == '-' {
            if !prev_dash {
                slug.push('-');
            }
            prev_dash = true;
        } else {
            slug.push(c);
            prev_dash = false;
        }
    }
    let slug = slug.trim_matches('-').to_string();

    // Truncate slug to 40 chars
    let slug = if slug.len() > 40 { &slug[..40] } else { &slug };
    let slug = slug.trim_end_matches('-');

    if slug.is_empty() {
        format!("{prefix}-{sanitized_id}")
    } else {
        format!("{prefix}-{sanitized_id}-{slug}")
    }
}

/// Replace characters in `task_id` that are not safe for branch/worktree names.
fn sanitize_task_id(task_id: &str) -> String {
    task_id.replace(':', "-")
}

/// Normalize a git ref output to a plain branch name.
///
/// Handles the various output formats that different git versions and
/// configurations can produce for remote HEAD refs:
/// - `origin/main` → `main`
/// - `refs/remotes/origin/main` → `main`
/// - `remotes/origin/main` → `main`
/// - `main` → `main`
fn normalize_branch_name(raw: &str) -> Option<String> {
    let branch = raw.trim();
    if branch.is_empty() {
        return None;
    }

    // Strip known prefixes in order of specificity.
    let cleaned = branch
        .strip_prefix("refs/remotes/origin/")
        .or_else(|| branch.strip_prefix("remotes/origin/"))
        .or_else(|| branch.strip_prefix("refs/heads/"))
        .or_else(|| branch.strip_prefix("origin/"))
        .unwrap_or(branch);

    if cleaned.is_empty() {
        return None;
    }
    Some(cleaned.to_string())
}

/// Detect the default branch of a repository.
///
/// Tries multiple strategies and normalizes the result so callers always
/// receive a clean branch name like `"main"`, never a raw ref path.
pub async fn detect_default_branch(project_dir: &Path) -> String {
    // Strategy 1: symbolic-ref (fast, works when origin/HEAD is set).
    let symref = Command::new("git")
        .args(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"])
        .current_dir(project_dir)
        .output_with_context()
        .await;

    if let Ok(o) = &symref {
        if o.status.success() {
            let raw = String::from_utf8_lossy(&o.stdout);
            if let Some(branch) = normalize_branch_name(&raw) {
                return branch;
            }
        }
    }

    // Strategy 2: rev-parse --abbrev-ref (resolves symref to target).
    let revparse = Command::new("git")
        .args(["rev-parse", "--abbrev-ref", "refs/remotes/origin/HEAD"])
        .current_dir(project_dir)
        .output_with_context()
        .await;

    if let Ok(o) = &revparse {
        if o.status.success() {
            let raw = String::from_utf8_lossy(&o.stdout);
            if let Some(branch) = normalize_branch_name(&raw) {
                return branch;
            }
        }
    }

    // Strategy 3: parse `git remote show origin` output.
    let remote_show = Command::new("git")
        .args(["remote", "show", "origin"])
        .current_dir(project_dir)
        .output_with_context()
        .await;

    if let Ok(o) = &remote_show {
        if o.status.success() {
            let stdout = String::from_utf8_lossy(&o.stdout);
            for line in stdout.lines() {
                let trimmed = line.trim();
                if trimmed.starts_with("HEAD branch:") {
                    if let Some(branch) = trimmed.split(':').nth(1) {
                        let branch = branch.trim();
                        if !branch.is_empty() && branch != "(unknown)" {
                            return branch.to_string();
                        }
                    }
                }
            }
        }
    }

    tracing::warn!(
        project_dir = %project_dir.display(),
        "could not detect default branch from git, falling back to 'main'"
    );
    "main".to_string()
}

/// Resolve PROJECT_DIR to the main repo if it's inside a worktree.
///
/// This prevents nested worktrees when subtasks inherit a parent's worktree dir.
pub async fn resolve_main_repo(project_dir: &Path) -> PathBuf {
    let output = Command::new("git")
        .args(["worktree", "list", "--porcelain"])
        .current_dir(project_dir)
        .output_with_context()
        .await;

    if let Ok(o) = output {
        if o.status.success() {
            let stdout = String::from_utf8_lossy(&o.stdout);
            if let Some(first_line) = stdout.lines().next() {
                if let Some(path) = first_line.strip_prefix("worktree ") {
                    let main_path = PathBuf::from(path);
                    if main_path != project_dir {
                        tracing::info!(
                            worktree = %project_dir.display(),
                            main = %main_path.display(),
                            "resolved worktree to main repo"
                        );
                        return main_path;
                    }
                }
            }
        }
    }

    project_dir.to_path_buf()
}

/// Resolve the starting point for creating a new local branch.
///
/// Preference order:
/// 1. `origin/<branch>` if it exists — cleanup kept the remote branch after
///    deleting the local one, so resume from the agent's committed work.
/// 2. `origin/<default_branch>` if it exists — anchors on the pushed tip of
///    the default branch so unpushed local commits in the operator's main
///    checkout don't leak into the worktree.
/// 3. `default_branch` as a last resort (no origin remote / never fetched).
pub(super) async fn resolve_branch_start_point(
    repo_root: &str,
    branch: &str,
    default_branch: &str,
) -> String {
    let verify = |reference: String| async move {
        Command::new("git")
            .args(["-C", repo_root, "rev-parse", "--verify", &reference])
            .output_with_context()
            .await
            .map(|o| o.status.success())
            .unwrap_or(false)
    };

    let origin_branch_ref = format!("origin/{branch}");
    if verify(origin_branch_ref.clone()).await {
        return origin_branch_ref;
    }

    let origin_default_ref = format!("origin/{default_branch}");
    if verify(origin_default_ref.clone()).await {
        return origin_default_ref;
    }

    default_branch.to_string()
}

/// Validate that a worktree directory has a working gitdir link.
///
/// In a git worktree, `.git` is a file containing `gitdir: /path/to/.git/worktrees/<name>`.
/// Returns `false` when the `.git` file is missing or points to a non-existent gitdir,
/// indicating the worktree metadata is broken and the directory should be cleaned up.
pub async fn validate_worktree_gitdir(worktree_dir: &Path) -> bool {
    let git_file = worktree_dir.join(".git");
    // Use tokio::fs::metadata for async-safe existence check
    if tokio::fs::metadata(&git_file).await.is_err() {
        return false;
    }
    // In a linked worktree .git is a file; in the main repo it's a directory (always valid).
    if tokio::fs::metadata(&git_file)
        .await
        .map(|m| m.is_dir())
        .unwrap_or(false)
    {
        return true;
    }

    let content = match tokio::fs::read_to_string(&git_file).await {
        Ok(c) => c,
        Err(_) => return false,
    };
    // Expected format: "gitdir: /absolute/path/to/.git/worktrees/<name>\n"
    // Use spawn_blocking for the final exists check on the resolved path
    if let Some(gitdir_path) = content
        .lines()
        .next()
        .and_then(|l| l.strip_prefix("gitdir: "))
    {
        // Use async metadata for the gitdir check too.
        return tokio::fs::metadata(gitdir_path.trim())
            .await
            .map(|m| m.is_dir())
            .unwrap_or(false);
    }
    false
}

/// Resolve the branch and worktree directory from a parent task, if available.
///
/// When a child task is created from a mention on a PR, it should work on the
/// parent task's branch so changes are committed to the existing PR rather than
/// a new one being opened.
async fn resolve_parent_branch(
    store: &Option<Arc<TaskStore>>,
    parent_id: Option<i64>,
    worktrees_base: &Path,
) -> Option<(String, PathBuf)> {
    let parent_id = parent_id?;
    let parent = store::opt_store_get_task_by_id(store, parent_id).await?;
    if parent.branch.is_empty() {
        return None;
    }
    let wt = if !parent.worktree.is_empty() {
        // Use async metadata to avoid blocking the reactor thread.
        let exists = tokio::fs::metadata(&parent.worktree)
            .await
            .map(|m| m.is_dir())
            .unwrap_or(false);
        if exists {
            PathBuf::from(&parent.worktree)
        } else {
            worktrees_base.join(&parent.branch)
        }
    } else {
        worktrees_base.join(&parent.branch)
    };
    tracing::info!(
        parent_id,
        branch = %parent.branch,
        worktree = %wt.display(),
        "child task inheriting parent branch"
    );
    Some((parent.branch, wt))
}

/// Set up a worktree for task execution.
///
/// Returns the working directory, branch name, and default branch.
pub async fn setup_worktree(
    task_id: &str,
    title: &str,
    project_dir: &Path,
    store: &Option<Arc<TaskStore>>,
    repo: &str,
) -> anyhow::Result<WorktreeSetup> {
    // Resolve to main repo (avoid nested worktrees)
    let main_dir = resolve_main_repo(project_dir).await;
    let default_branch = detect_default_branch(&main_dir).await;

    let worktrees_base = project_worktrees_dir(&main_dir);
    tokio::fs::create_dir_all(&worktrees_base).await?;

    // Check if we have a saved branch/worktree in store
    let task_record = store::opt_store_get_task(store, repo, task_id).await;
    let (saved_branch, saved_worktree, parent_id) = task_record
        .as_ref()
        .map(|t| {
            (
                Some(t.branch.clone()),
                Some(t.worktree.clone()),
                t.parent_id,
            )
        })
        .unwrap_or((None, None, None));

    let (branch_name_str, worktree_dir) = if let Some(ref saved) = saved_branch {
        if !saved.is_empty() {
            // Use spawn_blocking for blocking Path::exists call in async context
            let wt = match &saved_worktree {
                Some(wt) if !wt.is_empty() => {
                    let wt_str = wt.clone();
                    let exists = tokio::task::spawn_blocking(move || Path::new(&wt_str).exists())
                        .await
                        .unwrap_or(false);
                    if exists {
                        PathBuf::from(wt)
                    } else {
                        worktrees_base.join(saved)
                    }
                }
                _ => worktrees_base.join(saved),
            };
            (saved.clone(), wt)
        } else if let Some((parent_branch, parent_wt)) =
            resolve_parent_branch(store, parent_id, &worktrees_base).await
        {
            // Child task with no saved branch: inherit parent's branch so we
            // commit onto the existing PR instead of opening a new one.
            (parent_branch, parent_wt)
        } else {
            let bn = branch_name(task_id, title);
            (bn.clone(), worktrees_base.join(&bn))
        }
    } else {
        // No store record — check parent branch, then existing worktree by prefix
        if let Some((parent_branch, parent_wt)) =
            resolve_parent_branch(store, parent_id, &worktrees_base).await
        {
            (parent_branch, parent_wt)
        } else {
            let existing = find_existing_worktree(&worktrees_base, task_id).await;
            if let Some(existing_dir) = existing {
                let bn = existing_dir
                    .file_name()
                    .filter(|n| !n.is_empty())
                    .map(|n| n.to_string_lossy().to_string())
                    .unwrap_or_else(|| branch_name(task_id, title));
                tracing::info!(task_id, worktree = %existing_dir.display(), "found existing worktree");
                (bn, existing_dir)
            } else {
                let bn = branch_name(task_id, title);
                (bn.clone(), worktrees_base.join(&bn))
            }
        }
    };

    if branch_name_str.is_empty() {
        anyhow::bail!("empty branch name for task {task_id}");
    }

    // Abort any in-progress rebase in an existing worktree.
    //
    // Agents can leave a worktree stuck mid-rebase (e.g. after running
    // `git rebase -i` interactively).  The next dispatch attempt would
    // inherit that broken state, causing all subsequent git operations to
    // fail.  Aborting here is safe: if no rebase is in progress git exits
    // with a non-zero code which we silently ignore.
    // Use tokio::fs for async-safe existence check
    if tokio::fs::metadata(&worktree_dir).await.is_ok() {
        let _ = Command::new("git")
            .args(["rebase", "--abort"])
            .current_dir(&worktree_dir)
            .output_with_context()
            .await;

        // Check for a corrupted git index (e.g. "error: could not write index").
        // `git status` reads the index; a non-zero exit with index-related stderr
        // indicates corruption that will cause every subsequent git operation to
        // fail, leading to an infinite stuck-recovery loop.  When detected, nuke
        // the worktree and recreate it from scratch below.
        let index_ok = Command::new("git")
            .args(["status", "--porcelain"])
            .current_dir(&worktree_dir)
            .output_with_context()
            .await
            .map(|o| o.status.success())
            .unwrap_or(false);

        if !index_ok {
            let stderr_hint = Command::new("git")
                .args(["status", "--porcelain"])
                .current_dir(&worktree_dir)
                .output_with_context()
                .await
                .map(|o| String::from_utf8_lossy(&o.stderr).trim().to_string())
                .unwrap_or_default();
            tracing::warn!(
                task_id,
                worktree = %worktree_dir.display(),
                stderr = %stderr_hint,
                "corrupted worktree index detected — removing and recreating worktree"
            );
            // Remove git worktree reference first, then delete the directory.
            let _ = Command::new("git")
                .args([
                    "-C",
                    &main_dir.to_string_lossy(),
                    "worktree",
                    "remove",
                    "--force",
                    &worktree_dir.to_string_lossy(),
                ])
                .output_with_context()
                .await;
            // If the directory still exists (e.g. worktree remove failed), remove it
            // manually so the worktree-creation block below re-creates it cleanly.
            if tokio::fs::metadata(&worktree_dir).await.is_ok() {
                let _ = tokio::fs::remove_dir_all(&worktree_dir).await;
            }
            // Prune stale worktree metadata so git won't complain on re-add.
            let _ = Command::new("git")
                .args(["-C", &main_dir.to_string_lossy(), "worktree", "prune"])
                .output_with_context()
                .await;
        }
    }

    // Create worktree if it doesn't exist
    if tokio::fs::metadata(&worktree_dir).await.is_err() {
        tracing::info!(task_id, worktree = %worktree_dir.display(), "creating worktree");

        // Fetch latest so `origin/<default_branch>` (and any pre-existing
        // remote task branch) is fresh. We deliberately do NOT `git pull` on
        // the operator's checkout: branching from `origin/<default_branch>`
        // means unpushed local commits or in-progress work on `main` never
        // leak into the new worktree.
        let _ = Command::new("git")
            .args([
                "-C",
                &main_dir.to_string_lossy(),
                "fetch",
                "--prune",
                "origin",
            ])
            .output_with_context()
            .await;

        // Create local branch. Prefer `origin/<branch>` when it already exists
        // (recovery case: cleanup deleted local branch but kept the remote),
        // so the new worktree starts from the agent's committed work instead
        // of the default branch tip.
        let start_point = resolve_branch_start_point(
            &main_dir.to_string_lossy(),
            &branch_name_str,
            &default_branch,
        )
        .await;
        let _ = Command::new("git")
            .args([
                "-C",
                &main_dir.to_string_lossy(),
                "branch",
                &branch_name_str,
                &start_point,
            ])
            .output_with_context()
            .await;

        // Create worktree
        if let Some(parent) = worktree_dir.parent() {
            tokio::fs::create_dir_all(parent).await?;
        }

        let cloned = match super::cow::create_worktree(
            &main_dir,
            &project_name(&main_dir),
            &worktree_dir,
            &branch_name_str,
            &default_branch,
        )
        .await
        {
            Ok(()) => {
                tracing::info!(task_id, "worktree cloned from project template");
                true
            }
            Err(e) => {
                tracing::debug!(task_id, error = %e, "copy-on-write worktree unavailable, using git worktree add");
                false
            }
        };

        if !cloned {
            let output = Command::new("git")
                .args([
                    "-C",
                    &main_dir.to_string_lossy(),
                    "worktree",
                    "add",
                    &worktree_dir.to_string_lossy(),
                    &branch_name_str,
                ])
                .output_with_context()
                .await?;

            if !output.status.success() && tokio::fs::metadata(&worktree_dir).await.is_err() {
                let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
                let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
                // Retry: prune and recreate
                tracing::warn!(
                    task_id,
                    stdout = %stdout,
                    stderr = %stderr,
                    "worktree creation failed, retrying after prune"
                );

                let _ = Command::new("git")
                    .args(["-C", &main_dir.to_string_lossy(), "worktree", "prune"])
                    .output_with_context()
                    .await;

                let _ = Command::new("git")
                    .args([
                        "-C",
                        &main_dir.to_string_lossy(),
                        "branch",
                        "-D",
                        &branch_name_str,
                    ])
                    .output_with_context()
                    .await;

                let _ = Command::new("git")
                    .args([
                        "-C",
                        &main_dir.to_string_lossy(),
                        "branch",
                        &branch_name_str,
                        &start_point,
                    ])
                    .output_with_context()
                    .await;

                let retry_output = Command::new("git")
                    .args([
                        "-C",
                        &main_dir.to_string_lossy(),
                        "worktree",
                        "add",
                        &worktree_dir.to_string_lossy(),
                        &branch_name_str,
                    ])
                    .output_with_context()
                    .await;

                let mut retry_stdout = String::new();
                let mut retry_stderr = String::new();
                let mut retry_error = String::new();
                match retry_output {
                    Ok(output) => {
                        retry_stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
                        retry_stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
                        tracing::warn!(
                            task_id,
                            stdout = %retry_stdout,
                            stderr = %retry_stderr,
                            "worktree creation retry failed"
                        );
                    }
                    Err(err) => {
                        retry_error = err.to_string();
                        tracing::warn!(
                            task_id,
                            error = %retry_error,
                            "worktree creation retry failed to run"
                        );
                    }
                }

                if tokio::fs::metadata(&worktree_dir).await.is_err() {
                    anyhow::bail!(
                    "failed to create worktree at {} for task {} (stdout: {}, stderr: {}, retry stdout: {}, retry stderr: {}, retry error: {})",
                    worktree_dir.display(),
                    task_id,
                    stdout,
                    stderr,
                    retry_stdout,
                    retry_stderr,
                    retry_error
                );
                }
            }
        }
    }

    // Link issue to branch via GitHub API (Development sidebar).
    // Must happen before the agent pushes — createLinkedBranch only works
    // for branches that don't yet exist on GitHub.
    if !task_id.starts_with("internal:") {
        if let Ok(issue_num) = task_id.parse::<u64>() {
            if let Ok(gh) = crate::github::http::GhHttp::new() {
                match gh
                    .link_issue_to_branch(repo, issue_num, &branch_name_str)
                    .await
                {
                    Ok(id) => {
                        tracing::info!(task_id, branch = %branch_name_str, linked = %id, "linked issue to branch");
                    }
                    Err(e) => {
                        tracing::debug!(task_id, error = %e, "failed to link issue to branch (non-fatal)");
                    }
                }
            }
        }
    }

    // Save worktree info to store
    if let Err(e) = store::store_set_result(
        store,
        repo,
        task_id,
        &[
            (
                "worktree",
                serde_json::json!(worktree_dir.display().to_string()),
            ),
            ("branch", serde_json::json!(branch_name_str)),
        ],
    )
    .await
    {
        tracing::warn!(task_id, err = %e, "failed to save worktree info to store (non-fatal)");
    }

    tracing::info!(
        task_id,
        worktree = %worktree_dir.display(),
        branch = %branch_name_str,
        "worktree ready"
    );

    Ok(WorktreeSetup {
        work_dir: worktree_dir,
        branch: branch_name_str,
        default_branch,
        main_project_dir: main_dir,
    })
}

/// Find an existing worktree by task ID prefix.
async fn find_existing_worktree(worktrees_base: &Path, task_id: &str) -> Option<PathBuf> {
    let (prefix_new, legacy_prefixes) = if let Some(num) = task_id.strip_prefix("internal:") {
        (
            format!("internal-{num}-"),
            vec![
                format!("gh-task-internal-{num}-"),
                format!("gh-issue-internal-{num}-"),
            ],
        )
    } else {
        let sanitized_id = sanitize_task_id(task_id);
        (
            format!("gh-issue-{sanitized_id}-"),
            vec![format!("gh-task-{sanitized_id}-")],
        )
    };

    let mut entries = match tokio::fs::read_dir(worktrees_base).await {
        Ok(e) => e,
        Err(e) => {
            tracing::warn!(
                error = %e,
                path = %worktrees_base.display(),
                "failed to read worktrees directory while searching for existing worktree"
            );
            return None;
        }
    };
    loop {
        let next_entry = match entries.next_entry().await {
            Ok(Some(entry)) => entry,
            Ok(None) => break,
            Err(e) => {
                // Log the error but continue scanning - a single entry error shouldn't stop us
                tracing::warn!(error = %e, "failed to read directory entry while searching for worktree");
                continue;
            }
        };

        let name = next_entry.file_name().to_string_lossy().to_string();
        let matches =
            name.starts_with(&prefix_new) || legacy_prefixes.iter().any(|p| name.starts_with(p));
        if matches {
            match next_entry.metadata().await {
                Ok(metadata) if metadata.is_dir() => return Some(next_entry.path()),
                Ok(_) => {}
                Err(e) => {
                    tracing::warn!(
                        error = %e,
                        path = %next_entry.path().display(),
                        "failed to read metadata for candidate worktree entry"
                    );
                }
            }
        }
    }

    None
}

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

    /// Helper: run a git command in `dir`, panicking on failure.
    fn git(dir: &std::path::Path, args: &[&str]) {
        let mut cmd = std::process::Command::new("git");
        cmd.current_dir(dir);
        // Global commit.gpgsign calls the operator's signer (1Password)
        if args.first() == Some(&"commit") {
            cmd.args(["-c", "commit.gpgsign=false"]);
        }
        let out = cmd
            .args(args)
            .output()
            .unwrap_or_else(|e| panic!("git {:?} failed to start: {e}", args));
        if !out.status.success() {
            panic!(
                "git {:?} failed:\nstdout: {}\nstderr: {}",
                args,
                String::from_utf8_lossy(&out.stdout),
                String::from_utf8_lossy(&out.stderr)
            );
        }
    }

    /// When `origin/<branch>` exists, `resolve_branch_start_point` should
    /// return `"origin/<branch>"` so that the worktree starts from the
    /// already-committed work, not from the default branch tip.
    #[tokio::test]
    async fn resolve_branch_start_point_prefers_remote_over_default() {
        let remote = tempfile::tempdir().unwrap();
        git(remote.path(), &["init", "--bare"]);

        // Set up a working clone to push branches to the remote.
        let setup = tempfile::tempdir().unwrap();
        git(
            setup.path(),
            &["clone", remote.path().to_str().unwrap(), "."],
        );
        git(setup.path(), &["config", "user.email", "t@t.com"]);
        git(setup.path(), &["config", "user.name", "T"]);

        // Initial commit on main.
        std::fs::write(setup.path().join("README.md"), "main").unwrap();
        git(setup.path(), &["add", "."]);
        git(setup.path(), &["commit", "-m", "init"]);
        git(setup.path(), &["push", "origin", "HEAD:main"]);

        // Feature branch with a distinct commit.
        git(
            setup.path(),
            &["checkout", "-b", "gh-issue-42-fix-login-bug"],
        );
        std::fs::write(setup.path().join("feature.txt"), "work").unwrap();
        git(setup.path(), &["add", "."]);
        git(setup.path(), &["commit", "-m", "feature work"]);
        git(
            setup.path(),
            &["push", "origin", "gh-issue-42-fix-login-bug"],
        );

        // Local repo: clone + fetch, but NO local branch (simulates cleanup
        // with keep_remote_branch=true where local branch was deleted).
        let local = tempfile::tempdir().unwrap();
        git(
            local.path(),
            &["clone", remote.path().to_str().unwrap(), "."],
        );
        git(local.path(), &["config", "user.email", "t@t.com"]);
        git(local.path(), &["config", "user.name", "T"]);
        git(local.path(), &["fetch", "--all"]);
        // Confirm the local branch does NOT exist; only the remote tracking ref.
        let has_local = std::process::Command::new("git")
            .args([
                "-C",
                local.path().to_str().unwrap(),
                "rev-parse",
                "--verify",
                "gh-issue-42-fix-login-bug",
            ])
            .output()
            .unwrap()
            .status
            .success();
        assert!(!has_local, "local branch should not exist before the test");

        let repo_root = local.path().to_str().unwrap();

        // With remote branch present → should prefer origin/<branch>.
        let start =
            resolve_branch_start_point(repo_root, "gh-issue-42-fix-login-bug", "main").await;
        assert_eq!(
            start, "origin/gh-issue-42-fix-login-bug",
            "should use remote branch as start point when origin/<branch> exists"
        );
    }

    /// When `origin/<branch>` does NOT exist but `origin/<default_branch>` does,
    /// `resolve_branch_start_point` should anchor on the remote default branch
    /// so unpushed local commits on `main` don't leak into the worktree.
    #[tokio::test]
    async fn resolve_branch_start_point_prefers_origin_default_over_local() {
        let remote = tempfile::tempdir().unwrap();
        git(remote.path(), &["init", "--bare"]);

        let local = tempfile::tempdir().unwrap();
        git(
            local.path(),
            &["clone", remote.path().to_str().unwrap(), "."],
        );
        git(local.path(), &["config", "user.email", "t@t.com"]);
        git(local.path(), &["config", "user.name", "T"]);

        // Commit something so origin/main exists.
        std::fs::write(local.path().join("README.md"), "main").unwrap();
        git(local.path(), &["add", "."]);
        git(local.path(), &["commit", "-m", "init"]);
        git(local.path(), &["push", "origin", "HEAD:main"]);
        git(local.path(), &["fetch", "--all"]);

        let repo_root = local.path().to_str().unwrap();

        // Branch "no-such-branch" has never been pushed, but origin/main exists.
        let start = resolve_branch_start_point(repo_root, "no-such-branch", "main").await;
        assert_eq!(
            start, "origin/main",
            "should anchor on origin/<default_branch> instead of local default"
        );
    }

    /// Capture stdout of a git command in `dir`.
    fn git_stdout(dir: &std::path::Path, args: &[&str]) -> String {
        let out = std::process::Command::new("git")
            .args(args)
            .current_dir(dir)
            .output()
            .unwrap_or_else(|e| panic!("git {:?} failed to start: {e}", args));
        if !out.status.success() {
            panic!(
                "git {:?} failed:\nstdout: {}\nstderr: {}",
                args,
                String::from_utf8_lossy(&out.stdout),
                String::from_utf8_lossy(&out.stderr)
            );
        }
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    }

    /// End-to-end guard for the operator-main-leak fix: when the operator's
    /// local `main` has commits that are not yet pushed, `setup_worktree`
    /// must branch from `origin/main` and produce a worktree whose HEAD is
    /// the pushed tip — never the local-only tip.
    #[tokio::test]
    #[serial_test::serial(orch_home)]
    async fn setup_worktree_anchors_on_origin_not_local_main() {
        // Isolate ORCH_HOME so the worktree lands in a temp dir.
        let orch_home_dir = tempfile::tempdir().unwrap();
        let prev_orch_home = std::env::var("ORCH_HOME").ok();
        std::env::set_var("ORCH_HOME", orch_home_dir.path());

        // Bare "remote".
        let remote = tempfile::tempdir().unwrap();
        git(remote.path(), &["init", "--bare"]);

        // Operator's project clone.
        let project = tempfile::tempdir().unwrap();
        git(
            project.path(),
            &["clone", remote.path().to_str().unwrap(), "."],
        );
        git(project.path(), &["config", "user.email", "t@t.com"]);
        git(project.path(), &["config", "user.name", "T"]);

        // Pushed baseline on main.
        std::fs::write(project.path().join("README.md"), "pushed\n").unwrap();
        git(project.path(), &["add", "."]);
        git(project.path(), &["commit", "-m", "pushed baseline"]);
        git(project.path(), &["push", "origin", "HEAD:main"]);
        let pushed_sha = git_stdout(project.path(), &["rev-parse", "HEAD"]);

        // Ensure origin/HEAD is set so detect_default_branch resolves "main".
        git(project.path(), &["remote", "set-head", "origin", "main"]);

        // Operator's WIP: an unpushed local commit on top of main.
        std::fs::write(project.path().join("LOCAL_ONLY.md"), "unpushed\n").unwrap();
        git(project.path(), &["add", "."]);
        git(project.path(), &["commit", "-m", "local unpushed commit"]);
        let local_sha = git_stdout(project.path(), &["rev-parse", "HEAD"]);
        assert_ne!(
            pushed_sha, local_sha,
            "precondition: local main must be ahead of origin/main"
        );

        // Run setup_worktree for a fresh internal task (skips GitHub linking).
        let setup = setup_worktree(
            "internal:1",
            "leak guard",
            project.path(),
            &None,
            "test/repo",
        )
        .await
        .expect("setup_worktree should succeed");

        // Worktree must sit on the pushed tip, not the local-only tip.
        let wt_sha = git_stdout(&setup.work_dir, &["rev-parse", "HEAD"]);
        assert_eq!(
            wt_sha, pushed_sha,
            "worktree HEAD must equal origin/main, not local main"
        );
        assert_ne!(
            wt_sha, local_sha,
            "worktree must NOT include the operator's unpushed commit"
        );
        assert!(
            !setup.work_dir.join("LOCAL_ONLY.md").exists(),
            "unpushed-only file must not appear in the worktree"
        );

        // Restore ORCH_HOME.
        match prev_orch_home {
            Some(v) => std::env::set_var("ORCH_HOME", v),
            None => std::env::remove_var("ORCH_HOME"),
        }
    }

    /// When neither `origin/<branch>` nor `origin/<default_branch>` exist,
    /// fall back to the local default branch name as a last resort.
    #[tokio::test]
    async fn resolve_branch_start_point_falls_back_to_local_default() {
        let local = tempfile::tempdir().unwrap();
        git(local.path(), &["init"]);
        git(local.path(), &["config", "user.email", "t@t.com"]);
        git(local.path(), &["config", "user.name", "T"]);
        git(local.path(), &["checkout", "-b", "main"]);
        std::fs::write(local.path().join("README.md"), "main").unwrap();
        git(local.path(), &["add", "."]);
        git(local.path(), &["commit", "-m", "init"]);

        let repo_root = local.path().to_str().unwrap();

        // No remote at all → fall back to "main".
        let start = resolve_branch_start_point(repo_root, "no-such-branch", "main").await;
        assert_eq!(
            start, "main",
            "should fall back to local default_branch when no remote refs exist"
        );
    }

    #[test]
    fn branch_name_basic() {
        let name = branch_name("42", "Fix login bug");
        assert_eq!(name, "gh-issue-42-fix-login-bug");
    }

    #[test]
    fn branch_name_internal_task() {
        let name = branch_name("internal:8", "Fix login bug");
        assert_eq!(name, "internal-8-fix-login-bug");
    }

    #[test]
    fn branch_name_special_chars() {
        let name = branch_name("7", "Add OAuth2/OIDC (Google & GitHub)");
        assert_eq!(name, "gh-issue-7-add-oauth2-oidc-google-github");
    }

    #[test]
    fn branch_name_truncates_long_slug() {
        let title =
            "This is a very long task title that should be truncated to forty characters maximum";
        let name = branch_name("1", title);
        // slug part should be max 40 chars
        let slug = name.strip_prefix("gh-issue-1-").unwrap();
        assert!(slug.len() <= 40, "slug length {} > 40", slug.len());
    }

    #[test]
    fn branch_name_trims_trailing_dashes() {
        let name = branch_name("5", "Fix bug---");
        assert!(
            !name.ends_with('-'),
            "branch name should not end with dash: {name}"
        );
    }

    #[test]
    fn branch_name_empty_title() {
        let name = branch_name("99", "");
        assert_eq!(name, "gh-issue-99");
    }

    #[test]
    fn branch_name_empty_title_internal() {
        let name = branch_name("internal:99", "");
        assert_eq!(name, "internal-99");
    }

    #[test]
    fn branch_name_all_special_chars() {
        let name = branch_name("10", "--- ??? ---");
        assert_eq!(name, "gh-issue-10");
        assert!(!name.is_empty());
    }

    #[test]
    fn branch_name_chinese_chars_no_panic() {
        let name = branch_name("265", "implement 用户认证 user auth");
        assert!(name.starts_with("gh-issue-265-"));
        assert!(!name.is_empty());
        let slug = name.strip_prefix("gh-issue-265-").unwrap();
        assert!(slug.len() <= 40, "slug too long: {}", slug.len());
        assert!(slug.is_ascii(), "slug contains non-ASCII: {slug}");
    }

    #[test]
    fn task_id_from_worktree_name_parses_issue_branches() {
        assert_eq!(
            task_id_from_worktree_name("gh-issue-42-fix-login"),
            Some("42".to_string())
        );
        assert_eq!(
            task_id_from_worktree_name("gh-task-42-fix-login"),
            Some("42".to_string())
        );
    }

    #[test]
    fn task_id_from_worktree_name_parses_internal_branches() {
        assert_eq!(
            task_id_from_worktree_name("internal-8-fix-login"),
            Some("internal:8".to_string())
        );
        assert_eq!(
            task_id_from_worktree_name("gh-issue-internal-8-fix-login"),
            Some("internal:8".to_string())
        );
    }

    #[test]
    fn task_id_from_worktree_name_returns_none_for_unknown_names() {
        assert!(task_id_from_worktree_name("random-worktree").is_none());
    }

    #[test]
    fn branch_name_emoji_no_panic() {
        let name = branch_name("265", "fix 🚀 deployment pipeline 🔥");
        assert!(name.starts_with("gh-issue-265-"));
        let slug = name.strip_prefix("gh-issue-265-").unwrap();
        assert!(slug.is_ascii(), "slug contains non-ASCII: {slug}");
    }

    #[test]
    fn branch_name_all_non_ascii_falls_back_to_task_id() {
        let name = branch_name("265", "用户认证 실행 тест");
        assert_eq!(name, "gh-issue-265");
    }

    #[tokio::test]
    async fn find_existing_worktree_returns_none_for_missing() {
        let dir = tempfile::tempdir().unwrap();
        assert!(find_existing_worktree(dir.path(), "42").await.is_none());
    }

    #[tokio::test]
    async fn find_existing_worktree_matches_prefix() {
        let dir = tempfile::tempdir().unwrap();
        let wt_dir = dir.path().join("gh-issue-42-fix-login-bug");
        tokio::fs::create_dir(&wt_dir).await.unwrap();

        let result = find_existing_worktree(dir.path(), "42").await;
        assert_eq!(result, Some(wt_dir));
    }

    #[tokio::test]
    async fn find_existing_worktree_matches_internal_prefix() {
        let dir = tempfile::tempdir().unwrap();
        let wt_dir = dir.path().join("internal-8-fix");
        tokio::fs::create_dir(&wt_dir).await.unwrap();

        let result = find_existing_worktree(dir.path(), "internal:8").await;
        assert_eq!(result, Some(wt_dir));
    }

    #[tokio::test]
    async fn find_existing_worktree_matches_legacy_gh_task_prefix() {
        // Old worktrees created before the rename should still be found
        let dir = tempfile::tempdir().unwrap();
        let wt_dir = dir.path().join("gh-task-internal-8-fix");
        tokio::fs::create_dir(&wt_dir).await.unwrap();

        let result = find_existing_worktree(dir.path(), "internal:8").await;
        assert_eq!(result, Some(wt_dir));
    }

    #[tokio::test]
    async fn find_existing_worktree_matches_legacy_external_prefix() {
        // Old external worktrees with gh-task- prefix should still be found
        let dir = tempfile::tempdir().unwrap();
        let wt_dir = dir.path().join("gh-task-42-fix-login-bug");
        tokio::fs::create_dir(&wt_dir).await.unwrap();

        let result = find_existing_worktree(dir.path(), "42").await;
        assert_eq!(result, Some(wt_dir));
    }

    #[tokio::test]
    async fn find_existing_worktree_ignores_other_tasks() {
        let dir = tempfile::tempdir().unwrap();
        tokio::fs::create_dir(dir.path().join("gh-issue-43-other-task"))
            .await
            .unwrap();

        assert!(find_existing_worktree(dir.path(), "42").await.is_none());
    }

    // --- resolve_parent_branch tests ---

    /// No store → always returns None.
    #[tokio::test]
    async fn resolve_parent_branch_no_store_returns_none() {
        let dir = tempfile::tempdir().unwrap();
        let result = resolve_parent_branch(&None, Some(1), dir.path()).await;
        assert!(result.is_none());
    }

    /// parent_id = None → always returns None regardless of store.
    #[tokio::test]
    async fn resolve_parent_branch_no_parent_id_returns_none() {
        let dir = tempfile::tempdir().unwrap();
        let result = resolve_parent_branch(&None, None, dir.path()).await;
        assert!(result.is_none());
    }

    /// Parent exists but has empty branch → returns None so child gets its own branch.
    #[tokio::test]
    async fn resolve_parent_branch_empty_parent_branch_returns_none() {
        let db_dir = tempfile::tempdir().unwrap();
        let db_path = db_dir.path().join("test.db");
        let store = Arc::new(
            crate::store::TaskStore::open_single(&db_path)
                .await
                .unwrap(),
        );

        // Create parent task — branch defaults to empty string
        let parent_id = store
            .create_internal("owner/repo", "parent task", "", "issue", "99", None)
            .await
            .unwrap();

        let dir = tempfile::tempdir().unwrap();
        let store_opt = Some(store);
        let result = resolve_parent_branch(&store_opt, Some(parent_id), dir.path()).await;
        assert!(result.is_none());
    }

    /// Parent has a branch set → child inherits that branch and worktree path.
    #[tokio::test]
    async fn resolve_parent_branch_returns_parent_branch_and_worktree() {
        let db_dir = tempfile::tempdir().unwrap();
        let db_path = db_dir.path().join("test.db");
        let store = Arc::new(
            crate::store::TaskStore::open_single(&db_path)
                .await
                .unwrap(),
        );

        // Create parent task and set its branch
        let parent_id = store
            .create_internal("owner/repo", "parent task", "", "issue", "99", None)
            .await
            .unwrap();
        store
            .set_fields(
                parent_id,
                &[("branch", serde_json::json!("gh-issue-99-parent-task"))],
            )
            .await
            .unwrap();

        let worktrees_base = tempfile::tempdir().unwrap();
        let store_opt = Some(store);
        let result =
            resolve_parent_branch(&store_opt, Some(parent_id), worktrees_base.path()).await;

        let (branch, wt) = result.expect("should return parent branch");
        assert_eq!(branch, "gh-issue-99-parent-task");
        assert_eq!(wt, worktrees_base.path().join("gh-issue-99-parent-task"));
    }

    /// When parent has both branch and a worktree path that exists, use the worktree path.
    #[tokio::test]
    async fn resolve_parent_branch_prefers_existing_worktree_path() {
        let db_dir = tempfile::tempdir().unwrap();
        let db_path = db_dir.path().join("test.db");
        let store = Arc::new(
            crate::store::TaskStore::open_single(&db_path)
                .await
                .unwrap(),
        );

        let worktrees_base = tempfile::tempdir().unwrap();
        // Create the parent worktree directory
        let parent_wt_dir = worktrees_base.path().join("custom-worktree-path");
        tokio::fs::create_dir_all(&parent_wt_dir).await.unwrap();

        let parent_id = store
            .create_internal("owner/repo", "parent task", "", "issue", "99", None)
            .await
            .unwrap();
        store
            .set_fields(
                parent_id,
                &[
                    ("branch", serde_json::json!("gh-issue-99-parent-task")),
                    (
                        "worktree",
                        serde_json::json!(parent_wt_dir.to_string_lossy().as_ref()),
                    ),
                ],
            )
            .await
            .unwrap();

        let store_opt = Some(store);
        let result =
            resolve_parent_branch(&store_opt, Some(parent_id), worktrees_base.path()).await;

        let (branch, wt) = result.expect("should return parent branch");
        assert_eq!(branch, "gh-issue-99-parent-task");
        assert_eq!(wt, parent_wt_dir);
    }

    /// Regression test: concurrent calls to list_project_worktrees and
    /// validate_worktree_gitdir should not starve the Tokio worker thread
    /// pool. This was broken by blocking Path::exists/is_dir calls in async
    /// functions (issue #2467).
    #[tokio::test]
    async fn concurrent_worktree_checks_no_starvation() {
        let temp_dir = tempfile::tempdir().unwrap();
        let worktrees_base = temp_dir.path().join("worktrees");
        tokio::fs::create_dir_all(&worktrees_base).await.unwrap();

        // Create a fake worktree with valid gitdir
        let wt_dir = worktrees_base.join("gh-issue-123-test");
        tokio::fs::create_dir_all(&wt_dir).await.unwrap();
        // Create .git as a file pointing to a real directory (worktree link)
        let gitdir_target = temp_dir
            .path()
            .join(".git")
            .join("worktrees")
            .join("gh-issue-123-test");
        tokio::fs::create_dir_all(&gitdir_target).await.unwrap();
        let git_file = wt_dir.join(".git");
        tokio::fs::write(&git_file, format!("gitdir: {}\n", gitdir_target.display()))
            .await
            .unwrap();

        // Spawn many concurrent tasks - if any use blocking calls, they'll
        // block the worker thread and cause timeout or deadlock.
        let handles: Vec<_> = (0..20)
            .map(|i| {
                let wb = worktrees_base.clone();
                let wd = wt_dir.clone();
                tokio::spawn(async move {
                    if i % 2 == 0 {
                        list_project_worktrees(&wb).await.ok();
                    } else {
                        validate_worktree_gitdir(&wd).await;
                    }
                })
            })
            .collect();

        // Wait with timeout to detect starvation
        let results = tokio::time::timeout(std::time::Duration::from_secs(10), async {
            futures::future::join_all(handles).await
        })
        .await;

        assert!(
            results.is_ok(),
            "concurrent worktree checks timed out (starvation?)"
        );
    }

    // --- normalize_branch_name tests ---

    #[test]
    fn normalize_branch_name_strips_origin_prefix() {
        assert_eq!(
            normalize_branch_name("origin/main"),
            Some("main".to_string())
        );
        assert_eq!(
            normalize_branch_name("origin/develop"),
            Some("develop".to_string())
        );
    }

    #[test]
    fn normalize_branch_name_strips_full_ref_path() {
        assert_eq!(
            normalize_branch_name("refs/remotes/origin/main"),
            Some("main".to_string())
        );
        assert_eq!(
            normalize_branch_name("refs/remotes/origin/develop"),
            Some("develop".to_string())
        );
    }

    #[test]
    fn normalize_branch_name_strips_remotes_prefix() {
        assert_eq!(
            normalize_branch_name("remotes/origin/main"),
            Some("main".to_string())
        );
    }

    #[test]
    fn normalize_branch_name_passes_through_plain_branch() {
        assert_eq!(normalize_branch_name("main"), Some("main".to_string()));
        assert_eq!(normalize_branch_name("master"), Some("master".to_string()));
        assert_eq!(
            normalize_branch_name("feature/foo"),
            Some("feature/foo".to_string())
        );
    }

    #[test]
    fn normalize_branch_name_rejects_empty_and_refs_only() {
        assert_eq!(normalize_branch_name(""), None);
        assert_eq!(normalize_branch_name("   "), None);
        assert_eq!(
            normalize_branch_name("refs/heads/main"),
            Some("main".to_string())
        );
    }
}