trusty-code 0.7.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
Documentation
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
//! Tests for the `agents.*` JSON-RPC methods (issue #3449; base-agent
//! filtering issue #3465 follow-up).
//!
//! Why: split out of `protocol.rs` itself (issue #610's 500-SLOC production
//! cap, enforced by `scripts/check_line_cap.sh`) once the base-agent filter
//! additions tipped that file 1 line over — mirrors the identical
//! `workstreams/protocol.rs` + `protocol_tests.rs` split already established
//! in this crate: `#[path = "protocol_tests.rs"] mod tests;` in `protocol.rs`
//! keeps the module logically nested exactly as before (still `tests` from
//! any `super::`/doc-reference call site — only which file backs it moved),
//! while this file's `_tests.rs` suffix classifies it as a TEST file (1500
//! SLOC cap) instead of counting against the production cap.
//! What: every test from `protocol.rs`'s former inline `mod tests` block,
//! unchanged — `validate_agent_name` guards, `agents_list`'s embedded/disk
//! union and base-agent exclusion, `agents_create`/`agents_delete` and their
//! error mappings, `write_new_file`'s atomic-create/TOCTOU-race coverage, and
//! `register`'s wiring smoke test.
//! Test: this file — self-describing.

use super::*;

fn ctx() -> ConnectionContext {
    let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
    ConnectionContext::new(tx)
}

fn state(dir: &Path, project_bound: bool) -> AgentsCatalogState {
    AgentsCatalogState::new(dir.to_path_buf(), project_bound)
}

#[test]
fn validate_name_rejects_empty() {
    assert!(validate_agent_name("").is_err());
}

#[test]
fn validate_name_rejects_uppercase() {
    assert!(validate_agent_name("Engineer").is_err());
}

#[test]
fn validate_name_rejects_path_traversal() {
    assert!(validate_agent_name("../../etc/passwd").is_err());
    assert!(validate_agent_name("a/b").is_err());
    assert!(validate_agent_name("..").is_err());
}

#[test]
fn validate_name_rejects_too_long() {
    let long = "a".repeat(MAX_AGENT_NAME_LEN + 1);
    assert!(validate_agent_name(&long).is_err());
}

#[test]
fn validate_name_accepts_lowercase_alnum_hyphen() {
    assert!(validate_agent_name("my-custom-agent-2").is_ok());
}

#[tokio::test]
async fn list_returns_embedded_when_disk_empty() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let s = state(tmp.path(), false);
    let result = agents_list(&s, Value::Null, ctx()).await.expect("list");
    let agents = result["agents"].as_array().expect("array");
    assert_eq!(agents.len(), crate::assets::DEFAULT_AGENTS.len());
    assert!(agents.iter().all(|a| a["tier"] == "embedded"));
}

/// #8129: the agent catalog that backs `tcode agents.describe` surfaces all
/// four delivery-workflow agents, each from the embedded tier.
///
/// Why: `assets::tests::delivery_workflow_agents_are_dispatchable_with_bash`
/// pins the TABLE; this pins the wire surface an operator actually reads.
/// Three of the four were roster entries before this change but the fourth,
/// `version-control`, was absent entirely — a regression that removed any one
/// of them would leave the PM's delegation guidance pointing at a name the
/// catalog does not list.
/// What: lists against an empty disk dir so the embedded tier answers, and
/// asserts each name appears exactly once with `tier == "embedded"` and a
/// non-empty description.
/// Test: this test.
#[tokio::test]
async fn list_surfaces_the_four_delivery_workflow_agents() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let s = state(tmp.path(), false);
    let result = agents_list(&s, Value::Null, ctx()).await.expect("list");
    let agents = result["agents"].as_array().expect("array");

    for name in ["ticketing", "version-control", "local-ops", "documentation"] {
        let entries: Vec<_> = agents.iter().filter(|a| a["name"] == name).collect();
        assert_eq!(entries.len(), 1, "'{name}' must be listed exactly once");
        assert_eq!(entries[0]["tier"], "embedded");
        assert!(
            entries[0]["description"]
                .as_str()
                .is_some_and(|d| !d.is_empty()),
            "'{name}' must carry a description for the catalog listing"
        );
    }
}

#[tokio::test]
async fn list_disk_override_wins_and_suppresses_embedded() {
    let tmp = tempfile::tempdir().expect("tempdir");
    std::fs::write(
        tmp.path().join("engineer.md"),
        "---\nname: engineer\ndescription: DISK OVERRIDE\n---\n\nBody.\n",
    )
    .expect("write");
    let s = state(tmp.path(), true);
    let result = agents_list(&s, Value::Null, ctx()).await.expect("list");
    let agents = result["agents"].as_array().expect("array");
    let engineer_entries: Vec<_> = agents.iter().filter(|a| a["name"] == "engineer").collect();
    assert_eq!(engineer_entries.len(), 1, "must appear exactly once");
    assert_eq!(engineer_entries[0]["tier"], "project");
    assert_eq!(engineer_entries[0]["description"], "DISK OVERRIDE");
}

#[tokio::test]
async fn list_disk_only_entries_are_additive() {
    let tmp = tempfile::tempdir().expect("tempdir");
    std::fs::write(
        tmp.path().join("my-custom.md"),
        "---\nname: my-custom\ndescription: Custom\n---\n\nBody.\n",
    )
    .expect("write");
    let s = state(tmp.path(), true);
    let result = agents_list(&s, Value::Null, ctx()).await.expect("list");
    let agents = result["agents"].as_array().expect("array");
    assert_eq!(agents.len(), crate::assets::DEFAULT_AGENTS.len() + 1);
    assert!(
        agents
            .iter()
            .any(|a| a["name"] == "my-custom" && a["tier"] == "project")
    );
}

/// An unparseable disk file shadowing an embedded name must surface as
/// `tier: "broken"` — never as the healthy embedded entry, because
/// `resolve_agent`'s disk-wins rule means dispatch of that name WILL
/// fail (code-critic PR #3465 review, MEDIUM).
#[tokio::test]
async fn list_marks_unparseable_disk_override_as_broken() {
    let tmp = tempfile::tempdir().expect("tempdir");
    // `extends:` naming a nonexistent parent makes `load_md_agent`'s
    // compose step fail — the same failure `resolve_agent` would refuse
    // to dispatch through.
    std::fs::write(
        tmp.path().join("engineer.md"),
        "---\nname: engineer\nextends: nonexistent-parent\n---\n\nBody.\n",
    )
    .expect("write");
    let s = state(tmp.path(), true);
    let result = agents_list(&s, Value::Null, ctx()).await.expect("list");
    let agents = result["agents"].as_array().expect("array");
    let engineer_entries: Vec<_> = agents.iter().filter(|a| a["name"] == "engineer").collect();
    assert_eq!(engineer_entries.len(), 1, "must appear exactly once");
    assert_eq!(engineer_entries[0]["tier"], "broken");
    assert!(
        engineer_entries[0]["description"]
            .as_str()
            .expect("description")
            .contains("unparseable"),
    );
}

/// `agents.list` excludes every `BASE-*` composition-template name —
/// even when a real file exists on disk, as trusty-mpm's own bundle
/// installs (frontmatter `name: base-agent`, `role: base` — see
/// `content/agents/BASE-AGENT.md`) — while
/// `resolve_agent` (the dispatch/composition path) still finds it by
/// name, since composing a leaf agent's `extends: base-agent` chain
/// depends on it (issue #3465 follow-up).
///
/// Why: pins the LISTING-only nature of the filter — [`is_base_agent`]
/// must never leak into `resolve_agent`/`load_md_agent`, only into
/// `agents_list`. [`is_base_agent`]'s case-insensitivity (needed
/// because the real bundle's on-disk filename is uppercase
/// `BASE-AGENT.md`) is covered directly by its own doc/the
/// `assets::BASE_AGENT_NAMES` contract; this test uses the lowercase
/// filename so the same file also exercises `resolve_agent`'s exact-name
/// path join without relying on filesystem case-folding, which is not
/// portable (case-sensitive on Linux CI, case-insensitive by default on
/// macOS).
/// What: writes `base-agent.md` and a normal `engineer.md`; asserts the
/// list has no `base-agent` entry but does have `engineer`, then asserts
/// `super::super::resolve_agent` still resolves `base-agent` by name.
/// Test: this test.
#[tokio::test]
async fn list_excludes_base_agents_but_resolve_agent_still_finds_them() {
    let tmp = tempfile::tempdir().expect("tempdir");
    std::fs::write(
        tmp.path().join("base-agent.md"),
        "---\nname: base-agent\nrole: base\n---\n\nBase instructions.\n",
    )
    .expect("write");
    std::fs::write(
        tmp.path().join("engineer.md"),
        "---\nname: engineer\n---\n\nBody.\n",
    )
    .expect("write");

    let s = state(tmp.path(), true);
    let result = agents_list(&s, Value::Null, ctx()).await.expect("list");
    let agents = result["agents"].as_array().expect("array");
    assert!(
        !agents
            .iter()
            .any(|a| a["name"].as_str().is_some_and(is_base_agent)),
        "no BASE-* composition template may appear in the listing, got: {agents:?}"
    );
    assert!(
        agents.iter().any(|a| a["name"] == "engineer"),
        "a real dispatchable agent must still be listed, got: {agents:?}"
    );

    let resolved = super::super::resolve_agent(tmp.path(), "base-agent")
        .expect("resolve_agent must still resolve a base template by name");
    assert_eq!(resolved.agent.name, "base-agent");
}

#[tokio::test]
async fn create_writes_file_and_returns_tier() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let s = state(tmp.path(), true);
    let result = agents_create(
        &s,
        json!({"name": "my-agent", "content": "---\nname: my-agent\n---\n\nBody.\n"}),
        ctx(),
    )
    .await
    .expect("create");
    assert_eq!(result["name"], "my-agent");
    assert_eq!(result["tier"], "project");
    assert!(tmp.path().join("my-agent.md").exists());
}

#[tokio::test]
async fn create_rejects_invalid_name() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let s = state(tmp.path(), true);
    let err = agents_create(&s, json!({"name": "Bad Name!", "content": "x"}), ctx())
        .await
        .expect_err("must reject");
    assert_eq!(err.code, -32003);
}

#[tokio::test]
async fn create_rejects_path_traversal_name() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let s = state(tmp.path(), true);
    let err = agents_create(&s, json!({"name": "../../evil", "content": "x"}), ctx())
        .await
        .expect_err("must reject");
    assert_eq!(err.code, -32003);
    assert!(!tmp.path().parent().unwrap().join("evil.md").exists());
}

#[tokio::test]
async fn create_rejects_embedded_name_collision() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let s = state(tmp.path(), true);
    let err = agents_create(
        &s,
        json!({"name": "engineer", "content": "---\nname: engineer\n---\n\nBody.\n"}),
        ctx(),
    )
    .await
    .expect_err("must reject embedded collision");
    assert_eq!(err.code, -32001);
    assert!(!tmp.path().join("engineer.md").exists());
}

#[tokio::test]
async fn create_rejects_existing_disk_file() {
    let tmp = tempfile::tempdir().expect("tempdir");
    std::fs::write(tmp.path().join("dup.md"), "---\nname: dup\n---\n\nBody.\n").expect("write");
    let s = state(tmp.path(), true);
    let err = agents_create(
        &s,
        json!({"name": "dup", "content": "---\nname: dup\n---\n\nNew.\n"}),
        ctx(),
    )
    .await
    .expect_err("must reject existing file");
    // `-32009 already_exists` — NOT `-32008`, which is the workstreams'
    // `active_conflict` slot (code-critic PR #3465 review, LOW).
    assert_eq!(err.code, -32009);
    assert_eq!(err.data.as_ref().unwrap()["error_type"], "already_exists");
}

/// The conflict path must go through `create_new` (`O_CREAT|O_EXCL`) —
/// meaning a losing create can NEVER have truncated or overwritten the
/// existing file's content, even transiently (code-critic PR #3465
/// review, HIGH 1: the prior `exists()`-then-`write` shape let the
/// second of two racing creates silently clobber the first).
#[tokio::test]
async fn create_conflict_does_not_clobber_existing_content() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let original = "---\nname: dup\ndescription: ORIGINAL\n---\n\nBody.\n";
    std::fs::write(tmp.path().join("dup.md"), original).expect("write");
    let s = state(tmp.path(), true);

    let err = agents_create(&s, json!({"name": "dup", "content": "CLOBBER"}), ctx())
        .await
        .expect_err("must conflict");
    assert_eq!(err.code, -32009);

    let on_disk = std::fs::read_to_string(tmp.path().join("dup.md")).expect("read");
    assert_eq!(on_disk, original, "existing content must be untouched");
}

/// `write_new_file` is the shared atomic-create seam — exercise the io
/// `AlreadyExists` mapping directly, without a handler in the way.
#[test]
fn write_new_file_maps_already_exists_io_error() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let path = tmp.path().join("f.md");
    write_new_file(&path, "first", || "conflict".to_string()).expect("first create");
    let err =
        write_new_file(&path, "second", || "conflict".to_string()).expect_err("second create");
    assert_eq!(err.code, -32009);
    assert_eq!(
        std::fs::read_to_string(&path).expect("read"),
        "first",
        "loser must not touch the winner's content"
    );
}

/// Genuine concurrency: N threads race `write_new_file` against the
/// SAME path at the same time. Exactly one must win; every other must
/// get `AlreadyExists` (mapped to `-32009`) — never a torn/mixed write
/// (code-critic PR #3465 review, HIGH 1/HIGH 2: the original
/// `exists()`-then-`write` shape had no such guarantee under real
/// concurrency, only under the sequential re-creation this module's
/// other tests exercise).
#[test]
fn write_new_file_concurrent_create_exactly_one_wins() {
    use std::sync::{Arc, Barrier};

    let tmp = tempfile::tempdir().expect("tempdir");
    let path = Arc::new(tmp.path().join("race.md"));
    const N: usize = 16;
    let barrier = Arc::new(Barrier::new(N));

    let handles: Vec<_> = (0..N)
        .map(|i| {
            let path = Arc::clone(&path);
            let barrier = Arc::clone(&barrier);
            std::thread::spawn(move || {
                barrier.wait();
                write_new_file(&path, &format!("writer-{i}"), || "conflict".to_string()).map(|_| i)
            })
        })
        .collect();

    let results: Vec<_> = handles
        .into_iter()
        .map(|h| h.join().expect("thread"))
        .collect();
    let winners: Vec<_> = results.iter().filter(|r| r.is_ok()).collect();
    let losers: Vec<_> = results.iter().filter(|r| r.is_err()).collect();

    assert_eq!(winners.len(), 1, "exactly one racing create must win");
    assert_eq!(losers.len(), N - 1, "every other racer must lose");
    for loser in &losers {
        let err = loser.as_ref().unwrap_err();
        assert_eq!(
            err.code, -32009,
            "loser must get already_exists, not a torn write"
        );
    }

    // The file on disk must be exactly the winner's untouched content —
    // never a mix, truncation, or empty file from a lost race.
    let winner_idx = *winners[0].as_ref().unwrap();
    let on_disk = std::fs::read_to_string(path.as_path()).expect("read");
    assert_eq!(on_disk, format!("writer-{winner_idx}"));
}

#[tokio::test]
async fn delete_removes_disk_file() {
    let tmp = tempfile::tempdir().expect("tempdir");
    std::fs::write(
        tmp.path().join("my-agent.md"),
        "---\nname: my-agent\n---\n\nBody.\n",
    )
    .expect("write");
    let s = state(tmp.path(), true);
    agents_delete(&s, json!({"name": "my-agent"}), ctx())
        .await
        .expect("delete");
    assert!(!tmp.path().join("my-agent.md").exists());
}

#[tokio::test]
async fn delete_missing_name_returns_not_found() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let s = state(tmp.path(), true);
    let err = agents_delete(&s, json!({"name": "totally-bogus"}), ctx())
        .await
        .expect_err("must 404");
    assert_eq!(err.code, -32002);
}

#[tokio::test]
async fn delete_embedded_name_returns_permission_denied() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let s = state(tmp.path(), true);
    let err = agents_delete(&s, json!({"name": "engineer"}), ctx())
        .await
        .expect_err("must 403");
    assert_eq!(err.code, -32001);
}

#[tokio::test]
async fn register_wires_all_three_methods() {
    use trusty_mcp::Request;

    let tmp = tempfile::tempdir().expect("tempdir");
    let mut router = Router::new();
    register(&mut router, state(tmp.path(), true));

    let req = Request {
        jsonrpc: Some("2.0".to_string()),
        id: Some(Value::from(1)),
        method: "agents.list".to_string(),
        params: None,
    };
    let resp = router.dispatch(req, &ctx()).await;
    assert!(resp.result.is_some(), "agents.list must be wired");
    assert!(resp.result.unwrap()["agents"].is_array());
}

/// `agents.list` includes a `plugin`-tier entry, namespaced
/// `<plugin>:<name>`, for every agent discovered under
/// `<project_root>/.claude/plugins/*/agents/` (issue #3539).
///
/// Why: this is the acceptance criterion for #3539's namespacing decision
/// at the catalog-listing level — `project_root_two_levels_up` must
/// correctly recover the project root from `state.dir` (a real
/// `.claude/agents` directory, unlike this file's other tests which pass a
/// bare tempdir root as `dir` for brevity — plugin discovery specifically
/// needs the real on-disk shape).
/// Test: this test.
#[tokio::test]
async fn list_includes_namespaced_plugin_agents() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let agents_dir = tmp.path().join(".claude").join("agents");
    std::fs::create_dir_all(&agents_dir).expect("mkdir");
    let plugin_agents_dir = tmp
        .path()
        .join(".claude")
        .join("plugins")
        .join("my-plugin")
        .join("agents");
    std::fs::create_dir_all(&plugin_agents_dir).expect("mkdir");
    std::fs::write(
        plugin_agents_dir.join("reviewer.md"),
        "---\nname: reviewer\ndescription: Plugin reviewer\n---\n\nBody.\n",
    )
    .expect("write");

    let s = state(&agents_dir, true);
    let result = agents_list(&s, Value::Null, ctx()).await.expect("list");
    let agents = result["agents"].as_array().expect("array");
    let plugin_entry = agents
        .iter()
        .find(|a| a["name"] == "my-plugin:reviewer")
        .unwrap_or_else(|| panic!("expected a namespaced plugin entry, got: {agents:?}"));
    assert_eq!(plugin_entry["tier"], "plugin");
    assert_eq!(plugin_entry["description"], "Plugin reviewer");
}

/// A plugin shipping an agent whose LOCAL name matches an existing project
/// agent's name does NOT override the project entry — both appear, the
/// project one unnamespaced and unchanged, the plugin one namespaced
/// (issue #3539's additive-only guarantee).
///
/// Why: this is the explicit collision test #3539 calls for — namespacing
/// makes the "additive only, never overrides project/bundled" contract
/// structural (the keys literally cannot collide), and this test pins that
/// outcome rather than just trusting the mechanism.
/// Test: this test.
#[tokio::test]
async fn list_plugin_agent_does_not_override_project_agent_of_same_local_name() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let agents_dir = tmp.path().join(".claude").join("agents");
    std::fs::create_dir_all(&agents_dir).expect("mkdir");
    std::fs::write(
        agents_dir.join("engineer.md"),
        "---\nname: engineer\ndescription: PROJECT engineer\n---\n\nProject body.\n",
    )
    .expect("write");
    let plugin_agents_dir = tmp
        .path()
        .join(".claude")
        .join("plugins")
        .join("my-plugin")
        .join("agents");
    std::fs::create_dir_all(&plugin_agents_dir).expect("mkdir");
    std::fs::write(
        plugin_agents_dir.join("engineer.md"),
        "---\nname: engineer\ndescription: PLUGIN engineer\n---\n\nPlugin body.\n",
    )
    .expect("write");

    let s = state(&agents_dir, true);
    let result = agents_list(&s, Value::Null, ctx()).await.expect("list");
    let agents = result["agents"].as_array().expect("array");

    let project_entry = agents
        .iter()
        .find(|a| a["name"] == "engineer")
        .expect("project 'engineer' must still be present, untouched");
    assert_eq!(project_entry["tier"], "project");
    assert_eq!(project_entry["description"], "PROJECT engineer");

    let plugin_entry = agents
        .iter()
        .find(|a| a["name"] == "my-plugin:engineer")
        .expect("namespaced plugin entry must be present alongside it");
    assert_eq!(plugin_entry["tier"], "plugin");
    assert_eq!(plugin_entry["description"], "PLUGIN engineer");
}

/// `agents.list` never surfaces a plugin agent that is a symlink escaping
/// the plugin's `agents/` directory — the secret content a hostile plugin
/// would otherwise disclose never appears anywhere in the JSON response
/// (code-critic PR #3547 re-review, CRITICAL 5, CWE-59).
///
/// Test: this test.
#[tokio::test]
#[cfg(unix)]
async fn list_excludes_symlinked_plugin_agent_leak_file() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let agents_dir = tmp.path().join(".claude").join("agents");
    std::fs::create_dir_all(&agents_dir).expect("mkdir");
    let plugin_agents_dir = tmp
        .path()
        .join(".claude")
        .join("plugins")
        .join("my-plugin")
        .join("agents");
    std::fs::create_dir_all(&plugin_agents_dir).expect("mkdir");
    std::fs::write(
        plugin_agents_dir.join("reviewer.md"),
        "---\nname: reviewer\n---\n\nBody.\n",
    )
    .expect("write");

    let secret_dir = tmp.path().join("outside");
    std::fs::create_dir_all(&secret_dir).expect("mkdir");
    let secret_path = secret_dir.join("id_rsa");
    std::fs::write(&secret_path, "SECRET_KEY_MATERIAL").expect("write secret");
    std::os::unix::fs::symlink(&secret_path, plugin_agents_dir.join("leak.md")).expect("symlink");

    let s = state(&agents_dir, true);
    let result = agents_list(&s, Value::Null, ctx()).await.expect("list");
    let agents = result["agents"].as_array().expect("array");

    assert!(
        !agents.iter().any(|a| a["name"] == "my-plugin:leak"),
        "the symlinked entry must not be listed, got: {agents:?}"
    );
    assert!(
        !result.to_string().contains("SECRET_KEY_MATERIAL"),
        "the secret content must never appear anywhere in the response"
    );
}

/// `agents.describe` is reachable through the router like its three siblings
/// (#2074).
#[tokio::test]
async fn register_wires_describe() {
    use trusty_mcp::Request;

    let tmp = tempfile::tempdir().expect("tempdir");
    let mut router = Router::new();
    register(&mut router, state(tmp.path(), true));

    let req = Request {
        jsonrpc: Some("2.0".to_string()),
        id: Some(Value::from(1)),
        method: "agents.describe".to_string(),
        params: Some(json!({ "name": "engineer" })),
    };
    let resp = router.dispatch(req, &ctx()).await;
    let result = resp.result.expect("agents.describe must be wired");
    assert_eq!(result["name"], "engineer");
    assert_eq!(result["tier"], "embedded");
}

/// A `name` that resolves nowhere is a typed `-32002 not_found`, not a panic
/// and not an internal error (#2074).
#[tokio::test]
async fn describe_unknown_name_is_not_found() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let s = state(tmp.path(), true);

    let err = agents_describe(&s, json!({ "name": "no-such-agent" }), ctx())
        .await
        .expect_err("an unknown agent must be an error");

    assert_eq!(err.code, RpcError::not_found("x").code);
}

/// `agents.describe` applies the same name guard `create`/`delete` do, so a
/// traversing name never reaches a path join (#2074).
#[tokio::test]
async fn describe_rejects_invalid_name() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let s = state(tmp.path(), true);

    for bad in ["../../etc/passwd", "Engineer", ""] {
        assert!(
            agents_describe(&s, json!({ "name": bad }), ctx())
                .await
                .is_err(),
            "'{bad}' must be rejected"
        );
    }
}

/// One unparseable disk file does not stop `agents.list` reporting the rest of
/// the catalog, and the broken row is flagged (#2074).
///
/// Why: the operator repair path is "list, spot the bad one, delete it" — a
/// listing that failed wholesale because of one file would remove the only
/// affordance for finding which file it was.
#[tokio::test]
async fn list_still_lists_other_agents_when_one_disk_file_is_unparseable() {
    let tmp = tempfile::tempdir().expect("tempdir");
    std::fs::write(
        tmp.path().join("engineer.md"),
        "---\nname: engineer\nextends: nonexistent-parent\n---\n\nBody.\n",
    )
    .expect("write");

    let s = state(tmp.path(), true);
    let result = agents_list(&s, Value::Null, ctx()).await.expect("list");
    let agents = result["agents"].as_array().expect("array");

    assert_eq!(
        agents.len(),
        crate::assets::DEFAULT_AGENTS.len(),
        "the broken file overrides one name; every other agent still lists"
    );
    let broken: Vec<_> = agents.iter().filter(|a| a["tier"] == "broken").collect();
    assert_eq!(broken.len(), 1);
    assert_eq!(broken[0]["has_warnings"], true);
    assert!(
        agents
            .iter()
            .filter(|a| a["name"] != "engineer")
            .all(|a| a["has_warnings"] == false),
        "one bad file must not taint its neighbours: {agents:?}"
    );
}

/// `has_warnings` tracks the same divergence `agents.describe` reports (#2074).
#[tokio::test]
async fn list_flags_a_hand_edited_row_and_leaves_pristine_rows_clean() {
    let project = tempfile::tempdir().expect("project tempdir");
    crate::agents::deploy::ensure_roster_deployed(project.path()).expect("deploy");
    let target = crate::agents::deploy::roster_target(project.path());
    std::fs::write(
        target.join("engineer.md"),
        "---\nname: engineer\n---\n\nEdited.\n",
    )
    .expect("hand-edit");

    let s = state(&target, true);
    let result = agents_list(&s, Value::Null, ctx()).await.expect("list");
    let agents = result["agents"].as_array().expect("array");

    let flagged: Vec<_> = agents
        .iter()
        .filter(|a| a["has_warnings"] == true)
        .map(|a| a["name"].as_str().expect("name"))
        .collect();
    assert_eq!(
        flagged,
        vec!["engineer"],
        "only the edited row carries a warning: {agents:?}"
    );
}

/// The pre-#2074 `agents.list` wire shape still deserializes (#2074).
///
/// Why: `has_warnings` was added to every row. A client compiled against the
/// four-field shape must keep working, so this deserializes each entry into a
/// struct that knows nothing about the new key.
#[tokio::test]
async fn list_entries_still_parse_into_the_pre_2074_wire_shape() {
    /// Exactly the fields `agents.list` returned before #2074.
    #[derive(Deserialize)]
    struct PreSliceEntry {
        name: String,
        tier: String,
        description: Option<String>,
        model: Option<String>,
    }

    let tmp = tempfile::tempdir().expect("tempdir");
    std::fs::write(
        tmp.path().join("my-custom.md"),
        "---\nname: my-custom\ndescription: Custom\nmodel: sonnet\n---\n\nBody.\n",
    )
    .expect("write");

    let s = state(tmp.path(), true);
    let result = agents_list(&s, Value::Null, ctx()).await.expect("list");

    let entries: Vec<PreSliceEntry> =
        serde_json::from_value(result["agents"].clone()).expect("the old shape must still parse");
    let custom = entries
        .iter()
        .find(|e| e.name == "my-custom")
        .expect("the disk agent must be present");
    assert_eq!(custom.tier, "project");
    assert_eq!(custom.description.as_deref(), Some("Custom"));
    assert_eq!(custom.model.as_deref(), Some("sonnet"));
}