Skip to main content

vtcode_core/
primary_agent.rs

1use std::collections::BTreeMap;
2use std::error::Error;
3use std::fmt;
4use std::path::PathBuf;
5use std::sync::Arc;
6
7use vtcode_config::constants::{defaults::DEFAULT_PRIMARY_AGENT_NAME, tools};
8use vtcode_config::core::permissions::AgentPermissionsConfig;
9use vtcode_config::core::tools::ToolPolicy;
10use vtcode_config::{
11    DiscoveredSubagents, HookGroupConfig, HooksConfig, SubagentMcpServer, SubagentMemoryScope, SubagentSource,
12    SubagentSpec, builtin_primary_build_agent,
13};
14
15use crate::config::{ReasoningEffortLevel, VTCodeConfig};
16use crate::llm::provider::ToolDefinition;
17use crate::permissions::{PermissionRequest, ResolvedPermissionDecision, evaluate_effective_permissions};
18use crate::prompts::PromptContext;
19use crate::subagents::{ResolvedAgentRuntimeView, inline_mcp_provider};
20use tracing::warn;
21
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct ActivePrimaryAgentSpecIdentity {
24    pub name: String,
25    pub source: SubagentSource,
26    pub file_path: Option<PathBuf>,
27}
28
29#[derive(Debug, Clone, PartialEq)]
30pub struct ActivePrimaryAgent {
31    pub identity: ActivePrimaryAgentSpecIdentity,
32    pub display_name: String,
33    pub description: String,
34    pub color: Option<String>,
35    pub aliases: Vec<String>,
36    pub instructions: String,
37    pub tools: Option<Vec<String>>,
38    pub disallowed_tools: Vec<String>,
39    pub permissions: AgentPermissionsConfig,
40    pub model: Option<String>,
41    pub reasoning_effort: Option<ReasoningEffortLevel>,
42    pub hooks: Option<HooksConfig>,
43    pub skills: Vec<String>,
44    pub mcp_servers: Vec<SubagentMcpServer>,
45    pub memory: Option<SubagentMemoryScope>,
46    pub tool_policy_overrides: BTreeMap<String, ToolPolicy>,
47}
48
49impl ActivePrimaryAgent {
50    #[must_use]
51    pub fn from_spec(spec: &SubagentSpec) -> Self {
52        Self::from_runtime_view(&ResolvedAgentRuntimeView::from_spec(spec))
53    }
54
55    #[must_use]
56    pub fn from_runtime_view(runtime: &ResolvedAgentRuntimeView) -> Self {
57        Self {
58            identity: ActivePrimaryAgentSpecIdentity {
59                name: runtime.canonical_name.clone(),
60                source: runtime.source.clone(),
61                file_path: runtime.file_path.clone(),
62            },
63            display_name: runtime.display_name.clone(),
64            description: runtime.description.clone(),
65            color: runtime.color.clone(),
66            aliases: runtime.aliases.clone(),
67            instructions: runtime.instructions.clone(),
68            tools: runtime.tools.clone(),
69            disallowed_tools: runtime.disallowed_tools.clone(),
70            permissions: runtime.permissions.clone(),
71            model: runtime.model.clone(),
72            reasoning_effort: runtime.reasoning_effort,
73            hooks: runtime.hooks.clone(),
74            skills: runtime.skills.clone(),
75            mcp_servers: runtime.mcp_servers.clone(),
76            memory: runtime.memory,
77            tool_policy_overrides: runtime.tool_policy_overrides.clone(),
78        }
79    }
80
81    /// Canonical primary agent name (the active session "mode").
82    #[must_use]
83    pub fn name(&self) -> &str {
84        &self.identity.name
85    }
86
87    /// Whether this agent contributes lifecycle hooks that originate from
88    /// workspace-controlled content (project agent-spec files inside the
89    /// repository). Such hooks must be gated behind the workspace lifecycle
90    /// hook approval just like hooks declared in a workspace `vtcode.toml`.
91    #[must_use]
92    pub fn contributes_workspace_controlled_hooks(&self) -> bool {
93        self.hooks.is_some()
94            && matches!(
95                self.identity.source,
96                SubagentSource::ProjectVtcode | SubagentSource::ProjectClaude | SubagentSource::ProjectCodex
97            )
98    }
99}
100
101#[derive(Debug, Clone, PartialEq)]
102pub struct ActivePrimaryAgentState {
103    active: ActivePrimaryAgent,
104}
105
106impl Default for ActivePrimaryAgentState {
107    fn default() -> Self {
108        Self {
109            active: ActivePrimaryAgent::from_spec(&builtin_primary_build_agent()),
110        }
111    }
112}
113
114impl ActivePrimaryAgentState {
115    #[must_use]
116    pub const fn active(&self) -> &ActivePrimaryAgent {
117        &self.active
118    }
119
120    #[must_use]
121    pub fn from_discovery(discovered: &DiscoveredSubagents) -> Self {
122        Self::from_specs(&discovered.effective)
123    }
124
125    #[must_use]
126    pub fn from_specs(specs: &[SubagentSpec]) -> Self {
127        Self::from_specs_with_default(specs, DEFAULT_PRIMARY_AGENT_NAME)
128    }
129
130    #[must_use]
131    pub fn from_specs_with_default(specs: &[SubagentSpec], requested_default: &str) -> Self {
132        let requested = if requested_default.trim().is_empty() {
133            DEFAULT_PRIMARY_AGENT_NAME
134        } else {
135            requested_default.trim()
136        };
137        let active = match resolve_primary_agent(specs, requested) {
138            Ok(active) => active,
139            Err(_) => {
140                if let Some(requested_name) = fallback_notice(requested) {
141                    warn!(
142                        requested = %requested_name,
143                        fallback = %DEFAULT_PRIMARY_AGENT_NAME,
144                        "Primary agent '{}' was not discovered; falling back to the built-in '{}' agent. \
145                         Set default_primary_agent to a discovered agent or add a matching primary agent.",
146                        requested_name,
147                        DEFAULT_PRIMARY_AGENT_NAME,
148                    );
149                }
150                ActivePrimaryAgent::from_spec(&builtin_primary_build_agent())
151            }
152        };
153        Self { active }
154    }
155
156    pub fn reset_to_default_from_specs(&mut self, specs: &[SubagentSpec]) -> &ActivePrimaryAgent {
157        self.active = Self::from_specs(specs).active;
158        &self.active
159    }
160
161    /// Restore a previously captured active-agent snapshot. Runloop prompt
162    /// boundaries use this to keep a write-capable Build handoff intact when
163    /// unrelated queued UI input attempts to switch modes mid-turn.
164    pub fn restore_snapshot(&mut self, snapshot: ActivePrimaryAgent) -> &ActivePrimaryAgent {
165        self.active = snapshot;
166        &self.active
167    }
168
169    pub fn select_from_discovery(
170        &mut self,
171        discovered: &DiscoveredSubagents,
172        requested: &str,
173    ) -> PrimaryAgentResolutionResult<&ActivePrimaryAgent> {
174        self.select_from_specs(&discovered.effective, requested)
175    }
176
177    pub fn select_from_specs(
178        &mut self,
179        specs: &[SubagentSpec],
180        requested: &str,
181    ) -> PrimaryAgentResolutionResult<&ActivePrimaryAgent> {
182        let active = resolve_primary_agent(specs, requested)?;
183        self.active = active;
184        Ok(&self.active)
185    }
186}
187
188pub type PrimaryAgentResolutionResult<T> = Result<T, PrimaryAgentResolutionError>;
189
190#[derive(Debug, Clone, PartialEq, Eq)]
191pub enum PrimaryAgentResolutionError {
192    UnknownAgent { requested: String },
193}
194
195impl fmt::Display for PrimaryAgentResolutionError {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        match self {
198            Self::UnknownAgent { requested } => write!(f, "Unknown primary agent {requested}"),
199        }
200    }
201}
202
203impl Error for PrimaryAgentResolutionError {}
204
205pub fn resolve_discovered_primary_agent(
206    discovered: &DiscoveredSubagents,
207    requested: &str,
208) -> PrimaryAgentResolutionResult<ActivePrimaryAgent> {
209    resolve_primary_agent(&discovered.effective, requested)
210}
211
212pub fn resolve_primary_agent(
213    specs: &[SubagentSpec],
214    requested: &str,
215) -> PrimaryAgentResolutionResult<ActivePrimaryAgent> {
216    specs
217        .iter()
218        .find(|spec| spec.is_primary() && spec.name.eq_ignore_ascii_case(requested))
219        .or_else(|| specs.iter().find(|spec| spec.is_primary() && spec.matches_name(requested)))
220        .map(ActivePrimaryAgent::from_spec)
221        .ok_or_else(|| PrimaryAgentResolutionError::UnknownAgent { requested: requested.to_string() })
222}
223
224/// Returns `true` for cleanup-only child-agent tools that must remain
225/// available regardless of the active primary agent's tool policy.
226///
227/// NOTE: after `wait_agent`/`close_agent` were folded into the unified
228/// `agent` tool (action='wait'/'close'), `LIFECYCLE_CLEANUP_TOOLS` no longer
229/// matches any name that is actually *emitted* to the model — the emitted
230/// name is always `tools::AGENT` ("agent"). This carve-out therefore only
231/// takes effect if a caller passes one of the legacy granular names
232/// (`wait_agent`/`close_agent`) directly rather than the folded name.
233/// Expressing true per-action granularity at runtime (allow cleanup actions
234/// on the folded `agent` tool while denying `spawn`) requires
235/// execution-time action gating, the same mechanism used for
236/// `mcp:connect`/`mcp:disconnect` (see `action_qualified_policy_name` in
237/// `tool_intent.rs`), and is deferred — see
238/// `apply_primary_agent_tool_policy`'s doc comment for the specific gap.
239fn is_subagent_cleanup_tool(tool_name: &str) -> bool {
240    tools::LIFECYCLE_CLEANUP_TOOLS
241        .iter()
242        .any(|cleanup| cleanup.eq_ignore_ascii_case(tool_name))
243}
244
245/// Returns the configured agent name that should be surfaced to the operator
246/// when the resolver cannot find it and falls back to the built-in `build`
247/// agent, or `None` when the fallback is expected and should stay silent.
248///
249/// A fallback is expected (and therefore silent) when the operator asked for
250/// the default `build` agent — whether explicitly or because no
251/// `default_primary_agent` was configured — since the built-in `build` agent
252/// *is* the canonical build. Any other requested name that misses discovery is
253/// a configuration mismatch the operator should hear about.
254///
255/// Extracted as a pure predicate so the decision is unit-testable without a
256/// tracing subscriber.
257fn fallback_notice(requested_default: &str) -> Option<&str> {
258    let requested = requested_default.trim();
259    if requested.is_empty() || requested.eq_ignore_ascii_case(DEFAULT_PRIMARY_AGENT_NAME) {
260        None
261    } else {
262        Some(requested)
263    }
264}
265
266#[must_use]
267pub fn primary_agent_allows_tool(agent: &ActivePrimaryAgent, tool_name: &str) -> bool {
268    let tool_name = tool_name.trim();
269
270    // Cleanup tools stay available so restricted agents can still join or
271    // close already-running child work.
272    if is_subagent_cleanup_tool(tool_name) {
273        return true;
274    }
275
276    // The task tracker stays available so restricted primaries (including
277    // custom `auto` agents with an explicit `tools:` list) can still report
278    // progress. Planning/interview tools stay author-curated: unlike the
279    // tracker they change the session mode, so an explicit omission must
280    // keep working.
281    if tool_name.eq_ignore_ascii_case(tools::TASK_TRACKER) {
282        return true;
283    }
284
285    let allow_list_allows = agent
286        .tools
287        .as_ref()
288        .is_none_or(|tools| tools.iter().any(|allowed| allowed.trim().eq_ignore_ascii_case(tool_name)));
289    if !allow_list_allows {
290        return false;
291    }
292
293    !agent
294        .disallowed_tools
295        .iter()
296        .any(|denied| denied.trim().eq_ignore_ascii_case(tool_name))
297}
298
299/// Filters the emitted tool list down to those `primary_agent_allows_tool`
300/// permits for `agent`.
301///
302/// KNOWN LIMITATION: filtering is by each tool's canonical
303/// `function_name()`, and matching only trims and ignores ASCII case — it
304/// does not alias-resolve. For multi-action tools that fold several legacy
305/// actions into one emitted name (e.g. `agent` folding
306/// spawn/wait/close/send_input/resume, or `mcp` folding connect/disconnect),
307/// a granular allow/deny entry such as `"spawn_agent"` in
308/// `disallowed_tools`/`tools` has no effect on the folded `agent` tool: the
309/// whole tool is either present or absent based on whether `"agent"` itself
310/// is allowed. Expressing "allow cleanup (wait/close) but deny spawn"
311/// therefore cannot be done here; it requires execution-time action gating —
312/// the same action-qualified mechanism already used to keep `mcp:connect`/
313/// `mcp:disconnect` HITL-gated separately from bare `mcp` (see
314/// `action_qualified_policy_name` in `tool_intent.rs`) — applied per-action
315/// at the point the subagent tool call is dispatched. That is deferred.
316#[must_use]
317pub fn apply_primary_agent_tool_policy(
318    tools: Option<Arc<Vec<ToolDefinition>>>,
319    agent: &ActivePrimaryAgent,
320) -> Option<Arc<Vec<ToolDefinition>>> {
321    let tools = tools?;
322    let Some(first_rejected) = tools
323        .iter()
324        .position(|tool| !primary_agent_allows_tool(agent, tool.function_name()))
325    else {
326        return (!tools.is_empty()).then_some(tools);
327    };
328    let filtered = tools
329        .iter()
330        .take(first_rejected)
331        .chain(
332            tools
333                .iter()
334                .skip(first_rejected + 1)
335                .filter(|tool| primary_agent_allows_tool(agent, tool.function_name())),
336        )
337        .cloned()
338        .collect::<Vec<_>>();
339
340    (!filtered.is_empty()).then(|| Arc::new(filtered))
341}
342
343#[must_use]
344pub fn build_primary_agent_runtime_config(parent: &VTCodeConfig, agent: &ActivePrimaryAgent) -> VTCodeConfig {
345    let mut config = parent.clone();
346    // "inherit" (and empty) are sentinels meaning "use the parent's model" — mirrors
347    // resolve_subagent_model's handling in subagents/model.rs. Built-in primary agents
348    // (e.g. "auto", "build") default their `model` field to "inherit", so without this
349    // check every plain `exec` run would clobber a real, explicitly configured model
350    // (via --model or [agent].default_model) with the literal string "inherit", which
351    // then fails ModelId parsing entirely.
352    if let Some(model) = agent.model.as_ref() {
353        let trimmed = model.trim();
354        if !trimmed.is_empty() && !trimmed.eq_ignore_ascii_case("inherit") {
355            config.agent.default_model = model.clone();
356        }
357    }
358    if let Some(reasoning_effort) = agent.reasoning_effort {
359        config.agent.reasoning_effort = reasoning_effort;
360    }
361    merge_primary_mcp_servers(&mut config, agent.mcp_servers.as_slice());
362    config
363}
364
365#[must_use]
366pub fn build_primary_agent_hook_config(global: &HooksConfig, agent: &ActivePrimaryAgent) -> HooksConfig {
367    let mut config = global.clone();
368    merge_active_primary_hooks(&mut config, agent.hooks.as_ref());
369    config
370}
371
372pub fn apply_primary_agent_prompt_context(context: &mut PromptContext, agent: &ActivePrimaryAgent) {
373    context.replace_available_skills_with_named(agent.skills.as_slice());
374}
375
376#[must_use]
377pub fn active_primary_agent_permissions(agent: &ActivePrimaryAgent) -> &AgentPermissionsConfig {
378    &agent.permissions
379}
380
381pub fn evaluate_active_primary_agent_permissions(
382    config: &VTCodeConfig,
383    agent: &ActivePrimaryAgent,
384    workspace_root: &std::path::Path,
385    current_dir: &std::path::Path,
386    request: &PermissionRequest,
387) -> ResolvedPermissionDecision {
388    evaluate_effective_permissions(
389        &config.permissions,
390        active_primary_agent_permissions(agent),
391        workspace_root,
392        current_dir,
393        request,
394    )
395}
396
397fn merge_primary_mcp_servers(config: &mut VTCodeConfig, servers: &[SubagentMcpServer]) {
398    for server in servers {
399        match server {
400            SubagentMcpServer::Named(_) => {}
401            SubagentMcpServer::Inline(definition) => {
402                for (name, value) in definition {
403                    if config.mcp.providers.iter().any(|provider| provider.name == *name) {
404                        continue;
405                    }
406                    if let Some(provider) = inline_mcp_provider(name, value) {
407                        config.mcp.providers.push(provider);
408                    }
409                }
410            }
411        }
412    }
413}
414
415fn merge_active_primary_hooks(config: &mut HooksConfig, hooks: Option<&HooksConfig>) {
416    let Some(hooks) = hooks else {
417        return;
418    };
419
420    config.lifecycle.quiet_success_output |= hooks.lifecycle.quiet_success_output;
421    append_hook_groups(&mut config.lifecycle.session_start, &hooks.lifecycle.session_start);
422    append_hook_groups(&mut config.lifecycle.session_end, &hooks.lifecycle.session_end);
423    append_hook_groups(&mut config.lifecycle.subagent_start, &hooks.lifecycle.subagent_start);
424    append_hook_groups(&mut config.lifecycle.subagent_stop, &hooks.lifecycle.subagent_stop);
425    append_hook_groups(&mut config.lifecycle.user_prompt_submit, &hooks.lifecycle.user_prompt_submit);
426    append_hook_groups(&mut config.lifecycle.pre_tool_use, &hooks.lifecycle.pre_tool_use);
427    append_hook_groups(&mut config.lifecycle.post_tool_use, &hooks.lifecycle.post_tool_use);
428    append_hook_groups(&mut config.lifecycle.permission_request, &hooks.lifecycle.permission_request);
429    append_hook_groups(&mut config.lifecycle.pre_compact, &hooks.lifecycle.pre_compact);
430    append_hook_groups(&mut config.lifecycle.stop, &hooks.lifecycle.stop);
431    append_hook_groups(&mut config.lifecycle.notification, &hooks.lifecycle.notification);
432}
433
434fn append_hook_groups(target: &mut Vec<HookGroupConfig>, source: &[HookGroupConfig]) {
435    target.extend(source.iter().cloned());
436}
437
438#[cfg(test)]
439mod tests {
440    use std::collections::BTreeMap;
441
442    use serde_json::json;
443    use tempfile::TempDir;
444    use vtcode_config::core::permissions::{AgentPermissionsConfig, PermissionDefault};
445    use vtcode_config::{
446        HookCommandConfig, HooksConfig, IsolationMode, SubagentDiscoveryInput, SubagentMcpServer, SubagentMemoryScope,
447        SubagentSource, builtin_plan_agent, builtin_primary_auto_agent, builtin_primary_duck_agent, builtin_subagents,
448        discover_subagents,
449    };
450
451    use crate::config::constants::tools;
452    use crate::permissions::{ResolvedPermissionDecision, build_permission_request};
453
454    use super::*;
455
456    #[test]
457    fn resolves_existing_spec_by_name() {
458        let spec = test_spec("planner");
459        let active = resolve_primary_agent(&[spec], "planner").expect("resolved");
460
461        assert_eq!(active.identity.name, "planner");
462        assert_eq!(active.display_name, "planner");
463        assert_eq!(active.description, "planner description");
464        assert_eq!(active.color.as_deref(), Some("blue"));
465        assert_eq!(active.instructions, "planner instructions");
466        assert_eq!(active.tools, Some(vec!["code_search".to_string()]));
467        assert_eq!(active.disallowed_tools, vec!["file_operation".to_string()]);
468        assert_eq!(active.permissions.default, PermissionDefault::Deny);
469        assert_eq!(active.model.as_deref(), Some("gpt-5.1"));
470        assert_eq!(active.reasoning_effort, Some(ReasoningEffortLevel::High));
471        assert!(active.hooks.is_none());
472    }
473
474    #[test]
475    fn unknown_agent_error_preserves_current_active_agent() {
476        let current = test_spec("current");
477        let specs = vec![current.clone()];
478        let mut state = ActivePrimaryAgentState::default();
479        let original = state.select_from_specs(&specs, "current").expect("initial selection").clone();
480
481        let error = state.select_from_specs(&specs, "missing").expect_err("unknown agent");
482
483        assert_eq!(error, PrimaryAgentResolutionError::UnknownAgent { requested: "missing".to_string() });
484        assert_eq!(state.active(), &original);
485    }
486
487    #[test]
488    fn restore_snapshot_returns_to_write_capable_build_agent() {
489        let mut state = ActivePrimaryAgentState::default();
490        let build_snapshot = state.active().clone();
491        state
492            .select_from_specs(&[test_spec("duck")], "duck")
493            .expect("select leaked agent");
494        assert_eq!(state.active().identity.name, "duck");
495
496        state.restore_snapshot(build_snapshot);
497
498        assert_eq!(state.active().identity.name, "build");
499    }
500
501    #[test]
502    fn alias_resolution_uses_existing_matches_name_semantics() {
503        let mut spec = test_spec("reviewer");
504        spec.aliases = vec!["critic".to_string()];
505
506        let active = resolve_primary_agent(&[spec], "CRITIC").expect("resolved by alias");
507
508        assert_eq!(active.identity.name, "reviewer");
509        assert_eq!(active.display_name, "reviewer");
510    }
511
512    #[test]
513    fn exact_name_resolution_wins_over_alias() {
514        let mut build = test_spec("build");
515        build.aliases = vec!["builder".to_string()];
516        let builder = test_spec("builder");
517
518        let active = resolve_primary_agent(&[build, builder], "builder").expect("resolved");
519
520        assert_eq!(active.identity.name, "builder");
521    }
522
523    #[test]
524    fn ignored_subagent_fields_do_not_enter_primary_agent_runtime() {
525        let mut spec = test_spec("worker");
526        spec.aliases = vec!["builder".to_string()];
527        spec.skills = vec!["rust".to_string()];
528        spec.mcp_servers = vec![SubagentMcpServer::Named("filesystem".to_string())];
529        spec.background = true;
530        spec.max_turns = Some(12);
531        spec.nickname_candidates = vec!["w".to_string()];
532        spec.initial_prompt = Some("start here".to_string());
533        spec.memory = Some(SubagentMemoryScope::Project);
534        spec.isolation = Some(IsolationMode::Full);
535
536        let active = ActivePrimaryAgent::from_spec(&spec);
537
538        assert_eq!(active.identity.name, "worker");
539        assert_eq!(active.display_name, "worker");
540        assert_eq!(active.description, "worker description");
541        assert_eq!(active.color.as_deref(), Some("blue"));
542        assert_eq!(active.aliases, vec!["builder".to_string()]);
543        assert_eq!(active.instructions, "worker instructions");
544        assert_eq!(active.tools, Some(vec!["code_search".to_string()]));
545        assert_eq!(active.disallowed_tools, vec!["file_operation".to_string()]);
546        assert_eq!(active.permissions.default, PermissionDefault::Deny);
547        assert_eq!(active.model.as_deref(), Some("gpt-5.1"));
548        assert_eq!(active.reasoning_effort, Some(ReasoningEffortLevel::High));
549        assert_eq!(active.skills, vec!["rust".to_string()]);
550        assert_eq!(active.mcp_servers, vec![SubagentMcpServer::Named("filesystem".to_string())]);
551        assert_eq!(active.memory, Some(SubagentMemoryScope::Project));
552    }
553
554    #[test]
555    fn primary_runtime_adapter_uses_shared_resolved_view_for_overlapping_fields() {
556        let mut spec = test_spec("worker");
557        spec.description = "Worker display metadata".to_string();
558        spec.color = Some("green".to_string());
559        spec.aliases = vec!["builder".to_string()];
560        spec.skills = vec!["rust".to_string(), "repo".to_string()];
561        spec.mcp_servers = vec![SubagentMcpServer::Named("filesystem".to_string())];
562        spec.hooks = Some(HooksConfig::default());
563        spec.memory = Some(SubagentMemoryScope::Project);
564
565        let runtime = ResolvedAgentRuntimeView::from_spec(&spec);
566        let active = ActivePrimaryAgent::from_runtime_view(&runtime);
567
568        assert_eq!(runtime.canonical_name, "worker");
569        assert_eq!(runtime.display_name, "worker");
570        assert_eq!(runtime.description, "Worker display metadata");
571        assert_eq!(runtime.color.as_deref(), Some("green"));
572        assert_eq!(runtime.aliases, vec!["builder".to_string()]);
573        assert_eq!(runtime.skills, vec!["rust".to_string(), "repo".to_string()]);
574        assert_eq!(runtime.mcp_servers.len(), 1);
575        assert!(runtime.hooks.is_some());
576        assert_eq!(runtime.memory, Some(SubagentMemoryScope::Project));
577        assert!(runtime.read_only);
578        assert_eq!(active.identity.name, runtime.canonical_name);
579        assert_eq!(active.display_name, runtime.display_name);
580        assert_eq!(active.description, runtime.description);
581        assert_eq!(active.color, runtime.color);
582        assert_eq!(active.aliases, runtime.aliases);
583        assert_eq!(active.instructions, runtime.instructions);
584        assert_eq!(active.tools, runtime.tools);
585        assert_eq!(active.disallowed_tools, runtime.disallowed_tools);
586        assert_eq!(active.permissions, runtime.permissions);
587        assert_eq!(active.model, runtime.model);
588        assert_eq!(active.reasoning_effort, runtime.reasoning_effort);
589        assert_eq!(active.hooks, runtime.hooks);
590        assert_eq!(active.skills, runtime.skills);
591        assert_eq!(active.mcp_servers, runtime.mcp_servers);
592        assert_eq!(active.memory, runtime.memory);
593    }
594
595    #[test]
596    fn default_state_uses_builtin_build_agent() {
597        let mut state = ActivePrimaryAgentState::default();
598
599        assert_eq!(state.active().identity.name, DEFAULT_PRIMARY_AGENT_NAME);
600        assert_eq!(state.active().identity.name, "build");
601        assert_eq!(state.active().identity.source, SubagentSource::Builtin);
602
603        state.select_from_specs(&[test_spec("worker")], "worker").expect("selected");
604        assert_eq!(state.active().identity.name, "worker");
605
606        state.reset_to_default_from_specs(&[]);
607
608        assert_eq!(state.active().identity.name, DEFAULT_PRIMARY_AGENT_NAME);
609        assert_eq!(state.active().identity.name, "build");
610        assert_eq!(state.active().identity.source, SubagentSource::Builtin);
611    }
612
613    #[test]
614    fn from_specs_falls_back_to_builtin_build_agent() {
615        let active = ActivePrimaryAgentState::from_specs(&[]);
616
617        assert_eq!(active.active().identity.name, "build");
618        assert_eq!(active.active().identity.source, SubagentSource::Builtin);
619    }
620
621    #[test]
622    fn from_specs_with_default_selects_configured_primary_agent() {
623        let active = ActivePrimaryAgentState::from_specs_with_default(&[test_spec("builder")], "builder");
624
625        assert_eq!(active.active().identity.name, "builder");
626    }
627
628    #[test]
629    fn from_specs_with_default_falls_back_to_build_for_missing_configured_agent() {
630        let active = ActivePrimaryAgentState::from_specs_with_default(&[test_spec("builder")], "missing");
631
632        assert_eq!(active.active().identity.name, "build");
633        assert_eq!(active.active().identity.source, SubagentSource::Builtin);
634    }
635
636    #[test]
637    fn fallback_notice_silent_for_build_and_empty() {
638        // The built-in `build` agent is the canonical default, so falling back
639        // to it when the operator asked for `build` (or nothing) is expected.
640        assert_eq!(fallback_notice("build"), None);
641        assert_eq!(fallback_notice("BUILD"), None);
642        assert_eq!(fallback_notice("Build"), None);
643        assert_eq!(fallback_notice(""), None);
644        assert_eq!(fallback_notice("   "), None);
645    }
646
647    #[test]
648    fn fallback_notice_surfaces_non_default_mismatches() {
649        // Any other requested name that misses discovery is a configuration
650        // mismatch the operator should be warned about.
651        assert_eq!(fallback_notice("duck"), Some("duck"));
652        assert_eq!(fallback_notice("auto"), Some("auto"));
653        assert_eq!(fallback_notice("  duck  "), Some("duck"));
654    }
655
656    #[test]
657    fn discovery_precedence_overrides_builtin_build_agent() {
658        let temp = TempDir::new().expect("tempdir");
659        let discovered = discover_subagents(&SubagentDiscoveryInput {
660            workspace_root: temp.path().to_path_buf(),
661            cli_agents: Some(json!({
662                "build": {
663                    "description": "CLI build",
664                    "prompt": "cli build instructions",
665                    "model": "gpt-cli",
666                    "mode": "primary",
667                    "permissions": { "default": "ask" }
668                }
669            })),
670            plugin_agent_files: Vec::new(),
671            include_user_agents: false,
672        })
673        .expect("discovered subagents");
674
675        let active = ActivePrimaryAgentState::from_discovery(&discovered);
676
677        assert_eq!(active.active().identity.name, "build");
678        assert_eq!(active.active().identity.source, SubagentSource::Cli);
679        assert_eq!(active.active().instructions, "cli build instructions");
680        assert_eq!(active.active().model.as_deref(), Some("gpt-cli"));
681    }
682
683    #[test]
684    fn default_build_agent_allows_baseline_read_and_exec_tools() {
685        let active = ActivePrimaryAgentState::default();
686
687        assert!(primary_agent_allows_tool(active.active(), tools::CODE_SEARCH));
688        assert!(primary_agent_allows_tool(active.active(), tools::EXEC_COMMAND));
689        assert!(primary_agent_allows_tool(active.active(), tools::APPLY_PATCH));
690        assert!(primary_agent_allows_tool(active.active(), tools::RUN_PTY_CMD));
691        assert_eq!(active.active().permissions.default, PermissionDefault::Ask);
692    }
693
694    #[test]
695    fn build_and_auto_expose_the_same_tools_and_policy_decisions() {
696        let build = ActivePrimaryAgent::from_spec(&builtin_primary_build_agent());
697        let auto = ActivePrimaryAgent::from_spec(&builtin_primary_auto_agent());
698        let tools_to_compare = [
699            tools::CODE_SEARCH,
700            tools::EXEC_COMMAND,
701            tools::APPLY_PATCH,
702            tools::RUN_PTY_CMD,
703            tools::WRITE_FILE,
704            tools::REQUEST_USER_INPUT,
705        ];
706
707        for tool in tools_to_compare {
708            assert_eq!(
709                primary_agent_allows_tool(&build, tool),
710                primary_agent_allows_tool(&auto, tool),
711                "Build and Auto must expose the same capability for {tool}"
712            );
713        }
714    }
715
716    #[test]
717    fn readonly_primaries_expose_public_read_tools_and_block_apply_patch() {
718        for spec in [builtin_primary_duck_agent(), builtin_plan_agent()] {
719            let name = spec.name.clone();
720            let active = ActivePrimaryAgent::from_spec(&spec);
721
722            assert!(primary_agent_allows_tool(&active, tools::CODE_SEARCH), "{name} should expose code_search");
723            assert!(primary_agent_allows_tool(&active, tools::EXEC_COMMAND), "{name} should expose exec_command");
724            assert!(primary_agent_allows_tool(&active, tools::REQUEST_USER_INPUT));
725            assert!(primary_agent_allows_tool(&active, tools::RECORD_DECISION));
726
727            assert!(!primary_agent_allows_tool(&active, tools::APPLY_PATCH), "{name} must not expose apply_patch");
728            assert!(!primary_agent_allows_tool(&active, tools::RUN_PTY_CMD), "{name} must not expose run_pty_cmd");
729            assert!(!primary_agent_allows_tool(&active, tools::WRITE_FILE), "{name} must not expose write_file");
730        }
731    }
732
733    #[test]
734    fn tool_policy_intersects_allow_list_then_applies_deny_list() {
735        let mut spec = test_spec("worker");
736        spec.tools = Some(vec![" \tCoDe_SeArCh\n".to_string(), "\u{2003}ExEc_CoMmAnD\u{a0}".to_string()]);
737        spec.disallowed_tools = vec!["\u{a0}CODE_search\u{2003}".to_string()];
738        let active = ActivePrimaryAgent::from_spec(&spec);
739
740        assert!(primary_agent_allows_tool(&active, "\u{a0}EXEC_command\u{2003}"));
741        assert!(!primary_agent_allows_tool(&active, " \tcode_SEARCH\n"));
742        assert!(!primary_agent_allows_tool(&active, tools::APPLY_PATCH));
743        assert!(!primary_agent_allows_tool(&active, "exec_command_extra"));
744        assert!(!primary_agent_allows_tool(&active, tools::RUN_PTY_CMD));
745    }
746
747    #[test]
748    fn absent_tool_allow_list_allows_names_except_deny_matches() {
749        let mut spec = test_spec("worker");
750        spec.tools = None;
751        spec.disallowed_tools = vec![" \tCoDe_SeArCh\n".to_string()];
752        let active = ActivePrimaryAgent::from_spec(&spec);
753
754        assert!(primary_agent_allows_tool(&active, " ExEc_CoMmAnD "));
755        assert!(primary_agent_allows_tool(&active, "custom_tool"));
756        assert!(!primary_agent_allows_tool(&active, " CODE_search "));
757    }
758
759    #[test]
760    fn tool_policy_preserves_empty_name_matching() {
761        let mut spec = test_spec("worker");
762        spec.tools = None;
763        spec.disallowed_tools.clear();
764        let mut active = ActivePrimaryAgent::from_spec(&spec);
765
766        assert!(primary_agent_allows_tool(&active, ""));
767        assert!(primary_agent_allows_tool(&active, "\u{2003}\t\u{a0}"));
768        active.tools = Some(Vec::new());
769        assert!(!primary_agent_allows_tool(&active, ""));
770        assert!(!primary_agent_allows_tool(&active, "\u{2003}\t\u{a0}"));
771        active.tools = Some(vec!["\u{a0} \t".to_string()]);
772        assert!(primary_agent_allows_tool(&active, ""));
773        assert!(primary_agent_allows_tool(&active, "\u{2003}"));
774        assert!(!primary_agent_allows_tool(&active, "custom_tool"));
775        active.disallowed_tools = vec![String::new()];
776        assert!(!primary_agent_allows_tool(&active, ""));
777        assert!(!primary_agent_allows_tool(&active, "\u{2003}"));
778    }
779
780    #[test]
781    fn tool_policy_keeps_non_ascii_case_and_non_whitespace_distinct() {
782        let mut spec = test_spec("worker");
783        spec.tools = Some(vec!["\u{2003}CAFÉ\u{a0}".to_string()]);
784        spec.disallowed_tools = vec![" café ".to_string()];
785        let mut active = ActivePrimaryAgent::from_spec(&spec);
786
787        assert!(primary_agent_allows_tool(&active, " caFÉ "));
788        assert!(!primary_agent_allows_tool(&active, "café"));
789        assert!(!primary_agent_allows_tool(&active, "CAFE"));
790        assert!(!primary_agent_allows_tool(&active, "\u{200b}CAFÉ\u{200b}"));
791
792        active.tools = None;
793        assert!(primary_agent_allows_tool(&active, "CAFÉ"));
794        assert!(!primary_agent_allows_tool(&active, "CaFé"));
795    }
796
797    #[test]
798    fn mixed_case_cleanup_and_tracker_names_bypass_empty_allow_list_and_explicit_denials() {
799        let mut spec = test_spec("restricted");
800        spec.tools = Some(Vec::new());
801        spec.disallowed_tools = vec![
802            " Wait_AGENT ".to_string(),
803            "\u{2003}Close_Agent\u{a0}".to_string(),
804            "\tTask_TRACKER\n".to_string(),
805        ];
806        let active = ActivePrimaryAgent::from_spec(&spec);
807
808        assert!(primary_agent_allows_tool(&active, "\u{a0}WAIT_agent\u{2003}"));
809        assert!(primary_agent_allows_tool(&active, " Close_AGENT "));
810        assert!(primary_agent_allows_tool(&active, " TaSk_TrAcKeR "));
811        assert!(!primary_agent_allows_tool(&active, " Agent "));
812        assert!(!primary_agent_allows_tool(&active, " Spawn_AGENT "));
813        assert!(!primary_agent_allows_tool(&active, "task_tracker_extra"));
814        assert!(!primary_agent_allows_tool(&active, "wait_agent_extra"));
815    }
816
817    #[test]
818    fn filtered_tool_catalog_preserves_surviving_names_and_order() {
819        let mut spec = test_spec("worker");
820        spec.tools = Some(vec![
821            " APPLY_patch ".to_string(),
822            " EXEC_command ".to_string(),
823            " CODE_search ".to_string(),
824        ]);
825        spec.disallowed_tools = vec![" code_SEARCH ".to_string()];
826        let active = ActivePrimaryAgent::from_spec(&spec);
827        let catalog = Arc::new(
828            [
829                "Exec_Command",
830                "code_search",
831                "WaIt_AgEnT",
832                "apply_patch",
833                "TASK_TRACKER",
834                "run_pty_cmd",
835                "agent",
836            ]
837            .into_iter()
838            .map(|name| ToolDefinition::function(name.to_string(), String::new(), json!({"type": "object"})))
839            .collect(),
840        );
841
842        let filtered = apply_primary_agent_tool_policy(Some(Arc::clone(&catalog)), &active).expect("surviving tools");
843
844        assert!(!Arc::ptr_eq(&filtered, &catalog));
845        assert_eq!(
846            filtered.iter().map(ToolDefinition::function_name).collect::<Vec<_>>(),
847            ["Exec_Command", "WaIt_AgEnT", "apply_patch", "TASK_TRACKER"]
848        );
849        assert_eq!(catalog.len(), 7);
850        assert_eq!(catalog[1].function_name(), "code_search");
851    }
852
853    #[test]
854    fn unchanged_tool_catalog_reuses_shared_definitions() {
855        let mut spec = test_spec("worker");
856        spec.tools = None;
857        spec.disallowed_tools.clear();
858        let active = ActivePrimaryAgent::from_spec(&spec);
859        let catalog = Arc::new(vec![ToolDefinition::function(
860            "exec_command".to_string(),
861            "Run a command".to_string(),
862            json!({"type": "object", "properties": {"cmd": {"type": "string"}}}),
863        )]);
864
865        let filtered = apply_primary_agent_tool_policy(Some(Arc::clone(&catalog)), &active).expect("unchanged catalog");
866
867        assert!(Arc::ptr_eq(&filtered, &catalog));
868        assert_eq!(filtered[0].function_name(), "exec_command");
869    }
870
871    #[test]
872    fn tool_policy_returns_none_for_absent_empty_or_fully_denied_catalogs() {
873        let active = ActivePrimaryAgent::from_spec(&test_spec("worker"));
874        assert!(apply_primary_agent_tool_policy(None, &active).is_none());
875        assert!(apply_primary_agent_tool_policy(Some(Arc::new(Vec::new())), &active).is_none());
876        let denied = Arc::new(vec![ToolDefinition::function(
877            "apply_patch".to_string(),
878            String::new(),
879            json!({"type": "object"}),
880        )]);
881        assert!(apply_primary_agent_tool_policy(Some(denied), &active).is_none());
882    }
883
884    #[test]
885    fn empty_present_tool_allow_list_exposes_no_tools() {
886        let mut spec = test_spec("worker");
887        spec.tools = Some(Vec::new());
888        spec.disallowed_tools = Vec::new();
889        let active = ActivePrimaryAgent::from_spec(&spec);
890
891        assert!(!primary_agent_allows_tool(&active, tools::CODE_SEARCH));
892    }
893
894    // NOTE: `spawn_agent`/`wait_agent`/`close_agent`/etc. are legacy granular
895    // subagent-lifecycle tool names. Since wait/close were folded into the
896    // unified `agent` tool (action='wait'/'close'), these granular names are
897    // never actually emitted to the model — the only subagent tool name that
898    // ever reaches `apply_primary_agent_tool_policy`'s runtime filtering is
899    // `tools::AGENT` ("agent"). The assertions below against the granular
900    // names are legacy-taxonomy coverage of the `primary_agent_allows_tool`/
901    // `is_subagent_cleanup_tool` predicates directly (useful if a caller ever
902    // passes a legacy name explicitly), NOT a test of the runtime filtering
903    // path exercised by `apply_primary_agent_tool_policy`. The final
904    // assertion covers that real runtime path: with an allow-list that
905    // excludes "agent", the whole folded tool is filtered out, and there is
906    // currently no way to allow cleanup (wait/close) while denying spawn for
907    // the emitted "agent" tool (see `apply_primary_agent_tool_policy`'s doc
908    // comment for the deferred execution-time action-gating fix).
909    #[test]
910    fn subagent_cleanup_tools_bypass_policy_but_new_work_obeys_policy() {
911        let mut spec = test_spec("restricted");
912        spec.tools = Some(vec!["code_search".to_string()]);
913        spec.disallowed_tools = vec![
914            tools::SPAWN_AGENT.to_string(),
915            tools::WAIT_AGENT.to_string(),
916            tools::CLOSE_AGENT.to_string(),
917            tools::SEND_INPUT.to_string(),
918            tools::RESUME_AGENT.to_string(),
919            tools::SPAWN_BACKGROUND_SUBPROCESS.to_string(),
920        ];
921        let active = ActivePrimaryAgent::from_spec(&spec);
922
923        // Non-cleanup tools respect the policy.
924        assert!(!primary_agent_allows_tool(&active, "command_session"));
925        assert!(!primary_agent_allows_tool(&active, "file_operation"));
926        assert!(!primary_agent_allows_tool(&active, tools::SPAWN_AGENT));
927        assert!(!primary_agent_allows_tool(&active, tools::SPAWN_BACKGROUND_SUBPROCESS));
928        assert!(!primary_agent_allows_tool(&active, tools::SEND_INPUT));
929        assert!(!primary_agent_allows_tool(&active, tools::RESUME_AGENT));
930
931        // Cleanup tools remain available even when listed in disallowed_tools
932        // and absent from the allow list.
933        assert!(primary_agent_allows_tool(&active, tools::WAIT_AGENT));
934        assert!(primary_agent_allows_tool(&active, tools::CLOSE_AGENT));
935
936        // Runtime reality: the allow list excludes "agent" (the only name
937        // ever emitted for subagent tools post-fold), so the whole tool is
938        // filtered out regardless of the cleanup carve-out above.
939        assert!(!primary_agent_allows_tool(&active, tools::AGENT));
940    }
941
942    #[test]
943    fn task_tracker_bypasses_restricted_tool_allow_list_but_mode_tools_obey_it() {
944        // A custom primary with an explicit `tools:` list omitting the
945        // tracker must still expose it, while planning/interview tools stay
946        // author-curated and other tools stay gated.
947        let mut spec = test_spec("restricted");
948        spec.tools = Some(vec![tools::CODE_SEARCH.to_string()]);
949        let active = ActivePrimaryAgent::from_spec(&spec);
950
951        assert!(primary_agent_allows_tool(&active, tools::TASK_TRACKER));
952        assert!(!primary_agent_allows_tool(&active, tools::START_PLANNING));
953        assert!(!primary_agent_allows_tool(&active, tools::APPLY_PATCH));
954    }
955
956    #[test]
957    fn task_tracker_bypass_survives_explicit_disallow_entry() {
958        // Mirrors the cleanup-tool guarantee: even a `disallowed_tools`
959        // entry must not silence progress reporting.
960        let mut spec = test_spec("restricted");
961        spec.tools = Some(vec![tools::CODE_SEARCH.to_string()]);
962        spec.disallowed_tools = vec![tools::TASK_TRACKER.to_string()];
963        let active = ActivePrimaryAgent::from_spec(&spec);
964
965        assert!(primary_agent_allows_tool(&active, tools::TASK_TRACKER));
966        assert!(!primary_agent_allows_tool(&active, tools::APPLY_PATCH));
967    }
968
969    #[test]
970    fn build_primary_agent_runtime_config_preserves_baseline_fields_and_merges_mcp() {
971        let mut parent = VTCodeConfig::default();
972        parent.agent.default_model = "parent-model".to_string();
973        parent.mcp.providers.push(
974            serde_json::from_value(json!({
975                "name": "global",
976                "command": "global-mcp",
977                "args": []
978            }))
979            .expect("global provider"),
980        );
981
982        let mut spec = test_spec("worker");
983        spec.permissions = AgentPermissionsConfig::new(PermissionDefault::Auto);
984        spec.model = Some("agent-model".to_string());
985        spec.reasoning_effort = Some(ReasoningEffortLevel::Low);
986        spec.mcp_servers = vec![SubagentMcpServer::Inline(BTreeMap::from([
987            (
988                "global".to_string(),
989                json!({
990                    "type": "stdio",
991                    "command": "duplicate-mcp"
992                }),
993            ),
994            (
995                "local".to_string(),
996                json!({
997                    "type": "stdio",
998                    "command": "local-mcp"
999                }),
1000            ),
1001        ]))];
1002        let active = ActivePrimaryAgent::from_spec(&spec);
1003
1004        let runtime = build_primary_agent_runtime_config(&parent, &active);
1005
1006        assert_eq!(runtime.agent.default_model, "agent-model");
1007        assert_eq!(runtime.agent.reasoning_effort, ReasoningEffortLevel::Low);
1008        assert_eq!(runtime.mcp.providers.len(), 2);
1009        assert_eq!(runtime.mcp.providers[0].name, "global");
1010        assert_eq!(runtime.mcp.providers[1].name, "local");
1011        let providers = serde_json::to_value(&runtime.mcp.providers).expect("serialize providers");
1012        assert_eq!(providers[0]["command"], "global-mcp");
1013        assert_eq!(providers[1]["command"], "local-mcp");
1014        assert_eq!(providers[1]["args"], json!([]));
1015    }
1016
1017    #[test]
1018    fn build_primary_agent_runtime_config_inherits_parent_model_when_spec_says_inherit() {
1019        let mut parent = VTCodeConfig::default();
1020        parent.agent.default_model = "parent-model".to_string();
1021
1022        let mut spec = test_spec("auto");
1023        spec.model = Some("inherit".to_string());
1024        let active = ActivePrimaryAgent::from_spec(&spec);
1025
1026        let runtime = build_primary_agent_runtime_config(&parent, &active);
1027
1028        assert_eq!(runtime.agent.default_model, "parent-model");
1029    }
1030
1031    #[test]
1032    fn build_primary_agent_runtime_config_inherits_parent_model_when_spec_model_empty() {
1033        let mut parent = VTCodeConfig::default();
1034        parent.agent.default_model = "parent-model".to_string();
1035
1036        let mut spec = test_spec("auto");
1037        spec.model = Some(String::new());
1038        let active = ActivePrimaryAgent::from_spec(&spec);
1039
1040        let runtime = build_primary_agent_runtime_config(&parent, &active);
1041
1042        assert_eq!(runtime.agent.default_model, "parent-model");
1043    }
1044
1045    #[test]
1046    fn built_in_primary_agents_resolve_required_permission_policy() {
1047        let builtins = builtin_subagents();
1048
1049        for name in ["duck", "plan", "build", "auto"] {
1050            let active = resolve_primary_agent(&builtins, name)
1051                .unwrap_or_else(|_| panic!("missing built-in primary agent {name}"));
1052            assert_eq!(active.identity.name, name);
1053            let expected_default = match name {
1054                "build" => PermissionDefault::Ask,
1055                "auto" => PermissionDefault::Auto,
1056                "plan" | "duck" => PermissionDefault::Deny,
1057                _ => unreachable!("unexpected built-in primary agent"),
1058            };
1059            assert_eq!(active.permissions.default, expected_default);
1060        }
1061    }
1062
1063    #[test]
1064    fn active_primary_permissions_overlay_runtime_decisions() {
1065        let builtins = builtin_subagents();
1066        let mut state = ActivePrimaryAgentState::from_specs(&builtins);
1067        let config = VTCodeConfig::default();
1068        let workspace = TempDir::new().expect("workspace");
1069        let current_dir = workspace.path();
1070
1071        state.select_from_specs(&builtins, "auto").expect("auto primary");
1072        let exec = build_permission_request(
1073            workspace.path(),
1074            current_dir,
1075            tools::UNIFIED_EXEC,
1076            Some(&json!({"command": "cargo test"})),
1077        );
1078        assert_eq!(
1079            evaluate_active_primary_agent_permissions(&config, state.active(), workspace.path(), current_dir, &exec,),
1080            ResolvedPermissionDecision::Auto
1081        );
1082
1083        state.select_from_specs(&builtins, "plan").expect("plan primary");
1084        let edit = build_permission_request(
1085            workspace.path(),
1086            current_dir,
1087            tools::UNIFIED_FILE,
1088            Some(&json!({"action": "edit", "path": "src/lib.rs"})),
1089        );
1090        assert_eq!(
1091            evaluate_active_primary_agent_permissions(&config, state.active(), workspace.path(), current_dir, &edit,),
1092            ResolvedPermissionDecision::Deny
1093        );
1094    }
1095
1096    #[test]
1097    fn primary_agent_switching_changes_permission_policy_without_mutating_parent_config() {
1098        let builtins = builtin_subagents();
1099        let mut state = ActivePrimaryAgentState::from_specs(&builtins);
1100        let initial_model = state.active().model.clone();
1101        let initial_tools = state.active().tools.clone();
1102
1103        state.select_from_specs(&builtins, "auto").expect("auto primary");
1104        assert_eq!(state.active().identity.name, "auto");
1105        assert_eq!(state.active().permissions.default, PermissionDefault::Auto);
1106        assert_eq!(state.active().model, initial_model);
1107        assert_eq!(state.active().tools, initial_tools);
1108
1109        state.select_from_specs(&builtins, "duck").expect("duck primary");
1110        assert_eq!(state.active().identity.name, "duck");
1111        assert_eq!(state.active().permissions.default, PermissionDefault::Deny);
1112        assert_eq!(state.active().model, initial_model);
1113        assert_ne!(state.active().tools, initial_tools);
1114    }
1115
1116    #[test]
1117    fn primary_hook_config_merges_supported_main_session_events_after_global_hooks() {
1118        let mut global = HooksConfig::default();
1119        global.lifecycle.user_prompt_submit = vec![hook_group("global-user")];
1120        global.lifecycle.pre_tool_use = vec![hook_group("global-pre")];
1121        global.lifecycle.post_tool_use = vec![hook_group("global-post")];
1122        global.lifecycle.permission_request = vec![hook_group("global-permission")];
1123        global.lifecycle.pre_compact = vec![hook_group("global-compact")];
1124        global.lifecycle.stop = vec![hook_group("global-stop")];
1125        global.lifecycle.notification = vec![hook_group("global-notification")];
1126
1127        let mut primary_hooks = HooksConfig::default();
1128        primary_hooks.lifecycle.user_prompt_submit = vec![hook_group("primary-user")];
1129        primary_hooks.lifecycle.pre_tool_use = vec![hook_group("primary-pre")];
1130        primary_hooks.lifecycle.post_tool_use = vec![hook_group("primary-post")];
1131        primary_hooks.lifecycle.permission_request = vec![hook_group("primary-permission")];
1132        primary_hooks.lifecycle.pre_compact = vec![hook_group("primary-compact")];
1133        primary_hooks.lifecycle.stop = vec![hook_group("primary-stop")];
1134        primary_hooks.lifecycle.notification = vec![hook_group("primary-notification")];
1135
1136        let mut spec = test_spec("worker");
1137        spec.hooks = Some(primary_hooks);
1138        let active = ActivePrimaryAgent::from_spec(&spec);
1139
1140        let merged = build_primary_agent_hook_config(&global, &active);
1141
1142        assert_hook_commands(&merged.lifecycle.user_prompt_submit, &["global-user", "primary-user"]);
1143        assert_hook_commands(&merged.lifecycle.pre_tool_use, &["global-pre", "primary-pre"]);
1144        assert_hook_commands(&merged.lifecycle.post_tool_use, &["global-post", "primary-post"]);
1145        assert_hook_commands(&merged.lifecycle.permission_request, &["global-permission", "primary-permission"]);
1146        assert_hook_commands(&merged.lifecycle.pre_compact, &["global-compact", "primary-compact"]);
1147        assert_hook_commands(&merged.lifecycle.stop, &["global-stop", "primary-stop"]);
1148        assert_hook_commands(&merged.lifecycle.notification, &["global-notification", "primary-notification"]);
1149    }
1150
1151    #[test]
1152    fn primary_hook_config_merges_session_and_subagent_lifecycle_events() {
1153        let global = HooksConfig::default();
1154        let mut primary_hooks = HooksConfig::default();
1155        primary_hooks.lifecycle.session_start = vec![hook_group("primary-session-start")];
1156        primary_hooks.lifecycle.session_end = vec![hook_group("primary-session-end")];
1157        primary_hooks.lifecycle.subagent_start = vec![hook_group("primary-subagent-start")];
1158        primary_hooks.lifecycle.subagent_stop = vec![hook_group("primary-subagent-stop")];
1159        primary_hooks.lifecycle.task_completion = vec![hook_group("primary-task-completion")];
1160        primary_hooks.lifecycle.task_completed = vec![hook_group("primary-task-completed")];
1161
1162        let mut spec = test_spec("worker");
1163        spec.hooks = Some(primary_hooks);
1164        let active = ActivePrimaryAgent::from_spec(&spec);
1165
1166        let merged = build_primary_agent_hook_config(&global, &active);
1167
1168        assert_hook_commands(&merged.lifecycle.session_start, &["primary-session-start"]);
1169        assert_hook_commands(&merged.lifecycle.session_end, &["primary-session-end"]);
1170        assert_hook_commands(&merged.lifecycle.subagent_start, &["primary-subagent-start"]);
1171        assert_hook_commands(&merged.lifecycle.subagent_stop, &["primary-subagent-stop"]);
1172        assert!(merged.lifecycle.task_completion.is_empty());
1173        assert!(merged.lifecycle.task_completed.is_empty());
1174        assert!(merged.lifecycle.stop.is_empty());
1175    }
1176
1177    #[test]
1178    fn primary_hook_config_recomputes_without_previous_primary_leakage() {
1179        let global = HooksConfig::default();
1180        let mut first_hooks = HooksConfig::default();
1181        first_hooks.lifecycle.pre_tool_use = vec![hook_group("first-pre")];
1182        let mut second_hooks = HooksConfig::default();
1183        second_hooks.lifecycle.pre_tool_use = vec![hook_group("second-pre")];
1184
1185        let mut first = test_spec("first");
1186        first.hooks = Some(first_hooks);
1187        let mut second = test_spec("second");
1188        second.hooks = Some(second_hooks);
1189        let specs = vec![first, second];
1190        let mut state = ActivePrimaryAgentState::default();
1191
1192        state.select_from_specs(&specs, "first").expect("selected first");
1193        let first_config = build_primary_agent_hook_config(&global, state.active());
1194        assert_hook_commands(&first_config.lifecycle.pre_tool_use, &["first-pre"]);
1195
1196        state.select_from_specs(&specs, "second").expect("selected second");
1197        let second_config = build_primary_agent_hook_config(&global, state.active());
1198        assert_hook_commands(&second_config.lifecycle.pre_tool_use, &["second-pre"]);
1199    }
1200
1201    #[test]
1202    fn active_primary_state_recomputes_skills_mcp_and_metadata_on_switch() {
1203        let mut first = test_spec("first");
1204        first.description = "First metadata".to_string();
1205        first.color = Some("red".to_string());
1206        first.aliases = vec!["one".to_string()];
1207        first.skills = vec!["rust".to_string()];
1208        first.mcp_servers = vec![SubagentMcpServer::Inline(BTreeMap::from([(
1209            "first-mcp".to_string(),
1210            json!({
1211                "type": "stdio",
1212                "command": "first-mcp"
1213            }),
1214        )]))];
1215        let second = test_spec("second");
1216        let specs = vec![first, second];
1217        let mut state = ActivePrimaryAgentState::default();
1218
1219        state.select_from_specs(&specs, "one").expect("selected first by alias");
1220        assert_eq!(state.active().identity.name, "first");
1221        assert_eq!(state.active().description, "First metadata");
1222        assert_eq!(state.active().color.as_deref(), Some("red"));
1223        assert_eq!(state.active().aliases, vec!["one".to_string()]);
1224        assert_eq!(state.active().skills, vec!["rust".to_string()]);
1225        assert_eq!(state.active().mcp_servers.len(), 1);
1226
1227        state.select_from_specs(&specs, "second").expect("selected second");
1228        assert_eq!(state.active().identity.name, "second");
1229        assert_eq!(state.active().description, "second description");
1230        assert_eq!(state.active().color.as_deref(), Some("blue"));
1231        assert!(state.active().aliases.is_empty());
1232        assert!(state.active().skills.is_empty());
1233        assert!(state.active().mcp_servers.is_empty());
1234    }
1235
1236    fn test_spec(name: &str) -> SubagentSpec {
1237        SubagentSpec {
1238            name: name.to_string(),
1239            description: format!("{name} description"),
1240            prompt: format!("{name} instructions"),
1241            tools: Some(vec!["code_search".to_string()]),
1242            disallowed_tools: vec!["file_operation".to_string()],
1243            model: Some("gpt-5.1".to_string()),
1244            color: Some("blue".to_string()),
1245            reasoning_effort: Some(ReasoningEffortLevel::High),
1246            permissions: AgentPermissionsConfig::new(PermissionDefault::Deny),
1247            skills: Vec::new(),
1248            mcp_servers: Vec::new(),
1249            hooks: None,
1250            background: false,
1251            mode: vtcode_config::AgentMode::Primary,
1252            max_turns: None,
1253            nickname_candidates: Vec::new(),
1254            initial_prompt: None,
1255            memory: None,
1256            isolation: None,
1257            aliases: Vec::new(),
1258            source: SubagentSource::ProjectVtcode,
1259            file_path: None,
1260            warnings: Vec::new(),
1261            tool_policy_overrides: std::collections::BTreeMap::new(),
1262        }
1263    }
1264
1265    fn hook_group(command: &str) -> HookGroupConfig {
1266        HookGroupConfig {
1267            matcher: None,
1268            hooks: vec![HookCommandConfig {
1269                command: command.to_string(),
1270                ..HookCommandConfig::default()
1271            }],
1272        }
1273    }
1274
1275    fn assert_hook_commands(groups: &[HookGroupConfig], expected: &[&str]) {
1276        let commands = groups
1277            .iter()
1278            .flat_map(|group| group.hooks.iter())
1279            .map(|hook| hook.command.as_str())
1280            .collect::<Vec<_>>();
1281        assert_eq!(commands, expected);
1282    }
1283}