trusty-code 0.8.1

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
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
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
//! 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::path::{Path, PathBuf};
use std::time::Duration;

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

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>) {
    // #8203: a stub stands in for a daemon of THIS build unless a case says
    // otherwise.
    stub_daemon_with_build(socket, binding, Some(trusty_code::build_info::GIT_HASH));
}

/// [`stub_daemon_at`] publishing `build` as its `health.build` — `None` for a
/// daemon that predates #8164 and reports none (#8203).
fn stub_daemon_with_build(
    socket: &Path,
    binding: Option<serde_json::Value>,
    build: Option<&'static str>,
) {
    stub_daemon_full(socket, binding, build, trusty_code::VERSION, false);
}

/// [`stub_daemon_with_build`] with the published `version` chosen, and with
/// `fail_health` answering `health` with a JSON-RPC error (#8203).
fn stub_daemon_full(
    socket: &Path,
    binding: Option<serde_json::Value>,
    build: Option<&'static str>,
    version: &'static str,
    fail_health: bool,
) {
    if socket.exists() {
        std::fs::remove_file(socket).expect("clear the stale stub socket");
    }
    // `connect_hardened` refuses anything but a 0700 dir and a 0600 socket.
    // #7215: the code under test names this path, so the stub binds it through
    // the production `bind_hardened` rather than `bind_hardened_stub`.
    let listener = trusty_common::uds::bind_hardened(socket).expect("bind 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,
                };
                if fail_health {
                    let body = format!(
                        "{}\n",
                        serde_json::json!({
                            "jsonrpc": "2.0",
                            "id": request["id"].clone(),
                            "error": {"code": -32603, "message": "health is broken"},
                        })
                    );
                    let _ = reader.get_mut().write_all(body.as_bytes()).await;
                    let _ = reader.get_mut().flush().await;
                    return;
                }
                let mut result = serde_json::json!({
                    "server": "tcode", "status": "ok", "pid": 4242, "version": version,
                });
                if let Some(build) = build {
                    result["build"] = serde_json::json!(build);
                }
                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"));
    write_stub(&staging, body);
    let script = dir.join(name);
    std::fs::rename(&staging, &script).expect("move the stub into place");
    script
}

/// Write `#!/bin/sh\n<body>\n` to `staging` from a reaped child (#6231).
fn write_stub(staging: &Path, body: &str) {
    // See #10248
    trusty_common::exec_stub::write_executable(staging, format!("#!/bin/sh\n{body}\n"))
        .unwrap_or_else(|e| panic!("stub writer failed for {staging:?}: {e}"));
}

/// The per-user root that [`stable_stub`] keys its stubs under.
fn stable_stub_root() -> PathBuf {
    // SAFETY: `getuid` takes no arguments and cannot fail.
    let uid = unsafe { libc::getuid() };
    std::env::temp_dir().join(format!("trusty-test-stubs-{uid}"))
}

/// Return an executable `sh` stub for a FIXED `body`, written once per machine.
///
/// Why (#10212): macOS syspolicyd scans every new executable file on its
/// first launch, and a fresh stub per test is one more scan per test. A body
/// that names no per-test path is the same file for every test and every run.
/// What: the path is `<temp>/trusty-test-stubs-<uid>/<sha256(name, body)>/<name>`.
/// An existing file there is reused untouched. Otherwise [`write_stub`] fills
/// a staging name unique to this process and call, and a `rename` publishes it.
/// Two racing writers each rename a complete file of the same content, so the
/// path only ever names a closed executable (#6231). On EVERY call, reuse
/// included, the root, the key dir and the stub must be this user's, no
/// symlink, and not group- or world-writable, and the stub must hold exactly
/// this body; anything else panics (#10212: on Linux the root sits in the
/// shared `/tmp`, so another user could plant it). A body with a per-test path
/// must use [`stub_binary`] instead, or this root grows by one file per test.
/// Test: `a_stable_stub_is_written_once_and_reused`,
/// `racing_stable_stub_writers_both_get_an_executable`,
/// `a_planted_stable_stub_is_refused_not_reused`.
fn stable_stub(name: &str, body: &str) -> PathBuf {
    use std::os::unix::fs::DirBuilderExt;
    use std::sync::atomic::{AtomicU64, Ordering};
    static SEQ: AtomicU64 = AtomicU64::new(0);

    let script = stable_stub_path(name, body);
    let dir = script.parent().expect("stub dir").to_path_buf();
    std::fs::DirBuilder::new()
        .recursive(true)
        .mode(0o700)
        .create(&dir)
        .expect("create the stable stub dir");
    assert_private(&stable_stub_root());
    assert_private(&dir);
    if std::fs::symlink_metadata(&script).is_err() {
        let seq = SEQ.fetch_add(1, Ordering::Relaxed);
        let staging = dir.join(format!(".{name}.{}.{seq}.tmp", std::process::id()));
        write_stub(&staging, body);
        std::fs::rename(&staging, &script).expect("publish the stable stub");
    }
    assert_private(&script);
    let text = std::fs::read_to_string(&script).expect("read the stable stub");
    assert_eq!(
        text,
        format!("#!/bin/sh\n{body}\n"),
        "{script:?} does not hold the stub body; refusing to run it"
    );
    script
}

/// Where [`stable_stub`] keeps `name` with `body`.
fn stable_stub_path(name: &str, body: &str) -> PathBuf {
    use sha2::{Digest, Sha256};
    let digest = Sha256::new()
        .chain_update(name)
        .chain_update([0u8])
        .chain_update(body)
        .finalize();
    let key: String = digest[..12].iter().map(|b| format!("{b:02x}")).collect();
    stable_stub_root().join(key).join(name)
}

/// Panic unless `path` is this user's, not a symlink, and not group- or
/// world-writable (#10212).
fn assert_private(path: &Path) {
    use std::os::unix::fs::MetadataExt;
    let meta = std::fs::symlink_metadata(path).expect("stat a stable stub path");
    // SAFETY: `getuid` takes no arguments and cannot fail.
    let uid = unsafe { libc::getuid() };
    assert!(!meta.file_type().is_symlink(), "{path:?} is a symlink");
    assert_eq!(meta.uid(), uid, "{path:?} belongs to another user");
    assert_eq!(
        meta.mode() & 0o022,
        0,
        "{path:?} is group- or world-writable"
    );
}

/// 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) {
    // #7215: hardened by the production bind, as `stub_daemon_full` is.
    let listener = trusty_common::uds::bind_hardened(socket).expect("bind 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.
///
/// Why (#10212): a body naming the per-test marker made a new executable file
/// per test. What: one [`stable_stub`] that touches `spawned` beside the path
/// it was run as (`${0%/*}`), reached through a per-test symlink in `dir`, so
/// `marker` must be `dir/spawned`.
/// Test: `a_linked_marker_stub_marks_its_own_dir`.
fn marker_stub(dir: &Path, marker: &Path) -> PathBuf {
    assert_eq!(
        marker,
        dir.join("spawned"),
        "the marker sits beside the link"
    );
    let script = stable_stub("tcode-marker", "touch \"${0%/*}/spawned\"\nsleep 300");
    let link = dir.join("tcode-marker");
    std::os::unix::fs::symlink(&script, &link).expect("link the marker stub");
    link
}

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");
}

/// #8203: a live daemon from a DIFFERENT build — or one that reports no
/// build at all — is refused with both builds and the restart command, never
/// attached to.
///
/// Why: a daemon keeps running the code it started with. After a reinstall,
/// `tcode tui` attached to the old daemon and reproduced a fixed defect for
/// six hours with nothing on screen naming the mismatch.
/// What: a stub on the shared socket serving the same project, publishing a
/// foreign build and then no build; each call must fail, the error must name
/// both builds, the daemon's pid and the restart steps, and nothing may be
/// spawned. FAILS at c69c8e01be: the call attaches.
/// Test: this test.
#[tokio::test]
async fn refuses_a_daemon_from_a_different_build() {
    let _lock = ENV_LOCK.lock().await;
    let _env = EnvGuard::isolated();
    let project = tempfile::tempdir().expect("project");
    let canonical = project.path().canonicalize().expect("canonicalize");

    for (build, label) in [
        (Some("0123abc-stale"), "0123abc-stale"),
        (None, "<unreported>"),
    ] {
        let sock_dir = tempfile::tempdir().expect("socket dir");
        let socket = sock_dir.path().join("tcode.sock");
        stub_daemon_with_build(&socket, Some(binding_json(Some(&canonical))), build);

        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(&canonical), &stub, &socket)
            .await
            .expect_err("a daemon from another build must be refused")
            .to_string();
        for needle in [
            label,
            trusty_code::build_info::GIT_HASH,
            "4242",
            "tcode tui",
        ] {
            assert!(err.contains(needle), "refusal must name {needle:?}: {err}");
        }
        assert!(!marker.exists(), "a refusal must not spawn anything");
    }
}

/// **The "unknown" build hole.** `build.rs` falls back to `"unknown"` without
/// git, so two different releases can both report it. The versions must be
/// compared too: a daemon of the same build string but another version is
/// refused, naming both versions, and nothing is spawned.
/// FAILS at 97038f5a23: the equal builds attach.
/// Test: this test.
#[tokio::test]
async fn refuses_a_different_version_when_the_builds_match() {
    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");
    stub_daemon_full(
        &socket,
        Some(binding_json(Some(&canonical))),
        Some(trusty_code::build_info::GIT_HASH),
        "0.0.1-stale",
        false,
    );
    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(&canonical), &stub, &socket)
        .await
        .expect_err("a daemon of another version must be refused")
        .to_string();
    for needle in ["0.0.1-stale", trusty_code::VERSION, "4242"] {
        assert!(err.contains(needle), "refusal must name {needle:?}: {err}");
    }
    assert!(!marker.exists(), "a refusal must not spawn anything");
}

/// A `health` call that fails at the build check is its own message, not
/// "build <unreported>". `ensure_daemon_with` reads the binding first, so this
/// drives `check_build` directly.
/// FAILS at 97038f5a23: the error says the daemon runs build `<unreported>`.
/// Test: this test.
#[tokio::test]
async fn a_failed_health_call_is_not_reported_as_an_unreported_build() {
    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");
    stub_daemon_full(
        &socket,
        None,
        Some(trusty_code::build_info::GIT_HASH),
        trusty_code::VERSION,
        true,
    );

    let err = check_build(&socket)
        .await
        .expect_err("a daemon that cannot answer health is refused")
        .to_string();
    assert!(err.contains("`health` call failed"), "wrong message: {err}");
    assert!(!err.contains("<unreported>"), "wrong message: {err}");
}

/// 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")
                && !argv.contains("--http"),
            "the second project's daemon must bind its own socket and no TCP 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"), "must spawn `serve`: {argv}");
    // #6637: no TCP listener of any kind, and the shared socket when it is free.
    assert!(
        !argv.contains("--http") && !argv.contains("--port") && !argv.contains("--project-socket"),
        "must spawn the socket-only daemon on 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 stub = stable_stub("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 stub = stable_stub("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)"
    );
}

/// A body no earlier run wrote, so the first [`stable_stub`] call must create
/// it; the caller removes its directory afterwards.
fn fresh_body(tag: &str) -> String {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .expect("clock after the epoch")
        .as_nanos();
    format!("# {tag} {} {nanos}\nexit 0", std::process::id())
}

/// Why (#10212): a stable stub is only a saving if a second call reuses the
/// first call's file instead of writing a new one.
/// What: two calls with one fixed body return one path, and the inode and
/// mtime are unchanged by the second call. A helper that wrote a fresh file
/// per call would publish a new inode by `rename`. The body is fixed, so after
/// the first run on a machine this test creates no file at all.
/// Test: this test.
#[test]
fn a_stable_stub_is_written_once_and_reused() {
    use std::os::unix::fs::MetadataExt;
    let first = stable_stub("tcode-stable", "exit 0");
    let before = std::fs::metadata(&first).expect("stat the first stub");
    let second = stable_stub("tcode-stable", "exit 0");
    let after = std::fs::metadata(&second).expect("stat the second stub");
    assert_eq!(first, second, "one body must map to one path");
    assert!(first.starts_with(stable_stub_root()), "{first:?}");
    assert_eq!(
        before.ino(),
        after.ino(),
        "the second call rewrote the stub"
    );
    assert_eq!(
        before.modified().expect("mtime"),
        after.modified().expect("mtime"),
        "the second call touched the stub"
    );
}

/// Why (#10212): parallel tests share one stable stub, so two first callers
/// can write the same body at once.
/// What: per round, two threads released by a barrier call [`stable_stub`]
/// with a body no run has written. Both must get the same path, holding the
/// whole script with every execute bit set, and no staging file may remain.
/// Round 0 also runs the stub to exit 0; the other rounds do not, since each
/// launch of a new file is one more macOS first-launch scan.
/// Test: this test.
#[test]
fn racing_stable_stub_writers_both_get_an_executable() {
    use std::os::unix::fs::PermissionsExt;
    for round in 0..3 {
        let body = fresh_body(&format!("race-{round}"));
        let barrier = std::sync::Barrier::new(2);
        let paths: Vec<PathBuf> = std::thread::scope(|scope| {
            let handles: Vec<_> = (0..2)
                .map(|_| {
                    scope.spawn(|| {
                        barrier.wait();
                        stable_stub("tcode-race", &body)
                    })
                })
                .collect();
            handles
                .into_iter()
                .map(|h| h.join().expect("writer thread"))
                .collect()
        });
        let dir = paths[0].parent().expect("stub dir").to_path_buf();
        let seen: Vec<_> = paths
            .iter()
            .map(|path| {
                let mode = std::fs::metadata(path).expect("stat").permissions().mode();
                (mode, std::fs::read_to_string(path).expect("read the stub"))
            })
            .collect();
        let ran = (round == 0).then(|| {
            std::process::Command::new(&paths[0])
                .status()
                .expect("run the stub")
        });
        let leftovers = std::fs::read_dir(&dir).expect("list stub dir").count();
        let _ = std::fs::remove_dir_all(&dir);
        assert_eq!(paths[0], paths[1], "round {round}: one body, one path");
        for (mode, text) in seen {
            assert_eq!(mode & 0o111, 0o111, "round {round}: not executable");
            assert_eq!(text, format!("#!/bin/sh\n{body}\n"), "round {round}");
        }
        if let Some(status) = ran {
            assert!(status.success(), "round {round}: stub failed: {status}");
        }
        assert_eq!(leftovers, 1, "round {round}: a staging file was left");
    }
}

/// Why (#10212): the stable path is predictable, so a file already there may
/// not be this suite's stub; reusing it would run someone else's script.
/// What: plants a file at the hashed path, once with another body and once
/// with the right body but world-writable, and requires [`stable_stub`] to
/// panic rather than return it. Another uid cannot be faked here; the owner
/// check shares the code path.
/// Test: this test.
#[test]
fn a_planted_stable_stub_is_refused_not_reused() {
    use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
    for (case, wrong_body, mode) in [("body", true, 0o755), ("mode", false, 0o777)] {
        let body = fresh_body(&format!("planted-{case}"));
        let script = stable_stub_path("tcode-planted", &body);
        let dir = script.parent().expect("stub dir").to_path_buf();
        std::fs::DirBuilder::new()
            .recursive(true)
            .mode(0o700)
            .create(&dir)
            .expect("create the planted dir");
        let planted = if wrong_body { "exit 7" } else { body.as_str() };
        std::fs::write(&script, format!("#!/bin/sh\n{planted}\n")).expect("plant");
        std::fs::set_permissions(&script, std::fs::Permissions::from_mode(mode))
            .expect("chmod the planted stub");
        let reused = std::panic::catch_unwind(|| stable_stub("tcode-planted", &body));
        let _ = std::fs::remove_dir_all(&dir);
        assert!(reused.is_err(), "{case}: a planted stub was reused");
    }
}

/// Why (#10212): every "never spawned" case asserts `!marker.exists()`, which
/// passes vacuously if a run stub would mark some other directory.
/// What: spawns the linked [`marker_stub`] through [`spawn_daemon`], the
/// production spawn, and requires `dir/spawned` to appear.
/// Test: this test.
#[tokio::test]
async fn a_linked_marker_stub_marks_its_own_dir() {
    let dir = tempfile::tempdir().expect("tempdir");
    let marker = dir.path().join("spawned");
    let stub = marker_stub(dir.path(), &marker);
    let mut child = spawn_daemon(&stub, None, false, None).expect("spawn the marker stub");
    let mut seen = false;
    for _ in 0..200 {
        if marker.exists() {
            seen = true;
            break;
        }
        tokio::time::sleep(Duration::from_millis(10)).await;
    }
    child.start_kill().expect("signal the marker stub");
    child.wait().await.expect("reap the marker stub");
    assert!(seen, "a run marker stub must touch {marker:?}");
}