agpm-cli 0.4.8

AGent Package Manager - A Git-based package manager for coding agents
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
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
//! Markdown templating engine for AGPM resources.
//!
//! This module provides Tera-based templating functionality for Markdown resources,
//! enabling dynamic content generation during installation. It supports safe, sandboxed
//! template rendering with a rich context containing installation metadata.
//!
//! # Overview
//!
//! The templating system allows resource authors to:
//! - Reference other resources by name and type
//! - Access resolved installation paths and versions
//! - Use conditional logic and loops in templates
//! - Read and embed project-specific files (style guides, best practices, etc.)
//!
//! # Template Context
//!
//! Templates are rendered with a structured context containing:
//! - `agpm.resource`: Current resource information (name, type, install path, etc.)
//! - `agpm.deps`: Nested dependency information by resource type and name
//!
//! # Custom Filters
//!
//! - `content`: Read project-specific files (e.g., `{{ 'docs/guide.md' | content }}`)
//!
//! # Syntax Restrictions
//!
//! For security and safety, the following Tera features are disabled:
//! - `{% include %}` tags (no file system access)
//! - `{% extends %}` tags (no template inheritance)
//! - `{% import %}` tags (no external template imports)
//! - Custom functions that access the file system or network (except content filter)
//!
//! # Supported Features
//!
//! - Variable substitution: `{{ agpm.resource.install_path }}`
//! - Conditional logic: `{% if agpm.resource.source %}...{% endif %}`
//! - Loops: `{% for name, dep in agpm.deps.agents %}...{% endfor %}`
//! - Standard Tera filters (string manipulation, formatting)
//! - Project file embedding: `{{ 'path/to/file.md' | content }}`
//! - Literal blocks: Protect template syntax from rendering for documentation
//!
//! # Literal Blocks (Documentation Mode)
//!
//! When writing documentation that includes template syntax examples, you can use
//! `literal` fenced code blocks to protect the content from being rendered:
//!
//! ````markdown
//! # Template Documentation
//!
//! Here's how to use template variables:
//!
//! ```literal
//! {{ agpm.deps.snippets.example.content }}
//! ```
//!
//! The above syntax will be displayed literally, not rendered.
//! ````
//!
//! This is particularly useful for:
//! - Documentation snippets that show template syntax examples
//! - Tutorial content that explains how to use templates
//! - Example code that should not be executed during rendering
//!
//! The content inside `literal` blocks will be:
//! 1. Protected from template rendering (preserved as-is)
//! 2. Wrapped in standard markdown code fences in the output
//! 3. Displayed literally to the end user
//!
//! # Examples
//!
//! ## Basic Variable Substitution
//!
//! ```markdown
//! # {{ agpm.resource.name }}
//!
//! This agent is installed at: `{{ agpm.resource.install_path }}`
//! Version: {{ agpm.resource.version }}
//! ```
//!
//! ## Dependency Content Embedding (v0.4.7+)
//!
//! All dependencies automatically have `.content` field with processed content:
//!
//! ```markdown
//! ---
//! agpm.templating: true
//! dependencies:
//!   snippets:
//!     - path: snippets/best-practices.md
//!       name: best_practices
//! ---
//! # Code Reviewer
//!
//! ## Best Practices
//! {{ agpm.deps.snippets.best_practices.content }}
//! ```
//!
//! ## Project File Filter (v0.4.8+)
//!
//! Read project-specific files using the `content` filter:
//!
//! ```markdown
//! ---
//! agpm.templating: true
//! ---
//! # Team Agent
//!
//! ## Project Style Guide
//! {{ 'project/styleguide.md' | content }}
//!
//! ## Team Conventions
//! {{ 'docs/conventions.txt' | content }}
//! ```
//!
//! ## Combining Dependency Content + Project Files
//!
//! Use both features together for maximum flexibility:
//!
//! ```markdown
//! ---
//! agpm.templating: true
//! dependencies:
//!   snippets:
//!     - path: snippets/rust-patterns.md
//!       name: rust_patterns
//!     - path: snippets/error-handling.md
//!       name: error_handling
//! ---
//! # Rust Code Reviewer
//!
//! ## Shared Patterns (from AGPM repository)
//! {{ agpm.deps.snippets.rust_patterns.content }}
//!
//! ## Project-Specific Style Guide
//! {{ 'project/rust-style.md' | content }}
//!
//! ## Error Handling Best Practices
//! {{ agpm.deps.snippets.error_handling.content }}
//!
//! ## Team Conventions
//! {{ 'docs/team-conventions.txt' | content }}
//! ```
//!
//! **When to use each**:
//! - **Dependency content**: Versioned, shared resources from AGPM repos
//! - **Project files**: Team-specific, project-local documentation
//!
//! ## Literal Blocks for Documentation
//!
//! When creating documentation snippets that explain template syntax, use
//! `literal` blocks to prevent the examples from being rendered:
//!
//! ````markdown
//! ---
//! agpm.templating: true
//! ---
//! # AGPM Template Guide
//!
//! ## How to Embed Snippet Content
//!
//! To embed a snippet's content in your template, use this syntax:
//!
//! ```literal
//! {{ agpm.deps.snippets.best_practices.content }}
//! ```
//!
//! This will render the **current agent name**: {{ agpm.resource.name }}
//!
//! ## How to Loop Over Dependencies
//!
//! ```literal
//! {% for name, dep in agpm.deps.agents %}
//! - {{ name }}: {{ dep.version }}
//! {% endfor %}
//! ```
//!
//! The syntax examples above are displayed literally, while the agent name
//! below is dynamically rendered based on the context.
//! ````
//!
//! In this example:
//! - The `literal` blocks show template syntax examples without rendering them
//! - Regular template variables like `{{ agpm.resource.name }}` are still rendered
//! - This allows documentation to demonstrate template features while using them
//!
//! ## Recursive Project Files
//!
//! Project files can reference other project files (up to 10 levels):
//!
//! **Main agent** (`.claude/agents/reviewer.md`):
//! ```markdown
//! ---
//! agpm.templating: true
//! ---
//! # Code Reviewer
//!
//! {{ 'project/styleguide.md' | content }}
//! ```
//!
//! **Style guide** (`project/styleguide.md`):
//! ```markdown
//! # Coding Standards
//!
//! ## Rust-Specific Rules
//! {{ 'project/rust-style.md' | content }}
//! ```
//!
//! ## Dependency References
//!
//! Dependencies are accessible by name in the template context. The name is determined by:
//! 1. For manifest deps: the key in `[agents]`, `[snippets]`, etc.
//! 2. For transitive deps: the `name` field if specified, otherwise derived from path
//!
//! ```markdown
//! ## Dependencies
//!
//! This agent uses the following helper:
//! - {{ agpm.deps.snippets.helper.install_path }}
//!
//! {% if agpm.deps.agents %}
//! ## Related Agents
//! {% for agent in agpm.deps.agents %}
//! - {{ agent.name }} ({{ agent.version }})
//! {% endfor %}
//! {% endif %}
//! ```
//!
//! ### Custom Names for Transitive Dependencies
//!
//! ```yaml
//! ---
//! dependencies:
//!   agents:
//!     - path: "../shared/complex-path/helper.md"
//!       name: "helper"  # Use "helper" instead of deriving from path
//! ---
//! ```
//!
//! ## Conditional Content
//!
//! ```markdown
//! {% if agpm.resource.source == "community" %}
//! This resource is from the community repository.
//! {% elif agpm.resource.source %}
//! This resource is from the {{ agpm.resource.source }} source.
//! {% else %}
//! This is a local resource.
//! {% endif %}
//! ```

pub mod filters;

use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use serde_json::{Map, to_string, to_value};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use tera::{Context as TeraContext, Tera};

use crate::core::ResourceType;
use crate::lockfile::LockFile;

/// Sentinel markers used to guard non-templated dependency content.
/// Content enclosed between these markers should be treated as literal text
/// and never passed through the templating engine.
const NON_TEMPLATED_LITERAL_GUARD_START: &str = "__AGPM_LITERAL_RAW_START__";
const NON_TEMPLATED_LITERAL_GUARD_END: &str = "__AGPM_LITERAL_RAW_END__";

/// Convert Unix-style path (from lockfile) to platform-native format for display in templates.
///
/// Lockfiles always use Unix-style forward slashes for cross-platform compatibility,
/// but when rendering templates, we want to show paths in the platform's native format
/// so users see `.claude\agents\helper.md` on Windows and `.claude/agents/helper.md` on Unix.
///
/// # Arguments
///
/// * `unix_path` - Path string with forward slashes (from lockfile)
///
/// # Returns
///
/// Platform-native path string (backslashes on Windows, forward slashes on Unix)
///
/// # Examples
///
/// ```
/// # use agpm_cli::templating::to_native_path_display;
/// #[cfg(windows)]
/// assert_eq!(to_native_path_display(".claude/agents/test.md"), ".claude\\agents\\test.md");
///
/// #[cfg(not(windows))]
/// assert_eq!(to_native_path_display(".claude/agents/test.md"), ".claude/agents/test.md");
/// ```
pub fn to_native_path_display(unix_path: &str) -> String {
    #[cfg(windows)]
    {
        unix_path.replace('/', "\\")
    }
    #[cfg(not(windows))]
    {
        unix_path.to_string()
    }
}

/// Template context builder for AGPM resource installation.
///
/// This struct is responsible for building the template context that will be
/// available to Markdown templates during rendering. It collects data from
/// the manifest, lockfile, and current resource being processed.
///
/// # Context Structure
///
/// The built context follows this structure:
/// ```json
/// {
///   "agpm": {
///     "resource": {
///       "type": "agent",
///       "name": "example-agent",
///       "install_path": ".claude/agents/example.md",
///       "source": "community",
///       "version": "v1.0.0",
///       "resolved_commit": "abc123...",
///       "checksum": "sha256:...",
///       "path": "agents/example.md"
///     },
///     "deps": {
///       "agents": {
///         "helper": {
///           "install_path": ".claude/agents/helper.md",
///           "version": "v1.0.0",
///           "resolved_commit": "def456...",
///           "checksum": "sha256:...",
///           "source": "community",
///           "path": "agents/helper.md"
///         }
///       },
///       "snippets": { ... },
///       "commands": { ... }
///     }
///   }
/// }
/// ```
pub struct TemplateContextBuilder {
    /// The lockfile containing resolved resource information
    /// Shared via Arc to avoid expensive clones when building contexts for multiple resources
    lockfile: Arc<LockFile>,
    /// Project-specific template variables from the manifest
    project_config: Option<crate::manifest::ProjectConfig>,
    /// Cache instance for reading source files during content extraction
    /// Shared via Arc to avoid expensive clones
    cache: Arc<crate::cache::Cache>,
    /// Project root directory for resolving local file paths
    project_dir: PathBuf,
}

/// Template renderer with Tera engine and custom functions.
///
/// This struct wraps a Tera instance with AGPM-specific configuration,
/// custom functions, and filters. It provides a safe, sandboxed environment
/// for rendering Markdown templates.
///
/// # Security
///
/// The renderer is configured with security restrictions:
/// - No file system access via includes/extends (except content filter)
/// - No network access
/// - Sandboxed template execution
/// - Custom functions are carefully vetted
/// - Project file access restricted to project directory with validation
pub struct TemplateRenderer {
    /// The underlying Tera template engine
    tera: Tera,
    /// Whether templating is enabled globally
    enabled: bool,
}

/// Metadata about a resource for template context.
///
/// This struct represents the information available about a resource
/// in the template context. It includes both the resource's own metadata
/// and its resolved installation information.
#[derive(Clone, Serialize, Deserialize)]
pub struct ResourceTemplateData {
    /// Resource type (agent, snippet, command, etc.)
    #[serde(rename = "type")]
    pub resource_type: String,
    /// Logical resource name from manifest
    pub name: String,
    /// Resolved installation path
    pub install_path: String,
    /// Source identifier (if applicable)
    pub source: Option<String>,
    /// Resolved version (if applicable)
    pub version: Option<String>,
    /// Git commit SHA (if applicable)
    pub resolved_commit: Option<String>,
    /// SHA256 checksum of the content
    pub checksum: String,
    /// Source-relative path in repository
    pub path: String,
    /// Processed content of the resource file.
    ///
    /// Contains the file content with metadata stripped:
    /// - For Markdown: Content without YAML frontmatter
    /// - For JSON: Content without metadata fields
    ///
    /// This field is available for all dependencies, enabling template
    /// embedding via `{{ agpm.deps.<type>.<name>.content }}`.
    ///
    /// Note: This field is large and should not be printed in debug output.
    /// Use the Debug impl which shows only the content length.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
}

impl std::fmt::Debug for ResourceTemplateData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ResourceTemplateData")
            .field("resource_type", &self.resource_type)
            .field("name", &self.name)
            .field("install_path", &self.install_path)
            .field("source", &self.source)
            .field("version", &self.version)
            .field("resolved_commit", &self.resolved_commit)
            .field("checksum", &self.checksum)
            .field("path", &self.path)
            .field("content", &self.content.as_ref().map(|c| format!("<{} bytes>", c.len())))
            .finish()
    }
}

impl TemplateContextBuilder {
    /// Create a new template context builder.
    ///
    /// # Arguments
    ///
    /// * `lockfile` - The resolved lockfile, wrapped in Arc for efficient sharing
    /// * `project_config` - Optional project-specific template variables from the manifest
    /// * `cache` - Cache instance for reading source files during content extraction
    /// * `project_dir` - Project root directory for resolving local file paths
    pub fn new(
        lockfile: Arc<LockFile>,
        project_config: Option<crate::manifest::ProjectConfig>,
        cache: Arc<crate::cache::Cache>,
        project_dir: PathBuf,
    ) -> Self {
        Self {
            lockfile,
            project_config,
            cache,
            project_dir,
        }
    }

    /// Build the complete template context for a specific resource.
    ///
    /// # Arguments
    ///
    /// * `resource_name` - Name of the resource being rendered
    /// * `resource_type` - Type of the resource (agents, snippets, etc.)
    ///
    /// # Returns
    ///
    /// Returns a Tera `Context` containing all available template variables.
    pub async fn build_context(
        &self,
        resource_name: &str,
        resource_type: ResourceType,
    ) -> Result<TeraContext> {
        let mut context = TeraContext::new();

        // Build the nested agpm structure
        let mut agpm = Map::new();

        // Build current resource data
        let resource_data = self.build_resource_data(resource_name, resource_type)?;
        agpm.insert("resource".to_string(), to_value(resource_data)?);

        // Build dependency data
        let deps_data = self.build_dependencies_data().await?;
        agpm.insert("deps".to_string(), to_value(deps_data)?);

        // Add project variables if available
        if let Some(ref project_config) = self.project_config {
            let project_json = project_config.to_json_value();
            agpm.insert("project".to_string(), project_json);
        }

        // Insert the complete agpm object
        context.insert("agpm", &agpm);

        Ok(context)
    }

    /// Build resource metadata for the template context.
    ///
    /// # Arguments
    ///
    /// * `resource_name` - Name of the resource
    /// * `resource_type` - Type of the resource
    fn build_resource_data(
        &self,
        resource_name: &str,
        resource_type: ResourceType,
    ) -> Result<ResourceTemplateData> {
        let entry =
            self.lockfile.find_resource(resource_name, resource_type).with_context(|| {
                format!(
                    "Resource '{}' of type {:?} not found in lockfile",
                    resource_name, resource_type
                )
            })?;

        Ok(ResourceTemplateData {
            resource_type: resource_type.to_string(),
            name: resource_name.to_string(),
            install_path: to_native_path_display(&entry.installed_at),
            source: entry.source.clone(),
            version: entry.version.clone(),
            resolved_commit: entry.resolved_commit.clone(),
            checksum: entry.checksum.clone(),
            path: entry.path.clone(),
            content: None, // Will be populated when content extraction is implemented
        })
    }

    /// Extract and process content from a resource file.
    ///
    /// Reads the source file and processes it based on file type:
    /// - Markdown (.md): Strips YAML frontmatter, returns content only
    /// - JSON (.json): Removes metadata fields like `dependencies`
    /// - Other files: Returns raw content
    ///
    /// # Arguments
    ///
    /// * `resource` - The locked resource to extract content from
    ///
    /// # Returns
    ///
    /// Returns `Some(content)` if extraction succeeded, `None` on error (with warning logged)
    async fn extract_content(&self, resource: &crate::lockfile::LockedResource) -> Option<String> {
        tracing::debug!(
            "Attempting to extract content for resource '{}' (type: {:?})",
            resource.name,
            resource.resource_type
        );

        // Determine source path
        let source_path = if let Some(source_name) = &resource.source {
            let url = resource.url.as_ref()?;

            // Check if this is a local directory source
            let is_local_source = resource.resolved_commit.as_deref().is_none_or(str::is_empty);

            tracing::debug!(
                "Resource '{}': source='{}', url='{}', is_local={}",
                resource.name,
                source_name,
                url,
                is_local_source
            );

            if is_local_source {
                // Local directory source - use URL as path directly
                let path = std::path::PathBuf::from(url).join(&resource.path);
                tracing::debug!("Using local source path: {}", path.display());
                path
            } else {
                // Git-based source - get worktree path
                let sha = resource.resolved_commit.as_deref()?;

                tracing::debug!(
                    "Resource '{}': Getting worktree for SHA {}...",
                    resource.name,
                    &sha[..8.min(sha.len())]
                );

                // Use centralized worktree path construction
                let worktree_dir = match self.cache.get_worktree_path(url, sha) {
                    Ok(path) => {
                        tracing::debug!("Worktree path: {}", path.display());
                        path
                    }
                    Err(e) => {
                        tracing::warn!(
                            "Failed to construct worktree path for resource '{}': {}",
                            resource.name,
                            e
                        );
                        return None;
                    }
                };

                let full_path = worktree_dir.join(&resource.path);
                tracing::debug!(
                    "Full source path for '{}': {} (worktree exists: {})",
                    resource.name,
                    full_path.display(),
                    worktree_dir.exists()
                );
                full_path
            }
        } else {
            // Local file - path is relative to project or absolute
            let local_path = std::path::Path::new(&resource.path);
            let resolved_path = if local_path.is_absolute() {
                local_path.to_path_buf()
            } else {
                self.project_dir.join(local_path)
            };

            tracing::debug!(
                "Resource '{}': Using local file path: {}",
                resource.name,
                resolved_path.display()
            );

            resolved_path
        };

        // Read file content
        let content = match tokio::fs::read_to_string(&source_path).await {
            Ok(c) => c,
            Err(e) => {
                tracing::warn!(
                    "Failed to read content for resource '{}' from {}: {}",
                    resource.name,
                    source_path.display(),
                    e
                );
                return None;
            }
        };

        // Process based on file type
        let processed_content = if resource.path.ends_with(".md") {
            // Markdown: strip frontmatter and guard non-templated content that contains template syntax
            match crate::markdown::MarkdownDocument::parse(&content) {
                Ok(doc) => {
                    let templating_enabled =
                        Self::is_markdown_templating_enabled(doc.metadata.as_ref());
                    let mut stripped_content = doc.content;

                    if !templating_enabled
                        && Self::content_contains_template_syntax(&stripped_content)
                    {
                        tracing::debug!(
                            "Protecting non-templated markdown content for '{}'",
                            resource.name
                        );
                        stripped_content = Self::wrap_content_in_literal_guard(stripped_content);
                    }

                    stripped_content
                }
                Err(e) => {
                    tracing::warn!(
                        "Failed to parse markdown for resource '{}': {}. Using raw content.",
                        resource.name,
                        e
                    );
                    content
                }
            }
        } else if resource.path.ends_with(".json") {
            // JSON: parse and remove metadata fields
            match serde_json::from_str::<serde_json::Value>(&content) {
                Ok(mut json) => {
                    if let Some(obj) = json.as_object_mut() {
                        // Remove metadata fields that shouldn't be in embedded content
                        obj.remove("dependencies");
                    }
                    serde_json::to_string_pretty(&json).unwrap_or(content)
                }
                Err(e) => {
                    tracing::warn!(
                        "Failed to parse JSON for resource '{}': {}. Using raw content.",
                        resource.name,
                        e
                    );
                    content
                }
            }
        } else {
            // Other files: use raw content
            content
        };

        Some(processed_content)
    }

    /// Determine whether templating is explicitly enabled in Markdown frontmatter.
    fn is_markdown_templating_enabled(
        metadata: Option<&crate::markdown::MarkdownMetadata>,
    ) -> bool {
        metadata
            .and_then(|md| md.extra.get("agpm"))
            .and_then(|agpm| agpm.as_object())
            .and_then(|agpm_obj| agpm_obj.get("templating"))
            .and_then(|value| value.as_bool())
            .unwrap_or(false)
    }

    /// Detect if content contains Tera template syntax markers.
    fn content_contains_template_syntax(content: &str) -> bool {
        content.contains("{{") || content.contains("{%") || content.contains("{#")
    }

    /// Wrap non-templated content in a literal fence so it renders safely without being evaluated.
    fn wrap_content_in_literal_guard(content: String) -> String {
        let mut wrapped = String::with_capacity(
            content.len()
                + NON_TEMPLATED_LITERAL_GUARD_START.len()
                + NON_TEMPLATED_LITERAL_GUARD_END.len()
                + 2, // newline separators
        );

        wrapped.push_str(NON_TEMPLATED_LITERAL_GUARD_START);
        wrapped.push('\n');
        wrapped.push_str(&content);
        if !content.ends_with('\n') {
            wrapped.push('\n');
        }
        wrapped.push_str(NON_TEMPLATED_LITERAL_GUARD_END);

        wrapped
    }

    /// Build dependency data for the template context.
    ///
    /// This creates a nested structure of all dependencies by resource type and name.
    async fn build_dependencies_data(
        &self,
    ) -> Result<HashMap<String, HashMap<String, ResourceTemplateData>>> {
        let mut deps = HashMap::new();

        // Process each resource type
        for resource_type in [
            ResourceType::Agent,
            ResourceType::Snippet,
            ResourceType::Command,
            ResourceType::Script,
            ResourceType::Hook,
            ResourceType::McpServer,
        ] {
            let type_str_plural = resource_type.to_plural().to_string();
            let type_str_singular = resource_type.to_string();
            let mut type_deps = HashMap::new();

            let resources = self.lockfile.get_resources_by_type(resource_type);
            for resource in resources {
                // Extract content from source file
                let content = self.extract_content(resource).await;

                let template_data = ResourceTemplateData {
                    resource_type: type_str_singular.clone(),
                    name: resource.name.clone(),
                    install_path: to_native_path_display(&resource.installed_at),
                    source: resource.source.clone(),
                    version: resource.version.clone(),
                    resolved_commit: resource.resolved_commit.clone(),
                    checksum: resource.checksum.clone(),
                    path: resource.path.clone(),
                    content,
                };

                // Use manifest_alias if available, otherwise use resource name
                // For path-like names (containing / or \), extract just the basename
                // This ensures clean keys like "ai_attribution" instead of full paths
                let key_name = if let Some(alias) = &resource.manifest_alias {
                    alias.clone()
                } else if resource.name.contains('/') || resource.name.contains('\\') {
                    // Name looks like a path - extract basename without extension
                    std::path::Path::new(&resource.name)
                        .file_stem()
                        .and_then(|s| s.to_str())
                        .unwrap_or(&resource.name)
                        .to_string()
                } else {
                    // Use name as-is
                    resource.name.clone()
                };

                // Sanitize the key name by replacing hyphens with underscores
                // to avoid Tera interpreting them as minus operators
                let sanitized_key = key_name.replace('-', "_");
                type_deps.insert(sanitized_key, template_data);
            }

            if !type_deps.is_empty() {
                deps.insert(type_str_plural, type_deps);
            }
        }

        // Debug: Print what we're building
        tracing::debug!("Built dependencies data with {} resource types", deps.len());
        for (resource_type, resources) in &deps {
            tracing::debug!("  Type {}: {} resources", resource_type, resources.len());
            for name in resources.keys() {
                tracing::debug!("    - {}", name);
            }
        }

        Ok(deps)
    }

    /// Compute a stable digest of the template context data.
    ///
    /// This method creates a deterministic hash of all lockfile metadata that could
    /// affect template rendering. The digest is used as part of the cache key to ensure
    /// that changes to dependency versions or metadata properly invalidate the cache.
    ///
    /// # Returns
    ///
    /// Returns a hex-encoded string containing the first 16 characters of the SHA-256
    /// hash of the serialized template context data. This is sufficient to uniquely
    /// identify context changes while keeping the digest compact.
    ///
    /// # What's Included
    ///
    /// The digest includes all lockfile metadata that affects rendering:
    /// - Resource names, types, and installation paths
    /// - Dependency versions and resolved commits
    /// - Checksums and source information
    ///
    /// # Determinism
    ///
    /// The hash is stable across runs because:
    /// - Resources are sorted by type and name before hashing
    /// - JSON serialization uses consistent ordering (BTreeMap)
    /// - Only metadata fields that affect rendering are included
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::templating::TemplateContextBuilder;
    /// use agpm_cli::lockfile::LockFile;
    /// use std::path::{Path, PathBuf};
    /// use std::sync::Arc;
    ///
    /// # fn example() -> anyhow::Result<()> {
    /// let lockfile = LockFile::load(Path::new("agpm.lock"))?;
    /// let cache = Arc::new(agpm_cli::cache::Cache::new()?);
    /// let project_dir = std::env::current_dir()?;
    /// let builder = TemplateContextBuilder::new(
    ///     Arc::new(lockfile),
    ///     None,
    ///     cache,
    ///     project_dir
    /// );
    ///
    /// let digest = builder.compute_context_digest()?;
    /// println!("Template context digest: {}", digest);
    /// # Ok(())
    /// # }
    /// ```
    pub fn compute_context_digest(&self) -> Result<String> {
        use sha2::{Digest, Sha256};
        use std::collections::BTreeMap;

        // Build a deterministic representation of the lockfile data
        // Use BTreeMap for consistent ordering
        let mut digest_data: BTreeMap<String, BTreeMap<String, BTreeMap<&str, String>>> =
            BTreeMap::new();

        // Process each resource type in a consistent order
        for resource_type in [
            ResourceType::Agent,
            ResourceType::Snippet,
            ResourceType::Command,
            ResourceType::Script,
            ResourceType::Hook,
            ResourceType::McpServer,
        ] {
            let resources = self.lockfile.get_resources_by_type(resource_type);
            if resources.is_empty() {
                continue;
            }

            let type_str = resource_type.to_plural().to_string();
            let mut sorted_resources: Vec<_> = resources.iter().collect();
            // Sort by name for deterministic ordering
            sorted_resources.sort_by(|a, b| a.name.cmp(&b.name));

            let mut type_data = BTreeMap::new();
            for resource in sorted_resources {
                // Include only the fields that can affect template rendering
                let mut resource_data: BTreeMap<&str, String> = BTreeMap::new();
                resource_data.insert("name", resource.name.clone());
                resource_data.insert("install_path", resource.installed_at.clone());
                resource_data.insert("path", resource.path.clone());
                resource_data.insert("checksum", resource.checksum.clone());

                // Optional fields - only include if present
                if let Some(ref source) = resource.source {
                    resource_data.insert("source", source.to_string());
                }
                if let Some(ref version) = resource.version {
                    resource_data.insert("version", version.to_string());
                }
                if let Some(ref commit) = resource.resolved_commit {
                    resource_data.insert("resolved_commit", commit.to_string());
                }

                type_data.insert(resource.name.clone(), resource_data);
            }

            digest_data.insert(type_str, type_data);
        }

        // Serialize to JSON for stable representation
        let json_str =
            to_string(&digest_data).context("Failed to serialize template context for digest")?;

        // Compute SHA-256 hash
        let mut hasher = Sha256::new();
        hasher.update(json_str.as_bytes());
        let hash = hasher.finalize();

        // Return first 16 hex characters (64 bits) - sufficient for uniqueness
        Ok(hex::encode(&hash[..8]))
    }
}

impl TemplateRenderer {
    /// Create a new template renderer with AGPM-specific configuration.
    ///
    /// # Arguments
    ///
    /// * `enabled` - Whether templating is enabled globally
    /// * `project_dir` - Project root directory for content filter validation
    /// * `max_content_file_size` - Maximum file size in bytes for content filter (None for no limit)
    ///
    /// # Returns
    ///
    /// Returns a configured `TemplateRenderer` instance with custom filters registered.
    ///
    /// # Filters
    ///
    /// The following custom filters are registered:
    /// - `content`: Read project-specific files with path validation and size limits
    pub fn new(
        enabled: bool,
        project_dir: PathBuf,
        max_content_file_size: Option<u64>,
    ) -> Result<Self> {
        let mut tera = Tera::default();

        // Register custom filters
        tera.register_filter(
            "content",
            filters::create_content_filter(project_dir.clone(), max_content_file_size),
        );

        Ok(Self {
            tera,
            enabled,
        })
    }

    /// Protect literal blocks from template rendering by replacing them with placeholders.
    ///
    /// This method scans for ```literal fenced code blocks and replaces them with
    /// unique placeholders that won't be affected by template rendering. The original
    /// content is stored in a HashMap that can be used to restore the blocks later.
    ///
    /// # Arguments
    ///
    /// * `content` - The content to process
    ///
    /// # Returns
    ///
    /// Returns a tuple of:
    /// - Modified content with placeholders instead of literal blocks
    /// - HashMap mapping placeholder IDs to original content
    ///
    /// # Examples
    ///
    /// ````markdown
    /// # Documentation Example
    ///
    /// Use this syntax in templates:
    ///
    /// ```literal
    /// {{ agpm.deps.snippets.example.content }}
    /// ```
    /// ````
    ///
    /// The content inside the literal block will be protected from rendering.
    fn protect_literal_blocks(&self, content: &str) -> (String, HashMap<String, String>) {
        let mut placeholders = HashMap::new();
        let mut counter = 0;
        let mut result = String::with_capacity(content.len());

        // Split content by triple backticks to find code blocks
        let mut in_literal_block = false;
        let mut current_block = String::new();
        let lines = content.lines();

        for line in lines {
            if line.trim().starts_with("```literal") {
                // Start of literal block
                in_literal_block = true;
                current_block.clear();
                tracing::debug!("Found start of literal block");
                continue; // Skip the fence line
            } else if in_literal_block && line.trim().starts_with("```") {
                // End of literal block
                in_literal_block = false;

                // Generate unique placeholder
                let placeholder_id = format!("__AGPM_LITERAL_BLOCK_{}__", counter);
                counter += 1;

                // Store original content
                placeholders.insert(placeholder_id.clone(), current_block.clone());

                // Insert placeholder
                result.push_str(&placeholder_id);
                result.push('\n');

                tracing::debug!(
                    "Protected literal block with placeholder {} ({} bytes)",
                    placeholder_id,
                    current_block.len()
                );

                current_block.clear();
                continue; // Skip the fence line
            } else if in_literal_block {
                // Inside literal block - accumulate content
                if !current_block.is_empty() {
                    current_block.push('\n');
                }
                current_block.push_str(line);
            } else {
                // Regular content - pass through
                result.push_str(line);
                result.push('\n');
            }
        }

        // Handle unclosed literal block (add back as-is)
        if in_literal_block {
            tracing::warn!("Unclosed literal block found - treating as regular content");
            result.push_str("```literal\n");
            result.push_str(&current_block);
        }

        // Remove trailing newline if original didn't have one
        if !content.ends_with('\n') && result.ends_with('\n') {
            result.pop();
        }

        tracing::debug!("Protected {} literal block(s)", placeholders.len());
        (result, placeholders)
    }

    /// Restore literal blocks by replacing placeholders with original content.
    ///
    /// This method takes rendered content and restores any literal blocks that were
    /// protected during the rendering process.
    ///
    /// # Arguments
    ///
    /// * `content` - The rendered content containing placeholders
    /// * `placeholders` - HashMap mapping placeholder IDs to original content
    ///
    /// # Returns
    ///
    /// Returns the content with placeholders replaced by original literal blocks,
    /// wrapped in markdown code fences for proper display.
    fn restore_literal_blocks(
        &self,
        content: &str,
        placeholders: HashMap<String, String>,
    ) -> String {
        let mut result = content.to_string();

        for (placeholder_id, original_content) in placeholders {
            if original_content.starts_with(NON_TEMPLATED_LITERAL_GUARD_START) {
                result = result.replace(&placeholder_id, &original_content);
            } else {
                // Wrap in markdown code fence for display
                let replacement = format!("```\n{}\n```", original_content);
                result = result.replace(&placeholder_id, &replacement);
            }

            tracing::debug!(
                "Restored literal block {} ({} bytes)",
                placeholder_id,
                original_content.len()
            );
        }

        result
    }

    /// Collapse literal fences that were injected to protect non-templated dependency content.
    ///
    /// Any block that starts with ```literal, contains the sentinel marker on its first line,
    /// and ends with ``` will be replaced by the inner content without the sentinel or fences.
    fn collapse_non_templated_literal_guards(content: String) -> String {
        let mut result = String::with_capacity(content.len());
        let mut in_guard = false;

        for chunk in content.split_inclusive('\n') {
            let trimmed = chunk.trim_end_matches(['\r', '\n']);

            if !in_guard {
                if trimmed == NON_TEMPLATED_LITERAL_GUARD_START {
                    in_guard = true;
                } else {
                    result.push_str(chunk);
                }
            } else if trimmed == NON_TEMPLATED_LITERAL_GUARD_END {
                in_guard = false;
            } else {
                result.push_str(chunk);
            }
        }

        // If guard never closed, re-append the start marker and captured content to avoid dropping data.
        if in_guard {
            result.push_str(NON_TEMPLATED_LITERAL_GUARD_START);
        }

        result
    }

    /// Render a Markdown template with the given context.
    ///
    /// This method supports recursive template rendering where project files
    /// can reference other project files using the `content` filter.
    /// Rendering continues up to [`filters::MAX_RENDER_DEPTH`] levels deep.
    ///
    /// # Arguments
    ///
    /// * `template_content` - The raw Markdown template content
    /// * `context` - The template context containing variables
    ///
    /// # Returns
    ///
    /// Returns the rendered Markdown content.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Template syntax is invalid
    /// - Context variables are missing
    /// - Custom functions/filters fail
    /// - Recursive rendering exceeds maximum depth (10 levels)
    ///
    /// # Literal Blocks
    ///
    /// Content wrapped in ```literal fences will be protected from
    /// template rendering and displayed literally:
    ///
    /// ````markdown
    /// ```literal
    /// {{ agpm.deps.snippets.example.content }}
    /// ```
    /// ````
    ///
    /// This is useful for documentation that shows template syntax examples.
    ///
    /// # Recursive Rendering
    ///
    /// When a template contains `content` filter references, those files
    /// may themselves contain template syntax. The renderer automatically
    /// detects this and performs multiple rendering passes until either:
    /// - No template syntax remains in the output
    /// - Maximum depth is reached (error)
    ///
    /// Example recursive template chain:
    /// ```markdown
    /// # Main Agent
    /// {{ 'docs/guide.md' | content }}
    /// ```
    ///
    /// Where `docs/guide.md` contains:
    /// ```markdown
    /// # Guide
    /// {{ 'docs/common.md' | content }}
    /// ```
    ///
    /// This will render up to 10 levels deep.
    pub fn render_template(
        &mut self,
        template_content: &str,
        context: &TeraContext,
    ) -> Result<String> {
        tracing::debug!("render_template called, enabled={}", self.enabled);

        if !self.enabled {
            // If templating is disabled, return content as-is
            tracing::debug!("Templating disabled, returning content as-is");
            return Ok(template_content.to_string());
        }

        // Step 1: Protect literal blocks before any rendering
        let (protected_content, placeholders) = self.protect_literal_blocks(template_content);

        // Check if content contains template syntax (after protecting literals)
        if !self.contains_template_syntax(&protected_content) {
            // No template syntax found, restore literals and return
            tracing::debug!(
                "No template syntax found after protecting literals, returning content"
            );
            return Ok(self.restore_literal_blocks(&protected_content, placeholders));
        }

        // Log the template context for debugging
        tracing::debug!("Rendering template with context");
        Self::log_context_as_kv(context);

        // Step 2: Multi-pass rendering for recursive templates
        // This allows project files to reference other project files
        let mut current_content = protected_content;
        let mut depth = 0;
        let max_depth = filters::MAX_RENDER_DEPTH;

        let rendered = loop {
            depth += 1;

            // Check depth limit
            if depth > max_depth {
                bail!(
                    "Template rendering exceeded maximum recursion depth of {}. \
                     This usually indicates circular dependencies between project files. \
                     Please check your content filter references for cycles.",
                    max_depth
                );
            }

            tracing::debug!("Rendering pass {} of max {}", depth, max_depth);

            // Render the current content
            let rendered = self.tera.render_str(&current_content, context).map_err(|e| {
                // Extract detailed error information from Tera error
                let error_msg = Self::format_tera_error(&e);

                // Output the detailed error to stderr for immediate visibility
                eprintln!("Template rendering error:\n{}", error_msg);

                // Include the context in the error message for user visibility
                let context_str = Self::format_context_as_string(context);
                anyhow::Error::new(e).context(format!(
                    "Template rendering failed at depth {}:\n{}\n\nTemplate context:\n{}",
                    depth, error_msg, context_str
                ))
            })?;

            // Check if the rendered output still contains template syntax OUTSIDE code fences
            // This prevents re-rendering template syntax that was embedded as code examples
            if !self.contains_template_syntax_outside_fences(&rendered) {
                // No more template syntax outside fences - we're done with rendering
                tracing::debug!("Template rendering complete after {} pass(es)", depth);
                break rendered;
            }

            // More template syntax found outside fences - prepare for next iteration
            tracing::debug!("Template syntax detected in output, continuing to pass {}", depth + 1);
            current_content = rendered;
        };

        // Step 3: Restore literal blocks after all rendering is complete
        let restored = self.restore_literal_blocks(&rendered, placeholders);

        // Step 4: Collapse any literal guards that were added for non-templated dependencies
        Ok(Self::collapse_non_templated_literal_guards(restored))
    }

    /// Format a Tera error with detailed information about what went wrong.
    ///
    /// Tera errors can contain various types of issues:
    /// - Missing variables (e.g., "Variable `foo` not found")
    /// - Syntax errors (e.g., "Unexpected end of template")
    /// - Filter/function errors (e.g., "Filter `unknown` not found")
    ///
    /// This function extracts the root cause and formats it in a user-friendly way,
    /// filtering out unhelpful internal template names like '__tera_one_off'.
    ///
    /// # Arguments
    ///
    /// * `error` - The Tera error to format
    fn format_tera_error(error: &tera::Error) -> String {
        use std::error::Error;

        let mut messages = Vec::new();

        // Walk the entire error chain and collect all messages
        let mut all_messages = vec![error.to_string()];
        let mut current_error: Option<&dyn Error> = error.source();
        while let Some(err) = current_error {
            all_messages.push(err.to_string());
            current_error = err.source();
        }

        // Process messages to extract useful information
        for msg in all_messages {
            // Clean up the message by removing internal template names
            let cleaned = msg
                .replace("while rendering '__tera_one_off'", "")
                .replace("Failed to render '__tera_one_off'", "Template rendering failed")
                .replace("Failed to parse '__tera_one_off'", "Template syntax error")
                .replace("'__tera_one_off'", "template")
                .trim()
                .to_string();

            // Only keep non-empty, useful messages
            if !cleaned.is_empty()
                && cleaned != "Template rendering failed"
                && cleaned != "Template syntax error"
            {
                messages.push(cleaned);
            }
        }

        // If we got useful messages, return them
        if !messages.is_empty() {
            messages.join("\n  → ")
        } else {
            // Fallback: extract just the error kind
            "Template syntax error (see details above)".to_string()
        }
    }

    /// Format the template context as a string for error messages.
    ///
    /// # Arguments
    ///
    /// * `context` - The Tera context to format
    fn format_context_as_string(context: &TeraContext) -> String {
        let context_clone = context.clone();
        let json_value = context_clone.into_json();
        let mut output = String::new();

        // Recursively format the JSON structure with indentation
        fn format_value(key: &str, value: &serde_json::Value, indent: usize) -> Vec<String> {
            let prefix = "  ".repeat(indent);
            let mut lines = Vec::new();

            match value {
                serde_json::Value::Object(map) => {
                    lines.push(format!("{}{}:", prefix, key));
                    for (k, v) in map {
                        lines.extend(format_value(k, v, indent + 1));
                    }
                }
                serde_json::Value::Array(arr) => {
                    lines.push(format!("{}{}: [{} items]", prefix, key, arr.len()));
                    // Only show first few items to avoid spam
                    for (i, item) in arr.iter().take(3).enumerate() {
                        lines.extend(format_value(&format!("[{}]", i), item, indent + 1));
                    }
                    if arr.len() > 3 {
                        lines.push(format!("{}  ... {} more items", prefix, arr.len() - 3));
                    }
                }
                serde_json::Value::String(s) => {
                    // Truncate long strings
                    if s.len() > 100 {
                        lines.push(format!(
                            "{}{}: \"{}...\" ({} chars)",
                            prefix,
                            key,
                            &s[..97],
                            s.len()
                        ));
                    } else {
                        lines.push(format!("{}{}: \"{}\"", prefix, key, s));
                    }
                }
                serde_json::Value::Number(n) => {
                    lines.push(format!("{}{}: {}", prefix, key, n));
                }
                serde_json::Value::Bool(b) => {
                    lines.push(format!("{}{}: {}", prefix, key, b));
                }
                serde_json::Value::Null => {
                    lines.push(format!("{}{}: null", prefix, key));
                }
            }
            lines
        }

        if let serde_json::Value::Object(map) = &json_value {
            for (key, value) in map {
                output.push_str(&format_value(key, value, 1).join("\n"));
                output.push('\n');
            }
        }

        output
    }

    /// Log the template context as key-value pairs at debug level.
    ///
    /// # Arguments
    ///
    /// * `context` - The Tera context to log
    fn log_context_as_kv(context: &TeraContext) {
        let formatted = Self::format_context_as_string(context);
        for line in formatted.lines() {
            tracing::debug!("{}", line);
        }
    }

    /// Check if content contains Tera template syntax.
    ///
    /// # Arguments
    ///
    /// * `content` - The content to check
    ///
    /// # Returns
    ///
    /// Returns `true` if the content contains template delimiters.
    fn contains_template_syntax(&self, content: &str) -> bool {
        let has_vars = content.contains("{{");
        let has_tags = content.contains("{%");
        let has_comments = content.contains("{#");
        let result = has_vars || has_tags || has_comments;
        tracing::debug!(
            "Template syntax check: vars={}, tags={}, comments={}, result={}",
            has_vars,
            has_tags,
            has_comments,
            result
        );
        result
    }

    /// Check if content contains template syntax outside of code fences.
    ///
    /// This is used after rendering to determine if another pass is needed.
    /// It ignores template syntax inside code fences to prevent re-rendering
    /// content that has already been processed (like embedded dependency content).
    fn contains_template_syntax_outside_fences(&self, content: &str) -> bool {
        let mut in_code_fence = false;
        let mut in_guard = 0usize;

        for line in content.lines() {
            let trimmed = line.trim();

            if trimmed == NON_TEMPLATED_LITERAL_GUARD_START {
                in_guard = in_guard.saturating_add(1);
                continue;
            } else if trimmed == NON_TEMPLATED_LITERAL_GUARD_END {
                in_guard = in_guard.saturating_sub(1);
                continue;
            }

            if in_guard > 0 {
                continue;
            }

            // Track code fence boundaries
            if trimmed.starts_with("```") {
                in_code_fence = !in_code_fence;
                continue;
            }

            // Skip lines inside code fences
            if in_code_fence {
                continue;
            }

            // Check for template syntax in non-fenced content
            if line.contains("{{") || line.contains("{%") || line.contains("{#") {
                tracing::debug!(
                    "Template syntax found outside code fences: {:?}",
                    &line[..line.len().min(80)]
                );
                return true;
            }
        }

        tracing::debug!("No template syntax found outside code fences");
        false
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lockfile::{LockFile, LockedResource};

    fn create_test_lockfile() -> LockFile {
        let mut lockfile = LockFile::default();

        // Add a test agent
        lockfile.agents.push(LockedResource {
            name: "test-agent".to_string(),
            source: Some("community".to_string()),
            url: Some("https://github.com/example/community.git".to_string()),
            path: "agents/test-agent.md".to_string(),
            version: Some("v1.0.0".to_string()),
            resolved_commit: Some("abc123def456".to_string()),
            checksum: "sha256:testchecksum".to_string(),
            installed_at: ".claude/agents/test-agent.md".to_string(),
            dependencies: vec![],
            resource_type: ResourceType::Agent,
            tool: Some("claude-code".to_string()),
            manifest_alias: None,
            applied_patches: std::collections::HashMap::new(),
            install: None,
        });

        lockfile
    }

    #[tokio::test]
    async fn test_template_context_builder() {
        let lockfile = create_test_lockfile();

        let cache = crate::cache::Cache::new().unwrap();
        let project_dir = std::env::current_dir().unwrap();
        let builder =
            TemplateContextBuilder::new(Arc::new(lockfile), None, Arc::new(cache), project_dir);

        let _context = builder.build_context("test-agent", ResourceType::Agent).await.unwrap();

        // If we got here without panicking, context building succeeded
        // The actual context structure is tested implicitly by the renderer tests
    }

    #[test]
    fn test_template_renderer() {
        let project_dir = std::env::current_dir().unwrap();
        let mut renderer = TemplateRenderer::new(true, project_dir, None).unwrap();

        // Test rendering without template syntax
        let result = renderer.render_template("# Plain Markdown", &TeraContext::new()).unwrap();
        assert_eq!(result, "# Plain Markdown");

        // Test rendering with template syntax
        let mut context = TeraContext::new();
        context.insert("test_var", "test_value");

        let result = renderer.render_template("# {{ test_var }}", &context).unwrap();
        assert_eq!(result, "# test_value");
    }

    #[test]
    fn test_template_renderer_disabled() {
        let project_dir = std::env::current_dir().unwrap();
        let mut renderer = TemplateRenderer::new(false, project_dir, None).unwrap();

        let mut context = TeraContext::new();
        context.insert("test_var", "test_value");

        // Should return content as-is when disabled
        let result = renderer.render_template("# {{ test_var }}", &context).unwrap();
        assert_eq!(result, "# {{ test_var }}");
    }

    #[test]
    fn test_template_error_formatting() {
        let project_dir = std::env::current_dir().unwrap();
        let mut renderer = TemplateRenderer::new(true, project_dir, None).unwrap();
        let context = TeraContext::new();

        // Test with missing variable - should produce detailed error
        let result = renderer.render_template("# {{ missing_var }}", &context);
        assert!(result.is_err());

        let error = result.unwrap_err();
        let error_msg = format!("{}", error);

        // Error should NOT contain "__tera_one_off"
        assert!(
            !error_msg.contains("__tera_one_off"),
            "Error should not expose internal Tera template names"
        );

        // Error should contain useful information about the missing variable
        assert!(
            error_msg.contains("missing_var") || error_msg.contains("Variable"),
            "Error should mention the problematic variable or that a variable is missing. Got: {}",
            error_msg
        );
    }

    #[test]
    fn test_to_native_path_display() {
        // Test Unix-style path conversion
        let unix_path = ".claude/agents/test.md";
        let native_path = to_native_path_display(unix_path);

        #[cfg(windows)]
        {
            assert_eq!(native_path, ".claude\\agents\\test.md");
        }

        #[cfg(not(windows))]
        {
            assert_eq!(native_path, ".claude/agents/test.md");
        }
    }

    #[test]
    fn test_to_native_path_display_nested() {
        // Test deeply nested path
        let unix_path = ".claude/agents/ai/helpers/test.md";
        let native_path = to_native_path_display(unix_path);

        #[cfg(windows)]
        {
            assert_eq!(native_path, ".claude\\agents\\ai\\helpers\\test.md");
        }

        #[cfg(not(windows))]
        {
            assert_eq!(native_path, ".claude/agents/ai/helpers/test.md");
        }
    }

    #[tokio::test]
    async fn test_template_context_uses_native_paths() {
        let mut lockfile = create_test_lockfile();

        // Add another resource with a nested path
        lockfile.snippets.push(LockedResource {
            name: "test-snippet".to_string(),
            source: Some("community".to_string()),
            url: Some("https://github.com/example/community.git".to_string()),
            path: "snippets/utils/test.md".to_string(),
            version: Some("v1.0.0".to_string()),
            resolved_commit: Some("abc123def456".to_string()),
            checksum: "sha256:testchecksum".to_string(),
            installed_at: ".agpm/snippets/utils/test.md".to_string(),
            dependencies: vec![],
            resource_type: ResourceType::Snippet,
            tool: Some("agpm".to_string()),
            manifest_alias: None,
            applied_patches: std::collections::HashMap::new(),
            install: None,
        });

        let cache = crate::cache::Cache::new().unwrap();
        let project_dir = std::env::current_dir().unwrap();
        let builder =
            TemplateContextBuilder::new(Arc::new(lockfile), None, Arc::new(cache), project_dir);
        let context = builder.build_context("test-agent", ResourceType::Agent).await.unwrap();

        // Extract the agpm.resource.install_path from context
        let agpm_value = context.get("agpm").expect("agpm context should exist");
        let agpm_obj = agpm_value.as_object().expect("agpm should be an object");
        let resource_value = agpm_obj.get("resource").expect("resource should exist");
        let resource_obj = resource_value.as_object().expect("resource should be an object");
        let install_path = resource_obj
            .get("install_path")
            .expect("install_path should exist")
            .as_str()
            .expect("install_path should be a string");

        // Verify the path uses platform-native separators
        #[cfg(windows)]
        {
            assert_eq!(install_path, ".claude\\agents\\test-agent.md");
            assert!(install_path.contains('\\'), "Windows paths should use backslashes");
        }

        #[cfg(not(windows))]
        {
            assert_eq!(install_path, ".claude/agents/test-agent.md");
            assert!(install_path.contains('/'), "Unix paths should use forward slashes");
        }

        // Also verify dependency paths
        let deps_value = agpm_obj.get("deps").expect("deps should exist");
        let deps_obj = deps_value.as_object().expect("deps should be an object");
        let snippets = deps_obj.get("snippets").expect("snippets should exist");
        let snippets_obj = snippets.as_object().expect("snippets should be an object");
        let test_snippet = snippets_obj.get("test_snippet").expect("test_snippet should exist");
        let snippet_obj = test_snippet.as_object().expect("test_snippet should be an object");
        let snippet_path = snippet_obj
            .get("install_path")
            .expect("install_path should exist")
            .as_str()
            .expect("install_path should be a string");

        #[cfg(windows)]
        {
            assert_eq!(snippet_path, ".agpm\\snippets\\utils\\test.md");
        }

        #[cfg(not(windows))]
        {
            assert_eq!(snippet_path, ".agpm/snippets/utils/test.md");
        }
    }

    // Tests for literal block functionality (Phase 1)

    #[test]
    fn test_protect_literal_blocks_basic() {
        let project_dir = std::env::current_dir().unwrap();
        let renderer = TemplateRenderer::new(true, project_dir, None).unwrap();

        let content = r#"# Documentation

Use this syntax:

```literal
{{ agpm.deps.snippets.example.content }}
```

That's how you embed content."#;

        let (protected, placeholders) = renderer.protect_literal_blocks(content);

        // Should have one placeholder
        assert_eq!(placeholders.len(), 1);

        // Protected content should contain placeholder
        assert!(protected.contains("__AGPM_LITERAL_BLOCK_0__"));

        // Protected content should NOT contain the template syntax
        assert!(!protected.contains("{{ agpm.deps.snippets.example.content }}"));

        // Placeholder should contain the original content
        let placeholder_content = placeholders.get("__AGPM_LITERAL_BLOCK_0__").unwrap();
        assert!(placeholder_content.contains("{{ agpm.deps.snippets.example.content }}"));
    }

    #[test]
    fn test_protect_literal_blocks_multiple() {
        let project_dir = std::env::current_dir().unwrap();
        let renderer = TemplateRenderer::new(true, project_dir, None).unwrap();

        let content = r#"# First Example

```literal
{{ first.example }}
```

# Second Example

```literal
{{ second.example }}
```"#;

        let (protected, placeholders) = renderer.protect_literal_blocks(content);

        // Should have two placeholders
        assert_eq!(placeholders.len(), 2);

        // Both placeholders should be in the protected content
        assert!(protected.contains("__AGPM_LITERAL_BLOCK_0__"));
        assert!(protected.contains("__AGPM_LITERAL_BLOCK_1__"));

        // Original template syntax should not be in protected content
        assert!(!protected.contains("{{ first.example }}"));
        assert!(!protected.contains("{{ second.example }}"));
    }

    #[test]
    fn test_restore_literal_blocks() {
        let project_dir = std::env::current_dir().unwrap();
        let renderer = TemplateRenderer::new(true, project_dir, None).unwrap();

        let mut placeholders = HashMap::new();
        placeholders.insert(
            "__AGPM_LITERAL_BLOCK_0__".to_string(),
            "{{ agpm.deps.snippets.example.content }}".to_string(),
        );

        let content = "# Example\n\n__AGPM_LITERAL_BLOCK_0__\n\nDone.";
        let restored = renderer.restore_literal_blocks(content, placeholders);

        // Should contain the original content in a code fence
        assert!(restored.contains("```\n{{ agpm.deps.snippets.example.content }}\n```"));

        // Should NOT contain the placeholder
        assert!(!restored.contains("__AGPM_LITERAL_BLOCK_0__"));
    }

    #[test]
    fn test_literal_blocks_integration_with_rendering() {
        let project_dir = std::env::current_dir().unwrap();
        let mut renderer = TemplateRenderer::new(true, project_dir, None).unwrap();

        let template = r#"# Agent: {{ agent_name }}

## Documentation

Here's how to use template syntax:

```literal
{{ agpm.deps.snippets.helper.content }}
```

The agent name is: {{ agent_name }}"#;

        let mut context = TeraContext::new();
        context.insert("agent_name", "test-agent");

        let result = renderer.render_template(template, &context).unwrap();

        // The agent_name variable should be rendered
        assert!(result.contains("# Agent: test-agent"));
        assert!(result.contains("The agent name is: test-agent"));

        // The literal block should be preserved and wrapped in code fence
        assert!(result.contains("```\n{{ agpm.deps.snippets.helper.content }}\n```"));

        // The literal block should NOT be rendered (still has template syntax)
        assert!(result.contains("{{ agpm.deps.snippets.helper.content }}"));
    }

    #[test]
    fn test_literal_blocks_with_complex_template_syntax() {
        let project_dir = std::env::current_dir().unwrap();
        let mut renderer = TemplateRenderer::new(true, project_dir, None).unwrap();

        let template = r#"# Documentation

```literal
{% for item in agpm.deps.agents %}
{{ item.name }}: {{ item.version }}
{% endfor %}
```"#;

        let context = TeraContext::new();
        let result = renderer.render_template(template, &context).unwrap();

        // Should preserve the for loop syntax
        assert!(result.contains("{% for item in agpm.deps.agents %}"));
        assert!(result.contains("{{ item.name }}"));
        assert!(result.contains("{% endfor %}"));
    }

    #[test]
    fn test_literal_blocks_empty() {
        let project_dir = std::env::current_dir().unwrap();
        let mut renderer = TemplateRenderer::new(true, project_dir, None).unwrap();

        let template = r#"# Example

```literal
```

Done."#;

        let context = TeraContext::new();
        let result = renderer.render_template(template, &context).unwrap();

        // Should handle empty literal blocks gracefully
        assert!(result.contains("# Example"));
        assert!(result.contains("Done."));
    }

    #[test]
    fn test_literal_blocks_unclosed() {
        let project_dir = std::env::current_dir().unwrap();
        let renderer = TemplateRenderer::new(true, project_dir, None).unwrap();

        let content = r#"# Example

```literal
{{ template.syntax }}
This block is not closed"#;

        let (protected, placeholders) = renderer.protect_literal_blocks(content);

        // Should have no placeholders (unclosed block is treated as regular content)
        assert_eq!(placeholders.len(), 0);

        // Content should be preserved as-is
        assert!(protected.contains("```literal"));
        assert!(protected.contains("{{ template.syntax }}"));
    }

    #[test]
    fn test_literal_blocks_with_indentation() {
        let project_dir = std::env::current_dir().unwrap();
        let renderer = TemplateRenderer::new(true, project_dir, None).unwrap();

        let content = r#"# Example

    ```literal
    {{ indented.template }}
    ```"#;

        let (_protected, placeholders) = renderer.protect_literal_blocks(content);

        // Should detect indented literal blocks
        assert_eq!(placeholders.len(), 1);

        // Should preserve the indented template syntax
        let placeholder_content = placeholders.get("__AGPM_LITERAL_BLOCK_0__").unwrap();
        assert!(placeholder_content.contains("{{ indented.template }}"));
    }

    #[test]
    fn test_literal_blocks_in_transitive_dependency_content() {
        use std::fs;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path().to_path_buf();

        // Create a dependency file with literal blocks containing template syntax
        let dep_content = r#"---
agpm.templating: true
---
# Dependency Documentation

Here's a template example:

```literal
{{ nonexistent_variable }}
{{ agpm.deps.something.else }}
```

This should appear literally."#;

        // Write the dependency file
        let dep_path = project_dir.join("dependency.md");
        fs::write(&dep_path, dep_content).unwrap();

        // First, render the dependency content (simulating what happens when processing a dependency)
        let mut dep_renderer = TemplateRenderer::new(true, project_dir.clone(), None).unwrap();
        let dep_context = TeraContext::new();
        let rendered_dep = dep_renderer.render_template(dep_content, &dep_context).unwrap();

        // The rendered dependency should have the literal block converted to a regular code fence
        assert!(rendered_dep.contains("```\n{{ nonexistent_variable }}"));
        assert!(rendered_dep.contains("{{ agpm.deps.something.else }}\n```"));

        // Now simulate embedding this in a parent resource
        let parent_template = r#"# Parent Resource

## Embedded Documentation

{{ dependency_content }}

## End"#;

        // Create context with the rendered dependency content
        let mut parent_context = TeraContext::new();
        parent_context.insert("dependency_content", &rendered_dep);

        // Render the parent (with templating enabled)
        let mut parent_renderer = TemplateRenderer::new(true, project_dir.clone(), None).unwrap();
        let final_output =
            parent_renderer.render_template(parent_template, &parent_context).unwrap();

        // Verify the final output contains the template syntax literally
        assert!(
            final_output.contains("{{ nonexistent_variable }}"),
            "Template syntax from literal block should appear literally in final output"
        );
        assert!(
            final_output.contains("{{ agpm.deps.something.else }}"),
            "Template syntax from literal block should appear literally in final output"
        );

        // Verify it's in a code fence
        assert!(
            final_output.contains("```\n{{ nonexistent_variable }}"),
            "Literal content should be in a code fence"
        );

        // Verify it doesn't cause rendering errors
        assert!(!final_output.contains("__AGPM_LITERAL_BLOCK_"), "No placeholders should remain");
    }

    #[test]
    fn test_literal_blocks_with_nested_dependencies() {
        let project_dir = std::env::current_dir().unwrap();
        let mut renderer = TemplateRenderer::new(true, project_dir, None).unwrap();

        // Simulate a dependency that was already rendered with literal blocks
        let dep_content = r#"# Helper Snippet

Use this syntax:

```
{{ agpm.deps.snippets.example.content }}
{{ missing.variable }}
```

Done."#;

        // Now embed this in a parent template
        let parent_template = r#"# Main Agent

## Documentation

{{ helper_content }}

The agent uses templating."#;

        let mut context = TeraContext::new();
        context.insert("helper_content", dep_content);

        let result = renderer.render_template(parent_template, &context).unwrap();

        // The template syntax from the dependency should be preserved
        assert!(result.contains("{{ agpm.deps.snippets.example.content }}"));
        assert!(result.contains("{{ missing.variable }}"));

        // It should be in a code fence
        assert!(result.contains("```\n{{ agpm.deps.snippets.example.content }}"));
    }

    #[tokio::test]
    async fn test_non_templated_dependency_content_is_guarded() {
        use tempfile::TempDir;
        use tokio::fs;

        let temp_dir = TempDir::new().unwrap();
        let project_dir = temp_dir.path().to_path_buf();

        let snippets_dir = project_dir.join("snippets");
        fs::create_dir_all(&snippets_dir).await.unwrap();
        let snippet_path = snippets_dir.join("non-templated.md");
        fs::write(
            &snippet_path,
            r#"---
agpm:
  templating: false
---
# Example Snippet

This should show {{ agpm.deps.some.content }} literally.
"#,
        )
        .await
        .unwrap();

        let mut lockfile = LockFile::default();
        lockfile.commands.push(LockedResource {
            name: "test-command".to_string(),
            source: None,
            url: None,
            path: "commands/test.md".to_string(),
            version: None,
            resolved_commit: None,
            checksum: "sha256:test-command".to_string(),
            installed_at: ".claude/commands/test.md".to_string(),
            dependencies: vec![],
            resource_type: ResourceType::Command,
            tool: Some("claude-code".to_string()),
            manifest_alias: None,
            applied_patches: std::collections::HashMap::new(),
            install: None,
        });
        lockfile.snippets.push(LockedResource {
            name: "non_templated".to_string(),
            source: None,
            url: None,
            path: "snippets/non-templated.md".to_string(),
            version: None,
            resolved_commit: None,
            checksum: "sha256:test-snippet".to_string(),
            installed_at: ".agpm/snippets/non-templated.md".to_string(),
            dependencies: vec![],
            resource_type: ResourceType::Snippet,
            tool: Some("agpm".to_string()),
            manifest_alias: None,
            applied_patches: std::collections::HashMap::new(),
            install: None,
        });

        let cache = crate::cache::Cache::new().unwrap();
        let builder = TemplateContextBuilder::new(
            Arc::new(lockfile),
            None,
            Arc::new(cache),
            project_dir.clone(),
        );
        let context = builder.build_context("test-command", ResourceType::Command).await.unwrap();

        let mut renderer = TemplateRenderer::new(true, project_dir.clone(), None).unwrap();
        let template = r#"# Combined Output

{{ agpm.deps.snippets.non_templated.content }}
"#;
        let rendered = renderer.render_template(template, &context).unwrap();

        assert!(
            rendered.contains("# Example Snippet"),
            "Rendered output should include the snippet heading"
        );
        assert!(
            rendered.contains("{{ agpm.deps.some.content }}"),
            "Template syntax inside non-templated dependency should remain literal"
        );
        assert!(
            !rendered.contains(NON_TEMPLATED_LITERAL_GUARD_START)
                && !rendered.contains(NON_TEMPLATED_LITERAL_GUARD_END),
            "Internal literal guard markers should not leak into rendered output"
        );
        assert!(
            !rendered.contains("```literal"),
            "Synthetic literal fences should be removed after rendering"
        );
    }
}