agent-works 0.10.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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::Arc;

use agent_base::{AgentResult, AgentRuntime, Tool};

#[cfg(feature = "multi_agent")]
use crate::multi_agent::{MultiAgentConfig, MultiAgentRuntime};

#[cfg(feature = "memory")]
use crate::memory::{MemoryConfig, MemoryStore};

#[cfg(feature = "skill")]
use crate::skill::{LazySkillPrompter, Skill, SkillPrompter};

/// Read agent instruction files and build a combined prompt section.
///
/// Files are read in order; later entries have higher priority and appear
/// first in the output. Missing files are silently skipped.
fn build_agent_instructions_prompt(paths: &[PathBuf]) -> Option<String> {
    let mut sections = Vec::new();

    for path in paths {
        if let Ok(content) = std::fs::read_to_string(path) {
            let trimmed = content.trim();
            if !trimmed.is_empty() {
                sections.push(trimmed.to_string());
            }
        }
    }

    if sections.is_empty() {
        return None;
    }

    // Later entries (higher priority) appear first
    sections.reverse();
    Some(sections.join("\n\n---\n\n"))
}

/// Factory type for creating multi-agent tools from a MultiAgentRuntime.
#[cfg(feature = "multi_agent")]
pub type MultiAgentToolFactory =
    Arc<dyn Fn(Arc<MultiAgentRuntime>) -> Vec<Arc<dyn Tool>> + Send + Sync>;

/// Factory type for creating a skill detail tool from skills and a tool name.
#[cfg(feature = "skill")]
pub type SkillDetailToolFactory =
    Arc<dyn Fn(Vec<Arc<dyn Skill>>, String) -> Arc<dyn Tool> + Send + Sync>;

/// Factory type for creating a list-skills tool from a SkillRegistry.
#[cfg(feature = "skill")]
pub type ListSkillsToolFactory =
    Arc<dyn Fn(Arc<crate::skill::SkillRegistry>) -> Arc<dyn Tool> + Send + Sync>;

pub struct AgentBuilder {
    inner: agent_base::AgentBuilder,
    client: Arc<dyn agent_base::llm_trait::LlmProvider>,
    system_prompt: Option<String>,
    tool_names: HashSet<String>,
    /// Business tools to pass to child agents (all registered tools).
    business_tools: Vec<Arc<dyn Tool>>,
    /// Multi-agent configuration (None = disabled).
    #[cfg(feature = "multi_agent")]
    multi_agent_config: Option<MultiAgentConfig>,
    /// Factory to create multi-agent tools (injected by phi-kernel-tools).
    #[cfg(feature = "multi_agent")]
    multi_agent_tool_factory: Option<MultiAgentToolFactory>,
    /// Error recovery (stored for multi-agent child inheritance).
    error_recovery: Option<Arc<dyn agent_base::ToolErrorRecovery>>,
    /// Language preference.
    language: Option<agent_base::Language>,
    #[cfg(feature = "skill")]
    skills: Vec<Arc<dyn Skill>>,
    #[cfg(feature = "skill")]
    skill_prompter: Option<Arc<dyn SkillPrompter>>,
    #[cfg(feature = "skill")]
    skill_detail_tool_name: String,
    /// Optional: inject a custom skill-detail tool (old tool-based mode).
    /// In default prompt-injection mode, the LLM reads `SKILL.md` via
    /// `read_file` — no dedicated detail tool is needed.
    #[cfg(feature = "skill")]
    skill_detail_tool_factory: Option<SkillDetailToolFactory>,
    #[cfg(feature = "skill")]
    list_skills_tool_factory: Option<ListSkillsToolFactory>,
    #[cfg(feature = "skill")]
    disable_skill_prompt_injection: bool,
    /// Optional inline context compactor for the react loop.
    context_compactor: Option<Arc<dyn agent_base::ContextCompaction>>,
    /// Paths to agent instruction files (e.g., CLAUDE.md, INSTRUCTIONS.md).
    /// These files are read at build time and appended to the system prompt.
    /// Supports multiple paths (user-level + project-level); later entries
    /// have higher priority and appear first in the prompt.
    agent_instructions_paths: Vec<PathBuf>,
    /// Memory configuration (Phase 9b). `None` = memory disabled: no memory
    /// tools registered, no memory prompt injected (opt-in by design).
    #[cfg(feature = "memory")]
    memory_config: Option<MemoryConfig>,
}

impl AgentBuilder {
    pub fn new(client: Arc<dyn agent_base::llm_trait::LlmProvider>) -> Self {
        Self {
            inner: agent_base::AgentBuilder::new(client.clone()),
            client,
            system_prompt: None,
            tool_names: HashSet::new(),
            business_tools: Vec::new(),
            #[cfg(feature = "multi_agent")]
            multi_agent_config: None,
            #[cfg(feature = "multi_agent")]
            multi_agent_tool_factory: None,
            error_recovery: None,
            language: None,
            #[cfg(feature = "skill")]
            skills: Vec::new(),
            #[cfg(feature = "skill")]
            skill_prompter: None,
            #[cfg(feature = "skill")]
            skill_detail_tool_name: "get_skill_detail".to_string(),
            #[cfg(feature = "skill")]
            skill_detail_tool_factory: None,
            #[cfg(feature = "skill")]
            list_skills_tool_factory: None,
            #[cfg(feature = "skill")]
            disable_skill_prompt_injection: false,
            context_compactor: None,
            agent_instructions_paths: Vec::new(),
            #[cfg(feature = "memory")]
            memory_config: None,
        }
    }

    /// Enable multi-agent support with the given configuration.
    ///
    /// Also sets the tool factory to create the 5 multi-agent tools.
    /// Callers should use `phi_kernel_tools::multi_agent::create_all_tools` as the factory.
    #[cfg(feature = "multi_agent")]
    pub fn with_multi_agent(mut self, config: MultiAgentConfig) -> Self {
        self.multi_agent_config = Some(config);
        self
    }

    /// Disable multi-agent support.
    ///
    /// Removes any previously set multi-agent configuration. No multi-agent tools
    /// will be registered and the system prompt will not mention multi-agent capabilities.
    #[cfg(feature = "multi_agent")]
    pub fn without_multi_agent(mut self) -> Self {
        self.multi_agent_config = None;
        self.multi_agent_tool_factory = None;
        self
    }

    /// Set a custom factory for creating multi-agent tools.
    ///
    /// The factory receives the `MultiAgentRuntime` and returns the tools to register.
    /// If not set but multi-agent is enabled, no tools are registered (caller must
    /// set this for multi-agent to work).
    #[cfg(feature = "multi_agent")]
    pub fn with_multi_agent_tool_factory(mut self, factory: MultiAgentToolFactory) -> Self {
        self.multi_agent_tool_factory = Some(factory);
        self
    }

    /// Set a custom factory for creating the skill detail tool.
    ///
    /// The factory receives the skill list and tool name, and returns the tool.
    /// If not set but skills are registered, no detail tool is added.
    #[cfg(feature = "skill")]
    pub fn with_skill_detail_tool_factory(mut self, factory: SkillDetailToolFactory) -> Self {
        self.skill_detail_tool_factory = Some(factory);
        self
    }

    /// Set a custom factory for creating the list-skills tool.
    ///
    /// The factory receives the SkillRegistry and returns the tool.
    #[cfg(feature = "skill")]
    pub fn with_list_skills_tool_factory(mut self, factory: ListSkillsToolFactory) -> Self {
        self.list_skills_tool_factory = Some(factory);
        self
    }

    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
        let prompt = prompt.into();
        self.inner = self.inner.system_prompt(prompt.clone());
        self.system_prompt = Some(prompt);
        self
    }

    pub fn enable_thought(self, enable: bool) -> Self {
        Self {
            inner: self.inner.enable_thought(enable),
            ..self
        }
    }

    pub fn reasoning(self, config: agent_base::ReasoningConfig) -> Self {
        Self {
            inner: self.inner.reasoning(config),
            ..self
        }
    }

    pub fn enable_thinking(self, enable: bool) -> Self {
        Self {
            inner: self.inner.enable_thinking(enable),
            ..self
        }
    }

    pub fn thinking_budget(self, budget: u64) -> Self {
        Self {
            inner: self.inner.thinking_budget(budget),
            ..self
        }
    }

    pub fn tool_timeout(self, timeout_ms: u64) -> Self {
        Self {
            inner: self.inner.tool_timeout(timeout_ms),
            ..self
        }
    }

    pub fn max_tool_output_chars(self, max_chars: usize) -> Self {
        Self {
            inner: self.inner.max_tool_output_chars(max_chars),
            ..self
        }
    }

    pub fn max_sessions(self, max: usize) -> Self {
        Self {
            inner: self.inner.max_sessions(max),
            ..self
        }
    }

    pub fn max_turns_per_session(self, max: usize) -> Self {
        Self {
            inner: self.inner.max_turns_per_session(max),
            ..self
        }
    }

    pub fn execution_max_turns(self, max: u32) -> Self {
        Self {
            inner: self.inner.execution_max_turns(max),
            ..self
        }
    }

    pub fn max_message_tokens(self, max: usize) -> Self {
        Self {
            inner: self.inner.max_message_tokens(max),
            ..self
        }
    }

    pub fn register_tool(mut self, tool: impl Tool + 'static) -> Self {
        let tool_arc: Arc<dyn Tool> = Arc::new(tool);
        self.tool_names.insert(tool_arc.name().to_string());
        self.business_tools.push(tool_arc.clone());
        self.inner = self.inner.register_tool_arc(tool_arc);
        self
    }

    pub fn register_tool_arc(mut self, tool: Arc<dyn Tool>) -> Self {
        self.tool_names.insert(tool.name().to_string());
        self.business_tools.push(tool.clone());
        self.inner = self.inner.register_tool_arc(tool);
        self
    }

    pub fn approval_handler(self, handler: Arc<dyn agent_base::ApprovalHandler>) -> Self {
        Self {
            inner: self.inner.approval_handler(handler),
            ..self
        }
    }

    pub fn tool_policy(self, policy: Arc<dyn agent_base::ToolPolicy>) -> Self {
        Self {
            inner: self.inner.tool_policy(policy),
            ..self
        }
    }

    pub fn middleware(self, mw: impl agent_base::Middleware + 'static) -> Self {
        Self {
            inner: self.inner.middleware(mw),
            ..self
        }
    }

    pub fn guard(self, guard: impl agent_base::ReactLoopGuard + 'static) -> Self {
        Self {
            inner: self.inner.guard(guard),
            ..self
        }
    }

    pub fn context_window(self, max_tokens: usize) -> Self {
        Self {
            inner: self.inner.context_window(max_tokens),
            ..self
        }
    }

    pub fn context_window_manager(self, manager: agent_base::ContextWindowManager) -> Self {
        Self {
            inner: self.inner.context_window_manager(manager),
            ..self
        }
    }

    pub fn response_format(self, format: agent_base::ResponseFormat) -> Self {
        Self {
            inner: self.inner.response_format(format),
            ..self
        }
    }

    pub fn llm_retry(self, retry: agent_base::RetryConfig) -> Self {
        Self {
            inner: self.inner.llm_retry(retry),
            ..self
        }
    }

    pub fn session_store(self, store: Arc<dyn agent_base::SessionStore>) -> Self {
        Self {
            inner: self.inner.session_store(store),
            ..self
        }
    }

    pub fn error_recovery(mut self, recovery: Arc<dyn agent_base::ToolErrorRecovery>) -> Self {
        self.error_recovery = Some(recovery.clone());
        self.inner = self.inner.error_recovery(recovery);
        self
    }

    pub fn tool_error_retry_prompt(self, prompt: impl Into<String>) -> Self {
        Self {
            inner: self.inner.tool_error_retry_prompt(prompt),
            ..self
        }
    }

    pub fn language(mut self, language: agent_base::Language) -> Self {
        self.language = Some(language.clone());
        self.inner = self.inner.language(language);
        self
    }

    /// Set an inline context compactor for the react loop.
    ///
    /// When set, the react loop will check token count after each tool turn
    /// and compact the session if it exceeds the configured threshold.
    pub fn context_compactor(mut self, compactor: Arc<dyn agent_base::ContextCompaction>) -> Self {
        self.context_compactor = Some(compactor);
        self
    }

    pub fn event_bus_capacity(self, capacity: usize) -> Self {
        Self {
            inner: self.inner.event_bus_capacity(capacity),
            ..self
        }
    }

    pub fn session_id_generator(
        self,
        generator: Arc<dyn agent_base::types::SessionIdGenerator>,
    ) -> Self {
        Self {
            inner: self.inner.session_id_generator(generator),
            ..self
        }
    }

    /// Conditionally apply a transformation when `value` is `Some`.
    ///
    /// This is a convenience for option-chaining builder patterns:
    ///
    /// ```ignore
    /// builder.apply_if(args.thinking_budget, |b, budget| b.thinking_budget(budget))
    /// ```
    pub fn apply_if<T>(self, value: Option<T>, f: impl FnOnce(Self, T) -> Self) -> Self {
        match value {
            Some(v) => f(self, v),
            None => self,
        }
    }

    #[cfg(feature = "skill")]
    pub fn register_skill(mut self, skill: impl Skill + 'static) -> Self {
        self.skills.push(Arc::new(skill));
        self
    }

    #[cfg(feature = "skill")]
    pub fn register_skills(mut self, skills: Vec<Arc<dyn Skill>>) -> Self {
        self.skills.extend(skills);
        self
    }

    #[cfg(feature = "skill")]
    pub fn skill_prompter(mut self, prompter: Arc<dyn SkillPrompter>) -> Self {
        self.skill_prompter = Some(prompter);
        self
    }

    #[cfg(feature = "skill")]
    pub fn disable_skill_prompt_injection(mut self) -> Self {
        self.disable_skill_prompt_injection = true;
        self
    }

    /// Set paths to agent instruction files (e.g., CLAUDE.md, INSTRUCTIONS.md).
    ///
    /// These files are read at build time and appended to the system prompt.
    /// Supports multiple paths (user-level + project-level); later entries
    /// have higher priority and appear first in the prompt.
    ///
    /// Example:
    /// ```rust,ignore
    /// use std::path::PathBuf;
    /// use agent_works::AgentBuilder;
    /// let builder = AgentBuilder::new();
    /// let builder = builder.agent_instructions_paths(vec![
    ///     PathBuf::from("~/.claude/CLAUDE.md"),  // user-level
    ///     PathBuf::from(".claude/CLAUDE.md"),     // project-level
    /// ]);
    /// ```
    pub fn agent_instructions_paths(mut self, paths: Vec<PathBuf>) -> Self {
        self.agent_instructions_paths = paths;
        self
    }

    #[cfg(feature = "skill")]
    pub fn skill_detail_tool_name(mut self, name: impl Into<String>) -> Self {
        self.skill_detail_tool_name = name.into();
        self
    }

    /// Enable persistent auto-memory (Phase 9b) with the given configuration.
    ///
    /// Registers the four `memory_*` tools and appends the memory prompt
    /// (MEMORY.md index snapshot + tool guidance) to the system prompt at
    /// build time. Opt-in: without this call no memory tools exist and the
    /// prompt is untouched.
    #[cfg(feature = "memory")]
    pub fn memory_config(mut self, config: MemoryConfig) -> Self {
        self.memory_config = Some(config);
        self
    }

    /// Disable auto-memory (removes any previously set configuration).
    #[cfg(feature = "memory")]
    pub fn without_memory_config(mut self) -> Self {
        self.memory_config = None;
        self
    }

    /// Register the four memory tools and append the memory prompt (index
    /// snapshot + tool guidance) to the system prompt. No-op when no memory
    /// configuration was set. Called from every `build_*` path right after
    /// the agent-instructions (CLAUDE.md) injection.
    #[cfg(feature = "memory")]
    fn apply_memory_config(mut self) -> Self {
        let Some(config) = self.memory_config.take() else {
            return self;
        };

        let store = Arc::new(MemoryStore::new(
            config.memory_root.clone(),
            config.index_filename.clone(),
        ));

        // Register the memory tools unless the consumer already took the name.
        for tool in crate::tools::create_memory_tools(Arc::clone(&store)) {
            let tool_name = tool.name().to_string();
            if self.tool_names.contains(&tool_name) {
                tracing::warn!(tool = %tool_name, "memory tool name conflict; skipping registration");
                continue;
            }
            self.tool_names.insert(tool_name);
            self.inner = self.inner.register_tool_arc(tool);
        }

        // Inject the index snapshot + tool guidance into the system prompt.
        let index = store.read_index();
        if index.len() > 10_240 {
            tracing::warn!(
                index_bytes = index.len(),
                root = %config.memory_root.display(),
                "memory index is unusually large (>10KB); consider cleaning up stale memories"
            );
        }
        let mem_prompt = build_memory_system_prompt_with_config(&config, &index);
        tracing::info!(
            memory_root = %config.memory_root.display(),
            index_bytes = index.len(),
            tools = 4,
            "injecting memory prompt + tools into system prompt"
        );
        let new_prompt = match self.system_prompt.take() {
            Some(existing) => format!("{existing}\n\n---\n\n{mem_prompt}"),
            None => mem_prompt,
        };
        tracing::info!(
            prompt_len = new_prompt.len(),
            "system prompt after memory injection (full text logged at DEBUG level)"
        );
        tracing::debug!(system_prompt = %new_prompt, "full system prompt after memory injection");
        self.system_prompt = Some(new_prompt.clone());
        self.inner = self.inner.system_prompt(new_prompt);
        self
    }

    // ── Build ──

    pub fn build(self) -> AgentResult<AgentRuntime> {
        #[cfg(feature = "skill")]
        {
            self.build_with_skills()
        }
        #[cfg(not(feature = "skill"))]
        {
            self.build_inner()
        }
    }

    /// Build the runtime and return the multi-agent runtime (if enabled).
    ///
    /// Same as [`build`](Self::build) but also returns the `MultiAgentRuntime`
    /// created during setup. Callers that need to start the watcher task or
    /// access the mailbox should use this method.
    #[cfg(feature = "multi_agent")]
    pub fn build_with_ma(self) -> AgentResult<(AgentRuntime, Option<Arc<MultiAgentRuntime>>)> {
        #[cfg(feature = "skill")]
        {
            self.build_with_skills_ma()
        }
        #[cfg(not(feature = "skill"))]
        {
            self.build_inner_ma()
        }
    }

    #[allow(dead_code, unused_mut)]
    fn build_inner(mut self) -> AgentResult<AgentRuntime> {
        // Inject default guard if none was set by the consumer.
        // Uses the same LLM client for the judge (enabled by default).
        if self.inner.get_guard().is_none() {
            self.inner = self
                .inner
                .guard(crate::guard::DefaultGuard::with_llm_client(
                    crate::guard::DefaultGuardConfig::default(),
                    self.client.clone(),
                ));
        }

        // Inject agent instruction files (e.g., CLAUDE.md) into system prompt
        if !self.agent_instructions_paths.is_empty()
            && let Some(instructions) =
                build_agent_instructions_prompt(&self.agent_instructions_paths)
        {
            tracing::info!(
                paths = ?self.agent_instructions_paths,
                instructions_len = instructions.len(),
                "injecting agent instructions into system prompt"
            );
            let new_prompt = match self.system_prompt.take() {
                Some(existing) => format!("{}\n\n---\n\n{}", existing, instructions),
                None => instructions,
            };
            self.system_prompt = Some(new_prompt.clone());
            self.inner = self.inner.system_prompt(new_prompt);
        }

        // Register memory tools + inject memory prompt (Phase 9b)
        #[cfg(feature = "memory")]
        {
            self = self.apply_memory_config();
        }

        #[cfg(feature = "multi_agent")]
        let lang = self.language.clone().unwrap_or_default();
        #[cfg(feature = "multi_agent")]
        let business_tools = std::mem::take(&mut self.business_tools);
        #[cfg(feature = "multi_agent")]
        let error_recovery = self.error_recovery.clone();
        #[cfg(feature = "multi_agent")]
        let tool_names = self.tool_names.clone();

        #[cfg(feature = "multi_agent")]
        let ma_config = self.multi_agent_config.clone();
        #[cfg(feature = "multi_agent")]
        let ma_tool_factory = self.multi_agent_tool_factory.take();

        // Inject multi-agent prompt before build
        #[cfg(feature = "multi_agent")]
        if ma_config.as_ref().map(|c| c.enabled).unwrap_or(false) {
            let ma_prompt = build_multi_agent_system_prompt();
            let new_prompt = match self.system_prompt.take() {
                Some(existing) => format!("{}\n\n---\n\n{}", existing, ma_prompt),
                None => ma_prompt,
            };
            self.inner = self.inner.system_prompt(new_prompt);
        }

        // Inject inline context compactor if set
        if let Some(compactor) = self.context_compactor.take() {
            self.inner = self.inner.context_compactor(compactor);
        }

        let runtime = self.inner.build()?;

        // Post-build: register multi-agent tools if enabled and factory is set
        #[cfg(feature = "multi_agent")]
        if let Some(config) = ma_config
            && config.enabled
        {
            setup_multi_agent(
                &runtime,
                config,
                lang,
                business_tools,
                error_recovery,
                &tool_names,
                ma_tool_factory,
            )?;
        }

        Ok(runtime)
    }

    /// Like `build_inner` but also returns the `MultiAgentRuntime`.
    #[cfg(feature = "multi_agent")]
    #[allow(dead_code, unused_mut)]
    fn build_inner_ma(mut self) -> AgentResult<(AgentRuntime, Option<Arc<MultiAgentRuntime>>)> {
        if self.inner.get_guard().is_none() {
            self.inner = self
                .inner
                .guard(crate::guard::DefaultGuard::with_llm_client(
                    crate::guard::DefaultGuardConfig::default(),
                    self.client.clone(),
                ));
        }

        // Register memory tools + inject memory prompt (Phase 9b)
        #[cfg(feature = "memory")]
        {
            self = self.apply_memory_config();
        }

        let lang = self.language.clone().unwrap_or_default();
        let business_tools = std::mem::take(&mut self.business_tools);
        let error_recovery = self.error_recovery.clone();
        let tool_names = self.tool_names.clone();
        let ma_config = self.multi_agent_config.clone();
        let ma_tool_factory = self.multi_agent_tool_factory.take();

        if ma_config.as_ref().map(|c| c.enabled).unwrap_or(false) {
            let ma_prompt = build_multi_agent_system_prompt();
            let new_prompt = match self.system_prompt.take() {
                Some(existing) => format!("{}\n\n---\n\n{}", existing, ma_prompt),
                None => ma_prompt,
            };
            self.inner = self.inner.system_prompt(new_prompt);
        }

        if let Some(compactor) = self.context_compactor.take() {
            self.inner = self.inner.context_compactor(compactor);
        }

        let runtime = self.inner.build()?;

        let ma_runtime_out = if let Some(config) = ma_config
            && config.enabled
        {
            Some(setup_multi_agent(
                &runtime,
                config,
                lang,
                business_tools,
                error_recovery,
                &tool_names,
                ma_tool_factory,
            )?)
        } else {
            None
        };

        Ok((runtime, ma_runtime_out))
    }

    /// Build the runtime with skill support.
    ///
    /// # Runtime requirement
    ///
    /// This method uses [`tokio::task::block_in_place`] to populate the skill
    /// registry from a synchronous context. It **requires** a multi-threaded
    /// tokio runtime. Calling it on a `#[tokio::main]` single-threaded
    /// (`current_thread`) runtime will panic.
    ///
    /// The phi-agent CLI and all examples use the default multi-threaded runtime,
    /// so this is safe in practice.
    #[cfg(feature = "skill")]
    fn build_with_skills(mut self) -> AgentResult<AgentRuntime> {
        // Inject default guard if none was set by the consumer.
        // Uses the same LLM client for the judge (enabled by default).
        if self.inner.get_guard().is_none() {
            self.inner = self
                .inner
                .guard(crate::guard::DefaultGuard::with_llm_client(
                    crate::guard::DefaultGuardConfig::default(),
                    self.client.clone(),
                ));
        }

        // Inject agent instruction files (e.g., CLAUDE.md) into system prompt
        if !self.agent_instructions_paths.is_empty()
            && let Some(instructions) =
                build_agent_instructions_prompt(&self.agent_instructions_paths)
        {
            tracing::info!(
                paths = ?self.agent_instructions_paths,
                instructions_len = instructions.len(),
                "injecting agent instructions into system prompt"
            );
            let new_prompt = match self.system_prompt.take() {
                Some(existing) => format!("{}\n\n---\n\n{}", existing, instructions),
                None => instructions,
            };
            self.system_prompt = Some(new_prompt.clone());
            self.inner = self.inner.system_prompt(new_prompt);
        }

        // Register memory tools + inject memory prompt (Phase 9b)
        #[cfg(feature = "memory")]
        {
            self = self.apply_memory_config();
        }

        let mut ab = self.inner;
        #[cfg(feature = "multi_agent")]
        let lang = self.language.clone().unwrap_or_default();
        #[cfg(feature = "multi_agent")]
        let business_tools = std::mem::take(&mut self.business_tools);
        #[cfg(feature = "multi_agent")]
        let error_recovery = self.error_recovery.clone();
        #[cfg(feature = "multi_agent")]
        let tool_names = self.tool_names.clone();

        #[cfg(feature = "multi_agent")]
        let ma_config = self.multi_agent_config.clone();
        #[cfg(feature = "multi_agent")]
        let ma_tool_factory = self.multi_agent_tool_factory.take();

        // Process skills
        if !self.skills.is_empty() {
            let prompter: Arc<dyn SkillPrompter> = self
                .skill_prompter
                .take()
                .unwrap_or_else(|| Arc::new(LazySkillPrompter::new()));

            let mut skill_refs: Vec<Arc<dyn Skill>> = Vec::new();

            for skill in self.skills {
                for tool in skill.tools() {
                    let tool_name = tool.name().to_string();
                    if self.tool_names.contains(&tool_name) {
                        return Err(agent_base::AgentError::internal(format!(
                            "Tool name conflict: `{}` (Skill `{}`)",
                            tool_name,
                            skill.name()
                        )));
                    }
                    self.tool_names.insert(tool_name);
                    ab = ab.register_tool_arc(tool);
                }
                skill_refs.push(skill);
            }

            if !self.disable_skill_prompt_injection {
                let skill_prompt = prompter.build_prompt(&skill_refs, &self.skill_detail_tool_name);
                if !skill_prompt.is_empty() {
                    let new_prompt = match self.system_prompt.take() {
                        Some(existing) => format!("{}\n\n---\n\n{}", existing, skill_prompt),
                        None => skill_prompt,
                    };
                    self.system_prompt = Some(new_prompt.clone());
                    ab = ab.system_prompt(new_prompt);
                }
            }

            // Use injected factory if available, otherwise skip — prompt-injection
            // mode uses read_file instead of a dedicated detail tool.
            if let Some(factory) = self.skill_detail_tool_factory.take() {
                let detail_tool = factory(skill_refs.clone(), self.skill_detail_tool_name);
                ab = ab.register_tool_arc(detail_tool);
            }

            // Create SkillRegistry and populate it for the list-skills tool
            if let Some(factory) = self.list_skills_tool_factory.take() {
                let registry = Arc::new(crate::skill::SkillRegistry::new());
                for skill in &skill_refs {
                    tokio::task::block_in_place(|| {
                        tokio::runtime::Handle::current().block_on(async {
                            registry.register(skill.clone()).await;
                        })
                    });
                }
                let list_tool = factory(registry);
                ab = ab.register_tool_arc(list_tool);
            }
        }

        // Inject multi-agent prompt
        #[cfg(feature = "multi_agent")]
        if ma_config.as_ref().map(|c| c.enabled).unwrap_or(false) {
            let ma_prompt = build_multi_agent_system_prompt();
            let new_prompt = match self.system_prompt.take() {
                Some(existing) => format!("{}\n\n---\n\n{}", existing, ma_prompt),
                None => ma_prompt,
            };
            ab = ab.system_prompt(new_prompt);
        }

        // Inject inline context compactor if set
        if let Some(compactor) = self.context_compactor.take() {
            ab = ab.context_compactor(compactor);
        }

        let runtime = ab.build()?;

        // Post-build: register multi-agent tools
        #[cfg(feature = "multi_agent")]
        if let Some(config) = ma_config
            && config.enabled
        {
            setup_multi_agent(
                &runtime,
                config,
                lang,
                business_tools,
                error_recovery,
                &tool_names,
                ma_tool_factory,
            )?;
        }

        Ok(runtime)
    }

    /// Like `build_with_skills` but also returns the `MultiAgentRuntime`.
    #[cfg(all(feature = "skill", feature = "multi_agent"))]
    fn build_with_skills_ma(
        mut self,
    ) -> AgentResult<(AgentRuntime, Option<Arc<MultiAgentRuntime>>)> {
        if self.inner.get_guard().is_none() {
            self.inner = self
                .inner
                .guard(crate::guard::DefaultGuard::with_llm_client(
                    crate::guard::DefaultGuardConfig::default(),
                    self.client.clone(),
                ));
        }

        // Inject agent instruction files (e.g., CLAUDE.md) into system prompt
        if !self.agent_instructions_paths.is_empty()
            && let Some(instructions) =
                build_agent_instructions_prompt(&self.agent_instructions_paths)
        {
            tracing::info!(
                paths = ?self.agent_instructions_paths,
                instructions_len = instructions.len(),
                "injecting agent instructions into system prompt"
            );
            let new_prompt = match self.system_prompt.take() {
                Some(existing) => format!("{}\n\n---\n\n{}", existing, instructions),
                None => instructions,
            };
            self.system_prompt = Some(new_prompt.clone());
            self.inner = self.inner.system_prompt(new_prompt);
        }

        // Register memory tools + inject memory prompt (Phase 9b)
        #[cfg(feature = "memory")]
        {
            self = self.apply_memory_config();
        }

        let mut ab = self.inner;
        let lang = self.language.clone().unwrap_or_default();
        let business_tools = std::mem::take(&mut self.business_tools);
        let error_recovery = self.error_recovery.clone();
        let tool_names = self.tool_names.clone();
        let ma_config = self.multi_agent_config.clone();
        let ma_tool_factory = self.multi_agent_tool_factory.take();

        // Process skills
        if !self.skills.is_empty() {
            let prompter: Arc<dyn SkillPrompter> = self
                .skill_prompter
                .take()
                .unwrap_or_else(|| Arc::new(LazySkillPrompter::new()));

            let mut skill_refs: Vec<Arc<dyn Skill>> = Vec::new();

            for skill in self.skills {
                for tool in skill.tools() {
                    let tool_name = tool.name().to_string();
                    if self.tool_names.contains(&tool_name) {
                        return Err(agent_base::AgentError::internal(format!(
                            "Tool name conflict: `{}` (Skill `{}`)",
                            tool_name,
                            skill.name()
                        )));
                    }
                    self.tool_names.insert(tool_name);
                    ab = ab.register_tool_arc(tool);
                }
                skill_refs.push(skill);
            }

            if !self.disable_skill_prompt_injection {
                let skill_prompt = prompter.build_prompt(&skill_refs, &self.skill_detail_tool_name);
                if !skill_prompt.is_empty() {
                    let new_prompt = match self.system_prompt.take() {
                        Some(existing) => format!("{}\n\n---\n\n{}", existing, skill_prompt),
                        None => skill_prompt,
                    };
                    self.system_prompt = Some(new_prompt.clone());
                    ab = ab.system_prompt(new_prompt);
                }
            }

            if let Some(factory) = self.skill_detail_tool_factory.take() {
                let detail_tool = factory(skill_refs.clone(), self.skill_detail_tool_name);
                ab = ab.register_tool_arc(detail_tool);
            }

            if let Some(factory) = self.list_skills_tool_factory.take() {
                let registry = Arc::new(crate::skill::SkillRegistry::new());
                for skill in &skill_refs {
                    tokio::task::block_in_place(|| {
                        tokio::runtime::Handle::current().block_on(async {
                            registry.register(skill.clone()).await;
                        })
                    });
                }
                let list_tool = factory(registry);
                ab = ab.register_tool_arc(list_tool);
            }
        }

        // Inject multi-agent prompt
        if ma_config.as_ref().map(|c| c.enabled).unwrap_or(false) {
            let ma_prompt = build_multi_agent_system_prompt();
            let new_prompt = match self.system_prompt.take() {
                Some(existing) => format!("{}\n\n---\n\n{}", existing, ma_prompt),
                None => ma_prompt,
            };
            ab = ab.system_prompt(new_prompt);
        }

        if let Some(compactor) = self.context_compactor.take() {
            ab = ab.context_compactor(compactor);
        }

        let runtime = ab.build()?;

        let ma_runtime_out = if let Some(config) = ma_config
            && config.enabled
        {
            Some(setup_multi_agent(
                &runtime,
                config,
                lang,
                business_tools,
                error_recovery,
                &tool_names,
                ma_tool_factory,
            )?)
        } else {
            None
        };

        Ok((runtime, ma_runtime_out))
    }
}

/// Set up the MultiAgentRuntime, event bridge, and register tools on an already-built runtime.
///
/// # Safety / Runtime Requirement
///
/// This function uses [`tokio::task::block_in_place`] to register tools synchronously.
/// It **requires** a multi-threaded tokio runtime. Calling it on a
/// `#[tokio::main]` single-threaded (`current_thread`) runtime will panic.
///
/// The phi-agent CLI and all examples use the default multi-threaded runtime,
/// so this is safe in practice.
#[cfg(feature = "multi_agent")]
pub fn setup_multi_agent(
    runtime: &AgentRuntime,
    config: MultiAgentConfig,
    lang: agent_base::Language,
    business_tools: Vec<Arc<dyn Tool>>,
    error_recovery: Option<Arc<dyn agent_base::ToolErrorRecovery>>,
    existing_tool_names: &HashSet<String>,
    tool_factory: Option<MultiAgentToolFactory>,
) -> AgentResult<Arc<MultiAgentRuntime>> {
    let client = runtime.provider();
    let cancel_token = runtime.cancel_token();
    let tool_policy = runtime.tool_policy().cloned();
    let approval_handler = runtime.approval_handler().cloned();

    let ma_runtime = Arc::new(MultiAgentRuntime::new(
        config.clone(),
        client,
        business_tools,
        cancel_token,
        error_recovery,
        lang,
        tool_policy,
        approval_handler,
    ));

    // Set parent session manager for fork_history support
    ma_runtime.set_session_manager(Arc::new(runtime.session_manager().clone()));

    // Set up event bridge: child events → parent event bus
    let (event_tx, mut event_rx) =
        tokio::sync::mpsc::unbounded_channel::<agent_base::RuntimeEvent>();
    ma_runtime.set_event_sender(event_tx);
    let parent_runtime = runtime.clone();
    tokio::spawn(async move {
        while let Some(event) = event_rx.recv().await {
            parent_runtime.emit_event(event);
        }
    });

    // Register multi-agent tools if a factory is provided
    if let Some(factory) = tool_factory {
        let tools = factory(ma_runtime.clone());
        let registry = runtime.tools_mut();
        let mut reg = tokio::task::block_in_place(|| registry.blocking_write());
        for tool in tools {
            let tool_name = tool.name().to_string();
            if !existing_tool_names.contains(&tool_name) {
                reg.register_arc(tool);
            }
        }
        drop(reg);
    }

    Ok(ma_runtime)
}

/// Build the multi-agent system prompt guidance for the main agent.
#[cfg(feature = "multi_agent")]
pub fn build_multi_agent_system_prompt() -> String {
    r#"## Multi-Agent Capabilities

You 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.

### Tools

- `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"})`.
- `send_message`: Send follow-up context or tasks to a sub-agent (`trigger: true` starts execution).
- `list_agents`: List active sub-agents with their assigned task and status — use it to answer "what is agent X doing?".
- `close_agent`: Close a sub-agent when done.

### How Results Reach You

Sub-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.

### How Sub-Agents Work

Sub-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.

### When to Spawn

- Parallel tasks: analyze multiple codebases, compare implementations, etc.
- Tasks you want to delegate while you continue other work

### When NOT to Spawn

- Simple lookups (just use read_file or repo_map directly)
- Tasks that need your current conversation context"#
        .to_string()
}

/// Build the memory system prompt guidance.
///
/// Tells the LLM how to use the file-based persistent memory system.
/// Memory is stored as markdown files — the LLM uses `read_file` / `write_file`
/// to manage them, following the same convention as Claude Code Memory.
///
/// This is prompt-injection only — no dedicated memory tools are registered.
/// The LLM uses the general-purpose file tools to read/write memory files.
pub fn build_memory_system_prompt() -> String {
    r#"## Memory

You have a persistent file-based memory at `.phi/memory/`. Use `read_file` and `write_file` to manage it — there are no dedicated memory tools.

### How Memory Works

- `MEMORY.md` is the index — it lists all memories with one-line descriptions. Read it first when you need to recall something.
- Each memory is a separate `.md` file with YAML frontmatter:
  ```yaml
  ---
  name: <short-kebab-case-slug>
  description: <one-line summary — used to decide relevance during recall>
  metadata:
    node_type: memory
    type: user | feedback | project | reference
  ---

  <the fact or instruction>
  ```
- 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.
- Link related memories with `[[memory-name]]` in the body.
- `user` type = who the user is (role, expertise, preferences).
- `feedback` type = guidance the user has given on how you should work.
- `project` type = ongoing work, goals, or constraints.
- `reference` type = pointers to external resources (URLs, dashboards, tickets).

### When to Use Memory

- The user explicitly asks you to remember something ("remember this", "save that")
- You learn something important about the user's preferences or workflow
- After completing a significant task, save context that would help in future sessions
- The user gives you feedback on how to work — save it as `feedback` type

### When NOT to Use Memory

- For transient information that won't be useful beyond this session
- For facts already recorded in the codebase (code structure, git history, config files)
- For items that only matter to the current conversation

### Pro Tips

- When creating your first memory of a new type, you can read template files for format reference (check `.phi/templates/memory/` if available).
- Keep the MEMORY.md index concise — it's loaded into context every session.
- Before writing a new memory, check if an existing file already covers it — update instead of duplicating.

### Workflow

**To recall:** read `MEMORY.md` → find relevant entries by description → read the specific `.md` files you need.
**To remember:** create a new `.md` file with proper frontmatter → update `MEMORY.md` with a new entry.
**To update:** edit the existing `.md` file (don't create a duplicate).
**To forget:** delete the `.md` file → remove its entry from `MEMORY.md`."#
        .to_string()
}

/// Build the memory system prompt from a [`MemoryConfig`]
/// (Phase 9b).
///
/// Renders `config.prompt_template`, substituting the placeholders:
///
/// - `{memory_root}` — the memory directory path
/// - `{index_content}` — the `MEMORY.md` index snapshot (startup state); an
///   empty index renders as a friendly "no memories yet" line
/// - `{tools_description}` — fixed description of the four `memory_*` tools
///
/// The legacy no-arg [`build_memory_system_prompt`] is kept for callers that
/// don't register memory tools (prompt-injection-only mode).
#[cfg(feature = "memory")]
pub fn build_memory_system_prompt_with_config(
    config: &crate::memory::MemoryConfig,
    index_content: &str,
) -> String {
    let index = if index_content.trim().is_empty() {
        "(no memories yet — memory_write creates the first one)".to_string()
    } else {
        index_content.to_string()
    };
    config
        .prompt_template
        .replace("{memory_root}", &config.memory_root.to_string_lossy())
        .replace("{index_content}", &index)
        .replace(
            "{tools_description}",
            crate::tools::MEMORY_TOOLS_DESCRIPTION,
        )
}

#[cfg(test)]
mod tests {
    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());
    }
}