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
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
//! Unit tests for trusty-mpm's tmux adapter (#2398/#3386/#5151), split out
//! of `tmux.rs` to keep that file under the 500-SLOC production cap (#610) —
//! the inline `mod tests` counted as production source.
//!
//! Every process-spawning test drives a scripted fake `tmux` binary written
//! to a temp dir, so none of them needs a live tmux server.

use super::*;

// ── #8233: the pane COMMAND-line length guard ──

#[test]
fn pane_command_limit_sits_below_max_canon() {
    // The tty's canonical-mode buffer is MAX_CANON = 1024 bytes on macOS
    // (`sys/syslimits.h:89`; `fpathconf(pty, _PC_MAX_CANON)` agrees). The guard
    // must sit below it with room for the terminating newline, and must not be
    // so low that the fixed-shape launch line (< 512 bytes) cannot pass.
    const {
        assert!(MAX_PANE_COMMAND_BYTES < 1024);
        assert!(MAX_PANE_COMMAND_BYTES >= 512);
    }
}

#[test]
fn oversized_pane_command_is_refused() {
    // The failure this exists for: 1054 bytes typed, ~1020 delivered, the rest
    // dropped by the kernel with nothing able to notice.
    let line = "x".repeat(MAX_PANE_COMMAND_BYTES + 1);
    let msg = refuse_oversized_pane_command(&line).expect("an over-length line must be refused");
    assert!(msg.contains("MAX_CANON"), "{msg}");
    assert!(
        msg.contains(&(MAX_PANE_COMMAND_BYTES + 1).to_string()),
        "{msg}"
    );
}

#[test]
fn pane_command_at_the_limit_is_allowed() {
    let line = "x".repeat(MAX_PANE_COMMAND_BYTES);
    assert!(refuse_oversized_pane_command(&line).is_none());
}

#[test]
fn send_command_line_refuses_an_oversized_line() {
    // Nothing is typed and nothing is spawned: the refusal happens before any
    // tmux process starts, so a bogus binary path proves no exec occurred.
    let line = "x".repeat(MAX_PANE_COMMAND_BYTES + 1);
    let err = send_command_line(
        Some("/nonexistent/definitely-not-tmux"),
        &TmuxTarget::session("tm-sess"),
        &line,
    )
    .expect_err("an over-length command must be refused");
    assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput, "{err}");
    assert!(err.to_string().contains("#8233"), "{err}");
}

// ── #8308: the CLI/client launch lines go through the same guard ──

/// A fake `tmux` that appends each invocation's argv to `<dir>/argv.log`.
fn argv_logging_tmux(dir: &std::path::Path, exit: u8) -> (String, std::path::PathBuf) {
    let log = dir.join("argv.log");
    let script = format!(
        "#!/bin/sh\necho \"$*\" >> '{}'\necho 'fake failure' >&2\nexit {exit}\n",
        log.display()
    );
    (write_fake_tmux(dir, "fake-tmux-argv", &script), log)
}

#[serial_test::serial]
#[test]
fn launch_line_over_the_limit_is_refused_before_tmux_runs() {
    let dir = tempfile::tempdir().unwrap();
    let (bin, log) = argv_logging_tmux(dir.path(), 0);
    let line = "x".repeat(MAX_PANE_COMMAND_BYTES + 1);
    let err = send_launch_line(Some(&bin), "tm-sess", &line)
        .expect_err("an over-length launch line must be refused");
    assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput, "{err}");
    assert!(!log.exists(), "tmux must not run for a refused line");
}

#[serial_test::serial]
#[test]
fn launch_line_within_the_limit_reaches_tmux() {
    let dir = tempfile::tempdir().unwrap();
    let (bin, log) = argv_logging_tmux(dir.path(), 0);
    send_launch_line(Some(&bin), "tm-sess", "echo short-line").expect("a short line is typed");
    let argv = std::fs::read_to_string(&log).unwrap();
    assert!(argv.contains("-l echo short-line"), "{argv}");
    assert!(argv.contains("Enter"), "{argv}");

    // A non-zero `send-keys` exit is an error that carries tmux's stderr.
    let failing = tempfile::tempdir().unwrap();
    let (bin, _) = argv_logging_tmux(failing.path(), 1);
    let err = send_launch_line(Some(&bin), "tm-sess", "echo").expect_err("exit 1 is a failure");
    assert!(err.to_string().contains("fake failure"), "{err}");
}

/// #8308: no launch site types its `claude` line through the unguarded free
/// [`send_line`]; each goes through `cli_launch::send_spec_launch`, which types
/// through [`send_launch_line`].
///
/// Why: the sites take no tmux seam, so the wiring is pinned on their source.
/// A fixed file list missed the Architect launch in `fleet/launch.rs`, so the
/// check sweeps every tree instead.
/// What: walks every `.rs` under `src/` (`bin/`, `client/` and the rest) except
/// `core/tmux.rs`, which defines the function, and this file. It fails on a
/// call of the free `send_line(` and on a `use` of `core::tmux` that names it;
/// a `.send_line(` driver method and a `fn send_line(` definition are other
/// functions. The per-file counts stop a moved call from passing vacuously.
#[test]
fn cli_launch_paths_type_through_the_guard() {
    let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
    let mut offenders = Vec::new();
    for entry in walkdir::WalkDir::new(root.join("src")) {
        let entry = entry.unwrap();
        let rel = entry.path().strip_prefix(root).unwrap().to_string_lossy();
        if !rel.ends_with(".rs") || rel == "src/core/tmux.rs" || rel == "src/core/tmux_tests.rs" {
            continue;
        }
        let src = std::fs::read_to_string(entry.path()).unwrap();
        offenders.extend(
            unguarded_send_lines(&src)
                .iter()
                .map(|n| format!("{rel}:{n}")),
        );
    }
    assert!(
        offenders.is_empty(),
        "launch line typed through the unguarded core::tmux::send_line: {offenders:?}"
    );
    // #8308: the six sites start `claude` through the launch-spec helper, and
    // the helper is the one caller of the guarded send.
    let spec_send = "cli_launch::send_spec_launch(";
    for (file, needle, sites) in [
        ("src/bin/tm/commands/launch.rs", spec_send, 2),
        ("src/bin/tm/commands/session/start.rs", spec_send, 1),
        ("src/client/http_client/session_connect.rs", spec_send, 1),
        ("src/bin/tm/commands/fleet/launch.rs", spec_send, 1),
        ("src/runtime/cli_launch.rs", "tmux::send_launch_line(", 1),
    ] {
        let src = std::fs::read_to_string(root.join(file)).unwrap();
        assert_eq!(
            src.matches(needle).count(),
            sites,
            "{file}: expected {sites} `{needle}` site(s)"
        );
    }
}

/// The sweep's matcher flags a qualified or imported call and the import, and
/// nothing that is a different function (#8308).
#[test]
fn unguarded_send_lines_flags_calls_and_imports_only() {
    for (src, want) in [
        ("let s = tmux::send_line(None, &t, &cmd)?;", vec![1]),
        (
            "use trusty_mpm::core::tmux::{self, send_line};\nsend_line(None, &t, c);",
            vec![1, 2],
        ),
        (
            "use crate::core::tmux::{\n    TmuxTarget,\n    send_line,\n};",
            vec![1],
        ),
        (
            "driver.send_line(&t, x)?;\n    .send_line(&t, x)\nfn send_line(&self) {}",
            vec![],
        ),
        (
            "tmux::send_launch_line(None, s, c)?;\nx.send_line_to_pane(n, p, t);",
            vec![],
        ),
        (
            "// tmux::send_line(None, &t, c)\nuse crate::core::tmux::TmuxTarget;",
            vec![],
        ),
    ] {
        assert_eq!(unguarded_send_lines(src), want, "{src}");
    }
}

/// 1-based lines in `src` that call, or import, the free `core::tmux::send_line`.
fn unguarded_send_lines(src: &str) -> Vec<usize> {
    let is_ident = |c: char| c.is_alphanumeric() || c == '_';
    let mut hits = Vec::new();
    let mut open_use: Option<(usize, String)> = None;
    for (i, line) in src.lines().enumerate() {
        let code = line.trim_start();
        if code.starts_with("//") {
            continue;
        }
        for (at, _) in code.match_indices("send_line(") {
            let before = &code[..at];
            // A driver method, a definition, or a longer identifier.
            let other =
                before.ends_with('.') || before.ends_with("fn ") || before.ends_with(is_ident);
            if !other {
                hits.push(i + 1);
            }
        }
        let bare = code
            .strip_prefix("pub(crate) ")
            .or_else(|| code.strip_prefix("pub "));
        if open_use.is_none() && bare.unwrap_or(code).starts_with("use ") {
            open_use = Some((i + 1, String::new()));
        }
        let Some((start, stmt)) = open_use.as_mut() else {
            continue;
        };
        stmt.push_str(code);
        if code.contains(';') {
            if stmt.contains("tmux") && stmt.split(|c| !is_ident(c)).any(|w| w == "send_line") {
                hits.push(*start);
            }
            open_use = None;
        }
    }
    hits
}

// ── #2414: untyped-argv builders for display-message / show-environment ──

#[test]
fn display_message_argv_untargeted() {
    assert_eq!(
        display_message_argv(None, "#S"),
        vec!["display-message", "-p", "#S"]
    );
}

#[test]
fn display_message_argv_session_targeted() {
    assert_eq!(
        display_message_argv(Some(&TmuxTarget::session("tmpm-sess")), "#{pane_pid}"),
        vec!["display-message", "-t", "=tmpm-sess:", "-p", "#{pane_pid}"]
    );
}

#[test]
fn show_environment_argv_untargeted() {
    assert_eq!(
        show_environment_argv(None, "TM_MANAGED_SESSION_ID"),
        vec!["show-environment", "TM_MANAGED_SESSION_ID"]
    );
}

#[test]
fn show_environment_argv_session_targeted() {
    assert_eq!(
        show_environment_argv(Some("tmpm-sess"), "TM_MANAGED_SESSION_ID"),
        vec![
            "show-environment",
            "-t",
            "=tmpm-sess",
            "TM_MANAGED_SESSION_ID"
        ]
    );
}

#[serial_test::serial]
#[test]
fn run_tmux_argv_with_bin_does_not_panic_on_missing_binary() {
    // Mirrors `run_tmux_with_bin_does_not_panic_on_missing_binary` for the
    // untyped-argv spawn path.
    let result = run_tmux_argv_with_bin(
        "definitely-not-a-real-tmux-binary-2414",
        &[
            "display-message".to_string(),
            "-p".to_string(),
            "#S".to_string(),
        ],
    );
    assert!(result.is_err());
}

#[test]
fn resolve_tmux_binary_does_not_panic() {
    // Works whether or not tmux is installed on the test host.
    let _ = resolve_tmux_binary();
}

/// #6542: the override reaches every resolution inside the scoped future, and
/// no resolution outside it — concurrent tests must keep the real binary.
#[tokio::test]
async fn with_tmux_binary_scopes_the_override_to_its_future() {
    let shim = std::path::PathBuf::from("/nonexistent/tmux-shim-6542");
    let (inner, inner_bare, spawned) = with_tmux_binary(shim.clone(), async {
        tokio::task::yield_now().await;
        let spawned = tokio::spawn(async { resolve_tmux_binary() })
            .await
            .expect("spawned task");
        (
            resolve_tmux_binary(),
            resolve_tmux_binary_or_bare(),
            spawned,
        )
    })
    .await;
    assert_eq!(inner, Some(shim.clone()));
    assert_eq!(inner_bare, shim.to_string_lossy());
    assert_ne!(
        spawned,
        Some(shim.clone()),
        "another task must not inherit the override"
    );
    assert_ne!(resolve_tmux_binary(), Some(shim), "the scope must end");
}

#[test]
fn resolve_tmux_binary_or_bare_never_empty() {
    // Even when resolution fails entirely, the bare "tmux" fallback keeps
    // this non-empty — callers always get a spawnable binary name.
    assert!(!resolve_tmux_binary_or_bare().is_empty());
}

#[serial_test::serial]
#[test]
fn run_tmux_with_bin_does_not_panic_on_missing_binary() {
    // A deliberately bogus binary name must surface as an Err, never panic.
    let result = run_tmux_with_bin(
        "definitely-not-a-real-tmux-binary-2398",
        &TmuxCommand::ListSessions,
    );
    assert!(result.is_err());
}

#[serial_test::serial]
#[test]
fn create_managed_session_does_not_panic_on_missing_binary() {
    // Same smoke guarantee for the session-creation choke point: a bogus
    // binary must degrade to an Err (from the final new-session spawn),
    // never panic — including through the best-effort scrollback loop.
    let result = create_managed_session(
        Some("definitely-not-a-real-tmux-binary-2398"),
        "tmpm-test-2398-no-bin",
        None,
    );
    assert!(result.is_err());
}

#[test]
fn managed_session_command_sequence_matches_shared_layer() {
    // #3004 integration assertion: this crate's config-resolved
    // sequence must be EXACTLY what `trusty_common::tmux` would build
    // for `idempotent: true, command: None` (trusty-mpm's creation
    // semantics) with the same parameters — proving trusty-mpm's
    // session creation genuinely routes through the shared layer
    // rather than a local re-implementation drifting from it.
    let got = managed_session_command_sequence(
        "tmpm-sess",
        Some("/tmp/proj"),
        100_000,
        true,
        false,
        true,
    );
    let want = trusty_common::tmux::managed_session_commands(
        "tmpm-sess",
        Some("/tmp/proj"),
        100_000,
        true,
        false,
        true,
        None,
    );
    assert_eq!(got, want);
}

/// #3707: the exclusive create must not render `-A`, because `-A` is exactly
/// what turns a lost create race into two records sharing one pane.
#[test]
fn exclusive_command_sequence_omits_the_attach_flag() {
    let cmds =
        managed_session_command_sequence("tm-sess", Some("/tmp/p"), 100_000, true, false, false);
    let TmuxCommand::NewSession { idempotent, .. } = cmds.last().expect("ends with new-session")
    else {
        panic!("the sequence must end with NewSession");
    };
    assert!(!idempotent, "the exclusive create must not pass -A");
    let argv = trusty_common::tmux::tmux_argv(cmds.last().expect("ends with new-session"));
    assert!(
        !argv.contains(&"-A".to_string()),
        "argv still carries -A: {argv:?}"
    );
}

#[test]
fn managed_session_command_sequence_applies_options_before_new_session() {
    let cmds = managed_session_command_sequence("tmpm-sess", None, 50_000, false, false, true);
    assert_eq!(cmds.len(), 4);
    assert!(matches!(cmds[0], TmuxCommand::SetGlobalOption { .. }));
    assert!(matches!(cmds[1], TmuxCommand::SetGlobalOption { .. }));
    // #5151: the alternate-screen entry rides the same pre-new-session
    // path, at the WINDOW scope.
    assert!(matches!(cmds[2], TmuxCommand::SetWindowGlobalOption { .. }));
    assert!(matches!(cmds[3], TmuxCommand::NewSession { .. }));
}

// ── #3386: server-up confirmed before any `set-option -g` ───────────
//
// All of these drive a scripted fake `tmux` binary (a `#!/bin/sh` script
// written to a temp dir) rather than a live tmux server, so they are
// deterministic and safe to run anywhere `sh` exists.

/// Write an executable shell script at `dir/name` with body `body`,
/// returning its path as a `String` suitable for `create_managed_session`
/// / `run_tmux_with_bin`'s `bin` parameter.
///
/// #5391: the script is created already executable and the write handle is
/// dropped before it is returned, so no caller can exec it while this thread
/// still holds a writable fd — the same shape `trusty-agents`'
/// `test_env::write_executable_script` settled on for #1528. That closes the
/// self-inflicted half of the ETXTBSY race; the other half — a sibling
/// thread forking mid-write and handing its child an inherited copy of the
/// fd — is covered by the bounded retry in `core::spawn_disclaim`.
fn write_fake_tmux(dir: &std::path::Path, name: &str, body: &str) -> String {
    use std::io::Write as _;
    use std::os::unix::fs::OpenOptionsExt as _;

    let path = dir.join(name);
    {
        // `create_new` so the 0o755 mode is guaranteed to apply: `mode` is
        // honoured only when the open actually creates the file, and every
        // caller writes its script name once into its own temp dir.
        let mut f = std::fs::OpenOptions::new()
            .create_new(true)
            .write(true)
            .mode(0o755)
            .open(&path)
            .expect("create fake tmux script");
        f.write_all(body.as_bytes())
            .expect("write fake tmux script");
        // `f` drops here — the writable fd is closed before any exec.
    }
    path.to_string_lossy().into_owned()
}

#[serial_test::serial]
#[test]
fn ensure_server_up_retries_then_succeeds() {
    // Fails the first two `start-server` invocations (simulating the
    // #3386 window right after a dead server's socket dir is torn down),
    // then succeeds on the third — exactly `START_SERVER_MAX_ATTEMPTS`.
    let dir = tempfile::tempdir().unwrap();
    let counter = dir.path().join("attempts");
    std::fs::write(&counter, "0").unwrap();
    let script = format!(
        "#!/bin/sh\nn=$(cat '{counter}')\nn=$((n + 1))\necho \"$n\" > '{counter}'\nif [ \"$n\" -lt 3 ]; then\n  echo 'error connecting to socket (No such file or directory)' >&2\n  exit 1\nfi\nexit 0\n",
        counter = counter.display()
    );
    let bin = write_fake_tmux(dir.path(), "fake-tmux-retry", &script);

    let result = ensure_server_up(&bin);

    assert!(
        result.is_ok(),
        "must eventually succeed within {START_SERVER_MAX_ATTEMPTS} attempts: {result:?}"
    );
    assert_eq!(
        std::fs::read_to_string(&counter).unwrap().trim(),
        "3",
        "must have retried exactly up to the succeeding attempt"
    );
}

#[serial_test::serial]
#[test]
fn ensure_server_up_fails_loudly_after_exhausting_retries() {
    // Always fails — the probe must return a loud Err after exhausting
    // every attempt rather than silently reporting success.
    let dir = tempfile::tempdir().unwrap();
    let script =
        "#!/bin/sh\necho 'error connecting to socket (No such file or directory)' >&2\nexit 1\n";
    let bin = write_fake_tmux(dir.path(), "fake-tmux-always-fails", script);

    let result = ensure_server_up(&bin);

    assert!(
        result.is_err(),
        "an always-failing server probe must error loudly, never proceed as if it succeeded"
    );
    assert!(
        result.unwrap_err().contains("error connecting to socket"),
        "the Err must carry the underlying failure reason"
    );
}

#[serial_test::serial]
#[test]
fn probe_history_limit_reads_back_configured_value() {
    let dir = tempfile::tempdir().unwrap();
    let script = "#!/bin/sh\necho 100000\nexit 0\n";
    let bin = write_fake_tmux(dir.path(), "fake-tmux-show-options", script);

    assert_eq!(probe_history_limit(&bin), Ok(100_000));
}

#[serial_test::serial]
#[test]
fn probe_history_limit_errors_on_unparsable_output() {
    let dir = tempfile::tempdir().unwrap();
    let script = "#!/bin/sh\necho 'not-a-number'\nexit 0\n";
    let bin = write_fake_tmux(dir.path(), "fake-tmux-bad-output", script);

    let result = probe_history_limit(&bin);
    assert!(
        result.is_err(),
        "unparsable show-options output must error loudly, not silently pass verification"
    );
}

#[serial_test::serial]
#[test]
fn probe_history_limit_errors_on_nonzero_exit() {
    let dir = tempfile::tempdir().unwrap();
    let script = "#!/bin/sh\necho 'no server running' >&2\nexit 1\n";
    let bin = write_fake_tmux(dir.path(), "fake-tmux-show-options-fails", script);

    assert!(probe_history_limit(&bin).is_err());
}

// ── #5151: alternate-screen probe ───────────────────────────────────

/// A `show-options)` case body for a fake tmux that answers each probe
/// by OPTION NAME (`$4`), so the `history-limit` and `alternate-screen`
/// probes can be given different answers — the whole point of #5151 is
/// that they are separate options in separate scopes.
fn fake_show_options_case(history_limit: &str, alternate_screen: &str) -> String {
    format!(
        "  show-options)\n    case \"$4\" in\n      history-limit) echo {history_limit} ;;\n      alternate-screen) echo {alternate_screen} ;;\n    esac\n    ;;\n"
    )
}

#[serial_test::serial]
#[test]
fn probe_alternate_screen_reads_back_on() {
    let dir = tempfile::tempdir().unwrap();
    let bin = write_fake_tmux(
        dir.path(),
        "fake-tmux-alt-on",
        "#!/bin/sh\necho on\nexit 0\n",
    );
    assert_eq!(probe_alternate_screen(&bin), Ok(true));
}

#[serial_test::serial]
#[test]
fn probe_alternate_screen_reads_back_off() {
    let dir = tempfile::tempdir().unwrap();
    let bin = write_fake_tmux(
        dir.path(),
        "fake-tmux-alt-off",
        "#!/bin/sh\necho off\nexit 0\n",
    );
    assert_eq!(probe_alternate_screen(&bin), Ok(false));
}

#[serial_test::serial]
#[test]
fn probe_alternate_screen_errors_on_unrecognised_value() {
    // Anything tmux does not document must NOT be guessed at — a wrong
    // guess here is a silent pass on an option that did not land.
    let dir = tempfile::tempdir().unwrap();
    let bin = write_fake_tmux(
        dir.path(),
        "fake-tmux-alt-garbage",
        "#!/bin/sh\necho maybe\nexit 0\n",
    );
    assert!(probe_alternate_screen(&bin).is_err());
}

#[serial_test::serial]
#[test]
fn probe_alternate_screen_errors_on_nonzero_exit() {
    let dir = tempfile::tempdir().unwrap();
    let bin = write_fake_tmux(
        dir.path(),
        "fake-tmux-alt-fails",
        "#!/bin/sh\necho 'no server running' >&2\nexit 1\n",
    );
    assert!(probe_alternate_screen(&bin).is_err());
}

#[serial_test::serial]
#[test]
fn probe_alternate_screen_queries_the_window_scope() {
    // #5151 fail-open guard: the probe must read `-wg`, the same scope
    // `scrollback_option_commands` writes. Measured against live tmux
    // 3.6b, `set-option -pg alternate-screen off` exits 0, a `-pg`
    // readback reports "off", and the pane STILL enters the alternate
    // screen — a probe on any other scope would confirm nothing.
    let dir = tempfile::tempdir().unwrap();
    let log = dir.path().join("argv.log");
    let script = format!(
        "#!/bin/sh\necho \"$@\" >> '{log}'\necho off\nexit 0\n",
        log = log.display()
    );
    let bin = write_fake_tmux(dir.path(), "fake-tmux-alt-argv", &script);

    assert_eq!(probe_alternate_screen(&bin), Ok(false));
    assert_eq!(
        std::fs::read_to_string(&log).unwrap().trim(),
        "show-options -wg -v alternate-screen"
    );
}

#[serial_test::serial]
#[test]
fn create_managed_session_confirms_server_before_applying_options() {
    // #3386 end-to-end (still no live tmux): a fake `tmux` that records
    // each invocation's tmux sub-command (argv[0]) to a log file, always
    // succeeds, and echoes back the CONFIGURED history-limit for
    // `show-options` so the apply-and-verify cycle matches on its first
    // attempt. This exercises the EXACT choke point the
    // resume-after-server-death path (`SessionManager::resume` →
    // `resume_workdir::create_and_verify_pane` → `RealTmuxDriver::
    // create_session` → `TmuxDriver::create_session`) routes through, so
    // asserting the recorded order here proves the fix for that path too.
    //
    // #5040: the options are CONSTRUCTED here and injected, not resolved from
    // `~/.trusty-mpm/config.toml` on both sides. Reading the host config twice —
    // once here for the expectation, once inside `create_managed_session` for
    // the actual — let any concurrently-running test that redirects `$HOME`
    // answer the two reads from different environments, and this test failed
    // with no change to a single file it exercises. One value, passed in, cannot
    // diverge from itself.
    let dir = tempfile::tempdir().unwrap();
    let log = dir.path().join("calls.log");
    let opts = crate::core::trusty_tools_config::ResolvedTmuxOptions {
        history_limit: 123_456,
        mouse: true,
        alternate_screen: false,
    };
    let script = format!(
        "#!/bin/sh\necho \"$1\" >> '{log}'\ncase \"$1\" in\n{show_options}esac\nexit 0\n",
        log = log.display(),
        show_options = fake_show_options_case(
            &opts.history_limit.to_string(),
            if opts.alternate_screen { "on" } else { "off" },
        )
    );
    let bin = write_fake_tmux(dir.path(), "fake-tmux-order", &script);

    let outcome =
        create_managed_session_with_options(Some(&bin), "tmpm-3386-order-test", None, opts)
            .expect("fake tmux always exits 0");

    assert!(
        outcome.options_verified,
        "a fake tmux that echoes back the configured history-limit must verify successfully"
    );

    let calls = std::fs::read_to_string(&log).unwrap();
    let lines: Vec<&str> = calls.lines().collect();

    assert_eq!(
        lines.first(),
        Some(&"start-server"),
        "the server must be confirmed up BEFORE any set-option -g (#3386): {lines:?}"
    );
    let new_session_pos = lines
        .iter()
        .position(|l| *l == "new-session")
        .expect("new-session must still run");
    let set_option_positions: Vec<usize> = lines
        .iter()
        .enumerate()
        .filter(|(_, l)| **l == "set-option")
        .map(|(i, _)| i)
        .collect();
    assert!(
        !set_option_positions.is_empty(),
        "the scrollback/mouse options must still be applied: {lines:?}"
    );
    assert!(
        set_option_positions
            .iter()
            .all(|&p| p > 0 && p < new_session_pos),
        "set-option -g must run strictly AFTER start-server and BEFORE new-session \
         (#3386 / pre-existing #2398 ordering guarantee): {lines:?}"
    );
}

// ── #3386 review: apply-and-verify retries the WHOLE cycle ──────────

#[serial_test::serial]
#[test]
fn apply_and_verify_scrollback_options_succeeds_on_second_attempt() {
    // The probe reports the WRONG value on the first cycle, then the
    // correct value from the second cycle onward — the whole
    // apply-and-verify cycle (not just start-server) must retry and
    // eventually confirm success.
    let dir = tempfile::tempdir().unwrap();
    let counter = dir.path().join("probe-attempts");
    std::fs::write(&counter, "0").unwrap();
    let script = format!(
        "#!/bin/sh\ncase \"$1\" in\n  show-options)\n    case \"$4\" in\n      history-limit)\n        n=$(cat '{counter}')\n        n=$((n + 1))\n        echo \"$n\" > '{counter}'\n        if [ \"$n\" -lt 2 ]; then\n          echo 2000\n        else\n          echo 100000\n        fi\n        ;;\n      alternate-screen) echo on ;;\n    esac\n    ;;\nesac\nexit 0\n",
        counter = counter.display()
    );
    let bin = write_fake_tmux(dir.path(), "fake-tmux-verify-retry", &script);
    let options = trusty_common::tmux::scrollback_option_commands(100_000, true, true);

    let verified = apply_and_verify_scrollback_options(&bin, &options, 100_000, true);

    assert!(
        verified,
        "must succeed once the probe reports the expected value on a later attempt"
    );
    assert_eq!(
        std::fs::read_to_string(&counter).unwrap().trim(),
        "2",
        "must have retried the WHOLE cycle (not just start-server) exactly once"
    );
}

#[serial_test::serial]
#[test]
fn apply_and_verify_scrollback_options_returns_false_after_exhausting_retries() {
    // The probe ALWAYS reports the wrong value — every apply-and-verify
    // cycle must be attempted (never silently assumed to have worked),
    // and the function must return `false` (the caller-visible degraded
    // signal) rather than `true` once every attempt is exhausted.
    let dir = tempfile::tempdir().unwrap();
    let counter = dir.path().join("probe-attempts");
    std::fs::write(&counter, "0").unwrap();
    let script = format!(
        "#!/bin/sh\ncase \"$1\" in\n  show-options)\n    case \"$4\" in\n      history-limit)\n        n=$(cat '{counter}')\n        n=$((n + 1))\n        echo \"$n\" > '{counter}'\n        echo 2000\n        ;;\n      alternate-screen) echo on ;;\n    esac\n    ;;\nesac\nexit 0\n",
        counter = counter.display()
    );
    let bin = write_fake_tmux(dir.path(), "fake-tmux-verify-always-wrong", &script);
    let options = trusty_common::tmux::scrollback_option_commands(100_000, true, true);

    let verified = apply_and_verify_scrollback_options(&bin, &options, 100_000, true);

    assert!(
        !verified,
        "must return false (never silently proceed as verified) once every \
         apply-and-verify attempt is exhausted — this is the #3386 review's caller-visible \
         degraded signal"
    );
    assert_eq!(
        std::fs::read_to_string(&counter).unwrap().trim(),
        APPLY_VERIFY_MAX_ATTEMPTS.to_string(),
        "must have made exactly APPLY_VERIFY_MAX_ATTEMPTS probe attempts"
    );
}

// ── #5151: alternate-screen rides the same verified path ────────────

#[serial_test::serial]
#[test]
fn apply_and_verify_scrollback_options_fails_when_only_alternate_screen_is_wrong() {
    // #5151 regression: history-limit reads back correctly, but the
    // server reports `alternate-screen on` when `off` was configured —
    // exactly the shape a wrong-scope `set-option` produces. Verification
    // must fail. Before alternate-screen was probed at all this returned
    // `true`, reporting an ergonomics set that never landed.
    let dir = tempfile::tempdir().unwrap();
    let script = format!(
        "#!/bin/sh\ncase \"$1\" in\n{show_options}esac\nexit 0\n",
        show_options = fake_show_options_case("100000", "on")
    );
    let bin = write_fake_tmux(dir.path(), "fake-tmux-alt-mismatch", &script);
    let options = trusty_common::tmux::scrollback_option_commands(100_000, true, false);

    let verified = apply_and_verify_scrollback_options(&bin, &options, 100_000, false);

    assert!(
        !verified,
        "a correct history-limit must not verify away a wrong alternate-screen — that is \
         the fail-open #5151 exists to close"
    );
}

#[serial_test::serial]
#[test]
fn apply_and_verify_scrollback_options_verifies_alternate_screen_off() {
    // The positive counterpart: when the server DOES report the
    // configured `off`, the cycle verifies on its first attempt.
    let dir = tempfile::tempdir().unwrap();
    let script = format!(
        "#!/bin/sh\ncase \"$1\" in\n{show_options}esac\nexit 0\n",
        show_options = fake_show_options_case("100000", "off")
    );
    let bin = write_fake_tmux(dir.path(), "fake-tmux-alt-match", &script);
    let options = trusty_common::tmux::scrollback_option_commands(100_000, true, false);

    assert!(apply_and_verify_scrollback_options(
        &bin, &options, 100_000, false
    ));
}

#[serial_test::serial]
#[test]
fn apply_and_verify_probes_the_same_scope_it_sets() {
    // #5151 fail-open guard, asserted on the real argv the apply-and-
    // verify cycle emits: the `alternate-screen` set and its readback
    // must carry the SAME scope flag. A set at one scope verified by a
    // probe at another reports success for an option that did nothing.
    let dir = tempfile::tempdir().unwrap();
    let log = dir.path().join("argv.log");
    let script = format!(
        "#!/bin/sh\necho \"$@\" >> '{log}'\ncase \"$1\" in\n{show_options}esac\nexit 0\n",
        log = log.display(),
        show_options = fake_show_options_case("100000", "off")
    );
    let bin = write_fake_tmux(dir.path(), "fake-tmux-scope-log", &script);
    let options = trusty_common::tmux::scrollback_option_commands(100_000, true, false);

    assert!(apply_and_verify_scrollback_options(
        &bin, &options, 100_000, false
    ));

    let calls = std::fs::read_to_string(&log).unwrap();
    let scope_of = |prefix: &str| -> String {
        let line = calls
            .lines()
            .find(|l| l.starts_with(prefix) && l.contains("alternate-screen"))
            .unwrap_or_else(|| panic!("no {prefix} call for alternate-screen in: {calls}"));
        line.split_whitespace()
            .nth(1)
            .expect("scope flag")
            .to_string()
    };

    let set_scope = scope_of("set-option");
    let show_scope = scope_of("show-options");
    assert_eq!(set_scope, "-wg", "alternate-screen must be set at -wg");
    assert_eq!(
        show_scope, set_scope,
        "the readback must query the scope the set wrote: {calls}"
    );
}

// ── #6529: the tmux client's UTF-8 declaration decides whether tmux keeps
// the delimiters in a `-F` listing ────────────────────────────────────────

/// tmux reads ONE locale variable, by precedence — mirror that, not any-of.
///
/// Why: `LC_ALL=C` beside `LANG=en_US.UTF-8` is the case an any-of test gets
/// backwards. tmux takes the first non-empty of `LC_ALL`, `LC_CTYPE`, `LANG`
/// and tests only that one, so that environment is NOT UTF-8 to tmux and its
/// server sanitizes the tabs out of the reply.
/// What: pins each precedence step and the empty-value skip.
/// Test: this is the test.
#[test]
fn env_declares_utf8_follows_tmux_precedence() {
    assert!(declares_utf8(Some("en_US.UTF-8"), None, None));
    assert!(declares_utf8(Some("C.utf8"), None, None));
    assert!(!declares_utf8(Some("C"), None, None));
    assert!(!declares_utf8(Some("POSIX"), None, Some("en_US.UTF-8")));
    // An empty value is skipped, exactly as tmux's `*s == '\0'` test does.
    assert!(declares_utf8(Some(""), None, Some("en_US.UTF-8")));
    assert!(declares_utf8(None, Some("en_US.UTF-8"), Some("C")));
    // Nothing set at all — the environment launchd hands the daemon (#6529).
    assert!(!declares_utf8(None, None, None));
}

/// The helper injects `LC_ALL` only when the inherited environment needs it.
///
/// Why: overriding an operator's own UTF-8 locale is a behaviour change this
/// fix does not need. The injection exists for an environment that declares
/// nothing, which is what launchd hands the daemon.
/// What: builds a `Command` under this process's real environment and asserts
/// the helper's decision agrees with [`declares_utf8`] for that environment,
/// mutating no process-global state.
/// Test: this is the test.
#[test]
fn force_utf8_client_env_is_a_no_op_under_a_utf8_locale() {
    let read = |key: &str| std::env::var(key).ok();
    let already = declares_utf8(
        read("LC_ALL").as_deref(),
        read("LC_CTYPE").as_deref(),
        read("LANG").as_deref(),
    );
    let mut cmd = std::process::Command::new("true");
    force_utf8_client_env(&mut cmd);
    let injected = cmd
        .get_envs()
        .any(|(k, v)| k == "LC_ALL" && v == Some(std::ffi::OsStr::new(UTF8_LOCALE)));
    assert_eq!(
        injected, !already,
        "LC_ALL must be injected exactly when the environment does not already \
         declare UTF-8 (#6529)"
    );
}