Skip to main content

agent_works/
builder.rs

1use std::collections::HashSet;
2use std::path::PathBuf;
3use std::sync::Arc;
4
5use agent_base::{AgentResult, AgentRuntime, Tool};
6
7#[cfg(feature = "multi_agent")]
8use crate::multi_agent::{MultiAgentConfig, MultiAgentRuntime};
9
10#[cfg(feature = "memory")]
11use crate::memory::{MemoryConfig, MemoryStore};
12
13#[cfg(feature = "skill")]
14use crate::skill::{LazySkillPrompter, Skill, SkillPrompter};
15
16/// Read agent instruction files and build a combined prompt section.
17///
18/// Files are read in order; later entries have higher priority and appear
19/// first in the output. Missing files are silently skipped.
20fn build_agent_instructions_prompt(paths: &[PathBuf]) -> Option<String> {
21    let mut sections = Vec::new();
22
23    for path in paths {
24        if let Ok(content) = std::fs::read_to_string(path) {
25            let trimmed = content.trim();
26            if !trimmed.is_empty() {
27                sections.push(trimmed.to_string());
28            }
29        }
30    }
31
32    if sections.is_empty() {
33        return None;
34    }
35
36    // Later entries (higher priority) appear first
37    sections.reverse();
38    Some(sections.join("\n\n---\n\n"))
39}
40
41/// Factory type for creating multi-agent tools from a MultiAgentRuntime.
42#[cfg(feature = "multi_agent")]
43pub type MultiAgentToolFactory =
44    Arc<dyn Fn(Arc<MultiAgentRuntime>) -> Vec<Arc<dyn Tool>> + Send + Sync>;
45
46/// Factory type for creating a skill detail tool from skills and a tool name.
47#[cfg(feature = "skill")]
48pub type SkillDetailToolFactory =
49    Arc<dyn Fn(Vec<Arc<dyn Skill>>, String) -> Arc<dyn Tool> + Send + Sync>;
50
51/// Factory type for creating a list-skills tool from a SkillRegistry.
52#[cfg(feature = "skill")]
53pub type ListSkillsToolFactory =
54    Arc<dyn Fn(Arc<crate::skill::SkillRegistry>) -> Arc<dyn Tool> + Send + Sync>;
55
56pub struct AgentBuilder {
57    inner: agent_base::AgentBuilder,
58    client: Arc<dyn agent_base::llm_trait::LlmProvider>,
59    system_prompt: Option<String>,
60    tool_names: HashSet<String>,
61    /// Business tools to pass to child agents (all registered tools).
62    business_tools: Vec<Arc<dyn Tool>>,
63    /// Multi-agent configuration (None = disabled).
64    #[cfg(feature = "multi_agent")]
65    multi_agent_config: Option<MultiAgentConfig>,
66    /// Factory to create multi-agent tools (injected by phi-kernel-tools).
67    #[cfg(feature = "multi_agent")]
68    multi_agent_tool_factory: Option<MultiAgentToolFactory>,
69    /// Error recovery (stored for multi-agent child inheritance).
70    error_recovery: Option<Arc<dyn agent_base::ToolErrorRecovery>>,
71    /// Language preference.
72    language: Option<agent_base::Language>,
73    #[cfg(feature = "skill")]
74    skills: Vec<Arc<dyn Skill>>,
75    #[cfg(feature = "skill")]
76    skill_prompter: Option<Arc<dyn SkillPrompter>>,
77    #[cfg(feature = "skill")]
78    skill_detail_tool_name: String,
79    /// Optional: inject a custom skill-detail tool (old tool-based mode).
80    /// In default prompt-injection mode, the LLM reads `SKILL.md` via
81    /// `read_file` — no dedicated detail tool is needed.
82    #[cfg(feature = "skill")]
83    skill_detail_tool_factory: Option<SkillDetailToolFactory>,
84    #[cfg(feature = "skill")]
85    list_skills_tool_factory: Option<ListSkillsToolFactory>,
86    #[cfg(feature = "skill")]
87    disable_skill_prompt_injection: bool,
88    /// Optional inline context compactor for the react loop.
89    context_compactor: Option<Arc<dyn agent_base::ContextCompaction>>,
90    /// Paths to agent instruction files (e.g., CLAUDE.md, INSTRUCTIONS.md).
91    /// These files are read at build time and appended to the system prompt.
92    /// Supports multiple paths (user-level + project-level); later entries
93    /// have higher priority and appear first in the prompt.
94    agent_instructions_paths: Vec<PathBuf>,
95    /// Memory configuration (Phase 9b). `None` = memory disabled: no memory
96    /// tools registered, no memory prompt injected (opt-in by design).
97    #[cfg(feature = "memory")]
98    memory_config: Option<MemoryConfig>,
99}
100
101impl AgentBuilder {
102    pub fn new(client: Arc<dyn agent_base::llm_trait::LlmProvider>) -> Self {
103        Self {
104            inner: agent_base::AgentBuilder::new(client.clone()),
105            client,
106            system_prompt: None,
107            tool_names: HashSet::new(),
108            business_tools: Vec::new(),
109            #[cfg(feature = "multi_agent")]
110            multi_agent_config: None,
111            #[cfg(feature = "multi_agent")]
112            multi_agent_tool_factory: None,
113            error_recovery: None,
114            language: None,
115            #[cfg(feature = "skill")]
116            skills: Vec::new(),
117            #[cfg(feature = "skill")]
118            skill_prompter: None,
119            #[cfg(feature = "skill")]
120            skill_detail_tool_name: "get_skill_detail".to_string(),
121            #[cfg(feature = "skill")]
122            skill_detail_tool_factory: None,
123            #[cfg(feature = "skill")]
124            list_skills_tool_factory: None,
125            #[cfg(feature = "skill")]
126            disable_skill_prompt_injection: false,
127            context_compactor: None,
128            agent_instructions_paths: Vec::new(),
129            #[cfg(feature = "memory")]
130            memory_config: None,
131        }
132    }
133
134    /// Enable multi-agent support with the given configuration.
135    ///
136    /// Also sets the tool factory to create the 5 multi-agent tools.
137    /// Callers should use `phi_kernel_tools::multi_agent::create_all_tools` as the factory.
138    #[cfg(feature = "multi_agent")]
139    pub fn with_multi_agent(mut self, config: MultiAgentConfig) -> Self {
140        self.multi_agent_config = Some(config);
141        self
142    }
143
144    /// Disable multi-agent support.
145    ///
146    /// Removes any previously set multi-agent configuration. No multi-agent tools
147    /// will be registered and the system prompt will not mention multi-agent capabilities.
148    #[cfg(feature = "multi_agent")]
149    pub fn without_multi_agent(mut self) -> Self {
150        self.multi_agent_config = None;
151        self.multi_agent_tool_factory = None;
152        self
153    }
154
155    /// Set a custom factory for creating multi-agent tools.
156    ///
157    /// The factory receives the `MultiAgentRuntime` and returns the tools to register.
158    /// If not set but multi-agent is enabled, no tools are registered (caller must
159    /// set this for multi-agent to work).
160    #[cfg(feature = "multi_agent")]
161    pub fn with_multi_agent_tool_factory(mut self, factory: MultiAgentToolFactory) -> Self {
162        self.multi_agent_tool_factory = Some(factory);
163        self
164    }
165
166    /// Set a custom factory for creating the skill detail tool.
167    ///
168    /// The factory receives the skill list and tool name, and returns the tool.
169    /// If not set but skills are registered, no detail tool is added.
170    #[cfg(feature = "skill")]
171    pub fn with_skill_detail_tool_factory(mut self, factory: SkillDetailToolFactory) -> Self {
172        self.skill_detail_tool_factory = Some(factory);
173        self
174    }
175
176    /// Set a custom factory for creating the list-skills tool.
177    ///
178    /// The factory receives the SkillRegistry and returns the tool.
179    #[cfg(feature = "skill")]
180    pub fn with_list_skills_tool_factory(mut self, factory: ListSkillsToolFactory) -> Self {
181        self.list_skills_tool_factory = Some(factory);
182        self
183    }
184
185    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
186        let prompt = prompt.into();
187        self.inner = self.inner.system_prompt(prompt.clone());
188        self.system_prompt = Some(prompt);
189        self
190    }
191
192    pub fn enable_thought(self, enable: bool) -> Self {
193        Self {
194            inner: self.inner.enable_thought(enable),
195            ..self
196        }
197    }
198
199    pub fn reasoning(self, config: agent_base::ReasoningConfig) -> Self {
200        Self {
201            inner: self.inner.reasoning(config),
202            ..self
203        }
204    }
205
206    pub fn enable_thinking(self, enable: bool) -> Self {
207        Self {
208            inner: self.inner.enable_thinking(enable),
209            ..self
210        }
211    }
212
213    pub fn thinking_budget(self, budget: u64) -> Self {
214        Self {
215            inner: self.inner.thinking_budget(budget),
216            ..self
217        }
218    }
219
220    pub fn tool_timeout(self, timeout_ms: u64) -> Self {
221        Self {
222            inner: self.inner.tool_timeout(timeout_ms),
223            ..self
224        }
225    }
226
227    pub fn max_tool_output_chars(self, max_chars: usize) -> Self {
228        Self {
229            inner: self.inner.max_tool_output_chars(max_chars),
230            ..self
231        }
232    }
233
234    pub fn max_sessions(self, max: usize) -> Self {
235        Self {
236            inner: self.inner.max_sessions(max),
237            ..self
238        }
239    }
240
241    pub fn max_turns_per_session(self, max: usize) -> Self {
242        Self {
243            inner: self.inner.max_turns_per_session(max),
244            ..self
245        }
246    }
247
248    pub fn execution_max_turns(self, max: u32) -> Self {
249        Self {
250            inner: self.inner.execution_max_turns(max),
251            ..self
252        }
253    }
254
255    pub fn max_message_tokens(self, max: usize) -> Self {
256        Self {
257            inner: self.inner.max_message_tokens(max),
258            ..self
259        }
260    }
261
262    pub fn register_tool(mut self, tool: impl Tool + 'static) -> Self {
263        let tool_arc: Arc<dyn Tool> = Arc::new(tool);
264        self.tool_names.insert(tool_arc.name().to_string());
265        self.business_tools.push(tool_arc.clone());
266        self.inner = self.inner.register_tool_arc(tool_arc);
267        self
268    }
269
270    pub fn register_tool_arc(mut self, tool: Arc<dyn Tool>) -> Self {
271        self.tool_names.insert(tool.name().to_string());
272        self.business_tools.push(tool.clone());
273        self.inner = self.inner.register_tool_arc(tool);
274        self
275    }
276
277    pub fn approval_handler(self, handler: Arc<dyn agent_base::ApprovalHandler>) -> Self {
278        Self {
279            inner: self.inner.approval_handler(handler),
280            ..self
281        }
282    }
283
284    pub fn tool_policy(self, policy: Arc<dyn agent_base::ToolPolicy>) -> Self {
285        Self {
286            inner: self.inner.tool_policy(policy),
287            ..self
288        }
289    }
290
291    pub fn middleware(self, mw: impl agent_base::Middleware + 'static) -> Self {
292        Self {
293            inner: self.inner.middleware(mw),
294            ..self
295        }
296    }
297
298    pub fn guard(self, guard: impl agent_base::ReactLoopGuard + 'static) -> Self {
299        Self {
300            inner: self.inner.guard(guard),
301            ..self
302        }
303    }
304
305    /// Mount this runtime's action backend (M3 T10c): text turns route to it,
306    /// tool-envelope turns keep the tool-call backend. One backend per
307    /// runtime — build one runtime per session when the backend holds a
308    /// resident engine (the product's assembly-time choice).
309    pub fn action_backend(self, backend: Box<dyn agent_base::ActionBackend>) -> Self {
310        Self {
311            inner: self.inner.action_backend(backend),
312            ..self
313        }
314    }
315
316    /// The product's interaction surface for the action backend's `ExecCtx`
317    /// (OV-6): consent and ask_user suspend through it. Without one, every
318    /// interaction fails closed — a cell reaching for the human refuses, it
319    /// never hangs or silently allows.
320    pub fn interaction(self, channel: Arc<dyn agent_base::InteractionChannel>) -> Self {
321        Self {
322            inner: self.inner.interaction(channel),
323            ..self
324        }
325    }
326
327    /// Per-interaction deadline for the action backend's suspensions (`None`
328    /// = unbounded human time, the run's cancel token is the only guard).
329    /// Unset = the kernel's default watchdog.
330    pub fn interaction_timeout(self, interact_timeout: Option<std::time::Duration>) -> Self {
331        Self {
332            inner: self.inner.interaction_timeout(interact_timeout),
333            ..self
334        }
335    }
336
337    pub fn context_window(self, max_tokens: usize) -> Self {
338        Self {
339            inner: self.inner.context_window(max_tokens),
340            ..self
341        }
342    }
343
344    pub fn context_window_manager(self, manager: agent_base::ContextWindowManager) -> Self {
345        Self {
346            inner: self.inner.context_window_manager(manager),
347            ..self
348        }
349    }
350
351    pub fn response_format(self, format: agent_base::ResponseFormat) -> Self {
352        Self {
353            inner: self.inner.response_format(format),
354            ..self
355        }
356    }
357
358    pub fn llm_retry(self, retry: agent_base::RetryConfig) -> Self {
359        Self {
360            inner: self.inner.llm_retry(retry),
361            ..self
362        }
363    }
364
365    pub fn session_store(self, store: Arc<dyn agent_base::SessionStore>) -> Self {
366        Self {
367            inner: self.inner.session_store(store),
368            ..self
369        }
370    }
371
372    pub fn error_recovery(mut self, recovery: Arc<dyn agent_base::ToolErrorRecovery>) -> Self {
373        self.error_recovery = Some(recovery.clone());
374        self.inner = self.inner.error_recovery(recovery);
375        self
376    }
377
378    pub fn tool_error_retry_prompt(self, prompt: impl Into<String>) -> Self {
379        Self {
380            inner: self.inner.tool_error_retry_prompt(prompt),
381            ..self
382        }
383    }
384
385    pub fn language(mut self, language: agent_base::Language) -> Self {
386        self.language = Some(language.clone());
387        self.inner = self.inner.language(language);
388        self
389    }
390
391    /// Set an inline context compactor for the react loop.
392    ///
393    /// When set, the react loop will check token count after each tool turn
394    /// and compact the session if it exceeds the configured threshold.
395    pub fn context_compactor(mut self, compactor: Arc<dyn agent_base::ContextCompaction>) -> Self {
396        self.context_compactor = Some(compactor);
397        self
398    }
399
400    pub fn event_bus_capacity(self, capacity: usize) -> Self {
401        Self {
402            inner: self.inner.event_bus_capacity(capacity),
403            ..self
404        }
405    }
406
407    pub fn session_id_generator(
408        self,
409        generator: Arc<dyn agent_base::types::SessionIdGenerator>,
410    ) -> Self {
411        Self {
412            inner: self.inner.session_id_generator(generator),
413            ..self
414        }
415    }
416
417    /// Conditionally apply a transformation when `value` is `Some`.
418    ///
419    /// This is a convenience for option-chaining builder patterns:
420    ///
421    /// ```ignore
422    /// builder.apply_if(args.thinking_budget, |b, budget| b.thinking_budget(budget))
423    /// ```
424    pub fn apply_if<T>(self, value: Option<T>, f: impl FnOnce(Self, T) -> Self) -> Self {
425        match value {
426            Some(v) => f(self, v),
427            None => self,
428        }
429    }
430
431    #[cfg(feature = "skill")]
432    pub fn register_skill(mut self, skill: impl Skill + 'static) -> Self {
433        self.skills.push(Arc::new(skill));
434        self
435    }
436
437    #[cfg(feature = "skill")]
438    pub fn register_skills(mut self, skills: Vec<Arc<dyn Skill>>) -> Self {
439        self.skills.extend(skills);
440        self
441    }
442
443    #[cfg(feature = "skill")]
444    pub fn skill_prompter(mut self, prompter: Arc<dyn SkillPrompter>) -> Self {
445        self.skill_prompter = Some(prompter);
446        self
447    }
448
449    #[cfg(feature = "skill")]
450    pub fn disable_skill_prompt_injection(mut self) -> Self {
451        self.disable_skill_prompt_injection = true;
452        self
453    }
454
455    /// Set paths to agent instruction files (e.g., CLAUDE.md, INSTRUCTIONS.md).
456    ///
457    /// These files are read at build time and appended to the system prompt.
458    /// Supports multiple paths (user-level + project-level); later entries
459    /// have higher priority and appear first in the prompt.
460    ///
461    /// Example:
462    /// ```rust,ignore
463    /// use std::path::PathBuf;
464    /// use agent_works::AgentBuilder;
465    /// let builder = AgentBuilder::new();
466    /// let builder = builder.agent_instructions_paths(vec![
467    ///     PathBuf::from("~/.claude/CLAUDE.md"),  // user-level
468    ///     PathBuf::from(".claude/CLAUDE.md"),     // project-level
469    /// ]);
470    /// ```
471    pub fn agent_instructions_paths(mut self, paths: Vec<PathBuf>) -> Self {
472        self.agent_instructions_paths = paths;
473        self
474    }
475
476    #[cfg(feature = "skill")]
477    pub fn skill_detail_tool_name(mut self, name: impl Into<String>) -> Self {
478        self.skill_detail_tool_name = name.into();
479        self
480    }
481
482    /// Enable persistent auto-memory (Phase 9b) with the given configuration.
483    ///
484    /// Registers the four `memory_*` tools and appends the memory prompt
485    /// (MEMORY.md index snapshot + tool guidance) to the system prompt at
486    /// build time. Opt-in: without this call no memory tools exist and the
487    /// prompt is untouched.
488    #[cfg(feature = "memory")]
489    pub fn memory_config(mut self, config: MemoryConfig) -> Self {
490        self.memory_config = Some(config);
491        self
492    }
493
494    /// Disable auto-memory (removes any previously set configuration).
495    #[cfg(feature = "memory")]
496    pub fn without_memory_config(mut self) -> Self {
497        self.memory_config = None;
498        self
499    }
500
501    /// Register the four memory tools and append the memory prompt (index
502    /// snapshot + tool guidance) to the system prompt. No-op when no memory
503    /// configuration was set. Called from every `build_*` path right after
504    /// the agent-instructions (CLAUDE.md) injection.
505    #[cfg(feature = "memory")]
506    fn apply_memory_config(mut self) -> Self {
507        let Some(config) = self.memory_config.take() else {
508            return self;
509        };
510
511        let store = Arc::new(MemoryStore::new(
512            config.memory_root.clone(),
513            config.index_filename.clone(),
514        ));
515
516        // Register the memory tools unless the consumer already took the name.
517        for tool in crate::tools::create_memory_tools(Arc::clone(&store)) {
518            let tool_name = tool.name().to_string();
519            if self.tool_names.contains(&tool_name) {
520                tracing::warn!(tool = %tool_name, "memory tool name conflict; skipping registration");
521                continue;
522            }
523            self.tool_names.insert(tool_name);
524            self.inner = self.inner.register_tool_arc(tool);
525        }
526
527        // Inject the index snapshot + tool guidance into the system prompt.
528        let index = store.read_index();
529        if index.len() > 10_240 {
530            tracing::warn!(
531                index_bytes = index.len(),
532                root = %config.memory_root.display(),
533                "memory index is unusually large (>10KB); consider cleaning up stale memories"
534            );
535        }
536        let mem_prompt = build_memory_system_prompt_with_config(&config, &index);
537        tracing::info!(
538            memory_root = %config.memory_root.display(),
539            index_bytes = index.len(),
540            tools = 4,
541            "injecting memory prompt + tools into system prompt"
542        );
543        let new_prompt = match self.system_prompt.take() {
544            Some(existing) => format!("{existing}\n\n---\n\n{mem_prompt}"),
545            None => mem_prompt,
546        };
547        tracing::info!(
548            prompt_len = new_prompt.len(),
549            "system prompt after memory injection (full text logged at DEBUG level)"
550        );
551        tracing::debug!(system_prompt = %new_prompt, "full system prompt after memory injection");
552        self.system_prompt = Some(new_prompt.clone());
553        self.inner = self.inner.system_prompt(new_prompt);
554        self
555    }
556
557    // ── Build ──
558
559    pub fn build(self) -> AgentResult<AgentRuntime> {
560        #[cfg(feature = "skill")]
561        {
562            self.build_with_skills()
563        }
564        #[cfg(not(feature = "skill"))]
565        {
566            self.build_inner()
567        }
568    }
569
570    /// Build the runtime and return the multi-agent runtime (if enabled).
571    ///
572    /// Same as [`build`](Self::build) but also returns the `MultiAgentRuntime`
573    /// created during setup. Callers that need to start the watcher task or
574    /// access the mailbox should use this method.
575    #[cfg(feature = "multi_agent")]
576    pub fn build_with_ma(self) -> AgentResult<(AgentRuntime, Option<Arc<MultiAgentRuntime>>)> {
577        #[cfg(feature = "skill")]
578        {
579            self.build_with_skills_ma()
580        }
581        #[cfg(not(feature = "skill"))]
582        {
583            self.build_inner_ma()
584        }
585    }
586
587    #[allow(dead_code, unused_mut)]
588    fn build_inner(mut self) -> AgentResult<AgentRuntime> {
589        // Inject default guard if none was set by the consumer.
590        // Uses the same LLM client for the judge (enabled by default).
591        if self.inner.get_guard().is_none() {
592            self.inner = self
593                .inner
594                .guard(crate::guard::DefaultGuard::with_llm_client(
595                    crate::guard::DefaultGuardConfig::default(),
596                    self.client.clone(),
597                ));
598        }
599
600        // Inject agent instruction files (e.g., CLAUDE.md) into system prompt
601        if !self.agent_instructions_paths.is_empty()
602            && let Some(instructions) =
603                build_agent_instructions_prompt(&self.agent_instructions_paths)
604        {
605            tracing::info!(
606                paths = ?self.agent_instructions_paths,
607                instructions_len = instructions.len(),
608                "injecting agent instructions into system prompt"
609            );
610            let new_prompt = match self.system_prompt.take() {
611                Some(existing) => format!("{}\n\n---\n\n{}", existing, instructions),
612                None => instructions,
613            };
614            self.system_prompt = Some(new_prompt.clone());
615            self.inner = self.inner.system_prompt(new_prompt);
616        }
617
618        // Register memory tools + inject memory prompt (Phase 9b)
619        #[cfg(feature = "memory")]
620        {
621            self = self.apply_memory_config();
622        }
623
624        #[cfg(feature = "multi_agent")]
625        let lang = self.language.clone().unwrap_or_default();
626        #[cfg(feature = "multi_agent")]
627        let business_tools = std::mem::take(&mut self.business_tools);
628        #[cfg(feature = "multi_agent")]
629        let error_recovery = self.error_recovery.clone();
630        #[cfg(feature = "multi_agent")]
631        let tool_names = self.tool_names.clone();
632
633        #[cfg(feature = "multi_agent")]
634        let ma_config = self.multi_agent_config.clone();
635        #[cfg(feature = "multi_agent")]
636        let ma_tool_factory = self.multi_agent_tool_factory.take();
637
638        // Inject multi-agent prompt before build
639        #[cfg(feature = "multi_agent")]
640        if ma_config.as_ref().map(|c| c.enabled).unwrap_or(false) {
641            let ma_prompt = build_multi_agent_system_prompt();
642            let new_prompt = match self.system_prompt.take() {
643                Some(existing) => format!("{}\n\n---\n\n{}", existing, ma_prompt),
644                None => ma_prompt,
645            };
646            self.inner = self.inner.system_prompt(new_prompt);
647        }
648
649        // Inject inline context compactor if set
650        if let Some(compactor) = self.context_compactor.take() {
651            self.inner = self.inner.context_compactor(compactor);
652        }
653
654        let runtime = self.inner.build()?;
655
656        // Post-build: register multi-agent tools if enabled and factory is set
657        #[cfg(feature = "multi_agent")]
658        if let Some(config) = ma_config
659            && config.enabled
660        {
661            setup_multi_agent(
662                &runtime,
663                config,
664                lang,
665                business_tools,
666                error_recovery,
667                &tool_names,
668                ma_tool_factory,
669            )?;
670        }
671
672        Ok(runtime)
673    }
674
675    /// Like `build_inner` but also returns the `MultiAgentRuntime`.
676    #[cfg(feature = "multi_agent")]
677    #[allow(dead_code, unused_mut)]
678    fn build_inner_ma(mut self) -> AgentResult<(AgentRuntime, Option<Arc<MultiAgentRuntime>>)> {
679        if self.inner.get_guard().is_none() {
680            self.inner = self
681                .inner
682                .guard(crate::guard::DefaultGuard::with_llm_client(
683                    crate::guard::DefaultGuardConfig::default(),
684                    self.client.clone(),
685                ));
686        }
687
688        // Register memory tools + inject memory prompt (Phase 9b)
689        #[cfg(feature = "memory")]
690        {
691            self = self.apply_memory_config();
692        }
693
694        let lang = self.language.clone().unwrap_or_default();
695        let business_tools = std::mem::take(&mut self.business_tools);
696        let error_recovery = self.error_recovery.clone();
697        let tool_names = self.tool_names.clone();
698        let ma_config = self.multi_agent_config.clone();
699        let ma_tool_factory = self.multi_agent_tool_factory.take();
700
701        if ma_config.as_ref().map(|c| c.enabled).unwrap_or(false) {
702            let ma_prompt = build_multi_agent_system_prompt();
703            let new_prompt = match self.system_prompt.take() {
704                Some(existing) => format!("{}\n\n---\n\n{}", existing, ma_prompt),
705                None => ma_prompt,
706            };
707            self.inner = self.inner.system_prompt(new_prompt);
708        }
709
710        if let Some(compactor) = self.context_compactor.take() {
711            self.inner = self.inner.context_compactor(compactor);
712        }
713
714        let runtime = self.inner.build()?;
715
716        let ma_runtime_out = if let Some(config) = ma_config
717            && config.enabled
718        {
719            Some(setup_multi_agent(
720                &runtime,
721                config,
722                lang,
723                business_tools,
724                error_recovery,
725                &tool_names,
726                ma_tool_factory,
727            )?)
728        } else {
729            None
730        };
731
732        Ok((runtime, ma_runtime_out))
733    }
734
735    /// Build the runtime with skill support.
736    ///
737    /// # Runtime requirement
738    ///
739    /// This method uses [`tokio::task::block_in_place`] to populate the skill
740    /// registry from a synchronous context. It **requires** a multi-threaded
741    /// tokio runtime. Calling it on a `#[tokio::main]` single-threaded
742    /// (`current_thread`) runtime will panic.
743    ///
744    /// The phi-agent CLI and all examples use the default multi-threaded runtime,
745    /// so this is safe in practice.
746    #[cfg(feature = "skill")]
747    fn build_with_skills(mut self) -> AgentResult<AgentRuntime> {
748        // Inject default guard if none was set by the consumer.
749        // Uses the same LLM client for the judge (enabled by default).
750        if self.inner.get_guard().is_none() {
751            self.inner = self
752                .inner
753                .guard(crate::guard::DefaultGuard::with_llm_client(
754                    crate::guard::DefaultGuardConfig::default(),
755                    self.client.clone(),
756                ));
757        }
758
759        // Inject agent instruction files (e.g., CLAUDE.md) into system prompt
760        if !self.agent_instructions_paths.is_empty()
761            && let Some(instructions) =
762                build_agent_instructions_prompt(&self.agent_instructions_paths)
763        {
764            tracing::info!(
765                paths = ?self.agent_instructions_paths,
766                instructions_len = instructions.len(),
767                "injecting agent instructions into system prompt"
768            );
769            let new_prompt = match self.system_prompt.take() {
770                Some(existing) => format!("{}\n\n---\n\n{}", existing, instructions),
771                None => instructions,
772            };
773            self.system_prompt = Some(new_prompt.clone());
774            self.inner = self.inner.system_prompt(new_prompt);
775        }
776
777        // Register memory tools + inject memory prompt (Phase 9b)
778        #[cfg(feature = "memory")]
779        {
780            self = self.apply_memory_config();
781        }
782
783        let mut ab = self.inner;
784        #[cfg(feature = "multi_agent")]
785        let lang = self.language.clone().unwrap_or_default();
786        #[cfg(feature = "multi_agent")]
787        let business_tools = std::mem::take(&mut self.business_tools);
788        #[cfg(feature = "multi_agent")]
789        let error_recovery = self.error_recovery.clone();
790        #[cfg(feature = "multi_agent")]
791        let tool_names = self.tool_names.clone();
792
793        #[cfg(feature = "multi_agent")]
794        let ma_config = self.multi_agent_config.clone();
795        #[cfg(feature = "multi_agent")]
796        let ma_tool_factory = self.multi_agent_tool_factory.take();
797
798        // Process skills
799        if !self.skills.is_empty() {
800            let prompter: Arc<dyn SkillPrompter> = self
801                .skill_prompter
802                .take()
803                .unwrap_or_else(|| Arc::new(LazySkillPrompter::new()));
804
805            let mut skill_refs: Vec<Arc<dyn Skill>> = Vec::new();
806
807            for skill in self.skills {
808                for tool in skill.tools() {
809                    let tool_name = tool.name().to_string();
810                    if self.tool_names.contains(&tool_name) {
811                        return Err(agent_base::AgentError::internal(format!(
812                            "Tool name conflict: `{}` (Skill `{}`)",
813                            tool_name,
814                            skill.name()
815                        )));
816                    }
817                    self.tool_names.insert(tool_name);
818                    ab = ab.register_tool_arc(tool);
819                }
820                skill_refs.push(skill);
821            }
822
823            if !self.disable_skill_prompt_injection {
824                let skill_prompt = prompter.build_prompt(&skill_refs, &self.skill_detail_tool_name);
825                if !skill_prompt.is_empty() {
826                    let new_prompt = match self.system_prompt.take() {
827                        Some(existing) => format!("{}\n\n---\n\n{}", existing, skill_prompt),
828                        None => skill_prompt,
829                    };
830                    self.system_prompt = Some(new_prompt.clone());
831                    ab = ab.system_prompt(new_prompt);
832                }
833            }
834
835            // Use injected factory if available, otherwise skip — prompt-injection
836            // mode uses read_file instead of a dedicated detail tool.
837            if let Some(factory) = self.skill_detail_tool_factory.take() {
838                let detail_tool = factory(skill_refs.clone(), self.skill_detail_tool_name);
839                ab = ab.register_tool_arc(detail_tool);
840            }
841
842            // Create SkillRegistry and populate it for the list-skills tool
843            if let Some(factory) = self.list_skills_tool_factory.take() {
844                let registry = Arc::new(crate::skill::SkillRegistry::new());
845                for skill in &skill_refs {
846                    tokio::task::block_in_place(|| {
847                        tokio::runtime::Handle::current().block_on(async {
848                            registry.register(skill.clone()).await;
849                        })
850                    });
851                }
852                let list_tool = factory(registry);
853                ab = ab.register_tool_arc(list_tool);
854            }
855        }
856
857        // Inject multi-agent prompt
858        #[cfg(feature = "multi_agent")]
859        if ma_config.as_ref().map(|c| c.enabled).unwrap_or(false) {
860            let ma_prompt = build_multi_agent_system_prompt();
861            let new_prompt = match self.system_prompt.take() {
862                Some(existing) => format!("{}\n\n---\n\n{}", existing, ma_prompt),
863                None => ma_prompt,
864            };
865            ab = ab.system_prompt(new_prompt);
866        }
867
868        // Inject inline context compactor if set
869        if let Some(compactor) = self.context_compactor.take() {
870            ab = ab.context_compactor(compactor);
871        }
872
873        let runtime = ab.build()?;
874
875        // Post-build: register multi-agent tools
876        #[cfg(feature = "multi_agent")]
877        if let Some(config) = ma_config
878            && config.enabled
879        {
880            setup_multi_agent(
881                &runtime,
882                config,
883                lang,
884                business_tools,
885                error_recovery,
886                &tool_names,
887                ma_tool_factory,
888            )?;
889        }
890
891        Ok(runtime)
892    }
893
894    /// Like `build_with_skills` but also returns the `MultiAgentRuntime`.
895    #[cfg(all(feature = "skill", feature = "multi_agent"))]
896    fn build_with_skills_ma(
897        mut self,
898    ) -> AgentResult<(AgentRuntime, Option<Arc<MultiAgentRuntime>>)> {
899        if self.inner.get_guard().is_none() {
900            self.inner = self
901                .inner
902                .guard(crate::guard::DefaultGuard::with_llm_client(
903                    crate::guard::DefaultGuardConfig::default(),
904                    self.client.clone(),
905                ));
906        }
907
908        // Inject agent instruction files (e.g., CLAUDE.md) into system prompt
909        if !self.agent_instructions_paths.is_empty()
910            && let Some(instructions) =
911                build_agent_instructions_prompt(&self.agent_instructions_paths)
912        {
913            tracing::info!(
914                paths = ?self.agent_instructions_paths,
915                instructions_len = instructions.len(),
916                "injecting agent instructions into system prompt"
917            );
918            let new_prompt = match self.system_prompt.take() {
919                Some(existing) => format!("{}\n\n---\n\n{}", existing, instructions),
920                None => instructions,
921            };
922            self.system_prompt = Some(new_prompt.clone());
923            self.inner = self.inner.system_prompt(new_prompt);
924        }
925
926        // Register memory tools + inject memory prompt (Phase 9b)
927        #[cfg(feature = "memory")]
928        {
929            self = self.apply_memory_config();
930        }
931
932        let mut ab = self.inner;
933        let lang = self.language.clone().unwrap_or_default();
934        let business_tools = std::mem::take(&mut self.business_tools);
935        let error_recovery = self.error_recovery.clone();
936        let tool_names = self.tool_names.clone();
937        let ma_config = self.multi_agent_config.clone();
938        let ma_tool_factory = self.multi_agent_tool_factory.take();
939
940        // Process skills
941        if !self.skills.is_empty() {
942            let prompter: Arc<dyn SkillPrompter> = self
943                .skill_prompter
944                .take()
945                .unwrap_or_else(|| Arc::new(LazySkillPrompter::new()));
946
947            let mut skill_refs: Vec<Arc<dyn Skill>> = Vec::new();
948
949            for skill in self.skills {
950                for tool in skill.tools() {
951                    let tool_name = tool.name().to_string();
952                    if self.tool_names.contains(&tool_name) {
953                        return Err(agent_base::AgentError::internal(format!(
954                            "Tool name conflict: `{}` (Skill `{}`)",
955                            tool_name,
956                            skill.name()
957                        )));
958                    }
959                    self.tool_names.insert(tool_name);
960                    ab = ab.register_tool_arc(tool);
961                }
962                skill_refs.push(skill);
963            }
964
965            if !self.disable_skill_prompt_injection {
966                let skill_prompt = prompter.build_prompt(&skill_refs, &self.skill_detail_tool_name);
967                if !skill_prompt.is_empty() {
968                    let new_prompt = match self.system_prompt.take() {
969                        Some(existing) => format!("{}\n\n---\n\n{}", existing, skill_prompt),
970                        None => skill_prompt,
971                    };
972                    self.system_prompt = Some(new_prompt.clone());
973                    ab = ab.system_prompt(new_prompt);
974                }
975            }
976
977            if let Some(factory) = self.skill_detail_tool_factory.take() {
978                let detail_tool = factory(skill_refs.clone(), self.skill_detail_tool_name);
979                ab = ab.register_tool_arc(detail_tool);
980            }
981
982            if let Some(factory) = self.list_skills_tool_factory.take() {
983                let registry = Arc::new(crate::skill::SkillRegistry::new());
984                for skill in &skill_refs {
985                    tokio::task::block_in_place(|| {
986                        tokio::runtime::Handle::current().block_on(async {
987                            registry.register(skill.clone()).await;
988                        })
989                    });
990                }
991                let list_tool = factory(registry);
992                ab = ab.register_tool_arc(list_tool);
993            }
994        }
995
996        // Inject multi-agent prompt
997        if ma_config.as_ref().map(|c| c.enabled).unwrap_or(false) {
998            let ma_prompt = build_multi_agent_system_prompt();
999            let new_prompt = match self.system_prompt.take() {
1000                Some(existing) => format!("{}\n\n---\n\n{}", existing, ma_prompt),
1001                None => ma_prompt,
1002            };
1003            ab = ab.system_prompt(new_prompt);
1004        }
1005
1006        if let Some(compactor) = self.context_compactor.take() {
1007            ab = ab.context_compactor(compactor);
1008        }
1009
1010        let runtime = ab.build()?;
1011
1012        let ma_runtime_out = if let Some(config) = ma_config
1013            && config.enabled
1014        {
1015            Some(setup_multi_agent(
1016                &runtime,
1017                config,
1018                lang,
1019                business_tools,
1020                error_recovery,
1021                &tool_names,
1022                ma_tool_factory,
1023            )?)
1024        } else {
1025            None
1026        };
1027
1028        Ok((runtime, ma_runtime_out))
1029    }
1030}
1031
1032/// Set up the MultiAgentRuntime, event bridge, and register tools on an already-built runtime.
1033///
1034/// # Safety / Runtime Requirement
1035///
1036/// This function uses [`tokio::task::block_in_place`] to register tools synchronously.
1037/// It **requires** a multi-threaded tokio runtime. Calling it on a
1038/// `#[tokio::main]` single-threaded (`current_thread`) runtime will panic.
1039///
1040/// The phi-agent CLI and all examples use the default multi-threaded runtime,
1041/// so this is safe in practice.
1042#[cfg(feature = "multi_agent")]
1043pub fn setup_multi_agent(
1044    runtime: &AgentRuntime,
1045    config: MultiAgentConfig,
1046    lang: agent_base::Language,
1047    business_tools: Vec<Arc<dyn Tool>>,
1048    error_recovery: Option<Arc<dyn agent_base::ToolErrorRecovery>>,
1049    existing_tool_names: &HashSet<String>,
1050    tool_factory: Option<MultiAgentToolFactory>,
1051) -> AgentResult<Arc<MultiAgentRuntime>> {
1052    let client = runtime.provider();
1053    let cancel_token = runtime.cancel_token();
1054    let tool_policy = runtime.tool_policy().cloned();
1055    let approval_handler = runtime.approval_handler().cloned();
1056
1057    let ma_runtime = Arc::new(MultiAgentRuntime::new(
1058        config.clone(),
1059        client,
1060        business_tools,
1061        cancel_token,
1062        error_recovery,
1063        lang,
1064        tool_policy,
1065        approval_handler,
1066    ));
1067
1068    // Set parent session manager for fork_history support
1069    ma_runtime.set_session_manager(Arc::new(runtime.session_manager().clone()));
1070
1071    // Set up event bridge: child events → parent event bus
1072    let (event_tx, mut event_rx) =
1073        tokio::sync::mpsc::unbounded_channel::<agent_base::RuntimeEvent>();
1074    ma_runtime.set_event_sender(event_tx);
1075    let parent_runtime = runtime.clone();
1076    tokio::spawn(async move {
1077        while let Some(event) = event_rx.recv().await {
1078            parent_runtime.emit_event(event);
1079        }
1080    });
1081
1082    // Register multi-agent tools if a factory is provided
1083    if let Some(factory) = tool_factory {
1084        let tools = factory(ma_runtime.clone());
1085        let registry = runtime.tools_mut();
1086        let mut reg = tokio::task::block_in_place(|| registry.blocking_write());
1087        for tool in tools {
1088            let tool_name = tool.name().to_string();
1089            if !existing_tool_names.contains(&tool_name) {
1090                reg.register_arc(tool);
1091            }
1092        }
1093        drop(reg);
1094    }
1095
1096    Ok(ma_runtime)
1097}
1098
1099/// Build the multi-agent system prompt guidance for the main agent.
1100#[cfg(feature = "multi_agent")]
1101pub fn build_multi_agent_system_prompt() -> String {
1102    r#"## Multi-Agent Capabilities
1103
1104You can spawn sub-agents to work on tasks concurrently. Each sub-agent is an independent assistant with its own tools (repo_map, read_file, list_files, execute_command, etc.) and can reason through problems autonomously.
1105
1106### Tools
1107
1108- `spawn_agent`: Create a sub-agent. Use the `task` field to describe what you want done — the sub-agent will figure out the steps. Example: `spawn_agent({task_name: "analyze-codex", task: "analyze the codex project structure and output a structured report"})`.
1109- `send_message`: Send follow-up context or tasks to a sub-agent (`trigger: true` starts execution).
1110- `list_agents`: List active sub-agents with their assigned task and status — use it to answer "what is agent X doing?".
1111- `close_agent`: Close a sub-agent when done.
1112
1113### How Results Reach You
1114
1115Sub-agent results are **pushed into your context automatically** when they complete — there is no wait tool. To wait, simply end your turn: you will be woken with the result as a new message. Keep working on other things instead of polling.
1116
1117### How Sub-Agents Work
1118
1119Sub-agents are capable — they can explore codebases, read files, run commands, and produce structured analysis. You don't need to plan their steps or specify which tools to use. Just describe the goal in `task`, and the sub-agent handles the rest.
1120
1121### When to Spawn
1122
1123- Parallel tasks: analyze multiple codebases, compare implementations, etc.
1124- Tasks you want to delegate while you continue other work
1125
1126### When NOT to Spawn
1127
1128- Simple lookups (just use read_file or repo_map directly)
1129- Tasks that need your current conversation context"#
1130        .to_string()
1131}
1132
1133/// Build the memory system prompt guidance.
1134///
1135/// Tells the LLM how to use the file-based persistent memory system.
1136/// Memory is stored as markdown files — the LLM uses `read_file` / `write_file`
1137/// to manage them, following the same convention as Claude Code Memory.
1138///
1139/// This is prompt-injection only — no dedicated memory tools are registered.
1140/// The LLM uses the general-purpose file tools to read/write memory files.
1141pub fn build_memory_system_prompt() -> String {
1142    r#"## Memory
1143
1144You have a persistent file-based memory at `.phi/memory/`. Use `read_file` and `write_file` to manage it — there are no dedicated memory tools.
1145
1146### How Memory Works
1147
1148- `MEMORY.md` is the index — it lists all memories with one-line descriptions. Read it first when you need to recall something.
1149- Each memory is a separate `.md` file with YAML frontmatter:
1150  ```yaml
1151  ---
1152  name: <short-kebab-case-slug>
1153  description: <one-line summary — used to decide relevance during recall>
1154  metadata:
1155    node_type: memory
1156    type: user | feedback | project | reference
1157  ---
1158
1159  <the fact or instruction>
1160  ```
1161- The `description` field is the key for recall — write it so you can tell at a glance whether this memory is relevant to the current task.
1162- Link related memories with `[[memory-name]]` in the body.
1163- `user` type = who the user is (role, expertise, preferences).
1164- `feedback` type = guidance the user has given on how you should work.
1165- `project` type = ongoing work, goals, or constraints.
1166- `reference` type = pointers to external resources (URLs, dashboards, tickets).
1167
1168### When to Use Memory
1169
1170- The user explicitly asks you to remember something ("remember this", "save that")
1171- You learn something important about the user's preferences or workflow
1172- After completing a significant task, save context that would help in future sessions
1173- The user gives you feedback on how to work — save it as `feedback` type
1174
1175### When NOT to Use Memory
1176
1177- For transient information that won't be useful beyond this session
1178- For facts already recorded in the codebase (code structure, git history, config files)
1179- For items that only matter to the current conversation
1180
1181### Pro Tips
1182
1183- When creating your first memory of a new type, you can read template files for format reference (check `.phi/templates/memory/` if available).
1184- Keep the MEMORY.md index concise — it's loaded into context every session.
1185- Before writing a new memory, check if an existing file already covers it — update instead of duplicating.
1186
1187### Workflow
1188
1189**To recall:** read `MEMORY.md` → find relevant entries by description → read the specific `.md` files you need.
1190**To remember:** create a new `.md` file with proper frontmatter → update `MEMORY.md` with a new entry.
1191**To update:** edit the existing `.md` file (don't create a duplicate).
1192**To forget:** delete the `.md` file → remove its entry from `MEMORY.md`."#
1193        .to_string()
1194}
1195
1196/// Build the memory system prompt from a [`MemoryConfig`]
1197/// (Phase 9b).
1198///
1199/// Renders `config.prompt_template`, substituting the placeholders:
1200///
1201/// - `{memory_root}` — the memory directory path
1202/// - `{index_content}` — the `MEMORY.md` index snapshot (startup state); an
1203///   empty index renders as a friendly "no memories yet" line
1204/// - `{tools_description}` — fixed description of the four `memory_*` tools
1205///
1206/// The legacy no-arg [`build_memory_system_prompt`] is kept for callers that
1207/// don't register memory tools (prompt-injection-only mode).
1208#[cfg(feature = "memory")]
1209pub fn build_memory_system_prompt_with_config(
1210    config: &crate::memory::MemoryConfig,
1211    index_content: &str,
1212) -> String {
1213    let index = if index_content.trim().is_empty() {
1214        "(no memories yet — memory_write creates the first one)".to_string()
1215    } else {
1216        index_content.to_string()
1217    };
1218    config
1219        .prompt_template
1220        .replace("{memory_root}", &config.memory_root.to_string_lossy())
1221        .replace("{index_content}", &index)
1222        .replace(
1223            "{tools_description}",
1224            crate::tools::MEMORY_TOOLS_DESCRIPTION,
1225        )
1226}
1227
1228#[cfg(test)]
1229mod tests {
1230    use super::*;
1231    use agent_base::Content;
1232    use agent_base::llm_trait::response::FinishReason;
1233    use agent_base::llm_trait::types::UsageInfo;
1234    use agent_base::llm_trait::{
1235        Capabilities, ChatRequest, ChatResponse, ChatStream, LlmError, LlmProvider, ProviderInfo,
1236    };
1237
1238    // ── Stub LLM provider ──
1239
1240    struct StubProvider;
1241
1242    #[async_trait::async_trait]
1243    impl LlmProvider for StubProvider {
1244        async fn stream(&self, _request: ChatRequest) -> Result<ChatStream, LlmError> {
1245            let chunks = vec![
1246                Ok(agent_base::StreamChunk::Text("ok".to_string())),
1247                Ok(agent_base::StreamChunk::Stop {
1248                    finish_reason: Some("stop".to_string()),
1249                }),
1250            ];
1251            Ok(ChatStream::new(Box::pin(futures_util::stream::iter(
1252                chunks,
1253            ))))
1254        }
1255
1256        async fn chat(&self, _request: ChatRequest) -> Result<ChatResponse, LlmError> {
1257            Ok(ChatResponse {
1258                content: "ok".to_string(),
1259                tool_calls: vec![],
1260                usage: UsageInfo::default(),
1261                finish_reason: FinishReason::Stop,
1262                raw: None,
1263                reasoning_content: None,
1264                thinking_signature: None,
1265            })
1266        }
1267
1268        fn capabilities(&self) -> Capabilities {
1269            Capabilities {
1270                supports_streaming: true,
1271                supports_tools: true,
1272                ..Default::default()
1273            }
1274        }
1275
1276        fn info(&self) -> ProviderInfo {
1277            ProviderInfo {
1278                name: "stub".to_string(),
1279                model: "stub-model".to_string(),
1280                version: None,
1281            }
1282        }
1283    }
1284
1285    fn make_client() -> Arc<dyn LlmProvider> {
1286        Arc::new(StubProvider)
1287    }
1288
1289    // ── setup_multi_agent tests ──
1290
1291    #[cfg(feature = "multi_agent")]
1292    #[tokio::test(flavor = "multi_thread")]
1293    async fn test_setup_multi_agent_without_factory_registers_no_tools() {
1294        let client = make_client();
1295        let runtime = agent_base::AgentBuilder::new(client.clone())
1296            .build()
1297            .unwrap();
1298        let config = MultiAgentConfig::enabled();
1299
1300        let result = setup_multi_agent(
1301            &runtime,
1302            config,
1303            agent_base::Language::En,
1304            vec![],
1305            None,
1306            &HashSet::new(),
1307            None, // no factory
1308        );
1309        assert!(result.is_ok());
1310        let ma_runtime = result.unwrap();
1311        // Verify no tools were registered (the 5 multi-agent tools are absent)
1312        let agents = ma_runtime.list_agents();
1313        assert!(agents.is_empty());
1314    }
1315
1316    #[cfg(feature = "multi_agent")]
1317    #[tokio::test(flavor = "multi_thread")]
1318    async fn test_setup_multi_agent_with_factory_registers_tools() {
1319        let client = make_client();
1320        let runtime = agent_base::AgentBuilder::new(client.clone())
1321            .build()
1322            .unwrap();
1323        let config = MultiAgentConfig::enabled();
1324
1325        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
1326            // Minimal factory returning a single fake tool
1327            struct FakeTool;
1328            #[async_trait::async_trait]
1329            impl Tool for FakeTool {
1330                fn name(&self) -> &'static str {
1331                    "fake_tool"
1332                }
1333                fn description(&self) -> &'static str {
1334                    ""
1335                }
1336                fn schema(&self) -> serde_json::Value {
1337                    serde_json::json!({})
1338                }
1339                async fn call(
1340                    &self,
1341                    _args: &serde_json::Value,
1342                    _ctx: &agent_base::ToolContext,
1343                ) -> AgentResult<Vec<Content>> {
1344                    Ok(vec![Content::text("ok")])
1345                }
1346            }
1347            vec![Arc::new(FakeTool)]
1348        });
1349
1350        let result = setup_multi_agent(
1351            &runtime,
1352            config,
1353            agent_base::Language::En,
1354            vec![],
1355            None,
1356            &HashSet::new(),
1357            Some(factory),
1358        );
1359        assert!(result.is_ok());
1360
1361        // Check the tool was registered on the runtime
1362        let tools: Vec<String> = tokio::task::block_in_place(|| {
1363            let tools = runtime.tools_mut();
1364            let guard = tools.blocking_read();
1365            guard.metadatas().into_iter().map(|m| m.name).collect()
1366        });
1367        assert!(tools.contains(&"fake_tool".to_string()));
1368    }
1369
1370    #[cfg(feature = "multi_agent")]
1371    #[tokio::test(flavor = "multi_thread")]
1372    async fn test_setup_multi_agent_skips_duplicate_tool_names() {
1373        let client = make_client();
1374        let runtime = agent_base::AgentBuilder::new(client.clone())
1375            .build()
1376            .unwrap();
1377
1378        // Pre-register a tool with a conflicting name
1379        struct DupTool;
1380        #[async_trait::async_trait]
1381        impl Tool for DupTool {
1382            fn name(&self) -> &'static str {
1383                "dup_tool"
1384            }
1385            fn description(&self) -> &'static str {
1386                ""
1387            }
1388            fn schema(&self) -> serde_json::Value {
1389                serde_json::json!({})
1390            }
1391            async fn call(
1392                &self,
1393                _args: &serde_json::Value,
1394                _ctx: &agent_base::ToolContext,
1395            ) -> AgentResult<Vec<Content>> {
1396                Ok(vec![Content::text("ok")])
1397            }
1398        }
1399        {
1400            let tools = runtime.tools_mut();
1401            let mut reg = tokio::task::block_in_place(|| tools.blocking_write());
1402            reg.register(DupTool);
1403        }
1404
1405        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
1406            struct FakeTool;
1407            #[async_trait::async_trait]
1408            impl Tool for FakeTool {
1409                fn name(&self) -> &'static str {
1410                    "dup_tool"
1411                }
1412                fn description(&self) -> &'static str {
1413                    ""
1414                }
1415                fn schema(&self) -> serde_json::Value {
1416                    serde_json::json!({})
1417                }
1418                async fn call(
1419                    &self,
1420                    _args: &serde_json::Value,
1421                    _ctx: &agent_base::ToolContext,
1422                ) -> AgentResult<Vec<Content>> {
1423                    Ok(vec![Content::text("ok")])
1424                }
1425            }
1426            vec![Arc::new(FakeTool)]
1427        });
1428
1429        let mut existing = HashSet::new();
1430        existing.insert("dup_tool".to_string());
1431
1432        let result = setup_multi_agent(
1433            &runtime,
1434            MultiAgentConfig::enabled(),
1435            agent_base::Language::En,
1436            vec![],
1437            None,
1438            &existing,
1439            Some(factory),
1440        );
1441        assert!(result.is_ok());
1442        // dup_tool should NOT have been registered twice
1443        let tools = tokio::task::block_in_place(|| {
1444            let tools = runtime.tools_mut();
1445            let guard = tools.blocking_read();
1446            guard
1447                .metadatas()
1448                .into_iter()
1449                .map(|m| m.name)
1450                .collect::<Vec<String>>()
1451        });
1452        let count = tools.iter().filter(|n| n.as_str() == "dup_tool").count();
1453        assert_eq!(count, 1);
1454    }
1455
1456    // ── AgentBuilder factory methods ──
1457
1458    #[cfg(feature = "multi_agent")]
1459    #[tokio::test(flavor = "multi_thread")]
1460    async fn test_builder_with_multi_agent_without_factory_builds_ok() {
1461        let client = make_client();
1462        let runtime = AgentBuilder::new(client)
1463            .with_multi_agent(MultiAgentConfig::enabled())
1464            .build()
1465            .unwrap();
1466        // Should succeed even without a factory (no tools registered)
1467        let tools = tokio::task::block_in_place(|| {
1468            let tools = runtime.tools_mut();
1469            let guard = tools.blocking_read();
1470            guard
1471                .metadatas()
1472                .into_iter()
1473                .map(|m| m.name)
1474                .collect::<Vec<String>>()
1475        });
1476        // No multi-agent tools registered
1477        assert!(!tools.contains(&"spawn_agent".to_string()));
1478    }
1479
1480    #[cfg(feature = "multi_agent")]
1481    #[tokio::test(flavor = "multi_thread")]
1482    async fn test_builder_with_factory_registers_tools() {
1483        let client = make_client();
1484        // Create a simple factory that registers one recognizable tool
1485        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
1486            struct TestTool;
1487            #[async_trait::async_trait]
1488            impl Tool for TestTool {
1489                fn name(&self) -> &'static str {
1490                    "factory_test_tool"
1491                }
1492                fn description(&self) -> &'static str {
1493                    ""
1494                }
1495                fn schema(&self) -> serde_json::Value {
1496                    serde_json::json!({})
1497                }
1498                async fn call(
1499                    &self,
1500                    _args: &serde_json::Value,
1501                    _ctx: &agent_base::ToolContext,
1502                ) -> AgentResult<Vec<Content>> {
1503                    Ok(vec![Content::text("ok")])
1504                }
1505            }
1506            vec![Arc::new(TestTool)]
1507        });
1508
1509        let runtime = AgentBuilder::new(client)
1510            .with_multi_agent(MultiAgentConfig::enabled())
1511            .with_multi_agent_tool_factory(factory)
1512            .build()
1513            .unwrap();
1514
1515        let tools = tokio::task::block_in_place(|| {
1516            let tools = runtime.tools_mut();
1517            let guard = tools.blocking_read();
1518            guard
1519                .metadatas()
1520                .into_iter()
1521                .map(|m| m.name)
1522                .collect::<Vec<String>>()
1523        });
1524        assert!(tools.contains(&"factory_test_tool".to_string()));
1525    }
1526
1527    #[cfg(feature = "multi_agent")]
1528    #[test]
1529    fn test_builder_disabled_multi_agent_skips_factory() {
1530        let client = make_client();
1531        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
1532            panic!("factory should not be called when multi-agent is not configured");
1533        });
1534
1535        let runtime = AgentBuilder::new(client)
1536            .with_multi_agent_tool_factory(factory)
1537            // Don't enable multi-agent — default (None) means disabled
1538            .build()
1539            .unwrap();
1540
1541        let tools = tokio::task::block_in_place(|| {
1542            let tools = runtime.tools_mut();
1543            let guard = tools.blocking_read();
1544            guard
1545                .metadatas()
1546                .into_iter()
1547                .map(|m| m.name)
1548                .collect::<Vec<String>>()
1549        });
1550        assert!(!tools.contains(&"spawn_agent".to_string()));
1551    }
1552
1553    // ── build_multi_agent_system_prompt ──
1554
1555    #[cfg(feature = "multi_agent")]
1556    #[test]
1557    fn test_system_prompt_contains_tool_names() {
1558        let prompt = build_multi_agent_system_prompt();
1559        assert!(prompt.contains("spawn_agent"));
1560        assert!(prompt.contains("send_message"));
1561        assert!(prompt.contains("trigger"));
1562        assert!(prompt.contains("list_agents"));
1563        assert!(prompt.contains("close_agent"));
1564        // followup_task is gone (§8.3) — guidance must not advertise a tool
1565        // the factory no longer registers.
1566        assert!(!prompt.contains("followup_task"));
1567        // wait_agent is gone too — results are pushed, the parent waits by
1568        // ending its turn.
1569        assert!(!prompt.contains("wait_agent"));
1570        assert!(prompt.contains("pushed into your context automatically"));
1571    }
1572
1573    #[cfg(feature = "multi_agent")]
1574    #[test]
1575    fn test_system_prompt_contains_guidance() {
1576        let prompt = build_multi_agent_system_prompt();
1577        assert!(prompt.contains("When to Spawn"));
1578        assert!(prompt.contains("When NOT to Spawn"));
1579        assert!(prompt.contains("How Results Reach You"));
1580    }
1581
1582    // ── without_multi_agent ──
1583
1584    #[cfg(feature = "multi_agent")]
1585    #[tokio::test(flavor = "multi_thread")]
1586    async fn test_without_multi_agent_clears_config_and_factory() {
1587        let client = make_client();
1588
1589        // Set up a factory that would panic if called — without_multi_agent should prevent it
1590        let factory: MultiAgentToolFactory = Arc::new(|_rt| {
1591            panic!("factory should not be called when multi-agent is cleared");
1592        });
1593
1594        let runtime = AgentBuilder::new(client)
1595            .with_multi_agent(MultiAgentConfig::enabled())
1596            .with_multi_agent_tool_factory(factory)
1597            .without_multi_agent() // clear both
1598            .build()
1599            .unwrap();
1600
1601        let tools = tokio::task::block_in_place(|| {
1602            let tools = runtime.tools_mut();
1603            let guard = tools.blocking_read();
1604            guard
1605                .metadatas()
1606                .into_iter()
1607                .map(|m| m.name)
1608                .collect::<Vec<String>>()
1609        });
1610        assert!(!tools.contains(&"spawn_agent".to_string()));
1611    }
1612
1613    // ── apply_if ──
1614
1615    #[test]
1616    fn test_apply_if_some_applies_transformation() {
1617        let client = make_client();
1618        let builder = AgentBuilder::new(client)
1619            .apply_if(Some("custom prompt"), |b, prompt| b.system_prompt(prompt));
1620        // system_prompt is stored in self.system_prompt; verify it was set
1621        assert!(builder.system_prompt.unwrap().contains("custom prompt"));
1622    }
1623
1624    #[test]
1625    fn test_apply_if_none_passes_through() {
1626        let client = make_client();
1627        let builder = AgentBuilder::new(client).apply_if(None as Option<&str>, |_b, _prompt| {
1628            panic!("should not be called when value is None");
1629        });
1630        assert!(builder.system_prompt.is_none());
1631    }
1632
1633    // ── build_memory_system_prompt ──
1634
1635    #[test]
1636    fn test_build_memory_system_prompt_non_empty() {
1637        let prompt = build_memory_system_prompt();
1638        assert!(!prompt.is_empty());
1639        assert!(prompt.contains("Memory"));
1640        assert!(prompt.contains("MEMORY.md"));
1641        assert!(prompt.contains("read_file"));
1642        assert!(prompt.contains("write_file"));
1643    }
1644
1645    // ── build_memory_system_prompt_with_config (Phase 9b) ──
1646
1647    #[cfg(feature = "memory")]
1648    mod memory_tests {
1649        use super::*;
1650        use crate::memory::{CLAUDE_COMPATIBLE_TEMPLATE, MemoryConfig, MemoryStore};
1651
1652        fn temp_config() -> (tempfile::TempDir, MemoryConfig) {
1653            let dir = tempfile::tempdir().unwrap();
1654            let config = MemoryConfig::custom(
1655                dir.path().join("memory"),
1656                CLAUDE_COMPATIBLE_TEMPLATE.to_string(),
1657            );
1658            (dir, config)
1659        }
1660
1661        #[test]
1662        fn prompt_with_config_substitutes_all_placeholders() {
1663            let (_dir, config) = temp_config();
1664            let prompt =
1665                build_memory_system_prompt_with_config(&config, "- [alpha](alpha.md) — first\n");
1666            assert!(
1667                prompt.contains(config.memory_root.to_string_lossy().as_ref()),
1668                "{prompt}"
1669            );
1670            assert!(prompt.contains("- [alpha](alpha.md) — first"), "{prompt}");
1671            assert!(prompt.contains("memory_write"), "{prompt}");
1672            assert!(prompt.contains("memory_delete"), "{prompt}");
1673            assert!(!prompt.contains("{memory_root}"), "{prompt}");
1674            assert!(!prompt.contains("{index_content}"), "{prompt}");
1675            assert!(!prompt.contains("{tools_description}"), "{prompt}");
1676        }
1677
1678        #[test]
1679        fn prompt_with_config_handles_empty_index() {
1680            let (_dir, config) = temp_config();
1681            let prompt = build_memory_system_prompt_with_config(&config, "");
1682            assert!(prompt.contains("no memories yet"), "{prompt}");
1683        }
1684
1685        #[test]
1686        fn memory_disabled_by_default_registers_nothing() {
1687            let client = make_client();
1688            let runtime = AgentBuilder::new(client).build().unwrap();
1689            let names = runtime_tool_names(&runtime);
1690            assert!(!names.iter().any(|n| n.starts_with("memory_")), "{names:?}");
1691            assert!(runtime.config().system_prompt.is_none());
1692        }
1693
1694        #[test]
1695        fn without_memory_config_clears_previous_config() {
1696            let (_dir, config) = temp_config();
1697            let client = make_client();
1698            let builder = AgentBuilder::new(client)
1699                .memory_config(config)
1700                .without_memory_config();
1701            assert!(builder.memory_config.is_none());
1702        }
1703
1704        #[tokio::test(flavor = "multi_thread")]
1705        async fn memory_config_registers_tools_and_injects_prompt() {
1706            let (dir, config) = temp_config();
1707
1708            // Pre-seed one memory so the injected prompt carries a real row.
1709            let store = MemoryStore::new(config.memory_root.clone(), "MEMORY.md");
1710            store
1711                .write_memory("seed-note", "seeded before build", "project", "body", None)
1712                .unwrap();
1713
1714            let client = make_client();
1715            let runtime = AgentBuilder::new(client)
1716                .system_prompt("base prompt")
1717                .memory_config(config)
1718                .build()
1719                .unwrap();
1720
1721            // All four tools registered.
1722            let names = runtime_tool_names(&runtime);
1723            for expected in [
1724                "memory_write",
1725                "memory_read",
1726                "memory_list",
1727                "memory_delete",
1728            ] {
1729                assert!(names.contains(&expected.to_string()), "{names:?}");
1730            }
1731
1732            // Prompt = base + memory section with the seeded index row.
1733            let prompt =
1734                tokio::task::block_in_place(|| runtime.config().system_prompt.clone().unwrap());
1735            assert!(prompt.starts_with("base prompt"), "{prompt}");
1736            assert!(
1737                prompt.contains("- [seed-note](seed-note.md) — seeded before build"),
1738                "{prompt}"
1739            );
1740            assert!(
1741                prompt.contains(dir.path().join("memory").to_string_lossy().as_ref()),
1742                "{prompt}"
1743            );
1744        }
1745    }
1746
1747    // ── Named tool for register_tool / skill tests ──
1748
1749    struct NamedTool(&'static str);
1750
1751    #[async_trait::async_trait]
1752    impl Tool for NamedTool {
1753        fn name(&self) -> &'static str {
1754            self.0
1755        }
1756
1757        fn description(&self) -> &'static str {
1758            ""
1759        }
1760
1761        fn schema(&self) -> serde_json::Value {
1762            serde_json::json!({})
1763        }
1764
1765        async fn call(
1766            &self,
1767            _args: &serde_json::Value,
1768            _ctx: &agent_base::ToolContext,
1769        ) -> AgentResult<Vec<Content>> {
1770            Ok(vec![Content::text("ok")])
1771        }
1772    }
1773
1774    fn runtime_tool_names(runtime: &AgentRuntime) -> Vec<String> {
1775        tokio::task::block_in_place(|| {
1776            let tools = runtime.tools_mut();
1777            let guard = tools.blocking_read();
1778            guard.metadatas().into_iter().map(|m| m.name).collect()
1779        })
1780    }
1781
1782    #[tokio::test(flavor = "multi_thread")]
1783    async fn test_builder_scalar_passthrough_methods() {
1784        let client = make_client();
1785        let runtime = AgentBuilder::new(client)
1786            .enable_thought(true)
1787            .reasoning(agent_base::ReasoningConfig::default())
1788            .enable_thinking(false)
1789            .thinking_budget(1000)
1790            .tool_timeout(5000)
1791            .max_tool_output_chars(4000)
1792            .max_sessions(16)
1793            .max_turns_per_session(20)
1794            .execution_max_turns(10)
1795            .max_message_tokens(8000)
1796            .context_window(64_000)
1797            .context_window_manager(agent_base::ContextWindowManager::new(64_000))
1798            .response_format(agent_base::ResponseFormat::JsonObject)
1799            .llm_retry(agent_base::RetryConfig::default())
1800            .tool_error_retry_prompt("please retry")
1801            .language(agent_base::Language::En)
1802            .event_bus_capacity(256)
1803            .build()
1804            .unwrap();
1805
1806        assert!(runtime.provider().capabilities().supports_streaming);
1807    }
1808
1809    #[tokio::test(flavor = "multi_thread")]
1810    async fn test_register_tool_variants() {
1811        let client = make_client();
1812        let runtime = AgentBuilder::new(client)
1813            .register_tool(NamedTool("tool_by_value"))
1814            .register_tool_arc(Arc::new(NamedTool("tool_by_arc")))
1815            .build()
1816            .unwrap();
1817
1818        let names = runtime_tool_names(&runtime);
1819        assert!(names.contains(&"tool_by_value".to_string()));
1820        assert!(names.contains(&"tool_by_arc".to_string()));
1821    }
1822
1823    #[cfg(feature = "skill")]
1824    mod skill_tests {
1825        use super::*;
1826        use crate::skill::Skill;
1827
1828        struct TestSkill;
1829
1830        impl Skill for TestSkill {
1831            fn name(&self) -> &'static str {
1832                "test_skill"
1833            }
1834
1835            fn brief_description(&self) -> String {
1836                "a test skill".to_string()
1837            }
1838
1839            fn detailed_description(&self) -> String {
1840                "detailed test skill".to_string()
1841            }
1842
1843            fn tools(&self) -> Vec<Arc<dyn Tool>> {
1844                vec![]
1845            }
1846        }
1847
1848        struct ToolSkill;
1849
1850        impl Skill for ToolSkill {
1851            fn name(&self) -> &'static str {
1852                "tool_skill"
1853            }
1854
1855            fn brief_description(&self) -> String {
1856                "skill with a tool".to_string()
1857            }
1858
1859            fn detailed_description(&self) -> String {
1860                "skill that provides a tool".to_string()
1861            }
1862
1863            fn tools(&self) -> Vec<Arc<dyn Tool>> {
1864                vec![Arc::new(NamedTool("skill_provided_tool"))]
1865            }
1866        }
1867
1868        #[tokio::test(flavor = "multi_thread")]
1869        async fn test_register_skill_builds_ok() {
1870            let client = make_client();
1871            let runtime = AgentBuilder::new(client)
1872                .register_skill(TestSkill)
1873                .build()
1874                .unwrap();
1875            // Prompt injection is applied during build; no tools provided.
1876            assert!(runtime_tool_names(&runtime).is_empty());
1877        }
1878
1879        #[tokio::test(flavor = "multi_thread")]
1880        async fn test_register_skill_with_tool_registers_tool() {
1881            let client = make_client();
1882            let runtime = AgentBuilder::new(client)
1883                .register_skill(ToolSkill)
1884                .build()
1885                .unwrap();
1886            assert!(runtime_tool_names(&runtime).contains(&"skill_provided_tool".to_string()));
1887        }
1888
1889        #[tokio::test(flavor = "multi_thread")]
1890        async fn test_register_skill_tool_name_conflict() {
1891            let client = make_client();
1892            let result = AgentBuilder::new(client)
1893                .register_tool(NamedTool("skill_provided_tool"))
1894                .register_skill(ToolSkill)
1895                .build();
1896            let err = result.err().unwrap();
1897            assert!(format!("{err}").contains("Tool name conflict"));
1898        }
1899
1900        #[tokio::test(flavor = "multi_thread")]
1901        async fn test_skill_detail_tool_factory_registers_tool() {
1902            let client = make_client();
1903            let factory: SkillDetailToolFactory = Arc::new(|_skills, name| {
1904                assert_eq!(name, "get_skill_detail");
1905                Arc::new(NamedTool("detail_tool"))
1906            });
1907            let runtime = AgentBuilder::new(client)
1908                .register_skill(TestSkill)
1909                .with_skill_detail_tool_factory(factory)
1910                .build()
1911                .unwrap();
1912            assert!(runtime_tool_names(&runtime).contains(&"detail_tool".to_string()));
1913        }
1914
1915        #[tokio::test(flavor = "multi_thread")]
1916        async fn test_list_skills_tool_factory_registers_tool() {
1917            let client = make_client();
1918            let factory: ListSkillsToolFactory =
1919                Arc::new(|_registry| Arc::new(NamedTool("list_skills_tool")));
1920            let runtime = AgentBuilder::new(client)
1921                .register_skill(TestSkill)
1922                .with_list_skills_tool_factory(factory)
1923                .build()
1924                .unwrap();
1925            assert!(runtime_tool_names(&runtime).contains(&"list_skills_tool".to_string()));
1926        }
1927
1928        #[tokio::test(flavor = "multi_thread")]
1929        async fn test_disable_skill_prompt_injection_builds() {
1930            let client = make_client();
1931            let runtime = AgentBuilder::new(client)
1932                .register_skill(ToolSkill)
1933                .disable_skill_prompt_injection()
1934                .build()
1935                .unwrap();
1936            // Tool still registered; prompt injection skipped.
1937            assert!(runtime_tool_names(&runtime).contains(&"skill_provided_tool".to_string()));
1938        }
1939    }
1940
1941    // ── Agent instructions tests ──
1942
1943    #[test]
1944    fn test_build_agent_instructions_prompt_reads_files() {
1945        let tmp = tempfile::tempdir().unwrap();
1946        let file1 = tmp.path().join("CLAUDE.md");
1947        let file2 = tmp.path().join("INSTRUCTIONS.md");
1948        std::fs::write(&file1, "# User instructions\nBe helpful.").unwrap();
1949        std::fs::write(&file2, "# Project instructions\nFollow conventions.").unwrap();
1950
1951        let prompt = build_agent_instructions_prompt(&[file1, file2]);
1952        assert!(prompt.is_some());
1953        let prompt = prompt.unwrap();
1954        // Higher priority (later entries) appear first
1955        assert!(prompt.starts_with("# Project instructions"));
1956        assert!(prompt.contains("# User instructions"));
1957        assert!(prompt.contains("Be helpful."));
1958        assert!(prompt.contains("Follow conventions."));
1959    }
1960
1961    #[test]
1962    fn test_build_agent_instructions_prompt_skips_missing_files() {
1963        let prompt = build_agent_instructions_prompt(&[
1964            PathBuf::from("/nonexistent/CLAUDE.md"),
1965            PathBuf::from("/nonexistent/INSTRUCTIONS.md"),
1966        ]);
1967        assert!(prompt.is_none());
1968    }
1969
1970    #[test]
1971    fn test_build_agent_instructions_prompt_skips_empty_files() {
1972        let tmp = tempfile::tempdir().unwrap();
1973        let file = tmp.path().join("empty.md");
1974        std::fs::write(&file, "   \n  ").unwrap();
1975
1976        let prompt = build_agent_instructions_prompt(&[file]);
1977        assert!(prompt.is_none());
1978    }
1979}