trusty-mpm 1.3.4

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
//! Unit tests for the in-project spawn path (#1706, #1803, #1805, #1807).
//!
//! Why: split out of `inproject.rs` so the production module stays under the
//! 500-SLOC cap; the tests themselves are unchanged. Coverage: repos-root
//! resolution + `TRUSTY_MPM_REPOS_ROOT` precedence, old-layout migration
//! (`ensure_base_clone` + `migrate_old_layout_aside`), per-session worktree
//! creation, and `.git/info/exclude` idempotency.
//! What: pure-function + real-temp-repo assertions over the module's public
//! and private surface (reachable via `use super::*`).
//! Test: this IS the test module.

use super::*;

/// #1807: `tm launch` and the daemon in-project path must resolve the managed
/// repo root through the SAME function so a lone `TRUSTY_MPM_REPOS_ROOT` cannot
/// send them to different roots.
///
/// Why: before the fix, the daemon path used `base_clone_path` (which honours
/// `TRUSTY_MPM_REPOS_ROOT`) while `tm launch` used `workspace_subpath` (which
/// does NOT), so setting only `TRUSTY_MPM_REPOS_ROOT` re-diverged the roots.
/// This locks in that BOTH entry points now call `base_clone_path`, and proves
/// the old `workspace_subpath` path really did diverge (guarding against a
/// regression that reverts `tm launch` to it).
/// Test: this function IS the test.
#[test]
fn launch_and_daemon_agree_on_repos_root_env() {
    let _g = crate::core::trusty_tools_config::env_test_lock();

    // The #1807 scenario: ONLY TRUSTY_MPM_REPOS_ROOT is set (no WORKSPACE_ROOT).
    // SAFETY: guarded by the crate-wide env_test_lock; both vars restored below.
    unsafe {
        std::env::set_var(REPOS_ROOT_ENV, "/explicit/repos/root");
        std::env::remove_var(crate::core::trusty_tools_config::WORKSPACE_ROOT_ENV);
    }

    // Daemon in-project path AND (post-fix) `tm launch` both resolve via this.
    let unified = base_clone_path("owner", "repo");

    // The PRE-fix `tm launch` path resolved via workspace_subpath → workspace_root,
    // which ignores TRUSTY_MPM_REPOS_ROOT.
    let cfg = crate::core::trusty_tools_config::TrustyToolsConfig::load();
    let gh = trusty_common::github_path::GithubPath {
        owner: "owner".into(),
        repo: "repo".into(),
    };
    let pre_fix_launch = crate::core::trusty_tools_config::workspace_subpath(&cfg, &gh);

    // SAFETY: guarded by env_test_lock.
    unsafe { std::env::remove_var(REPOS_ROOT_ENV) };

    assert_eq!(
        unified,
        PathBuf::from("/explicit/repos/root/owner/repo"),
        "the unified resolver (used by BOTH entry points) must honour \
             TRUSTY_MPM_REPOS_ROOT"
    );
    assert_ne!(
        unified, pre_fix_launch,
        "the pre-#1807 tm launch path (workspace_subpath) diverged from the \
             daemon root; tm launch must now use base_clone_path instead"
    );
}

/// #1805: `ensure_base_clone` must migrate a pre-existing old-layout dir aside
/// (non-empty, no top-level `.git`) and then successfully clone the fresh base,
/// instead of failing and silently falling back to full-clone-per-session.
///
/// Why: this is the exact scenario observed on `bobmatnyc/trusty-tools` — 37
/// stale UUID full-clone subdirs with no top-level `.git`. Cloning into that
/// non-empty dir fails, so the new `.worktrees/` layout never engaged.
/// Non-tautology proof: the backup-path prefix is derived from the PUBLIC
/// constant `OLD_LAYOUT_BACKUP_SUFFIX`, and the assertions check both that the
/// OLD marker survived in the backup AND that a NEW `.git` now exists at the
/// base — a silent-fallback (no migration) would leave the marker at the base
/// and no `.git`, failing both.
/// Test: this function IS the test.
#[test]
fn ensure_base_clone_migrates_old_layout_dir_aside() {
    // 1. Build a real source repo to clone from.
    let src = crate::test_support::hermetic_temp_dir();
    let src_path = src.path();
    let init = std::process::Command::new("git")
        .args(["init", src_path.to_str().expect("src utf8")])
        .output()
        .expect("git init src");
    assert!(init.status.success(), "git init src failed");
    for (k, v) in [("user.email", "t@example.com"), ("user.name", "T")] {
        let ok = std::process::Command::new("git")
            .args(["-C", src_path.to_str().expect("utf8"), "config", k, v])
            .status()
            .expect("git config");
        assert!(ok.success(), "git config {k} failed");
    }
    std::fs::write(src_path.join("README"), b"src").expect("write README");
    let add = std::process::Command::new("git")
        .args(["-C", src_path.to_str().expect("utf8"), "add", "."])
        .status()
        .expect("git add");
    assert!(add.success(), "git add failed");
    let commit = std::process::Command::new("git")
        .args([
            "-C",
            src_path.to_str().expect("utf8"),
            "commit",
            "-m",
            "init",
        ])
        .status()
        .expect("git commit");
    assert!(commit.success(), "git commit failed");

    // 2. Build an OLD-LAYOUT base dir: <parent>/owner/repo/ containing a fake
    //    per-session UUID full-clone subdir and NO top-level `.git`.
    let parent = crate::test_support::hermetic_temp_dir();
    let base = parent.path().join("owner").join("repo");
    let old_session = base.join("00000000-old-session-uuid");
    std::fs::create_dir_all(&old_session).expect("create old-layout subdir");
    std::fs::write(old_session.join("MARKER"), b"legacy").expect("write marker");
    assert!(
        !base.join(".git").exists(),
        "precondition: no top-level .git"
    );

    // 3. ensure_base_clone must migrate the old dir aside and clone fresh.
    let url = src_path.to_str().expect("src url utf8");
    ensure_base_clone(url, &base).expect("ensure_base_clone must migrate + clone");

    // 4. The base now holds a FRESH clone (top-level `.git` present).
    assert!(
        base.join(".git").exists(),
        "fresh shared-base clone must exist at the base path after migration"
    );

    // 5. A sibling backup dir carrying the documented suffix must exist and
    //    still contain the OLD marker (data preserved, not deleted).
    let repo_parent = base.parent().expect("base has parent");
    let backup = std::fs::read_dir(repo_parent)
        .expect("read owner dir")
        .filter_map(Result::ok)
        .map(|e| e.path())
        .find(|p| {
            p.file_name()
                .and_then(|n| n.to_str())
                .map(|n| n.contains(OLD_LAYOUT_BACKUP_SUFFIX))
                .unwrap_or(false)
        })
        .expect("a migrated backup dir must exist");
    assert!(
        backup
            .join("00000000-old-session-uuid")
            .join("MARKER")
            .exists(),
        "the old per-session data must be preserved under the backup dir"
    );
}

/// #1805: the migrator must be a no-op for the cases that are NOT old-layout —
/// an empty base dir and a dir that already contains `.git`.
///
/// Why: git clone succeeds into an empty/absent dir, and an existing `.git` is
/// the reuse path handled by the caller; migrating either would be destructive
/// and wrong. This guards the precise old-layout signature.
/// Test: this function IS the test.
#[test]
fn migrate_old_layout_aside_ignores_empty_and_git_dirs() {
    // Empty dir → Ok(None), dir untouched.
    let empty = crate::test_support::hermetic_temp_dir();
    let empty_base = empty.path().join("owner").join("repo");
    std::fs::create_dir_all(&empty_base).expect("create empty base");
    assert!(
        migrate_old_layout_aside(&empty_base)
            .expect("empty dir must not error")
            .is_none(),
        "an empty base dir must not be migrated"
    );
    assert!(empty_base.is_dir(), "empty base dir must remain in place");

    // Dir with a top-level `.git` → Ok(None), dir untouched.
    let git = crate::test_support::hermetic_temp_dir();
    let git_base = git.path().join("owner").join("repo");
    std::fs::create_dir_all(git_base.join(".git")).expect("create .git");
    std::fs::write(git_base.join("file"), b"x").expect("write file");
    assert!(
        migrate_old_layout_aside(&git_base)
            .expect("git dir must not error")
            .is_none(),
        "a dir with a top-level .git must not be migrated"
    );
    assert!(
        git_base.join(".git").is_dir(),
        ".git dir must remain in place"
    );

    // Absent path → Ok(None).
    let absent = git.path().join("does").join("not").join("exist");
    assert!(
        migrate_old_layout_aside(&absent)
            .expect("absent path must not error")
            .is_none(),
        "an absent path must not be migrated"
    );
}

#[test]
fn try_inproject_spawn_returns_none_for_non_git_path() {
    // A directory that is not a git repo must return Ok(None), not an error.
    let tmp = std::env::temp_dir();
    let result = try_inproject_spawn(&tmp);
    assert!(
        matches!(result, Ok(None)),
        "non-git path should yield Ok(None), got {result:?}"
    );
}

#[test]
fn get_origin_url_returns_none_for_non_git() {
    // A non-git directory should return None cleanly.
    let tmp = std::env::temp_dir();
    assert!(get_origin_url(&tmp).is_none());
}

#[test]
fn repos_root_default_ends_with_canonical_segment() {
    // Without env overrides, repos_root() must resolve to ~/trusty-mpm-projects
    // (the canonical base — same root as workspace_root()).
    // Skip when env is overridden so CI with custom roots doesn't false-fail.
    if std::env::var(REPOS_ROOT_ENV).is_ok()
        || std::env::var(crate::core::trusty_tools_config::WORKSPACE_ROOT_ENV).is_ok()
    {
        return;
    }
    let root = repos_root();
    assert!(
        root.ends_with(DEFAULT_REPOS_DIR),
        "repos_root() default must end with '{DEFAULT_REPOS_DIR}', got {}",
        root.display()
    );
}

#[test]
fn base_clone_path_resolves_to_canonical_root() {
    // Without env overrides, base_clone_path must return
    // ~/trusty-mpm-projects/<owner>/<repo> (#1803).
    if std::env::var(REPOS_ROOT_ENV).is_ok()
        || std::env::var(crate::core::trusty_tools_config::WORKSPACE_ROOT_ENV).is_ok()
    {
        return;
    }
    let base = base_clone_path("myorg", "myrepo");
    assert!(
        base.ends_with("trusty-mpm-projects/myorg/myrepo"),
        "base_clone_path must resolve to …/trusty-mpm-projects/myorg/myrepo, got {}",
        base.display()
    );
}

#[test]
fn session_worktree_path_uses_dot_prefix() {
    // create_session_worktree must place the worktree at
    // <base>/.worktrees/<worktree_name> (dot-prefixed) so it is gitignored via
    // .git/info/exclude (#1803). Since #2032 `worktree_name` is the resolved
    // SEMANTIC tmux name (e.g. `tm-trusty-tools-01`), not a raw session UUID.
    // We call the PRODUCTION function against a real temporary git repository
    // (with an initial commit so `git worktree add` can branch from HEAD) and
    // assert: (a) path is under <base>/.worktrees/, (b) ends with the name,
    // (c) the directory actually exists after the call.
    //
    // Non-tautology proof: `expected_parent` is hardcoded as `base.join(".worktrees")`
    // — NOT derived from production code. If `create_session_worktree` changed
    // to `base_path.join("worktrees").join(...)` the `starts_with` assertion
    // would fail because `base/worktrees/<name>` does NOT start with `base/.worktrees`.
    let tmp = crate::test_support::hermetic_temp_dir();
    let base = tmp.path();

    // Initialise a real git repo so `git worktree add` can run.
    let init = std::process::Command::new("git")
        .args(["init", base.to_str().expect("base is utf8")])
        .output()
        .expect("git init");
    assert!(
        init.status.success(),
        "git init failed: {}",
        String::from_utf8_lossy(&init.stderr)
    );

    // Configure identity (required for `git commit`).
    for (k, v) in [("user.email", "test@example.com"), ("user.name", "Test")] {
        let ok = std::process::Command::new("git")
            .args(["-C", base.to_str().expect("base is utf8"), "config", k, v])
            .status()
            .expect("git config");
        assert!(ok.success(), "git config {k} failed");
    }

    // Create an initial commit so HEAD exists and `git worktree add -b` works.
    std::fs::write(base.join("README"), b"init").expect("write README");
    let add = std::process::Command::new("git")
        .args(["-C", base.to_str().expect("base is utf8"), "add", "."])
        .status()
        .expect("git add");
    assert!(add.success(), "git add failed");
    let commit = std::process::Command::new("git")
        .args([
            "-C",
            base.to_str().expect("base is utf8"),
            "commit",
            "-m",
            "init",
        ])
        .status()
        .expect("git commit");
    assert!(commit.success(), "git commit failed");

    // Call the production function.
    let name = "tm-test-repo-01";
    let worktree_path =
        create_session_worktree(base, name, &crate::session_manager::ManagedSessionId::new())
            .expect("create_session_worktree must succeed on a real git repo");

    // (a) Path must be under <base>/.worktrees/ — hardcoded, not from production.
    let expected_parent = base.join(".worktrees");
    assert!(
        worktree_path.starts_with(&expected_parent),
        "worktree must be under <base>/.worktrees/, got {}",
        worktree_path.display()
    );

    // (b) Path must end with the semantic worktree name.
    assert!(
        worktree_path.ends_with(name),
        "worktree path must end with worktree name {name}, got {}",
        worktree_path.display()
    );

    // (c) The directory must actually exist (git worktree was created on disk).
    assert!(
        worktree_path.is_dir(),
        "worktree directory must exist on disk, got {}",
        worktree_path.display()
    );
}

/// Issue #2032: a worktree directory OR branch that already exists for a
/// candidate name must be detected by [`worktree_name_collides`] so
/// `SessionManager::resolve_session_name`'s extra-collision predicate steers
/// away from it instead of `create_session_worktree` silently clobbering (or
/// confusingly erroring on) it.
///
/// Why: the tmux-liveness check alone cannot see git worktrees/branches — a
/// stale worktree left behind by a hand-deleted-but-not-decommissioned
/// session must still be treated as a collision.
/// What: (a) an absent name must not collide; (b) after creating a worktree
/// for a name, THAT SAME name must collide (both the dir and the branch
/// exist); (c) a name whose branch exists but whose worktree dir was manually
/// removed must still collide (branch-only check).
/// Test: this function IS the test.
#[test]
fn worktree_name_collides_detects_existing_dir_and_branch() {
    let tmp = crate::test_support::hermetic_temp_dir();
    let base = tmp.path();

    let init = std::process::Command::new("git")
        .args(["init", base.to_str().expect("base is utf8")])
        .output()
        .expect("git init");
    assert!(init.status.success(), "git init failed");
    for (k, v) in [("user.email", "test@example.com"), ("user.name", "Test")] {
        let ok = std::process::Command::new("git")
            .args(["-C", base.to_str().expect("utf8"), "config", k, v])
            .status()
            .expect("git config");
        assert!(ok.success(), "git config {k} failed");
    }
    std::fs::write(base.join("README"), b"init").expect("write README");
    let add = std::process::Command::new("git")
        .args(["-C", base.to_str().expect("utf8"), "add", "."])
        .status()
        .expect("git add");
    assert!(add.success(), "git add failed");
    let commit = std::process::Command::new("git")
        .args(["-C", base.to_str().expect("utf8"), "commit", "-m", "init"])
        .status()
        .expect("git commit");
    assert!(commit.success(), "git commit failed");

    // (a) No collision before anything exists.
    assert!(
        !worktree_name_collides(base, "tm-fresh-01"),
        "an unused name must not collide"
    );

    // (b) After creating the worktree, the SAME name must collide.
    create_session_worktree(
        base,
        "tm-fresh-01",
        &crate::session_manager::ManagedSessionId::new(),
    )
    .expect("create_session_worktree");
    assert!(
        worktree_name_collides(base, "tm-fresh-01"),
        "an in-use name (dir + branch both exist) must collide"
    );

    // (c) Remove the worktree directory (but not the branch) via `git worktree
    // remove`, which deletes the dir but leaves the branch ref intact — the
    // branch-only check must still report a collision.
    let remove = std::process::Command::new("git")
        .arg("-C")
        .arg(base)
        .args(["worktree", "remove", "--force"])
        .arg(base.join(".worktrees").join("tm-fresh-01"))
        .output()
        .expect("git worktree remove");
    assert!(
        remove.status.success(),
        "git worktree remove failed: {}",
        String::from_utf8_lossy(&remove.stderr)
    );
    assert!(
        !base.join(".worktrees").join("tm-fresh-01").exists(),
        "worktree dir must be gone after `git worktree remove`"
    );
    assert!(
        worktree_name_collides(base, "tm-fresh-01"),
        "a name whose branch still exists must still collide even after the \
         worktree dir was removed"
    );
}

/// Issue #2032: [`create_session_worktree`] must refuse to clobber an
/// existing worktree directory rather than silently overwriting it.
///
/// Why: `worktree_name_collides` is the PROACTIVE guard used by name
/// resolution; this is the DEFENSIVE guard inside `create_session_worktree`
/// itself, covering a caller that skips the collision check (or a TOCTOU
/// race).
/// What: creates a worktree for a name, then calls `create_session_worktree`
/// again for the SAME name and asserts it returns `Err` (not a panic, not a
/// silent overwrite) and that the original worktree directory is untouched.
/// Test: this function IS the test.
#[test]
fn create_session_worktree_rejects_existing_worktree_dir() {
    let tmp = crate::test_support::hermetic_temp_dir();
    let base = tmp.path();

    let init = std::process::Command::new("git")
        .args(["init", base.to_str().expect("base is utf8")])
        .output()
        .expect("git init");
    assert!(init.status.success(), "git init failed");
    for (k, v) in [("user.email", "test@example.com"), ("user.name", "Test")] {
        let ok = std::process::Command::new("git")
            .args(["-C", base.to_str().expect("utf8"), "config", k, v])
            .status()
            .expect("git config");
        assert!(ok.success(), "git config {k} failed");
    }
    std::fs::write(base.join("README"), b"init").expect("write README");
    let add = std::process::Command::new("git")
        .args(["-C", base.to_str().expect("utf8"), "add", "."])
        .status()
        .expect("git add");
    assert!(add.success(), "git add failed");
    let commit = std::process::Command::new("git")
        .args(["-C", base.to_str().expect("utf8"), "commit", "-m", "init"])
        .status()
        .expect("git commit");
    assert!(commit.success(), "git commit failed");

    let first = create_session_worktree(
        base,
        "tm-dup-01",
        &crate::session_manager::ManagedSessionId::new(),
    )
    .expect("first create must succeed");
    assert!(first.is_dir(), "first worktree must exist");

    let second = create_session_worktree(
        base,
        "tm-dup-01",
        &crate::session_manager::ManagedSessionId::new(),
    );
    assert!(
        second.is_err(),
        "creating a worktree for an already-existing name must error, not clobber"
    );
    assert!(
        first.is_dir(),
        "the original worktree must remain untouched after the rejected re-create"
    );
}

#[test]
fn ensure_worktrees_gitignored_idempotent() {
    // ensure_worktrees_gitignored must write .worktrees/ to .git/info/exclude
    // exactly ONCE even when called multiple times (idempotent) (#1803).
    let tmp = crate::test_support::hermetic_temp_dir();
    let base = tmp.path();
    // Create a minimal .git dir (not a real git repo, but enough for the function).
    std::fs::create_dir_all(base.join(".git")).expect("create .git");

    // First call: must write the entry.
    ensure_worktrees_gitignored(base).expect("first call must succeed");

    let exclude = base.join(".git").join("info").join("exclude");
    let content1 = std::fs::read_to_string(&exclude).expect("exclude readable");
    let count1 = content1
        .lines()
        .filter(|l| l.trim() == ".worktrees/")
        .count();
    assert_eq!(
        count1, 1,
        "must contain exactly one .worktrees/ entry after first call"
    );

    // Second call: must NOT duplicate the entry.
    ensure_worktrees_gitignored(base).expect("second call must succeed (idempotent)");
    let content2 = std::fs::read_to_string(&exclude).expect("exclude readable");
    let count2 = content2
        .lines()
        .filter(|l| l.trim() == ".worktrees/")
        .count();
    assert_eq!(
        count2, 1,
        "second call must not add a duplicate .worktrees/ entry"
    );
}

/// #1919 regression guard: [`ensure_base_clone`] must emit a `CloningRepo`
/// stage event on the actual first-run clone — the exact "tm: first run for
/// X — cloning into ..." scenario #1904 set out to make observable — and must
/// NOT re-emit it on a subsequent idempotent call against an already-present
/// base clone (the reuse path takes the early `Ok(())` return above the emit
/// site and never runs `git clone` again).
///
/// Why: this is the single most important observable gap #1919 identified —
/// `try_inproject_spawn` (and therefore `ensure_base_clone`) runs from inside
/// `spawn_managed`'s `is_local_workdir` branch, several layers below any
/// `emit(...)` call `provision_in` already had; before this fix nothing in
/// the in-project path announced the clone stage at all.
/// What: builds a real local source repo (same fixture pattern as
/// `ensure_base_clone_migrates_old_layout_dir_aside`), calls `ensure_base_clone`
/// once inside a fresh `provisioning_stage::scoped` (asserting exactly one
/// `CloningRepo` event, since the base dir does not yet exist), then calls it
/// again inside a SECOND fresh scope against the now-existing base clone
/// (asserting ZERO events, proving the reuse path is silent).
/// Test: this function IS the test.
#[tokio::test]
async fn ensure_base_clone_emits_cloning_repo_only_on_fresh_clone() {
    use crate::core::provisioning_stage::{ProvisioningStage, StageEmitter, scoped};

    // 1. Build a real source repo to clone from (mirrors the fixture used by
    //    `ensure_base_clone_migrates_old_layout_dir_aside` above).
    let src = crate::test_support::hermetic_temp_dir();
    let src_path = src.path();
    let init = std::process::Command::new("git")
        .args(["init", src_path.to_str().expect("src utf8")])
        .output()
        .expect("git init src");
    assert!(init.status.success(), "git init src failed");
    for (k, v) in [("user.email", "t@example.com"), ("user.name", "T")] {
        let ok = std::process::Command::new("git")
            .args(["-C", src_path.to_str().expect("utf8"), "config", k, v])
            .status()
            .expect("git config");
        assert!(ok.success(), "git config {k} failed");
    }
    std::fs::write(src_path.join("README"), b"src").expect("write README");
    let add = std::process::Command::new("git")
        .args(["-C", src_path.to_str().expect("utf8"), "add", "."])
        .status()
        .expect("git add");
    assert!(add.success(), "git add failed");
    let commit = std::process::Command::new("git")
        .args([
            "-C",
            src_path.to_str().expect("utf8"),
            "commit",
            "-m",
            "init",
        ])
        .status()
        .expect("git commit");
    assert!(commit.success(), "git commit failed");

    let parent = crate::test_support::hermetic_temp_dir();
    let base = parent.path().join("owner").join("repo");
    let url = src_path.to_str().expect("src url utf8").to_string();

    // 2. Fresh clone: exactly one CloningRepo event.
    let (tx1, mut rx1) = tokio::sync::broadcast::channel(8);
    let emitter1 = StageEmitter::new("s-1", "https://example.com/owner/repo", tx1);
    let base_for_clone = base.clone();
    let url_for_clone = url.clone();
    scoped(emitter1, async move {
        ensure_base_clone(&url_for_clone, &base_for_clone)
            .expect("first ensure_base_clone must succeed (fresh clone)");
    })
    .await;

    let mut stages1 = Vec::new();
    while let Ok(value) = rx1.try_recv() {
        stages1.push(value["stage"].as_str().unwrap().to_string());
    }
    assert_eq!(
        stages1,
        vec![ProvisioningStage::CloningRepo.wire_name()],
        "a fresh base clone must emit exactly one CloningRepo stage event"
    );

    // 3. Idempotent reuse: zero events (the base clone already exists).
    let (tx2, mut rx2) = tokio::sync::broadcast::channel(8);
    let emitter2 = StageEmitter::new("s-2", "https://example.com/owner/repo", tx2);
    scoped(emitter2, async move {
        ensure_base_clone(&url, &base).expect("second ensure_base_clone must succeed (reuse)");
    })
    .await;

    let mut stages2 = Vec::new();
    while let Ok(value) = rx2.try_recv() {
        stages2.push(value["stage"].as_str().unwrap().to_string());
    }
    assert!(
        stages2.is_empty(),
        "reusing an existing base clone must NOT re-emit CloningRepo, got: {stages2:?}"
    );
}

/// #2189: [`create_session_worktree`] must leave the new session branch with a
/// working `git pull` (upstream tracking `origin/<default>`) WITHOUT letting a
/// bare `git push` target the default branch.
///
/// Why: before this fix the new `session/<name>` branch had no upstream at
/// all, so `git pull` inside a session worktree failed with "There is no
/// tracking information for the current branch." Naively setting the
/// upstream to `origin/<default>` would fix `pull` but ALSO make a bare `git
/// push` try to push session commits onto the shared default branch — this
/// test proves both halves: pull-tracking works AND push is scoped to the
/// worktree's own branch.
/// What: builds a real bare `origin` remote with one commit on `main`, clones
/// it into `base` (mirroring what `ensure_base_clone` produces in
/// production — `origin` wired up, `refs/remotes/origin/HEAD` set), then
/// calls the production `create_session_worktree` and asserts: (a) `git -C
/// <worktree> rev-parse --abbrev-ref --symbolic-full-name @{u}` resolves to
/// `origin/main`; (b) `git -C <worktree> config --worktree push.default` ==
/// `"current"`; (c) `git -C <base> config extensions.worktreeConfig` ==
/// `"true"`.
/// Test: this function IS the test.
#[test]
fn create_session_worktree_sets_pull_upstream_and_worktree_scoped_push() {
    // 1. A real bare `origin` remote, explicitly on `main` so the assertions
    //    below are not at the mercy of the host's `init.defaultBranch`.
    let origin_dir = crate::test_support::hermetic_temp_dir();
    let origin_path = origin_dir.path();
    let init = std::process::Command::new("git")
        .args([
            "init",
            "--bare",
            "-b",
            "main",
            origin_path.to_str().expect("origin utf8"),
        ])
        .output()
        .expect("git init --bare origin");
    assert!(
        init.status.success(),
        "git init --bare origin failed: {}",
        String::from_utf8_lossy(&init.stderr)
    );

    // 2. Seed the bare origin with one commit via a scratch clone (a bare repo
    //    has no working tree to commit into directly).
    let seed = crate::test_support::hermetic_temp_dir();
    let seed_path = seed.path();
    let clone_seed = std::process::Command::new("git")
        .args([
            "clone",
            origin_path.to_str().expect("origin utf8"),
            seed_path.to_str().expect("seed utf8"),
        ])
        .output()
        .expect("git clone seed");
    assert!(
        clone_seed.status.success(),
        "git clone seed failed: {}",
        String::from_utf8_lossy(&clone_seed.stderr)
    );
    for (k, v) in [("user.email", "t@example.com"), ("user.name", "T")] {
        let ok = std::process::Command::new("git")
            .args(["-C", seed_path.to_str().expect("seed utf8"), "config", k, v])
            .status()
            .expect("git config");
        assert!(ok.success(), "git config {k} failed");
    }
    std::fs::write(seed_path.join("README"), b"seed").expect("write README");
    let add = std::process::Command::new("git")
        .args(["-C", seed_path.to_str().expect("seed utf8"), "add", "."])
        .status()
        .expect("git add");
    assert!(add.success(), "git add failed");
    let commit = std::process::Command::new("git")
        .args([
            "-C",
            seed_path.to_str().expect("seed utf8"),
            "commit",
            "-m",
            "init",
        ])
        .status()
        .expect("git commit");
    assert!(commit.success(), "git commit failed");
    let push_seed = std::process::Command::new("git")
        .args([
            "-C",
            seed_path.to_str().expect("seed utf8"),
            "push",
            "origin",
            "main",
        ])
        .status()
        .expect("git push seed");
    assert!(push_seed.success(), "git push seed failed");

    // 3. Clone the now-non-empty bare origin into `base` — this mirrors what
    //    `ensure_base_clone` produces in production: `origin` remote wired up
    //    and `refs/remotes/origin/HEAD` set by the clone itself.
    let base_parent = crate::test_support::hermetic_temp_dir();
    let base = base_parent.path().join("base");
    let clone_base = std::process::Command::new("git")
        .args([
            "clone",
            origin_path.to_str().expect("origin utf8"),
            base.to_str().expect("base utf8"),
        ])
        .output()
        .expect("git clone base");
    assert!(
        clone_base.status.success(),
        "git clone base failed: {}",
        String::from_utf8_lossy(&clone_base.stderr)
    );
    for (k, v) in [("user.email", "t@example.com"), ("user.name", "T")] {
        let ok = std::process::Command::new("git")
            .args(["-C", base.to_str().expect("base utf8"), "config", k, v])
            .status()
            .expect("git config");
        assert!(ok.success(), "git config {k} failed");
    }

    // 4. Call the production function under test.
    let worktree_path = create_session_worktree(
        &base,
        "tm-pull-01",
        &crate::session_manager::ManagedSessionId::new(),
    )
    .expect("create_session_worktree must succeed");

    // (a) `git pull` must work: @{u} resolves to origin/main.
    let upstream = std::process::Command::new("git")
        .arg("-C")
        .arg(&worktree_path)
        .args(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"])
        .output()
        .expect("git rev-parse @{u}");
    assert!(
        upstream.status.success(),
        "worktree branch must have an upstream set (git pull must work): {}",
        String::from_utf8_lossy(&upstream.stderr)
    );
    assert_eq!(
        String::from_utf8_lossy(&upstream.stdout).trim(),
        "origin/main",
        "worktree branch upstream must track origin/main"
    );

    // (b) push.default=current must be scoped to THIS worktree only, so a
    // bare `git push` targets `origin/session/tm-pull-01`, never `main`.
    let push_default = std::process::Command::new("git")
        .arg("-C")
        .arg(&worktree_path)
        .args(["config", "--worktree", "push.default"])
        .output()
        .expect("git config --worktree push.default");
    assert!(
        push_default.status.success(),
        "worktree-scoped push.default must be set: {}",
        String::from_utf8_lossy(&push_default.stderr)
    );
    assert_eq!(
        String::from_utf8_lossy(&push_default.stdout).trim(),
        "current",
        "push.default must be worktree-scoped to 'current' so push never targets main"
    );

    // (c) extensions.worktreeConfig must be enabled on the base clone —
    // required for the worktree-scoped config in (b) to take effect at all.
    let ext = std::process::Command::new("git")
        .arg("-C")
        .arg(&base)
        .args(["config", "extensions.worktreeConfig"])
        .output()
        .expect("git config extensions.worktreeConfig");
    assert!(
        ext.status.success(),
        "extensions.worktreeConfig must be set on the base clone"
    );
    assert_eq!(
        String::from_utf8_lossy(&ext.stdout).trim(),
        "true",
        "extensions.worktreeConfig must be true"
    );

    // (d) #2867: the foreign upstream is only ever armed behind an EFFECTIVE
    // push pin. Assert the pin as `git push` itself resolves it (full config
    // stack), not merely as a `--worktree`-scoped key.
    let effective = std::process::Command::new("git")
        .arg("-C")
        .arg(&worktree_path)
        .args(["config", "--get", "push.default"])
        .output()
        .expect("git config --get push.default");
    assert_eq!(
        String::from_utf8_lossy(&effective.stdout).trim(),
        "current",
        "the EFFECTIVE push.default (not just the --worktree key) must be `current` \
         whenever a foreign upstream is set (#2867)"
    );
}

/// #2867: [`super::push_is_pinned_to_current`] must report the EFFECTIVE
/// `push.default`, because that — not the exit code of the write that set it —
/// is what decides whether writing a foreign upstream is safe.
///
/// Why: the PR #2863 clobber came from a worktree whose branch tracked a ref it
/// did not own. `configure_session_branch_tracking` may only create that
/// tracking state while a bare `git push` is provably confined to the current
/// branch; if the detector returned `true` optimistically the gate would be
/// decorative.
/// What: builds a real repo, asserts the detector is `false` with no
/// `push.default` set and `false` for a non-`current` value, then enables
/// `extensions.worktreeConfig`, pins `push.default=current` in a linked
/// worktree, and asserts it flips to `true` there while a NON-pinned sibling
/// worktree still reports `false` — proving the detector reads worktree-scoped
/// config rather than the shared repo config.
/// Test: this function IS the test.
#[test]
fn push_pin_detection_matches_effective_config() {
    let repo_dir = crate::test_support::hermetic_temp_dir();
    let repo = repo_dir.path().to_path_buf();
    let git = |args: &[&str], cwd: &std::path::Path| -> bool {
        std::process::Command::new("git")
            .arg("-C")
            .arg(cwd)
            .args(args)
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
    };
    if !std::process::Command::new("git")
        .args(["init", "-q", "-b", "main"])
        .arg(&repo)
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
    {
        return; // git unavailable — nothing to assert
    }
    assert!(git(&["config", "user.email", "t@example.com"], &repo));
    assert!(git(&["config", "user.name", "T"], &repo));
    std::fs::write(repo.join("README"), b"seed").expect("write README");
    assert!(git(&["add", "."], &repo));
    assert!(git(&["commit", "-qm", "init"], &repo));

    assert!(
        !super::push_is_pinned_to_current(&repo),
        "an unset push.default must NOT be reported as pinned"
    );
    assert!(git(&["config", "push.default", "simple"], &repo));
    assert!(
        !super::push_is_pinned_to_current(&repo),
        "push.default=simple must NOT be reported as pinned"
    );

    // Two linked worktrees off the same repo: only one gets the pin.
    let wt_parent = crate::test_support::hermetic_temp_dir();
    let pinned = wt_parent.path().join("pinned");
    let unpinned = wt_parent.path().join("unpinned");
    assert!(git(
        &[
            "worktree",
            "add",
            "-q",
            "-b",
            "wt-a",
            pinned.to_str().unwrap()
        ],
        &repo
    ));
    assert!(git(
        &[
            "worktree",
            "add",
            "-q",
            "-b",
            "wt-b",
            unpinned.to_str().unwrap()
        ],
        &repo
    ));
    assert!(git(&["config", "extensions.worktreeConfig", "true"], &repo));
    assert!(git(
        &["config", "--worktree", "push.default", "current"],
        &pinned
    ));

    assert!(
        super::push_is_pinned_to_current(&pinned),
        "a worktree-scoped push.default=current must be reported as pinned"
    );
    assert!(
        !super::push_is_pinned_to_current(&unpinned),
        "a sibling worktree without the pin must NOT be reported as pinned — \
         the detector must read worktree-scoped config, not the shared repo config"
    );
}