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
//! Unit tests for [`super`] — the PM prompt composer and the retired-override
//! detector.
//!
//! Split out of `instruction_overrides.rs` by #4286: restoring coverage for the
//! roster-absent memory slot and the unapplied-section report pushed the parent
//! file to 538 SLOC, over the 500 production cap. Same `#[path]` split
//! `claude_md_sections.rs` already uses.

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

/// Write `<project>/.trusty-mpm/<name>` with `content`, creating dirs.
fn write_override(project: &Path, name: &str, content: &str) {
    let dir = project.join(OVERRIDE_DIR_NAME);
    fs::create_dir_all(&dir).expect("create .trusty-mpm");
    fs::write(dir.join(name), content).expect("write override");
}

/// Deploy a composed agent into the PROJECT tier (`<project>/.claude/agents`).
///
/// Why: the project tier is the highest-precedence roster source and the one
/// the daemon managed-spawn path actually deploys into, so a test that writes
/// here asserts the real launch shape without depending on the machine's
/// `~/.claude/agents` (which these tests must never require or forbid).
fn deploy_agent(project: &Path, name: &str) {
    let dir = project.join(".claude").join("agents");
    fs::create_dir_all(&dir).expect("create .claude/agents");
    fs::write(
        dir.join(format!("{name}.md")),
        format!(
            "---\nname: {name}\nrole: {name}\ndescription: Handles {name} work.\n\
             model: sonnet\n---\n\n# {name}\n"
        ),
    )
    .expect("write agent");
}

#[test]
fn bundled_delegation_appends_deployed_roster() {
    // Issue #4069 REGRESSION GATE. The delegation section must describe the
    // agents that are actually deployed, not the static asset's
    // hand-maintained table. `ticketing` and `memory-manager` are deployed
    // in reality but appear NOWHERE in any bundled asset, so a section that
    // accounts for exactly those two can only come from the live scan.
    // Against the pre-fix code this assertion fails: `resolve_pm_prompt`
    // returned the static `rc().required("sections/agent-delegation.md").md` verbatim.
    //
    // #4513 changed HOW the live scan reaches the prompt for these two. They
    // are deployed into `<project>/.claude/agents`, a tier Claude Code loads
    // itself, so the harness's own Agent-type listing already carries them and
    // the roster states the count instead of repeating the names. The count is
    // still live-scan output — no static asset can produce it.
    let tmp = TempDir::new().unwrap();
    deploy_agent(tmp.path(), "ticketing");
    deploy_agent(tmp.path(), "memory-manager");

    let prompt = resolve_pm_prompt(rc(), tmp.path());

    assert!(
        prompt.contains("## Delegation Authority"),
        "the live roster section must be present"
    );
    // Re-derived rather than hard-coded: the union spans the machine's own
    // tiers too, so only the same computation is stable across machines. Both
    // deployed agents are inside this number — the temp project tier is one of
    // the harness-loaded tiers.
    let harness_published = crate::core::delegation_authority::roster_from_dirs(
        &crate::core::delegation_authority::harness_loaded_agent_dirs(tmp.path()),
    )
    .len();
    assert!(
        harness_published >= 2,
        "the two deployed agents must be in the harness-loaded union"
    );
    assert!(
        prompt.contains(&format!("the {harness_published} agents it carries")),
        "the live scan must account for both deployed agents (#4069, #4513)"
    );
    assert!(
        !prompt.contains("### ticketing") && !prompt.contains("### memory-manager"),
        "the harness publishes both; repeating them is the #4513 duplication"
    );
    assert!(
        !prompt.contains("Handles ticketing work."),
        "the agent `description` is already published by the harness's Agent-type \
         catalog; re-emitting it as `Handles:` made the roster a second copy"
    );

    // The bundled routing doctrine is APPENDED to, never replaced: the roster
    // carries no make/mise or keyword routing rules, which live in the single
    // Routing Table the six former routing surfaces were collapsed into.
    assert!(prompt.contains("# Agent Delegation Routing"));
    assert!(prompt.contains("## Routing Table"));
    assert!(prompt.contains("every `make` and `mise run` target"));

    // Review HIGH-2 / MEDIUM-2: the two blocks contradict each other on
    // concrete points, and the roster is a tier UNION that no single launch
    // mode fully loads. Both are resolved by the note between them, which
    // must be present whenever a roster is rendered.
    assert!(
        prompt.contains("authoritative for WHICH agents exist"),
        "#4513: the harness's own listing, not the roster, is now the block \
         declared authoritative over the stale doctrine table"
    );
    assert!(
        prompt.contains("re-route to the closest listed alternative"),
        "an advertised-but-unloadable agent must carry a recovery instruction"
    );

    // Ordering: doctrine first, note, roster after, BASE_PM floor last.
    let doctrine = prompt.find("# Agent Delegation Routing").expect("doctrine");
    let note = prompt
        .find("authoritative for WHICH agents exist")
        .expect("note");
    let roster = prompt.find("## Delegation Authority").expect("roster");
    let base = prompt.find("## Prohibitions (CANONICAL").expect("base");
    assert!(doctrine < note, "doctrine precedes the note");
    assert!(note < roster, "the note precedes the roster it governs");
    assert!(roster < base, "BASE_PM floor stays last");
}

#[test]
fn no_overrides_uses_bundled() {
    // No `.trusty-mpm/` dir at all → the bundled four sections are present
    // and BASE_PM is the last section.
    let tmp = TempDir::new().unwrap();
    let prompt = resolve_pm_prompt(rc(), tmp.path());

    assert!(prompt.contains("# PM Agent -- Trusty MPM"));
    assert!(prompt.contains("# PM Workflow Configuration"));
    assert!(prompt.contains("# Agent Delegation Routing"));
    assert!(prompt.contains("## Prohibitions (CANONICAL"));

    let base = prompt.find("## Prohibitions (CANONICAL").expect("base");
    let delegation = prompt.find("# Agent Delegation Routing").expect("deleg");
    assert!(base > delegation, "BASE_PM floor must be last");
}

// RETIREMENT GATES (#4286). Each of the six tests below was previously the
// assertion that a `.trusty-mpm/` file DID override, and each is now
// inverted to assert it does NOT. They are inverted rather than deleted on
// purpose: an inverted test still fails if someone reinstates the read path,
// whereas a deleted one would let the whole mechanism come back unnoticed.

#[test]
fn a_retired_instructions_file_no_longer_reaches_the_prompt() {
    // Was `instructions_appended`. This is the file that actually exists in
    // the field, so it is the retirement's highest-blast-radius case.
    let tmp = TempDir::new().unwrap();
    write_override(
        tmp.path(),
        FILE_INSTRUCTIONS,
        "# Project Rules\n\nALWAYS_RUN_MAKE_CHECK\n",
    );
    let prompt = resolve_pm_prompt(rc(), tmp.path());

    assert!(
        !prompt.contains("ALWAYS_RUN_MAKE_CHECK"),
        "a retired INSTRUCTIONS.md must not contribute to the prompt"
    );
    // The bundled sections are unaffected.
    assert!(prompt.contains("# PM Agent -- Trusty MPM"));
    assert!(prompt.contains("# Agent Delegation Routing"));
    assert!(prompt.contains("## Prohibitions (CANONICAL"));
}

#[test]
fn a_retired_workflow_file_no_longer_replaces_the_workflow_section() {
    // Was `workflow_override_replaces`. The bundled workflow heading now
    // SURVIVES, which is the exact inversion.
    let tmp = TempDir::new().unwrap();
    write_override(
        tmp.path(),
        FILE_WORKFLOW,
        "# Custom Workflow\n\nTWO_PHASE_ONLY\n",
    );
    let prompt = resolve_pm_prompt(rc(), tmp.path());

    assert!(!prompt.contains("TWO_PHASE_ONLY"));
    assert!(
        prompt.contains("# PM Workflow Configuration"),
        "the bundled workflow section must survive a retired WORKFLOW.md"
    );
}

#[test]
fn a_retired_delegation_file_no_longer_suppresses_the_live_roster() {
    // Was `agent_delegation_override_replaces`. This inversion also closes
    // the #4069 defect by construction: the retired file can no longer
    // suppress the live roster, because it is not read at all.
    let tmp = TempDir::new().unwrap();
    deploy_agent(tmp.path(), "ticketing");
    write_override(
        tmp.path(),
        FILE_AGENT_DELEGATION,
        "# Custom Routing\n\nROUTE_ALL_TO_ENGINEER\n",
    );
    let prompt = resolve_pm_prompt(rc(), tmp.path());

    assert!(!prompt.contains("ROUTE_ALL_TO_ENGINEER"));
    assert!(prompt.contains("# Agent Delegation Routing"));
    let harness_published = crate::core::delegation_authority::roster_from_dirs(
        &crate::core::delegation_authority::harness_loaded_agent_dirs(tmp.path()),
    )
    .len();
    assert!(
        prompt.contains(&format!("the {harness_published} agents it carries")),
        "the live roster must reach the prompt — a retired file cannot suppress \
         it. #4513: `ticketing` sits in the project tier, which the harness loads \
         itself, so the live scan reaches the prompt as the count rather than as \
         a `### ticketing` entry."
    );
}

#[test]
fn a_retired_memory_file_no_longer_slots_a_memory_block() {
    // Was `memory_override_is_slotted_after_pm_instructions`.
    let tmp = TempDir::new().unwrap();
    write_override(
        tmp.path(),
        FILE_MEMORY,
        "Recall from the `team` palace before any task.\n",
    );
    let prompt = resolve_pm_prompt(rc(), tmp.path());

    assert!(!prompt.contains(MEMORY_OVERRIDE_HEADING));
    assert!(!prompt.contains("Recall from the `team` palace"));
    assert!(prompt.contains("# PM Agent -- Trusty MPM"));
}

#[test]
fn a_retired_deployed_file_no_longer_replaces_the_body() {
    // Was `pm_deployed_replaces_body_but_keeps_base_floor`. This was the
    // most destructive of the five — a full-body replacement — so the
    // inversion asserts every bundled section is back.
    let tmp = TempDir::new().unwrap();
    write_override(
        tmp.path(),
        FILE_PM_DEPLOYED,
        "# Wholly Custom PM\n\nDO_EXACTLY_THIS\n",
    );
    let prompt = resolve_pm_prompt(rc(), tmp.path());

    assert!(!prompt.contains("DO_EXACTLY_THIS"));
    assert!(prompt.contains("# PM Agent -- Trusty MPM"));
    assert!(prompt.contains("# PM Workflow Configuration"));
    assert!(prompt.contains("# Agent Delegation Routing"));
    assert!(prompt.contains("## Prohibitions (CANONICAL"));
    assert!(prompt.contains("## Trusty Tool Priority (Non-Overridable)"));
}

#[test]
fn every_retired_file_present_at_once_changes_nothing() {
    // Was `pm_deployed_still_appends_instructions`. The strongest form of
    // the retirement claim: a project carrying ALL FIVE files receives
    // byte-for-byte the prompt of a project carrying none.
    let with = TempDir::new().unwrap();
    for name in LEGACY_OVERRIDE_FILES {
        write_override(with.path(), name, &format!("CONTENT_OF_{name}\n"));
    }
    let without = TempDir::new().unwrap();

    let (with_prompt, _) =
        resolve_pm_prompt_with_roster(rc(), with.path(), || Some("## Delegation Authority".into()));
    let (without_prompt, _) = resolve_pm_prompt_with_roster(rc(), without.path(), || {
        Some("## Delegation Authority".into())
    });

    assert_eq!(
        with_prompt, without_prompt,
        "the five retired files must have zero effect on the composed prompt"
    );
}

#[test]
fn a_named_memory_override_is_slotted_on_the_roster_absent_path() {
    // COVERAGE RESTORED (#4286). `MEMORY_OVERRIDE_HEADING` is still live —
    // `assemble_sections` slots a MEMORY override as a delimited block — but
    // its only test drove it through the retired `.trusty-mpm/MEMORY.md`
    // file. Retiring that file left the behaviour real and untested. The
    // surviving way to reach it is a CLAUDE.md `MEMORY` block on the
    // roster-absent path, which is what this covers.
    let tmp = TempDir::new().unwrap();
    fs::write(
        tmp.path().join("CLAUDE.md"),
        "<!-- TRUSTY-MPM: MEMORY START v=1 -->\n\
         Recall from the `team` palace before any task.\n\
         <!-- TRUSTY-MPM: MEMORY END -->\n",
    )
    .unwrap();

    let (prompt, source) = resolve_pm_prompt_with_roster(rc(), tmp.path(), || None);
    assert_eq!(source, PromptSource::Legacy, "no roster -> string assembly");

    assert!(prompt.contains(MEMORY_OVERRIDE_HEADING));
    assert!(prompt.contains("Recall from the `team` palace"));

    let pm = prompt.find("# PM Agent -- Trusty MPM").expect("pm");
    let mem = prompt.find(MEMORY_OVERRIDE_HEADING).expect("mem");
    let wf = prompt
        .find("# PM Workflow Configuration")
        .expect("bundled workflow");
    assert!(pm < mem, "the memory block follows PM_INSTRUCTIONS");
    assert!(mem < wf, "and precedes the workflow section");
}

#[test]
fn unaddressable_sections_are_reported_unapplied_on_the_roster_absent_path() {
    // COVERAGE RESTORED (#4286). The string assembly can address only
    // rc().required("sections/workflow.md"), MEMORY and AGENT-DELEGATION. Overrides for any other section
    // are handed to `warn_unapplied` rather than dropped in silence — that
    // call is still live, and its test went with the #4399 cluster.
    //
    // Asserted in its observable form: the override body must NOT appear
    // (it could not be applied), while the bundled section survives.
    let tmp = TempDir::new().unwrap();
    fs::write(
        tmp.path().join("CLAUDE.md"),
        "<!-- TRUSTY-MPM: SEARCH START v=1 -->\n\
         UNAPPLIED_SEARCH_BODY\n\
         <!-- TRUSTY-MPM: SEARCH END -->\n\n\
         <!-- TRUSTY-MPM: WORKFLOW START v=1 -->\n\
         APPLIED_WORKFLOW_BODY\n\
         <!-- TRUSTY-MPM: WORKFLOW END -->\n",
    )
    .unwrap();

    let (prompt, source) = resolve_pm_prompt_with_roster(rc(), tmp.path(), || None);
    assert_eq!(source, PromptSource::Legacy);

    assert!(
        !prompt.contains("UNAPPLIED_SEARCH_BODY"),
        "SEARCH has no slot in the string assembly and must not land"
    );
    // ...and the section it aimed at is still delivered from the bundle.
    assert!(prompt.contains("## Code Search Protocol (Context-First)"));
    // The addressable sibling in the same file still applies, which is what
    // makes the negative above a real limitation rather than a dropped file.
    assert!(prompt.contains("APPLIED_WORKFLOW_BODY"));
}

#[test]
fn legacy_override_files_are_the_five_retired_names() {
    // Pins the detector's set against the individual constants, so adding a
    // sixth name to one place and not the other is a red test rather than a
    // file that is silently never detected.
    assert_eq!(
        LEGACY_OVERRIDE_FILES,
        [
            "PM_INSTRUCTIONS_DEPLOYED.md",
            "AGENT_DELEGATION.md",
            "WORKFLOW.md",
            "MEMORY.md",
            "INSTRUCTIONS.md",
        ]
    );
}

#[test]
fn no_legacy_files_detected_in_a_clean_project() {
    let tmp = TempDir::new().unwrap();
    assert!(detect_legacy_overrides(tmp.path()).is_empty());
    // A `.trusty-mpm/` directory holding only non-override state is clean.
    fs::create_dir_all(tmp.path().join(OVERRIDE_DIR_NAME)).unwrap();
    fs::write(
        tmp.path()
            .join(OVERRIDE_DIR_NAME)
            .join("last-instructions.md"),
        "composed",
    )
    .unwrap();
    assert!(detect_legacy_overrides(tmp.path()).is_empty());
}

#[test]
fn every_retired_file_is_detected() {
    let tmp = TempDir::new().unwrap();
    for name in LEGACY_OVERRIDE_FILES {
        write_override(tmp.path(), name, "x\n");
    }
    let found = detect_legacy_overrides(tmp.path());
    assert_eq!(found.len(), LEGACY_OVERRIDE_FILES.len());
    for name in LEGACY_OVERRIDE_FILES {
        assert!(
            found.iter().any(|p| p.ends_with(name)),
            "detector missed {name}"
        );
    }
}

#[test]
fn legacy_file_signal_names_the_migration() {
    // The migration hint is what turns a failure into an actionable one; it
    // must name the destination surface AND the marker grammar.
    assert!(LEGACY_MIGRATION_HINT.contains("CLAUDE.md"));
    assert!(LEGACY_MIGRATION_HINT.contains("TRUSTY-MPM:"));
    assert!(LEGACY_MIGRATION_HINT.contains("#4286"));
}

#[test]
fn missing_override_dir_uses_bundled() {
    // A `.trusty-mpm/` directory that does not exist is not an error.
    let tmp = TempDir::new().unwrap();
    assert!(!tmp.path().join(OVERRIDE_DIR_NAME).exists());
    let prompt = resolve_pm_prompt(rc(), tmp.path());
    assert!(prompt.contains("# PM Agent -- Trusty MPM"));
    assert!(prompt.contains("## Prohibitions (CANONICAL"));
}

#[test]
fn a_directory_in_a_retired_files_place_is_not_detected_and_not_fatal() {
    // Was `unreadable_override_falls_back`. The detector uses `is_file`, so
    // a directory sitting where a retired file would be is NOT reported —
    // reporting it would send the operator to migrate a directory. The
    // launch must also still succeed.
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join(OVERRIDE_DIR_NAME);
    fs::create_dir_all(&dir).unwrap();
    fs::create_dir(dir.join(FILE_WORKFLOW)).unwrap();

    assert!(detect_legacy_overrides(tmp.path()).is_empty());
    let prompt = resolve_pm_prompt(rc(), tmp.path());
    assert!(prompt.contains("# PM Workflow Configuration"));
    assert!(prompt.contains("## Prohibitions (CANONICAL"));
}

#[test]
fn an_empty_retired_file_is_still_detected() {
    // Was `empty_override_falls_back`. Emptiness used to mean "no override";
    // it now means nothing at all for composition, but the file must still
    // be REPORTED — an empty leftover is still a file the operator has to
    // delete, and staying silent about it leaves `tm doctor` green with a
    // retired file on disk.
    let tmp = TempDir::new().unwrap();
    write_override(tmp.path(), FILE_WORKFLOW, "   \n\t\n");

    assert_eq!(detect_legacy_overrides(tmp.path()).len(), 1);
    let prompt = resolve_pm_prompt(rc(), tmp.path());
    assert!(prompt.contains("# PM Workflow Configuration"));
    assert!(prompt.contains("## Prohibitions (CANONICAL"));
}

#[test]
fn separators_are_consistent() {
    // The resolved prompt uses the same `---` rule the bundled assembler
    // uses, so the two never visually diverge.
    let tmp = TempDir::new().unwrap();
    let prompt = resolve_pm_prompt(rc(), tmp.path());
    assert!(prompt.contains(SECTION_SEPARATOR));
}

#[test]
fn stack_profile_present_when_detected() {
    // A detected project (Cargo.toml) folds in the auto-derived stack profile
    // right after PM_INSTRUCTIONS and before the BASE_PM floor, routing to the
    // detected engineer — never a hardcoded default (#1971).
    use crate::core::stack_profile::STACK_PROFILE_HEADING;
    let tmp = TempDir::new().unwrap();
    fs::write(tmp.path().join("Cargo.toml"), "[package]\nname=\"x\"\n").unwrap();

    let prompt = resolve_pm_prompt(rc(), tmp.path());
    assert!(prompt.contains(STACK_PROFILE_HEADING));
    assert!(prompt.contains("`rust-engineer`"));

    let pm = prompt.find("# PM Agent -- Trusty MPM").expect("pm");
    let stack = prompt.find(STACK_PROFILE_HEADING).expect("stack");
    let base = prompt.find("## Prohibitions (CANONICAL").expect("base");
    assert!(pm < stack, "stack profile follows PM_INSTRUCTIONS");
    assert!(stack < base, "stack profile precedes the BASE_PM floor");
}

#[test]
fn stack_profile_neutral_when_undetected() {
    // An unknown project type yields a neutral, detect-first profile — the PM
    // is told NOT to assume any stack rather than inheriting a default.
    use crate::core::stack_profile::STACK_PROFILE_HEADING;
    let tmp = TempDir::new().unwrap();
    let prompt = resolve_pm_prompt(rc(), tmp.path());
    assert!(prompt.contains(STACK_PROFILE_HEADING));
    assert!(prompt.contains("Do NOT assume any stack"));
}

#[test]
fn framework_guaranteed_conventions_survive_every_override_combination() {
    // Issue #3374 (mirrors `primary_directive_mandate_not_duplicated_across_
    // channels` in instruction_pipeline.rs): the proportional-documentation
    // policy and the ticket-attribution-at-change-site convention must live in
    // the BASE_PM floor and therefore survive EVERY override combination —
    // including the full-PM-replacement branch, where every bundled body
    // section is discarded but the floor is still appended.
    //
    // #6807: the commit/PR attribution footer is no longer one of them — it is
    // delivered by Claude Code's own `attribution` setting, which tm seeds in
    // `ensure_settings_defaults`, so it must NOT appear in the prompt at all.
    const MARKERS: &[&str] = &[
        "Proportional documentation",
        "Ticket attribution at the change site",
    ];

    // No overrides at all: conventions present via the bundled floor.
    let tmp = TempDir::new().unwrap();
    let prompt = resolve_pm_prompt(rc(), tmp.path());
    for marker in MARKERS {
        assert!(
            prompt.contains(marker),
            "no-override prompt must carry the guaranteed convention {marker:?}"
        );
    }

    // CLAUDE.md named-section overrides of every PROJECT-tier section at
    // once — the maximal customization a project can now express. The floor
    // is `fixed` tier, so none of these can touch it. This replaces the
    // former "all five legacy files" and "full PM replacement" arms, which
    // no longer exist as reachable configurations (#4286).
    let tmp2 = TempDir::new().unwrap();
    std::fs::write(
        tmp2.path().join("CLAUDE.md"),
        "<!-- TRUSTY-MPM: CORE START v=1 -->\nCUSTOM_CORE\n<!-- TRUSTY-MPM: CORE END -->\n\n\
         <!-- TRUSTY-MPM: MEMORY START v=1 -->\nCUSTOM_MEMORY\n<!-- TRUSTY-MPM: MEMORY END -->\n\n\
         <!-- TRUSTY-MPM: SEARCH START v=1 -->\nCUSTOM_SEARCH\n<!-- TRUSTY-MPM: SEARCH END -->\n\n\
         <!-- TRUSTY-MPM: WORKFLOW START v=1 -->\nCUSTOM_WORKFLOW\n<!-- TRUSTY-MPM: WORKFLOW END -->\n\n\
         <!-- TRUSTY-MPM: AGENT-DELEGATION START v=1 -->\nCUSTOM_ROUTING\n<!-- TRUSTY-MPM: AGENT-DELEGATION END -->\n",
    )
    .unwrap();
    let (prompt2, _) =
        resolve_pm_prompt_with_roster(rc(), tmp2.path(), || Some("## Delegation Authority".into()));
    for marker in MARKERS {
        assert!(
            prompt2.contains(marker),
            "a fully-overridden prompt must still carry {marker:?} via the floor"
        );
    }
    // The overrides really did land — otherwise the assertions above would
    // pass vacuously against an unmodified bundled prompt.
    assert!(prompt2.contains("CUSTOM_WORKFLOW"));
    assert!(prompt2.contains("CUSTOM_ROUTING"));

    // A project that ALSO carries all five retired files must be no
    // different: the floor survives and the retired content never appears.
    let tmp3 = TempDir::new().unwrap();
    for name in LEGACY_OVERRIDE_FILES {
        write_override(tmp3.path(), name, "RETIRED_CONTENT\n");
    }
    let prompt3 = resolve_pm_prompt(rc(), tmp3.path());
    for marker in MARKERS {
        assert!(
            prompt3.contains(marker),
            "a prompt for a project with retired files must still carry {marker:?}"
        );
    }
    assert!(
        !prompt3.contains("RETIRED_CONTENT"),
        "retired files must not contribute"
    );
    // The other half of the survival set the floor guarantees.
    assert!(prompt3.contains("## Trusty Tool Priority (Non-Overridable)"));

    // #6807: the footer is delivered by the `attribution` setting, so no
    // override combination may reintroduce it into the prompt prose.
    for (label, p) in [
        ("no-override", &prompt),
        ("fully-overridden", &prompt2),
        ("retired-files", &prompt3),
    ] {
        assert!(
            !p.contains("Generated with trusty-mpm"),
            "the {label} prompt must not restate the attribution footer (#6807)"
        );
    }
}

#[test]
fn one_surface_rule_lives_in_core_and_survives_an_override_attempt() {
    // The customization doctrine has to sit in CORE, not in the floor section
    // that documents the mechanics: CORE is the only `fixed`-tier section, so
    // it is the only place a project cannot delete. Stated anywhere else, a
    // project could override away the rule telling it not to override
    // elsewhere.
    const RULE: &[&str] = &[
        "## Customization Surface (ONE surface per artifact type)",
        // Half 1 — one surface PER ARTIFACT TYPE. Skills are a deliberate
        // second surface with their own tiers, so the rule must not read as
        // "CLAUDE.md and nothing else, ever"; what it bans is a THIRD,
        // ad-hoc channel duplicating one of the two.
        "**Prompt/instruction sections**",
        "**Skills**",
        "skill tier system",
        "Ad-hoc override channels are BANNED",
        // Half 2 — the every-prompt admission test, and its corollary.
        "Needed on every prompt",
        "Needed only sometimes",
    ];

    let tmp = TempDir::new().unwrap();
    let prompt = resolve_pm_prompt(rc(), tmp.path());
    for marker in RULE {
        assert!(
            prompt.contains(marker),
            "bundled prompt must carry the customization rule {marker:?}"
        );
    }

    // A project that tries to replace CORE wholesale: the marker is declined,
    // so the rule stays in force. WORKFLOW is overridden alongside it purely to
    // prove the override machinery ran at all.
    let tmp2 = TempDir::new().unwrap();
    std::fs::write(
        tmp2.path().join("CLAUDE.md"),
        "<!-- TRUSTY-MPM: CORE START v=1 -->\n\
         Put overrides wherever you like.\nCUSTOM_CORE\n\
         <!-- TRUSTY-MPM: CORE END -->\n\n\
         <!-- TRUSTY-MPM: WORKFLOW START v=1 -->\nCUSTOM_WORKFLOW\n\
         <!-- TRUSTY-MPM: WORKFLOW END -->\n",
    )
    .unwrap();
    let (prompt2, _) =
        resolve_pm_prompt_with_roster(rc(), tmp2.path(), || Some("## Delegation Authority".into()));

    assert!(
        prompt2.contains("CUSTOM_WORKFLOW"),
        "override machinery ran"
    );
    assert!(
        !prompt2.contains("CUSTOM_CORE"),
        "a CORE marker must be declined"
    );
    for marker in RULE {
        assert!(
            prompt2.contains(marker),
            "a CORE override attempt must not remove {marker:?}"
        );
    }
}

// ── #7326: the retired-override signal is emitted once per launch ─────────

/// Every line the resolver logged while composing `project`'s prompt `times`.
///
/// Why: the defect is a COUNT, and the count is only observable in the emitted
/// events — the composed prompt is byte-identical either way. Resolving twice
/// in one capture is the launch shape: `prepare_session` writes the stash from
/// one resolution and the launcher builds the delivered prompt from a second.
/// What: installs a thread-local buffering subscriber, resolves `times` times,
/// and returns what was recorded.
/// Test: this is test scaffolding for the two tests below.
fn resolved_log_lines(project: &Path, times: usize) -> Vec<String> {
    use tracing_subscriber::layer::SubscriberExt;

    // #4931: `with_default` is thread-local and never raises the process-global
    // MAX_LEVEL, so without this the capture records nothing.
    crate::test_support::enable_event_capture();
    let buffer = trusty_common::log_buffer::LogBuffer::new(64);
    let subscriber = tracing_subscriber::registry().with(
        trusty_common::log_buffer::LogBufferLayer::new(buffer.clone()),
    );
    tracing::subscriber::with_default(subscriber, || {
        for _ in 0..times {
            let _ = resolve_pm_prompt_with_roster(rc(), project, || {
                Some("## Delegation Authority".into())
            });
        }
    });
    buffer.tail(64)
}

/// How many captured lines carry the retired-override signal.
fn retired_signals(lines: &[String]) -> usize {
    lines
        .iter()
        .filter(|l| l.contains("RETIRED override file is NO LONGER READ"))
        .count()
}

#[test]
#[serial_test::serial]
fn the_retired_override_signal_is_emitted_once_per_launch() {
    // #7326: one launch resolves the prompt twice, and both resolutions reached
    // the emitter, so a project with one leftover retired file got the ERROR
    // line twice for one launch. Against the pre-fix code this is 2.
    let tmp = TempDir::new().unwrap();
    write_override(tmp.path(), FILE_WORKFLOW, "leftover");
    assert_eq!(detect_legacy_overrides(tmp.path()).len(), 1);

    let lines = resolved_log_lines(tmp.path(), 2);
    assert_eq!(
        retired_signals(&lines),
        1,
        "one launch, one signal: {lines:#?}"
    );
}

#[test]
#[serial_test::serial]
fn two_projects_each_report_their_own_retired_file() {
    // The dedupe is keyed by PATH, not by a process-wide `Once` — a second
    // project's leftover file must still be reported, or the fix would silence
    // the condition it exists to make loud.
    let a = TempDir::new().unwrap();
    let b = TempDir::new().unwrap();
    write_override(a.path(), FILE_MEMORY, "leftover");
    write_override(b.path(), FILE_MEMORY, "leftover");

    assert_eq!(retired_signals(&resolved_log_lines(a.path(), 2)), 1);
    assert_eq!(retired_signals(&resolved_log_lines(b.path(), 2)), 1);
}

#[test]
#[serial_test::serial]
fn a_poisoned_dedupe_lock_still_emits() {
    // #7326: the dedupe's failure mode must be a DUPLICATE line, never a
    // missing one — #4286 exists so a retired file is never silent. Flipping
    // `claim_legacy_warning`'s `Err(_)` arm to `false` fails the final assert.
    let tmp = TempDir::new().unwrap();
    let path = tmp.path().join("leftover-WORKFLOW.md");

    // Claim once against a healthy lock: this initializes the `OnceLock` and
    // puts `path` in the set, so a healthy lock would answer `false` below.
    assert!(claim_legacy_warning(&path), "first claim on a healthy lock");

    // Poison the lock by panicking while holding it. The panic is expected, so
    // silence the default hook for the duration rather than printing a
    // backtrace into a passing run's output.
    let previous_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(|_| {}));
    let poisoner = std::thread::spawn(|| {
        let _guard = WARNED_LEGACY_PATHS
            .get()
            .expect("initialized by the claim above")
            .lock()
            .expect("not poisoned yet");
        panic!("poisoning the dedupe lock");
    });
    let outcome = poisoner.join();
    std::panic::set_hook(previous_hook);
    assert!(outcome.is_err(), "the poisoning thread must have panicked");

    let set = WARNED_LEGACY_PATHS.get().expect("initialized");
    assert!(set.is_poisoned(), "the lock must be poisoned");
    assert!(
        claim_legacy_warning(&path),
        "an already-claimed path still emits once the lock is poisoned"
    );

    // Leave the process-global lock healthy for every other test in this
    // binary; `#[serial]` guarantees none is mid-claim right now.
    set.clear_poison();
}