trusty-mpm 1.8.2

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

use crate::core::hook::HookEvent;
use crate::core::hook::HookEventRecord;
use crate::core::memory::MemoryPressure;
use crate::core::memory::MemoryUsage;
use crate::core::overseer_config::OverseerConfig;
use crate::core::paths::FrameworkPaths;
use crate::core::session::{ControlModel, SessionStatus};

use super::core::{DaemonState, HOOK_HISTORY_LIMIT, ReapResult};
use super::overseer::build_overseer;

use crate::core::session::{Session, SessionId};

/// Build a [`DaemonState`] rooted under an empty temp directory.
///
/// Why: tests that assert overseer/LLM config defaults must NOT read from the
/// real `~/.trusty-mpm/framework/hooks/` — on a dev machine the operator's
/// `overseer.toml` may have `[llm] enabled = true` with a live API key, which
/// would make "disabled by default" assertions fail (#1571). Pointing
/// [`DaemonState::with_paths`] at a freshly-created, empty temp directory
/// guarantees that `overseer.toml` and `optimizer.toml` are absent, so the
/// daemon falls back to its disabled/default policy regardless of the host
/// environment. The `TempDir` is returned so the caller can hold it alive for
/// the test's duration; the paths it contains are only consulted at
/// construction time, so the directory can be dropped afterwards without
/// affecting the in-memory state.
/// What: creates a `tempfile::TempDir`, builds `FrameworkPaths::under` it, and
/// calls `DaemonState::with_paths`, returning both.
/// Test: `new_overseer_is_disabled_when_file_missing`, `overseer_is_accessible`,
/// `llm_overseer_is_none_without_key`, `overseer_handler_reports_strategy`.
fn hermetic_state() -> (DaemonState, tempfile::TempDir) {
    let dir = tempfile::tempdir().expect("temp dir for hermetic DaemonState");
    let paths = FrameworkPaths::under(dir.path());
    let state = DaemonState::with_paths(&paths);
    (state, dir)
}

fn sample_session() -> Session {
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let n = COUNTER.fetch_add(1, Ordering::Relaxed);
    let mut s = Session::new(SessionId::new(), "/tmp/p", ControlModel::Tmux, None);
    s.tmux_name = format!("tmpm-test-{n}");
    s.status = SessionStatus::Active;
    s
}

#[test]
fn register_and_list_sessions() {
    let state = DaemonState::new();
    let s = sample_session();
    let id = s.id;
    state.register_session(s);
    assert_eq!(state.list_sessions().len(), 1);
    assert!(state.session(id).is_some());
    assert!(state.remove_session(id).is_some());
    assert!(state.list_sessions().is_empty());
}

#[test]
fn update_session_mutates_existing() {
    let state = DaemonState::new();
    let s = sample_session();
    let id = s.id;
    state.register_session(s);
    let ran = state.update_session(&id, |session| {
        session.status = SessionStatus::Paused;
        session.pause_summary = Some("note".to_string());
    });
    assert!(ran);
    let updated = state.session(id).expect("session exists");
    assert_eq!(updated.status, SessionStatus::Paused);
    assert_eq!(updated.pause_summary.as_deref(), Some("note"));
}

#[test]
fn update_session_missing_is_false() {
    let state = DaemonState::new();
    let ran = state.update_session(&SessionId::new(), |_| {});
    assert!(!ran);
}

#[test]
fn register_and_list_projects() {
    let state = DaemonState::new();
    assert!(state.list_projects().is_empty());
    let info = state.register_project(PathBuf::from("/work/demo"));
    assert_eq!(info.name, "demo");
    assert_eq!(state.list_projects().len(), 1);
    // Re-registering the same path replaces rather than duplicates.
    state.register_project(PathBuf::from("/work/demo"));
    assert_eq!(state.list_projects().len(), 1);
    state.register_project(PathBuf::from("/work/other"));
    assert_eq!(state.list_projects().len(), 2);
}

#[test]
fn project_lookup_by_path() {
    let state = DaemonState::new();
    state.register_project(PathBuf::from("/work/demo"));
    assert!(state.project(std::path::Path::new("/work/demo")).is_some());
    assert!(
        state
            .project(std::path::Path::new("/work/missing"))
            .is_none()
    );
}

#[test]
fn list_sessions_for_project_filters() {
    let state = DaemonState::new();
    let mut in_proj = sample_session();
    in_proj.project_path = Some(PathBuf::from("/work/demo"));
    let mut other_proj = sample_session();
    other_proj.project_path = Some(PathBuf::from("/work/other"));
    let no_proj = sample_session();
    state.register_session(in_proj.clone());
    state.register_session(other_proj);
    state.register_session(no_proj);

    let listed = state.list_sessions_for_project(std::path::Path::new("/work/demo"));
    assert_eq!(listed.len(), 1);
    assert_eq!(listed[0].id, in_proj.id);
}

#[test]
fn find_session_by_id_or_name() {
    let state = DaemonState::new();
    let s = sample_session();
    let id = s.id;
    let name = s.tmux_name.clone();
    state.register_session(s);

    assert!(state.find_session(&id.0.to_string()).is_some());
    assert!(state.find_session(&name).is_some());
    assert!(state.find_session("tmpm-no-such-name").is_none());
    assert!(
        state
            .find_session(&SessionId::new().0.to_string())
            .is_none()
    );
}

#[test]
fn breaker_tracks_outcomes() {
    let state = DaemonState::new();
    // Default threshold is 3 consecutive failures.
    for _ in 0..3 {
        state.record_outcome("research", false);
    }
    let cb = state.breaker("research");
    assert!(!cb.allows_delegation());
    // A success resets the counter (after an attempt_reset path it closes).
    state.record_outcome("research", true);
    assert_eq!(state.breaker("research").consecutive_failures, 0);
}

#[test]
fn memory_pressure_is_classified() {
    let state = DaemonState::new();
    let id = SessionId::new();
    let pressure = state.record_memory(
        id,
        MemoryUsage {
            used_tokens: 900,
            window_tokens: 1000,
        },
    );
    assert_eq!(pressure, MemoryPressure::Compact);
    assert!(state.memory_for(id).is_some());
}

#[test]
fn reap_dead_sessions() {
    // Three registered sessions; tmux reports only two of them alive.
    // `reap_against` (the testable core of `reap_dead_sessions`) must drop
    // exactly the one whose tmux_name is absent from the live set.
    let state = DaemonState::new();
    let alive_a = sample_session();
    let alive_b = sample_session();
    let dead = sample_session();
    let (id_a, id_b, id_dead) = (alive_a.id, alive_b.id, dead.id);
    state.register_session(alive_a.clone());
    state.register_session(alive_b.clone());
    state.register_session(dead);
    assert_eq!(state.list_sessions().len(), 3);

    let live: std::collections::HashSet<String> =
        [alive_a.tmux_name.clone(), alive_b.tmux_name.clone()]
            .into_iter()
            .collect();
    let result = state.reap_against(&live);

    assert_eq!(result.reaped, 1);
    assert_eq!(result.stopped, 0);
    assert!(state.session(id_a).is_some());
    assert!(state.session(id_b).is_some());
    assert!(state.session(id_dead).is_none());

    // Reaping again is idempotent — nothing left to remove.
    assert_eq!(state.reap_against(&live), ReapResult::default());
}

#[test]
fn reap_against_empty_live_removes_all_tmux_sessions() {
    // An empty live set (e.g. tmux server fully stopped) drops every
    // tmux-hosted entry.
    let state = DaemonState::new();
    state.register_session(sample_session());
    state.register_session(sample_session());
    let result = state.reap_against(&std::collections::HashSet::new());
    assert_eq!(result.reaped, 2);
    assert!(state.list_sessions().is_empty());
}

#[test]
fn reap_keeps_native_sessions() {
    // Native (Terminal.app) sessions have no tmux session; the tmux-based
    // reaper must never delete them, even against an empty live set.
    let state = DaemonState::new();
    let mut native = sample_session();
    native.origin = crate::core::session::SessionHost::Native;
    native.pid = Some(9999);
    let native_id = native.id;
    let tmux = sample_session();
    let tmux_id = tmux.id;
    state.register_session(native);
    state.register_session(tmux);

    let result = state.reap_against(&std::collections::HashSet::new());

    // Only the tmux-hosted session is reaped.
    assert_eq!(result.reaped, 1);
    assert!(state.session(native_id).is_some());
    assert!(state.session(tmux_id).is_none());
}

#[test]
fn set_session_pid_updates_field() {
    // Registering a session leaves `pid` unset; set_session_pid records it.
    // Use a hermetic state so the PID-file write lands under a temp dir, never
    // the operator's real `~/.trusty-mpm/pids`.
    let (state, _tmp) = hermetic_state();
    let s = sample_session();
    let id = s.id;
    state.register_session(s);
    assert_eq!(state.session(id).unwrap().pid, None);

    assert!(state.set_session_pid(id, 4242));
    assert_eq!(state.session(id).unwrap().pid, Some(4242));

    // An unknown id is reported as not updated.
    assert!(!state.set_session_pid(SessionId::new(), 1));
}

#[test]
fn pid_registry_is_under_framework_root() {
    // The PID registry must resolve to `<framework_root>/pids` so the spawn,
    // drop, and sweep paths all agree on one directory.
    let (state, _tmp) = hermetic_state();
    let expected = state.framework_root().join("pids");
    assert_eq!(state.pid_registry().dir(), expected.as_path());
}

#[test]
fn set_session_pid_writes_pidfile() {
    // Recording a PID must also write a `<uuid>.pid` file to the registry so a
    // future orphan-GC sweep can find this claude process even after the tmux
    // pane and in-memory entry are gone (§10.3).
    let (state, _tmp) = hermetic_state();
    let s = sample_session();
    let id = s.id;
    state.register_session(s);
    assert!(state.set_session_pid(id, 4242));

    let entries = state.pid_registry().entries().unwrap();
    assert_eq!(entries.len(), 1);
    assert_eq!(entries[0].session_id, id.0.to_string());
    assert_eq!(entries[0].pid, 4242);

    // Removing the session must clear its PID file (no orphan left behind).
    state.remove_session(id);
    assert!(state.pid_registry().entries().unwrap().is_empty());
}

#[tokio::test]
async fn gather_live_session_ids_unions_both() {
    // The live-id set the PID sweep uses must include every legacy DaemonState
    // session id (the SM store starts empty in a hermetic state, so the legacy
    // ids are what must be present).
    let (state, _tmp) = hermetic_state();
    let a = sample_session();
    let b = sample_session();
    let (id_a, id_b) = (a.id, b.id);
    state.register_session(a);
    state.register_session(b);

    let ids = state.gather_live_session_ids().await;
    assert!(ids.contains(&id_a.0.to_string()));
    assert!(ids.contains(&id_b.0.to_string()));
}

#[test]
fn reap_marks_stopped_when_pid_dead() {
    // A tmux session that is still alive but whose tracked `claude` process
    // has exited (u32::MAX is a guaranteed-dead PID) must be marked Stopped
    // — not removed — so the operator can still see it.
    let state = DaemonState::new();
    let mut session = sample_session();
    session.pid = Some(u32::MAX);
    let id = session.id;
    let tmux_name = session.tmux_name.clone();
    state.register_session(session);

    let live: std::collections::HashSet<String> = [tmux_name].into_iter().collect();
    let result = state.reap_against(&live);

    assert_eq!(result.reaped, 0);
    assert_eq!(result.stopped, 1);
    let after = state.session(id).expect("session is kept, not removed");
    assert_eq!(after.status, SessionStatus::Stopped);
}

/// A `Running` delegation belonging to `session`, standing in `cwd` with no
/// worktree of its own — the shape `live_shared_tree_writers` reports (#6497).
fn unisolated_running_delegation(
    session: crate::core::session::SessionId,
    cwd: &std::path::Path,
) -> crate::core::agent::Delegation {
    let mut d = crate::core::agent::Delegation::new(
        session,
        None,
        "rust-engineer",
        crate::core::agent::ModelTier::Sonnet,
        "finish the work",
    );
    d.status = crate::core::agent::DelegationStatus::Running;
    d.cwd = Some(cwd.to_path_buf());
    d.isolation = None;
    d
}

/// The #6497 regression. When the reaper buries a session, that session's agents
/// went down with it — their `SubagentStop` never arrives, so their records
/// stayed live for six hours and `live_shared_tree_writers` kept reporting them
/// as writing in the shared checkout, refusing a successor's serialized
/// dispatch.
#[test]
fn reap_stales_a_dead_sessions_delegations() {
    let state = DaemonState::new();
    let session = sample_session();
    let id = session.id;
    let cwd = std::path::PathBuf::from("/repo/main");
    state.register_session(session);
    state.upsert_delegation(unisolated_running_delegation(id, &cwd));

    assert_eq!(
        state.live_shared_tree_writers(&cwd, None).len(),
        1,
        "the record blocks a dispatch while its session is alive"
    );

    // The tmux session is gone from `list-sessions` — the reaper's positive
    // evidence of death.
    let result = state.reap_against(&std::collections::HashSet::new());
    assert_eq!(result.reaped, 1);

    assert!(
        state.live_shared_tree_writers(&cwd, None).is_empty(),
        "a dead session's records must stop blocking dispatch"
    );
    let after = state.all_delegations();
    assert_eq!(after.len(), 1, "the record is staled, never dropped");
    assert_eq!(
        after[0].status,
        crate::core::agent::DelegationStatus::Stale,
        "Stale records that tracking gave up, and stays resolvable by a late stop"
    );
    assert!(
        after[0].ended_at.is_none(),
        "staling must not stamp ended_at — that field means `reached a terminal status`"
    );
}

/// The control: a session the reaper leaves alone keeps every one of its
/// delegations live, so the ADR-0048 shared-checkout guard is untouched for
/// every session that is still running.
#[test]
fn reap_leaves_a_live_sessions_delegations_alone() {
    let state = DaemonState::new();
    let session = sample_session();
    let id = session.id;
    let tmux_name = session.tmux_name.clone();
    let cwd = std::path::PathBuf::from("/repo/main");
    state.register_session(session);
    state.upsert_delegation(unisolated_running_delegation(id, &cwd));

    let live: std::collections::HashSet<String> = [tmux_name].into_iter().collect();
    let result = state.reap_against(&live);

    assert_eq!(result.reaped, 0);
    assert_eq!(
        state.live_shared_tree_writers(&cwd, None).len(),
        1,
        "a live session's agent must still block a second writer in its checkout"
    );
}

/// The #6556 regression, second defect. A `rust-engineer` dispatched with
/// `isolation: "worktree"` and demonstrably running in
/// `.claude/worktrees/agent-…` was named by the ADR-0049 deny as "running there
/// with no worktree of its own", because the query read the DECLARED isolation
/// and that field was empty on the record. `worktree_path` is the agent's own
/// report of where it is, and it says otherwise.
///
/// Fails before the fix: the pre-#6556 filter consults `isolation` alone, so a
/// record with `isolation: None` and a recorded agent worktree is still
/// reported.
#[test]
fn a_recorded_worktree_outranks_a_missing_isolation_declaration() {
    let state = DaemonState::new();
    let session = sample_session();
    let id = session.id;
    let cwd = std::path::PathBuf::from("/repo/main");
    state.register_session(session);

    let mut d = unisolated_running_delegation(id, &cwd);
    // What the agent reported from its own hook cwd (#4311) — a tree that is
    // not the dispatcher's, and where its latest hook still runs.
    let tree = std::path::PathBuf::from("/repo/main/.claude/worktrees/agent-aa049179cd3e4e1bb");
    d.worktree_path = Some(tree.clone());
    d.last_agent_cwd = Some(tree);
    state.upsert_delegation(d);

    assert!(
        state.live_shared_tree_writers(&cwd, None).is_empty(),
        "an agent that reported a tree of its own is not writing in the shared checkout"
    );
}

/// The #6556 critic round, HIGH 2. `worktree_path` is a one-way latch, so an
/// agent that entered a worktree and came back out — `EnterWorktree`, then
/// `ExitWorktree` with `action: "keep"`, which restores the dispatcher's cwd —
/// was excluded from the shared-tree count for the rest of its life while
/// writing in the shared checkout the whole time.
///
/// Fails before this round: `holds_its_own_tree` reads `worktree_path` alone, so
/// the writer stays invisible after it leaves.
#[test]
fn an_agent_that_leaves_its_worktree_blocks_the_shared_tree_again() {
    let state = DaemonState::new();
    let session = sample_session();
    let id = session.id;
    let cwd = std::path::PathBuf::from("/repo/main");
    let tree = std::path::PathBuf::from("/repo/main/.claude/worktrees/agent-enterexit");
    state.register_session(session);

    // In its own tree: granted, and standing in it.
    let mut d = unisolated_running_delegation(id, &cwd);
    d.worktree_path = Some(tree.clone());
    d.last_agent_cwd = Some(tree.clone());
    let delegation_id = d.id;
    state.upsert_delegation(d);
    assert!(
        state.live_shared_tree_writers(&cwd, None).is_empty(),
        "while it is in its own tree it is not writing in the shared checkout"
    );

    // ExitWorktree with `action: "keep"`: the tree stays its own — the reap
    // needs that — but the agent is back in the dispatcher's checkout.
    state.mutate_delegation(delegation_id, |d| d.last_agent_cwd = Some(cwd.clone()));
    assert_eq!(
        state.live_shared_tree_writers(&cwd, None).len(),
        1,
        "once it walks back into the shared checkout it must block again"
    );
    assert_eq!(
        state
            .all_delegations()
            .into_iter()
            .next()
            .expect("one")
            .worktree_path,
        Some(tree),
        "and the ownership latch must survive, or the reap loses the tree's owner"
    );
}

/// The control for the rule above: `worktree_path` is `None` both when the agent
/// shares the dispatcher's tree AND before it has made its first tool call, so
/// absence must never be read as evidence of a separate tree. The isolation test
/// still decides, and an unisolated engineer still blocks.
#[test]
fn an_unrecorded_worktree_leaves_the_isolation_test_deciding() {
    let state = DaemonState::new();
    let session = sample_session();
    let id = session.id;
    let cwd = std::path::PathBuf::from("/repo/main");
    state.register_session(session);
    state.upsert_delegation(unisolated_running_delegation(id, &cwd));
    assert_eq!(
        state.live_shared_tree_writers(&cwd, None).len(),
        1,
        "no recorded worktree means undetermined, and the guard still blocks"
    );

    // A recorded path EQUAL to the dispatcher's cwd is the same agent in the
    // same tree — that is not evidence of separation either.
    let state = DaemonState::new();
    let session = sample_session();
    let id = session.id;
    state.register_session(session);
    let mut d = unisolated_running_delegation(id, &cwd);
    d.worktree_path = Some(cwd.clone());
    d.last_agent_cwd = Some(cwd.clone());
    state.upsert_delegation(d);
    assert_eq!(
        state.live_shared_tree_writers(&cwd, None).len(),
        1,
        "a recorded path equal to the dispatch cwd names the shared tree, not a separate one"
    );
}

/// The #6556 critic round, HIGH 1. `reconcile_by_agent_type` identifies a record
/// by KIND, so a stop belonging to an agent whose own dispatch was never
/// observed — dispatched while the daemon was unreachable — can stale a sibling
/// that is still writing. Releasing that tree for a documents-only commit is the
/// bargain #6556 makes; releasing it for a second FILE-MUTATING dispatch is the
/// ADR-0048 harm, and no later signal undoes two writers on one HEAD.
///
/// Fails before this round: `claim_shared_tree_dispatch` read
/// `live_shared_tree_writers`, which omits every `Stale` record, so the claim
/// was granted and a second engineer was admitted onto the live agent's HEAD.
#[test]
fn a_type_reconciled_record_still_occupies_the_tree_for_a_dispatch() {
    let state = DaemonState::new();
    let session = sample_session();
    let id = session.id;
    let cwd = std::path::PathBuf::from("/repo/main");
    state.register_session(session);

    let mut d = unisolated_running_delegation(id, &cwd);
    d.started_at = Some(chrono::Utc::now());
    // What `reconcile_by_agent_type` writes when a sibling's stop names this
    // record's agent type and nothing else could be it.
    d.status = crate::core::agent::DelegationStatus::Stale;
    d.stale_by_agent_type = true;
    state.upsert_delegation(d);

    assert!(
        state.live_shared_tree_writers(&cwd, None).is_empty(),
        "the ADR-0049 commit guard honours the reconciliation — that is the point of #6556"
    );
    assert_eq!(
        state.shared_tree_occupants(&cwd, None).len(),
        1,
        "but the tree is still occupied, because the identification was by type"
    );

    // And the claim the dispatch guard actually takes must be refused.
    let mut recorded = false;
    let (occupants, claimed) = state.claim_shared_tree_dispatch(
        &cwd,
        None,
        true,
        crate::daemon::state::sessions::SharedTreeQuestion::Dispatch,
        |_| recorded = true,
    );
    assert_eq!(occupants.len(), 1, "the deny must name the occupant");
    assert!(
        !claimed,
        "a second file-mutating dispatch must not be admitted"
    );
    assert!(
        !recorded,
        "and nothing may be recorded when the claim is refused"
    );
}

/// Occupancy is BOUNDED. Without a bound a type-reconciled record would hold the
/// tree for the whole 24 h `STALE_RETENTION_SECS` window — four times the budget
/// it would have had if nothing had reconciled it — so it ends exactly where the
/// staleness sweep would have ended it anyway.
#[test]
fn a_type_reconciled_record_stops_occupying_at_its_original_budget() {
    let state = DaemonState::new();
    let session = sample_session();
    let id = session.id;
    let cwd = std::path::PathBuf::from("/repo/main");
    state.register_session(session);

    let mut d = unisolated_running_delegation(id, &cwd);
    d.started_at = Some(
        chrono::Utc::now()
            - chrono::Duration::seconds(
                crate::daemon::state::sessions::RUNNING_STALE_AFTER_SECS + 60,
            ),
    );
    d.status = crate::core::agent::DelegationStatus::Stale;
    d.stale_by_agent_type = true;
    state.upsert_delegation(d);

    assert!(
        state.shared_tree_occupants(&cwd, None).is_empty(),
        "past its own liveness budget the record occupies nothing — the sweep would \
         have staled it by now regardless"
    );
}

/// A record staled by the sweep or by #6497's dead-session reaper must NOT
/// re-acquire occupancy. Those act on evidence about the record's OWN owner, and
/// #6497 released the tree deliberately so a successor session could take it.
#[test]
fn an_ordinarily_staled_record_occupies_nothing() {
    let state = DaemonState::new();
    let session = sample_session();
    let id = session.id;
    let cwd = std::path::PathBuf::from("/repo/main");
    state.register_session(session);

    let mut d = unisolated_running_delegation(id, &cwd);
    d.started_at = Some(chrono::Utc::now());
    d.status = crate::core::agent::DelegationStatus::Stale;
    // `stale_by_agent_type` deliberately left false.
    state.upsert_delegation(d);

    assert!(
        state.shared_tree_occupants(&cwd, None).is_empty(),
        "only a TYPE-reconciled stale keeps occupancy; #6497's reaper must still release"
    );
}

#[test]
fn new_reads_default_when_optimizer_file_missing() {
    // With no framework installed (the optimizer.toml file absent), the
    // daemon must still construct, falling back to the default policy.
    let state = DaemonState::new();
    assert_eq!(
        state.optimizer_config().default_level,
        crate::core::compress::CompressionLevel::Trim
    );
}

#[test]
fn reload_optimizer_config_picks_up_file_changes() {
    // Reloading from an explicit temp file must overwrite the in-memory
    // policy with whatever the file declares.
    use std::io::Write;
    let state = DaemonState::new();
    let dir = tempfile::tempdir().expect("temp dir");
    let path = dir.path().join("optimizer.toml");
    let mut file = std::fs::File::create(&path).expect("create file");
    writeln!(file, "[default]\nlevel = \"caveman\"").expect("write file");

    state
        .reload_optimizer_config_from(&path)
        .expect("reload succeeds");
    assert_eq!(
        state.optimizer_config().default_level,
        crate::core::compress::CompressionLevel::Caveman
    );

    // A missing file reloads to the default policy rather than erroring.
    state
        .reload_optimizer_config_from(&dir.path().join("absent.toml"))
        .expect("missing file is not an error");
    assert_eq!(
        state.optimizer_config().default_level,
        crate::core::compress::CompressionLevel::Trim
    );
}

#[test]
fn new_overseer_is_disabled_when_file_missing() {
    // With no framework installed (overseer.toml absent in a hermetic temp
    // dir), the overseer must be present but disabled — oversight is opt-in.
    // Uses `hermetic_state()` so the real `~/.trusty-mpm/overseer.toml` — if
    // present on a dev machine with an API key — cannot enable the LLM
    // overseer and make this assertion spuriously fail (#1571).
    let (state, _dir) = hermetic_state();
    assert!(!state.overseer().is_enabled());
}

#[test]
fn overseer_is_deterministic_without_llm() {
    // With the `[llm]` section absent/disabled, the overseer is the plain
    // deterministic strategy and (with no rules) reports disabled.
    let cfg = OverseerConfig::default();
    let build = build_overseer(cfg);
    assert!(!build.overseer.is_enabled());
    assert_eq!(build.handler, "deterministic");
    assert!(build.llm.is_none());
}

#[test]
fn overseer_falls_back_when_llm_key_missing() {
    // `[llm] enabled = true` but no API key resolves: the daemon must not
    // panic — it falls back to the deterministic overseer.
    let mut cfg = OverseerConfig::default();
    cfg.llm.enabled = true;
    cfg.llm.api_key_env = "TRUSTY_MPM_DEFINITELY_NOT_SET".to_string(); // pragma: allowlist secret
    let build = build_overseer(cfg);
    // Deterministic with no rules and disabled top-level flag → disabled.
    assert!(!build.overseer.is_enabled());
    assert_eq!(build.handler, "deterministic");
    assert!(build.llm.is_none());
}

#[test]
fn llm_overseer_is_none_without_key() {
    // A daemon that starts from an empty framework root (no overseer.toml
    // → no [llm] config) must not build an LLM chat handler, regardless of
    // any API keys present in the operator's environment (#1571).
    let (state, _dir) = hermetic_state();
    assert!(state.llm_overseer().is_none());
}

#[test]
fn overseer_handler_reports_strategy() {
    // A daemon built from an empty framework root reports the deterministic
    // handler — the default when no overseer.toml is installed (#1571).
    let (state, _dir) = hermetic_state();
    assert_eq!(state.overseer_handler(), "deterministic");
}

#[test]
fn overseer_is_accessible() {
    // The shared overseer can be cloned out and queried; with no overseer.toml
    // in the hermetic temp dir the overseer must report disabled (#1571).
    let (state, _dir) = hermetic_state();
    let overseer = state.overseer();
    assert!(!overseer.is_enabled());
}

#[test]
fn audit_logger_is_accessible() {
    let state = DaemonState::new();
    // The audit logger resolves a dated JSONL path under `logs/overseer`.
    let audit = state.audit();
    assert_eq!(
        audit.path().extension().and_then(|e| e.to_str()),
        Some("jsonl")
    );
}

/// #8545: a lib test's `DaemonState::new()` roots outside every fenced home,
/// and its audit write lands there. The root is checked before the write, so a
/// regression fails here without touching the operator's `~/.trusty-mpm`.
#[test]
fn new_never_writes_under_the_real_home() {
    use crate::core::home_write_fence::{armed_roots, fenced_root};
    use crate::daemon::audit::AuditEntry;
    assert!(!armed_roots().is_empty(), "the lib binary arms the fence");
    let state = DaemonState::new();
    let audit = state.audit();
    for path in [state.framework_root(), audit.path()] {
        assert!(
            fenced_root(path, armed_roots()).is_none(),
            "{} sits under a fenced home root {:?}",
            path.display(),
            armed_roots()
        );
    }
    audit.log(AuditEntry {
        ts: "2026-09-26T00:00:00Z".into(),
        session: "tmpm-8545".into(),
        event: "PreToolUse".into(),
        tool: None,
        decision: "allow".into(),
        reason: "#8545 regression".into(),
        handler: "deterministic".into(),
    });
    let written = std::fs::read_to_string(audit.path()).expect("the audit line landed");
    assert!(written.contains("#8545 regression"), "{written}");
}

#[test]
fn hook_history_is_bounded() {
    let state = DaemonState::new();
    let id = SessionId::new();
    for _ in 0..(HOOK_HISTORY_LIMIT + 50) {
        state.push_hook_event(HookEventRecord::now(
            id,
            HookEvent::PreToolUse,
            serde_json::Value::Null,
        ));
    }
    assert_eq!(state.recent_hook_events().len(), HOOK_HISTORY_LIMIT);
    assert_eq!(state.hook_events_for(id).len(), HOOK_HISTORY_LIMIT);
}

#[test]
fn pairing_round_trip() {
    // A freshly-generated code confirms once, binds the chat id, and is
    // then consumed so the same code cannot validate twice. The state is
    // rooted at a temp dir so the persisted record never touches HOME.
    let dir = tempfile::tempdir().expect("temp dir");
    let state = DaemonState::with_root(dir.path().to_path_buf());
    assert_eq!(state.paired_chat_id(), None);
    let code = state.generate_pair_code();
    assert_eq!(code.len(), 6);
    assert!(code.chars().all(|c| c.is_ascii_alphanumeric()));
    assert!(state.confirm_pair_code(&code, 12345678));
    assert_eq!(state.paired_chat_id(), Some(12345678));
    // The code was consumed; confirming it again must fail.
    assert!(!state.confirm_pair_code(&code, 999));
}

#[test]
fn wrong_pair_code_is_rejected() {
    let dir = tempfile::tempdir().expect("temp dir");
    let state = DaemonState::with_root(dir.path().to_path_buf());
    let _code = state.generate_pair_code();
    assert!(!state.confirm_pair_code("ZZZZZZ", 12345678));
    assert_eq!(state.paired_chat_id(), None);
}

#[test]
fn pairing_persists_to_disk() {
    // Confirming a code writes pairing.json; a fresh state rooted at the
    // same directory restores the binding without a new handshake.
    let dir = tempfile::tempdir().expect("temp dir");
    let root = dir.path().to_path_buf();
    let state = DaemonState::with_root(root.clone());
    let code = state.generate_pair_code();
    assert!(state.confirm_pair_code(&code, 555));
    // The on-disk record exists.
    assert_eq!(
        crate::daemon::pairing_store::load(&root).map(|r| r.chat_id),
        Some(555)
    );
    // A new state restores the pairing from disk.
    let restored = DaemonState::with_root(root);
    assert_eq!(restored.paired_chat_id(), Some(555));
}

#[test]
fn pairing_reset_clears_disk() {
    // clear_pairing drops the binding in memory and removes pairing.json.
    let dir = tempfile::tempdir().expect("temp dir");
    let root = dir.path().to_path_buf();
    let state = DaemonState::with_root(root.clone());
    let code = state.generate_pair_code();
    assert!(state.confirm_pair_code(&code, 777));
    state.clear_pairing();
    assert_eq!(state.paired_chat_id(), None);
    assert!(crate::daemon::pairing_store::load(&root).is_none());
}

#[test]
fn pairing_code_persists_to_disk() {
    // Minting a code writes the shared pending_pair.json, the single source of
    // truth that every confirm surface validates against (#1500).
    let dir = tempfile::tempdir().expect("temp dir");
    let root = dir.path().to_path_buf();
    let state = DaemonState::with_root(root.clone());
    let code = state.generate_pair_code();
    let pending = crate::daemon::pairing_store::load_pending(&root).expect("pending code on disk");
    assert_eq!(pending.code, code);
}

#[test]
fn pairing_confirms_shared_disk_code() {
    // THE #1500 REGRESSION GUARD: a code minted on one DaemonState instance is
    // confirmed on a DIFFERENT instance rooted at the same framework root, even
    // though the second instance never held the code in its in-memory mutex.
    // Before the shared on-disk pending store this returned false ("invalid
    // code") and operators had to pre-seed pairing.json.
    let dir = tempfile::tempdir().expect("temp dir");
    let root = dir.path().to_path_buf();

    let minting = DaemonState::with_root(root.clone());
    let code = minting.generate_pair_code();

    // A second, independent daemon instance (e.g. the ephemeral-port duplicate
    // from #1499) shares the framework root but has an empty in-memory pair_code.
    let confirming = DaemonState::with_root(root.clone());
    assert!(
        confirming.confirm_pair_code(&code, 31415),
        "code minted on a sibling instance must validate via the shared store"
    );
    assert_eq!(confirming.paired_chat_id(), Some(31415));

    // The shared pending code was consumed: a third instance cannot replay it.
    let replay = DaemonState::with_root(root);
    assert!(!replay.confirm_pair_code(&code, 999));
}

#[test]
fn concurrent_pairing_confirms() {
    // THE #1506 REGRESSION GUARD: two concurrent confirm attempts race on the
    // same pending code. The atomic rename-based claim must ensure exactly ONE
    // wins; the WINNER must have the device registered in state, the LOSER must
    // not. This catches the pre-fix TOCTOU race where both reads could precede
    // both deletes.
    let dir = tempfile::tempdir().expect("temp dir");
    let root = dir.path().to_path_buf();

    let minting = DaemonState::with_root(root.clone());
    let code = minting.generate_pair_code();

    // Use Arc so each thread can own a confirming state.
    let confirming1 = std::sync::Arc::new(DaemonState::with_root(root.clone()));
    let confirming2 = std::sync::Arc::new(DaemonState::with_root(root.clone()));
    let c1_ref = confirming1.clone();
    let c2_ref = confirming2.clone();

    let code1 = code.clone();
    let code2 = code.clone();
    let c1 = std::thread::spawn(move || c1_ref.confirm_pair_code(&code1, 111));
    let c2 = std::thread::spawn(move || c2_ref.confirm_pair_code(&code2, 222));

    let res1 = c1.join().expect("thread 1 must not panic");
    let res2 = c2.join().expect("thread 2 must not panic");

    // Exactly one confirm should succeed due to the atomic claim.
    assert!(
        res1 ^ res2,
        "exactly one concurrent confirm must win the atomic claim (got res1={res1} res2={res2})"
    );

    // The WINNER must have its chat_id registered; the LOSER must not.
    if res1 {
        assert_eq!(
            confirming1.paired_chat_id(),
            Some(111),
            "winner (thread 1) must have chat_id 111 registered"
        );
        assert_eq!(
            confirming2.paired_chat_id(),
            None,
            "loser (thread 2) must not have registered any chat_id"
        );
    } else {
        assert_eq!(
            confirming2.paired_chat_id(),
            Some(222),
            "winner (thread 2) must have chat_id 222 registered"
        );
        assert_eq!(
            confirming1.paired_chat_id(),
            None,
            "loser (thread 1) must not have registered any chat_id"
        );
    }

    // The pending code file must be gone — consumed by the winner's claim.
    assert!(
        crate::daemon::pairing_store::load_pending(&root).is_none(),
        "pending code file must be absent after a winning confirm"
    );
}

// ─── #1744 managed reap tests ───────────────────────────────────────────────

/// Inline minimal [`crate::session_manager::ManagedTmuxDriver`] for reap tests.
struct MinFakeDriver {
    sessions: std::sync::Mutex<Vec<String>>,
}
impl MinFakeDriver {
    fn new() -> std::sync::Arc<Self> {
        std::sync::Arc::new(Self {
            sessions: std::sync::Mutex::new(Vec::new()),
        })
    }
}
impl crate::session_manager::ManagedTmuxDriver for MinFakeDriver {
    fn create_session(
        &self,
        name: &str,
        _: &str,
    ) -> Result<(), crate::session_manager::ManagedError> {
        self.sessions.lock().unwrap().push(name.to_owned());
        Ok(())
    }
    fn kill_session(&self, name: &str) -> Result<(), crate::session_manager::ManagedError> {
        self.sessions.lock().unwrap().retain(|n| n != name);
        Ok(())
    }
    fn send_line(&self, _: &str, _: &str) -> Result<(), crate::session_manager::ManagedError> {
        Ok(())
    }
    fn capture(&self, _: &str, _: usize) -> Result<String, crate::session_manager::ManagedError> {
        Ok(String::new())
    }
    fn list_sessions(&self) -> Result<Vec<String>, crate::session_manager::ManagedError> {
        Ok(self.sessions.lock().unwrap().clone())
    }
}

#[tokio::test]
async fn reap_dead_managed_sessions_marks_stopped() {
    // Why (#1744): reap_managed_against must mark Active managed sessions Stopped
    // when their tmux_name is absent from the live set.
    // What: seed one Active session; call reap_managed_against with an empty live
    // set (simulating the tmux pane having gone away); assert Stopped.
    let tmp = tempfile::TempDir::new().unwrap();
    let fake = MinFakeDriver::new();
    let mgr = crate::session_manager::SessionManager::new(tmp.path(), fake)
        .await
        .expect("session manager");
    let mgr = std::sync::Arc::new(mgr);

    // Create a session and promote to Active.
    let record = mgr
        .create(
            "task".into(),
            Some(PathBuf::from("/tmp/test-reap")),
            None,
            None,
            None,
            None,
        )
        .await
        .expect("create");
    let id = record.id;
    mgr.set_workspace(
        &id,
        PathBuf::from("/tmp/test-reap"),
        crate::session_manager::ManagedSessionState::Active,
    )
    .await
    .expect("set Active");

    // Wire into a DaemonState via with_session_manager.
    let state = DaemonState::with_session_manager(std::sync::Arc::clone(&mgr));

    // Simulate the tmux session being gone: pass an empty live set.
    let live = std::collections::HashSet::new();
    state.reap_managed_against(&live).await;

    let after = mgr.get(&id).await.expect("get after reap");
    assert_eq!(
        after.state,
        crate::session_manager::ManagedSessionState::Stopped,
        "reap_managed_against must mark Active session Stopped when tmux_name absent (#1744)"
    );
    // #6194: pin the CAUSE, not just the state. An empty live set is a lost
    // tmux server, so the record must stay auto-resumable — and if a future
    // change reroutes the reaper away from `stop_with_cause`, this catches it
    // rather than letting the cause silently go unrecorded.
    assert_eq!(
        after.stop_cause,
        Some(crate::session_manager::StopCause::Unexpected),
        "an empty live set is a whole-server loss, not a decision about this session"
    );
    assert!(after.is_auto_resumable());
}

/// #8233 acceptance item 4: the reaper leaves a session another path is
/// resuming exactly as it found it.
///
/// Why: `resume_inner`'s recreate branch kills and rebuilds the tmux session,
/// so a sweep whose `live` snapshot predates that kill sees the name missing
/// and — before this guard — stopped the record, killed the pane the resume had
/// just made, and stamped `Deliberate`, which no automatic path revives.
/// What: holds the real claim, sweeps with a live set that omits the session,
/// and asserts the record is untouched — still `Active`, and with NO stop cause
/// written, because a skipped session must not be half-acted-on either.
/// Test: this function IS the test.
#[tokio::test]
async fn reap_managed_against_skips_a_session_whose_resume_is_in_flight() {
    let tmp = tempfile::TempDir::new().unwrap();
    let mgr = crate::session_manager::SessionManager::new(tmp.path(), MinFakeDriver::new())
        .await
        .expect("session manager");
    let mgr = std::sync::Arc::new(mgr);
    let id = active_session_in_state(&mgr, "resuming", "/tmp/test-reap-in-flight").await;
    let state = DaemonState::with_session_manager(std::sync::Arc::clone(&mgr));

    // The claim the resume route holds for its whole span.
    let claim = mgr.begin_resume(&id).expect("claim granted");
    // A non-empty live set that does NOT contain this session: the exact
    // observation the recreate branch produces mid-resume.
    let mut live = std::collections::HashSet::new();
    live.insert("some-other-live-session".to_string());
    state.reap_managed_against(&live).await;

    let after = mgr.get(&id).await.expect("get after reap");
    assert_eq!(
        after.state,
        crate::session_manager::ManagedSessionState::Active,
        "the reaper must not stop a session whose resume is in flight (#8233)"
    );
    assert_eq!(
        after.stop_cause, None,
        "and must write no stop cause for it either — a `Deliberate` stamp here \
         is what made such a session permanently un-auto-resumable"
    );
    drop(claim);
}

/// Seed one Active managed session rooted at `workspace`, wired into a state.
///
/// Why: the two #6194 reaper tests below differ only in the live set they reap
/// against, so the six-step create/promote/wire sequence is shared.
/// Test: `reap_marks_a_targeted_kill_deliberate`,
/// `reap_leaves_a_whole_server_loss_auto_resumable`,
/// `reap_managed_against_skips_a_session_whose_resume_is_in_flight`.
async fn active_session_in_state(
    mgr: &std::sync::Arc<crate::session_manager::SessionManager>,
    task: &str,
    workspace: &str,
) -> crate::session_manager::ManagedSessionId {
    let record = mgr
        .create(
            task.into(),
            Some(PathBuf::from(workspace)),
            None,
            None,
            None,
            None,
        )
        .await
        .expect("create");
    mgr.set_workspace(
        &record.id,
        PathBuf::from(workspace),
        crate::session_manager::ManagedSessionState::Active,
    )
    .await
    .expect("set Active");
    record.id
}

/// A session killed while the tmux server is alive is not auto-resumed (#6194).
///
/// Why: this is the reported repro. The operator kills one managed session; the
/// server stays up because other sessions are still running, so the reaper can
/// attribute the disappearance to a decision and must record it as one. Before
/// the fix the supervisor respawned this session within one interval.
/// Test: this function IS the test.
#[tokio::test]
async fn reap_marks_a_targeted_kill_deliberate() {
    let tmp = tempfile::TempDir::new().unwrap();
    let mgr = crate::session_manager::SessionManager::new(tmp.path(), MinFakeDriver::new())
        .await
        .expect("session manager");
    let mgr = std::sync::Arc::new(mgr);
    let id = active_session_in_state(&mgr, "killed", "/tmp/test-reap-killed").await;
    let state = DaemonState::with_session_manager(std::sync::Arc::clone(&mgr));

    // The server is alive — some OTHER session is still listed — and this
    // record's own tmux_name is not.
    let live: std::collections::HashSet<String> =
        ["someone-elses-shell".to_string()].into_iter().collect();
    state.reap_managed_against(&live).await;

    let after = mgr.get(&id).await.expect("get after reap");
    assert_eq!(
        after.state,
        crate::session_manager::ManagedSessionState::Stopped
    );
    assert_eq!(
        after.stop_cause,
        Some(crate::session_manager::StopCause::Deliberate)
    );
    assert!(
        !after.is_auto_resumable(),
        "a session killed out-of-band while the server is alive must not be auto-resumed"
    );
}

/// A whole-server loss leaves the entire fleet auto-resumable (#6194).
///
/// Why: `TmuxDriver::list_sessions` maps "no server running" to an empty list,
/// so `tmux kill-server`, a crash, an upgrade, or a logout reaps every Active
/// record in one tick. Stamping those `Deliberate` would leave the whole fleet
/// permanently un-auto-resumable — worse than the defect being fixed, and a
/// regression against the pre-#6194 supervisor, which restored exactly this.
/// Two records so the assertion is about the sweep, not one row.
/// Test: this function IS the test.
#[tokio::test]
async fn reap_leaves_a_whole_server_loss_auto_resumable() {
    let tmp = tempfile::TempDir::new().unwrap();
    let mgr = crate::session_manager::SessionManager::new(tmp.path(), MinFakeDriver::new())
        .await
        .expect("session manager");
    let mgr = std::sync::Arc::new(mgr);
    let first = active_session_in_state(&mgr, "fleet-a", "/tmp/test-reap-fleet-a").await;
    let second = active_session_in_state(&mgr, "fleet-b", "/tmp/test-reap-fleet-b").await;
    let state = DaemonState::with_session_manager(std::sync::Arc::clone(&mgr));

    // No tmux session of any kind on the host — the server itself is gone.
    let live = std::collections::HashSet::new();
    state.reap_managed_against(&live).await;

    for id in [first, second] {
        let after = mgr.get(&id).await.expect("get after reap");
        assert_eq!(
            after.state,
            crate::session_manager::ManagedSessionState::Stopped,
            "the safety net still converges the record (#1744)"
        );
        assert_eq!(
            after.stop_cause,
            Some(crate::session_manager::StopCause::Unexpected)
        );
        assert!(
            after.is_auto_resumable(),
            "losing the tmux server is not a decision about any session — the supervisor \
             must still be able to restore this fleet"
        );
    }
}

/// #8942: when the Architect's name is missing from the live set, its record
/// goes `Stopped`, and no teardown reaches a pane of that name.
#[tokio::test]
async fn the_tmux_gone_reaper_marks_a_supervisor_record_stopped_without_teardown() {
    let tmp = tempfile::TempDir::new().unwrap();
    let driver = MinFakeDriver::new();
    let mgr = crate::session_manager::SessionManager::new(tmp.path(), driver.clone())
        .await
        .expect("session manager");
    let mgr = std::sync::Arc::new(mgr);
    let id = active_session_in_state(&mgr, "architect", "/tmp/test-reap-architect").await;
    let mut record = mgr.get(&id).await.expect("record");
    record.kind = crate::session_manager::SessionKind::Supervisor;
    let name = record.tmux_name.clone();
    mgr.store.write().await.upsert(record).await.expect("seed");
    let state = DaemonState::with_session_manager(std::sync::Arc::clone(&mgr));

    let live: std::collections::HashSet<String> =
        ["someone-elses-shell".to_string()].into_iter().collect();
    state.reap_managed_against(&live).await;

    let after = mgr.get(&id).await.expect("get after reap");
    assert_eq!(
        after.state,
        crate::session_manager::ManagedSessionState::Stopped
    );
    assert_eq!(
        after.stop_cause,
        Some(crate::session_manager::StopCause::Deliberate)
    );
    assert!(
        driver.sessions.lock().unwrap().contains(&name),
        "the reaper killed a pane carrying the Architect's name"
    );
}

/// #3822 hardening (code-critic review): `project_registry()`'s session-
/// history seed must not depend on some OTHER call site having already
/// warmed `managed_sessions` first — it must warm `session_manager()` itself.
///
/// Why: the pre-hardening code peeked at `self.managed_sessions.get()`,
/// which is `None` unless another caller happened to race ahead and
/// `get_or_init` it first. That made the seed's completeness an unenforced
/// startup-ordering invariant: on a daemon restart, if `project_registry()`
/// is the FIRST thing anything touches (plausible — an MCP `project_list`
/// call, or any of its 15+ other call sites, arriving before a session-list
/// call), a session persisted by an EARLIER daemon process would silently
/// stay unregistered — resurrecting #3822 for pre-existing sessions even
/// after `register_from_session` closed the gap for newly-spawned ones.
/// What: seeds a session record directly into the on-disk session-manager
/// store (the SAME `<framework_root>/session-manager` path
/// `DaemonState::session_manager()` itself uses) via a throwaway
/// `SessionManager` instance — simulating a session left behind by an
/// earlier process — WITHOUT ever calling `DaemonState::session_manager()`
/// on the state under test. A fresh `DaemonState` pointed at that same
/// `framework_root` (whose `managed_sessions` `OnceCell` has therefore never
/// been touched by anything) then calls `project_registry()` FIRST, and the
/// session's implied project must still be visible.
/// Test: this function IS the test.
#[tokio::test]
async fn project_registry_seeds_session_history_without_prewarmed_managed_sessions() {
    let dir = tempfile::tempdir().expect("temp dir");
    let paths = FrameworkPaths::under(dir.path());

    // Seed the on-disk store directly — mirrors what an EARLIER daemon
    // process would have left behind. Uses `FakeNoopTmuxDriver` so this
    // never touches real tmux or spawns a real session.
    let data_dir = paths.root.join("session-manager");
    tokio::fs::create_dir_all(&data_dir)
        .await
        .expect("mkdir session-manager data dir");
    let fake_tmux: std::sync::Arc<dyn crate::session_manager::ManagedTmuxDriver> =
        std::sync::Arc::new(crate::session_manager::FakeNoopTmuxDriver);
    let seed_mgr = crate::session_manager::SessionManager::new(&data_dir, fake_tmux)
        .await
        .expect("seed session manager");
    seed_mgr
        .create(
            "task".into(),
            Some(PathBuf::from("/tmp/wt-3822-hardening")),
            None,
            None,
            Some("https://github.com/octocat/Hello-World.git".into()),
            Some("main".into()),
        )
        .await
        .expect("seed session record");
    drop(seed_mgr);

    // Fresh DaemonState pointed at the SAME framework_root — its OWN
    // `managed_sessions` OnceCell has never been touched by anything,
    // reproducing the #3822 ordering hazard: `project_registry()` is the
    // very first thing to touch this state.
    let fresh = DaemonState::with_paths(&paths);
    let registry = fresh.project_registry().await;
    let all = registry.list().await.expect("list");
    assert!(
        all.iter()
            .any(|p| p.repo_url == "https://github.com/octocat/Hello-World.git"),
        "a session persisted by an earlier process must be registered at the FIRST \
         project_registry() touch, even though nothing warmed managed_sessions first \
         (#3822 hardening — project_registry() must warm session_manager() itself, \
         not merely peek at whether something else already did): {all:?}"
    );
}

/// The Layer-3 manager state is provisioned at daemon construction and reachable
/// via the shared accessor (#2578) — the palace handle it threads through always
/// carries the stable portfolio id, regardless of whether the memory engine is
/// compiled/available (that availability is the palace tests' concern).
#[test]
fn manager_state_is_provisioned() {
    let (state, _dir) = hermetic_state();
    let manager = state.manager_state();
    assert_eq!(
        manager.palace().id(),
        crate::daemon::manager::PORTFOLIO_PALACE_ID,
        "daemon startup must auto-provision the portfolio manager palace"
    );
}

/// A daemon isolated by its framework root alone must not reach live tmux
/// (#6348).
///
/// Before the fix this constructor asked only whether `$HOME` had been
/// reassigned. Under an untouched `$HOME` it resolved a real driver, and on the
/// machine that reproduced the bug that driver listed 250 live operator panes
/// for `reconcile_on_boot` to adopt — each adopted record carrying a real
/// project directory. The no-op driver installed instead reports tmux
/// UNOBSERVABLE, which is what keeps reconciliation from touching any record.
#[tokio::test]
async fn session_manager_refuses_tmux_on_a_scratch_framework_root() {
    let tmp = tempfile::tempdir().unwrap();
    let state = DaemonState::with_root(tmp.path().to_path_buf());
    let mgr = state.session_manager().await;

    let live = mgr.tmux_driver().list_sessions();
    assert!(
        live.is_err(),
        "a scratch framework root must leave tmux unobservable, got {live:?}"
    );
}

/// `caller = None` is the fail-closed value: a HEAD-write query that names no
/// session of its own hears about every record, exactly as it did before #6797
/// gave the question a caller. Pinned so a future caller that cannot identify
/// itself degrades toward the deny rather than toward the allow.
#[test]
fn head_write_without_a_caller_excludes_nothing() {
    let (state, _dir) = hermetic_state();
    let session = crate::core::session::SessionId(uuid::Uuid::new_v4());
    let cwd = std::path::PathBuf::from("/repo/main");
    state.upsert_delegation(unisolated_running_delegation(session, &cwd));

    assert_eq!(
        state.live_shared_tree_writers_excluding(&cwd, None, None),
        vec!["rust-engineer".to_string()],
        "an unidentified caller must still be told about the writer"
    );
    assert!(
        state
            .live_shared_tree_writers_excluding(&cwd, None, Some(session))
            .is_empty(),
        "and naming that session must exclude its own record"
    );
}

/// The #8161 half of the tree-membership rule. A `reset --keep` into a parked
/// worktree asks who holds it, and the answer used to omit the one agent that
/// matters: an isolated agent standing in its own tree carries the checkout it
/// was dispatched FROM, so no directory-keyed query on the tree matched it.
///
/// Fails before the fix: the filter keyed on `Delegation::cwd` alone.
#[test]
fn a_live_agent_is_counted_in_the_worktree_it_stands_in() {
    let state = DaemonState::new();
    let session = sample_session();
    let id = session.id;
    let checkout = std::path::PathBuf::from("/repo/main");
    let tree = checkout.join(".claude/worktrees/agent-parked");
    state.register_session(session);

    let mut d = unisolated_running_delegation(id, &checkout);
    d.isolation = Some("worktree".to_string());
    d.worktree_path = Some(tree.clone());
    d.last_agent_cwd = Some(tree.join("crates/foo"));
    state.upsert_delegation(d);

    assert_eq!(
        state.live_shared_tree_writers_excluding(&tree, None, None),
        vec!["rust-engineer".to_string()],
        "a tree-holders query must name the agent standing in the tree"
    );
    assert!(
        state
            .live_shared_tree_writers_excluding(&tree, None, Some(id))
            .is_empty(),
        "a session-scoped HEAD write still excludes its own session (#6797)"
    );
    assert!(
        state.live_shared_tree_writers(&checkout, None).is_empty(),
        "and the agent is still not a writer in the checkout it left"
    );
}

/// The #8535 regression. The harness moved the PM's cwd into an agent's
/// worktree, so a qa dispatch made from there was stamped with that worktree,
/// and when the harness then isolated the agent anyway the record still read
/// as a second writer in the PM's directory until its ownership claim landed.
/// Here the claim has not landed (`worktree_path` is `None`) but the agent's
/// own hook already reports a different harness tree.
///
/// Fails before the fix: `holds_its_own_tree` needed `worktree_path`, so the
/// record fell through to the isolation test and was reported.
#[test]
fn a_record_stamped_in_a_relocated_pm_cwd_is_not_a_writer_there() {
    let state = DaemonState::new();
    let session = sample_session();
    let id = session.id;
    let relocated = std::path::PathBuf::from("/repo/main/.claude/worktrees/agent-engineer");
    state.register_session(session);

    let mut d = unisolated_running_delegation(id, &relocated);
    d.agent = "qa".to_string();
    d.last_agent_cwd = Some(std::path::PathBuf::from(
        "/repo/main/.claude/worktrees/agent-qa/tests",
    ));
    state.upsert_delegation(d);

    assert!(
        state.shared_tree_occupants(&relocated, None).is_empty(),
        "an agent standing in another harness tree is not a writer in the PM's cwd"
    );
}

/// #8161 critic round: rule 1 on the DISPATCH question. When the PM's cwd sits
/// inside a live agent's worktree (#8535), an unisolated dispatch from there
/// would join that agent's tree, so the agent occupies it even though its
/// record carries the checkout it was dispatched from.
///
/// Fails before the fix: the filter matched `Delegation::cwd` only.
#[test]
fn a_live_agent_occupies_its_worktree_for_a_dispatch_from_inside_it() {
    let state = DaemonState::new();
    let session = sample_session();
    let id = session.id;
    let checkout = std::path::PathBuf::from("/repo/main");
    let tree = checkout.join(".claude/worktrees/agent-live");
    state.register_session(session);

    let mut d = unisolated_running_delegation(id, &checkout);
    d.isolation = Some("worktree".to_string());
    d.worktree_path = Some(tree.clone());
    d.last_agent_cwd = Some(tree.clone());
    state.upsert_delegation(d);

    assert_eq!(
        state.shared_tree_occupants(&tree, None),
        vec!["rust-engineer".to_string()]
    );
    assert!(state.shared_tree_occupants(&checkout, None).is_empty());
}

/// The control for the #8161 rule: a positively read-only agent standing in a
/// parked worktree does not block consolidating into it.
#[test]
fn a_read_only_agent_in_a_linked_worktree_is_not_a_writer() {
    let state = DaemonState::new();
    let session = sample_session();
    let id = session.id;
    let checkout = std::path::PathBuf::from("/repo/main");
    let tree = checkout.join(".claude/worktrees/agent-parked");
    state.register_session(session);

    let mut d = unisolated_running_delegation(id, &checkout);
    d.agent = "research".to_string();
    d.last_agent_cwd = Some(tree.clone());
    state.upsert_delegation(d);

    assert!(
        state
            .live_shared_tree_writers_excluding(&tree, None, None)
            .is_empty()
    );
}