oxdock-process 0.44.0-alpha

Process orchestration for OxDock environments.
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
use std::collections::HashMap;
use std::sync::Arc;

use anyhow::{Result, anyhow, bail};

use crate::contract::CommandContext;

/// Maximum bytes to buffer while scanning for closing delimiter.
/// If exceeded without finding closing delimiter, buffered bytes are flushed as literals.
const MAX_PLACEHOLDER_SCAN: usize = 1024;

/// Configurable delimiter syntax for template expansion.
pub struct TemplateDelimiters {
    pub open: &'static [u8],
    pub close: &'static [u8],
}

impl Default for TemplateDelimiters {
    fn default() -> Self {
        Self {
            open: b"{{",
            close: b"}}",
        }
    }
}

/// Resolver for `{{ MODULE::FUNC(args) }}` placeholder calls.
///
/// Receives the module name, function name, and already resolved argument
/// values, and returns the call result. Only pure value returning host
/// functions may back this: no handles, no pipes, no I/O. The resolver
/// carries no formatting logic; formatting lives with the function.
pub type PlaceholderCall = Arc<
    dyn Fn(&str, &str, Vec<oxdock_parser::Value>) -> Result<oxdock_parser::Value> + Send + Sync,
>;

/// Streaming template expansion state machine.
///
/// Processes input bytes incrementally, expanding `{{ env:KEY }}` placeholders.
/// At most `MAX_PLACEHOLDER_SCAN` bytes are held in buffer. Plain text streams
/// flush immediately with zero buffering.
pub struct StreamingExpand {
    /// Bytes accumulated as key payload inside `{{ ... }}` (no open delimiter prefix).
    buffer: Vec<u8>,
    /// Explicit key=value overrides (take precedence over env).
    overrides: HashMap<String, String>,
    /// Environment variable lookup.
    env: HashMap<String, String>,
    /// Structured variable lookup (for key-path evaluation).
    vars: HashMap<String, oxdock_parser::Value>,
    /// Optional dispatcher for `{{ MODULE::FUNC(args) }}` calls. When set,
    /// placeholders holding a call expression are evaluated through it.
    /// Carries dispatch only; formatting stays with the callee.
    call_resolver: Option<PlaceholderCall>,
    /// State: are we currently inside a placeholder?
    in_placeholder: bool,
    /// Trailing opening byte from previous chunk : deferred across chunks.
    pending_brace: bool,
    /// Trailing closing byte from previous chunk : deferred across chunks.
    pending_close_brace: bool,
    /// Trailing backslash from previous chunk : deferred across chunks so
    /// `\{{` split across a boundary still emits a literal opener.
    pending_escape: bool,
    /// Trailing `\` + `{` from previous chunk : deferred across chunks so
    /// a `\{` split across a boundary still resolves as an escape pair.
    pending_escape_brace: bool,
    /// Configurable delimiter syntax.
    delimiters: TemplateDelimiters,
}

impl StreamingExpand {
    /// Create with env vars and optional explicit overrides.
    /// Overrides take precedence over env vars.
    pub fn new(overrides: &[(String, String)], env: &HashMap<String, String>) -> Self {
        Self {
            buffer: Vec::with_capacity(256),
            overrides: overrides.iter().cloned().collect(),
            env: env.clone(),
            vars: HashMap::new(),
            call_resolver: None,
            in_placeholder: false,
            pending_brace: false,
            pending_close_brace: false,
            pending_escape: false,
            pending_escape_brace: false,
            delimiters: TemplateDelimiters::default(),
        }
    }

    /// Create with env vars, structured variables, and optional explicit overrides.
    /// Enables key-path evaluation in template tags (e.g., `{{ pkg.package.name }}`).
    pub fn with_vars(mut self, vars: &HashMap<String, oxdock_parser::Value>) -> Self {
        self.vars = vars.clone();
        self
    }

    /// Enable `{{ MODULE::FUNC(args) }}` calls, dispatched through `resolver`.
    /// Args are `$var.path` references, string, int, float, and bool
    /// literals, or `{key: value}` and `[item]` literals nesting those
    /// same shapes. Unknown functions and bad arity fail strict at expansion.
    pub fn with_call_resolver(mut self, resolver: PlaceholderCall) -> Self {
        self.call_resolver = Some(resolver);
        self
    }

    /// Process a chunk of input bytes, writing expanded output to `out`.
    /// Returns early on empty input to preserve pending boundary state.
    pub fn process_bytes(&mut self, input: &[u8], out: &mut Vec<u8>) -> Result<usize> {
        if input.is_empty() {
            return Ok(0);
        }

        let start_len = out.len();
        let mut i = 0;

        // Handle pending close brace from previous chunk
        if self.pending_close_brace {
            self.pending_close_brace = false;
            if input[0] == self.delimiters.close[1] {
                // Confirmed close delimiter across boundary : extract key, lookup, emit
                let key = extract_key(&self.buffer);
                let value = lookup(
                    &key,
                    &self.overrides,
                    &self.env,
                    &self.vars,
                    self.call_resolver.as_ref(),
                )?;
                out.extend_from_slice(value.as_bytes());
                self.buffer.clear();
                self.in_placeholder = false;
                i = self.delimiters.close.len() - 1; // Skip input[0] (the second byte)
            } else {
                // Lone closing byte : treat as literal part of key
                // Push it to buffer, then let scan_placeholder process input[0]
                self.buffer.push(self.delimiters.close[0]);
                i = 0; // Do NOT skip input[0]: let scan_placeholder handle it
            }
        }

        // Handle pending open brace from previous chunk
        if self.pending_brace {
            self.pending_brace = false;
            if input[0] == self.delimiters.open[1] {
                // Confirmed `{{` across boundary : enter PlaceholderScan
                self.in_placeholder = true;
                self.buffer.clear();
                i = 1; // Skip the second open byte
            } else {
                // Single open byte was just a literal : flush it
                out.push(self.delimiters.open[0]);
            }
        }

        // Handle pending escape pair from previous chunk: a trailing `\{`
        // combines with a leading `{` into a literal opener. Anything
        // else means both bytes were literal; re-emit them, then let the
        // scan below handle this chunk from the start.
        if self.pending_escape_brace {
            self.pending_escape_brace = false;
            if !input.is_empty() && input[0] == self.delimiters.open[1] {
                out.extend_from_slice(b"{{");
                i = 1;
            } else {
                out.push(b'\\');
                out.push(self.delimiters.open[0]);
            }
        }

        // Handle pending escape from previous chunk: a lone trailing `\`
        // combines with a leading `{{` into a literal opener, or with a
        // leading `\` into a literal backslash (the pair is complete, so
        // whatever follows processes normally). A lone trailing `{`
        // cannot decide yet, so it joins the deferred pair above.
        if self.pending_escape {
            self.pending_escape = false;
            if input.len() >= 2 && input[0] == b'{' && input[1] == b'{' {
                out.extend_from_slice(b"{{");
                i = 2;
            } else if input.len() == 1 && input[0] == self.delimiters.open[0] {
                self.pending_escape_brace = true;
                i = 1;
            } else if !input.is_empty() && input[0] == b'\\' {
                out.push(b'\\');
                i = 1;
            } else {
                // Not an escape : the backslash was literal; reprocess
                // this chunk from the start (a lone `{` still defers via
                // the pending_brace path below).
                out.push(b'\\');
            }
        }

        if self.in_placeholder {
            // We're inside a placeholder : scan for closing delimiter
            i = self.scan_placeholder(input, i, out)?;
        }

        // Normal state : scan for opening byte or flush literals
        while i < input.len() {
            if input[i] == b'\\' {
                if i + 2 < input.len() && input[i + 1] == b'{' && input[i + 2] == b'{' {
                    // Escaped opener : emit a literal `{{`, consume all three
                    out.extend_from_slice(b"{{");
                    i += 3;
                } else if i + 2 == input.len() && input[i + 1] == self.delimiters.open[0] {
                    // `\{` ends the chunk : defer the pair; the next
                    // chunk decides literal `{{` vs literal `\` + `{`.
                    self.pending_escape_brace = true;
                    i += 2;
                } else if i + 1 < input.len() && input[i + 1] == b'\\' {
                    // Escaped backslash : emit one `\`, consume both (this
                    // keeps `\\{{ ... }}` expanding, matching the lenient
                    // interpolator used for command arguments)
                    out.push(b'\\');
                    i += 2;
                } else if i + 1 == input.len() {
                    // Trailing backslash : defer across the chunk boundary
                    self.pending_escape = true;
                    i += 1;
                } else {
                    // Ordinary backslash : literal, reprocess what follows
                    out.push(b'\\');
                    i += 1;
                }
            } else if input[i] == self.delimiters.open[0] {
                if i + 1 < input.len() && input[i + 1] == self.delimiters.open[1] {
                    // Found open delimiter : enter PlaceholderScan
                    self.in_placeholder = true;
                    self.buffer.clear();
                    i += 2;
                    i = self.scan_placeholder(input, i, out)?;
                } else if i + 1 == input.len() {
                    // Opening byte is the LAST byte of chunk : defer
                    self.pending_brace = true;
                    i += 1;
                } else {
                    // Single opening byte in the middle : flush as literal
                    out.push(self.delimiters.open[0]);
                    i += 1;
                }
            } else {
                // Flush literal bytes until we find an opening byte, a
                // backslash (potential `\{{` escape), or end of chunk
                let start = i;
                while i < input.len() && input[i] != self.delimiters.open[0] && input[i] != b'\\' {
                    i += 1;
                }
                out.extend_from_slice(&input[start..i]);
            }
        }

        Ok(out.len() - start_len)
    }

    /// Flush remaining buffer. Incomplete placeholders are treated as literals.
    pub fn flush(mut self, out: &mut Vec<u8>) -> Result<()> {
        // Emit deferred closing byte if present
        if self.pending_close_brace {
            self.buffer.push(self.delimiters.close[0]);
            self.pending_close_brace = false;
        }
        // Emit deferred opening byte if present
        if self.pending_brace {
            out.push(self.delimiters.open[0]);
            self.pending_brace = false;
        }
        // Emit deferred backslash if present
        if self.pending_escape {
            out.push(b'\\');
            self.pending_escape = false;
        }
        // Emit deferred escape pair if present
        if self.pending_escape_brace {
            out.push(b'\\');
            out.push(self.delimiters.open[0]);
            self.pending_escape_brace = false;
        }
        // If inside placeholder, emit open delimiter prefix ONCE before buffer
        if self.in_placeholder {
            out.extend_from_slice(self.delimiters.open);
            self.in_placeholder = false;
        }
        // Flush remaining buffer as literal text
        out.extend_from_slice(&self.buffer);
        self.buffer.clear();
        Ok(())
    }

    /// Process a complete string (convenience for short command arguments).
    pub fn expand_string(self, input: &str) -> Result<String> {
        let mut out = Vec::with_capacity(input.len());
        let mut expander = self;
        expander.process_bytes(input.as_bytes(), &mut out)?;
        expander.flush(&mut out)?;
        Ok(String::from_utf8(out).unwrap_or_default())
    }

    /// Scan for closing delimiter starting at position `i`.
    /// Returns the next position to process after the placeholder.
    fn scan_placeholder(&mut self, input: &[u8], mut i: usize, out: &mut Vec<u8>) -> Result<usize> {
        while i < input.len() {
            if input[i] == self.delimiters.close[0] {
                if i + 1 < input.len() && input[i + 1] == self.delimiters.close[1] {
                    // Found closing delimiter : extract key, lookup, emit expansion
                    let key = extract_key(&self.buffer);
                    let value = lookup(
                        &key,
                        &self.overrides,
                        &self.env,
                        &self.vars,
                        self.call_resolver.as_ref(),
                    )?;
                    out.extend_from_slice(value.as_bytes());
                    self.buffer.clear();
                    self.in_placeholder = false;
                    return Ok(i + 2);
                }
                if i + 1 == input.len() {
                    // Closing byte is the LAST byte : defer to next chunk
                    self.pending_close_brace = true;
                    return Ok(i + 1);
                }
            }
            self.buffer.push(input[i]);
            i += 1;

            // Buffer limit exceeded : flush as literal
            if self.buffer.len() > MAX_PLACEHOLDER_SCAN {
                out.extend_from_slice(self.delimiters.open);
                out.extend_from_slice(&self.buffer);
                self.buffer.clear();
                self.in_placeholder = false;
                return Ok(i);
            }
        }
        Ok(i)
    }
}

/// Extract and trim key from buffer content (the bytes between delimiters).
fn extract_key(buffer: &[u8]) -> String {
    String::from_utf8_lossy(buffer).trim().to_string()
}

/// Lookup a key in overrides and env, stripping namespace prefixes.
///
/// Strict resolution contract:
/// - `{{ KEY }}` (bare) → overrides only
/// - `{{ env:KEY }}` → overrides then env
/// - `{{ $var }}` → script vars
/// - `{{ $var.field }}` → script var key-path
/// - `{{ MODULE::FUNC(args) }}` → placeholder call via `calls`
///
/// All missing or invalid references return an error.
fn lookup(
    raw_key: &str,
    overrides: &HashMap<String, String>,
    env: &HashMap<String, String>,
    vars: &HashMap<String, oxdock_parser::Value>,
    calls: Option<&PlaceholderCall>,
) -> Result<String> {
    use oxdock_parser::template::{PlaceholderKey, classify_placeholder_key, split_var_path};
    let key = raw_key.trim();

    // 1. Explicit overrides (command-level CLI flags: KEY=val)
    if let Some(val) = overrides.get(key) {
        return Ok(val.clone());
    }

    // Shapes below come from the single template owner: this keeps
    // its own order (overrides first), sources, and errors.
    match classify_placeholder_key(key) {
        // 2. Environment variables: must be prefixed with "env:"
        PlaceholderKey::Env(env_key) => {
            // Trim once up front like the static gate and the
            // script-engine expansion, so `{{ env: FOO }}` looks up
            // `FOO` (never the padded spelling) on every layer.
            let env_key = env_key.trim();
            // Empty names bail explicitly (same message as the miss
            // below) instead of relying on the lookup miss alone.
            if env_key.is_empty() {
                bail!("undefined environment variable: ''");
            }
            if let Some(val) = overrides.get(env_key).or_else(|| env.get(env_key)) {
                return Ok(val.clone());
            }
            let hint = if vars.contains_key(env_key) {
                format!("; did you mean '${env_key}' (script variable)?")
            } else {
                String::new()
            };
            bail!("undefined environment variable: '{env_key}'{hint}");
        }

        // 3. Script variables: must be prefixed with "$". Path split
        // through the single template owner; dotted paths traverse
        // strictly, plain names read directly.
        PlaceholderKey::Dollar(rest) => {
            let parts = split_var_path(rest);
            if parts.len() == 1 {
                if let Some(val) = vars.get(&parts[0]) {
                    return format_value_for_string(val);
                }
                let hint = if env.contains_key(rest) {
                    format!("; did you mean 'env:{rest}' (environment variable)?")
                } else if overrides.contains_key(rest) {
                    format!("; did you mean '{rest}' (step override)?")
                } else {
                    String::new()
                };
                bail!("undefined script variable: '${rest}'{hint}");
            }
            return resolve_key_path_strict(&parts, vars);
        }

        // 4. Placeholder calls: `MODULE::FUNC(args)` dispatches through
        // the registered resolver. Without one, the shape falls through
        // to the invalid placeholder error below. Bare heads are not
        // resolvable here: they fail as invalid placeholders, never as
        // missing keys.
        PlaceholderKey::Call(call) => {
            let Some(module) = call.module else {
                // Bare `FUNC(...)` has no registry entry in override
                // expansion: explicit invalid-format error, never silent
                // fallthrough.
                bail!(
                    "invalid placeholder format '{key}': script variables must start with '$' and environment variables with 'env:'"
                );
            };
            let (name, args_raw) = (call.name, call.args_raw);
            let Some(resolver) = calls else {
                bail!(
                    "placeholder call '{module}::{name}' has no function registry; register one with with_call_resolver"
                );
            };
            let args_src = oxdock_parser::template::split_placeholder_args(args_raw);
            let mut args = Vec::with_capacity(args_src.len());
            for src in args_src {
                args.push(resolve_call_arg(&src, vars)?);
            }
            let result = resolver(module, name, args)?;
            return format_value_for_string(&result);
        }

        // 5. Unprefixed key: could be a missing step override or invalid
        // syntax. `script_env:` has no meaning in this context: it reads
        // as invalid exactly like any other non-shape. Qualified CONST
        // shapes never resolve here (no CONST store) and fall through
        // to the invalid-format error below. Bare idents (`Var` and
        // `Bare`) name missing overrides, exactly as before.
        // `$ALIAS::NAME` is invalid here like everywhere: the split
        // lives in the template owner.
        PlaceholderKey::DollarQualified { .. } => {
            bail!(
                "invalid placeholder format '{key}': script variables must start with '$' and environment variables with 'env:'"
            );
        }
        PlaceholderKey::ConstRef { .. } | PlaceholderKey::KeyPath { .. } => {}
        PlaceholderKey::Var(name) | PlaceholderKey::Bare(name) => {
            if !name.is_empty()
                && name
                    .chars()
                    .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
            {
                let hint = if vars.contains_key(name) {
                    format!("; did you mean '${name}' (script variable)?")
                } else if env.contains_key(name) {
                    format!("; did you mean 'env:{name}' (environment variable)?")
                } else {
                    String::new()
                };
                bail!("missing required step override argument: '{name}'{hint}");
            }
        }
        PlaceholderKey::ScriptEnv(name) => {
            // Empty names bail explicitly; non-empty `script_env:`
            // has no meaning here and falls through to the invalid
            // placeholder error below, as before.
            if name.trim().is_empty() {
                bail!("undefined environment variable: ''");
            }
        }
        PlaceholderKey::Empty => {}
    }
    bail!(
        "invalid placeholder format '{key}': script variables must start with '$' and environment variables with 'env:'"
    );
}

/// Split a `MODULE::FUNC(args)` placeholder body for call resolution
/// outside the streaming expander. Returns `None` when the body is not
/// call shaped, so plain keys keep their own handling. Single grammar
/// behind every phase: classifies through the shared
/// `oxdock_parser::template::classify_placeholder_key`, so runtime
/// dispatch and parse-time qualification can never disagree on what
/// counts as one call.
pub fn parse_placeholder_call(key: &str) -> Option<(String, String, Vec<String>)> {
    use oxdock_parser::template::{PlaceholderKey, classify_placeholder_key};
    let PlaceholderKey::Call(call) = classify_placeholder_key(key.trim()) else {
        return None;
    };
    let module = call.module?.to_string();
    let args = oxdock_parser::template::split_placeholder_args(call.args_raw);
    Some((module, call.name.to_string(), args))
}

/// Maximum nesting for map and list literals in placeholder call
/// args: the parser's shared argument depth budget.
const MAX_LITERAL_DEPTH: usize = oxdock_parser::template::MAX_TEMPLATE_ARG_DEPTH;

/// Resolve one placeholder call argument against script variables for
/// call resolution outside the streaming expander. Same grammar there:
/// `$var.path`, string, int, float, and bool literals, plus `{...}`
/// and `[...]` literals holding those shapes nested.
pub fn resolve_placeholder_arg(
    src: &str,
    vars: &HashMap<String, oxdock_parser::Value>,
) -> Result<oxdock_parser::Value> {
    resolve_call_arg(src, vars)
}

/// Resolve one call argument to a value: `$var.path` from vars, a
/// string, int, float, or bool literal, or a `{key: value}` map or
/// `[item]` list literal holding those same shapes nested.
fn resolve_call_arg(
    src: &str,
    vars: &HashMap<String, oxdock_parser::Value>,
) -> Result<oxdock_parser::Value> {
    resolve_call_value(src, vars, 0)
}

fn resolve_call_value(
    src: &str,
    vars: &HashMap<String, oxdock_parser::Value>,
    depth: usize,
) -> Result<oxdock_parser::Value> {
    use oxdock_parser::template::{
        ScalarLit, TemplateArg, classify_template_arg, parse_scalar_literal, parse_string_literal,
        parse_var_path,
    };
    if depth > MAX_LITERAL_DEPTH {
        bail!("placeholder call argument nests too deep (limit {MAX_LITERAL_DEPTH})");
    }
    match classify_template_arg(src) {
        TemplateArg::Dollar(rest) => {
            let Some(parts) = parse_var_path(rest) else {
                // `$` refs split through the single template owner; the
                // empty check below keeps the historical
                // malformed-argument error.
                bail!("invalid placeholder call argument: empty variable reference");
            };
            return resolve_value_path(&parts, vars);
        }
        TemplateArg::Str(literal_src) => {
            if let Some(literal) = parse_string_literal(literal_src) {
                return literal.map(oxdock_parser::Value::string);
            }
        }
        TemplateArg::Map(inner) => {
            return resolve_call_map(inner, vars, depth);
        }
        TemplateArg::List(inner) => {
            return resolve_call_list(inner, vars, depth);
        }
        TemplateArg::Scalar(scalar_src) => match parse_scalar_literal(scalar_src) {
            Some(ScalarLit::Bool(value)) => return Ok(oxdock_parser::Value::bool(value)),
            Some(ScalarLit::Int(value)) => return Ok(oxdock_parser::Value::int(value)),
            Some(ScalarLit::Float(value)) => return Ok(oxdock_parser::Value::float(value)),
            None => {}
        },
        // CONST shapes never resolve in override expansion (no CONST
        // store here); fall through to the invalid-argument error
        // below like any other unresolvable shape. `$ALIAS::NAME`
        // is invalid here like everywhere.
        TemplateArg::DollarQualified { .. } => {}
        TemplateArg::ConstRef { .. } | TemplateArg::KeyPath { .. } | TemplateArg::Var(_) => {}
        TemplateArg::Invalid(_) => {}
    }
    bail!(
        "invalid placeholder call argument '{src}': use $var.path, a string, int, float, or bool literal, or a {{key: value}} or [item] literal"
    )
}

/// Resolve a `{key: value}` map literal. Keys validate through the
/// shared key parser; values recurse through [`resolve_call_value`].
fn resolve_call_map(
    inner: &str,
    vars: &HashMap<String, oxdock_parser::Value>,
    depth: usize,
) -> Result<oxdock_parser::Value> {
    use oxdock_parser::template::{parse_map_key, split_map_entry, split_top_level};
    let mut entries = std::collections::BTreeMap::new();
    if inner.trim().is_empty() {
        return Ok(oxdock_parser::Value::map(entries));
    }
    for entry in split_top_level(inner, ',') {
        let Some((key_src, value_src)) = split_map_entry(&entry) else {
            bail!("invalid map literal entry '{entry}': use key: value");
        };
        let key = parse_map_key(&key_src)?;
        if entries.contains_key(&key) {
            bail!("duplicate key '{key}' in map literal");
        }
        let value = resolve_call_value(&value_src, vars, depth + 1)?;
        entries.insert(key, value);
    }
    Ok(oxdock_parser::Value::map(entries))
}

/// Resolve a `[item]` list literal, elements recursing through
/// [`resolve_call_value`].
fn resolve_call_list(
    inner: &str,
    vars: &HashMap<String, oxdock_parser::Value>,
    depth: usize,
) -> Result<oxdock_parser::Value> {
    let mut items = Vec::new();
    if inner.trim().is_empty() {
        return Ok(oxdock_parser::Value::list(items));
    }
    for item in oxdock_parser::template::split_top_level(inner, ',') {
        items.push(resolve_call_value(&item, vars, depth + 1)?);
    }
    Ok(oxdock_parser::Value::list(items))
}

/// Resolve a dotted path against vars, cloning the value for the caller.
/// Mirrors `resolve_key_path_strict` but returns the value instead of
/// its string form so calls receive typed arguments.
fn resolve_value_path(
    parts: &[String],
    vars: &HashMap<String, oxdock_parser::Value>,
) -> Result<oxdock_parser::Value> {
    if parts.is_empty() || parts[0].is_empty() {
        bail!("invalid placeholder call argument: empty variable reference");
    }
    let root_key = parts[0].as_str();
    let mut current = vars
        .get(root_key)
        .ok_or_else(|| anyhow!("undefined script variable: '${root_key}'"))?
        .clone();
    for segment in &parts[1..] {
        if segment.contains('(') || segment.contains(')') {
            bail!("nested calls are not supported in placeholder arguments");
        }
        if let Some(map) = current.as_map() {
            current = map
                .get(segment)
                .ok_or_else(|| anyhow!("property '{segment}' not found on object '${root_key}'"))?
                .clone();
        } else if let Some(list) = current.as_list() {
            let idx: usize = segment
                .parse()
                .map_err(|_| anyhow!("invalid array index '{segment}' on list '${root_key}'"))?;
            current = list
                .get(idx)
                .ok_or_else(|| {
                    anyhow!(
                        "index {idx} out of bounds for list '${root_key}' (len: {})",
                        list.len()
                    )
                })?
                .clone();
        } else {
            bail!("cannot access property '{segment}' on primitive value of '${root_key}'")
        }
    }
    Ok(current)
}

/// Resolve nested key-paths against the vars map.
///
/// Fails explicitly on missing object keys, out-of-bounds array indices,
/// or type mismatches (e.g. trying to access a property on a primitive).
fn resolve_key_path_strict(
    parts: &[String],
    vars: &HashMap<String, oxdock_parser::Value>,
) -> Result<String> {
    let root_key = parts[0].as_str();
    let mut current = vars
        .get(root_key)
        .ok_or_else(|| anyhow!("undefined script variable: '${root_key}'"))?;

    for segment in &parts[1..] {
        if let Some(map) = current.as_map() {
            current = map
                .get(segment)
                .ok_or_else(|| anyhow!("property '{segment}' not found on object '${root_key}'"))?;
        } else if let Some(list) = current.as_list() {
            let idx: usize = segment
                .parse()
                .map_err(|_| anyhow!("invalid array index '{segment}' on list '${root_key}'"))?;
            current = list.get(idx).ok_or_else(|| {
                anyhow!(
                    "index {idx} out of bounds for list '${root_key}' (len: {})",
                    list.len()
                )
            })?;
        } else {
            bail!("cannot access property '{segment}' on primitive value of '${root_key}'")
        }
    }

    format_value_for_string(current)
}

/// Format a Value as a string for inline interpolation.
/// Render a script value as inline text: the single renderer behind
/// placeholder expansion everywhere (streaming file templates and
/// engine string expansion alike), so one value renders one way in
/// every context. Pipes are refused: they carry streams between
/// steps, not text, and silently rendering a handle hides a bug.
///
/// Float rendering is defined as `f.to_string()`: Rust's `Display` for
/// `f64` already produces the shortest round-trip decimal (Ryū since
/// 1.36), so `ECHO` / `{{ }}` output stays clean (`3.14`, not
/// `3.140000`) with no extra dependency.
pub fn format_value_for_string(val: &oxdock_parser::Value) -> anyhow::Result<String> {
    if let Some(s) = val.as_str() {
        return Ok(s.to_string());
    }
    if let Some(i) = val.as_i64() {
        return Ok(i.to_string());
    }
    if let Some(f) = val.as_f64() {
        return Ok(f.to_string());
    }
    if let Some(b) = val.as_bool() {
        return Ok(b.to_string());
    }
    if val.as_pipe_handle().is_some() {
        anyhow::bail!(
            "cannot render PIPE as STRING: pipes carry streams between steps, not text. Capture the producing step's output with LET $var: STRING = ... instead."
        );
    }
    if val.as_semaphore().is_some() {
        anyhow::bail!(
            "cannot render SEMAPHORE as STRING: semaphores coordinate task access between steps, not text."
        );
    }
    if val.as_permit().is_some() {
        anyhow::bail!(
            "cannot render PERMIT as STRING: permits grant scoped task access, not text."
        );
    }
    if let Some(d) = val.as_duration() {
        return Ok(oxdock_parser::command::format_duration(&d));
    }
    if let Some(p) = val.as_path() {
        return Ok(p.to_string_lossy().to_string());
    }
    if let Some(items) = val.as_list() {
        let parts: Vec<String> = items
            .iter()
            .map(format_value_for_string)
            .collect::<anyhow::Result<_>>()?;
        return Ok(parts.join(" "));
    }
    if let Some(map) = val.as_map() {
        let mut parts = Vec::with_capacity(map.len());
        for (k, v) in map.iter() {
            parts.push(format!("\"{}\": {}", k, format_value_for_string(v)?));
        }
        return Ok(parts.join(", "));
    }
    if let Some(id) = val.as_handle() {
        return Ok(format!("task#{}", id));
    }
    Ok(format!("{}", val))
}

// Legacy functions for backward compatibility

pub(crate) fn expand_with_lookup<F>(input: &str, mut lookup_fn: F) -> String
where
    F: FnMut(&str) -> Option<String>,
{
    let mut out = String::with_capacity(input.len());
    let mut chars = input.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '{' {
            if let Some(&'{') = chars.peek() {
                chars.next(); // consume second '{'
                let mut content = String::new();
                let mut closed = false;
                // Look ahead for closing }}
                let mut inner_chars = chars.clone();
                while let Some(ch) = inner_chars.next() {
                    if ch == '}'
                        && let Some(&'}') = inner_chars.peek()
                    {
                        closed = true;
                        break;
                    }
                    content.push(ch);
                }

                if closed {
                    // Advance main iterator past content and closing braces.
                    // Count chars, not bytes: content may contain multi-byte
                    // UTF-8 (e.g. non-ASCII placeholder names).
                    for _ in 0..content.chars().count() {
                        chars.next();
                    }
                    chars.next(); // first }
                    chars.next(); // second }

                    let key = content.trim();
                    if !key.is_empty() {
                        out.push_str(&lookup_fn(key).unwrap_or_default());
                    }
                } else {
                    out.push('{');
                    out.push('{');
                }
            } else {
                out.push('{');
            }
        } else {
            out.push(c);
        }
    }
    out
}

pub fn expand_script_env(input: &str, script_envs: &HashMap<String, String>) -> String {
    expand_with_lookup(input, |name| {
        if let Some(key) = name.strip_prefix("env:") {
            script_envs
                .get(key)
                .cloned()
                .or_else(|| std::env::var(key).ok())
        } else {
            None
        }
    })
}

pub fn expand_command_env(input: &str, ctx: &CommandContext) -> String {
    expand_with_lookup(input, |name| {
        if let Some(key) = name.strip_prefix("env:") {
            ctx.envs().get(key).cloned()
        } else {
            None
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    #[test]
    fn basic_expansion() {
        let mut env = HashMap::new();
        env.insert("NAME".into(), "World".into());
        let expander = StreamingExpand::new(&[], &env);
        let result = expander.expand_string("Hello {{ env:NAME }}").unwrap();
        assert_eq!(result, "Hello World");
    }

    #[test]
    fn multiple_vars() {
        let mut env = HashMap::new();
        env.insert("A".into(), "X".into());
        env.insert("B".into(), "Y".into());
        let expander = StreamingExpand::new(&[], &env);
        let result = expander
            .expand_string("{{ env:A }} and {{ env:B }}")
            .unwrap();
        assert_eq!(result, "X and Y");
    }

    #[test]
    fn missing_var() {
        let env = HashMap::new();
        let expander = StreamingExpand::new(&[], &env);
        let result = expander.expand_string("{{ env:MISSING }}");
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("undefined environment variable"),
            "error should mention undefined environment variable"
        );
    }

    #[test]
    fn spaced_env_name_resolves_trimmed() {
        // `{{ env: FOO }}` looks up `FOO` on every layer: the lookup
        // trims up front like the static gate and the script engine,
        // instead of missing on the padded spelling.
        let mut env = HashMap::new();
        env.insert("FOO".into(), "bar".into());
        let expander = StreamingExpand::new(&[], &env);
        assert_eq!(expander.expand_string("{{ env: FOO }}").unwrap(), "bar");
    }

    #[test]
    fn empty_env_names_bail() {
        // Empty `env:` / `script_env:` names never interpolate empty:
        // every layer rejects them, matching the static gate and the
        // script-engine expansion.
        let env = HashMap::new();
        for text in ["{{ env: }}", "{{ script_env: }}", "{{ script_env:   }}"] {
            let expander = StreamingExpand::new(&[], &env);
            let result = expander.expand_string(text);
            assert!(result.is_err(), "{text:?} must fail");
        }
    }

    #[test]
    fn no_placeholders() {
        let env = HashMap::new();
        let expander = StreamingExpand::new(&[], &env);
        let result = expander.expand_string("plain text").unwrap();
        assert_eq!(result, "plain text");
    }

    #[test]
    fn empty_input() {
        let env = HashMap::new();
        let expander = StreamingExpand::new(&[], &env);
        let result = expander.expand_string("").unwrap();
        assert_eq!(result, "");
    }

    #[test]
    fn override_precedence() {
        let mut env = HashMap::new();
        env.insert("KEY".into(), "envval".into());
        let overrides = vec![("KEY".into(), "override".into())];
        let expander = StreamingExpand::new(&overrides, &env);
        let result = expander.expand_string("{{ env:KEY }}").unwrap();
        assert_eq!(result, "override");
    }

    #[test]
    fn override_with_namespace() {
        let mut env = HashMap::new();
        env.insert("CRATE".into(), "envval".into());
        let overrides = vec![("CRATE".into(), "override".into())];
        let expander = StreamingExpand::new(&overrides, &env);
        let result = expander.expand_string("{{ env:CRATE }}").unwrap();
        assert_eq!(result, "override");
    }

    #[test]
    fn override_raw_key_match() {
        let mut env = HashMap::new();
        env.insert("CRATE".into(), "envval".into());
        let overrides = vec![("env:CRATE".into(), "override".into())];
        let expander = StreamingExpand::new(&overrides, &env);
        let result = expander.expand_string("{{ env:CRATE }}").unwrap();
        assert_eq!(result, "override");
    }

    #[test]
    fn unclosed_placeholder() {
        let env = HashMap::new();
        let expander = StreamingExpand::new(&[], &env);
        let result = expander.expand_string("{{ env:KEY").unwrap();
        assert_eq!(result, "{{ env:KEY");
    }

    #[test]
    fn unclosed_with_prefix() {
        let env = HashMap::new();
        let expander = StreamingExpand::new(&[], &env);
        let result = expander.expand_string("Hello {{ env:KEY").unwrap();
        assert_eq!(result, "Hello {{ env:KEY");
    }

    #[test]
    fn buffer_limit_exceeded() {
        let env = HashMap::new();
        let expander = StreamingExpand::new(&[], &env);
        // Create input with `{{` followed by >1024 bytes without `}}`
        let mut input = b"{{ ".to_vec();
        input.extend(std::iter::repeat_n(b'x', 2000));
        let result = expander
            .expand_string(&String::from_utf8_lossy(&input))
            .unwrap();
        // Should flush as literal with `{{` prefix
        assert!(result.starts_with("{{ "));
        assert!(result.len() > 1024);
    }

    #[test]
    fn escaped_opener_emits_literal() {
        let mut env = HashMap::new();
        env.insert("PROJECT".into(), "OxDock".into());
        let expander = StreamingExpand::new(&[], &env);
        let result = expander
            .expand_string("Built with \\{{ env:PROJECT }}")
            .unwrap();
        assert_eq!(result, "Built with {{ env:PROJECT }}");
    }

    /// Stub resolver echoing `upper` over one string arg, for call tests.
    fn shout_resolver() -> PlaceholderCall {
        Arc::new(|module, func, args| {
            if module == "T" && func == "SHOUT" && args.len() == 1 {
                let s = args[0]
                    .as_str()
                    .ok_or_else(|| anyhow!("SHOUT expects a string"))?;
                return Ok(oxdock_parser::Value::string(s.to_uppercase()));
            }
            bail!("unknown placeholder function '{module}::{func}'")
        })
    }

    #[test]
    fn placeholder_call_with_var_arg() {
        let env = HashMap::new();
        let mut vars = HashMap::new();
        vars.insert(
            "who".to_string(),
            oxdock_parser::Value::string("bob".to_string()),
        );
        let expander = StreamingExpand::new(&[], &env)
            .with_vars(&vars)
            .with_call_resolver(shout_resolver());
        let result = expander.expand_string("hi {{ T::SHOUT($who) }}!").unwrap();
        assert_eq!(result, "hi BOB!");
    }

    #[test]
    fn placeholder_call_with_literal_args() {
        let env = HashMap::new();
        let expander = StreamingExpand::new(&[], &env).with_call_resolver(shout_resolver());
        let result = expander
            .expand_string("{{ T::SHOUT(\"bob\") }} {{ T::SHOUT( \"ann\" ) }}")
            .unwrap();
        assert_eq!(result, "BOB ANN");
    }

    #[test]
    fn placeholder_call_output_stays_literal() {
        // Call output containing `{{ }}` is terminal text, never re-expanded.
        let env = HashMap::new();
        let mut vars = HashMap::new();
        vars.insert(
            "any".to_string(),
            oxdock_parser::Value::string("v".to_string()),
        );
        let resolver: PlaceholderCall = Arc::new(|_, _, _| {
            Ok(oxdock_parser::Value::string(
                "x {{ env:NOPE }} y".to_string(),
            ))
        });
        let expander = StreamingExpand::new(&[], &env)
            .with_vars(&vars)
            .with_call_resolver(resolver);
        let result = expander.expand_string("{{ T::SHOUT($any) }}").unwrap();
        assert_eq!(result, "x {{ env:NOPE }} y");
    }

    #[test]
    fn placeholder_call_unknown_function_fails() {
        let env = HashMap::new();
        let expander = StreamingExpand::new(&[], &env).with_call_resolver(shout_resolver());
        let result = expander.expand_string("{{ T::NOPE($x) }}");
        assert!(result.is_err());
    }

    #[test]
    fn placeholder_call_without_resolver_fails() {
        let env = HashMap::new();
        let expander = StreamingExpand::new(&[], &env);
        let result = expander.expand_string("{{ T::SHOUT($x) }}");
        assert!(result.is_err());
    }

    #[test]
    fn escaped_opener_across_chunks() {
        let mut env = HashMap::new();
        env.insert("PROJECT".into(), "OxDock".into());
        let mut expander = StreamingExpand::new(&[], &env);
        let mut out = Vec::new();

        // Split `\` / `{{ env:PROJECT }}` across chunks
        expander.process_bytes(b"Built with \\", &mut out).unwrap();
        expander
            .process_bytes(b"{{ env:PROJECT }}", &mut out)
            .unwrap();
        expander.flush(&mut out).unwrap();

        assert_eq!(
            String::from_utf8_lossy(&out),
            "Built with {{ env:PROJECT }}"
        );
    }

    #[test]
    fn double_backslash_then_placeholder_expands() {
        let mut env = HashMap::new();
        env.insert("PROJECT".into(), "OxDock".into());
        let expander = StreamingExpand::new(&[], &env);
        let result = expander.expand_string("\\\\{{ env:PROJECT }}").unwrap();
        assert_eq!(result, "\\OxDock");
    }

    #[test]
    fn trailing_backslash_flushes_literal() {
        let env = HashMap::new();
        let expander = StreamingExpand::new(&[], &env);
        let result = expander.expand_string("end\\").unwrap();
        assert_eq!(result, "end\\");
    }

    #[test]
    fn backslash_before_other_text_is_literal() {
        let env = HashMap::new();
        let expander = StreamingExpand::new(&[], &env);
        let result = expander.expand_string("a\\b \\{ once }").unwrap();
        assert_eq!(result, "a\\b \\{ once }");
    }

    #[test]
    fn escaped_pair_split_across_chunks() {
        let mut env = HashMap::new();
        env.insert("PROJECT".into(), "OxDock".into());
        let mut expander = StreamingExpand::new(&[], &env);
        let mut out = Vec::new();

        // Split `\\` / `{{ env:PROJECT }}` across chunks: the pair
        // completes to one backslash, then the placeholder expands
        expander.process_bytes(b"\\", &mut out).unwrap();
        expander
            .process_bytes(b"\\{{ env:PROJECT }}", &mut out)
            .unwrap();
        expander.flush(&mut out).unwrap();

        assert_eq!(String::from_utf8_lossy(&out), "\\OxDock");
    }

    #[test]
    fn partial_across_chunks() {
        let mut env = HashMap::new();
        env.insert("NAME".into(), "World".into());
        let mut expander = StreamingExpand::new(&[], &env);
        let mut out = Vec::new();

        // Split `{{ env:NA` / `ME }}` across chunks
        expander.process_bytes(b"{{ env:NA", &mut out).unwrap();
        expander.process_bytes(b"ME }}", &mut out).unwrap();
        expander.flush(&mut out).unwrap();

        assert_eq!(String::from_utf8_lossy(&out), "World");
    }

    #[test]
    fn trailing_brace_across_chunks() {
        let mut env = HashMap::new();
        env.insert("NAME".into(), "World".into());
        let mut expander = StreamingExpand::new(&[], &env);
        let mut out = Vec::new();

        // Split `...{` / `{env:NAME}}` across chunks
        expander.process_bytes(b"...", &mut out).unwrap();
        expander.process_bytes(b"{", &mut out).unwrap();
        expander.process_bytes(b"{env:NAME}}", &mut out).unwrap();
        expander.flush(&mut out).unwrap();

        assert_eq!(String::from_utf8_lossy(&out), "...World");
    }

    #[test]
    fn trailing_brace_at_eof() {
        let env = HashMap::new();
        let mut expander = StreamingExpand::new(&[], &env);
        let mut out = Vec::new();

        expander.process_bytes(b"hello{", &mut out).unwrap();
        expander.flush(&mut out).unwrap();

        assert_eq!(String::from_utf8_lossy(&out), "hello{");
    }

    #[test]
    fn immediate_flush_guarantee() {
        let env = HashMap::new();
        let mut expander = StreamingExpand::new(&[], &env);
        let mut out = Vec::new();

        // 1MB of plain text with no placeholders
        let input = std::iter::repeat_n(b'x', 1024 * 1024).collect::<Vec<_>>();
        expander.process_bytes(&input, &mut out).unwrap();
        expander.flush(&mut out).unwrap();

        assert_eq!(out.len(), 1024 * 1024);
    }

    #[test]
    fn nested_braces() {
        let mut env = HashMap::new();
        env.insert("KEY{1}".into(), "val".into());
        let expander = StreamingExpand::new(&[], &env);
        let result = expander.expand_string("{{ env:KEY{1} }}").unwrap();
        assert_eq!(result, "val");
    }

    #[test]
    fn split_close_delimiter_across_chunks() {
        let mut env = HashMap::new();
        env.insert("NAME".into(), "World".into());
        let mut expander = StreamingExpand::new(&[], &env);
        let mut out = Vec::new();

        // Split `}}` across chunks: `{{ env:NAME` / `}}`
        expander.process_bytes(b"{{ env:NAME", &mut out).unwrap();
        expander.process_bytes(b"}}", &mut out).unwrap();
        expander.flush(&mut out).unwrap();

        assert_eq!(String::from_utf8_lossy(&out), "World");
    }

    #[test]
    fn split_close_delimiter_with_trailing_content() {
        let mut env = HashMap::new();
        env.insert("NAME".into(), "World".into());
        let mut expander = StreamingExpand::new(&[], &env);
        let mut out = Vec::new();

        // Split `}}` across chunks with content after
        expander.process_bytes(b"{{ env:NAME", &mut out).unwrap();
        expander.process_bytes(b"}} rest", &mut out).unwrap();
        expander.flush(&mut out).unwrap();

        assert_eq!(String::from_utf8_lossy(&out), "World rest");
    }

    #[test]
    fn empty_input_preserves_pending_state() {
        let mut env = HashMap::new();
        env.insert("NAME".into(), "World".into());
        let mut expander = StreamingExpand::new(&[], &env);
        let mut out = Vec::new();

        // End chunk with closing byte, then empty input, then confirm
        expander.process_bytes(b"{{ env:NAME", &mut out).unwrap();
        expander.process_bytes(b"", &mut out).unwrap(); // empty: should preserve state
        expander.process_bytes(b"}}", &mut out).unwrap();
        expander.flush(&mut out).unwrap();

        assert_eq!(String::from_utf8_lossy(&out), "World");
    }

    #[test]
    fn missing_env_var_errors() {
        let env = HashMap::new();
        let expander = StreamingExpand::new(&[], &env);
        let result = expander.expand_string("{{ env:UNDEFINED_VAR }}");
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("undefined environment variable"), "got: {msg}");
        assert!(msg.contains("UNDEFINED_VAR"), "got: {msg}");
    }

    #[test]
    fn missing_script_var_errors() {
        let env = HashMap::new();
        let expander = StreamingExpand::new(&[], &env);
        let result = expander.expand_string("{{ $undefined_var }}");
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("undefined script variable"), "got: {msg}");
        assert!(msg.contains("$undefined_var"), "got: {msg}");
    }

    #[test]
    fn missing_key_in_map_errors() {
        let mut vars = HashMap::new();
        vars.insert(
            "cfg".into(),
            oxdock_parser::Value::map(std::collections::BTreeMap::from([(
                "server".into(),
                oxdock_parser::Value::map(std::collections::BTreeMap::from([(
                    "port".into(),
                    oxdock_parser::Value::int(8080),
                )])),
            )])),
        );
        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
        let result = expander.expand_string("{{ $cfg.missing_key }}");
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("property 'missing_key' not found"),
            "got: {msg}"
        );
    }

    #[test]
    fn out_of_bounds_array_index_errors() {
        let mut vars = HashMap::new();
        vars.insert(
            "arr".into(),
            oxdock_parser::Value::list(vec![oxdock_parser::Value::string("a".into())]),
        );
        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
        let result = expander.expand_string("{{ $arr.5 }}");
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("index 5 out of bounds"), "got: {msg}");
    }

    #[test]
    fn type_mismatch_navigation_errors() {
        let mut vars = HashMap::new();
        vars.insert("name".into(), oxdock_parser::Value::string("alice".into()));
        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
        let result = expander.expand_string("{{ $name.sub_field }}");
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("cannot access property 'sub_field' on primitive"),
            "got: {msg}"
        );
    }

    #[test]
    fn unprefixed_identifier_errors() {
        let env = HashMap::new();
        let expander = StreamingExpand::new(&[], &env);
        let result = expander.expand_string("{{ bare_word }}");
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("missing required step override"), "got: {msg}");
    }

    // ── Strict namespace isolation tests ─────────────────────────────────────

    #[test]
    fn script_var_does_not_fall_back_to_env() {
        let mut env = HashMap::new();
        env.insert("WHO".into(), "from-env".into());
        let expander = StreamingExpand::new(&[], &env);
        // $WHO queries vars, NOT env : should error even though env has WHO
        let result = expander.expand_string("{{ $WHO }}");
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("undefined script variable"), "got: {msg}");
        assert!(
            msg.contains("did you mean 'env:WHO'"),
            "hint should suggest env: prefix, got: {msg}"
        );
    }

    #[test]
    fn env_var_does_not_fall_back_to_vars() {
        let mut vars = HashMap::new();
        vars.insert(
            "HOST".into(),
            oxdock_parser::Value::string("from-var".into()),
        );
        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
        // env:HOST queries env, NOT vars : should error even though vars has HOST
        let result = expander.expand_string("{{ env:HOST }}");
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("undefined environment variable"), "got: {msg}");
        assert!(
            msg.contains("did you mean '$HOST'"),
            "hint should suggest $ prefix, got: {msg}"
        );
    }

    #[test]
    fn step_override_does_not_fall_back_to_vars() {
        let mut vars = HashMap::new();
        vars.insert("PORT".into(), oxdock_parser::Value::int(8080));
        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
        // PORT (bare) queries overrides, NOT vars : should error
        let result = expander.expand_string("{{ PORT }}");
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("missing required step override"), "got: {msg}");
        assert!(
            msg.contains("did you mean '$PORT'"),
            "hint should suggest $ prefix, got: {msg}"
        );
    }

    #[test]
    fn env_prefix_isolated_from_script_vars() {
        let mut vars = HashMap::new();
        vars.insert("MODE".into(), oxdock_parser::Value::string("dev".into()));
        let expander = StreamingExpand::new(&[], &HashMap::new()).with_vars(&vars);
        // env:MODE looks in env, not vars : should error
        let result = expander.expand_string("{{ env:MODE }}");
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("undefined environment variable"), "got: {msg}");
        assert!(
            msg.contains("did you mean '$MODE'"),
            "hint should suggest $ prefix, got: {msg}"
        );
    }

    #[test]
    fn dollar_prefix_isolated_from_env() {
        let mut env = HashMap::new();
        env.insert("PORT".into(), "3000".into());
        let expander = StreamingExpand::new(&[], &env);
        // $PORT looks in vars, not env : should error
        let result = expander.expand_string("{{ $PORT }}");
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("undefined script variable"), "got: {msg}");
        assert!(
            msg.contains("did you mean 'env:PORT'"),
            "hint should suggest env: prefix, got: {msg}"
        );
    }

    #[test]
    fn empty_placeholder_errors() {
        let expander = StreamingExpand::new(&[], &HashMap::new());
        let result = expander.expand_string("{{ }}");
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("invalid placeholder format"), "got: {msg}");
    }

    #[test]
    fn malformed_symbol_placeholder_errors() {
        let expander = StreamingExpand::new(&[], &HashMap::new());
        let result = expander.expand_string("{{ @invalid! }}");
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("invalid placeholder format"), "got: {msg}");
    }

    #[test]
    fn bare_call_head_fails_as_invalid_placeholder() {
        // Directive 3: bare `FUNC(...)` has no registry entry in
        // override expansion. The `Call` arm handles `module == None`
        // explicitly instead of silently falling through.
        let expander = StreamingExpand::new(&[], &HashMap::new());
        let result = expander.expand_string("{{ FOO() }}");
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("invalid placeholder format"), "got: {msg}");
    }

    /// Feed input in fixed-size chunks, then flush: exercises every
    /// chunk-boundary alignment for the given split size.
    fn render_split(
        input: &[u8],
        size: usize,
        env: &HashMap<String, String>,
    ) -> Result<String, anyhow::Error> {
        let mut expander = StreamingExpand::new(&[], env);
        let mut out = Vec::new();
        for chunk in input.chunks(size) {
            expander.process_bytes(chunk, &mut out)?;
        }
        expander.flush(&mut out)?;
        Ok(String::from_utf8_lossy(&out).into_owned())
    }

    #[test]
    fn escaped_opener_one_byte_chunks_stays_literal() {
        let mut env = HashMap::new();
        env.insert("NAME".into(), "World".into());
        // Every byte arrives alone: `\` | `{` | `{` | ... must still
        // resolve to a literal opener, never an expansion.
        let out = render_split(b"\\{{ env:NAME }}", 1, &env).unwrap();
        assert_eq!(out, "{{ env:NAME }}");
    }

    #[test]
    fn escaped_opener_two_byte_chunks_stays_literal() {
        let mut env = HashMap::new();
        env.insert("NAME".into(), "World".into());
        // Two-byte splits land `\{` and lone `{` at chunk ends.
        let out = render_split(b"a\\{{ env:NAME }}b", 2, &env).unwrap();
        assert_eq!(out, "a{{ env:NAME }}b");
    }

    #[test]
    fn escaped_opener_split_variants_stay_literal() {
        let mut env = HashMap::new();
        env.insert("NAME".into(), "World".into());
        for chunks in [
            vec![b"\\".as_slice(), b"{", b"{ env:NAME }}"],
            vec![b"\\{".as_slice(), b"{ env:NAME }}"],
            vec![b"\\{{ env:NAME ".as_slice(), b"}}"],
        ] {
            let mut expander = StreamingExpand::new(&[], &env);
            let mut out = Vec::new();
            for chunk in chunks {
                expander.process_bytes(chunk, &mut out).unwrap();
            }
            expander.flush(&mut out).unwrap();
            assert_eq!(
                String::from_utf8_lossy(&out),
                "{{ env:NAME }}",
                "chunks must not corrupt the escape"
            );
        }
    }

    #[test]
    fn plain_opener_split_chunks_still_expands() {
        let mut env = HashMap::new();
        env.insert("NAME".into(), "World".into());
        // The fix must not swallow genuine openers fragmented the
        // same way: `{` | `{` opens, then the key resolves.
        let out = render_split(b"{{ env:NAME }}", 1, &env).unwrap();
        assert_eq!(out, "World");
    }

    #[test]
    fn double_backslash_split_chunks_still_expands() {
        let mut env = HashMap::new();
        env.insert("NAME".into(), "World".into());
        // `\\` completes to one backslash; the opener after it expands.
        let out = render_split(b"\\\\{{ env:NAME }}", 1, &env).unwrap();
        assert_eq!(out, "\\World");
    }

    #[test]
    fn trailing_escape_brace_flushes_literal() {
        let env = HashMap::new();
        let expander = StreamingExpand::new(&[], &env);
        let result = expander.expand_string("end\\{").unwrap();
        assert_eq!(result, "end\\{");
    }

    // ── Single-pass substitution tests ────────────────────────────────────
    // Substituted values are emitted verbatim and never re-scanned for
    // `{{ ... }}`. These pin the top-level-only behavior: a value that
    // itself contains a placeholder stays literal instead of expanding.

    #[test]
    fn substituted_override_value_is_not_rescanned() {
        let mut env = HashMap::new();
        env.insert("OTHER".into(), "world".into());
        let overrides = vec![("NAME".into(), "{{ env:OTHER }}".into())];
        let expander = StreamingExpand::new(&overrides, &env);
        let result = expander.expand_string("Hello {{ NAME }}").unwrap();
        assert_eq!(result, "Hello {{ env:OTHER }}");
    }

    #[test]
    fn substituted_env_value_is_not_rescanned() {
        let mut env = HashMap::new();
        env.insert("NAME".into(), "{{ env:OTHER }}".into());
        env.insert("OTHER".into(), "world".into());
        let expander = StreamingExpand::new(&[], &env);
        let result = expander.expand_string("Hello {{ env:NAME }}").unwrap();
        assert_eq!(result, "Hello {{ env:OTHER }}");
    }

    #[test]
    fn substituted_script_var_value_is_not_rescanned() {
        let mut vars = HashMap::new();
        vars.insert(
            "inner".into(),
            oxdock_parser::Value::string("{{ env:OTHER }}".into()),
        );
        let mut env = HashMap::new();
        env.insert("OTHER".into(), "world".into());
        let expander = StreamingExpand::new(&[], &env).with_vars(&vars);
        let result = expander.expand_string("Hello {{ $inner }}").unwrap();
        assert_eq!(result, "Hello {{ env:OTHER }}");
    }

    /// Echo resolver returning the debug shape of each argument, so
    /// literal parsing asserts on values instead of formatting.
    fn shape_resolver() -> PlaceholderCall {
        Arc::new(|module, func, args| {
            if module == "T" && func == "SHAPE" {
                let shape = args
                    .iter()
                    .map(|arg| arg.type_name().to_string())
                    .collect::<Vec<_>>()
                    .join(",");
                return Ok(oxdock_parser::Value::string(shape));
            }
            bail!("unknown placeholder function '{module}::{func}'")
        })
    }

    #[test]
    fn placeholder_call_with_empty_map_literal() {
        let expander =
            StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
        let result = expander.expand_string("{{ T::SHAPE({}) }}").unwrap();
        assert_eq!(result, "MAP");
    }

    #[test]
    fn placeholder_call_with_map_and_list_literals() {
        let expander =
            StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
        let result = expander
            .expand_string("{{ T::SHAPE({a: 1, b: \"x\"}, [1, true]) }}")
            .unwrap();
        assert_eq!(result, "MAP,LIST");
    }

    #[test]
    fn placeholder_call_map_commas_nest_inside_literals() {
        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
            let map = args[0].as_map().expect("map");
            let format = map
                .get("format")
                .and_then(|v| v.as_str())
                .expect("format string");
            Ok(oxdock_parser::Value::string(format.to_string()))
        });
        let expander = StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(resolver);
        let result = expander
            .expand_string("{{ T::SHAPE({min_level: 2, format: \"a,b\"}) }}")
            .unwrap();
        assert_eq!(result, "a,b");
    }

    #[test]
    fn placeholder_call_map_values_accept_var_refs_and_nesting() {
        let mut vars = HashMap::new();
        vars.insert("depth".into(), oxdock_parser::Value::int(2));
        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
            let map = args[0].as_map().expect("map");
            let depth = map.get("n").and_then(|v| v.as_i64()).expect("int");
            let tags = map.get("tags").and_then(|v| v.as_list()).expect("list");
            Ok(oxdock_parser::Value::string(format!(
                "{depth}:{}",
                tags.len()
            )))
        });
        let expander = StreamingExpand::new(&[], &HashMap::new())
            .with_vars(&vars)
            .with_call_resolver(resolver);
        let result = expander
            .expand_string("{{ T::SHAPE({n: $depth, tags: [\"a\", \"b\"]}) }}")
            .unwrap();
        assert_eq!(result, "2:2");
    }

    #[test]
    fn placeholder_call_rejects_malformed_literals() {
        for bad in [
            "{{ T::SHAPE({a}) }}",
            "{{ T::SHAPE({a: 1, a: 2}) }}",
            "{{ T::SHAPE({\"a\": 1: 2}) }}",
            "{{ T::SHAPE([1) }}",
            "{{ T::SHAPE({a: 1) }}",
        ] {
            let expander =
                StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
            assert!(expander.expand_string(bad).is_err(), "must fail: {bad}");
        }
    }

    #[test]
    fn placeholder_call_rejects_adjacent_string_literals() {
        // Missing commas and infix expressions must fail, never merge
        // into one string.
        for bad in [
            "{{ T::SHAPE(\"a\" \"b\") }}",
            "{{ T::SHAPE(\"a\" + \"b\") }}",
            "{{ T::SHAPE(\"foo\\\") }}",
        ] {
            let expander =
                StreamingExpand::new(&[], &HashMap::new()).with_call_resolver(shape_resolver());
            assert!(expander.expand_string(bad).is_err(), "must fail: {bad}");
        }
    }

    #[test]
    fn placeholder_call_brackets_inside_block_strings_resolve() {
        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
            let first = &args[0];
            if let Some(items) = first.as_list() {
                return Ok(oxdock_parser::Value::string(
                    items[0].as_str().unwrap_or("?").to_string(),
                ));
            }
            if let Some(entries) = first.as_map() {
                return Ok(oxdock_parser::Value::string(
                    entries
                        .get("k")
                        .and_then(|v| v.as_str())
                        .unwrap_or("?")
                        .to_string(),
                ));
            }
            bail!("expected list or map")
        });
        let list = StreamingExpand::new(&[], &HashMap::new())
            .with_call_resolver(resolver.clone())
            .expand_string("{{ T::ECHO([\"\"\"a]b\"\"\"]) }}")
            .unwrap();
        assert_eq!(list, "a]b");
        let map = StreamingExpand::new(&[], &HashMap::new())
            .with_call_resolver(resolver.clone())
            .expand_string("{{ T::ECHO({k: \"\"\"a}b\"\"\"}) }}")
            .unwrap();
        assert_eq!(map, "a}b");
    }

    #[test]
    fn placeholder_call_single_quotes_match_double_quotes() {
        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
            Ok(oxdock_parser::Value::string(
                args.iter()
                    .map(|a| a.as_str().unwrap_or("?").to_string())
                    .collect::<Vec<_>>()
                    .join("|"),
            ))
        });
        for (double, single) in [
            ("{{ T::ECHO(\"hi\") }}", "{{ T::ECHO('hi') }}"),
            ("{{ T::ECHO(\"a,b\") }}", "{{ T::ECHO('a,b') }}"),
            ("{{ T::ECHO({k: \"v\"}) }}", "{{ T::ECHO({k: 'v'}) }}"),
            ("{{ T::ECHO({\"k\": \"v\"}) }}", "{{ T::ECHO({'k': 'v'}) }}"),
            ("{{ T::ECHO([\"a\"]) }}", "{{ T::ECHO(['a']) }}"),
        ] {
            let left = StreamingExpand::new(&[], &HashMap::new())
                .with_call_resolver(resolver.clone())
                .expand_string(double)
                .unwrap();
            let right = StreamingExpand::new(&[], &HashMap::new())
                .with_call_resolver(resolver.clone())
                .expand_string(single)
                .unwrap();
            assert_eq!(
                left, right,
                "quote style must not matter: {double} vs {single}"
            );
        }
    }

    #[test]
    fn placeholder_call_triple_quoted_matches_single_line() {
        let resolver: PlaceholderCall = Arc::new(|_, _, args| {
            Ok(oxdock_parser::Value::string(
                args[0].as_str().unwrap_or("?").to_string(),
            ))
        });
        let plain = StreamingExpand::new(&[], &HashMap::new())
            .with_call_resolver(resolver.clone())
            .expand_string("{{ T::ECHO(\"Release installs\") }}")
            .unwrap();
        let block = StreamingExpand::new(&[], &HashMap::new())
            .with_call_resolver(resolver.clone())
            .expand_string("{{ T::ECHO(\"\"\"Release installs\"\"\") }}")
            .unwrap();
        assert_eq!(plain, block);
    }
}