yolop 0.7.0

Yolop — a terminal coding agent built on everruns-runtime
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
// Git worktree management for yolop sessions.
//
// Each session can get an isolated worktree on a dedicated branch, branched
// from `origin/main`, so the user's primary checkout stays untouched. Worktrees
// live outside the repo (tmp dir, falling back to `~/.yolop/worktrees/`).

use crate::session_log::{SessionWorkspaceMetadata, WorktreeMetadata, write_session_workspace};
use crate::settings::WorktreesMode;
use anyhow::{Context, Result, bail};
use everruns_core::typed_id::SessionId;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, RwLock};

/// Patterns naming git-ignored paths to copy into freshly-created worktrees,
/// `.gitignore`-style. Lives at the repo root.
const WORKTREE_INCLUDE_FILE: &str = ".worktreeinclude";

/// Copied into managed worktrees automatically, without needing a
/// `.worktreeinclude` entry (mirrors Codex). Only copied when git-ignored.
const IMPLICIT_INCLUDE: &str = "AGENTS.override.md";

const IMPLEMENT_VERBS: &[&str] = &[
    "fix",
    "implement",
    "add",
    "create",
    "build",
    "write",
    "update",
    "change",
    "refactor",
    "ship",
    "debug",
    "patch",
    "remove",
    "delete",
    "migrate",
    "replace",
    "introduce",
    "integrate",
    "wire",
    "hook",
    "land",
    "port",
    "rewrite",
    "repair",
    "correct",
    "extend",
    "modify",
];

const STOP_WORDS: &[&str] = &[
    "a", "an", "the", "to", "for", "in", "on", "at", "of", "and", "or", "with", "from", "this",
    "that", "please", "can", "you", "me", "my", "i", "we", "it", "is", "are", "be", "do", "does",
];

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorktreeInfo {
    pub path: PathBuf,
    pub branch: String,
    pub base_ref: String,
    pub slug: String,
}

/// Session-scoped worktree coordinator. Thread-safe for concurrent reads; writes
/// are serialized through the inner `RwLock`s.
pub struct WorktreeManager {
    mode: WorktreesMode,
    repo_root: Option<PathBuf>,
    active_root: Arc<RwLock<PathBuf>>,
    worktree: RwLock<Option<WorktreeInfo>>,
    session_id: SessionId,
    session_dir: PathBuf,
    auto_disabled: AtomicBool,
}

impl WorktreeManager {
    pub fn new(
        mode: WorktreesMode,
        repo_root: Option<PathBuf>,
        initial_active_root: PathBuf,
        session_id: SessionId,
        session_dir: PathBuf,
        restored: Option<WorktreeInfo>,
    ) -> Self {
        let active = restored
            .as_ref()
            .map(|w| w.path.clone())
            .unwrap_or(initial_active_root);
        Self {
            mode,
            repo_root,
            active_root: Arc::new(RwLock::new(active)),
            worktree: RwLock::new(restored),
            session_id,
            session_dir,
            auto_disabled: AtomicBool::new(false),
        }
    }

    pub fn shared_active_root(&self) -> Arc<RwLock<PathBuf>> {
        self.active_root.clone()
    }

    pub fn active_root(&self) -> PathBuf {
        self.active_root
            .read()
            .map(|p| p.clone())
            .unwrap_or_else(|_| PathBuf::from("."))
    }

    pub fn worktree_info(&self) -> Option<WorktreeInfo> {
        self.worktree.read().ok().and_then(|g| g.clone())
    }

    pub fn disable_auto(&self) {
        self.auto_disabled.store(true, Ordering::SeqCst);
    }

    pub fn auto_disabled(&self) -> bool {
        self.auto_disabled.load(Ordering::SeqCst)
    }

    pub fn status_message(&self) -> String {
        if let Some(info) = self.worktree_info() {
            let repo = self
                .repo_root
                .as_ref()
                .map(|p| p.display().to_string())
                .unwrap_or_else(|| "unknown".to_string());
            return format!(
                "active worktree\nrepo: {repo}\nbranch: {}\npath: {}\nbase: {}",
                info.branch,
                info.path.display(),
                info.base_ref,
            );
        }
        if self.repo_root.is_none() {
            return "worktrees: not in a git repository".to_string();
        }
        if self.auto_disabled() {
            return "worktrees: auto activation disabled for this session (already-active \
                    worktrees are unchanged)"
                .to_string();
        }
        format!(
            "worktrees: {} (inactive — activates on implementation prompts)",
            self.mode.as_str()
        )
    }

    /// Returns `true` when the active root changed (worktree was created or restored).
    pub fn ensure_before_turn(&self, prompt: &str) -> Result<bool> {
        if self.worktree.read().map(|g| g.is_some()).unwrap_or(false) {
            return Ok(false);
        }
        if !self.should_activate(prompt) {
            return Ok(false);
        }
        self.activate(Some(prompt))?;
        Ok(true)
    }

    pub fn ensure_always(&self) -> Result<bool> {
        if self.worktree.read().map(|g| g.is_some()).unwrap_or(false) {
            return Ok(false);
        }
        if !self.can_use_worktrees() {
            return Ok(false);
        }
        self.activate(None)?;
        Ok(true)
    }

    fn should_activate(&self, prompt: &str) -> bool {
        if self.auto_disabled.load(Ordering::SeqCst) {
            return false;
        }
        match self.mode {
            WorktreesMode::Off => false,
            WorktreesMode::Always => self.can_use_worktrees(),
            WorktreesMode::Auto => {
                self.can_use_worktrees() && looks_like_implementation_intent(prompt)
            }
        }
    }

    fn can_use_worktrees(&self) -> bool {
        self.repo_root.is_some() && self.mode != WorktreesMode::Off
    }

    fn activate(&self, prompt: Option<&str>) -> Result<()> {
        let repo_root = self
            .repo_root
            .as_ref()
            .context("worktree activation requires a git repository")?;
        let slug = prompt
            .map(slug_from_prompt)
            .filter(|s| !s.is_empty())
            .unwrap_or_else(|| "session".to_string());
        let branch = branch_name(&slug, self.session_id);
        let base_ref = resolve_base_ref(repo_root);
        let path = worktree_path(repo_root, &self.session_id.to_string())?;

        let info = if path.exists() && worktree_contains_path(repo_root, &path) {
            WorktreeInfo {
                path: path.clone(),
                branch: branch.clone(),
                base_ref: base_ref.clone(),
                slug: slug.clone(),
            }
        } else {
            create_worktree(repo_root, &path, &branch, &base_ref)?;
            WorktreeInfo {
                path: path.clone(),
                branch,
                base_ref,
                slug,
            }
        };

        {
            let mut active = self
                .active_root
                .write()
                .map_err(|_| anyhow::anyhow!("active workspace lock poisoned"))?;
            *active = info.path.clone();
        }
        {
            let mut guard = self
                .worktree
                .write()
                .map_err(|_| anyhow::anyhow!("worktree lock poisoned"))?;
            *guard = Some(info.clone());
        }
        self.persist_metadata(&info)?;
        Ok(())
    }

    pub fn restore_from_metadata(&self, metadata: &SessionWorkspaceMetadata) -> Result<()> {
        let Some(worktree) = metadata.worktree.clone() else {
            return Ok(());
        };
        let repo_root = metadata
            .repo_root
            .as_ref()
            .or(self.repo_root.as_ref())
            .context("resume worktree metadata missing repo_root")?;

        let info = if worktree.path.exists() && worktree_contains_path(repo_root, &worktree.path) {
            WorktreeInfo {
                path: worktree.path.clone(),
                branch: worktree.branch.clone(),
                base_ref: worktree.base_ref.clone(),
                slug: worktree.slug.clone(),
            }
        } else {
            recreate_worktree(repo_root, &worktree)?
        };

        {
            let mut active = self
                .active_root
                .write()
                .map_err(|_| anyhow::anyhow!("active workspace lock poisoned"))?;
            *active = info.path.clone();
        }
        {
            let mut guard = self
                .worktree
                .write()
                .map_err(|_| anyhow::anyhow!("worktree lock poisoned"))?;
            *guard = Some(info.clone());
        }
        self.persist_metadata(&info)?;
        Ok(())
    }

    fn persist_metadata(&self, info: &WorktreeInfo) -> Result<()> {
        let mut metadata = SessionWorkspaceMetadata::new(info.path.clone(), self.repo_root.clone());
        metadata.worktree = Some(WorktreeMetadata {
            path: info.path.clone(),
            branch: info.branch.clone(),
            base_ref: info.base_ref.clone(),
            slug: info.slug.clone(),
        });
        write_session_workspace(&self.session_dir, &metadata).map_err(|e| anyhow::anyhow!("{e}"))
    }

    /// Short slug for the compact session status bar.
    pub fn status_bar_compact(&self) -> Option<String> {
        self.worktree_info().map(|info| info.slug)
    }

    /// Branch and filesystem path for the expanded status bar subsection.
    pub fn status_bar_expanded(&self) -> Option<(String, String)> {
        self.worktree_info().map(|info| {
            (
                info.branch,
                truncate_status_path(&info.path.display().to_string(), 72),
            )
        })
    }

    /// Light transcript notice when a worktree is activated mid-session.
    pub fn switch_notice(&self) -> Option<String> {
        self.worktree_info()
            .map(|info| format!("Switched to worktree · {}", info.branch))
    }
}

fn truncate_status_path(path: &str, max_len: usize) -> String {
    if path.chars().count() <= max_len {
        return path.to_string();
    }
    let tail_len = max_len.saturating_sub(1);
    let tail: String = path.chars().rev().take(tail_len).collect::<String>();
    format!("{}", tail.chars().rev().collect::<String>())
}

pub fn detect_repo_root(path: &Path) -> Option<PathBuf> {
    let output = Command::new("git")
        .arg("-C")
        .arg(path)
        .args(["rev-parse", "--show-toplevel"])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let text = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if text.is_empty() {
        None
    } else {
        std::fs::canonicalize(&text).ok()
    }
}

pub fn looks_like_implementation_intent(prompt: &str) -> bool {
    let trimmed = prompt.trim();
    if trimmed.is_empty() {
        return false;
    }
    if trimmed.starts_with("/ship") {
        return true;
    }
    let lower = format!(" {lower} ", lower = trimmed.to_ascii_lowercase());
    IMPLEMENT_VERBS
        .iter()
        .any(|verb| lower.contains(&format!(" {verb} ")))
}

pub fn slug_from_prompt(prompt: &str) -> String {
    let words: Vec<String> = prompt
        .to_ascii_lowercase()
        .split(|c: char| !c.is_ascii_alphanumeric())
        .filter(|w| !w.is_empty())
        .filter(|w| STOP_WORDS.iter().all(|stop| stop != w))
        .take(5)
        .map(str::to_string)
        .collect();
    if words.is_empty() {
        "session".to_string()
    } else {
        words.join("-")
    }
}

pub fn branch_name(slug: &str, session_id: SessionId) -> String {
    let suffix = session_suffix(session_id);
    let base = slug.trim_matches('-');
    if base.is_empty() {
        format!("session-{suffix}")
    } else {
        format!("{base}-{suffix}")
    }
}

fn session_suffix(session_id: SessionId) -> String {
    let compact: String = session_id
        .to_string()
        .chars()
        .filter(|c| c.is_ascii_alphanumeric())
        .collect();
    let suffix: String = compact.chars().rev().take(8).collect::<String>();
    let suffix: String = suffix.chars().rev().collect();
    if suffix.is_empty() {
        "00000000".to_string()
    } else {
        suffix
    }
}

pub fn repo_id(repo_root: &Path) -> String {
    let mut hasher = DefaultHasher::new();
    repo_root.display().to_string().hash(&mut hasher);
    format!("{:08x}", hasher.finish())
}

pub fn worktree_parent_dir(repo_id: &str) -> PathBuf {
    let tmp_base = std::env::var_os("TMPDIR")
        .map(PathBuf::from)
        .or_else(|| Some(PathBuf::from("/tmp")))
        .unwrap();
    let tmp_candidate = tmp_base.join("yolop").join("worktrees").join(repo_id);
    if std::fs::create_dir_all(&tmp_candidate).is_ok() {
        return tmp_candidate;
    }
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".yolop")
        .join("worktrees")
        .join(repo_id)
}

pub fn worktree_path(repo_root: &Path, session_id: &str) -> Result<PathBuf> {
    let parent = worktree_parent_dir(&repo_id(repo_root));
    std::fs::create_dir_all(&parent)
        .with_context(|| format!("create worktree parent {}", parent.display()))?;
    Ok(parent.join(session_id))
}

fn resolve_base_ref(repo_root: &Path) -> String {
    for candidate in ["origin/main", "origin/master", "main", "master"] {
        if git_verify_ref(repo_root, candidate) {
            return candidate.to_string();
        }
    }
    "HEAD".to_string()
}

fn git_verify_ref(repo_root: &Path, reference: &str) -> bool {
    git_output(repo_root, &["rev-parse", "--verify", reference]).is_some()
}

fn create_worktree(repo_root: &Path, path: &Path, branch: &str, base_ref: &str) -> Result<()> {
    if path.exists() {
        std::fs::remove_dir_all(path).with_context(|| {
            format!(
                "remove stale worktree path {} before recreate",
                path.display()
            )
        })?;
    }
    // Best-effort fetch so origin/main is current when used as the base.
    if base_ref.starts_with("origin/") {
        let remote_branch = base_ref.strip_prefix("origin/").unwrap_or(base_ref);
        let _ = Command::new("git")
            .arg("-C")
            .arg(repo_root)
            .args(["fetch", "origin", remote_branch])
            .status();
    }
    let status = Command::new("git")
        .arg("-C")
        .arg(repo_root)
        .args([
            "worktree",
            "add",
            "-B",
            branch,
            &path.display().to_string(),
            base_ref,
        ])
        .status()
        .with_context(|| format!("git worktree add for {}", path.display()))?;
    if status.success() {
        copy_worktree_includes(repo_root, path);
        return Ok(());
    }
    bail!(
        "git worktree add -B {branch} {} {base_ref} failed",
        path.display()
    );
}

/// Copy git-ignored files matching `.worktreeinclude` (plus an ignored
/// `AGENTS.override.md`) from the source checkout into a fresh worktree.
///
/// `git worktree add` only materializes tracked files, so intentionally-ignored
/// setup files (`.env`, local secrets, …) are otherwise missing. Best-effort:
/// failures are logged, never fatal. Skips symlinks and never overwrites a file
/// already present in the new checkout.
fn copy_worktree_includes(repo_root: &Path, worktree_path: &Path) {
    use ignore::gitignore::GitignoreBuilder;

    let mut builder = GitignoreBuilder::new(repo_root);
    let include_file = repo_root.join(WORKTREE_INCLUDE_FILE);
    if include_file.is_file()
        && let Some(err) = builder.add(&include_file)
    {
        tracing::warn!(error = %err, file = %include_file.display(), "ignoring malformed .worktreeinclude");
    }
    // Implicit, un-listed include — only copied if it is actually git-ignored.
    let _ = builder.add_line(None, IMPLICIT_INCLUDE);
    let matcher = match builder.build() {
        Ok(m) => m,
        Err(err) => {
            tracing::warn!(error = %err, "failed to build .worktreeinclude matcher");
            return;
        }
    };

    // Enumerate git-ignored files in the source checkout (relative paths).
    let output = match Command::new("git")
        .arg("-C")
        .arg(repo_root)
        .args([
            "ls-files",
            "-z",
            "--others",
            "--ignored",
            "--exclude-standard",
        ])
        .output()
    {
        Ok(out) if out.status.success() => out.stdout,
        Ok(out) => {
            tracing::warn!(
                status = ?out.status.code(),
                stderr = %String::from_utf8_lossy(&out.stderr).trim(),
                "git ls-files failed; skipping .worktreeinclude copy"
            );
            return;
        }
        Err(err) => {
            tracing::warn!(error = %err, "could not run git ls-files; skipping .worktreeinclude copy");
            return;
        }
    };

    // Resolve once so we can confirm copied sources stay inside the repo even if
    // a parent component is a symlink (git won't list through symlinked dirs,
    // but guard defensively against symlink escape).
    let repo_canon = std::fs::canonicalize(repo_root).unwrap_or_else(|_| repo_root.to_path_buf());

    let mut copied = 0usize;
    for rel in output.split(|&b| b == 0) {
        if rel.is_empty() {
            continue;
        }
        let rel = Path::new(std::str::from_utf8(rel).unwrap_or_default());
        if rel.as_os_str().is_empty() {
            continue;
        }
        if !matcher.matched_path_or_any_parents(rel, false).is_ignore() {
            continue;
        }
        let src = repo_root.join(rel);
        // Skip symlinks; copy regular files only.
        match std::fs::symlink_metadata(&src) {
            Ok(meta) if meta.file_type().is_symlink() => continue,
            Ok(meta) if !meta.is_file() => continue,
            Ok(_) => {}
            Err(_) => continue,
        }
        // Reject any source that resolves outside the repo (symlinked parent
        // escape). `std::fs::copy` follows symlinks, so this prevents reading
        // and re-materializing files from outside the checkout.
        match std::fs::canonicalize(&src) {
            Ok(canon) if canon.starts_with(&repo_canon) => {}
            _ => {
                tracing::warn!(src = %src.display(), "skipping worktree include resolving outside repo");
                continue;
            }
        }
        let dest = worktree_path.join(rel);
        if dest.exists() {
            continue;
        }
        if let Some(parent) = dest.parent()
            && let Err(err) = std::fs::create_dir_all(parent)
        {
            tracing::warn!(error = %err, dest = %dest.display(), "failed to create worktree include dir");
            continue;
        }
        match std::fs::copy(&src, &dest) {
            Ok(_) => copied += 1,
            Err(err) => {
                tracing::warn!(error = %err, src = %src.display(), "failed to copy worktree include");
            }
        }
    }
    if copied > 0 {
        tracing::info!(count = copied, worktree = %worktree_path.display(), "copied ignored files into worktree");
    }
}

fn recreate_worktree(repo_root: &Path, saved: &WorktreeMetadata) -> Result<WorktreeInfo> {
    let path = saved.path.clone();
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("create worktree parent {}", parent.display()))?;
    }
    if path.exists() {
        let _ = std::fs::remove_dir_all(&path);
    }
    if branch_exists(repo_root, &saved.branch) {
        let status = Command::new("git")
            .arg("-C")
            .arg(repo_root)
            .args([
                "worktree",
                "add",
                &path.display().to_string(),
                &saved.branch,
            ])
            .status()
            .with_context(|| format!("reattach worktree branch {}", saved.branch))?;
        if !status.success() {
            bail!("git worktree add {} {}", path.display(), saved.branch);
        }
        copy_worktree_includes(repo_root, &path);
    } else {
        create_worktree(repo_root, &path, &saved.branch, &saved.base_ref)?;
    }
    Ok(WorktreeInfo {
        path,
        branch: saved.branch.clone(),
        base_ref: saved.base_ref.clone(),
        slug: saved.slug.clone(),
    })
}

fn branch_exists(repo_root: &Path, branch: &str) -> bool {
    git_output(
        repo_root,
        &["show-ref", "--verify", &format!("refs/heads/{branch}")],
    )
    .is_some()
}

fn worktree_contains_path(repo_root: &Path, path: &Path) -> bool {
    let canonical = match std::fs::canonicalize(path) {
        Ok(p) => p,
        Err(_) => return false,
    };
    let listing = match Command::new("git")
        .arg("-C")
        .arg(repo_root)
        .args(["worktree", "list", "--porcelain"])
        .output()
    {
        Ok(output) if output.status.success() => {
            String::from_utf8_lossy(&output.stdout).into_owned()
        }
        _ => return false,
    };
    listing.lines().any(|line| {
        line.strip_prefix("worktree ")
            .and_then(|p| std::fs::canonicalize(p).ok())
            .is_some_and(|listed| listed == canonical)
    })
}

fn git_output(repo_root: &Path, args: &[&str]) -> Option<String> {
    let output = Command::new("git")
        .arg("-C")
        .arg(repo_root)
        .args(args)
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let text = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if text.is_empty() { None } else { Some(text) }
}

pub fn restore_worktree_from_metadata(metadata: &SessionWorkspaceMetadata) -> Option<WorktreeInfo> {
    let worktree = metadata.worktree.as_ref()?;
    let repo_root = metadata.repo_root.as_ref()?;
    if worktree.path.exists() && worktree_contains_path(repo_root, &worktree.path) {
        return Some(WorktreeInfo {
            path: worktree.path.clone(),
            branch: worktree.branch.clone(),
            base_ref: worktree.base_ref.clone(),
            slug: worktree.slug.clone(),
        });
    }
    recreate_worktree(repo_root, worktree).ok()
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PruneReport {
    pub removed: Vec<PathBuf>,
    pub kept: usize,
    pub errors: Vec<String>,
}

/// Roots that may contain session worktrees (tmp + persistent fallback).
pub fn worktree_storage_roots() -> Vec<PathBuf> {
    let mut roots = Vec::new();
    let tmp_base = std::env::var_os("TMPDIR")
        .map(PathBuf::from)
        .or_else(|| Some(PathBuf::from("/tmp")))
        .unwrap();
    roots.push(tmp_base.join("yolop").join("worktrees"));
    roots.push(
        dirs::home_dir()
            .unwrap_or_else(|| PathBuf::from("."))
            .join(".yolop")
            .join("worktrees"),
    );
    roots
}

pub fn referenced_worktree_paths(
    sessions_dir: &Path,
) -> Result<std::collections::HashSet<PathBuf>> {
    use crate::session_log::{read_session_workspace_metadata, session_dir_path};
    use everruns_core::typed_id::SessionId;

    let mut referenced = std::collections::HashSet::new();
    if !sessions_dir.is_dir() {
        return Ok(referenced);
    }
    for entry in std::fs::read_dir(sessions_dir)? {
        let entry = entry?;
        if !entry.file_type()?.is_dir() {
            continue;
        }
        let name = entry.file_name();
        let Some(name) = name.to_str() else {
            continue;
        };
        let Ok(session_id) = name.parse::<SessionId>() else {
            continue;
        };
        let session_dir = session_dir_path(sessions_dir, session_id);
        if let Some(metadata) = read_session_workspace_metadata(&session_dir)?
            && let Some(worktree) = metadata.worktree
        {
            if let Ok(path) = std::fs::canonicalize(&worktree.path) {
                referenced.insert(path);
            } else {
                referenced.insert(worktree.path);
            }
        }
    }
    Ok(referenced)
}

pub fn list_worktree_paths_on_disk() -> Result<Vec<PathBuf>> {
    let mut paths = Vec::new();
    for root in worktree_storage_roots() {
        if !root.is_dir() {
            continue;
        }
        for repo_entry in std::fs::read_dir(&root)? {
            let repo_entry = repo_entry?;
            if !repo_entry.file_type()?.is_dir() {
                continue;
            }
            for session_entry in std::fs::read_dir(repo_entry.path())? {
                let session_entry = session_entry?;
                if session_entry.file_type()?.is_dir() {
                    paths.push(session_entry.path());
                }
            }
        }
    }
    paths.sort();
    Ok(paths)
}

fn main_repo_for_worktree(worktree_path: &Path) -> Option<PathBuf> {
    let git_common = git_output(worktree_path, &["rev-parse", "--git-common-dir"])?;
    let git_path = PathBuf::from(git_common);
    if git_path.is_absolute() {
        git_path.parent().map(|p| p.to_path_buf())
    } else {
        worktree_path
            .join(&git_path)
            .parent()
            .map(|p| p.to_path_buf())
    }
}

pub fn remove_worktree_path(path: &Path) -> Result<()> {
    if let Some(repo_root) = main_repo_for_worktree(path) {
        let status = Command::new("git")
            .arg("-C")
            .arg(&repo_root)
            .args(["worktree", "remove", "--force", &path.display().to_string()])
            .status()
            .with_context(|| format!("git worktree remove {}", path.display()))?;
        if status.success() {
            return Ok(());
        }
    }
    if path.exists() {
        std::fs::remove_dir_all(path)
            .with_context(|| format!("remove worktree directory {}", path.display()))?;
    }
    Ok(())
}

pub fn prune_orphan_worktrees(sessions_dir: &Path, dry_run: bool) -> Result<PruneReport> {
    let referenced = referenced_worktree_paths(sessions_dir)?;
    let mut report = PruneReport {
        removed: Vec::new(),
        kept: 0,
        errors: Vec::new(),
    };
    for path in list_worktree_paths_on_disk()? {
        let canonical = std::fs::canonicalize(&path).unwrap_or(path.clone());
        if referenced.contains(&canonical) || referenced.contains(&path) {
            report.kept += 1;
            continue;
        }
        if dry_run {
            report.removed.push(path);
            continue;
        }
        match remove_worktree_path(&path) {
            Ok(()) => report.removed.push(path),
            Err(err) => report.errors.push(format!("{}: {err}", path.display())),
        }
    }
    Ok(report)
}

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

    #[test]
    fn slug_from_prompt_strips_stop_words() {
        assert_eq!(
            slug_from_prompt("Please fix the auth bug in login"),
            "fix-auth-bug-login"
        );
    }

    #[test]
    fn implementation_intent_matches_common_verbs() {
        assert!(looks_like_implementation_intent("fix the auth bug"));
        assert!(looks_like_implementation_intent("/ship this change"));
        assert!(!looks_like_implementation_intent("how does auth work?"));
        assert!(!looks_like_implementation_intent("explain the module"));
    }

    #[test]
    fn branch_name_uses_slug_and_session_suffix() {
        let id = SessionId::default();
        let branch = branch_name("fix-auth", id);
        assert!(branch.starts_with("fix-auth-"));
        assert!(branch.len() > "fix-auth-".len());
    }

    #[test]
    fn truncate_status_path_keeps_tail() {
        let path = "/var/folders/rs/tcmw11q17s961ch7pb76czc0000gn/T/yolop/worktrees/b85662b381593c9f/session_019ee6c2";
        let truncated = truncate_status_path(path, 40);
        assert!(truncated.starts_with(''));
        assert!(truncated.contains("session_019ee6c2"));
        assert!(truncated.chars().count() <= 40);
    }

    #[test]
    fn worktree_manager_creates_isolated_branch_on_implementation_prompt() {
        let _guard = crate::test_env::lock();
        let repo = tempfile::tempdir().expect("repo");
        std::process::Command::new("git")
            .args(["init", "-b", "main"])
            .current_dir(repo.path())
            .status()
            .expect("git init");
        std::fs::write(repo.path().join("README.md"), "hello").expect("readme");
        std::process::Command::new("git")
            .args(["add", "README.md"])
            .current_dir(repo.path())
            .status()
            .expect("git add");
        std::process::Command::new("git")
            .args([
                "-c",
                "commit.gpgsign=false",
                "commit",
                "-m",
                "init",
                "--author",
                "test <test@example.com>",
            ])
            .env("GIT_COMMITTER_NAME", "test")
            .env("GIT_COMMITTER_EMAIL", "test@example.com")
            .current_dir(repo.path())
            .status()
            .expect("git commit");

        let sessions = tempfile::tempdir().expect("sessions");
        let session_id = SessionId::from_seed(99);
        let session_dir = sessions.path().join(session_id.to_string());
        std::fs::create_dir_all(&session_dir).expect("session dir");

        let manager = WorktreeManager::new(
            WorktreesMode::Auto,
            detect_repo_root(repo.path()),
            repo.path().to_path_buf(),
            session_id,
            session_dir,
            None,
        );

        manager
            .ensure_before_turn("fix the readme typo")
            .expect("activate worktree");
        let info = manager.worktree_info().expect("worktree info");
        assert!(info.path.exists());
        assert!(info.branch.starts_with("fix-readme"));
        assert_ne!(info.path, repo.path());

        let main_branch =
            git_output(repo.path(), &["branch", "--show-current"]).expect("main branch");
        assert_eq!(main_branch, "main");
    }

    #[test]
    fn copies_ignored_includes_into_worktree() {
        let repo = tempfile::tempdir().expect("repo");
        let run = |args: &[&str]| {
            let status = std::process::Command::new("git")
                .arg("-c")
                .arg("commit.gpgsign=false")
                .args(args)
                .current_dir(repo.path())
                .env("GIT_COMMITTER_NAME", "test")
                .env("GIT_COMMITTER_EMAIL", "test@example.com")
                .status()
                .expect("git");
            assert!(status.success(), "git {args:?} failed");
        };
        run(&["init", "-b", "main"]);
        std::fs::write(
            repo.path().join(".gitignore"),
            ".env\nsecrets/\nAGENTS.override.md\n",
        )
        .expect("gitignore");
        std::fs::write(
            repo.path().join(".worktreeinclude"),
            ".env\nsecrets/secret.txt\n",
        )
        .expect("worktreeinclude");
        // Ignored files that should be copied.
        std::fs::write(repo.path().join(".env"), "TOKEN=abc").expect("env");
        std::fs::create_dir_all(repo.path().join("secrets")).expect("secrets dir");
        std::fs::write(repo.path().join("secrets/secret.txt"), "shh").expect("secret");
        // Ignored AGENTS.override.md is copied implicitly without being listed.
        std::fs::write(repo.path().join("AGENTS.override.md"), "override").expect("override");
        // Ignored but not matched by .worktreeinclude — must NOT be copied.
        std::fs::write(repo.path().join("secrets/other.txt"), "nope").expect("other");
        std::fs::write(repo.path().join("README.md"), "hello").expect("readme");
        run(&["add", "README.md", ".gitignore"]);
        run(&[
            "commit",
            "-m",
            "init",
            "--author",
            "test <test@example.com>",
        ]);

        // Unique, isolated worktree path so parallel tests can't collide.
        let wt_parent = tempfile::tempdir().expect("wt parent");
        let worktree = wt_parent.path().join("wt");
        create_worktree(repo.path(), &worktree, "copy-test", "HEAD").expect("create worktree");

        assert_eq!(
            std::fs::read_to_string(worktree.join(".env")).unwrap(),
            "TOKEN=abc"
        );
        assert_eq!(
            std::fs::read_to_string(worktree.join("secrets/secret.txt")).unwrap(),
            "shh"
        );
        assert_eq!(
            std::fs::read_to_string(worktree.join("AGENTS.override.md")).unwrap(),
            "override"
        );
        assert!(!worktree.join("secrets/other.txt").exists());

        let _ = std::process::Command::new("git")
            .arg("-C")
            .arg(repo.path())
            .args([
                "worktree",
                "remove",
                "--force",
                &worktree.display().to_string(),
            ])
            .status();
    }

    #[test]
    fn disable_auto_and_status_message() {
        let manager = WorktreeManager::new(
            WorktreesMode::Auto,
            Some(PathBuf::from("/tmp/repo")),
            PathBuf::from("/tmp/repo"),
            SessionId::from_seed(1),
            PathBuf::from("/tmp/session"),
            None,
        );
        assert!(manager.status_message().contains("auto"));
        manager.disable_auto();
        assert!(manager.auto_disabled());
        assert!(manager.status_message().contains("disabled"));
    }

    #[test]
    fn prune_removes_unreferenced_worktree_dirs() {
        let _guard = crate::test_env::lock();
        let sessions = tempfile::tempdir().expect("sessions");
        let storage = tempfile::tempdir().expect("storage");
        let storage_path = storage.path().to_path_buf();
        let previous_tmpdir = std::env::var_os("TMPDIR");
        // SAFETY: test-only TMPDIR override; restored before this test returns.
        unsafe {
            std::env::set_var("TMPDIR", &storage_path);
        }

        let orphan = storage_path
            .join("yolop")
            .join("worktrees")
            .join("abc12345")
            .join("orphan-session");
        std::fs::create_dir_all(&orphan).expect("orphan");

        let report = prune_orphan_worktrees(sessions.path(), false).expect("prune");
        assert_eq!(report.kept, 0);
        assert_eq!(report.removed.len(), 1);
        assert!(!orphan.exists());

        // SAFETY: restore prior TMPDIR so later tests see a valid temp root.
        unsafe {
            match &previous_tmpdir {
                Some(value) => std::env::set_var("TMPDIR", value),
                None => std::env::remove_var("TMPDIR"),
            }
        }
    }
}