qua 0.75.0

Structure-aware query CLI for the Quarb engine
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
//! `text:DIR` over a folder of documents (lang/TODO.md): the folder
//! tree, each document leaf read at the text level — sections and
//! paragraphs under every file, subfolders walked. A folder that
//! holds a treebank still reads as the treebank
//! (corpus_conllu.rs covers that).

fn qua(args: &[&str]) -> String {
    let out = std::process::Command::new(env!("CARGO_BIN_EXE_qua"))
        .env("QUARB_LOCALE", "C")
        .args(args)
        .stdin(std::process::Stdio::null())
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "qua {args:?}: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    String::from_utf8(out.stdout).unwrap()
}

#[test]
fn a_folder_of_documents_reads_at_the_text_level() {
    let dir = std::env::temp_dir().join(format!("quarb-manuscript-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("part2")).unwrap();
    std::fs::write(
        dir.join("01-one.md"),
        "# One\n\nTom *painted* the fence.\n\n## Aside\n\nBen watched.\n",
    )
    .unwrap();
    std::fs::write(
        dir.join("02-two.md"),
        "# Two\n\nHuck came by. He had a dead cat.\n",
    )
    .unwrap();
    std::fs::write(
        dir.join("part2/03-three.md"),
        "# Three\n\nAunt Polly sighed.\n",
    )
    .unwrap();
    let text = format!("text:{}", dir.display());

    // the files and the subfolder, by name
    assert_eq!(qua(&["/* | :name", &text]), "01-one.md\n02-two.md\npart2\n");
    // sections across the whole folder, the subfolder included
    assert_eq!(
        qua(&["//section::lemma", &text]),
        "One\nAside\nTwo\nThree\n"
    );
    // words per chapter file: the prose, without the markup
    assert_eq!(
        qua(&[
            r#"//*[:name == *".md"] | "${:name} ${(//paragraph | :: | wc @| sum)}""#,
            &text
        ]),
        "01-one.md 6\n02-two.md 8\n03-three.md 3\n"
    );
    // the same folder as a named mount beside another
    assert_eq!(
        qua(&[
            "/ms//section @| count",
            &format!("ms={text}"),
            &format!("again={text}")
        ]),
        "4\n"
    );
    // the corpus reading over the same folder: tokens and sentences
    // under every chapter, counted across the whole manuscript
    let corpus = format!("corpus:{}", dir.display());
    // five of prose, four headings: headings are sentences
    assert_eq!(qua(&["//sentence @| count", &corpus]), "9\n");
    assert_eq!(
        qua(&[
            r#"//*[:name == *".md"] | "${:name} ${(//token<word> @| count)}""#,
            &corpus
        ]),
        // the headings' words counted too: headings are sentences
        "01-one.md 8\n02-two.md 9\n03-three.md 4\n"
    );
    assert_eq!(
        qua(&[r#"//token[::lower = "tom"] @| count"#, &corpus]),
        "1\n"
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn a_folder_of_editions_reads_at_the_literary_level() {
    let dir = std::env::temp_dir().join(format!("quarb-editions-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let play =
        "@@@!litogramma\n\n@#() A Play\n\n@: Tom\nHello there.\n:@\n\n@: Huck\nHello.\n:@\n\n#@\n";
    std::fs::write(dir.join("play.atd"), play).unwrap();
    std::fs::write(dir.join("notes.csv"), "a,b\n1,2\n").unwrap();
    let lit = format!("lit:{}", dir.display());
    // the edition is read with its speeches; the table stays a leaf
    // (a drama speech's node is named `speech`: quarb_text::SPEECH)
    assert_eq!(qua(&["//speech @| count", &lit]), "2\n");
    assert_eq!(qua(&["/* | :name", &lit]), "notes.csv\nplay.atd\n");
    // the text level reads the same edition's blocks without tokens
    let text = format!("text:{}", dir.display());
    assert_eq!(qua(&["//token @| count", &text]), "0\n");
    let _ = std::fs::remove_dir_all(&dir);
}

/// A step that asks a text reading for `dialogue` is told the name
/// the drama speech bears now (KIND_RENAMED; the user's ruling of
/// 2026-11-26: "A note for the old name. Where a text reading is
/// asked for a node named `dialogue`, the engine says the drama
/// speech is `speech` since 0.75. The note stays through 0.76 and
/// then goes"). A 0.74 user's `//dialogue @| count` over a play
/// answered 0 in silence where it had answered every speech.
#[test]
fn a_step_that_asks_for_dialogue_is_told_the_speech() {
    let dir = std::env::temp_dir().join(format!("quarb-old-name-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("editions")).unwrap();
    let play =
        "@@@!litogramma\n\n@#() A Play\n\n@: Tom\nHello there.\n:@\n\n@: Huck\nHello.\n:@\n\n#@\n";
    std::fs::write(dir.join("editions/play.atd"), play).unwrap();
    std::fs::write(dir.join("books.json"), r#"{"books": [{"title": "Emma"}]}"#).unwrap();
    const NOTE: &str = "warning KIND_RENAMED (//dialogue): no node of a text reading is named \
                        'dialogue': the drama speech is 'speech' since 0.75. Spell it another \
                        way: qua man KIND_RENAMED";
    let file = dir.join("editions/play.atd");
    let said = |query: &str, sources: &[&str]| {
        let mut args = vec![query];
        args.extend(sources);
        let (ok, out, err) = qua_full(&args);
        assert!(ok, "{query} {sources:?}: {err}");
        (out.trim().to_string(), err.trim().to_string())
    };
    // every text reading of the edition, and a folder of editions,
    // whose root is none of them: the answer as it is, and the note
    for source in [
        format!("lit:{}", file.display()),
        format!("text:{}", file.display()),
        format!("corpus:{}", file.display()),
        format!("lit:{}", dir.join("editions").display()),
    ] {
        assert_eq!(
            said("//dialogue @| count", &[&source]),
            ("0".to_string(), NOTE.to_string()),
            "{source}"
        );
    }
    let lit = format!("lit:{}", file.display());
    // wherever the step stands in the query, once
    for query in [
        "//speech[//dialogue] @| count",
        "//speech @| count | (^//dialogue @| count)",
        "//dialogue | (^//dialogue @| count)",
    ] {
        let (_, err) = said(query, &[&lit]);
        assert_eq!(err, NOTE, "{query}");
    }
    // quiet: the name as it is; a name tested in a predicate, which
    // is no step; a kind the reading never had
    for (query, answer) in [
        ("//speech @| count", "2"),
        (r#"//speech[:name = "dialogue"] @| count"#, "0"),
        ("//paragraf @| count", "0"),
    ] {
        assert_eq!(
            said(query, &[&lit]),
            (answer.to_string(), String::new()),
            "{query}"
        );
    }
    // mounted under a name, alone or beside another source: the
    // root is none of them, and the reading answers for it (the
    // named mount every page uses was not told)
    let json = dir.join("books.json").display().to_string();
    let play = format!("play={lit}");
    let books = format!("books={json}");
    for (query, sources) in [
        ("//dialogue @| count", &[play.as_str()][..]),
        ("/play//dialogue @| count", &[play.as_str()][..]),
        ("//dialogue @| count", &[play.as_str(), books.as_str()][..]),
        (
            "/play//dialogue @| count",
            &[books.as_str(), play.as_str()][..],
        ),
    ] {
        assert_eq!(
            said(query, sources),
            ("0".to_string(), NOTE.to_string()),
            "{query} {sources:?}"
        );
    }
    // beside a source that HAS nodes of that name the step answers
    // them, and a step that reached a node is told nothing: the name
    // is a right one there. (The note was told from the query's words
    // alone through pin 43, on a step that had matched.) A step of
    // that name that reaches nothing is told, beside it or under it
    // in the same query.
    std::fs::write(
        dir.join("talk.json"),
        r#"{"scenes": [{"dialogue": "a line"}, {"dialogue": "another"}]}"#,
    )
    .unwrap();
    let talk = format!("talk={}", dir.join("talk.json").display());
    for (query, answer, told) in [
        ("//dialogue @| count", "2", ""),
        ("/talk//dialogue @| count", "2", ""),
        ("/talk/scenes/*/dialogue::", "a line\nanother", ""),
        ("/play//dialogue @| count", "0", NOTE),
        ("/talk//dialogue/dialogue @| count", "0", NOTE),
        // inside a predicate the step is told from the query's words
        ("/talk/scenes/*[/dialogue] @| count", "2", NOTE),
    ] {
        assert_eq!(
            said(query, &[&play, &talk]),
            (answer.to_string(), told.to_string()),
            "{query}"
        );
    }
    assert_eq!(
        said("//dialogue @| count", &[&talk]),
        ("2".to_string(), String::new())
    );
    // quiet: sources none of which is a text reading
    assert_eq!(
        said("//dialogue @| count", &[&json]),
        ("0".to_string(), String::new())
    );
    assert_eq!(
        said("//dialogue @| count", &[&books, &format!("more={json}")]),
        ("0".to_string(), String::new())
    );
    let _ = std::fs::remove_dir_all(&dir);
}

/// "stanza and line in 0.75", and of the block that holds them
/// "Agreed with poetry > stanza > line." (the user's rulings of
/// 2026-11-27): a block of verse is `poetry` and its parts `stanza`
/// and `line` in every text reading, and a step that asks for the
/// names they bore through 0.74, `verse`, `strophe` and `stichos`, is
/// told as one that asks for `dialogue` is. An atrep document mounted
/// with no reading keeps its own names, the format's, and is told
/// nothing.
#[test]
fn a_step_that_asks_for_verse_strophe_or_stichos_is_told_the_names_they_bear() {
    let dir = std::env::temp_dir().join(format!("quarb-verse-names-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let ode = "@@@!koine\n\n@@@=\nHappy the man, whose wish and care\nA few paternal acres \
               bound,\n\nContent to breathe his native air\nIn his own ground.\n=@@@\n";
    let file = dir.join("ode.atd");
    std::fs::write(&file, ode).unwrap();
    const POETRY: &str = "warning KIND_RENAMED (//verse): no node of a text reading is named \
                          'verse': the block of verse is 'poetry' since 0.75. Spell it another \
                          way: qua man KIND_RENAMED";
    const STANZA: &str = "warning KIND_RENAMED (//strophe): no node of a text reading is named \
                          'strophe': the stanza of a poetry block is 'stanza' since 0.75. Spell \
                          it another way: qua man KIND_RENAMED";
    const LINE: &str = "warning KIND_RENAMED (//stichos): no node of a text reading is named \
                        'stichos': the line of a poetry block is 'line' since 0.75. Spell it \
                        another way: qua man KIND_RENAMED";
    let said = |query: &str, source: &str| {
        let (ok, out, err) = qua_full(&[query, source]);
        assert!(ok, "{query} {source}: {err}");
        (out.trim().replace('\n', " "), err.trim().to_string())
    };
    let quiet = |answer: &str| (answer.to_string(), String::new());
    for reading in ["lit", "text", "koine", "corpus"] {
        let source = format!("{reading}:{}", file.display());
        // the names as they are
        for (query, answer) in [
            ("//poetry @| count", "1"),
            ("//stanza @| count", "2"),
            ("//poetry/stanza/line @| count", "4"),
            ("//stanza[2]/line[1]::taxis", "3"),
            ("//line[::taxis = 4]::", "In his own ground."),
        ] {
            assert_eq!(said(query, &source), quiet(answer), "{query} {source}");
        }
        // the names they bore: the answer as it is, and the note
        assert_eq!(
            said("//verse @| count", &source),
            ("0".to_string(), POETRY.to_string()),
            "{source}"
        );
        assert_eq!(
            said("//strophe @| count", &source),
            ("0".to_string(), STANZA.to_string()),
            "{source}"
        );
        assert_eq!(
            said("//stichos @| count", &source),
            ("0".to_string(), LINE.to_string()),
            "{source}"
        );
        // both in one query: each told once
        let (answer, err) = said("//strophe/stichos @| count", &source);
        assert_eq!(answer, "0", "{source}");
        let mut told: Vec<&str> = err.lines().collect();
        told.sort_unstable();
        assert_eq!(told, [LINE, STANZA], "{source}");
    }
    // a step named `verse` that REACHES a node is told nothing: a
    // folder of that name under a text reading, a key of that name in
    // a file mounted beside one (the note was told on both, and
    // `--fail-on-warning` failed a query that was right)
    std::fs::create_dir_all(dir.join("shelf/verse")).unwrap();
    std::fs::write(
        dir.join("shelf/verse/iliad.txt"),
        "Sing, goddess, the wrath of Achilles.\n\nMany souls it sent to Hades.\n",
    )
    .unwrap();
    std::fs::write(
        dir.join("mark.json"),
        r#"{"book": "Mark", "verse": [{"n": 1}, {"n": 2}]}"#,
    )
    .unwrap();
    let shelf = format!("corpus:{}", dir.join("shelf").display());
    let ode = format!("ode=lit:{}", file.display());
    let data = format!("data={}", dir.join("mark.json").display());
    for (query, sources, answer, told) in [
        ("/verse//paragraph @| count", &[shelf.as_str()][..], "2", ""),
        ("//verse @| count", &[shelf.as_str()][..], "1", ""),
        ("/verse//verse @| count", &[shelf.as_str()][..], "0", POETRY),
        (
            "/data//verse @| count",
            &[ode.as_str(), data.as_str()][..],
            "1",
            "",
        ),
        (
            "//verse @| count",
            &[ode.as_str(), data.as_str()][..],
            "1",
            "",
        ),
        (
            "/ode//verse @| count",
            &[ode.as_str(), data.as_str()][..],
            "0",
            POETRY,
        ),
    ] {
        let mut args = vec!["--fail-on-warning", query];
        args.extend(sources);
        let (ok, out, err) = qua_full(&args);
        assert_eq!(
            (ok, out.trim(), err.trim()),
            (told.is_empty(), answer, told),
            "{query} {sources:?}"
        );
    }
    // with no reading named the document is atrep's own tree, and
    // the words are the format's: answered, and nothing said
    let bare = file.display().to_string();
    for (query, answer) in [
        ("//stichoi/strophe/stichos @| count", "4"),
        ("//strophe @| count", "2"),
        ("//stichos[4]::", "In his own ground."),
    ] {
        assert_eq!(said(query, &bare), quiet(answer), "{query}");
    }
}

/// A reference that resolves to nothing wears the traits of
/// reference with `undef-` before each (the user's rulings of
/// 2026-11-27: "simply prefix with undef-"; "confirmed, <undef-siglum>
/// it is"), and the trait it wore through 0.74, `<dangling>`, is worn
/// by no node of a text reading: a step that filters by it, negated
/// or not, is told as one that asks for `dialogue` is. An atrep
/// document mounted with no reading keeps the trait, there
/// litogramma's own, and is told nothing.
#[test]
fn a_step_that_filters_by_dangling_is_told_the_undefined_reference() {
    let dir = std::env::temp_dir().join(format!("quarb-undef-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("wrath.html");
    std::fs::write(
        &file,
        "<html><body>\n\
         <p id=\"one\">Sing, goddess<a role=\"doc-noteref\" href=\"#fn9\">9</a>, the wrath.</p>\n\
         <p>See <a href=\"#one\">above</a> and <a href=\"#nowhere\">elsewhere</a>.</p>\n\
         </body></html>\n",
    )
    .unwrap();
    const TOLD: &str = "warning KIND_RENAMED (//*<dangling>): no node of a text reading wears \
                        'dangling': an undefined reference wears 'undef-ref' since 0.75. Spell \
                        it another way: qua man KIND_RENAMED";
    let said = |query: &str, source: &str| {
        let (ok, out, err) = qua_full(&[query, source]);
        assert!(ok, "{query} {source}: {err}");
        (out.trim().replace('\n', " "), err.trim().to_string())
    };
    let quiet = |answer: &str| (answer.to_string(), String::new());
    let text = format!("text:{}", file.display());
    for (query, answer) in [
        // the callout that reaches no note: no node, its place marked
        ("//*<undef-noteref> | :name", "paragraph"),
        ("//*<undef-deixis> @| count", "1"),
        ("//footnote @| count", "0"),
        // the link that lands nowhere keeps its node and its name
        ("//ref<undef-ref>::target", "#nowhere"),
        ("//ref<!undef-ref>::target", "#one"),
        ("//*<undef-ref> @| count", "2"),
        ("//*<noteref> @| count", "0"),
    ] {
        assert_eq!(said(query, &text), quiet(answer), "{query}");
    }
    // the trait they wore: the answer as it is, and the note
    assert_eq!(
        said("//*<dangling> @| count", &text),
        ("0".to_string(), TOLD.to_string())
    );
    assert_eq!(
        said("//ref<!dangling> @| count", &text),
        ("2".to_string(), TOLD.to_string())
    );
    // with tokens the place is the token the callout follows
    let corpus = format!("corpus:{}", file.display());
    assert_eq!(said("//token<undef-noteref>::", &corpus), quiet("goddess"));
    // a bare atrep document keeps litogramma's trait, and is told
    // nothing
    let atd = dir.join("wrath.atd");
    std::fs::write(&atd, "@@@!koine\n\nSing, goddess@^(n9), the wrath.\n").unwrap();
    let (_, err) = said("//*<dangling> @| count", &atd.display().to_string());
    assert_eq!(err, "");
}

/// `?notes=mounted` and `?notes=hidden` (the user's words of
/// 2026-11-27: "?notes=mounted and ?notes=hidden (for mounted but
/// hidden tokens as we have it now with ?notes=omit)"), on each of
/// the four text readings: a note stands outside the tree by default;
/// mounted, each family's notes stand in it under a node at the root;
/// hidden, they stand there and hold no tokens. `omit`, the name the
/// second bore through 0.74, is taken as it.
#[test]
fn notes_mount_in_the_tree_by_the_option() {
    let dir = std::env::temp_dir().join(format!("quarb-notes-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let md = dir.join("wrath.md");
    std::fs::write(
        &md,
        "# The Wrath\n\nSing, goddess[^1], the wrath of Achilles.[^2]\n\n\
         [^1]: The Muse is meant.\n[^2]: Its cause is told later.\n",
    )
    .unwrap();
    let tei = dir.join("wrath.xml");
    std::fs::write(
        &tei,
        "<TEI xmlns=\"http://www.tei-c.org/ns/1.0\"><text><body><div><head>The Wrath</head>\
         <p>Sing, goddess<note place=\"foot\">The Muse is meant.</note>, the wrath of \
         Achilles.</p></div></body></text></TEI>\n",
    )
    .unwrap();
    let said = |query: &str, source: &str| {
        let (ok, out, err) = qua_full(&[query, source]);
        assert!(ok, "{query} {source}: {err}");
        assert_eq!(err.trim(), "", "{query} {source}");
        out.trim().replace('\n', " ")
    };
    let md = md.display().to_string();
    let tei = tei.display().to_string();
    // the text and koine levels: the tree
    for reading in ["text", "koine"] {
        let plain = format!("p={reading}:{md}");
        assert_eq!(said("/p/* | :name", &plain), "section", "{reading}");
        assert_eq!(said("/p//footnote @| count", &plain), "0", "{reading}");
        assert_eq!(said("*//footnote @| count", &plain), "2", "{reading}");
        for how in ["mounted", "hidden", "omit"] {
            let mounted = format!("p={reading}:{md}?notes={how}");
            assert_eq!(
                said("/p/* | :name", &mounted),
                "section footnotes",
                "{reading} {how}"
            );
            assert_eq!(
                said("/p/footnotes/footnote::", &mounted),
                "The Muse is meant. Its cause is told later.",
                "{reading} {how}"
            );
            assert_eq!(
                said("/p//*<noteref>->footnote | :parent-name", &mounted),
                "footnotes footnotes",
                "{reading} {how}"
            );
        }
    }
    // an atrep document under text: reads through the koine route,
    // and its mount's options go with it (that route cleared them
    // when it began: the option mounted no note, and `?references=`
    // was lost there the same way)
    let atd = dir.join("hamlet.atd");
    std::fs::write(
        &atd,
        "@@@!litogramma\n\n@#() Hamlet\n\nTo be, or not to be.@^(n1)\n\n@^\nThe Folio reads \
         thus.\n^@(n1)\n\n#@\n",
    )
    .unwrap();
    let atd = atd.display().to_string();
    for reading in ["text", "koine", "corpus", "lit"] {
        assert_eq!(
            said("/p//footnote @| count", &format!("p={reading}:{atd}")),
            "0",
            "{reading}"
        );
        assert_eq!(
            said(
                "/p//footnote::",
                &format!("p={reading}:{atd}?notes=mounted")
            ),
            "The Folio reads thus.",
            "{reading}"
        );
    }
    // an office file is read from its bytes, by another road: the
    // option is taken there too (`text:book.odt?notes=mounted`
    // mounted no note, and said nothing)
    let odt = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../quarb-text-odt/tests/fixtures/tom-sawyer.odt"
    );
    for reading in ["text", "corpus"] {
        assert_eq!(
            said("/p//footnote @| count", &format!("p={reading}:{odt}")),
            "0",
            "{reading}"
        );
        assert_eq!(
            said(
                "/p/footnotes/footnote @| count",
                &format!("p={reading}:{odt}?notes=mounted")
            ),
            "2",
            "{reading}"
        );
    }
    // the corpus reading: the tokens too, counted after the text's
    let corpus = |options: &str| format!("p=corpus:{md}{options}");
    assert_eq!(said("/p//token @| count", &corpus("")), "11");
    assert_eq!(said("*//token @| count", &corpus("")), "22");
    assert_eq!(said("/p//token @| count", &corpus("?notes=mounted")), "22");
    assert_eq!(said("*//token @| count", &corpus("?notes=mounted")), "22");
    assert_eq!(
        said(
            "/p//footnote//token[1] | %(w = ::; n = :::n)",
            &corpus("?notes=mounted")
        ),
        r#"%(w = "The"; n = 12) %(w = "Its"; n = 17)"#
    );
    for how in ["hidden", "omit"] {
        let hidden = corpus(&format!("?notes={how}"));
        assert_eq!(said("/p//token @| count", &hidden), "11", "{how}");
        assert_eq!(said("*//token @| count", &hidden), "11", "{how}");
        assert_eq!(said("/p//footnote @| count", &hidden), "2", "{how}");
    }
    // the literary reading
    let lit = |options: &str| format!("p=lit:{tei}{options}");
    assert_eq!(said("/p/* | :name", &lit("")), "section");
    assert_eq!(said("/p//token @| count", &lit("")), "11");
    assert_eq!(
        said("/p/* | :name", &lit("?notes=mounted")),
        "section footnotes"
    );
    assert_eq!(said("/p//token @| count", &lit("?notes=mounted")), "16");
    assert_eq!(said("/p//token @| count", &lit("?notes=hidden")), "11");
    assert_eq!(
        said(
            "/p//*<note> | %(k = :name; up = :parent-name)",
            &lit("?notes=hidden")
        ),
        r#"%(k = "footnote"; up = "footnotes")"#
    );
    // another word is refused, and the option on a bare file
    for (source, told) in [
        (
            format!("p=text:{md}?notes=all"),
            "notes=all — notes= takes mounted or hidden (a note stands outside the tree by default)",
        ),
        (
            format!("p=corpus:{md}?notes=all"),
            "corpus: notes=all — notes= takes mounted or hidden",
        ),
        (
            format!("p=lit:{tei}?notes=all"),
            "lit: notes=all — notes= takes mounted or hidden",
        ),
        (
            format!("p=koine:{md}?notes=all"),
            "notes=all — notes= takes mounted or hidden",
        ),
        (
            format!("p={md}?notes=mounted"),
            "unknown option \"notes=mounted\"",
        ),
    ] {
        let (ok, _, err) = qua_full(&["/p/* | :name", &source]);
        assert!(!ok && err.contains(told), "{source}: {err}");
    }
    let _ = std::fs::remove_dir_all(&dir);
}

/// `:::offset` counts the bytes of the FILE (the user's words of
/// 2026-11-27: "Offset is typically byte position (zero-based)";
/// "that can be extremely useful for finding the location using other
/// tools"). The reader's place is the file's where the file is UTF-8
/// as read; past a byte-order mark it counts the mark; where the file
/// was decoded from another encoding it answers null, as it does
/// where the reader knows no place (HTML, plain text). A folder's
/// leaf answers as the file alone does.
#[test]
fn an_offset_counts_the_bytes_of_the_file() {
    let dir = std::env::temp_dir().join(format!("quarb-offset-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("shelf")).unwrap();
    let write = |name: &str, bytes: &[u8]| std::fs::write(dir.join(name), bytes).unwrap();
    let wrath = "# The Wrath\n\nSing, goddess[^1], the wrath.\n\n[^1]: The Muse is meant.\n";
    write("shelf/wrath.md", wrath.as_bytes());
    write(
        "shelf/wrath.tex",
        b"\\section{Wrath}\n\nSing, goddess\\footnote{The Muse.}, the wrath.\n",
    );
    write(
        "shelf/wrath.html",
        b"<html><body><h1>Wrath</h1><p>Sing, goddess.</p></body></html>\n",
    );
    write("shelf/wrath.txt", b"Sing, goddess, the wrath.\n");
    // (a byte-order mark; Cyrillic in UTF-8; the same in another
    // encoding)
    write(
        "marked.md",
        "\u{feff}# The Wrath\n\nSing, goddess.\n".as_bytes(),
    );
    let gnev = "# Гнев\n\nГнев, богиня, воспой.\n";
    write("gnev.md", gnev.as_bytes());
    let cp1251: Vec<u8> = gnev
        .chars()
        .map(|c| match c {
            'А'..='я' => (c as u32 - 0x410 + 0xC0) as u8,
            c => c as u8,
        })
        .collect();
    write("gnev-1251.md", &cp1251);
    let said = |query: &str, source: &str| {
        let (ok, out, err) = qua_full(&[query, &format!("{}/{source}", dir.display())]);
        assert!(ok, "{query} {source}: {err}");
        assert_eq!(err.trim(), "", "{query} {source}");
        out.trim().replace('\n', " ")
    };
    let said_of = |query: &str, reading: &str, source: &str| {
        let (ok, out, err) = qua_full(&[query, &format!("{reading}:{}/{source}", dir.display())]);
        assert!(ok, "{query} {reading}:{source}: {err}");
        out.trim().replace('\n', " ")
    };
    let _ = said;
    const PLACES: &str = "//* | %(:name; o = :::offset)";
    for reading in ["text", "corpus"] {
        assert_eq!(
            said_of("//section | %(o = :::offset)", reading, "shelf/wrath.md"),
            "%(o = 0)",
            "{reading}"
        );
        assert_eq!(
            said_of("//paragraph | %(o = :::offset)", reading, "shelf/wrath.md"),
            "%(o = 13)",
            "{reading}"
        );
        // the callout: 13 characters into its paragraph, byte 26 of
        // the file
        assert_eq!(
            said_of(
                "//*<noteref> | ->footnote | %(at = $-::at; off = $-::offset)",
                reading,
                "shelf/wrath.md"
            ),
            "%(at = 13; off = 26)",
            "{reading}"
        );
        assert_eq!(
            said_of("//paragraph | %(o = :::offset)", reading, "shelf/wrath.tex"),
            "%(o = 17)",
            "{reading}"
        );
    }
    assert_eq!(&wrath[26..30], "[^1]");
    // a reader that knows no place
    assert_eq!(
        said_of("//paragraph | %(o = :::offset)", "text", "shelf/wrath.html"),
        "%(o = null)"
    );
    assert_eq!(
        said_of("//paragraph | %(o = :::offset)", "text", "shelf/wrath.txt"),
        "%(o = null)"
    );
    // the mark is counted; another encoding has no place to give
    assert_eq!(
        said_of(PLACES, "text", "marked.md"),
        r#"%(name = "section"; o = 3) %(name = "paragraph"; o = 16)"#
    );
    assert_eq!(
        said_of(PLACES, "text", "gnev.md"),
        r#"%(name = "section"; o = 0) %(name = "paragraph"; o = 12)"#
    );
    assert_eq!(
        said_of(PLACES, "text", "gnev-1251.md?encoding=windows-1251"),
        r#"%(name = "section"; o = null) %(name = "paragraph"; o = null)"#
    );
    // a folder's leaves, each as its file alone
    assert_eq!(
        said_of(
            "/* | %(:name; o = (//paragraph[1]:::offset))",
            "text",
            "shelf"
        ),
        r#"%(name = "wrath.html"; o = null) %(name = "wrath.md"; o = 13) %(name = "wrath.tex"; o = 17) %(name = "wrath.txt"; o = null)"#
    );
    let _ = std::fs::remove_dir_all(&dir);
}

/// A folder's leaves and an office file take the mount's options, as
/// a file read alone does ("every document of a folder mount alike").
/// Under `text:DIR` the Markdown, HTML and plain leaves were read by
/// the composing layer itself and took none: `?notes=mounted` and
/// `?references=` passed them by. An office file is read from its
/// bytes by a road that took none either: `text:article.odt
/// ?references=...`, the Readings' own example of the option with a
/// .docx, lowered no reference. Both on 0.74.0 too.
#[test]
fn a_folders_leaves_and_an_office_file_take_the_mounts_options() {
    let dir = std::env::temp_dir().join(format!("quarb-leaves-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("shelf")).unwrap();
    let refs = "# Sources\n\nThe frame is Austen [1]; the war is Homer [2].\n\n## References\n\n\
                1. Austen, Jane. Emma. London: John Murray, 1815.\n\
                2. Homer. The Iliad. Translated by Samuel Butler. London: Longmans, 1898.\n";
    std::fs::write(dir.join("shelf/refs.md"), refs).unwrap();
    std::fs::write(
        dir.join("shelf/wrath.md"),
        "# The Wrath\n\nSing, goddess[^1], the wrath.\n\n[^1]: The Muse is meant.\n",
    )
    .unwrap();
    std::fs::write(
        dir.join("shelf/wrath.html"),
        "<html><body><h1>Wrath</h1><p>Sing, goddess<a epub:type=\"noteref\" \
         href=\"#n1\">1</a>.</p><aside epub:type=\"footnote\" id=\"n1\"><p>The Muse.</p>\
         </aside></body></html>\n",
    )
    .unwrap();
    std::fs::write(
        dir.join("shelf/wrath.tex"),
        "\\section{Wrath}\n\nSing, goddess\\footnote{The Muse.}, the wrath.\n",
    )
    .unwrap();
    let said = |query: &str, source: &str| {
        let (ok, out, err) = qua_full(&[query, source]);
        assert!(ok, "{query} {source}: {err}");
        assert_eq!(err.trim(), "", "{query} {source}");
        out.trim().replace('\n', " ")
    };
    let shelf = format!("text:{}/shelf", dir.display());
    // by default no leaf holds a note in its tree
    assert_eq!(
        said("/* | %(:name; notes = (//footnote @| count))", &shelf),
        r#"%(name = "refs.md"; notes = 0) %(name = "wrath.html"; notes = 0) %(name = "wrath.md"; notes = 0) %(name = "wrath.tex"; notes = 0)"#
    );
    // mounted: each document that has notes carries its own
    // `footnotes`, the folder none
    assert_eq!(
        said(
            "/* | %(:name; notes = (/footnotes/footnote @| count))",
            &format!("{shelf}?notes=mounted")
        ),
        r#"%(name = "refs.md"; notes = 0) %(name = "wrath.html"; notes = 1) %(name = "wrath.md"; notes = 1) %(name = "wrath.tex"; notes = 1)"#
    );
    assert_eq!(
        said("/footnotes @| count", &format!("{shelf}?notes=mounted")),
        "0"
    );
    // the reference list of one leaf
    assert_eq!(
        said(
            "/* | %(:name; bibs = (//bib @| count); cits = (//cit @| count))",
            &format!("{shelf}?references=cmos")
        ),
        r#"%(name = "refs.md"; bibs = 2; cits = 2) %(name = "wrath.html"; bibs = 0; cits = 0) %(name = "wrath.md"; bibs = 0; cits = 0) %(name = "wrath.tex"; bibs = 0; cits = 0)"#
    );
    // an office file: the same text as an OpenDocument
    let odt = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../quarb-text-odt/tests/fixtures/refs.odt"
    );
    assert_eq!(said("//bib @| count", &format!("text:{odt}")), "0");
    assert_eq!(
        said("//bib[2] | %", &format!("text:{odt}?references=cmos")),
        r#"%(onym = "2"; auctor = "Homer"; titulus = "The Iliad"; locus = "London"; officina = "Longmans"; annus = "1898")"#
    );
    assert_eq!(
        said("//cit @| count", &format!("text:{odt}?references=cmos")),
        "2"
    );
    let _ = std::fs::remove_dir_all(&dir);
}

fn qua_full(args: &[&str]) -> (bool, String, String) {
    let out = std::process::Command::new(env!("CARGO_BIN_EXE_qua"))
        .env("QUARB_LOCALE", "C")
        .args(args)
        .stdin(std::process::Stdio::null())
        .output()
        .unwrap();
    (
        out.status.success(),
        String::from_utf8(out.stdout).unwrap(),
        String::from_utf8(out.stderr).unwrap(),
    )
}

/// A leaf whose declared identity the reading knows but whose import
/// it refuses stays a document: its declared fields answer null and
/// the refusal rides into --diagnostics=info, so one unreadable file does not
/// refuse the shelf. The same file mounted alone is refused with the
/// reason. An `.xml` declaring no identity the readings know is left
/// to the default grafting, its markup as a DOM.
#[test]
fn an_unreadable_leaf_answers_null_with_the_reason_in_explain() {
    let dir = std::env::temp_dir().join(format!("quarb-letters-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("good.xml"),
        r#"<TEI xmlns="http://www.tei-c.org/ns/1.0">
<text><body>
<div type="chapter"><head>The fence</head>
<p>Tom painted the fence.</p>
<p>Ben watched.</p></div>
</body></text></TEI>"#,
    )
    .unwrap();
    // An inline the importer does not take (atrep is strict by the
    // user's rule: litogramma says what it can say and refuses the
    // rest): `<sub>`, as some Tolstoy Digital letters carry it.
    std::fs::write(
        dir.join("bad.xml"),
        r#"<TEI xmlns="http://www.tei-c.org/ns/1.0">
<teiHeader><fileDesc><titleStmt><title>A letter</title></titleStmt></fileDesc></teiHeader>
<text><body><p>Dear friend, H<sub>2</sub>O.</p></body></text></TEI>"#,
    )
    .unwrap();
    std::fs::write(
        dir.join("plain.xml"),
        "<things><p>no identity declared</p></things>\n",
    )
    .unwrap();
    for level in ["text", "corpus", "lit"] {
        let mount = format!("{level}:{}", dir.display());
        // the paragraphs of the readable TEI, none from the refused
        // leaf, none from the undeclared markup
        assert_eq!(qua(&["//paragraph @| count", &mount]), "2\n", "{level}");
        // the refused leaf is a document with nothing under it
        assert_eq!(
            qua(&[r#"//*[:name = "bad.xml"]//* @| count"#, &mount]),
            "0\n",
            "{level}"
        );
        assert_eq!(
            qua(&[r#"//*[:name = "bad.xml"] | %(::lemma)"#, &mount]),
            "%(lemma = null)\n",
            "{level}"
        );
        // the shelf still lists it
        assert_eq!(
            qua(&["/* | :name", &mount]),
            "bad.xml\ngood.xml\nplain.xml\n",
            "{level}"
        );
        // the reason rides into --diagnostics=info, and only there
        let (ok, out, err) = qua_full(&["--diagnostics=info", "//paragraph @| count", &mount]);
        assert!(ok && out == "2\n", "{level}: {out} {err}");
        assert!(
            err.contains("bad.xml") && err.contains("answer null") && err.contains("sub"),
            "{level}: {err}"
        );
        let (_, _, err) = qua_full(&["//paragraph @| count", &mount]);
        assert!(!err.contains("answer null"), "{level}: {err}");
        // mounted alone, the same file is refused with the reason
        let (ok, _, err) = qua_full(&[
            "//paragraph @| count",
            &format!("{level}:{}", dir.join("bad.xml").display()),
        ]);
        assert!(!ok && err.contains("sub"), "{level}: {err}");
    }
    // the undeclared markup keeps its DOM under text:
    assert_eq!(
        qua(&["//p::", &format!("text:{}", dir.display())]),
        "no identity declared\n"
    );
    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn the_plan_prices_the_files_the_folder_exposes() {
    // The reader honours an ignore file and skips hidden entries;
    // the plan and the budget count the same files, so a folder's
    // bound does not depend on what its ignored caches hold.
    let dir = std::env::temp_dir().join(format!("quarb-planned-shelf-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("raw")).unwrap();
    std::fs::write(dir.join("a.txt"), "one paragraph\n").unwrap();
    std::fs::write(dir.join("raw/b.txt"), "sub paragraph, longer\n").unwrap();
    std::fs::write(dir.join(".gitignore"), "raw/\n").unwrap();
    let mount = format!("text:{}", dir.display());
    assert_eq!(qua(&["//paragraph @| count", &mount]), "1\n");
    let plan = qua(&["--plan", "//paragraph @| count", &mount]);
    assert!(plan.contains("bytes-min=14\n"), "{plan}");
    assert!(plan.contains("bytes-max=14\n"), "{plan}");
    // A budget the exposed file fits runs; the ignored one is not
    // priced against it.
    assert_eq!(
        qua(&["--budget", "bytes=20", "//paragraph @| count", &mount]),
        "1\n"
    );
    let (ok, _, err) = qua_full(&["--budget", "bytes=10", "//paragraph @| count", &mount]);
    assert!(!ok && err.contains("14 bytes"), "{err}");
    // Mounted with the ignore file set aside, both read and plan
    // take the subtree; shown hidden, the ignore file itself.
    assert_eq!(qua(&["--no-ignore", "//paragraph @| count", &mount]), "2\n");
    let plan = qua(&["--no-ignore", "--plan", "//paragraph @| count", &mount]);
    assert!(plan.contains("bytes-min=36\n"), "{plan}");
    let plan = qua(&[
        "--no-ignore",
        "--hidden",
        "--plan",
        "//paragraph @| count",
        &mount,
    ]);
    assert!(plan.contains("bytes-min=41\n"), "{plan}");
    let _ = std::fs::remove_dir_all(&dir);
}