proef-core 0.10.0

Engine-agnostic core of proef: parsing, binding, lowering, IR, emit, dispatch, World, events, errors
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
//! Pack validation passes 1–13 (TECH-SPEC §4.1).
//!
//! 1. `match:` guard rails (literal anchor, no adjacent captures, balanced
//!    braces, declared params) · 2. params/defaults coverage · 3. duplicate
//!    macro names across packs (in `mod.rs`, at insertion) · 4. `use:` cycle +
//!    depth ≤ [`MAX_USE_DEPTH`] · 5. unknown/missing `with:` keys ·
//!    6. finite-retry lint (typed `retry:` plus a raw-block scan for infinite
//!    hurl `retry`/`repeat` options, and the same scan's refusal of an option
//!    declared both in `[Options]` and as its typed twin) · 7.
//!    probe-instantiation parse of payload
//!    blocks via the claiming engine's [`StepKindSpec::validate`] hook ·
//!    8. every payload kind is claimed by a registered engine.
//!
//! Fragments (ADR-0018) add five more: 9. a `ref:` names a loaded fragment ·
//! 10. no two fragment files declare the same name (in `mod.rs`, at insertion) ·
//! 11. a step is `ref:` **xor** a payload/`use:` · 12. an option family is not
//! declared both in the fragment's own `[Options]` and as the step's key, and no
//! variable is both supplied by the fragment's `[Options] variable:` and given by
//! a `bind:` — pass 6's rule applied across the file boundary, family-to-family
//! for options and name-to-name for variables · 13. a fragment file the
//! engine's scanner could not read, or an annotation it could not attach (in
//! `mod.rs`, at scan time).
//!
//! Fragments deliberately **skip pass 7**: they parse as authored, so there is
//! no probe instantiation to guess at. Their `bind:` tables are checked here
//! for reachability; whether every `{{…}}` is actually supplied is a lower-time
//! question (`proef::lower::unbound_placeholder`), because only lowering knows
//! what earlier steps captured.

use std::collections::BTreeMap;
use std::sync::Arc;

use super::locate;
use super::{
    ExpectItem, Macro, MacroBody, MacroStep, MacroStepKind, PackSet, PackSource, PayloadForm,
    RawMacro, RawStep,
};
use crate::diag::Diag;
use crate::engine::StepKindSpec;
use crate::matcher;
use crate::resolve::{self, Resolution, ResolveCtx, ResolveMode};
use crate::step::Retry;
use crate::world::World;

/// Maximum `use:` nesting depth (TECH-SPEC §4.1 pass 4).
pub const MAX_USE_DEPTH: usize = 32;

/// Normalize one raw macro into a [`Macro`], emitting structural
/// diagnostics (passes 1, 2, and the per-step shape rules) along the way.
/// Returns `None` only when the macro is too malformed to keep.
// One cohesive listing of the body-shape rules; splitting hides the order.
#[allow(clippy::too_many_lines)]
pub(crate) fn normalize_macro(
    name: &str,
    raw: &RawMacro,
    pack_name: &str,
    source: &PackSource,
    diags: &mut Vec<Diag>,
) -> Option<Macro> {
    let span = locate::macro_span(&source.text, name);
    let match_span = locate::match_span(&source.text, name);
    let at = |diag: Diag| {
        diag.with_source(source.name.clone(), Arc::clone(&source.text))
            .maybe_span(span)
    };

    // Pass 1: match guard rails.
    if let Some(pattern) = &raw.match_ {
        for problem in matcher::pattern_problems(pattern, &raw.params) {
            diags.push(at(Diag::error(
                problem.code(),
                format!("macro `{name}`: {problem}"),
            )));
        }
    }

    // Pass 2: defaults must name declared params.
    for default_key in raw.defaults.keys() {
        if !raw.params.contains(default_key) {
            let suggestion = matcher::closest(default_key, raw.params.iter().map(String::as_str))
                .map(|p| format!(" — did you mean `{p}`?"))
                .unwrap_or_default();
            diags.push(at(Diag::error(
                "proef::pack::default_not_param",
                format!(
                    "macro `{name}`: default `{default_key}` is not a declared param{suggestion}"
                ),
            )));
        }
    }

    // Pass 2b: a macro-scope `bind:` needs something in this macro to bind.
    // Same rule as the step-scope check, at the scope above it: a `bind:` no
    // `ref:` can read is silently dropped at lower time, and a setting quietly
    // ignored is the bug both halves refuse to ship. The predicate is *this
    // macro's own* steps because a `use:` target resolves its own scopes — a
    // parent's macro-scope table never reaches the child (ADR-0018).
    if !raw.bind.is_empty() && !raw.steps.iter().any(|step| step.ref_.is_some()) {
        diags.push(at(Diag::error(
            "proef::pack::bind_without_ref",
            format!(
                "macro `{name}`: `bind:` supplies a fragment's `{{{{}}}}` variables, but no step here has a `ref:` — a `use:` target resolves its own bindings, so this table would go unread"
            ),
        )));
    }

    // Body shape: steps XOR expect.
    let body = match (&raw.steps.is_empty(), &raw.expect) {
        (false, Some(_)) => {
            diags.push(at(Diag::error(
                "proef::pack::steps_and_expect",
                format!("macro `{name}` has both `steps:` and `expect:` — a macro is a request sequence or an assert-only macro, not both"),
            )));
            return None;
        }
        (true, None) => {
            diags.push(at(Diag::error(
                "proef::pack::empty_macro",
                format!("macro `{name}` has neither `steps:` nor `expect:`"),
            )));
            return None;
        }
        (true, Some(items)) => {
            let mut expect = Vec::new();
            // Positional pairing with `hurl:` lines in source order: only
            // items that carry the key produce one (assert-only macros have
            // no `steps:`, so every `hurl:` line in the block is an expect
            // item's), so the ordinal advances only when `item.hurl` is `Some`.
            // The line scanner only recognises block-style `key:` lines
            // (`locate::key_line_spans`), so a flow-style item (`- {hurl: …}`)
            // parses to `Some` but contributes no line — exactly the hazard
            // `analyze::index_use_refs` already guards for `use:` lines. Same
            // fix: when the counts disagree the pairing can't be trusted, so
            // every item in this macro falls back to the macro's own span
            // instead of risking an ordinal-shifted wrong line.
            let hurl_spans = locate::expect_hurl_line_spans(&source.text, name);
            let hurl_key_count = items.iter().filter(|item| item.hurl.is_some()).count();
            let spans_reliable = hurl_spans.len() == hurl_key_count;
            let mut hurl_ordinal = 0usize;
            for (index, item) in items.iter().enumerate() {
                let has_hurl_key = item.hurl.is_some();
                // A blank or whitespace-only `hurl:` block scalar carries no
                // assert lines — same as omitting the key outright (and, left
                // unrejected, lowers to a zero-line merged-asserts step that
                // underflows the sidecar span arithmetic).
                let fragment_is_blank = item
                    .hurl
                    .as_deref()
                    .is_none_or(|fragment| fragment.trim().is_empty());
                if item.status.is_none() && fragment_is_blank {
                    let fragment_span = (spans_reliable && has_hurl_key)
                        .then(|| hurl_spans.get(hurl_ordinal).copied())
                        .flatten();
                    diags.push(
                        at(Diag::error(
                            "proef::pack::empty_expect",
                            format!("macro `{name}` expect item {index} asserts nothing — give it `status:` and/or `hurl:` assert lines"),
                        ))
                        .maybe_span(fragment_span)
                        .with_help("an `expect:` item must carry at least one assert line, from `status:` and/or non-blank `hurl:` content"),
                    );
                    if has_hurl_key {
                        hurl_ordinal += 1;
                    }
                    continue;
                }
                if has_hurl_key {
                    hurl_ordinal += 1;
                }
                expect.push(ExpectItem {
                    status: item.status.clone(),
                    fragment: item.hurl.clone(),
                });
            }
            MacroBody::Expect(expect)
        }
        (false, None) => {
            let mut steps = Vec::new();
            for (index, step) in raw.steps.iter().enumerate() {
                if let Some(step) = normalize_step(name, index, step, &at, diags) {
                    steps.push(step);
                }
            }
            MacroBody::Steps(steps)
        }
    };

    Some(Macro {
        name: name.to_owned(),
        pack: pack_name.to_owned(),
        params: raw.params.clone(),
        defaults: raw.defaults.clone(),
        pattern: raw.match_.clone(),
        description: raw.description.clone(),
        tags: raw.tags.clone(),
        body,
        bind: raw.bind.clone(),
        source: Arc::clone(&source.text),
        span,
        match_span,
    })
}

/// Normalize one raw step, emitting per-step shape diagnostics.
// One cohesive listing of the step shape rules; splitting hides the order.
#[allow(clippy::too_many_lines)]
fn normalize_step(
    macro_name: &str,
    index: usize,
    raw: &RawStep,
    at: &impl Fn(Diag) -> Diag,
    diags: &mut Vec<Diag>,
) -> Option<MacroStep> {
    // saveAs targets: only `global` exists (ADR-0005).
    let mut save_as = BTreeMap::new();
    if let Some(targets) = &raw.save_as {
        for (capture, target) in targets {
            if target == "global" {
                save_as.insert(capture.clone(), target.clone());
            } else {
                diags.push(at(Diag::error(
                    "proef::pack::bad_save_target",
                    format!("macro `{macro_name}` step {index}: `saveAs: {{ {capture}: {target} }}` — the only target is `global`"),
                )));
            }
        }
    }

    // Finite-retry lint, typed half (pass 6): count 0 is pointless.
    let retry = match &raw.retry {
        Some(r) if i64::from(r.count) > MAX_COUNT => {
            diags.push(at(Diag::error(
                "proef::pack::retry_not_finite",
                format!(
                    "macro `{macro_name}` step {index}: `retry.count` {} is budget-hostile — the cap is {MAX_COUNT}",
                    r.count
                ),
            )));
            None
        }
        Some(r) if r.count == 0 => {
            diags.push(at(Diag::error(
                "proef::pack::retry_not_finite",
                format!("macro `{macro_name}` step {index}: `retry.count` must be ≥ 1"),
            )));
            None
        }
        Some(r) => Some(Retry {
            count: r.count,
            interval_ms: r.interval_ms,
        }),
        None => None,
    };

    // `bind:` supplies a *fragment's* `{{names}}`. On an inline step there is
    // nothing to supply them to — `${…}` splices at lower time — so accepting it
    // there would silently ignore what the author wrote.
    if !raw.bind.is_empty() && raw.ref_.is_none() {
        diags.push(at(Diag::error(
            "proef::pack::bind_without_ref",
            format!(
                "macro `{macro_name}` step {index}: `bind:` supplies a fragment's `{{{{}}}}` variables, so it needs a `ref:` — an inline `hurl:` block takes `${{}}` instead"
            ),
        )));
    }

    let kind = if let Some(target) = &raw.ref_ {
        // Body form: a step is exactly one of `hurl:`, `use:`, `ref:`.
        if !raw.payload.is_empty() || raw.use_.is_some() {
            let other = if raw.use_.is_some() {
                "use:"
            } else {
                "a payload"
            };
            diags.push(at(Diag::error(
                "proef::pack::body_form_conflict",
                format!(
                    "macro `{macro_name}` step {index}: a step is either `ref:` or {other}, not both"
                ),
            )));
            return None;
        }
        if raw.with.is_some() {
            diags.push(at(Diag::error(
                "proef::pack::with_without_use",
                format!("macro `{macro_name}` step {index}: `with:` only accompanies `use:`"),
            )));
        }
        // Unlike `use:`, a `ref:` step *does* take the step modifiers: it is one
        // request of this macro's own, not an inlining of somebody else's steps.
        MacroStepKind::Ref {
            target: target.clone(),
        }
    } else {
        match (&raw.use_, raw.payload.len()) {
            (Some(target), 0) => {
                if raw.optional || raw.when.is_some() || retry.is_some() || !save_as.is_empty() {
                    diags.push(at(Diag::error(
                    "proef::pack::use_with_modifiers",
                    format!("macro `{macro_name}` step {index}: `use:` steps take only `with:` (and `name:`) — modifiers belong on the target macro's steps"),
                )));
                }
                MacroStepKind::Use {
                    target: target.clone(),
                    with: raw.with.clone().unwrap_or_default(),
                }
            }
            (Some(_), _) => {
                diags.push(at(Diag::error(
                "proef::pack::use_with_payload",
                format!("macro `{macro_name}` step {index}: a step is either `use:` or a payload, not both"),
            )));
                return None;
            }
            (None, 0) => {
                diags.push(at(Diag::error(
                "proef::pack::empty_step",
                format!(
                    "macro `{macro_name}` step {index} has no payload (`hurl: |…`), no `ref:`, and no `use:`"
                ),
            )));
                return None;
            }
            (None, 1) => {
                if raw.with.is_some() {
                    diags.push(at(Diag::error(
                        "proef::pack::with_without_use",
                        format!(
                            "macro `{macro_name}` step {index}: `with:` only accompanies `use:`"
                        ),
                    )));
                }
                let (kind_key, value) = raw
                    .payload
                    .iter()
                    .next()
                    .map(|(k, v)| (k.clone(), v.clone()))?;
                let payload = match value {
                    serde_norway::Value::String(text) => PayloadForm::Raw(text),
                    other => PayloadForm::Structured(
                        serde_json::to_value(&other).unwrap_or(serde_json::Value::Null),
                    ),
                };
                MacroStepKind::Payload {
                    kind: kind_key,
                    payload,
                }
            }
            (None, _) => {
                let keys: Vec<&str> = raw.payload.keys().map(String::as_str).collect();
                diags.push(at(Diag::error(
                    "proef::pack::multiple_payloads",
                    format!(
                        "macro `{macro_name}` step {index} has {} payload keys ({}) — one per step",
                        keys.len(),
                        keys.join(", ")
                    ),
                )));
                return None;
            }
        }
    };

    // Delay cap (pass 6, typed half): a pause no budget can absorb is a
    // hang, not a test (ADR-0007).
    let delay_ms = match raw.delay {
        Some(ms) if ms > MAX_DELAY_MS => {
            diags.push(at(Diag::error(
                "proef::pack::delay_unbounded",
                format!(
                    "macro `{macro_name}` step {index}: `delay: {ms}` exceeds the {MAX_DELAY_MS} ms (1 hour) cap"
                ),
            )));
            None
        }
        other => other,
    };

    Some(MacroStep {
        name: raw.name.clone(),
        delay_ms,
        kind,
        optional: raw.optional,
        when: raw.when.clone(),
        retry,
        save_as,
        bind: raw.bind.clone(),
    })
}

/// Pass-6 caps (ADR-0007): counts or pauses above these cannot be absorbed
/// by any batch budget — they are hangs, not tests.
const MAX_COUNT: i64 = 10_000;
const MAX_DELAY_MS: u64 = 3_600_000;

/// Parse a raw `[Options]` duration value (`3000`, `500ms`, `3s`, `2m`) into
/// milliseconds. Templates (`{{…}}`) and anything else non-numeric return
/// `None` — the runtime budget still bounds those.
fn raw_duration_ms(value: &str) -> Option<u64> {
    let value = value.trim();
    let (number, unit_ms) = if let Some(n) = value.strip_suffix("ms") {
        (n, 1)
    } else if let Some(n) = value.strip_suffix('s') {
        (n, 1000)
    } else if let Some(n) = value.strip_suffix('m') {
        (n, 60_000)
    } else {
        (value, 1)
    };
    number.trim().parse::<u64>().ok()?.checked_mul(unit_ms)
}

/// Passes over the complete macro set: `use:` graph (4, 5), payload kinds (8),
/// raw-block finite-retry scan (6), and engine probe validation (7).
pub(crate) fn run_cross_macro_passes(set: &PackSet, kinds: &[StepKindSpec], diags: &mut Vec<Diag>) {
    for macro_ in set.macros.values() {
        let at = |diag: Diag| {
            diag.with_source(macro_.pack.clone(), Arc::clone(&macro_.source))
                .maybe_span(macro_.span)
        };
        let MacroBody::Steps(steps) = &macro_.body else {
            continue;
        };

        let mut payload_ordinals: BTreeMap<&str, usize> = BTreeMap::new();
        for (index, step) in steps.iter().enumerate() {
            match &step.kind {
                MacroStepKind::Use { target, with } => {
                    use_target_passes(set, macro_, index, target, with, &at, diags);
                }
                MacroStepKind::Ref { target } => {
                    ref_target_passes(set, macro_, index, step, target, &at, diags);
                }
                MacroStepKind::Payload { kind, payload } => {
                    let ordinal = *payload_ordinals
                        .entry(kind.as_str())
                        .and_modify(|n| *n += 1)
                        .or_insert(0);
                    payload_passes(
                        macro_, index, kind, step, payload, ordinal, kinds, &at, diags,
                    );
                }
            }
        }
    }

    use_graph_passes(set, diags);
}

/// Target existence for one `ref:`, plus the double-declaration checks against
/// the fragment's own `[Options]` — the same rule `lint_raw_options` applies to
/// an inline block, so the two body forms behave identically rather than
/// differing by where the hurl text happens to live.
///
/// Two comparisons, because the two halves of an `[Options]` section clash on
/// different keys: option *families* (`retry:`, `delay:`) family-to-family, and
/// supplied *variables* name-to-name.
fn ref_target_passes(
    set: &PackSet,
    macro_: &Macro,
    index: usize,
    step: &MacroStep,
    target: &str,
    at: &impl Fn(Diag) -> Diag,
    diags: &mut Vec<Diag>,
) {
    let Some(fragment) = set.find_fragment(target) else {
        let suggestion = matcher::closest(
            target.rsplit('#').next().unwrap_or(target),
            set.fragments.keys().map(String::as_str),
        )
        .map(|f| format!(" — did you mean `{f}`?"))
        .unwrap_or_default();
        diags.push(
            at(Diag::error(
                "proef::pack::unknown_ref",
                format!(
                    "macro `{}` step {index}: `ref: {target}` names no loaded fragment{suggestion}",
                    macro_.name
                ),
            ))
            .with_help(if set.fragments.is_empty() {
                "no fragment files were loaded — set `[run] fragments` in proef.toml to the \
                 directory holding them"
            } else {
                "a fragment is one hurl entry marked `# @proef <name>` in a scanned file"
            }),
        );
        return;
    };
    // Every option family the step sets, not just retry: `delay:` bakes into the
    // same `[Options]` section through the same code path, so leaving it
    // unchecked reproduces exactly the silent last-wins the inline half of this
    // rule exists to refuse. The families come from the step itself, so this and
    // `lint_raw_options` cannot disagree about what a step declared.
    for family in step.declared_options() {
        if fragment.declared_options.iter().any(|o| o == family) {
            diags.push(at(Diag::error(
                "proef::pack::option_declared_twice",
                format!(
                    "macro `{}` step {index}: `{family}` is declared twice — in fragment `{}` (`{}` line {}) and as this step's own `{family}:`",
                    macro_.name, fragment.name, fragment.file, fragment.line
                ),
            )).with_help(
                "an entry carries one policy per option — delete whichever of the two is not authoritative",
            ));
        }
    }
    // The same rule one level down. A `bind:` reaches hurl as `[Options]
    // variable:`, so a fragment supplying that name is the identical silent
    // last-wins — except here the *fragment's* line lands last and wins,
    // discarding the value the pack author wrote. Worse than the retry case:
    // hurl assigns `variable:` into the run-level set rather than scoping it,
    // so the discarded value stays discarded for every later entry too.
    for name in &fragment.supplied_variables {
        let Some(scope) = binding_scope(set, macro_, step, name) else {
            continue;
        };
        diags.push(
            at(Diag::error(
                "proef::pack::option_declared_twice",
                format!(
                    "macro `{}` step {index}: `{name}` is supplied twice — by fragment `{}` (`{}` line {}) and by the {scope} `bind:`",
                    macro_.name, fragment.name, fragment.file, fragment.line
                ),
            ))
            .with_help(format!(
                "delete whichever is not authoritative — both reach the entry as \
                 `variable: {name}=`, where the fragment's own line lands last and the bound \
                 value would never reach the request",
            )),
        );
    }
}

/// Which `bind:` scope supplies `name`, most specific first — the half of a
/// double-supply diagnostic that says where to look for the other declaration.
fn binding_scope(
    set: &PackSet,
    macro_: &Macro,
    step: &MacroStep,
    name: &str,
) -> Option<&'static str> {
    if step.bind.contains_key(name) {
        Some("step's")
    } else if macro_.bind.contains_key(name) {
        Some("macro's")
    } else if set
        .bind
        .get(&macro_.pack)
        .is_some_and(|table| table.contains_key(name))
    {
        Some("pack's")
    } else {
        None
    }
}

/// Pass 4 (target existence) + pass 5 (`with:` key coverage) for one `use:`.
fn use_target_passes(
    set: &PackSet,
    macro_: &Macro,
    index: usize,
    target: &str,
    with: &BTreeMap<String, String>,
    at: &impl Fn(Diag) -> Diag,
    diags: &mut Vec<Diag>,
) {
    let Some(target_macro) = set.find_use_target(target) else {
        let suggestion = matcher::closest(
            target.rsplit('#').next().unwrap_or(target),
            set.macros.keys().map(String::as_str),
        )
        .map(|m| format!(" — did you mean `{m}`?"))
        .unwrap_or_default();
        diags.push(at(Diag::error(
            "proef::pack::unknown_use",
            format!(
                "macro `{}` step {index}: `use: {target}` names no loaded macro{suggestion}",
                macro_.name
            ),
        )));
        return;
    };

    for key in with.keys() {
        if !target_macro.params.contains(key) {
            let suggestion = matcher::closest(key, target_macro.params.iter().map(String::as_str))
                .map(|p| format!(" — did you mean `{p}`?"))
                .unwrap_or_default();
            diags.push(at(Diag::error(
                "proef::pack::unknown_with_key",
                format!(
                    "macro `{}` step {index}: `with:` key `{key}` is not a param of `{}`{suggestion}",
                    macro_.name, target_macro.name
                ),
            )));
        }
    }
    for param in &target_macro.params {
        if !with.contains_key(param) && !target_macro.defaults.contains_key(param) {
            diags.push(at(Diag::error(
                "proef::pack::missing_use_param",
                format!(
                    "macro `{}` step {index}: `use: {}` needs `with: {{ {param}: … }}` (no default exists)",
                    macro_.name, target_macro.name
                ),
            )));
        }
    }
}

/// Passes 8 (kind claimed), 6 (raw-block infinite retry/repeat), and 7
/// (engine probe validation) for one payload step.
#[allow(clippy::too_many_arguments)]
fn payload_passes(
    macro_: &Macro,
    index: usize,
    kind: &str,
    step: &MacroStep,
    payload: &PayloadForm,
    ordinal: usize,
    kinds: &[StepKindSpec],
    at: &impl Fn(Diag) -> Diag,
    diags: &mut Vec<Diag>,
) {
    // Pass 8: the kind must be claimed by a registered engine.
    let Some(spec) = kinds.iter().find(|s| s.prefix == kind) else {
        let suggestion = matcher::closest(kind, kinds.iter().map(|s| s.prefix))
            .map(|p| format!(" — did you mean `{p}:`?"))
            .unwrap_or_default();
        diags.push(at(Diag::error(
            "proef::pack::unknown_step_kind",
            format!(
                "macro `{}` step {index}: step kind `{kind}:` is not claimed by any registered engine{suggestion}",
                macro_.name
            ),
        )));
        return;
    };

    let text = match payload {
        PayloadForm::Raw(text) => text,
        PayloadForm::Structured(value) => {
            // Structured payload (ADR-0004): hand its canonical JSON text to
            // the engine's validator — the same load-time gate raw payloads
            // get. `${…}` placeholders may remain inside strings; validators
            // check shape, not values.
            if let Some(validate) = spec.validate
                && let Ok(json) = serde_json::to_string(value)
                && let Err(err) = validate(&json)
            {
                diags.push(at(Diag::error(
                    "proef::pack::payload_invalid",
                    format!(
                        "macro `{}` step {index}: `{kind}:` payload is invalid — {}",
                        macro_.name, err.message
                    ),
                )));
            }
            return;
        }
    };

    lint_raw_options(macro_, index, kind, step, ordinal, text, at, diags);

    // Pass 7: probe-instantiation parse via the engine's validator.
    let Some(validate) = spec.validate else {
        return;
    };
    match probe_lower(macro_, text) {
        Err(err) => {
            diags.push(at(Diag::error(
                "proef::pack::bad_reference",
                format!("macro `{}` step {index}: {err}", macro_.name),
            )));
        }
        Ok(candidates) => {
            let mut first_error = None;
            let mut passed = false;
            for candidate in &candidates {
                match validate(candidate) {
                    Ok(()) => {
                        passed = true;
                        break;
                    }
                    Err(err) => first_error = first_error.or(Some(err)),
                }
            }
            if !passed && let Some(err) = first_error {
                diags.push(
                        at(Diag::error(
                            "proef::pack::invalid_hurl",
                            format!(
                                "macro `{}` step {index}: payload does not parse: {} (payload line {}, column {})",
                                macro_.name, err.message, err.line, err.column
                            ),
                        ))
                        .maybe_span(locate::payload_line_span(
                            &macro_.source,
                            &macro_.name,
                            kind,
                            ordinal,
                            err.line,
                        )),
                    );
            }
        }
    }
}

/// Pass 6 (raw half): hurl allows infinite `retry`/`repeat` and unbounded
/// `delay` — parse numeric raw-option values and reject what no budget can
/// absorb (ADR-0007). Non-numeric values (`{{…}}` templates) pass: the
/// runtime batch budget still bounds those.
///
/// Also the double-declaration check: an option set *both* in the block's own
/// `[Options]` and as its YAML twin (`retry:` / `delay:`). Lowering extends an
/// author's section rather than opening a second one, and hurl resolves
/// duplicate options last-wins, so the raw value quietly beat the typed one —
/// the pack said one thing and the run did another. Only `[Options]`-section
/// lines count: a request header may legitimately be named `retry`, and this
/// is a hard error, so it must not fire on one.
// Both checks read the same one-pass scan; splitting them would walk the block
// twice and duplicate the fence and section bookkeeping.
#[allow(clippy::too_many_arguments)]
fn lint_raw_options(
    macro_: &Macro,
    index: usize,
    kind: &str,
    step: &MacroStep,
    ordinal: usize,
    text: &str,
    at: &impl Fn(Diag) -> Diag,
    diags: &mut Vec<Diag>,
) {
    let mut in_fence = false;
    let mut in_options = false;
    // One report per option family is enough to act on; a block whose every
    // entry repeats the clash would otherwise bury the step in duplicates.
    // A list rather than a flag per family, so a new family needs no latch.
    let mut said: Vec<&'static str> = Vec::new();
    for (line_no, line) in text.lines().enumerate() {
        let trimmed = line.trim();
        if trimmed.starts_with("```") {
            in_fence = !in_fence;
            continue;
        }
        if in_fence {
            continue; // fenced body data — a literal `retry: -1` is payload, not an option
        }
        // A section runs until the next section header or the next entry.
        if trimmed.starts_with('[') {
            in_options = trimmed == "[Options]";
        } else if crate::lower::is_method_line(trimmed) {
            in_options = false;
        }
        let mut reject = |code: &'static str, message: String| {
            diags.push(
                at(Diag::error(
                    code,
                    format!("macro `{}` step {index}: {message}", macro_.name),
                ))
                .maybe_span(locate::payload_line_span(
                    &macro_.source,
                    &macro_.name,
                    kind,
                    ordinal,
                    line_no + 1,
                )),
            );
        };
        for option in ["retry", "repeat"] {
            if let Some(value) = trimmed.strip_prefix(&format!("{option}:")) {
                match value.trim().parse::<i64>() {
                    Ok(-1) => reject(
                        "proef::pack::retry_not_finite",
                        format!(
                            "`{option}: -1` is infinite — budgets require a finite count (ADR-0007)"
                        ),
                    ),
                    Ok(n) if n > MAX_COUNT => reject(
                        "proef::pack::retry_not_finite",
                        format!("`{option}: {n}` is budget-hostile — the cap is {MAX_COUNT}"),
                    ),
                    _ => {}
                }
            }
        }
        if let Some(value) = trimmed.strip_prefix("delay:")
            && let Some(ms) = raw_duration_ms(value)
            && ms > MAX_DELAY_MS
        {
            reject(
                "proef::pack::delay_unbounded",
                format!(
                    "`delay: {}` exceeds the {MAX_DELAY_MS} ms (1 hour) cap",
                    value.trim()
                ),
            );
        }
        if !in_options {
            continue;
        }
        // hurl's `retry-interval` folds into `retry` — one policy, and a step's
        // `retry:` sets both — so the two spellings map to the one family the
        // pack knows (`engine::OPTION_FAMILIES`).
        let option = if trimmed.starts_with("retry:") || trimmed.starts_with("retry-interval:") {
            "retry"
        } else if trimmed.starts_with("delay:") {
            "delay"
        } else {
            continue;
        };
        if step.declared_options().any(|f| f == option) && !said.contains(&option) {
            said.push(option);
            diags.push(
                at(Diag::error(
                    "proef::pack::option_declared_twice",
                    format!(
                        "macro `{}` step {index}: `{option}` is declared twice — here in `[Options]`, and as the step's own `{option}:`",
                        macro_.name
                    ),
                ))
                .maybe_span(locate::payload_line_span(
                    &macro_.source,
                    &macro_.name,
                    kind,
                    ordinal,
                    line_no + 1,
                ))
                .with_help(
                    "an entry carries one policy per option — delete whichever of the two is not authoritative",
                ),
            );
        }
    }
}

/// Probe-lower a payload: substitute placeholder params and resolve in
/// [`ResolveMode::Probe`]. Engine payload grammar is positional (URLs need a
/// scheme or template, statuses need digits), so two placeholder shapes are
/// tried — template-form first, numeric second; a block failing both is
/// genuinely malformed. The authoritative check is M2's parse of the *real*
/// emitted artifact; this pass is early feedback at pack-authoring time.
fn probe_lower(macro_: &Macro, text: &str) -> Result<Vec<String>, resolve::ResolveError> {
    let world = World::default();
    let empty = BTreeMap::new();
    let mut candidates = Vec::new();
    for placeholder in ["{{probe}}", "1"] {
        let args: BTreeMap<String, String> = macro_
            .params
            .iter()
            .map(|p| (p.clone(), placeholder.to_owned()))
            .collect();
        let ctx = ResolveCtx {
            args: &args,
            defaults: &macro_.defaults,
            env: &empty,
            config_vars: &empty,
            run_id: "probe-run",
            world: &world,
            mode: ResolveMode::Probe,
        };
        // A fresh probe, not a scenario — the occurrence counter starts at 0
        // for each placeholder candidate; this pass only checks grammar.
        let mut fakes = 0;
        let Resolution { text, .. } = resolve::resolve(text, &ctx, &mut fakes)?;
        candidates.push(text);
    }
    Ok(candidates)
}

/// Pass 4: `use:` reference cycles and depth over the whole macro graph.
/// Three-color DFS with memoized chain depths — node-linear where a per-root
/// path enumeration goes exponential on shared (multi-edge) `use:` targets.
fn use_graph_passes(set: &PackSet, diags: &mut Vec<Diag>) {
    let mut colors: BTreeMap<&str, Color> = BTreeMap::new();
    let mut chains: BTreeMap<&str, usize> = BTreeMap::new();
    for macro_ in set.macros.values() {
        visit_uses(set, macro_, &mut colors, &mut chains, diags);
    }
    for macro_ in set.macros.values() {
        if chains.get(macro_.name.as_str()).copied().unwrap_or(1) <= MAX_USE_DEPTH {
            continue;
        }
        let path = longest_use_path(set, macro_, &chains);
        // The first macro past the limit carries the diagnostic — the same
        // attribution the depth-33 stack frame had under the walking scheme.
        let Some(deep) = path.get(MAX_USE_DEPTH).copied() else {
            continue; // depth reached only through a cycle — already reported
        };
        diags.push(
            Diag::error(
                "proef::pack::use_too_deep",
                format!(
                    "`use:` nesting exceeds depth {MAX_USE_DEPTH} (via `{}`)",
                    path[..=MAX_USE_DEPTH]
                        .iter()
                        .map(|m| m.name.as_str())
                        .collect::<Vec<_>>()
                        .join("` → `")
                ),
            )
            .with_source(deep.pack.clone(), Arc::clone(&deep.source))
            .maybe_span(deep.span),
        );
    }
}

#[derive(Clone, Copy)]
enum Color {
    Gray,
    Black,
}

enum Frame<'a> {
    Enter(&'a Macro),
    Exit(&'a Macro),
}

/// Resolvable `use:` targets of a macro, in step order.
fn use_targets<'a>(set: &'a PackSet, macro_: &'a Macro) -> Vec<&'a Macro> {
    let MacroBody::Steps(steps) = &macro_.body else {
        return Vec::new();
    };
    steps
        .iter()
        .filter_map(|step| {
            let MacroStepKind::Use { target, .. } = &step.kind else {
                return None;
            };
            set.find_use_target(target) // unresolved: reported by use_target_passes
        })
        .collect()
}

/// Iterative DFS from one root (explicit frames — the walk must stay
/// stack-safe on arbitrarily long chains): gray while on the path, black once
/// the longest downstream chain is memoized in `chains`. A `use:` edge to a
/// gray macro closes a cycle.
fn visit_uses<'a>(
    set: &'a PackSet,
    root: &'a Macro,
    colors: &mut BTreeMap<&'a str, Color>,
    chains: &mut BTreeMap<&'a str, usize>,
    diags: &mut Vec<Diag>,
) {
    if colors.contains_key(root.name.as_str()) {
        return;
    }
    let mut work = vec![Frame::Enter(root)];
    let mut path: Vec<&'a Macro> = Vec::new();
    while let Some(frame) = work.pop() {
        match frame {
            Frame::Enter(m) => {
                if colors.contains_key(m.name.as_str()) {
                    continue; // finished via an earlier multi-edge
                }
                colors.insert(m.name.as_str(), Color::Gray);
                path.push(m);
                work.push(Frame::Exit(m));
                for next in use_targets(set, m).into_iter().rev() {
                    match colors.get(next.name.as_str()).copied() {
                        Some(Color::Gray) => report_use_cycle(&path, next, diags),
                        Some(Color::Black) => {} // chain read at Exit
                        None => work.push(Frame::Enter(next)),
                    }
                }
            }
            Frame::Exit(m) => {
                path.pop();
                let chain = 1 + use_targets(set, m)
                    .into_iter()
                    .filter_map(|next| chains.get(next.name.as_str()).copied())
                    .max()
                    .unwrap_or(0);
                colors.insert(m.name.as_str(), Color::Black);
                chains.insert(m.name.as_str(), chain);
            }
        }
    }
}

/// Render one cycle: rotate the gray-path ring to start at its
/// lexicographically-first member; the member whose `use:` closes back to it
/// carries the diagnostic.
fn report_use_cycle(path: &[&Macro], next: &Macro, diags: &mut Vec<Diag>) {
    let pos = path.iter().position(|m| m.name == next.name).unwrap_or(0);
    let ring = &path[pos..];
    let min_ix = ring
        .iter()
        .enumerate()
        .min_by_key(|(_, m)| m.name.as_str())
        .map_or(0, |(i, _)| i);
    let rotated: Vec<&Macro> = ring[min_ix..]
        .iter()
        .chain(&ring[..min_ix])
        .copied()
        .collect();
    let Some(closer) = rotated.last().copied() else {
        return;
    };
    let names: Vec<&str> = rotated.iter().map(|m| m.name.as_str()).collect();
    diags.push(
        Diag::error(
            "proef::pack::use_cycle",
            format!("`use:` cycle: `{}` → `{}`", names.join("` → `"), names[0]),
        )
        .with_source(closer.pack.clone(), Arc::clone(&closer.source))
        .maybe_span(closer.span),
    );
}

/// Follow max-chain children from `from` — in a cycle-free graph this is a
/// longest `use:` chain, matching the memoized depth that triggered the
/// diagnostic.
fn longest_use_path<'a>(
    set: &'a PackSet,
    from: &'a Macro,
    chains: &BTreeMap<&'a str, usize>,
) -> Vec<&'a Macro> {
    let mut path = vec![from];
    while path.len() <= MAX_USE_DEPTH {
        let cur = path[path.len() - 1];
        let next = use_targets(set, cur)
            .into_iter()
            .filter(|cand| !path.iter().any(|m| m.name == cand.name))
            .max_by_key(|cand| chains.get(cand.name.as_str()).copied().unwrap_or(1));
        match next {
            Some(next) => path.push(next),
            None => break,
        }
    }
    path
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)]

    use std::sync::Arc;

    use crate::diag::FrontError;
    use crate::engine::{PayloadProbeError, StepKindSpec};
    use crate::pack::{self, PackSource};

    fn deny(_json: &str) -> Result<(), PayloadProbeError> {
        Err(PayloadProbeError {
            line: 1,
            column: 1,
            message: "unknown alt verb".into(),
        })
    }

    const KINDS: &[StepKindSpec] = &[StepKindSpec {
        prefix: "alt",
        schema: "true",
        validate: Some(deny),
        fragments: None,
    }];

    /// A whitespace-only `hurl:` fragment with no `status:` carries no assert
    /// line — lowering it would produce a zero-line merged-asserts step, which
    /// underflows the sidecar's `start + lines - 1` span arithmetic. Pack
    /// validation rejects it before that can happen, spanning the `hurl:`
    /// line itself rather than the whole macro.
    #[test]
    fn whitespace_only_expect_fragment_is_rejected() {
        let source = PackSource {
            name: "expect.yaml".into(),
            text: Arc::from(
                "macros:\n  empty:\n    match: nothing binds this\n    expect:\n      - hurl: |\n\n",
            ),
        };
        let err = pack::load(&[source], &crate::pack::FragmentCorpus::empty(), KINDS).unwrap_err();
        let FrontError::Diagnostics(diags) = err else {
            panic!("diagnostics expected");
        };
        let diag = diags
            .iter()
            .find(|d| d.code == "proef::pack::empty_expect")
            .unwrap_or_else(|| panic!("expected proef::pack::empty_expect in {diags:?}"));
        assert!(diag.help.is_some(), "a remediation hint is expected");
        let text = diag.source_text.as_ref().unwrap();
        let span = diag
            .span
            .unwrap_or_else(|| panic!("expected a span: {diag:?}"));
        assert_eq!(
            &text[span.start..span.end],
            "hurl: |",
            "span should land on the empty fragment's `hurl:` line, not the whole macro"
        );
    }

    /// A flow-style item (`- {status: …, hurl: …}`) parses `item.hurl` to
    /// `Some`, but the block-style line scanner behind
    /// `locate::expect_hurl_line_spans` cannot see it and contributes no
    /// span — the same hazard `analyze::index_use_refs` already guards for
    /// `use:` lines. Pin that the guard here falls back to the macro's own
    /// span for the whole macro, rather than pairing a later blank item onto
    /// a wrong, ordinal-shifted line.
    #[test]
    fn flow_style_hurl_key_falls_back_to_the_macro_span() {
        let text: Arc<str> = Arc::from(concat!(
            "macros:\n",
            "  mixed:\n",
            "    match: nothing binds this\n",
            "    expect:\n",
            "      - {status: \"200\", hurl: 'jsonpath \"$.a\" exists'}\n",
            "      - hurl: |\n",
            "\n",
            "      - hurl: |\n",
            "          jsonpath \"$.b\" exists\n",
        ));
        let source = PackSource {
            name: "mixed.yaml".into(),
            text: Arc::clone(&text),
        };
        let err = pack::load(&[source], &crate::pack::FragmentCorpus::empty(), KINDS).unwrap_err();
        let FrontError::Diagnostics(diags) = err else {
            panic!("diagnostics expected");
        };
        let empty_expect: Vec<_> = diags
            .iter()
            .filter(|d| d.code == "proef::pack::empty_expect")
            .collect();
        assert_eq!(
            empty_expect.len(),
            1,
            "only the blank second item should be flagged: {diags:?}"
        );
        let diag = empty_expect[0];
        assert!(
            diag.message.contains("expect item 1"),
            "the blank item is index 1: {diag:?}"
        );
        let macro_span =
            crate::pack::locate::macro_span(&text, "mixed").unwrap_or_else(|| panic!("macro span"));
        assert_eq!(
            diag.span,
            Some(macro_span),
            "an unreliable line-scan pairing must anchor on the macro, not a later item's line"
        );
    }

    /// Structured payloads reach the engine's validator at load time —
    /// the same gate raw payloads have always had.
    #[test]
    fn structured_payloads_run_the_engine_validator() {
        let source = PackSource {
            name: "alt.yaml".into(),
            text: Arc::from(
                "macros:\n  probe:\n    match: the alternate step runs\n    steps:\n      - alt:\n          bogus: 1\n",
            ),
        };
        let err = pack::load(&[source], &crate::pack::FragmentCorpus::empty(), KINDS).unwrap_err();
        let FrontError::Diagnostics(diags) = err else {
            panic!("diagnostics expected");
        };
        assert!(
            diags
                .iter()
                .any(|d| d.code == "proef::pack::payload_invalid"
                    && d.message.contains("unknown alt verb")),
            "{diags:?}"
        );
    }

    /// A doubled-edge `use:` chain that path enumeration would walk ~2^30
    /// times loads instantly under the node-linear graph passes, and a chain
    /// of exactly [`MAX_USE_DEPTH`] macros raises no diagnostics.
    #[test]
    fn use_graph_walk_is_linear_on_multi_edge_dags() {
        const PLAIN: &[StepKindSpec] = &[StepKindSpec {
            prefix: "alt",
            schema: "true",
            validate: None,
            fragments: None,
        }];
        use std::fmt::Write as _;
        let mut yaml = String::from("macros:\n");
        for i in 0..31 {
            writeln!(yaml, "  m{i:02}:").unwrap();
            if i == 0 {
                yaml.push_str("    match: the chain runs\n");
            }
            writeln!(
                yaml,
                "    steps:\n      - use: m{next:02}\n      - use: m{next:02}",
                next = i + 1
            )
            .unwrap();
        }
        yaml.push_str("  m31:\n    steps:\n      - alt:\n          probe: 1\n");
        let packs = pack::load(
            &[PackSource {
                name: "chain.yaml".into(),
                text: Arc::from(yaml.as_str()),
            }],
            &crate::pack::FragmentCorpus::empty(),
            PLAIN,
        )
        .unwrap();
        assert_eq!(packs.macros.len(), 32);
    }

    /// No validator, so nothing but the raw-option lint speaks.
    const RAW: &[StepKindSpec] = &[StepKindSpec {
        prefix: "alt",
        schema: "true",
        validate: None,
        fragments: None,
    }];

    /// Setting an option in both the block's `[Options]` and its YAML twin
    /// used to run silently: lowering extends the author's own section rather
    /// than opening a second one, and hurl resolves a duplicated option
    /// last-wins, so the raw value won and the pack's `retry:` was a lie. The
    /// span lands on the raw line — the one that used to take effect.
    #[test]
    fn an_option_set_in_both_places_is_rejected() {
        let source = PackSource {
            name: "twice.yaml".into(),
            text: Arc::from(concat!(
                "macros:\n",
                "  twiceOver:\n",
                "    match: I set the retry in both places\n",
                "    steps:\n",
                "      - retry: { count: 3, interval_ms: 200 }\n",
                "        alt: |\n",
                "          GET http://x\n",
                "          [Options]\n",
                "          retry: 5\n",
                "          HTTP 200\n",
            )),
        };
        let FrontError::Diagnostics(diags) =
            pack::load(&[source], &crate::pack::FragmentCorpus::empty(), RAW).unwrap_err()
        else {
            panic!("diagnostics expected");
        };
        let diag = diags
            .iter()
            .find(|d| d.code == "proef::pack::option_declared_twice")
            .unwrap_or_else(|| panic!("expected the clash in {diags:?}"));
        assert!(diag.help.is_some(), "a remediation hint is expected");
        let text = diag.source_text.as_ref().unwrap();
        let span = diag
            .span
            .unwrap_or_else(|| panic!("expected a span: {diag:?}"));
        assert_eq!(
            &text[span.start..span.end],
            "retry: 5",
            "span should land on the raw option line, not the whole macro"
        );
        assert_eq!(
            diags
                .iter()
                .filter(|d| d.code == "proef::pack::option_declared_twice")
                .count(),
            1,
            "one report per option family, however many entries repeat it"
        );
    }

    /// The scan is `[Options]`-scoped on purpose. `retry` is a legal *request
    /// header* name, and a header line is `name: value` like an option line —
    /// so a line-shaped match alone would turn an ordinary header into a hard
    /// error the moment the step also carried a typed `retry:`.
    #[test]
    fn a_request_header_named_retry_is_not_a_clash() {
        let source = PackSource {
            name: "header.yaml".into(),
            text: Arc::from(concat!(
                "macros:\n",
                "  headerRetry:\n",
                "    match: the request header is named retry\n",
                "    steps:\n",
                "      - retry: { count: 3, interval_ms: 200 }\n",
                "        alt: |\n",
                "          GET http://x\n",
                "          retry: 5\n",
                "          HTTP 200\n",
            )),
        };
        pack::load(&[source], &crate::pack::FragmentCorpus::empty(), RAW)
            .unwrap_or_else(|err| panic!("a header named `retry` must not clash: {err:?}"));
    }

    // -----------------------------------------------------------------------
    // Fragments (ADR-0018)
    // -----------------------------------------------------------------------

    /// A stand-in for a real engine's scanner. `proef-core` cannot depend on
    /// `proef-engine-hurl`, so these tests drive the loader through the seam
    /// exactly as a future engine would — which is also the point: nothing in
    /// the loading rules knows what hurl is.
    ///
    /// `@name` opens a fragment, `retry` marks the one above as declaring a
    /// retry policy, `?var` a read, `!var` a capture, and `@!boom` fails.
    fn fake_scan(
        text: &str,
    ) -> Result<Vec<crate::engine::ScannedFragment>, crate::engine::FragmentScanError> {
        let mut out: Vec<crate::engine::ScannedFragment> = Vec::new();
        for (index, line) in text.lines().enumerate() {
            let line = line.trim();
            if line == "@!boom" {
                return Err(crate::engine::FragmentScanError {
                    line: index + 1,
                    column: 1,
                    message: "unreadable entry".to_owned(),
                });
            }
            if let Some(name) = line.strip_prefix('@') {
                out.push(crate::engine::ScannedFragment {
                    name: name.to_owned(),
                    text: format!("GET http://x/{name}\n"),
                    line: index + 1,
                    placeholders: Vec::new(),
                    declared_options: Vec::new(),
                    supplied_variables: Vec::new(),
                });
            } else if let Some(last) = out.last_mut() {
                if line == "retry" {
                    last.declared_options.push("retry".to_owned());
                } else if let Some(read) = line.strip_prefix('?') {
                    last.placeholders.push(read.to_owned());
                } else if let Some(supplied) = line.strip_prefix('=') {
                    use std::fmt::Write as _;
                    let _ = write!(last.text, "[Options]\nvariable: {supplied}=from-fragment\n");
                    last.supplied_variables.push(supplied.to_owned());
                }
            }
        }
        Ok(out)
    }

    const SCANNING: &[StepKindSpec] = &[StepKindSpec {
        prefix: "alt",
        schema: "true",
        validate: None,
        fragments: Some(crate::engine::FragmentSupport {
            ext: "frag",
            scan: fake_scan,
        }),
    }];

    fn source(name: &str, text: &str) -> PackSource {
        PackSource {
            name: name.to_owned(),
            text: Arc::from(text),
        }
    }

    fn diags_of(packs: &[PackSource], fragments: &[PackSource]) -> Vec<crate::diag::Diag> {
        let corpus = pack::FragmentCorpus::new(fragments.to_vec(), SCANNING);
        match pack::load(packs, &corpus, SCANNING) {
            Ok(_) => Vec::new(),
            Err(FrontError::Diagnostics(diags)) => diags,
            Err(other) => panic!("diagnostics expected, got {other:?}"),
        }
    }

    fn has(diags: &[crate::diag::Diag], code: &str) -> bool {
        diags.iter().any(|d| d.code == code)
    }

    #[test]
    fn a_ref_names_a_loaded_fragment() {
        let packs = pack::load(
            &[source(
                "p.yaml",
                "macros:\n  m:\n    match: it runs\n    steps:\n      - ref: admin.search\n",
            )],
            &pack::FragmentCorpus::new(vec![source("api.frag", "@admin.search\n")], SCANNING),
            SCANNING,
        )
        .unwrap_or_else(|err| panic!("should load: {err:?}"));
        assert_eq!(packs.fragments.len(), 1);
        assert!(packs.find_fragment("admin.search").is_some());
        // Qualified and bare spellings resolve the same fragment, as `use:` does.
        assert!(packs.find_fragment("api.frag#admin.search").is_some());
        assert!(packs.find_fragment("other.frag#admin.search").is_none());
    }

    #[test]
    fn a_ref_to_an_unknown_fragment_is_rejected_with_a_suggestion() {
        let diags = diags_of(
            &[source(
                "p.yaml",
                "macros:\n  m:\n    match: it runs\n    steps:\n      - ref: admin.serch\n",
            )],
            &[source("api.frag", "@admin.search\n")],
        );
        let diag = diags
            .iter()
            .find(|d| d.code == "proef::pack::unknown_ref")
            .unwrap_or_else(|| panic!("expected unknown_ref in {diags:?}"));
        assert!(diag.message.contains("did you mean `admin.search`?"));
    }

    /// With no fragment files loaded at all, the help has to say so — otherwise
    /// the author reads "names no loaded fragment" as a typo in their own name.
    #[test]
    fn an_unknown_ref_with_no_fragments_loaded_points_at_the_config() {
        let diags = diags_of(
            &[source(
                "p.yaml",
                "macros:\n  m:\n    match: it runs\n    steps:\n      - ref: admin.search\n",
            )],
            &[],
        );
        let diag = diags
            .iter()
            .find(|d| d.code == "proef::pack::unknown_ref")
            .unwrap_or_else(|| panic!("expected unknown_ref in {diags:?}"));
        assert!(
            diag.help
                .as_deref()
                .unwrap_or_default()
                .contains("fragments"),
            "{:?}",
            diag.help
        );
    }

    #[test]
    fn a_step_is_one_body_form_only() {
        let diags = diags_of(
            &[source(
                "p.yaml",
                "macros:\n  m:\n    match: it runs\n    steps:\n      - ref: f\n        alt: |\n          GET http://x\n",
            )],
            &[source("api.frag", "@f\n")],
        );
        assert!(has(&diags, "proef::pack::body_form_conflict"), "{diags:?}");
    }

    /// `bind:` feeds a fragment's variables. On an inline step there is nothing
    /// to feed, so accepting it would silently ignore what the author wrote.
    #[test]
    fn bind_without_a_ref_is_rejected() {
        let diags = diags_of(
            &[source(
                "p.yaml",
                "macros:\n  m:\n    match: it runs\n    steps:\n      - bind: { a: b }\n        alt: |\n          GET http://x\n",
            )],
            &[],
        );
        assert!(has(&diags, "proef::pack::bind_without_ref"), "{diags:?}");
    }

    /// The same rule one scope up. A macro-scope `bind:` on a macro with no
    /// `ref:` step is unreadable — and the tempting reading, that a `use:`
    /// target will pick it up, is wrong: the child resolves its own scopes.
    /// Left unchecked this is the *silent* half of the same mistake, and it is
    /// the one authors hit, because factoring plumbing upward is the habit.
    #[test]
    fn a_macro_scope_bind_with_no_ref_step_is_rejected() {
        let diags = diags_of(
            &[source(
                "p.yaml",
                "macros:\n  target:\n    match: the target\n    steps:\n      - ref: f\n  m:\n    match: it runs\n    bind:\n      a: b\n    steps:\n      - use: target\n",
            )],
            &[source("api.frag", "@f\n")],
        );
        assert!(has(&diags, "proef::pack::bind_without_ref"), "{diags:?}");
    }

    /// …and it must not fire on a macro that does have one, or the rule would
    /// refuse the feature it exists to protect.
    #[test]
    fn a_macro_scope_bind_beside_a_ref_step_is_accepted() {
        let diags = diags_of(
            &[source(
                "p.yaml",
                "macros:\n  m:\n    match: it runs\n    bind:\n      a: b\n    steps:\n      - ref: f\n",
            )],
            &[source("api.frag", "@f\n")],
        );
        assert!(!has(&diags, "proef::pack::bind_without_ref"), "{diags:?}");
    }

    /// `bind:` reaches hurl as `[Options] variable:`, so a fragment supplying
    /// the same name is the same silent last-wins `option_declared_twice` was
    /// built for — and it lands the wrong way round: the fragment's literal
    /// wins and the bound value never reaches the request. Checked at each
    /// scope, because the diagnostic has to say where the other half lives.
    #[test]
    fn a_variable_the_fragment_supplies_and_the_pack_binds_is_refused() {
        for (scope, pack) in [
            (
                "step's",
                "macros:\n  m:\n    match: it runs\n    steps:\n      - ref: f\n        bind:\n          token: v\n",
            ),
            (
                "macro's",
                "macros:\n  m:\n    match: it runs\n    bind:\n      token: v\n    steps:\n      - ref: f\n",
            ),
            (
                "pack's",
                "bind:\n  token: v\nmacros:\n  m:\n    match: it runs\n    steps:\n      - ref: f\n",
            ),
        ] {
            let diags = diags_of(
                &[source("p.yaml", pack)],
                &[source("api.frag", "@f\n=token\n")],
            );
            let diag = diags
                .iter()
                .find(|d| d.code == "proef::pack::option_declared_twice")
                .unwrap_or_else(|| panic!("expected {scope} clash in {diags:?}"));
            assert!(
                diag.message.contains("token") && diag.message.contains(scope),
                "{scope}: {}",
                diag.message
            );
        }
    }

    /// The other half of the same rule: a fragment may supply a variable no one
    /// binds. That is how the file stays runnable under stock `hurl` with no
    /// variables file, so refusing it would break ADR-0018's premise.
    #[test]
    fn a_variable_only_the_fragment_supplies_is_accepted() {
        let diags = diags_of(
            &[source(
                "p.yaml",
                "macros:\n  m:\n    match: it runs\n    steps:\n      - ref: f\n",
            )],
            &[source("api.frag", "@f\n=token\n")],
        );
        assert!(
            !has(&diags, "proef::pack::option_declared_twice"),
            "{diags:?}"
        );
    }

    #[test]
    fn fragment_names_are_global() {
        let diags = diags_of(
            &[source(
                "p.yaml",
                "macros:\n  m:\n    match: it runs\n    steps:\n      - ref: dup\n",
            )],
            &[source("a.frag", "@dup\n"), source("b.frag", "@dup\n")],
        );
        let diag = diags
            .iter()
            .find(|d| d.code == "proef::pack::duplicate_fragment")
            .unwrap_or_else(|| panic!("expected duplicate_fragment in {diags:?}"));
        assert!(diag.message.contains("a.frag") && diag.message.contains("b.frag"));
    }

    /// A fragment file the engine cannot read reports its own diagnostic and is
    /// skipped — the same "never sinks its siblings" rule packs get.
    #[test]
    fn an_unreadable_fragment_file_does_not_sink_the_others() {
        let diags = diags_of(
            &[source(
                "p.yaml",
                "macros:\n  m:\n    match: it runs\n    steps:\n      - ref: ok\n",
            )],
            &[source("bad.frag", "@!boom\n"), source("good.frag", "@ok\n")],
        );
        assert!(has(&diags, "proef::pack::bad_annotation"), "{diags:?}");
        assert!(
            !has(&diags, "proef::pack::unknown_ref"),
            "the readable file still loaded: {diags:?}"
        );
    }

    /// The same rule an inline block gets: one authority per option, whichever
    /// body form the hurl text lives in.
    #[test]
    fn retry_declared_by_both_fragment_and_step_is_rejected() {
        let diags = diags_of(
            &[source(
                "p.yaml",
                "macros:\n  m:\n    match: it runs\n    steps:\n      - ref: poll\n        retry: { count: 3, interval_ms: 200 }\n",
            )],
            &[source("api.frag", "@poll\nretry\n")],
        );
        let diag = diags
            .iter()
            .find(|d| d.code == "proef::pack::option_declared_twice")
            .unwrap_or_else(|| panic!("expected option_declared_twice in {diags:?}"));
        assert!(diag.message.contains("fragment `poll`"), "{}", diag.message);
    }

    #[test]
    fn bind_scopes_survive_loading() {
        let packs = pack::load(
            &[source(
                "p.yaml",
                "bind:\n  base: ${url:base}\nmacros:\n  m:\n    match: it runs\n    bind:\n      q: ${q}\n    steps:\n      - ref: f\n        bind:\n          id: \"{{recordId}}\"\n",
            )],
            &pack::FragmentCorpus::new(vec![source("api.frag", "@f\n")], SCANNING),
            SCANNING,
        )
        .unwrap_or_else(|err| panic!("should load: {err:?}"));
        assert_eq!(packs.bind["p.yaml"]["base"], "${url:base}");
        let macro_ = &packs.macros["m"];
        assert_eq!(macro_.bind["q"], "${q}");
        let crate::pack::MacroBody::Steps(steps) = &macro_.body else {
            panic!("steps expected");
        };
        assert_eq!(steps[0].bind["id"], "{{recordId}}");
    }

    /// A corpus is scanned **at most once**, however many times packs are loaded
    /// against it.
    ///
    /// One `proef test` loads packs up to four times — the suite, then
    /// `[run] setup`/`teardown`, each validated and then run — always against
    /// the same corpus. Rescanning per load measured ~75% of a 200-file run's
    /// total work, so this is a performance property, and performance nothing
    /// asserts is performance that quietly comes back.
    #[test]
    fn one_corpus_is_scanned_once_however_many_loads_read_it() {
        let packs = [source(
            "p.yaml",
            "macros:\n  m:\n    match: it runs\n    steps:\n      - ref: admin.search\n",
        )];
        let corpus =
            pack::FragmentCorpus::new(vec![source("api.frag", "@admin.search\n")], SCANNING);

        let (first, _) = pack::load_collecting(&packs, &corpus, SCANNING);
        let (second, _) = pack::load_collecting(&packs, &corpus, SCANNING);

        assert!(first.find_fragment("admin.search").is_some());
        assert!(
            Arc::ptr_eq(&first.fragments, &second.fragments),
            "a second load must reuse the first scan, not repeat it"
        );
    }

    /// A corpus nothing `ref:`s is never scanned — CONFIG.md's promise that
    /// pointing proef at a corpus you did not write costs nothing.
    ///
    /// Proven by making the scan *observable*: the file would fail to parse, so
    /// a `bad_annotation` diagnostic appears exactly when the scan ran. Sharing
    /// one corpus across loads must not have turned the scan eager.
    #[test]
    fn a_corpus_no_pack_refs_is_never_scanned() {
        let unreadable = vec![source("api.frag", "@!boom\n")];

        let no_ref = [source(
            "p.yaml",
            "macros:\n  m:\n    match: it runs\n    steps:\n      - alt: GET /x\n",
        )];
        let corpus = pack::FragmentCorpus::new(unreadable.clone(), SCANNING);
        let (_, diags) = pack::load_collecting(&no_ref, &corpus, SCANNING);
        assert!(
            !diags
                .iter()
                .any(|d| d.code == "proef::pack::bad_annotation"),
            "no `ref:` anywhere, so the corpus must never be read: {diags:?}"
        );

        // Control: the same corpus, with a `ref:` present, *is* scanned — so the
        // assertion above is about laziness, not about a scanner that never runs.
        let with_ref = [source(
            "p.yaml",
            "macros:\n  m:\n    match: it runs\n    steps:\n      - ref: whatever\n",
        )];
        let corpus = pack::FragmentCorpus::new(unreadable, SCANNING);
        let (_, diags) = pack::load_collecting(&with_ref, &corpus, SCANNING);
        assert!(
            diags
                .iter()
                .any(|d| d.code == "proef::pack::bad_annotation"),
            "a pack with a `ref:` must reach the scanner: {diags:?}"
        );
    }
}