teamctl 0.11.0

Declarative CLI for running persistent AI agent teams.
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
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{bail, Context, Result};
use team_core::compose::Compose;
use team_core::render::{
    boot_script_path, claude_settings_path, codex_home_dir, env_path, mcp_path, opencode_home_dir,
    render_agent, render_claude_settings, write_agent_skills, write_codex_config,
    write_opencode_config, write_role_prompt_concat, write_subagents_json,
};
use team_core::supervisor::{AgentSpec, AgentState, Supervisor, TmuxSupervisor};

use super::agent_filter::AgentSelector;

pub fn run(root: &Path, project: Option<&str>, sel: &AgentSelector, fresh: bool) -> Result<()> {
    let compose = super::load(root)?;
    super::update_check::maybe_print_banner(&compose.root);
    let errs = team_core::validate::validate(&compose);
    if !errs.is_empty() {
        for e in &errs {
            eprintln!("error: {e}");
        }
        bail!("{} validation error(s) — fix before up", errs.len());
    }
    let scoped = project
        .map(|name| super::project_filter::resolve(&compose, name))
        .transpose()?;
    // Per-agent target set (T-305). `None` => no agent-level filter
    // (no-arg / `<project>`-only contracts, untouched). Only reached
    // when `scoped` is `Some` — clap requires a project for the
    // selector forms.
    let targets = match scoped.as_deref() {
        Some(id) => super::agent_filter::resolve(&compose, id, sel)?,
        None => None,
    };

    // T-469: refuse a same-name-different-folder launch before any side
    // effects. Two teams sharing a `project_id` in different folders alias
    // each other (identity is name-keyed, not path-keyed) and crash-loop;
    // bail early with the conflicting directory named.
    guard_no_name_collision(&compose, scoped.as_deref())?;

    // Per T-133: scoped runs skip cross-project work — wrapper write,
    // DB-side projects/agents/acls/channels rewrite, snapshot rewrite
    // — because each of those clobbers state owned by *other*
    // projects. The unscoped path is unchanged.
    if scoped.is_none() {
        ensure_wrapper_and_dirs(&compose)?;
        render_all_public(&compose)?;
        register_all_public(&compose)?;
        ensure_claude_trust(&compose)?;
    } else {
        // Per-project work: re-render the named project's env+mcp
        // (operator may have edited them) and pre-accept Claude trust
        // for that project's cwds. Both are idempotent and project-
        // scoped on disk.
        render_project_public(&compose, scoped.as_deref().unwrap())?;
        ensure_claude_trust_for_project(&compose, scoped.as_deref().unwrap())?;
    }

    let mut touched = 0usize;
    let sup = TmuxSupervisor;
    for h in compose.agents() {
        if scoped.as_deref().is_some_and(|id| id != h.project) {
            continue;
        }
        if targets.as_ref().is_some_and(|t| !t.contains(h.agent)) {
            continue;
        }
        let spec = AgentSpec::from_handle(h, &compose.root, &compose.global.supervisor.tmux_prefix);
        let running = matches!(sup.state(&spec)?, AgentState::Running);
        // In a per-agent scope the operator named this agent on the
        // command line, so an already-running session is worth calling
        // out explicitly rather than silently. `up` stays idempotent
        // (sup.up() is a no-op for a running session) — this only adds
        // a clearer line, never an error.
        if targets.is_some() && running {
            println!("up · {} (already running)", h.id());
            touched += 1;
            continue;
        }
        // Only `--fresh` an agent we're actually about to spawn. `up`
        // never restarts a running agent (sup.up() is a no-op), so
        // freshening a running one would move its live session aside with
        // no respawn to replace it — a latent desync where the agent
        // silently comes up fresh on its NEXT natural restart. Skip
        // running agents here; `reload --fresh` is the path to refresh a
        // running agent's conversation.
        if !running {
            freshen_for_spec(&compose.root, &spec, &h.spec.runtime, fresh);
        }
        sup.up(&spec)?;
        println!("up · {}{}", h.id(), fresh_suffix(fresh && !running));
        touched += 1;
    }

    // Spawn one team-bot per manager that carries a `telegram:` block.
    // Each bot runs in its own tmux session and is scoped via
    // --manager so DMs reach exactly that manager.
    let team_bot = super::bot::team_bot_bin();
    source_dotenv_into_process(&compose.root);
    for spec in super::bot::bot_specs(&compose) {
        // Project guard preserved verbatim from the pre-T-305 path.
        let split = spec.manager.split_once(':');
        if scoped
            .as_deref()
            .is_some_and(|id| split.map(|(p, _)| p) != Some(id))
        {
            continue;
        }
        // A bot's lifecycle follows its manager agent: in a per-agent
        // scope, skip the bot unless its manager is targeted.
        // `targets` is `Some` only when `scoped` is `Some`, so the
        // guard above has already pinned `split` to the in-scope pair.
        if let Some(t) = &targets {
            if !t.contains(split.map(|(_, a)| a).unwrap_or("")) {
                continue;
            }
        }
        match super::bot::up_one(&spec, &team_bot, &compose.root) {
            Ok(true) => {
                println!("up · bot {}{}", spec.session, spec.manager);
                touched += 1;
            }
            Ok(false) => {}
            Err(e) => eprintln!("warn · bot {}: {e:#}", spec.session),
        }
    }

    if let (Some(id), 0) = (scoped.as_deref(), touched) {
        println!("no agents in scope for project {id}.");
    }

    // Persist the applied-state snapshot so a reload immediately
    // afterwards correctly sees zero diff. Scoped runs merge just the
    // named project's per-agent entries into the existing
    // applied.json (T-133) — preserves correctness for the next
    // unscoped reload while still recording what this scoped up
    // applied.
    let bin = super::team_mcp_bin().display().to_string();
    let next = super::snapshot::compute(&compose, &bin);
    let snap = match scoped.as_deref() {
        Some(id) => {
            let prev = super::snapshot::read(&compose.root);
            super::snapshot::merge_project_into(prev.as_ref(), &next, id)
        }
        None => next,
    };
    super::snapshot::write(&compose.root, &snap)?;

    // T-466: record this team in the durable, system-wide registry so
    // `teamctl ps`, orphan reaping, and the same-name guard can see teams
    // across the host — not just the one in the cwd. Best-effort: a
    // registry hiccup must not fail an otherwise-successful `up`.
    record_in_registry(&compose, scoped.as_deref());

    // T-370: keep the host awake (no idle-sleep) while agents are up so
    // long-running tasks survive display sleep. Host-level + refcounted;
    // macOS-only, no-op elsewhere. Only when we actually brought something up.
    if touched > 0 {
        super::caffeinate::ensure_running();
    }
    Ok(())
}

/// Build the registry rows for the in-scope projects: one
/// [`team_core::registry::TeamEntry`] per project, agents folded in and
/// sorted. `scoped` (a `--project` filter) restricts the set to that
/// project; `None` records every project in the compose. The row's
/// `agents` is the project's full declared roster — a `--agent` filter
/// narrows what `up` *spawns*, not the team membership the registry
/// records (which is the shape `ps` wants to show). Pure over its inputs
/// so the mapping is unit-testable without a live `Compose` or `$HOME`.
fn registry_entries<'a>(
    agents: impl Iterator<Item = (&'a str, &'a str)>,
    root: &Path,
    tmux_prefix: &str,
    scoped: Option<&str>,
    started_at: &str,
) -> Vec<team_core::registry::TeamEntry> {
    let mut by_project: BTreeMap<&str, Vec<String>> = BTreeMap::new();
    for (project, agent) in agents {
        if scoped.is_some_and(|id| id != project) {
            continue;
        }
        by_project
            .entry(project)
            .or_default()
            .push(agent.to_string());
    }
    by_project
        .into_iter()
        .map(|(project, mut names)| {
            names.sort();
            team_core::registry::TeamEntry {
                project_id: project.to_string(),
                root: root.to_path_buf(),
                tmux_prefix: tmux_prefix.to_string(),
                agents: names,
                started_at: started_at.to_string(),
            }
        })
        .collect()
}

/// T-469: refuse a launch that would alias an already-running team. teamctl
/// identity is name-keyed (session UUID, tmux name, mailbox key), never
/// path-keyed, so two teams with the same `project_id` in different folders
/// alias each other's sessions — the crash-loop behind the owner's report
/// (tg 2318). If the durable registry already records any in-scope
/// `project_id` at a DIFFERENT, still-live root, bail before any side
/// effects, naming the conflicting directory. A re-up of the same
/// `(project_id, root)` is fine.
///
/// `pub(super)` so `reload` — the other spawn path — shares the guard.
/// Best-effort: a missing, unreadable, OR corrupt registry skips the guard
/// (the store degrades to empty) rather than blocking a legitimate launch.
/// The check iterates per declared agent, so a project with zero agents is
/// not examined — it has no session/tmux/mailbox identity to alias.
pub(super) fn guard_no_name_collision(compose: &Compose, scoped: Option<&str>) -> Result<()> {
    let Some(dir) = team_core::registry::config_dir() else {
        return Ok(());
    };
    let reg = match team_core::registry::load(&dir) {
        Ok(r) => r,
        Err(_) => return Ok(()), // can't check ⇒ don't block
    };
    guard_no_name_collision_in(&reg, compose, scoped, &|p| p.exists())
}

/// Inner half of [`guard_no_name_collision`] with the registry and the
/// liveness check injected, so the guard's decision is unit-testable without
/// `$HOME` or the real filesystem.
fn guard_no_name_collision_in(
    reg: &team_core::registry::Registry,
    compose: &Compose,
    scoped: Option<&str>,
    path_exists: &impl Fn(&Path) -> bool,
) -> Result<()> {
    let mut seen = BTreeSet::new();
    for h in compose.agents() {
        if scoped.is_some_and(|s| s != h.project) || !seen.insert(h.project) {
            continue;
        }
        if let Some(other) =
            team_core::registry::same_name_other_root(reg, h.project, &compose.root, path_exists)
        {
            bail!(
                "project `{}` is already up at {} — two teams with the same project id in \
                 different folders alias each other (they share session ids, tmux names, and \
                 mailbox keys) and can crash-loop. Rename the project here, or `teamctl down` \
                 the other team first.",
                h.project,
                other.display()
            );
        }
    }
    Ok(())
}

/// Persist this team's registry rows. Resolves the config dir from `$HOME`
/// (skipping with a warning if unset), then delegates to
/// [`record_in_registry_in`]. Never returns an error: the registry is a
/// convenience side store, and a failure here must not undo a successful
/// `up`. `pub(super)` so `reload` can refresh the registry after applying
/// a diff (T-468) — keeping `ps` / reaping accurate across reloads.
pub(super) fn record_in_registry(compose: &Compose, scoped: Option<&str>) {
    let Some(dir) = team_core::registry::config_dir() else {
        eprintln!("warn · teams registry: neither HOME nor USERPROFILE set, skipping");
        return;
    };
    record_in_registry_in(&dir, compose, scoped);
}

/// Inner half of [`record_in_registry`] with the config dir injected, so
/// the `up` → `teams.json` write path is testable against a real `Compose`
/// without resolving (or mutating) `$HOME`.
fn record_in_registry_in(dir: &Path, compose: &Compose, scoped: Option<&str>) {
    let started_at = team_core::registry::now_rfc3339();
    let entries = registry_entries(
        compose.agents().map(|h| (h.project, h.agent)),
        &compose.root,
        &compose.global.supervisor.tmux_prefix,
        scoped,
        &started_at,
    );
    if let Err(e) = team_core::registry::upsert_many(dir, entries) {
        eprintln!("warn · teams registry: {e:#}");
    }
}

/// What a `--fresh` request resolves to for one agent, before any I/O.
/// Split out from [`freshen_for_spec`] so the runtime-gate decision —
/// the codex/gemini parity carve-out — is unit-testable without touching
/// the filesystem or `$HOME`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FreshenAction {
    /// `--fresh` not set: do nothing.
    Skip,
    /// `--fresh` on a runtime with no mapped session model (gemini):
    /// warn and skip (parity gap).
    UnsupportedRuntime,
    /// `--fresh` on a Claude agent: move its session aside.
    Freshen,
    /// `--fresh` on a codex agent: move its per-agent CODEX_HOME
    /// sessions dir aside (`.bak` recovery copy) so the wrapper's
    /// resume probe falls through to a fresh spawn.
    WipeCodexSessions,
    /// `--fresh` on an opencode agent: move its per-agent session db
    /// (plus -shm/-wal sidecars) into a `db.bak/` recovery copy so the
    /// wrapper's resume probe falls through to a fresh spawn.
    WipeOpencodeSessions,
}

/// Resolve `(runtime, fresh)` to a [`FreshenAction`]. Pure — no I/O.
pub(crate) fn freshen_action(runtime: &str, fresh: bool) -> FreshenAction {
    if !fresh {
        FreshenAction::Skip
    } else if runtime == "claude-code" {
        FreshenAction::Freshen
    } else if runtime == "codex" {
        FreshenAction::WipeCodexSessions
    } else if runtime == "opencode" {
        FreshenAction::WipeOpencodeSessions
    } else {
        FreshenAction::UnsupportedRuntime
    }
}

/// T-352: when `--fresh` is set, drop the agent's session state just
/// before it (re)spawns so the wrapper opens a brand-new conversation
/// (re-running `BOOTSTRAP_PROMPT`). Claude: move the session JSONL
/// aside (same deterministic UUID, `.bak` recovery copy kept). Codex:
/// move the per-agent CODEX_HOME `sessions/` subdir to `sessions.bak`
/// (same recovery-copy parity) — the wrapper's resume probe then finds
/// no rollout and boots fresh; config.toml and the auth.json symlink
/// live at the codex-home root and survive. OpenCode: move the
/// per-agent session db (+ -shm/-wal sidecars) into `db.bak/` (same
/// parity) — the resume probe finds no db and boots fresh;
/// opencode.json at the home root survives.
/// Durable on-disk files are never touched.
///
/// Gemini has no session resume, so we warn-and-skip rather than abort
/// a mixed-runtime team (parity gap). Best-effort — a failure warns but
/// never blocks the respawn (coming up on the existing conversation is
/// strictly safer than refusing to start).
///
/// Call only for an agent that is actually being (re)spawned: freshening
/// an agent that won't respawn would move its live session aside with no
/// new conversation to replace it (a latent desync), so the callers gate
/// on "about to start this agent" before calling here.
pub(crate) fn freshen_for_spec(root: &Path, spec: &AgentSpec, runtime: &str, fresh: bool) {
    let id = format!("{}:{}", spec.project, spec.agent);
    match freshen_action(runtime, fresh) {
        FreshenAction::Skip => {}
        FreshenAction::UnsupportedRuntime => {
            eprintln!("warn · {id} (--fresh skipped: {runtime} runtime has no session resume yet)");
        }
        FreshenAction::Freshen => {
            let Some(home) = team_core::session::claude_home() else {
                eprintln!("warn · {id} (--fresh skipped: $HOME unset)");
                return;
            };
            if let Err(e) = team_core::session::freshen_session(&home, &spec.project, &spec.agent) {
                eprintln!("warn · {id} (--fresh: could not move session aside: {e})");
            }
        }
        FreshenAction::WipeCodexSessions => {
            // Move-aside, matching Claude's `.bak` recovery copy. An
            // absent dir just means "nothing to freshen" (first spawn,
            // or already fresh) — silently keep any earlier backup
            // instead of clobbering it with nothing.
            let home = codex_home_dir(root, &spec.project, &spec.agent);
            let sessions = home.join("sessions");
            if !sessions.exists() {
                return;
            }
            let bak = home.join("sessions.bak");
            if let Err(e) = fs::remove_dir_all(&bak) {
                if e.kind() != std::io::ErrorKind::NotFound {
                    eprintln!("warn · {id} (--fresh: could not clear old sessions backup: {e})");
                }
            }
            if let Err(e) = fs::rename(&sessions, &bak) {
                eprintln!("warn · {id} (--fresh: could not move codex sessions aside: {e})");
            }
        }
        FreshenAction::WipeOpencodeSessions => {
            // Same move-aside parity as codex, adapted to opencode's
            // session store: one sqlite db (plus optional -shm/-wal
            // sidecars) instead of a directory tree. An absent db means
            // "nothing to freshen" — silently keep any earlier backup.
            // opencode.json at the home root is untouched.
            let home = opencode_home_dir(root, &spec.project, &spec.agent);
            // "Nothing to freshen" means db AND sidecars all absent —
            // gating on the db alone would strand an orphan -wal/-shm
            // left by a previous partial move.
            if ["agent.db", "agent.db-shm", "agent.db-wal"]
                .iter()
                .all(|n| !home.join(n).exists())
            {
                return;
            }
            let bak = home.join("db.bak");
            if let Err(e) = fs::remove_dir_all(&bak) {
                if e.kind() != std::io::ErrorKind::NotFound {
                    eprintln!("warn · {id} (--fresh: could not clear old db backup: {e})");
                }
            }
            if let Err(e) = fs::create_dir_all(&bak) {
                eprintln!("warn · {id} (--fresh: could not create db backup dir: {e})");
                return;
            }
            for name in ["agent.db", "agent.db-shm", "agent.db-wal"] {
                let src = home.join(name);
                if !src.exists() {
                    continue; // sidecars only exist while WAL is active
                }
                if let Err(e) = fs::rename(&src, bak.join(name)) {
                    eprintln!("warn · {id} (--fresh: could not move {name} aside: {e})");
                }
            }
        }
    }
}

/// `" (fresh)"` when a `--fresh` restart is in effect, else empty. Kept a
/// free function so `up` and `reload` annotate their per-line logs and
/// dry-run output identically.
pub(crate) fn fresh_suffix(fresh: bool) -> &'static str {
    if fresh {
        " (fresh)"
    } else {
        ""
    }
}

/// Render env + MCP for the named project's agents only. Mirrors
/// `render_all_public` but only iterates that project's agents. The
/// unscoped path remains the canonical "ensure dirs and render every
/// project" call.
pub fn render_project_public(compose: &Compose, project_id: &str) -> Result<()> {
    let envs_dir = compose.root.join("state/envs");
    let mcp_dir = compose.root.join("state/mcp");
    let claude_dir = compose.root.join("state/claude");
    fs::create_dir_all(&envs_dir)?;
    fs::create_dir_all(&mcp_dir)?;
    fs::create_dir_all(&claude_dir)?;
    // #428: per-agent activity-heartbeat markers (touched by the rendered
    // hooks, stat()d by the TUI). Created here alongside the other state
    // subdirs so the rendered hook can be a bare `touch` of the marker.
    fs::create_dir_all(compose.root.join("state/heartbeats"))?;
    let bin = super::team_mcp_bin().display().to_string();
    for h in compose.agents().filter(|h| h.project == project_id) {
        let (env, mcp) = render_agent(compose, h, &bin);
        fs::write(env_path(&compose.root, h.project, h.agent), env)?;
        fs::write(mcp_path(&compose.root, h.project, h.agent), mcp)?;
        if let Some(settings) = render_claude_settings(compose, h) {
            fs::write(
                claude_settings_path(&compose.root, h.project, h.agent),
                settings,
            )?;
        }
        // Codex reads MCP servers from `[mcp_servers.*]` tables in its
        // per-agent CODEX_HOME (no --mcp-config flag); render (or clear)
        // that config.toml alongside the JSON.
        write_codex_config(compose, h, &bin)
            .with_context(|| format!("write codex config for {}:{}", h.project, h.agent))?;
        // OpenCode reads MCP servers + instructions from the per-agent
        // opencode.json its OPENCODE_CONFIG points at; render (or clear)
        // it alongside the JSON, same lifecycle as the codex config.
        write_opencode_config(compose, h, &bin)
            .with_context(|| format!("write opencode config for {}:{}", h.project, h.agent))?;
        // Mirror render_all_public: the scoped path must also
        // re-materialize multi-file role_prompt concat or a scoped
        // reload after a source-file edit boots the agent against a
        // stale concat file (zombie-prompt regression).
        write_role_prompt_concat(compose, h)
            .with_context(|| format!("write role_prompt concat for {}:{}", h.project, h.agent))?;
        // #383 Phase 3a: render the per-agent `--agents` JSON (or clear a
        // stale one) alongside the env/mcp/settings files.
        write_subagents_json(compose, h)
            .with_context(|| format!("write sub-agents json for {}:{}", h.project, h.agent))?;
        // #383 Phase 3b: materialize (or clear) the per-agent skills scope
        // dir so `claude --add-dir` surfaces declared skills.
        write_agent_skills(compose, h)
            .with_context(|| format!("write agent skills for {}:{}", h.project, h.agent))?;
    }
    Ok(())
}

/// Pre-accept Claude Code's per-workspace trust dialog for every cwd that
/// will host a `claude-code` agent. Without this, the runtime blocks on a
/// "Do you trust this folder?" prompt the moment it boots, defeating the
/// "agents start working when teamctl up runs" model.
///
/// Running `teamctl up` is itself an explicit "I trust this directory"
/// signal -- the user is about to launch AI agents with tool access in
/// it -- so we record that consent in `~/.claude.json` once instead of
/// making them click through the dialog every restart.
fn ensure_claude_trust(compose: &Compose) -> Result<()> {
    ensure_claude_trust_inner(compose, None)
}

fn ensure_claude_trust_for_project(compose: &Compose, project_id: &str) -> Result<()> {
    ensure_claude_trust_inner(compose, Some(project_id))
}

fn ensure_claude_trust_inner(compose: &Compose, project_id: Option<&str>) -> Result<()> {
    let cwds: BTreeSet<PathBuf> = compose
        .agents()
        .filter(|h| project_id.is_none_or(|id| h.project == id))
        .filter(|h| h.spec.runtime == "claude-code")
        .filter_map(|h| {
            let project = compose
                .projects
                .iter()
                .find(|p| p.project.id == h.project)?;
            let cwd = if project.project.cwd.is_absolute() {
                project.project.cwd.clone()
            } else {
                compose.root.join(&project.project.cwd)
            };
            cwd.canonicalize().ok().or(Some(cwd))
        })
        .collect();

    if cwds.is_empty() {
        return Ok(());
    }
    let Some(home) = std::env::var_os("HOME").map(PathBuf::from) else {
        return Ok(());
    };
    let config_path = home.join(".claude.json");

    let mut config: serde_json::Value = match fs::read_to_string(&config_path) {
        Ok(s) => serde_json::from_str(&s).unwrap_or_else(|_| serde_json::json!({})),
        Err(_) => serde_json::json!({}),
    };
    if !config
        .get("projects")
        .map(|v| v.is_object())
        .unwrap_or(false)
    {
        config["projects"] = serde_json::json!({});
    }
    let projects = config["projects"].as_object_mut().unwrap();

    let mut newly_trusted = Vec::new();
    for cwd in &cwds {
        let key = cwd.display().to_string();
        let entry = projects
            .entry(key.clone())
            .or_insert_with(|| serde_json::json!({}));
        if !entry.is_object() {
            *entry = serde_json::json!({});
        }
        let obj = entry.as_object_mut().unwrap();
        let already = matches!(
            obj.get("hasTrustDialogAccepted"),
            Some(serde_json::Value::Bool(true))
        );
        if !already {
            obj.insert(
                "hasTrustDialogAccepted".into(),
                serde_json::Value::Bool(true),
            );
            newly_trusted.push(key);
        }
    }

    if newly_trusted.is_empty() {
        return Ok(());
    }

    // Write atomically so a concurrent claude reader never sees a
    // half-written config.
    let tmp = config_path.with_extension("json.teamctl.tmp");
    fs::write(&tmp, serde_json::to_string_pretty(&config)?)?;
    fs::rename(&tmp, &config_path)?;

    // Transparency: editing the user's Claude Code config on their behalf is
    // not something we do silently. Tell them — at `up`, where a human is at
    // the terminal — exactly which folders we marked trusted and where, and
    // why. (This is a notice, not a prompt: agent panes stay non-interactive.)
    // User-facing copy: no em-dash (owner house style); singular/plural agree.
    // Wording is neda's polish pass (msg 1634).
    let n = newly_trusted.len();
    let folder_word = if n == 1 { "folder" } else { "folders" };
    let delete_phrase = if n == 1 { "that key" } else { "those keys" };
    eprintln!();
    eprintln!("trust · marked {n} {folder_word} trusted in your Claude Code config");
    eprintln!("        so agents don't stall on Claude's \"trust this folder\" prompt:");
    for path in &newly_trusted {
        eprintln!("{path}");
    }
    eprintln!(
        "        config: {} (key: hasTrustDialogAccepted)",
        config_path.display()
    );
    eprintln!("        running `teamctl up` granted this trust; delete {delete_phrase} to undo.");
    eprintln!();
    Ok(())
}

/// Render per-agent env + MCP files. Called by `up` and `reload`.
pub fn render_all_public(compose: &Compose) -> Result<()> {
    let envs_dir = compose.root.join("state/envs");
    let mcp_dir = compose.root.join("state/mcp");
    let claude_dir = compose.root.join("state/claude");
    fs::create_dir_all(&envs_dir)?;
    fs::create_dir_all(&mcp_dir)?;
    fs::create_dir_all(&claude_dir)?;
    // #428: per-agent activity-heartbeat markers (touched by the rendered
    // hooks, stat()d by the TUI). Created here alongside the other state
    // subdirs so the rendered hook can be a bare `touch` of the marker.
    fs::create_dir_all(compose.root.join("state/heartbeats"))?;
    let bin = super::team_mcp_bin().display().to_string();
    for h in compose.agents() {
        let (env, mcp) = render_agent(compose, h, &bin);
        fs::write(env_path(&compose.root, h.project, h.agent), env)?;
        fs::write(mcp_path(&compose.root, h.project, h.agent), mcp)?;
        if let Some(settings) = render_claude_settings(compose, h) {
            fs::write(
                claude_settings_path(&compose.root, h.project, h.agent),
                settings,
            )?;
        }
        // Codex reads MCP servers from `[mcp_servers.*]` tables in its
        // per-agent CODEX_HOME (no --mcp-config flag); render (or clear)
        // that config.toml alongside the JSON.
        write_codex_config(compose, h, &bin)
            .with_context(|| format!("write codex config for {}:{}", h.project, h.agent))?;
        // OpenCode reads MCP servers + instructions from the per-agent
        // opencode.json its OPENCODE_CONFIG points at; render (or clear)
        // it alongside the JSON, same lifecycle as the codex config.
        write_opencode_config(compose, h, &bin)
            .with_context(|| format!("write opencode config for {}:{}", h.project, h.agent))?;
        // Re-materialize multi-file role_prompt concat unconditionally
        // so any edit to a source file flows into the agent's prompt at
        // the next render — single-form is a no-op (back-compat).
        write_role_prompt_concat(compose, h)
            .with_context(|| format!("write role_prompt concat for {}:{}", h.project, h.agent))?;
        // #383 Phase 3a: render the per-agent `--agents` JSON (or clear a
        // stale one) alongside the env/mcp/settings files.
        write_subagents_json(compose, h)
            .with_context(|| format!("write sub-agents json for {}:{}", h.project, h.agent))?;
        // #383 Phase 3b: materialize (or clear) the per-agent skills scope
        // dir so `claude --add-dir` surfaces declared skills.
        write_agent_skills(compose, h)
            .with_context(|| format!("write agent skills for {}:{}", h.project, h.agent))?;
    }
    Ok(())
}

/// Insert rows for every project + agent so `list_team` has something to return.
pub fn register_all_public(compose: &Compose) -> Result<()> {
    use rusqlite::{params, Connection};
    let db = compose.root.join(&compose.global.broker.path);
    if let Some(parent) = db.parent() {
        fs::create_dir_all(parent)?;
    }
    let conn = Connection::open(&db)?;
    conn.busy_timeout(std::time::Duration::from_secs(5))?;
    conn.pragma_update(None, "journal_mode", "WAL")?;
    conn.pragma_update(None, "foreign_keys", "ON")?;
    team_core::mailbox::ensure(&conn)?;
    for p in &compose.projects {
        conn.execute(
            "INSERT OR IGNORE INTO projects (id, name) VALUES (?1, ?2)",
            params![p.project.id, p.project.name],
        )?;
    }
    for h in compose.agents() {
        conn.execute(
            "INSERT INTO agents (id, project_id, role, runtime, is_manager, reports_to) VALUES (?1,?2,?3,?4,?5,?6)
             ON CONFLICT(id) DO UPDATE SET role=excluded.role, runtime=excluded.runtime, is_manager=excluded.is_manager, reports_to=excluded.reports_to",
            params![
                h.id(),
                h.project,
                h.agent,
                h.spec.runtime,
                if h.is_manager { 1 } else { 0 },
                h.spec.reports_to.as_deref(),
            ],
        )?;
        // Per-agent ACLs.
        let can_dm = serde_json::to_string(&h.spec.can_dm)?;
        let can_bc = serde_json::to_string(&h.spec.can_broadcast)?;
        conn.execute(
            "INSERT INTO agent_acls (agent_id, can_dm_json, can_bcast_json)
             VALUES (?1,?2,?3)
             ON CONFLICT(agent_id) DO UPDATE SET can_dm_json=excluded.can_dm_json, can_bcast_json=excluded.can_bcast_json",
            params![h.id(), can_dm, can_bc],
        )?;
    }

    // Channels + membership. Wipe and rewrite so removed members disappear.
    for p in &compose.projects {
        for ch in &p.channels {
            let cid = format!("{}:{}", p.project.id, ch.name);
            let wildcard = matches!(
                ch.members,
                team_core::compose::ChannelMembers::All(ref s) if s == "*"
            );
            conn.execute(
                "INSERT INTO channels (id, project_id, name, wildcard) VALUES (?1,?2,?3,?4)
                 ON CONFLICT(id) DO UPDATE SET wildcard=excluded.wildcard",
                params![cid, p.project.id, ch.name, if wildcard { 1 } else { 0 }],
            )?;
            conn.execute(
                "DELETE FROM channel_members WHERE channel_id = ?1",
                params![cid],
            )?;
            match &ch.members {
                team_core::compose::ChannelMembers::All(_) => {
                    // Wildcard: join every agent in this project.
                    let agents: Vec<String> = p
                        .managers
                        .keys()
                        .chain(p.workers.keys())
                        .map(|a| format!("{}:{}", p.project.id, a))
                        .collect();
                    for aid in agents {
                        conn.execute(
                            "INSERT OR IGNORE INTO channel_members (channel_id, agent_id) VALUES (?1,?2)",
                            params![cid, aid],
                        )?;
                    }
                }
                team_core::compose::ChannelMembers::Explicit(members) => {
                    for m in members {
                        let aid = format!("{}:{}", p.project.id, m);
                        conn.execute(
                            "INSERT OR IGNORE INTO channel_members (channel_id, agent_id) VALUES (?1,?2)",
                            params![cid, aid],
                        )?;
                    }
                }
            }
        }
    }
    Ok(())
}

/// Write `bin/agent-wrapper.sh`, `bin/boot.sh`, and create `state/` subdirs.
///
/// Both scripts are teamctl-managed infrastructure: they get rewritten on
/// every `teamctl up` so upgrading the binary picks up wrapper fixes (pty
/// handling, argv quoting, ...) and boot-context fixes without users having
/// to rm and re-init their workspace. Customization happens through env vars
/// in the generated `state/envs/<agent>.env`, not by editing the scripts.
pub fn ensure_wrapper_and_dirs(compose: &Compose) -> Result<()> {
    write_managed_executable(&super::agent_wrapper(&compose.root), DEFAULT_WRAPPER)?;
    write_managed_executable(&boot_script_path(&compose.root), DEFAULT_BOOT_SCRIPT)?;
    fs::create_dir_all(compose.root.join("state/envs"))?;
    fs::create_dir_all(compose.root.join("state/mcp"))?;
    Ok(())
}

/// Write a teamctl-managed executable asset and make it `0o755` on unix.
/// Idempotent: only rewrites when the on-disk copy has drifted from the
/// embedded one, so a `teamctl up` that changes nothing leaves mtimes alone.
fn write_managed_executable(path: &Path, content: &str) -> Result<()> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    let needs_write = match fs::read_to_string(path) {
        Ok(existing) => existing != content,
        Err(_) => true,
    };
    if needs_write {
        fs::write(path, content)?;
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(path)?.permissions();
        perms.set_mode(0o755);
        fs::set_permissions(path, perms)?;
    }
    Ok(())
}

const DEFAULT_WRAPPER: &str = include_str!("../../assets/agent-wrapper.sh");
const DEFAULT_BOOT_SCRIPT: &str = include_str!("../../assets/boot.sh");

/// Pull `<root>/.env` (and `<root>/../.env`) into the process so the
/// tmux session for `team-bot` inherits the bot token + chat-ids the
/// operator wrote with `teamctl bot setup`. Mirrors the loader in
/// `cmd::env::run`. Idempotent — never overwrites a value already in
/// the environment.
fn source_dotenv_into_process(root: &std::path::Path) {
    for f in [
        root.join(".env"),
        root.parent().unwrap_or(root).join(".env"),
    ] {
        if !f.is_file() {
            continue;
        }
        let Ok(raw) = fs::read_to_string(&f) else {
            continue;
        };
        for line in raw.lines() {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }
            let line = line.strip_prefix("export ").unwrap_or(line);
            if let Some((k, v)) = line.split_once('=') {
                let v = v.trim().trim_matches('"').trim_matches('\'');
                if std::env::var_os(k).is_none() {
                    // SAFETY: single-threaded CLI startup.
                    unsafe { std::env::set_var(k, v) };
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::DEFAULT_BOOT_SCRIPT;
    use super::DEFAULT_WRAPPER;
    use super::*;
    use std::collections::BTreeMap;
    use team_core::compose::*;
    use team_core::render::role_prompt_concat_path;

    #[test]
    fn registry_entries_groups_by_project_and_sorts_agents() {
        let root = Path::new("/r/a/.team");
        let agents = vec![("main", "scout"), ("main", "compass"), ("ops", "otto")];
        let entries =
            registry_entries(agents.into_iter(), root, "t-", None, "2026-06-13T00:00:00Z");
        assert_eq!(entries.len(), 2);
        // BTreeMap keys → project-sorted; agents sorted within a project.
        assert_eq!(entries[0].project_id, "main");
        assert_eq!(entries[0].agents, vec!["compass", "scout"]);
        assert_eq!(entries[0].root, root);
        assert_eq!(entries[0].tmux_prefix, "t-");
        assert_eq!(entries[0].started_at, "2026-06-13T00:00:00Z");
        assert_eq!(entries[1].project_id, "ops");
        assert_eq!(entries[1].agents, vec!["otto"]);
    }

    #[test]
    fn registry_entries_scoped_records_only_that_project() {
        let agents = vec![("main", "compass"), ("ops", "otto")];
        let entries = registry_entries(
            agents.into_iter(),
            Path::new("/r/a/.team"),
            "t-",
            Some("ops"),
            "T0",
        );
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].project_id, "ops");
        assert_eq!(entries[0].agents, vec!["otto"]);
    }

    #[test]
    fn up_guards_against_same_name_in_a_different_folder() {
        use team_core::registry::{Registry, TeamEntry};
        // A compose for project `main`, loaded from a tempdir (its canonical
        // root) — the self-contained-fixture pattern (no shipped template).
        let team = tempfile::tempdir().unwrap();
        fs::create_dir_all(team.path().join("projects")).unwrap();
        fs::write(
            team.path().join("team-compose.yaml"),
            "version: 2\nsupervisor:\n  type: tmux\n  tmux_prefix: t-\nprojects:\n  - file: projects/main.yaml\n",
        )
        .unwrap();
        fs::write(
            team.path().join("projects/main.yaml"),
            "version: 2\nproject:\n  id: main\n  name: Main\n  cwd: ./workspace\nmanagers:\n  lead:\n    runtime: claude-code\n    role_prompt: roles/lead.md\n",
        )
        .unwrap();
        let compose = Compose::load(team.path()).unwrap();

        let make_reg = |root: PathBuf| {
            let mut reg = Registry::default();
            reg.teams.push(TeamEntry {
                project_id: "main".into(),
                root,
                tmux_prefix: "t-".into(),
                agents: vec!["lead".into()],
                started_at: "T0".into(),
            });
            reg
        };
        // `main` already up at a DIFFERENT, live folder → bail, naming it.
        let other = make_reg(PathBuf::from("/elsewhere/.team"));
        let live = |p: &Path| p == Path::new("/elsewhere/.team/team-compose.yaml");
        let err = guard_no_name_collision_in(&other, &compose, None, &live)
            .expect_err("same name in a different live folder must be refused");
        assert!(
            err.to_string().contains("/elsewhere/.team"),
            "error names the conflicting dir: {err}"
        );
        assert!(
            err.to_string().contains("teamctl down"),
            "error gives actionable resolution: {err}"
        );
        // A re-up of the SAME (project, root) → not a conflict.
        let same = make_reg(compose.root.clone());
        assert!(guard_no_name_collision_in(&same, &compose, None, &live).is_ok());
    }

    #[test]
    fn record_then_clear_roundtrips_a_real_compose() {
        // End-to-end through the actual `up`/`down` glue (Compose::load →
        // compose.agents() → registry_entries → upsert_many → teams.json,
        // then clear) — the closest to the up→down round trip without
        // spawning tmux. The compose is a self-contained fixture written
        // to a tempdir, NOT a shipped template: templates carry
        // `{{project_id}}` placeholders that don't parse before `init`
        // substitution (T-466 regression — a real one broke this test once
        // a template was templatized). The config dir is a second tempdir,
        // so no `$HOME` touch and no env race.
        let team = tempfile::tempdir().unwrap();
        fs::create_dir_all(team.path().join("projects")).unwrap();
        fs::write(
            team.path().join("team-compose.yaml"),
            "version: 2\n\
             supervisor:\n  type: tmux\n  tmux_prefix: treg-\n\
             projects:\n  - file: projects/demo.yaml\n",
        )
        .unwrap();
        fs::write(
            team.path().join("projects/demo.yaml"),
            "version: 2\n\
             project:\n  id: demo\n  name: Demo\n  cwd: ./workspace\n\
             managers:\n  lead:\n    runtime: claude-code\n    role_prompt: roles/lead.md\n\
             workers:\n  helper:\n    runtime: claude-code\n    role_prompt: roles/helper.md\n    reports_to: lead\n",
        )
        .unwrap();
        let compose = Compose::load(team.path()).unwrap();
        let cfg = tempfile::tempdir().unwrap();

        record_in_registry_in(cfg.path(), &compose, None);

        let reg = team_core::registry::load(cfg.path()).unwrap();
        assert_eq!(reg.teams.len(), 1, "one row for the single project");
        let t = &reg.teams[0];
        assert_eq!(t.project_id, "demo");
        assert_eq!(t.root, compose.root, "row keyed on the compose root");
        assert_eq!(t.tmux_prefix, compose.global.supervisor.tmux_prefix);
        assert_eq!(t.agents, vec!["helper", "lead"], "roster folded + sorted");
        assert!(!t.started_at.is_empty(), "started_at stamped");

        // The `down` clear path empties this root.
        team_core::registry::clear(cfg.path(), &compose.root, None).unwrap();
        let after = team_core::registry::load(cfg.path()).unwrap();
        assert!(
            after.teams.is_empty(),
            "whole-root clear empties the registry"
        );
    }

    /// The wrapper's `auto_confirm_known_dialogs` watcher relies on a
    /// fixed set of dialog-header substrings. A silent edit that drops
    /// one of them would re-strand agents at boot or mid-shift, so
    /// pin them here.
    #[test]
    fn freshen_action_gates_on_fresh_and_runtime() {
        // Not fresh → nothing, regardless of runtime. Fresh → move
        // Claude's session aside, move codex's per-agent sessions dir
        // aside, move opencode's per-agent session db aside; gemini
        // stays a warn-and-skip (parity gap), never an abort.
        assert_eq!(freshen_action("claude-code", false), FreshenAction::Skip);
        assert_eq!(freshen_action("codex", false), FreshenAction::Skip);
        assert_eq!(freshen_action("opencode", false), FreshenAction::Skip);
        assert_eq!(freshen_action("claude-code", true), FreshenAction::Freshen);
        assert_eq!(
            freshen_action("codex", true),
            FreshenAction::WipeCodexSessions
        );
        assert_eq!(
            freshen_action("opencode", true),
            FreshenAction::WipeOpencodeSessions
        );
        assert_eq!(
            freshen_action("gemini", true),
            FreshenAction::UnsupportedRuntime
        );
    }

    /// The auto-confirm watcher dismisses the one-shot dialogs that would
    /// otherwise strand a headless pane. `Quick safety check:` is the
    /// first-run trust-folder prompt that `--permission-mode auto` (the
    /// headless default since 0.8.7) raises — the watcher didn't match it,
    /// so an auto session froze at boot whenever the pre-trust missed. It
    /// is a one-time trust gate, not `auto`'s risky-action classifier, so
    /// accepting it keeps the safety gate intact; the watcher must never
    /// match `auto`'s risky-action prompts. Because the header is ordinary
    /// prose, the watcher requires it to co-occur with the menu line
    /// `trust this folder` before sending Enter — pin both so a future edit
    /// can't drop the co-occurrence guard and reintroduce stray Enters. The
    /// MCP-enable dialog is auto-accepted the same way (Enter enables the
    /// discovered project MCP servers), gated on its own two-string
    /// co-occurrence so prose can't trip it.
    #[test]
    fn wrapper_auto_confirm_patterns_present() {
        for marker in [
            "Loading development channels",
            "Bypass Permissions mode",
            "Stop and wait for limit to reset",
            "Quick safety check:",
            "MCP servers may execute code",
            "auto_confirm_known_dialogs",
        ] {
            assert!(
                DEFAULT_WRAPPER.contains(marker),
                "DEFAULT_WRAPPER missing marker: {marker}",
            );
        }
        // The trust-folder and MCP-enable dialogs must each be gated on a
        // two-string co-occurrence, not a bare match: both greps per dialog
        // must be present in the watcher.
        assert!(
            DEFAULT_WRAPPER.contains("grep -q 'Quick safety check:'")
                && DEFAULT_WRAPPER.contains("grep -q 'trust this folder'"),
            "watcher must require 'Quick safety check:' AND 'trust this folder' to co-occur",
        );
        assert!(
            DEFAULT_WRAPPER.contains("grep -q 'MCP servers may execute code'")
                && DEFAULT_WRAPPER.contains("grep -q 'Enter to confirm · Esc'"),
            "watcher must require 'MCP servers may execute code' AND the 'Enter to confirm · Esc' \
             footer chrome to co-occur",
        );
    }

    /// Owner-reported crash-loop (2026-06-13): two installs that share a
    /// `project.id` derive the same deterministic session UUID; the
    /// resume-probe globs every cwd slug and matches the *other* install's
    /// jsonl, and claude — scoped to this cwd — can't resume it, exiting
    /// non-zero forever. The wrapper self-heals: after a `--resume` launch
    /// exits non-zero it retries ONCE, forcing a cwd-scoped `--session-id`
    /// (per-cwd, verified) so it opens a fresh local session on a collision
    /// and errors harmlessly on a genuine crash. Pin the load-bearing pieces
    /// so a future wrapper edit can't silently drop the heal and bring the
    /// crash-loop back.
    #[test]
    fn wrapper_self_heals_resume_collision() {
        // The --resume branch must tag the launch so the heal can tell a
        // resume from a fresh launch.
        assert!(
            DEFAULT_WRAPPER.contains("--resume \"$CLAUDE_SESSION_ID\"")
                && DEFAULT_WRAPPER.contains("RESUMED=1"),
            "wrapper must mark RESUMED=1 when launching with --resume",
        );
        // The one-shot fallback forces a fresh cwd-scoped --session-id.
        assert!(
            DEFAULT_WRAPPER.contains("[ \"${FORCE_FRESH_SESSION:-0}\" = 1 ]")
                && DEFAULT_WRAPPER.contains("--session-id \"$CLAUDE_SESSION_ID\""),
            "wrapper must force a fresh --session-id launch when FORCE_FRESH_SESSION is set",
        );
        // The trigger: a resumed launch that exits non-zero retries exactly
        // once (guarded by RESUMED and the one-shot flag, so it can't loop).
        assert!(
            DEFAULT_WRAPPER.contains("[ \"$ec\" -ne 0 ]")
                && DEFAULT_WRAPPER.contains("[ \"${RESUMED:-0}\" = 1 ]")
                && DEFAULT_WRAPPER.contains("FORCE_FRESH_SESSION=1"),
            "wrapper must retry-fresh only after a resumed launch exits non-zero",
        );
        // Order is load-bearing and a plain substring pin can't catch a
        // reorder: the retry must arm the one-shot and `continue` BEFORE the
        // reset clears it. If a future edit moved `continue` below the reset
        // (defeating the heal) or dropped the reset (risking a loop), this
        // contiguous block changes and the test fails.
        assert!(
            DEFAULT_WRAPPER.contains(
                "        FORCE_FRESH_SESSION=1\n        continue\n    fi\n    FORCE_FRESH_SESSION=0\n"
            ),
            "the retry must set the one-shot and `continue` before the reset clears it",
        );
        // Per-iteration reset of RESUMED guards a stale resume flag from
        // carrying into a later iteration and mis-arming the heal.
        assert!(
            DEFAULT_WRAPPER.contains("RESUMED=0"),
            "wrapper must reset RESUMED each iteration",
        );
    }

    /// #383 Phase 3a: the wrapper threads per-agent sub-agents via
    /// `--agents` when render wrote the JSON file (guarded by `[ -f ]`, so
    /// agents with no `subagents:` pass no flag). Pin the marker so a silent
    /// wrapper edit can't drop it and strand declared sub-agents.
    #[test]
    fn wrapper_threads_subagents_via_agents_flag() {
        assert!(
            DEFAULT_WRAPPER.contains("--agents \"$(cat \"$CLAUDE_AGENTS_JSON\")\""),
            "wrapper must pass --agents from CLAUDE_AGENTS_JSON",
        );
    }

    /// #383 Phase 3b: the wrapper threads per-agent skills via `--add-dir`
    /// when render materialized the scope dir (guarded by `[ -d ]`, so
    /// agents with no `skills:` pass no flag). Pin the marker so a silent
    /// wrapper edit can't drop it and strand declared skills.
    #[test]
    fn wrapper_threads_skills_via_add_dir_flag() {
        assert!(
            DEFAULT_WRAPPER.contains("--add-dir \"$CLAUDE_AGENT_SCOPE\""),
            "wrapper must pass --add-dir from CLAUDE_AGENT_SCOPE",
        );
    }

    /// T-361: headless claude-code agents default to `--permission-mode
    /// auto` and no longer pass `--dangerously-skip-permissions`. The
    /// attended opt-out keys off PERMISSION_MODE, which `render()` omits for
    /// agents with no `permission_mode:` — so under `set -u` the comparison
    /// must default the var. Pin the new shape so a silent edit can't bring
    /// back the bypass-everything flag, drop the auto default, or break the
    /// unset-safe attended branch.
    #[test]
    fn wrapper_defaults_headless_to_permission_mode_auto() {
        assert!(
            DEFAULT_WRAPPER.contains("--permission-mode \"${PERMISSION_MODE:-auto}\""),
            "wrapper must default headless agents to --permission-mode auto",
        );
        assert!(
            !DEFAULT_WRAPPER.contains("--dangerously-skip-permissions"),
            "wrapper must not pass --dangerously-skip-permissions (#361)",
        );
        assert!(
            DEFAULT_WRAPPER.contains("[ \"${PERMISSION_MODE:-}\" = \"attended\" ]"),
            "wrapper must keep the set -u-safe attended opt-out branch",
        );
    }

    /// The `codex)` case body of the wrapper, sliced between the case
    /// label and its `;;` terminator — so negative assertions (no
    /// `--mcp-config`) can't be fouled by the claude-code branch's
    /// legitimate use of the same flag.
    fn wrapper_codex_branch() -> &'static str {
        let start = DEFAULT_WRAPPER
            .find("codex)")
            .expect("DEFAULT_WRAPPER has a codex) case");
        let body = &DEFAULT_WRAPPER[start..];
        let end = body.find(";;").expect("codex) case terminated by ;;");
        &body[..end]
    }

    /// Codex launch correctness: the real Codex CLI has no --mcp-config
    /// or --instructions flags (TypeScript-era leftovers). MCP rides the
    /// per-agent CODEX_HOME config.toml; instructions + reasoning effort
    /// ride the repeatable `-c KEY=VALUE` override. Pin the shapes so a
    /// silent wrapper edit can't reintroduce the phantom flags and break
    /// every codex spawn at argv parsing.
    #[test]
    fn wrapper_codex_uses_config_overrides_not_phantom_flags() {
        let codex = wrapper_codex_branch();
        assert!(
            codex.contains("-c \"model_reasoning_effort=$EFFORT\""),
            "codex branch must pass effort via -c model_reasoning_effort",
        );
        assert!(
            codex.contains("-c \"model_instructions_file=$SYSTEM_PROMPT_PATH\""),
            "codex branch must pass the role prompt via -c model_instructions_file",
        );
        // Match the full flag usage, not the bare flag name — the codex
        // branch's comments legitimately name the nonexistent flags to
        // explain why the -c overrides are used instead.
        assert!(
            !codex.contains("--mcp-config \"$MCP_CONFIG\""),
            "codex has no --mcp-config flag — MCP goes through CODEX_HOME/config.toml",
        );
        assert!(
            !codex.contains("--instructions \"$SYSTEM_PROMPT_PATH\""),
            "codex has no --instructions flag",
        );
        assert!(
            codex.contains("export CODEX_HOME"),
            "codex branch must export the per-agent CODEX_HOME",
        );
    }

    /// Codex permission mapping mirrors the claude-code branch's
    /// semantics: attended → codex's own interactive default (no flags),
    /// bypassPermissions → --yolo, headless default → `-a never` plus the
    /// workspace-write sandbox (approvals can't prompt in an unattended
    /// pane; the sandbox boundary is the guardrail).
    #[test]
    fn wrapper_codex_permission_mapping_present() {
        let codex = wrapper_codex_branch();
        assert!(
            codex.contains("-a never -s workspace-write"),
            "codex headless default must be -a never -s workspace-write",
        );
        assert!(
            codex.contains("--yolo"),
            "codex bypassPermissions must map to --yolo",
        );
        assert!(
            codex.contains("[ \"${PERMISSION_MODE:-}\" = \"attended\" ]"),
            "codex branch must keep the set -u-safe attended opt-out",
        );
    }

    /// Codex's first-run "trust this folder" dialog defaults to the
    /// trust option, so the auto-confirm watcher accepts it with one
    /// Enter — otherwise the first spawn in a new directory strands an
    /// unattended pane. The dialog wording has drifted across codex
    /// releases, so pin BOTH observed variants (and the codex arm
    /// opting into the watcher) so a silent edit can't re-strand codex
    /// boots on either wording.
    #[test]
    fn wrapper_codex_trust_dialog_auto_confirmed() {
        assert!(
            DEFAULT_WRAPPER.contains("Yes, I trust this folder"),
            "auto-confirm watcher must match codex's classic trust-folder wording",
        );
        assert!(
            DEFAULT_WRAPPER.contains("Yes, allow Codex to work in this folder"),
            "auto-confirm watcher must match codex's newer trust-folder wording",
        );
        assert!(
            DEFAULT_WRAPPER.contains("Do you trust the contents of this directory"),
            "auto-confirm watcher must match codex 0.144's trust-dialog wording",
        );
        // Co-occurrence guard: the codex wordings must only fire alongside
        // dialog chrome, or an agent that merely PRINTS a wording in prose
        // (this team discusses these dialogs constantly) triggers a stray
        // Enter. "Yes, I trust this folder" doubles as claude's own trust
        // option label, which makes the single-string form doubly unsafe.
        assert!(
            DEFAULT_WRAPPER.contains("Press enter to continue|2\\. No"),
            "codex trust match must require dialog chrome co-occurrence",
        );
        assert!(
            wrapper_codex_branch().contains("AUTO_CONFIRM=1"),
            "codex branch must opt into the auto-confirm watcher",
        );
    }

    /// Codex session resume: the per-agent CODEX_HOME isolates the
    /// session store, so the wrapper probes it for rollout JSONLs
    /// (sessions/YYYY/MM/DD layout) and reopens the newest one with
    /// `codex resume --last` — subcommand before flags. The resume path
    /// must NOT re-inject the bootstrap positional (whether `resume`
    /// accepts a PROMPT is unverified upstream); a one-shot tmux nudge
    /// re-grounds the agent instead. Pin the probe glob, the subcommand
    /// shape, the fresh-only positional, and the nudge so a silent edit
    /// can't regress any half.
    #[test]
    fn wrapper_codex_resume_branch_present() {
        let codex = wrapper_codex_branch();
        assert!(
            codex.contains("set -- resume --last"),
            "codex resume path must lead the argv with the resume subcommand",
        );
        assert!(
            codex.contains("\"$CODEX_HOME/sessions\"/*/*/*/*.jsonl"),
            "codex resume probe must glob the sessions/YYYY/MM/DD rollout layout",
        );
        assert!(
            codex.contains("[ \"$RESUMED\" = 0 ] && set -- \"$@\" \"$BOOTSTRAP_PROMPT\""),
            "codex must pass the bootstrap positional on fresh spawns only",
        );
        assert!(
            DEFAULT_WRAPPER.contains("nudge_resumed_session"),
            "wrapper must define the resumed-session wake-up nudge",
        );
        assert!(
            DEFAULT_WRAPPER.contains("Restarted mid-shift: call inbox_peek"),
            "nudge must point the resumed agent at inbox_peek catch-up",
        );
        // The nudge must re-fire Enter after a beat: a resumed codex TUI
        // loads history before the composer goes live, so the first Enter
        // can be eaten mid-boot and the text strands unsubmitted (observed
        // live on codex 0.144.3).
        let nudge_start = DEFAULT_WRAPPER
            .find("nudge_resumed_session() {")
            .expect("nudge helper present");
        let nudge = &DEFAULT_WRAPPER[nudge_start..nudge_start + 700];
        assert!(
            nudge.matches("send-keys").count() >= 2,
            "nudge must send a trailing bare Enter to beat the resume-boot race",
        );
    }

    /// Resume crash-loop self-heal: a corrupt session store makes the
    /// resume path (`codex resume --last`, `opencode -c`) die instantly
    /// on every boot, and the resume probe re-matches it forever. The
    /// wrapper counts consecutive fast resume-path exits (a single
    /// counter shared by both runtimes — the probes set the shared
    /// RESUMED flag) and moves the runtime's session store aside after
    /// the third, so the next boot is fresh. Pin the counter, the
    /// threshold, and both move-aside paths so a silent edit can't
    /// reintroduce the infinite crash loop for either runtime.
    #[test]
    fn wrapper_resume_crash_loop_self_heal_present() {
        for marker in [
            "RESUME_FAST_FAILS=$((RESUME_FAST_FAILS + 1))",
            "[ \"$RESUME_FAST_FAILS\" -ge 3 ]",
            "$CODEX_HOME/sessions.crash-bak",
            "$OC_HOME/db.crash-bak",
            "mv \"$OPENCODE_DB\" \"$OPENCODE_DB-shm\" \"$OPENCODE_DB-wal\" \"$OC_HOME/db.crash-bak/\"",
        ] {
            assert!(
                DEFAULT_WRAPPER.contains(marker),
                "DEFAULT_WRAPPER missing marker: {marker}",
            );
        }
    }

    /// The opencode case body of the wrapper, sliced between the case
    /// label and its `;;` terminator — same trap as
    /// [`wrapper_codex_branch`]: negative assertions must not be fouled
    /// by other branches' legitimate use of the same flags. (The
    /// wrapper itself never writes the literal case-label string in
    /// comments outside the branch, so `find` lands on the real label.)
    fn wrapper_opencode_branch() -> &'static str {
        let start = DEFAULT_WRAPPER
            .find("opencode)")
            .expect("DEFAULT_WRAPPER has an opencode case");
        let body = &DEFAULT_WRAPPER[start..];
        let end = body.find(";;").expect("opencode case terminated by ;;");
        &body[..end]
    }

    /// OpenCode launch correctness: MCP + instructions ride the
    /// per-agent OPENCODE_CONFIG json (no --mcp-config flag), the TUI
    /// auto-upgrades the shared binary in place unless
    /// OPENCODE_DISABLE_AUTOUPDATE=1 is exported (verified
    /// 1.17.13→1.17.18 mid-run), missing auth silently falls back to
    /// free anonymous models (so the wrapper must warn), and `effort:`
    /// has no TUI mapping (`--variant` is run-subcommand only). Pin all
    /// four so a silent wrapper edit can't regress any of them.
    #[test]
    fn wrapper_opencode_launch_shape_present() {
        let opencode = wrapper_opencode_branch();
        assert!(
            opencode.contains("export OPENCODE_DISABLE_AUTOUPDATE=1"),
            "opencode branch must disable the in-place binary autoupdate",
        );
        assert!(
            opencode.contains("$HOME/.local/share/opencode/auth.json")
                && opencode.contains("free anonymous models"),
            "opencode branch must warn when auth.json is absent (silent free-tier fallback)",
        );
        assert!(
            opencode.contains("--model \"$MODEL\""),
            "opencode branch must thread model (provider/model form)",
        );
        assert!(
            !opencode.contains("--mcp-config \"$MCP_CONFIG\""),
            "opencode has no --mcp-config flag — MCP goes through OPENCODE_CONFIG json",
        );
        assert!(
            !opencode.contains("--effort") && !opencode.contains("--variant \""),
            "effort is unsupported on opencode v1 — no flag may be wired",
        );
        assert!(
            !opencode.contains("AUTO_CONFIRM=1"),
            "opencode boots straight to the composer — no dialogs to auto-confirm",
        );
    }

    /// OpenCode permission mapping: attended keeps opencode's own
    /// interactive ask-prompts; everything else — including
    /// bypassPermissions, since opencode has no full-bypass equivalent
    /// (--yolo closed not-planned upstream) — maps to `--auto`
    /// (auto-approve anything not explicitly denied).
    #[test]
    fn wrapper_opencode_permission_mapping_present() {
        let opencode = wrapper_opencode_branch();
        assert!(
            opencode.contains("set -- \"$@\" --auto"),
            "opencode headless default must be --auto",
        );
        // Match the full flag usage, not the bare flag name — the
        // branch's comments legitimately name codex's --yolo to explain
        // why bypassPermissions downgrades to --auto here.
        assert!(
            !opencode.contains("set -- \"$@\" --yolo"),
            "opencode has no full-bypass flag — bypassPermissions downgrades to --auto",
        );
        assert!(
            opencode.contains("[ \"${PERMISSION_MODE:-}\" = \"attended\" ]"),
            "opencode branch must keep the set -u-safe attended opt-out",
        );
    }

    /// OpenCode session resume: the per-agent OPENCODE_DB isolates the
    /// session store, so the wrapper probes for the db file and
    /// continues the prior conversation with `-c` — scoped to the cwd
    /// within that db, which is exact per agent. The resume path must
    /// NOT pass `--prompt` (the one-shot nudge re-grounds the agent);
    /// fresh spawns pass the bootstrap via `--prompt`, a flag, not a
    /// positional. Pin the probe, the flag selection, and the set -u
    /// defaults for the env-file-rendered vars.
    #[test]
    fn wrapper_opencode_resume_branch_present() {
        let opencode = wrapper_opencode_branch();
        assert!(
            opencode.contains("[ -n \"$OPENCODE_DB\" ] && [ -f \"$OPENCODE_DB\" ]"),
            "opencode resume probe must check the per-agent db file",
        );
        assert!(
            opencode.contains("set -- \"$@\" -c"),
            "opencode resume path must continue via -c",
        );
        assert!(
            opencode
                .contains("[ \"$RESUMED\" = 0 ] && set -- \"$@\" --prompt \"$BOOTSTRAP_PROMPT\""),
            "opencode must pass the bootstrap via --prompt on fresh spawns only",
        );
        for marker in [": \"${OPENCODE_DB:=}\"", ": \"${OPENCODE_CONFIG:=}\""] {
            assert!(
                DEFAULT_WRAPPER.contains(marker),
                "DEFAULT_WRAPPER missing set -u default: {marker}",
            );
        }
    }

    /// T-174: the wrapper picks `--resume` vs `--session-id` by
    /// probing the on-disk session jsonl. A silent edit that drops
    /// the resume branch would re-trigger "Session ID is already in
    /// use" on the second `teamctl up` under claude 2.1.138+; an edit
    /// that drops the create branch would break first-launch.
    /// Pin both markers plus the glob shape so neither half regresses.
    #[test]
    fn wrapper_session_id_resume_branch_present() {
        for marker in [
            "--session-id \"$CLAUDE_SESSION_ID\"",
            "--resume \"$CLAUDE_SESSION_ID\"",
            "$HOME/.claude/projects/",
            "$CLAUDE_SESSION_ID.jsonl",
        ] {
            assert!(
                DEFAULT_WRAPPER.contains(marker),
                "DEFAULT_WRAPPER missing marker: {marker}",
            );
        }
    }

    /// T-190: the wrapper runs under `set -u`. Both
    /// `CLAUDE_SESSION_ID` and `CLAUDE_SESSION_NAME` are rendered
    /// into the env file only for `runtime: claude-code` agents
    /// (team-core::render::render_env). If they're absent for any
    /// reason — env file from an older render, write race, future
    /// runtime variant — the unguarded `[ -n "$CLAUDE_SESSION_ID" ]`
    /// reference aborts the wrapper, the tmux pane closes, and the
    /// supervisor marks the agent stopped without a diagnostic.
    /// The defaults at the top of the wrapper close that hole; a
    /// silent edit that drops them re-opens the failure mode.
    #[test]
    fn wrapper_session_vars_have_set_u_defaults() {
        for marker in [
            ": \"${CLAUDE_SESSION_ID:=}\"",
            ": \"${CLAUDE_SESSION_NAME:=}\"",
        ] {
            assert!(
                DEFAULT_WRAPPER.contains(marker),
                "DEFAULT_WRAPPER missing marker: {marker}",
            );
        }
    }

    /// T-190: macOS ships bash 3.2 as `/bin/sh`. Bash 3.2 has a
    /// parser bug where `${VAR:=DEFAULT}` cannot reliably parse
    /// escape sequences inside DEFAULT (backslash-backtick,
    /// backslash-quote). The wrapper's BOOTSTRAP_PROMPT default
    /// contains both, so the pre-T-190 `${BOOTSTRAP_PROMPT:=...}`
    /// shape aborted every spawn on macOS — the 0.8.0 fresh-install
    /// regression. The fix is conditional assignment, not parameter
    /// expansion: pin that BOTH the `:=` form is GONE and the
    /// `[ -z ]` plain-assignment shape is present, so a future
    /// cleanup can't silently regress macOS again.
    #[test]
    fn wrapper_bootstrap_prompt_default_is_macos_safe() {
        assert!(
            !DEFAULT_WRAPPER.contains("${BOOTSTRAP_PROMPT:="),
            "DEFAULT_WRAPPER still uses ${{VAR:=DEFAULT}} for \
             BOOTSTRAP_PROMPT — that shape is bash-3.2-fatal on \
             macOS when DEFAULT contains escape sequences. Keep \
             the conditional-assignment form.",
        );
        for marker in [
            "if [ -z \"${BOOTSTRAP_PROMPT:-}\" ]; then",
            "BOOTSTRAP_PROMPT=\"Begin your shift as ${AGENT}.",
        ] {
            assert!(
                DEFAULT_WRAPPER.contains(marker),
                "DEFAULT_WRAPPER missing marker: {marker}",
            );
        }
    }

    /// The bootstrap default block, sliced from the `[ -z ]` guard to its
    /// closing `fi` — so per-runtime prompt assertions can't be fouled by
    /// text elsewhere in the wrapper.
    fn wrapper_bootstrap_block() -> &'static str {
        let start = DEFAULT_WRAPPER
            .find("if [ -z \"${BOOTSTRAP_PROMPT:-}\" ]; then")
            .expect("DEFAULT_WRAPPER has the bootstrap default guard");
        let body = &DEFAULT_WRAPPER[start..];
        let end = body.find("\nfi").expect("bootstrap guard closed by fi");
        &body[..end]
    }

    /// Delivery differs per runtime, so the bootstrap default must too:
    /// claude-code keeps the Channels text (events pushed into the
    /// session, no polling); every other runtime gets the honest story —
    /// team-mcp types `📬 sender: "preview…" (+N more)` nudges into the
    /// pane, and the agent starts with an `inbox_peek` catch-up. Telling
    /// a non-claude agent "traffic is delivered as channel events"
    /// strands it idle forever, because its runtime drops MCP
    /// notifications.
    #[test]
    fn wrapper_bootstrap_prompt_dispatches_on_runtime() {
        let block = wrapper_bootstrap_block();
        assert!(
            block.contains("case \"$RUNTIME\" in"),
            "bootstrap default must dispatch on $RUNTIME",
        );
        let (claude, other) = block
            .split_once("*)")
            .expect("bootstrap case has a catch-all arm");
        assert!(
            claude.contains("Claude Code Channels") && claude.contains("you do not need to poll"),
            "claude-code prompt must keep the Channels delivery text",
        );
        assert!(
            other.contains("Call inbox_peek now"),
            "non-claude prompt must instruct the startup inbox_peek catch-up",
        );
        assert!(
            other.contains("(+N more)")
                && other.contains("inbox_read")
                && other.contains("inbox_ack"),
            "non-claude prompt must describe the nudge's preview shape and the drain loop",
        );
        assert!(
            !other.to_lowercase().contains("channel"),
            "non-claude prompt must not claim channel-event delivery",
        );
    }

    fn compose_with_multi_role_prompt(root: &Path, project_id: &str) -> Compose {
        let mut managers = BTreeMap::new();
        managers.insert(
            "mgr".into(),
            Agent {
                runtime: "claude-code".into(),
                model: None,
                role_prompt: Some(RolePrompt::Multiple(vec![
                    PathBuf::from("roles/_base.md"),
                    PathBuf::from("roles/mgr.md"),
                ])),
                permission_mode: None,
                autonomy: "low_risk_only".into(),
                can_dm: vec![],
                can_broadcast: vec![],
                reports_to: None,
                on_rate_limit: None,
                effort: None,
                ultracode: false,
                interfaces: None,
                display_name: None,
                hooks: vec![],
                mcps: Default::default(),
                subagents: vec![],
                skills: vec![],
            },
        );
        Compose {
            root: root.to_path_buf(),
            global: Global {
                version: team_core::compose::SchemaVersion::new("2.0.0"),
                broker: Default::default(),
                supervisor: Default::default(),
                budget: Default::default(),
                hitl: Default::default(),
                rate_limits: Default::default(),
                interfaces: vec![],
                projects: vec![],
                attachments: Default::default(),
            },
            projects: vec![Project {
                version: 2,
                project: ProjectMeta {
                    id: project_id.into(),
                    name: project_id.into(),
                    cwd: root.to_path_buf(),
                },
                channels: vec![],
                managers,
                workers: Default::default(),
                interfaces: None,
            }],
        }
    }

    #[test]
    fn render_project_public_writes_role_prompt_concat() {
        // Regression for T-103 qa finding: the scoped reload path
        // must materialize the multi-file role_prompt concat too,
        // else editing a source file and running
        // `teamctl reload <project>` boots the agent against a stale
        // concat file (zombie-prompt).
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        std::fs::create_dir_all(root.join("roles")).unwrap();
        std::fs::create_dir_all(root.join("state")).unwrap();
        std::fs::write(root.join("roles/_base.md"), "BASE").unwrap();
        std::fs::write(root.join("roles/mgr.md"), "MGR").unwrap();

        let compose = compose_with_multi_role_prompt(root, "p");
        render_project_public(&compose, "p").expect("render_project_public");

        // #428: render must create the heartbeat dir so the rendered bare
        // `touch` hook has somewhere to write. If this regresses, the dir is
        // missing => `touch` fails => no marker => every agent reads Idle
        // (the safe failure, but a silent loss of the working signal).
        assert!(
            root.join("state/heartbeats").is_dir(),
            "render must create state/heartbeats/"
        );

        let concat = role_prompt_concat_path(root, "p", "mgr");
        let got = std::fs::read_to_string(&concat).expect("concat file written");
        assert_eq!(got, "BASE\n\n\n\nMGR");

        // No zombies: a source edit + re-render must update the concat.
        std::fs::write(root.join("roles/_base.md"), "BASE-v2").unwrap();
        render_project_public(&compose, "p").expect("render_project_public re-run");
        let got = std::fs::read_to_string(&concat).unwrap();
        assert_eq!(got, "BASE-v2\n\n\n\nMGR");
    }

    /// Serializes the HOME-mutating test(s) in this binary; `$HOME` is
    /// process-global, so a concurrent reader/writer would race.
    static HOME_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// Point `$HOME` at `home` for the guard's lifetime, then restore it, so
    /// the trust write lands in a throwaway `.claude.json`, never the real one.
    struct HomeGuard {
        _lock: std::sync::MutexGuard<'static, ()>,
        prev: Option<std::ffi::OsString>,
    }

    impl HomeGuard {
        fn set(home: &Path) -> Self {
            let lock = HOME_LOCK.lock().unwrap_or_else(|e| e.into_inner());
            let prev = std::env::var_os("HOME");
            // SAFETY: HOME_LOCK serializes every HOME mutation in this binary,
            // matching the `unsafe { set_var }` convention elsewhere in up.rs.
            unsafe { std::env::set_var("HOME", home) };
            Self { _lock: lock, prev }
        }
    }

    impl Drop for HomeGuard {
        fn drop(&mut self) {
            // SAFETY: still holding HOME_LOCK (see `set`).
            match &self.prev {
                Some(v) => unsafe { std::env::set_var("HOME", v) },
                None => unsafe { std::env::remove_var("HOME") },
            }
        }
    }

    /// `ensure_claude_trust` pre-accepts Claude's workspace-trust dialog by
    /// writing `hasTrustDialogAccepted: true` under each claude-code agent's
    /// cwd, and is a no-op on a second run (trust already on disk) so the `up`
    /// notice doesn't nag on every restart.
    #[test]
    fn ensure_claude_trust_writes_key_then_is_idempotent() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join(".team");
        std::fs::create_dir_all(root.join("projects")).unwrap();
        std::fs::write(
            root.join("team-compose.yaml"),
            r#"
version: 2
broker:
  type: sqlite
  path: state/mailbox.db
supervisor:
  type: tmux
  tmux_prefix: a-
projects:
  - file: projects/hello.yaml
"#,
        )
        .unwrap();
        std::fs::write(
            root.join("projects/hello.yaml"),
            r#"
version: 2
project:
  id: hello
  name: Hello
  cwd: .
managers:
  manager:
    runtime: claude-code
    model: claude-opus-4-8
"#,
        )
        .unwrap();
        let compose = Compose::load(&root).expect("compose loads");

        let home = dir.path().join("home");
        std::fs::create_dir_all(&home).unwrap();
        let config_path = home.join(".claude.json");
        let _guard = HomeGuard::set(&home);

        // First run writes the trust key for the agent's (canonicalized) cwd.
        ensure_claude_trust(&compose).expect("first ensure_claude_trust");
        let cfg: serde_json::Value = serde_json::from_str(
            &std::fs::read_to_string(&config_path).expect("wrote .claude.json"),
        )
        .expect("config is valid json");
        let key = root.canonicalize().unwrap().display().to_string();
        assert_eq!(
            cfg["projects"][&key]["hasTrustDialogAccepted"],
            serde_json::Value::Bool(true),
            "trust key must be written for the agent cwd; config: {cfg}",
        );

        // Second run is a no-op: trust is on disk, so nothing is rewritten
        // (and the operator notice does not re-fire).
        let before = std::fs::read_to_string(&config_path).unwrap();
        ensure_claude_trust(&compose).expect("second ensure_claude_trust");
        let after = std::fs::read_to_string(&config_path).unwrap();
        assert_eq!(before, after, "second run must not rewrite the config");
    }

    /// #430: the boot-context asset must carry the REQUIRED `hookEventName`
    /// inside `hookSpecificOutput` — without it Claude Code silently drops
    /// `additionalContext` and the hook injects nothing while still exiting 0
    /// (the exact silent-no-op the de-risk pass caught). Pin that, plus the
    /// `SessionStart` event name and the wake-aware verb mapping, so a future
    /// edit can't quietly hollow the asset out.
    #[test]
    fn boot_script_emits_session_start_context() {
        assert!(
            DEFAULT_BOOT_SCRIPT.contains(r#""hookEventName":"SessionStart""#),
            "boot.sh must emit the required hookEventName or CC drops additionalContext"
        );
        assert!(
            DEFAULT_BOOT_SCRIPT.contains("additionalContext"),
            "boot.sh must emit additionalContext"
        );
        for verb in ["resumed", "cleared context", "compacted", "booted"] {
            assert!(
                DEFAULT_BOOT_SCRIPT.contains(verb),
                "boot.sh missing wake-aware verb: {verb}"
            );
        }
        // POSIX `/bin/sh` shebang + `set -u`, matching the wrapper's contract
        // (the command runs in the agent's shell, macOS bash 3.2 included).
        assert!(DEFAULT_BOOT_SCRIPT.starts_with("#!/bin/sh"));
        assert!(DEFAULT_BOOT_SCRIPT.contains("set -u"));
        // #439: the two source-specific extensions and the argv-optional
        // guards. The `${1:-}` / `${2:-}` reads keep the script `set -u`-safe
        // when an older rendered hook passes no argv (downtime then omits).
        assert!(
            DEFAULT_BOOT_SCRIPT.contains("${1:-}") && DEFAULT_BOOT_SCRIPT.contains("${2:-}"),
            "boot.sh must guard its optional argv under set -u"
        );
        assert!(
            DEFAULT_BOOT_SCRIPT.contains("You were down for"),
            "boot.sh must carry the downtime sentence"
        );
        assert!(
            DEFAULT_BOOT_SCRIPT.contains("Re-anchor before continuing"),
            "boot.sh must carry the compact re-anchor copy"
        );
    }

    /// #439: execute the real boot.sh asset on the host shell and assert the
    /// wake notice per `source` × file-state. Each run exercises only its
    /// host's native branch — macOS takes the BSD `stat -f`/`date -r` path,
    /// Linux the GNU `stat -c`/`date -d` path — so it is the CI matrix across
    /// BOTH the macos-14 and ubuntu-24.04 legs that proves the two portability
    /// fallbacks on real hardware, not just reasoned about. Mtimes are set
    /// precisely via `File::set_modified` (in std since 1.75, under our 1.86
    /// MSRV) so the buckets are deterministic.
    #[test]
    fn boot_script_reports_downtime_and_reanchor() {
        use std::io::Write;
        use std::process::{Command, Stdio};
        use std::time::{Duration, SystemTime};

        let dir = tempfile::tempdir().unwrap();
        let script = dir.path().join("boot.sh");
        std::fs::write(&script, DEFAULT_BOOT_SCRIPT).unwrap();

        // Run boot.sh under /bin/sh with the given stdin source + argv paths,
        // returning the parsed `additionalContext`. Parsing as JSON also
        // enforces the ASCII no-escaping contract: a stray quote in any
        // injected copy would break this parse and fail the test.
        let run = |source: &str, args: &[&std::path::Path]| -> String {
            let mut cmd = Command::new("/bin/sh");
            cmd.arg(&script);
            for a in args {
                cmd.arg(a);
            }
            cmd.stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .stderr(Stdio::null());
            let mut child = cmd.spawn().unwrap();
            let payload = format!("{{\"source\":\"{source}\"}}");
            child
                .stdin
                .take()
                .unwrap()
                .write_all(payload.as_bytes())
                .unwrap();
            let out = child.wait_with_output().unwrap();
            assert!(
                out.status.success(),
                "boot.sh exited non-zero for source={source}"
            );
            let stdout = String::from_utf8(out.stdout).unwrap();
            let v: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap();
            v["hookSpecificOutput"]["additionalContext"]
                .as_str()
                .unwrap()
                .to_string()
        };

        // A file whose mtime is `secs_ago` seconds before now.
        let aged = |name: &str, secs_ago: u64| -> std::path::PathBuf {
            let p = dir.path().join(name);
            let f = std::fs::File::create(&p).unwrap();
            f.set_modified(SystemTime::now() - Duration::from_secs(secs_ago))
                .unwrap();
            p
        };
        let missing = dir.path().join("does-not-exist");

        // source variants, no argv: base notice only, with the compact
        // re-anchor appended on `compact`.
        let startup = run("startup", &[]);
        assert!(startup.starts_with("You booted at "), "{startup}");
        assert!(
            !startup.contains("You were down"),
            "no argv => no downtime: {startup}"
        );
        for (src, lead) in [
            ("resume", "You resumed at "),
            ("clear", "You cleared context at "),
        ] {
            let out = run(src, &[]);
            assert!(out.starts_with(lead), "{out}");
            assert!(
                !out.contains("You were down") && !out.contains("Re-anchor"),
                "{src} must stay the base notice: {out}"
            );
        }
        let compact = run("compact", &[]);
        assert!(compact.starts_with("You compacted at "), "{compact}");
        assert!(
            compact.contains("Re-anchor before continuing: re-read your working files"),
            "compact must carry the re-anchor copy: {compact}"
        );

        // startup downtime from LASTSEEN ($1), marker ($2) absent.
        assert!(
            run("startup", &[&aged("ls_2h", 7200), &missing])
                .contains("You were down for about 2 hours (last active "),
            "2h lastseen => 2 hours"
        );
        assert!(
            run("startup", &[&aged("ls_30s", 30), &missing])
                .contains("You were down for under a minute (last active "),
            "30s lastseen => under a minute"
        );

        // Unclean shutdown: the marker survived and is fresher than LASTSEEN,
        // so its mtime wins.
        assert!(
            run("startup", &[&aged("l_2h", 7200), &aged("m_10m", 600)])
                .contains("You were down for about 10 minutes "),
            "present marker (10m) beats lastseen (2h)"
        );

        // Omit cases: both files missing, and a non-startup source never
        // reports downtime even with a usable file present.
        assert!(
            !run("startup", &[&missing, &missing]).contains("You were down"),
            "both missing => omit"
        );
        assert!(
            !run("resume", &[&aged("ls_for_resume", 7200), &missing]).contains("You were down"),
            "resume must not report downtime"
        );
    }

    /// #430: `teamctl up` materializes `bin/boot.sh` next to the wrapper, with
    /// the embedded content and a 0o755 mode, so Claude Code's SessionStart
    /// hook can execute it. Mirrors the wrapper's managed-asset contract.
    #[test]
    fn ensure_wrapper_and_dirs_writes_executable_boot_script() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join(".team");
        std::fs::create_dir_all(root.join("projects")).unwrap();
        std::fs::write(
            root.join("team-compose.yaml"),
            r#"
version: 2
broker:
  type: sqlite
  path: state/mailbox.db
supervisor:
  type: tmux
  tmux_prefix: a-
projects:
  - file: projects/hello.yaml
"#,
        )
        .unwrap();
        std::fs::write(
            root.join("projects/hello.yaml"),
            r#"
version: 2
project:
  id: hello
  name: Hello
  cwd: .
managers:
  manager:
    runtime: claude-code
    model: claude-opus-4-8
"#,
        )
        .unwrap();
        let compose = Compose::load(&root).expect("compose loads");

        ensure_wrapper_and_dirs(&compose).expect("ensure_wrapper_and_dirs");

        let boot = team_core::render::boot_script_path(&compose.root);
        assert!(boot.is_file(), "bin/boot.sh must be written");
        assert_eq!(
            std::fs::read_to_string(&boot).unwrap(),
            DEFAULT_BOOT_SCRIPT,
            "on-disk boot.sh must match the embedded asset"
        );
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&boot).unwrap().permissions().mode();
            assert_eq!(mode & 0o777, 0o755, "boot.sh must be chmod 0o755");
        }
    }

    /// Minimal spec for exercising [`freshen_for_spec`] — only the
    /// project/agent pair matters (they key the codex-home path).
    fn spec_for(root: &Path, project: &str, agent: &str) -> AgentSpec {
        AgentSpec {
            project: project.into(),
            agent: agent.into(),
            tmux_session: format!("test-{project}-{agent}"),
            wrapper: root.join("wrapper.sh"),
            cwd: root.to_path_buf(),
            env_file: root.join("env"),
        }
    }

    /// T-352 parity: the codex `--fresh` arm moves the sessions dir
    /// aside as a `sessions.bak` recovery copy (matching Claude's
    /// `.bak`), leaves config.toml and the auth.json symlink at the
    /// codex-home root untouched, treats a missing sessions dir as a
    /// silent no-op (keeping any earlier backup), and replaces a
    /// stale backup from an earlier `--fresh`.
    #[test]
    fn freshen_codex_moves_sessions_aside_keeping_home_root() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let spec = spec_for(root, "hello", "dev");
        let home = codex_home_dir(root, "hello", "dev");
        let sessions = home.join("sessions");
        let bak = home.join("sessions.bak");

        // Stage a rollout plus the root-level files the wrapper relies on.
        std::fs::create_dir_all(sessions.join("2026/07/01")).unwrap();
        std::fs::write(sessions.join("2026/07/01/rollout-1.jsonl"), "v1").unwrap();
        std::fs::write(home.join("config.toml"), "[mcp_servers.team]").unwrap();
        let real_auth = root.join("real-auth.json");
        std::fs::write(&real_auth, "{}").unwrap();
        std::os::unix::fs::symlink(&real_auth, home.join("auth.json")).unwrap();

        freshen_for_spec(root, &spec, "codex", true);
        assert!(!sessions.exists(), "sessions dir must be moved aside");
        assert_eq!(
            std::fs::read_to_string(bak.join("2026/07/01/rollout-1.jsonl")).unwrap(),
            "v1",
            "recovery copy must carry the rollout",
        );
        assert!(home.join("config.toml").is_file(), "config.toml survives");
        assert!(
            home.join("auth.json")
                .symlink_metadata()
                .unwrap()
                .file_type()
                .is_symlink(),
            "auth.json symlink survives as a symlink",
        );

        // Missing sessions dir: silent no-op that keeps the backup.
        freshen_for_spec(root, &spec, "codex", true);
        assert!(
            bak.join("2026/07/01/rollout-1.jsonl").is_file(),
            "no-op freshen must not clobber the existing backup",
        );

        // A newer session replaces the pre-existing .bak wholesale.
        std::fs::create_dir_all(sessions.join("2026/07/02")).unwrap();
        std::fs::write(sessions.join("2026/07/02/rollout-2.jsonl"), "v2").unwrap();
        freshen_for_spec(root, &spec, "codex", true);
        assert!(!sessions.exists());
        assert!(
            !bak.join("2026/07/01/rollout-1.jsonl").exists(),
            "stale backup must be replaced, not merged into",
        );
        assert_eq!(
            std::fs::read_to_string(bak.join("2026/07/02/rollout-2.jsonl")).unwrap(),
            "v2",
        );
    }

    /// OpenCode `--fresh` parity: the session db moves into a `db.bak/`
    /// recovery copy together with its -shm/-wal sidecars (absent
    /// sidecars skipped), opencode.json at the home root is untouched,
    /// a missing db is a silent no-op (keeping any earlier backup),
    /// and a later `--fresh` replaces a stale backup wholesale.
    #[test]
    fn freshen_opencode_moves_db_aside_keeping_home_root() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let spec = spec_for(root, "hello", "dev");
        let home = team_core::render::opencode_home_dir(root, "hello", "dev");
        let bak = home.join("db.bak");

        // Stage the db + one sidecar plus the managed config the
        // wrapper relies on (the -shm sidecar is deliberately absent —
        // WAL sidecars only exist while sqlite holds the db open).
        std::fs::create_dir_all(&home).unwrap();
        std::fs::write(home.join("agent.db"), "v1").unwrap();
        std::fs::write(home.join("agent.db-wal"), "wal1").unwrap();
        std::fs::write(home.join("opencode.json"), "{}").unwrap();

        freshen_for_spec(root, &spec, "opencode", true);
        assert!(!home.join("agent.db").exists(), "db must be moved aside");
        assert!(!home.join("agent.db-wal").exists(), "sidecar moves too");
        assert_eq!(std::fs::read_to_string(bak.join("agent.db")).unwrap(), "v1");
        assert_eq!(
            std::fs::read_to_string(bak.join("agent.db-wal")).unwrap(),
            "wal1",
        );
        assert!(
            home.join("opencode.json").is_file(),
            "managed config survives"
        );

        // Missing db: silent no-op that keeps the backup.
        freshen_for_spec(root, &spec, "opencode", true);
        assert_eq!(
            std::fs::read_to_string(bak.join("agent.db")).unwrap(),
            "v1",
            "no-op freshen must not clobber the existing backup",
        );

        // A newer session replaces the pre-existing db.bak wholesale.
        std::fs::write(home.join("agent.db"), "v2").unwrap();
        freshen_for_spec(root, &spec, "opencode", true);
        assert!(!home.join("agent.db").exists());
        assert_eq!(std::fs::read_to_string(bak.join("agent.db")).unwrap(), "v2");
        assert!(
            !bak.join("agent.db-wal").exists(),
            "stale backup must be replaced, not merged into",
        );
    }
}