trusty-code 0.7.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
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
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
//! Tests for [`super`] — `tcode tui`'s attach-or-spawn daemon policy
//! (#4512; retransported onto the daemon's Unix socket in #6637).
//!
//! Why a sibling file: `daemon_autospawn.rs` is a production file under the
//! 500-SLOC cap (issue #610); the same `#[cfg(test)] #[path = ...]` split
//! `tui_client/engine.rs` uses keeps these cases in a test-capped file.
//! What: every branch of [`super::ensure_daemon_with`] is exercised against
//! REAL child processes and a REAL socket answering `health` — no mocked
//! internals — so the spawn, the readiness gate, and the binding check are
//! all genuinely executed. Stub children stand in for the daemon: a `sh`
//! script that records its pid and argv then sleeps (a daemon that stays
//! up), one that exits immediately (a daemon that fails to bind), and one
//! that touches a marker file (to prove a branch never spawned anything).
//!
//! Because readiness comes from the stub SOCKET rather than from the stub
//! child, `ensure_daemon_with` can return before the child has run a single
//! line. Nothing a stub writes may therefore be read directly — go through
//! [`SleepingStub::argv`] / [`SleepingStub::pid`], which poll (#6231, #5073).
//!
//! The spawn cases need the reverse ordering too: the socket must be UNBOUND
//! when the call is entered, or it attaches instead of spawning and the stub
//! never runs. That is arranged by [`bind_socket_after_spawn`], which keys off
//! the stub's own argv record rather than a wall clock — a timer raced the
//! fixture's own setup and lost under compile load (#5073).
//!
//! The `TCODE_DAEMON_URL` isolation the old `EnvGuard` needed is gone with the
//! env var itself. `TRUSTY_DATA_DIR_OVERRIDE` is still set, for the
//! spawned-daemon log path alone.

use std::os::unix::fs::PermissionsExt as _;
use std::path::{Path, PathBuf};
use std::time::Duration;

use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::UnixListener;

use super::*;

/// Serializes every case here, since they all mutate the process-global
/// `TRUSTY_DATA_DIR_OVERRIDE`. Mirrors `crate::task::mock_llm`'s convention.
static ENV_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

/// RAII guard repointing `resolve_data_dir("trusty-code")` at a fresh temp
/// directory, so the spawned-daemon log belongs to this test alone.
struct EnvGuard {
    _data_dir: tempfile::TempDir,
}

impl EnvGuard {
    fn isolated() -> Self {
        let data_dir = tempfile::tempdir().expect("data dir");
        // SAFETY: test-only env mutation, serialized by `ENV_LOCK`.
        unsafe {
            std::env::set_var(trusty_common::DATA_DIR_OVERRIDE_ENV, data_dir.path());
        }
        Self {
            _data_dir: data_dir,
        }
    }
}

impl Drop for EnvGuard {
    fn drop(&mut self) {
        // SAFETY: test-only env mutation, serialized by `ENV_LOCK`.
        unsafe {
            std::env::remove_var(trusty_common::DATA_DIR_OVERRIDE_ENV);
        }
    }
}

/// A stub daemon answering `health` on a real hardened socket.
///
/// Why hand-rolled rather than the real daemon: these tests are about the
/// attach/spawn DECISION, and a real daemon would drag a router, a workstream
/// store and a log-drain scheduler in behind it. One method and one frame is
/// the whole surface `ensure_daemon_with` consults.
fn stub_daemon_socket(dir: &Path, binding: Option<serde_json::Value>) -> PathBuf {
    let socket = dir.join("tcode.sock");
    stub_daemon_at(&socket, binding);
    socket
}

/// [`stub_daemon_socket`] at an exact path — #4600's per-project socket sits
/// beside the shared one. A stale socket file already there is replaced, as
/// the real daemon's singleton bind replaces one.
fn stub_daemon_at(socket: &Path, binding: Option<serde_json::Value>) {
    let dir = socket.parent().expect("a socket path has a parent");
    // `connect_hardened` refuses a socket whose containing directory is wider
    // than `0700`, and `tempfile` creates one at the process umask.
    std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
        .expect("harden the stub socket directory");
    if socket.exists() {
        std::fs::remove_file(socket).expect("clear the stale stub socket");
    }
    let listener = UnixListener::bind(socket).expect("bind the stub socket");
    std::fs::set_permissions(socket, std::fs::Permissions::from_mode(0o600))
        .expect("harden the stub socket");
    tokio::spawn(async move {
        while let Ok((stream, _)) = listener.accept().await {
            let binding = binding.clone();
            tokio::spawn(async move {
                let mut reader = BufReader::new(stream);
                let mut line = String::new();
                if reader.read_line(&mut line).await.unwrap_or(0) == 0 {
                    // A bare connect-and-close is `socket_is_serving`'s probe.
                    return;
                }
                let request: serde_json::Value = match serde_json::from_str(&line) {
                    Ok(request) => request,
                    Err(_) => return,
                };
                let mut result = serde_json::json!({"server": "tcode", "status": "ok"});
                if let Some(binding) = binding {
                    result["binding"] = binding;
                }
                let body = format!(
                    "{}\n",
                    serde_json::json!({
                        "jsonrpc": "2.0",
                        "id": request["id"].clone(),
                        "result": result,
                    })
                );
                let _ = reader.get_mut().write_all(body.as_bytes()).await;
                let _ = reader.get_mut().flush().await;
            });
        }
    });
}

/// The `binding` payload a daemon bound to `root` publishes.
fn binding_json(root: Option<&Path>) -> serde_json::Value {
    trusty_code::binding::ProjectBinding::resolve(root.map(Path::to_path_buf))
        .expect("must bind")
        .to_json()
}

/// Write an executable `sh` stub to `dir` and return its path. The stub
/// stands in for the `tcode` binary that would be spawned.
///
/// Why (#6231): exec fails with ETXTBSY on Linux while ANY process holds a
/// write fd on the file's inode. An in-process `std::fs::write` fd leaks into
/// whatever child a concurrent test forks during the write, and it stays open
/// there until that child execs — so the stub's own exec can fail after this
/// process has already closed its fd. Renaming does not help: the leaked fd
/// names the same inode.
/// What: a short-lived `sh` child writes and chmods `.<name>.tmp`, and is
/// reaped before this returns; the finished file is then renamed to `name`.
/// This process never opens the stub for writing, so no fork can inherit a
/// write fd onto it, and the final path only ever names a closed,
/// executable file. No ETXTBSY retry is needed.
/// Test: every stub-spawning case here, notably
/// `the_spawned_daemon_leads_its_own_session`.
fn stub_binary(dir: &Path, name: &str, body: &str) -> PathBuf {
    let staging = dir.join(format!(".{name}.tmp"));
    let status = std::process::Command::new("/bin/sh")
        .arg("-c")
        .arg(r#"printf '%s\n' "$2" > "$1" && chmod 755 "$1""#)
        .arg("sh")
        .arg(&staging)
        .arg(format!("#!/bin/sh\n{body}"))
        .stdin(std::process::Stdio::null())
        .status()
        .expect("run the stub writer");
    assert!(
        status.success(),
        "stub writer failed for {staging:?}: {status}"
    );
    let script = dir.join(name);
    std::fs::rename(&staging, &script).expect("move the stub into place");
    script
}

/// A stub that records its own pid and the argv it was called with, then
/// sleeps — the "daemon that comes up and stays up" case.
///
/// The pid is written to disk rather than read off a `Child` handle because
/// `ensure_daemon_with` does not RETURN one: it drops the handle without
/// signalling, which is exactly the behaviour
/// [`the_tui_never_signals_the_daemon_on_exit`] has to observe from outside.
/// Reading either record straight after the call raced the write and failed
/// with `NotFound` under parallel load (#6231, #5073), so [`SleepingStub::argv`]
/// and [`SleepingStub::pid`] are the only supported readers and both poll.
struct SleepingStub {
    /// The executable `sh` script `ensure_daemon_with` is pointed at.
    path: PathBuf,
    /// Where the stub appends `"$@"` — written FIRST, before the pid. One line
    /// per spawn, so a #4600 race case can see its second spawn.
    argv_log: PathBuf,
    /// Where the stub appends `$$`, one line per spawn.
    pid_log: PathBuf,
}

impl SleepingStub {
    /// Write the stub into `dir`, logging argv and pid beside it.
    ///
    /// The caller must keep `dir`'s `TempDir` alive longer than the returned
    /// value: [`Drop`] reads `pid_log` out of that directory to reap the
    /// child, so the stub has to drop FIRST (declare it after the `TempDir`).
    fn new(dir: &Path) -> Self {
        let argv_log = dir.join("argv");
        let pid_log = dir.join("pid");
        let path = stub_binary(
            dir,
            "tcode-sleep",
            &format!(
                "echo \"$@\" >> {}\necho $$ >> {}\nsleep 300",
                argv_log.display(),
                pid_log.display()
            ),
        );
        Self {
            path,
            argv_log,
            pid_log,
        }
    }

    /// Block until the stub has recorded its argv, then return it.
    ///
    /// Non-empty is the condition, not mere existence: `sh`'s `>` redirect
    /// creates the file before `echo` writes into it, so an existence-only
    /// wait can still read `""` — which would make
    /// [`spawns_projectless_when_the_tui_is_projectless`]'s
    /// `!argv.contains("--project")` assertion pass vacuously.
    async fn argv(&self) -> String {
        wait_for_record(&self.argv_log, "argv").await
    }

    /// Block until the stub has recorded its pid, then return it.
    async fn pid(&self) -> u32 {
        wait_for_record(&self.pid_log, "pid")
            .await
            .trim()
            .parse::<u32>()
            .expect("the stub records its pid as a bare integer")
    }
}

impl Drop for SleepingStub {
    /// Reap the `sleep 300` child, panic or no panic.
    ///
    /// Why: `ensure_daemon_with` deliberately never signals a daemon it
    /// spawned, so nothing else will. A panicking assertion used to strand
    /// one five-minute sleeper per failed test, and a flake investigation
    /// re-runs the suite ~10× — the strays pile up. Best-effort by design: a
    /// test whose stub was never spawned leaves no pid file. Every recorded pid
    /// is reaped, since a #4600 race case spawns the stub twice.
    fn drop(&mut self) {
        if let Ok(raw) = std::fs::read_to_string(&self.pid_log) {
            raw.lines()
                .filter_map(|line| line.trim().parse::<u32>().ok())
                .for_each(kill);
        }
    }
}

/// Poll `path` until it holds a non-empty record, then return it.
///
/// The budget is 2s (200 × 10ms): long enough to absorb a `fork`/`exec`
/// delayed by a saturated machine, short enough that a stub which genuinely
/// never ran fails the test rather than hanging it.
async fn wait_for_record(path: &Path, label: &str) -> String {
    for _ in 0..200 {
        if let Ok(raw) = std::fs::read_to_string(path)
            && !raw.trim().is_empty()
        {
            return raw;
        }
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
    panic!("the spawned stub never recorded its {label} at {path:?}");
}

/// Bind the stub daemon socket only once `stub` has ACTUALLY been spawned.
///
/// Why (#5073): every spawn test needs the socket UNBOUND when
/// [`ensure_daemon_with`] is entered. A socket already answering sends the call
/// down the attach branch, which never executes the stub at all — and the argv
/// wait afterwards then fails with "the spawned stub never recorded its argv",
/// which is exactly the flake reported. These tests used to arrange the
/// ordering with a 150 ms wall-clock delay, and that is a race against the
/// test's OWN setup: writing the `sh` stub, `chmod`-ing it and entering
/// `ensure_daemon_with` can outlast 150 ms on a machine that is also compiling,
/// at which point the socket is live before the call starts and the attach
/// branch wins. No shared file and no clobbered temp dir — one wall clock
/// standing in for an ordering.
/// What: waits for the stub's own argv record, which can only exist AFTER the
/// spawn, and binds the socket only then. The ordering is causal, so no amount
/// of load can invert it.
/// Test: `a_stalled_setup_still_reaches_the_spawn_branch`, plus the three spawn
/// tests that depend on it.
fn bind_socket_after_spawn(stub: &SleepingStub, dir: &Path, binding: serde_json::Value) {
    bind_at_after_spawn(stub, dir.join("tcode.sock"), binding);
}

/// [`bind_socket_after_spawn`] at an exact socket path (#4600).
fn bind_at_after_spawn(stub: &SleepingStub, socket: PathBuf, binding: serde_json::Value) {
    bind_once_argv_has(&stub.argv_log, "", socket, Some(binding));
}

/// Bind `socket` once the stub's `argv_log` contains `needle` — `""` for the
/// first spawn, `"--project-socket"` for a #4600 second spawn. `binding:
/// None` binds a daemon that reports no project. Gives up silently after 2s,
/// so a case that correctly spawns nothing leaves no stray panic behind.
fn bind_once_argv_has(
    argv_log: &Path,
    needle: &'static str,
    socket: PathBuf,
    binding: Option<serde_json::Value>,
) {
    let argv_log = argv_log.to_path_buf();
    tokio::spawn(async move {
        for _ in 0..200 {
            if std::fs::read_to_string(&argv_log)
                .is_ok_and(|raw| !raw.trim().is_empty() && raw.contains(needle))
            {
                stub_daemon_at(&socket, binding);
                return;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    });
}

/// A daemon whose `health` fails: it accepts each connection and drops it, so
/// `socket_is_serving` sees it live but the `health` call reads EOF (#4600).
fn mute_daemon_at(socket: &Path) {
    let dir = socket.parent().expect("a socket path has a parent");
    std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
        .expect("harden the stub socket directory");
    let listener = UnixListener::bind(socket).expect("bind the mute socket");
    std::fs::set_permissions(socket, std::fs::Permissions::from_mode(0o600))
        .expect("harden the mute socket");
    tokio::spawn(async move { while listener.accept().await.is_ok() {} });
}

/// A stub that touches `marker` — used to PROVE a branch never spawned it.
fn marker_stub(dir: &Path, marker: &Path) -> PathBuf {
    stub_binary(
        dir,
        "tcode-marker",
        &format!("touch {}\nsleep 300", marker.display()),
    )
}

fn is_alive(pid: u32) -> bool {
    // SAFETY: signal 0 performs permission/existence checks only and never
    // delivers a signal; it has no memory-safety effects.
    unsafe { libc::kill(pid as libc::pid_t, 0) == 0 }
}

fn kill(pid: u32) {
    // SAFETY: `pid` names a stub process this test spawned; `kill` has no
    // memory-safety effects.
    unsafe {
        libc::kill(pid as libc::pid_t, libc::SIGKILL);
    }
}

/// A LIVE daemon bound to the SAME project must be attached to, never
/// re-spawned: the binary is never executed at all.
#[tokio::test]
async fn attaches_to_a_live_daemon_without_spawning() {
    let _lock = ENV_LOCK.lock().await;
    let _env = EnvGuard::isolated();
    let project = tempfile::tempdir().expect("project");
    let canonical = project.path().canonicalize().expect("canonicalize");
    let sock_dir = tempfile::tempdir().expect("socket dir");
    let socket = stub_daemon_socket(sock_dir.path(), Some(binding_json(Some(&canonical))));

    let dir = tempfile::tempdir().expect("tempdir");
    let marker = dir.path().join("spawned");
    let stub = marker_stub(dir.path(), &marker);

    let resolved = ensure_daemon_with(Some(&canonical), &stub, &socket)
        .await
        .expect("must attach to the live daemon");

    assert_eq!(resolved, socket);
    assert!(
        !marker.exists(),
        "must not have spawned anything: {marker:?}"
    );
}

/// A projectless TUI must attach to a projectless daemon — the other
/// agreeing pair.
#[tokio::test]
async fn attaches_to_a_projectless_daemon_when_projectless() {
    let _lock = ENV_LOCK.lock().await;
    let _env = EnvGuard::isolated();
    let sock_dir = tempfile::tempdir().expect("socket dir");
    let socket = stub_daemon_socket(sock_dir.path(), Some(binding_json(None)));

    let dir = tempfile::tempdir().expect("tempdir");
    let marker = dir.path().join("spawned");
    let stub = marker_stub(dir.path(), &marker);

    let resolved = ensure_daemon_with(None, &stub, &socket)
        .await
        .expect("a projectless TUI must attach to a projectless daemon");
    assert_eq!(resolved, socket);
    assert!(!marker.exists(), "must not have spawned anything");
}

/// This project's own socket beside the shared `socket` (#4600).
fn own_socket(socket: &Path, project: Option<&Path>) -> PathBuf {
    trusty_code::serve::uds::project_socket_path(socket, project)
}

/// **The #4600 regression.** A second project must get a daemon of its own
/// while another project's daemon holds the shared socket — never an attach
/// to the first project's daemon, and never a refusal that leaves the second
/// project unable to run.
///
/// Why: the shared socket used to be the only one, so project B's TUI could
/// only refuse A's daemon (#4512) and stop. Two cases: a bound client against
/// another project's daemon, and a projectless client against a bound one
/// (the owner's 2026-09-16 reproduction). Each also leaves a STALE socket file
/// at the own path, which must read as "nothing there", not as a reason to
/// fall back to the shared socket.
/// What: the stub binds the own socket only after it has been spawned, with
/// the client's binding; the call must return that socket, distinct from the
/// shared one, and the stub's argv must carry `--project-socket`.
/// Test: this test.
#[tokio::test]
async fn a_second_project_starts_its_own_daemon_beside_the_first() {
    let _lock = ENV_LOCK.lock().await;
    let _env = EnvGuard::isolated();
    let their_project = tempfile::tempdir().expect("their project");
    let our_project = tempfile::tempdir().expect("our project");
    let theirs = their_project.path().canonicalize().expect("canonicalize");
    let ours = our_project.path().canonicalize().expect("canonicalize");

    for wanted in [Some(ours.as_path()), None] {
        let sock_dir = tempfile::tempdir().expect("socket dir");
        let shared = stub_daemon_socket(sock_dir.path(), Some(binding_json(Some(&theirs))));
        let own = own_socket(&shared, wanted);
        drop(std::os::unix::net::UnixListener::bind(&own).expect("leave a stale own socket"));

        let dir = tempfile::tempdir().expect("tempdir");
        let stub = SleepingStub::new(dir.path());
        bind_at_after_spawn(&stub, own.clone(), binding_json(wanted));

        let resolved = ensure_daemon_with(wanted, &stub.path, &shared).await;
        assert!(
            matches!(&resolved, Ok(path) if *path == own && *path != shared),
            "project {wanted:?} must get its own daemon on {own:?}, not attach to or be \
             refused by the other project's daemon on {shared:?}: {resolved:?}"
        );
        let argv = stub.argv().await;
        assert!(
            argv.contains("--project-socket") && argv.contains("--port 0"),
            "the second project's daemon must bind its own socket and no fixed port: {argv}"
        );
        assert_eq!(
            argv.contains("--project "),
            wanted.is_some(),
            "--project must be forwarded exactly when the client has one: {argv}"
        );
    }
}

/// Same-project reuse holds on the own socket too (#4600): a TUI for a
/// project whose daemon already runs on its own socket attaches to it while
/// another project holds the shared socket, and starts nothing.
#[tokio::test]
async fn a_second_project_reuses_its_own_running_daemon() {
    let _lock = ENV_LOCK.lock().await;
    let _env = EnvGuard::isolated();
    let their_project = tempfile::tempdir().expect("their project");
    let our_project = tempfile::tempdir().expect("our project");
    let theirs = their_project.path().canonicalize().expect("canonicalize");
    let ours = our_project.path().canonicalize().expect("canonicalize");
    let sock_dir = tempfile::tempdir().expect("socket dir");
    let shared = stub_daemon_socket(sock_dir.path(), Some(binding_json(Some(&theirs))));
    let own = own_socket(&shared, Some(&ours));
    stub_daemon_at(&own, Some(binding_json(Some(&ours))));

    let dir = tempfile::tempdir().expect("tempdir");
    let marker = dir.path().join("spawned");
    let stub = marker_stub(dir.path(), &marker);

    let resolved = ensure_daemon_with(Some(&ours), &stub, &shared).await;
    assert!(
        matches!(&resolved, Ok(path) if *path == own),
        "must reuse this project's running daemon on {own:?}: {resolved:?}"
    );
    assert!(!marker.exists(), "must not have spawned anything");
}

/// The error path (#4600): this project's own socket answered by a daemon
/// serving ANOTHER project — a hash collision, or a daemon started by hand —
/// is refused with both projects named, and nothing is spawned. The shared
/// socket is free here, so falling through to it would also be wrong: a
/// competing daemon cannot take the own socket while that one holds it.
#[tokio::test]
async fn refuses_another_projects_daemon_on_this_projects_own_socket() {
    let _lock = ENV_LOCK.lock().await;
    let _env = EnvGuard::isolated();
    let their_project = tempfile::tempdir().expect("their project");
    let our_project = tempfile::tempdir().expect("our project");
    let theirs = their_project.path().canonicalize().expect("canonicalize");
    let ours = our_project.path().canonicalize().expect("canonicalize");
    let sock_dir = tempfile::tempdir().expect("socket dir");
    let shared = sock_dir.path().join("tcode.sock");
    let own = own_socket(&shared, Some(&ours));
    stub_daemon_at(&own, Some(binding_json(Some(&theirs))));

    let dir = tempfile::tempdir().expect("tempdir");
    let marker = dir.path().join("spawned");
    let stub = marker_stub(dir.path(), &marker);

    let err = ensure_daemon_with(Some(&ours), &stub, &shared)
        .await
        .expect_err("a daemon on another project must not be attached to");

    let rendered = format!("{err:#}");
    assert!(
        rendered.contains(&theirs.display().to_string()),
        "error must name the daemon's project: {rendered}"
    );
    assert!(
        rendered.contains(&ours.display().to_string()),
        "error must name the requested project: {rendered}"
    );
    assert!(
        !marker.exists(),
        "must not start a competing daemon on a socket already bound: {rendered}"
    );
}

/// A third project answering on our own socket after the spawn is refused,
/// naming both projects (#4600).
// #4600: covers the post-spawn identity check in `use_shared_socket`; without
// it the TUI would attach to whatever answers on its own socket.
#[tokio::test]
async fn refuses_a_third_projects_daemon_that_answers_on_our_socket_after_our_spawn() {
    let _lock = ENV_LOCK.lock().await;
    let _env = EnvGuard::isolated();
    let their_project = tempfile::tempdir().expect("their project");
    let our_project = tempfile::tempdir().expect("our project");
    let third_project = tempfile::tempdir().expect("third project");
    let theirs = their_project.path().canonicalize().expect("canonicalize");
    let ours = our_project.path().canonicalize().expect("canonicalize");
    let third = third_project.path().canonicalize().expect("canonicalize");
    let sock_dir = tempfile::tempdir().expect("socket dir");
    let shared = stub_daemon_socket(sock_dir.path(), Some(binding_json(Some(&theirs))));
    let own = own_socket(&shared, Some(&ours));

    let dir = tempfile::tempdir().expect("tempdir");
    let stub = SleepingStub::new(dir.path());
    bind_once_argv_has(
        &stub.argv_log,
        "--project-socket",
        own.clone(),
        Some(binding_json(Some(&third))),
    );

    let err = ensure_daemon_with(Some(&ours), &stub.path, &shared)
        .await
        .expect_err("a third project's daemon must not be attached to");

    let rendered = format!("{err:#}");
    assert!(
        rendered.contains(&third.display().to_string()),
        "error must name the project that answered on our socket: {rendered}"
    );
    assert!(
        rendered.contains(&ours.display().to_string()),
        "error must name the requested project: {rendered}"
    );
    let argv = stub.argv().await;
    assert!(
        argv.lines().count() == 1 && argv.contains("--project-socket"),
        "exactly one own-socket spawn must have happened: {argv}"
    );
}

/// Assert a #4600 refusal names `socket`, offers a retry, and never tells the
/// operator to stop a daemon (owner directive 2026-08-01).
fn assert_unverified_refusal(rendered: &str, socket: &Path) {
    assert!(
        rendered.contains(&socket.display().to_string()),
        "the refusal must name the daemon's socket {socket:?}: {rendered}"
    );
    assert!(
        rendered.contains("run `tcode tui` again"),
        "the refusal must carry an actionable remedy: {rendered}"
    );
    assert!(
        !rendered.to_lowercase().contains("stop"),
        "the refusal must never tell the operator to stop a daemon: {rendered}"
    );
}

/// **#4600: an unverifiable shared daemon is refused, never passed over.**
///
/// Why: a shared daemon that reports no project, or whose `health` fails, may
/// already serve this project, so starting this project's daemon beside it
/// could give one project two daemons. 207f12dfde started one anyway.
/// What: both unverifiable shapes on the shared socket, for a bound and a
/// projectless client. A daemon matching the client is staged to answer on
/// the own socket the moment anything is spawned, so a spawn turns the
/// refusal into an attach and fails the case.
/// Test: this test.
#[tokio::test]
async fn refuses_an_unverifiable_shared_daemon_without_spawning() {
    let _lock = ENV_LOCK.lock().await;
    let _env = EnvGuard::isolated();
    let project = tempfile::tempdir().expect("project");
    let ours = project.path().canonicalize().expect("canonicalize");

    for wanted in [Some(ours.as_path()), None] {
        for health_fails in [false, true] {
            let sock_dir = tempfile::tempdir().expect("socket dir");
            let shared = sock_dir.path().join("tcode.sock");
            if health_fails {
                mute_daemon_at(&shared);
            } else {
                stub_daemon_at(&shared, None);
            }
            let dir = tempfile::tempdir().expect("tempdir");
            let stub = SleepingStub::new(dir.path());
            bind_at_after_spawn(&stub, own_socket(&shared, wanted), binding_json(wanted));

            let resolved = ensure_daemon_with(wanted, &stub.path, &shared).await;
            let case = format!("wanted {wanted:?}, health fails: {health_fails}");
            let rendered = match &resolved {
                Err(e) => format!("{e:#}"),
                Ok(path) => panic!("{case}: must refuse, not attach to {path:?}"),
            };
            assert_unverified_refusal(&rendered, &shared);
            let argv = std::fs::read_to_string(&stub.argv_log).unwrap_or_default();
            assert!(argv.is_empty(), "{case}: nothing may be spawned: {argv}");
            assert!(
                !argv.contains("--project-socket"),
                "{case}: no daemon may start on the own socket: {argv}"
            );
        }
    }
}

/// **The #4600 cold-start race, lost to another project.**
///
/// Why: two TUIs can both find the shared socket free and both spawn. When
/// the other project's daemon answers first, our child is still starting, so
/// readiness alone would attach this TUI to the wrong project — and a bare
/// refusal would leave this project unable to run.
/// What: the stub stays alive and never binds. The other project answers on
/// the shared socket after the first spawn; our project answers on its own
/// socket only after a second spawn carrying `--project-socket`.
/// Test: this test.
#[tokio::test]
async fn a_cold_start_race_lost_to_another_project_starts_our_own_daemon() {
    let _lock = ENV_LOCK.lock().await;
    let _env = EnvGuard::isolated();
    let their_project = tempfile::tempdir().expect("their project");
    let our_project = tempfile::tempdir().expect("our project");
    let theirs = their_project.path().canonicalize().expect("canonicalize");
    let ours = our_project.path().canonicalize().expect("canonicalize");
    let sock_dir = tempfile::tempdir().expect("socket dir");
    let shared = sock_dir.path().join("tcode.sock");
    let own = own_socket(&shared, Some(&ours));

    let dir = tempfile::tempdir().expect("tempdir");
    let stub = SleepingStub::new(dir.path());
    let theirs_json = binding_json(Some(&theirs));
    bind_once_argv_has(&stub.argv_log, "", shared.clone(), Some(theirs_json));
    let ours_json = binding_json(Some(&ours));
    bind_once_argv_has(
        &stub.argv_log,
        "--project-socket",
        own.clone(),
        Some(ours_json),
    );

    let resolved = ensure_daemon_with(Some(&ours), &stub.path, &shared).await;
    assert!(
        matches!(&resolved, Ok(path) if *path == own),
        "after losing the shared socket to another project, this project must run \
         on its own socket {own:?}: {resolved:?}"
    );
    let argv = stub.argv().await;
    let spawns: Vec<&str> = argv.lines().collect();
    assert!(
        spawns.len() == 2
            && !spawns[0].contains("--project-socket")
            && spawns[1].contains("--project-socket"),
        "one shared spawn, then one own-socket spawn: {argv}"
    );
}

/// The #4600 cold-start race, lost to a daemon that reports no project: the
/// re-probe refuses it, exactly as a live one found before spawning is
/// refused, and starts no second daemon.
/// Test: this test.
#[tokio::test]
async fn a_cold_start_race_lost_to_an_unverifiable_daemon_is_refused() {
    let _lock = ENV_LOCK.lock().await;
    let _env = EnvGuard::isolated();
    let project = tempfile::tempdir().expect("project");
    let ours = project.path().canonicalize().expect("canonicalize");
    let sock_dir = tempfile::tempdir().expect("socket dir");
    let shared = sock_dir.path().join("tcode.sock");

    let dir = tempfile::tempdir().expect("tempdir");
    let stub = SleepingStub::new(dir.path());
    bind_once_argv_has(&stub.argv_log, "", shared.clone(), None);

    let err = ensure_daemon_with(Some(&ours), &stub.path, &shared)
        .await
        .expect_err("an unverifiable daemon must not be attached to");
    assert_unverified_refusal(&format!("{err:#}"), &shared);
    let argv = stub.argv().await;
    assert!(
        argv.lines().count() == 1 && !argv.contains("--project-socket"),
        "only the one shared spawn may happen: {argv}"
    );
}

/// The #4600 cold-start race, lost to a daemon of OUR project: our child dies
/// on the taken socket, and the re-probe attaches to the winner instead of
/// reporting the failed start.
/// What: the stub records its argv, waits for the socket file to appear, and
/// exits 1 — what a real daemon does when its singleton bind is refused.
/// Test: this test.
#[tokio::test]
async fn a_cold_start_race_lost_to_our_own_project_attaches() {
    let _lock = ENV_LOCK.lock().await;
    let _env = EnvGuard::isolated();
    let project = tempfile::tempdir().expect("project");
    let ours = project.path().canonicalize().expect("canonicalize");
    let sock_dir = tempfile::tempdir().expect("socket dir");
    let shared = sock_dir.path().join("tcode.sock");

    let dir = tempfile::tempdir().expect("tempdir");
    let argv_log = dir.path().join("argv");
    let stub = stub_binary(
        dir.path(),
        "tcode-loses",
        &format!(
            "echo \"$@\" >> {argv}\ni=0\nwhile [ ! -S {sock} ] && [ $i -lt 500 ]; do \
             sleep 0.01; i=$((i+1)); done\nexit 1",
            argv = argv_log.display(),
            sock = shared.display(),
        ),
    );
    bind_once_argv_has(
        &argv_log,
        "",
        shared.clone(),
        Some(binding_json(Some(&ours))),
    );

    let resolved = ensure_daemon_with(Some(&ours), &stub, &shared).await;
    assert!(
        matches!(&resolved, Ok(path) if *path == shared),
        "a race lost to this project's own daemon must attach to it: {resolved:?}"
    );
    let argv = std::fs::read_to_string(&argv_log).unwrap_or_default();
    assert!(
        argv.lines().count() == 1 && !argv.contains("--project-socket"),
        "no second daemon may start for this project: {argv}"
    );
}

/// Projectless and bound are not interchangeable in EITHER direction — a
/// project-bound TUI must not silently lose its project to a projectless
/// daemon, and a projectless TUI must not silently inherit a project it
/// never named. Since #4600 the mismatch is only reachable on the client's
/// OWN socket; a mismatch on the shared one starts the client's own daemon.
#[tokio::test]
async fn refuses_a_project_bound_client_against_a_projectless_daemon() {
    let _lock = ENV_LOCK.lock().await;
    let _env = EnvGuard::isolated();
    let project = tempfile::tempdir().expect("project");
    let ours = project.path().canonicalize().expect("canonicalize");

    // Bound client, projectless daemon.
    {
        let sock_dir = tempfile::tempdir().expect("socket dir");
        let shared = sock_dir.path().join("tcode.sock");
        stub_daemon_at(&own_socket(&shared, Some(&ours)), Some(binding_json(None)));
        let dir = tempfile::tempdir().expect("tempdir");
        let marker = dir.path().join("spawned");
        let stub = marker_stub(dir.path(), &marker);
        let err = ensure_daemon_with(Some(&ours), &stub, &shared)
            .await
            .expect_err("a bound TUI must not attach to a projectless daemon");
        let rendered = format!("{err:#}");
        assert!(rendered.contains("<projectless>"), "{rendered}");
        assert!(!marker.exists(), "must not spawn a competing daemon");
    }

    // Projectless client, bound daemon.
    {
        let sock_dir = tempfile::tempdir().expect("socket dir");
        let shared = sock_dir.path().join("tcode.sock");
        stub_daemon_at(&own_socket(&shared, None), Some(binding_json(Some(&ours))));
        let dir = tempfile::tempdir().expect("tempdir");
        let marker = dir.path().join("spawned");
        let stub = marker_stub(dir.path(), &marker);
        let err = ensure_daemon_with(None, &stub, &shared)
            .await
            .expect_err("a projectless TUI must not inherit a daemon's project");
        let rendered = format!("{err:#}");
        assert!(rendered.contains(&ours.display().to_string()), "{rendered}");
        assert!(rendered.contains("<projectless>"), "{rendered}");
        assert!(!marker.exists(), "must not spawn a competing daemon");
    }
}

/// #8205: the refusal must name the FLAG that resolves it.
///
/// Why: a bare `tcode tui` in a repository now derives its own project, so an
/// operator who typed no flag at all can hit this refusal against a
/// projectless daemon — and "relaunch this TUI against <projectless>" is not
/// a command anyone can run. The message has to carry `--projectless` for one
/// mismatch class and `--project <root>` for the other.
/// What: a repo-derived `wanted` against a projectless daemon on its own
/// socket, then the inverse, asserting each error names its own flag.
/// Test: this test.
#[tokio::test]
async fn refusal_against_a_projectless_daemon_names_the_projectless_flag() {
    let _lock = ENV_LOCK.lock().await;
    let _env = EnvGuard::isolated();
    let project = tempfile::tempdir().expect("project");
    let ours = project.path().canonicalize().expect("canonicalize");

    {
        let sock_dir = tempfile::tempdir().expect("socket dir");
        let shared = sock_dir.path().join("tcode.sock");
        stub_daemon_at(&own_socket(&shared, Some(&ours)), Some(binding_json(None)));
        let dir = tempfile::tempdir().expect("tempdir");
        let marker = dir.path().join("spawned");
        let stub = marker_stub(dir.path(), &marker);
        let err = ensure_daemon_with(Some(&ours), &stub, &shared)
            .await
            .expect_err("a repo-homed TUI must not attach to a projectless daemon");
        let rendered = format!("{err:#}");
        assert!(
            rendered.contains("tcode tui --projectless"),
            "the refusal must name the flag that matches a projectless daemon: {rendered}"
        );
    }

    {
        let sock_dir = tempfile::tempdir().expect("socket dir");
        let shared = sock_dir.path().join("tcode.sock");
        stub_daemon_at(&own_socket(&shared, None), Some(binding_json(Some(&ours))));
        let dir = tempfile::tempdir().expect("tempdir");
        let marker = dir.path().join("spawned");
        let stub = marker_stub(dir.path(), &marker);
        let err = ensure_daemon_with(None, &stub, &shared)
            .await
            .expect_err("a projectless TUI must not inherit a daemon's project");
        let rendered = format!("{err:#}");
        assert!(
            rendered.contains(&format!("tcode tui --project {}", ours.display())),
            "the refusal must name the flag and the root: {rendered}"
        );
    }
}

/// A daemon too old to report its binding cannot be verified, so it is
/// refused — failing CLOSED, since "old build" is no evidence that its
/// project is the right one. Placed on the client's own socket (#4600); the
/// shared-socket case is `refuses_an_unverifiable_shared_daemon_without_spawning`.
#[tokio::test]
async fn refuses_a_daemon_that_cannot_report_its_binding() {
    let _lock = ENV_LOCK.lock().await;
    let _env = EnvGuard::isolated();
    let sock_dir = tempfile::tempdir().expect("socket dir");
    let shared = sock_dir.path().join("tcode.sock");
    stub_daemon_at(&own_socket(&shared, None), None);

    let dir = tempfile::tempdir().expect("tempdir");
    let marker = dir.path().join("spawned");
    let stub = marker_stub(dir.path(), &marker);

    let err = ensure_daemon_with(None, &stub, &shared)
        .await
        .expect_err("an unverifiable daemon must not be attached to");

    let rendered = format!("{err:#}");
    assert!(
        rendered.contains("does not report which project"),
        "error must say the binding could not be confirmed: {rendered}"
    );
    assert!(!marker.exists(), "must not spawn a competing daemon");
}

/// `ReportedBinding` must read every shape `health` can answer with, and
/// never guess.
#[test]
fn reported_binding_parses_every_health_shape() {
    let project = tempfile::tempdir().expect("project");
    let canonical = project.path().canonicalize().expect("canonicalize");
    assert_eq!(
        ReportedBinding::from_health(&serde_json::json!({"binding": binding_json(None)})),
        ReportedBinding::Projectless
    );
    assert_eq!(
        ReportedBinding::from_health(
            &serde_json::json!({"binding": binding_json(Some(&canonical))})
        ),
        ReportedBinding::Bound(canonical)
    );
    assert_eq!(
        ReportedBinding::from_health(&serde_json::json!({"status": "ok"})),
        ReportedBinding::Unreported
    );
    assert_eq!(
        ReportedBinding::from_health(&serde_json::json!({"binding": "nonsense"})),
        ReportedBinding::Unreported
    );
}

/// Each state has to name itself in a way an operator can act on.
#[test]
fn reported_binding_describes_each_state() {
    assert_eq!(ReportedBinding::Projectless.describe(), "<projectless>");
    assert_eq!(
        ReportedBinding::Bound(PathBuf::from("/tmp/x")).describe(),
        "/tmp/x"
    );
    assert!(
        ReportedBinding::Unreported
            .describe()
            .contains("unreported")
    );
}

/// No daemon at all: one must be SPAWNED and waited for, with `--project`
/// forwarded through so its binding matches the TUI's.
#[tokio::test]
async fn spawns_a_daemon_when_none_is_running() {
    let _lock = ENV_LOCK.lock().await;
    let _env = EnvGuard::isolated();
    let project = tempfile::tempdir().expect("project");
    let canonical = project.path().canonicalize().expect("canonicalize");

    let sock_dir = tempfile::tempdir().expect("socket dir");
    let socket = sock_dir.path().join("tcode.sock");

    let dir = tempfile::tempdir().expect("tempdir");
    let stub = SleepingStub::new(dir.path());
    // Bound only once the stub has RUN, so the attach branch cannot win and
    // the readiness wait is genuinely exercised (#5073).
    bind_socket_after_spawn(&stub, sock_dir.path(), binding_json(Some(&canonical)));

    let resolved = ensure_daemon_with(Some(&canonical), &stub.path, &socket)
        .await
        .expect("must spawn a daemon");
    assert_eq!(resolved, socket);

    // #6231: the stub is a real child, and readiness came from the socket
    // rather than from it — so its argv has to be waited for, not assumed.
    let argv = stub.argv().await;
    assert!(
        argv.contains("serve") && argv.contains("--http"),
        "must spawn `serve --http`: {argv}"
    );
    // #4600: no fixed port, and the shared socket when it is free.
    assert!(
        argv.contains("--port 0") && !argv.contains("--project-socket"),
        "must spawn on an OS-assigned port and the shared socket: {argv}"
    );
    assert!(
        argv.contains("--project") && argv.contains(canonical.to_str().expect("utf8")),
        "must forward --project to the daemon: {argv}"
    );
}

/// A PROJECTLESS TUI must spawn a projectless daemon — `--project` is
/// omitted entirely rather than defaulting to the launch directory.
#[tokio::test]
async fn spawns_projectless_when_the_tui_is_projectless() {
    let _lock = ENV_LOCK.lock().await;
    let _env = EnvGuard::isolated();

    let sock_dir = tempfile::tempdir().expect("socket dir");
    let socket = sock_dir.path().join("tcode.sock");

    let dir = tempfile::tempdir().expect("tempdir");
    let stub = SleepingStub::new(dir.path());
    bind_socket_after_spawn(&stub, sock_dir.path(), binding_json(None));

    ensure_daemon_with(None, &stub.path, &socket)
        .await
        .expect("must spawn a daemon");

    // #5073: an existence-only wait would be worse than the race — an empty
    // argv passes the negative assertion below for the wrong reason.
    let argv = stub.argv().await;
    assert!(
        !argv.contains("--project"),
        "a projectless TUI must not bind the daemon to a project: {argv}"
    );
}

/// **The #5073 regression.** A setup slow enough to outlast the old 150 ms
/// wall-clock bind must still exercise the SPAWN branch.
///
/// Why: the flake was never in `ensure_daemon_with` — a live socket really
/// should be attached to. It was in the fixture: a socket bound on a timer
/// races the test's own setup, and on a loaded machine it wins, so the call
/// attaches, the stub never runs, and the argv wait dies with "the spawned
/// stub never recorded its argv". Stalling here for well past 150 ms makes
/// that losing order deterministic rather than load-dependent.
/// What: arranges the late bind, sleeps far longer than the retired timer, and
/// then requires the stub to have been executed.
#[tokio::test]
async fn a_stalled_setup_still_reaches_the_spawn_branch() {
    let _lock = ENV_LOCK.lock().await;
    let _env = EnvGuard::isolated();

    let sock_dir = tempfile::tempdir().expect("socket dir");
    let socket = sock_dir.path().join("tcode.sock");

    let dir = tempfile::tempdir().expect("tempdir");
    let stub = SleepingStub::new(dir.path());
    bind_socket_after_spawn(&stub, sock_dir.path(), binding_json(None));

    // A saturated machine stalls between fixture setup and the call itself.
    tokio::time::sleep(Duration::from_millis(600)).await;
    assert!(
        !socket_is_serving(&socket, Duration::from_millis(200)).await,
        "nothing may answer {socket:?} before the stub has been spawned — a \
         live socket here sends the call down the attach branch and the stub \
         is never executed"
    );

    ensure_daemon_with(None, &stub.path, &socket)
        .await
        .expect("must spawn a daemon");

    let argv = stub.argv().await;
    assert!(
        argv.contains("serve"),
        "the spawn branch must have run the stub: {argv}"
    );
}

/// **The readiness gate is the SOCKET, not `GET /health`.**
///
/// A daemon whose HTTP listener answers but whose socket is unbound is a
/// daemon `tcode tui` cannot drive at all — every client call goes over the
/// socket. This spawns a child that stays up, stands a healthy HTTP endpoint
/// beside it, and asserts the wait is still pending; binding the socket is
/// what completes it.
#[tokio::test]
async fn daemon_autospawn_waits_on_socket_not_http() {
    let _lock = ENV_LOCK.lock().await;
    let _env = EnvGuard::isolated();

    // A healthy HTTP daemon, which must not satisfy the gate.
    let http = wiremock::MockServer::start().await;
    wiremock::Mock::given(wiremock::matchers::method("GET"))
        .and(wiremock::matchers::path("/health"))
        .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(
            serde_json::json!({"server": "tcode", "status": "ok", "binding": binding_json(None)}),
        ))
        .mount(&http)
        .await;

    let sock_dir = tempfile::tempdir().expect("socket dir");
    let socket = sock_dir.path().join("tcode.sock");
    let dir = tempfile::tempdir().expect("tempdir");
    let stub = SleepingStub::new(dir.path());

    let spawn_socket = socket.clone();
    let spawn_stub = stub.path.clone();
    let waiting =
        tokio::spawn(async move { ensure_daemon_with(None, &spawn_stub, &spawn_socket).await });

    // The child is up and HTTP is healthy; readiness must NOT be reached.
    tokio::time::sleep(Duration::from_millis(1200)).await;
    assert!(
        !waiting.is_finished(),
        "a healthy HTTP listener must not satisfy the socket readiness gate"
    );

    // Binding the socket is what completes it.
    stub_daemon_socket(sock_dir.path(), Some(binding_json(None)));
    let resolved = tokio::time::timeout(Duration::from_secs(10), waiting)
        .await
        .expect("the wait must complete once the socket answers")
        .expect("the wait task must not panic")
        .expect("readiness must be reported");
    assert_eq!(resolved, socket);
}

/// **The rule this module exists to guarantee.** The TUI NEVER signals the
/// daemon on exit, regardless of which process started it (owner directive,
/// 2026-08-01): the daemon owns PM lifecycle and agent dispatch, so a client
/// quitting must not destroy live work.
///
/// Both cases are asserted against real processes, after everything
/// `ensure_daemon_with` returned has been dropped — the drop is the moment a
/// `kill_on_drop` handle or a teardown step would have fired:
///
/// 1. a daemon THIS call spawned, and
/// 2. a pre-existing daemon it merely attached to.
#[tokio::test]
async fn the_tui_never_signals_the_daemon_on_exit() {
    let _lock = ENV_LOCK.lock().await;

    // 1. A daemon we spawned ourselves. The stub lives at FUNCTION scope on
    // purpose: its `Drop` reaps the child, and reaping it inside the block
    // below would kill the very process the `is_alive` assertion is about.
    let dir = tempfile::tempdir().expect("tempdir");
    let stub = SleepingStub::new(dir.path());
    let sock_dir = tempfile::tempdir().expect("socket dir");
    let our_pid = {
        let _env = EnvGuard::isolated();
        let socket = sock_dir.path().join("tcode.sock");
        bind_socket_after_spawn(&stub, sock_dir.path(), binding_json(None));
        let resolved = ensure_daemon_with(None, &stub.path, &socket)
            .await
            .expect("must spawn a daemon");
        assert_eq!(resolved, socket);
        stub.pid().await
        // Everything `ensure_daemon_with` produced is dropped here.
    };
    assert!(
        is_alive(our_pid),
        "a daemon the TUI spawned must OUTLIVE it (pid {our_pid} was killed)"
    );

    // 2. Somebody else's daemon, started outside `ensure_daemon_with`.
    let _env = EnvGuard::isolated();
    let foreign_sock_dir = tempfile::tempdir().expect("socket dir");
    let foreign_socket = stub_daemon_socket(foreign_sock_dir.path(), Some(binding_json(None)));
    let foreign_dir = tempfile::tempdir().expect("tempdir");
    let foreign_stub = SleepingStub::new(foreign_dir.path());
    let mut foreign = tokio::process::Command::new(&foreign_stub.path)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .expect("spawn foreign daemon");
    let foreign_pid = foreign.id().expect("foreign pid");

    ensure_daemon_with(None, &foreign_stub.path, &foreign_socket)
        .await
        .expect("must attach");

    assert!(
        is_alive(foreign_pid),
        "a pre-existing daemon must survive the TUI too (pid {foreign_pid})"
    );
    foreign.kill().await.expect("clean up foreign daemon");
}

/// A spawned daemon that dies immediately (the socket-already-bound case)
/// must be reported straight away, not spun out to the startup timeout.
#[tokio::test]
async fn reports_a_daemon_that_dies_on_startup() {
    let _lock = ENV_LOCK.lock().await;
    let _env = EnvGuard::isolated();

    let dir = tempfile::tempdir().expect("tempdir");
    let stub = stub_binary(dir.path(), "tcode-dies", "exit 3");
    let sock_dir = tempfile::tempdir().expect("socket dir");
    // Nothing is bound here, so readiness can only ever come from the child
    // — which exits at once.
    let socket = sock_dir.path().join("tcode.sock");
    let started = std::time::Instant::now();
    let err = ensure_daemon_with(None, &stub, &socket)
        .await
        .expect_err("a daemon that exits must surface an error");

    assert!(
        started.elapsed() < STARTUP_TIMEOUT,
        "must fail fast rather than spin out the startup budget"
    );
    let rendered = format!("{err:#}");
    assert!(
        rendered.contains("exited during startup"),
        "error must name the early exit: {rendered}"
    );
}

/// Why (#8783): the daemon outlives the TUI, but a daemon left in the TUI's
/// session dies with it — closing the terminal SIGHUPs the foreground group.
/// What: spawns the command [`spawn_daemon`] builds around an `exec sleep`
/// stub and compares `getsid(child)` with the child's pid while it is alive.
/// Test: this test.
#[tokio::test]
async fn the_spawned_daemon_leads_its_own_session() {
    let dir = tempfile::tempdir().expect("tempdir");
    let stub = stub_binary(dir.path(), "tcode-session", "exec sleep 300");
    let mut child = spawn_daemon(&stub, None, false, None).expect("spawn the stub daemon");
    let pid = child.id().expect("a live child has a pid") as libc::pid_t;
    // SAFETY: `getsid` only reads the session of our own unreaped child.
    let sid = unsafe { libc::getsid(pid) };
    child.start_kill().expect("signal the stub daemon");
    child.wait().await.expect("reap the stub daemon");
    assert_eq!(
        sid, pid,
        "the daemon `tcode tui` starts must lead its own session (#8783)"
    );
}