youtube-legend-cli 0.4.0

Non-interactive Rust CLI that downloads YouTube subtitles through third-party providers, using a native Unix stdin/stdout interface.
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
//! Agent-native payload reduction applied to the JSON envelope.
//!
//! An agent that drives this CLI in a loop pays for every byte the
//! envelope carries. Piping the whole envelope through an external JSON
//! processor does not help: the bytes were already produced. This module
//! performs the cut on the [`serde_json::Value`] *before* it is
//! serialised, so the trimmed elements never reach a string buffer.
//!
//! # Operation order
//!
//! The order is fixed and is part of the contract:
//!
//! 1. `filter`
//! 2. `sort`
//! 3. `dedupe-by`
//! 4. `limit`
//! 5. `select`
//! 6. `count-only`
//! 7. `truncate-content`
//! 8. `max-output-bytes`
//!
//! # Error envelopes
//!
//! An envelope carrying `error: true` or `ok: false` is returned
//! untouched. A filter can never silence a failure: the caller always
//! sees the error it needs to branch on.
//!
//! # Example
//!
//! ```
//! use youtube_legend_cli::surface::SurfaceOptions;
//!
//! let mut opts = SurfaceOptions::default();
//! opts.select = vec!["video_id".to_string()];
//! let envelope = serde_json::json!({ "video_id": "abc", "content": "hello" });
//! let (out, report) = opts.apply(envelope);
//! assert_eq!(report.output_count, 1);
//! assert!(out.get("content").is_none());
//! ```

use crate::error::{AppError, AppResult};
use serde::Serialize;
use serde_json::{Map, Value};

/// Keys searched, in order, to locate the array of result rows inside an
/// envelope object. The first key that holds a JSON array wins.
const RESULT_ARRAY_KEYS: [&str; 6] = ["results", "items", "rows", "matches", "data", "entries"];

/// Comparison performed by a single `--filter` expression.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum FilterOp {
    /// `key=value` or `key==value` — the rendered value must be equal.
    Equals,
    /// `key!=value` — the rendered value must differ.
    NotEquals,
    /// `key~value` — the rendered value must contain the substring.
    Contains,
}

/// One parsed `--filter` expression.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Filter {
    /// Dotted path into the element, for example `info.provider`.
    pub path: String,
    /// Comparison to perform.
    pub op: FilterOp,
    /// Right-hand side, compared against the rendered scalar.
    pub value: String,
}

impl Filter {
    /// Parse a single filter expression.
    ///
    /// Accepted shapes are `key=value`, `key==value`, `key!=value` and
    /// `key~substring`. A malformed expression is a usage error, never a
    /// silently empty result set.
    ///
    /// # Errors
    ///
    /// Returns [`AppError::InvalidUsage`] when the expression carries no
    /// recognised operator or an empty key.
    pub fn parse(raw: &str) -> AppResult<Self> {
        // `!=` must be probed before `=` so that `a!=b` does not parse
        // as key `a!` equals `b`.
        let (path, op, value) = if let Some((k, v)) = raw.split_once("!=") {
            (k, FilterOp::NotEquals, v)
        } else if let Some((k, v)) = raw.split_once("==") {
            (k, FilterOp::Equals, v)
        } else if let Some((k, v)) = raw.split_once('~') {
            (k, FilterOp::Contains, v)
        } else if let Some((k, v)) = raw.split_once('=') {
            (k, FilterOp::Equals, v)
        } else {
            return Err(AppError::InvalidUsage(format!(
                "--filter {raw:?}: expected key=value, key!=value or key~substring"
            )));
        };
        let path = path.trim();
        if path.is_empty() {
            return Err(AppError::InvalidUsage(format!(
                "--filter {raw:?}: the key on the left of the operator is empty"
            )));
        }
        Ok(Self {
            path: path.to_string(),
            op,
            value: value.to_string(),
        })
    }

    /// Evaluate the filter against one element.
    ///
    /// An element that lacks the path never matches: a filter narrows,
    /// so an absent field cannot satisfy it.
    #[must_use]
    pub fn matches(&self, element: &Value) -> bool {
        let Some(found) = lookup_path(element, &self.path) else {
            return matches!(self.op, FilterOp::NotEquals);
        };
        let rendered = render_scalar(found);
        match self.op {
            FilterOp::Equals => rendered == self.value,
            FilterOp::NotEquals => rendered != self.value,
            FilterOp::Contains => rendered.contains(&self.value),
        }
    }
}

/// What the reduction layer did, reported back inside the envelope under
/// the `agent_surface` key.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct SurfaceReport {
    /// Elements the layer received.
    pub input_count: usize,
    /// Elements the layer emitted.
    pub output_count: usize,
    /// `true` when `--limit` or `--max-output-bytes` dropped elements.
    pub limited: bool,
    /// `true` when at least one string was shortened.
    pub content_truncated: bool,
    /// `true` when `--max-output-bytes` dropped elements.
    pub output_truncated: bool,
}

/// The eight agent-native reduction knobs, resolved from the command
/// line.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct SurfaceOptions {
    /// `--select` / `--fields`: dotted paths to keep. Empty means "keep
    /// everything".
    pub select: Vec<String>,
    /// `--filter`, repeatable, conjoined with AND.
    pub filters: Vec<Filter>,
    /// `--limit`: maximum number of elements emitted.
    pub limit: Option<usize>,
    /// `--sort`: dotted path to sort ascending by.
    pub sort: Option<String>,
    /// `--dedupe-by`: dotted path whose repeated values are dropped.
    pub dedupe_by: Option<String>,
    /// `--count-only`: replace the payload with `{"count": N}`.
    pub count_only: bool,
    /// `--truncate-content`: shorten strings above N characters.
    pub truncate_content: Option<usize>,
    /// `--max-output-bytes`: cap the serialised envelope.
    pub max_output_bytes: Option<usize>,
}

impl SurfaceOptions {
    /// `true` when at least one knob is engaged.
    ///
    /// A CLI invocation that engages nothing must produce exactly the
    /// envelope it produced before this layer existed, including the
    /// absence of the `agent_surface` block.
    #[must_use]
    pub fn is_active(&self) -> bool {
        !self.select.is_empty()
            || !self.filters.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 every engaged knob to `envelope`, in the fixed order.
    ///
    /// Returns the reduced envelope and the report describing the cut.
    /// An error envelope passes through untouched.
    #[must_use]
    pub fn apply(&self, envelope: Value) -> (Value, SurfaceReport) {
        if is_error_envelope(&envelope) {
            return (envelope, SurfaceReport::default());
        }
        match locate_rows(&envelope) {
            Some(key) => self.apply_to_rows(envelope, &key),
            None => self.apply_to_single(envelope),
        }
    }

    /// Reduce an envelope whose rows live under `key`.
    fn apply_to_rows(&self, mut envelope: Value, key: &str) -> (Value, SurfaceReport) {
        let mut report = SurfaceReport::default();
        let rows = envelope
            .get_mut(key)
            .and_then(Value::as_array_mut)
            .map(std::mem::take)
            .unwrap_or_default();
        report.input_count = rows.len();

        let rows = self.reduce_rows(rows, &mut report);
        report.output_count = rows.len();

        if self.count_only {
            let mut out = json_count(report.output_count);
            attach_report(&mut out, report);
            return (out, report);
        }

        if let Some(slot) = envelope.get_mut(key) {
            *slot = Value::Array(rows);
        }

        if let Some(max) = self.truncate_content {
            report.content_truncated = truncate_strings(&mut envelope, max);
        }

        attach_report(&mut envelope, report);

        if let Some(cap) = self.max_output_bytes {
            let dropped = enforce_byte_cap(&mut envelope, key, cap, &mut report);
            if dropped > 0 {
                report.output_truncated = true;
                report.limited = true;
                report.output_count = report.output_count.saturating_sub(dropped);
                attach_report(&mut envelope, report);
            }
        }

        (envelope, report)
    }

    /// Reduce an envelope that is one object rather than a row array.
    ///
    /// `filter`, `sort`, `dedupe-by` and `limit` treat the object as a
    /// one-element list, so a filter that rejects it yields zero rows and
    /// `select` still projects the surviving object.
    fn apply_to_single(&self, envelope: Value) -> (Value, SurfaceReport) {
        let mut report = SurfaceReport {
            input_count: 1,
            ..SurfaceReport::default()
        };
        let mut rows = self.reduce_rows(vec![envelope], &mut report);
        report.output_count = rows.len();

        if self.count_only {
            let mut out = json_count(report.output_count);
            attach_report(&mut out, report);
            return (out, report);
        }

        let mut out = rows.pop().unwrap_or_else(|| Value::Object(Map::new()));

        if let Some(max) = self.truncate_content {
            report.content_truncated = truncate_strings(&mut out, max);
        }

        if let Some(cap) = self.max_output_bytes {
            // A single object carries no elements to drop, so the cap can
            // only be reported, never enforced by slicing the JSON text.
            if serialised_len(&out) > cap {
                report.output_truncated = true;
            }
        }

        attach_report(&mut out, report);
        (out, report)
    }

    /// Run steps 1 through 5 over a row vector.
    fn reduce_rows(&self, rows: Vec<Value>, report: &mut SurfaceReport) -> Vec<Value> {
        // 1. filter
        let mut rows: Vec<Value> = rows
            .into_iter()
            .filter(|row| self.filters.iter().all(|f| f.matches(row)))
            .collect();

        // 2. sort — stable, ascending, absent key last.
        if let Some(path) = &self.sort {
            rows.sort_by(|a, b| compare_by_path(a, b, path));
        }

        // 3. dedupe-by — first occurrence wins, absent key always kept.
        if let Some(path) = &self.dedupe_by {
            let mut seen: Vec<String> = Vec::new();
            rows.retain(|row| match lookup_path(row, path) {
                None => true,
                Some(v) => {
                    let key = render_scalar(v);
                    if seen.contains(&key) {
                        false
                    } else {
                        seen.push(key);
                        true
                    }
                }
            });
        }

        // 4. limit
        if let Some(limit) = self.limit {
            if rows.len() > limit {
                rows.truncate(limit);
                report.limited = true;
            }
        }

        // 5. select
        if !self.select.is_empty() {
            rows = rows.iter().map(|row| project(row, &self.select)).collect();
        }

        rows
    }
}

/// `true` when the envelope declares a failure the caller must see.
fn is_error_envelope(value: &Value) -> bool {
    value.get("error") == Some(&Value::Bool(true)) || value.get("ok") == Some(&Value::Bool(false))
}

/// The first [`RESULT_ARRAY_KEYS`] entry that holds an array, if any.
fn locate_rows(envelope: &Value) -> Option<String> {
    let obj = envelope.as_object()?;
    RESULT_ARRAY_KEYS
        .iter()
        .find(|key| obj.get(**key).is_some_and(Value::is_array))
        .map(|key| (*key).to_string())
}

/// `{"count": n}`.
fn json_count(n: usize) -> Value {
    let mut map = Map::new();
    map.insert("count".to_string(), Value::from(n));
    Value::Object(map)
}

/// Insert the `agent_surface` block into an object envelope.
fn attach_report(envelope: &mut Value, report: SurfaceReport) {
    if let Some(obj) = envelope.as_object_mut() {
        if let Ok(v) = serde_json::to_value(report) {
            obj.insert("agent_surface".to_string(), v);
        }
    }
}

/// Walk a dotted path into `value`.
///
/// A numeric segment indexes into an array, so `results.0.title` works
/// the same way an operator expects.
#[must_use]
pub fn lookup_path<'a>(value: &'a Value, path: &str) -> Option<&'a Value> {
    let mut cursor = value;
    for segment in path.split('.') {
        cursor = match cursor {
            Value::Object(map) => map.get(segment)?,
            Value::Array(items) => items.get(segment.parse::<usize>().ok()?)?,
            _ => return None,
        };
    }
    Some(cursor)
}

/// Render a JSON scalar the way a filter or a dedupe key compares it.
///
/// Strings lose their quotes so `--filter provider=cache` matches
/// `"cache"`. Composite values fall back to their compact JSON form.
fn render_scalar(value: &Value) -> String {
    match value {
        Value::String(s) => s.clone(),
        Value::Null => String::new(),
        other => other.to_string(),
    }
}

/// Build a new object carrying only the selected dotted paths.
///
/// A path the element does not carry is skipped, never emitted as
/// `null`.
fn project(element: &Value, paths: &[String]) -> Value {
    let mut out = Map::new();
    for path in paths {
        if let Some(found) = lookup_path(element, path) {
            insert_path(&mut out, path, found.clone());
        }
    }
    Value::Object(out)
}

/// Insert `value` at a dotted `path`, creating intermediate objects.
fn insert_path(root: &mut Map<String, Value>, path: &str, value: Value) {
    let mut segments = path.split('.').peekable();
    let mut cursor = root;
    while let Some(segment) = segments.next() {
        if segments.peek().is_none() {
            cursor.insert(segment.to_string(), value);
            return;
        }
        let entry = cursor
            .entry(segment.to_string())
            .or_insert_with(|| Value::Object(Map::new()));
        if !entry.is_object() {
            *entry = Value::Object(Map::new());
        }
        match entry.as_object_mut() {
            Some(map) => cursor = map,
            // Unreachable: `entry` was just forced to be an object.
            None => return,
        }
    }
}

/// Compare two elements by a dotted path, ascending, absent key last.
///
/// Two numeric values compare numerically; anything else compares as its
/// rendered string.
fn compare_by_path(a: &Value, b: &Value, path: &str) -> std::cmp::Ordering {
    use std::cmp::Ordering;
    match (lookup_path(a, path), lookup_path(b, path)) {
        (None, None) => Ordering::Equal,
        (None, Some(_)) => Ordering::Greater,
        (Some(_), None) => Ordering::Less,
        (Some(x), Some(y)) => match (x.as_f64(), y.as_f64()) {
            (Some(nx), Some(ny)) => nx.partial_cmp(&ny).unwrap_or(Ordering::Equal),
            _ => render_scalar(x).cmp(&render_scalar(y)),
        },
    }
}

/// Shorten every string in `value` above `max` **characters**.
///
/// The cut lands on a character boundary by construction, so a UTF-8
/// sequence is never split. Returns `true` when at least one string was
/// shortened.
fn truncate_strings(value: &mut Value, max: usize) -> bool {
    match value {
        Value::String(s) => {
            if s.chars().count() > max {
                let cut: String = s.chars().take(max).collect();
                *s = cut;
                true
            } else {
                false
            }
        }
        Value::Array(items) => items.iter_mut().fold(false, |acc, item| {
            let hit = truncate_strings(item, max);
            acc || hit
        }),
        Value::Object(map) => map.iter_mut().fold(false, |acc, (_, item)| {
            let hit = truncate_strings(item, max);
            acc || hit
        }),
        _ => false,
    }
}

/// Serialised byte length of `value`, or `usize::MAX` when it cannot be
/// serialised (which no [`Value`] produced here can be).
fn serialised_len(value: &Value) -> usize {
    serde_json::to_vec(value).map_or(usize::MAX, |v| v.len())
}

/// Drop elements from the end of `envelope[key]` until the serialised
/// envelope fits `cap`. Returns how many elements were dropped.
///
/// Elements are removed whole. The JSON text itself is never sliced,
/// because a sliced envelope would not parse.
///
/// The `agent_surface` block is already attached when this runs and is
/// refreshed on every iteration, so the report counts against the cap
/// instead of escaping it. Without that, an envelope trimmed to exactly
/// `cap` grew back over it the moment the report was appended.
fn enforce_byte_cap(
    envelope: &mut Value,
    key: &str,
    cap: usize,
    report: &mut SurfaceReport,
) -> usize {
    let mut dropped = 0usize;
    while serialised_len(envelope) > cap {
        let Some(rows) = envelope.get_mut(key).and_then(Value::as_array_mut) else {
            break;
        };
        if rows.pop().is_none() {
            break;
        }
        dropped += 1;
        let mut projected = *report;
        projected.output_truncated = true;
        projected.limited = true;
        projected.output_count = projected.output_count.saturating_sub(dropped);
        attach_report(envelope, projected);
    }
    dropped
}

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

    fn rows(n: usize) -> Value {
        let items: Vec<Value> = (0..n)
            .map(|i| json!({ "id": i, "name": format!("n{i}") }))
            .collect();
        json!({ "results": items })
    }

    #[test]
    fn inactive_options_are_a_no_op() {
        let opts = SurfaceOptions::default();
        assert!(!opts.is_active());
    }

    #[test]
    fn filter_parses_every_operator() {
        assert_eq!(Filter::parse("a=b").expect("parses").op, FilterOp::Equals);
        assert_eq!(Filter::parse("a==b").expect("parses").op, FilterOp::Equals);
        assert_eq!(
            Filter::parse("a!=b").expect("parses").op,
            FilterOp::NotEquals
        );
        assert_eq!(Filter::parse("a~b").expect("parses").op, FilterOp::Contains);
    }

    #[test]
    fn malformed_filter_is_a_usage_error_not_an_empty_set() {
        let err = Filter::parse("no_operator_here").unwrap_err();
        assert!(matches!(err, AppError::InvalidUsage(_)));
        assert!(Filter::parse("=missing_key").is_err());
    }

    #[test]
    fn filter_conjoins_with_and() {
        let opts = SurfaceOptions {
            filters: vec![
                Filter::parse("id!=0").expect("parses"),
                Filter::parse("name~n").expect("parses"),
            ],
            ..SurfaceOptions::default()
        };
        let (out, report) = opts.apply(rows(3));
        assert_eq!(report.input_count, 3);
        assert_eq!(report.output_count, 2);
        assert_eq!(out["results"].as_array().map(Vec::len), Some(2));
    }

    #[test]
    fn error_envelope_is_never_silenced_by_a_filter() {
        let opts = SurfaceOptions {
            filters: vec![Filter::parse("id=999").expect("parses")],
            ..SurfaceOptions::default()
        };
        let envelope = json!({ "error": true, "code": 70, "message": "boom" });
        let (out, _) = opts.apply(envelope.clone());
        assert_eq!(out, envelope, "an error envelope must pass through intact");
    }

    #[test]
    fn ok_false_envelope_is_never_silenced() {
        let opts = SurfaceOptions {
            count_only: true,
            ..SurfaceOptions::default()
        };
        let envelope = json!({ "ok": false, "message": "boom" });
        let (out, _) = opts.apply(envelope.clone());
        assert_eq!(out, envelope);
    }

    #[test]
    fn select_skips_absent_keys_instead_of_emitting_null() {
        let opts = SurfaceOptions {
            select: vec!["id".to_string(), "absent".to_string()],
            ..SurfaceOptions::default()
        };
        let (out, _) = opts.apply(rows(1));
        let first = &out["results"][0];
        assert!(first.get("id").is_some());
        assert!(
            first.get("absent").is_none(),
            "absent key must be skipped, not null: {first}"
        );
    }

    #[test]
    fn select_supports_dotted_paths() {
        let opts = SurfaceOptions {
            select: vec!["info.provider".to_string()],
            ..SurfaceOptions::default()
        };
        let envelope = json!({ "results": [{ "info": { "provider": "cache", "x": 1 } }] });
        let (out, _) = opts.apply(envelope);
        assert_eq!(out["results"][0]["info"]["provider"], json!("cache"));
        assert!(out["results"][0]["info"].get("x").is_none());
    }

    #[test]
    fn sort_is_ascending_numeric_and_puts_absent_keys_last() {
        let opts = SurfaceOptions {
            sort: Some("id".to_string()),
            ..SurfaceOptions::default()
        };
        let envelope = json!({ "results": [{"id": 10}, {"other": 1}, {"id": 2}] });
        let (out, _) = opts.apply(envelope);
        let arr = out["results"].as_array().cloned().unwrap_or_default();
        assert_eq!(arr[0]["id"], json!(2));
        assert_eq!(arr[1]["id"], json!(10));
        assert!(arr[2].get("id").is_none());
    }

    #[test]
    fn dedupe_keeps_first_and_always_keeps_elements_without_the_key() {
        let opts = SurfaceOptions {
            dedupe_by: Some("id".to_string()),
            ..SurfaceOptions::default()
        };
        let envelope =
            json!({ "results": [{"id":1,"t":"a"},{"id":1,"t":"b"},{"t":"c"},{"t":"d"}] });
        let (out, report) = opts.apply(envelope);
        assert_eq!(report.output_count, 3);
        assert_eq!(out["results"][0]["t"], json!("a"));
    }

    #[test]
    fn limit_reports_that_it_cut() {
        let opts = SurfaceOptions {
            limit: Some(2),
            ..SurfaceOptions::default()
        };
        let (_, report) = opts.apply(rows(5));
        assert_eq!(report.output_count, 2);
        assert!(report.limited);
    }

    #[test]
    fn count_only_counts_after_filter_dedupe_and_limit() {
        let opts = SurfaceOptions {
            filters: vec![Filter::parse("id!=0").expect("parses")],
            limit: Some(2),
            count_only: true,
            ..SurfaceOptions::default()
        };
        let (out, _) = opts.apply(rows(10));
        assert_eq!(out["count"], json!(2));
        assert!(out.get("results").is_none());
    }

    #[test]
    fn truncate_content_counts_characters_and_never_splits_utf8() {
        let opts = SurfaceOptions {
            truncate_content: Some(3),
            ..SurfaceOptions::default()
        };
        // Each of these characters is multi-byte in UTF-8.
        let envelope = json!({ "results": [{ "t": "áéíóú" }] });
        let (out, report) = opts.apply(envelope);
        assert!(report.content_truncated);
        let s = out["results"][0]["t"].as_str().unwrap_or_default();
        assert_eq!(s.chars().count(), 3);
        assert_eq!(s, "áéí");
    }

    #[test]
    fn max_output_bytes_drops_whole_elements_and_leaves_valid_json() {
        const CAP: usize = 400;
        let opts = SurfaceOptions {
            max_output_bytes: Some(CAP),
            ..SurfaceOptions::default()
        };
        let (out, report) = opts.apply(rows(40));
        assert!(report.output_truncated);
        let text = serde_json::to_string(&out).expect("still serialises");
        assert!(
            text.len() <= CAP,
            "the cap must bind the whole envelope, agent_surface included, got {}",
            text.len()
        );
        serde_json::from_str::<Value>(&text).expect("the emitted text must still parse");
        let kept = out["results"].as_array().map(Vec::len).unwrap_or_default();
        assert!(kept > 0 && kept < 40, "some rows must survive, got {kept}");
        assert_eq!(report.output_count, kept);
    }

    /// The floor of `--max-output-bytes` is the envelope skeleton. Once
    /// every element is gone there is nothing left to drop, and slicing
    /// the JSON text would produce a document that does not parse — so
    /// the layer stops and still reports the truncation.
    #[test]
    fn a_cap_below_the_skeleton_empties_the_rows_and_still_parses() {
        let opts = SurfaceOptions {
            max_output_bytes: Some(1),
            ..SurfaceOptions::default()
        };
        let (out, report) = opts.apply(rows(5));
        assert!(report.output_truncated);
        assert_eq!(report.output_count, 0);
        assert_eq!(out["results"].as_array().map(Vec::len), Some(0));
        let text = serde_json::to_string(&out).expect("still serialises");
        serde_json::from_str::<Value>(&text).expect("the emitted text must still parse");
    }

    #[test]
    fn agent_surface_block_is_attached_when_active() {
        let opts = SurfaceOptions {
            limit: Some(1),
            ..SurfaceOptions::default()
        };
        let (out, _) = opts.apply(rows(3));
        let block = &out["agent_surface"];
        assert_eq!(block["input_count"], json!(3));
        assert_eq!(block["output_count"], json!(1));
        assert_eq!(block["limited"], json!(true));
    }

    #[test]
    fn single_object_envelope_is_projected_as_one_element() {
        let opts = SurfaceOptions {
            select: vec!["video_id".to_string()],
            ..SurfaceOptions::default()
        };
        let envelope = json!({ "video_id": "abc", "content": "long body" });
        let (out, report) = opts.apply(envelope);
        assert_eq!(report.input_count, 1);
        assert_eq!(report.output_count, 1);
        assert_eq!(out["video_id"], json!("abc"));
        assert!(out.get("content").is_none());
    }

    #[test]
    fn lookup_path_indexes_arrays_by_number() {
        let v = json!({ "a": [{ "b": 7 }] });
        assert_eq!(lookup_path(&v, "a.0.b"), Some(&json!(7)));
        assert_eq!(lookup_path(&v, "a.9.b"), None);
    }
}