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
//! Agent-native payload reduction. The binary cuts JSON before the model sees it.

use serde_json::{Map, Value};

/// Flags that reshape structured stdout.
#[derive(Debug, Clone, Default)]
pub struct Surface {
    /// `key=value` predicates every emitted row must satisfy.
    pub filter: Vec<String>,
    /// Keys kept in each row; every other key is dropped.
    pub select: Vec<String>,
    /// Ceiling on the number of rows emitted.
    pub limit: Option<usize>,
    /// Key the rows are ordered by.
    pub sort: Option<String>,
    /// Key whose repeated values collapse to the first row seen.
    pub dedupe_by: Option<String>,
    /// Emit the row count instead of the rows themselves.
    pub count_only: bool,
    /// Ceiling on the length of each string value, in characters.
    pub truncate_content: Option<usize>,
    /// Ceiling on the whole payload, in bytes.
    pub max_output_bytes: Option<usize>,
}

impl Surface {
    /// True when any reduction knob is active.
    pub fn active(&self) -> bool {
        !self.filter.is_empty()
            || !self.select.is_empty()
            || self.limit.is_some()
            || self.sort.is_some()
            || self.dedupe_by.is_some()
            || self.count_only
            || self.truncate_content.is_some()
            || self.max_output_bytes.is_some()
    }

    /// Apply the fixed order: filter, sort, dedupe, limit, select, count, truncate, max-bytes.
    pub fn apply(&self, mut value: Value) -> Result<Value, crate::error::Error> {
        if is_failure(&value) || is_summary(&value) {
            return Ok(value);
        }
        for expr in &self.filter {
            let _ = parse_filter(expr)?;
        }
        if let Some(arr) = find_array_mut(&mut value) {
            // `take` already MOVES the array out of the document, so the
            // `.as_array().cloned()` that used to follow duplicated every row
            // immediately after taking ownership of them. On a batch with many
            // segments that clone was the process's memory peak, paid inside
            // the one code path whose entire purpose is to make the payload
            // smaller.
            let mut rows = match arr.take() {
                Value::Array(rows) => rows,
                _ => Vec::new(),
            };
            rows = apply_filters(rows, &self.filter)?;
            if let Some(key) = &self.sort {
                rows.sort_by(|a, b| cmp_key(a, b, key));
            }
            if let Some(key) = &self.dedupe_by {
                rows = dedupe(rows, key);
            }
            if let Some(n) = self.limit {
                rows.truncate(n);
            }
            if !self.select.is_empty() {
                rows = rows
                    .into_iter()
                    .map(|row| project(row, &self.select))
                    .collect();
            }
            if self.count_only {
                return Ok(counted(&value, rows.len()));
            }
            *arr = Value::Array(rows);
        } else if !self.filter.is_empty() || self.limit == Some(0) {
            // An envelope with no row array is one result, so the row flags
            // still mean something: a predicate it fails, or a limit of zero,
            // reduces it to none. Both used to be silent no-ops — `--filter
            // name=absent version` returned the full document with exit 0, an
            // answer that does not satisfy the predicate the caller gave.
            //
            // Emptying to the identity envelope is the singular form of the
            // empty array the same flags produce on a list, and it keeps
            // working line by line in an NDJSON batch, where each line is its
            // own document.
            let keep = self.limit != Some(0)
                && apply_filters(vec![value.clone()], &self.filter)?.len() == 1;
            if !keep {
                // `--count-only` still governs the shape of the answer: the
                // count is simply zero. Returning the emptied envelope here
                // instead would drop the count the caller asked for.
                if self.count_only {
                    return Ok(counted(&value, 0));
                }
                let mut empty = serde_json::json!({});
                carry_envelope_identity(&value, &mut empty);
                return Ok(empty);
            }
            if self.count_only {
                return Ok(counted(&value, 1));
            }
        } else if self.count_only {
            // An envelope with no row array is one result, and saying so is the
            // only honest answer. It used to fall through and emit the whole
            // payload: `--count-only` on `version`, `config path`, `locale
            // show` or a single-target `transcribe` returned everything, in
            // silence. FR-027 exists for "o agente que economiza token", so
            // answering a request to count with the full document is the exact
            // inverse of what was asked.
            return Ok(counted(&value, 1));
        } else if !self.select.is_empty() {
            // No array, so `--select` projects the envelope itself, and the
            // caller named every key they wanted. Adding identity back here
            // would hand them fields they did not ask for, which is the one
            // thing a projection must not do — `select_projects_version_name`
            // pins that. The asymmetry against the array case is real but
            // deliberate: there `--select` projects the rows, not the envelope,
            // so the envelope was never the thing being narrowed.
            value = project(value, &self.select);
        }
        if let Some(n) = self.truncate_content {
            if truncate_strings(&mut value, n) {
                if let Some(obj) = value.as_object_mut() {
                    obj.insert("content_truncated".to_string(), Value::Bool(true));
                }
            }
        }
        if let Some(max) = self.max_output_bytes {
            value = cap_bytes(value, max);
        }
        Ok(value)
    }
}

/// The two fields that tie a response to the request that caused it.
///
/// The PRD keeps the success envelope for exactly this reason — "id e versão
/// ligam pedido e resposta" — so no reduction flag may drop them. Reducing a
/// payload is not the same as removing the label on it.
const ENVELOPE_IDENTITY: &[&str] = &["schema_version", "correlation_id"];

/// The `--count-only` answer: a count that still says which request it answers.
fn counted(source: &Value, n: usize) -> Value {
    let mut out = serde_json::json!({ "count": n });
    carry_envelope_identity(source, &mut out);
    out
}

/// Copy the envelope's identity onto a reshaped document that lost it.
fn carry_envelope_identity(source: &Value, target: &mut Value) {
    let (Some(from), Some(to)) = (source.as_object(), target.as_object_mut()) else {
        return;
    };
    for key in ENVELOPE_IDENTITY {
        if let Some(v) = from.get(*key) {
            to.entry((*key).to_string()).or_insert_with(|| v.clone());
        }
    }
}

/// A batch summary line carries its own keys (`ok`, `failed`, `total`), so
/// projection must never strip it: `--select` cuts file rows only.
fn is_summary(value: &Value) -> bool {
    value.get("summary").and_then(Value::as_bool) == Some(true)
}

fn is_failure(value: &Value) -> bool {
    value.get("error").and_then(Value::as_bool) == Some(true)
        || value.get("ok").and_then(Value::as_bool) == Some(false)
}

/// Names consulted only when an envelope carries more than one array.
///
/// This used to be the sole way the row array was found, and it was inherited
/// from another product: `results`, `items`, `entities`, `memories`, `hits` and
/// `matches` are emitted by no verb here, while `licenses`, `commands`,
/// `schemas` and `segments` — four of the seven arrays this product actually
/// publishes — were absent. Every agent-native flag was therefore silently
/// inert on `licenses`, `commands`, `schema` and on `transcribe --timestamps`,
/// which is the one array that grows without bound.
///
/// A hand-maintained list of names is the defect, not the missing entries, so
/// it is no longer the primary rule.
const PREFERRED_ROW_KEYS: &[&str] = &[
    "models", "checks", "keys", "licenses", "commands", "schemas", "segments",
];

/// The array of rows the shaping flags operate on.
///
/// Every envelope this product emits carries at most one top-level array, so
/// the array itself identifies the rows and no list has to be kept in step with
/// the verbs. The names above are only a tie-break, kept for the day an
/// envelope carries two.
fn find_array_mut(value: &mut Value) -> Option<&mut Value> {
    let obj = value.as_object_mut()?;
    let arrays: Vec<String> = obj
        .iter()
        .filter(|(_, v)| v.is_array())
        .map(|(k, _)| k.clone())
        .collect();

    let chosen = match arrays.as_slice() {
        [] => return None,
        [only] => only.clone(),
        many => PREFERRED_ROW_KEYS
            .iter()
            .find(|k| many.iter().any(|a| a == *k))
            .map(|k| (*k).to_string())?,
    };
    obj.get_mut(&chosen)
}

fn apply_filters(rows: Vec<Value>, filters: &[String]) -> Result<Vec<Value>, crate::error::Error> {
    let mut out = rows;
    for expr in filters {
        let pred = parse_filter(expr)?;
        out.retain(|row| pred(row));
    }
    Ok(out)
}

/// A compiled `--filter` expression.
type RowPredicate = Box<dyn Fn(&Value) -> bool>;

fn parse_filter(expr: &str) -> Result<RowPredicate, crate::error::Error> {
    if let Some((k, v)) = expr.split_once("~") {
        let k = k.to_string();
        let v = v.to_string();
        return Ok(Box::new(move |row| {
            dotted(row, &k).map(|s| s.contains(&v)).unwrap_or(false)
        }));
    }
    if let Some((k, v)) = expr.split_once("!=") {
        let k = k.to_string();
        let v = v.to_string();
        return Ok(Box::new(move |row| {
            dotted(row, &k).map(|s| s != v).unwrap_or(true)
        }));
    }
    if let Some((k, v)) = expr.split_once("==").or_else(|| expr.split_once('=')) {
        let k = k.to_string();
        let v = v.to_string();
        return Ok(Box::new(move |row| {
            dotted(row, &k).map(|s| s == v).unwrap_or(false)
        }));
    }
    Err(crate::error::Error::Usage(format!(
        "malformed filter: {expr}"
    )))
}

fn dotted(row: &Value, key: &str) -> Option<String> {
    let mut cur = row;
    for part in key.split('.') {
        cur = cur.get(part)?;
    }
    match cur {
        Value::String(s) => Some(s.clone()),
        Value::Number(n) => Some(n.to_string()),
        Value::Bool(b) => Some(b.to_string()),
        _ => Some(cur.to_string()),
    }
}

fn cmp_key(a: &Value, b: &Value, key: &str) -> std::cmp::Ordering {
    use std::cmp::Ordering;
    match (dotted(a, key), dotted(b, key)) {
        (Some(x), Some(y)) => match (x.parse::<f64>(), y.parse::<f64>()) {
            (Ok(xn), Ok(yn)) => xn.partial_cmp(&yn).unwrap_or(Ordering::Equal),
            _ => x.cmp(&y),
        },
        (Some(_), None) => Ordering::Less,
        (None, Some(_)) => Ordering::Greater,
        (None, None) => Ordering::Equal,
    }
}

fn dedupe(rows: Vec<Value>, key: &str) -> Vec<Value> {
    let mut seen = std::collections::BTreeSet::new();
    let mut out = Vec::new();
    for row in rows {
        match dotted(&row, key) {
            Some(v) if !seen.insert(v.clone()) => {}
            _ => out.push(row),
        }
    }
    out
}

fn project(row: Value, keys: &[String]) -> Value {
    let mut map = Map::new();
    for key in keys {
        if let Some(v) = dotted_value(&row, key) {
            insert_dotted(&mut map, key, v);
        }
    }
    Value::Object(map)
}

fn dotted_value(row: &Value, key: &str) -> Option<Value> {
    let mut cur = row;
    for part in key.split('.') {
        cur = cur.get(part)?;
    }
    Some(cur.clone())
}

fn insert_dotted(map: &mut Map<String, Value>, key: &str, value: Value) {
    // One `split_once` decides both cases. The previous shape asked
    // `contains('.')` first and then unwrapped the split, so the invariant that
    // made the unwrap safe lived in a different statement from the unwrap
    // itself — safe today, and one edit away from an exit 101 in a binary whose
    // exit table has no entry for a panic.
    let Some((head, rest)) = key.split_once('.') else {
        map.insert(key.to_string(), value);
        return;
    };
    let entry = map
        .entry(head.to_string())
        .or_insert_with(|| Value::Object(Map::new()));
    if let Some(child) = entry.as_object_mut() {
        insert_dotted(child, rest, value);
    }
}

/// Visible cut marker appended to every truncated string.
const TRUNCATION_MARKER: char = '…';

/// Shorten every string past `max_chars` and report whether anything was cut.
///
/// The marker counts toward the budget: the result is never longer than
/// `max_chars` characters, so a limit of 1 yields the marker alone and a limit
/// of 0 yields an empty string. Counting is done in characters, never bytes, so
/// a multi-byte character is never split.
// `any` short-circuits, and this function mutates in place. Swapping the fold
// for it would stop at the first string that needed shortening and leave every
// later one at full length, silently defeating the limit the caller asked for.
// The `|| acc` order matters for the same reason: the call has to run first.
#[allow(clippy::unnecessary_fold)]
/// Fields that hold transcription content, the only thing FR-028 shortens.
///
/// This replaced a thirty-entry allowlist of identity fields, and the swap is
/// the point rather than the entries. Protecting identity by name means the
/// list grows with every field the product gains, and it was already wrong
/// three times: two drafts missed whole verbs, and even the cured list could
/// not protect a value travelling under a generic key. `doctor` proved that
/// last part inside one envelope — `engine: "stub"` survived at the top while
/// the same fact became `"st…"` under `checks[].detail`, and the absolute path
/// of `nvcc` became `"/t…"`.
///
/// Content is the closed set here: FR-028 says "agente com fala longa" and
/// "transcrição longa não explode o contexto". A CLI that emits one kind of
/// prose can name that prose, and everything else is identity by default.
/// Envelope keys that hold prose, seeding `config content-keys`.
pub const CONTENT_KEYS: &[&str] = &["text"];

/// The prose keys in force for this invocation.
///
/// Published once, like the container lists in `audio`, because the two places
/// that consult it sit inside the recursive walk and threading a parameter
/// through it would touch every arm for one value that never changes.
static ACTIVE_CONTENT_KEYS: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();

/// Publish the operator's prose keys. Called once, before any reduction.
pub fn publish_content_keys(keys: Vec<String>) {
    let _ = ACTIVE_CONTENT_KEYS.set(keys);
}

/// True when this key holds prose that `--truncate-content` may shorten.
fn is_content_key(key: &str) -> bool {
    ACTIVE_CONTENT_KEYS.get().map_or_else(
        || CONTENT_KEYS.contains(&key),
        |keys| keys.iter().any(|k| k == key),
    )
}

/// Truncate a string without splitting a letter from the marks that spell it.
///
/// Counting `chars` keeps the output valid UTF-8, which is necessary and not
/// sufficient. A letter written in decomposed form is a base character followed
/// by combining marks — `e` plus U+0301 spells `é` — and a cut between them
/// does not corrupt the encoding, it silently changes the letter. Measured on
/// `"caf" + "e\u{301}" + "x"` under a five character cap: the old code emitted
/// `cafe…`, having dropped an accent nobody asked it to drop.
///
/// FR-054 states the requirement as "texto longo cortado não parte letra
/// acentuada", so an accent that disappears is the defect the criterion names,
/// even though the JSON stays well formed.
///
/// The cut retreats past any marks rather than keeping them: a mark with no
/// base is not a letter either, and dropping the whole cluster is the only
/// choice that leaves every remaining letter as it was written.
fn truncate_scalar(value: &mut Value, max_chars: usize) -> bool {
    let Value::String(s) = value else {
        return false;
    };
    if s.chars().count() <= max_chars {
        return false;
    }
    let chars: Vec<char> = s.chars().collect();
    let mut keep = max_chars.saturating_sub(1);
    // Walk back while the first discarded character belongs to the last kept
    // one. Bounded by `keep`, and a string of nothing but marks simply empties.
    while keep > 0
        && chars
            .get(keep)
            .is_some_and(|c| unicode_normalization::char::is_combining_mark(*c))
    {
        keep -= 1;
    }
    let mut out: String = chars.iter().take(keep).collect();
    if max_chars > 0 {
        out.push(TRUNCATION_MARKER);
    }
    *s = out;
    true
}

fn truncate_strings(value: &mut Value, max_chars: usize) -> bool {
    match value {
        // A bare string with no key above it carries no name to judge by, so
        // it is left alone: only a named content field is content.
        Value::String(_) => false,
        // Deliberately not `any`: the closure mutates, and `any` short-circuits
        // on the first hit, which would leave every later element uncut.
        Value::Array(items) => {
            let mut cut = false;
            for v in items.iter_mut() {
                cut |= truncate_strings(v, max_chars);
            }
            cut
        }
        Value::Object(map) => map.iter_mut().fold(false, |acc, (key, v)| {
            // Descend until a content field is named, then shorten everything
            // under it. Nothing else in an envelope is content.
            //
            // A named content key only counts when it holds prose: a string, or
            // an array of them. In a published JSON Schema `text` is a property
            // NAME whose value is `{"type":"string"}`, and shortening under it
            // turned the contract into `{"type":"st…"}` — a JSON Schema that is
            // not one. Matching by key name has this failure in both
            // directions, and the value's shape is what separates the two.
            if is_content_key(key.as_str()) && holds_prose(v) {
                return truncate_all_strings(v, max_chars) || acc;
            }
            truncate_strings(v, max_chars) || acc
        }),
        _ => false,
    }
}

/// True when a value is prose rather than structure.
///
/// A string is prose. An array of strings is prose. An object is not: in a
/// contract document a content-named key can hold a type declaration, and
/// shortening that produces something that still parses while no longer being
/// what it claims.
fn holds_prose(value: &Value) -> bool {
    match value {
        Value::String(_) => true,
        Value::Array(items) => items.iter().all(|v| matches!(v, Value::String(_))),
        _ => false,
    }
}

/// Shorten every string beneath a node already known to be content.
fn truncate_all_strings(value: &mut Value, max_chars: usize) -> bool {
    match value {
        Value::String(_) => {
            let mut scalar = value.take();
            let cut = truncate_scalar(&mut scalar, max_chars);
            *value = scalar;
            cut
        }
        // Same reason as above: mutation plus short-circuit would skip work.
        Value::Array(items) => {
            let mut cut = false;
            for v in items.iter_mut() {
                cut |= truncate_all_strings(v, max_chars);
            }
            cut
        }
        Value::Object(map) => {
            let mut cut = false;
            for (_, v) in map.iter_mut() {
                cut |= truncate_all_strings(v, max_chars);
            }
            cut
        }
        _ => false,
    }
}

/// Drop trailing rows until the encoded envelope fits, never splitting the text.
///
/// Two defects lived here, and both were measured on the binary.
///
/// It kept a second hand-maintained list of row keys, separate from the one
/// `find_array_mut` used, so fixing that one left this one broken: the cap was
/// inert on `licenses`, `commands`, `schemas` and `segments`. It now shares the
/// single locator, so there is one place to be wrong instead of two.
///
/// Worse, when even the empty envelope exceeded the cap it returned the
/// original untouched — `--max-output-bytes 50` answered with 1260 bytes, over
/// twenty times the request. That is fail-open on the flag whose whole purpose
/// is protecting the caller's context, and it failed hardest at the smallest
/// cap, which is when the caller needs it most. The floor is now the emptied
/// envelope, which is the smallest honest answer available, and it says so.
fn cap_bytes(value: Value, max: usize) -> Value {
    if encoded_len(&value) <= max {
        return value;
    }
    let original = value.clone();
    let mut value = value;

    // Stage one: drop trailing rows, if this envelope has any.
    //
    // An envelope with no array used to return here, which meant the content
    // shortening below was unreachable for it. Measured by an independent
    // reviewer: `transcribe` without `--timestamps` serialises no `segments`
    // array, so `--max-output-bytes 500` on five minutes of audio answered
    // with 11331 bytes — larger than the 11307 it returns with no cap at all,
    // because the only thing the cap did was add its own flag. The same held
    // for `version`, `config path` and `locale show`.
    //
    // My own test missed it by passing `--timestamps` on every transcribe
    // invocation, so it only ever exercised the branch that worked.
    if find_array_mut(&mut value).is_some() {
        let mut rows = find_array_mut(&mut value)
            .and_then(|a| a.as_array().cloned())
            .unwrap_or_default();
        while !rows.is_empty() {
            rows.pop();
            let mut clone = value.clone();
            if let Some(target) = find_array_mut(&mut clone) {
                *target = Value::Array(rows.clone());
            }
            if let Some(fitted) = fits(&original, &clone, max) {
                return fitted;
            }
        }
        if let Some(target) = find_array_mut(&mut value) {
            *target = Value::Array(Vec::new());
        }
        if let Some(fitted) = fits(&original, &value, max) {
            return fitted;
        }
    }

    // Stage two: shorten content until it fits.
    //
    // Dropping rows is not enough when the bulk is a single content string,
    // and for the verbs above there are no rows at all. Shortening a content
    // value is not "splitting the JSON text": the document stays well-formed
    // and identity stays whole, which is the same line `--truncate-content`
    // draws. Halving converges in a few passes and needs no arithmetic about
    // encoding overhead.
    let mut limit = longest_content_len(&value);
    while limit > 0 {
        limit /= 2;
        let mut clone = value.clone();
        if truncate_strings(&mut clone, limit) {
            // Content shortened here is content shortened, whichever flag
            // caused it. Raising only `output_truncated` left a consumer
            // reading a cut transcript with no `content_truncated` to warn it,
            // which is the flag the published contract ties to that fact.
            if let Some(obj) = clone.as_object_mut() {
                obj.insert("content_truncated".to_string(), Value::Bool(true));
            }
        }
        if let Some(fitted) = fits(&original, &clone, max) {
            return fitted;
        }
    }

    // The identity envelope is the floor: schema_version, correlation_id and
    // the target cannot be dropped without answering a different question than
    // the one asked.
    truncate_strings(&mut value, 0);
    announce_if_changed(&original, value)
}

/// Accept a candidate only if it fits AFTER it is marked.
///
/// The size used to be checked on the unmarked candidate, and
/// `announce_if_changed` then added `output_truncated` on the way out. That
/// flag is around two dozen bytes spent outside the budget that had just been
/// approved, so `--max-output-bytes 8000` could answer with 8003 and the
/// ceiling the flag promises was not a ceiling. Marking first and measuring the
/// marked document is the only order in which the answer is bounded by what the
/// caller asked for.
fn fits(original: &Value, candidate: &Value, max: usize) -> Option<Value> {
    let marked = announce_if_changed(original, candidate.clone());
    (encoded_len(&marked) <= max).then_some(marked)
}

/// Flag the result only when something was actually removed.
///
/// Marking unconditionally made the cap grow the envelope by the 24 bytes of
/// its own flag while changing nothing else — `--max-output-bytes 0 version`
/// returned the untouched document plus `output_truncated: true`. An agent
/// branching on that flag concludes its data is incomplete and retries or
/// discards a whole answer. It also violated this product's own stated
/// invariant, that an untruncated answer must not claim truncation.
fn announce_if_changed(original: &Value, shaped: Value) -> Value {
    if &shaped == original {
        return shaped;
    }
    mark_output_truncated(shaped)
}

/// Characters in the longest content string, the starting point for halving.
fn longest_content_len(value: &Value) -> usize {
    match value {
        Value::Object(map) => map
            .iter()
            .map(|(k, v)| {
                if is_content_key(k.as_str()) {
                    longest_string(v)
                } else {
                    longest_content_len(v)
                }
            })
            .max()
            .unwrap_or(0),
        Value::Array(items) => items.iter().map(longest_content_len).max().unwrap_or(0),
        _ => 0,
    }
}

fn longest_string(value: &Value) -> usize {
    match value {
        Value::String(s) => s.chars().count(),
        Value::Object(map) => map.values().map(longest_string).max().unwrap_or(0),
        Value::Array(items) => items.iter().map(longest_string).max().unwrap_or(0),
        _ => 0,
    }
}

fn encoded_len(value: &Value) -> usize {
    serde_json::to_vec(value).map(|b| b.len()).unwrap_or(0)
}

/// Record that the byte cap could not be met by dropping rows alone.
///
/// Silence here would let an agent read a shortened payload as a complete one.
fn mark_output_truncated(mut value: Value) -> Value {
    if let Some(obj) = value.as_object_mut() {
        obj.insert("output_truncated".to_string(), Value::Bool(true));
    }
    value
}

#[cfg(test)]
mod tests {
    /// The cap is a ceiling, so it must hold even when the bulk is numeric.
    ///
    /// Measured: a transcribe envelope with timestamps and a long transcript
    /// came back at 8003 bytes under `--max-output-bytes 8000`. Stage one
    /// empties the segment array, but if nothing after it is recognised as
    /// content, `longest_content_len` is zero, the halving loop never runs, and
    /// the function returns whatever stage one left.
    #[test]
    fn cap_holds_when_content_is_not_the_bulk() {
        let rows: Vec<serde_json::Value> = (0..400)
            .map(|i| serde_json::json!({"start": i as f64, "end": i as f64 + 1.0}))
            .collect();
        let doc = serde_json::json!({
            "schema_version": "0.1.0",
            "correlation_id": "cid",
            "segments": rows,
        });
        let shaped = super::cap_bytes(doc, 800);
        let len = serde_json::to_vec(&shaped).expect("encode").len();
        assert!(len <= 800, "the cap did not hold: {len} bytes");
    }

    use super::*;

    #[test]
    fn select_text_only() {
        let s = Surface {
            select: vec!["text".into()],
            ..Surface::default()
        };
        let v = serde_json::json!({"results":[{"text":"hi","file":"a.wav"}]});
        let out = s.apply(v).unwrap();
        assert_eq!(out["results"][0]["text"], "hi");
        assert!(out["results"][0].get("file").is_none());
    }

    #[test]
    fn filter_does_not_hide_error() {
        let s = Surface {
            filter: vec!["text=nope".into()],
            ..Surface::default()
        };
        let v = serde_json::json!({"error":true,"ok":false,"message":"x"});
        let out = s.apply(v).unwrap();
        assert_eq!(out["error"], true);
    }

    #[test]
    fn summary_survives_select() {
        let s = Surface {
            select: vec!["text".into()],
            ..Surface::default()
        };
        let v = serde_json::json!({"summary":true,"ok":2,"failed":1,"total":3});
        let out = s.apply(v).unwrap();
        assert_eq!(out["summary"], true);
        assert_eq!(out["ok"], 2);
        assert_eq!(out["failed"], 1);
        assert_eq!(out["total"], 3);
    }

    #[test]
    fn truncate_marks_and_flags() {
        let s = Surface {
            truncate_content: Some(10),
            ..Surface::default()
        };
        let v = serde_json::json!({"results":[{"text":"abcdefghijklmnop"}]});
        let out = s.apply(v).unwrap();
        let text = out["results"][0]["text"].as_str().unwrap();
        assert!(text.ends_with('…'));
        assert_eq!(text.chars().count(), 10);
        assert_eq!(out["content_truncated"], true);
    }

    #[test]
    fn truncate_does_not_split_utf8() {
        let long = "configuração ambígua ".repeat(20);
        let s = Surface {
            // Character 11 is the multi-byte 'ç': a byte-wise cut would split it.
            truncate_content: Some(11),
            ..Surface::default()
        };
        let v = serde_json::json!({"results":[{"text":long}]});
        let out = s.apply(v).unwrap();
        let text = out["results"][0]["text"].as_str().unwrap();
        // Valid UTF-8 by construction; assert the character budget is respected.
        assert!(text.chars().count() <= 11);
        assert_eq!(text, "configuraç…");
        assert_eq!(out["content_truncated"], true);
    }

    /// `--truncate-content` used to recurse over the whole document, so the
    /// flag that shortens a transcript also shortened the fields that identify
    /// the response. A caller could not correlate a request with its answer
    /// after asking for a smaller payload.
    ///
    /// The earlier unit tests missed this because they shaped documents as
    /// `{"results":[...]}` with no envelope keys — a shape production never
    /// emits — so the truncator never met an identity field.
    #[test]
    fn truncation_never_touches_the_fields_that_identify_the_response() {
        let s = Surface {
            truncate_content: Some(8),
            ..Surface::default()
        };
        let v = serde_json::json!({
            "schema_version": "0.1.0",
            "correlation_id": "0198c0de-dead-beef-cafe-000000000000",
            "file": "/very/long/path/to/some/recording.wav",
            "model": "large-v3",
            "language_source": "detection",
            "results": [{"text": "a transcript long enough to be shortened"}],
        });
        let out = s.apply(v).unwrap();

        assert_eq!(
            out["correlation_id"],
            "0198c0de-dead-beef-cafe-000000000000"
        );
        assert_eq!(out["schema_version"], "0.1.0");
        assert_eq!(out["file"], "/very/long/path/to/some/recording.wav");
        assert_eq!(out["model"], "large-v3");
        assert_eq!(out["language_source"], "detection");

        // The content the caller actually asked to shorten still shrinks.
        let text = out["results"][0]["text"].as_str().unwrap();
        assert!(text.chars().count() <= 8, "content is still truncated");
        assert_eq!(out["content_truncated"], true);
    }

    /// A digest is the one field where a truncated value is actively harmful:
    /// it still looks like a digest, and it compares unequal against the real
    /// one, so an agent checking integrity concludes the model is corrupt.
    /// The same reasoning covers the origin and the filename, which locate the
    /// model rather than describe it.
    #[test]
    fn truncation_never_shortens_a_digest_an_origin_or_a_filename() {
        let s = Surface {
            truncate_content: Some(4),
            ..Surface::default()
        };
        let listing = serde_json::json!({
            "models": [{
                "name": "tiny",
                "filename": "ggml-tiny.bin",
                "sha1": "bd577a113a864445d4c299885e0cb97d4ba92b5f",
                "url": "https://example.test/ggml-tiny.bin",
            }],
        });
        let out = s.apply(listing).unwrap();
        let row = &out["models"][0];

        assert_eq!(row["sha1"], "bd577a113a864445d4c299885e0cb97d4ba92b5f");
        assert_eq!(row["url"], "https://example.test/ggml-tiny.bin");
        assert_eq!(row["filename"], "ggml-tiny.bin");
        assert_eq!(row["name"], "tiny");
    }

    /// The flag still does its job, or trading one defect for a worse one.
    ///
    /// This assertion used to ride on an invented `notes` field, which no verb
    /// emits. That made it prove the old rule — "shorten anything not named as
    /// identity" — rather than the requirement, and it went green while
    /// `doctor` was shortening the absolute path of `nvcc`. FR-028 names the
    /// target: transcription text.
    #[test]
    fn truncation_still_shortens_the_transcription_text() {
        let s = Surface {
            truncate_content: Some(4),
            ..Surface::default()
        };
        let result = serde_json::json!({
            "file": "/long/path/to/recording.wav",
            "model": "small",
            "text": "a spoken passage long enough to need shortening",
            "segments": [
                {"start": 0.0, "end": 1.0, "text": "another long spoken passage"},
            ],
        });
        let out = s.apply(result).unwrap();

        assert!(
            out["text"].as_str().expect("text").chars().count() <= 4,
            "the one field FR-028 exists to shorten was left whole: {out}"
        );
        assert!(
            out["segments"][0]["text"]
                .as_str()
                .expect("segment text")
                .chars()
                .count()
                <= 4,
            "a segment's text is transcription too: {out}"
        );
        assert_eq!(
            out["content_truncated"], true,
            "a cut must be announced: {out}"
        );
        // The row around the content keeps its identity.
        assert_eq!(out["file"], "/long/path/to/recording.wav");
        assert_eq!(out["model"], "small");
        assert_eq!(out["segments"][0]["start"], 0.0);
    }

    /// The `version` verb's whole contract is being identical across
    /// invocations, so no output flag may alter it.
    #[test]
    fn truncation_leaves_the_version_verb_byte_identical() {
        let s = Surface {
            truncate_content: Some(4),
            ..Surface::default()
        };
        let identity = serde_json::json!({
            "schema_version": "0.1.0",
            "correlation_id": "0198c0de-dead-beef-cafe-000000000000",
            "name": "whisper-nvidia-cli",
            "version": "0.1.0",
            "contract_version": "0.1.0",
            "engine": "stub",
        });
        let out = s.apply(identity.clone()).unwrap();
        assert_eq!(out, identity, "version must survive any output shaping");
    }

    #[test]
    fn truncate_absent_when_nothing_cut() {
        let s = Surface {
            truncate_content: Some(64),
            ..Surface::default()
        };
        let v = serde_json::json!({"results":[{"text":"curto"}]});
        let out = s.apply(v).unwrap();
        assert_eq!(out["results"][0]["text"], "curto");
        assert!(out.get("content_truncated").is_none());
    }

    #[test]
    fn malformed_filter_is_usage() {
        let s = Surface {
            filter: vec!["no-operator".into()],
            ..Surface::default()
        };
        let v = serde_json::json!({"results":[{"a":1}]});
        assert!(s.apply(v).is_err());
    }
}

#[cfg(test)]
mod grapheme_truncation_tests {
    use super::*;
    use serde_json::json;

    /// FR-028: a cut must not separate a letter from the marks that spell it.
    ///
    /// This said FR-054 — "Sem telemetria" — which has nothing to do with
    /// truncating text. The traceability gate counts the identifier wherever it
    /// appears, so the wrong citation marked a privacy requirement as covered
    /// by a test that never touches the network.
    ///
    /// The encoding stays valid either way — this is not a UTF-8 bug — but a
    /// letter written in decomposed form loses its accent when the cut lands
    /// between the base and the mark, and the reader is never told.
    #[test]
    fn truncation_does_not_strip_an_accent_from_its_letter() {
        // "cafex" with a combining acute on the e: six code points, five
        // letters as anyone reading it would count.
        let decomposed = "cafe\u{301}x";
        assert_eq!(decomposed.chars().count(), 6, "six code points");

        let mut value = json!(decomposed);
        assert!(
            truncate_scalar(&mut value, 5),
            "six chars under a five cap cuts"
        );
        let out = value.as_str().expect("string");

        assert!(
            !out.contains('e') || out.contains('\u{301}'),
            "the accent was dropped and the letter silently changed: {out:?}"
        );
        assert_eq!(
            out, "caf\u{2026}",
            "the whole cluster leaves, not half of it"
        );
    }

    /// The precomposed spelling of the same word is unaffected.
    ///
    /// Without this, a fix that simply refused to keep accented letters would
    /// pass the assertion above.
    #[test]
    fn precomposed_letters_are_kept_as_normal_characters() {
        let mut value = json!("caf\u{e9}xy");
        assert!(
            truncate_scalar(&mut value, 5),
            "five code points under a five cap"
        );
        assert_eq!(
            value.as_str().expect("string"),
            "caf\u{e9}\u{2026}",
            "a precomposed letter is one character and must be kept"
        );
    }

    /// A string of nothing but marks empties rather than looping or panicking.
    #[test]
    fn a_string_of_bare_marks_terminates() {
        let mut value = json!("\u{301}\u{301}\u{301}\u{301}");
        assert!(
            truncate_scalar(&mut value, 2),
            "four chars under a two cap cuts"
        );
        assert_eq!(
            value.as_str().expect("string"),
            "\u{2026}",
            "nothing to keep"
        );
    }
}