wickra-terminal-core 0.2.0

Data-driven core of the Wickra trading terminal: sources, O(1) state and panels that emit view-models.
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
//! The configs and commands in the documentation are the ones the code accepts.
//!
//! Every broken example this repository has shipped was broken the same way: a
//! snippet written once, correct at the time or not, and never executed again.
//! The README's Python example omitted a field the config required and used a
//! command shape the deserialiser rejected; the cookbook's TOML used `;` as a
//! statement separator, which TOML has no concept of. Both looked fine.
//!
//! So this reads the snippets out of the markdown rather than restating them: a
//! test carrying its own copy of an example only proves the copy is right.

use std::fs;
use std::path::{Path, PathBuf};

use wickra_terminal_core::{Config, SourceSpec, Terminal};

/// The documents whose examples must work.
const DOCS: [&str; 8] = [
    "README.md",
    "ARCHITECTURE.md",
    "docs/INDICATORS.md",
    "docs/Cookbook.md",
    "docs/PANELS.md",
    "docs/RENDERERS.md",
    "docs/SOURCES.md",
    "docs/STREAMING.md",
];

/// The eight binding READMEs, which are also the registry landing pages:
/// `PyPI`, `npm`, `NuGet`, Maven Central, `pkg.go.dev` and r-universe render
/// them as the first thing a user of that language reads.
///
/// They are not in [`DOCS`], and adding them there would be decorative: each
/// embeds its config and commands inside a language snippet -- a Python string,
/// a Go raw literal, an escaped C string -- so a guard that reads fenced JSON
/// blocks finds nothing in them. What they do carry uniformly is the command
/// table, which P11.13 had to correct by hand across all eight, and which is
/// checked below.
///
/// Eight for nine languages: C and C++ share `bindings/c/README.md`, because the
/// C++ surface is a header inside the C binding rather than a binding of its
/// own -- the same shape the indicator library uses.
const BINDING_READMES: [&str; 8] = [
    "bindings/c/README.md",
    "bindings/csharp/README.md",
    "bindings/go/README.md",
    "bindings/java/README.md",
    "bindings/node/README.md",
    "bindings/python/README.md",
    "bindings/r/README.md",
    "bindings/wasm/README.md",
];

/// The English word for a count, for the prose that states one.
///
/// A table rather than a `match`: every arm of a match over this range but the
/// live one would be a branch no test reaches, and the coverage gate reads an
/// unreached branch as untested code rather than as a spelling table. Indexing
/// panics on a count past the end, which is the right answer -- a boundary that
/// grew past twenty needs a sentence written for it, not a silent numeral.
const NUMBER_WORDS: [&str; 21] = [
    "zero",
    "one",
    "two",
    "three",
    "four",
    "five",
    "six",
    "seven",
    "eight",
    "nine",
    "ten",
    "eleven",
    "twelve",
    "thirteen",
    "fourteen",
    "fifteen",
    "sixteen",
    "seventeen",
    "eighteen",
    "nineteen",
    "twenty",
];

/// The repository root, found by walking up from this crate.
fn repo_root() -> PathBuf {
    let mut dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    for _ in 0..8 {
        if dir.join("README.md").is_file() && dir.join("docs").is_dir() {
            return dir;
        }
        dir = dir
            .parent()
            .unwrap_or_else(|| panic!("no repository root above {}", env!("CARGO_MANIFEST_DIR")))
            .to_path_buf();
    }
    panic!("no repository root found");
}

/// Every fenced block of one language in a markdown file.
fn fenced_blocks(markdown: &str, language: &str) -> Vec<String> {
    let open = format!("```{language}");
    let mut blocks = Vec::new();
    let mut current: Option<String> = None;
    for line in markdown.lines() {
        match current {
            None if line.trim() == open => current = Some(String::new()),
            None => {}
            Some(_) if line.trim() == "```" => {
                blocks.push(current.take().unwrap_or_default());
            }
            Some(ref mut body) => {
                body.push_str(line);
                body.push('\n');
            }
        }
    }
    blocks
}

fn read(root: &Path, rel: &str) -> String {
    fs::read_to_string(root.join(rel)).unwrap_or_else(|err| panic!("{rel}: {err}"))
}

#[test]
fn every_documented_toml_config_parses() {
    let root = repo_root();
    let mut checked = 0;
    for rel in DOCS {
        for (index, block) in fenced_blocks(&read(&root, rel), "toml").iter().enumerate() {
            Config::from_toml(block)
                .unwrap_or_else(|err| panic!("{rel} toml block {index} does not parse: {err}"));
            checked += 1;
        }
    }
    assert!(checked > 0, "no TOML config examples found to check");
}

#[test]
fn every_documented_json_config_parses() {
    let root = repo_root();
    let mut checked = 0;
    for rel in DOCS {
        for (index, block) in fenced_blocks(&read(&root, rel), "json").iter().enumerate() {
            // A block may hold a config, a command, or an example response. Only
            // the configs are checked here; the commands have their own test and
            // a response is not an input at all.
            let Ok(value) = serde_json::from_str::<serde_json::Value>(block) else {
                continue;
            };
            let Some(object) = value.as_object() else {
                continue;
            };
            if !object.contains_key("sources") && !object.contains_key("indicators") {
                continue;
            }
            Config::from_json(block).unwrap_or_else(|err| {
                panic!("{rel} json block {index} is not a valid config: {err}")
            });
            checked += 1;
        }
    }
    assert!(checked > 0, "no JSON config examples found to check");
}

#[test]
fn every_documented_command_is_accepted() {
    let root = repo_root();
    // A fresh terminal per block, not per file. Each fenced block is a
    // self-contained scenario -- one of them adds a source and then addresses it
    // by id -- so replaying every block against one terminal would shift those
    // ids and fail the documentation for being read the way it is written.
    let dataset =
        fs::read_to_string(root.join("golden/replay/basic.json")).expect("the golden replay feed");

    let mut checked = 0;
    for rel in DOCS {
        for (index, block) in fenced_blocks(&read(&root, rel), "json").iter().enumerate() {
            let commands: Vec<&str> = block
                .lines()
                .map(str::trim)
                .filter(|line| line.starts_with('{'))
                .filter(|line| {
                    serde_json::from_str::<serde_json::Value>(line)
                        .ok()
                        .and_then(|v| {
                            v.get("type")
                                .and_then(serde_json::Value::as_str)
                                .map(str::to_string)
                        })
                        .is_some()
                })
                .collect();
            if commands.is_empty() {
                continue;
            }

            // Source 0 is a Replay, because the documented commands include
            // `Seek` and only a replayable source accepts it.
            let mut config = Config::default_layout();
            config.sources = vec![SourceSpec::Replay {
                dataset: dataset.clone(),
            }];
            let mut terminal = Terminal::new(&config).expect("the default config must build");
            terminal
                .command_json(r#"{"type":"Subscribe","source":0,"symbol":"BTC/USDT"}"#)
                .expect("subscribe");

            for command in commands {
                terminal.command_json(command).unwrap_or_else(|err| {
                    panic!(
                        "{rel} block {index} documents a command the terminal rejects:
  {command}
  {err}"
                    )
                });
                checked += 1;
            }
        }
    }
    assert!(checked > 0, "no command examples found to check");
}

/// Documents that state how many indicators this terminal reaches.
///
/// Every bare occurrence of the number in these files carries a marker, because
/// the guard is only worth as much as its coverage: three of these documents
/// used to state the count in prose outside any marker, so the test passed while
/// six sites were free to rot.
const COUNTED: [&str; 6] = [
    "README.md",
    "ARCHITECTURE.md",
    "docs/INDICATORS.md",
    "ROADMAP.md",
    "BENCHMARKS.md",
    "docs/STREAMING.md",
];

#[test]
fn the_documented_indicator_count_is_the_real_one() {
    // The indicator library keeps its counts in step with a workflow that
    // rewrites them on every push. This repository has no such workflow, and the
    // count is the single most load-bearing number in its README — it was 514
    // while the core wired two. A marker rather than a loose regular expression
    // because the README also cites the library's own 514 and a sibling
    // project's, and only this terminal's own figure should move with the
    // registry.
    let root = repo_root();
    let actual = wickra_terminal_core::registry::DEFAULTS.len().to_string();

    for rel in COUNTED {
        let text = read(&root, rel);
        let mut found = 0;
        let mut rest = text.as_str();
        while let Some(start) = rest.find(OPEN) {
            let after = &rest[start + OPEN.len()..];
            let end = after
                .find(CLOSE)
                .unwrap_or_else(|| panic!("{rel}: an indicator-count marker is not closed"));
            let claimed = &after[..end];
            assert_eq!(
                claimed, actual,
                "{rel} claims {claimed} indicators; the registry has {actual}"
            );
            found += 1;
            rest = &after[end + CLOSE.len()..];
        }
        // Per file rather than a total: a document that lost its marker used to
        // be masked by another that had gained one.
        assert!(found > 0, "{rel} states no indicator count in a marker");
    }
}

/// The count of indicators wickra-core holds that this terminal cannot reach.
///
/// Not derivable from the registry, which only knows what it registered, so the
/// documents state it and this checks the arithmetic instead: unreachable plus
/// registered must be the library's total. A regeneration that reaches further
/// moves both numbers, and a stale one is caught here rather than by a reader.
#[test]
fn the_unreachable_indicator_count_adds_up() {
    const LIBRARY_TOTAL: usize = 504;
    let root = repo_root();
    // Reachable, not registered. Six of the library's indicators answer with a
    // histogram rather than a reading, so they are carried by the profile
    // surface instead of the registry -- reachable from the terminal all the
    // same, and counting them as unreachable would be a lie in the other
    // direction.
    let registered = wickra_terminal_core::registry::DEFAULTS.len()
        + wickra_terminal_core::registry::PROFILES.len();
    let needle = format!(" of the {LIBRARY_TOTAL}");
    let mut checked = 0;

    for rel in ["docs/INDICATORS.md", "ROADMAP.md"] {
        let text = read(&root, rel);
        for (idx, _) in text.match_indices(&needle) {
            let claimed: usize = text[..idx]
                .rsplit(|c: char| !c.is_ascii_digit())
                .find(|word| !word.is_empty())
                .unwrap_or_else(|| panic!("{rel}: no number before \"{needle}\""))
                .parse()
                .unwrap_or_else(|err| panic!("{rel}: {err}"));
            assert_eq!(
                claimed + registered,
                LIBRARY_TOTAL,
                "{rel} says {claimed} unreachable and the terminal reaches {registered},                  which is not the {LIBRARY_TOTAL} the library ships"
            );
            checked += 1;
        }
    }
    assert!(checked > 0, "no unreachable-count claim found to check");
}

/// `CITATION.cff` states the count in prose, and nothing checked it.
///
/// It cannot carry the marker the other documents use: that marker is an HTML
/// comment, and this is YAML whose abstract is rendered verbatim by GitHub's
/// "Cite this repository" widget and by Zenodo. So the phrase itself is the
/// anchor. It had drifted to 457 while the registry held 455, which is the whole
/// reason the other six documents are guarded rather than trusted.
#[test]
fn the_citation_abstract_states_the_real_indicator_count() {
    // Anchored on the phrase alone, not on the line break before it: the
    // abstract is a folded YAML scalar, so where it wraps is a formatting
    // detail and the count sits on the other side of it.
    const PHRASE: &str = "the Wickra indicators are constructible";

    let root = repo_root();
    let text = read(&root, "CITATION.cff");
    let actual = wickra_terminal_core::registry::DEFAULTS.len().to_string();

    let before = text
        .split(PHRASE)
        .next()
        .unwrap_or_else(|| panic!("CITATION.cff no longer says \"{PHRASE}\""));
    assert_ne!(
        before, text,
        "CITATION.cff no longer states an indicator count"
    );
    let claimed: String = before
        .chars()
        .rev()
        .skip_while(|c| !c.is_ascii_digit())
        .take_while(char::is_ascii_digit)
        .collect::<String>()
        .chars()
        .rev()
        .collect();
    assert_eq!(
        claimed, actual,
        "CITATION.cff claims {claimed} indicators; the registry has {actual}"
    );
}

/// The first released section of the changelog, as `(version, date)`.
///
/// `## [Unreleased]` carries no date and is skipped by the same pattern that
/// finds a release: a released heading is `## [x.y.z] - YYYY-MM-DD`.
fn released_in_changelog(root: &std::path::Path) -> Option<(String, String)> {
    read(root, "CHANGELOG.md").lines().find_map(|line| {
        let rest = line.strip_prefix("## [")?;
        let (version, rest) = rest.split_once("] - ")?;
        let date = rest.trim();
        (date.len() == 10 && date.starts_with("20"))
            .then(|| (version.to_string(), date.to_string()))
    })
}

/// `version` and `date-released` say exactly one thing, and it has to be true.
///
/// They are what GitHub's citation box and Zenodo present as the thing being
/// cited, so carrying them against zero releases dates something that never
/// happened — which is why this file omitted both. The other side is just as
/// real: once a release exists, a citation without them cites nothing in
/// particular, and both keys are release touchpoints nobody would remember on
/// their own.
///
/// So the rule is the pairing rather than either half of it. While the changelog
/// shows no released section both keys must be absent; the moment one is cut,
/// both must be present and agree with it. Cutting a release therefore fails
/// here until the citation is brought along, rather than shipping a stale one.
#[test]
fn the_citation_matches_the_release_state() {
    let root = repo_root();
    let text = read(&root, "CITATION.cff");
    // Line-anchored: `cff-version:` is the schema version and belongs here.
    let value_of = |key: &str| -> Option<String> {
        text.lines()
            .find(|line| line.starts_with(key))?
            .split_once(':')
            .map(|(_, v)| v.trim().trim_matches('"').to_string())
    };

    match released_in_changelog(&root) {
        None => {
            for key in ["version:", "date-released:"] {
                assert!(
                    value_of(key).is_none(),
                    "CITATION.cff carries {key}, which cites a release that does not exist"
                );
            }
        }
        Some((version, date)) => {
            assert_eq!(
                value_of("version:").as_deref(),
                Some(version.as_str()),
                "CHANGELOG released {version}; CITATION.cff does not cite it"
            );
            assert_eq!(
                value_of("date-released:").as_deref(),
                Some(date.as_str()),
                "CHANGELOG dates the release {date}; CITATION.cff does not"
            );
        }
    }
}

/// The README's performance table and `BENCHMARKS.md` state the same numbers.
///
/// Both are published claims about how fast this is, measured once and written
/// twice. A re-measurement that updated one and not the other would leave the
/// repository asserting two speeds for the same path -- and the README is the
/// one a reader meets first, so it is the one that would be believed.
///
/// The pairs are matched by their measurement rather than by their wording: the
/// two tables describe the same benchmark in different words on purpose, one for
/// a reader choosing the project and one for a reader running the suite.
#[test]
fn the_readme_and_the_benchmark_page_agree_on_the_numbers() {
    let root = repo_root();
    let readme = read(&root, "README.md");
    let bench = read(&root, "BENCHMARKS.md");

    // Row by row from the benchmark page, which is the one measured against.
    let rows: Vec<(String, String)> = bench
        .lines()
        .filter(|line| line.starts_with("| `"))
        .filter_map(|line| {
            let cells: Vec<&str> = line.split('|').map(str::trim).collect();
            // | name | what | median | throughput |
            (cells.len() >= 6).then(|| (cells[3].to_owned(), cells[4].to_owned()))
        })
        .filter(|(median, _)| median.ends_with("ns") || median.ends_with("\u{b5}s"))
        .collect();
    assert!(
        rows.len() >= 5,
        "found only {rows:?} measured rows in BENCHMARKS.md"
    );

    let mut checked = 0;
    for (median, throughput) in rows {
        // The last row is the no-boundary comparison, which the README does not
        // carry: it exists to make two numbers on that page comparable, not to
        // describe the product.
        if !readme.contains(&median) {
            continue;
        }
        assert!(
            readme.contains(&format!("| {median} | {throughput} |")),
            "the README pairs {median} with a throughput BENCHMARKS.md does not: {throughput}"
        );
        checked += 1;
    }
    assert!(
        checked >= 5,
        "only {checked} of the benchmark rows reached the README"
    );
}

/// The documented bounds are the constants the code actually uses.
///
/// Those numbers are a contract a reader plans a layout around -- how much a
/// panel carries by default, and how much is behind it to scroll to. They are
/// written once in the source and again in the table, and this repository has
/// already watched the indicator count, the binding command tables and the fuzz
/// target list drift the same way.
///
/// The constants are `pub(crate)`, so they are read out of the source rather
/// than imported: making them public to be testable would be the test dictating
/// the API, which is the reasoning `every_binding_readme_documents_every_command`
/// gives for reading the `Command` enum the same way.
#[test]
fn the_documented_bounds_are_the_real_ones() {
    /// The value of a `const NAME: usize = N;` in the given source.
    fn constant(source: &str, name: &str) -> usize {
        let needle = format!("const {name}: usize = ");
        let at = source
            .find(&needle)
            .unwrap_or_else(|| panic!("{name} is gone or was renamed"));
        source[at + needle.len()..]
            .split(';')
            .next()
            .and_then(|value| value.trim().parse().ok())
            .unwrap_or_else(|| panic!("{name} is no longer a plain number"))
    }

    let root = repo_root();
    let panels = read(&root, "crates/wickra-terminal-core/src/panels/mod.rs");
    let state = read(&root, "crates/wickra-terminal-core/src/state.rs");
    let doc = read(&root, "docs/PANELS.md");

    let depth = constant(&panels, "DEFAULT_DEPTH");
    let points = constant(&panels, "CHART_POINTS");
    let bars_kept = constant(&state, "OHLC_HISTORY");
    let prices_kept = constant(&state, "PRICE_HISTORY");
    let levels_kept = constant(&state, "MAX_FOOTPRINT_LEVELS");
    let alt_kept = constant(&state, "ALT_BARS_KEPT");
    // `TAPE_ROWS` is written in terms of `DEFAULT_DEPTH`, which is the point:
    // the tape carries twice what a ladder does because it is a stream rather
    // than a snapshot.
    assert!(
        panels.contains("const TAPE_ROWS: usize = DEFAULT_DEPTH * 2;"),
        "TAPE_ROWS is no longer twice the default depth"
    );
    let tape_rows = depth * 2;

    // `docs/STREAMING.md` restates the same ceilings in prose, which is a second
    // copy of every number above and drifts the same way.
    let streaming = read(&root, "docs/STREAMING.md");
    let pending = constant(
        &read(&root, "crates/wickra-terminal-core/src/source/manual.rs"),
        "MAX_PENDING_EVENTS",
    );
    let series = constant(&state, "INDICATOR_SERIES");
    let tape_kept = constant(&state, "TAPE_PRINTS_KEPT");
    for claim in [
        format!("the tape ring at {tape_kept} prints"),
        format!("the price history at {prices_kept}"),
        format!("each indicator's series at {series}"),
        format!("the footprint at {levels_kept:} price levels").replace("1024", "1,024"),
        format!("pending queue at {pending} events").replace("4096", "4,096"),
    ] {
        assert!(
            streaming.contains(&claim),
            "docs/STREAMING.md does not say {claim:?}"
        );
    }

    for claim in [
        format!("| `chart` | {points} bars, {points} price points"),
        format!("{bars_kept} bars kept, {prices_kept} price points"),
        format!("| `book` | {depth} levels a side"),
        format!("| `tape` | {tape_rows} prints | {tape_kept} kept"),
        format!("| `footprint` | {depth} levels | {levels_kept} levels kept"),
        format!("| `bars` | {depth} bars a stream | {alt_kept} kept"),
    ] {
        assert!(
            doc.contains(&claim),
            "docs/PANELS.md does not say {claim:?}"
        );
    }
}

/// Every fuzz target is named in the threat model, and every name is a target.
///
/// The threat model lists what is fuzzed as one of the guarantees the code is
/// held to, and nothing checked the list against the directory. It had drifted
/// both ways: it named four of the five targets and mapped two of the four to
/// the wrong one. The target it omitted, `registry_drive`, is the one that found
/// a real fault -- an indicator period of 10^20 that aborted the process.
///
/// A promise about what is tested is worth exactly what checks it.
#[test]
fn every_fuzz_target_is_named_in_the_threat_model() {
    let root = repo_root();
    let model = read(&root, "THREAT_MODEL.md");
    let manifest = read(&root, "fuzz/Cargo.toml");

    let dir = root.join("fuzz/fuzz_targets");
    let mut targets: Vec<String> = std::fs::read_dir(&dir)
        .expect("fuzz/fuzz_targets is readable")
        .flatten()
        .filter_map(|entry| {
            let path = entry.path();
            (path.extension()? == "rs").then(|| path.file_stem()?.to_str().map(str::to_owned))?
        })
        .collect();
    targets.sort();
    assert!(
        targets.len() >= 5,
        "found only {targets:?} in fuzz/fuzz_targets"
    );

    for target in &targets {
        assert!(
            model.contains(&format!("`{target}`")),
            "THREAT_MODEL.md does not name the {target} fuzz target"
        );
        // A target the manifest does not build is a file cargo-fuzz never runs,
        // which the threat model would then be crediting for nothing.
        assert!(
            manifest.contains(&format!("fuzz_targets/{target}.rs")),
            "fuzz/Cargo.toml does not build the {target} target"
        );
    }

    // And nothing named there that does not exist: a list that outlives its
    // targets claims coverage the repository has stopped having.
    for line in model
        .lines()
        .filter(|line| line.trim_start().starts_with('|'))
    {
        let Some(name) = line.split('`').nth(1) else {
            continue;
        };
        if name.ends_with("_parse")
            || name.ends_with("_event")
            || name.ends_with("_fold")
            || name.ends_with("_model")
            || name.ends_with("_drive")
        {
            assert!(
                targets.iter().any(|target| target == name),
                "THREAT_MODEL.md names a {name} fuzz target that does not exist"
            );
        }
    }
}

/// Every command the READMEs promise is driven by at least one binding suite.
///
/// `every_binding_readme_documents_every_command` below checks the promise is
/// complete. Nothing checked it was kept, and that is exactly how four commands
/// came to be documented in nine READMEs and executed by no binding at all:
/// `SetRecording` and `ExportRecording` by none, `ReplayPosition` only by the C
/// example, `FeedDerivatives` by none. The recorder had never run outside Rust
/// while nine pages described how to use it.
///
/// One suite, not all of them. Holding every command to every language would
/// fail for reasons that are not defects -- the two suites that carry no JSON
/// dependency read answers by matching on the wire form, and some commands are
/// only sensible against a source kind another suite happens to use. What must
/// never be true again is a command that nine pages document and nothing
/// anywhere runs.
#[test]
fn every_documented_command_is_driven_by_a_binding_suite() {
    /// Where a binding proves its reach.
    ///
    /// `examples/c` is the C hub's suite: it is run by ctest in the `c-abi`
    /// job, which is why it counts. `golden/commands` counts for a different
    /// reason -- the scenarios there are driven by all nine suites through the
    /// manifest, so a command in a scenario file is executed in nine languages
    /// even though it appears in no suite's source. Leaving it out reported
    /// `AddSource`, `RemoveSource`, `SetFocus`, `Unsubscribe` and
    /// `SetTimeframe` as undriven, which is the opposite of true: they are the
    /// best-covered commands there are.
    const SUITE_DIRS: [&str; 9] = [
        "bindings/python/tests",
        "bindings/node/__tests__",
        "bindings/wasm/tests",
        "bindings/go",
        "bindings/csharp/WickraTerminal.Tests",
        "bindings/java/src/test/java/org/wickra/terminal",
        "bindings/r/tests",
        "examples/c",
        "golden/commands",
    ];

    let root = repo_root();
    let commands = command_variants(&root);
    // A floor, not the count. `every_binding_readme_documents_every_command`
    // pins the exact number, and a second copy of it here is a second place to
    // forget -- which is what happened the first time a command was added after
    // this test was written. All this needs is the assurance that the parse
    // found an enum at all.
    assert!(
        commands.len() >= 16,
        "the command enum parsed as {commands:?}, which is not the enum"
    );

    // Read once: eight directories against sixteen names is a hundred and
    // twenty-eight scans of the same files otherwise.
    let mut haystack = String::new();
    for dir in SUITE_DIRS {
        let path = root.join(dir);
        let entries =
            std::fs::read_dir(&path).unwrap_or_else(|err| panic!("{dir} is not readable: {err}"));
        for entry in entries.flatten() {
            if entry.path().is_file() {
                if let Ok(text) = std::fs::read_to_string(entry.path()) {
                    haystack.push_str(&text);
                }
            }
        }
    }
    assert!(
        haystack.len() > 10_000,
        "the suites read as {} bytes, which is not the suites",
        haystack.len()
    );

    let undriven: Vec<&str> = commands
        .iter()
        .copied()
        .filter(|name| !haystack.contains(&format!("\"{name}\"")))
        .collect();
    assert!(
        undriven.is_empty(),
        "documented in every binding README and driven by no binding suite: {undriven:?}"
    );
}

/// The `Command` variants, read out of the source.
///
/// `Command` is private -- it is an implementation detail of the JSON boundary,
/// and making it public to be testable would be the test dictating the API.
fn command_variants(root: &std::path::Path) -> Vec<&'static str> {
    let source = read(root, "crates/wickra-terminal-core/src/terminal.rs");
    let start = source
        .find("enum Command {")
        .expect("the Command enum moved or was renamed");
    let body = &source[start..];
    let body = &body[..body
        .find(
            "
}",
        )
        .expect("an unterminated enum")];

    // One variant per line at four spaces of indent, which is how the enum is
    // written; deeper indents are a variant's fields.
    body.lines()
        .skip(1)
        .filter_map(|line| {
            let rest = line.strip_prefix("    ")?;
            if rest.starts_with(' ') || !rest.starts_with(char::is_uppercase) {
                return None;
            }
            let name = rest
                .split(|c: char| !c.is_alphanumeric() && c != '_')
                .next()
                .unwrap_or_default();
            (!name.is_empty()).then(|| Box::leak(name.to_owned().into_boxed_str()) as &'static str)
        })
        .collect()
}

/// The command table in every binding README lists exactly the commands that
/// exist.
///
/// These tables are the API reference for eight registries, and they had already
/// drifted once: P11.13 corrected all eight by hand, with nothing to stop the
/// next drift. A command added to the core and not to the tables is undocumented
/// in eight places at once; one removed leaves eight pages describing something
/// that now errors.
///
/// The variants are read out of the source because `Command` is private -- it is
/// an implementation detail of the JSON boundary, and making it public to be
/// testable would be the test dictating the API.
#[test]
fn every_binding_readme_documents_every_command() {
    let root = repo_root();
    let source = read(&root, "crates/wickra-terminal-core/src/terminal.rs");
    let start = source
        .find("enum Command {")
        .expect("the Command enum moved or was renamed");
    let body = &source[start..];
    let body = &body[..body
        .find(
            "
}",
        )
        .expect("an unterminated enum")];

    // One variant per line at four spaces of indent, which is how the enum is
    // written; deeper indents are a variant's fields.
    let variants: Vec<&str> = body
        .lines()
        .skip(1)
        .filter_map(|line| {
            let rest = line.strip_prefix("    ")?;
            if rest.starts_with(' ') || !rest.starts_with(char::is_uppercase) {
                return None;
            }
            Some(
                rest.split(|c: char| !c.is_alphanumeric() && c != '_')
                    .next()
                    .unwrap_or_default(),
            )
        })
        .filter(|name| !name.is_empty())
        .collect();
    assert_eq!(
        variants.len(),
        19,
        "expected nineteen commands, found {variants:?}"
    );

    for rel in BINDING_READMES {
        let text = read(&root, rel);
        // The command table specifically, found by its header: these READMEs
        // carry other tables whose first cell is also backticked, and reading
        // those made this reject a correct page.
        let after_header = text
            .split_once("| Command | Effect |")
            .unwrap_or_else(|| panic!("{rel} has no command table"))
            .1;
        let table: String = after_header
            .lines()
            .skip(1)
            .take_while(|line| line.starts_with('|'))
            .collect::<Vec<_>>()
            .join("\n");
        assert!(!table.is_empty(), "{rel}'s command table is empty");

        for variant in &variants {
            assert!(
                table.contains(&format!("`{variant}`")),
                "{rel} does not document the {variant} command"
            );
        }

        // The sentence above the table, and not only the table. The prose said
        // "thirteen" -- the number of table ROWS -- while the table below it
        // carried all nineteen commands, because a row groups the commands that
        // belong together (`Subscribe` / `Unsubscribe`, and three panel
        // commands on one line). Every check above passed the whole time, in
        // nine READMEs at once, and a reader takes the count from the sentence
        // rather than by counting rows. `golden/README.md` said nineteen
        // throughout, so the repository contradicted itself in public.
        let spelled = NUMBER_WORDS[variants.len()];
        assert!(
            text.contains(&format!("the same {spelled} commands")),
            "{rel} does not say it drives {spelled} commands"
        );

        // And nothing the core does not have: a table row for a command that was
        // renamed or removed reads as an API that exists.
        //
        // Only the first cell, which is the command column. The description
        // beside it backticks other things -- `Manual` is a source kind, not a
        // command -- and reading those made this reject a correct table.
        for row in table.lines() {
            let command_cell = row.split('|').nth(1).unwrap_or_default();
            for name in command_cell.split('`').skip(1).step_by(2) {
                assert!(
                    variants.contains(&name),
                    "{rel} documents {name}, which is not a command"
                );
            }
        }
    }
}

const OPEN: &str = "<!--indicator-count-->";
const CLOSE: &str = "<!--/indicator-count-->";

#[test]
fn benchmarks_md_lists_the_benchmarks_that_exist() {
    // BENCHMARKS.md described four benchmarks while three existed, and
    // contradicted itself two sections apart: four bullet points above, three
    // table rows below. Nobody reads a document against its own source, so this
    // does.
    let root = repo_root();
    let bench = fs::read_to_string(root.join("crates/wickra-terminal-bench/benches/terminal.rs"))
        .expect("the bench source");
    let doc = read(&root, "BENCHMARKS.md");

    let defined = names_between(&bench, "bench_function(\"", "\"");
    assert!(
        !defined.is_empty(),
        "no benchmarks found in the bench source"
    );

    let in_prose = names_between(&doc, "- **`", "`**");
    let in_table = names_between(
        &doc, "
| `", "`",
    );

    assert_eq!(
        in_prose, defined,
        "BENCHMARKS.md's prose and the bench source disagree"
    );
    assert_eq!(
        in_table, defined,
        "BENCHMARKS.md's results table and the bench source disagree"
    );
}

/// Every substring bracketed by `open` and `close`, as a sorted set.
fn names_between(text: &str, open: &str, close: &str) -> Vec<String> {
    let mut found = Vec::new();
    let mut rest = text;
    while let Some(start) = rest.find(open) {
        let after = &rest[start + open.len()..];
        let Some(end) = after.find(close) else { break };
        found.push(after[..end].to_string());
        rest = &after[end + close.len()..];
    }
    found.sort_unstable();
    found.dedup();
    found
}

/// The data rows of the markdown table whose header line is `header`.
fn table_rows<'a>(text: &'a str, header: &str) -> Vec<&'a str> {
    let start = text
        .find(header)
        .unwrap_or_else(|| panic!("no table headed {header}"));
    text[start..]
        .lines()
        .skip(1)
        .take_while(|line| line.starts_with('|'))
        .filter(|line| !line.trim_start_matches('|').trim_start().starts_with('-'))
        .collect()
}

/// The cell at `index` of a markdown row, trimmed.
fn cell(row: &str, index: usize) -> &str {
    row.split('|')
        .nth(index + 1)
        .unwrap_or_else(|| panic!("row has no cell {index}: {row}"))
        .trim()
}

/// `docs/INDICATORS.md` lists every input family the registry actually feeds.
///
/// The prose said "all four families" over a table of five, and stayed saying it
/// while four more were wired. A count in prose is not checkable, so the table
/// is checked instead, against the families the generator emitted.
#[test]
fn the_documented_input_families_are_the_registered_ones() {
    let text = read(&repo_root(), "docs/INDICATORS.md");
    let rows = table_rows(&text, "| Input | Fed with | Advances |");
    let documented: Vec<String> = rows
        .iter()
        .map(|row| cell(row, 0).replace(['`', ' '], ""))
        .collect();

    for family in wickra_terminal_core::registry::INPUT_FAMILIES {
        let key = family.replace(' ', "");
        assert!(
            documented
                .iter()
                .any(|row| row.ends_with(&format!("({key})")) || row == &key),
            "docs/INDICATORS.md lists no input family for {family}; it has {documented:?}"
        );
    }
    assert_eq!(
        documented.len(),
        wickra_terminal_core::registry::INPUT_FAMILIES.len(),
        "docs/INDICATORS.md lists {} input families, the registry feeds {}",
        documented.len(),
        wickra_terminal_core::registry::INPUT_FAMILIES.len()
    );
}

/// The reach table adds up, and every document citing its total agrees.
///
/// Only the registry row carries a marker, so the other three and the total were
/// bare numbers that nothing moved when a surface grew. The total is the number
/// this repository is judged by, which is exactly why it should not be a number
/// someone remembered to update.
#[test]
fn the_reach_table_sums_to_the_documented_total() {
    // The one indicator no surface fits: `Footprint` answers with price levels,
    // and the terminal renders it from its own state as the `footprint` panel.
    const FOOTPRINT: usize = 1;
    let root = repo_root();
    let profiles = wickra_terminal_core::registry::PROFILES.len();
    let bars = wickra_terminal_core::registry::BAR_TYPES.len();
    let total = wickra_terminal_core::registry::DEFAULTS.len() + profiles + bars + FOOTPRINT;

    let text = read(&root, "docs/INDICATORS.md");
    let rows = table_rows(&text, "| Surface | Count | What it answers with |");
    let mut summed = 0;
    for row in &rows {
        let surface = cell(row, 0);
        let claimed = cell(row, 1)
            .replace(OPEN, "")
            .replace(CLOSE, "")
            .parse::<usize>()
            .unwrap_or_else(|_| panic!("the {surface} row states no count"));
        let actual = match surface {
            "registry" => wickra_terminal_core::registry::DEFAULTS.len(),
            "profiles" => profiles,
            "alternative bars" => bars,
            "the `footprint` panel" => FOOTPRINT,
            other => panic!("unknown surface row {other}; teach this test what counts it"),
        };
        assert_eq!(
            claimed, actual,
            "the {surface} row claims {claimed}, there are {actual}"
        );
        summed += actual;
    }
    assert_eq!(summed, total, "the reach table covers {summed} of {total}");

    // Every document that states the total, stating it as bold digits and
    // nothing else, so the guard cannot be satisfied by an unrelated number.
    for rel in ["docs/INDICATORS.md", "README.md", "CHANGELOG.md"] {
        let text = read(&root, rel);
        let cited: Vec<&str> = text
            .match_indices("**")
            .filter_map(|(idx, _)| {
                let rest = &text[idx + 2..];
                let end = rest.find("**")?;
                let inner = &rest[..end];
                inner.chars().all(|c| c.is_ascii_digit()).then_some(inner)
            })
            .collect();
        assert!(!cited.is_empty(), "{rel} states no reach total");
        for claim in cited {
            assert_eq!(claim, total.to_string(), "{rel} claims a reach of {claim}");
        }
    }
}

/// Every panel the core can emit is one the web renderer knows how to draw.
///
/// The core is where the list lives, so this is where the guard belongs. Two
/// panels — `Profile` and `Bars` — were added to `PanelKind`, given view-models,
/// given TUI widgets, and never taught to the web renderer. The core emitted
/// them in every frame; `findPanel` never asked for them; they vanished without
/// an error anywhere. ARCHITECTURE.md says adding a panel here makes it appear
/// in every renderer at once, and for those two it was not true.
///
/// Nothing else could have caught it. The golden corpus compares frames, which
/// were correct. The web suite tests the mappings it has. A panel a renderer has
/// simply never heard of has no test to fail.
///
/// Checked in three places, because each is a separate way to drop a panel: the
/// `PanelKind` union (the layout would place nothing), the `PanelView` union
/// (`findPanel` would not type-check against it), and a section in the template
/// (the placement exists and draws nothing).
/// Every action the shared keymap can bind reaches one renderer or the other on
/// purpose, and none of them is silently inert.
///
/// `layout.keybinds` sits in the config precisely so a rebinding moves both
/// front-ends, which makes a bound action that no renderer answers the worst
/// shape available: the key looks configured, the config validates, and nothing
/// happens. `remove_source` and `save_recording` were exactly that in the
/// browser -- bound in the default keymap, answered by the TUI, and dropped into
/// `runAction`'s catch-all.
///
/// Three are deliberately unanswered in the browser and are named here rather
/// than inferred, so adding a fourth is a decision someone writes down:
/// `quit`, because a tab is not the terminal's to close, and the panel-focus and
/// scroll pairs, because a web panel is a scrollable box the browser drives.
#[test]
fn every_bound_action_reaches_a_renderer() {
    /// Answered by the TUI alone, each for a reason a browser cannot argue with.
    ///
    /// `quit`, because a tab is not the terminal's to close. The scroll pair,
    /// because a web panel is a scrollable box the browser already drives. The
    /// panel-focus pair, because focus is a renderer's own idea and the browser
    /// does not have one -- and `remove_panel` and `move_panel` go with it for
    /// exactly that reason: with no focused panel there is nothing for them to
    /// act on, and a key that removed an arbitrary panel would be worse than a
    /// key that does nothing. The browser removes with the `x` on the panel
    /// itself, which names its target by sitting on it.
    const BROWSER_DECLINES: [&str; 7] = [
        "quit",
        "next_panel",
        "prev_panel",
        "scroll_up",
        "scroll_down",
        "remove_panel",
        "move_panel",
    ];

    let root = repo_root();
    let input_rs = read(&root, "crates/ui-tui/src/input.rs");
    let app_vue = read(&root, "web/src/App.vue");
    let binds = wickra_terminal_core::config::Keybinds::default();
    assert!(
        binds.bindings.len() >= 19,
        "the default keymap shrank to {} actions",
        binds.bindings.len()
    );

    for action in binds.bindings.keys() {
        assert!(
            input_rs.contains(&format!("Some(\"{action}\")")),
            "crates/ui-tui/src/input.rs: {action:?} is bound and the TUI keymap resolves it to nothing"
        );
        if BROWSER_DECLINES.contains(&action.as_str()) {
            continue;
        }
        assert!(
            app_vue.contains(&format!("case '{action}'")),
            "web/src/App.vue: {action:?} is bound and runAction drops it into the catch-all"
        );
    }
}

#[test]
fn every_panel_kind_reaches_the_web_renderer() {
    let root = repo_root();
    let panels_rs = read(&root, "crates/wickra-terminal-core/src/panels/mod.rs");
    let types_ts = read(&root, "web/src/types.ts");
    let app_vue = read(&root, "web/src/App.vue");

    // The variants of `enum PanelKind`, read from the enum itself rather than
    // restated here — a list this test carried its own copy of would go stale
    // in exactly the way the bug did.
    let body = panels_rs
        .split_once("pub enum PanelKind {")
        .and_then(|(_, rest)| rest.split_once("\n}"))
        .map(|(body, _)| body)
        .expect("panels/mod.rs declares enum PanelKind");
    let kinds: Vec<&str> = body
        .lines()
        .map(str::trim)
        .filter_map(|line| line.strip_suffix(','))
        .filter(|name| {
            name.chars().next().is_some_and(char::is_uppercase)
                && name.chars().all(char::is_alphanumeric)
        })
        .collect();
    assert!(kinds.len() >= 7, "found only {kinds:?} in PanelKind");

    for kind in kinds {
        let tag = kind.to_lowercase();
        assert!(
            types_ts.contains(&format!("'{kind}'")),
            "web/src/types.ts: PanelKind has no {kind}, so the layout places nothing for it"
        );
        assert!(
            types_ts.contains(&format!("panel: '{tag}'")),
            "web/src/types.ts: PanelView has no {tag} variant, so the frame's is discarded"
        );
        assert!(
            app_vue.contains(&format!("placements.{kind}")),
            "web/src/App.vue: no section for {kind}, so it is placed and never drawn"
        );
    }
}