trusty-mpm 1.8.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
//! Tests for the auto-`git init` decision and driver (#6274).
//!
//! Why: the decision has four arms an operator can hit on their first ever
//! `tm` run — initialize, leave alone, refuse, prerequisite error — and three
//! of them write (or deliberately do not write) to a real directory. #7749 adds
//! two refusals to the third arm, both driven by the downward child-repository
//! scan, and both asserted here twice: once on the pure decision with a canned
//! scan, once end to end against a real directory.
//! What: pure-decision tests for [`super::plan_auto_init`],
//! [`super::stderr_means_no_repository`] and the message builders, plus
//! driver tests that run real git against hermetic temp directories.
//! Test: this file.

use std::path::{Path, PathBuf};
use std::process::Command;

use super::{
    AutoInitOutcome, AutoInitPlan, AutoInitRefusal, RepoContext, classify_rev_parse_failure,
    ensure_git_repo_with, initialized_message, missing_git_error, plan_auto_init, refusal_message,
    stderr_means_no_repository,
};
use trusty_mpm::core::child_repo_scan::{ChildRepoScan, ScanIncomplete};

use crate::test_support::hermetic_temp_dir;

/// A program name no PATH entry can resolve, for the prerequisite arm.
const ABSENT_GIT: &str = "tm-test-no-such-git-executable-6274";

/// Run a real git command that must succeed, for fixture setup.
fn git_ok(dir: &Path, args: &[&str]) {
    let out = Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(args)
        .output()
        .expect("git must be installed to run these tests");
    assert!(
        out.status.success(),
        "git {args:?} failed in {}: {}",
        dir.display(),
        String::from_utf8_lossy(&out.stderr)
    );
}

/// `git rev-parse --show-toplevel` from `dir`, or `None` when there is none.
fn toplevel(dir: &Path) -> Option<PathBuf> {
    let out = Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(["rev-parse", "--show-toplevel"])
        .output()
        .ok()
        .filter(|o| o.status.success())?;
    Some(PathBuf::from(
        String::from_utf8_lossy(&out.stdout).trim().to_owned(),
    ))
}

// ── The pure decision ────────────────────────────────────────────────────────

/// The feature itself: a plain directory that is nobody's home earns an init.
#[test]
fn plan_initializes_a_plain_directory() {
    let plan = plan_auto_init(
        Path::new("/Users/someone/scratch/notes"),
        Some(Path::new("/Users/someone")),
        RepoContext::Absent,
        || ChildRepoScan::Clear,
    );
    assert_eq!(plan, AutoInitPlan::Init);
}

/// `$HOME` never gets a repository it did not already have — a `.git` there
/// silently adopts every descendant directory as part of one repo.
#[test]
fn plan_refuses_the_home_directory() {
    let home = Path::new("/Users/someone");
    assert_eq!(
        plan_auto_init(home, Some(home), RepoContext::Absent, || {
            ChildRepoScan::Clear
        }),
        AutoInitPlan::Refuse(AutoInitRefusal::HomeDirectory)
    );
}

/// Same for `/`, which has no parent.
#[test]
fn plan_refuses_the_filesystem_root() {
    assert_eq!(
        plan_auto_init(
            Path::new("/"),
            Some(Path::new("/Users/someone")),
            RepoContext::Absent,
            || ChildRepoScan::Clear
        ),
        AutoInitPlan::Refuse(AutoInitRefusal::FilesystemRoot)
    );
}

/// The guards must not fire on a directory that ALREADY is a repository: an
/// operator whose home directory is a dotfiles repo keeps today's behavior.
#[test]
fn plan_leaves_an_existing_repo_alone_even_in_the_home_directory() {
    let home = Path::new("/Users/someone");
    assert_eq!(
        plan_auto_init(home, Some(home), RepoContext::Present, || {
            ChildRepoScan::Clear
        }),
        AutoInitPlan::AlreadyGit
    );
}

/// With no resolvable home directory the plain-directory case still initializes.
#[test]
fn plan_initializes_when_the_home_directory_is_unknown() {
    assert_eq!(
        plan_auto_init(Path::new("/srv/project"), None, RepoContext::Absent, || {
            ChildRepoScan::Clear
        }),
        AutoInitPlan::Init
    );
}

/// FAILS BEFORE #7749: a directory with a repository beneath it planned `Init`,
/// and the `.git` that produced became an ancestor repository for that child.
#[test]
fn plan_refuses_a_workspace_parent() {
    let child = PathBuf::from("/Users/someone/workspace/packages/api");
    let plan = plan_auto_init(
        Path::new("/Users/someone/workspace"),
        Some(Path::new("/Users/someone")),
        RepoContext::Absent,
        || ChildRepoScan::Found(child.clone()),
    );
    assert_eq!(
        plan,
        AutoInitPlan::Refuse(AutoInitRefusal::WorkspaceParent(child))
    );
}

/// Fail-Open Check: a scan that could not finish is not an absence of child
/// repositories, so it refuses rather than initializing. FAILS BEFORE #7749,
/// which had no downward scan to be incomplete.
#[test]
fn plan_refuses_an_unfinished_scan() {
    let stop = ScanIncomplete::Unreadable {
        path: PathBuf::from("/Users/someone/workspace/locked"),
        error: "Permission denied (os error 13)".to_string(),
    };
    let plan = plan_auto_init(
        Path::new("/Users/someone/workspace"),
        Some(Path::new("/Users/someone")),
        RepoContext::Absent,
        || ChildRepoScan::Incomplete(stop.clone()),
    );
    assert_eq!(
        plan,
        AutoInitPlan::Refuse(AutoInitRefusal::ScanIncomplete(stop))
    );
}

/// The scan is the only guard that walks the filesystem, so it must not run for
/// a directory an earlier arm already decided — otherwise every `tm` invocation
/// inside a repository pays for a downward walk it cannot act on.
#[test]
fn plan_does_not_scan_when_an_earlier_guard_already_decided() {
    fn never() -> ChildRepoScan {
        panic!("the downward scan must not run once an earlier guard decided");
    }
    let home = Path::new("/Users/someone");
    assert_eq!(
        plan_auto_init(home, Some(home), RepoContext::Present, never),
        AutoInitPlan::AlreadyGit
    );
    assert_eq!(
        plan_auto_init(Path::new("/"), None, RepoContext::Absent, never),
        AutoInitPlan::Refuse(AutoInitRefusal::FilesystemRoot)
    );
    assert_eq!(
        plan_auto_init(home, Some(home), RepoContext::Absent, never),
        AutoInitPlan::Refuse(AutoInitRefusal::HomeDirectory)
    );
}

// ── The "is there a repository here" stderr discrimination ───────────────────

/// The long phrase is the only thing that means "no repository".
#[test]
fn no_repo_stderr_matches_the_long_phrase() {
    assert!(stderr_means_no_repository(
        "fatal: not a git repository (or any of the parent directories): .git"
    ));
}

/// A stale worktree pointer contains the SHORT phrase while meaning the
/// opposite — matching it would `git init` over a broken repository.
#[test]
fn no_repo_stderr_rejects_the_stale_worktree_pointer() {
    assert!(!stderr_means_no_repository(
        "fatal: not a git repository: (null)"
    ));
}

/// Any other failure (dubious ownership, permissions) is not "no repository".
#[test]
fn no_repo_stderr_rejects_an_unrelated_failure() {
    assert!(!stderr_means_no_repository(
        "fatal: detected dubious ownership in repository at '/srv/project'"
    ));
}

// ── Operator-facing messages ─────────────────────────────────────────────────

/// The notice says where the repository was created.
#[test]
fn initialized_message_names_the_directory() {
    let msg = initialized_message(Path::new("/srv/project"));
    assert_eq!(msg, "tm: initialized git in /srv/project");
}

/// A refusal states its reason, not just that it refused.
#[test]
fn refusal_message_names_the_home_directory() {
    let msg = refusal_message(&AutoInitRefusal::HomeDirectory, Path::new("/Users/someone"));
    assert!(msg.contains("/Users/someone"), "{msg}");
    assert!(msg.contains("home directory"), "{msg}");
}

/// Same for the filesystem-root arm.
#[test]
fn refusal_message_names_the_filesystem_root() {
    let msg = refusal_message(&AutoInitRefusal::FilesystemRoot, Path::new("/"));
    assert!(msg.contains("filesystem root"), "{msg}");
}

/// #7749: the refusal names the child repository, so the operator can see which
/// project a `.git` here would have been an ancestor of.
#[test]
fn refusal_message_names_the_child_repository() {
    let msg = refusal_message(
        &AutoInitRefusal::WorkspaceParent(PathBuf::from("/Users/someone/ws/api")),
        Path::new("/Users/someone/ws"),
    );
    assert!(msg.contains("/Users/someone/ws/api"), "{msg}");
    assert!(msg.contains("ancestor"), "{msg}");
    // #7749 review: the scan arms carry the seed guard's remedy, not the
    // site-guard trailer.
    assert!(
        msg.contains("run `git init` there yourself and retry"),
        "{msg}"
    );
    assert!(!msg.contains("Run tm from a project directory."), "{msg}");
}

/// #7749: an unfinished scan says what stopped it, which is the only thing the
/// operator can act on. #7749 review: and what to do about it — this arm fires
/// for any plain directory wider than the 256-directory scan budget, where the
/// old shared trailer ("Run tm from a project directory.") told an operator
/// already standing in their project to go stand in it.
#[test]
fn refusal_message_says_what_stopped_the_scan() {
    let msg = refusal_message(
        &AutoInitRefusal::ScanIncomplete(ScanIncomplete::BudgetExhausted),
        Path::new("/Users/someone/ws"),
    );
    assert!(msg.contains("could not rule out git repositories"), "{msg}");
    assert!(msg.contains("the scan stopped after checking"), "{msg}");
    assert!(
        msg.contains(
            "If /Users/someone/ws is a single project, run `git init` there yourself and \
             retry; otherwise run tm from the actual project directory."
        ),
        "{msg}"
    );
    assert!(!msg.contains("Run tm from a project directory."), "{msg}");
}

/// #7749 review: the site guards keep the trailer that is right for them —
/// nobody wants `git init` in `$HOME` or at `/`.
#[test]
fn refusal_message_keeps_the_site_trailer_for_home_and_root() {
    for (refusal, dir) in [
        (AutoInitRefusal::HomeDirectory, "/Users/someone"),
        (AutoInitRefusal::FilesystemRoot, "/"),
    ] {
        let msg = refusal_message(&refusal, Path::new(dir));
        assert!(msg.ends_with("Run tm from a project directory."), "{msg}");
        assert!(!msg.contains("git init"), "{msg}");
    }
}

/// The prerequisite error names `git` — this feature never installs the binary.
#[test]
fn missing_git_error_names_git_and_the_directory() {
    let msg = missing_git_error(Path::new("/srv/project")).to_string();
    assert!(msg.contains("`git` was not found on PATH"), "{msg}");
    assert!(msg.contains("/srv/project"), "{msg}");
}

// ── The driver, against real git ─────────────────────────────────────────────

/// The headline case: a plain directory becomes a repository rooted at itself.
#[test]
fn auto_init_initializes_a_plain_directory() {
    let tmp = hermetic_temp_dir();
    let dir = tmp.path().join("fresh-project");
    std::fs::create_dir(&dir).unwrap();

    let outcome = ensure_git_repo_with(&dir, Some(tmp.path()), "git").unwrap();

    assert_eq!(outcome, AutoInitOutcome::Initialized);
    assert!(dir.join(".git").is_dir(), "a .git directory must exist now");
    assert_eq!(
        toplevel(&dir).map(|p| p.canonicalize().unwrap()),
        Some(dir.canonicalize().unwrap()),
        "the repository root must be the invocation directory, not a parent"
    );
}

/// Regression for the pre-fix refusal path: the directory `tm` used to answer
/// "not in a git project" for is, after this call, exactly what
/// `classify_cwd_project` calls a usable project — with no origin remote.
#[test]
fn non_git_directory_now_classifies_as_a_usable_project() {
    use crate::commands::guided::{CwdProject, classify_cwd_project};

    let tmp = hermetic_temp_dir();
    let dir = tmp.path().join("plain");
    std::fs::create_dir(&dir).unwrap();
    assert!(
        matches!(classify_cwd_project(&dir), CwdProject::NotGit),
        "precondition: this is the directory tm used to refuse"
    );

    ensure_git_repo_with(&dir, Some(tmp.path()), "git").unwrap();

    assert!(
        matches!(classify_cwd_project(&dir), CwdProject::Usable(_)),
        "after auto-init tm must see an ordinary project here"
    );
    assert_eq!(
        trusty_mpm::daemon::managed_routes::inproject::get_origin_url(&dir).unwrap(),
        None,
        "a freshly initialized repo has no origin — the no-remote flow takes over"
    );
}

/// An existing repository root is left exactly as it was.
#[test]
fn auto_init_leaves_a_repo_root_alone() {
    let tmp = hermetic_temp_dir();
    let repo = tmp.path().join("repo");
    std::fs::create_dir(&repo).unwrap();
    git_ok(&repo, &["init"]);

    let outcome = ensure_git_repo_with(&repo, Some(tmp.path()), "git").unwrap();

    assert_eq!(outcome, AutoInitOutcome::AlreadyGit);
}

/// A directory INSIDE another repository's work tree — untracked, so it is not
/// part of that repo's tree — still must not get a nested repository: git is
/// already present there.
#[test]
fn auto_init_does_not_init_inside_another_work_tree() {
    let tmp = hermetic_temp_dir();
    let repo = tmp.path().join("repo");
    std::fs::create_dir(&repo).unwrap();
    git_ok(&repo, &["init"]);
    let nested = repo.join("untracked-notes");
    std::fs::create_dir(&nested).unwrap();

    let outcome = ensure_git_repo_with(&nested, Some(tmp.path()), "git").unwrap();

    assert_eq!(outcome, AutoInitOutcome::AlreadyGit);
    assert!(
        !nested.join(".git").exists(),
        "a nested repository must not be created inside another work tree"
    );
}

/// A bare repository has no work tree, so a `--show-toplevel` check would call
/// it a plain directory and re-initialize it. `--git-dir` does not.
#[test]
fn auto_init_leaves_a_bare_repository_alone() {
    let tmp = hermetic_temp_dir();
    let bare = tmp.path().join("origin.git");
    std::fs::create_dir(&bare).unwrap();
    git_ok(&bare, &["init", "--bare"]);

    let outcome = ensure_git_repo_with(&bare, Some(tmp.path()), "git").unwrap();

    assert_eq!(outcome, AutoInitOutcome::AlreadyGit);
}

/// The home-directory guard, end to end: nothing is written.
#[test]
fn auto_init_refuses_the_home_directory() {
    let tmp = hermetic_temp_dir();
    let home = tmp.path().join("home");
    std::fs::create_dir(&home).unwrap();

    let outcome = ensure_git_repo_with(&home, Some(&home), "git").unwrap();

    assert_eq!(
        outcome,
        AutoInitOutcome::Refused(AutoInitRefusal::HomeDirectory)
    );
    assert!(
        !home.join(".git").exists(),
        "the home directory must not become a repository"
    );
}

/// No git executable: a prerequisite error naming git, and nothing written.
#[test]
fn ensure_reports_a_missing_git_executable_without_writing() {
    let tmp = hermetic_temp_dir();
    let dir = tmp.path().join("plain");
    std::fs::create_dir(&dir).unwrap();

    let err = ensure_git_repo_with(&dir, Some(tmp.path()), ABSENT_GIT)
        .expect_err("a missing git executable must be an error, not a silent skip");

    assert!(
        err.to_string().contains("`git` was not found on PATH"),
        "{err}"
    );
    assert!(
        !dir.join(".git").exists(),
        "nothing may be written when git is unavailable"
    );
}

/// FAILS BEFORE #7749: `tm launch` in a workspace parent ran `git init` there,
/// and the `.git` became an ancestor repository for every child project. The
/// child is at depth 2, because a direct-children-only check would miss the
/// `packages/<name>` shape every JS monorepo produces.
#[test]
fn auto_init_refuses_a_workspace_parent_with_a_deep_child_repository() {
    let tmp = hermetic_temp_dir();
    let ws = tmp.path().join("workspace");
    let child = ws.join("packages").join("api");
    std::fs::create_dir_all(&child).unwrap();
    git_ok(&child, &["init"]);

    let outcome = ensure_git_repo_with(&ws, Some(tmp.path()), "git").unwrap();

    assert_eq!(
        outcome,
        AutoInitOutcome::Refused(AutoInitRefusal::WorkspaceParent(child))
    );
    assert!(
        !ws.join(".git").exists(),
        "a workspace parent must not become a repository"
    );
}

/// Fail-Open Check (#7749): a scan stopped by a permission error must refuse,
/// never fall through to `git init` — an unreadable subtree is exactly where a
/// child repository could be hiding.
#[cfg(unix)]
#[test]
fn auto_init_refuses_when_the_downward_scan_cannot_finish() {
    use std::os::unix::fs::PermissionsExt;
    let tmp = hermetic_temp_dir();
    let ws = tmp.path().join("workspace");
    let locked = ws.join("locked");
    std::fs::create_dir_all(&locked).unwrap();
    std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
    let _restore = RestoreMode(locked.clone());
    if std::fs::read_dir(&locked).is_ok() {
        eprintln!("#7749 test: running with permission overrides (root?), skipping");
        return;
    }

    let outcome = ensure_git_repo_with(&ws, Some(tmp.path()), "git").unwrap();

    match outcome {
        AutoInitOutcome::Refused(AutoInitRefusal::ScanIncomplete(ScanIncomplete::Unreadable {
            path,
            ..
        })) => assert_eq!(path, locked),
        other => panic!("an unreadable subtree must refuse the init, got {other:?}"),
    }
    assert!(
        !ws.join(".git").exists(),
        "nothing may be initialized while a child repository cannot be ruled out"
    );
}

/// Restores a locked-down directory's mode so `TempDir::drop` can remove it.
#[cfg(unix)]
struct RestoreMode(PathBuf);

#[cfg(unix)]
impl Drop for RestoreMode {
    fn drop(&mut self) {
        use std::os::unix::fs::PermissionsExt;
        let _ = std::fs::set_permissions(&self.0, std::fs::Permissions::from_mode(0o755));
    }
}

// ── git's verdict versus a `.git` above the directory (#9495) ────────────────

/// git's classic upward-discovery failure wording.
const CLASSIC_NO_REPO: &str =
    "fatal: not a git repository (or any of the parent directories): .git";

/// The file the fake git writes into its `-C` directory when asked to `init`.
const INIT_MARKER: &str = "fake-git-init-ran";

/// Write a `git` stand-in that fails `rev-parse` with `stderr` and records an
/// `init` as [`INIT_MARKER`] in the target directory.
///
/// Why: real git's no-repository wording depends on the host's mounts, so a
/// test that pins one wording needs a fake, and a fake `init` keeps a real
/// `git init` out of the fixture. #9034: exec'ing a file this process just
/// wrote can race a sibling test's fork (ETXTBSY), so the shim is probed until
/// it runs before the code under test sees it.
#[cfg(unix)]
fn fake_git(dir: &Path, stderr: &str) -> String {
    use std::os::unix::fs::PermissionsExt;
    // ETXTBSY is 26 on both Linux and macOS.
    const ETXTBSY: i32 = 26;
    let shim = dir.join("fake-git");
    let script = format!(
        "#!/bin/sh\ncase \"$3\" in\n  rev-parse) printf '%s\\n' '{stderr}' >&2; exit 128 ;;\n  \
         init) : > \"$2/{INIT_MARKER}\"; exit 0 ;;\nesac\nexit 0\n"
    );
    std::fs::write(&shim, script).unwrap();
    std::fs::set_permissions(&shim, std::fs::Permissions::from_mode(0o755)).unwrap();
    for _ in 0..100 {
        match Command::new(&shim).arg("probe").output() {
            Ok(_) => return shim.to_string_lossy().into_owned(),
            Err(e) if e.raw_os_error() == Some(ETXTBSY) => {
                std::thread::sleep(std::time::Duration::from_millis(20));
            }
            Err(e) => panic!("fake git at {} did not run: {e}", shim.display()),
        }
    }
    panic!("fake git at {} stayed busy (ETXTBSY)", shim.display());
}

/// Fail-Open Check (#9495): git's classic "no repository" wording under a real
/// `.git` must not reach `git init`. Discovery stops short of a real repository
/// for an unreadable `.git`, `GIT_CEILING_DIRECTORIES`, or a mount boundary,
/// and an init there nests a second repository inside the real checkout.
#[cfg(unix)]
#[test]
fn auto_init_refuses_the_classic_no_repo_wording_under_a_real_git() {
    let tmp = hermetic_temp_dir();
    let repo = tmp.path().join("real-repo");
    std::fs::create_dir_all(repo.join(".git")).unwrap();
    let dir = repo.join("sub");
    std::fs::create_dir(&dir).unwrap();
    let git = fake_git(tmp.path(), CLASSIC_NO_REPO);

    let result = ensure_git_repo_with(&dir, Some(tmp.path()), &git);

    assert!(
        !dir.join(INIT_MARKER).exists(),
        "git init must not run under a real .git, got {result:?}"
    );
    let err = result.expect_err("a .git above the directory must be an error, never an init");
    let expected = repo.canonicalize().unwrap().join(".git");
    assert!(
        err.to_string().contains(&expected.display().to_string()),
        "the error must name the .git it found: {err}"
    );
}

/// git's wording when upward discovery stops at a filesystem boundary, as on a
/// `/tmp` that is its own mount.
const MOUNT_BOUNDARY_NO_REPO: &str = "fatal: not a git repository (or any parent up to mount point /)\n\
     Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).";

/// FAILS BEFORE #9495: the mount-boundary wording did not match the full
/// "(or any of the parent directories)" clause, so a plain directory on its
/// own mount read as an unreadable verdict and every `tm` run there errored.
#[test]
fn classify_accepts_the_mount_boundary_wording_with_no_git_above() {
    let tmp = hermetic_temp_dir();
    let dir = tmp.path().join("plain");
    std::fs::create_dir(&dir).unwrap();

    let context = classify_rev_parse_failure(&dir, MOUNT_BOUNDARY_NO_REPO);

    assert_eq!(context.ok(), Some(RepoContext::Absent));
}

/// The classic wording with no `.git` above is still absence (#9495 keeps it).
#[test]
fn classify_accepts_the_classic_wording_with_no_git_above() {
    let tmp = hermetic_temp_dir();
    let dir = tmp.path().join("plain");
    std::fs::create_dir(&dir).unwrap();

    let context = classify_rev_parse_failure(&dir, CLASSIC_NO_REPO);

    assert_eq!(context.ok(), Some(RepoContext::Absent));
}

/// Fail-Open Check (#9495): the mount-boundary wording under a real `.git` is
/// discovery stopping short of a real repository, never absence.
#[test]
fn classify_refuses_the_mount_boundary_wording_under_a_real_git() {
    let tmp = hermetic_temp_dir();
    let repo = tmp.path().join("real-repo");
    std::fs::create_dir_all(repo.join(".git")).unwrap();
    let dir = repo.join("sub");
    std::fs::create_dir(&dir).unwrap();

    let context = classify_rev_parse_failure(&dir, MOUNT_BOUNDARY_NO_REPO);

    assert!(
        context.is_err(),
        "a .git above must not classify as Absent, got {context:?}"
    );
}

/// Every other `rev-parse` failure stays an error, as before #9495: the colon
/// forms name a broken repository, and the rest are not about discovery.
#[test]
fn classify_keeps_every_other_failure_an_error() {
    let tmp = hermetic_temp_dir();
    let dir = tmp.path().join("plain");
    std::fs::create_dir(&dir).unwrap();

    for stderr in [
        "fatal: not a git repository: (null)",
        "fatal: not a git repository: '/srv/project/.git'",
        "fatal: detected dubious ownership in repository at '/srv/project'",
        "fatal: cannot change to '/srv/project': Permission denied",
        "error: could not open '.git/HEAD': Permission denied",
    ] {
        let context = classify_rev_parse_failure(&dir, stderr);
        assert!(
            context.is_err(),
            "{stderr:?} must stay an error, got {context:?}"
        );
    }
}

// ── What `tm launch` does after a refusal ────────────────────────────────────

/// #7749 review: the route `tm launch` takes once this guard refuses, pinned
/// as observed rather than assumed.
///
/// A plain directory with more than `WORKSPACE_SCAN_BUDGET` subdirectories
/// refuses at `launch.rs:128` and nothing is initialized. The launch does NOT
/// stop there: `git config --get remote.origin.url` outside a repository exits
/// 1, which `get_origin_url` maps to `Ok(None)`, which `plan_for_origin` maps
/// to `OriginPlan::LiveCheckout` — so `launch` calls `connect` on a directory
/// that has no repository. `connect` performs no git check of its own, so the
/// refusal printed here is the operator's only explanation of why no managed
/// clone was made, which is why it now names the remedy.
#[test]
fn launch_route_after_a_scan_refusal_falls_through_to_the_live_checkout() {
    use crate::commands::origin_plan::{OriginPlan, plan_for_origin};
    use trusty_mpm::core::child_repo_scan::WORKSPACE_SCAN_BUDGET;

    let tmp = hermetic_temp_dir();
    let ws = tmp.path().join("wide-workspace");
    std::fs::create_dir(&ws).unwrap();
    for i in 0..=WORKSPACE_SCAN_BUDGET {
        std::fs::create_dir(ws.join(format!("d{i}"))).unwrap();
    }

    // Step 1 — `launch.rs:128`: the downward scan cannot finish, so the guard
    // refuses and writes nothing.
    let outcome = ensure_git_repo_with(&ws, Some(tmp.path()), "git").unwrap();
    assert_eq!(
        outcome,
        AutoInitOutcome::Refused(AutoInitRefusal::ScanIncomplete(
            ScanIncomplete::BudgetExhausted
        ))
    );
    assert!(!ws.join(".git").exists(), "nothing may be initialized");

    // Step 2 — `launch.rs` reads the origin of a directory with no repository.
    // This is `Ok(None)`, not an error: git-config exits 1 for a key it cannot
    // find, and outside a repository there is no key.
    let origin =
        trusty_mpm::daemon::managed_routes::inproject::get_origin_url(&ws).unwrap_or_else(|e| {
            panic!("git config outside a repository must not be an error, got: {e}")
        });
    assert_eq!(origin, None);

    // Step 3 — that is the live-checkout plan, so the launch continues into
    // `connect` against the un-initialized directory instead of stopping.
    assert_eq!(plan_for_origin(origin.as_deref()), OriginPlan::LiveCheckout);
}

/// A path that is not a directory is the caller's error to report; this call
/// stays silent and writes nothing.
#[test]
fn auto_init_skips_a_path_that_is_not_a_directory() {
    let tmp = hermetic_temp_dir();
    let missing = tmp.path().join("does-not-exist");

    let outcome = ensure_git_repo_with(&missing, Some(tmp.path()), "git").unwrap();

    assert_eq!(outcome, AutoInitOutcome::NotADirectory);
    assert!(!missing.exists(), "the path must not be created");
}