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
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
//! The transcription pipeline: argv to samples to text.
//!
//! `transcribe` and everything it reaches used to live in `commands.rs`, next to
//! the dispatcher and to the verbs that answer about the product. That module
//! was the largest and the least tested in the crate because it held six
//! unrelated responsibilities behind one name, so a reader looking for the batch
//! loop and a reader looking for `config get` opened the same file.
//!
//! The cut follows the coupling that was already there: everything in this file
//! is reached only from `transcribe`, and `transcribe` is reached only from
//! `commands::dispatch`. Nothing was renamed, no signature changed and no
//! behaviour moved with it; only the module boundary did.

use std::borrow::Cow;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use is_terminal::IsTerminal;
use serde_json::json;
use uuid::Uuid;

use crate::audio::{self, PcmData};
use crate::catalog::Catalog;
use crate::cli::TranscribeArgs;
use crate::commands::Ctx;
use crate::config;
use crate::error::Error;
use crate::gpu;
use crate::output::{self, Segment, TranscriptionResult, SCHEMA_VERSION};
use crate::paths::AppPaths;

/// Transcribe, and under `--ndjson` keep the stream's shape whatever happens.
///
/// FR-003 promises one line per target plus a summary. That promise was kept in
/// the loop that walks the targets, so every failure that returns before the
/// loop broke it silently: a lone target that failed to decode emitted one bare
/// error envelope and no summary, and a batch whose paths were all absent did
/// the same. Measured under `--ndjson`: two corrupt files gave 3 lines and a
/// summary, while two absent files gave 1 line and none.
///
/// Both early returns are deliberate — a data fault must be reported before the
/// resource gate, or the same missing file answers 66 alone and 69 in a batch —
/// so the fix is not to remove them. It is to stop the promise from living in
/// one branch. An agent parsing NDJSON counts the summary to know the stream
/// ended; a stream that sometimes omits it cannot be told from a truncated one.
///
/// The exit code is untouched: the condition still decides it. Only the shape
/// of what reaches stdout is made unconditional.
pub(crate) fn transcribe(ctx: &mut Ctx<'_>, args: TranscribeArgs) -> Result<(), Error> {
    let ndjson = args.ndjson;
    // Read before the run, because the failure may be the reason there are no
    // resolved targets to read afterwards.
    let named = args.argv_targets();
    let outcome = transcribe_inner(ctx, args);
    let Err(err) = outcome else {
        return outcome;
    };
    // `error_reported` means the loop already wrote a line per target and the
    // summary; writing them again would give the agent a second tally.
    if !ndjson || ctx.error_reported || named.is_empty() {
        return Err(err);
    }
    // Every named target failed, and for the same reason: the fault arrived
    // before any of them was attempted. Saying so per target is what keeps the
    // line count equal to the target count.
    for target in &named {
        let resolved = target.display().to_string();
        output::write_error(
            &err,
            ctx.correlation_id,
            ctx.surface,
            Some(crate::error::TargetRef {
                resolved: &resolved,
                source: "argv",
            }),
        )?;
    }
    output::write_value(
        &json!({
            "schema_version": SCHEMA_VERSION,
            "correlation_id": ctx.correlation_id,
            "summary": true,
            "ok": 0u64,
            "failed": named.len() as u64,
            "total": named.len() as u64,
        }),
        ctx.surface,
    )?;
    ctx.error_reported = true;
    Err(err)
}

fn transcribe_inner(ctx: &mut Ctx<'_>, args: TranscribeArgs) -> Result<(), Error> {
    gpu::warn_ignored_cuda_env(ctx.ui);
    let effective = ctx.store.effective();
    let model_name = args
        .model
        .clone()
        .or(effective.model.clone())
        .unwrap_or_else(|| "large-v3".into());
    let language = args
        .language
        .clone()
        .or(effective.language.clone())
        .unwrap_or_else(|| "auto".into());
    let language_source = if args.language.is_some() {
        "argv"
    } else if ctx.store.language.is_some() {
        "config"
    } else {
        "default"
    };
    // An unknown language code is an argv fault, caught before any work.
    // Left unchecked it reaches the C engine and surfaces as a resource error.
    if !crate::engine::is_known_language(&language) {
        return Err(Error::Usage(format!("unknown language: {language}")));
    }
    // The bounds are written once, in `config`, and the message is derived from
    // them. Spelling "1..=16" by hand next to `BEAM_RANGE` meant that widening
    // the range would leave the advice telling the operator the old limit, and
    // advice that is wrong is worse than none because it is meant to be obeyed.
    let seeds = config::Store::seeds();
    let beam = args
        .beam
        .or(effective.beam)
        .or(seeds.beam)
        .unwrap_or_default();
    if !config::BEAM_RANGE.contains(&beam) {
        return Err(Error::Usage(config::range_message(
            "beam",
            &config::BEAM_RANGE,
        )));
    }
    let vad = args.vad.or(effective.vad).or(seeds.vad).unwrap_or_default();
    if !config::VAD_RANGE.contains(&vad) {
        return Err(Error::Usage(config::range_message(
            "vad",
            &config::VAD_RANGE,
        )));
    }
    let concurrency = args
        .concurrency
        .or(effective.concurrency)
        .or(seeds.concurrency)
        .unwrap_or_default();
    if !config::CONCURRENCY_RANGE.contains(&concurrency) {
        return Err(Error::Usage(config::range_message(
            "concurrency",
            &config::CONCURRENCY_RANGE,
        )));
    }
    let device = args
        .device
        .or(effective.device)
        .or(seeds.device)
        .unwrap_or_default();
    let timeout = ctx
        .timeout
        .or(effective.timeout)
        .or(seeds.timeout)
        .unwrap_or_default();
    // The seed is the single source; repeating `24.0 * 3600.0` here is how
    // `config get` and the run came to disagree about the same key.
    let max_duration = effective
        .max_duration
        .or(config::Store::seeds().max_duration)
        .unwrap_or_default();

    let catalog = Catalog::load_or_seed(ctx.paths, effective.origin())?;
    let entry = catalog.get(&model_name)?.clone();

    // Two distinct checks share this cap, and conflating them was the defect.
    //
    // The first is a prediction: a cap smaller than the model on disk can
    // never be honoured, so the run is refused before any work. The second,
    // inside the per-file path, measures what the process is actually holding
    // and stops when it goes over. Only the prediction existed, which meant a
    // cap the operator set to protect a shared machine was never enforced
    // against the process it was named after.
    let max_memory = args.max_memory.unwrap_or(effective.max_memory.unwrap_or(0));
    if max_memory > 0 && max_memory < entry.size_bytes {
        return Err(Error::MemoryCap);
    }
    // Published here so the decode loop can see it. The stage-boundary checks
    // below stay: they cover inference, which allocates outside any loop this
    // process owns.
    gpu::publish_memory_cap(max_memory);
    // Published here for the same reason the cap is: these values belong to the
    // invocation, and the loops that read them sit several frames below, behind
    // entry points reached from more than one caller.
    let poll_ms = effective
        .probe_poll_ms
        .or(seeds.probe_poll_ms)
        .unwrap_or_default();
    gpu::publish_probe_poll_ms(poll_ms);
    crate::media_helper::publish_helper_poll_ms(poll_ms);
    gpu::publish_nvidia_smi_path(
        effective
            .nvidia_smi_path
            .clone()
            .or(seeds.nvidia_smi_path.clone())
            .unwrap_or_default(),
    );
    crate::media_helper::publish_helper_args(
        effective
            .helper_args
            .clone()
            .or(seeds.helper_args.clone())
            .unwrap_or_default(),
    );

    let (targets, source) = resolve_transcribe_targets(ctx, &args)?;

    if args.dry_run {
        // Same rule the rest of the product follows: name a target only when
        // there is exactly one unambiguous target. Naming the first of N made
        // this envelope contradict itself, reporting `target_resolved: a.wav`
        // beside `would_transcribe.files: 2`. The `-` for stdin matches the
        // spelling every other path uses; `source.to_string()` produced a
        // second word for the same slot.
        let mut envelope = json!({
            "schema_version": SCHEMA_VERSION,
            "correlation_id": ctx.correlation_id,
            "dry_run": true,
            "would_transcribe": {
                    "files": targets.len(),
                    "model": model_name,
                    "language": language,
                    "beam_size": beam,
                    "device": device,
                    "concurrency": concurrency,
                "vad": vad,
            }
        });
        let designated = match targets.as_slice() {
            [only] => Some(only.display().to_string()),
            _ if targets.is_empty() && source == "stdin" => Some("-".to_string()),
            _ => None,
        };
        if let (Some(resolved), Some(map)) = (designated, envelope.as_object_mut()) {
            map.insert("target_resolved".into(), resolved.into());
            map.insert("target_source".into(), source.into());
        }
        return output::write_value(&envelope, ctx.surface);
    }

    // The deadline must cover the whole invocation, including a blocking
    // stdin read, so it is armed before any stage that can stall.
    //
    // The targets are already resolved here, so a timeout on a single named
    // file can say which file it was. A batch names none, for the same reason
    // the top-level envelope does not: the deadline belongs to the invocation
    // and each NDJSON line already carries its own target.
    let deadline_target = match targets.as_slice() {
        [only] => Some((only.display().to_string(), source)),
        _ if targets.is_empty() && source == "stdin" => Some(("-".to_string(), source)),
        _ => None,
    };
    // The watchdog fires past the deadline, not on it. Both clocks used to hold
    // the same instant, and the watchdog won every race because it is a thread
    // that wakes on time while the cooperative check only runs at a wave
    // boundary. A batch under `--timeout` therefore ended with one bare 124 and
    // no summary, and the cooperative path written for FR-003 was unreachable.
    //
    // The grace does not weaken `--timeout`: the cooperative path still stops
    // at the deadline and reports every target. It only decides who reports the
    // stop. The watchdog stays for what the cooperative path cannot see — a
    // blocked stdin read, a stalled download — and forces the exit after it.
    // `timeout == 0` means no deadline at all, so the grace must not conjure
    // one: adding it unguarded would arm a watchdog on every invocation that
    // asked for none.
    //
    // The grace exists to let the cooperative path write the NDJSON summary,
    // so it is spent only where a summary is owed. A single target has none:
    // giving it the grace merely made `--timeout` late, which FR-034 measures
    // directly — it requires the deadline to land inside the inference pass
    // rather than after it.
    // A summary is only written when the run walks a list of targets. `--ndjson`
    // alone does not create one: a stdin run has no targets at all and returns
    // a single object, so granting it the grace only made `--timeout` late,
    // which is the same defect FR-034 measures on a single file.
    let emits_summary = !targets.is_empty() && (args.ndjson || targets.len() > 1);
    let armed = if timeout == 0 {
        0
    } else if emits_summary {
        timeout.saturating_add(effective.timeout_grace.unwrap_or(5))
    } else {
        timeout
    };
    // Publish the cooperative instant before arming the watchdog, so the long
    // stages that can stop themselves — decoding, inference — see the deadline
    // the caller asked for rather than the padded one.
    crate::signal::publish_deadline(timeout);
    crate::signal::arm_deadline(armed, ctx.correlation_id, deadline_target);

    // Input is validated before the resource gate. An argv or data fault is
    // deterministic and host-independent, while a missing GPU is a property
    // of the machine; reporting 69 for an empty stdin hides the real fault
    // and makes the input contract unverifiable without a card.
    let stdin_pcm = if targets.is_empty() && source == "stdin" {
        // The cap travels into the read itself, so an oversized recording is
        // refused while it is still arriving. Measured on a 20 minute wav under
        // a 10 second cap: 7.99 s and 124.7 MiB before, against 0.00 s and
        // 13.5 MiB for the identical file through `--file`.
        let forced = args.input_format.as_ref().map(|f| f.as_str());
        let bytes = read_stdin(ctx.no_input, max_duration, forced)?;
        // A container that declares no frame count reaches here unrefused, so
        // the post-decode check in `finish_pcm` remains the backstop.
        Some(audio::decode_bytes(&bytes, forced)?)
    } else {
        None
    };

    // The same rule has to hold for a named file, or the contract contradicts
    // itself: the identical corrupt bytes answered 65 through stdin and 69
    // through `--file`, so whether a data fault was reportable depended on the
    // machine that read it.
    //
    // Only a final verdict may pre-empt the gate. A batch is excluded because
    // FR-003 owes one line per target and a per-file fault belongs on its own
    // line, not on the invocation. Video is excluded because the helper, not
    // the native decoder, decides. A helper retry is excluded for the same
    // reason: a native failure there is not yet an answer.
    // Decoded here and carried, not decoded here and thrown away.
    //
    // The stdin path above already works this way: it decodes once and hands
    // the samples forward. The named-file path asked the same bytes the same
    // question and discarded the answer, so the file was decoded twice —
    // once to validate and once to transcribe. Measured on a twenty minute wav
    // in paired runs, with the validation and without it: 60.21 s and 59.47 s
    // against 44.82 s and 42.41 s, about 27% of the wall clock spent producing
    // samples that were dropped.
    //
    // Reusing the decode also removes a way for the two answers to disagree.
    // `inspect_file` ignored `--input-format` while the transcription honoured
    // it, so the validating decode and the real one were not even asking about
    // the same interpretation of the bytes.
    // Resolved once, here, so every decision below reads the same answer: the
    // persisted path when the operator set one, and otherwise whatever
    // `ffmpeg` the PATH already offers.
    //
    // Leaving it empty made the product refuse formats the host could plainly
    // decode. `Cargo.toml` asks symphonia for `ogg` and `vorbis`, which are a
    // container and one codec that fits in it — an Opus voice note is that same
    // container with a codec symphonia has no decoder for, so a WhatsApp `.ogg`
    // exited 65 "unsupported codec" on a machine with a working ffmpeg one
    // directory away. Nothing here decides to use the helper; it only stops the
    // product from pretending the helper is absent.
    let helper =
        crate::media_helper::resolve_helper(effective.helper.as_deref().unwrap_or_default())
            .unwrap_or_default();

    let named_pcm = if let [only] = targets.as_slice() {
        // Ordered deliberately: the header answer comes first because it is
        // free, and the byte answer second because it is not.
        //
        // `inspect_file` decodes the whole recording to decide whether the
        // bytes are a data fault. That verdict is worth its cost only for a
        // file the run would otherwise accept. Measured on a twenty minute wav
        // under `max-duration 10`: 16.55 s and 49 MiB spent validating a file
        // the container header disqualifies in 139 us, because the expensive
        // question was asked before the cheap one. The per-target guard in
        // `transcribe_path` was already reading that header — it just ran after
        // this block, so it could never save the work it was written to save.
        refuse_over_duration(only, max_duration)?;

        let helper_may_recover =
            helper_retry_allowed(&helper, effective.helper_fallback.unwrap_or(true));
        if !audio::is_video_path(only) && !helper_may_recover {
            // `started` is taken before the decode so the reported duration
            // still covers the work, exactly as it did when the decode lived
            // inside `transcribe_path`.
            let started = Instant::now();
            let pcm = decode_path_with_hint(only, args.input_format.map(|f| f.as_str()))?;
            Some((pcm, started))
        } else {
            None
        }
    } else {
        None
    };

    let gpu_info = gpu::probe_checked(device)?;
    // Argv is judged before the environment. `--device 9` on a host with one
    // card is a fault in the request, and FR-022 answers it with 78; running
    // the toolkit gate first answered 69 instead, telling the caller to install
    // CUDA when the real fix was to pass a device index that exists. The card
    // gate inside `ensure_device` still reports an absent GPU as 70, so FR-020
    // keeps its answer for the host that has no card at all.
    gpu::ensure_device(&gpu_info, device)?;
    if !gpu_info.toolkit {
        return Err(Error::ToolkitMissing);
    }
    gpu::ensure_vram(&gpu_info, entry.vram_bytes, concurrency)?;

    // Why the verification failed decides what to do about it, and collapsing
    // the answer into a bool threw that away. A model present but unreadable —
    // wrong owner, wrong mode — answered exactly like a model that was never
    // downloaded: exit 78 telling the operator to download a file that is
    // already there, or exit 69 marked retryable when the retry cannot help.
    // `models verify` on the same file already reported the permission fault as
    // 74, so the information existed and only this call site discarded it.
    match crate::model::verify(ctx.paths, &entry) {
        Ok(_) => {}
        // Absent, truncated or superseded bytes are what a download repairs.
        Err(
            Error::ModelNotFound { .. }
            | Error::ModelSizeMismatch { .. }
            | Error::ModelDigestMismatch { .. },
        ) => {
            if ctx.offline {
                return Err(Error::OfflineMissingModel { name: model_name });
            }
            let dl = effective.download_knobs();
            crate::model::download(ctx.paths, &entry, &dl, ctx.offline)?;
        }
        // Anything else is a fault of the host or the catalog. Downloading over
        // it would not fix it and would hide it behind a network error.
        Err(other) => return Err(other),
    }

    crate::engine::silence_native_logs();
    let model_path = crate::model::model_path(ctx.paths, &entry);
    let deadline = if timeout > 0 {
        Some(Instant::now() + Duration::from_secs(timeout))
    } else {
        None
    };

    // Resolved once for the whole batch: compiling the filter per target would
    // pay the regex build on every file, and a broken pattern must fail before
    // any transcription starts rather than on the first file that matches it.
    let hallucination_re = if effective.hallucination_filter.unwrap_or(true) {
        let custom = effective.hallucination_patterns.clone().unwrap_or_default();
        if custom.trim().is_empty() {
            Some(Cow::Borrowed(audio::default_hallucination_regex()))
        } else {
            Some(Cow::Owned(audio::hallucination_regex_from(&[custom])?))
        }
    } else {
        None
    };

    // Resolved from configuration rather than read off constants, so a
    // recording with a high noise floor has a window and a floor the operator
    // can actually move. The seeds reproduce the old compiled numbers exactly.
    // Published before any decode runs, because the check that reads them is
    // several frames below this point.
    audio::publish_containers(
        effective
            .audio_extensions
            .clone()
            .or(seeds.audio_extensions.clone())
            .unwrap_or_default(),
        effective
            .video_extensions
            .clone()
            .or(seeds.video_extensions.clone())
            .unwrap_or_default(),
    );

    let vad_settings = audio::VadSettings::from_ms(
        effective
            .vad_frame_ms
            .or(seeds.vad_frame_ms)
            .unwrap_or_default(),
        effective
            .vad_rms_min
            .or(seeds.vad_rms_min)
            .unwrap_or_default(),
        effective
            .vad_rms_max
            .or(seeds.vad_rms_max)
            .unwrap_or_default(),
    );

    let knobs = ResolvedKnobs {
        entry: &entry,
        model_path: &model_path,
        language: &language,
        language_source,
        beam,
        vad,
        device,
        max_duration,
        timestamps: args.timestamps,
        input_format: args.input_format.map(|f| f.as_str()),
        deadline,
        helper: helper.clone(),
        helper_fallback: effective.helper_fallback.unwrap_or(true),
        max_memory,
        hallucination: hallucination_re.as_deref(),
        vad_settings,
    };

    let ndjson = args.ndjson || targets.len() > 1;
    let mut transcript = TranscriptSink::open(args.output.as_deref())?;

    if let Some(pcm) = stdin_pcm {
        let result = finish_pcm(
            ctx,
            pcm,
            "stdin".to_string(),
            source,
            &knobs,
            Instant::now(),
        )?;
        transcript.push(&result.text)?;
        output::write_json(&result, ctx.surface)?;
        return Ok(());
    }

    let outcomes = run_targets(ctx, &targets, &knobs, source, concurrency, named_pcm);

    let mut success = 0u64;
    let mut errors = 0u64;
    let mut fatal: Option<Error> = None;
    // `run_targets` preserves the order of `targets`, so zipping recovers which
    // named slot produced each outcome. Without it a failing line in a batch
    // carried no structured target and an agent had to parse the prose message
    // to learn which of its files had failed.
    for (target, outcome) in targets.iter().zip(outcomes) {
        match outcome {
            Ok(result) => {
                success += 1;
                transcript.push(&result.text)?;
                output::write_json(&result, ctx.surface)?;
            }
            Err(e) => {
                errors += 1;
                // A single target may fail without erasing the lines already
                // emitted; a lone target still fails the whole invocation.
                if !ndjson {
                    return Err(e);
                }
                let resolved = target.display().to_string();
                output::write_error(
                    &e,
                    ctx.correlation_id,
                    ctx.surface,
                    Some(crate::error::TargetRef {
                        resolved: &resolved,
                        source,
                    }),
                )?;
                // A whole-invocation condition must still reach the exit code.
                // Emitting it only as a line makes an agent that branches on
                // the exit code conclude the batch succeeded.
                //
                // A lone target is the invocation, so its verdict is the run's
                // verdict too, and `--ndjson` may only change the SHAPE of what
                // reaches stdout, never the code. That used to hold by accident:
                // a single target was decoded before this loop and propagated by
                // `?`, but only while the helper was unable to retry. Arming the
                // helper removed the accident and the same undecodable file
                // started answering 0. A batch stays different on purpose — one
                // bad file among many belongs to that file, and the tally is
                // where it is reported.
                //
                // The error is moved rather than rebuilt: `clone_fatal` knows
                // the payload-free variants only, so cloning here would turn a
                // decode fault into a 143.
                if fatal.is_none() && (is_invocation_fatal(&e) || targets.len() == 1) {
                    fatal = Some(e);
                }
            }
        }
    }
    if ndjson {
        output::write_value(
            &json!({
                "schema_version": SCHEMA_VERSION,
                "correlation_id": ctx.correlation_id,
                "summary": true,
                "ok": success,
                "failed": errors,
                "total": targets.len() as u64,
            }),
            ctx.surface,
        )?;
    }
    // The summary is emitted first so the agent still gets the tally, then the
    // invocation fails with the code the condition demands. In NDJSON the
    // condition already has its own line per target, so the top level must not
    // write it a third time after the summary.
    match fatal {
        Some(e) => {
            ctx.error_reported = ndjson;
            Err(e)
        }
        None => Ok(()),
    }
}

/// The operator's `--output` file, opened once and fed as results land.
///
/// Opened before the first target so an unwritable path fails the invocation
/// up front, rather than after minutes of inference. Each transcript is written
/// before its own envelope reaches stdout, so a line never claims text that is
/// not yet on disk.
///
/// A batch writes every transcript into the one file, in target order, each
/// terminated by a newline. That is the only shape that keeps `--output` a
/// single well-defined path; per-target files would need a naming scheme the
/// caller did not ask for, and stdout already carries the per-file structure.
struct TranscriptSink(Option<std::fs::File>);

impl TranscriptSink {
    fn open(path: Option<&Path>) -> Result<Self, Error> {
        match path {
            None => Ok(Self(None)),
            Some(p) => Ok(Self(Some(std::fs::File::create(p).map_err(Error::Io)?))),
        }
    }

    fn push(&mut self, text: &str) -> Result<(), Error> {
        let Some(file) = self.0.as_mut() else {
            return Ok(());
        };
        use std::io::Write;
        file.write_all(text.as_bytes()).map_err(Error::Io)?;
        // A transcript that already ends in a newline must not gain a blank
        // line, and one that does not must not run into the next target.
        if !text.ends_with('\n') {
            file.write_all(b"\n").map_err(Error::Io)?;
        }
        file.flush().map_err(Error::Io)
    }
}

/// True when the failure ended the whole invocation, not just one target.
///
/// A decode fault belongs to its file. An interrupt or a blown deadline
/// belongs to the process, and must reach the exit code.
fn is_invocation_fatal(err: &Error) -> bool {
    matches!(
        err,
        Error::Timeout | Error::Interrupted | Error::Terminated | Error::BrokenPipe
    )
}

/// Rebuild a fatal condition for propagation. These variants carry no payload.
fn clone_fatal(err: &Error) -> Error {
    match err {
        Error::Timeout => Error::Timeout,
        Error::Interrupted => Error::Interrupted,
        Error::BrokenPipe => Error::BrokenPipe,
        _ => Error::Terminated,
    }
}

/// Every knob of one transcription, resolved once.
///
/// The file path and the stdin path used to rebuild this list positionally,
/// which is how `--timestamps` and `--input-format` silently stopped applying
/// to one of the two. Same-typed positional arguments cannot be type-checked.
struct ResolvedKnobs<'a> {
    entry: &'a crate::catalog::ModelEntry,
    model_path: &'a Path,
    language: &'a str,
    language_source: &'static str,
    beam: i32,
    vad: f32,
    device: u32,
    max_duration: f64,
    timestamps: bool,
    input_format: Option<&'static str>,
    deadline: Option<Instant>,
    helper: String,
    helper_fallback: bool,
    /// Resident memory ceiling for this process, or zero for no ceiling.
    max_memory: u64,
    /// Compiled caption filter, or `None` when the operator turned it off.
    hallucination: Option<&'a regex::Regex>,
    /// Window and floors the voice-activity cut runs with.
    vad_settings: crate::audio::VadSettings,
}

/// Whether a decode failure may be retried through the external helper.
///
/// Pure so it can be tested on a host with no GPU and no helper installed.
fn helper_retry_allowed(helper: &str, helper_fallback: bool) -> bool {
    helper_fallback && !helper.trim().is_empty()
}

/// Run every target, honouring the parallel ceiling and keeping input order.
///
/// Order matters: NDJSON lines are matched to inputs by position, so results
/// are collected per wave and emitted in the order the agent asked for.
///
/// `pre_decoded` carries the samples the caller already produced while
/// validating a lone target. Emitting the outcome through this function rather
/// than short-circuiting in the caller keeps NDJSON accounting in one place:
/// a single target still owes its line and, under `--ndjson`, its summary.
fn run_targets(
    ctx: &Ctx<'_>,
    targets: &[PathBuf],
    knobs: &ResolvedKnobs<'_>,
    source: &'static str,
    concurrency: usize,
    pre_decoded: Option<(crate::audio::PcmData, Instant)>,
) -> Vec<Result<TranscriptionResult, Error>> {
    if let (Some((pcm, started)), [only]) = (pre_decoded, targets) {
        return vec![finish_pcm(
            ctx,
            pcm,
            only.display().to_string(),
            source,
            knobs,
            started,
        )];
    }
    // A shared cursor, not waves. `targets.chunks(concurrency)` made every
    // chunk a barrier: the next group could not start until the slowest member
    // of the current one finished. Transcription batches are heterogeneous by
    // nature — a thirty second note next to an hour of meeting — so with four
    // workers and one slow file, three of them sat idle for the whole of it.
    // Workers now pull the next index themselves and nobody waits on a peer.
    //
    // Order still holds: each worker writes into its own slot, so the NDJSON
    // lines keep matching inputs by position as FR-003 requires.
    let next = std::sync::atomic::AtomicUsize::new(0);
    let slots: Vec<std::sync::Mutex<Option<Result<TranscriptionResult, Error>>>> = (0..targets
        .len())
        .map(|_| std::sync::Mutex::new(None))
        .collect();
    let workers = concurrency.max(1).min(targets.len().max(1));

    std::thread::scope(|scope| {
        for _ in 0..workers {
            let next = &next;
            let slots = &slots;
            scope.spawn(move || loop {
                let i = next.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                if i >= targets.len() {
                    return;
                }
                // Checked per target rather than per wave. Abandoning the rest
                // of the batch must still produce one line per target: FR-003
                // promises N lines plus the summary, and a summary whose total
                // exceeds ok+failed is a silent gap for the agent.
                let stopped = if knobs.deadline.map(|d| Instant::now() > d).unwrap_or(false) {
                    Some(Error::Timeout)
                } else if crate::signal::is_shutdown_requested() {
                    // A shutdown seen but not yet classified is still a
                    // shutdown; never drop it because the reason has not landed.
                    Some(crate::signal::shutdown_error().unwrap_or(Error::Interrupted))
                } else {
                    None
                };
                // The engine caches one context per model and device, so the
                // batch shares the loaded weights and only the pass that built
                // them reports a cold load. The VRAM gate still reserves one
                // copy per worker, which over-reserves and only fails closed.
                let outcome = match stopped {
                    Some(err) => Err(clone_fatal(&err)),
                    None => transcribe_path(ctx, &targets[i], knobs, source),
                };
                if let Ok(mut slot) = slots[i].lock() {
                    *slot = Some(outcome);
                }
            });
        }
    });

    slots
        .into_iter()
        .map(|slot| {
            slot.into_inner()
                .ok()
                .flatten()
                // A worker that panicked left its slot empty. The batch still
                // owes this target a line, so the gap becomes a failure rather
                // than a missing row.
                .unwrap_or_else(|| Err(Error::WhisperInference("worker panicked".into())))
        })
        .collect()
}

fn resolve_transcribe_targets(
    ctx: &Ctx<'_>,
    args: &TranscribeArgs,
) -> Result<(Vec<PathBuf>, &'static str), Error> {
    if args.use_active {
        let marker = ctx.paths.active_target_file();
        // The message names the file because nothing in this binary writes it.
        // The marker belongs to whatever orchestrates these one-shot runs, and
        // "pass --file or set one" told the caller to perform an action no verb
        // here offers: `commands` lists no way to set it. An instruction whose
        // means the product does not provide is a dead end dressed as advice.
        let raw = std::fs::read_to_string(&marker).map_err(|_| {
            Error::Config(format!(
                "no active target: pass --file, or write one absolute path into {}",
                marker.display()
            ))
        })?;
        let path = PathBuf::from(raw.trim());
        if !path.exists() {
            return Err(Error::InputNotFound {
                path: path.display().to_string(),
            });
        }
        return Ok((vec![path], "active"));
    }
    let argv = args.argv_targets();
    if !argv.is_empty() {
        // An invocation whose every named target is absent is a data fault, and
        // it has to be reported as one before the resource gate runs. Checking
        // only the lone-target case made the same missing file answer 66 alone
        // and 69 in a batch, because the GPU gate got there first.
        //
        // The check stops at "all absent" on purpose. When one path of a batch
        // does exist there is real work to do, so each missing path becomes its
        // own NDJSON error line and FR-003 keeps its resilience.
        if argv.iter().all(|p| !p.exists()) {
            return Err(Error::InputNotFound {
                path: argv[0].display().to_string(),
            });
        }
        return Ok((argv, "argv"));
    }
    if args.stdin || !std::io::stdin().is_terminal() {
        if ctx.no_input && !args.stdin {
            return Err(Error::NoInput);
        }
        return Ok((Vec::new(), "stdin"));
    }
    Err(Error::NoInput)
}

/// Refuse an over-long recording from its container header.
///
/// Reads the declared frame count and touches no samples: measured at 139 us on
/// a twenty minute wav, against 16 s to decode the same file. A container that
/// declares no frame count returns `None` and the cap is then enforced after
/// decoding, inside `finish_pcm`, so skipping it here is safe.
///
/// Extracted because it has to run in two places. The per-target call in
/// `transcribe_path` is what a batch needs; the single-target call before input
/// validation is what stops a disqualified file from being decoded whole just
/// to be refused by its header a moment later.
fn refuse_over_duration(path: &Path, max_duration: f64) -> Result<(), Error> {
    if let Some(seconds) = audio::probe_duration(path) {
        if seconds > max_duration {
            return Err(Error::DurationCap);
        }
    }
    Ok(())
}

fn transcribe_path(
    ctx: &Ctx<'_>,
    path: &Path,
    knobs: &ResolvedKnobs<'_>,
    source: &'static str,
) -> Result<TranscriptionResult, Error> {
    let started = Instant::now();

    refuse_over_duration(path, knobs.max_duration)?;

    let pcm = if audio::is_video_path(path) {
        decode_via_helper(ctx.paths, &knobs.helper, path, knobs.deadline)?
    } else {
        match decode_path_with_hint(path, knobs.input_format) {
            Ok(p) => p,
            Err(e)
                if e.is_decode_fault()
                    && helper_retry_allowed(&knobs.helper, knobs.helper_fallback) =>
            {
                decode_via_helper(ctx.paths, &knobs.helper, path, knobs.deadline).map_err(
                    |helper_err| {
                        // A stopped invocation must not be reported as a decode
                        // fault; the original error only wins when the retry
                        // genuinely failed to decode.
                        if is_invocation_fatal(&helper_err) {
                            helper_err
                        } else {
                            e
                        }
                    },
                )?
            }
            Err(e) => return Err(e),
        }
    };
    finish_pcm(ctx, pcm, path.display().to_string(), source, knobs, started)
}

/// Extract a track with the persisted helper into a tracked temporary dir.
///
/// The path is derived and registered *before* the directory exists, so a
/// forced exit cannot land in a window where the directory is on disk but
/// unknown to the cleanup list. A forced exit skips destructors, which is why
/// the `tempfile` guard alone is not enough.
fn decode_via_helper(
    paths: &AppPaths,
    helper: &str,
    path: &Path,
    deadline: Option<Instant>,
) -> Result<PcmData, Error> {
    let work = paths.work_dir().join(Uuid::now_v7().to_string());
    crate::signal::register_temp(&work);
    let result = std::fs::create_dir_all(&work)
        .map_err(Error::Io)
        .and_then(|()| crate::media_helper::extract_with_helper(helper, path, &work, deadline))
        .and_then(|wav| audio::decode_file(&wav));
    let _ = std::fs::remove_dir_all(&work);
    crate::signal::release_temp(&work);
    result
}

/// Decode a file, honouring a forced container when the caller declared one.
///
/// A file with no extension still has to enter, which is why the forced format
/// must reach the file path and not only the stdin path.
fn decode_path_with_hint(path: &Path, forced: Option<&str>) -> Result<PcmData, Error> {
    match forced {
        // Streamed, like the unforced path. Reading the file whole to answer a
        // question the first twelve bytes settle put the entire recording —
        // twice — in memory, and did it below every memory checkpoint.
        Some(format) => audio::decode_file_with_format(path, format),
        None => audio::decode_file(path),
    }
}

fn finish_pcm(
    ctx: &Ctx<'_>,
    pcm: PcmData,
    file: String,
    source: &'static str,
    knobs: &ResolvedKnobs<'_>,
    started: Instant,
) -> Result<TranscriptionResult, Error> {
    let (language, language_source) = (knobs.language, knobs.language_source);
    let (entry, model_path, device) = (knobs.entry, knobs.model_path, knobs.device);
    let (beam, vad, deadline) = (knobs.beam, knobs.vad, knobs.deadline);
    if pcm.duration_seconds() > knobs.max_duration {
        return Err(Error::DurationCap);
    }
    if let Some(d) = deadline {
        if Instant::now() > d {
            return Err(Error::Timeout);
        }
    }
    let samples = audio::to_16k_mono(&pcm)?;
    // Checked right after decoding, which is where a long recording actually
    // costs memory, and again after inference. Checking only before the run
    // measured nothing the flag claims to measure.
    gpu::ensure_process_memory(knobs.max_memory)?;
    let chunks = audio::vad_chunks(&samples, vad, &knobs.vad_settings);
    // Both branches build a second buffer alongside `samples`, and the empty
    // branch copies it whole. That doubling is known before it happens, so the
    // cap gets to refuse it rather than discover it afterwards.
    let second_buffer: u64 = if chunks.is_empty() {
        samples.len() as u64 * 4
    } else {
        chunks
            .iter()
            .map(|(s, e)| (e.min(&samples.len()).saturating_sub(*s)) as u64 * 4)
            .sum()
    };
    gpu::ensure_headroom(second_buffer)?;
    // Borrow when there is no cut, own only when there is one. The empty branch
    // used to `clone()` the whole buffer, and with the shipped default of
    // `--vad 0` the chunks are ALWAYS empty, so the product's normal route paid
    // a full copy of the audio — 76 MiB for twenty minutes at 16 kHz — to hand
    // the engine bytes it already had. `engine::transcribe` takes `&[f32]`, so
    // nothing downstream needed the owned copy in the first place.
    //
    // The `with_capacity` is not a guess: `second_buffer` above is the exact
    // byte count of this vector, computed so the cap could refuse it. Growing
    // by doubling instead would realloc and copy tens of MiB repeatedly, and
    // the transient peak could trip the very cap that was just checked.
    let (used, vad_chunks): (Cow<'_, [f32]>, usize) = if chunks.is_empty() {
        (Cow::Borrowed(samples.as_slice()), 0usize)
    } else {
        let mut joined = Vec::with_capacity(second_buffer as usize / 4);
        for (s, e) in &chunks {
            let piece = &samples[*s..(*e).min(samples.len())];
            let start = joined.len();
            joined.extend_from_slice(piece);
            crate::audio::ramp_edges(&mut joined[start..]);
        }
        (Cow::Owned(joined), chunks.len())
    };
    let out = crate::engine::transcribe(&crate::engine::TranscribeRequest {
        model_path,
        samples: &used,
        language,
        beam,
        device,
        deadline,
    })?;
    gpu::ensure_process_memory(knobs.max_memory)?;
    let filtered = audio::filter_hallucinations(&out.text, knobs.hallucination);
    let hallucinations_removed = filtered.removed;
    let cleaned = audio::collapse_consecutive_repeats(&filtered.text);
    // Detection resolves the code, so the envelope must say where it came from.
    let language_source = if out.language_detected {
        "detection"
    } else {
        language_source
    };
    Ok(TranscriptionResult {
        schema_version: SCHEMA_VERSION,
        correlation_id: ctx.correlation_id.to_string(),
        target_resolved: file.clone(),
        target_source: source.to_string(),
        file,
        language: out.language,
        language_source: language_source.to_string(),
        model: entry.name.clone(),
        device,
        duration_seconds: pcm.duration_seconds(),
        text: cleaned,
        // The engine timed these against the buffer it was handed, which is the
        // speech with the pauses removed. Put them back on the recording's clock
        // before anyone uses them to cut the file. With no cut, `chunks` is
        // empty and the mapping is the identity.
        segments: if knobs.timestamps {
            Some(
                out.segments
                    .into_iter()
                    .map(|s| Segment {
                        start: audio::source_time(&chunks, samples.len(), s.start),
                        end: audio::source_time(&chunks, samples.len(), s.end),
                        text: s.text,
                    })
                    .collect(),
            )
        } else {
            None
        },
        vad_chunks,
        hallucinations_removed,
        processing_time_ms: started.elapsed().as_millis(),
        // Reported by the engine, which is the only layer that knows whether
        // the weights were loaded or reused.
        cold_load: out.cold_load,
    })
}

/// Bytes read from stdin between two memory-cap checks.
///
/// Small enough that the overshoot is the buffer's own growth step rather than
/// the size of the stream, and large enough that reading `/proc/self/statm`
/// once per chunk is noise next to the I/O it guards.
const STDIN_CHUNK: usize = 64 * 1024;

/// Read the recording from stdin, refusing early on the operator's limits.
///
/// `max_duration` is consulted here rather than after the read because stdin is
/// a stream the caller is still writing. A cap checked afterwards has already
/// let a multi-gigabyte pipe through to refuse it, which costs the host the
/// very memory the refusal exists to protect. The file path answers the same
/// question from the header without reading the recording at all; this is the
/// closest a stream can get to that.
fn read_stdin(no_input: bool, max_duration: f64, forced: Option<&str>) -> Result<Vec<u8>, Error> {
    // `--no-input` is a declarative refusal: it must fail before touching the
    // descriptor, not only when the descriptor happens to be a terminal.
    if no_input {
        return Err(Error::NoInput);
    }
    if std::io::stdin().is_terminal() {
        return Err(Error::NoInput);
    }
    // Read in chunks rather than `read_to_end`, so the memory cap is consulted
    // while the bytes are still arriving. Both decode loops already poll it,
    // but stdin reached the decoder with the whole stream already resident:
    // under a fixed 20 MiB cap the file path stayed flat at 19 MiB while the
    // stdin path tracked the input up to 7.75 times the cap. A cap enforced
    // only after the allocation has landed does not protect the host.
    let mut buf = Vec::new();
    let mut stdin = std::io::stdin().lock();
    let mut chunk = [0u8; STDIN_CHUNK];
    // The header carries the declared frame count, so the duration is known
    // long before the recording is. Asked once, as soon as enough bytes have
    // arrived for the probe to answer: asking on every chunk would re-probe the
    // same header for the whole read.
    let mut duration_checked = false;
    let read = loop {
        if crate::gpu::memory_cap_exceeded() {
            return Err(Error::MemoryCap);
        }
        if !duration_checked && buf.len() >= audio::probe_prefix() {
            duration_checked = true;
            if let Some(seconds) = audio::probe_duration_bytes(&buf, forced) {
                if seconds > max_duration {
                    return Err(Error::DurationCap);
                }
            }
        }
        match std::io::Read::read(&mut stdin, &mut chunk) {
            Ok(0) => break Ok(()),
            Ok(n) => buf.extend_from_slice(&chunk[..n]),
            Err(e) => break Err(e),
        }
    };
    // A signal ends the blocking read and leaves the buffer empty. Reporting
    // "no audio input" then tells the agent it forgot to pass a file, when in
    // fact the operator cancelled: the cause has to be checked before the
    // symptom. The batch path already got this right; only stdin did not.
    if let Some(err) = crate::signal::shutdown_error() {
        return Err(err);
    }
    read?;
    if buf.is_empty() {
        return Err(Error::NoInput);
    }
    Ok(buf)
}

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

    /// FR-039 and FR-040: an interrupt or a blown deadline ends the whole
    /// invocation, so it must reach the exit code even in NDJSON batch mode
    /// where per-target failures are emitted as lines.
    #[test]
    fn invocation_conditions_are_fatal() {
        for err in [
            Error::Timeout,
            Error::Interrupted,
            Error::Terminated,
            Error::BrokenPipe,
        ] {
            assert!(is_invocation_fatal(&err), "{err} must fail the invocation");
        }
    }

    /// A fault that belongs to one file must not fail the whole batch.
    #[test]
    fn per_target_faults_are_not_fatal() {
        for err in [
            Error::InputNotFound { path: "x".into() },
            Error::UnsupportedFormat {
                format: "xyz".into(),
            },
            Error::AudioDecode(anyhow::anyhow!("bad")),
            Error::HelperMissing,
        ] {
            assert!(!is_invocation_fatal(&err), "{err} must stay per-target");
        }
    }

    /// The propagated condition must keep the contract exit code.
    #[test]
    fn fatal_clone_preserves_the_exit_code() {
        for err in [
            Error::Timeout,
            Error::Interrupted,
            Error::Terminated,
            Error::BrokenPipe,
        ] {
            assert_eq!(clone_fatal(&err).exit_code(), err.exit_code());
        }
    }

    /// FR-013: the helper is only retried when one is actually configured.
    #[test]
    fn helper_retry_needs_a_configured_helper() {
        assert!(!helper_retry_allowed("", true), "no helper means no retry");
        assert!(
            !helper_retry_allowed("   ", true),
            "blank helper means no retry"
        );
        assert!(
            !helper_retry_allowed("/usr/bin/ffmpeg", false),
            "opt-in required"
        );
        assert!(helper_retry_allowed("/usr/bin/ffmpeg", true));
    }

    /// The rescue answers "I cannot read these bytes", and nothing else.
    ///
    /// Retrying a blown memory cap costs the host a second decoder while it is
    /// already over the ceiling that refusal exists to defend: measured, peak
    /// RSS across the process tree tripled. A deadline and a signal are the
    /// same class — the invocation is over, and a second reader cannot reopen
    /// it.
    #[test]
    fn only_a_decode_fault_reaches_the_helper() {
        assert!(Error::AudioDecode(anyhow::anyhow!("bad frame")).is_decode_fault());
        assert!(Error::UnsupportedFormat {
            format: "opus".into()
        }
        .is_decode_fault());
        for err in [
            Error::MemoryCap,
            Error::DurationCap,
            Error::Timeout,
            Error::Interrupted,
            Error::Terminated,
            Error::BrokenPipe,
        ] {
            assert!(
                !err.is_decode_fault(),
                "{err} is a verdict on the run, not on the container"
            );
        }
    }
}

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

    /// FR-003: N targets must produce N lines plus the summary, even when the
    /// batch is abandoned mid-way. A summary whose total exceeds ok+failed
    /// leaves the agent unable to tell which targets were never attempted.
    #[test]
    fn abandoning_a_batch_still_accounts_for_every_target() {
        // Simulates the accounting run_targets performs when it stops early.
        let total = 5usize;
        let done = 2usize;
        let mut out: Vec<Result<(), Error>> = (0..done).map(|_| Ok(())).collect();
        for _ in 0..(total - out.len()) {
            out.push(Err(clone_fatal(&Error::Timeout)));
        }
        assert_eq!(out.len(), total, "every target must be accounted for");
        let ok = out.iter().filter(|r| r.is_ok()).count();
        let failed = out.iter().filter(|r| r.is_err()).count();
        assert_eq!(ok + failed, total, "ok+failed must equal total");
        assert_eq!(ok, done);
    }

    /// An unclassified shutdown must not be silently dropped.
    #[test]
    fn unclassified_shutdown_still_yields_a_fatal_error() {
        let err = crate::signal::shutdown_error().unwrap_or(Error::Interrupted);
        assert!(is_invocation_fatal(&err));
        assert!(matches!(err.exit_code(), 130 | 143,));
    }
}