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
//! Unit tests for [`super`] (#2196).
//!
//! Why: split into a sibling `tests.rs` so the production `untracked_sync.rs`
//! stays comfortably under the 500-SLOC cap while these get the generous
//! 1500-SLOC test-file cap (mirrors `inproject/tests.rs`).
//! What: glob-matcher unit tests, `collect_matches`/`sync_untracked_files`
//! behaviour against real temp directories, the size cap, the path-escape
//! guard, a real-git-worktree round trip proving `.git/info/exclude` resolution
//! survives the linked-worktree gitlink indirection, and the #4733 refusals (a
//! broken repo copies nothing; a tracked path is never overwritten).
//!
//! #7497: the real-worktree fixtures call
//! `create_session_worktree_unchecked`, the ungated constructor — see
//! `inproject/tests.rs` for why a fixture opts out of the disk gate explicitly.
//! Test: this IS the test module.

use std::path::Path;

use super::*;

// ── glob_match ───────────────────────────────────────────────────────────

#[test]
fn glob_match_exact() {
    assert!(glob_match(".env", ".env"));
    assert!(!glob_match(".env", ".env.local"));
}

#[test]
fn glob_match_prefix() {
    assert!(glob_match(".env.*", ".env.local"));
    assert!(glob_match(".env.*", ".env.production"));
    assert!(!glob_match(".env.*", ".envrc"));
    assert!(
        !glob_match(".env.*", ".env"),
        "trailing '*' requires >=0 more chars after the dot"
    );
}

#[test]
fn glob_match_suffix() {
    assert!(glob_match("*.env", "prod.env"));
    assert!(glob_match("*.env", ".env"));
    assert!(!glob_match("*.env", "prod.env.bak"));
}

#[test]
fn glob_match_no_match() {
    assert!(!glob_match(".env", "not-env"));
    assert!(!glob_match(".env.*", "other-file.txt"));
}

// ── test fixtures ────────────────────────────────────────────────────────

/// Build a source checkout root with the fixture files the #2196 issue's
/// test plan names: `.env`, `.env.local`, `.env.local.bak` (must NOT match
/// `.env.local` exactly, nor `.env.*` since it has no trailing wildcard
/// continuation issue — `.env.local.bak` DOES start with `.env.` so it is
/// deliberately given a name that also proves the "only allowlisted
/// patterns, nothing broader" guarantee: `random.txt` never matches any
/// default pattern), an oversized file, and a `node_modules/` directory
/// (which must never be recursed into or copied as a whole).
fn make_source_fixture() -> tempfile::TempDir {
    let src = tempfile::TempDir::new().expect("src tmp dir");
    std::fs::write(src.path().join(".env"), b"SECRET=1").expect("write .env");
    std::fs::write(src.path().join(".env.local"), b"SECRET=2").expect("write .env.local");
    std::fs::write(src.path().join("random.txt"), b"not a secret").expect("write random.txt");

    std::fs::create_dir_all(src.path().join("node_modules/some-pkg")).expect("mkdir node_modules");
    std::fs::write(
        src.path().join("node_modules/some-pkg/.env"),
        b"nested, must not be touched by a top-level pattern",
    )
    .expect("write nested .env");

    let oversized = vec![0u8; (MAX_SYNC_FILE_BYTES + 1) as usize];
    std::fs::write(src.path().join(".env.oversized"), &oversized).expect("write oversized file");

    src
}

/// Default `.env*` allowlist used by most tests here (mirrors
/// `DEFAULT_UNTRACKED_SYNC_PATTERNS`).
fn default_patterns() -> Vec<String> {
    vec![".env".into(), ".env.local".into(), ".env.*".into()]
}

// ── sync_untracked_files: matching + non-matching + size cap + no-recurse ──

#[test]
fn syncs_matching_files_only() {
    let src = make_source_fixture();
    let dest = tempfile::TempDir::new().expect("dest tmp dir");

    sync_untracked_files(src.path(), dest.path(), &default_patterns());

    assert!(dest.path().join(".env").is_file(), ".env must be copied");
    assert!(
        dest.path().join(".env.local").is_file(),
        ".env.local must be copied"
    );
    assert!(
        !dest.path().join("random.txt").exists(),
        "non-matching file must NOT be copied"
    );
    assert!(
        !dest.path().join("node_modules").exists(),
        "node_modules/ must NOT be copied (directories are never matched)"
    );
    assert!(
        !dest.path().join(".env.oversized").exists(),
        "oversized file must be skipped, not copied"
    );

    assert_eq!(
        std::fs::read(dest.path().join(".env")).expect("read copied .env"),
        b"SECRET=1"
    );
}

#[test]
fn oversized_file_is_skipped() {
    let src = tempfile::TempDir::new().expect("src tmp dir");
    let oversized = vec![b'x'; (MAX_SYNC_FILE_BYTES + 1) as usize];
    std::fs::write(src.path().join(".env"), &oversized).expect("write oversized .env");
    let dest = tempfile::TempDir::new().expect("dest tmp dir");

    sync_untracked_files(src.path(), dest.path(), &[".env".to_string()]);

    assert!(
        !dest.path().join(".env").exists(),
        "a file over MAX_SYNC_FILE_BYTES must never be copied"
    );
}

#[test]
fn empty_patterns_copies_nothing() {
    let src = make_source_fixture();
    let dest = tempfile::TempDir::new().expect("dest tmp dir");

    sync_untracked_files(src.path(), dest.path(), &[]);

    assert!(
        !dest.path().join(".env").exists(),
        "an empty allowlist must copy nothing (mirrors the caller's enabled=false gate)"
    );
}

// ── non-fatal on missing/unreadable source ──────────────────────────────

#[test]
fn missing_source_root_is_non_fatal() {
    let dest = tempfile::TempDir::new().expect("dest tmp dir");
    let missing_source = Path::new("/this/path/does/not/exist/anywhere/2196");

    // Must not panic; must simply copy nothing.
    sync_untracked_files(missing_source, dest.path(), &default_patterns());

    assert!(
        std::fs::read_dir(dest.path())
            .expect("dest still readable")
            .next()
            .is_none(),
        "dest worktree must stay empty when the source root is missing"
    );
}

#[test]
fn missing_source_file_is_non_fatal() {
    // A pattern that matches nothing existing must not panic or error.
    let src = tempfile::TempDir::new().expect("src tmp dir");
    let dest = tempfile::TempDir::new().expect("dest tmp dir");

    sync_untracked_files(src.path(), dest.path(), &[".env.nonexistent".to_string()]);

    assert!(
        std::fs::read_dir(dest.path())
            .expect("dest still readable")
            .next()
            .is_none(),
        "no candidate files exist; sync must be a silent no-op"
    );
}

// ── path-escape guard ────────────────────────────────────────────────────

#[test]
fn path_escape_pattern_matches_nothing() {
    let src = tempfile::TempDir::new().expect("src tmp dir");
    // A secret OUTSIDE the source root that a malicious/misconfigured
    // pattern might try to reach via `..`.
    let outside = tempfile::TempDir::new().expect("outside tmp dir");
    std::fs::write(outside.path().join(".env"), b"must never be reachable")
        .expect("write outside .env");
    let dest = tempfile::TempDir::new().expect("dest tmp dir");

    let escape_pattern = format!(
        "../{}/.env",
        outside
            .path()
            .file_name()
            .expect("outside dir has a name")
            .to_string_lossy()
    );

    sync_untracked_files(src.path(), dest.path(), &[escape_pattern]);

    assert!(
        std::fs::read_dir(dest.path())
            .expect("dest still readable")
            .next()
            .is_none(),
        "a pattern with a `..`-escaping directory component must copy nothing"
    );
}

#[test]
fn absolute_pattern_matches_nothing() {
    let src = tempfile::TempDir::new().expect("src tmp dir");
    let dest = tempfile::TempDir::new().expect("dest tmp dir");

    sync_untracked_files(src.path(), dest.path(), &["/etc/.env".to_string()]);

    assert!(
        std::fs::read_dir(dest.path())
            .expect("dest still readable")
            .next()
            .is_none(),
        "an absolute pattern must copy nothing"
    );
}

// ── subdirectory pattern (explicit path separator) ──────────────────────

#[test]
fn subdirectory_pattern_matches_one_level_non_recursively() {
    let src = tempfile::TempDir::new().expect("src tmp dir");
    std::fs::create_dir_all(src.path().join("config")).expect("mkdir config");
    std::fs::write(src.path().join("config/.env"), b"nested secret").expect("write config/.env");
    std::fs::create_dir_all(src.path().join("config/nested")).expect("mkdir config/nested");
    std::fs::write(src.path().join("config/nested/.env"), b"too deep")
        .expect("write config/nested/.env");
    let dest = tempfile::TempDir::new().expect("dest tmp dir");

    sync_untracked_files(src.path(), dest.path(), &["config/.env".to_string()]);

    assert!(
        dest.path().join("config/.env").is_file(),
        "an explicit subdirectory pattern must copy that one file"
    );
    assert!(
        !dest.path().join("config/nested").exists(),
        "a subdirectory pattern must not recurse further than the named directory"
    );
}

// ── real linked-worktree .git/info/exclude round trip ───────────────────

/// Init a minimal, committed git repo at `path` (mirrors the setup already
/// used by `inproject::tests`).
fn init_base_repo(path: &Path) {
    let init = std::process::Command::new("git")
        .args(["init", path.to_str().expect("utf8")])
        .output()
        .expect("git init");
    assert!(init.status.success(), "git init failed");
    for (k, v) in [("user.email", "t@example.com"), ("user.name", "T")] {
        let ok = std::process::Command::new("git")
            .args(["-C", path.to_str().expect("utf8"), "config", k, v])
            .status()
            .expect("git config");
        assert!(ok.success(), "git config {k} failed");
    }
    std::fs::write(path.join("README"), b"init").expect("write README");
    let add = std::process::Command::new("git")
        .args(["-C", 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", path.to_str().expect("utf8"), "commit", "-m", "init"])
        .status()
        .expect("git commit");
    assert!(commit.success(), "git commit failed");
}

#[test]
fn copied_files_are_added_to_shared_worktree_exclude() {
    let base_tmp = tempfile::TempDir::new().expect("base tmp dir");
    let base = base_tmp.path();
    init_base_repo(base);

    let worktree = super::super::create_session_worktree_unchecked(
        base,
        "untracked-sync-exclude-test",
        &crate::session_manager::ManagedSessionId::new(),
    )
    .expect("create_session_worktree must succeed against a real, committed base repo");
    assert!(
        worktree.join(".git").is_file(),
        "sanity: a linked worktree's .git must be a FILE (gitlink), not a directory"
    );

    let src = make_source_fixture();
    sync_untracked_files(src.path(), &worktree, &default_patterns());

    assert!(worktree.join(".env").is_file(), ".env must be copied");
    assert!(worktree.join(".env.local").is_file());

    // The exclude entry must land in the SHARED common dir's info/exclude —
    // NOT at <worktree>/.git/info/exclude (that path cannot exist: .git is a
    // gitlink file, not a directory).
    let exclude_out = std::process::Command::new("git")
        .arg("-C")
        .arg(&worktree)
        .args(["rev-parse", "--git-path", "info/exclude"])
        .output()
        .expect("git rev-parse");
    assert!(exclude_out.status.success());
    let raw = String::from_utf8_lossy(&exclude_out.stdout)
        .trim()
        .to_string();
    let exclude_path = if Path::new(&raw).is_absolute() {
        std::path::PathBuf::from(raw)
    } else {
        worktree.join(raw)
    };
    let content = std::fs::read_to_string(&exclude_path).expect("exclude file readable");
    assert!(
        content.lines().any(|l| l.trim() == ".env"),
        "exclude file must list .env: {content}"
    );
    assert!(
        content.lines().any(|l| l.trim() == ".env.local"),
        "exclude file must list .env.local: {content}"
    );
}

#[test]
fn append_to_git_exclude_is_idempotent() {
    let base_tmp = tempfile::TempDir::new().expect("base tmp dir");
    let base = base_tmp.path();
    init_base_repo(base);
    let worktree = super::super::create_session_worktree_unchecked(
        base,
        "untracked-sync-idempotent-test",
        &crate::session_manager::ManagedSessionId::new(),
    )
    .expect("create_session_worktree must succeed");

    let exclude = match resolve_git_exclude(&worktree) {
        ExcludeTarget::Registered(p) => p,
        _ => panic!("a real linked worktree must resolve its shared info/exclude path"),
    };
    append_paths_to_exclude(&exclude, &[".env".to_string()]).expect("first append");
    append_paths_to_exclude(&exclude, &[".env".to_string()]).expect("second append");

    let exclude_out = std::process::Command::new("git")
        .arg("-C")
        .arg(&worktree)
        .args(["rev-parse", "--git-path", "info/exclude"])
        .output()
        .expect("git rev-parse");
    let raw = String::from_utf8_lossy(&exclude_out.stdout)
        .trim()
        .to_string();
    let exclude_path = if Path::new(&raw).is_absolute() {
        std::path::PathBuf::from(raw)
    } else {
        worktree.join(raw)
    };
    let content = std::fs::read_to_string(&exclude_path).expect("exclude readable");
    let count = content.lines().filter(|l| l.trim() == ".env").count();
    assert_eq!(
        count, 1,
        "repeated appends must not duplicate the entry: {content}"
    );
}

// ── #4733: a failed git probe must not leave a secret unregistered ──────────

/// Regression guard for #4733, git-history leg.
///
/// Why: before this fix the exclude-append ran AFTER the copy and a failure was
/// only a `warn!`. A destination whose `.git` git merely declined to read — a
/// stale worktree gitlink, `detected dubious ownership`, an unreadable `.git` —
/// therefore ended up holding the operator's `.env` with no exclude entry, where
/// a later `git add -A && git commit` stages it into history. Against the
/// pre-fix implementation this test fails on its first assertion (`.env` IS
/// copied).
/// What: a destination whose `.git` is a gitlink pointing nowhere — git 2.54.0
/// answers `fatal: not a git repository: (null)`, which contains the shorter
/// phrase `not a git repository` while meaning the opposite. Asserts nothing is
/// copied at all.
/// Test: this test itself.
#[test]
fn broken_repo_copies_nothing() {
    let src = make_source_fixture();
    let dest = tempfile::TempDir::new().expect("dest tmp dir");
    std::fs::write(dest.path().join(".git"), "gitdir: /nonexistent/xyz-4733\n")
        .expect("write stale gitlink");

    sync_untracked_files(src.path(), dest.path(), &default_patterns());

    assert!(
        !dest.path().join(".env").exists(),
        "a secret must never be written into a repository git could not confirm \
         would ignore it (#4733)"
    );
    assert!(
        !dest.path().join(".env.local").exists(),
        ".env.local must be refused for the same reason (#4733)"
    );
}

/// Why: the guard must not over-refuse. A destination with no repository at all
/// has no history for a secret to leak into, and this is the shape every
/// existing caller-level test uses.
/// What: a plain temp directory still receives the allowlisted files.
/// Test: this test itself.
#[test]
fn plain_directory_destination_still_copies() {
    let src = make_source_fixture();
    let dest = tempfile::TempDir::new().expect("dest tmp dir");

    sync_untracked_files(src.path(), dest.path(), &default_patterns());

    assert!(
        dest.path().join(".env").is_file(),
        "a non-repository destination has no history to leak into — copying stays allowed"
    );
}

/// Why: appending to `info/exclude` succeeds unconditionally and proves nothing
/// about a path the repo already TRACKS — git deliberately reports tracked paths
/// as not-ignored, and `git add -A` stages their modifications regardless. The
/// `check-ignore` re-verification is what catches that, mirroring
/// `native_mcp::is_env_local_actually_ignored`.
/// What: commits a `.env` into the base repo, then syncs a DIFFERENT `.env` from
/// a source checkout. Asserts the tracked file is left untouched.
/// Test: this test itself.
#[test]
fn tracked_secret_is_not_overwritten_in_worktree() {
    let base_tmp = tempfile::TempDir::new().expect("base tmp dir");
    let base = base_tmp.path();
    init_base_repo(base);
    std::fs::write(base.join(".env"), b"COMMITTED=placeholder").expect("write tracked .env");
    for args in [vec!["add", "-A"], vec!["commit", "-m", "track env"]] {
        let ok = std::process::Command::new("git")
            .args(["-C", base.to_str().expect("utf8")])
            .args(&args)
            .status()
            .expect("git");
        assert!(ok.success(), "git {args:?} failed");
    }

    let worktree = super::super::create_session_worktree_unchecked(
        base,
        "untracked-sync-tracked-test",
        &crate::session_manager::ManagedSessionId::new(),
    )
    .expect("create_session_worktree must succeed");

    let src = make_source_fixture();
    sync_untracked_files(src.path(), &worktree, &default_patterns());

    assert_eq!(
        std::fs::read(worktree.join(".env")).expect("tracked .env present in worktree"),
        b"COMMITTED=placeholder",
        "a TRACKED path is never ignored no matter what info/exclude says — \
         overwriting it would stage the operator's real secret (#4733)"
    );
    assert!(
        worktree.join(".env.local").is_file(),
        "the untracked sibling is still delivered — the refusal is per-path"
    );
}

/// git's classic wording of "no repository": discovery reached `/`.
const PARENT_DIRS_STDERR: &str =
    "fatal: not a git repository (or any of the parent directories): .git";

/// Why: git prints [`PARENT_DIRS_STDERR`] for an unreadable `.git` just as readily
/// as for a genuinely empty directory, so the message is a necessary and never a
/// sufficient condition; the filesystem witness decides.
/// What: asserts the classifier refuses when an ancestor carries a `.git` entry
/// despite the "no repository" wording, concedes `NoRepo` only without one, and
/// never believes the stale-worktree near-miss wording.
/// Test: this test itself.
#[test]
fn classify_rev_parse_failure_corroborates_the_no_repo_message() {
    let tmp = tempfile::TempDir::new().expect("tmp dir");
    let msg = PARENT_DIRS_STDERR;

    assert!(
        matches!(
            classify_rev_parse_failure(tmp.path(), msg),
            ExcludeTarget::NoRepo
        ),
        "no ancestor .git witness → the message is believed"
    );
    assert!(
        matches!(
            classify_rev_parse_failure(tmp.path(), "fatal: not a git repository: (null)"),
            ExcludeTarget::Unknown(_)
        ),
        "the stale-worktree near-miss contains the short phrase but means the opposite"
    );

    std::fs::write(tmp.path().join(".git"), "gitdir: /somewhere\n").expect("gitlink");
    assert!(
        matches!(
            classify_rev_parse_failure(tmp.path(), msg),
            ExcludeTarget::Unknown(_)
        ),
        "a .git witness contradicts the message — a disagreement is 'cannot be asked'"
    );
}

/// Why: registration and verification are different jobs, and a broken
/// `info/exclude` defeats both — `git check-ignore` refuses to run at all
/// (`fatal: cannot use .git/info/exclude as an exclude file`), so the question
/// "would `git add -A` stage this?" becomes unanswerable. An unanswerable
/// question must be a refusal, not a copy. Against an implementation that
/// treats the append as best-effort and copies regardless, this test fails:
/// `.env` lands in the worktree unignored.
/// What: a real linked worktree whose resolved `info/exclude` path is replaced
/// by a DIRECTORY. Asserts nothing is copied.
/// Test: this test itself.
#[test]
fn broken_exclude_file_still_refuses_unignored_paths() {
    let base_tmp = tempfile::TempDir::new().expect("base tmp dir");
    let base = base_tmp.path();
    init_base_repo(base);
    let worktree = super::super::create_session_worktree_unchecked(
        base,
        "untracked-sync-broken-exclude-test",
        &crate::session_manager::ManagedSessionId::new(),
    )
    .expect("create_session_worktree must succeed");

    let exclude = match resolve_git_exclude(&worktree) {
        ExcludeTarget::Registered(p) => p,
        _ => panic!("a real linked worktree must resolve its shared info/exclude path"),
    };
    let _ = std::fs::remove_file(&exclude);
    std::fs::create_dir_all(&exclude).expect("replace info/exclude with a directory");

    let src = make_source_fixture();
    sync_untracked_files(src.path(), &worktree, &default_patterns());

    assert!(
        !worktree.join(".env").exists(),
        "with registration broken and no .gitignore covering it, `git check-ignore` \
         is the only remaining guarantee and it must refuse (#4733)"
    );
    assert!(
        !worktree.join(".env.local").exists(),
        ".env.local must be refused for the same reason (#4733)"
    );
}

/// Why: git is not always on `PATH` — a stripped container, a broken shim, a
/// daemon started with a sanitised environment. A spawn failure tells us
/// nothing about whether the destination is a repository, so it must refuse.
/// This gate runs BEFORE any copy and before `is_path_git_ignored`, so an
/// unspawnable git means nothing is written at all.
/// What: a real linked worktree (so the only variable is the binary) resolved
/// with a program name that cannot be spawned. Asserts `Unknown` — which
/// `broken_repo_copies_nothing` separately pins as "copy nothing".
/// Test: this test itself.
#[test]
fn missing_git_binary_copies_nothing() {
    let base_tmp = tempfile::TempDir::new().expect("base tmp dir");
    let base = base_tmp.path();
    init_base_repo(base);
    let worktree = super::super::create_session_worktree_unchecked(
        base,
        "untracked-sync-missing-git-test",
        &crate::session_manager::ManagedSessionId::new(),
    )
    .expect("create_session_worktree must succeed");

    // Sanity: with a real git this worktree resolves its exclude file.
    assert!(
        matches!(resolve_git_exclude(&worktree), ExcludeTarget::Registered(_)),
        "sanity: a real linked worktree resolves with a working git"
    );

    assert!(
        matches!(
            resolve_git_exclude_with(&worktree, "trusty-no-such-git-binary-4733"),
            ExcludeTarget::Unknown(_)
        ),
        "an unspawnable git answers nothing — it must never be read as 'no repository', \
         which would let a secret be copied into a live worktree (#4733)"
    );
}

/// Why: `Path::ancestors` walks LEXICALLY. Without `.canonicalize()` a path
/// reached through a symlink (or a relative one) yields a chain that is not its
/// real parentage, so the destination's `.git` is never visited and the
/// permissive `NoRepo` wins — which copies the operator's `.env` into a live
/// repository unregistered. Dropping the call passes every other test in this
/// file; this is the one that fails.
/// What: `link -> repo/sub`, with `.git` on `repo` only. The lexical ancestors
/// of `link` never include `repo`; the canonicalised ones do.
/// Test: this test itself.
#[test]
fn classify_rev_parse_failure_canonicalises_before_walking_ancestors() {
    let tmp = tempfile::TempDir::new().expect("tmp dir");
    let repo = tmp.path().join("repo");
    std::fs::create_dir_all(repo.join("sub")).expect("mkdir repo/sub");
    std::fs::write(repo.join(".git"), "gitdir: /somewhere\n").expect("gitlink");
    let link = tmp.path().join("link");
    std::os::unix::fs::symlink(repo.join("sub"), &link).expect("symlink");

    assert!(
        matches!(
            classify_rev_parse_failure(&link, PARENT_DIRS_STDERR),
            ExcludeTarget::Unknown(_)
        ),
        "the real parent carries a .git — only a canonicalised ancestor walk sees it"
    );
}

/// git's mount-boundary wording of "no repository", captured from git 2.53 on
/// a tmpfs `/tmp`: discovery stops at the filesystem boundary instead of `/`.
const MOUNT_BOUNDARY_STDERR: &str = "fatal: not a git repository (or any parent up to mount point /)\n\
     Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).\n";

/// Why: #9495 — on a tmpfs `/tmp` git prints the mount-boundary wording, which
/// the classifier did not recognise, so a plain directory with no repository
/// read as `Unknown` and the session launched without its allowlisted files.
/// What: feeds the boundary wording as text (no mount layout needed) and expects
/// `NoRepo` with no `.git` witness; the colon forms and unrelated git failures
/// must still answer `Unknown`.
/// Test: this test itself.
#[test]
fn classify_rev_parse_failure_accepts_the_mount_boundary_wording() {
    let tmp = tempfile::TempDir::new().expect("tmp dir");
    assert!(
        matches!(
            classify_rev_parse_failure(tmp.path(), MOUNT_BOUNDARY_STDERR),
            ExcludeTarget::NoRepo
        ),
        "the mount-boundary wording with no .git witness is a genuine absence"
    );

    for stderr in [
        "fatal: not a git repository: (null)",
        "fatal: not a git repository: '/nonexistent/x'",
        "fatal: detected dubious ownership in repository at '/x'",
        "fatal: cannot change to '/x': Permission denied",
    ] {
        assert!(
            matches!(
                classify_rev_parse_failure(tmp.path(), stderr),
                ExcludeTarget::Unknown(_)
            ),
            "unrecognised failure must refuse, not read as no repository: {stderr:?}"
        );
    }
}

/// Why: #9495 Fail-Open Check — widening the accepted wording must not widen
/// what gets copied unregistered. git prints the same boundary text when
/// discovery is cut short above a real repository, so the ancestor `.git`
/// witness stays the gate.
/// What: a `.git` gitlink on the destination plus the boundary wording; expects
/// `Unknown`, which `sync_untracked_files` turns into "copy nothing".
/// Test: this test itself.
#[test]
fn classify_rev_parse_failure_refuses_the_mount_boundary_wording_under_a_real_repo() {
    let tmp = tempfile::TempDir::new().expect("tmp dir");
    std::fs::write(tmp.path().join(".git"), "gitdir: /somewhere\n").expect("gitlink");
    assert!(
        matches!(
            classify_rev_parse_failure(tmp.path(), MOUNT_BOUNDARY_STDERR),
            ExcludeTarget::Unknown(_)
        ),
        "an ancestor .git contradicts the boundary wording — never copy into a real repo"
    );
}