quarb-compose 0.33.0

Adapter composition: parseable leaf content grafts an inner arbor
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
//! Adapter composition: descend *through* a leaf into its content.
//!
//! A filesystem's `.json` file, an archive's `config.xml` entry, a
//! message's HTML part — trees of files are full of leaves whose
//! *content* is itself a tree in another notation. Composition
//! grafts that inner tree onto the outer one: wrap any adapter in
//! a [`ComposeAdapter`] and a leaf whose name or content says
//! "parse me" gains the parsed arbor as its children:
//!
//! ```text
//! /data/store.json/books/*[/price:: < 12]/title::
//!       └ outer (fs) ┘└──── inner (json) ────┘
//! ```
//!
//! The graft happens on first touch, lazily: a leaf is only read
//! and parsed when navigation actually enters it. Detection is by
//! extension (`.json`, `.xml`, `.html`/`.htm`/`.xhtml`/`.svg`,
//! `.csv`/`.tsv`), else by sniffing the content's first
//! character; a parse failure simply leaves the leaf a leaf.
//! Archive leaves (`.zip`, `.tar`, `.tar.gz`) are binary, so they
//! graft by *path* rather than content — available when the outer
//! substrate has real paths (see
//! [`ComposeAdapter::with_source_paths`]) — and the grafted
//! archive composes in turn, so one path runs filesystem → tar →
//! JSON without a seam. The
//! inner root is *identified with* the outer leaf node — the leaf
//! itself answers the inner root's children — so there is no
//! phantom node between the file and its content.
//!
//! Locators show the boundary with a bang, jar-URL style:
//! `store.json!/books/1`.

use quarb::source::SourceDecoding;
use quarb::{AstAdapter, NodeId, Value};
use std::cell::RefCell;
use std::collections::HashMap;
use std::path::PathBuf;

/// A parsed inner arbor.
enum Inner {
    Json(quarb_json::JsonAdapter),
    Xml(quarb_xml::XmlAdapter),
    Html(quarb_html::HtmlAdapter),
    Text(quarb_text::TextModel),
    Csv(quarb_csv::CsvAdapter),
    #[cfg(feature = "source")]
    Syntax(quarb_tree_sitter::TreeSitterAdapter),
    #[cfg(feature = "source")]
    Code(quarb_code::CodeModel),
    /// A grafted archive, itself composed so its own parseable
    /// entries graft in turn.
    Archive(Box<ComposeAdapter<quarb_archive::ArchiveAdapter>>),
}

impl Inner {
    fn adapter(&self) -> &dyn AstAdapter {
        match self {
            Inner::Json(a) => a,
            Inner::Xml(a) => a,
            Inner::Html(a) => a,
            Inner::Text(a) => a,
            Inner::Csv(a) => a,
            #[cfg(feature = "source")]
            Inner::Syntax(a) => a,
            #[cfg(feature = "source")]
            Inner::Code(a) => a,
            Inner::Archive(a) => &**a,
        }
    }

    fn locator(&self, node: NodeId) -> String {
        match self {
            Inner::Json(a) => a.pointer(node),
            Inner::Xml(a) => a.locator(node),
            Inner::Html(a) => a.locator(node),
            Inner::Text(a) => a.locator(node),
            Inner::Csv(a) => a.locator(node),
            #[cfg(feature = "source")]
            Inner::Syntax(a) => a.locator(node),
            #[cfg(feature = "source")]
            Inner::Code(a) => a.locator(node),
            Inner::Archive(a) => a.locator(node, |o| a.outer().locator(o)),
        }
    }
}

/// The level source-file leaves graft at: the syntax level (the
/// literal parse — the default) or the code level (identifiers
/// as names). Chosen per mount by the `code:` target prefix, and
/// inherited by nested composes (an archive inside a `code:`
/// mount grafts its source entries at the code level too) — the
/// filesystem-into-declarations namespace has no seam.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SourceGraft {
    #[default]
    Syntax,
    Code,
}

/// The level marked-up documents (`.html`, `.htm`, `.md`) graft
/// at: their DOM by default, or the text level — sections,
/// paragraphs, lists, and what the page declares about itself
/// in its head — when the mount asks for the reader's model
/// (`text:` on an archive or directory).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DocumentGraft {
    #[default]
    Dom,
    Text,
}

/// The declaration reporter a host hands the source boundary: by
/// the source's name, the XML prologue for XML-family names, the
/// HTML prescan for HTML names, both tried (prologue first) for a
/// name that says nothing — a plain text file declares nothing
/// either way.
pub fn declared_encoding(name: &str, bytes: &[u8]) -> Option<String> {
    let ext = name.rsplit('.').next().unwrap_or("").to_ascii_lowercase();
    match ext.as_str() {
        "xml" | "svg" | "xhtml" | "fb2" | "tei" | "rss" | "atom" | "opml" | "xsd" | "xsl" => {
            quarb_xml::declared_encoding(bytes)
        }
        "html" | "htm" => quarb_html::declared_encoding(bytes),
        // RTF's header names its code page (`\ansicpg1251`).
        "rtf" => quarb_text_rtf::declared_encoding(bytes),
        _ => quarb_xml::declared_encoding(bytes).or_else(|| quarb_html::declared_encoding(bytes)),
    }
}

/// The rule a host mount carries: `?encoding=` validated at open,
/// the reporter above.
pub fn source_decoding(
    explicit: Option<&str>,
) -> Result<SourceDecoding, quarb::source::SourceError> {
    SourceDecoding::default()
        .with_declared(declared_encoding)
        .with_option(explicit)
}

/// Read one file at the source boundary under the host rule:
/// `?encoding=`, then a byte-order mark, then what the file
/// declares, then strict UTF-8.
pub fn read_source(
    path: &std::path::Path,
    explicit: Option<&str>,
) -> std::io::Result<Result<quarb::source::Decoded, quarb::source::SourceError>> {
    let bytes = std::fs::read(path)?;
    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
    Ok(source_decoding(explicit).and_then(|d| d.decode(name, &bytes)))
}

/// Names [`quarb_archive::ArchiveAdapter::open`] can take: the
/// zip family, tar, and gzip (`.gz` alone included — the open
/// checks magic bytes, and a failure leaves the leaf a leaf).
fn archive_name(name: &str) -> bool {
    let ext = name.rsplit('.').next().unwrap_or("").to_ascii_lowercase();
    matches!(
        ext.as_str(),
        "zip" | "tar" | "tgz" | "gz" | "7z" | "xz" | "txz" | "bz2" | "tbz2" | "zst" | "tzst"
    )
}

/// Parse `content` by `name`'s extension, else by sniffing.
fn parse_inner(
    name: &str,
    content: &str,
    graft: SourceGraft,
    doc: DocumentGraft,
    csv: quarb_csv::CsvOptions,
) -> Option<Inner> {
    #[cfg(not(feature = "source"))]
    let _ = graft;
    let ext = name.rsplit('.').next().unwrap_or("").to_ascii_lowercase();
    match ext.as_str() {
        "json" => {
            return quarb_json::JsonAdapter::parse(content)
                .ok()
                .map(Inner::Json);
        }
        "jsonl" | "ndjson" => {
            return quarb_json::JsonAdapter::parse_lines(content)
                .ok()
                .map(Inner::Json);
        }
        "xml" | "svg" | "xhtml" => {
            // A FictionBook declared by its namespace grafts at the
            // text level through the koine route when the level
            // asks for it; the DOM otherwise, like any XML.
            #[cfg(feature = "koine")]
            if doc == DocumentGraft::Text
                && quarb_text_koine::detect_xml_kind(content) == Some("fb2")
                && let Ok(m) = quarb_text_koine::parse_xml_as(content, "fb2")
            {
                return Some(Inner::Text(m));
            }
            return quarb_xml::XmlAdapter::parse(content).ok().map(Inner::Xml);
        }
        "fb2" => {
            #[cfg(feature = "koine")]
            if doc == DocumentGraft::Text
                && let Ok(m) = quarb_text_koine::parse_xml_as(content, "fb2")
            {
                return Some(Inner::Text(m));
            }
            return quarb_xml::XmlAdapter::parse(content).ok().map(Inner::Xml);
        }
        "html" | "htm" => {
            return Some(match doc {
                DocumentGraft::Dom => Inner::Html(quarb_html::HtmlAdapter::parse(content)),
                DocumentGraft::Text => Inner::Text(quarb_text_html::parse(content)),
            });
        }
        "yaml" | "yml" => return quarb_yaml::parse(content).ok().map(Inner::Json),
        "toml" => return quarb_toml::parse(content).ok().map(Inner::Json),
        "md" | "markdown" => {
            return Some(match doc {
                DocumentGraft::Dom => Inner::Html(quarb_markdown::parse(content)),
                DocumentGraft::Text => Inner::Text(quarb_text_markdown::parse(content)),
            });
        }
        // Plain text grafts at the text level (blank-line
        // paragraphs); html/md keep their DOM-level graft.
        "txt" => return Some(Inner::Text(quarb_text::TextModel::parse_plain(content))),
        "csv" => {
            return quarb_csv::CsvAdapter::parse_declared(content, b',', csv)
                .ok()
                .map(Inner::Csv);
        }
        "tsv" => {
            return quarb_csv::CsvAdapter::parse_declared(content, b'\t', csv)
                .ok()
                .map(Inner::Csv);
        }
        #[cfg(feature = "source")]
        ext if quarb_tree_sitter::supported(ext) => {
            return match graft {
                SourceGraft::Syntax => quarb_tree_sitter::TreeSitterAdapter::parse(content, ext)
                    .ok()
                    .map(Inner::Syntax),
                SourceGraft::Code => quarb_code::CodeModel::parse(content, ext)
                    .ok()
                    .map(Inner::Code),
            };
        }
        _ => {}
    }
    // Content sniff for extensionless names.
    let t = content.trim_start();
    if t.starts_with('{') || t.starts_with('[') {
        return quarb_json::JsonAdapter::parse(content)
            .ok()
            .map(Inner::Json);
    }
    if t.starts_with("<?xml") {
        return quarb_xml::XmlAdapter::parse(content).ok().map(Inner::Xml);
    }
    None
}

/// One graft: an inner arbor mounted at an outer leaf.
struct Graft {
    outer: NodeId,
    inner: Inner,
}

/// Grafted node ids carry this tag bit; the rest indexes the intern
/// table. The bit sits at the top of the 56-bit id window that
/// `MountAdapter` leaves an inner adapter — it reserves the high byte
/// (bits 56–63) for the mount index — so a grafted id survives being
/// packed into a mount and still round-trips. It must stay below bit
/// 56 for that reason; the top bit (1 << 63) collided with the mount
/// byte. Outer adapters use small sequential indices, far below this
/// bit, so a set bit 55 unambiguously marks a graft.
const GRAFT_BIT: u64 = 1 << 55;

/// Any adapter, with parseable leaf content grafted as subtrees.
/// A host's reader for a document leaf: the path in, its text-level
/// model out, or `None` to leave the leaf to the default grafting.
pub type DocumentReader = std::rc::Rc<dyn Fn(&std::path::Path) -> Option<quarb_text::TextModel>>;

pub struct ComposeAdapter<A: AstAdapter> {
    outer: A,
    grafts: RefCell<Vec<Graft>>,
    /// Outer leaf → its graft index (`None`: probed, not
    /// parseable).
    probed: RefCell<HashMap<NodeId, Option<usize>>>,
    /// (graft, inner id) → interned composite id, and the reverse.
    interned: RefCell<HashMap<(usize, NodeId), NodeId>>,
    reverse: RefCell<Vec<(usize, NodeId)>>,
    /// Maps an outer leaf to a filesystem path, when the outer
    /// substrate has one. Enables archive grafts, which are
    /// binary and open by path rather than parsing from text.
    source_path: Option<fn(&A, NodeId) -> Option<PathBuf>>,
    /// The level source-file leaves graft at.
    source_graft: SourceGraft,
    /// The level marked-up documents graft at.
    document_graft: DocumentGraft,
    /// Maps an outer leaf to the URL its document is served
    /// from, so a text-level graft joins relative references
    /// against it and `-->` can land on a sibling document.
    document_url: Option<fn(&A, NodeId) -> Option<String>>,
    /// URL → outer leaf, built on first `document_by_ref`.
    urls: RefCell<Option<HashMap<String, NodeId>>>,
    /// The host's own reading of a document leaf, by path: when it
    /// answers, its model is the graft (a corpus reading with its
    /// tokens, a format this crate does not parse); when it
    /// declines, the leaf grafts as it otherwise would.
    document_reader: Option<DocumentReader>,
    /// The mount's rule at the source boundary (`?encoding=` and
    /// the declaration reporter): every leaf this layer reads by
    /// path decodes under it, and the layer answers `::::encoding`
    /// / `::::replaced` on the leaf it grafted. A leaf with no path
    /// grafts from the outer adapter's text as before.
    decoding: SourceDecoding,
    /// Per graft: the record of its decoding, when this layer did
    /// it.
    decoded: RefCell<HashMap<usize, (String, usize)>>,
    /// The mount's `?delimiter=` / `?decimal=`, for the delimited
    /// leaves it grafts.
    csv: quarb_csv::CsvOptions,
}

impl<A: AstAdapter> ComposeAdapter<A> {
    pub fn new(outer: A) -> Self {
        ComposeAdapter {
            outer,
            grafts: RefCell::new(Vec::new()),
            probed: RefCell::new(HashMap::new()),
            interned: RefCell::new(HashMap::new()),
            reverse: RefCell::new(Vec::new()),
            source_path: None,
            source_graft: SourceGraft::default(),
            document_graft: DocumentGraft::default(),
            document_url: None,
            urls: RefCell::new(None),
            document_reader: None,
            decoding: SourceDecoding::default(),
            decoded: RefCell::new(HashMap::new()),
            csv: quarb_csv::CsvOptions::default(),
        }
    }

    /// The delimited-text options for this mount (builder-style).
    pub fn with_csv_options(mut self, csv: quarb_csv::CsvOptions) -> Self {
        self.csv = csv;
        self
    }

    /// The source-boundary rule for this mount (builder-style):
    /// the `?encoding=` option and the reporter the host chose.
    /// Reaches grafted archives too.
    pub fn with_decoding(mut self, decoding: SourceDecoding) -> Self {
        self.decoding = decoding;
        self
    }

    /// Hand document leaves to the host's reader first
    /// (builder-style); needs the outer leaves' paths
    /// ([`with_source_paths`](Self::with_source_paths)).
    pub fn with_document_reader(mut self, reader: DocumentReader) -> Self {
        self.document_reader = Some(reader);
        self
    }

    /// Declare where each outer leaf's document is served from
    /// (builder-style): a text-level graft joins its relative
    /// references against that URL, and `-->` from any graft
    /// lands on the leaf holding the referenced document (its
    /// fragment's bearer when named) without a host registration.
    pub fn with_document_urls(mut self, document_url: fn(&A, NodeId) -> Option<String>) -> Self {
        self.document_url = Some(document_url);
        self
    }

    /// The outer leaf serving `url` (fragment-stripped), from the
    /// declared URLs; the whole outer tree is walked once.
    fn leaf_by_url(&self, url: &str) -> Option<NodeId> {
        let f = self.document_url?;
        if self.urls.borrow().is_none() {
            let mut map = HashMap::new();
            let mut stack = vec![self.outer.root()];
            while let Some(n) = stack.pop() {
                let kids = self.outer.children(n);
                if kids.is_empty() {
                    if let Some(u) = f(&self.outer, n) {
                        map.entry(u.split('#').next().unwrap_or(&u).to_string())
                            .or_insert(n);
                    }
                } else {
                    stack.extend(kids);
                }
            }
            *self.urls.borrow_mut() = Some(map);
        }
        self.urls.borrow().as_ref()?.get(url).copied()
    }

    /// Choose the level source-file leaves graft at
    /// (builder-style; the default is the syntax level).
    pub fn with_source_graft(mut self, graft: SourceGraft) -> Self {
        self.source_graft = graft;
        self
    }

    /// Choose the level marked-up documents graft at
    /// (builder-style; the default is the DOM).
    pub fn with_document_graft(mut self, graft: DocumentGraft) -> Self {
        self.document_graft = graft;
        self
    }

    /// Like [`new`](Self::new), with a hook mapping outer leaves
    /// to filesystem paths, so archive leaves (`.zip`,
    /// `.tar[.gz]`) graft too. The grafted archive composes in
    /// turn: its own parseable entries graft, and one path walks
    /// filesystem → archive → document.
    pub fn with_source_paths(outer: A, source_path: fn(&A, NodeId) -> Option<PathBuf>) -> Self {
        ComposeAdapter {
            source_path: Some(source_path),
            ..Self::new(outer)
        }
    }

    /// The wrapped adapter (for outer-specific calls).
    pub fn outer(&self) -> &A {
        &self.outer
    }

    /// A combined locator: `outer_locator(leaf)!inner-path` for
    /// grafted nodes.
    pub fn locator(&self, node: NodeId, outer_locator: impl Fn(NodeId) -> String) -> String {
        match self.split(node) {
            None => outer_locator(node),
            Some((g, inner)) => {
                let grafts = self.grafts.borrow();
                let graft = &grafts[g];
                format!(
                    "{}!{}",
                    outer_locator(graft.outer),
                    graft.inner.locator(inner)
                )
            }
        }
    }

    /// Decode a composite id.
    /// The graft's fill for a node inside a grafted document: the
    /// outer leaf's provenance (the file's path and mtime) with the
    /// mtime re-labelled as the source rung, and the node's path
    /// inside the document.
    fn graft_fill(&self, outer_leaf: NodeId, inner_path: String) -> quarb::Provenance {
        let mut fill = self.outer.provenance(outer_leaf).as_source_rung();
        fill.path = Some(inner_path);
        fill
    }

    fn split(&self, node: NodeId) -> Option<(usize, NodeId)> {
        if node.0 & GRAFT_BIT == 0 {
            return None;
        }
        self.reverse
            .borrow()
            .get((node.0 & !GRAFT_BIT) as usize)
            .copied()
    }

    fn intern(&self, graft: usize, inner: NodeId) -> NodeId {
        if let Some(&id) = self.interned.borrow().get(&(graft, inner)) {
            return id;
        }
        let mut rev = self.reverse.borrow_mut();
        let id = NodeId(GRAFT_BIT | rev.len() as u64);
        rev.push((graft, inner));
        self.interned.borrow_mut().insert((graft, inner), id);
        id
    }

    /// The graft at an outer leaf, probing (read + parse) on first
    /// touch. Only childless outer nodes with text content are
    /// candidates.
    fn graft_at(&self, node: NodeId) -> Option<usize> {
        if let Some(&g) = self.probed.borrow().get(&node) {
            return g;
        }
        let g = (|| {
            if !self.outer.children(node).is_empty() {
                return None;
            }
            let name = self.outer.name(node)?;
            if archive_name(&name)
                && let Some(path_of) = self.source_path
                && let Some(path) = path_of(&self.outer, node)
                && let Ok(a) =
                    quarb_archive::ArchiveAdapter::open_with_decoding(&path, self.decoding.clone())
            {
                let inner = Inner::Archive(Box::new(
                    ComposeAdapter::new(a)
                        .with_source_graft(self.source_graft)
                        .with_document_graft(self.document_graft)
                        .with_decoding(self.decoding.clone())
                        .with_csv_options(self.csv),
                ));
                let mut grafts = self.grafts.borrow_mut();
                grafts.push(Graft { outer: node, inner });
                return Some(grafts.len() - 1);
            }
            if let Some(read) = &self.document_reader
                && let Some(path_of) = self.source_path
                && let Some(path) = path_of(&self.outer, node)
                && let Some(model) = read(&path)
            {
                let mut grafts = self.grafts.borrow_mut();
                grafts.push(Graft {
                    outer: node,
                    inner: Inner::Text(model),
                });
                return Some(grafts.len() - 1);
            }
            // Through the path when there is one: the bytes meet
            // the boundary here, under the mount's rule, and the
            // record stays with the graft. A leaf whose bytes refuse
            // to decode (not UTF-8, nothing declared) stays a leaf.
            let mut record = None;
            let content = match self
                .source_path
                .and_then(|path_of| path_of(&self.outer, node))
                .and_then(|p| std::fs::read(p).ok())
            {
                Some(bytes) => {
                    let d = self.decoding.decode(&name, &bytes).ok()?;
                    record = Some((d.encoding, d.replaced));
                    d.text
                }
                None => match self.outer.default_value(node)? {
                    Value::Str(s) => s,
                    _ => return None,
                },
            };
            let mut inner = parse_inner(
                &name,
                &content,
                self.source_graft,
                self.document_graft,
                self.csv,
            )?;
            if let (Inner::Text(model), Some(f)) = (&mut inner, self.document_url)
                && let Some(u) = f(&self.outer, node)
            {
                model.set_document_url(&u);
            }
            let mut grafts = self.grafts.borrow_mut();
            grafts.push(Graft { outer: node, inner });
            if let Some(r) = record {
                self.decoded.borrow_mut().insert(grafts.len() - 1, r);
            }
            Some(grafts.len() - 1)
        })();
        self.probed.borrow_mut().insert(node, g);
        g
    }

    /// Map an inner node up: the inner root becomes the outer
    /// leaf.
    fn wrap(&self, graft: usize, inner: NodeId) -> NodeId {
        let grafts = self.grafts.borrow();
        if inner == grafts[graft].inner.adapter().root() {
            grafts[graft].outer
        } else {
            drop(grafts);
            self.intern(graft, inner)
        }
    }
}

impl<A: AstAdapter> AstAdapter for ComposeAdapter<A> {
    fn root(&self) -> NodeId {
        self.outer.root()
    }

    fn children(&self, node: NodeId) -> Vec<NodeId> {
        match self.split(node) {
            Some((g, inner)) => {
                let ids: Vec<NodeId> = {
                    let grafts = self.grafts.borrow();
                    grafts[g].inner.adapter().children(inner)
                };
                ids.into_iter().map(|c| self.wrap(g, c)).collect()
            }
            None => {
                let outer = self.outer.children(node);
                if !outer.is_empty() {
                    return outer;
                }
                match self.graft_at(node) {
                    Some(g) => {
                        let ids: Vec<NodeId> = {
                            let grafts = self.grafts.borrow();
                            let a = grafts[g].inner.adapter();
                            a.children(a.root())
                        };
                        ids.into_iter().map(|c| self.wrap(g, c)).collect()
                    }
                    None => Vec::new(),
                }
            }
        }
    }

    /// A child by name: the outer source's own lookup first (a
    /// database reads `/books/7` by key), and the listing only where
    /// the node may hold a grafted document — a leaf with a path or
    /// with text. A miss on a node that cannot hold one stays a
    /// miss, without listing its children.
    fn children_named(&self, node: NodeId, name: &str) -> Vec<NodeId> {
        match self.split(node) {
            Some((g, inner)) => {
                let ids: Vec<NodeId> = {
                    let grafts = self.grafts.borrow();
                    grafts[g].inner.adapter().children_named(inner, name)
                };
                ids.into_iter().map(|c| self.wrap(g, c)).collect()
            }
            None => {
                let named = self.outer.children_named(node, name);
                if !named.is_empty() {
                    return named;
                }
                if self.source_path.is_none()
                    && !matches!(self.outer.default_value(node), Some(Value::Str(_)))
                {
                    return Vec::new();
                }
                self.children(node)
                    .into_iter()
                    .filter(|&c| self.answers_to(c, name))
                    .collect()
            }
        }
    }

    fn name(&self, node: NodeId) -> Option<String> {
        match self.split(node) {
            Some((g, inner)) => self.grafts.borrow()[g].inner.adapter().name(inner),
            None => self.outer.name(node),
        }
    }

    fn parent(&self, node: NodeId) -> Option<NodeId> {
        match self.split(node) {
            Some((g, inner)) => {
                let p = self.grafts.borrow()[g].inner.adapter().parent(inner)?;
                Some(self.wrap(g, p))
            }
            None => self.outer.parent(node),
        }
    }

    fn child_host(&self, node: NodeId) -> NodeId {
        match self.split(node) {
            Some((g, inner)) => {
                let h = self.grafts.borrow()[g].inner.adapter().child_host(inner);
                self.wrap(g, h)
            }
            None => self.outer.child_host(node),
        }
    }

    fn properties(&self, node: NodeId) -> Vec<(String, Value)> {
        match self.split(node) {
            Some((g, inner)) => self.grafts.borrow()[g].inner.adapter().properties(inner),
            None => self.outer.properties(node),
        }
    }

    /// The walk is open when the outer tree opens to it (a graft is
    /// read whole once reached).
    fn walks_for_references(&self) -> bool {
        self.outer.walks_for_references()
    }
    /// A declaration answers on its own side of the boundary; across
    /// it only a reference property of the source's own can reach.
    fn can_refer_to(&self, source: NodeId, target: NodeId) -> Option<bool> {
        match (self.split(source), self.split(target)) {
            (None, None) => self.outer.can_refer_to(source, target),
            (Some((g, s)), Some((h, t))) if g == h => {
                self.grafts.borrow()[g].inner.adapter().can_refer_to(s, t)
            }
            _ => self.ref_property(source).map(|_| true),
        }
    }
    fn reference_properties(&self, source: NodeId, target: NodeId) -> Vec<String> {
        match (self.split(source), self.split(target)) {
            (None, None) => self.outer.reference_properties(source, target),
            (Some((g, s)), Some((h, t))) if g == h => self.grafts.borrow()[g]
                .inner
                .adapter()
                .reference_properties(s, t),
            _ => self.ref_property(source).into_iter().collect(),
        }
    }
    /// The outer source's own index over a scope of its own nodes
    /// (a database reading `/books/*` by key).
    fn index_referrers(
        &self,
        scope: &str,
        property: &str,
        label: Option<&str>,
        target: NodeId,
    ) -> Option<Vec<NodeId>> {
        match self.split(target) {
            None => self.outer.index_referrers(scope, property, label, target),
            Some(_) => None,
        }
    }
    fn tree_identities(&self) -> Vec<(String, NodeId)> {
        self.outer.tree_identities()
    }
    fn reverse_label(&self, target: NodeId) -> Option<String> {
        match self.split(target) {
            Some((g, inner)) => self.grafts.borrow()[g].inner.adapter().reverse_label(inner),
            None => self.outer.reverse_label(target),
        }
    }
    fn resolve_needs_label(&self, node: NodeId, property: &str) -> bool {
        match self.split(node) {
            Some((g, inner)) => self.grafts.borrow()[g]
                .inner
                .adapter()
                .resolve_needs_label(inner, property),
            None => self.outer.resolve_needs_label(node, property),
        }
    }
    fn property_names(&self, node: NodeId) -> Vec<String> {
        match self.split(node) {
            Some((g, inner)) => self.grafts.borrow()[g]
                .inner
                .adapter()
                .property_names(inner),
            None => self.outer.property_names(node),
        }
    }
    /// The outer source, or any document grafted so far.
    fn resolves_references(&self) -> bool {
        self.outer.resolves_references()
            || self
                .grafts
                .borrow()
                .iter()
                .any(|g| g.inner.adapter().resolves_references())
    }

    /// The outer tree's non-tree nodes, then each graft's (the
    /// grafts already read).
    fn non_tree_nodes(&self) -> Vec<NodeId> {
        let mut out = self.outer.non_tree_nodes();
        let grafts = self.grafts.borrow();
        for (g, graft) in grafts.iter().enumerate() {
            out.extend(
                graft
                    .inner
                    .adapter()
                    .non_tree_nodes()
                    .into_iter()
                    .map(|n| self.wrap(g, n)),
            );
        }
        out
    }

    /// A written name reaches a node by the owning adapter's rule
    /// (its aliases included).
    fn answers_to(&self, node: NodeId, name: &str) -> bool {
        match self.split(node) {
            Some((g, inner)) => self.grafts.borrow()[g]
                .inner
                .adapter()
                .answers_to(inner, name),
            None => self.outer.answers_to(node, name),
        }
    }

    /// The graft root IS the outer leaf, so the leaf wears the
    /// grafted document's own traits too — a page's declared tags
    /// on the file that holds it.
    fn traits(&self, node: NodeId) -> Vec<String> {
        match self.split(node) {
            Some((g, inner)) => self.grafts.borrow()[g].inner.adapter().traits(inner),
            None => {
                let mut out = self.outer.traits(node);
                if let Some(g) = self.graft_at(node) {
                    let grafts = self.grafts.borrow();
                    let a = grafts[g].inner.adapter();
                    for t in a.traits(a.root()) {
                        if !out.contains(&t) {
                            out.push(t);
                        }
                    }
                }
                out
            }
        }
    }

    fn property(&self, node: NodeId, name: &str) -> Option<Value> {
        match self.split(node) {
            Some((g, inner)) => self.grafts.borrow()[g]
                .inner
                .adapter()
                .property(inner, name),
            // The graft root IS the outer leaf, so a property the
            // outer can't answer falls through to the grafted
            // document's root — `::key` dual exposure works *at*
            // the graft, not only one level in.
            None => self.outer.property(node, name).or_else(|| {
                let g = self.graft_at(node)?;
                let grafts = self.grafts.borrow();
                let a = grafts[g].inner.adapter();
                a.property(a.root(), name)
            }),
        }
    }

    fn default_value(&self, node: NodeId) -> Option<Value> {
        match self.split(node) {
            Some((g, inner)) => self.grafts.borrow()[g].inner.adapter().default_value(inner),
            // A leaf that did not graft (plain text, a format this
            // crate does not parse) is still a source: read through
            // its path under the mount's rule, so `?encoding=` and
            // a declaration reach it. The outer adapter's own text
            // (strict UTF-8) stands where there is no path.
            None => {
                if self.decoding.explicit.is_some()
                    && self.outer.children(node).is_empty()
                    && let Some(path_of) = self.source_path
                    && let Some(p) = path_of(&self.outer, node)
                    && p.is_file()
                    && let Ok(bytes) = std::fs::read(&p)
                {
                    let name = self.outer.name(node).unwrap_or_default();
                    return self
                        .decoding
                        .decode(&name, &bytes)
                        .ok()
                        .map(|d| Value::Str(d.text));
                }
                self.outer.default_value(node)
            }
        }
    }

    fn metadata(&self, node: NodeId, key: &str) -> Option<Value> {
        match self.split(node) {
            Some((g, inner)) => self.grafts.borrow()[g].inner.adapter().metadata(inner, key),
            // Like properties: what the outer cannot answer, the
            // grafted document's root may (`::::"og:type"` on the
            // file that holds the page).
            None => self.outer.metadata(node, key).or_else(|| {
                let g = self.graft_at(node)?;
                if matches!(key, "encoding" | "replaced") {
                    // A leaf the host's reader read by path has no
                    // record yet: decode its bytes under the mount's
                    // rule once, for the record alone.
                    if !self.decoded.borrow().contains_key(&g)
                        && let Some(path_of) = self.source_path
                        && let Some(p) = path_of(&self.outer, node)
                        && let Ok(bytes) = std::fs::read(&p)
                    {
                        let name = self.outer.name(node).unwrap_or_default();
                        if let Ok(d) = self.decoding.decode(&name, &bytes) {
                            self.decoded
                                .borrow_mut()
                                .insert(g, (d.encoding, d.replaced));
                        }
                    }
                    if let Some((enc, replaced)) = self.decoded.borrow().get(&g) {
                        return Some(match key {
                            "encoding" => Value::Str(enc.clone()),
                            _ => Value::Int(*replaced as i64),
                        });
                    }
                }
                let grafts = self.grafts.borrow();
                let a = grafts[g].inner.adapter();
                a.metadata(a.root(), key)
            }),
        }
    }

    /// A graft's own aliases are not merged: a node either belongs
    /// to the outer document or to a graft, and the alias list is
    /// consulted only after the owning adapter's `property` misses.
    fn aliased_metadata(&self, node: NodeId) -> &'static [&'static str] {
        match self.split(node) {
            Some((g, inner)) => self.grafts.borrow()[g]
                .inner
                .adapter()
                .aliased_metadata(inner),
            None => self.outer.aliased_metadata(node),
        }
    }

    /// A graft is a provenance layer: the grafted document's own
    /// components win, and the outer *leaf* it was parsed from fills
    /// the rest (with an fs outer: the file's path and mtime). The
    /// jar-style composite locator is deliberately not the source —
    /// `?src` names a document, and the intra-document address is
    /// dpid's job.
    fn provenance(&self, node: NodeId) -> quarb::Provenance {
        match self.split(node) {
            Some((g, inner)) => {
                // Clone what we need out of the borrow before calling
                // into `self.outer` (which may re-enter the graft
                // tables).
                let (inner_prov, outer_leaf, inner_path) = {
                    let grafts = self.grafts.borrow();
                    let a = grafts[g].inner.adapter();
                    (
                        a.provenance(inner),
                        grafts[g].outer,
                        quarb::name_path(a, inner),
                    )
                };
                inner_prov.or(self.graft_fill(outer_leaf, inner_path))
            }
            None => self.outer.provenance(node),
        }
    }
    /// The same layering, entry by entry.
    fn provenance_list(&self, node: NodeId) -> quarb::ProvenanceList {
        match self.split(node) {
            Some((g, inner)) => {
                let (inner_list, outer_leaf, inner_path) = {
                    let grafts = self.grafts.borrow();
                    let a = grafts[g].inner.adapter();
                    (
                        a.provenance_list(inner),
                        grafts[g].outer,
                        quarb::name_path(a, inner),
                    )
                };
                inner_list.or(self.graft_fill(outer_leaf, inner_path))
            }
            None => self.outer.provenance_list(node),
        }
    }

    fn resolve(&self, node: NodeId, property: &str, hint: Option<&str>) -> Option<NodeId> {
        match self.split(node) {
            Some((g, inner)) => {
                let t = self.grafts.borrow()[g]
                    .inner
                    .adapter()
                    .resolve(inner, property, hint)?;
                Some(self.wrap(g, t))
            }
            None => self.outer.resolve(node, property, hint),
        }
    }

    /// A trait test reaches the graft — and, on the outer leaf,
    /// the graft's root, as `traits` does.
    fn has_trait(&self, node: NodeId, name: &str) -> bool {
        match self.split(node) {
            Some((g, inner)) => self.grafts.borrow()[g]
                .inner
                .adapter()
                .has_trait(inner, name),
            None => {
                self.outer.has_trait(node, name)
                    || self.graft_at(node).is_some_and(|g| {
                        let grafts = self.grafts.borrow();
                        let a = grafts[g].inner.adapter();
                        a.has_trait(a.root(), name)
                    })
            }
        }
    }

    fn ref_property(&self, node: NodeId) -> Option<String> {
        match self.split(node) {
            Some((g, inner)) => self.grafts.borrow()[g].inner.adapter().ref_property(inner),
            None => self.outer.ref_property(node),
        }
    }

    /// A graft's external references (a text-level ref leaving
    /// its document) come through; an outer leaf's own do too.
    fn external_ref(
        &self,
        node: NodeId,
        property: &str,
        hint: Option<&str>,
    ) -> Option<quarb::ExternalRef> {
        match self.split(node) {
            Some((g, inner)) => self.grafts.borrow()[g]
                .inner
                .adapter()
                .external_ref(inner, property, hint),
            None => self.outer.external_ref(node, property, hint),
        }
    }

    fn ref_label(&self, node: NodeId, property: &str) -> Option<String> {
        match self.split(node) {
            Some((g, inner)) => self.grafts.borrow()[g]
                .inner
                .adapter()
                .ref_label(inner, property),
            None => self.outer.ref_label(node, property),
        }
    }

    /// A fragment lands inside the document: on an outer leaf
    /// that holds a graft, inside that graft.
    fn resolve_fragment(&self, node: NodeId, fragment: &str) -> Option<NodeId> {
        match self.split(node) {
            Some((g, inner)) => {
                let t = self.grafts.borrow()[g]
                    .inner
                    .adapter()
                    .resolve_fragment(inner, fragment)?;
                Some(self.wrap(g, t))
            }
            None => match self.graft_at(node) {
                Some(g) => {
                    let t = {
                        let grafts = self.grafts.borrow();
                        let a = grafts[g].inner.adapter();
                        a.resolve_fragment(a.root(), fragment)?
                    };
                    Some(self.wrap(g, t))
                }
                None => self.outer.resolve_fragment(node, fragment),
            },
        }
    }

    /// The leaf serving a URL, from the declared document URLs;
    /// else whatever the outer answers.
    fn document_by_ref(&self, id: &str) -> Option<NodeId> {
        if let Some(leaf) = self.leaf_by_url(id) {
            // The graft is parsed here so a fragment can land.
            let _ = self.graft_at(leaf);
            return Some(leaf);
        }
        self.outer.document_by_ref(id)
    }

    /// A reverse index answers on one side of the boundary only:
    /// inside a graft, the graft's own; on the outer tree, the
    /// outer's declared references (a catalog key, a model `ref`),
    /// which no graft can hold a referrer for.
    fn reverse_resolve(
        &self,
        node: NodeId,
        property: Option<&str>,
        hint: Option<&str>,
    ) -> Option<Vec<NodeId>> {
        match self.split(node) {
            Some((g, inner)) => {
                let v = self.grafts.borrow()[g]
                    .inner
                    .adapter()
                    .reverse_resolve(inner, property, hint)?;
                Some(v.into_iter().map(|t| self.wrap(g, t)).collect())
            }
            None => self.outer.reverse_resolve(node, property, hint),
        }
    }

    /// Inside a graft the graft's index answers; on the outer tree
    /// a name may also live inside grafts, so the walk stays.
    fn descendants_named(&self, node: NodeId, name: &str) -> Option<Vec<(NodeId, usize)>> {
        let (g, inner) = self.split(node)?;
        let v = self.grafts.borrow()[g]
            .inner
            .adapter()
            .descendants_named(inner, name)?;
        Some(v.into_iter().map(|(t, d)| (self.wrap(g, t), d)).collect())
    }

    fn descendants_where(
        &self,
        node: NodeId,
        name: &str,
        property: &str,
        value: &Value,
    ) -> Option<Vec<(NodeId, usize)>> {
        let (g, inner) = self.split(node)?;
        let v = self.grafts.borrow()[g]
            .inner
            .adapter()
            .descendants_where(inner, name, property, value)?;
        Some(v.into_iter().map(|(t, d)| (self.wrap(g, t), d)).collect())
    }

    fn has_node(&self, node: NodeId) -> bool {
        match self.split(node) {
            Some((g, inner)) => self.grafts.borrow()[g].inner.adapter().has_node(inner),
            None => self.outer.has_node(node),
        }
    }

    fn unit_scale(&self, expr: &str) -> Option<(f64, String)> {
        self.outer.unit_scale(expr)
    }

    fn allow_shell(&self) -> bool {
        self.outer.allow_shell()
    }

    fn quantifier_bound(&self) -> usize {
        self.outer.quantifier_bound()
    }

    fn invocation_instant(&self) -> Option<(i64, u32)> {
        self.outer.invocation_instant()
    }

    fn prefetch_links(&self, nodes: &[NodeId], dir: quarb::LinkDir) {
        let outer: Vec<NodeId> = nodes
            .iter()
            .copied()
            .filter(|n| self.split(*n).is_none())
            .collect();
        if !outer.is_empty() {
            self.outer.prefetch_links(&outer, dir);
        }
    }

    fn links(&self, node: NodeId) -> Vec<(String, NodeId)> {
        match self.split(node) {
            Some((g, inner)) => {
                let ls: Vec<(String, NodeId)> = {
                    let grafts = self.grafts.borrow();
                    grafts[g].inner.adapter().links(inner)
                };
                ls.into_iter().map(|(l, n)| (l, self.wrap(g, n))).collect()
            }
            None => self.outer.links(node),
        }
    }

    fn backlinks(&self, node: NodeId) -> Vec<(String, NodeId)> {
        match self.split(node) {
            Some((g, inner)) => {
                let ls: Vec<(String, NodeId)> = {
                    let grafts = self.grafts.borrow();
                    grafts[g].inner.adapter().backlinks(inner)
                };
                ls.into_iter().map(|(l, n)| (l, self.wrap(g, n))).collect()
            }
            None => self.outer.backlinks(node),
        }
    }

    fn link_property(
        &self,
        source: NodeId,
        label: &str,
        target: NodeId,
        name: &str,
    ) -> Option<Value> {
        // An edge lives on one side of the graft boundary: both
        // endpoints are inner (same graft) or both outer.
        match (self.split(source), self.split(target)) {
            (Some((g, src)), Some((gt, tgt))) if g == gt => self.grafts.borrow()[g]
                .inner
                .adapter()
                .link_property(src, label, tgt, name),
            (None, None) => self.outer.link_property(source, label, target, name),
            _ => None,
        }
    }
}