ggen-engine 26.10.11

SPARQL-in-Tera code generation engine (vendored, renamed from praxis/crates/ggen)
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
//! Hygen-style template parsing and Tera environment construction.
//!
//! A template is a leading `--- yaml ---` frontmatter block followed by a
//! Tera body. The frontmatter key set is closed ([`Frontmatter`] uses
//! `deny_unknown_fields`), so any unrecognized key is a hard error.
//!
//! [`build_tera`] produces a Tera environment with a `sparql(query="…")`
//! function bound to a `DeterministicGraph`, plus `snake_case` and
//! `pascal_case` filters.

use std::{
    collections::{BTreeMap, HashMap},
    path::{Path, PathBuf},
    sync::Arc,
};

use inflector::Inflector;
use schemars::JsonSchema;
use serde::Deserialize;
use tera::{Tera, Value};

use crate::{
    error::{AppError, Result, TemplateFailureCause},
    graph::{EngineQueryResults, EngineRow, EngineValue, GraphEngine},
};

/// Closed frontmatter key set for a ggen template (Hygen semantics).
///
/// Unknown keys are rejected at parse time (`deny_unknown_fields`).
///
/// `#[derive(JsonSchema)]` is load-bearing: it lets
/// `tests/frontmatter_schema_match.rs` compare this struct's *actual* field
/// set (via `schemars::schema_for!`) against `schema/frontmatter-schema.ttl`,
/// instead of a hand-maintained mirror list that could itself drift.
// `struct_excessive_bools`: this is a deserialized YAML frontmatter schema
// whose field set is pinned 1:1 against `schema/frontmatter-schema.ttl` by
// `tests/frontmatter_schema_match.rs`'s `JsonSchema` comparison. Collapsing
// the independent boolean flags into an enum/bitflags would be a real,
// user-facing frontmatter schema change, not a clippy-scoped cleanup.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Frontmatter {
    /// Output path relative to the project root (Tera-renderable).
    pub to: String,
    /// Named SPARQL queries available to the template body. Accepts a bare
    /// string (implicitly named `default`), a YAML sequence (implicitly
    /// named `query_0`, `query_1`, …), or the explicit mapping form
    /// `{name: query}` — the same three forms and naming convention as
    /// ggen-core's own frontmatter `sparql:` field
    /// (`crates/ggen-core/src/template_types.rs`'s `sparql_map`
    /// deserializer), replicated faithfully.
    #[serde(default, deserialize_with = "sparql_map")]
    pub sparql: BTreeMap<String, String>,
    /// Explicit named `sparql:` result that governs projection cardinality.
    /// When set, dynamic `to:` paths fan out once per row; static paths
    /// aggregate one body rendering per row into a single output. When
    /// absent, the historical first-array/`to`-contains-`{{` behavior is
    /// preserved exactly.
    #[serde(default)]
    pub for_each: Option<String>,
    /// Optional CONSTRUCT query whose result feeds the template.
    #[serde(default)]
    pub construct: Option<String>,
    /// Inject into an existing file instead of creating a new one.
    #[serde(default)]
    pub inject: bool,
    /// Inject before the selected host-content match. A bare string keeps
    /// the historical `contains + line + first` behavior; a structured
    /// declaration can opt into exact/regex matching and cardinality.
    #[serde(default)]
    pub before: Option<MatchSpec>,
    /// Inject after the selected host-content match. Defaults are identical
    /// to `before`.
    #[serde(default)]
    pub after: Option<MatchSpec>,
    /// Inject at this 1-based line number.
    #[serde(default)]
    pub at_line: Option<usize>,
    /// Skip the write when the existing file satisfies this selector. A bare
    /// string preserves the historical whole-file substring behavior.
    #[serde(default)]
    pub skip_if: Option<MatchSpec>,
    /// Skip the write entirely when the target file already exists.
    #[serde(default)]
    pub unless_exists: bool,
    /// Declares this rule eligible for `ggen-mcp`'s bounded unattended-write
    /// dispatcher (Gall CP31-CP33): when its signal fires, the write may be
    /// applied with no human/LLM decision step, because `unless_exists` (see
    /// above) already guarantees it can only ever create a file that does not
    /// exist -- it can never clobber hand-written content. Requires
    /// `unless_exists: true` in the same frontmatter block; a template
    /// setting this without also setting `unless_exists` is a real config
    /// error (`FM-TPL-027`, see `write.rs`), not silently coerced.
    #[serde(default)]
    pub unattended_write_eligible: bool,
    /// Overwrite an existing, differing file instead of failing closed.
    #[serde(default)]
    pub force: bool,
    /// SPARQL ASK guard: generate only when the graph satisfies it.
    #[serde(default)]
    pub when: Option<String>,
    /// Skip the write when the rendered body is empty.
    #[serde(default)]
    pub skip_empty: bool,
    /// Load the Tera body from this path instead (relative to the template
    /// file's own directory); frontmatter fields still come from this file.
    #[serde(default)]
    pub from: Option<String>,
    /// Shell command run before the write decision. Refused (not executed)
    /// if it matches [`crate::shell_safety::check_shell_command_safe`]'s
    /// denylist. Runs with the project root as its working directory.
    #[serde(default, alias = "sh")]
    pub sh_before: Option<String>,
    /// Shell command run after a successful `Written`/`Injected` outcome
    /// (never after `Skipped`). Same denylist and working directory as
    /// `sh_before`.
    #[serde(default)]
    pub sh_after: Option<String>,
    /// Before overwriting an existing file (`force` or `inject`), copy it to
    /// `<path>.bak` first.
    #[serde(default)]
    pub backup: bool,
    /// SHACL shape file paths (relative to the project root) declared as
    /// governing this output. Enforced (not just existence-checked): after
    /// admission the union of these shape documents is evaluated via
    /// `GraphEngine::validate_shacl` against the active graph (the
    /// per-template `rdf:`/`rdf_inline:` overlay when declared, else the
    /// shared project graph), and a non-conforming result -- or an engine
    /// with no SHACL support -- refuses the sync (`crate::sync`'s
    /// `admit_shape_files`). Fixed 2026-08-03: this used to be
    /// existence-checked only.
    #[serde(default)]
    pub shape: Vec<String>,
    /// When `true`, the sync pipeline renders this template's body twice
    /// with identical inputs and refuses if the bytes differ (a real,
    /// enforced determinism assertion, not a declared-but-unchecked claim).
    #[serde(default)]
    pub determinism: Option<bool>,
    /// Freeze policy for this output once written; see [`FreezePolicy`].
    /// Defaults to `never` (no freeze behavior) when absent.
    #[serde(default)]
    pub freeze_policy: Option<FreezePolicy>,
    /// Directory (relative to the project root) storing per-output BLAKE3
    /// checksums for `freeze_policy: checksum`. Required when that policy
    /// is set; ignored otherwise.
    #[serde(default)]
    pub freeze_slots_dir: Option<String>,
    /// RDF/Turtle file paths loaded into a per-template overlay graph,
    /// resolved relative to the template file's own directory (never the
    /// project root) — the same traversal-safety check as `from:`. Accepts
    /// either a bare string or a YAML sequence (`rdf: foo.ttl` or
    /// `rdf: [foo.ttl, bar.ttl]`), matching ggen-core's
    /// `template_types.rs::string_or_seq` semantics exactly. See
    /// `crate::sync`'s overlay construction: the base graph's triples plus
    /// every file here, queried/rendered for THIS template only — the
    /// shared project graph is never mutated, and no other template in the
    /// same run observes these extra triples.
    #[serde(default, deserialize_with = "string_or_seq")]
    pub rdf: Vec<String>,
    /// Literal inline Turtle text (not file paths), loaded into the same
    /// per-template overlay graph as `rdf:`. Same string-or-sequence
    /// acceptance as `rdf:`.
    #[serde(default, deserialize_with = "string_or_seq")]
    pub rdf_inline: Vec<String>,
    /// Extra Turtle `@prefix` declarations (prefix name → IRI) prepended
    /// before parsing `rdf:`/`rdf_inline:` content. Ignored when both
    /// `rdf:` and `rdf_inline:` are empty.
    #[serde(default)]
    pub prefixes: BTreeMap<String, String>,
    /// RDF base IRI (`@base`) prepended before parsing `rdf:`/`rdf_inline:`
    /// content. Ignored when both `rdf:` and `rdf_inline:` are empty.
    #[serde(default)]
    pub base: Option<String>,
}

/// Backward-compatible textual selector used by `before`, `after`, and
/// `skip_if`.
///
/// Bare strings preserve the original Hygen-derived behavior. Structured
/// declarations expose the complete matcher algebra while every optional
/// property has a deterministic default.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum MatchSpec {
    /// Compatibility form. `before`/`after` resolve to
    /// `contains + line + first`; `skip_if` resolves to
    /// `contains + file + first`.
    Literal(String),
    /// Explicit matcher declaration.
    Structured(MatchRule),
}

impl MatchSpec {
    /// Pattern text, before output-phase Tera rendering.
    #[must_use]
    pub fn pattern(&self) -> &str {
        match self {
            Self::Literal(pattern) => pattern,
            Self::Structured(rule) => &rule.pattern,
        }
    }

    /// Clone the declaration while replacing only its rendered pattern.
    #[must_use]
    pub fn with_pattern(&self, pattern: String) -> Self {
        match self {
            Self::Literal(_) => Self::Literal(pattern),
            Self::Structured(rule) => {
                let mut rendered = rule.clone();
                rendered.pattern = pattern;
                Self::Structured(rendered)
            }
        }
    }

    /// Whether this declaration opted into the structured matcher algebra.
    #[must_use]
    pub fn is_structured(&self) -> bool {
        matches!(self, Self::Structured(_))
    }
}

impl From<String> for MatchSpec {
    fn from(value: String) -> Self {
        Self::Literal(value)
    }
}

impl From<&str> for MatchSpec {
    fn from(value: &str) -> Self {
        Self::Literal(value.to_string())
    }
}

/// Explicit host-content matcher. All fields except `pattern` have sane,
/// compatibility-oriented defaults.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct MatchRule {
    /// Literal or regular-expression pattern. Tera-rendered per output.
    pub pattern: String,
    /// Matching algorithm. Defaults to `contains`.
    #[serde(default)]
    pub matcher: MatchKind,
    /// Candidate scope. `auto` resolves to line scope for `before`/`after`
    /// and file scope for `skip_if`.
    #[serde(default)]
    pub scope: MatchScope,
    /// Which observed match supplies the consequence. Defaults to `first`.
    #[serde(default)]
    pub occurrence: MatchOccurrence,
    /// One-based occurrence used by `nth`. Defaults to `1`.
    #[serde(default = "default_match_index")]
    pub index: usize,
    /// Case-sensitive matching by default.
    #[serde(default = "default_true")]
    pub case_sensitive: bool,
    /// Match original text by default; set true to trim candidate boundaries.
    #[serde(default)]
    pub trim: bool,
}

/// Matcher algorithm.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum MatchKind {
    /// Candidate contains the pattern.
    #[default]
    Contains,
    /// Candidate exactly equals the pattern.
    Exact,
    /// Rust `regex` pattern.
    Regex,
}

/// Candidate scope.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum MatchScope {
    /// Property-specific compatibility default.
    #[default]
    Auto,
    /// Match each line independently. Occurrences count matching lines.
    Line,
    /// Match the complete file. Occurrences count non-overlapping spans.
    File,
}

/// Match cardinality/selection law.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum MatchOccurrence {
    /// Select the first observed match.
    #[default]
    First,
    /// Select the last observed match.
    Last,
    /// Require exactly one observed match.
    Unique,
    /// Select the one-based `index` occurrence.
    Nth,
}

const fn default_match_index() -> usize {
    1
}

const fn default_true() -> bool {
    true
}

/// Freeze policy for a frontmatter's output, once it has been written once.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum FreezePolicy {
    /// Never skip on freeze grounds; the normal write decision table applies
    /// unchanged. Equivalent to omitting `freeze_policy` entirely.
    Never,
    /// Once the target exists, always skip regeneration — a one-time
    /// scaffold that is never touched again by `ggen sync`.
    Always,
    /// Skip regeneration only when the target's on-disk content no longer
    /// matches the checksum ggen recorded the last time it wrote this file
    /// (i.e. a human has edited it since); otherwise proceed normally and
    /// record the new checksum. Requires `freeze_slots_dir`.
    Checksum,
}

/// A parsed template: validated frontmatter plus the raw Tera body.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Template {
    /// Parsed and validated frontmatter block.
    pub frontmatter: Frontmatter,
    /// Tera template body (everything after the closing `---`).
    pub body: String,
}

impl Template {
    /// Parse a template file: a leading `---` YAML `---` block, then the body.
    ///
    /// # Errors
    /// - `[FM-TPL-001]` when the file does not start with a `---` line at all.
    /// - `[FM-TPL-012]` when the opening `---` is present but not on its own
    ///   line (trailing content after it on the same line).
    /// - `[FM-TPL-013]` when the frontmatter block is unterminated (no
    ///   closing `---` line found).
    /// - `[FM-TPL-002]` when the YAML fails to deserialize, including any
    ///   unknown frontmatter key (closed key set, fail closed).
    pub fn parse(content: &str) -> Result<Self> {
        let rest = content.strip_prefix("---").ok_or_else(|| {
            AppError::fm_tpl(
                1,
                "template must start with a `---` frontmatter block. \
                 Remediation: begin the file with `---`, YAML keys, `---`.",
            )
        })?;
        // The opening delimiter must be its own line.
        let rest = rest.strip_prefix('\n').ok_or_else(|| {
            AppError::fm_tpl(12, "`---` frontmatter delimiter must be on its own line")
        })?;
        let (yaml, body) = split_closing_delimiter(rest).ok_or_else(|| {
            AppError::fm_tpl(
                13,
                "unterminated frontmatter: no closing `---` line found. \
                 Remediation: close the YAML block with a `---` line.",
            )
        })?;
        let frontmatter: Frontmatter = serde_yaml::from_str(yaml).map_err(|e| {
            AppError::fm_tpl(
                2,
                format!(
                    "frontmatter rejected: {e}. \
                     Remediation: use only the closed key set (to, sparql, for_each, construct, \
                     inject, before, after, at_line, skip_if, unless_exists, \
                     unattended_write_eligible, force, \
                     when, skip_empty, from, sh_before, sh_after, backup, shape, \
                     determinism, freeze_policy, freeze_slots_dir, rdf, rdf_inline, \
                     prefixes, base)."
                ),
            )
        })?;
        if frontmatter.unattended_write_eligible && !frontmatter.unless_exists {
            return Err(AppError::fm_tpl(
                27,
                "unattended_write_eligible: true requires unless_exists: true in the same \
                 frontmatter block -- eligibility for ggen-mcp's bounded unattended-write \
                 dispatcher (Gall CP31-CP33) depends on the create-only guarantee \
                 unless_exists provides; a rule that could overwrite existing content is \
                 never eligible for a zero-decision-step write. \
                 Remediation: add `unless_exists: true`, or remove \
                 `unattended_write_eligible` if this rule may overwrite existing content.",
            ));
        }
        Ok(Self {
            frontmatter,
            body: body.to_string(),
        })
    }
}

/// Split `rest` at the first line that is exactly `---`, returning
/// `(yaml, body)`. The body excludes the delimiter line itself.
fn split_closing_delimiter(rest: &str) -> Option<(&str, &str)> {
    let mut offset = 0usize;
    for line in rest.split_inclusive('\n') {
        if line.trim_end_matches(['\r', '\n']) == "---" {
            let yaml = &rest[..offset];
            let body = &rest[offset + line.len()..];
            return Some((yaml, body));
        }
        offset += line.len();
    }
    None
}

/// Accept `rdf: "<path>"` (single) or `rdf: ["<a>", "<b>"]` (sequence) —
/// replicates ggen-core's `template_types.rs::string_or_seq` deserializer
/// (same visitor structure, same accepted shapes) for `rdf:`/`rdf_inline:`.
fn string_or_seq<'de, D>(de: D) -> std::result::Result<Vec<String>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use serde::de::{Error as DeError, SeqAccess, Visitor};
    use std::fmt;

    struct StrOrSeq;

    impl<'de> Visitor<'de> for StrOrSeq {
        type Value = Vec<String>;

        fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
            f.write_str("a string or a sequence of strings")
        }

        fn visit_str<E>(self, v: &str) -> std::result::Result<Self::Value, E>
        where
            E: DeError,
        {
            Ok(vec![v.to_string()])
        }

        fn visit_string<E>(self, v: String) -> std::result::Result<Self::Value, E>
        where
            E: DeError,
        {
            Ok(vec![v])
        }

        fn visit_seq<A>(self, mut seq: A) -> std::result::Result<Self::Value, A::Error>
        where
            A: SeqAccess<'de>,
        {
            let mut out = Vec::new();
            while let Some(s) = seq.next_element::<String>()? {
                out.push(s);
            }
            Ok(out)
        }
    }

    de.deserialize_any(StrOrSeq)
}

/// Accept `sparql: "<query>"` (single, named `default`),
/// `sparql: ["<q0>", "<q1>"]` (named `query_0`, `query_1`, …), or
/// `sparql: { name: "<query>" }` (explicit mapping) — replicates
/// ggen-core's `template_types.rs::sparql_map` deserializer (same untagged
/// enum, same naming convention) so templates authored against either
/// convention parse identically here.
fn sparql_map<'de, D>(de: D) -> std::result::Result<BTreeMap<String, String>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum OneOrMapOrSeq {
        One(String),
        Map(BTreeMap<String, String>),
        Seq(Vec<String>),
    }
    match OneOrMapOrSeq::deserialize(de)? {
        OneOrMapOrSeq::One(q) => {
            let mut m = BTreeMap::new();
            m.insert("default".to_string(), q);
            Ok(m)
        }
        OneOrMapOrSeq::Map(m) => Ok(m),
        OneOrMapOrSeq::Seq(queries) => {
            let mut m = BTreeMap::new();
            for (i, query) in queries.into_iter().enumerate() {
                m.insert(format!("query_{i}"), query);
            }
            Ok(m)
        }
    }
}

/// Build a Tera environment bound to `graph`.
///
/// Registers:
/// - `sparql(query="…")` — executes the query against the graph.
///   ASK → bool; SELECT → array of `{var: value}` objects (bare variable
///   names, e.g. `name`, never `?name` — see
///   `sparql_row_keys_are_bare_not_question_mark_prefixed` for why that's a
///   pinned invariant, not an accident); CONSTRUCT / DESCRIBE → array of
///   `{subject, predicate, object}` objects.
/// - `local(iri="…")` — the local name/fragment of an IRI (after the last
///   `#` or `/`).
/// - `sparql_first(rows=…)` / `sparql_first(results=…)` — the first row of a
///   SELECT result array, or `null` if empty. With `column="…"` given
///   (either convention), returns just that column's value instead of the
///   full row object. `rows=` and `results=` are the same convention under
///   two names (the engine's own, and ggen-core's); passing both is a hard
///   error.
/// - `sparql_values(rows=…, column="…")` / `sparql_values(results=…,
///   column="…")` — the array of one column's values across every row.
/// - `sparql_empty(rows=…)` / `sparql_empty(results=…)` — `true` if the
///   array is empty.
/// - `sparql_count(rows=…)` / `sparql_count(results=…)` — the number of
///   rows.
/// - `snake_case`, `pascal_case`, `camel_case`, `kebab_case`,
///   `shouty_snake_case`, `title_case`, `pluralize`, `singularize` filters,
///   plus the bare aliases `snake`, `pascal`, `camel`, `kebab`, `shouty`,
///   `title` (identical output to their `_case`-suffixed counterparts —
///   `title` deliberately shadows Tera's own built-in `title` filter,
///   matching the semantics templates ported from ggen-core were authored
///   against).
///
/// # Errors
/// Returns `[FM-TPL-015]` only for a structural failure isolating the
/// `templates/` directory itself (e.g. unreadable, or a genuine
/// inheritance-chain/macro-import defect spanning multiple files — see
/// `load_templates_glob_lenient`'s doc comment for why a *single* broken
/// file's parse error no longer reaches this point at all). Previously a
/// syntax error in ANY file under `templates/**/*` — including one no
/// active rule/template references — aborted this call entirely; that
/// collateral failure mode is what `load_templates_glob_lenient` fixes.
pub fn build_tera(graph: Arc<dyn GraphEngine>) -> Result<Tera> {
    build_tera_with_packs(graph, &[])
}

/// [`build_tera`], plus eager registration of every resolved pack's
/// `templates/` files under `<pack-name>://<subpath>` names.
///
/// Mechanism: Tera 1.x has no public loader trait (its only bulk entry
/// point is the glob constructor), so pack templates are registered
/// *eagerly* at build time using the same lenient per-file discipline as
/// `load_templates_glob_lenient`: a file that fails to parse is skipped
/// with a `WARN` (it still fails loudly at render if something imports it),
/// never a silent drop. A project template's
/// `{% import "demolib://macros/util.tera" as u %}` then resolves by plain
/// Tera name lookup, exactly like any same-directory import.
///
/// Zero drift: `build_tera` delegates with an empty pack slice, so projects
/// not using URI imports take the identical code path as before — nothing
/// is registered, nothing is re-checked twice (the empty-slice early return
/// in `attach_pack_templates` skips the post-registration inheritance/
/// macro re-check too).
///
/// # Errors
/// Inherits `load_templates_glob_lenient`'s `[FM-TPL-015]`, plus the
/// post-registration re-check mapped to `[FM-TPL-015]` as well (a genuine
/// inheritance/macro-import defect spanning a project template and a pack
/// template).
pub fn build_tera_with_packs(
    graph: Arc<dyn GraphEngine>, packs: &[crate::pack::Pack],
) -> Result<Tera> {
    let mut tera = load_templates_glob_lenient(Path::new("templates"))?;
    attach_pack_templates(&mut tera, packs)?;
    tera.register_function("sparql", move |args: &HashMap<String, Value>| {
        let query = args
            .get("query")
            .and_then(Value::as_str)
            .ok_or_else(|| tera::Error::msg("sparql() requires a string `query` argument"))?;
        sparql_to_value(graph.as_ref(), query).map_err(|e| tera::Error::msg(e.to_string()))
    });
    tera.register_function("local", local_fn);
    tera.register_function("sparql_first", sparql_first_fn);
    tera.register_function("sparql_values", sparql_values_fn);
    tera.register_function("sparql_empty", sparql_empty_fn);
    tera.register_function("sparql_count", sparql_count_fn);
    tera.register_filter("snake_case", snake_case_filter);
    tera.register_filter("snake", snake_case_filter);
    tera.register_filter("pascal_case", pascal_case_filter);
    tera.register_filter("pascal", pascal_case_filter);
    tera.register_filter("camel_case", camel_case_filter);
    tera.register_filter("camel", camel_case_filter);
    tera.register_filter("kebab_case", kebab_case_filter);
    tera.register_filter("kebab", kebab_case_filter);
    tera.register_filter("shouty_snake_case", shouty_snake_case_filter);
    tera.register_filter("shouty", shouty_snake_case_filter);
    tera.register_filter("title_case", title_case_filter);
    // Deliberately shadows Tera's own built-in `title` filter: the 35 real
    // templates this alias exists for were authored against ggen-core's
    // `title` (== this crate's `title_case`) semantics, not Tera's.
    tera.register_filter("title", title_case_filter);
    tera.register_filter("pluralize", pluralize_filter);
    tera.register_filter("singularize", singularize_filter);
    // The four filters below are true linguistic inflections (irregular
    // plurals, ordinal suffixes, Rails-style module-path stripping) rather
    // than mechanical case conversion — deliberately backed by the
    // `Inflector` crate instead of hand-rolled, unlike `snake_case`/
    // `pascal_case`/etc. above. Composing with a proven library here (the
    // Hygen doc parity's own `h.inflection.*` is backed by an external
    // library too — node.inflection, not hand-rolled) beats reimplementing
    // English pluralization rules and ordinal-suffix exceptions by hand.
    tera.register_filter("ordinalize", ordinalize_filter);
    tera.register_filter("demodulize", demodulize_filter);
    tera.register_filter("foreign_key", foreign_key_filter);
    tera.register_filter("tableize", tableize_filter);
    tera.register_filter("classify", classify_filter);
    tera.register_filter("hex_to_u64", hex_to_u64_filter);
    Ok(tera)
}

/// Lenient replacement for `Tera::new("templates/**/*")`: parses every file
/// under `templates_dir` (relative to the current working directory,
/// matching `Tera::new`'s own glob-then-canonicalize semantics) *individually*.
///
/// A file that fails to parse is skipped — never registered — and its path
/// and error are logged at `WARN`, not silently discarded. This isolates a
/// broken, unreferenced template file from every unrelated
/// `[[generation.rules]]` rule or frontmatter template that doesn't
/// `{% include %}`/`{% extends %}` it: previously `Tera::new`'s own
/// `load_from_glob` aggregated every file's parse error into one `Err` and
/// aborted registration entirely — one orphaned file with a syntax error
/// (e.g. Jinja2-style `default("x")` instead of Tera's `default(value="x")`)
/// collaterally blocked every active rule in the same project. A file that
/// something DOES reference still fails loudly, just at the point it's
/// actually used (Tera's own `TemplateNotFound`/`MissingParent`), not
/// collaterally for the entire sync.
///
/// Returns an empty [`Tera::default`] (matching `Tera::new`'s own behavior
/// for a glob that matches nothing) when `templates_dir` doesn't exist at
/// all.
///
/// # Errors
/// `[FM-TPL-015]` if `templates_dir` exists but isn't readable, or if
/// building the inheritance chain / checking macro imports over the
/// *successfully-parsed* subset fails (a defect spanning multiple files
/// that all parsed fine individually — e.g. a child `{% extends %}`ing a
/// parent that itself failed to parse, or a real circular extend).
pub(crate) fn load_templates_glob_lenient(templates_dir: &Path) -> Result<Tera> {
    if !templates_dir.is_dir() {
        return Ok(Tera::default());
    }
    let canonical_root = templates_dir.canonicalize().map_err(|e| {
        AppError::fm_tpl(
            15,
            format!(
                "`{}` directory unreadable: {e}. Remediation: check its permissions.",
                templates_dir.display()
            ),
        )
    })?;

    let mut files: Vec<PathBuf> = Vec::new();
    collect_files_recursive(&canonical_root, &mut files).map_err(|e| {
        AppError::fm_tpl(
            15,
            format!(
                "walking `{}` failed: {e}. Remediation: check its permissions.",
                templates_dir.display()
            ),
        )
    })?;
    // Deterministic registration order (matters for reproducible error
    // ordering, not for correctness — Tera's inheritance build is a
    // separate, order-independent pass below).
    files.sort();

    let mut tera = Tera::default();
    for path in files {
        let rel_name = path
            .strip_prefix(&canonical_root)
            .unwrap_or(&path)
            .to_string_lossy()
            .replace('\\', "/");
        let content = match std::fs::read_to_string(&path) {
            Ok(c) => c,
            Err(e) => {
                tracing::warn!(
                    template.path = %rel_name,
                    template.error = %e,
                    "templates/**/* glob: skipping unreadable template file \
                     (it will still fail loudly if a rule or include actually uses it)",
                );
                continue;
            }
        }; // continue above is deliberate: no further code in this loop body reads `content`
           // before falling to the next file if it wasn't produced.
        match tera::Template::new(
            &rel_name,
            Some(path.to_string_lossy().to_string()),
            &content,
        ) {
            Ok(tpl) => {
                tera.templates.insert(rel_name, tpl);
            }
            Err(e) => {
                tracing::warn!(
                    template.path = %rel_name,
                    template.error = %e,
                    "templates/**/* glob: skipping unparseable template file \
                     (it will still fail loudly if a rule or include actually uses it)",
                );
            }
        }
    }

    tera.build_inheritance_chains().map_err(|e| {
        AppError::fm_tpl(
            15,
            format!(
                "Tera inheritance chain build failed across `{}`: {e}. \
                 Remediation: fix the reported `extends`/parent relationship.",
                templates_dir.display()
            ),
        )
    })?;
    tera.check_macro_files().map_err(|e| {
        AppError::fm_tpl(
            15,
            format!(
                "Tera macro import check failed across `{}`: {e}. \
                 Remediation: fix the reported macro import path.",
                templates_dir.display()
            ),
        )
    })?;
    Ok(tera)
}

/// Recursively collect every regular file under `dir` (mirrors
/// `Tera::new`'s own `templates/**/*` glob scope: every file at any depth,
/// no extension filter, symlinks followed via `Path::is_dir`/`is_file`
/// which resolve through them).
fn collect_files_recursive(dir: &Path, out: &mut Vec<PathBuf>) -> std::io::Result<()> {
    for entry in std::fs::read_dir(dir)? {
        let path = entry?.path();
        if path.is_dir() {
            collect_files_recursive(&path, out)?;
        } else if path.is_file() {
            out.push(path);
        }
    }
    Ok(())
}

/// Eagerly register every resolved pack's `templates/` files into `tera`
/// under `<pack-name>://<subpath>` names, so a project template can
/// `{% import "demolib://macros/util.tera" as u %}` across packs. Same
/// lenient per-file discipline as `load_templates_glob_lenient`; then
/// re-runs the inheritance/macro checks over the enlarged template set.
fn attach_pack_templates(tera: &mut Tera, packs: &[crate::pack::Pack]) -> Result<()> {
    if packs.is_empty() {
        return Ok(());
    }
    for pack in packs {
        let templates_dir = pack.root.join("templates");
        if !templates_dir.is_dir() {
            continue;
        }
        let canonical_root = templates_dir.canonicalize().map_err(|e| {
            AppError::fm_tpl(
                15,
                format!(
                    "pack `{}` templates directory `{}` unreadable: {e}",
                    pack.name,
                    templates_dir.display()
                ),
            )
        })?;
        let mut files: Vec<PathBuf> = Vec::new();
        collect_files_recursive(&canonical_root, &mut files).map_err(|e| {
            AppError::fm_tpl(
                15,
                format!(
                    "walking pack `{}` templates `{}` failed: {e}",
                    pack.name,
                    templates_dir.display()
                ),
            )
        })?;
        // Deterministic registration order.
        files.sort();
        for path in files {
            let rel = path
                .strip_prefix(&canonical_root)
                .unwrap_or(&path)
                .to_string_lossy()
                .replace('\\', "/");
            let registered_name = format!("{}://{}", pack.name, rel);
            let content = match std::fs::read_to_string(&path) {
                Ok(c) => c,
                Err(e) => {
                    tracing::warn!(
                        template.name = %registered_name,
                        template.error = %e,
                        "pack templates: skipping unreadable pack template file",
                    );
                    continue;
                }
            };
            match tera::Template::new(
                &registered_name,
                Some(path.to_string_lossy().to_string()),
                &content,
            ) {
                Ok(tpl) => {
                    tera.templates.insert(registered_name, tpl);
                }
                Err(e) => {
                    tracing::warn!(
                        template.name = %registered_name,
                        template.error = %e,
                        "pack templates: skipping unparseable pack template file \
                         (it will still fail loudly if a rule or include actually uses it)",
                    );
                }
            }
        }
    }
    tera.build_inheritance_chains().map_err(|e| {
        AppError::fm_tpl(
            15,
            format!("Tera inheritance chain build failed across project+pack templates: {e}"),
        )
    })?;
    tera.check_macro_files().map_err(|e| {
        AppError::fm_tpl(
            15,
            format!("Tera macro import check failed across project+pack templates: {e}"),
        )
    })?;
    Ok(())
}

/// Resolve a `<pack-name>://<subpath>` template URI to the on-disk file
/// `<pack.root>/templates/<subpath>` against the already-resolved pack set.
///
/// Fail closed with a typed `[FM-TPL-028]` error naming both the URI and
/// the searched path: not-a-URI, unknown pack (listing the resolved pack
/// names), `..` traversal, and missing file each refuse with the URI and
/// the searched filesystem path in the message.
///
/// # Errors
/// `[FM-TPL-028]` for every refusal above.
pub fn resolve_pack_template(uri: &str, packs: &[crate::pack::Pack]) -> Result<PathBuf> {
    let Some((pack_name, subpath)) = uri.split_once("://") else {
        return Err(AppError::fm_tpl(
            28,
            format!("`{uri}` is not a `<pack-name>://<subpath>` template URI"),
        ));
    };
    let Some(pack) = packs.iter().find(|p| p.name == pack_name) else {
        let names: Vec<&str> = packs.iter().map(|p| p.name.as_str()).collect();
        return Err(AppError::fm_tpl(
            28,
            format!(
                "template URI `{uri}` names unknown pack `{pack_name}`; resolved packs: [{}]",
                names.join(", ")
            ),
        ));
    };
    if subpath.split('/').any(|seg| seg == "..") {
        return Err(AppError::fm_tpl(
            28,
            format!("template URI `{uri}` contains a `..` segment; traversal refused"),
        ));
    }
    let searched = pack.root.join("templates").join(subpath.replace('\\', "/"));
    if !searched.is_file() {
        return Err(AppError::fm_tpl(
            28,
            format!(
                "template URI `{uri}` does not exist: searched `{}`",
                searched.display()
            ),
        ));
    }
    Ok(searched)
}

/// Walk a `tera::Error`'s `source()` chain and join every level's `Display`
/// text with a colon separator. Tera's own `Display` impl prints only the
/// outermost wrapper message (something like "Failed to render 'x'") and
/// drops the actual cause (something like "Variable `sparql_results` not
/// found in context") — this crate's own
/// `sparql_functions_reject_both_rows_and_results` test (below) already had
/// to reach for `{:?}` instead of `{}` for exactly this reason. Used by
/// `crate::generation_rules` so an `[FM-GEN-008]` message carries the real
/// cause, not just the wrapper.
pub(crate) fn tera_error_full_chain(err: &tera::Error) -> String {
    use std::error::Error as StdError;
    let mut parts = vec![err.to_string()];
    let mut cause = StdError::source(err);
    while let Some(e) = cause {
        parts.push(e.to_string());
        cause = e.source();
    }
    parts.join(": ")
}

/// Best-effort extraction of a `<line> | <code>` gutter (Tera's own
/// pest-derived parse-error formatting) from a Tera error's full chain.
/// `None` for the overwhelming majority of `[FM-GEN-008]` failures —
/// render-time semantic errors like "Variable ... not found" carry no
/// line/col at all; only a genuine parse failure (e.g.
/// `render_output_file`'s own `render_str` hitting a syntax error inside
/// `output_file` itself) does.
pub(crate) fn tera_error_location(err: &tera::Error) -> Option<String> {
    tera_error_full_chain(err).lines().find_map(|line| {
        let trimmed = line.trim_start();
        let digits: String = trimmed.chars().take_while(char::is_ascii_digit).collect();
        if digits.is_empty() {
            return None;
        }
        let rest = trimmed[digits.len()..].trim_start();
        rest.starts_with('|').then(|| format!("line {digits}"))
    })
}

/// Classify a Tera render/parse failure into a [`TemplateFailureCause`],
/// combining `tera::ErrorKind` matching (where Tera gives a structured
/// variant) with message substring matching on the `Msg` catch-all (the
/// only signal Tera's 1.20.1 error model exposes for the rest — see
/// [`TemplateFailureCause`]'s own doc comment). `own_template_name` is the
/// name the caller registered/is rendering (e.g. `generation_rule::agent-rs`)
/// — used to tell a top-level `TemplateNotFound` (this template itself was
/// never registered) apart from one raised for a *different* name (an
/// `{% include %}`/`{% extends %}` target that's missing).
///
/// Tera 1.20.1's `Processor::render` (`renderer/processor.rs::render`)
/// unconditionally wraps EVERY render-time error one level deep —
/// `Error::chain(self.get_error_location(), e)`, i.e. an outer
/// `ErrorKind::Msg("Failed to render '<name>'")` whose `source()` is the
/// real cause — confirmed empirically: even a bare "Variable ... not found"
/// or `FilterNotFound` arrives wrapped this way. Classifying on `err.kind`
/// directly (the first version of this function did) therefore always saw
/// the generic wrapper and always fell through to
/// [`TemplateFailureCause::TemplateRenderInternal`]. This walks past that
/// one (or more) wrapper layer(s) to the real cause before classifying.
pub(crate) fn classify_tera_render_error(
    err: &tera::Error, own_template_name: &str,
) -> TemplateFailureCause {
    use std::error::Error as StdError;
    let mut current = err;
    loop {
        match &current.kind {
            tera::ErrorKind::Msg(_) => {
                match StdError::source(current).and_then(|s| s.downcast_ref::<tera::Error>()) {
                    // A generic wrapper around a further tera::Error --
                    // unwrap one level and re-classify on the real cause.
                    Some(inner) => {
                        current = inner;
                    }
                    // No further tera::Error inside: THIS Msg text is the
                    // real leaf cause (e.g. a bare
                    // `Error::msg("Variable ... not found ...")`, which
                    // carries no source at all).
                    None => return classify_msg(&current.to_string()),
                }
            }
            other => return classify_kind(other, own_template_name),
        }
    }
}

/// The non-`Msg` half of [`classify_tera_render_error`]'s match, extracted
/// so the unwrap loop above can re-invoke it at whatever depth the real
/// cause turns out to live at.
fn classify_kind(kind: &tera::ErrorKind, own_template_name: &str) -> TemplateFailureCause {
    match kind {
        tera::ErrorKind::TemplateNotFound(name) => {
            if name == own_template_name {
                TemplateFailureCause::TemplateNotFound
            } else {
                TemplateFailureCause::TemplateIncludeNotFound
            }
        }
        tera::ErrorKind::MissingParent { .. } | tera::ErrorKind::CircularExtend { .. } => {
            TemplateFailureCause::TemplateIncludeNotFound
        }
        tera::ErrorKind::FilterNotFound(_)
        | tera::ErrorKind::FunctionNotFound(_)
        | tera::ErrorKind::TestNotFound(_) => TemplateFailureCause::TemplateFilterUnknown,
        // The filter/function/test name WAS found; it failed when invoked
        // (wrong argument shape, wrong value type) — a context problem,
        // not an unknown-identifier problem. `Json` (a context value that
        // failed to serialize) is the same class of problem.
        tera::ErrorKind::CallFunction(_)
        | tera::ErrorKind::CallFilter(_)
        | tera::ErrorKind::CallTest(_)
        | tera::ErrorKind::Json(_) => TemplateFailureCause::TemplateContextInvalid,
        tera::ErrorKind::Io(_) | tera::ErrorKind::Utf8Conversion { .. } => {
            TemplateFailureCause::TemplateRenderInternal
        }
        tera::ErrorKind::InvalidMacroDefinition(_) => TemplateFailureCause::TemplateParseFailed,
        // Reached only if a `Msg` variant's `source()` downcast to
        // `tera::Error` but that inner error's OWN kind is again `Msg` with
        // no further tera::Error source — handled by the loop above, never
        // this arm directly; kept for exhaustiveness against Tera's
        // `#[non_exhaustive]`-style `ErrorKind`.
        tera::ErrorKind::Msg(msg) => classify_msg(msg),
        _ => TemplateFailureCause::TemplateRenderInternal,
    }
}

/// Substring classification for `tera::ErrorKind::Msg` — the catch-all
/// variant every render-time semantic error (variable lookup, math
/// operation, parse-error wrapper text) actually arrives as in Tera 1.20.1.
fn classify_msg(msg: &str) -> TemplateFailureCause {
    if msg.contains("not found in context") {
        TemplateFailureCause::TemplateVariableMissing
    } else if msg.contains("Failed to parse") || msg.contains("expected") {
        TemplateFailureCause::TemplateParseFailed
    } else if msg.contains("is not a number") || msg.contains("can not be evaluated") {
        TemplateFailureCause::TemplateContextInvalid
    } else {
        TemplateFailureCause::TemplateRenderInternal
    }
}

/// Execute `query` and convert the engine-neutral results into a Tera
/// [`Value`] (behavior-preserving: identical JSON shapes to the previous
/// oxigraph-typed implementation).
pub(crate) fn sparql_to_value(graph: &dyn GraphEngine, query: &str) -> Result<Value> {
    match graph.query(query)? {
        EngineQueryResults::Boolean(b) => Ok(Value::Bool(b)),
        EngineQueryResults::Solutions(solutions) => {
            Ok(Value::Array(solutions_to_values(solutions)))
        }
        EngineQueryResults::Graph(triples) => {
            let rows = triples
                .into_iter()
                .map(|triple| {
                    let mut row = tera::Map::new();
                    row.insert("subject".to_string(), Value::String(triple.subject));
                    row.insert("predicate".to_string(), Value::String(triple.predicate));
                    row.insert("object".to_string(), Value::String(triple.object_value));
                    Value::Object(row)
                })
                .collect();
            Ok(Value::Array(rows))
        }
    }
}

/// Convert engine-neutral SELECT rows into Tera `Value::Object`s (bare
/// variable-name keys, e.g. `name`, never `?name`). Shared by
/// [`sparql_to_value`]'s `Solutions` branch and
/// `crate::generation_rules`'s per-row context building, so both call sites
/// agree on the exact same row shape.
///
/// Datatype-aware: each cell's [`EngineValue`] (produced by
/// `graph::term_to_engine_value`) is mapped 1:1 to the matching Tera/JSON
/// `Value` variant by [`engine_value_to_tera`] — `xsd:boolean` literals
/// become `Value::Bool`, integer/decimal/float-family literals become
/// `Value::Number`, everything else stays `Value::String` exactly as
/// before. See [`EngineValue`]'s doc comment for the full datatype table
/// and the documented lossy-string scope boundary (language tags,
/// `xsd:dateTime`/`xsd:date`).
pub(crate) fn solutions_to_values(rows: Vec<EngineRow>) -> Vec<Value> {
    rows.into_iter()
        .map(|solution| {
            let mut row = tera::Map::new();
            for (var, value) in solution {
                row.insert(var, engine_value_to_tera(value));
            }
            Value::Object(row)
        })
        .collect()
}

/// Map one [`EngineValue`] cell to its Tera/JSON `Value` — the single
/// conversion point [`solutions_to_values`] uses for every row cell.
fn engine_value_to_tera(value: EngineValue) -> Value {
    match value {
        EngineValue::Bool(b) => Value::Bool(b),
        EngineValue::Int(n) => Value::Number(n.into()),
        // `term_to_engine_value` already filters out non-finite floats
        // (falls back to `EngineValue::String` with a warning), so
        // `from_f64` here is infallible in practice; the `unwrap_or`
        // fallback exists only as defense-in-depth, never expected to fire.
        EngineValue::Float(f) => serde_json::Number::from_f64(f).map_or(Value::Null, Value::Number),
        EngineValue::String(s) => Value::String(s),
    }
}

/// `local(iri="…")` — the local name/fragment of an IRI: the substring
/// after the last `#`, or after the last `/` if there is no `#`, or the
/// whole string if neither separator is present.
fn local_fn(args: &HashMap<String, Value>) -> tera::Result<Value> {
    let iri = args
        .get("iri")
        .and_then(Value::as_str)
        .ok_or_else(|| tera::Error::msg("local() requires a string `iri` argument"))?;
    let local = iri
        .rsplit_once('#')
        .map(|(_, frag)| frag)
        .or_else(|| iri.rsplit_once('/').map(|(_, seg)| seg))
        .unwrap_or(iri);
    Ok(Value::String(local.to_string()))
}

/// Extract the rows array from either the engine's own `rows=` convention or
/// ggen-core's `results=` convention (`crates/ggen-core/src/register.rs`'s
/// `SparqlFirstFn`/`SparqlValuesFn`/`SparqlEmptyFn`/`SparqlCountFn`) — both
/// name the identical SELECT-result-array argument. Supplying both in the
/// same call is a hard error (never a silent pick of one); supplying
/// neither names both accepted argument names in the error.
fn rows_or_results_arg<'a>(
    args: &'a HashMap<String, Value>, fn_name: &str,
) -> tera::Result<&'a Vec<Value>> {
    match (args.get("rows"), args.get("results")) {
        (Some(_), Some(_)) => Err(tera::Error::msg(format!(
            "{fn_name}() accepts either `rows` or `results`, not both — pick one convention"
        ))),
        (Some(v), None) => v.as_array().ok_or_else(|| {
            tera::Error::msg(format!("{fn_name}() requires an array `rows` argument"))
        }),
        (None, Some(v)) => v.as_array().ok_or_else(|| {
            tera::Error::msg(format!("{fn_name}() requires an array `results` argument"))
        }),
        (None, None) => Err(tera::Error::msg(format!(
            "{fn_name}() requires an array `rows` or `results` argument"
        ))),
    }
}

/// `sparql_first(rows=…)` / `sparql_first(results=…)` — the first row, or
/// `null` if empty. With `column="…"` given (under either convention),
/// returns just that column's value from the first row instead of the full
/// row object — `null` when the first row is not an object or lacks that
/// column, matching ggen-core's `SparqlFirstFn` result-shape semantics.
fn sparql_first_fn(args: &HashMap<String, Value>) -> tera::Result<Value> {
    let rows = rows_or_results_arg(args, "sparql_first")?;
    let Some(first) = rows.first() else {
        return Ok(Value::Null);
    };
    match args.get("column").and_then(Value::as_str) {
        Some(column) => Ok(first
            .as_object()
            .and_then(|o| o.get(column))
            .cloned()
            .unwrap_or(Value::Null)),
        None => Ok(first.clone()),
    }
}

/// `sparql_values(rows=…, column="…")` / `sparql_values(results=…,
/// column="…")` — the array of `column`'s value across every row
/// (missing/non-object rows contribute `null`). `column` is required under
/// either convention (unchanged from the engine's original `rows=`-only
/// behavior).
fn sparql_values_fn(args: &HashMap<String, Value>) -> tera::Result<Value> {
    let rows = rows_or_results_arg(args, "sparql_values")?;
    let column = args
        .get("column")
        .and_then(Value::as_str)
        .ok_or_else(|| tera::Error::msg("sparql_values() requires a string `column` argument"))?;
    let values: Vec<Value> = rows
        .iter()
        .map(|row| {
            row.as_object()
                .and_then(|o| o.get(column))
                .cloned()
                .unwrap_or(Value::Null)
        })
        .collect();
    Ok(Value::Array(values))
}

/// `sparql_empty(rows=…)` / `sparql_empty(results=…)` — `true` if the array
/// has no elements.
fn sparql_empty_fn(args: &HashMap<String, Value>) -> tera::Result<Value> {
    let rows = rows_or_results_arg(args, "sparql_empty")?;
    Ok(Value::Bool(rows.is_empty()))
}

/// `sparql_count(rows=…)` / `sparql_count(results=…)` — the number of rows.
fn sparql_count_fn(args: &HashMap<String, Value>) -> tera::Result<Value> {
    let rows = rows_or_results_arg(args, "sparql_count")?;
    Ok(Value::Number(rows.len().into()))
}

/// `hex_to_u64` filter: `"0x560b48233d2e635f"` (or `"560b48233d2e635f"`,
/// case-insensitive, optional `0x` prefix) → the JSON number `6197033906917782879`.
///
/// For emitting hex-encoded ontology literals (e.g. `ceng:caseSeed`) as a
/// plain integer where the consuming Rust type is numeric (`u64`), not a
/// string — the template layer converts once here instead of asking every
/// numeric-seed consumer to accept a hex-string encoding.
fn hex_to_u64_filter(value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
    let s = value
        .as_str()
        .ok_or_else(|| tera::Error::msg("hex_to_u64 filter requires a string"))?;
    let trimmed = s
        .strip_prefix("0x")
        .or_else(|| s.strip_prefix("0X"))
        .unwrap_or(s);
    let n = u64::from_str_radix(trimmed, 16)
        .map_err(|e| tera::Error::msg(format!("hex_to_u64: {s:?} is not valid hex: {e}")))?;
    Ok(Value::Number(n.into()))
}

// ── Case-conversion and inflection filters ──────────────────────────────
//
// All backed by the `Inflector` crate rather than hand-rolled string
// scanning (a prior version of this file hand-rolled each of these
// independently; replaced for consistency — one tested, maintained
// implementation of English case/inflection rules instead of N ad-hoc
// ones that could each drift from the others' edge-case handling). This
// mirrors Hygen's own `h.inflection.*`/`h.changeCase.*`, which are
// likewise backed by external libraries (node.inflection, change-case),
// not hand-rolled in Hygen's own codebase either.

/// `snake_case` filter: `FooBar`, `foo-bar`, `foo bar` → `foo_bar`.
#[allow(clippy::unnecessary_wraps)]
fn snake_case_filter(value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
    let s = value
        .as_str()
        .ok_or_else(|| tera::Error::msg("snake_case filter requires a string"))?;
    Ok(Value::String(s.to_snake_case()))
}

/// `pascal_case` filter: `foo_bar`, `foo-bar`, `foo bar` → `FooBar`.
#[allow(clippy::unnecessary_wraps)]
fn pascal_case_filter(value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
    let s = value
        .as_str()
        .ok_or_else(|| tera::Error::msg("pascal_case filter requires a string"))?;
    Ok(Value::String(s.to_pascal_case()))
}

/// `camel_case` filter: `foo_bar`, `FooBar`, `foo-bar` → `fooBar`
/// (lowerCamelCase — first word lowercase, subsequent words capitalized, no
/// separators).
#[allow(clippy::unnecessary_wraps)]
fn camel_case_filter(value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
    let s = value
        .as_str()
        .ok_or_else(|| tera::Error::msg("camel_case filter requires a string"))?;
    Ok(Value::String(s.to_camel_case()))
}

/// `kebab_case` filter: `foo_bar`, `FooBar`, `foo bar` → `foo-bar`.
#[allow(clippy::unnecessary_wraps)]
fn kebab_case_filter(value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
    let s = value
        .as_str()
        .ok_or_else(|| tera::Error::msg("kebab_case filter requires a string"))?;
    Ok(Value::String(s.to_kebab_case()))
}

/// `shouty_snake_case` filter: `foo_bar`, `FooBar`, `foo-bar` → `FOO_BAR`.
#[allow(clippy::unnecessary_wraps)]
fn shouty_snake_case_filter(value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
    let s = value
        .as_str()
        .ok_or_else(|| tera::Error::msg("shouty_snake_case filter requires a string"))?;
    Ok(Value::String(s.to_screaming_snake_case()))
}

/// `title_case` filter: `foo_bar`, `FooBar`, `foo-bar` → `Foo Bar`.
#[allow(clippy::unnecessary_wraps)]
fn title_case_filter(value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
    let s = value
        .as_str()
        .ok_or_else(|| tera::Error::msg("title_case filter requires a string"))?;
    Ok(Value::String(s.to_title_case()))
}

/// `pluralize` filter: English pluralization (`bus`→`buses`, `city`→
/// `cities`, `cat`→`cats`; also handles some, not all, irregulars —
/// `goose`→`geese`, `man`→`men`, `woman`→`women`, `tooth`→`teeth`,
/// `foot`→`feet` verified correct; `person`→`"personople"` is a confirmed,
/// real gap in this filter's underlying library (Inflector 0.11.4), not
/// silently glossed over — see this file's own
/// `pluralize_singularize_known_inflector_gaps_are_pinned_not_silent` test).
#[allow(clippy::unnecessary_wraps)]
fn pluralize_filter(value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
    let s = value
        .as_str()
        .ok_or_else(|| tera::Error::msg("pluralize filter requires a string"))?;
    Ok(Value::String(s.to_plural()))
}

/// `singularize` filter: reverse of `pluralize` (`buses`→`bus`, `cities`→
/// `city`, `cats`→`cat`, `mice`→`mouse`, `geese`→`goose`, `men`→`man`,
/// `women`→`woman`, `teeth`→`tooth`, `feet`→`foot` — all verified correct).
/// `children`/`people` do NOT singularize (both left unchanged) — a
/// confirmed gap in the underlying library, pinned by a test rather than
/// silently wrong, same caveat as `pluralize` above.
#[allow(clippy::unnecessary_wraps)]
fn singularize_filter(value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
    let s = value
        .as_str()
        .ok_or_else(|| tera::Error::msg("singularize filter requires a string"))?;
    Ok(Value::String(s.to_singular()))
}

/// `ordinalize` filter: `"1"` → `"1st"`, `"2"` → `"2nd"`, `"11"` →
/// `"11th"`. Hygen's `h.inflection.ordinalize` equivalent — no ggen
/// predecessor had this at all (a genuinely new capability, not a
/// hand-rolled-to-library migration like the filters above).
#[allow(clippy::unnecessary_wraps)]
fn ordinalize_filter(value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
    let s = value
        .as_str()
        .ok_or_else(|| tera::Error::msg("ordinalize filter requires a string"))?;
    Ok(Value::String(s.ordinalize()))
}

/// `demodulize` filter: `"Foo::Bar::Baz"` → `"Baz"` — strips a Rust/Ruby-
/// style module path down to its final segment. Hygen's
/// `h.inflection.demodulize` equivalent.
#[allow(clippy::unnecessary_wraps)]
fn demodulize_filter(value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
    let s = value
        .as_str()
        .ok_or_else(|| tera::Error::msg("demodulize filter requires a string"))?;
    Ok(Value::String(s.demodulize().clone()))
}

/// `foreign_key` filter: `"Message"` → `"message_id"` — the Rails-style
/// foreign-key column-name convention. Hygen's `h.inflection.foreign_key`
/// equivalent.
#[allow(clippy::unnecessary_wraps)]
fn foreign_key_filter(value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
    let s = value
        .as_str()
        .ok_or_else(|| tera::Error::msg("foreign_key filter requires a string"))?;
    Ok(Value::String(s.to_foreign_key()))
}

/// `tableize` filter: `"RawScaledScorer"` → `"raw_scaled_scorers"` — plural
/// `snake_case`, the Rails table-naming convention. Hygen's
/// `h.inflection.tableize` equivalent.
#[allow(clippy::unnecessary_wraps)]
fn tableize_filter(value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
    let s = value
        .as_str()
        .ok_or_else(|| tera::Error::msg("tableize filter requires a string"))?;
    Ok(Value::String(s.to_table_case()))
}

/// `classify` filter: `"line_items"` → `"LineItem"` — singular `PascalCase`,
/// the Rails class-naming convention (roughly `tableize`'s inverse).
/// Hygen's `h.inflection.classify` equivalent.
#[allow(clippy::unnecessary_wraps)]
fn classify_filter(value: &Value, _args: &HashMap<String, Value>) -> tera::Result<Value> {
    let s = value
        .as_str()
        .ok_or_else(|| tera::Error::msg("classify filter requires a string"))?;
    Ok(Value::String(s.to_class_case()))
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    const TTL: &str = r#"
        @prefix ex: <http://example.org/> .
        ex:alice ex:name "alice_smith" .
        ex:bob   ex:name "bob_jones" .
    "#;

    fn graph() -> Arc<dyn GraphEngine> {
        let g = crate::graph::DeterministicGraph::new().expect("graph");
        g.insert_turtle(TTL).expect("ttl");
        Arc::new(g)
    }

    #[test]
    fn sparql_row_keys_are_bare_not_question_mark_prefixed() {
        // Direct regression guard for a confirmed bug in ~/ggen's rendering
        // engine (ggen-core/src/pipeline.rs builds row keys with
        // `var.to_string()`, whose `Display` impl is `write!(f, "?{name}")`,
        // forcing template authors to write `row["?name"]`). This crate's
        // `sparql_to_value` must keep using `Variable::as_str()` (bare name,
        // no `?`), so `row.name` works directly. If this test ever fails
        // after touching `sparql_to_value`, that's this exact regression.
        let value = sparql_to_value(
            graph().as_ref(),
            "SELECT ?name WHERE { ?s <http://example.org/name> ?name } ORDER BY ?name",
        )
        .expect("query");
        let rows = value.as_array().expect("array");
        let first = rows[0].as_object().expect("object");
        assert!(
            first.contains_key("name"),
            "row must have bare key `name`: {first:?}"
        );
        assert!(
            !first.contains_key("?name"),
            "row must NOT have `?`-prefixed key `?name`: {first:?}"
        );
    }

    #[test]
    fn parse_and_render_with_sparql_against_graph() {
        let content = "---\nto: out.rs\nsparql:\n  people: SELECT ?name WHERE { ?s <http://example.org/name> ?name } ORDER BY ?name\n---\n{% for row in sparql(query=q) %}{{ row.name | pascal_case }};{% endfor %}";
        let tpl = Template::parse(content).expect("parse");
        assert_eq!(tpl.frontmatter.to, "out.rs");
        let q = tpl.frontmatter.sparql.get("people").expect("query").clone();

        let mut tera = build_tera(graph()).expect("build tera");
        let mut ctx = tera::Context::new();
        ctx.insert("q", &q);
        let rendered = tera.render_str(&tpl.body, &ctx).expect("render");
        assert_eq!(rendered, "AliceSmith;BobJones;");
    }

    #[test]
    fn ask_query_returns_bool() {
        let tera = build_tera(graph()).expect("build tera");
        let mut t = tera;
        let rendered = t
            .render_str(
                "{% if sparql(query=\"ASK { ?s ?p ?o }\") %}yes{% else %}no{% endif %}",
                &tera::Context::new(),
            )
            .expect("render");
        assert_eq!(rendered, "yes");
    }

    #[test]
    fn construct_returns_triples() {
        let mut tera = build_tera(graph()).expect("build tera");
        let rendered = tera
            .render_str(
                "{% set ts = sparql(query=\"CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }\") %}{{ ts | length }}",
                &tera::Context::new(),
            )
            .expect("render");
        assert_eq!(rendered, "2");
    }

    #[test]
    fn unknown_frontmatter_key_is_err() {
        let content = "---\nto: out.rs\nvars:\n  x: 1\n---\nbody";
        let err = Template::parse(content).expect_err("must reject `vars:`");
        assert!(err.to_string().contains("FM-TPL-002"), "{err}");
    }

    #[test]
    fn missing_frontmatter_is_err() {
        let err = Template::parse("no frontmatter here").expect_err("must reject");
        assert!(err.to_string().contains("FM-TPL-001"), "{err}");
    }

    #[test]
    fn snake_and_pascal_filters() {
        let mut tera = build_tera(graph()).expect("build tera");
        let rendered = tera
            .render_str(
                "{{ \"FooBarBaz\" | snake_case }} {{ \"foo_bar-baz qux\" | pascal_case }}",
                &tera::Context::new(),
            )
            .expect("render");
        assert_eq!(rendered, "foo_bar_baz FooBarBazQux");
    }

    #[test]
    fn camel_kebab_shouty_title_filters() {
        let mut tera = build_tera(graph()).expect("build tera");
        let rendered = tera
            .render_str(
                "{{ \"foo_bar-baz\" | camel_case }} \
                 {{ \"FooBarBaz\" | kebab_case }} \
                 {{ \"foo-bar baz\" | shouty_snake_case }} \
                 {{ \"foo_bar-baz\" | title_case }}",
                &tera::Context::new(),
            )
            .expect("render");
        assert_eq!(rendered, "fooBarBaz foo-bar-baz FOO_BAR_BAZ Foo Bar Baz");
    }

    #[test]
    fn pluralize_and_singularize_filters() {
        let mut tera = build_tera(graph()).expect("build tera");
        let rendered = tera
            .render_str(
                "{{ \"cat\" | pluralize }} {{ \"city\" | pluralize }} {{ \"bus\" | pluralize }} \
                 {{ \"cats\" | singularize }} {{ \"cities\" | singularize }} {{ \"buses\" | singularize }}",
                &tera::Context::new(),
            )
            .expect("render");
        assert_eq!(rendered, "cats cities buses cat city bus");
    }

    #[test]
    fn pluralize_singularize_handle_some_irregulars_via_inflector() {
        // The prior hand-rolled heuristic could not handle irregular
        // plurals at all. Inflector handles SOME — verified directly
        // against the library's real output (a standalone probe run while
        // building this feature), not assumed: `goose`/`man`/`woman`/
        // `tooth`/`foot` pluralize correctly, and `mice`/`geese`/`men`/
        // `women`/`teeth`/`feet` singularize correctly.
        let mut tera = build_tera(graph()).expect("build tera");
        let rendered = tera
            .render_str(
                "{{ \"goose\" | pluralize }} {{ \"man\" | pluralize }} \
                 {{ \"woman\" | pluralize }} {{ \"tooth\" | pluralize }} \
                 {{ \"foot\" | pluralize }} \
                 {{ \"mice\" | singularize }} {{ \"geese\" | singularize }} \
                 {{ \"men\" | singularize }} {{ \"women\" | singularize }} \
                 {{ \"teeth\" | singularize }} {{ \"feet\" | singularize }}",
                &tera::Context::new(),
            )
            .expect("render");
        assert_eq!(
            rendered,
            "geese men women teeth feet mouse goose man woman tooth foot"
        );
    }

    #[test]
    fn pluralize_singularize_known_inflector_gaps_are_pinned_not_silent() {
        // Real, verified gaps in Inflector 0.11.4's own irregular table —
        // NOT a ggen bug, but pinned here so a future Inflector upgrade
        // that fixes these is noticed (test starts failing) rather than
        // the gap silently persisting undocumented. Confirmed by direct
        // probe before writing this: `person` pluralizes to the garbled
        // `"personople"` (not `"people"`), and singularizing `"children"`/
        // `"people"` leaves them unchanged (not `"child"`/`"person"`).
        let mut tera = build_tera(graph()).expect("build tera");
        let rendered = tera
            .render_str(
                "{{ \"person\" | pluralize }} {{ \"children\" | singularize }} \
                 {{ \"people\" | singularize }}",
                &tera::Context::new(),
            )
            .expect("render");
        assert_eq!(rendered, "personople children people");
    }

    #[test]
    fn true_inflection_filters_ordinalize_demodulize_foreign_key_tableize_classify() {
        let mut tera = build_tera(graph()).expect("build tera");
        let rendered = tera
            .render_str(
                "{{ \"1\" | ordinalize }} {{ \"2\" | ordinalize }} {{ \"11\" | ordinalize }} \
                 {{ \"Foo::Bar::Baz\" | demodulize }} \
                 {{ \"Message\" | foreign_key }} \
                 {{ \"RawScaledScorer\" | tableize }} \
                 {{ \"line_items\" | classify }}",
                &tera::Context::new(),
            )
            .expect("render");
        assert_eq!(
            rendered,
            "1st 2nd 11th Baz message_id raw_scaled_scorers LineItem"
        );
    }

    #[test]
    fn local_function_strips_namespace() {
        let mut tera = build_tera(graph()).expect("build tera");
        let rendered = tera
            .render_str(
                "{{ local(iri=\"http://example.org/name\") }} \
                 {{ local(iri=\"http://example.org/ns#Widget\") }} \
                 {{ local(iri=\"plain\") }}",
                &tera::Context::new(),
            )
            .expect("render");
        assert_eq!(rendered, "name Widget plain");
    }

    #[test]
    fn sparql_first_values_empty_count_functions() {
        let mut tera = build_tera(graph()).expect("build tera");
        let rendered = tera
            .render_str(
                "{% set rows = sparql(query=\"SELECT ?name WHERE { ?s <http://example.org/name> ?name } ORDER BY ?name\") %}\
                 {% set first = sparql_first(rows=rows) %}\
                 {{ first.name }};\
                 {{ sparql_values(rows=rows, column=\"name\") | join(sep=\",\") }};\
                 {{ sparql_count(rows=rows) }};\
                 {{ sparql_empty(rows=rows) }};\
                 {{ sparql_empty(rows=[]) }}",
                &tera::Context::new(),
            )
            .expect("render");
        assert_eq!(rendered, "alice_smith;alice_smith,bob_jones;2;false;true");
    }

    #[test]
    fn sparql_first_on_empty_rows_is_null() {
        let mut tera = build_tera(graph()).expect("build tera");
        let rendered = tera
            .render_str("{{ sparql_first(rows=[]) }}", &tera::Context::new())
            .expect("render");
        assert_eq!(
            rendered, "",
            "Tera renders a Value::Null function result as empty output"
        );
    }

    // ---- Gap 2: bare filter aliases (snake, pascal, camel, kebab, title) ----

    #[test]
    fn filter_aliases_match_full_names_byte_identical() {
        let mut tera = build_tera(graph()).expect("build tera");
        for s in ["hello_world_example", "HelloWorldExample"] {
            let mut ctx = tera::Context::new();
            ctx.insert("v", s);
            let rendered = tera
                .render_str(
                    "{{ v | snake }}|{{ v | snake_case }}|\
                     {{ v | pascal }}|{{ v | pascal_case }}|\
                     {{ v | camel }}|{{ v | camel_case }}|\
                     {{ v | kebab }}|{{ v | kebab_case }}|\
                     {{ v | title }}|{{ v | title_case }}|\
                     {{ v | shouty }}|{{ v | shouty_snake_case }}",
                    &ctx,
                )
                .expect("render");
            let parts: Vec<&str> = rendered.split('|').collect();
            assert_eq!(parts.len(), 12, "unexpected render shape: {rendered:?}");
            assert_eq!(parts[0], parts[1], "snake alias mismatch for {s}");
            assert_eq!(parts[2], parts[3], "pascal alias mismatch for {s}");
            assert_eq!(parts[4], parts[5], "camel alias mismatch for {s}");
            assert_eq!(parts[6], parts[7], "kebab alias mismatch for {s}");
            assert_eq!(parts[8], parts[9], "title alias mismatch for {s}");
            assert_eq!(parts[10], parts[11], "shouty alias mismatch for {s}");
        }
    }

    // ---- Gap 3: sparql_* rows=/results= reconciliation ----

    #[test]
    fn sparql_first_values_accept_results_alias_and_column_extraction() {
        let mut tera = build_tera(graph()).expect("build tera");
        let rendered = tera
            .render_str(
                "{% set rows = sparql(query=\"SELECT ?name WHERE { ?s <http://example.org/name> ?name } ORDER BY ?name\") %}\
                 {% set first_full = sparql_first(results=rows) %}\
                 {{ first_full.name }};\
                 {{ sparql_first(results=rows, column=\"name\") }};\
                 {{ sparql_values(results=rows, column=\"name\") | join(sep=\",\") }};\
                 {{ sparql_empty(results=rows) }};\
                 {{ sparql_count(results=rows) }}",
                &tera::Context::new(),
            )
            .expect("render");
        assert_eq!(
            rendered, "alice_smith;alice_smith;alice_smith,bob_jones;false;2",
            "results= must behave identically to rows=, and results=+column= \
             must extract the scalar/list for that column"
        );
    }

    #[test]
    fn sparql_functions_reject_both_rows_and_results() {
        let mut tera = build_tera(graph()).expect("build tera");
        for call in [
            "sparql_first(rows=[], results=[])",
            "sparql_values(rows=[], results=[], column=\"x\")",
            "sparql_empty(rows=[], results=[])",
            "sparql_count(rows=[], results=[])",
        ] {
            let err = tera
                .render_str(&format!("{{{{ {call} }}}}"), &tera::Context::new())
                .unwrap_err();
            // Tera's `Display` only prints the outer "Failed to render"
            // wrapper, not the chained function-call cause — `{:?}` walks
            // the full `source` chain (`Error { kind, source: Some(..) }`),
            // which is where our own message actually lands.
            assert!(
                format!("{err:?}").contains("not both"),
                "{call} must refuse rows=+results= loudly: {err:?}"
            );
        }
    }

    // ---- Gap 4: flexible `sparql:` frontmatter deserializer ----

    #[test]
    fn sparql_field_accepts_bare_string_and_sequence_forms() {
        const QUERY: &str =
            "SELECT ?name WHERE { ?s <http://example.org/name> ?name } ORDER BY ?name";
        let map_tpl = Template::parse(&format!(
            "---\nto: out.rs\nsparql:\n  people: {QUERY}\n---\nbody"
        ))
        .expect("map form parses");
        let bare_tpl = Template::parse(&format!("---\nto: out.rs\nsparql: {QUERY}\n---\nbody"))
            .expect("bare form parses");
        let seq_tpl = Template::parse(&format!("---\nto: out.rs\nsparql:\n  - {QUERY}\n---\nbody"))
            .expect("sequence form parses");

        assert_eq!(
            map_tpl.frontmatter.sparql.get("people").map(String::as_str),
            Some(QUERY)
        );
        assert_eq!(
            bare_tpl
                .frontmatter
                .sparql
                .get("default")
                .map(String::as_str),
            Some(QUERY),
            "bare string must be named `default`, matching ggen-core's convention"
        );
        assert_eq!(
            seq_tpl.frontmatter.sparql.get("query_0").map(String::as_str),
            Some(QUERY),
            "sequence entries must be named `query_0`, `query_1`, …, matching ggen-core's convention"
        );
    }

    #[test]
    fn bare_string_sparql_field_is_queryable_same_as_map_form() {
        let content = "---\nto: out.rs\nsparql: SELECT ?name WHERE { ?s <http://example.org/name> ?name } ORDER BY ?name\n---\n{% for row in sparql(query=q) %}{{ row.name | pascal_case }};{% endfor %}";
        let tpl = Template::parse(content).expect("parse");
        let q = tpl
            .frontmatter
            .sparql
            .get("default")
            .expect("default query")
            .clone();

        let mut tera = build_tera(graph()).expect("build tera");
        let mut ctx = tera::Context::new();
        ctx.insert("q", &q);
        let rendered = tera.render_str(&tpl.body, &ctx).expect("render");
        assert_eq!(
            rendered, "AliceSmith;BobJones;",
            "identical to the mapping-form test `parse_and_render_with_sparql_against_graph`"
        );
    }
}