whisper-nvidia-cli 0.1.0

One-shot agent-native local NVIDIA GPU speech-to-text CLI powered by whisper.cpp
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
//! Persistable knobs. Flags win, then this file, then compiled seeds.

use std::collections::BTreeMap;
use std::path::Path;

use serde::{Deserialize, Serialize};

use crate::error::Error;
use crate::paths::AppPaths;

/// Official catalog origin. The single place the seed URL is written.
///
/// Every read goes through [`Store::effective`], so no verb repeats this
/// literal. Changing the official origin is a one-line change here.
pub const DEFAULT_ORIGIN_BASE: &str = "https://huggingface.co/ggerganov/whisper.cpp/resolve/main";

/// Accepted beam width. Shared by the flag check and the config check.
pub const BEAM_RANGE: std::ops::RangeInclusive<i32> = 1..=16;
/// Accepted VAD threshold.
pub const VAD_RANGE: std::ops::RangeInclusive<f32> = 0.0..=1.0;
/// Accepted parallel copies.
pub const CONCURRENCY_RANGE: std::ops::RangeInclusive<usize> = 1..=32;

/// Phrase the accepted range of a numeric key from the range itself.
///
/// The bounds used to be spelled by hand in five messages next to the very
/// constants that define them. Widening a range then left the advice quoting
/// the old limit, and an operator who obeys a stale hint is worse off than one
/// who gets none, because the hint is written to be followed.
pub fn range_message<T: std::fmt::Display>(
    key: &str,
    range: &std::ops::RangeInclusive<T>,
) -> String {
    format!("{key} must be {}..={}", range.start(), range.end())
}

/// Everything `model::download` needs, resolved once against the seeds.
///
/// Passing the whole set is what keeps configuration resolved in ONE place.
/// The alternative, letting `model` re-read the file for the keys the argument
/// list did not carry, produces a second resolution that cannot see the flags
/// the operator typed and can therefore disagree with the first.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DownloadKnobs {
    /// How many attempts a single download gets.
    pub retries: u32,
    /// Ceiling on the whole retry sequence, in seconds.
    pub max_elapsed_secs: u64,
    /// Ceiling on one attempt, in seconds.
    pub timeout_secs: u64,
    /// Base of the exponential backoff between attempts, in milliseconds.
    pub backoff_ms: u64,
    /// Proxy URL, or empty for a direct connection.
    pub proxy: String,
    /// Streaming buffer size, in bytes.
    pub io_chunk: usize,
}

/// Closed inventory of writable keys (FR-052).
pub const WRITABLE_KEYS: &[&str] = &[
    "model",
    "language",
    "device",
    "timeout",
    "timeout-grace",
    "max-duration",
    "beam",
    "vad",
    "concurrency",
    "helper",
    "helper-fallback",
    "max-memory",
    "locale",
    "origin-base",
    "download-retries",
    "retry-max-elapsed",
    "download-timeout",
    "download-backoff-ms",
    "http-proxy",
    "hallucination-filter",
    "hallucination-patterns",
    "log-level",
    "log-format",
    "log-timestamps",
    "vad-frame-ms",
    "vad-rms-min",
    "vad-rms-max",
    "resample-taps",
    "io-chunk-bytes",
    "probe-poll-ms",
    "helper-args",
    "nvidia-smi-path",
    "audio-extensions",
    "video-extensions",
    "content-keys",
];

/// Accepted energy window of the cut, in milliseconds.
///
/// The floor is 10 ms because a shorter window measures noise rather than
/// speech; the ceiling is 100 ms because beyond it a single frame straddles the
/// boundary between silence and a word and the cut lands in the middle of it.
pub const VAD_FRAME_MS_RANGE: std::ops::RangeInclusive<u32> = 10..=100;
/// Accepted RMS floor for either end of the sensitivity map.
pub const VAD_RMS_RANGE: std::ops::RangeInclusive<f32> = 0.0..=1.0;
/// Accepted tap count of the resampling filter. Odd counts keep it symmetric.
pub const RESAMPLE_TAPS_RANGE: std::ops::RangeInclusive<usize> = 3..=511;
/// Accepted streaming buffer size, in bytes.
pub const IO_CHUNK_RANGE: std::ops::RangeInclusive<usize> = 4096..=16_777_216;
/// Accepted child-process poll interval, in milliseconds.
pub const PROBE_POLL_RANGE: std::ops::RangeInclusive<u64> = 1..=1000;
/// Accepted base of the download retry backoff, in milliseconds.
pub const BACKOFF_RANGE: std::ops::RangeInclusive<u64> = 0..=60_000;
/// Accepted stderr verbosity names.
pub const LOG_LEVELS: &[&str] = &["off", "error", "warn", "info", "debug", "trace"];
/// Accepted stderr log shapes.
pub const LOG_FORMATS: &[&str] = &["text", "json"];

/// On-disk configuration. Absent keys mean "use seed".
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Store {
    /// Default whisper model name used when no `--model` flag is given.
    pub model: Option<String>,
    /// Default language code, or `auto` to let the engine detect it.
    pub language: Option<String>,
    /// Zero-based index of the GPU inference runs on.
    pub device: Option<u32>,
    /// Deadline for one run, in seconds. Zero disables the deadline.
    pub timeout: Option<u64>,
    /// Seconds the watchdog waits past `timeout` before forcing the exit.
    ///
    /// Two clocks own the same deadline: a cooperative one that stops between
    /// batch waves, finishes the pending lines and writes the summary FR-003
    /// owes, and a watchdog thread that exists for the case the cooperative one
    /// can never reach — a blocked stdin read or a stalled download. Given the
    /// same instant the watchdog always won, so a batch under `--timeout` ended
    /// with one bare 124 and no summary, and the cooperative path was dead code.
    ///
    /// The grace makes the watchdog the backstop it was meant to be. It is a
    /// policy, so it lives here rather than in the code.
    #[serde(rename = "timeout-grace")]
    pub timeout_grace: Option<u64>,
    /// Longest input accepted, in seconds. Longer audio fails closed.
    #[serde(rename = "max-duration")]
    pub max_duration: Option<f64>,
    /// Beam search width used for decoding, within [`BEAM_RANGE`].
    pub beam: Option<i32>,
    /// Voice-activity threshold used to split the audio, within [`VAD_RANGE`].
    pub vad: Option<f32>,
    /// Files transcribed in parallel in a batch, within [`CONCURRENCY_RANGE`].
    pub concurrency: Option<usize>,
    /// Path to an external decode helper. Empty means no helper.
    pub helper: Option<String>,
    /// Whether a failed helper run retries in-process instead of failing.
    #[serde(rename = "helper-fallback")]
    pub helper_fallback: Option<bool>,
    /// Cap on process memory, in bytes. Zero means no cap.
    #[serde(rename = "max-memory")]
    pub max_memory: Option<u64>,
    /// Locale tag for human-facing messages. Absent means detect from the host.
    pub locale: Option<String>,
    /// Base URL model downloads are resolved against. Must be `https://`.
    #[serde(rename = "origin-base")]
    pub origin_base: Option<String>,
    /// Retries attempted after a failed model download.
    #[serde(rename = "download-retries")]
    pub download_retries: Option<u32>,
    /// Total budget for a download and its retries, in seconds.
    #[serde(rename = "retry-max-elapsed")]
    pub retry_max_elapsed: Option<u64>,
    /// Per-request HTTP deadline for a model download, in seconds.
    #[serde(rename = "download-timeout")]
    pub download_timeout: Option<u64>,
    /// Base of the exponential backoff between download retries, in ms.
    #[serde(rename = "download-backoff-ms")]
    pub download_backoff_ms: Option<u64>,
    /// Proxy URL for model downloads. Empty means a direct connection.
    ///
    /// The usual answer, `HTTPS_PROXY`, is not one here: this product ignores
    /// environment variables, so without a key an operator behind a corporate
    /// proxy had no way at all to reach the model host.
    #[serde(rename = "http-proxy")]
    pub http_proxy: Option<String>,
    /// Whether the caption filter runs at all.
    #[serde(rename = "hallucination-filter")]
    pub hallucination_filter: Option<bool>,
    /// Regex alternatives for the caption filter, replacing the seeded list.
    ///
    /// This is the body of an alternation, not a comma-separated list: a regex
    /// may legitimately contain a comma, so any separator would have to be
    /// escaped and the escaping would then be the thing operators get wrong.
    #[serde(rename = "hallucination-patterns")]
    pub hallucination_patterns: Option<String>,
    /// Default stderr verbosity when neither `-q` nor `-v` is passed.
    #[serde(rename = "log-level")]
    pub log_level: Option<String>,
    /// Stderr log shape: `text` or `json`.
    #[serde(rename = "log-format")]
    pub log_format: Option<String>,
    /// Whether stderr log lines carry a timestamp.
    #[serde(rename = "log-timestamps")]
    pub log_timestamps: Option<bool>,
    /// Energy window of the voice-activity cut, in milliseconds.
    #[serde(rename = "vad-frame-ms")]
    pub vad_frame_ms: Option<u32>,
    /// RMS floor the cut uses at sensitivity just above zero.
    #[serde(rename = "vad-rms-min")]
    pub vad_rms_min: Option<f32>,
    /// RMS floor the cut uses at sensitivity 1.0.
    #[serde(rename = "vad-rms-max")]
    pub vad_rms_max: Option<f32>,
    /// Taps in the anti-aliasing filter used when resampling.
    #[serde(rename = "resample-taps")]
    pub resample_taps: Option<usize>,
    /// Read and write buffer size for streaming I/O, in bytes.
    #[serde(rename = "io-chunk-bytes")]
    pub io_chunk_bytes: Option<usize>,
    /// How often a spawned child process is polled, in milliseconds.
    #[serde(rename = "probe-poll-ms")]
    pub probe_poll_ms: Option<u64>,
    /// Extra arguments handed to the decode helper, comma separated.
    #[serde(rename = "helper-args")]
    pub helper_args: Option<Vec<String>>,
    /// Path to the NVIDIA query tool. Empty means find it on the `PATH`.
    #[serde(rename = "nvidia-smi-path")]
    pub nvidia_smi_path: Option<String>,
    /// Audio container extensions the native decoder accepts, comma separated.
    #[serde(rename = "audio-extensions")]
    pub audio_extensions: Option<Vec<String>>,
    /// Video container extensions routed to the helper, comma separated.
    #[serde(rename = "video-extensions")]
    pub video_extensions: Option<Vec<String>>,
    /// Envelope keys that `--truncate-content` shortens, comma separated.
    #[serde(rename = "content-keys")]
    pub content_keys: Option<Vec<String>>,
}

/// Compiled seeds. First release persists these; the operator may change them.
impl Store {
    /// Product seeds for a first-run host.
    pub fn seeds() -> Self {
        Self {
            // `large-v3` is the product default: it is the most accurate model
            // in the catalogue, and the VRAM gate refuses it before loading on
            // a card that cannot hold it, so the failure is a clean 70 rather
            // than a bad transcription. An operator on a small card overrides
            // this once with `config set model small`.
            model: Some("large-v3".into()),
            language: Some("auto".into()),
            device: Some(0),
            timeout: Some(0),
            timeout_grace: Some(5),
            max_duration: Some(24.0 * 3600.0),
            beam: Some(5),
            // Sensitivity 0.0 means the cut is OFF, not "the lowest floor".
            // `audio::vad_chunks` short-circuits on a threshold at or below
            // zero and returns no ranges at all, which is the contract for
            // "use the whole file". The weakest floor the map can produce is
            // still 0.002, and measured on 95 s of speech it cut the take into
            // 122 chunks; every cut costs the decoder the context it uses to
            // choose words, so a knob whose minimum still cuts has no position
            // meaning "leave the recording alone". FR-051 covers the other
            // direction, where a cut that is on finds nothing.
            vad: Some(0.0),
            concurrency: Some(1),
            helper: Some(String::new()),
            // On by default because the native decoder cannot cover the formats
            // people actually hand a transcriber. Symphonia has no Opus
            // decoder, so a WhatsApp voice note was refused with 65 on a host
            // that had ffmpeg installed. The empty `helper` above is not a
            // contradiction: an empty path means "find one", and the PATH is
            // consulted at call time, so this seed carries no machine-specific
            // value into the config file.
            helper_fallback: Some(true),
            max_memory: Some(0),
            locale: None,
            origin_base: Some(DEFAULT_ORIGIN_BASE.into()),
            download_retries: Some(2),
            retry_max_elapsed: Some(120),
            download_timeout: Some(600),
            // Every value below was a bare literal somewhere in `src/`. The
            // seed is the same number the code used, so nothing changes for an
            // operator who never touches these; what changes is that the ones
            // who need to touch them now can.
            download_backoff_ms: Some(200),
            http_proxy: Some(String::new()),
            hallucination_filter: Some(true),
            hallucination_patterns: Some(String::new()),
            log_level: Some("warn".into()),
            log_format: Some("text".into()),
            log_timestamps: Some(false),
            // 30 ms at the engine's 16 kHz is the 480-sample window the cut
            // has always used.
            vad_frame_ms: Some(30),
            vad_rms_min: Some(0.002),
            vad_rms_max: Some(0.10),
            resample_taps: Some(31),
            io_chunk_bytes: Some(64 * 1024),
            probe_poll_ms: Some(25),
            helper_args: Some(Vec::new()),
            nvidia_smi_path: Some(String::new()),
            audio_extensions: Some(
                crate::audio::AUDIO_EXT
                    .iter()
                    .map(|s| (*s).to_string())
                    .collect(),
            ),
            video_extensions: Some(
                crate::audio::VIDEO_EXT
                    .iter()
                    .map(|s| (*s).to_string())
                    .collect(),
            ),
            content_keys: Some(
                crate::surface::CONTENT_KEYS
                    .iter()
                    .map(|s| (*s).to_string())
                    .collect(),
            ),
        }
    }

    /// Load from disk or return empty (seeds applied at merge).
    pub fn load(path: &Path) -> Result<Self, Error> {
        if !path.exists() {
            return Ok(Self::default());
        }
        // A config file that cannot be READ is a configuration fault, not a
        // generic I/O fault. FR-016 is explicit — "config ilegível devolve
        // código 78" — and the `?` here used to widen the error into
        // `Error::Io`, which answers 74. The two codes tell an agent different
        // things: 74 says the machine is having trouble, 78 says fix the
        // configuration. The directory case stays 74, because that failure
        // happens while creating the parent and FR-050 assigns 74 to it.
        let raw = std::fs::read_to_string(path)
            .map_err(|e| Error::Config(format!("cannot read {}: {e}", path.display())))?;
        toml::from_str(&raw).map_err(|e| Error::Config(e.to_string()))
    }

    /// Atomic write via tempfile + rename.
    pub fn save(&self, path: &Path) -> Result<(), Error> {
        let body = toml::to_string_pretty(self).map_err(|e| Error::Config(e.to_string()))?;
        crate::paths::write_atomic(path, &body)
    }

    /// Overlay stored values onto seeds.
    pub fn effective(&self) -> Self {
        let mut out = Self::seeds();
        merge_opt(&mut out.model, &self.model);
        merge_opt(&mut out.language, &self.language);
        merge_opt(&mut out.device, &self.device);
        merge_opt(&mut out.timeout, &self.timeout);
        merge_opt(&mut out.timeout_grace, &self.timeout_grace);
        merge_opt(&mut out.max_duration, &self.max_duration);
        merge_opt(&mut out.beam, &self.beam);
        merge_opt(&mut out.vad, &self.vad);
        merge_opt(&mut out.concurrency, &self.concurrency);
        merge_opt(&mut out.helper, &self.helper);
        merge_opt(&mut out.helper_fallback, &self.helper_fallback);
        merge_opt(&mut out.max_memory, &self.max_memory);
        merge_opt(&mut out.locale, &self.locale);
        merge_opt(&mut out.origin_base, &self.origin_base);
        merge_opt(&mut out.download_retries, &self.download_retries);
        merge_opt(&mut out.retry_max_elapsed, &self.retry_max_elapsed);
        merge_opt(&mut out.download_timeout, &self.download_timeout);
        merge_opt(&mut out.download_backoff_ms, &self.download_backoff_ms);
        merge_opt(&mut out.http_proxy, &self.http_proxy);
        merge_opt(&mut out.hallucination_filter, &self.hallucination_filter);
        merge_opt(
            &mut out.hallucination_patterns,
            &self.hallucination_patterns,
        );
        merge_opt(&mut out.log_level, &self.log_level);
        merge_opt(&mut out.log_format, &self.log_format);
        merge_opt(&mut out.log_timestamps, &self.log_timestamps);
        merge_opt(&mut out.vad_frame_ms, &self.vad_frame_ms);
        merge_opt(&mut out.vad_rms_min, &self.vad_rms_min);
        merge_opt(&mut out.vad_rms_max, &self.vad_rms_max);
        merge_opt(&mut out.resample_taps, &self.resample_taps);
        merge_opt(&mut out.io_chunk_bytes, &self.io_chunk_bytes);
        merge_opt(&mut out.probe_poll_ms, &self.probe_poll_ms);
        merge_opt(&mut out.helper_args, &self.helper_args);
        merge_opt(&mut out.nvidia_smi_path, &self.nvidia_smi_path);
        merge_opt(&mut out.audio_extensions, &self.audio_extensions);
        merge_opt(&mut out.video_extensions, &self.video_extensions);
        merge_opt(&mut out.content_keys, &self.content_keys);
        out
    }

    /// Catalog origin of an already-effective store.
    ///
    /// Call this on the value returned by [`Store::effective`]. Verbs must
    /// never inline the seed URL; that is how four copies drift apart.
    pub fn origin(&self) -> &str {
        self.origin_base.as_deref().unwrap_or(DEFAULT_ORIGIN_BASE)
    }

    /// The three download knobs, resolved once against the seeds.
    ///
    /// Both call sites of `model::download` used to inline `2`, `120` and
    /// `600`, which is the same seed drift `get_key` had: four copies of a
    /// number that is defined in exactly one place.
    ///
    /// Call this on the value returned by [`Store::effective`].
    pub fn download_knobs(&self) -> DownloadKnobs {
        let s = Self::seeds();
        DownloadKnobs {
            retries: self
                .download_retries
                .or(s.download_retries)
                .unwrap_or_default(),
            max_elapsed_secs: self
                .retry_max_elapsed
                .or(s.retry_max_elapsed)
                .unwrap_or_default(),
            timeout_secs: self
                .download_timeout
                .or(s.download_timeout)
                .unwrap_or_default(),
            backoff_ms: self
                .download_backoff_ms
                .or(s.download_backoff_ms)
                .unwrap_or_default(),
            proxy: self
                .http_proxy
                .clone()
                .or(s.http_proxy.clone())
                .unwrap_or_default(),
            // A zero-byte buffer would read nothing forever, so it never wins.
            io_chunk: self
                .io_chunk_bytes
                .or(s.io_chunk_bytes)
                .filter(|n| *n > 0)
                .unwrap_or(64 * 1024),
        }
    }

    /// Read one key as a string.
    ///
    /// Every fallback here comes from [`Store::seeds`] and never from a literal
    /// written a second time. The literals used to live in both places, and the
    /// two copies did not even agree: `max-duration` seeded 24 hours while this
    /// function fell back to `0`, which in this product means "no limit". A
    /// `config get` that answers one number while the run uses another is a
    /// silent lie, and it is silent precisely because nothing compares them.
    pub fn get_key(&self, key: &str) -> Result<String, Error> {
        let e = self.effective();
        let s = Self::seeds();
        let value = match key {
            "model" => e.model.or(s.model).unwrap_or_default(),
            "language" => e.language.or(s.language).unwrap_or_default(),
            "device" => e.device.or(s.device).unwrap_or_default().to_string(),
            "timeout" => e.timeout.or(s.timeout).unwrap_or_default().to_string(),
            "timeout-grace" => e
                .timeout_grace
                .or(s.timeout_grace)
                .unwrap_or_default()
                .to_string(),
            "max-duration" => e
                .max_duration
                .or(s.max_duration)
                .unwrap_or_default()
                .to_string(),
            "beam" => e.beam.or(s.beam).unwrap_or_default().to_string(),
            "vad" => e.vad.or(s.vad).unwrap_or_default().to_string(),
            "concurrency" => e
                .concurrency
                .or(s.concurrency)
                .unwrap_or_default()
                .to_string(),
            "helper" => e.helper.or(s.helper).unwrap_or_default(),
            "helper-fallback" => e
                .helper_fallback
                .or(s.helper_fallback)
                .unwrap_or_default()
                .to_string(),
            "max-memory" => e
                .max_memory
                .or(s.max_memory)
                .unwrap_or_default()
                .to_string(),
            "locale" => e.locale.or(s.locale).unwrap_or_default(),
            "origin-base" => e.origin_base.or(s.origin_base).unwrap_or_default(),
            "download-retries" => e
                .download_retries
                .or(s.download_retries)
                .unwrap_or_default()
                .to_string(),
            "retry-max-elapsed" => e
                .retry_max_elapsed
                .or(s.retry_max_elapsed)
                .unwrap_or_default()
                .to_string(),
            "download-timeout" => e
                .download_timeout
                .or(s.download_timeout)
                .unwrap_or_default()
                .to_string(),
            "download-backoff-ms" => e
                .download_backoff_ms
                .or(s.download_backoff_ms)
                .unwrap_or_default()
                .to_string(),
            "http-proxy" => e.http_proxy.or(s.http_proxy).unwrap_or_default(),
            "hallucination-filter" => e
                .hallucination_filter
                .or(s.hallucination_filter)
                .unwrap_or_default()
                .to_string(),
            "hallucination-patterns" => e
                .hallucination_patterns
                .or(s.hallucination_patterns)
                .unwrap_or_default(),
            "log-level" => e.log_level.or(s.log_level).unwrap_or_default(),
            "log-format" => e.log_format.or(s.log_format).unwrap_or_default(),
            "log-timestamps" => e
                .log_timestamps
                .or(s.log_timestamps)
                .unwrap_or_default()
                .to_string(),
            "vad-frame-ms" => e
                .vad_frame_ms
                .or(s.vad_frame_ms)
                .unwrap_or_default()
                .to_string(),
            "vad-rms-min" => e
                .vad_rms_min
                .or(s.vad_rms_min)
                .unwrap_or_default()
                .to_string(),
            "vad-rms-max" => e
                .vad_rms_max
                .or(s.vad_rms_max)
                .unwrap_or_default()
                .to_string(),
            "resample-taps" => e
                .resample_taps
                .or(s.resample_taps)
                .unwrap_or_default()
                .to_string(),
            "io-chunk-bytes" => e
                .io_chunk_bytes
                .or(s.io_chunk_bytes)
                .unwrap_or_default()
                .to_string(),
            "probe-poll-ms" => e
                .probe_poll_ms
                .or(s.probe_poll_ms)
                .unwrap_or_default()
                .to_string(),
            "helper-args" => e
                .helper_args
                .or(s.helper_args)
                .unwrap_or_default()
                .join(","),
            "nvidia-smi-path" => e.nvidia_smi_path.or(s.nvidia_smi_path).unwrap_or_default(),
            "audio-extensions" => e
                .audio_extensions
                .or(s.audio_extensions)
                .unwrap_or_default()
                .join(","),
            "video-extensions" => e
                .video_extensions
                .or(s.video_extensions)
                .unwrap_or_default()
                .join(","),
            "content-keys" => e
                .content_keys
                .or(s.content_keys)
                .unwrap_or_default()
                .join(","),
            _ => return Err(Error::Config(format!("unknown key: {key}"))),
        };
        Ok(value)
    }

    /// Write one key. Unknown keys fail closed.
    pub fn set_key(&mut self, key: &str, value: &str) -> Result<(), Error> {
        if !WRITABLE_KEYS.contains(&key) {
            return Err(Error::Config(format!("unknown key: {key}")));
        }
        match key {
            "model" => self.model = Some(value.to_string()),
            "language" => self.language = Some(value.to_string()),
            "device" => self.device = Some(parse_u32(value)?),
            "timeout" => self.timeout = Some(parse_u64(value)?),
            "timeout-grace" => self.timeout_grace = Some(parse_u64(value)?),
            "max-duration" => self.max_duration = Some(parse_f64(value)?),
            // Range violations here are config faults (78), not argv faults (2).
            // The same value passed as a flag is rejected by the verb with 2.
            "beam" => {
                let n = parse_i32(value)?;
                if !(BEAM_RANGE).contains(&n) {
                    return Err(Error::Config(range_message("beam", &BEAM_RANGE)));
                }
                self.beam = Some(n);
            }
            "vad" => {
                let n = parse_f32(value)?;
                if !(VAD_RANGE).contains(&n) {
                    return Err(Error::Config(range_message("vad", &VAD_RANGE)));
                }
                self.vad = Some(n);
            }
            "concurrency" => {
                let n = parse_usize(value)?;
                if !(CONCURRENCY_RANGE).contains(&n) {
                    return Err(Error::Config(range_message(
                        "concurrency",
                        &CONCURRENCY_RANGE,
                    )));
                }
                self.concurrency = Some(n);
            }
            "helper" => self.helper = Some(value.to_string()),
            "helper-fallback" => self.helper_fallback = Some(parse_bool(value)?),
            "max-memory" => self.max_memory = Some(parse_u64(value)?),
            "locale" => self.locale = Some(value.to_string()),
            "origin-base" => {
                if !value.starts_with("https://") {
                    return Err(Error::InsecureOrigin {
                        url: value.to_string(),
                    });
                }
                self.origin_base = Some(value.trim_end_matches('/').to_string());
            }
            "download-retries" => self.download_retries = Some(parse_u32(value)?),
            "retry-max-elapsed" => self.retry_max_elapsed = Some(parse_u64(value)?),
            "download-timeout" => self.download_timeout = Some(parse_u64(value)?),
            "download-backoff-ms" => {
                let n = parse_u64(value)?;
                if !BACKOFF_RANGE.contains(&n) {
                    return Err(Error::Config(range_message(key, &BACKOFF_RANGE)));
                }
                self.download_backoff_ms = Some(n);
            }
            "http-proxy" => {
                // Empty clears it. A non-empty value must be a URL scheme the
                // client can actually dial, or the failure lands much later as
                // an opaque connection error.
                if !value.is_empty()
                    && !(value.starts_with("http://") || value.starts_with("https://"))
                {
                    return Err(Error::Config(format!(
                        "http-proxy must start with http:// or https://: {value}"
                    )));
                }
                self.http_proxy = Some(value.to_string());
            }
            "hallucination-filter" => self.hallucination_filter = Some(parse_bool(value)?),
            "hallucination-patterns" => {
                // Compiled here so a broken pattern is refused at `config set`,
                // where the operator is looking, and not on the first
                // transcription that happens to run afterwards.
                if !value.trim().is_empty() {
                    crate::audio::hallucination_regex_from(&[value.to_string()])?;
                }
                self.hallucination_patterns = Some(value.to_string());
            }
            "log-level" => {
                if !LOG_LEVELS.contains(&value) {
                    return Err(Error::Config(format!(
                        "log-level must be one of {}",
                        LOG_LEVELS.join(", ")
                    )));
                }
                self.log_level = Some(value.to_string());
            }
            "log-format" => {
                if !LOG_FORMATS.contains(&value) {
                    return Err(Error::Config(format!(
                        "log-format must be one of {}",
                        LOG_FORMATS.join(", ")
                    )));
                }
                self.log_format = Some(value.to_string());
            }
            "log-timestamps" => self.log_timestamps = Some(parse_bool(value)?),
            "vad-frame-ms" => {
                let n = parse_u32(value)?;
                if !VAD_FRAME_MS_RANGE.contains(&n) {
                    return Err(Error::Config(range_message(key, &VAD_FRAME_MS_RANGE)));
                }
                self.vad_frame_ms = Some(n);
            }
            "vad-rms-min" => self.vad_rms_min = Some(parse_rms(key, value)?),
            "vad-rms-max" => self.vad_rms_max = Some(parse_rms(key, value)?),
            "resample-taps" => {
                let n = parse_usize(value)?;
                if !RESAMPLE_TAPS_RANGE.contains(&n) {
                    return Err(Error::Config(range_message(key, &RESAMPLE_TAPS_RANGE)));
                }
                if n % 2 == 0 {
                    // An even tap count has no centre sample, so the filter is
                    // no longer symmetric and the resampled audio drifts by
                    // half a sample against its own timestamps.
                    return Err(Error::Config("resample-taps must be odd".into()));
                }
                self.resample_taps = Some(n);
            }
            "io-chunk-bytes" => {
                let n = parse_usize(value)?;
                if !IO_CHUNK_RANGE.contains(&n) {
                    return Err(Error::Config(range_message(key, &IO_CHUNK_RANGE)));
                }
                self.io_chunk_bytes = Some(n);
            }
            "probe-poll-ms" => {
                let n = parse_u64(value)?;
                if !PROBE_POLL_RANGE.contains(&n) {
                    return Err(Error::Config(range_message(key, &PROBE_POLL_RANGE)));
                }
                self.probe_poll_ms = Some(n);
            }
            "helper-args" => self.helper_args = Some(parse_list(value)),
            "nvidia-smi-path" => self.nvidia_smi_path = Some(value.to_string()),
            "audio-extensions" => self.audio_extensions = Some(parse_ext_list(key, value)?),
            "video-extensions" => self.video_extensions = Some(parse_ext_list(key, value)?),
            "content-keys" => self.content_keys = Some(parse_list(value)),
            _ => return Err(Error::Config(format!("unknown key: {key}"))),
        }
        Ok(())
    }

    /// Restore a key to the compiled seed.
    pub fn unset_key(&mut self, key: &str) -> Result<(), Error> {
        if !WRITABLE_KEYS.contains(&key) {
            return Err(Error::Config(format!("unknown key: {key}")));
        }
        match key {
            "model" => self.model = None,
            "language" => self.language = None,
            "device" => self.device = None,
            "timeout" => self.timeout = None,
            "timeout-grace" => self.timeout_grace = None,
            "max-duration" => self.max_duration = None,
            "beam" => self.beam = None,
            "vad" => self.vad = None,
            "concurrency" => self.concurrency = None,
            "helper" => self.helper = None,
            "helper-fallback" => self.helper_fallback = None,
            "max-memory" => self.max_memory = None,
            "locale" => self.locale = None,
            "origin-base" => self.origin_base = None,
            "download-retries" => self.download_retries = None,
            "retry-max-elapsed" => self.retry_max_elapsed = None,
            "download-timeout" => self.download_timeout = None,
            "download-backoff-ms" => self.download_backoff_ms = None,
            "http-proxy" => self.http_proxy = None,
            "hallucination-filter" => self.hallucination_filter = None,
            "hallucination-patterns" => self.hallucination_patterns = None,
            "log-level" => self.log_level = None,
            "log-format" => self.log_format = None,
            "log-timestamps" => self.log_timestamps = None,
            "vad-frame-ms" => self.vad_frame_ms = None,
            "vad-rms-min" => self.vad_rms_min = None,
            "vad-rms-max" => self.vad_rms_max = None,
            "resample-taps" => self.resample_taps = None,
            "io-chunk-bytes" => self.io_chunk_bytes = None,
            "probe-poll-ms" => self.probe_poll_ms = None,
            "helper-args" => self.helper_args = None,
            "nvidia-smi-path" => self.nvidia_smi_path = None,
            "audio-extensions" => self.audio_extensions = None,
            "video-extensions" => self.video_extensions = None,
            "content-keys" => self.content_keys = None,
            _ => return Err(Error::Config(format!("unknown key: {key}"))),
        }
        Ok(())
    }

    /// Effective map for `config list`.
    pub fn list_map(&self) -> BTreeMap<String, String> {
        WRITABLE_KEYS
            .iter()
            .filter_map(|k| self.get_key(k).ok().map(|v| ((*k).to_string(), v)))
            .collect()
    }
}

fn merge_opt<T: Clone>(dst: &mut Option<T>, src: &Option<T>) {
    if src.is_some() {
        *dst = src.clone();
    }
}

/// Split a comma separated value, dropping blanks and surrounding space.
fn parse_list(v: &str) -> Vec<String> {
    v.split(',')
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string)
        .collect()
}

/// Same as [`parse_list`], but for extensions, which carry no dot and no case.
///
/// A value like `.OPUS` is what an operator naturally types, and silently
/// storing it that way would make the lookup miss every file, because the
/// comparison is against a lowercase extension with no leading dot.
fn parse_ext_list(key: &str, v: &str) -> Result<Vec<String>, Error> {
    let out: Vec<String> = parse_list(v)
        .into_iter()
        .map(|s| s.trim_start_matches('.').to_ascii_lowercase())
        .collect();
    if out.is_empty() {
        return Err(Error::Config(format!("{key} must list at least one item")));
    }
    Ok(out)
}

/// Parse an RMS floor and hold it inside [`VAD_RMS_RANGE`].
fn parse_rms(key: &str, v: &str) -> Result<f32, Error> {
    let n: f32 = v
        .parse()
        .map_err(|_| Error::Config(format!("not a number: {v}")))?;
    if !VAD_RMS_RANGE.contains(&n) {
        return Err(Error::Config(range_message(key, &VAD_RMS_RANGE)));
    }
    Ok(n)
}

fn parse_u32(v: &str) -> Result<u32, Error> {
    v.parse()
        .map_err(|_| Error::Config(format!("not u32: {v}")))
}
fn parse_u64(v: &str) -> Result<u64, Error> {
    v.parse()
        .map_err(|_| Error::Config(format!("not u64: {v}")))
}
fn parse_i32(v: &str) -> Result<i32, Error> {
    v.parse()
        .map_err(|_| Error::Config(format!("not i32: {v}")))
}
fn parse_f32(v: &str) -> Result<f32, Error> {
    v.parse()
        .map_err(|_| Error::Config(format!("not f32: {v}")))
}
fn parse_f64(v: &str) -> Result<f64, Error> {
    v.parse()
        .map_err(|_| Error::Config(format!("not f64: {v}")))
}
fn parse_usize(v: &str) -> Result<usize, Error> {
    v.parse()
        .map_err(|_| Error::Config(format!("not usize: {v}")))
}
fn parse_bool(v: &str) -> Result<bool, Error> {
    match v {
        "true" | "1" | "yes" => Ok(true),
        "false" | "0" | "no" => Ok(false),
        _ => Err(Error::Config(format!("not bool: {v}"))),
    }
}

/// Load the store for a resolved path jail.
pub fn load(paths: &AppPaths) -> Result<Store, Error> {
    paths.ensure()?;
    Store::load(&paths.config_file())
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The product ships accurate by default, and cuts as little as possible.
    ///
    /// Both seeds are deliberate and they belong together: `large-v3` is the
    /// most accurate model in the catalogue, and a VAD sensitivity of 0.0 is
    /// the lowest energy floor the cut accepts, so faint speech still opens a
    /// chunk instead of being dropped. A card too small for `large-v3` is
    /// refused by the VRAM gate with a clean 70 before any weights load, which
    /// is a better failure than a quietly worse transcription.
    #[test]
    fn default_model_is_the_most_accurate_and_the_cut_is_widest() {
        assert_eq!(Store::seeds().model.as_deref(), Some("large-v3"));
        assert_eq!(Store::seeds().vad, Some(0.0));
        assert!(
            VAD_RANGE.contains(&Store::seeds().vad.expect("seeded vad")),
            "the seeded sensitivity must be inside the accepted range"
        );
    }

    #[test]
    fn default_concurrency_is_one() {
        assert_eq!(Store::seeds().concurrency, Some(1));
    }

    #[test]
    fn origin_is_never_empty_and_matches_the_single_seed() {
        assert_eq!(Store::default().effective().origin(), DEFAULT_ORIGIN_BASE);
        assert!(DEFAULT_ORIGIN_BASE.starts_with("https://"));
    }

    #[test]
    fn out_of_range_config_value_is_config_not_usage() {
        let mut s = Store::default();
        for (key, value) in [("beam", "99"), ("vad", "2"), ("concurrency", "0")] {
            let err = s.set_key(key, value).expect_err(key);
            assert_eq!(err.exit_code(), 78, "{key} must fail closed as config");
        }
    }

    #[test]
    fn unset_restores_the_seed() {
        let mut s = Store::default();
        s.set_key("beam", "3").expect("set");
        assert_eq!(s.get_key("beam").expect("get"), "3");
        s.unset_key("beam").expect("unset");
        assert_eq!(s.get_key("beam").expect("get"), "5");
    }

    #[test]
    fn unknown_key_fails() {
        let mut s = Store::default();
        assert!(s.set_key("nope", "x").is_err());
    }

    /// A key that `effective` forgets is a key the operator cannot set.
    ///
    /// Eighteen keys were declared, given seeds, given `set`/`get`/`unset` arms
    /// and a schema entry, and every one of them was still inert, because
    /// `effective` never merged them: the stored value was read from disk and
    /// then thrown away under the seed. Nothing failed, `config set` answered
    /// ok, and `config get` even echoed the new value — it just never reached
    /// the run. This test walks the whole inventory so the next key cannot be
    /// born the same way.
    #[test]
    fn every_writable_key_survives_effective() {
        for key in WRITABLE_KEYS {
            let mut s = Store::default();
            let seeded = Store::seeds()
                .get_key(key)
                .unwrap_or_else(|e| panic!("{key} must be readable: {e}"));
            let probe = distinct_value(key, &seeded);
            s.set_key(key, &probe)
                .unwrap_or_else(|e| panic!("{key} must accept {probe:?}: {e}"));
            let got = s
                .get_key(key)
                .unwrap_or_else(|e| panic!("{key} must be readable: {e}"));
            assert_ne!(
                got, seeded,
                "{key} did not survive effective(): the seed overwrote the stored value"
            );
        }
    }

    /// A legal value for `key` that is guaranteed to differ from `seeded`.
    fn distinct_value(key: &str, seeded: &str) -> String {
        match key {
            "model" => "small".into(),
            "language" => "pt".into(),
            "locale" => "en".into(),
            "helper" | "nvidia-smi-path" => "/usr/bin/true".into(),
            "http-proxy" => "http://proxy.invalid:3128".into(),
            "origin-base" => "https://mirror.invalid/models".into(),
            "hallucination-patterns" => "meu ruido".into(),
            "log-level" => "debug".into(),
            "log-format" => "json".into(),
            "helper-args" | "content-keys" => "alpha,beta".into(),
            "audio-extensions" | "video-extensions" => "wav,mp3".into(),
            "vad" | "vad-rms-min" | "vad-rms-max" => "0.25".into(),
            "beam" => "7".into(),
            "concurrency" => "3".into(),
            "vad-frame-ms" => "40".into(),
            "resample-taps" => "63".into(),
            "io-chunk-bytes" => "8192".into(),
            "probe-poll-ms" => "7".into(),
            // Booleans have exactly one other value.
            "helper-fallback" | "hallucination-filter" | "log-timestamps" => {
                if seeded == "true" { "false" } else { "true" }.into()
            }
            // Everything else is a plain non-negative number.
            _ => {
                let n: u64 = seeded.parse().unwrap_or(0);
                (n + 17).to_string()
            }
        }
    }

    #[test]
    fn list_contains_required_keys() {
        // Every writable key must be listable, or `config list` stops being
        // the audit surface FR-052 promises.
        let keys = Store::seeds().list_map();
        for required in WRITABLE_KEYS {
            assert!(keys.contains_key(*required), "missing {required}");
        }
        assert_eq!(keys.len(), WRITABLE_KEYS.len());
    }
}