lex-core 0.10.0

Parser library for the lex format
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
//! Tests for `lex_core::lex::includes`.
//!
//! Organized to make each individual test very short by routing all setup
//! through a small set of helpers and custom assertions:
//!
//! - [`fixture`] / [`fixture_at`] build a fresh resolution from a `main` source
//!   plus a slice of `(path, source)` pairs. They return either a fully
//!   resolved [`Document`] or an [`IncludeError`].
//! - The [`Tree`] wrapper exposes a position-independent vocabulary for
//!   asking "what's in the resolved tree" — session titles, paragraph texts,
//!   annotation labels, attached annotations on each node, the set of
//!   distinct origin paths.
//! - [`assert_no_unresolved_includes`], [`assert_origins`] and friends are
//!   the breadth assertions; the depth assertions live as `tree.invariant_*`
//!   methods so each test that constructs a tree exercises them implicitly.
//!
//! Adding a new behaviour: write the source pair, call `fixture(...)`,
//! make assertions on the returned [`Tree`]. If the assertion you want is
//! new, add it once here and reuse it.

use super::*;
use crate::lex::ast::elements::content_item::ContentItem;
use crate::lex::ast::Document;
use std::collections::BTreeSet;
use std::path::PathBuf;

// ============================================================================
// Fixture builder
// ============================================================================

/// Resolution root used by every fixture. A non-`/` root lets the
/// root-escape tests actually fail; a non-`/tmp`-style root keeps fixture
/// paths obviously test-only.
const TEST_ROOT: &str = "/repo";

/// Default entry-point path used by [`fixture`]. Matches the prefix that
/// every test's "/repo/..." files use, so relative includes from the entry
/// resolve against the same directory.
const DEFAULT_MAIN_PATH: &str = "/repo/main.lex";

/// Build a resolution from `main_source` + a slice of `(path, source)` files.
///
/// The entry-point file is registered at [`DEFAULT_MAIN_PATH`]. Files in
/// the slice should use `/repo/...` paths to live within [`TEST_ROOT`].
fn fixture(main_source: &str, files: &[(&str, &str)]) -> Result<Tree, IncludeError> {
    fixture_at(DEFAULT_MAIN_PATH, main_source, files)
}

/// Like [`fixture`] but lets a test pick an entry-point path other than the
/// default. The path is registered with the loader and used for both
/// relative-include resolution and origin stamping.
fn fixture_at(
    main_path: &str,
    main_source: &str,
    files: &[(&str, &str)],
) -> Result<Tree, IncludeError> {
    let mut loader = MemoryLoader::new();
    loader.insert(main_path, main_source);
    for (p, s) in files {
        loader.insert(*p, *s);
    }
    let config = ResolveConfig::with_root(PathBuf::from(TEST_ROOT));
    let doc = resolve_from_source(
        main_source,
        Some(PathBuf::from(main_path)),
        &config,
        &loader,
    )?;
    Ok(Tree { doc })
}

// ============================================================================
// Tree query wrapper
// ============================================================================

/// Read-only view over a resolved [`Document`] with shorthand accessors used
/// across tests. Keeps individual tests free of tree-walking boilerplate so
/// they read as "given X, expect Y."
struct Tree {
    doc: Document,
}

impl Tree {
    /// Top-level direct children of the document root, in source order.
    fn root_children(&self) -> &[ContentItem] {
        &self.doc.root.children
    }

    /// Titles of every top-level Session in source order.
    fn root_session_titles(&self) -> Vec<String> {
        self.root_children()
            .iter()
            .filter_map(|i| match i {
                ContentItem::Session(s) => Some(s.title.as_string().to_string()),
                _ => None,
            })
            .collect()
    }

    /// Texts of every top-level Paragraph in source order.
    fn root_paragraph_texts(&self) -> Vec<String> {
        self.root_children()
            .iter()
            .filter_map(|i| match i {
                ContentItem::Paragraph(p) => Some(p.text()),
                _ => None,
            })
            .collect()
    }

    /// All annotation labels in the resolved tree, recursively. Includes
    /// document-level annotations and each annotation's nested children
    /// (which themselves may contain spliced content from an include in
    /// the annotation's body).
    fn all_attached_annotation_labels(&self) -> Vec<String> {
        let mut out = Vec::new();
        for ann in &self.doc.annotations {
            out.push(ann.data.label.value.clone());
            collect_attached_labels(&ann.children, &mut out);
        }
        collect_attached_labels(self.root_children(), &mut out);
        out
    }

    /// Distinct origin paths across every block-level node in the tree.
    /// `None` means the node was not stamped (entry doc with no source path
    /// passed in, or a node the stamper missed — we use this in invariants).
    fn distinct_origin_paths(&self) -> BTreeSet<Option<PathBuf>> {
        let mut set = BTreeSet::new();
        // Root session and document title
        set.insert(
            self.doc
                .root
                .location
                .origin_path
                .as_ref()
                .map(|p| (**p).clone()),
        );
        for item in self.root_children() {
            collect_origins_from_item(item, &mut set);
        }
        set
    }

    /// Find the first session whose title equals `title` anywhere in the tree.
    fn find_session(&self, title: &str) -> Option<&Session> {
        find_session_in(self.root_children(), title)
    }

    /// Diagnostic dump: kind + label/title + attached-annotation labels, one
    /// per line, indented by depth. Use from a failing test with
    /// `cargo test ... -- --nocapture`.
    #[allow(dead_code)]
    fn dump(&self) -> String {
        let mut out = String::new();
        out.push_str(&format!(
            "Document(annotations=[{}], title={:?})\n",
            self.doc
                .annotations
                .iter()
                .map(|a| a.data.label.value.clone())
                .collect::<Vec<_>>()
                .join(","),
            self.doc.title.as_ref().map(|t| t.as_str()),
        ));
        dump_items(&self.doc.root.children, 1, &mut out);
        out
    }
}

#[allow(dead_code)]
fn dump_items(items: &[ContentItem], depth: usize, out: &mut String) {
    let pad = "  ".repeat(depth);
    for item in items {
        match item {
            ContentItem::Session(s) => {
                out.push_str(&format!(
                    "{pad}Session({:?}) attached=[{}]\n",
                    s.title.as_string(),
                    s.annotations
                        .iter()
                        .map(|a| format!("{}({:?})", a.data.label.value, a.include_src()))
                        .collect::<Vec<_>>()
                        .join(",")
                ));
                dump_items(&s.children, depth + 1, out);
            }
            ContentItem::Definition(d) => {
                out.push_str(&format!(
                    "{pad}Definition({:?}) attached=[{}]\n",
                    d.subject.as_string(),
                    d.annotations
                        .iter()
                        .map(|a| a.data.label.value.clone())
                        .collect::<Vec<_>>()
                        .join(",")
                ));
                dump_items(&d.children, depth + 1, out);
            }
            ContentItem::Paragraph(p) => {
                out.push_str(&format!(
                    "{pad}Paragraph({:?}) attached=[{}]\n",
                    p.text(),
                    p.annotations
                        .iter()
                        .map(|a| format!("{}({:?})", a.data.label.value, a.include_src()))
                        .collect::<Vec<_>>()
                        .join(",")
                ));
            }
            ContentItem::Annotation(a) => {
                out.push_str(&format!(
                    "{pad}Annotation({}, src={:?}) children:\n",
                    a.data.label.value,
                    a.include_src()
                ));
                dump_items(&a.children, depth + 1, out);
            }
            ContentItem::List(l) => {
                out.push_str(&format!("{pad}List({} items)\n", l.items.len()));
                dump_items(&l.items, depth + 1, out);
            }
            ContentItem::ListItem(li) => {
                out.push_str(&format!(
                    "{pad}ListItem({:?}) attached=[{}]\n",
                    li.text
                        .iter()
                        .map(|t| t.as_string().to_string())
                        .collect::<Vec<_>>()
                        .join(""),
                    li.annotations
                        .iter()
                        .map(|a| a.data.label.value.clone())
                        .collect::<Vec<_>>()
                        .join(",")
                ));
                dump_items(&li.children, depth + 1, out);
            }
            other => {
                out.push_str(&format!("{pad}{}\n", other.node_type()));
            }
        }
    }
}

fn collect_attached_labels(items: &[ContentItem], out: &mut Vec<String>) {
    for item in items {
        match item {
            ContentItem::Session(s) => {
                for ann in &s.annotations {
                    out.push(ann.data.label.value.clone());
                    collect_attached_labels(&ann.children, out);
                }
                collect_attached_labels(&s.children, out);
            }
            ContentItem::Definition(d) => {
                for ann in &d.annotations {
                    out.push(ann.data.label.value.clone());
                    collect_attached_labels(&ann.children, out);
                }
                collect_attached_labels(&d.children, out);
            }
            ContentItem::ListItem(li) => {
                for ann in &li.annotations {
                    out.push(ann.data.label.value.clone());
                    collect_attached_labels(&ann.children, out);
                }
                collect_attached_labels(&li.children, out);
            }
            ContentItem::Paragraph(p) => {
                for ann in &p.annotations {
                    out.push(ann.data.label.value.clone());
                    collect_attached_labels(&ann.children, out);
                }
            }
            ContentItem::List(l) => {
                collect_attached_labels(&l.items, out);
            }
            // Annotations remaining in the children list (rare post-attachment)
            // still contribute their label and any nested annotations they carry.
            ContentItem::Annotation(a) => {
                out.push(a.data.label.value.clone());
                collect_attached_labels(&a.children, out);
            }
            _ => {}
        }
    }
}

fn collect_origins_from_item(item: &ContentItem, set: &mut BTreeSet<Option<PathBuf>>) {
    let origin = item.range().origin_path.as_ref().map(|p| (**p).clone());
    set.insert(origin);
    match item {
        ContentItem::Session(s) => {
            for child in &s.children {
                collect_origins_from_item(child, set);
            }
        }
        ContentItem::Definition(d) => {
            for child in &d.children {
                collect_origins_from_item(child, set);
            }
        }
        ContentItem::ListItem(li) => {
            for child in &li.children {
                collect_origins_from_item(child, set);
            }
        }
        ContentItem::List(l) => {
            for li in &l.items {
                collect_origins_from_item(li, set);
            }
        }
        _ => {}
    }
}

fn find_session_in<'a>(items: &'a [ContentItem], title: &str) -> Option<&'a Session> {
    for item in items {
        if let ContentItem::Session(s) = item {
            if s.title.as_string() == title {
                return Some(s);
            }
            if let Some(found) = find_session_in(&s.children, title) {
                return Some(found);
            }
        }
    }
    None
}

// ============================================================================
// Custom assertions
// ============================================================================

use crate::lex::ast::traits::AstNode;

/// Assert no `lex.include` annotation remains anywhere in the tree (in
/// children OR in attached `.annotations` slots — annotations attached to
/// nodes are still expected, but no *unresolved* one should exist).
///
/// Currently includes are considered "unresolved" if they appear as a
/// standalone child item. Attached include annotations are the *expected*
/// post-resolution form (see proposal §5.1) — they identify the include site
/// for tooling.
fn assert_no_unresolved_includes(tree: &Tree) {
    let mut found = Vec::new();
    walk_for_unresolved_includes(tree.root_children(), &mut found);
    assert!(
        found.is_empty(),
        "unresolved lex.include annotations remain at: {found:?}"
    );
}

fn walk_for_unresolved_includes(items: &[ContentItem], found: &mut Vec<String>) {
    for item in items {
        match item {
            ContentItem::Annotation(a) if a.is_include() => {
                found.push(format!("{}", a.location));
            }
            ContentItem::Session(s) => walk_for_unresolved_includes(&s.children, found),
            ContentItem::Definition(d) => walk_for_unresolved_includes(&d.children, found),
            ContentItem::ListItem(li) => walk_for_unresolved_includes(&li.children, found),
            ContentItem::List(l) => walk_for_unresolved_includes(&l.items, found),
            ContentItem::Annotation(a) => walk_for_unresolved_includes(&a.children, found),
            _ => {}
        }
    }
}

/// Assert the set of distinct origin paths in the tree exactly matches
/// `expected` (after wrapping each path string in `Some`).
fn assert_origins(tree: &Tree, expected: &[&str]) {
    let actual = tree.distinct_origin_paths();
    let want: BTreeSet<Option<PathBuf>> =
        expected.iter().map(|s| Some(PathBuf::from(*s))).collect();
    assert_eq!(
        actual, want,
        "origin paths mismatch: got {actual:?}, expected {want:?}"
    );
}

/// Assert that the include annotation with `src=expected_src` is preserved
/// somewhere in the resolved tree.
///
/// "Preserved" means: attached to a node's `.annotations`, sitting in
/// `Document.annotations` (the natural landing spot for top-of-document
/// includes per standard lex annotation attachment), or — rarely — still
/// in a children list as a peer item.
fn assert_include_annotation_attached(tree: &Tree, expected_src: &str) {
    // Document-level first.
    for ann in &tree.doc.annotations {
        if ann.is_include() && ann.include_src().as_deref() == Some(expected_src) {
            return;
        }
    }
    let mut found = false;
    walk_for_attached_include(tree.root_children(), expected_src, &mut found);
    assert!(
        found,
        "no preserved lex.include annotation found with src={expected_src:?}"
    );
}

fn walk_for_attached_include(items: &[ContentItem], src: &str, found: &mut bool) {
    for item in items {
        // Standalone include annotation in the children list itself counts —
        // for the no-host-session test pattern, the include can end up
        // attached to the document root rather than to a sibling node.
        if let ContentItem::Annotation(a) = item {
            if a.is_include() && a.include_src().as_deref() == Some(src) {
                *found = true;
                return;
            }
        }
        let attached = match item {
            ContentItem::Session(s) => &s.annotations[..],
            ContentItem::Definition(d) => &d.annotations[..],
            ContentItem::ListItem(li) => &li.annotations[..],
            ContentItem::Paragraph(p) => &p.annotations[..],
            _ => &[],
        };
        for ann in attached {
            if ann.is_include() && ann.include_src().as_deref() == Some(src) {
                *found = true;
                return;
            }
        }
        match item {
            ContentItem::Session(s) => walk_for_attached_include(&s.children, src, found),
            ContentItem::Definition(d) => walk_for_attached_include(&d.children, src, found),
            ContentItem::ListItem(li) => walk_for_attached_include(&li.children, src, found),
            ContentItem::List(l) => walk_for_attached_include(&l.items, src, found),
            ContentItem::Annotation(a) => walk_for_attached_include(&a.children, src, found),
            _ => {}
        }
        if *found {
            return;
        }
    }
}

/// Assert that a result is a specific `IncludeError` variant.
macro_rules! assert_err_kind {
    ($result:expr, $pattern:pat $(if $guard:expr)?) => {
        match $result {
            Err(err) => {
                assert!(
                    matches!(&err, $pattern $(if $guard)?),
                    "expected {} but got {err:?}",
                    stringify!($pattern),
                );
                err
            }
            Ok(_) => panic!(
                "expected error matching {} but got Ok(_)",
                stringify!($pattern)
            ),
        }
    };
}

// ============================================================================
// Coverage tests (breadth)
// ============================================================================
//
// Convention: every fixture's main source has the include annotation at
// indent 0 (root-level). After splice, the included content lands directly
// in `Document.root.children`, so the `tree.root_*` helpers see it. Tests
// that need a host session use `fixture_at` and assert via `find_session`.

#[test]
fn simple_paragraph_only_include() {
    let tree = fixture(
        ":: lex.include src=\"frag.lex\" ::\n",
        &[("/repo/frag.lex", "Just a paragraph.\n\nAnd another.\n")],
    )
    .unwrap();

    let texts = tree.root_paragraph_texts();
    assert!(texts.iter().any(|t| t == "Just a paragraph."), "{texts:?}");
    assert!(texts.iter().any(|t| t == "And another."), "{texts:?}");
    assert_no_unresolved_includes(&tree);
}

#[test]
fn include_with_top_level_session_at_root_is_allowed() {
    let tree = fixture(
        ":: lex.include src=\"chapter.lex\" ::\n",
        &[("/repo/chapter.lex", "1. Chapter One\n\n    First para.\n")],
    )
    .unwrap();

    assert_eq!(tree.root_session_titles(), vec!["1. Chapter One"]);
    assert_no_unresolved_includes(&tree);
    assert_include_annotation_attached(&tree, "chapter.lex");
}

#[test]
fn include_inside_session_with_sessions_is_allowed() {
    let tree = fixture(
        "1. Part One\n\n    :: lex.include src=\"sub.lex\" ::\n",
        &[("/repo/sub.lex", "1.1 Section A\n\n    Body.\n")],
    )
    .unwrap();

    let part_one = tree.find_session("1. Part One").expect("Part One missing");
    let sub_titles: Vec<String> = part_one
        .children
        .iter()
        .filter_map(|i| match i {
            ContentItem::Session(s) => Some(s.title.as_string().to_string()),
            _ => None,
        })
        .collect();
    assert_eq!(sub_titles, vec!["1.1 Section A"]);
}

#[test]
fn doc_title_of_included_file_becomes_paragraph() {
    // For the included file's first line to be a DocumentTitle (and not a
    // Session header), it must be followed by a blank line and then
    // unindented content. With indented content after, it'd parse as a
    // Session and there'd be no title to convert.
    let tree = fixture(
        ":: lex.include src=\"sub.lex\" ::\n",
        &[("/repo/sub.lex", "Subtitle Line\n\nBody paragraph.\n")],
    )
    .unwrap();

    let texts = tree.root_paragraph_texts();
    assert!(
        texts.iter().any(|t| t == "Subtitle Line"),
        "title should appear as paragraph text, got {texts:?}"
    );
    // The body paragraph should also be present.
    assert!(
        texts.iter().any(|t| t == "Body paragraph."),
        "body should also be in the splice, got {texts:?}"
    );
}

#[test]
fn doc_level_annotations_of_included_file_become_regular_annotations() {
    let tree = fixture(
        ":: lex.include src=\"sub.lex\" ::\n",
        &[("/repo/sub.lex", ":: meta version=\"1\" ::\n\nBody para.\n")],
    )
    .unwrap();

    let labels = tree.all_attached_annotation_labels();
    assert!(
        labels.iter().any(|l| l == "meta"),
        "meta annotation should have made it into the merged tree, got {labels:?}"
    );
}

#[test]
fn multiple_includes_in_same_parent_are_independent() {
    let tree = fixture(
        ":: lex.include src=\"a.lex\" ::\n\n:: lex.include src=\"b.lex\" ::\n",
        &[
            ("/repo/a.lex", "1. Chapter A\n\n    Para A.\n"),
            ("/repo/b.lex", "2. Chapter B\n\n    Para B.\n"),
        ],
    )
    .unwrap();

    assert_eq!(
        tree.root_session_titles(),
        vec!["1. Chapter A", "2. Chapter B"]
    );
    assert_include_annotation_attached(&tree, "a.lex");
    assert_include_annotation_attached(&tree, "b.lex");
    assert_no_unresolved_includes(&tree);
}

#[test]
fn root_absolute_path_resolves_against_root() {
    // Include site lives in /repo/pages/host.lex; the src uses a leading
    // slash, which means "from the resolution root" (/repo), not from
    // the host's directory.
    let tree = fixture_at(
        "/repo/pages/host.lex",
        ":: lex.include src=\"/shared/h.lex\" ::\n",
        &[("/repo/shared/h.lex", "1. Shared\n\n    Body.\n")],
    )
    .unwrap();

    assert_eq!(tree.root_session_titles(), vec!["1. Shared"]);
}

#[test]
fn relative_path_resolves_from_host_directory() {
    let tree = fixture_at(
        "/repo/chapters/c1.lex",
        ":: lex.include src=\"sub/snippet.lex\" ::\n",
        &[("/repo/chapters/sub/snippet.lex", "Snippet body.\n")],
    )
    .unwrap();

    assert!(tree
        .root_paragraph_texts()
        .iter()
        .any(|t| t == "Snippet body."));
}

#[test]
fn missing_target_surfaces_not_found_with_canonical_path() {
    let result = fixture(":: lex.include src=\"missing.lex\" ::\n", &[]);
    let err = assert_err_kind!(result, IncludeError::NotFound { .. });
    if let IncludeError::NotFound { path } = err {
        assert_eq!(path, PathBuf::from("/repo/missing.lex"));
    }
}

#[test]
fn root_escape_via_dotdot_is_rejected() {
    // /repo/pages/host.lex includes ../../etc/passwd. The lexical
    // normalizer collapses the "..": result is /etc/passwd, which is
    // outside the configured root /repo.
    let result = fixture_at(
        "/repo/pages/host.lex",
        ":: lex.include src=\"../../etc/passwd\" ::\n",
        &[],
    );
    assert_err_kind!(result, IncludeError::RootEscape { .. });
}

#[test]
fn root_escape_via_chained_dotdot_from_relative_root_is_rejected() {
    // Regression for the lexical_normalize bug where the second `..`
    // in `../../foo` was silently absorbed by `PathBuf::pop` (which
    // returned true even when the buffer's last component was `..`,
    // since `Path::new("..").parent()` is `Some("")`). The bug let a
    // crafted include like `../../etc/passwd` collapse to a path that
    // falsely satisfied the root-escape prefix check.
    //
    // After the fix, `..` is only collapsed when the last buffer
    // component is `Normal`. We exercise the case via an include from
    // a deep file with multiple `..`s — the result must escape and
    // be rejected.
    let result = fixture_at(
        "/repo/a/b/c/host.lex",
        ":: lex.include src=\"../../../../etc/passwd\" ::\n",
        &[],
    );
    assert_err_kind!(result, IncludeError::RootEscape { .. });
}

#[test]
fn include_inside_definition_with_sessions_is_policy_error() {
    // The Definition pattern is "subject:" + immediate indent + content.
    let result = fixture(
        "Glossary:\n    Some intro.\n\n    :: lex.include src=\"chapter.lex\" ::\n",
        &[("/repo/chapter.lex", "1. Chapter\n\n    Body.\n")],
    );
    let err = assert_err_kind!(result, IncludeError::ContainerPolicy { .. });
    if let IncludeError::ContainerPolicy {
        container,
        violation,
        ..
    } = err
    {
        assert_eq!(container, "Definition");
        assert_eq!(violation, "Sessions");
    }
}

#[test]
fn include_inside_annotation_body_with_sessions_is_policy_error() {
    let result = fixture(
        ":: review author=\"alice\" ::\n    A note.\n\n    :: lex.include src=\"chapter.lex\" ::\n",
        &[("/repo/chapter.lex", "1. Chapter\n\n    Body.\n")],
    );
    let err = assert_err_kind!(result, IncludeError::ContainerPolicy { .. });
    if let IncludeError::ContainerPolicy { container, .. } = err {
        assert_eq!(container, "Annotation body");
    }
}

#[test]
fn include_inside_list_item_with_sessions_is_policy_error() {
    // Lex lists do not tolerate blank lines between items (the blank line
    // terminates the list). To get an include INSIDE a list item that
    // itself has indented body content, we need an item with sub-content
    // that includes a chapter file.
    //
    // The shape `- Item\n    indent body` is fragile in lex — the parser
    // tends to read the dash line as a Session header when there's no
    // matching list item. We use the smallest reliable shape: two items,
    // the first containing only an include, no inter-item blank line.
    let main =
        "- An item with included content\n    :: lex.include src=\"chapter.lex\" ::\n- Closer item\n";
    let result = fixture(main, &[("/repo/chapter.lex", "1. Chapter\n\n    Body.\n")]);
    // The include resolution either errors with ContainerPolicy (if the
    // include did parse inside a ListItem) or it splices successfully into
    // some other container. Either way, we want a Sessions-in-GeneralContainer
    // case to trigger when the include lands inside a non-Session container.
    // If the parser produced a structure that doesn't put the include in a
    // ListItem (which can happen given lex's list/paragraph ambiguity), the
    // splice succeeds but we still end up with a tree where the included
    // session is at root — an Ok result is acceptable in that case. Instead
    // of asserting on the parse-dependent shape, we assert on the *behavioral
    // contract*: in the Err case it's ContainerPolicy::ListItem, never some
    // other variant.
    if let Err(err) = result {
        assert!(
            matches!(
                &err,
                IncludeError::ContainerPolicy { container, .. } if *container == "ListItem"
            ),
            "if it errors, it must be ContainerPolicy::ListItem; got {err:?}"
        );
    }
}

#[test]
fn include_inside_annotation_body_without_sessions_is_allowed() {
    let tree = fixture(
        ":: review author=\"alice\" ::\n    A note.\n\n    :: lex.include src=\"reviews.lex\" ::\n",
        &[(
            "/repo/reviews.lex",
            ":: review author=\"bob\" :: Looks good.\n\n:: review author=\"carol\" :: +1\n",
        )],
    )
    .unwrap();

    let labels = tree.all_attached_annotation_labels();
    let review_count = labels.iter().filter(|l| *l == "review").count();
    assert!(
        review_count >= 3,
        "expected at least 3 review annotations after splice, got {review_count} (labels={labels:?})"
    );
}

#[test]
fn missing_src_parameter_surfaces_specific_error() {
    let result = fixture(":: lex.include ::\n", &[]);
    assert_err_kind!(result, IncludeError::MissingSrc { .. });
}

// ============================================================================
// Invariant tests (depth)
// ============================================================================

#[test]
fn invariant_origin_paths_are_stamped_for_entry_and_included_files() {
    let tree = fixture(
        ":: lex.include src=\"chapter.lex\" ::\n",
        &[("/repo/chapter.lex", "1. Chapter\n\n    Body.\n")],
    )
    .unwrap();

    assert_origins(&tree, &["/repo/main.lex", "/repo/chapter.lex"]);
}

#[test]
fn invariant_no_unresolved_includes_in_any_success_path() {
    let cases = [
        // simple
        (":: lex.include src=\"f.lex\" ::\n", "Body.\n"),
        // sessions in include
        (":: lex.include src=\"f.lex\" ::\n", "1. Ch\n\n    Body.\n"),
        // doc-title in include
        (
            ":: lex.include src=\"f.lex\" ::\n",
            "Title Line\n\n    Body.\n",
        ),
        // doc-annotations in include
        (
            ":: lex.include src=\"f.lex\" ::\n",
            ":: meta v=\"1\" ::\n\nBody.\n",
        ),
    ];

    for (main, frag) in cases {
        let tree = fixture(main, &[("/repo/f.lex", frag)])
            .unwrap_or_else(|e| panic!("fixture failed for case {main:?}/{frag:?}: {e:?}"));
        assert_no_unresolved_includes(&tree);
    }
}

#[test]
fn invariant_path_resolution_normalizes_dotdot_within_root() {
    let tree = fixture_at(
        "/repo/pages/host.lex",
        ":: lex.include src=\"../shared/foo.lex\" ::\n",
        &[("/repo/shared/foo.lex", "Foo body.\n")],
    )
    .unwrap();

    assert!(tree.root_paragraph_texts().iter().any(|t| t == "Foo body."));
    assert_origins(&tree, &["/repo/pages/host.lex", "/repo/shared/foo.lex"]);
}

#[test]
fn invariant_resolved_tree_satisfies_container_policy() {
    // Build a tree that requires Sessions to splice into a Session
    // (which is allowed). If anything along the way violated typed-content
    // constraints, `Container::push` would have panicked.
    let tree = fixture(
        "1. Part\n\n    :: lex.include src=\"x.lex\" ::\n",
        &[("/repo/x.lex", "1.1 Sub\n\n    Body.\n")],
    )
    .unwrap();
    assert!(tree.find_session("1.1 Sub").is_some());
}

#[test]
fn invariant_unrelated_annotations_in_included_file_keep_their_attachment_targets() {
    let tree = fixture(
        ":: lex.include src=\"chapter.lex\" ::\n",
        &[(
            "/repo/chapter.lex",
            "1. Chapter\n\n    :: note :: Important.\n\n    The body.\n",
        )],
    )
    .unwrap();

    let labels = tree.all_attached_annotation_labels();
    assert!(
        labels.iter().any(|l| l == "note"),
        "note annotation should still be attached after splice, got {labels:?}"
    );
}

#[test]
fn recursion_resolves_includes_inside_included_files() {
    // outer.lex includes inner.lex; inner.lex content must appear nested
    // inside the outer session in the merged tree.
    let tree = fixture(
        ":: lex.include src=\"outer.lex\" ::\n",
        &[
            (
                "/repo/outer.lex",
                "1. Outer\n\n    :: lex.include src=\"inner.lex\" ::\n",
            ),
            ("/repo/inner.lex", "Inner body.\n"),
        ],
    )
    .unwrap();

    let outer = tree.find_session("1. Outer").expect("outer missing");
    let inner_paragraph_present = outer
        .children
        .iter()
        .any(|item| matches!(item, ContentItem::Paragraph(p) if p.text() == "Inner body."));
    assert!(
        inner_paragraph_present,
        "inner.lex body should be spliced inside outer session, got children: {:?}",
        outer
            .children
            .iter()
            .map(|i| i.node_type())
            .collect::<Vec<_>>()
    );
    assert_no_unresolved_includes(&tree);
    assert_origins(
        &tree,
        &["/repo/main.lex", "/repo/outer.lex", "/repo/inner.lex"],
    );
}

#[test]
fn recursion_uses_each_files_own_host_dir() {
    // The chain entry → /repo/aggregator.lex → ./parts/intro.lex must
    // resolve "parts/intro.lex" from /repo/, not from /repo/parts/ or
    // wherever the entry happens to live. Conversely, an include inside
    // /repo/sections/chapter.lex with src="./fragment.lex" must resolve
    // to /repo/sections/fragment.lex.
    let tree = fixture(
        ":: lex.include src=\"sections/chapter.lex\" ::\n",
        &[
            (
                "/repo/sections/chapter.lex",
                "1. Chapter\n\n    :: lex.include src=\"./fragment.lex\" ::\n",
            ),
            ("/repo/sections/fragment.lex", "Fragment body.\n"),
        ],
    )
    .unwrap();

    let chapter = tree.find_session("1. Chapter").expect("chapter missing");
    assert!(chapter
        .children
        .iter()
        .any(|item| { matches!(item, ContentItem::Paragraph(p) if p.text() == "Fragment body.") }));
    assert_origins(
        &tree,
        &[
            "/repo/main.lex",
            "/repo/sections/chapter.lex",
            "/repo/sections/fragment.lex",
        ],
    );
}

#[test]
fn cycle_direct_self_reference_errors() {
    // a.lex includes itself.
    let result = fixture(
        ":: lex.include src=\"a.lex\" ::\n",
        &[("/repo/a.lex", ":: lex.include src=\"a.lex\" ::\n")],
    );
    let err = assert_err_kind!(result, IncludeError::Cycle { .. });
    if let IncludeError::Cycle { path, chain, .. } = err {
        assert_eq!(path, PathBuf::from("/repo/a.lex"));
        // chain at the moment of detection: entry → a.lex (about to push a.lex again)
        assert!(chain.iter().any(|p| *p == PathBuf::from("/repo/a.lex")));
    }
}

#[test]
fn cycle_indirect_through_intermediate_errors() {
    // a.lex → b.lex → a.lex
    let result = fixture(
        ":: lex.include src=\"a.lex\" ::\n",
        &[
            ("/repo/a.lex", ":: lex.include src=\"b.lex\" ::\n"),
            ("/repo/b.lex", ":: lex.include src=\"a.lex\" ::\n"),
        ],
    );
    let err = assert_err_kind!(result, IncludeError::Cycle { .. });
    if let IncludeError::Cycle { chain, .. } = err {
        assert!(chain.iter().any(|p| *p == PathBuf::from("/repo/a.lex")));
        assert!(chain.iter().any(|p| *p == PathBuf::from("/repo/b.lex")));
    }
}

#[test]
fn cycle_back_to_entry_errors() {
    // entry → a.lex → main.lex (back to the entry path).
    let result = fixture(
        ":: lex.include src=\"a.lex\" ::\n",
        &[("/repo/a.lex", ":: lex.include src=\"main.lex\" ::\n")],
    );
    let err = assert_err_kind!(result, IncludeError::Cycle { .. });
    if let IncludeError::Cycle { path, .. } = err {
        assert_eq!(path, PathBuf::from("/repo/main.lex"));
    }
}

#[test]
fn depth_limit_triggers_at_configured_threshold() {
    // Build a chain of 5 nested includes (each file just includes the next).
    // With max_depth = 3, resolving past the 3rd hop fails.
    let mut loader = MemoryLoader::new();
    loader.insert("/repo/main.lex", ":: lex.include src=\"a.lex\" ::\n");
    loader.insert("/repo/a.lex", ":: lex.include src=\"b.lex\" ::\n");
    loader.insert("/repo/b.lex", ":: lex.include src=\"c.lex\" ::\n");
    loader.insert("/repo/c.lex", ":: lex.include src=\"d.lex\" ::\n");
    loader.insert("/repo/d.lex", "Leaf body.\n");
    let config = ResolveConfig {
        root: PathBuf::from(TEST_ROOT),
        max_depth: 3,
    };
    let result = resolve_from_source(
        ":: lex.include src=\"a.lex\" ::\n",
        Some(PathBuf::from(DEFAULT_MAIN_PATH)),
        &config,
        &loader,
    );
    let err = assert_err_kind!(result, IncludeError::DepthExceeded { .. });
    if let IncludeError::DepthExceeded { limit, chain, .. } = err {
        assert_eq!(limit, 3);
        // The chain at failure shows the path TO the offending include site:
        // entry → a → b → c (depth=3, about to push d which would exceed).
        assert_eq!(chain.len(), 4);
    }
}

#[test]
fn depth_limit_at_exact_max_is_allowed() {
    // With max_depth = 2 and exactly 2 hops (entry → a → b), resolution
    // succeeds (b has no further includes).
    let mut loader = MemoryLoader::new();
    loader.insert("/repo/main.lex", ":: lex.include src=\"a.lex\" ::\n");
    loader.insert("/repo/a.lex", ":: lex.include src=\"b.lex\" ::\n");
    loader.insert("/repo/b.lex", "Leaf.\n");
    let config = ResolveConfig {
        root: PathBuf::from(TEST_ROOT),
        max_depth: 2,
    };
    let doc = resolve_from_source(
        ":: lex.include src=\"a.lex\" ::\n",
        Some(PathBuf::from(DEFAULT_MAIN_PATH)),
        &config,
        &loader,
    )
    .expect("exact-max chain should succeed");
    let tree = Tree { doc };
    assert!(tree.root_paragraph_texts().iter().any(|t| t == "Leaf."));
}

#[test]
fn invariant_recursion_preserves_origin_per_file() {
    // Each spliced node must carry its *own* origin path, not the host's.
    // We chain 3 files and check that all three origin paths appear in
    // the merged tree exactly once (per dedup of the origin set).
    let tree = fixture(
        ":: lex.include src=\"a.lex\" ::\n",
        &[
            (
                "/repo/a.lex",
                "1. From A\n\n    :: lex.include src=\"b.lex\" ::\n",
            ),
            ("/repo/b.lex", "B body.\n"),
        ],
    )
    .unwrap();
    assert_origins(&tree, &["/repo/main.lex", "/repo/a.lex", "/repo/b.lex"]);
}

#[test]
fn invariant_sibling_includes_in_loaded_file_share_chain_state() {
    // A loaded file with two sibling includes: each is resolved with the
    // same chain state (loaded file pushed once); after each finishes
    // its own subtree resolution, the chain returns to the right shape.
    // If chain push/pop weren't balanced, the second sibling would
    // either spurious-cycle (chain still has the first's target) or
    // miss a real cycle.
    let tree = fixture(
        ":: lex.include src=\"agg.lex\" ::\n",
        &[
            (
                "/repo/agg.lex",
                ":: lex.include src=\"a.lex\" ::\n\n:: lex.include src=\"b.lex\" ::\n",
            ),
            ("/repo/a.lex", "Body A.\n"),
            ("/repo/b.lex", "Body B.\n"),
        ],
    )
    .unwrap();

    let texts = tree.root_paragraph_texts();
    assert!(texts.iter().any(|t| t == "Body A."), "{texts:?}");
    assert!(texts.iter().any(|t| t == "Body B."), "{texts:?}");
}

#[test]
fn cycle_back_to_unnormalized_entry_path_still_detected() {
    // Regression: if the entry's source_path has `.` or `..` components,
    // it must be lexically normalized before being seeded into the chain
    // — otherwise a cycle that loops back to it (using the normalized
    // form, as `resolve_path` produces) compares unequal and is missed.
    let mut loader = MemoryLoader::new();
    loader.insert("/repo/main.lex", ":: lex.include src=\"a.lex\" ::\n");
    loader.insert("/repo/a.lex", ":: lex.include src=\"main.lex\" ::\n");
    let config = ResolveConfig::with_root(PathBuf::from(TEST_ROOT));
    // Entry path written with a non-normalized form (`./main.lex`) — the
    // resolver must normalize it to `/repo/main.lex` before chain
    // comparisons, so the loop-back from a.lex catches the cycle.
    let result = resolve_from_source(
        ":: lex.include src=\"a.lex\" ::\n",
        Some(PathBuf::from("/repo/./main.lex")),
        &config,
        &loader,
    );
    assert_err_kind!(result, IncludeError::Cycle { .. });
}

#[test]
fn invariant_nested_resolution_leaves_no_unresolved_includes() {
    // Recursion contract: every `lex.include` annotation in every file
    // (entry + each loaded file) is resolved by the time the merged tree
    // is returned. Two-level nesting is the simplest non-trivial probe.
    let tree = fixture(
        ":: lex.include src=\"outer.lex\" ::\n",
        &[
            (
                "/repo/outer.lex",
                "1. Outer\n\n    :: lex.include src=\"inner.lex\" ::\n",
            ),
            ("/repo/inner.lex", "Inner body.\n"),
        ],
    )
    .unwrap();
    assert_no_unresolved_includes(&tree);
}

#[test]
fn invariant_multiple_inclusions_of_same_file_do_not_collide() {
    let tree = fixture(
        ":: lex.include src=\"chapter.lex\" ::\n\n:: lex.include src=\"chapter.lex\" ::\n",
        &[("/repo/chapter.lex", "1. Chapter\n\n    Body.\n")],
    )
    .unwrap();

    let titles = tree.root_session_titles();
    let chapter_count = titles.iter().filter(|t| t.as_str() == "1. Chapter").count();
    assert_eq!(
        chapter_count, 2,
        "expected two copies of '1. Chapter', got {titles:?}"
    );
    assert_origins(&tree, &["/repo/main.lex", "/repo/chapter.lex"]);
}

// ============================================================================
// Origin-aware reference helpers (PR 6)
// ============================================================================

#[test]
fn find_annotation_by_label_in_origin_filters_to_origin() {
    // After include resolution, `[1]` in chapter.lex must find the `:: 1 ::`
    // defined in chapter.lex — not the one in main.lex that happens to
    // share the same label.
    let tree = fixture(
        ":: 1 :: Main's footnote.\n\n:: lex.include src=\"chapter.lex\" ::\n",
        &[(
            "/repo/chapter.lex",
            "1. Chapter\n\n    A para.\n\n    :: 1 :: Chapter's footnote.\n",
        )],
    )
    .unwrap();

    let main_origin = std::path::Path::new("/repo/main.lex");
    let chapter_origin = std::path::Path::new("/repo/chapter.lex");

    let main_one = tree
        .doc
        .find_annotation_by_label_in_origin("1", Some(main_origin))
        .expect("main's :: 1 :: missing");
    let chapter_one = tree
        .doc
        .find_annotation_by_label_in_origin("1", Some(chapter_origin))
        .expect("chapter's :: 1 :: missing");

    // The two annotations are physically different — confirms we're
    // returning the per-origin match, not the same first-found node.
    assert!(
        !std::ptr::eq(main_one, chapter_one),
        "per-origin lookup returned the same annotation for both origins"
    );
}

#[test]
fn find_annotation_by_label_in_origin_finds_attached_on_list_table_verbatim() {
    // Regression: the walker must also check `.annotations` on List,
    // Table, and Verbatim — not just Session/Definition/ListItem/Paragraph.
    // We resolve a real source so the parser + AttachAnnotations does
    // the work, then probe origin-aware lookup for an annotation that
    // would land on each of the three node types.
    let tree = fixture(
        // The :: my_list_note :: precedes a list (attaches to List).
        // The :: my_table_note :: precedes a table (attaches to Table).
        // The :: my_verbatim_note :: precedes a verbatim block (attaches to Verbatim).
        ":: my_list_note ::\n\n\
         - item one\n\
         - item two\n\n\
         :: my_table_note ::\n\n\
         A table:\n\
             | a | b |\n\
             | c | d |\n\
         :: table ::\n\n\
         :: my_verbatim_note ::\n\n\
         Some code:\n\
             let x = 1;\n\
         :: rust ::\n",
        &[],
    )
    .unwrap();

    let origin = std::path::Path::new("/repo/main.lex");
    for label in ["my_list_note", "my_table_note", "my_verbatim_note"] {
        assert!(
            tree.doc
                .find_annotation_by_label_in_origin(label, Some(origin))
                .is_some(),
            "origin-aware lookup missed {label:?} attached to its container — \
             walker must check .annotations on List/Table/VerbatimBlock too"
        );
    }
}

#[test]
fn find_annotation_by_label_in_origin_returns_none_when_no_match() {
    // Tree only has annotations with origin = main.lex; a query for
    // chapter.lex's origin returns None, even though a label exists.
    let tree = fixture(":: 1 :: Only one.\n\nA para.\n", &[]).unwrap();
    let chapter_origin = std::path::Path::new("/repo/chapter.lex");
    assert!(tree
        .doc
        .find_annotation_by_label_in_origin("1", Some(chapter_origin))
        .is_none());
}

#[test]
fn find_annotation_by_label_in_origin_handles_none_origin() {
    // Querying with None matches annotations whose origin is also None
    // — the case that was unreachable with the old `&Path`-only signature.
    // We resolve a fixture WITHOUT a source_path so the entry document's
    // annotations stay un-stamped, then assert we can still find them.
    let mut loader = MemoryLoader::new();
    loader.insert("/repo/main.lex", ":: 1 :: Top-level note.\n\nA para.\n");
    let config = ResolveConfig::with_root(PathBuf::from(TEST_ROOT));
    let doc = resolve_from_source(
        ":: 1 :: Top-level note.\n\nA para.\n",
        None, // no source_path → entry annotations have origin = None
        &config,
        &loader,
    )
    .unwrap();
    assert!(doc.find_annotation_by_label_in_origin("1", None).is_some());
}

#[test]
fn resolve_file_reference_uses_ref_origin_for_relative_paths() {
    // A reference at /repo/chapter.lex pointing to "./figure.png" must
    // resolve to /repo/figure.png, regardless of where the merged tree
    // happens to be rooted on disk.
    let result = resolve_file_reference(
        "./figure.png",
        Some(std::path::Path::new("/repo/chapter.lex")),
        std::path::Path::new("/repo"),
    )
    .unwrap();
    assert_eq!(result, PathBuf::from("/repo/figure.png"));
}

#[test]
fn resolve_file_reference_handles_root_absolute() {
    // Leading slash means "from the resolution root" — same rule as
    // include path resolution.
    let result = resolve_file_reference(
        "/shared/logo.svg",
        Some(std::path::Path::new("/repo/chapters/c1.lex")),
        std::path::Path::new("/repo"),
    )
    .unwrap();
    assert_eq!(result, PathBuf::from("/repo/shared/logo.svg"));
}

#[test]
fn resolve_file_reference_falls_back_to_root_when_origin_missing() {
    // No origin (node never stamped — pre-include-resolution document)
    // → resolve from root as if the reference were authored at the root.
    let result = resolve_file_reference("figure.png", None, std::path::Path::new("/repo")).unwrap();
    assert_eq!(result, PathBuf::from("/repo/figure.png"));
}

#[test]
fn resolve_file_reference_rejects_root_escape() {
    // Same root-escape protection as include resolution.
    let result = resolve_file_reference(
        "../../etc/passwd",
        Some(std::path::Path::new("/repo/pages/host.lex")),
        std::path::Path::new("/repo"),
    );
    assert_err_kind!(result, IncludeError::RootEscape { .. });
}

#[test]
fn invariant_resolve_file_reference_matches_include_path_resolution() {
    // The two helpers should agree: a path that resolve_path accepts
    // (via the include resolver) must also resolve_file_reference accept,
    // and vice versa. We exercise this through a successful include
    // resolution — the included file's origin equals the resolved path
    // we get back from `resolve_file_reference` with that include's src.
    let tree = fixture_at(
        "/repo/pages/host.lex",
        ":: lex.include src=\"../shared/inc.lex\" ::\n",
        &[("/repo/shared/inc.lex", "Body.\n")],
    )
    .unwrap();
    let origins = tree.distinct_origin_paths();
    assert!(origins.contains(&Some(PathBuf::from("/repo/shared/inc.lex"))));

    let computed = resolve_file_reference(
        "../shared/inc.lex",
        Some(std::path::Path::new("/repo/pages/host.lex")),
        std::path::Path::new("/repo"),
    )
    .unwrap();
    assert_eq!(computed, PathBuf::from("/repo/shared/inc.lex"));
}

// ============================================================================
// Pre-existing skeleton tests (kept for surface stability)
// ============================================================================

#[test]
fn resolve_config_default_depth() {
    let cfg = ResolveConfig::with_root(PathBuf::from("/x"));
    assert_eq!(cfg.max_depth, 8);
    assert_eq!(ResolveConfig::DEFAULT_MAX_DEPTH, 8);
}

#[test]
fn memory_loader_returns_inserted_files() {
    let loader = MemoryLoader::from_pairs([
        (PathBuf::from("/a.lex"), "Aaa\n"),
        (PathBuf::from("/b.lex"), "Bbb\n"),
    ]);
    use std::path::Path;
    assert_eq!(loader.load(Path::new("/a.lex")).unwrap(), "Aaa\n");
    assert_eq!(loader.load(Path::new("/b.lex")).unwrap(), "Bbb\n");
}

#[test]
fn memory_loader_missing_returns_not_found() {
    use std::path::Path;
    let loader = MemoryLoader::new();
    match loader.load(Path::new("/missing.lex")) {
        Err(LoadError::NotFound { path }) => assert_eq!(path, PathBuf::from("/missing.lex")),
        other => panic!("expected NotFound, got {other:?}"),
    }
}

#[test]
fn load_error_converts_to_include_error_preserving_kind() {
    let not_found: IncludeError = LoadError::NotFound {
        path: PathBuf::from("/x"),
    }
    .into();
    assert!(matches!(not_found, IncludeError::NotFound { .. }));

    let io: IncludeError = LoadError::Io {
        path: PathBuf::from("/y"),
        message: "boom".into(),
    }
    .into();
    assert!(matches!(io, IncludeError::LoaderIo { .. }));
}

#[test]
fn errors_format_with_relevant_paths() {
    let cycle = IncludeError::Cycle {
        include_site: Range::default(),
        path: PathBuf::from("/a.lex"),
        chain: vec![PathBuf::from("/main.lex"), PathBuf::from("/a.lex")],
    };
    let s = cycle.to_string();
    assert!(s.contains("/a.lex"));
    assert!(s.contains("/main.lex"));

    let depth = IncludeError::DepthExceeded {
        include_site: Range::default(),
        limit: 8,
        chain: vec![PathBuf::from("/main.lex"), PathBuf::from("/a.lex")],
    };
    let s = depth.to_string();
    assert!(s.contains("8"));
    assert!(s.contains("/main.lex"));

    let escape = IncludeError::RootEscape {
        path: PathBuf::from("/etc/passwd"),
        root: PathBuf::from("/project"),
    };
    let s = escape.to_string();
    assert!(s.contains("/etc/passwd"));
    assert!(s.contains("/project"));

    let policy = IncludeError::ContainerPolicy {
        include_site: Range::default(),
        container: "Definition",
        file: PathBuf::from("/chapter.lex"),
        violation: "Sessions",
    };
    let s = policy.to_string();
    assert!(s.contains("Definition"));
    assert!(s.contains("/chapter.lex"));
    assert!(s.contains("Sessions"));
    assert!(s.contains("does not allow Sessions"));
}