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
//! Tests for the bundled framework-tier manifest (#4760).
//!
//! Why: this module is the one place "which agents always deploy" is decided, so
//! its two properties must be pinned independently — the SHIPPED asset validates
//! (a build-integrity guard), and the composition rule behaves correctly against
//! SYNTHETIC categories (so a behaviour test cannot pass by accident of what the
//! real manifest happens to contain).
//! What: validation-failure coverage for every [`FrameworkManifestError`]
//! variant, composition coverage for each of the four deployment categories, the
//! skill-roster declaration (#4765), and the "no marker detected" vs "manifest
//! is broken" distinction.
//! Test: this file.

use super::super::workspace::MAX_WORKSPACE_MEMBERS;
use super::*;
use std::fs;
use tempfile::TempDir;

/// A synthetic catalog whose names are deliberately NOT real bundled agents, so
/// a composition test can never pass because of what the shipped manifest says.
fn fake_catalog() -> BTreeSet<String> {
    [
        "rust-engineer",
        "js-engineer",
        "react-engineer",
        "vercel-ops",
        "qa",
        "ops",
    ]
    .iter()
    .map(|s| (*s).to_string())
    .collect()
}

/// A synthetic manifest over [`fake_catalog`], exercising all five categories.
///
/// Since #4765 the markers are part of the fixture, so every composition test
/// below is independent of the SHIPPED markers as well as of the shipped roster.
fn fake_manifest() -> String {
    r#"
version = 1

[agent_categories]
universal = ["qa"]
deprecated = ["ops"]

[[agent_categories.language]]
stem = "rust-engineer"
markers = ["Cargo.toml"]

[[agent_categories.language]]
stem = "js-engineer"
markers = ["package.json"]

[[agent_categories.framework]]
stem = "react-engineer"
markers = ["package.json::\"react\""]

[[agent_categories.platform]]
stem = "vercel-ops"
markers = ["vercel.json"]

[skill_categories]
universal = ["tm"]
"#
    .to_string()
}

/// A synthetic skill catalog, deliberately not the real bundled one.
fn fake_skill_catalog() -> BTreeSet<String> {
    ["tm"].iter().map(|s| (*s).to_string()).collect()
}

fn parsed_fake() -> AgentCategories {
    parse_framework_manifest(&fake_manifest(), &fake_catalog()).expect("fixture is valid")
}

fn touch(dir: &Path, name: &str) {
    let path = dir.join(name);
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).unwrap();
    }
    fs::write(path, "").unwrap();
}

// ---------------------------------------------------------------------------
// The shipped asset
// ---------------------------------------------------------------------------

#[test]
fn bundled_framework_manifest_is_valid() {
    // The build-integrity guard `framework_agent_scope`'s panic branch relies
    // on. If this fails, the shipped asset is corrupt and the panic is live.
    let categories = framework_agent_categories().expect("bundled manifest must validate");
    assert!(!categories.universal.is_empty());
    assert_eq!(
        categories
            .platform
            .iter()
            .map(|entry| entry.stem.as_str())
            .collect::<Vec<_>>(),
        vec!["gcp-ops", "vercel-ops"],
        "the two platform-ops agents are platform-gated"
    );
    // #4765: the markers are the manifest's too, so the shipped gate is pinned
    // here rather than in a Rust table nobody reads next to the category.
    let entry = |list: &[GatedAgent], stem: &str| {
        list.iter()
            .find(|e| e.stem == stem)
            .unwrap_or_else(|| panic!("{stem} must be declared"))
            .markers
            .clone()
    };
    assert_eq!(
        entry(&categories.language, "elixir-engineer"),
        vec!["mix.exs".to_string()],
        "elixir-engineer is language-gated on mix.exs"
    );
    assert_eq!(
        entry(&categories.framework, "phoenix-engineer"),
        vec!["mix.exs::{:phoenix,".to_string()],
        "phoenix-engineer is framework-gated on the phoenix dependency"
    );
    // #4760: `deprecated` is EMPTY and that is correct. `ops` was its only
    // occupant and the owner ruled it deleted from the bundle outright, so it
    // needs no declaration. The category remains as the MECHANISM for retiring
    // a future agent that must stay bundled; its behaviour is proven against a
    // synthetic catalog by `deprecated_agent_never_deploys`, which does not
    // depend on whichever agent happens to be retired today.
    assert!(categories.deprecated.is_empty());
}

#[test]
fn bundled_agent_stems_excludes_foundations() {
    let stems = bundled_agent_stems(&crate::core::content_source::test_support::repo_roster());
    assert!(
        stems.contains("engineer"),
        "dispatchable agents are included"
    );
    assert!(
        stems.contains("elixir-engineer"),
        "#4760 added elixir-engineer to the bundle"
    );
    assert!(
        !stems.contains("ops"),
        "#4760 deleted the deprecated `ops` agent from the bundle"
    );
    for base in [
        "BASE-AGENT",
        "BASE-ENGINEER",
        "BASE-OPS",
        "BASE-QA",
        "BASE-RESEARCH",
    ] {
        assert!(
            !stems.contains(base),
            "{base} is an inheritance fragment, not a dispatchable agent"
        );
    }
}

#[test]
fn bundled_manifest_partitions_the_whole_catalog() {
    // Every bundled agent is declared exactly once — the invariant that makes a
    // newly added agent fail loudly instead of quietly never deploying.
    // #9011: the strict partition, against the checkout roster.
    let roster = crate::core::content_source::test_support::repo_roster();
    let categories = framework_agent_categories_for(&roster).expect("valid");
    let declared: Vec<String> = labelled_stems(&categories)
        .into_iter()
        .map(|(_, stem)| stem.clone())
        .collect();
    let mut sorted = declared.clone();
    sorted.sort();
    sorted.dedup();
    assert_eq!(sorted.len(), declared.len(), "no stem declared twice");
    assert_eq!(
        sorted,
        bundled_agent_stems(&roster).into_iter().collect::<Vec<_>>(),
        "the five categories must exactly cover the bundled catalog"
    );
}

/// Whether `stem` deploys under `scope`, by the same rule the deployer applies.
///
/// Why: the composition states its gate as an `exclude` list, so asserting on
/// list membership would pin the mechanism. These tests assert the behaviour the
/// deployer actually consults — `HarnessPlan::agent_selected`'s rule.
fn deploys(scope: &AgentSet, stem: &str) -> bool {
    super::super::schema::selection_matches(stem, &scope.include, &scope.exclude)
}

#[test]
fn framework_agent_scope_selects_universal_agents() {
    // The real entry point over the real asset: a bare directory still gets the
    // universal roster, and never the deprecated agent.
    let tmp = TempDir::new().unwrap();
    let scope = framework_agent_scope(tmp.path());
    assert!(deploys(&scope, "engineer"));
    assert!(deploys(&scope, "qa"));
    assert_eq!(scope.source, ContentSource::Bundled);
}

#[test]
fn undeclared_source_agents_still_deploy() {
    // The gate is an exclusion, not an allowlist: a source-directory agent the
    // manifest never names — a `BASE-*` inheritance fragment, or an agent a
    // catalog checkout adds — must still deploy. Silently deploying LESS than
    // the source carries is the failure class this work removes.
    let tmp = TempDir::new().unwrap();
    let scope = framework_agent_scope(tmp.path());
    assert!(deploys(&scope, "base-engineer"));
    assert!(deploys(&scope, "some-catalog-only-agent"));
}

// ---------------------------------------------------------------------------
// Loud failure — every variant, none reachable from "no marker detected"
// ---------------------------------------------------------------------------

#[test]
fn malformed_manifest_is_an_error() {
    let err = parse_framework_manifest("this is not toml {{{", &fake_catalog())
        .expect_err("malformed input must not resolve to a selection");
    assert!(matches!(err, FrameworkManifestError::Malformed(_)));
}

#[test]
fn missing_section_is_an_error() {
    // A well-formed manifest with no [agent_categories] must NOT fall through to
    // "deploy everything" — it is an error.
    let err = parse_framework_manifest("version = 1\n", &fake_catalog())
        .expect_err("a manifest with no categories declares nothing");
    assert_eq!(err, FrameworkManifestError::MissingCategories);
}

#[test]
fn empty_universal_is_an_error() {
    // The "never silently deploy nothing" half of the requirement.
    let raw = "[agent_categories]\nuniversal = []\n";
    let err = parse_framework_manifest(raw, &fake_catalog()).expect_err("empty universal");
    assert_eq!(err, FrameworkManifestError::EmptyUniversal);
}

#[test]
fn unknown_stem_is_an_error() {
    let raw = "[agent_categories]\nuniversal = [\"qa\", \"no-such-agent\"]\n";
    let err = parse_framework_manifest(raw, &fake_catalog()).expect_err("unknown stem");
    assert_eq!(
        err,
        FrameworkManifestError::UnknownAgent {
            category: "universal",
            stem: "no-such-agent".to_string(),
        }
    );
}

#[test]
fn undeclared_bundled_agent_is_an_error() {
    // `rust-engineer`, `react-engineer`, `vercel-ops` and `ops` are in the
    // catalog but not declared here.
    let raw = "[agent_categories]\nuniversal = [\"qa\"]\n";
    let err = parse_framework_manifest(raw, &fake_catalog()).expect_err("undeclared agents");
    match err {
        FrameworkManifestError::UndeclaredAgents(missing) => {
            assert_eq!(
                missing,
                vec![
                    "js-engineer".to_string(),
                    "ops".to_string(),
                    "react-engineer".to_string(),
                    "rust-engineer".to_string(),
                    "vercel-ops".to_string()
                ]
            );
        }
        other => panic!("expected UndeclaredAgents, got {other:?}"),
    }
}

#[test]
fn duplicate_declaration_is_an_error() {
    let raw = "[agent_categories]\nuniversal = [\"qa\"]\ndeprecated = [\"qa\"]\n";
    let err = parse_framework_manifest(raw, &fake_catalog()).expect_err("duplicate");
    assert_eq!(
        err,
        FrameworkManifestError::DuplicateDeclaration("qa".to_string())
    );
}

#[test]
fn gated_entry_without_markers_is_an_error() {
    // #4765: markers moved into the manifest, so "gated but with no condition"
    // is now representable — and undeployable. That must be loud, not silent.
    let raw = r#"
[agent_categories]
universal = ["ops"]

[[agent_categories.language]]
stem = "qa"
markers = []

[[agent_categories.language]]
stem = "rust-engineer"
markers = ["Cargo.toml"]

[[agent_categories.language]]
stem = "js-engineer"
markers = ["package.json"]

[[agent_categories.framework]]
stem = "react-engineer"
markers = ["package.json"]

[[agent_categories.platform]]
stem = "vercel-ops"
markers = ["vercel.json"]
"#;
    let err = parse_framework_manifest(raw, &fake_catalog()).expect_err("ungated entry");
    assert_eq!(
        err,
        FrameworkManifestError::UngatedEntry {
            category: "language",
            stem: "qa".to_string(),
        }
    );
}

// ---------------------------------------------------------------------------
// The skill roster (#4765)
// ---------------------------------------------------------------------------

#[test]
fn detected_stack_engineers_matches_the_manifest() {
    // `core::stack_profile` primes the PM prompt from this entry point, and it
    // must read the SAME declaration the deployer reads — a prompt naming an
    // engineer the project never received is the drift #1971 exists to prevent.
    let tmp = TempDir::new().unwrap();
    touch(tmp.path(), "Cargo.toml");

    let detected = detected_stack_engineers(tmp.path()).engineers;
    assert!(
        detected.contains("rust-engineer"),
        "a Cargo project's stack profile names rust-engineer: {detected:?}"
    );
    assert!(
        !detected.contains("python-engineer"),
        "...and not a language the project shows no marker for: {detected:?}"
    );

    // Every stem it reports must be one the manifest actually declares as
    // stack-gated, so the prompt can never name an agent the deploy filter
    // would drop.
    let categories = framework_agent_categories().expect("bundled manifest must validate");
    let declared: BTreeSet<&str> = categories
        .language
        .iter()
        .chain(categories.framework.iter())
        .map(|entry| entry.stem.as_str())
        .collect();
    for stem in &detected {
        assert!(
            declared.contains(stem.as_str()),
            "`{stem}` is reported to the prompt but is not a declared stack agent"
        );
    }
}

/// A Cargo workspace with nested Svelte UIs detects the web engineers too.
///
/// Why (#7781, owner ruling 2026-09-13): root-only detection answered
/// `rust-engineer` alone for trusty-tools itself, whose eight Svelte front ends
/// live in `crates/*/ui` and are declared by no root manifest key — so the PM
/// was primed to route front-end work to a Rust specialist. This fails on the
/// pre-#7781 commit, where the nested `package.json` is never probed.
/// What: builds that layout in a temp dir — root `Cargo.toml` with a
/// `[workspace]` section, a member crate, and a `ui/` package declaring
/// `svelte` — and asserts the Rust, JS/TS, and Svelte engineers are all named.
/// Test: this function IS the test.
#[test]
fn mixed_stack_repo_detects_nested_web_engineers() {
    let tmp = TempDir::new().unwrap();
    fs::write(
        tmp.path().join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/*\"]\n",
    )
    .unwrap();
    touch(tmp.path(), "crates/app/Cargo.toml");
    fs::create_dir_all(tmp.path().join("crates/app/ui")).unwrap();
    fs::write(
        tmp.path().join("crates/app/ui/package.json"),
        r#"{"devDependencies":{"svelte":"^5.0.0"}}"#,
    )
    .unwrap();
    touch(tmp.path(), "crates/app/ui/tsconfig.json");

    let detected = detected_stack_engineers(tmp.path()).engineers;
    for expected in [
        "rust-engineer",
        "javascript-engineer",
        "typescript-engineer",
        "svelte-engineer",
    ] {
        assert!(
            detected.contains(expected),
            "a Cargo workspace with a nested Svelte UI must detect `{expected}`: {detected:?}"
        );
    }
    assert!(
        !detected.contains("python-engineer"),
        "the walk must not invent a stack the repo has no marker for: {detected:?}"
    );
}

/// A repo with only a root `Cargo.toml` still detects `rust-engineer` alone.
///
/// Why: the nested walk must add stacks the repo really has and nothing else.
/// A walk that over-detects would put every engineer in every roster, which is
/// the noise the gates exist to remove (#1941), so the narrow case is pinned
/// beside the wide one.
/// What: a temp dir holding one `Cargo.toml`; asserts the detected set is
/// exactly `{rust-engineer}`.
/// Test: this function IS the test.
#[test]
fn rust_only_repo_detects_only_rust_engineer() {
    let tmp = TempDir::new().unwrap();
    touch(tmp.path(), "Cargo.toml");

    let detected = detected_stack_engineers(tmp.path()).engineers;
    assert_eq!(
        detected,
        BTreeSet::from(["rust-engineer".to_string()]),
        "a single-crate Rust repo detects exactly one engineer"
    );
}

/// Both scan flags reach the public entry point, and stay distinct there.
///
/// Why (#7781 round-2 HIGH, split in round-3): every scan bound fails closed by
/// returning fewer engineers, so a partial answer used to be identical to a
/// complete one. The flags have to survive the two hops from the walk through
/// `MarkerProbe` to this public return type, or nothing downstream can act on
/// them — and they have to arrive SEPARATE, because #7751 fails closed on
/// `truncated` alone and an ordinary deep repository must not trip it.
/// What: three trees. One nests a directory past `MAX_NESTED_DEPTH` and must
/// report `depth_limited` without `truncated`, while still detecting its stack
/// — a bound reports a partial answer, it never suppresses one. One declares
/// more workspace members than `MAX_WORKSPACE_MEMBERS` so the shared member cap
/// trips, and must report `truncated` without `depth_limited`. One is shallow
/// and must report neither.
/// Test: this function IS the test.
#[test]
fn truncated_detection_is_reported_to_the_caller() {
    let deep = TempDir::new().unwrap();
    touch(deep.path(), "Cargo.toml");
    // `a/b/c/d` sits AT the depth bound and still has a child, so the walk
    // stops with part of the tree unread.
    fs::create_dir_all(deep.path().join("a/b/c/d/e")).unwrap();

    let detected = detected_stack_engineers(deep.path());
    assert!(
        detected.depth_limited,
        "a tree with directories past the depth bound must report the depth limit"
    );
    assert!(
        !detected.truncated,
        "#7781 round-3: the depth bound is scope, not a resource cap — the \
         fail-closed flag must stay clear"
    );
    assert!(
        detected.engineers.contains("rust-engineer"),
        "a bound reports a PARTIAL answer; it must not suppress what was found"
    );

    // One member past the cap, so the walk meets an anchored directory the
    // declared-member pass had no room for: the shared ceiling trips.
    let wide = TempDir::new().unwrap();
    fs::write(wide.path().join("package.json"), r#"{"workspaces":["m*"]}"#).unwrap();
    for i in 0..=MAX_WORKSPACE_MEMBERS {
        touch(wide.path(), &format!("m{i:04}/package.json"));
    }

    let detected = detected_stack_engineers(wide.path());
    assert!(
        detected.truncated,
        "exhausting the shared member cap is truncation the caller must see"
    );
    assert!(
        !detected.depth_limited,
        "a one-level-deep workspace never reaches the depth bound"
    );

    let shallow = TempDir::new().unwrap();
    touch(shallow.path(), "Cargo.toml");
    let detected = detected_stack_engineers(shallow.path());
    assert!(
        !detected.truncated && !detected.depth_limited,
        "a tree the walk read in full must claim neither bound"
    );
}

/// The DECLARED-member cap reaches the caller, even when the walk cannot see it.
///
/// Why (#7781 round-3 review): `StackDetection::truncated` documents itself as
/// covering every resource cap, and `workspace::probe_roots` dropped declared
/// members past `MAX_WORKSPACE_MEMBERS` with a bare `break` and no signal.
/// `truncated_detection_is_reported_to_the_caller` did not catch it: its dropped
/// member sits at depth 1, where the nested walk meets it and trips the SHARED
/// member cap instead, so the flag arrived for the wrong reason.
/// What: a workspace declaring `MAX_WORKSPACE_MEMBERS + 1` members whose extra
/// member lives under `vendor/` — a `SKIP_DIR_NAMES` directory the nested walk
/// never descends into — so the declared pass is the ONLY thing that can report
/// the cap. Asserts `truncated` without `depth_limited`.
/// Test: this function IS the test.
#[test]
fn declared_member_cap_is_reported_to_the_caller() {
    let tmp = TempDir::new().unwrap();
    fs::write(
        tmp.path().join("package.json"),
        r#"{"workspaces":["m*","vendor/*"]}"#,
    )
    .unwrap();
    for i in 0..MAX_WORKSPACE_MEMBERS {
        touch(tmp.path(), &format!("m{i:04}/package.json"));
    }
    // The member past the cap, parked where the nested walk cannot find it.
    touch(tmp.path(), "vendor/dropped/package.json");

    let detected = detected_stack_engineers(tmp.path());
    assert!(
        detected.truncated,
        "dropping a declared member is a resource cap, and the caller must see \
         it whether or not the nested walk can reach that member"
    );
    assert!(
        !detected.depth_limited,
        "a one-level-deep workspace never reaches the depth bound"
    );
}

#[test]
fn bundled_skill_roster_is_valid() {
    // The shipped `[skill_categories]` must exactly cover the content's skills
    // (#9012: the strict partition runs against the checkout's content).
    let content = crate::core::content_source::test_support::repo_content();
    let skills =
        framework_skill_categories_for(&content).expect("bundled skill roster must validate");
    assert_eq!(
        skills.universal.len(),
        bundled_skill_stems(&content).len(),
        "every bundled skill is declared exactly once"
    );
    assert!(skills.universal.contains(&"tm".to_string()));
    // The runtime read checks the manifest's own shape and agrees.
    assert_eq!(framework_skill_categories().expect("runtime read"), skills);
}

#[test]
fn bundled_skill_stems_excludes_reference_files() {
    let stems = bundled_skill_stems(&crate::core::content_source::test_support::repo_content());
    assert!(stems.contains("systematic-debugging"));
    assert!(
        !stems.iter().any(|s| s.contains('/')),
        "a skill's own references/*.md are not catalog entries"
    );
}

#[test]
fn missing_skill_section_is_an_error() {
    let err = parse_framework_skills("version = 1\n", &fake_skill_catalog())
        .expect_err("a manifest with no skill section declares nothing");
    assert_eq!(err, FrameworkManifestError::MissingSkillCategories);
}

#[test]
fn unknown_skill_is_an_error() {
    let raw = "[skill_categories]\nuniversal = [\"tm\", \"no-such-skill\"]\n";
    let err = parse_framework_skills(raw, &fake_skill_catalog()).expect_err("unknown skill");
    assert_eq!(
        err,
        FrameworkManifestError::UnknownSkill("no-such-skill".to_string())
    );
}

#[test]
fn undeclared_bundled_skill_is_an_error() {
    let raw = "[skill_categories]\nuniversal = []\n";
    let err = parse_framework_skills(raw, &fake_skill_catalog()).expect_err("undeclared skill");
    assert_eq!(
        err,
        FrameworkManifestError::UndeclaredSkills(vec!["tm".to_string()])
    );
}

#[test]
fn duplicate_skill_is_an_error() {
    let raw = "[skill_categories]\nuniversal = [\"tm\", \"tm\"]\n";
    let err = parse_framework_skills(raw, &fake_skill_catalog()).expect_err("duplicate skill");
    assert_eq!(
        err,
        FrameworkManifestError::DuplicateSkill("tm".to_string())
    );
}

// ---------------------------------------------------------------------------
// Composition — against SYNTHETIC categories
// ---------------------------------------------------------------------------

#[test]
fn universal_agents_deploy_with_no_markers() {
    let tmp = TempDir::new().unwrap();
    touch(tmp.path(), "README.md");
    let scope = agent_scope_from(&parsed_fake(), tmp.path());
    assert!(
        deploys(&scope, "qa"),
        "universal deploys with zero detection"
    );
}

#[test]
fn language_engineers_still_gate_on_detection() {
    // A Cargo project keeps rust-engineer; a project whose detected stack is a
    // DIFFERENT declared language does not. The negative case must detect
    // something — a project matching no fixture marker at all takes the
    // unknown-project fallback and keeps everything, which is
    // `unknown_project_keeps_every_stack_engineer`'s subject, not this one.
    let rust = TempDir::new().unwrap();
    touch(rust.path(), "Cargo.toml");
    let scope = agent_scope_from(&parsed_fake(), rust.path());
    assert!(deploys(&scope, "rust-engineer"));
    assert!(
        deploys(&scope, "qa"),
        "universal is unaffected by stack gating"
    );

    let js = TempDir::new().unwrap();
    touch(js.path(), "package.json");
    let scope = agent_scope_from(&parsed_fake(), js.path());
    assert!(
        deploys(&scope, "js-engineer"),
        "the JS project detects its own engineer"
    );
    assert!(
        !deploys(&scope, "rust-engineer"),
        "a JS project must not get the Rust engineer"
    );
    assert!(
        deploys(&scope, "qa"),
        "...and the exclusion must be stack-specific, not a blanket drop"
    );
}

#[test]
fn framework_engineers_gate_on_detection() {
    // #4760: `react-engineer` requires a DECLARED react dependency, not merely
    // a `package.json`. A framework-free JS project and a Rust project both
    // miss it, while the language engineers in the same call still fire.
    let react = TempDir::new().unwrap();
    std::fs::write(
        react.path().join("package.json"),
        "{\"dependencies\": {\"react\": \"^18.0.0\"}}",
    )
    .unwrap();
    assert!(deploys(
        &agent_scope_from(&parsed_fake(), react.path()),
        "react-engineer"
    ));

    let bare_js = TempDir::new().unwrap();
    std::fs::write(
        bare_js.path().join("package.json"),
        "{\"dependencies\": {\"lodash\": \"^4.0.0\"}}",
    )
    .unwrap();
    assert!(
        !deploys(
            &agent_scope_from(&parsed_fake(), bare_js.path()),
            "react-engineer"
        ),
        "a framework-free JS project must not receive react-engineer"
    );

    let rust = TempDir::new().unwrap();
    touch(rust.path(), "Cargo.toml");
    let scope = agent_scope_from(&parsed_fake(), rust.path());
    assert!(!deploys(&scope, "react-engineer"));
    assert!(
        deploys(&scope, "rust-engineer"),
        "the same call still selects the detected stack engineer"
    );
}

#[test]
fn deprecated_agent_never_deploys() {
    // `ops` IS in the synthetic catalog and IS declared — only its category
    // keeps it out. Every other fixture agent is checked in the same call so a
    // blanket-drop selection cannot make this pass.
    for markers in [
        vec!["README.md"],
        vec!["Cargo.toml"],
        vec!["package.json", "vercel.json"],
    ] {
        let tmp = TempDir::new().unwrap();
        for m in &markers {
            touch(tmp.path(), m);
        }
        let scope = agent_scope_from(&parsed_fake(), tmp.path());
        assert!(
            !deploys(&scope, "ops"),
            "deprecated `ops` must not deploy for markers {markers:?}"
        );
        assert!(
            deploys(&scope, "qa"),
            "...while the universal agent still does, for markers {markers:?}"
        );
    }
}

#[test]
fn platform_agent_absent_without_marker() {
    // "No platform detected" is an ORDINARY result: a selection that simply
    // drops the platform agents, distinguishable from the Err a broken manifest
    // produces (see `malformed_manifest_is_an_error`).
    let tmp = TempDir::new().unwrap();
    touch(tmp.path(), "Cargo.toml");
    let scope = agent_scope_from(&parsed_fake(), tmp.path());
    assert!(
        !deploys(&scope, "vercel-ops"),
        "no Vercel marker -> no vercel-ops"
    );
    assert!(
        deploys(&scope, "rust-engineer") && deploys(&scope, "qa"),
        "the same call still deploys the stack and universal agents — the empty \
         platform result is explicit, not a collapsed selection"
    );
}

#[test]
fn platform_agent_deploys_with_marker() {
    let tmp = TempDir::new().unwrap();
    touch(tmp.path(), "Cargo.toml");
    touch(tmp.path(), "vercel.json");
    assert!(deploys(
        &agent_scope_from(&parsed_fake(), tmp.path()),
        "vercel-ops"
    ));
}

#[test]
fn no_platform_detected_is_not_a_manifest_error() {
    // The distinguishability requirement, stated as one assertion set: the same
    // manifest that yields Ok for a platform-less project yields Err when the
    // document itself is broken.
    let tmp = TempDir::new().unwrap();
    touch(tmp.path(), "Cargo.toml");
    assert!(parse_framework_manifest(&fake_manifest(), &fake_catalog()).is_ok());
    assert!(!deploys(
        &agent_scope_from(&parsed_fake(), tmp.path()),
        "vercel-ops"
    ));
    assert!(parse_framework_manifest("broken {{{", &fake_catalog()).is_err());
}

#[test]
fn unknown_project_keeps_every_stack_engineer() {
    // Zero-regression fallback: a project with NO recognised stack marker keeps
    // every language and framework engineer, exactly as `language_agent_scope`
    // behaved before #4760. Platform agents get no such fallback.
    let tmp = TempDir::new().unwrap();
    touch(tmp.path(), "README.md");
    let scope = agent_scope_from(&parsed_fake(), tmp.path());
    assert!(deploys(&scope, "rust-engineer"));
    assert!(deploys(&scope, "react-engineer"));
    assert!(
        !deploys(&scope, "vercel-ops"),
        "platform has no unknown-project fallback"
    );
    assert!(!deploys(&scope, "ops"));
}

// ---------------------------------------------------------------------------
// The per-operation detection memo (#7806)
// ---------------------------------------------------------------------------

/// A second detection over an unchanged tree walks nothing and reads nothing.
///
/// Why: #7806 — `ManifestSources::resolve` reaches `framework_agent_scope` from
/// five-plus call sites in one launch, and each re-ran the full nested walk plus
/// every manifest read for an answer that cannot change between them.
/// What: the per-key compute counter stays at 1 across a second
/// `detected_stack_engineers` AND a `framework_agent_scope` on the same
/// directory. The tree is DELETED between the calls, so any surviving walk or
/// read would answer with an empty set instead of the memoized one.
#[test]
fn stack_detection_is_memoized_per_project() {
    let tmp = TempDir::new().unwrap();
    touch(tmp.path(), "Cargo.toml");
    let dir = tmp.path().to_path_buf();

    let first = detected_stack_engineers(&dir);
    assert!(first.engineers.contains("rust-engineer"), "{first:?}");
    assert_eq!(super::super::detect_memo::computes_for(&dir), 1);

    drop(tmp);
    let second = detected_stack_engineers(&dir);
    assert_eq!(
        second.engineers, first.engineers,
        "the memo answers a vanished tree, so nothing was walked or read"
    );
    let scope = framework_agent_scope(&dir);
    assert!(deploys(&scope, "rust-engineer"));
    assert_eq!(
        super::super::detect_memo::computes_for(&dir),
        1,
        "both entry points share ONE walk"
    );
}

/// An invalidated memo re-detects the tree as it now stands.
///
/// Why: explicit invalidation is the ONLY thing that expires an entry (#7806),
/// so the arm that keeps a long-lived daemon correct needs its own proof.
/// What: a `package.json` added after the first detection is invisible until
/// `invalidate_stack_detection`, and detected immediately after.
#[test]
fn invalidating_picks_up_a_changed_tree() {
    let tmp = TempDir::new().unwrap();
    touch(tmp.path(), "Cargo.toml");
    let before = detected_stack_engineers(tmp.path());
    assert!(
        !before.engineers.contains("javascript-engineer"),
        "{before:?}"
    );

    fs::write(tmp.path().join("package.json"), "{}").unwrap();
    assert_eq!(
        detected_stack_engineers(tmp.path()).engineers,
        before.engineers,
        "the memo holds until the operation boundary"
    );

    super::super::detect_memo::invalidate_stack_detection(tmp.path());
    let after = detected_stack_engineers(tmp.path());
    assert!(after.engineers.contains("javascript-engineer"), "{after:?}");
    assert_eq!(super::super::detect_memo::computes_for(tmp.path()), 2);
}

/// Two projects get two answers.
///
/// Why: a memo keyed on anything coarser than the project directory would serve
/// the first project's roster to the second — the failure mode that makes an
/// unkeyed cache worse than no cache at all.
/// What: a Cargo project and an npm project detected in the same process, each
/// computed exactly once and each carrying only its own engineer.
#[test]
fn memo_is_keyed_by_project_dir() {
    let rust = TempDir::new().unwrap();
    touch(rust.path(), "Cargo.toml");
    let js = TempDir::new().unwrap();
    touch(js.path(), "package.json");

    let rust_engineers = detected_stack_engineers(rust.path()).engineers;
    let js_engineers = detected_stack_engineers(js.path()).engineers;

    assert!(rust_engineers.contains("rust-engineer"));
    assert!(!rust_engineers.contains("javascript-engineer"));
    assert!(js_engineers.contains("javascript-engineer"));
    assert!(!js_engineers.contains("rust-engineer"));
    assert_eq!(super::super::detect_memo::computes_for(rust.path()), 1);
    assert_eq!(super::super::detect_memo::computes_for(js.path()), 1);
}