trusty-common 0.26.1

Shared utilities and provider-agnostic streaming chat (ChatProvider, OllamaProvider, OpenRouter, tool-use) for trusty-* projects
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
//! Tests for the `update` module.
//!
//! Why: Kept in a sibling file to respect the 500-line cap on `mod.rs`
//! while still using `#[cfg(test)]` so the test helpers are compiled only
//! in test mode.

use super::*;
use serial_test::serial;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};

/// Serialize tests that mutate environment variables to prevent races when
/// `cargo test` runs them on parallel threads.
static ENV_LOCK: Mutex<()> = Mutex::new(());

/// Monotonic counter guaranteeing every `unique_crate` name generated by
/// [`run_cache_freshness_test`] is actually unique.
///
/// Why (issue #2460): the previous generator combined the process id with a
/// nanosecond timestamp, but two test threads scheduled close enough
/// together can observe the *same* `SystemTime::now()` value on platforms
/// where the wall clock does not have true nanosecond resolution — the two
/// cache-freshness tests would then race on the identical cache file. A
/// process-wide atomic counter is deterministic by construction and cannot
/// collide, independent of clock granularity or thread scheduling.
/// What: `fetch_add`'d once per call; the returned value is folded into the
/// generated crate name.
/// Test: covered indirectly — `cache_fresh_returns_some_when_newer` and
/// `cache_fresh_returns_none_when_current` no longer flake under
/// `--test-threads` > 1 (see the repro loop in the PR description).
static UNIQUE_CRATE_COUNTER: AtomicU64 = AtomicU64::new(0);

// ── semver helpers ──────────────────────────────────────────────────────

#[test]
fn semver_newer_returns_true() {
    assert!(is_newer("0.20.0", "0.19.0"));
    assert!(is_newer("1.0.0", "0.99.99"));
    assert!(is_newer("0.19.1", "0.19.0"));
}

#[test]
fn semver_equal_returns_false() {
    assert!(!is_newer("0.19.0", "0.19.0"));
}

#[test]
fn semver_older_returns_false() {
    assert!(!is_newer("0.18.0", "0.19.0"));
    assert!(!is_newer("0.19.0", "1.0.0"));
}

#[test]
fn semver_prerelease_stripped() {
    // Pre-release suffixes are stripped before comparison.
    assert!(!is_newer("0.19.0-beta.1", "0.19.0"));
    assert!(is_newer("0.20.0-alpha.1", "0.19.0"));
}

#[test]
fn semver_parse_strips_prerelease() {
    assert_eq!(parse_version("1.2.3-beta.1"), Some((1, 2, 3)));
    assert_eq!(parse_version("1.2.3+build.42"), Some((1, 2, 3)));
    assert_eq!(parse_version("1.2.3-rc.1+sha.abc"), Some((1, 2, 3)));
}

#[test]
fn semver_parse_handles_missing_patch() {
    assert_eq!(parse_version("1.2"), Some((1, 2, 0)));
    assert_eq!(parse_version("1"), Some((1, 0, 0)));
}

#[test]
fn semver_parse_rejects_garbage() {
    assert_eq!(parse_version("not-a-version"), None);
    assert_eq!(parse_version(""), None);
}

// ── notice formatting ───────────────────────────────────────────────────

#[test]
fn notice_formats_correctly() {
    let info = UpdateInfo {
        crate_name: "trusty-search".to_owned(),
        current: "0.19.0".to_owned(),
        latest: "0.20.0".to_owned(),
    };
    let n = notice(&info);
    assert!(n.contains("trusty-search"), "crate name missing: {n}");
    assert!(n.contains("0.20.0"), "latest version missing: {n}");
    assert!(n.contains("0.19.0"), "current version missing: {n}");
    assert!(n.contains("cargo install"), "install command missing: {n}");
    assert!(n.contains("--locked"), "--locked flag missing: {n}");
}

// ── opt-out env var ────────────────────────────────────────────────────

// Issue #3689: `check_throttled_skips_when_no_update_check_set` and
// `check_throttled_skips_when_ci_set` mutate the process-global
// `NO_UPDATE_CHECK_ENV`/`CI_ENV` vars for the DURATION of their own
// `check_throttled(...).await` call (the env is set, THEN awaited, THEN
// cleared — the mutation deliberately outlives the brief `ENV_LOCK` critical
// sections around the set/remove calls, since `check_throttled` itself must
// observe the var). `cache_fresh_returns_some_when_newer` also calls
// `check_throttled` (via `run_cache_freshness_test`) without expecting either
// var to be set; without `#[serial]` these two tests can race a THIRD,
// concurrently-scheduled `check_throttled` call and have it observe a
// spuriously-set `CI_ENV`/`NO_UPDATE_CHECK_ENV`, turning an expected
// `Some(..)` into `None` (flaked under parallel `cargo test`: "expected
// Some, got None"). `#[serial(update_check_throttled_env)]` (the crate's
// existing named-group convention — see
// `verify_installed_binary_finds_binary_via_path`'s
// `update_verify_installed_binary_env`, #3608/#3629) gives the three
// `check_throttled` callers mutual exclusion for their whole async body,
// including the `.await`, which a bare `std::sync::Mutex` guard cannot span.
#[tokio::test]
#[serial(update_check_throttled_env)]
async fn check_throttled_skips_when_no_update_check_set() {
    // Set the env var while holding the lock, then drop the lock before
    // the await so clippy::await-holding-lock is satisfied.
    {
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // Safety: env mutation is serialized by ENV_LOCK; guard dropped
        // before the async call below.
        unsafe { std::env::set_var(NO_UPDATE_CHECK_ENV, "1") };
    }
    let result = check_throttled("trusty-search", "0.19.0").await;
    {
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe { std::env::remove_var(NO_UPDATE_CHECK_ENV) };
    }
    assert!(
        result.is_none(),
        "expected None when {NO_UPDATE_CHECK_ENV} is set"
    );
}

#[tokio::test]
#[serial(update_check_throttled_env)]
async fn check_throttled_skips_when_ci_set() {
    {
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe { std::env::set_var(CI_ENV, "true") };
    }
    let result = check_throttled("trusty-search", "0.19.0").await;
    {
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        unsafe { std::env::remove_var(CI_ENV) };
    }
    assert!(result.is_none(), "expected None when CI is set");
}

// ── cache freshness logic (uses a temp cache dir) ────────────────────────

/// Write a cache entry with the given `last_check_unix` timestamp and
/// `latest_version`, then call `check_throttled` and verify the result
/// matches `expected_is_some`. No real network is used because a fresh
/// cache entry suppresses the network call.
async fn run_cache_freshness_test(
    last_check_unix: u64,
    latest_version: &str,
    current_version: &str,
    expected_is_some: bool,
) {
    // Use a unique crate name to avoid cross-test cache pollution. The
    // atomic counter (not just pid + nanosecond timestamp) guarantees
    // uniqueness by construction — see `UNIQUE_CRATE_COUNTER` (issue #2460).
    let unique_crate = format!(
        "test-crate-{}-{}",
        std::process::id(),
        UNIQUE_CRATE_COUNTER.fetch_add(1, Ordering::Relaxed)
    );

    let entry = CacheEntry {
        last_check_unix,
        latest_version: latest_version.to_owned(),
    };
    write_cache(&unique_crate, &entry);

    // The cache is fresh, so check_throttled returns the cached result
    // without any network call.
    let result = check_throttled(&unique_crate, current_version).await;
    assert_eq!(
        result.is_some(),
        expected_is_some,
        "freshness={expected_is_some}: latest={latest_version} current={current_version}"
    );

    // Clean up.
    let _ = std::fs::remove_file(cache_path(&unique_crate));
}

// Issue #3689: shares `update_check_throttled_env` with the two
// `check_throttled_skips_when_*` tests above — see the doc comment there.
// This test's own `check_throttled` call expects a live (non-throttled)
// result (`Some`), so a sibling test's transient `CI_ENV`/
// `NO_UPDATE_CHECK_ENV` mutation racing this `.await` was observed flipping
// it to `None` under parallel `cargo test`.
#[tokio::test]
#[serial(update_check_throttled_env)]
async fn cache_fresh_returns_some_when_newer() {
    // Cache written 1 h ago (well within 24 h) with a newer version.
    run_cache_freshness_test(now_unix_secs() - 3600, "1.0.0", "0.19.0", true).await;
}

#[tokio::test]
async fn cache_fresh_returns_none_when_current() {
    // Cache written 1 h ago with the same version — already up to date.
    run_cache_freshness_test(now_unix_secs() - 3600, "0.19.0", "0.19.0", false).await;
}

// ── corrupt / missing cache file ──────────────────────────────────────

#[test]
fn corrupt_cache_returns_none() {
    // Write garbage bytes to the cache file; read_cache must return None.
    let unique_crate = format!("corrupt-test-{}", std::process::id());
    let path = cache_path(&unique_crate);
    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    let _ = std::fs::write(&path, b"this is not valid json {{{{");
    let result = read_cache(&unique_crate);
    let _ = std::fs::remove_file(&path);
    assert!(result.is_none(), "corrupt cache must yield None");
}

#[test]
fn missing_cache_returns_none() {
    let unique_crate = format!("missing-test-{}", std::process::id());
    // Ensure the file does not exist.
    let _ = std::fs::remove_file(cache_path(&unique_crate));
    let result = read_cache(&unique_crate);
    assert!(result.is_none(), "missing cache must yield None");
}

// ── cache round-trip ──────────────────────────────────────────────────

#[test]
fn cache_round_trip() {
    let unique_crate = format!("roundtrip-{}", std::process::id());
    let entry = CacheEntry {
        last_check_unix: 1_700_000_000,
        latest_version: "9.9.9".to_owned(),
    };
    write_cache(&unique_crate, &entry);
    let back = read_cache(&unique_crate);
    let _ = std::fs::remove_file(cache_path(&unique_crate));
    let back = back.expect("cache round-trip should succeed");
    assert_eq!(back.last_check_unix, 1_700_000_000);
    assert_eq!(back.latest_version, "9.9.9");
}

// ── upgrade primitive tests ────────────────────────────────────────────────

/// Verify the command constructed by `perform_upgrade` uses the right args.
///
/// Why: We can't actually run `cargo install` in a unit test without touching
/// the network and the filesystem. This test validates the command construction
/// logic by inspecting that `perform_upgrade` calls cargo with `install` and
/// `--locked` — validated by running it against a non-existent crate name and
/// checking that it fails with the right kind of error (cargo not found is
/// acceptable too, meaning the command was built).
/// Test: tagged #[ignore] because it shells out; run manually with
/// `cargo test -p trusty-common --features update-check -- --include-ignored`.
#[tokio::test]
#[ignore]
async fn perform_upgrade_fails_cleanly_on_nonexistent_crate() {
    let result = super::perform_upgrade("___trusty_test_crate_does_not_exist___").await;
    // Should be Err because cargo install would fail for a nonexistent crate.
    assert!(
        result.is_err(),
        "expected Err for nonexistent crate, got Ok"
    );
    let msg = result.unwrap_err().to_string();
    // The error message should mention cargo or the status.
    assert!(
        msg.contains("cargo install") || msg.contains("status") || msg.contains("exited"),
        "unexpected error message: {msg}"
    );
}

/// Redirect the REAL (OS-level) stdout file descriptor to `tmp` for the
/// duration of `f`, then restore it — regardless of whether `f` panics.
///
/// Why (#3830 regression proof): `Command::status()` "inheriting" stdio
/// means a child writes to whatever fd 1 currently points to; the only way
/// to OBSERVE that from a test is to control what fd 1 points to before
/// spawning, run the command, then read it back — asserting on the
/// captured `Output.stdout`/`stderr` bytes proves nothing about the
/// INHERIT path, because `.status()` never populates those fields at all.
/// A prior version of this test suite made exactly that mistake (asserted
/// only `is_ok()`), which still passed even when `run_with_mode` was
/// reverted to `.status()` — reviewed and caught by code-critic on PR #3834.
///
/// CRITICAL: fd 1 is process-global. If this ran as an ordinary parallel
/// `#[test]`, the default test harness's OWN per-test "test x ... ok" status
/// line — printed by the harness-controller thread through the REAL stdout,
/// not through the per-test captured sink — can land in `tmp` mid-redirect
/// whenever ANY sibling test (not just ones touching this file) finishes on
/// another thread. `#[serial]` only excludes other `#[serial]`-tagged tests,
/// not the harness's own status printing, so this was observed to flake
/// (`cargo test` `--test-threads` > 1, confirmed empirically). The `#[test]`
/// wrappers below never call this directly on the main test-binary
/// invocation — they re-exec the test binary, selecting ONLY the `_inner`
/// test (`--test-threads=1`), so it runs as the sole test in a dedicated
/// process with no sibling thread able to write through the hijacked fd.
///
/// What: `dup`s the real stdout fd aside, `dup2`s `tmp`'s fd onto it, runs
/// `f`, restores the saved fd (via a guard so a panic inside `f` still
/// restores it), and returns `f`'s result.
/// Test: used by `run_with_mode_capture_never_leaks_to_parent_stdio_inner`
/// and `run_with_mode_inherit_leaks_to_parent_stdio_inner` below.
#[cfg(unix)]
async fn with_real_stdout_redirected_to<Fut, T>(tmp: &std::fs::File, f: Fut) -> T
where
    Fut: std::future::Future<Output = T>,
{
    use std::os::unix::io::AsRawFd;

    /// RAII guard: restores the saved real-stdout fd on drop, so a panic in
    /// `f` can never leave the process's stdout permanently redirected.
    struct RestoreStdout(std::os::raw::c_int);
    impl Drop for RestoreStdout {
        fn drop(&mut self) {
            unsafe {
                libc::dup2(self.0, libc::STDOUT_FILENO);
                libc::close(self.0);
            }
        }
    }

    let saved = unsafe { libc::dup(libc::STDOUT_FILENO) };
    assert!(saved >= 0, "dup(STDOUT_FILENO) failed");
    let _restore = RestoreStdout(saved);

    let rc = unsafe { libc::dup2(tmp.as_raw_fd(), libc::STDOUT_FILENO) };
    assert!(rc >= 0, "dup2(tmp, STDOUT_FILENO) failed");

    f.await
}

/// Re-exec this test binary, running ONLY `inner_test_name` (an `#[ignore]`d
/// test) alone with `--test-threads=1`, and assert it exits 0.
///
/// Why: see [`with_real_stdout_redirected_to`]'s doc — any test that hijacks
/// the process's real stdout fd must run with zero sibling test threads, or
/// the harness's own status-line printing can land in the hijacked fd and
/// corrupt the assertion. Re-execing the compiled test binary, filtered to
/// exactly one `#[ignore]`d test name, is the standard way to get that
/// isolation without spinning up a second crate/binary just for this.
/// What: `Command::new(current_exe())` with
/// `[name, "--exact", "--ignored", "--test-threads=1"]`; panics with the
/// child's captured stdout/stderr on a non-zero exit (so a failure inside
/// the isolated test is not silently swallowed).
/// Test: exercised by every `_inner`-test wrapper below.
#[cfg(unix)]
fn run_isolated_inner_test(inner_test_name: &str) {
    let exe = std::env::current_exe().expect("resolve current test binary");
    let output = std::process::Command::new(&exe)
        .args([inner_test_name, "--exact", "--ignored", "--test-threads=1"])
        .output()
        .expect("re-exec test binary for isolated fd test");
    assert!(
        output.status.success(),
        "isolated test `{inner_test_name}` failed ({}):\n--- stdout ---\n{}\n--- stderr ---\n{}",
        output.status,
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );
}

/// The #3830 regression proof: [`UpgradeOutput::Capture`] must NEVER let a
/// child's output reach the parent's real (inherited) stdout, no matter how
/// noisy the child is or whether it succeeds.
///
/// Why: see [`with_real_stdout_redirected_to`]'s doc — this replaces a
/// weaker predecessor that only asserted `is_ok()`, which passed even
/// against a reverted `.status()`-based implementation (code-critic finding
/// on PR #3834). `#[ignore]`d + only ever invoked, alone, via
/// [`run_isolated_inner_test`] from the `#[test]` wrapper immediately below
/// — see that function's doc for why this can't be an ordinary parallel test.
/// What: redirects the real stdout fd to a tempfile, runs a noisy,
/// successful `sh -c` command through `run_with_mode(.., Capture, ..)`,
/// restores stdout, then asserts the tempfile received ZERO bytes.
/// Test: this is the test (invoked via
/// `run_with_mode_capture_never_leaks_to_parent_stdio`).
#[cfg(unix)]
#[tokio::test]
#[ignore]
async fn run_with_mode_capture_never_leaks_to_parent_stdio_inner() {
    use std::io::Read;

    let tmp = tempfile::NamedTempFile::new().expect("create tempfile");
    let mut cmd = tokio::process::Command::new("sh");
    cmd.args([
        "-c",
        "for i in $(seq 1 20); do echo \"LEAK_MARKER_3830 stdout $i\"; \
         echo \"LEAK_MARKER_3830 stderr $i\" >&2; done; exit 0",
    ]);

    let result = with_real_stdout_redirected_to(
        tmp.as_file(),
        super::upgrade::run_with_mode(
            cmd,
            super::upgrade::UpgradeOutput::Capture,
            "`noisy-capture`",
        ),
    )
    .await;
    assert!(result.is_ok(), "expected Ok, got {result:?}");

    let mut contents = String::new();
    tmp.reopen()
        .expect("reopen tempfile")
        .read_to_string(&mut contents)
        .expect("read tempfile");
    assert!(
        contents.is_empty(),
        "Capture mode leaked to the parent's real stdout fd: {contents:?}"
    );
}

/// `#[test]` entry point for the isolated inner test above — see
/// [`run_isolated_inner_test`]'s doc for why this indirection exists. This is
/// the test `cargo test` actually runs; it re-execs the binary so the real
/// fd-1 hijack happens with zero sibling test threads.
/// Test: this wraps `run_with_mode_capture_never_leaks_to_parent_stdio_inner`.
#[cfg(unix)]
#[test]
fn run_with_mode_capture_never_leaks_to_parent_stdio() {
    run_isolated_inner_test(
        "update::tests::run_with_mode_capture_never_leaks_to_parent_stdio_inner",
    );
}

/// Contrast/methodology-validation test: [`UpgradeOutput::Inherit`] (the
/// mode `perform_upgrade` — unchanged, used by the standalone
/// trusty-memory/trusty-search `upgrade` commands — still uses) DOES let a
/// child's stdout reach the parent's real stdout fd.
///
/// Why: without this, the Capture test passing could mean either "Capture
/// correctly avoids the parent's stdout" OR "the fd-redirection technique
/// itself is broken and never observes anything" — indistinguishable from a
/// test that trivially always passes. This proves the harness DOES detect a
/// leak when one is expected, grounding the sibling test's negative result.
/// `#[ignore]`d for the same process-isolation reason — see
/// [`with_real_stdout_redirected_to`]'s doc.
/// What: same redirect-run-restore shape, but through
/// `UpgradeOutput::Inherit`; asserts the tempfile DOES contain the child's
/// marker text.
/// Test: this is the test (invoked via
/// `run_with_mode_inherit_leaks_to_parent_stdio`).
#[cfg(unix)]
#[tokio::test]
#[ignore]
async fn run_with_mode_inherit_leaks_to_parent_stdio_inner() {
    use std::io::Read;

    let tmp = tempfile::NamedTempFile::new().expect("create tempfile");
    let mut cmd = tokio::process::Command::new("sh");
    cmd.args(["-c", "echo 'LEAK_MARKER_3830 inherit-path'; exit 0"]);

    let result = with_real_stdout_redirected_to(
        tmp.as_file(),
        super::upgrade::run_with_mode(
            cmd,
            super::upgrade::UpgradeOutput::Inherit,
            "`noisy-inherit`",
        ),
    )
    .await;
    assert!(result.is_ok(), "expected Ok, got {result:?}");

    let mut contents = String::new();
    tmp.reopen()
        .expect("reopen tempfile")
        .read_to_string(&mut contents)
        .expect("read tempfile");
    assert!(
        contents.contains("LEAK_MARKER_3830 inherit-path"),
        "expected Inherit mode to leak to the parent's real stdout fd (the fd-redirection \
         technique may be broken — this test found nothing, which would make the sibling \
         Capture test's negative result meaningless): {contents:?}"
    );
}

/// `#[test]` entry point for the isolated inner test above — see
/// [`run_isolated_inner_test`]'s doc.
/// Test: this wraps `run_with_mode_inherit_leaks_to_parent_stdio_inner`.
#[cfg(unix)]
#[test]
fn run_with_mode_inherit_leaks_to_parent_stdio() {
    run_isolated_inner_test("update::tests::run_with_mode_inherit_leaks_to_parent_stdio_inner");
}

/// Why (#3830): the error path's diagnostic must come from the child's
/// CAPTURED stderr — only reachable if the command was actually run via
/// `.output()`. `.status()` (the pre-fix `Inherit` path) has no `stderr`
/// field to read, so this exact assertion would not compile against that
/// code either — pinning the fix at the type level as well as behaviourally.
/// What: runs a command that writes a distinctive marker to stderr and
/// exits non-zero via `UpgradeOutput::Capture`; asserts the returned error's
/// message contains that exact marker.
/// Test: this is the test.
#[tokio::test]
async fn run_with_mode_capture_folds_stderr_into_error() {
    let mut cmd = tokio::process::Command::new("sh");
    cmd.args([
        "-c",
        "echo 'DISTINCTIVE_MARKER_3830_COMMON: cargo install failed' >&2; exit 7",
    ]);
    let err = super::upgrade::run_with_mode(
        cmd,
        super::upgrade::UpgradeOutput::Capture,
        "`fake cargo install`",
    )
    .await
    .expect_err("expected Err");
    let msg = err.to_string();
    assert!(
        msg.contains("DISTINCTIVE_MARKER_3830_COMMON: cargo install failed"),
        "error message did not fold in captured stderr: {msg}"
    );
    assert!(msg.contains("fake cargo install"));
}

/// Verify that `verify_installed_binary` passes for `cargo`, which is always
/// on PATH for any developer machine.
///
/// Why: We need a real binary that is always present to test the happy path
/// without installing anything. `cargo --version` is a safe no-side-effect probe.
/// Test: tagged #[ignore] (shells out); run manually with `--include-ignored`.
#[tokio::test]
#[ignore]
async fn verify_installed_binary_passes_for_cargo() {
    let result = super::verify_installed_binary("cargo").await;
    assert!(
        result.is_ok(),
        "expected Ok for `cargo --version`, got: {:?}",
        result
    );
}

/// Verify that `verify_installed_binary` returns Err for a non-existent binary.
///
/// Why: Confirms the health gate catches missing binaries before a self-exit.
/// Test: sync test — no shell-out needed because `which` will quickly fail.
#[tokio::test]
async fn verify_installed_binary_fails_for_missing_binary() {
    let result = super::verify_installed_binary("___no_such_binary_xyz_999___").await;
    assert!(
        result.is_err(),
        "expected Err for non-existent binary, got Ok"
    );
}

// ── candidate_bin_dirs (pure path-resolution logic, issue #1771) ──────────

#[test]
fn candidate_bin_dirs_falls_back_to_dot_cargo() {
    let home = std::path::Path::new("/home/tester");
    let dirs = super::upgrade::candidate_bin_dirs(Some(home), None);
    assert_eq!(dirs[0], home.join(".cargo").join("bin"));
}

#[test]
fn candidate_bin_dirs_prefers_cargo_home_override() {
    let home = std::path::Path::new("/home/tester");
    let dirs = super::upgrade::candidate_bin_dirs(Some(home), Some("/opt/custom-cargo"));
    assert_eq!(
        dirs[0],
        std::path::PathBuf::from("/opt/custom-cargo").join("bin"),
        "CARGO_HOME override must take priority over ~/.cargo/bin"
    );
}

#[test]
fn candidate_bin_dirs_ignores_empty_cargo_home() {
    let home = std::path::Path::new("/home/tester");
    let dirs = super::upgrade::candidate_bin_dirs(Some(home), Some(""));
    assert_eq!(
        dirs[0],
        home.join(".cargo").join("bin"),
        "empty CARGO_HOME must fall back to ~/.cargo/bin, not be treated as a path"
    );
}

#[test]
fn candidate_bin_dirs_includes_local_bin() {
    let home = std::path::Path::new("/home/tester");
    let dirs = super::upgrade::candidate_bin_dirs(Some(home), None);
    assert!(
        dirs.contains(&home.join(".local").join("bin")),
        "~/.local/bin (the prebuilt installer's default) must be a candidate: {dirs:?}"
    );
    // ~/.local/bin must be checked after ~/.cargo/bin, not before.
    let local_idx = dirs
        .iter()
        .position(|d| d == &home.join(".local").join("bin"))
        .expect("local bin present");
    let cargo_idx = dirs
        .iter()
        .position(|d| d == &home.join(".cargo").join("bin"))
        .expect("cargo bin present");
    assert!(cargo_idx < local_idx, "cargo bin must be checked first");
}

#[test]
fn candidate_bin_dirs_empty_without_home_or_cargo_home() {
    let dirs = super::upgrade::candidate_bin_dirs(None, None);
    assert!(
        dirs.is_empty(),
        "no home and no CARGO_HOME override must yield zero candidates"
    );
}

// ── verify_installed_binary directory resolution (issue #1771) ────────────
//
// These write a tiny executable shell script that exits 0 on `--version` and
// point HOME at a tempdir so the real filesystem/env are never touched.

/// Write a minimal executable shell script at `path` that responds
/// successfully to `--version`, standing in for a real installed binary.
#[cfg(unix)]
fn write_fake_binary(path: &std::path::Path) {
    use std::os::unix::fs::PermissionsExt;
    std::fs::write(path, b"#!/bin/sh\necho fake 1.0.0\nexit 0\n").expect("write fake binary");
    let mut perms = std::fs::metadata(path)
        .expect("stat fake binary")
        .permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(path, perms).expect("chmod fake binary");
}

/// Snapshot of the env vars mutated by the `verify_installed_binary_*`
/// directory-resolution tests, captured so they can be restored verbatim.
#[cfg(unix)]
struct EnvSnapshot {
    home: Option<String>,
    cargo_home: Option<String>,
    path: Option<String>,
}

/// Set `HOME` (and clear `CARGO_HOME` unless `cargo_home` is given) and
/// return the prior values so the caller can restore them afterward.
///
/// Why: Split into non-async set/restore steps (rather than wrapping an
/// awaited closure) so the `ENV_LOCK` guard is only ever held across the
/// synchronous mutation, never across an `.await` point
/// (`clippy::await_holding_lock`).
#[cfg(unix)]
fn set_home_env(home: &std::path::Path, cargo_home: Option<&str>) -> EnvSnapshot {
    let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let snapshot = EnvSnapshot {
        home: std::env::var("HOME").ok(),
        cargo_home: std::env::var("CARGO_HOME").ok(),
        path: std::env::var("PATH").ok(),
    };
    unsafe {
        std::env::set_var("HOME", home);
        match cargo_home {
            Some(v) => std::env::set_var("CARGO_HOME", v),
            None => std::env::remove_var("CARGO_HOME"),
        }
    }
    snapshot
}

/// Restore env vars captured by [`set_home_env`]. Must be called after the
/// awaited work under test has completed.
#[cfg(unix)]
fn restore_home_env(snapshot: EnvSnapshot) {
    let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    unsafe {
        match snapshot.home {
            Some(h) => std::env::set_var("HOME", h),
            None => std::env::remove_var("HOME"),
        }
        match snapshot.cargo_home {
            Some(h) => std::env::set_var("CARGO_HOME", h),
            None => std::env::remove_var("CARGO_HOME"),
        }
        match snapshot.path {
            Some(p) => std::env::set_var("PATH", p),
            None => std::env::remove_var("PATH"),
        }
    }
}

#[cfg(unix)]
#[tokio::test]
#[serial(update_verify_installed_binary_env)]
async fn verify_installed_binary_finds_binary_in_cargo_bin() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let cargo_bin = tmp.path().join(".cargo").join("bin");
    std::fs::create_dir_all(&cargo_bin).expect("mkdir .cargo/bin");
    write_fake_binary(&cargo_bin.join("fake_trusty_bin_cargo"));

    let snapshot = set_home_env(tmp.path(), None);
    let result = super::verify_installed_binary("fake_trusty_bin_cargo").await;
    restore_home_env(snapshot);

    assert!(result.is_ok(), "expected Ok, got {result:?}");
}

#[cfg(unix)]
#[tokio::test]
#[serial(update_verify_installed_binary_env)]
async fn verify_installed_binary_finds_binary_in_local_bin() {
    let tmp = tempfile::tempdir().expect("tempdir");
    // Deliberately do NOT create ~/.cargo/bin — only ~/.local/bin has the
    // binary, mirroring a prebuilt-installer-only install (issue #1771/#1992).
    let local_bin = tmp.path().join(".local").join("bin");
    std::fs::create_dir_all(&local_bin).expect("mkdir .local/bin");
    write_fake_binary(&local_bin.join("fake_trusty_bin_local"));

    let snapshot = set_home_env(tmp.path(), None);
    let result = super::verify_installed_binary("fake_trusty_bin_local").await;
    restore_home_env(snapshot);

    assert!(
        result.is_ok(),
        "expected Ok when binary only exists in ~/.local/bin, got {result:?}"
    );
}

#[cfg(unix)]
#[tokio::test]
#[serial(update_verify_installed_binary_env)]
async fn verify_installed_binary_honours_cargo_home_override() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let custom_cargo_home = tmp.path().join("custom-cargo-home");
    let custom_bin = custom_cargo_home.join("bin");
    std::fs::create_dir_all(&custom_bin).expect("mkdir custom cargo bin");
    write_fake_binary(&custom_bin.join("fake_trusty_bin_cargo_home"));

    let home_dir = tmp.path().join("home");
    std::fs::create_dir_all(&home_dir).expect("mkdir home");

    let snapshot = set_home_env(
        &home_dir,
        Some(custom_cargo_home.to_str().expect("utf8 path")),
    );
    let result = super::verify_installed_binary("fake_trusty_bin_cargo_home").await;
    restore_home_env(snapshot);

    assert!(
        result.is_ok(),
        "expected Ok when binary is under $CARGO_HOME/bin, got {result:?}"
    );
}

#[cfg(unix)]
#[tokio::test]
// #3608: this test additionally mutates PATH (beyond what `set_home_env`
// covers), so it needs full-body isolation from every other test in this
// file that touches HOME/CARGO_HOME/PATH — not just the brief per-mutation
// `ENV_LOCK` critical sections `set_home_env`/`restore_home_env` take. A
// `std::sync::Mutex` guard can't span the `.await` below without tripping
// `clippy::await_holding_lock`, so `#[serial]` (already used elsewhere in
// this crate for the same class of problem, e.g.
// `inference::credentials::resolver::tests`) is the correct primitive: it
// serializes the whole async test body, including the await, against every
// other test carrying the same group tag.
#[serial(update_verify_installed_binary_env)]
async fn verify_installed_binary_finds_binary_via_path() {
    // HOME points at an empty tempdir with neither ~/.cargo/bin nor
    // ~/.local/bin containing the binary, forcing the PATH/`which` fallback.
    let home_tmp = tempfile::tempdir().expect("home tempdir");
    let path_tmp = tempfile::tempdir().expect("path tempdir");
    write_fake_binary(&path_tmp.path().join("fake_trusty_bin_path"));

    let snapshot = set_home_env(home_tmp.path(), None);
    // #3608: this mutation used to run with no lock held at all (the guard
    // taken by `set_home_env` above is already released by the time this
    // line runs). Take a fresh, brief `ENV_LOCK` critical section around it,
    // matching the convention every other synchronous env mutation in this
    // file uses (e.g. `check_throttled_skips_when_no_update_check_set`).
    {
        let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let prev_path = std::env::var("PATH").unwrap_or_default();
        let new_path = format!("{}:{prev_path}", path_tmp.path().display());
        // Safety: env mutation is serialized by ENV_LOCK (held above) and by
        // `#[serial(update_verify_installed_binary_env)]` for the full
        // async body including the await below.
        unsafe { std::env::set_var("PATH", &new_path) };
    }

    let result = super::verify_installed_binary("fake_trusty_bin_path").await;
    restore_home_env(snapshot);

    assert!(
        result.is_ok(),
        "expected Ok via PATH fallback, got {result:?}"
    );
}

/// Verify that `is_launchd_supervised` returns `false` in a normal test env.
///
/// Why: Unit tests run in a developer terminal / CI, neither of which is a
/// launchd-managed job. This catches regressions where the heuristic fires
/// too eagerly.
/// Test: the test sets `TERM_PROGRAM` to a non-empty value (mimicking an
/// interactive terminal session) and clears `XPC_SERVICE_NAME` to ensure the
/// fast path returns false.
#[test]
fn is_launchd_supervised_returns_false_in_test_env() {
    // Env mutations must be serialised with the same lock used by the other
    // env-mutating tests.
    let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    unsafe {
        std::env::set_var("TERM_PROGRAM", "TestRunner");
        std::env::remove_var("XPC_SERVICE_NAME");
    }
    let result = super::is_launchd_supervised();
    unsafe {
        std::env::remove_var("TERM_PROGRAM");
    }
    // In a terminal (TERM_PROGRAM set) the function must return false even
    // if XPC_SERVICE_NAME were somehow present.
    assert!(
        !result,
        "is_launchd_supervised returned true inside a test terminal env"
    );
}

// ── verify_installed_binary_at_path (issue #3554) ─────────────────────────
//
// The #3554 regression: the name-based `verify_installed_binary` can be
// fooled by a stale binary that resolves EARLIER than the just-installed one
// (via `candidate_bin_dirs`'s priority order, or a bare-name PATH `which`).
// `verify_installed_binary_at_path` takes the concrete path directly, so it
// must read the exact binary at that path regardless of what else exists.

/// Write a minimal executable shell script at `path` that echoes
/// `version_line` on `--version` and exits 0.
#[cfg(unix)]
fn write_versioned_binary(path: &std::path::Path, version_line: &str) {
    use std::os::unix::fs::PermissionsExt;
    std::fs::write(path, format!("#!/bin/sh\necho '{version_line}'\nexit 0\n"))
        .expect("write versioned fake binary");
    let mut perms = std::fs::metadata(path)
        .expect("stat fake binary")
        .permissions();
    perms.set_mode(0o755);
    std::fs::set_permissions(path, perms).expect("chmod fake binary");
}

/// THE #3554 regression shape: an isolated `$HOME`/`$CARGO_HOME` that ALSO
/// contains a stale, OLDER binary in `~/.cargo/bin` (checked FIRST by
/// `candidate_bin_dirs`) while the just-installed, NEWER binary lives in
/// `~/.local/bin` — exactly Bob's repro (cargo-install `tm` 0.19.26 shadowing
/// a freshly-downloaded 0.19.29 at `~/.local/bin/tm`).
///
/// Why this reproduces the bug (not a false-pass): first we prove the OLD
/// name-based `verify_installed_binary` reads the STALE `~/.cargo/bin` copy
/// in this exact shape (mirroring the pre-#3554 installer code path), then
/// we prove `verify_installed_binary_at_path` — pointed directly at the
/// concrete `~/.local/bin` file the installer actually just wrote — reads the
/// correct NEW version instead. A test that only exercised a clean `$HOME`
/// (no `~/.cargo/bin` entry) would pass either way and would NOT have caught
/// #3554; this one fails against the pre-fix code path.
#[cfg(unix)]
#[tokio::test]
async fn verify_installed_binary_at_path_reads_exact_binary_despite_path_shadow() {
    let tmp = tempfile::tempdir().expect("tempdir");

    // Stale binary at `~/.cargo/bin/tm` — 0.19.26.
    let cargo_bin = tmp.path().join(".cargo").join("bin");
    std::fs::create_dir_all(&cargo_bin).expect("mkdir .cargo/bin");
    write_versioned_binary(&cargo_bin.join("tm"), "trusty-mpm 0.19.26");

    // Just-installed binary at `~/.local/bin/tm` — 0.19.29.
    let local_bin = tmp.path().join(".local").join("bin");
    std::fs::create_dir_all(&local_bin).expect("mkdir .local/bin");
    let install_path = local_bin.join("tm");
    write_versioned_binary(&install_path, "trusty-mpm 0.19.29");

    let snapshot = set_home_env(tmp.path(), None);

    // Sanity: the OLD name-based resolver reads the STALE binary in this
    // exact shape — proving the shape reproduces #3554's mechanism.
    let stale = super::verify_installed_binary("tm").await;
    // verify_installed_binary only confirms success/failure (not the
    // version), so probe the version it would have health-gated directly to
    // show it is the cargo-bin (stale) copy, not the local-bin (new) one.
    let stale_bin_path = super::upgrade::candidate_bin_dirs(Some(tmp.path()), None)
        .into_iter()
        .map(|d| d.join("tm"))
        .find(|p| p.exists())
        .expect("candidate_bin_dirs must find a `tm` binary");
    restore_home_env(snapshot);

    assert!(
        stale.is_ok(),
        "the stale binary must itself be a healthy exit 0"
    );
    assert_eq!(
        stale_bin_path,
        cargo_bin.join("tm"),
        "name-based resolution must pick ~/.cargo/bin FIRST (the #3554 mechanism) \
         — got {stale_bin_path:?}"
    );

    // THE fix: pointed at the concrete install path, the health gate reads
    // the NEW version — never the stale shadowing copy.
    let reported = super::verify_installed_binary_at_path(&install_path)
        .await
        .expect("health gate must pass against the concrete install path");
    assert!(
        reported.contains("0.19.29"),
        "must read the NEW binary's version even though an older copy exists \
         at a higher-priority path; got: {reported:?}"
    );
    assert!(
        !reported.contains("0.19.26"),
        "must NOT read the stale shadowed binary; got: {reported:?}"
    );
}

#[cfg(unix)]
#[tokio::test]
async fn verify_installed_binary_at_path_fails_for_missing_binary() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let missing = tmp.path().join("does-not-exist").join("tm");

    let result = super::verify_installed_binary_at_path(&missing).await;

    assert!(
        result.is_err(),
        "a missing binary must be a hard error, not a silent pass"
    );
}

// ── live crates.io integration test (requires network) ───────────────────────
// Tagged #[ignore] so it is skipped in normal CI runs.

#[tokio::test]
#[ignore]
async fn live_crates_io_with_old_version_returns_some() {
    // Deliberately old version — should show trusty-search is newer.
    let result = check_crates_io("trusty-search", "0.0.1").await;
    assert!(
        result.is_some(),
        "expected Some(UpdateInfo) for old version 0.0.1 — is network available?"
    );
    let info = result.unwrap();
    println!("crates.io returned: latest={}", info.latest);
    assert!(
        !info.latest.is_empty(),
        "latest version should not be empty"
    );
    // Verify the notice string renders correctly
    let n = notice(&info);
    println!("Notice: {n}");
    assert!(
        n.contains("cargo install trusty-search --locked"),
        "notice missing install cmd: {n}"
    );
    assert!(n.contains(&info.latest), "notice missing latest version");
    assert!(n.contains("0.0.1"), "notice missing current version");
}