radio-cli 0.14.1

A lightweight terminal radio and podcast player
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
//! Crate-internal property-based tests covering historical bugs across:
//! - D1: `clean_text` grapheme cap & ASCII fast-path parity, ICY Latin-1/GBK/UTF-8 repair,
//!   recording filename `NAME_MAX <= 255` UTF-8 bounds
//! - D2: URL validation & control-char rejection, credential redaction & idempotence,
//!   directory host anti-spoofing, recording space saturation & bitrate precedence
//! - D3: `validate_page` pagination & 200k catalog boundary
//! - D4: Chinese territory code lookup (>= 2-char rule, aliases, locale fallback)
//! - D5: RSS/Atom feed parsing (chunk-split UTF-8 BOM, Atom `type`, `<source>` scoping,
//!   `<published>` vs `<updated>` order independence), RadioInfo XML multi-table &
//!   strict attribute validation, OPML empty-element nesting & dedup
//! - D6: `publish_noclobber` 6-case matrix, `open_private_directory` & `open_nofollow_nonblock`
//! - D8: `append_error_tail` UTF-8 bounds & HLS/HTTP reconnect line classification
//! - D11: Progressive v2 checkpoint torn-tail recovery & `MAX_WINDOW_INDEX` overflow guard
//! - D12: `ipc_socket_path` `sun_path` length bound

use crate::prop;

use crate::{
    clean_text, config, directory, files, messages::Locale, player, podcast, recorder, redact,
    speech::Segment, territories,
};
use prop::{check, gen_ascii_ident, gen_unicode};
use rand::Rng;
use reqwest::Url;
use std::{
    collections::BTreeSet,
    fs,
    io::{BufReader, Read},
    os::unix::fs::PermissionsExt,
    path::PathBuf,
    time::Duration,
};
use unicode_segmentation::UnicodeSegmentation;

/// Covers D1 (`48223c4`) — `clean_text` strips all controls, caps at <= 1024 scalars,
/// ends on a whole grapheme boundary, is idempotent, and ASCII fast-path matches slow path.
#[test]
fn prop_clean_text_grapheme_and_control_invariants() {
    check(
        "clean_text_invariants",
        300,
        |rng, case| {
            if case == 0 {
                // Multi-scalar ZWJ clusters crossing the 1024 scalar boundary.
                format!("{}👨\u{200d}👩\u{200d}👧tail", "a".repeat(1022))
            } else if case == 1 {
                "a".repeat(1200)
            } else {
                let n = rng.random_range(0..=160);
                gen_unicode(rng, n)
            }
        },
        |input| {
            let out = clean_text(input);
            if out.chars().any(char::is_control) {
                return Err(format!("control char remained in clean_text: {out:?}"));
            }
            if out.chars().count() > 1024 {
                return Err(format!("exceeded 1024 scalars: {}", out.chars().count()));
            }
            if clean_text(&out) != out {
                return Err("clean_text is not idempotent".into());
            }
            // Reference slow-path oracle matching UAX #29 spec.
            let mut oracle = String::new();
            let mut count = 0usize;
            for g in input.graphemes(true) {
                if g.chars().next().is_none_or(char::is_control) {
                    continue;
                }
                count += g.chars().count();
                if count > 1024 {
                    break;
                }
                oracle.push_str(g);
            }
            if out != oracle {
                return Err(format!("fast/slow clean_text mismatch on {input:?}"));
            }
            Ok(())
        },
    );
}

/// Covers D2 (`20a906d`, `4b6514b`) + B5 (control-char URL validation, zero-alloc secret_name,
/// nested-URL scoping, redaction idempotence).
#[test]
fn prop_redact_urls_and_validate_url_security() {
    check(
        "redact_urls_zero_leak_and_idempotence",
        250,
        |rng, case| {
            let secret = format!("SEC{}RET", gen_ascii_ident(rng, 4, 10));
            let host = format!("{}.example.test", gen_ascii_ident(rng, 3, 8));
            let param = [
                "token",
                "api_key",
                "Access%5FToken",
                "password",
                "sig",
                "auth",
                "x-amz-signature",
                "secret",
            ][rng.random_range(0..8)];
            let mode = if case < 4 {
                case as u8
            } else {
                rng.random_range(0..5)
            };
            (secret, host, param.to_owned(), mode)
        },
        |(secret, host, param, mode)| {
            let url = match mode {
                0 => format!("https://user:{secret}@{host}/stream.mp3"),
                1 => format!("https://{host}/live?{param}={secret}&fmt=aac"),
                2 => format!(
                    "https://{host}/proxy?next=https://inner.test/a?{param}={secret}&lang=en"
                ),
                3 => {
                    // B5 non-secret sibling param with '@' after nested URL must NOT false-positive.
                    let benign =
                        format!("https://{host}/cb?next=https://other.test&email=me@host.com");
                    if redact::has_url_credentials(&benign) {
                        return Err(format!("B5 false positive on {benign:?}"));
                    }
                    return Ok(());
                }
                _ => {
                    format!("error fetching http://{secret}:pw@{host}/x?{param}={secret} (timeout)")
                }
            };
            if !redact::has_url_credentials(&url) {
                return Err(format!("missed credentials in {url:?}"));
            }
            let redacted = redact::urls(&url);
            if redacted.contains(secret) {
                return Err(format!("secret {secret:?} leaked in {redacted:?}"));
            }
            if !redacted.contains(host) {
                return Err(format!("host {host:?} stripped from {redacted:?}"));
            }
            if redact::urls(&redacted) != redacted {
                return Err(format!("redact::urls not idempotent on {redacted:?}"));
            }
            Ok(())
        },
    );

    // B5: validate_url rejects ASCII control characters (\t, \r, \n, \0, \x1f) and non-http(s).
    check(
        "validate_url_rejects_controls_and_bad_schemes",
        200,
        |rng, case| {
            let ctrl = ['\t', '\r', '\n', '\0', '\x1b'][rng.random_range(0..5)];
            let host = format!("{}.example.test", gen_ascii_ident(rng, 2, 8));
            let kind = if case < 4 {
                case as u8
            } else {
                rng.random_range(0..4)
            };
            (ctrl, host, kind)
        },
        |(ctrl, host, kind)| {
            match kind {
                0 => {
                    let bad = format!("https://user{ctrl}:pass@{host}/a");
                    if config::validate_url(&bad).is_ok() {
                        return Err(format!("control char accepted in URL: {bad:?}"));
                    }
                }
                1 => {
                    let bad = format!("ht{ctrl}tps://{host}/stream");
                    if config::validate_url(&bad).is_ok() {
                        return Err(format!("control char in scheme accepted: {bad:?}"));
                    }
                }
                2 => {
                    let bad = format!("file:///{host}/a.mp3");
                    if config::validate_url(&bad).is_ok() {
                        return Err(format!("non-http scheme accepted: {bad:?}"));
                    }
                }
                _ => {
                    let good = format!("https://{host}/stream?q=1");
                    config::validate_url(&good)
                        .map_err(|e| format!("valid URL rejected: {good:?}: {e}"))?;
                }
            }
            Ok(())
        },
    );
}

/// Covers B6 (`directory::valid_directory_host`) + D3 (`177d1fe` `validate_page` exact bounds).
#[test]
fn prop_directory_host_validation_and_pagination_bounds() {
    check(
        "directory_host_anti_spoofing",
        200,
        |rng, case| {
            let label = gen_ascii_ident(rng, 1, 8);
            match case {
                0 => ("evil.example/.api.radio-browser.info".into(), false),
                1 => ("evil.example?.api.radio-browser.info".into(), false),
                2 => ("evil.example#.api.radio-browser.info".into(), false),
                3 => ("de1.api.radio-browser.info".into(), true),
                _ => {
                    if rng.random_bool(0.5) {
                        (format!("{label}.api.radio-browser.info"), true)
                    } else {
                        let spoof = match rng.random_range(0..6) {
                            0 => format!("{label}/.api.radio-browser.info"),
                            1 => format!("{label}?.api.radio-browser.info"),
                            2 => format!("{label}#.api.radio-browser.info"),
                            3 => format!("{label}@.api.radio-browser.info"),
                            4 => format!("{label}:80/.api.radio-browser.info"),
                            _ => format!("{label}.api.radio-browser.info.evil.com"),
                        };
                        (spoof, false)
                    }
                }
            }
        },
        |(host, expected)| {
            let valid_label = !host.starts_with('-') && !host.contains("--");
            let got = directory::valid_directory_host(host);
            if *expected && valid_label && !got {
                return Err(format!("valid directory host rejected: {host:?}"));
            }
            if !expected && got {
                return Err(format!("spoofed directory host accepted: {host:?}"));
            }
            Ok(())
        },
    );

    check(
        "directory_validate_page_bounds",
        300,
        |rng, case| match case {
            0 => (199_000usize, 1000usize),
            1 => (200_000, 0),
            2 => (200_000, 1),
            3 => (usize::MAX, 1),
            4 => (0, 1001),
            _ => (rng.random_range(0..=210_000), rng.random_range(0..=1100)),
        },
        |(offset, received)| {
            let ok = *received <= 1000 && offset.saturating_add(*received) <= 200_000;
            let got = directory::validate_page_for_test(*offset, *received).is_ok();
            if got != ok {
                return Err(format!("validate_page({offset}, {received})={got} != {ok}"));
            }
            Ok(())
        },
    );
}

/// Covers D1 (`953734f`, `6b56beb`, `f7e905b`, `5f7a573`, `ab39229`) +
/// D5 (`cef7c64`, `de87341`, `3b85366`, `87a184b`) — ICY GBK/Latin-1/UTF-8 repair,
/// raw IPC JSON parsing, and RadioInfo XML strictness.
#[test]
fn prop_player_icy_encoding_and_radioinfo_xml() {
    // Latin-1 mojibake UTF-8 round-trip (`953734f`) + GBK byte-run repair (`6b56beb`, `ab39229`).
    check(
        "player_icy_latin1_utf8_roundtrip",
        200,
        |rng, _| {
            let parts = [
                "上海爵士",
                "北京广播",
                "Café",
                "Björk",
                "Jazz 98.7",
                "你好世界",
            ];
            let n = rng.random_range(1..=3);
            (0..n)
                .map(|_| parts[rng.random_range(0..parts.len())])
                .collect::<Vec<_>>()
                .join(" - ")
        },
        |title| {
            // Re-encode UTF-8 bytes as Latin-1 scalars (simulating ICY ISO-8859-1 transport).
            let mojibake: String = title.as_bytes().iter().map(|&b| char::from(b)).collect();
            let recovered = player::icy_title(&mojibake);
            if recovered != *title {
                return Err(format!(
                    "Latin-1 round-trip failed: orig={title:?}, mojibake={mojibake:?}, got={recovered:?}"
                ));
            }
            // Idempotence on already-clean UTF-8 titles.
            if player::icy_title(title) != *title {
                return Err(format!("icy_title altered valid UTF-8: {title:?}"));
            }
            // Valid IPC JSON frame with embedded raw GBK/invalid bytes never fails to parse (`f7e905b`).
            let mut raw_ipc =
                br#"{"event":"property-change","name":"media-title","data":""#.to_vec();
            raw_ipc.extend_from_slice(&[0xc9, 0xcf, 0xba, 0xa3]); // GBK "上海"
            raw_ipc.extend_from_slice(br#""}"#);
            if player::parse_ipc_message_for_test(&raw_ipc).is_err() {
                return Err("parse_ipc_message dropped valid JSON with raw GBK bytes".into());
            }
            // Raw GBK bytes recover "上海" (`6b56beb`).
            let repaired = player::icy_title_bytes(&[0xc9, 0xcf, 0xba, 0xa3]);
            if repaired != "上海" {
                return Err(format!(
                    "GBK bytes failed to decode to 上海: got {repaired:?}"
                ));
            }
            Ok(())
        },
    );

    // RadioInfo XML multi-table isolation & strict attribute validation (`cef7c64`, `de87341`, `3b85366`, `87a184b`).
    check(
        "player_radioinfo_strict_xml",
        200,
        |rng, case| {
            let artist = gen_ascii_ident(rng, 2, 10);
            let song = gen_ascii_ident(rng, 2, 10);
            let mode = if case < 5 {
                case as u8
            } else {
                rng.random_range(0..5)
            };
            (artist, song, mode)
        },
        |(artist, song, mode)| {
            match mode {
                0 => {
                    // Valid single table extracts Artist - Title.
                    let xml = format!(
                        "<RadioInfo><Table><DB_DALET_ARTIST_NAME>{artist}</DB_DALET_ARTIST_NAME><DB_DALET_TITLE_NAME>{song}</DB_DALET_TITLE_NAME></Table></RadioInfo>"
                    );
                    let got = player::radioinfo_title_for_test(&xml);
                    if got.as_deref() != Some(format!("{artist} - {song}").as_str()) {
                        return Err(format!("valid RadioInfo failed: got {got:?}"));
                    }
                }
                1 => {
                    // Multi-table isolation: Table 1 has only song, Table 2 has artist -> must NOT borrow across tables (`de87341`).
                    let xml = format!(
                        "<RadioInfo><Table><DB_DALET_TITLE_NAME>{song}</DB_DALET_TITLE_NAME></Table><Table><DB_DALET_ARTIST_NAME>{artist}</DB_DALET_ARTIST_NAME></Table></RadioInfo>"
                    );
                    let got = player::radioinfo_title_for_test(&xml);
                    if got.as_deref() != Some(song.as_str()) {
                        return Err(format!("borrowed across <Table>: got {got:?}"));
                    }
                }
                2 => {
                    // Malformed attribute on trailing ignored element must reject (`3b85366`).
                    let xml = format!(
                        "<RadioInfo><Table><DB_DALET_TITLE_NAME>{song}</DB_DALET_TITLE_NAME></Table><Extra broken/></RadioInfo>"
                    );
                    if player::radioinfo_title_for_test(&xml).is_some() {
                        return Err("malformed trailing attribute accepted".into());
                    }
                }
                3 => {
                    // Literal unescaped '<' in attribute must reject (`87a184b`).
                    let xml = format!(
                        "<RadioInfo x=\"a<b\"><Table><DB_DALET_TITLE_NAME>{song}</DB_DALET_TITLE_NAME></Table></RadioInfo>"
                    );
                    if player::radioinfo_title_for_test(&xml).is_some() {
                        return Err("literal '<' in attribute accepted".into());
                    }
                }
                _ => {
                    // Escaped &lt; in attribute succeeds (`87a184b`).
                    let xml = format!(
                        "<RadioInfo x=\"a&lt;b\"><Table><DB_DALET_TITLE_NAME>{song}</DB_DALET_TITLE_NAME></Table></RadioInfo>"
                    );
                    if player::radioinfo_title_for_test(&xml).as_deref() != Some(song.as_str()) {
                        return Err("escaped &lt; in attribute wrongly rejected".into());
                    }
                }
            }
            Ok(())
        },
    );
}

/// Covers D4 (`59bb14d`, `2e2b4f8`, `00a93e9`) — Chinese territory matching >=2 chars,
/// short aliases, and locale fallback precedence.
#[test]
fn prop_territories_matching_and_locale_fallback() {
    check(
        "territories_single_char_and_fallback",
        200,
        |rng, case| {
            let single = ["中", "国", "美", "日", "法", "a", "Z", " "][rng.random_range(0..8)];
            let code = ["CN", "HK", "MO", "TW", "US", "ZZ", ""][rng.random_range(0..7)];
            let upstream = if case % 2 == 0 { "UpstreamLand" } else { "" };
            (single.to_owned(), code.to_owned(), upstream.to_owned())
        },
        |(single, code, upstream)| {
            // `2e2b4f8`: 0- or 1-character queries NEVER match any territory codes.
            if territories::matching_codes(single).next().is_some() {
                return Err(format!("1-char query {single:?} widened to territories"));
            }
            // `00a93e9`: short aliases always resolve to canonical ISO codes.
            for (alias, iso) in [("香港", "HK"), ("澳门", "MO")] {
                if !territories::matching_prefix_codes(alias).any(|c| c == iso) {
                    return Err(format!("alias {alias} missed {iso}"));
                }
            }
            // `59bb14d`: English locale must never emit Chinese CLDR names; fallback preserves upstream.
            let en = territories::display_in(Locale::En, code, upstream);
            if en.chars().any(|c| ('\u{4e00}'..='\u{9fff}').contains(&c)) {
                return Err(format!("En locale emitted Chinese text: {en:?}"));
            }
            if code == "ZZ" && !upstream.is_empty() && !en.contains(upstream) {
                return Err(format!("unknown code dropped upstream name: got {en:?}"));
            }
            Ok(())
        },
    );
}

struct ChunkedReader<'a> {
    data: &'a [u8],
    pos: usize,
    chunk: usize,
}
impl Read for ChunkedReader<'_> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        if self.pos >= self.data.len() {
            return Ok(0);
        }
        let take = buf.len().min(self.chunk).min(self.data.len() - self.pos);
        buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]);
        self.pos += take;
        Ok(take)
    }
}

/// Covers D5 (`fab168a`, `c681d0f`, `410d849`, `49ecebb`, `4895ee0`) + B20 (duration bounds) —
/// Chunk-split UTF-8 BOM, Atom `type`, `<source>` isolation, `<published>` vs `<updated>` order,
/// and OPML nesting depth & order-preserving URL dedup.
#[test]
fn prop_podcast_feed_xml_bom_atom_and_opml() {
    let base = Url::parse("https://example.test/feed.xml").unwrap();

    // Chunk-split UTF-8 BOM (`49ecebb`), Atom text types (`fab168a`), <source> isolation (`c681d0f`),
    // and <published> vs <updated> order independence (`410d849`).
    check(
        "podcast_feed_atom_bom_and_scoping",
        150,
        |rng, _| {
            let chunk = rng.random_range(1..=7usize);
            let with_bom = rng.random_bool(0.6);
            let pub_first = rng.random_bool(0.5);
            let title_word = gen_ascii_ident(rng, 2, 10);
            let ep_id = gen_ascii_ident(rng, 3, 10);
            (chunk, with_bom, pub_first, title_word, ep_id)
        },
        |(chunk, with_bom, pub_first, word, ep_id)| {
            if ep_id.is_empty() {
                return Ok(());
            }
            let chunk = (*chunk).max(1);
            let dates = if *pub_first {
                "<published>2025-01-10T00:00:00Z</published><updated>2026-06-01T00:00:00Z</updated>"
            } else {
                "<updated>2026-06-01T00:00:00Z</updated><published>2025-01-10T00:00:00Z</published>"
            };
            let xml = format!(
                r#"<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title type="text">&lt;{word}&gt; Show</title>
  <entry>
    <id>{ep_id}</id>
    <title type="text">Ep &lt;{word}&gt;</title>
    {dates}
    <source>
      <id>foreign-source-id</id>
      <title>Foreign Source</title>
    </source>
    <link rel="enclosure" href="https://example.test/{ep_id}.mp3" type="audio/mpeg"/>
  </entry>
</feed>"#
            );
            let mut bytes = Vec::new();
            if *with_bom {
                bytes.extend_from_slice(&[0xef, 0xbb, 0xbf]);
            }
            bytes.extend_from_slice(xml.as_bytes());

            let full = podcast::parse_feed_for_test(&bytes, &base)
                .map_err(|e| format!("contiguous parse failed: {e}"))?;
            let chunked = podcast::parse_reader_for_test(
                BufReader::with_capacity(
                    chunk,
                    ChunkedReader {
                        data: &bytes,
                        pos: 0,
                        chunk,
                    },
                ),
                &base,
            )
            .map_err(|e| format!("chunked(chunk={chunk}) parse failed: {e}"))?
            .ok_or_else(|| "chunked parse returned None".to_owned())?;

            if full.feed.title != format!("<{word}> Show") {
                return Err(format!(
                    "Atom type=text stripped literal <...>: {:?}",
                    full.feed.title
                ));
            }
            if full.episodes.len() != 1 || full.episodes[0].guid.as_deref() != Some(ep_id.as_str())
            {
                return Err("Atom <source><id> leaked into entry".into());
            }
            if full.episodes[0].published.as_deref() != Some("2025-01-10T00:00:00+00:00") {
                return Err(format!(
                    "Atom <published> lost precedence to <updated>: {:?}",
                    full.episodes[0].published
                ));
            }
            if chunked.feed.title != full.feed.title
                || chunked.episodes.len() != full.episodes.len()
                || chunked.episodes[0].guid != full.episodes[0].guid
            {
                return Err("chunk-split BOM parse diverged from contiguous parse".into());
            }
            Ok(())
        },
    );

    // OPML empty-element depth & order-preserving URL dedup (`4895ee0`).
    check(
        "podcast_opml_depth_and_dedup",
        100,
        |rng, case| {
            let depth = match case {
                0 => 63usize,
                1 => 64,
                2 => 65,
                _ => rng.random_range(1..=68),
            };
            let n_urls = rng.random_range(1..=8usize);
            let urls: Vec<String> = (0..n_urls)
                .map(|_| format!("https://example.test/f{}.xml", rng.random_range(0..4)))
                .collect();
            (depth, urls)
        },
        |(depth, urls)| {
            let mut xml = String::from("<opml version=\"2.0\"><body>");
            // Open `depth - 2` nested outlines (total depth including <opml><body> is `depth`).
            let extra = depth.saturating_sub(2);
            for i in 0..extra {
                xml.push_str(&format!("<outline text=\"g{i}\">"));
            }
            for u in urls {
                // Include trailing '/' inside attribute and space before '/>' (`4895ee0`).
                xml.push_str(&format!("<outline text=\"a/\" xmlUrl=\"{u}\" />"));
            }
            for _ in 0..extra {
                xml.push_str("</outline>");
            }
            xml.push_str("</body></opml>");
            let parsed = podcast::opml_for_test(xml.as_bytes());
            if *depth > 64 {
                if parsed.is_ok() {
                    return Err(format!("OPML depth {depth} > 64 was accepted"));
                }
            } else {
                let got = parsed.map_err(|e| format!("valid OPML depth {depth} failed: {e}"))?;
                let mut expected = Vec::new();
                for u in urls {
                    if !expected.contains(u) {
                        expected.push(u.clone());
                    }
                }
                if got != expected {
                    return Err(format!(
                        "OPML dedup order mismatch: {got:?} != {expected:?}"
                    ));
                }
            }
            Ok(())
        },
    );
}

/// Covers D6/D8 (`c984825`, `f3f8f42`, `36bc4bd`, `8438c4c`) —
/// `publish_noclobber` 6-case matrix & `open_private_directory` security invariants.
#[test]
fn prop_files_noclobber_and_private_directory_security() {
    let dir = tempfile::tempdir().unwrap();
    // 1. Missing destination succeeds and moves partial.
    let p1 = dir.path().join("p1.part");
    let f1 = dir.path().join("f1.mp3");
    fs::write(&p1, b"audio1").unwrap();
    files::publish_noclobber(&p1, &f1).unwrap();
    assert!(!p1.exists() && fs::read(&f1).unwrap() == b"audio1");

    // 2. Same-inode hardlink (resumed crash between hard_link and unlink) succeeds (`f3f8f42`).
    let p2 = dir.path().join("p2.part");
    let f2 = dir.path().join("f2.mp3");
    fs::write(&p2, b"audio2").unwrap();
    fs::hard_link(&p2, &f2).unwrap();
    files::publish_noclobber(&p2, &f2).unwrap();
    assert!(!p2.exists() && fs::read(&f2).unwrap() == b"audio2");

    // 3. Distinct file with identical bytes is NEVER overwritten (`f3f8f42`).
    let p3 = dir.path().join("p3.part");
    let f3 = dir.path().join("f3.mp3");
    fs::write(&p3, b"same").unwrap();
    fs::write(&f3, b"same").unwrap();
    assert!(files::publish_noclobber(&p3, &f3).is_err());
    assert!(p3.exists() && fs::read(&f3).unwrap() == b"same");

    // 4. Symlink at destination is NEVER overwritten (`36bc4bd`, `f3f8f42`).
    let p4 = dir.path().join("p4.part");
    let target = dir.path().join("target.mp3");
    let sym = dir.path().join("sym.mp3");
    fs::write(&p4, b"new").unwrap();
    fs::write(&target, b"victim").unwrap();
    std::os::unix::fs::symlink(&target, &sym).unwrap();
    assert!(files::publish_noclobber(&p4, &sym).is_err());
    assert_eq!(fs::read(&target).unwrap(), b"victim");

    // 5. Same path (p == f) rejects (`f3f8f42`).
    assert!(files::publish_noclobber(&f1, &f1).is_err());

    // `open_private_directory` (`8438c4c`): accepts only 0700 real directories.
    check(
        "open_private_directory_mode_matrix",
        64,
        |rng, case| match case {
            0 => 0o700u32,
            1 => 0o755,
            2 => 0o770,
            3 => 0o707,
            _ => 0o700 | (rng.random_range(0..=0o077u32)),
        },
        |mode| {
            let sub = dir.path().join(format!("priv_{mode:o}"));
            let _ = fs::remove_dir(&sub);
            fs::create_dir(&sub).unwrap();
            fs::set_permissions(&sub, fs::Permissions::from_mode(*mode)).unwrap();
            let ok = files::open_private_directory(&sub).is_ok();
            let expected = (*mode & 0o077) == 0;
            if ok != expected {
                return Err(format!(
                    "open_private_directory(mode={mode:o})={ok} != {expected}"
                ));
            }
            Ok(())
        },
    );
    // Symlink to a 0700 dir must still be rejected via O_NOFOLLOW.
    let good_dir = dir.path().join("good_0700");
    fs::create_dir(&good_dir).unwrap();
    fs::set_permissions(&good_dir, fs::Permissions::from_mode(0o700)).unwrap();
    let sym_dir = dir.path().join("sym_0700");
    std::os::unix::fs::symlink(&good_dir, &sym_dir).unwrap();
    assert!(files::open_private_directory(&sym_dir).is_err());
    assert!(files::open_nofollow_nonblock(&sym).unwrap().is_none());
}

/// Covers D1 (`8ee7301`), D2 (`dbb3f46`, `6aea445`), D8 (`9a69e83`, `21d7b13`, `3aa7709`),
/// D12 (`d9048d9`) — Filename UTF-8 `NAME_MAX <= 255`, space estimate overflow & precedence,
/// stderr tail UTF-8 safety, and IPC socket `sun_path <= 100` bound.
#[test]
fn prop_recorder_filenames_space_stderr_and_socket_path() {
    check(
        "recorder_filename_and_space_invariants",
        250,
        |rng, _| {
            let station = gen_unicode(rng, 40);
            let track = gen_unicode(rng, 60);
            let reserve_mb: u64 = if rng.random_bool(0.25) {
                u64::MAX / (1024 * 1024) + rng.random_range(0..10)
            } else {
                rng.random_range(0..=10_000)
            };
            let bitrate: u64 = if rng.random_bool(0.25) {
                u64::MAX
            } else {
                rng.random_range(0..=5_000_000)
            };
            let secs: u64 = rng.random_range(0..=86_400 * 30);
            (station, track, reserve_mb, bitrate, secs)
        },
        |(station, track, reserve_mb, bitrate, secs)| {
            // Filename components never exceed byte/char caps and never contain path separators/controls.
            let s_comp = recorder::test_hooks::filename_component(station, 40, 120);
            let t_comp = recorder::test_hooks::track_filename_component(track, 80);
            if s_comp.len() > 120 || s_comp.chars().count() > 40 {
                return Err(format!("station component exceeded cap: {s_comp:?}"));
            }
            if t_comp.len() > 80 || t_comp.chars().count() > 40 {
                return Err(format!("track component exceeded cap: {t_comp:?}"));
            }
            for c in s_comp.chars().chain(t_comp.chars()) {
                if c == '/' || c == '\\' || c == '\0' || c.is_control() {
                    return Err(format!("unsafe char {c:?} in filename component"));
                }
            }
            // Full filename stays <= 255 bytes even with ".json.tmp" sidecar suffix.
            let full_name = format!("20260101-000000-{s_comp}-{t_comp}-12345678.mp3.part");
            if full_name.len() + ".json.tmp".len() > 255 {
                return Err(format!(
                    "recording name exceeded NAME_MAX: {}",
                    full_name.len() + ".json.tmp".len()
                ));
            }
            // Space estimation never overflows and respects precedence audio > format > catalog (`6aea445`, `dbb3f46`).
            let info = serde_json::json!({
                "streams": [{"bit_rate": bitrate.to_string()}],
                "format": {"bit_rate": "64000"}
            });
            let (est1, known1) = recorder::test_hooks::required_space(
                *reserve_mb,
                128,
                &info,
                Some(Duration::from_secs(*secs)),
            );
            let (est2, _) = recorder::test_hooks::required_space(
                *reserve_mb,
                128,
                &info,
                Some(Duration::from_secs(secs.saturating_add(60))),
            );
            if est2 < est1 {
                return Err("required_space is not monotonic in duration".into());
            }
            if *bitrate > 0 && !known1 {
                return Err("positive stream bitrate should yield known estimate".into());
            }
            // Error tail stays valid UTF-8 and bounded to ERROR_TAIL_BYTES (`9a69e83`),
            // preserving `\t` and `\n` (`0be2f96`) while stripping other controls.
            let mut tail = String::new();
            for _ in 0..40 {
                recorder::test_hooks::append_error_tail(&mut tail, track);
            }
            if tail.len() > 8192 {
                return Err(format!("error tail exceeded 8192 bytes: {}", tail.len()));
            }
            if tail
                .chars()
                .any(|c| c.is_control() && c != '\n' && c != '\t')
            {
                return Err("disallowed control char remained in error tail".into());
            }
            // FFmpeg progress-line filter (`3aa7709`) never misclassifies reconnect markers.
            if recorder::test_hooks::recording_progress("Will reconnect at 123")
                || recorder::test_hooks::recording_progress("Failed to open segment 4")
                || !recorder::test_hooks::recording_progress("out_time_us=12345")
            {
                return Err("recording_progress misclassified FFmpeg stderr line".into());
            }
            Ok(())
        },
    );

    // `d9048d9`: ipc_socket_path falls back to temp dir whenever runtime_dir would exceed 100 bytes.
    check(
        "ipc_socket_path_sun_path_bound",
        100,
        |rng, _| rng.random_range(1..=160usize),
        |depth| {
            let dir = PathBuf::from(format!("/{}", "a".repeat(*depth)));
            let sock = player::ipc_socket_path_for_test(&dir);
            if sock.starts_with(&dir) && sock.as_os_str().len() > 100 {
                return Err(format!(
                    "socket path inside deep runtime_dir exceeded 100 bytes: {}",
                    sock.as_os_str().len()
                ));
            }
            Ok(())
        },
    );
}

/// Covers D11 (`2d8ee4c`) + B4 (`MAX_WINDOW_INDEX` u64 overflow guard) —
/// Torn-tail recovery at EVERY byte offset in v2 append-only progressive checkpoints.
#[test]
fn prop_progressive_checkpoint_torn_tail_and_window_bounds() {
    let dir = tempfile::tempdir().unwrap();
    let cfg = crate::test_support::config(dir.path());
    let ep = podcast::Episode {
        id: "ep-prop".into(),
        feed_id: "feed-prop".into(),
        title: "Test".into(),
        url: "https://example.test/ep.mp3".into(),
        ..Default::default()
    };

    // B4: MAX_WINDOW_INDEX overflow guard for extreme u64 positions.
    let max_idx = podcast::progressive::test_hooks::max_window_index();
    assert!(
        max_idx
            .checked_mul(15_000)
            .and_then(|v| v.checked_add(16_000))
            .is_some()
    );
    let mut full = BTreeSet::new();
    full.insert(max_idx);
    // Must not panic or wrap on u64::MAX position!
    let _ = podcast::progressive::test_hooks::next_window(full, Some(u64::MAX), u64::MAX);

    // Torn-tail crash recovery (`2d8ee4c`): truncating the last appended line at ANY byte offset
    // recovers the exact prefix of committed newline-terminated windows!
    let windows = vec![
        (
            0u64,
            None,
            vec![Segment {
                epoch: 0,
                start_ms: 0,
                end_ms: 5000,
                text: "first".into(),
            }],
        ),
        (
            1u64,
            None,
            vec![Segment {
                epoch: 0,
                start_ms: 15_000,
                end_ms: 20_000,
                text: "second".into(),
            }],
        ),
        (
            2u64,
            Some(45_000),
            vec![Segment {
                epoch: 0,
                start_ms: 30_000,
                end_ms: 35_000,
                text: "third".into(),
            }],
        ),
    ];
    let path =
        podcast::progressive::test_hooks::write_and_append_checkpoint(&cfg, &ep, &windows).unwrap();
    let full_bytes = fs::read(&path).unwrap();
    let last_nl = full_bytes[..full_bytes.len() - 1]
        .iter()
        .rposition(|&b| b == b'\n')
        .unwrap();
    for cut in (last_nl + 1)..full_bytes.len() {
        fs::write(&path, &full_bytes[..cut]).unwrap();
        let (got_windows, got_segs) = podcast::progressive::test_hooks::read_checkpoint(&cfg, &ep)
            .unwrap()
            .unwrap();
        assert_eq!(
            got_windows,
            BTreeSet::from([0u64, 1u64]),
            "torn tail at byte {cut} broke committed windows"
        );
        assert_eq!(got_segs.len(), 2);
    }
    // Restoring the complete final newline recovers all 3 windows.
    fs::write(&path, &full_bytes).unwrap();
    let (got_windows, got_segs) = podcast::progressive::test_hooks::read_checkpoint(&cfg, &ep)
        .unwrap()
        .unwrap();
    assert_eq!(got_windows, BTreeSet::from([0u64, 1u64, 2u64]));
    assert_eq!(got_segs.len(), 3);
}

/// Covers D3 (`efe76c6`, `7510412`, `3050754`) + B14 (`station_position` inside `read_snapshot`) —
/// WAL snapshot isolation under concurrent writes & exact rational shrink guard `4*new < 3*old`.
#[test]
fn prop_store_read_snapshot_and_shrink_policy() {
    use crate::{
        error::{DomainError, ErrorCode},
        model::{Filter, Sort, Station},
        store::Store,
    };

    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("radio.db");
    let mut store = Store::open(&path).unwrap();
    let store2 = Store::open(&path).unwrap();

    let rows: Vec<Station> = (0..100usize)
        .map(|i| Station {
            stationuuid: uuid::Uuid::from_u128(9000 + i as u128).to_string(),
            name: format!("Snap {i:03}"),
            url: format!("http://example.test/s/{i}"),
            clickcount: i as u64,
            votes: i as u64,
            active: true,
            ..Station::default()
        })
        .collect();
    store.begin_sync().unwrap();
    store.stage(&rows).unwrap();
    store.finish_sync().unwrap();

    // `efe76c6` + B14: `read_snapshot` isolates concurrent commits AND supports `station_position`!
    let target = rows[50].stationuuid.clone();
    let filter = Filter {
        sort: Sort::Votes,
        ..Filter::default()
    };
    let (before, pos, after) = store
        .read_snapshot(|s| {
            let before = s.search_count(&filter)?;
            let pos = s.station_position(&target, &filter)?;
            store2.upsert(&Station {
                stationuuid: uuid::Uuid::new_v4().to_string(),
                name: "New Concurrent".into(),
                url: "http://example.test/new".into(),
                active: true,
                custom: true,
                ..Station::default()
            })?;
            let after = s.search_count(&filter)?;
            Ok((before, pos, after))
        })
        .unwrap();
    assert_eq!(before, 100);
    assert_eq!(after, 100);
    assert_eq!(pos, Some(49));

    // Exact shrink guard `4 * new < 3 * old` evaluated inside publication lock (`7510412`, `3050754`).
    check(
        "store_shrink_threshold_exact_rational",
        40,
        |rng, case| match case {
            0 => 74usize,
            1 => 75,
            2 => 0,
            _ => rng.random_range(0..=100),
        },
        |new_count| {
            let prev_dir = store.directory_count().unwrap();
            store.begin_sync().unwrap();
            store.stage(&rows[..*new_count]).unwrap();
            let res = store.finish_sync_cancellable(
                || false,
                |s, count| {
                    let prev = s.directory_count()?;
                    Ok((prev > 0 && count * 4 < prev * 3)
                        .then(|| DomainError::new(ErrorCode::CatalogShrink)))
                },
            );
            let expected_err = if *new_count == 0 {
                Some(ErrorCode::EmptyCatalog)
            } else if prev_dir > 0 && *new_count * 4 < prev_dir * 3 {
                Some(ErrorCode::CatalogShrink)
            } else {
                None
            };
            match (expected_err, res) {
                (Some(code), Err(e))
                    if e.downcast_ref::<DomainError>().map(|d| d.code) == Some(code) => {}
                (None, Ok(_)) => {
                    // Restore 100 directory rows for subsequent cases.
                    store.begin_sync().unwrap();
                    store.stage(&rows).unwrap();
                    store.finish_sync().unwrap();
                }
                (exp, got) => {
                    return Err(format!(
                        "shrink mismatch prev={prev_dir} new={new_count} expected={exp:?} got={got:?}"
                    ));
                }
            }
            Ok(())
        },
    );
}