trusty-mpm 1.8.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
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
//! Tests for the instruction merge pipeline and bundled prompt assembly.
//!
//! Split out of `instruction_pipeline.rs` (#4318) so the production file stays
//! under the 500-SLOC cap enforced by `scripts/check_line_cap.sh`. The module is
//! included with `#[path]`, so `use super::*` still reaches the pipeline's items
//! exactly as it did inline; nothing about the assertions changed in the move.

use super::*;
use crate::core::content_source::test_support::rc;
use std::fs;
use std::path::Path;
use tempfile::TempDir;

/// Write `<name>.md` into `dir` with the given raw content.
fn write_file(path: &PathBuf, content: &str) {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).expect("create parent");
    }
    fs::write(path, content).expect("write file");
}

// ── #4588 / #4589: one resolution path, two operator-visible numbers ────────

/// RAII override of every environment input
/// [`crate::core::delegation_authority::deployed_agent_dirs`] consults, so a
/// roster assertion is a property of the TEST rather than of the developer's
/// machine.
///
/// Why: the roster is a three-tier union and two of those tiers are
/// machine-global (`$CLAUDE_CONFIG_DIR/agents` and `$HOME/.claude/agents`).
/// Without this, the exact-count assertions below would read whatever the
/// developer happens to have deployed — and live `tm` sessions rewrite those
/// directories mid-run, which is a documented 1-in-4 flake in
/// `bundled_pm_package_tests`.
/// What: points `$HOME` and `$CLAUDE_CONFIG_DIR` at a fresh temp root and
/// restores both on drop (including on a panic-driven unwind).
/// Test: used by `session_start_count_matches_the_delivered_delegation_roster`.
struct RosterTiers {
    tmp: TempDir,
    prev_home: Option<std::ffi::OsString>,
    prev_config: Option<std::ffi::OsString>,
}

impl RosterTiers {
    /// Callers MUST be tagged `#[serial_test::serial]` — this mutates
    /// process-global environment state.
    fn new() -> Self {
        let tmp = TempDir::new().expect("tempdir");
        let prev_home = std::env::var_os("HOME");
        let prev_config = std::env::var_os("CLAUDE_CONFIG_DIR");
        // SAFETY: every caller is `#[serial]`, so no other test thread races
        // this set/restore.
        unsafe {
            std::env::set_var("HOME", tmp.path().join("home"));
            std::env::set_var("CLAUDE_CONFIG_DIR", tmp.path().join("claude-config"));
        }
        Self {
            tmp,
            prev_home,
            prev_config,
        }
    }

    /// The project whose roster is under test.
    fn project(&self) -> PathBuf {
        self.tmp.path().join("project")
    }

    /// The temp `$HOME` this guard installed — where an ambient
    /// [`crate::core::paths::FrameworkPaths::default`] resolves while it is held.
    fn home(&self) -> PathBuf {
        self.tmp.path().join("home")
    }

    /// Tier 1 — `<project>/.claude/agents`, the operator's hand-placed agents.
    fn project_tier(&self) -> PathBuf {
        self.project().join(".claude").join("agents")
    }

    /// Tier 2 — the tm-managed `$CLAUDE_CONFIG_DIR/agents` bundled agents
    /// deploy into since #4409. This is the ONE directory the pre-#4588
    /// session-start count was derived from.
    fn managed_tier(&self) -> PathBuf {
        self.tmp.path().join("claude-config").join("agents")
    }

    /// Tier 3 — the operator's own generic `~/.claude/agents`, which tm never
    /// writes to. This tier held the five agents behind #4588's observed
    /// 34-vs-39 delta. #4513: with `CLAUDE_CONFIG_DIR` set, Claude Code reads
    /// tier 2 as its user tier and never loads this one, so tier 3 is the only
    /// tier whose agents the harness cannot publish for itself.
    fn generic_tier(&self) -> PathBuf {
        self.tmp.path().join("home").join(".claude").join("agents")
    }
}

impl Drop for RosterTiers {
    fn drop(&mut self) {
        // SAFETY: caller is `#[serial]`.
        unsafe {
            match self.prev_home.take() {
                Some(v) => std::env::set_var("HOME", v),
                None => std::env::remove_var("HOME"),
            }
            match self.prev_config.take() {
                Some(v) => std::env::set_var("CLAUDE_CONFIG_DIR", v),
                None => std::env::remove_var("CLAUDE_CONFIG_DIR"),
            }
        }
    }
}

/// Write a minimal composed agent named `name` into `dir`.
fn write_roster_agent(dir: &Path, name: &str) {
    fs::create_dir_all(dir).expect("create tier");
    fs::write(
        dir.join(format!("{name}.md")),
        format!("---\nname: {name}\nrole: {name}\ndescription: Handles {name} work.\n---\n"),
    )
    .expect("write agent");
}

/// Build a `PipelineInput` for the isolated project `tiers` describes.
///
/// #4588: the pipeline resolves the roster from the PROJECT, not from a
/// caller-named directory, so every test that asserts an exact `agent_count`
/// must pin all three tiers — hence [`RosterTiers`] rather than a bare
/// `TempDir`.
fn input_in(tiers: &RosterTiers) -> PipelineInput {
    PipelineInput {
        project_dir: tiers.project(),
        claude_md_path: tiers.project().join("CLAUDE.md"),
        // #7673: the fixture's own home, injected. The project sits beside it,
        // so the seed-site guard permits the stub.
        home: Some(tiers.home()),
    }
}

#[serial_test::serial]
#[test]
fn pipeline_full() {
    // The pipeline reports the roster it resolved and leaves an existing
    // CLAUDE.md alone. #4832 removed the `merged` text this used to assert on.
    let tiers = RosterTiers::new();
    let input = input_in(&tiers);

    write_roster_agent(&tiers.project_tier(), "engineer");
    write_file(&input.claude_md_path, "# Project\n\nPROJECT SECTION\n");

    let out = build_instructions(&input).unwrap();
    assert_eq!(out.agent_count, 1);
    assert!(
        !out.claude_md_created,
        "existing CLAUDE.md is not recreated"
    );
}

#[serial_test::serial]
#[test]
fn pipeline_does_not_read_the_retired_framework_instructions() {
    // Why (#4832): `build_instructions` used to read
    // `<framework_root>/instructions/INSTRUCTIONS.md`, and ANY error other than
    // `NotFound` — a directory planted at that path is the cheapest one to
    // produce — became `PrepError::Instructions`, the sole fatal variant. The
    // content was never used, so a session died over unread bytes.
    // FAILS BEFORE THIS CHANGE: the read returned `IsADirectory` and the
    // pipeline returned `Err`.
    let tiers = RosterTiers::new();
    let input = input_in(&tiers);
    let retired =
        crate::core::paths::FrameworkPaths::under(tiers.tmp.path()).framework_instructions_path();
    fs::create_dir_all(&retired).expect("plant a directory at the retired path");
    write_roster_agent(&tiers.project_tier(), "qa");
    write_file(&input.claude_md_path, "# Project\n\nPROJECT NOTES\n");

    let out =
        build_instructions(&input).expect("an unreadable retired path must not fail the pipeline");
    assert_eq!(out.agent_count, 1);
}

#[serial_test::serial]
#[test]
fn pipeline_creates_claude_md() {
    // CLAUDE.md absent → it is created as a side effect, claude_md_created
    // is true, and the file on disk contains the stub — but the stub text
    // is NOT folded into `merged` (dead code removed).
    let tiers = RosterTiers::new();
    let input = input_in(&tiers);

    assert!(!input.claude_md_path.exists());
    let out = build_instructions(&input).unwrap();
    assert!(out.claude_md_created);
    assert!(input.claude_md_path.exists());

    let on_disk = fs::read_to_string(&input.claude_md_path).unwrap();
    assert!(on_disk.contains("# Project Instructions"));
    assert!(on_disk.contains("trusty-mpm will never modify this file again"));
    // #6807: the footer left the stub for Claude Code's `attribution` setting,
    // which tm seeds in `ensure_settings_defaults`. A stub that still restated
    // it would be a second, drift-prone source of the same string.
    assert!(
        !on_disk.contains("Generated with trusty-mpm"),
        "seeded stub must not restate the attribution footer: {on_disk}"
    );
}

#[serial_test::serial]
#[test]
fn pipeline_claude_md_left_byte_identical() {
    // Why (#2170): trusty-mpm must NEVER modify a target project's
    // CLAUDE.md. An existing file — including one that happens to
    // contain the literal delegation-block markers as ordinary operator
    // text — must come back out of `build_instructions` completely
    // untouched on disk, and its content must not leak into `merged`
    // (dead code removed).
    let tiers = RosterTiers::new();
    let input = input_in(&tiers);
    let custom = "# My Project\n\nCUSTOM HAND-WRITTEN CONTENT\n";
    write_file(&input.claude_md_path, custom);

    let out = build_instructions(&input).unwrap();
    assert!(!out.claude_md_created);
    let on_disk = fs::read_to_string(&input.claude_md_path).unwrap();
    assert_eq!(
        on_disk, custom,
        "pre-existing CLAUDE.md must be left byte-identical: {on_disk}"
    );
    assert!(
        !on_disk.contains(DELEGATION_BLOCK_BEGIN),
        "no delegation-directive block may be injected: {on_disk}"
    );
    let _ = out;
}

// ── #5228: absent CLAUDE.md ≠ new project ───────────────────────────────────

/// A REAL git repository whose `main` gained `CLAUDE.md` after a branch was cut
/// from it — the exact shape #5228 reproduced in a live worktree.
///
/// Why a real repo and not a mocked filesystem: the bug is entirely about git
/// history. What separates "new project" from "stale branch" is whether a
/// remote-tracking ref carries the file, which only git can answer; a fake
/// filesystem would assert against the test's own stub of that answer and would
/// have passed against the pre-fix code.
/// What: a bare `origin` whose `main` holds commit 1 (no `CLAUDE.md`) then
/// commit 2 (adds it), plus a real `git worktree` checked out on a branch cut
/// at commit 1 with its upstream pointed at `origin/main` — mirroring what
/// `configure_session_branch_tracking` (#2189) sets up in production.
/// Test: the four `#5228` tests below.
struct StaleWorktreeFixture {
    _tmp: TempDir,
    /// The per-session worktree, on a branch that predates `CLAUDE.md`.
    worktree: PathBuf,
    /// The tracked `CLAUDE.md` content on `origin/main`.
    upstream_content: &'static str,
}

/// The upstream `CLAUDE.md` body — deliberately unlike [`CLAUDE_MD_STUB`], so
/// an assertion cannot pass on a stub that happens to share a heading.
const UPSTREAM_CLAUDE_MD: &str = "# Real Project Instructions\n\nDo the real thing.\n";

fn git_ok(dir: &Path, args: &[&str]) -> bool {
    std::process::Command::new("git")
        .arg("-C")
        .arg(dir)
        .args(args)
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false)
}

fn git_identity(dir: &Path) {
    assert!(git_ok(dir, &["config", "user.email", "ci@test.invalid"]));
    assert!(git_ok(dir, &["config", "user.name", "CI"]));
    assert!(git_ok(dir, &["config", "commit.gpgsign", "false"]));
}

impl StaleWorktreeFixture {
    /// Returns `None` when git is unavailable — callers skip rather than fail,
    /// matching `session_launch::worktree_sync`'s fixture.
    ///
    /// `add_claude_md_upstream`: when false, `origin/main` never gains a
    /// `CLAUDE.md`, which is the genuinely-new-project control.
    fn build(add_claude_md_upstream: bool) -> Option<Self> {
        let tmp = crate::test_support::hermetic_temp_dir();
        let root = std::fs::canonicalize(tmp.path()).unwrap_or_else(|_| tmp.path().into());
        let origin = root.join("origin.git");
        let seed = root.join("seed");
        let base = root.join("base");
        let worktree = root.join("worktree");
        fs::create_dir_all(&origin).ok()?;
        fs::create_dir_all(&seed).ok()?;

        if !git_ok(&origin, &["init", "--bare", "--initial-branch=main"]) {
            eprintln!("#5228 tests: git unavailable, skipping");
            return None;
        }
        assert!(git_ok(&seed, &["init", "--initial-branch=main"]));
        git_identity(&seed);
        // Commit 1: the state the stale branch is cut from — no CLAUDE.md.
        fs::write(seed.join("README.md"), "base\n").ok()?;
        assert!(git_ok(&seed, &["add", "-A"]));
        assert!(git_ok(&seed, &["commit", "-m", "base"]));
        assert!(git_ok(
            &seed,
            &["remote", "add", "origin", origin.to_str()?]
        ));
        assert!(git_ok(&seed, &["push", "origin", "main"]));
        assert!(git_ok(
            &origin,
            &["symbolic-ref", "HEAD", "refs/heads/main"]
        ));

        // The checkout the worktree is cut from, at commit 1.
        // Cloned from the fixture's own root, never the test process's cwd —
        // that cwd is this repository's checkout.
        assert!(git_ok(&root, &["clone", origin.to_str()?, base.to_str()?]));
        git_identity(&base);
        assert!(git_ok(
            &base,
            &["worktree", "add", "-b", "stale-branch", worktree.to_str()?]
        ));
        git_identity(&worktree);
        assert!(git_ok(
            &worktree,
            &["branch", "--set-upstream-to=origin/main", "stale-branch"]
        ));

        if add_claude_md_upstream {
            // Commit 2 — CLAUDE.md becomes tracked upstream (#4660/#4661), out
            // from under the already-cut branch.
            fs::write(seed.join("CLAUDE.md"), UPSTREAM_CLAUDE_MD).ok()?;
            assert!(git_ok(&seed, &["add", "-A"]));
            assert!(git_ok(&seed, &["commit", "-m", "track CLAUDE.md"]));
            assert!(git_ok(&seed, &["push", "origin", "main"]));
            // The worktree learns about it the way a live one does: a fetch of
            // the shared remote-tracking refs, with no merge.
            assert!(git_ok(&worktree, &["fetch", "origin"]));
        }

        assert!(
            !worktree.join("CLAUDE.md").exists(),
            "fixture invariant: the stale worktree must not have CLAUDE.md on disk"
        );
        Some(Self {
            _tmp: tmp,
            worktree,
            upstream_content: UPSTREAM_CLAUDE_MD,
        })
    }

    fn claude_md(&self) -> PathBuf {
        self.worktree.join("CLAUDE.md")
    }
}

#[test]
fn load_or_create_claude_md_refuses_to_stub_a_branch_predating_the_tracked_file() {
    // FAILS BEFORE THIS CHANGE (#5228): the pre-fix writer read `NotFound`,
    // wrote CLAUDE_MD_STUB, and returned `Ok((stub, true))` — handing the
    // session boilerplate in place of the project's only non-dynamic
    // instruction source, and leaving an untracked file that looks authored to
    // every later run.
    let Some(fx) = StaleWorktreeFixture::build(true) else {
        return;
    };
    let path = fx.claude_md();

    let err = load_or_create_claude_md(&path, None)
        .expect_err("a branch that merely predates the tracked CLAUDE.md must not be stubbed");

    assert!(
        !path.exists(),
        "the refusal must leave nothing behind: a stub on disk is the permanent half of the bug"
    );
    let PipelineError::Io { source, .. } = &err;
    let msg = source.to_string();
    assert!(msg.contains("stale-branch"), "must name the branch: {msg}");
    assert!(msg.contains("origin/main"), "must name the ref: {msg}");
    assert!(
        msg.contains("merge --ff-only"),
        "must carry a recovery command: {msg}"
    );
    let _ = fx.upstream_content;
}

#[test]
fn build_instructions_refuses_a_stale_worktree_rather_than_seeding_a_stub() {
    // The refusal has to reach the pipeline, because that is where it becomes
    // fatal: `prepare_session` maps a `PipelineError` onto
    // `PrepError::Instructions`, the one condition #4752 rules must stop a
    // launch. A writer that refused while `build_instructions` still returned
    // `Ok` would start the session anyway.
    let Some(fx) = StaleWorktreeFixture::build(true) else {
        return;
    };
    let input = PipelineInput {
        project_dir: fx.worktree.clone(),
        claude_md_path: fx.claude_md(),
        home: None,
    };

    let err = build_instructions(&input).expect_err("a stale worktree must refuse the pipeline");
    assert!(
        err.to_string().contains("CLAUDE.md"),
        "the pipeline error must name the file: {err}"
    );
    assert!(!fx.claude_md().exists(), "no stub may be written");
}

#[test]
fn load_or_create_claude_md_still_seeds_when_upstream_has_no_claude_md() {
    // The ordinary path inside a real repository: `origin/main` never tracked a
    // CLAUDE.md, so this project genuinely is new and the stub is correct. The
    // #5228 probe must not turn "in a git repo" into "refuse".
    let Some(fx) = StaleWorktreeFixture::build(false) else {
        return;
    };
    let path = fx.claude_md();

    let (content, created) =
        load_or_create_claude_md(&path, None).expect("a genuinely new project is still seeded");
    assert!(created);
    assert_eq!(content, CLAUDE_MD_STUB);
    assert_eq!(fs::read_to_string(&path).unwrap(), CLAUDE_MD_STUB);
}

#[test]
fn load_or_create_claude_md_reads_a_present_file_in_a_git_worktree() {
    // The ordinary path with the file present — the state a worktree reaches
    // after the recovery command the refusal prints. It must read back
    // byte-identical and report `created == false`, with no git probe involved.
    let Some(fx) = StaleWorktreeFixture::build(true) else {
        return;
    };
    assert!(git_ok(&fx.worktree, &["merge", "--ff-only", "origin/main"]));
    let path = fx.claude_md();
    assert_eq!(fs::read_to_string(&path).unwrap(), fx.upstream_content);

    let (content, created) = load_or_create_claude_md(&path, None).expect("a present file loads");
    assert!(!created, "an existing CLAUDE.md is never recreated");
    assert_eq!(content, fx.upstream_content);
    assert_eq!(fs::read_to_string(&path).unwrap(), fx.upstream_content);
}

/// #7673, the 2026-09-12 finding: a tm seed template was sitting at `$HOME`,
/// so Claude Code prepended it to every turn of every agent in every project
/// under the home directory.
///
/// FAILS BEFORE THIS CHANGE: nothing consulted the home directory, so this
/// wrote `$HOME/CLAUDE.md` and returned `Ok((stub, true))`.
#[test]
fn load_or_create_claude_md_refuses_to_seed_at_the_home_directory() {
    let tmp = TempDir::new().unwrap();
    let home = tmp.path().join("home");
    // A dotfiles repo makes `$HOME` look exactly like a project root; the home
    // refusal is first and unconditional, so it still fires.
    fs::create_dir_all(home.join(".git")).unwrap();
    let path = home.join("CLAUDE.md");

    let err =
        load_or_create_claude_md(&path, Some(&home)).expect_err("seeding at $HOME must be refused");

    let PipelineError::Io { source, .. } = &err;
    assert!(
        source.to_string().contains("home directory"),
        "the refusal must name the reason: {source}"
    );
    assert!(!path.exists(), "nothing is written: {err:?}");
}

/// FAILS BEFORE THIS CHANGE: any directory at all was seeded, so a `CLAUDE.md`
/// could land at `/Users` and load into every project on the machine.
#[test]
fn load_or_create_claude_md_refuses_to_seed_above_the_home_directory() {
    let tmp = TempDir::new().unwrap();
    let home = tmp.path().join("users").join("ada");
    fs::create_dir_all(&home).unwrap();
    // The ancestor — `/Users` in the real shape.
    let above = tmp.path().join("users");
    let path = above.join("CLAUDE.md");

    let err = load_or_create_claude_md(&path, Some(&home))
        .expect_err("a directory above $HOME must be refused");

    let PipelineError::Io { source, .. } = &err;
    assert!(
        source.to_string().contains("above the home directory"),
        "the refusal must name the reason: {source}"
    );
    assert!(!path.exists(), "nothing is written: {err:?}");
}

/// The CRITICAL regression of the first round: a subdirectory of a git repo is
/// exactly what `tm session start`'s own `refuse_outside_a_git_project` gate
/// certifies, and the seed guard must agree with it.
#[test]
fn load_or_create_claude_md_seeds_in_a_subdirectory_of_a_git_repo() {
    let tmp = crate::test_support::hermetic_temp_dir();
    let repo = tmp.path();
    if !git_ok(repo, &["init", "--initial-branch=main"]) {
        eprintln!("#7673 tests: git unavailable, skipping");
        return;
    }
    git_identity(repo);
    let nested = repo.join("crates").join("thing");
    fs::create_dir_all(&nested).unwrap();

    let path = nested.join("CLAUDE.md");
    // #7673: a fixture home, never the ambient `$HOME`.
    let home = repo.join("fixture-home");
    let (content, created) = load_or_create_claude_md(&path, Some(&home))
        .expect("a subdirectory of a git project seeds");
    assert!(created);
    assert_eq!(content, CLAUDE_MD_STUB);
}

/// FAILS BEFORE #7764: the child-repository scan ran once, several git
/// subprocesses before the write, and the stub was then written regardless. A
/// repository created inside that window made this exactly the ancestor
/// `CLAUDE.md` seed #7673 refuses.
///
/// The prompt seam is the one point that provably runs BETWEEN the first scan
/// and the write, so creating the child there puts it inside the real window
/// rather than a simulated one.
#[test]
fn a_child_repository_created_between_the_check_and_the_write_refuses_the_seed() {
    let tmp = crate::test_support::hermetic_temp_dir();
    let ws = tmp.path().join("workspace");
    fs::create_dir_all(&ws).unwrap();
    let path = ws.join("CLAUDE.md");
    // #7673: a fixture home, never the ambient `$HOME`.
    let home = tmp.path().join("fixture-home");
    let child = ws.join("packages").join("api");

    let mut appears_mid_window = || {
        fs::create_dir_all(child.join(".git")).expect("create the child repository");
        false
    };
    let seam: Option<&mut dyn FnMut() -> bool> = Some(&mut appears_mid_window);
    let err = load_or_create_claude_md_with_init(&path, Some(&home), seam)
        .expect_err("a repository that appeared mid-window must refuse the seed");

    assert!(err.to_string().contains("packages/api"), "{err}");
    assert!(
        !path.exists(),
        "no CLAUDE.md may be written above a child repository"
    );
}

/// The re-check must not refuse the seed it exists to protect: an accepted
/// `git init` offer makes the directory a repository of its own, which is a
/// seed site, not a workspace parent.
#[test]
fn an_accepted_git_init_offer_still_seeds_through_the_recheck() {
    let tmp = crate::test_support::hermetic_temp_dir();
    if !git_ok(tmp.path(), &["--version"]) {
        eprintln!("#7764 test: git unavailable, skipping");
        return;
    }
    let dir = tmp.path().join("new-project");
    fs::create_dir_all(&dir).unwrap();
    let path = dir.join("CLAUDE.md");
    // #7673: a fixture home, never the ambient `$HOME`.
    let home = tmp.path().join("fixture-home");

    let mut accept = || true;
    let seam: Option<&mut dyn FnMut() -> bool> = Some(&mut accept);
    let (content, created) = load_or_create_claude_md_with_init(&path, Some(&home), seam)
        .expect("an accepted offer seeds the directory it just initialised");

    assert!(created);
    assert_eq!(content, CLAUDE_MD_STUB);
    assert!(
        dir.join(".git").is_dir(),
        "the accepted offer must have created the repository"
    );
}

/// A first-touch directory — the shape `tm sessions instructions --dir <dir>` is
/// documented to accept — must still seed. The first round refused it, which is
/// what forced the fixture workarounds this round removed.
#[test]
fn load_or_create_claude_md_seeds_in_a_bare_first_touch_directory() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("scratch");
    fs::create_dir_all(&dir).unwrap();
    let path = dir.join("CLAUDE.md");
    // #7673: a fixture home, never the ambient `$HOME`.
    let home = tmp.path().join("fixture-home");

    let (content, created) =
        load_or_create_claude_md(&path, Some(&home)).expect("a first-touch directory seeds");
    assert!(created);
    assert_eq!(content, CLAUDE_MD_STUB);
}

/// FAILS BEFORE THIS ROUND: `--dir ""` yields a bare `CLAUDE.md` whose parent is
/// the empty path, and the `if let` around the guard then bound nothing and fell
/// through to the write with no check at all.
#[test]
fn load_or_create_claude_md_fails_closed_on_a_path_with_no_directory() {
    // A name nothing in the crate root can satisfy, so the read misses and the
    // seeding arm — the one under test — is the arm that runs.
    let path = PathBuf::from("CLAUDE.md.7673-no-directory-component");

    // #7673: a fixture home, never the ambient `$HOME`.
    let home = std::env::temp_dir().join("7673-fixture-home");
    let err = load_or_create_claude_md(&path, Some(&home))
        .expect_err("a path with no directory component must be refused, never seeded");

    let PipelineError::Io { source, .. } = &err;
    assert!(
        source.to_string().contains("no directory component"),
        "the refusal must name the reason: {source}"
    );
    assert!(!path.exists(), "nothing is written: {err:?}");
}

#[test]
fn load_or_create_claude_md_still_seeds_in_a_repo_with_no_remote() {
    // The fall-open arm the fixture's `else { return; }` skip does NOT cover:
    // git answers, the directory IS a work tree, and no candidate ref exists at
    // all. `@{upstream}`, `origin/HEAD`, `origin/main` and `origin/master` must
    // all miss and the stub must still be seeded. An untested fall-open arm is
    // where the next regression lands.
    let tmp = crate::test_support::hermetic_temp_dir();
    let dir = tmp.path();
    if !git_ok(dir, &["init", "--initial-branch=main"]) {
        eprintln!("#5228 tests: git unavailable, skipping");
        return;
    }
    git_identity(dir);
    fs::write(dir.join("README.md"), "local only\n").unwrap();
    assert!(git_ok(dir, &["add", "-A"]));
    assert!(git_ok(dir, &["commit", "-m", "local only"]));

    let path = dir.join("CLAUDE.md");
    let (content, created) = load_or_create_claude_md(&path, None)
        .expect("a repo with no remote is not stale, it is local");
    assert!(created);
    assert_eq!(content, CLAUDE_MD_STUB);
    assert_eq!(fs::read_to_string(&path).unwrap(), CLAUDE_MD_STUB);
}

#[test]
fn load_or_create_claude_md_ignores_an_abandoned_origin_main_when_upstream_answered() {
    // Why (#5228 review, MEDIUM 1): `origin/main`/`origin/master` are a LAST
    // RESORT, not an override. Default branch `develop` carries no CLAUDE.md, so
    // this project is genuinely new — but a stale `origin/main` still has one.
    // Consulting it would refuse a launch that should proceed AND print a remedy
    // telling the operator to merge an abandoned branch.
    let tmp = crate::test_support::hermetic_temp_dir();
    let root = std::fs::canonicalize(tmp.path()).unwrap_or_else(|_| tmp.path().into());
    let origin = root.join("origin.git");
    let seed = root.join("seed");
    let work = root.join("work");
    fs::create_dir_all(&origin).unwrap();
    fs::create_dir_all(&seed).unwrap();

    if !git_ok(&origin, &["init", "--bare", "--initial-branch=develop"]) {
        eprintln!("#5228 tests: git unavailable, skipping");
        return;
    }
    assert!(git_ok(&seed, &["init", "--initial-branch=main"]));
    git_identity(&seed);
    // The abandoned `main`, which DOES carry a CLAUDE.md.
    fs::write(seed.join("CLAUDE.md"), UPSTREAM_CLAUDE_MD).unwrap();
    assert!(git_ok(&seed, &["add", "-A"]));
    assert!(git_ok(&seed, &["commit", "-m", "old main with CLAUDE.md"]));
    assert!(git_ok(
        &seed,
        &["remote", "add", "origin", origin.to_str().unwrap()]
    ));
    assert!(git_ok(&seed, &["push", "origin", "main"]));
    // The live default branch, which does not.
    assert!(git_ok(&seed, &["checkout", "--orphan", "develop"]));
    assert!(git_ok(&seed, &["rm", "-q", "-f", "CLAUDE.md"]));
    fs::write(seed.join("README.md"), "develop\n").unwrap();
    assert!(git_ok(&seed, &["add", "-A"]));
    assert!(git_ok(&seed, &["commit", "-m", "develop line"]));
    assert!(git_ok(&seed, &["push", "origin", "develop"]));
    assert!(git_ok(
        &origin,
        &["symbolic-ref", "HEAD", "refs/heads/develop"]
    ));

    assert!(git_ok(
        &root,
        &["clone", origin.to_str().unwrap(), work.to_str().unwrap()]
    ));
    git_identity(&work);
    assert!(!work.join("CLAUDE.md").exists());
    // Both authoritative signals answer, and neither carries the file.
    assert!(git_ok(
        &work,
        &["cat-file", "-e", "origin/main:./CLAUDE.md"]
    ));
    assert!(!git_ok(
        &work,
        &["cat-file", "-e", "origin/develop:./CLAUDE.md"]
    ));

    let path = work.join("CLAUDE.md");
    let (content, created) = load_or_create_claude_md(&path, None)
        .expect("an abandoned origin/main must not override origin/develop");
    assert!(created);
    assert_eq!(content, CLAUDE_MD_STUB);
}

#[test]
fn stale_claude_md_refusal_names_the_branch_ref_and_recovery() {
    // Why: the refusal stops a launch, so its message is the whole interface —
    // a bare "file missing" would send the operator hunting the wrong problem.
    let msg = stale_claude_md_message(
        Path::new("/w/proj/CLAUDE.md"),
        &UpstreamTracked {
            reference: "origin/main".to_string(),
            position: "branch `fix/4061-example`".to_string(),
            detached: false,
        },
    );
    assert!(msg.contains("CLAUDE.md"), "{msg}");
    assert!(msg.contains("fix/4061-example"), "{msg}");
    assert!(msg.contains("origin/main"), "{msg}");
    assert!(
        msg.contains("git -C /w/proj merge --ff-only origin/main"),
        "{msg}"
    );
    assert!(
        msg.contains("git -C /w/proj checkout origin/main -- CLAUDE.md"),
        "{msg}"
    );
}

#[test]
fn stale_claude_md_refusal_offers_no_merge_on_a_detached_head() {
    // Why: `merge --ff-only` on a detached HEAD moves HEAD and drops the commit
    // the operator deliberately checked out. Printing it as the headline remedy
    // would make the refusal's own advice destructive.
    let msg = stale_claude_md_message(
        Path::new("/w/proj/CLAUDE.md"),
        &UpstreamTracked {
            reference: "origin/main".to_string(),
            position: "detached HEAD at 1a2b3c4".to_string(),
            detached: true,
        },
    );
    assert!(msg.contains("detached HEAD at 1a2b3c4"), "{msg}");
    assert!(
        msg.contains("git -C /w/proj checkout origin/main -- CLAUDE.md"),
        "{msg}"
    );
    assert!(
        !msg.contains("merge --ff-only"),
        "a detached HEAD must never be told to fast-forward: {msg}"
    );
}

#[test]
fn strip_delegation_block_removes_legacy_block() {
    // Why (#2170 cleanup helper): a workspace polluted by the old #2125
    // injection must have the fenced block removed, leaving the
    // operator's own content untouched.
    let polluted = format!(
        "{DELEGATION_BLOCK_BEGIN}\n\nSome injected directive text.\n\n{DELEGATION_BLOCK_END}\n\n# My Project\n\nOperator notes.\n"
    );
    let cleaned = strip_delegation_block(&polluted);
    assert!(!cleaned.contains(DELEGATION_BLOCK_BEGIN));
    assert!(!cleaned.contains(DELEGATION_BLOCK_END));
    assert!(!cleaned.contains("Some injected directive text."));
    assert_eq!(cleaned, "# My Project\n\nOperator notes.\n");
}

#[test]
fn strip_delegation_block_noop_when_absent() {
    // Why: a clean CLAUDE.md (the common case post-#2170) must be
    // returned byte-identical.
    let clean = "# My Project\n\nOperator notes.\n";
    assert_eq!(strip_delegation_block(clean), clean);
}

/// The section file a PM-body section is authored in; `None` outside the body.
fn pm_body_source(id: SectionId) -> Option<&'static str> {
    let path = match id {
        SectionId::Identity => "identity",
        SectionId::Core => "core",
        SectionId::PmAllowlist => "pm-allowlist",
        SectionId::DelegationMechanics => "delegation-mechanics",
        SectionId::AgentRouting => "agent-routing",
        SectionId::SubagentReEngagement => "subagent-re-engagement",
        SectionId::Phases => "phases",
        SectionId::QaGate => "qa-gate",
        SectionId::GitFileTracking => "git-file-tracking",
        SectionId::TicketsPrsReleases => "tickets-prs-releases",
        SectionId::MessagesReportsSessions => "messages-reports-sessions",
        SectionId::AutonomousExecution => "autonomous-execution",
        SectionId::Memory => "memory",
        SectionId::Search => "search",
        _ => return None,
    };
    rc().instruction(&format!("sections/{path}.md"))
}

#[test]
fn pm_instructions_is_the_pm_body_sections() {
    // #4183: the legacy PM body is RECONSTITUTED, never kept as a fourth copy
    // on disk. #4318 moved the source of that reconstitution from the
    // `include_str!` constants to the MANIFEST, because the manifest may now
    // author a rule inline — rebuilding from the constants would deliver such a
    // rule to the packaged composer and not to the legacy override assembly,
    // which is the split-brain this asserts against.
    // #8533: Identity opens the prompt and `core` was split into nine
    // sections, so the body is every section before the stack profile.
    let body = pm_instructions(rc());
    let projected = crate::core::bundled_pm_package::authored_run(rc(), &PM_BODY_SECTIONS);
    assert_eq!(body, format!("{projected}\n"));
    assert!(
        body.starts_with(rc().required("sections/identity.md").trim()),
        "Identity opens the body"
    );

    // Every section source is still delivered in full, in order, and the
    // manifest-authored rules ride along.
    for id in PM_BODY_SECTIONS {
        let expected = pm_body_source(id).expect("every PM-body section has a source");
        assert!(body.contains(expected.trim()), "{id:?} went missing");
    }
    // #8361: autonomy is its own section now. On the legacy path it lives
    // inside this blob, so omitting it from the run would drop the rule from
    // every roster-absent prompt while the packaged path kept it.
    assert!(body.contains("## Autonomous Execution"));
    assert!(body.contains("### Clickable References"));
    // The "honest" ban now lives only in the output styles' `Communication —
    // Write Plainly` section, the one channel a manual `claude` launch keeps.
    // A copy here is the second statement that move exists to prevent.
    assert!(!body.contains("### Banned Word"));

    // The paragraph break is `Join::Blank`'s literal, which is what makes
    // this string byte-identical to what the packaged composer emits.
    assert!(body.contains("## Memory Protocol (Context-First)"));
    assert!(body.contains("## Code Search Protocol (Context-First)"));
    assert!(
        !body.contains("## Context-First Protocol\n"),
        "the merged Memory+Search block must not survive as a fourth copy"
    );
}

#[test]
fn base_pm_is_its_three_tail_sections() {
    // Same no-second-copy property for the non-overridable floor, plus the
    // one reordering #4183 makes: the tool-priority mandate travels with the
    // other non-overridable rules and so now precedes the conventions.
    //
    // #4573 added `enforcement` (Prohibitions + Circuit Breakers) as the second
    // floor section. Asserting it HERE — over `base_pm(rc())`, the string every
    // legacy branch appends, including the `PM_INSTRUCTIONS_DEPLOYED.md` full
    // replacement — is what proves the tier change alone did not leave the
    // legacy paths without the authority tables.
    // #8533: Identity moved to the top of the prompt, out of this tail.
    let floor = base_pm(rc());
    assert_eq!(
        floor,
        format!(
            "{}\n\n{}\n\n{}\n",
            rc().required("sections/enforcement.md").trim(),
            rc().required("sections/non-overridable-rules.md").trim(),
            rc().required("sections/framework-guaranteed-conventions.md")
                .trim()
        )
    );

    let tool = floor
        .find("## Trusty Tool Priority (Non-Overridable)")
        .expect("the tool-priority mandate stays in the floor");
    let conventions = floor
        .find("## Framework-Guaranteed Conventions (Non-Overridable)")
        .expect("the guaranteed conventions stay in the floor");
    assert!(
        tool < conventions,
        "tool priority now rides with the non-overridable rules it belongs to"
    );
}

#[test]
fn workflow_section_carries_the_opportunistic_fix_rule() {
    // The opportunistic-fix rule (owner amendment on #4183) is authored in the
    // manifest, not in `workflow.md`, so the constant alone does not carry it.
    // Every consumer must therefore read the section through the manifest —
    // otherwise a project with no override and a project on the legacy path
    // would receive different workflows.
    let section = workflow_section(rc());
    assert!(section.starts_with(rc().required("sections/workflow.md").trim()));
    assert!(section.contains("## Opportunistic Fixes"));
    // Ruling 35 (2026-10-05): the Completion Standard wins, so an easy fix is
    // noted once and not made in the same work.
    assert!(section.contains("noted in one comment on the CURRENT issue or PR"));
    assert!(section.contains("not made in the same work"));
    assert!(
        !rc()
            .required("sections/workflow.md")
            .contains("## Opportunistic Fixes"),
        "the rule is manifest-authored; finding it in workflow.md means it was \
         duplicated"
    );
}

#[test]
fn delegation_doctrine_carries_the_precedence_note() {
    // #4318 moved the roster-precedence note out of a Rust literal and into the
    // manifest. The doctrine string every composer uses must still be the asset
    // followed by that note, in that order.
    let doctrine = delegation_doctrine(rc());
    assert!(doctrine.starts_with(rc().required("sections/agent-delegation.md").trim()));
    assert!(doctrine.ends_with("do not retry the same agent."));
    // #8533: the note is now the pinned agent-selection block.
    assert!(doctrine.contains("**Agent selection.**"));
    assert!(doctrine.contains("authoritative for WHICH agents exist"));
}

#[test]
fn the_installed_prompt_carries_the_manifest_authored_rules() {
    // `assemble_system_prompt` writes
    // `~/.trusty-mpm/framework/instructions/INSTRUCTIONS.md`, which `tm install`
    // and `tm launch` hand to `claude --append-system-prompt-file`. It has no
    // agent roster, so it cannot use the package composer — which is exactly why
    // it has to project the manifest rather than concatenate the constants. A
    // manifest-authored rule missing here is a rule half the launch paths never
    // see.
    let prompt = assemble_system_prompt(rc());
    for marker in ["### Clickable References", "## Opportunistic Fixes"] {
        assert!(
            prompt.contains(marker),
            "the installed prompt must carry {marker:?}"
        );
    }
}

#[test]
fn assemble_system_prompt_contains_all_sections() {
    // Why: the assembled prompt is the contract `claude` receives; every
    // bundled section must be present and joined with the `---` rule.
    let prompt = assemble_system_prompt(rc());
    assert!(prompt.contains("# PM Agent -- Trusty MPM"));
    assert!(prompt.contains("## Prohibitions (CANONICAL"));
    assert!(prompt.contains("# PM Workflow Configuration"));
    assert!(prompt.contains("# Agent Delegation Routing"));
    // The Trusty tool-priority block now lives inside the BASE_PM floor.
    assert!(prompt.contains("## Trusty Tool Priority (Non-Overridable)"));
    assert!(prompt.contains("\n\n---\n\n"));
    // The former floor (#8533: now opening with the Prohibitions) comes last.
    let base = prompt.find("## Prohibitions (CANONICAL").expect("base_pm");
    let delegation = prompt
        .find("# Agent Delegation Routing")
        .expect("delegation");
    assert!(base > delegation, "BASE_PM floor must be appended last");
    // Ticketing-specific content was stripped from the bundled assets.
    assert!(!prompt.contains("mcp__mcp-ticketer__"));
    assert!(!prompt.contains("ticketing_agent"));
}

// ── #4752: the compiled prompt owns a path nothing else writes ─────────────

#[test]
fn compiled_prompt_path_is_project_local() {
    // Why (#4752, then #4832): the compiled prompt belongs to the PROJECT whose
    // session runs it, under that session's own directory.
    // What: pins `<project>/.trusty-mpm/sessions/<id>/INSTRUCTIONS-COMPILED.md`.
    // `/some/project` is not a git repo, so the harness root is the path itself.
    let project = Path::new("/some/project");
    assert_eq!(
        compiled_prompt_path(project, "sess-1"),
        Path::new("/some/project/.trusty-mpm/sessions/sess-1/INSTRUCTIONS-COMPILED.md")
    );
}

#[test]
fn compiled_prompt_path_is_per_session() {
    // Why (#4832): project-scoping still let two concurrent sessions in ONE
    // project overwrite each other's compiled prompt. FAILS BEFORE THIS CHANGE
    // — `compiled_prompt_path` took only the project and returned one path.
    let project = Path::new("/some/project");
    assert_ne!(
        compiled_prompt_path(project, "sess-a"),
        compiled_prompt_path(project, "sess-b"),
        "two sessions in one project must not share one compiled-prompt file"
    );
}

#[test]
fn compiled_prompt_path_never_collides_across_projects() {
    // Why (#4752 review, MEDIUM 4): ONE global file used to serve every
    // project, so concurrent sessions overwrote each other.
    let a = compiled_prompt_path(Path::new("/projects/alpha"), "s");
    let b = compiled_prompt_path(Path::new("/projects/beta"), "s");
    assert_ne!(
        a, b,
        "two projects must not share one compiled-prompt file — that was the collision"
    );
}

#[test]
fn compiled_prompt_path_never_lands_inside_a_worktree() {
    // Why (#4832, owner ruling): a worktree carries code, config and docs —
    // never harness state. FAILS BEFORE THIS CHANGE: the path was
    // `<worktree>/.trusty-mpm/framework/INSTRUCTIONS-COMPILED.md`.
    let tmp = crate::test_support::hermetic_temp_dir();
    let repo = tmp.path().join("proj");
    let wt = tmp.path().join("wt");
    init_git_repo_with_worktree(&repo, &wt);

    let compiled = compiled_prompt_path(&wt, "sess-1");
    let wt_canon = std::fs::canonicalize(&wt).unwrap();
    assert!(
        !compiled.starts_with(&wt_canon) && !compiled.starts_with(&wt),
        "the compiled prompt must not be written inside the worktree: {}",
        compiled.display()
    );
    assert!(
        compiled.starts_with(std::fs::canonicalize(&repo).unwrap()),
        "it belongs to the main checkout: {}",
        compiled.display()
    );
}

/// Build a committed repo at `repo` plus a linked worktree at `wt`.
///
/// Why: the worktree assertions above are only meaningful against a REAL git
/// worktree — a plain temp directory cannot reproduce the shape.
fn init_git_repo_with_worktree(repo: &Path, wt: &Path) {
    let run = |dir: &Path, args: &[&str]| {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(dir)
            .args(args)
            .output()
            .unwrap_or_else(|e| panic!("git {args:?}: {e}"));
        assert!(
            out.status.success(),
            "git {args:?} failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    };
    fs::create_dir_all(repo).unwrap();
    run(repo, &["init", "-q", "-b", "main"]);
    run(repo, &["config", "user.email", "t@example.com"]);
    run(repo, &["config", "user.name", "T"]);
    fs::write(repo.join("README.md"), "# t\n").unwrap();
    run(repo, &["add", "-A"]);
    run(repo, &["commit", "-qm", "init"]);
    run(
        repo,
        &["worktree", "add", "-q", "-b", "feat", wt.to_str().unwrap()],
    );
}

#[test]
fn compiled_prompt_path_is_not_the_bundled_instructions_path() {
    // The original #4752 defect: the compiled OUTPUT must not share a path with
    // the bundled INPUT the pipeline used to read.
    let tmp = TempDir::new().unwrap();
    let paths = crate::core::paths::FrameworkPaths::under(tmp.path());
    assert_ne!(
        compiled_prompt_path(tmp.path(), "s"),
        paths.framework_instructions_path()
    );
}

// ── #4832: migration off the pre-#4832 per-project path ────────────────────

#[test]
fn migrate_removes_a_legacy_compiled_prompt() {
    // Why (#4832): an upgraded install keeps the old file forever with no
    // writer left to refresh it, and it is exactly the file an operator opens
    // to answer "what is my session running".
    let tmp = TempDir::new().unwrap();
    let legacy = tmp
        .path()
        .join(".trusty-mpm")
        .join("framework")
        .join(COMPILED_PROMPT_FILE);
    write_file(&legacy, "OLD COMPILED PROMPT");

    assert!(
        remove_legacy_compiled_prompt(tmp.path()).expect("removal succeeds"),
        "an existing legacy file must be reported as removed"
    );
    assert!(!legacy.exists());
    assert!(
        !legacy.parent().unwrap().exists(),
        "the now-empty framework/ directory goes with it"
    );
}

#[test]
fn migrate_keeps_a_sibling_manifest() {
    // The operator-authored `manifest.toml` now LIVES in `framework/`, so the
    // migration must never take the directory with it when it is non-empty.
    let tmp = TempDir::new().unwrap();
    let framework = tmp.path().join(".trusty-mpm").join("framework");
    write_file(&framework.join(COMPILED_PROMPT_FILE), "OLD");
    write_file(&framework.join("manifest.toml"), "[style]\n");

    remove_legacy_compiled_prompt(tmp.path()).expect("removal succeeds");
    assert!(
        framework.join("manifest.toml").exists(),
        "an operator's manifest override must survive the migration"
    );
}

#[test]
fn migrate_is_a_noop_when_absent() {
    let tmp = TempDir::new().unwrap();
    assert!(
        !remove_legacy_compiled_prompt(tmp.path()).expect("absence is not an error"),
        "nothing was removed, so the call must report false"
    );
}

#[test]
fn migrate_keeps_an_empty_framework_dir_when_nothing_migrated() {
    // #4841 review: `tm project init` seeds an empty `framework/` and this
    // migration runs on EVERY launch. Ungated, init created the directory and
    // the next launch deleted it.
    let tmp = TempDir::new().unwrap();
    let framework = tmp
        .path()
        .join(crate::core::harness_root::HARNESS_DIR)
        .join(crate::core::harness_root::FRAMEWORK_DIR);
    std::fs::create_dir_all(&framework).unwrap();

    assert!(
        !remove_legacy_compiled_prompt(tmp.path()).expect("absence is not an error"),
        "there was no legacy prompt to migrate"
    );
    assert!(
        framework.is_dir(),
        "a scaffolded, empty framework/ must survive a launch that migrated nothing"
    );
}

#[test]
fn instructions_failure_message_names_the_path_and_a_remedy() {
    // Why (#4752 ruling follow-up 1): the write is fatal, so a refused launch
    // must tell the operator what was refused, where, and what to do — not
    // surface a bare io error.
    let err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");
    let msg = instructions_failure_message(Path::new("/p/.trusty-mpm/framework/X.md"), &err);
    assert!(
        msg.contains("/p/.trusty-mpm/framework/X.md"),
        "must name the path: {msg}"
    );
    assert!(msg.contains("denied"), "must carry the cause: {msg}");
    assert!(
        msg.contains("was NOT started"),
        "must say the session did not start: {msg}"
    );
    assert!(msg.contains("permissions"), "must point at a remedy: {msg}");
}

#[test]
fn no_bundled_artifact_targets_the_compiled_prompt_path() {
    // Why (#4752): the defect was two writers on one path. This pins the
    // bundle-installer half — no entry in the canonical artifact table may
    // resolve to the compiled prompt's filename, at any depth, so the
    // `install_to` pass can never write there. A future artifact re-adding a
    // stub under that name turns this red instead of silently reintroducing
    // last-writer-wins.
    // What: scans `bundle::ALL` for any `rel_path` whose file name is
    // `COMPILED_PROMPT_FILE`.
    let clashing: Vec<&str> = crate::core::bundle::ALL
        .iter()
        .map(|a| a.rel_path)
        .filter(|p| Path::new(p).file_name().and_then(|n| n.to_str()) == Some(COMPILED_PROMPT_FILE))
        .collect();
    assert!(
        clashing.is_empty(),
        "no bundled artifact may target {COMPILED_PROMPT_FILE}; found {clashing:?}"
    );
}

#[test]
fn remove_stale_bundled_instructions_deletes_a_leftover() {
    // Why (#4752): a pre-#4752 install left the compiled prompt at
    // `instructions/INSTRUCTIONS.md`. Nothing writes it now but
    // `build_instructions` still reads it, so an upgraded machine would fold a
    // frozen old prompt into the pipeline forever. `tm install` removes it.
    let tmp = TempDir::new().unwrap();
    let paths = crate::core::paths::FrameworkPaths::under(tmp.path());
    let stale = paths.framework_instructions_path();
    write_file(&stale, "# an old compiled prompt\n");

    assert!(
        remove_stale_bundled_instructions(&stale).expect("removal succeeds"),
        "an existing leftover must be reported as removed"
    );
    assert!(!stale.exists(), "the stale leftover must be gone");
    // The compiled prompt is a DIFFERENT, project-local file.
    assert_ne!(stale, compiled_prompt_path(tmp.path(), "s"));
}

#[test]
fn remove_stale_bundled_instructions_is_a_noop_when_absent() {
    // Why: the common case is a fresh machine that never had the file. That
    // must not be an error, and must not report a removal.
    let tmp = TempDir::new().unwrap();
    let paths = crate::core::paths::FrameworkPaths::under(tmp.path());
    assert!(
        !remove_stale_bundled_instructions(&paths.framework_instructions_path())
            .expect("absence is not an error"),
        "nothing was removed, so the call must report false"
    );
}

#[test]
fn write_compiled_prompt_to_creates_parent_dirs() {
    // Why: the launch path calls this against a framework root that may not
    // exist yet on a machine that never ran `tm install`; a missing parent must
    // not fail the launch.
    // What: writes into a two-deep absent directory and reads the bytes back
    // verbatim.
    let tmp = TempDir::new().unwrap();
    let dest = tmp.path().join("a").join("b").join(COMPILED_PROMPT_FILE);
    write_compiled_prompt_to(&dest, "COMPILED-BODY").expect("write succeeds");
    assert_eq!(fs::read_to_string(&dest).unwrap(), "COMPILED-BODY");
}

/// Why (#7514): this write used to append an instruction-compression savings row
/// against `FrameworkPaths::default()` — which resolves under the operator's own
/// home — so every unit test that wrote a compiled prompt into a tempdir put a
/// synthetic row in the operator's real ledger and a marker in its
/// `usage/no-fold-warned/`. The `💸` statusline segment then reported a figure no
/// launch produced. A bare write must touch its destination and nothing else.
/// FAILS BEFORE THIS CHANGE: `<home>/.trusty-mpm/usage/` existed afterwards.
/// Test: itself.
#[test]
#[serial_test::serial]
fn a_bare_compiled_write_records_no_savings_row() {
    let tiers = RosterTiers::new();
    let project = tiers.project();
    let dest = compiled_prompt_path(&project, "sess-7514");
    // Above the #7491 floor and below the source set, so the producer WOULD
    // have recorded a row: what is asserted is that it is never asked to.
    let plausible = "x".repeat(
        crate::core::savings_instructions::min_plausible_compiled_bytes(
            crate::core::savings_instructions::SectionBytes::of(rc()),
        ) + 137,
    );

    write_compiled_prompt_to(&dest, &plausible).expect("write succeeds");

    assert_eq!(fs::read_to_string(&dest).unwrap(), plausible);
    assert!(
        !tiers.home().join(".trusty-mpm").join("usage").exists(),
        "a bare compiled write must not reach the operator's savings ledger"
    );
}

/// Why (#7514): the other half of the split — the recording write must land its
/// measurement in the root the CALLER named, or threading the root through
/// `prepare_session_inner` would be decoration. The fixture is LARGER than the
/// source set on purpose: the producer then takes the "folded nothing" branch,
/// which writes its marker before any model pricing, so the assertion does not
/// depend on whether this host's configured PM model is in the price table.
/// Test: itself.
///
/// #7746: uses [`write_compiled_prompt_recording_in_with`] and a fixed
/// zero-roster closure rather than [`write_compiled_prompt_recording_in`] and
/// the ambient [`crate::core::savings_instructions::ambient_source_bytes`].
/// The ambient path reads process-global `$CLAUDE_CONFIG_DIR`/`$HOME` TWICE —
/// once here, once again inside the write's own internal recomputation — and
/// a concurrently running `RosterTiers`-guarded test mutating either variable
/// between those two reads could make the second `source_bytes` disagree with
/// `sources` below, so `bulky` was no longer provably above the source set
/// and the "folded nothing" branch this test exercises did not fire. The
/// fixed closure removes both reads, so the two computations agree by
/// construction instead of by luck.
#[test]
fn a_recording_compiled_write_reaches_the_named_framework_root() {
    let root = TempDir::new().expect("framework root");
    let project = TempDir::new().expect("project");
    let dest = compiled_prompt_path(project.path(), "sess-7514");
    // #7616: the source set is no longer the bundled sections alone — it also
    // carries this machine's undeduped roster, so summing `SECTION_SOURCES` here
    // would undercount and the fixture would land on the folded branch instead.
    // #7746: the roster count itself is fixed at zero rather than read from the
    // ambient machine-global tiers — see the fn doc above for why.
    fn no_roster(_: &Path) -> usize {
        0
    }
    let sources = crate::core::savings_instructions::source_bytes_with(
        project.path(),
        crate::core::savings_instructions::SectionBytes::of(rc()),
        no_roster,
    );
    let bulky = "x".repeat(sources + 1);

    write_compiled_prompt_recording_in_with(rc(), root.path(), &dest, &bulky, no_roster)
        .expect("write succeeds");

    assert_eq!(fs::read_to_string(&dest).unwrap(), bulky);
    assert!(
        root.path().join("usage").join("no-fold-warned").exists(),
        "the fold must be measured against the framework root the caller named"
    );
}

#[test]
fn compiled_prompt_write_is_the_full_assembled_prompt_never_a_stub() {
    // Why (#383 regression guard, retained through #4752's path move): the
    // compiled file must only ever hold a FULL composed prompt. #383 was a
    // 4-line stub winning a last-writer race on the shared path; the path is
    // now project-local and single-writer, but the content contract still
    // needs pinning.
    // What: writes the bundled assembly to a project's compiled path and
    // asserts it is neither empty nor the historical stub.
    let tmp = TempDir::new().unwrap();
    let dest = compiled_prompt_path(tmp.path(), "s");
    write_compiled_prompt_to(&dest, &assemble_system_prompt(rc())).expect("write succeeds");

    let on_disk = fs::read_to_string(&dest).unwrap();
    assert_eq!(on_disk, assemble_system_prompt(rc()));
    assert!(!on_disk.trim().is_empty());
    assert!(
        !on_disk.trim().eq("# trusty-mpm Framework Instructions\n\nThis Claude Code instance is managed by trusty-mpm.\nDaemon endpoint: ${TRUSTY_MPM_URL:-http://localhost:7799}"),
        "stub content must never be written — full assembled prompt required"
    );
}

#[test]
fn primary_directive_mandate_not_duplicated_across_channels() {
    // Issue #2647 (R2): the FULL mandate table (Prohibitions, Circuit
    // Breakers, Delegation Map, PM Allowlist) must live in exactly ONE
    // channel — the appended system prompt (`assemble_system_prompt`,
    // always injected via `--append-system-prompt-file` on tm-driven
    // spawns). Before this fix, every bundled output-style file (loaded
    // independently via the Claude Code `outputStyle` settings key) ALSO
    // carried a full, near-identical restatement of that table —
    // duplicated tokens every session.
    //
    // Code-critic follow-up: `outputStyle` is deployed to
    // `<project>/.claude/output-styles/*.md` + `settings.json`
    // (`settings.rs`) and therefore applies to ANY `claude` launched in
    // that directory — including a manual `claude` invocation that never
    // receives `--append-system-prompt-file` at all
    // (`runtime/claude_code.rs`). A style with NOTHING but a pointer to
    // the appended prompt would leave such a launch with zero
    // enforcement. So each style keeps a short, SELF-CONTAINED minimal
    // mandate (PRIMARY DIRECTIVE statement, override-phrase list, a
    // prohibition summary) alongside the pointer to the full table —
    // this test asserts that block survived the dedup, not just that the
    // heading sentinel is de-duplicated.
    const SENTINEL: &str = "PRIMARY DIRECTIVE";
    let assembled = assemble_system_prompt(rc());
    assert_eq!(
        assembled.matches(SENTINEL).count(),
        0,
        "the appended system prompt must not carry a literal PRIMARY \
         DIRECTIVE banner — the mandate lives there as Identity + \
         Prohibitions content"
    );

    // The appended prompt must still carry the substantive, canonical
    // mandate content — so the mandate can never silently vanish from
    // BOTH channels at once just because the banner text moved.
    assert!(
        assembled.contains("## Prohibitions"),
        "the appended prompt must carry the canonical Prohibitions table"
    );
    assert!(
        assembled.contains("## Circuit Breakers"),
        "the appended prompt must carry the canonical Circuit Breakers table"
    );
    assert!(
        assembled.contains("don't delegate"),
        "the appended prompt must carry at least one override phrase"
    );

    // #8453: PM styles only — a supervisor session receives neither this
    // prompt nor a PRIMARY DIRECTIVE.
    for style in crate::core::bundle::pm_output_styles() {
        let combined =
            assembled.matches(SENTINEL).count() + style.content(rc()).matches(SENTINEL).count();
        assert_eq!(
            combined, 1,
            "{}: PRIMARY DIRECTIVE sentinel must appear exactly once across \
             the appended prompt + this output style (one heading, never a \
             full restatement of the mandate TABLE) — got {combined}",
            style.id
        );

        // Each style must still carry its OWN self-contained minimal
        // mandate — the override-phrase list and a prohibition summary —
        // so a manual `claude` launch (no --append-system-prompt-file)
        // in a tm-provisioned workspace is never left with zero
        // enforcement.
        assert!(
            style.content(rc()).contains("do this yourself"),
            "{}: must carry its own self-contained override-phrase list",
            style.id
        );
        assert!(
            style.content(rc()).contains("Minimum prohibitions"),
            "{}: must carry its own self-contained prohibition summary",
            style.id
        );
    }
}

#[serial_test::serial]
#[test]
fn pipeline_no_agents_still_succeeds() {
    // Every tier empty yields a zero agent_count, and the delegation section
    // the PM receives says so. #4832: the section is asserted through the
    // resolver that renders it, since the pipeline no longer returns text.
    let tiers = RosterTiers::new();
    let input = input_in(&tiers);

    let out = build_instructions(&input).unwrap();
    assert_eq!(out.agent_count, 0);
    let authority = crate::core::delegation_authority::generate_authority(&[]);
    assert!(authority.to_lowercase().contains("no delegatable agents"));
}

#[serial_test::serial]
#[test]
fn session_start_count_matches_the_delivered_delegation_roster() {
    // THE #4588 GATE. `tm session start` prints
    // `Instructions: {agent_count} agents in delegation authority` straight
    // from `PipelineOutput::agent_count`, while the roster the PM actually
    // receives is rendered by `deployed_roster_section`. Those were two
    // independent resolutions — a single-directory scan versus a three-tier
    // union — so the printed number understated the delivered roster (34 vs 39
    // measured live on tm 1.3.1). Both must now come from ONE resolver, which
    // is what this asserts: not that the number is plausible, but that it is
    // the SAME number, computed the same way, over a roster spanning all three
    // tiers with a deliberate cross-tier duplicate.
    let tiers = RosterTiers::new();

    write_roster_agent(&tiers.managed_tier(), "engineer");
    write_roster_agent(&tiers.managed_tier(), "qa");
    write_roster_agent(&tiers.generic_tier(), "writer");
    write_roster_agent(&tiers.project_tier(), "ticketing");
    // Deployed in two tiers at once — the union must advertise it exactly once,
    // so a naive concatenation cannot pass this test either.
    write_roster_agent(&tiers.generic_tier(), "qa");

    let input = PipelineInput {
        project_dir: tiers.project(),
        claude_md_path: tiers.project().join("CLAUDE.md"),
        home: Some(tiers.home()),
    };

    let out = build_instructions(&input).expect("pipeline");
    let delivered = crate::core::delegation_authority::deployed_roster_section(&tiers.project())
        .expect("a roster is deployed in three tiers, so a section must render");
    let delivered_entries = delivered.matches("\n### ").count();
    // #4513: the PM now receives the roster in TWO listings — the harness's own
    // agent-type listing, and this section for the tiers the harness does not
    // load. The gate is unchanged in meaning: every agent the printed count
    // claims must be reachable by the PM through one of them.
    let harness_published = crate::core::delegation_authority::roster_from_dirs(
        &crate::core::delegation_authority::harness_loaded_agent_dirs(&tiers.project()),
    )
    .len();

    assert_eq!(
        out.agent_count,
        delivered_entries + harness_published,
        "the count `tm session start` prints must equal the number of agents \
         the PM was actually given (#4588)\nprinted: {}\nharness-published: \
         {harness_published}\ndelivered roster:\n{delivered}",
        out.agent_count
    );
    assert_eq!(
        out.agent_count, 4,
        "engineer + qa + writer + ticketing, with the cross-tier `qa` counted once"
    );
    assert_eq!(
        delivered_entries, 1,
        "only `writer` sits in a tier the harness cannot publish (#4513); the \
         other three must not be repeated:\n{delivered}"
    );
}

#[serial_test::serial]
#[test]
fn the_composed_prompt_names_only_the_agents_the_harness_cannot_publish() {
    // #4513 END-TO-END. The two halves the PM must receive: every agent Claude
    // Code loads for itself is accounted for by a count, and every agent it does
    // NOT load still arrives as a full entry with its model hint — otherwise the
    // cut would make an agent invisible rather than merely unrepeated.
    let tiers = RosterTiers::new();
    write_roster_agent(&tiers.managed_tier(), "rust-engineer");
    write_roster_agent(&tiers.project_tier(), "ticketing");
    // Written by hand rather than via `write_roster_agent`: this one must carry
    // a `model:`, so the assertion below can prove the roster's own field
    // survives the cut and is not merely the header text.
    fs::create_dir_all(tiers.generic_tier()).expect("create generic tier");
    fs::write(
        tiers.generic_tier().join("copyeditor.md"),
        "---\nname: copyeditor\nrole: editor\nmodel: sonnet\n---\n",
    )
    .expect("write copyeditor");

    let prompt = crate::core::instruction_overrides::resolve_pm_prompt(rc(), &tiers.project());

    assert!(
        prompt.contains("## Delegation Authority"),
        "the roster header must survive the cut:\n{prompt}"
    );
    assert!(
        prompt.contains("the 2 agents it carries"),
        "the two harness-loaded tiers must be accounted for by count"
    );
    assert!(
        !prompt.contains("### rust-engineer") && !prompt.contains("### ticketing"),
        "a harness-published agent must not be repeated"
    );
    assert!(
        prompt.contains("### copyeditor"),
        "an agent in the home tier is published NOWHERE else and must be named"
    );
    assert!(
        prompt.contains("**Model:** sonnet"),
        "the roster's own value — the model hint — must still reach the prompt"
    );
}

// ── #4752 round 4: the shared fatal compiled-prompt refresh ─────────────────

#[test]
fn refresh_compiled_prompt_writes_the_project_local_file() {
    // Why (#4752 round 4): this is the single entry point all THREE pre-spawn
    // paths now route through — fresh start, daemon resume, and the bare-`tm`
    // in-place relaunch that round 3 missed entirely. Pinning it directly means
    // the guarantee is asserted on the implementation, not only through the
    // daemon's thin `refresh_resume_compiled_prompt` delegate.
    //
    // FIXTURE: a stale sentinel is pre-seeded so "the file exists" cannot pass;
    // only a real refresh overwrites it.
    //
    // #7514: driven through the root-taking seam, so the fold this composes is
    // recorded under `root` rather than the operator's own `~/.trusty-mpm`.
    let root = TempDir::new().expect("framework root");
    let tmp = TempDir::new().expect("tempdir");
    let dest = compiled_prompt_path(tmp.path(), "sess-1");
    fs::create_dir_all(dest.parent().expect("has a parent")).expect("create parent");
    const STALE: &str = "STALE-FROM-A-PREVIOUS-LAUNCH";
    fs::write(&dest, STALE).expect("seed stale");

    refresh_compiled_prompt_in(root.path(), tmp.path(), "sess-1").expect("refresh must succeed");

    let on_disk = fs::read_to_string(&dest).expect("readable");
    assert_ne!(
        on_disk, STALE,
        "a stale compiled prompt must be overwritten"
    );
    assert!(
        on_disk.contains("# PM Agent -- Trusty MPM"),
        "must hold the resolved PM prompt, not a fragment: {on_disk}"
    );
    assert!(
        dest.starts_with(tmp.path()),
        "the compiled prompt is PROJECT-LOCAL; a global path would restore the \
         cross-project collision #4752 removed"
    );
}

#[test]
fn refresh_compiled_prompt_reports_an_actionable_failure() {
    // Why (#4752): the write is fatal at all three call sites, so a refusal is
    // operator-facing — it must name the path and say the session did not
    // start, never surface a bare io error.
    //
    // FIXTURE: a directory planted at the exact destination, so only this write
    // fails and nothing else in the compose path does.
    // #7514: root-taking seam, so a failed refresh cannot touch the operator's
    // ledger on its way to the error.
    let root = TempDir::new().expect("framework root");
    let tmp = TempDir::new().expect("tempdir");
    let dest = compiled_prompt_path(tmp.path(), "sess-1");
    fs::create_dir_all(&dest).expect("plant a directory at the compiled path");

    let msg = refresh_compiled_prompt_in(root.path(), tmp.path(), "sess-1")
        .expect_err("a failed compiled write must be reported as an error");
    assert!(
        msg.contains(&dest.display().to_string()),
        "must name the path: {msg}"
    );
    assert!(
        msg.contains("was NOT started"),
        "must say the session did not start: {msg}"
    );
    assert!(msg.contains("permissions"), "must point at a remedy: {msg}");
}

/// #9012: resume and in-place relaunch gate on this refresh; with no content
/// it refuses, naming `tm content install`, and writes no compiled prompt.
#[test]
fn refresh_compiled_prompt_without_content_names_tm_content_install() {
    let root = TempDir::new().expect("framework root");
    let project = TempDir::new().expect("project outside any checkout");
    let cache = TempDir::new().expect("empty content cache");
    let dest = compiled_prompt_path(project.path(), "sess-1");

    let msg = refresh_compiled_prompt_loading(root.path(), project.path(), "sess-1", |_| {
        crate::core::content_source::framework_content_in(
            cache.path(),
            crate::core::content_source::DevOverride::Off,
        )
    })
    .expect_err("no content installed");
    assert!(msg.contains("tm content install"), "{msg}");
    assert!(msg.contains("tm content update"), "{msg}");
    assert!(
        !dest.exists(),
        "a refused refresh writes no compiled prompt"
    );
}

/// Make `path` unreadable; `false` when the platform or privileges prevent it.
fn deny_read_pipeline(path: &Path) -> bool {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if fs::set_permissions(path, fs::Permissions::from_mode(0o000)).is_err() {
            return false;
        }
        fs::read_to_string(path).is_err()
    }
    #[cfg(not(unix))]
    {
        let _ = path;
        false
    }
}

#[test]
fn build_instructions_reports_an_unreadable_agent_file() {
    // #5544 review: `agent_count` is what `tm session start` prints. It came
    // from the non-reporting `resolve_roster`, so an agent file that could not
    // be read lowered the number with nothing carried out of the pipeline to
    // say so — the count read as a total when it was a floor.
    let project = TempDir::new().unwrap();
    let tier = project.path().join(".claude").join("agents");
    fs::create_dir_all(&tier).unwrap();
    let locked = tier.join("qa.md");
    fs::write(&locked, "---\nname: qa\n---\n\n# Q\n").unwrap();
    if !deny_read_pipeline(&locked) {
        eprintln!("skipping: cannot deny read on this platform/privilege level");
        return;
    }

    let out = build_instructions(&PipelineInput {
        project_dir: project.path().to_path_buf(),
        claude_md_path: project.path().join("CLAUDE.md"),
        home: None,
    })
    .expect("pipeline succeeds — the roster stays fail-open");

    assert!(
        !out.roster_is_complete(),
        "a failed roster read must make the count self-declare as partial"
    );
    assert!(
        out.unreadable_agent_paths.contains(&locked),
        "the lost path must reach the caller: {:?}",
        out.unreadable_agent_paths
    );

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let _ = fs::set_permissions(&locked, fs::Permissions::from_mode(0o600));
    }
}

#[test]
fn build_instructions_reports_a_complete_roster_when_nothing_failed() {
    // The healthy path must keep saying so, or the flag above is not a signal.
    let project = TempDir::new().unwrap();
    let out = build_instructions(&PipelineInput {
        project_dir: project.path().to_path_buf(),
        claude_md_path: project.path().join("CLAUDE.md"),
        home: None,
    })
    .expect("pipeline succeeds");
    assert!(out.roster_is_complete());
    assert!(out.unreadable_agent_paths.is_empty());
}

/// FAILS BEFORE THIS ROUND (#7673 round 2 review, MEDIUM): three seed tests
/// passed the real `$HOME` into `load_or_create_claude_md`, so their outcome
/// depended on where the developer's home directory sits relative to the
/// temp dir. Every seed test here must pass a fixture home instead.
#[test]
fn no_seed_test_reads_the_ambient_home_directory() {
    let source = include_str!("instruction_pipeline_tests.rs");
    let needle = concat!("dirs::", "home_dir()");
    assert_eq!(
        source.matches(needle).count(),
        0,
        "pass a fixture home under the test's temp dir, not the ambient one"
    );
}

/// The backtick-quoted words in `stub` between `from` and the next `until`,
/// with line wrapping folded to single spaces so a re-wrap cannot move them.
fn quoted_tokens_between(stub: &str, from: &str, until: &str) -> Vec<String> {
    let flat = stub.split_whitespace().collect::<Vec<_>>().join(" ");
    let start = flat.find(from).expect("stub carries the opening phrase") + from.len();
    let len = flat[start..]
        .find(until)
        .expect("stub carries the closing phrase");
    flat[start..start + len]
        .split('`')
        .skip(1)
        .step_by(2)
        .map(str::to_string)
        .collect()
}

/// #8533: the seeded `CLAUDE.md` named the pre-split token set, so a new
/// project was told `CORE` held the allowlist, phases and QA gate it no longer
/// does. Both lists are checked against the one source of truth — every
/// overridable `SectionId`, and every overridable section owning a safety-core
/// member — so a new section or a new core member fails here until the stub
/// names it.
#[test]
fn the_stub_lists_exactly_the_overridable_section_tokens() {
    use crate::core::claude_md_sections::section_token;
    use crate::core::instruction_package::SectionId;
    use crate::core::instruction_safety_core::{SAFETY_CORE, is_fixed_core_section};

    let mut overridable = quoted_tokens_between(CLAUDE_MD_STUB, "Tokens:", " is the one token");
    let fixed = overridable.split_off(overridable.len().saturating_sub(1));
    let expected: Vec<&str> = SectionId::CANONICAL
        .into_iter()
        .filter(|id| !is_fixed_core_section(*id))
        .map(section_token)
        .collect();
    assert_eq!(overridable, expected, "the stub's Tokens: list");
    let expected_fixed: Vec<&str> = SectionId::CANONICAL
        .into_iter()
        .filter(|id| is_fixed_core_section(*id))
        .map(section_token)
        .collect();
    assert_eq!(
        fixed, expected_fixed,
        "the one token the stub says is declined"
    );

    let keeps_core = quoted_tokens_between(CLAUDE_MD_STUB, "An override of", "replaces");
    let mut expected_core: Vec<&str> = SAFETY_CORE
        .iter()
        .filter(|m| !is_fixed_core_section(m.section))
        .map(|m| section_token(m.section))
        .collect();
    expected_core.dedup();
    assert_eq!(keeps_core, expected_core, "sections that keep a core block");
    for member in SAFETY_CORE
        .iter()
        .filter(|m| !is_fixed_core_section(m.section))
    {
        assert!(
            CLAUDE_MD_STUB.contains(&member.name.to_lowercase()),
            "the stub names safety-core member `{}`",
            member.name
        );
    }
}