agent-works 0.14.0

Batteries-included Agent toolbox built on agent-base
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
use agent_base::{AgentResult, AgentRuntime};

use super::*;
use agent_base::Content;
use agent_base::llm_trait::response::FinishReason;
use agent_base::llm_trait::types::UsageInfo;
use agent_base::llm_trait::{
    Capabilities, ChatRequest, ChatResponse, ChatStream, LlmError, LlmProvider, ProviderInfo,
};

// ── Stub LLM provider ──

struct StubProvider;

#[async_trait::async_trait]
impl LlmProvider for StubProvider {
    async fn stream(&self, _request: ChatRequest) -> Result<ChatStream, LlmError> {
        let chunks = vec![
            Ok(agent_base::StreamChunk::Text("ok".to_string())),
            Ok(agent_base::StreamChunk::Stop {
                finish_reason: Some("stop".to_string()),
            }),
        ];
        Ok(ChatStream::new(Box::pin(futures_util::stream::iter(
            chunks,
        ))))
    }

    async fn chat(&self, _request: ChatRequest) -> Result<ChatResponse, LlmError> {
        Ok(ChatResponse {
            content: "ok".to_string(),
            tool_calls: vec![],
            usage: UsageInfo::default(),
            finish_reason: FinishReason::Stop,
            raw: None,
            reasoning_content: None,
            thinking_signature: None,
        })
    }

    fn capabilities(&self) -> Capabilities {
        Capabilities {
            supports_streaming: true,
            supports_tools: true,
            ..Default::default()
        }
    }

    fn info(&self) -> ProviderInfo {
        ProviderInfo {
            name: "stub".to_string(),
            model: "stub-model".to_string(),
            version: None,
        }
    }
}

fn make_client() -> Arc<dyn LlmProvider> {
    Arc::new(StubProvider)
}

// ── setup_multi_agent tests ──

#[cfg(feature = "multi_agent")]
#[tokio::test(flavor = "multi_thread")]
async fn test_setup_multi_agent_without_factory_registers_no_tools() {
    let client = make_client();
    let runtime = agent_base::AgentBuilder::new(client.clone())
        .build()
        .unwrap();
    let config = MultiAgentConfig::enabled();

    let result = setup_multi_agent(
        &runtime,
        config,
        agent_base::Language::En,
        vec![],
        None,
        &HashSet::new(),
        None, // no factory
    );
    assert!(result.is_ok());
    let ma_runtime = result.unwrap();
    // Verify no tools were registered (the 5 multi-agent tools are absent)
    let agents = ma_runtime.list_agents();
    assert!(agents.is_empty());
}

#[cfg(feature = "multi_agent")]
#[tokio::test(flavor = "multi_thread")]
async fn test_setup_multi_agent_with_factory_registers_tools() {
    let client = make_client();
    let runtime = agent_base::AgentBuilder::new(client.clone())
        .build()
        .unwrap();
    let config = MultiAgentConfig::enabled();

    let factory: MultiAgentToolFactory = Arc::new(|_rt| {
        // Minimal factory returning a single fake tool
        struct FakeTool;
        #[async_trait::async_trait]
        impl Tool for FakeTool {
            fn name(&self) -> &'static str {
                "fake_tool"
            }
            fn description(&self) -> &'static str {
                ""
            }
            fn schema(&self) -> serde_json::Value {
                serde_json::json!({})
            }
            async fn call(
                &self,
                _args: &serde_json::Value,
                _ctx: &agent_base::ToolContext,
            ) -> AgentResult<Vec<Content>> {
                Ok(vec![Content::text("ok")])
            }
        }
        vec![Arc::new(FakeTool)]
    });

    let result = setup_multi_agent(
        &runtime,
        config,
        agent_base::Language::En,
        vec![],
        None,
        &HashSet::new(),
        Some(factory),
    );
    assert!(result.is_ok());

    // Check the tool was registered on the runtime
    let tools: Vec<String> = tokio::task::block_in_place(|| {
        let tools = runtime.tools_mut();
        let guard = tools.blocking_read();
        guard.metadatas().into_iter().map(|m| m.name).collect()
    });
    assert!(tools.contains(&"fake_tool".to_string()));
}

#[cfg(feature = "multi_agent")]
#[tokio::test(flavor = "multi_thread")]
async fn test_setup_multi_agent_skips_duplicate_tool_names() {
    let client = make_client();
    let runtime = agent_base::AgentBuilder::new(client.clone())
        .build()
        .unwrap();

    // Pre-register a tool with a conflicting name
    struct DupTool;
    #[async_trait::async_trait]
    impl Tool for DupTool {
        fn name(&self) -> &'static str {
            "dup_tool"
        }
        fn description(&self) -> &'static str {
            ""
        }
        fn schema(&self) -> serde_json::Value {
            serde_json::json!({})
        }
        async fn call(
            &self,
            _args: &serde_json::Value,
            _ctx: &agent_base::ToolContext,
        ) -> AgentResult<Vec<Content>> {
            Ok(vec![Content::text("ok")])
        }
    }
    {
        let tools = runtime.tools_mut();
        let mut reg = tokio::task::block_in_place(|| tools.blocking_write());
        reg.register(DupTool);
    }

    let factory: MultiAgentToolFactory = Arc::new(|_rt| {
        struct FakeTool;
        #[async_trait::async_trait]
        impl Tool for FakeTool {
            fn name(&self) -> &'static str {
                "dup_tool"
            }
            fn description(&self) -> &'static str {
                ""
            }
            fn schema(&self) -> serde_json::Value {
                serde_json::json!({})
            }
            async fn call(
                &self,
                _args: &serde_json::Value,
                _ctx: &agent_base::ToolContext,
            ) -> AgentResult<Vec<Content>> {
                Ok(vec![Content::text("ok")])
            }
        }
        vec![Arc::new(FakeTool)]
    });

    let mut existing = HashSet::new();
    existing.insert("dup_tool".to_string());

    let result = setup_multi_agent(
        &runtime,
        MultiAgentConfig::enabled(),
        agent_base::Language::En,
        vec![],
        None,
        &existing,
        Some(factory),
    );
    assert!(result.is_ok());
    // dup_tool should NOT have been registered twice
    let tools = tokio::task::block_in_place(|| {
        let tools = runtime.tools_mut();
        let guard = tools.blocking_read();
        guard
            .metadatas()
            .into_iter()
            .map(|m| m.name)
            .collect::<Vec<String>>()
    });
    let count = tools.iter().filter(|n| n.as_str() == "dup_tool").count();
    assert_eq!(count, 1);
}

// ── AgentBuilder factory methods ──

#[cfg(feature = "multi_agent")]
#[tokio::test(flavor = "multi_thread")]
async fn test_builder_with_multi_agent_without_factory_builds_ok() {
    let client = make_client();
    let runtime = AgentBuilder::new(client)
        .with_multi_agent(MultiAgentConfig::enabled())
        .build()
        .unwrap();
    // Should succeed even without a factory (no tools registered)
    let tools = tokio::task::block_in_place(|| {
        let tools = runtime.tools_mut();
        let guard = tools.blocking_read();
        guard
            .metadatas()
            .into_iter()
            .map(|m| m.name)
            .collect::<Vec<String>>()
    });
    // No multi-agent tools registered
    assert!(!tools.contains(&"spawn_agent".to_string()));
}

#[cfg(feature = "multi_agent")]
#[tokio::test(flavor = "multi_thread")]
async fn test_builder_with_factory_registers_tools() {
    let client = make_client();
    // Create a simple factory that registers one recognizable tool
    let factory: MultiAgentToolFactory = Arc::new(|_rt| {
        struct TestTool;
        #[async_trait::async_trait]
        impl Tool for TestTool {
            fn name(&self) -> &'static str {
                "factory_test_tool"
            }
            fn description(&self) -> &'static str {
                ""
            }
            fn schema(&self) -> serde_json::Value {
                serde_json::json!({})
            }
            async fn call(
                &self,
                _args: &serde_json::Value,
                _ctx: &agent_base::ToolContext,
            ) -> AgentResult<Vec<Content>> {
                Ok(vec![Content::text("ok")])
            }
        }
        vec![Arc::new(TestTool)]
    });

    let runtime = AgentBuilder::new(client)
        .with_multi_agent(MultiAgentConfig::enabled())
        .with_multi_agent_tool_factory(factory)
        .build()
        .unwrap();

    let tools = tokio::task::block_in_place(|| {
        let tools = runtime.tools_mut();
        let guard = tools.blocking_read();
        guard
            .metadatas()
            .into_iter()
            .map(|m| m.name)
            .collect::<Vec<String>>()
    });
    assert!(tools.contains(&"factory_test_tool".to_string()));
}

#[cfg(feature = "multi_agent")]
#[test]
fn test_builder_disabled_multi_agent_skips_factory() {
    let client = make_client();
    let factory: MultiAgentToolFactory = Arc::new(|_rt| {
        panic!("factory should not be called when multi-agent is not configured");
    });

    let runtime = AgentBuilder::new(client)
        .with_multi_agent_tool_factory(factory)
        // Don't enable multi-agent — default (None) means disabled
        .build()
        .unwrap();

    let tools = tokio::task::block_in_place(|| {
        let tools = runtime.tools_mut();
        let guard = tools.blocking_read();
        guard
            .metadatas()
            .into_iter()
            .map(|m| m.name)
            .collect::<Vec<String>>()
    });
    assert!(!tools.contains(&"spawn_agent".to_string()));
}

// ── build_multi_agent_system_prompt ──

#[cfg(feature = "multi_agent")]
#[test]
fn test_system_prompt_contains_tool_names() {
    let prompt = build_multi_agent_system_prompt();
    assert!(prompt.contains("spawn_agent"));
    assert!(prompt.contains("send_message"));
    assert!(prompt.contains("trigger"));
    assert!(prompt.contains("list_agents"));
    assert!(prompt.contains("close_agent"));
    // followup_task is gone (§8.3) — guidance must not advertise a tool
    // the factory no longer registers.
    assert!(!prompt.contains("followup_task"));
    // wait_agent is gone too — results are pushed, the parent waits by
    // ending its turn.
    assert!(!prompt.contains("wait_agent"));
    assert!(prompt.contains("pushed into your context automatically"));
}

#[cfg(feature = "multi_agent")]
#[test]
fn test_system_prompt_contains_guidance() {
    let prompt = build_multi_agent_system_prompt();
    assert!(prompt.contains("When to Spawn"));
    assert!(prompt.contains("When NOT to Spawn"));
    assert!(prompt.contains("How Results Reach You"));
}

// ── without_multi_agent ──

#[cfg(feature = "multi_agent")]
#[tokio::test(flavor = "multi_thread")]
async fn test_without_multi_agent_clears_config_and_factory() {
    let client = make_client();

    // Set up a factory that would panic if called — without_multi_agent should prevent it
    let factory: MultiAgentToolFactory = Arc::new(|_rt| {
        panic!("factory should not be called when multi-agent is cleared");
    });

    let runtime = AgentBuilder::new(client)
        .with_multi_agent(MultiAgentConfig::enabled())
        .with_multi_agent_tool_factory(factory)
        .without_multi_agent() // clear both
        .build()
        .unwrap();

    let tools = tokio::task::block_in_place(|| {
        let tools = runtime.tools_mut();
        let guard = tools.blocking_read();
        guard
            .metadatas()
            .into_iter()
            .map(|m| m.name)
            .collect::<Vec<String>>()
    });
    assert!(!tools.contains(&"spawn_agent".to_string()));
}

// ── apply_if ──

#[test]
fn test_apply_if_some_applies_transformation() {
    let client = make_client();
    let builder = AgentBuilder::new(client)
        .apply_if(Some("custom prompt"), |b, prompt| b.system_prompt(prompt));
    // system_prompt is stored in self.system_prompt; verify it was set
    assert!(builder.system_prompt.unwrap().contains("custom prompt"));
}

#[test]
fn test_apply_if_none_passes_through() {
    let client = make_client();
    let builder = AgentBuilder::new(client).apply_if(None as Option<&str>, |_b, _prompt| {
        panic!("should not be called when value is None");
    });
    assert!(builder.system_prompt.is_none());
}

// ── build_memory_system_prompt ──

#[test]
fn test_build_memory_system_prompt_non_empty() {
    let prompt = build_memory_system_prompt();
    assert!(!prompt.is_empty());
    assert!(prompt.contains("Memory"));
    assert!(prompt.contains("MEMORY.md"));
    assert!(prompt.contains("read_file"));
    assert!(prompt.contains("write_file"));
}

// ── build_memory_system_prompt_with_config (Phase 9b) ──

#[cfg(feature = "memory")]
mod memory_tests {
    use super::*;
    use crate::memory::{CLAUDE_COMPATIBLE_TEMPLATE, MemoryConfig, MemoryStore};

    fn temp_config() -> (tempfile::TempDir, MemoryConfig) {
        let dir = tempfile::tempdir().unwrap();
        let config = MemoryConfig::custom(
            dir.path().join("memory"),
            CLAUDE_COMPATIBLE_TEMPLATE.to_string(),
        );
        (dir, config)
    }

    #[test]
    fn prompt_with_config_substitutes_all_placeholders() {
        let (_dir, config) = temp_config();
        let prompt =
            build_memory_system_prompt_with_config(&config, "- [alpha](alpha.md) — first\n");
        assert!(
            prompt.contains(config.memory_root.to_string_lossy().as_ref()),
            "{prompt}"
        );
        assert!(prompt.contains("- [alpha](alpha.md) — first"), "{prompt}");
        assert!(prompt.contains("memory_write"), "{prompt}");
        assert!(prompt.contains("memory_delete"), "{prompt}");
        assert!(!prompt.contains("{memory_root}"), "{prompt}");
        assert!(!prompt.contains("{index_content}"), "{prompt}");
        assert!(!prompt.contains("{tools_description}"), "{prompt}");
    }

    #[test]
    fn prompt_with_config_handles_empty_index() {
        let (_dir, config) = temp_config();
        let prompt = build_memory_system_prompt_with_config(&config, "");
        assert!(prompt.contains("no memories yet"), "{prompt}");
    }

    #[test]
    fn memory_disabled_by_default_registers_nothing() {
        let client = make_client();
        let runtime = AgentBuilder::new(client).build().unwrap();
        let names = runtime_tool_names(&runtime);
        assert!(!names.iter().any(|n| n.starts_with("memory_")), "{names:?}");
        assert!(runtime.config().system_prompt.is_none());
    }

    #[test]
    fn without_memory_config_clears_previous_config() {
        let (_dir, config) = temp_config();
        let client = make_client();
        let builder = AgentBuilder::new(client)
            .memory_config(config)
            .without_memory_config();
        assert!(builder.memory_config.is_none());
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn memory_config_registers_tools_and_injects_prompt() {
        let (dir, config) = temp_config();

        // Pre-seed one memory so the injected prompt carries a real row.
        let store = MemoryStore::new(config.memory_root.clone(), "MEMORY.md");
        store
            .write_memory("seed-note", "seeded before build", "project", "body", None)
            .unwrap();

        let client = make_client();
        let runtime = AgentBuilder::new(client)
            .system_prompt("base prompt")
            .memory_config(config)
            .build()
            .unwrap();

        // All four tools registered.
        let names = runtime_tool_names(&runtime);
        for expected in [
            "memory_write",
            "memory_read",
            "memory_list",
            "memory_delete",
        ] {
            assert!(names.contains(&expected.to_string()), "{names:?}");
        }

        // Prompt = base + memory section with the seeded index row.
        let prompt =
            tokio::task::block_in_place(|| runtime.config().system_prompt.clone().unwrap());
        assert!(prompt.starts_with("base prompt"), "{prompt}");
        assert!(
            prompt.contains("- [seed-note](seed-note.md) — seeded before build"),
            "{prompt}"
        );
        assert!(
            prompt.contains(dir.path().join("memory").to_string_lossy().as_ref()),
            "{prompt}"
        );
    }
}

// ── Named tool for register_tool / skill tests ──

struct NamedTool(&'static str);

#[async_trait::async_trait]
impl Tool for NamedTool {
    fn name(&self) -> &'static str {
        self.0
    }

    fn description(&self) -> &'static str {
        ""
    }

    fn schema(&self) -> serde_json::Value {
        serde_json::json!({})
    }

    async fn call(
        &self,
        _args: &serde_json::Value,
        _ctx: &agent_base::ToolContext,
    ) -> AgentResult<Vec<Content>> {
        Ok(vec![Content::text("ok")])
    }
}

fn runtime_tool_names(runtime: &AgentRuntime) -> Vec<String> {
    tokio::task::block_in_place(|| {
        let tools = runtime.tools_mut();
        let guard = tools.blocking_read();
        guard.metadatas().into_iter().map(|m| m.name).collect()
    })
}

#[tokio::test(flavor = "multi_thread")]
async fn test_builder_scalar_passthrough_methods() {
    let client = make_client();
    let runtime = AgentBuilder::new(client)
        .enable_thought(true)
        .reasoning(agent_base::ReasoningConfig::default())
        .enable_thinking(false)
        .thinking_budget(1000)
        .tool_timeout(5000)
        .max_tool_output_chars(4000)
        .max_sessions(16)
        .max_turns_per_session(20)
        .execution_max_turns(10)
        .max_message_tokens(8000)
        .context_window(64_000)
        .context_window_manager(agent_base::ContextWindowManager::new(64_000))
        .response_format(agent_base::ResponseFormat::JsonObject)
        .llm_retry(agent_base::RetryConfig::default())
        .tool_error_retry_prompt("please retry")
        .language(agent_base::Language::En)
        .event_bus_capacity(256)
        .build()
        .unwrap();

    assert!(runtime.provider().capabilities().supports_streaming);
}

#[tokio::test(flavor = "multi_thread")]
async fn test_register_tool_variants() {
    let client = make_client();
    let runtime = AgentBuilder::new(client)
        .register_tool(NamedTool("tool_by_value"))
        .register_tool_arc(Arc::new(NamedTool("tool_by_arc")))
        .build()
        .unwrap();

    let names = runtime_tool_names(&runtime);
    assert!(names.contains(&"tool_by_value".to_string()));
    assert!(names.contains(&"tool_by_arc".to_string()));
}

#[cfg(feature = "skill")]
mod skill_tests {
    use super::*;
    use crate::skill::Skill;

    struct TestSkill;

    impl Skill for TestSkill {
        fn name(&self) -> &'static str {
            "test_skill"
        }

        fn brief_description(&self) -> String {
            "a test skill".to_string()
        }

        fn detailed_description(&self) -> String {
            "detailed test skill".to_string()
        }

        fn tools(&self) -> Vec<Arc<dyn Tool>> {
            vec![]
        }
    }

    struct ToolSkill;

    impl Skill for ToolSkill {
        fn name(&self) -> &'static str {
            "tool_skill"
        }

        fn brief_description(&self) -> String {
            "skill with a tool".to_string()
        }

        fn detailed_description(&self) -> String {
            "skill that provides a tool".to_string()
        }

        fn tools(&self) -> Vec<Arc<dyn Tool>> {
            vec![Arc::new(NamedTool("skill_provided_tool"))]
        }
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_register_skill_builds_ok() {
        let client = make_client();
        let runtime = AgentBuilder::new(client)
            .register_skill(TestSkill)
            .build()
            .unwrap();
        // Prompt injection is applied during build; no tools provided.
        assert!(runtime_tool_names(&runtime).is_empty());
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_register_skill_with_tool_registers_tool() {
        let client = make_client();
        let runtime = AgentBuilder::new(client)
            .register_skill(ToolSkill)
            .build()
            .unwrap();
        assert!(runtime_tool_names(&runtime).contains(&"skill_provided_tool".to_string()));
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_register_skill_tool_name_conflict() {
        let client = make_client();
        let result = AgentBuilder::new(client)
            .register_tool(NamedTool("skill_provided_tool"))
            .register_skill(ToolSkill)
            .build();
        let err = result.err().unwrap();
        assert!(format!("{err}").contains("Tool name conflict"));
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_skill_detail_tool_factory_registers_tool() {
        let client = make_client();
        let factory: SkillDetailToolFactory = Arc::new(|_skills, name| {
            assert_eq!(name, "get_skill_detail");
            Arc::new(NamedTool("detail_tool"))
        });
        let runtime = AgentBuilder::new(client)
            .register_skill(TestSkill)
            .with_skill_detail_tool_factory(factory)
            .build()
            .unwrap();
        assert!(runtime_tool_names(&runtime).contains(&"detail_tool".to_string()));
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_list_skills_tool_factory_registers_tool() {
        let client = make_client();
        let factory: ListSkillsToolFactory =
            Arc::new(|_registry| Arc::new(NamedTool("list_skills_tool")));
        let runtime = AgentBuilder::new(client)
            .register_skill(TestSkill)
            .with_list_skills_tool_factory(factory)
            .build()
            .unwrap();
        assert!(runtime_tool_names(&runtime).contains(&"list_skills_tool".to_string()));
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_disable_skill_prompt_injection_builds() {
        let client = make_client();
        let runtime = AgentBuilder::new(client)
            .register_skill(ToolSkill)
            .disable_skill_prompt_injection()
            .build()
            .unwrap();
        // Tool still registered; prompt injection skipped.
        assert!(runtime_tool_names(&runtime).contains(&"skill_provided_tool".to_string()));
    }
}

// ── Agent instructions tests ──

#[test]
fn test_build_agent_instructions_prompt_reads_files() {
    let tmp = tempfile::tempdir().unwrap();
    let file1 = tmp.path().join("CLAUDE.md");
    let file2 = tmp.path().join("INSTRUCTIONS.md");
    std::fs::write(&file1, "# User instructions\nBe helpful.").unwrap();
    std::fs::write(&file2, "# Project instructions\nFollow conventions.").unwrap();

    let prompt = build_agent_instructions_prompt(&[file1, file2]);
    assert!(prompt.is_some());
    let prompt = prompt.unwrap();
    // Higher priority (later entries) appear first
    assert!(prompt.starts_with("# Project instructions"));
    assert!(prompt.contains("# User instructions"));
    assert!(prompt.contains("Be helpful."));
    assert!(prompt.contains("Follow conventions."));
}

#[test]
fn test_build_agent_instructions_prompt_skips_missing_files() {
    let prompt = build_agent_instructions_prompt(&[
        PathBuf::from("/nonexistent/CLAUDE.md"),
        PathBuf::from("/nonexistent/INSTRUCTIONS.md"),
    ]);
    assert!(prompt.is_none());
}

#[test]
fn test_build_agent_instructions_prompt_skips_empty_files() {
    let tmp = tempfile::tempdir().unwrap();
    let file = tmp.path().join("empty.md");
    std::fs::write(&file, "   \n  ").unwrap();

    let prompt = build_agent_instructions_prompt(&[file]);
    assert!(prompt.is_none());
}