dirge-agent 0.19.18

Minimalistic coding agent written in Rust, optimized for memory footprint and performance
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
//! User-defined **agent profiles** (dirge-ykeu, Phase 1: load-only).
//!
//! An agent profile is a named bundle of `{ prompt, model, tools, reasoning,
//! temperature }`. This module *loads* them; nothing here changes runtime
//! behavior yet — later phases wire `/agent <name>` switching and fold the
//! built-in roles (critic/review/…) into the same registry. Absent any
//! definitions the registry is empty and dirge behaves exactly as before
//! (fully opt-in).
//!
//! Two sources, layered (later overrides earlier, by name):
//!   1. `config.json` `"agents": { "<name>": { … } }` (lowest precedence)
//!   2. global files  `<config_dir>/agents/<name>.md`
//!   3. project files `.dirge/agents/<name>.md`            (highest)
//!
//! The `.md` files use the same YAML-ish frontmatter + body shape as skills
//! and prompts (a tiny hand-rolled parser — no serde_yaml).

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use serde::Deserialize;

/// Global agent-profile directory: `~/.config/dirge/agents/`.
pub fn global_agents_dir() -> PathBuf {
    crate::session::storage::config_path().join("agents")
}

/// Per-project agent-profile directory: `<project-root>/.dirge/agents/`.
/// Anchored at the project root (git-root walk-up, `DIRGE_PROJECT_ROOT`
/// override) via `ProjectPaths` rather than the raw launch CWD, so a
/// subdirectory launch still finds the repo's profiles (dirge-vpma.17).
pub fn project_agents_dir(cwd: &Path) -> PathBuf {
    crate::extras::dirge_paths::ProjectPaths::new(cwd).agents_dir()
}

/// Resolve a profile's `model` field to a model string for the active client.
/// If it names a `providers` alias carrying a `model`, that model is used; else
/// the value is treated as the model name. `None` → keep the current model.
///
/// Same-client resolution: only the model string is taken even when the alias
/// implies a different backend (`provider_type`/`base_url`). Shared by `/agent`
/// switching and the `task` tool's per-profile subagent routing.
pub fn resolve_model_alias(cfg: &crate::config::Config, model: Option<&str>) -> Option<String> {
    let m = model?;
    if let Some(providers) = &cfg.providers
        && let Some(entry) = providers.get(m)
        && let Some(model_str) = &entry.model
    {
        return Some(model_str.clone());
    }
    Some(m.to_string())
}

/// Which tools an agent may call. Enforced (in a later phase) through the same
/// permission-layer mechanism that backs prompt `deny_tools`.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum ToolPolicy {
    /// No restriction — every tool available (the default).
    #[default]
    All,
    /// Only these tool names are allowed.
    Allow(Vec<String>),
    /// Every tool except these names.
    Deny(Vec<String>),
}

impl ToolPolicy {
    /// Convert to the deny-list shape consumed by the permission layer
    /// (`current_prompt_deny_tools` / `apply_prompt_deny`). `Allow` is
    /// realized as "deny every built-in not in the allow-list" over
    /// `builtins`. Because `builtins` (`BUILTIN_TOOL_NAMES`) includes the
    /// `mcp_tool` and `plugin_tool` umbrella names, an `allow` list that
    /// omits them also denies ALL MCP and plugin tools wholesale — so
    /// `allow_tools` is a genuine cap (dirge-74nb). It cannot, however,
    /// allow-list a SPECIFIC MCP/plugin tool by name (those aren't
    /// enumerable here); to permit one, allow its umbrella (`mcp_tool` /
    /// `plugin_tool`). Names are lowercased to match the permission layer.
    #[allow(dead_code)] // consumed by `/agent` switching
    pub fn to_deny_list(&self, builtins: &[&str]) -> Vec<String> {
        match self {
            ToolPolicy::All => Vec::new(),
            ToolPolicy::Deny(names) => names.clone(),
            ToolPolicy::Allow(allow) => {
                let allow: Vec<String> = allow.iter().map(|s| s.to_ascii_lowercase()).collect();
                builtins
                    .iter()
                    .map(|b| b.to_ascii_lowercase())
                    .filter(|b| !allow.contains(b))
                    .collect()
            }
        }
    }
}

/// Capability tier for a `task(agent=…)` subagent's tool set:
/// `Toolless` (the unchanged one-shot `btw_query` default), `Readonly`
/// (a real filtered agent loop with the read-only tool universe), and
/// `ReadWrite` (readonly PLUS the write/bash family — a subagent can
/// edit the code tree and run builds/tests directly). Durable-state /
/// session-attribution / recursion / interactive tools stay stripped
/// regardless of tier (see `SUBAGENT_FORCED_EXCLUDES`), so even
/// `ReadWrite` can't write agent state or attribute to a session.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum SubagentToolTier {
    /// No tools — the subagent runs a one-shot `btw_query` (unchanged default).
    #[default]
    Toolless,
    /// Read-only tool set (read/grep/glob/…); no mutation, no recursion.
    Readonly,
    /// Read-write tool set — readonly + write/edit/bash/apply_patch.
    ReadWrite,
}

/// Which MCP tools a `task(agent=…)` subagent may call, on top of its tier's
/// built-in universe (issue #701). MCP tools are otherwise unreachable to a
/// subagent — the tier universe is built-in-only, so `allow` can't name one.
///
/// This is a SEPARATE opt-in channel from the tier: it can only add tools that
/// are genuinely MCP-sourced (validated against the live agent's MCP-tool set
/// at fork time), so it can never smuggle a built-in like `bash` past the
/// tier cap. Honored only on the tooled tiers (`Readonly`/`ReadWrite`); a
/// `Toolless` profile has no loop to attach tools to, so it's ignored there
/// (with a warning at route-build time).
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum SubagentMcpAccess {
    /// No MCP tools (the default — unchanged behavior).
    #[default]
    None,
    /// Every connected MCP tool.
    All,
    /// Only these MCP tool names (lowercased). Names that don't match a live
    /// MCP tool at fork time are silently dropped.
    Only(Vec<String>),
}

/// Per-profile policy for what tools a `task(agent=…)` subagent may use.
/// Layered over [`SubagentToolTier`]: the tier fixes the tool universe,
/// `allow`/`deny` are raw overrides (for readonly, `allow` cannot escalate
/// past the tier and `deny` narrows), and `max_turns` bounds the loop.
/// Defaults to a tool-less subagent.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SubagentToolPolicy {
    pub tier: SubagentToolTier,
    pub allow: Vec<String>,
    pub deny: Vec<String>,
    pub max_turns: Option<usize>,
    pub timeout_secs: Option<u64>,
    /// MCP tools to grant on top of the tier's built-in universe (#701).
    pub mcp: SubagentMcpAccess,
}

/// `config.json` `agents.<name>.subagent` block (serde). Mirrors the `.md`
/// frontmatter's `subagent_*` keys so both sources describe the same shape.
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(default)]
pub struct SubagentConfig {
    /// Tier name: "readonly" | "toolless" (omitted/unknown → toolless).
    pub tools: Option<String>,
    pub allow: Option<Vec<String>>,
    pub deny: Option<Vec<String>>,
    pub max_turns: Option<usize>,
    pub timeout_secs: Option<u64>,
    /// MCP access (#701). Accepts either a string (`"all"` / `"none"` / a
    /// single tool name) or a list of tool names.
    pub mcp: Option<McpAccessConfig>,
}

/// `config.json` `subagent.mcp` value: either a scalar (`"all"` / `"none"` /
/// one tool name) or a list of tool names. Mirrors the `.md` `subagent_mcp`
/// key, which accepts `all`, a bare name, or `[a, b]`.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum McpAccessConfig {
    Flag(String),
    List(Vec<String>),
}

/// Convert a `config.json` `subagent.mcp` value into [`SubagentMcpAccess`].
fn mcp_access_from_config(raw: Option<McpAccessConfig>) -> SubagentMcpAccess {
    match raw {
        None => SubagentMcpAccess::None,
        Some(McpAccessConfig::Flag(s)) => parse_mcp_access(&s),
        Some(McpAccessConfig::List(v)) => {
            let names = normalize_names(v);
            if names.is_empty() {
                SubagentMcpAccess::None
            } else {
                SubagentMcpAccess::Only(names)
            }
        }
    }
}

/// Parse an `.md` `subagent_mcp` frontmatter value (or a config scalar).
/// `all`/`*`/`true` → every MCP tool; empty/`none`/`off`/`false` → none;
/// `[a, b]` or a bare `a, b` / single name → those specific tool names.
fn parse_mcp_access(value: &str) -> SubagentMcpAccess {
    let trimmed = value.trim();
    if !trimmed.starts_with('[') {
        match trimmed.to_ascii_lowercase().as_str() {
            "" | "none" | "off" | "false" => return SubagentMcpAccess::None,
            "all" | "*" | "true" => return SubagentMcpAccess::All,
            _ => {}
        }
    }
    let names = parse_inline_list(trimmed);
    if names.is_empty() {
        SubagentMcpAccess::None
    } else {
        SubagentMcpAccess::Only(names)
    }
}

/// Map a tier name to its enum. Tolerant: known names map to variants,
/// anything else (incl. empty) → `Toolless` with a warning so a typo is
/// visible rather than silently upgrading a subagent.
fn parse_subagent_tier(raw: &str, agent_name: &str) -> SubagentToolTier {
    match raw.trim().to_ascii_lowercase().as_str() {
        "" | "toolless" | "none" | "off" | "false" => SubagentToolTier::Toolless,
        "readonly" | "read-only" | "read" => SubagentToolTier::Readonly,
        "readwrite" | "read-write" | "rw" | "full" => SubagentToolTier::ReadWrite,
        other => {
            tracing::warn!(
                target: "dirge::agents",
                agent = %agent_name,
                tier = %other,
                "unknown subagent tier; falling back to toolless"
            );
            SubagentToolTier::Toolless
        }
    }
}

/// Where a definition came from — drives precedence and the `/agents` listing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentSource {
    Config,
    GlobalFile,
    ProjectFile,
}

impl AgentSource {
    pub fn label(self) -> &'static str {
        match self {
            AgentSource::Config => "config.json",
            AgentSource::GlobalFile => "global file",
            AgentSource::ProjectFile => "project file",
        }
    }
}

/// A resolved agent profile.
#[derive(Debug, Clone)]
pub struct AgentDefinition {
    pub name: String,
    /// System prompt body. `None` → use the active/default prompt.
    pub prompt: Option<String>,
    /// `providers` alias to route this agent's calls through. `None` → default.
    pub model: Option<String>,
    pub tools: ToolPolicy,
    /// Reasoning effort hint (e.g. "low" / "medium" / "high"). Free-form.
    pub reasoning: Option<String>,
    pub temperature: Option<f64>,
    /// One-line summary for the `/agents` listing.
    pub description: Option<String>,
    /// What tools a `task(agent="<name>")` subagent may use. Defaults to
    /// tool-less (today's behavior); opt into `Readonly` per-profile.
    pub subagent: SubagentToolPolicy,
    pub source: AgentSource,
}

/// `config.json` `agents` entry (serde). Flat tool keys mirror the `.md`
/// frontmatter so both sources describe an agent the same way.
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(default)]
pub struct AgentConfig {
    pub prompt: Option<String>,
    pub model: Option<String>,
    pub allow_tools: Option<Vec<String>>,
    pub deny_tools: Option<Vec<String>>,
    pub reasoning: Option<String>,
    pub temperature: Option<f64>,
    pub description: Option<String>,
    /// Per-profile subagent tool policy. Omitted → tool-less subagent.
    pub subagent: Option<SubagentConfig>,
}

/// `deny_tools` wins when both are present (conservative); else `allow_tools`;
/// else unrestricted.
fn policy_from(allow: Option<Vec<String>>, deny: Option<Vec<String>>) -> ToolPolicy {
    match (deny, allow) {
        (Some(d), _) if !d.is_empty() => ToolPolicy::Deny(normalize_names(d)),
        (_, Some(a)) if !a.is_empty() => ToolPolicy::Allow(normalize_names(a)),
        _ => ToolPolicy::All,
    }
}

fn normalize_names(names: Vec<String>) -> Vec<String> {
    names
        .into_iter()
        .map(|s| s.trim().to_ascii_lowercase())
        .filter(|s| !s.is_empty())
        .collect()
}

impl AgentConfig {
    fn into_definition(self, name: &str, source: AgentSource) -> AgentDefinition {
        let s = self.subagent.unwrap_or_default();
        AgentDefinition {
            name: name.to_string(),
            prompt: self.prompt.filter(|p| !p.trim().is_empty()),
            model: self.model.filter(|m| !m.trim().is_empty()),
            tools: policy_from(self.allow_tools, self.deny_tools),
            reasoning: self.reasoning,
            temperature: self.temperature,
            description: self.description,
            subagent: SubagentToolPolicy {
                tier: s
                    .tools
                    .as_deref()
                    .map(|t| parse_subagent_tier(t, name))
                    .unwrap_or_default(),
                allow: s.allow.unwrap_or_default(),
                deny: s.deny.unwrap_or_default(),
                max_turns: s.max_turns,
                timeout_secs: s.timeout_secs,
                mcp: mcp_access_from_config(s.mcp),
            },
            source,
        }
    }
}

/// The merged, precedence-resolved set of agent profiles.
#[derive(Debug, Clone, Default)]
pub struct AgentRegistry {
    agents: BTreeMap<String, AgentDefinition>,
}

impl AgentRegistry {
    /// Load + merge from all sources. Order matters: config first, then global
    /// files, then project files — each `insert` overrides the same name, so
    /// the effective precedence is project > global > config.
    pub fn load(
        config_agents: Option<&std::collections::HashMap<String, AgentConfig>>,
        global_dir: Option<&Path>,
        project_dir: Option<&Path>,
    ) -> Self {
        let mut agents: BTreeMap<String, AgentDefinition> = BTreeMap::new();

        if let Some(cfg) = config_agents {
            for (name, ac) in cfg {
                if name.trim().is_empty() {
                    continue;
                }
                agents.insert(
                    name.clone(),
                    ac.clone().into_definition(name, AgentSource::Config),
                );
            }
        }
        if let Some(dir) = global_dir {
            load_dir(dir, AgentSource::GlobalFile, &mut agents);
        }
        if let Some(dir) = project_dir {
            load_dir(dir, AgentSource::ProjectFile, &mut agents);
        }

        Self { agents }
    }

    // Used by `/agent <name>` switching (next phase) and the test suite.
    #[allow(dead_code)]
    pub fn get(&self, name: &str) -> Option<&AgentDefinition> {
        self.agents.get(name)
    }

    pub fn is_empty(&self) -> bool {
        self.agents.is_empty()
    }

    pub fn len(&self) -> usize {
        self.agents.len()
    }

    /// Profiles in stable (name-sorted) order.
    pub fn iter(&self) -> impl Iterator<Item = &AgentDefinition> {
        self.agents.values()
    }

    // Used by `/agent` tab-completion (next phase).
    #[allow(dead_code)]
    pub fn names(&self) -> impl Iterator<Item = &str> {
        self.agents.keys().map(String::as_str)
    }
}

/// Scan `<dir>/*.md`, parsing each into a definition (filename stem = name).
/// Missing dir or unreadable files are skipped silently — agents are optional.
fn load_dir(dir: &Path, source: AgentSource, out: &mut BTreeMap<String, AgentDefinition>) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("md") {
            continue;
        }
        let Some(name) = path.file_stem().and_then(|s| s.to_str()) else {
            continue;
        };
        if name.trim().is_empty() {
            continue;
        }
        let Ok(raw) = std::fs::read_to_string(&path) else {
            continue;
        };
        out.insert(name.to_string(), parse_agent_md(name, &raw, source));
    }
}

/// Parse `---\n<frontmatter>\n---\n<body>` into an [`AgentDefinition`]. The body
/// is the agent's prompt; frontmatter keys (all optional): `model`,
/// `deny_tools`, `allow_tools`, `reasoning`, `temperature`, `description`.
/// Tolerant: a file without frontmatter is treated as a body-only (prompt)
/// agent. Mirrors `context::prompts`' tiny parser (no serde_yaml).
pub(crate) fn parse_agent_md(name: &str, raw: &str, source: AgentSource) -> AgentDefinition {
    let mut def = AgentDefinition {
        name: name.to_string(),
        prompt: None,
        model: None,
        tools: ToolPolicy::All,
        reasoning: None,
        temperature: None,
        description: None,
        subagent: SubagentToolPolicy::default(),
        source,
    };

    let after_open = raw
        .strip_prefix("---\n")
        .or_else(|| raw.strip_prefix("---\r\n"));
    let (front, body) = match after_open {
        Some(rest) => match rest
            .find("\n---\n")
            .map(|p| (p, 5))
            .or_else(|| rest.find("\r\n---\r\n").map(|p| (p, 7)))
        {
            Some((pos, marker_len)) => (&rest[..pos], &rest[pos + marker_len..]),
            None => ("", raw), // malformed → whole file is the body
        },
        None => ("", raw),
    };

    let body = body.trim();
    if !body.is_empty() {
        def.prompt = Some(body.to_string());
    }

    let mut allow: Option<Vec<String>> = None;
    let mut deny: Option<Vec<String>> = None;
    let mut sub_tier: Option<String> = None;
    let mut sub_allow: Option<Vec<String>> = None;
    let mut sub_deny: Option<Vec<String>> = None;
    let mut sub_max_turns: Option<usize> = None;
    let mut sub_timeout_secs: Option<u64> = None;
    let mut sub_mcp: Option<SubagentMcpAccess> = None;
    for line in front.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let Some((key, value)) = line.split_once(':') else {
            continue;
        };
        let (key, value) = (key.trim(), value.trim());
        match key {
            "model" if !value.is_empty() => def.model = Some(value.to_string()),
            "reasoning" if !value.is_empty() => def.reasoning = Some(value.to_string()),
            "description" if !value.is_empty() => def.description = Some(value.to_string()),
            "temperature" => def.temperature = value.parse::<f64>().ok(),
            "deny_tools" => deny = Some(parse_inline_list(value)),
            "allow_tools" => allow = Some(parse_inline_list(value)),
            "subagent_tools" if !value.is_empty() => sub_tier = Some(value.to_string()),
            "subagent_max_turns" => sub_max_turns = value.parse::<usize>().ok(),
            "subagent_timeout_secs" => sub_timeout_secs = value.parse::<u64>().ok(),
            "subagent_allow" => sub_allow = Some(parse_inline_list(value)),
            "subagent_deny" => sub_deny = Some(parse_inline_list(value)),
            "subagent_mcp" => sub_mcp = Some(parse_mcp_access(value)),
            _ => {}
        }
    }
    def.tools = policy_from(allow, deny);
    def.subagent = SubagentToolPolicy {
        tier: sub_tier
            .as_deref()
            .map(|t| parse_subagent_tier(t, name))
            .unwrap_or_default(),
        allow: sub_allow.unwrap_or_default(),
        deny: sub_deny.unwrap_or_default(),
        max_turns: sub_max_turns,
        timeout_secs: sub_timeout_secs,
        mcp: sub_mcp.unwrap_or_default(),
    };
    def
}

/// Parse an inline `[a, b, c]` (or bare `a, b`) list of tool names.
fn parse_inline_list(value: &str) -> Vec<String> {
    let inner = value.trim().trim_start_matches('[').trim_end_matches(']');
    inner
        .split(',')
        .map(|s| s.trim().trim_matches(|c| c == '"' || c == '\''))
        .filter(|s| !s.is_empty())
        .map(|s| s.to_ascii_lowercase())
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    #[test]
    fn parses_md_frontmatter_and_body() {
        let raw = "---\nmodel: haiku\ndeny_tools: [bash, write, edit]\nreasoning: high\ntemperature: 0.2\ndescription: read-only reviewer\n---\nYou are a careful reviewer. Report findings.\n";
        let def = parse_agent_md("reviewer", raw, AgentSource::ProjectFile);
        assert_eq!(def.name, "reviewer");
        assert_eq!(def.model.as_deref(), Some("haiku"));
        assert_eq!(def.reasoning.as_deref(), Some("high"));
        assert_eq!(def.temperature, Some(0.2));
        assert_eq!(def.description.as_deref(), Some("read-only reviewer"));
        assert_eq!(
            def.tools,
            ToolPolicy::Deny(vec!["bash".into(), "write".into(), "edit".into()])
        );
        assert_eq!(
            def.prompt.as_deref(),
            Some("You are a careful reviewer. Report findings.")
        );
    }

    #[test]
    fn body_only_file_is_a_prompt_agent() {
        let def = parse_agent_md(
            "scout",
            "Find where X is handled. Read-only.",
            AgentSource::GlobalFile,
        );
        assert!(def.model.is_none());
        assert_eq!(def.tools, ToolPolicy::All);
        assert_eq!(
            def.prompt.as_deref(),
            Some("Find where X is handled. Read-only.")
        );
        // Default profile → tool-less subagent (unchanged behavior).
        assert_eq!(def.subagent.tier, SubagentToolTier::Toolless);
    }

    #[test]
    fn subagent_frontmatter_enables_readonly_tier() {
        let raw = "---\nmodel: haiku\nsubagent_tools: readonly\nsubagent_max_turns: 12\nsubagent_deny: [webfetch]\n---\nbody";
        let def = parse_agent_md("researcher", raw, AgentSource::GlobalFile);
        assert_eq!(def.subagent.tier, SubagentToolTier::Readonly);
        assert_eq!(def.subagent.max_turns, Some(12));
        assert_eq!(def.subagent.deny, vec!["webfetch"]);
    }

    #[test]
    fn subagent_mcp_frontmatter_forms() {
        // list form
        let def = parse_agent_md(
            "r",
            "---\nsubagent_tools: readonly\nsubagent_mcp: [search_graph, find_refs]\n---\nb",
            AgentSource::ProjectFile,
        );
        assert_eq!(
            def.subagent.mcp,
            SubagentMcpAccess::Only(vec!["search_graph".into(), "find_refs".into()])
        );
        // `all` wildcard
        let def = parse_agent_md(
            "r",
            "---\nsubagent_tools: readonly\nsubagent_mcp: all\n---\nb",
            AgentSource::ProjectFile,
        );
        assert_eq!(def.subagent.mcp, SubagentMcpAccess::All);
        // bare single name
        let def = parse_agent_md(
            "r",
            "---\nsubagent_tools: readonly\nsubagent_mcp: search_graph\n---\nb",
            AgentSource::ProjectFile,
        );
        assert_eq!(
            def.subagent.mcp,
            SubagentMcpAccess::Only(vec!["search_graph".into()])
        );
        // omitted → None (default, unchanged behavior)
        let def = parse_agent_md(
            "r",
            "---\nsubagent_tools: readonly\n---\nb",
            AgentSource::Config,
        );
        assert_eq!(def.subagent.mcp, SubagentMcpAccess::None);
        // explicit none
        let def = parse_agent_md(
            "r",
            "---\nsubagent_tools: readonly\nsubagent_mcp: none\n---\nb",
            AgentSource::Config,
        );
        assert_eq!(def.subagent.mcp, SubagentMcpAccess::None);
    }

    #[test]
    fn subagent_mcp_config_json_forms() {
        // list
        let def = AgentConfig {
            subagent: Some(SubagentConfig {
                tools: Some("readonly".into()),
                mcp: Some(McpAccessConfig::List(vec!["Search_Graph".into()])),
                ..Default::default()
            }),
            ..Default::default()
        }
        .into_definition("r", AgentSource::Config);
        // normalized (lowercased)
        assert_eq!(
            def.subagent.mcp,
            SubagentMcpAccess::Only(vec!["search_graph".into()])
        );
        // scalar "all"
        let def = AgentConfig {
            subagent: Some(SubagentConfig {
                tools: Some("readonly".into()),
                mcp: Some(McpAccessConfig::Flag("all".into())),
                ..Default::default()
            }),
            ..Default::default()
        }
        .into_definition("r", AgentSource::Config);
        assert_eq!(def.subagent.mcp, SubagentMcpAccess::All);
    }

    #[test]
    fn subagent_frontmatter_unknown_tier_warns_and_falls_back() {
        let raw = "---\nsubagent_tools: banana\n---\nbody";
        let def = parse_agent_md("x", raw, AgentSource::Config);
        assert_eq!(
            def.subagent.tier,
            SubagentToolTier::Toolless,
            "an unknown tier name must fall back to tool-less, never escalate"
        );
    }

    #[test]
    fn subagent_config_json_into_definition() {
        let cfg = AgentConfig {
            subagent: Some(SubagentConfig {
                tools: Some("read-only".into()),
                deny: Some(vec!["grep".into()]),
                max_turns: Some(40),
                ..Default::default()
            }),
            ..Default::default()
        };
        let def = cfg.into_definition("res", AgentSource::Config);
        assert_eq!(def.subagent.tier, SubagentToolTier::Readonly);
        assert_eq!(def.subagent.deny, vec!["grep"]);
        assert_eq!(def.subagent.max_turns, Some(40));
        // readwrite is recognized as the read-write tier (parses; resolver yields the write/bash family)
        let rw = AgentConfig {
            subagent: Some(SubagentConfig {
                tools: Some("readwrite".into()),
                ..Default::default()
            }),
            ..Default::default()
        };
        assert_eq!(
            rw.into_definition("rw", AgentSource::Config).subagent.tier,
            SubagentToolTier::ReadWrite
        );
    }

    #[test]
    fn deny_wins_over_allow_when_both_present() {
        let raw = "---\nallow_tools: [read]\ndeny_tools: [bash]\n---\nbody";
        let def = parse_agent_md("a", raw, AgentSource::Config);
        assert_eq!(def.tools, ToolPolicy::Deny(vec!["bash".into()]));
    }

    #[test]
    fn precedence_project_over_global_over_config() {
        let tmp = std::env::temp_dir().join(format!("dirge-agents-test-{}", std::process::id()));
        let global = tmp.join("global");
        let project = tmp.join("project");
        std::fs::create_dir_all(&global).unwrap();
        std::fs::create_dir_all(&project).unwrap();
        // Same agent name "rev" defined in all three sources with a distinct model.
        let mut config: HashMap<String, AgentConfig> = HashMap::new();
        config.insert(
            "rev".into(),
            AgentConfig {
                model: Some("config-model".into()),
                ..Default::default()
            },
        );
        std::fs::write(global.join("rev.md"), "---\nmodel: global-model\n---\nb").unwrap();
        std::fs::write(project.join("rev.md"), "---\nmodel: project-model\n---\nb").unwrap();
        // A second agent only in config to confirm merge (not just override).
        config.insert(
            "only-config".into(),
            AgentConfig {
                model: Some("c".into()),
                ..Default::default()
            },
        );

        let reg = AgentRegistry::load(Some(&config), Some(&global), Some(&project));
        assert_eq!(reg.len(), 2);
        assert_eq!(
            reg.get("rev").unwrap().model.as_deref(),
            Some("project-model")
        );
        assert_eq!(reg.get("rev").unwrap().source, AgentSource::ProjectFile);
        assert_eq!(reg.get("only-config").unwrap().model.as_deref(), Some("c"));
        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn tool_policy_to_deny_list() {
        let builtins = ["read", "write", "edit", "bash"];
        assert!(ToolPolicy::All.to_deny_list(&builtins).is_empty());
        assert_eq!(
            ToolPolicy::Deny(vec!["bash".into()]).to_deny_list(&builtins),
            vec!["bash".to_string()]
        );
        // Allow(read) → deny every other built-in.
        let mut got = ToolPolicy::Allow(vec!["read".into()]).to_deny_list(&builtins);
        got.sort();
        assert_eq!(got, vec!["bash", "edit", "write"]);
    }

    /// dirge-74nb: over the REAL builtin set, an `allow_tools` list that
    /// omits the umbrellas denies all MCP *and* plugin tools — `allow_tools`
    /// is a genuine cap, not a built-ins-only filter.
    #[test]
    fn allow_tools_caps_mcp_and_plugin_via_umbrellas() {
        let deny = ToolPolicy::Allow(vec!["read".into(), "grep".into()])
            .to_deny_list(crate::agent::tools::BUILTIN_TOOL_NAMES);
        assert!(
            deny.iter().any(|d| d == "mcp_tool"),
            "MCP umbrella must be denied"
        );
        assert!(
            deny.iter().any(|d| d == "plugin_tool"),
            "plugin umbrella must be denied (dirge-74nb)"
        );
        // The allowed tools are NOT denied.
        assert!(!deny.iter().any(|d| d == "read"));
        assert!(!deny.iter().any(|d| d == "grep"));

        // Explicitly allowing an umbrella keeps that whole class callable.
        let deny = ToolPolicy::Allow(vec!["read".into(), "plugin_tool".into()])
            .to_deny_list(crate::agent::tools::BUILTIN_TOOL_NAMES);
        assert!(
            !deny.iter().any(|d| d == "plugin_tool"),
            "allowed umbrella stays callable"
        );
    }

    #[test]
    fn resolve_model_alias_prefers_provider_entry() {
        use crate::config::{Config, ProviderEntry};
        let mut providers = HashMap::new();
        providers.insert(
            "fast".to_string(),
            ProviderEntry {
                model: Some("anthropic/haiku".to_string()),
                ..Default::default()
            },
        );
        let cfg = Config {
            providers: Some(providers),
            ..Default::default()
        };
        // Alias with a model → that model string.
        assert_eq!(
            resolve_model_alias(&cfg, Some("fast")).as_deref(),
            Some("anthropic/haiku")
        );
        // Unknown alias → used verbatim as a model name.
        assert_eq!(
            resolve_model_alias(&cfg, Some("openai/gpt-4o")).as_deref(),
            Some("openai/gpt-4o")
        );
        // None → None (keep current model).
        assert_eq!(resolve_model_alias(&cfg, None), None);
    }

    #[test]
    fn empty_when_nothing_configured() {
        let reg = AgentRegistry::load(None, None, None);
        assert!(reg.is_empty());
    }
}