boundgraph-slice 0.1.0

Layer 4 of BoundGraph: the slicers that turn raw tool output into size-capped condensates.
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
//! Condensing command output: keep what failed, drop what scrolled past.
//!
//! # Why this slicer earns its place first
//!
//! Log output is the dominant term in the quadratic cost formula. A ten
//! thousand line build log costs more tokens than every prompt in a flow put
//! together, and almost all of it is noise — the same "Compiling" line four
//! hundred times, with the three lines anyone cares about somewhere in the
//! middle.
//!
//! # What is kept, in what order
//!
//! The cap is spent in priority order, so that a small cap still produces
//! something useful rather than the first `n` lines:
//!
//! 1. **The command outcome.** Exit status and timing, always, regardless of
//!    the cap. They cost a handful of tokens and they are the first thing
//!    anyone asks about a failed command. A slicer that dropped them to fit two
//!    more log lines would have optimised the wrong way.
//! 2. **A floor of head and tail lines.** Failures cluster at both ends: what
//!    was invoked is at the top, the summary is at the bottom. A few of each are
//!    kept before anything competes for the budget.
//! 3. **Error lines**, in the order they appeared.
//! 4. **Warning lines.**
//! 5. **More head and tail**, then anything else that fits.
//!
//! # Repetition is collapsed, not dropped
//!
//! Consecutive identical lines become one line with a count. *Consecutive*
//! rather than global, because collapsing repeats that were far apart would
//! reorder the log and quietly imply the two occurrences were adjacent — and
//! the gap between two identical errors is often the whole story.
//!
//! # What the model is told it did not see
//!
//! Every count of what was dropped is reported. A model reading a condensate
//! with no elision marker will reason as though it has the whole log; one that
//! can see `9821 lines dropped` knows to ask for the original, which is in the
//! content store under [`Condensate::raw`](boundgraph_core::Condensate::raw).

use async_trait::async_trait;
use boundgraph_core::{SchemaId, SlicerId};
use serde::{Deserialize, Serialize};
use serde_json::json;

use crate::slicer::{Raw, Slice, SliceError, Slicer};

/// The schema a log condensate declares.
pub const LOG_SCHEMA: &str = "boundgraph.log.v1";

/// How important a line looked.
///
/// Judged by convention rather than by parsing: there is no grammar for "a log
/// line", and every toolchain writes its own. The conventions matched below are
/// the ones that are near-universal, and a line that matches none of them is
/// simply informational — which is the safe default, since being wrong here
/// costs priority rather than correctness.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Level {
    /// Something failed.
    Error,
    /// Something is suspect.
    Warning,
    /// Everything else.
    Info,
}

impl Level {
    /// Classify a line by the conventions toolchains actually use.
    ///
    /// Case-insensitive, and anchored to word-ish positions so that a path
    /// containing `error` — `src/error.rs`, which appears in almost every Rust
    /// build log — is not mistaken for an error line.
    pub fn of(line: &str) -> Self {
        let lower = line.to_ascii_lowercase();
        let trimmed = lower.trim_start();

        // Leading markers: `error:`, `error[E0308]:`, `E: `, `FAILED`, and the
        // shapes test harnesses and compilers put at the start of a line.
        const ERROR_PREFIX: &[&str] = &[
            "error",
            "fatal",
            "panic",
            "failed",
            "failure",
            "exception",
            "traceback",
            "e:",
            "err:",
            "[error]",
            "[fatal]",
        ];
        const WARNING_PREFIX: &[&str] = &["warning", "warn", "w:", "[warn", "deprecated"];

        if ERROR_PREFIX.iter().any(|m| trimmed.starts_with(m)) {
            return Self::Error;
        }
        if WARNING_PREFIX.iter().any(|m| trimmed.starts_with(m)) {
            return Self::Warning;
        }

        // Embedded markers, which is how test runners report: `test x ... FAILED`,
        // `1 failed`, `assertion failed`. Checked after prefixes so a line that
        // is both is reported at its stronger level.
        const ERROR_INFIX: &[&str] = &[
            " failed",
            "failed:",
            " error:",
            "assertion",
            "segmentation fault",
        ];
        const WARNING_INFIX: &[&str] = &[" warning:", " deprecated"];

        if ERROR_INFIX.iter().any(|m| lower.contains(m)) || counts(&lower, "error") {
            return Self::Error;
        }
        if WARNING_INFIX.iter().any(|m| lower.contains(m)) || counts(&lower, "warning") {
            return Self::Warning;
        }
        Self::Info
    }

    /// Whether this level is worth keeping ahead of ordinary output.
    pub fn is_notable(self) -> bool {
        matches!(self, Self::Error | Self::Warning)
    }
}

/// Whether `lower` reports a *count* of `noun`, as in `2 errors` or `1 warning`.
///
/// Matching the bare word would be far too eager: `src/error.rs` and
/// `writing errors.log` appear in ordinary build output constantly, and
/// treating them as failures would spend the cap on compiler progress. The
/// count form is the one that actually reports a result, so the digit before it
/// is what makes the match safe.
fn counts(lower: &str, noun: &str) -> bool {
    lower.match_indices(noun).any(|(at, _)| {
        // Reject `errors.log`: a count is followed by a word boundary.
        let after = lower[at + noun.len()..].chars().next();
        if after.is_some_and(|c| c.is_alphanumeric() && c != 's') {
            return false;
        }
        let tail = lower[at + noun.len()..].trim_start_matches('s');
        if tail.starts_with('.') || tail.starts_with('/') || tail.starts_with('_') {
            return false;
        }
        // And it is preceded by a number: "2 errors", not "of errors".
        lower[..at]
            .trim_end()
            .rsplit(|c: char| c.is_whitespace())
            .next()
            .is_some_and(|word| !word.is_empty() && word.chars().all(|c| c.is_ascii_digit()))
    })
}

/// One line of output, after consecutive repeats were collapsed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LogLine {
    /// The line number in the original output, counting from one.
    ///
    /// Kept so a reader can tell that lines 12 and 4_310 are not adjacent, and
    /// so a gap in the numbering *is* the elision marker.
    pub n: usize,
    /// The text, with trailing whitespace removed.
    pub text: String,
    /// How important it looked. Omitted from the payload when informational,
    /// since that is the common case and repeating it would cost tokens.
    #[serde(skip_serializing_if = "is_info")]
    pub level: Level,
    /// How many consecutive identical lines this stands for. Omitted when one.
    #[serde(skip_serializing_if = "is_one")]
    pub repeats: usize,
}

fn is_info(level: &Level) -> bool {
    matches!(level, Level::Info)
}

fn is_one(n: &usize) -> bool {
    *n == 1
}

/// What did not make it into the summary.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Dropped {
    /// Lines not shown, after collapsing.
    pub lines: usize,
    /// Error lines not shown. Non-zero here is a strong hint to fetch the raw.
    pub errors: usize,
    /// Warning lines not shown.
    pub warnings: usize,
    /// Lines removed by collapsing consecutive repeats.
    pub repeated: usize,
}

impl Dropped {
    /// Whether anything was lost.
    pub fn any(&self) -> bool {
        self.lines > 0 || self.repeated > 0
    }
}

/// Condenses command and build output.
///
/// # Example
///
/// ```
/// use boundgraph_slice::{LogSlicer, MemoryStore, Raw, Slicer};
///
/// let noisy = (0..5_000)
///     .map(|i| format!("Compiling crate_{i}"))
///     .collect::<Vec<_>>()
///     .join("\n")
///     + "\nerror[E0308]: mismatched types\n";
///
/// let condensate = tokio::runtime::Builder::new_current_thread()
///     .build()?
///     .block_on(LogSlicer::new().condense(&Raw::new(noisy), 300, &MemoryStore::new()))?;
///
/// // The error survived; the five thousand Compiling lines did not.
/// assert!(condensate.lossy);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, Copy)]
pub struct LogSlicer {
    /// Lines from the start kept before anything competes for the budget.
    head: usize,
    /// Lines from the end kept on the same basis.
    tail: usize,
}

impl Default for LogSlicer {
    fn default() -> Self {
        Self::new()
    }
}

impl LogSlicer {
    /// A slicer keeping three lines from each end as a floor.
    pub fn new() -> Self {
        Self { head: 3, tail: 3 }
    }

    /// Keep this many lines from each end before prioritising by level.
    #[must_use]
    pub fn anchored(mut self, head: usize, tail: usize) -> Self {
        self.head = head;
        self.tail = tail;
        self
    }

    /// Collapse consecutive identical lines, numbering by the original.
    fn collapse(text: &str) -> (Vec<LogLine>, usize) {
        let mut out: Vec<LogLine> = Vec::new();
        let mut collapsed = 0;

        for (index, raw_line) in text.lines().enumerate() {
            let line = raw_line.trim_end();
            match out.last_mut() {
                // Only *consecutive* repeats collapse — see the module docs.
                Some(last) if last.text == line => {
                    last.repeats += 1;
                    collapsed += 1;
                }
                _ => out.push(LogLine {
                    n: index + 1,
                    text: line.to_string(),
                    level: Level::of(line),
                    repeats: 1,
                }),
            }
        }
        (out, collapsed)
    }

    /// The order the cap is spent in. Returns indices into `lines`.
    ///
    /// Head and tail come before errors deliberately: a floor of structural
    /// context is what stops a tiny cap from producing a bare error with no
    /// indication of what was even being built.
    fn priority(&self, lines: &[LogLine]) -> Vec<usize> {
        let count = lines.len();
        let mut order: Vec<usize> = Vec::with_capacity(count);
        let mut seen = vec![false; count];

        let take = |index: usize, order: &mut Vec<usize>, seen: &mut Vec<bool>| {
            if index < count && !seen[index] {
                seen[index] = true;
                order.push(index);
            }
        };

        // 1. The floor of head and tail.
        for i in 0..self.head.min(count) {
            take(i, &mut order, &mut seen);
        }
        for i in count.saturating_sub(self.tail)..count {
            take(i, &mut order, &mut seen);
        }
        // 2. Errors, then warnings, each in the order they appeared.
        for level in [Level::Error, Level::Warning] {
            for (i, line) in lines.iter().enumerate() {
                if line.level == level {
                    take(i, &mut order, &mut seen);
                }
            }
        }
        // 3. Everything else, in order.
        for i in 0..count {
            take(i, &mut order, &mut seen);
        }
        order
    }

    /// Assemble the payload for a chosen set of lines.
    fn payload(
        kept: &[LogLine],
        total: usize,
        collapsed: usize,
        all: &[LogLine],
        command: Option<&crate::slicer::CommandOutcome>,
    ) -> serde_json::Value {
        let shown: std::collections::BTreeSet<usize> = kept.iter().map(|l| l.n).collect();
        let dropped = Dropped {
            lines: all.len() - kept.len(),
            errors: all
                .iter()
                .filter(|l| l.level == Level::Error && !shown.contains(&l.n))
                .count(),
            warnings: all
                .iter()
                .filter(|l| l.level == Level::Warning && !shown.contains(&l.n))
                .count(),
            repeated: collapsed,
        };

        let mut payload = json!({
            "lines": kept,
            "total_lines": total,
        });

        // Always present, whatever the cap.
        if let Some(outcome) = command {
            payload["command"] = json!(outcome.summary());
            payload["exit"] = json!(outcome.exit);
        }
        if dropped.any() {
            payload["dropped"] = json!(dropped);
        }
        payload
    }
}

#[async_trait]
impl Slicer for LogSlicer {
    fn id(&self) -> SlicerId {
        SlicerId::new("log", 1)
    }

    async fn slice(&self, raw: &Raw, cap: usize) -> Result<Slice, SliceError> {
        let text = raw.text();
        let (lines, collapsed) = Self::collapse(&text);
        let total = text.lines().count();
        let schema = SchemaId::new(LOG_SCHEMA, 1);

        let order = self.priority(&lines);
        let counter = self.counter();

        // The envelope — command summary, totals, dropped counts — is retained
        // whatever the cap, so if it alone does not fit there is no slice to
        // make. Reporting the *measured* floor rather than a constant matters
        // because the floor depends on the input: a long command line costs
        // more than a short one, and telling an author "at least 64" when their
        // invocation needs 90 would send them round again.
        let envelope = Self::payload(&[], total, collapsed, &lines, raw.command.as_ref());
        let floor = counter.count(&serde_json::to_string(&envelope).unwrap_or_default());
        if floor > cap {
            return Err(SliceError::CapTooSmall {
                cap,
                minimum: floor,
            });
        }

        // Grow the kept set in priority order while it still fits. Measuring
        // the real rendered payload each time rather than estimating per line:
        // the envelope is not free and the alternative is a guess that has to
        // be corrected afterwards anyway.
        let mut chosen: Vec<usize> = Vec::new();
        for &index in &order {
            let mut candidate = chosen.clone();
            candidate.push(index);
            candidate.sort_unstable();

            let kept: Vec<LogLine> = candidate.iter().map(|&i| lines[i].clone()).collect();
            let payload = Self::payload(&kept, total, collapsed, &lines, raw.command.as_ref());

            if counter.count(&serde_json::to_string(&payload).unwrap_or_default()) > cap {
                // This line does not fit. A later one in priority order may be
                // shorter, so keep going rather than stopping here.
                continue;
            }
            chosen = candidate;
        }

        chosen.sort_unstable();
        let kept: Vec<LogLine> = chosen.iter().map(|&i| lines[i].clone()).collect();
        let lossy = kept.len() < lines.len() || collapsed > 0;
        let payload = Self::payload(&kept, total, collapsed, &lines, raw.command.as_ref());

        Ok(Slice {
            schema,
            payload,
            lossy,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::slicer::{CommandOutcome, MemoryStore};
    use std::time::Duration;

    fn raw_of(text: &str) -> Raw {
        Raw::new(text.as_bytes().to_vec())
    }

    async fn slice(text: &str, cap: usize) -> Slice {
        LogSlicer::new()
            .slice(&raw_of(text), cap)
            .await
            .expect("the log slicer handles anything")
    }

    fn texts(slice: &Slice) -> Vec<String> {
        slice.payload["lines"]
            .as_array()
            .unwrap()
            .iter()
            .map(|l| l["text"].as_str().unwrap().to_string())
            .collect()
    }

    /// A realistic build log: a lot of noise around a little signal.
    fn build_log() -> String {
        let mut out = String::from("$ cargo build --release\n");
        for i in 0..500 {
            out.push_str(&format!("   Compiling crate_{i} v0.1.0\n"));
        }
        out.push_str("warning: unused variable `x`\n");
        for i in 500..1_000 {
            out.push_str(&format!("   Compiling crate_{i} v0.1.0\n"));
        }
        out.push_str("error[E0308]: mismatched types\n");
        out.push_str("  --> src/main.rs:42:9\n");
        out.push_str("error: could not compile `app` due to 1 previous error\n");
        out
    }

    // ── priorities ──────────────────────────────────────────────────────────

    /// The criterion: errors and warnings beat informational lines.
    #[tokio::test]
    async fn errors_survive_a_cap_that_drops_almost_everything() {
        let slice = slice(&build_log(), 300).await;
        let kept = texts(&slice);

        assert!(
            kept.iter().any(|l| l.contains("E0308")),
            "the error must survive: {kept:?}"
        );
        assert!(
            kept.iter().any(|l| l.contains("could not compile")),
            "and so must the second one"
        );
        assert!(slice.lossy);
    }

    /// The one warning survives a cap that keeps only a handful of the thousand
    /// informational lines it is buried among. Ordinary lines do get whatever
    /// budget is left over — that is the point of filling — so the property
    /// worth asserting is that the warning is never the thing that loses.
    #[tokio::test]
    async fn warnings_outrank_informational_lines() {
        for cap in [200, 300, 400, 800] {
            let slice = slice(&build_log(), cap).await;
            let kept = texts(&slice);
            assert!(
                kept.iter().any(|l| l.contains("warning: unused variable")),
                "the warning should survive cap {cap}: {kept:?}"
            );
        }
    }

    /// The criterion: the first and last portions are retained.
    #[tokio::test]
    async fn the_head_and_tail_are_anchored() {
        let slice = slice(&build_log(), 500).await;
        let kept = texts(&slice);

        assert!(
            kept[0].contains("cargo build --release"),
            "the invocation is the head: {:?}",
            kept[0]
        );
        assert!(
            kept.last().unwrap().contains("could not compile"),
            "the summary is the tail: {:?}",
            kept.last()
        );
    }

    #[tokio::test]
    async fn kept_lines_stay_in_the_order_they_appeared() {
        let slice = slice(&build_log(), 600).await;
        let numbers: Vec<u64> = slice.payload["lines"]
            .as_array()
            .unwrap()
            .iter()
            .map(|l| l["n"].as_u64().unwrap())
            .collect();

        assert!(
            numbers.windows(2).all(|w| w[0] < w[1]),
            "a reordered log is a misleading log: {numbers:?}"
        );
    }

    /// The line numbers are the elision marker: a gap says lines are missing.
    #[tokio::test]
    async fn line_numbers_reference_the_original_so_gaps_are_visible() {
        let slice = slice(&build_log(), 300).await;
        let numbers: Vec<u64> = slice.payload["lines"]
            .as_array()
            .unwrap()
            .iter()
            .map(|l| l["n"].as_u64().unwrap())
            .collect();

        assert!(
            numbers.windows(2).any(|w| w[1] - w[0] > 1),
            "a heavily sliced log should show gaps"
        );
    }

    // ── repetition ──────────────────────────────────────────────────────────

    /// The criterion: repeated identical lines are collapsed with a count.
    #[tokio::test]
    async fn consecutive_repeats_collapse_to_one_line_with_a_count() {
        let text = "start\nsame\nsame\nsame\nsame\nend";
        let slice = slice(text, 200).await;

        let same = slice.payload["lines"]
            .as_array()
            .unwrap()
            .iter()
            .find(|l| l["text"] == "same")
            .expect("the repeated line");
        assert_eq!(same["repeats"], 4);
        assert_eq!(slice.payload["dropped"]["repeated"], 3);
        assert!(slice.lossy, "collapsing is lossy even when nothing is cut");
    }

    /// Collapsing repeats that were far apart would imply they were adjacent,
    /// and the gap between two identical errors is often the whole story.
    #[tokio::test]
    async fn repeats_that_are_not_adjacent_are_not_collapsed() {
        let text = "same\nother\nsame";
        let slice = slice(text, 200).await;

        let same: Vec<_> = slice.payload["lines"]
            .as_array()
            .unwrap()
            .iter()
            .filter(|l| l["text"] == "same")
            .collect();
        assert_eq!(same.len(), 2, "two separate occurrences, kept separate");
    }

    #[tokio::test]
    async fn a_line_that_appears_once_carries_no_count() {
        let slice = slice("only once\n", 200).await;
        assert!(slice.payload["lines"][0].get("repeats").is_none());
    }

    // ── the command outcome ─────────────────────────────────────────────────

    /// The criterion: exit status and timing survive regardless of the cap.
    #[tokio::test]
    async fn the_exit_status_and_timing_survive_the_smallest_cap() {
        let raw = raw_of(&build_log()).from_command(CommandOutcome::new(
            "cargo build --release",
            101,
            Duration::from_millis(4_200),
        ));

        // 60 is the measured floor for this invocation — below it there is no
        // slice to make, and the slicer says so rather than dropping the exit
        // status to fit.
        for cap in [60, 64, 128, 1_000] {
            let slice = LogSlicer::new().slice(&raw, cap).await.unwrap();
            assert_eq!(slice.payload["exit"], 101, "at cap {cap}");
            assert!(
                slice.payload["command"]
                    .as_str()
                    .unwrap()
                    .contains("4200ms"),
                "timing must survive cap {cap}"
            );
        }
    }

    /// The envelope is retained whatever the cap, so a cap that cannot hold it
    /// is a flow-authoring error rather than an excuse to drop the exit status.
    /// The floor is measured from the input, because a long command line costs
    /// more than a short one.
    #[tokio::test]
    async fn a_cap_below_the_envelope_reports_the_measured_floor() {
        let raw = raw_of("some output\n").from_command(CommandOutcome::new(
            "cargo build --release --workspace --all-features",
            101,
            Duration::from_millis(4_200),
        ));

        let err = LogSlicer::new().slice(&raw, 20).await.unwrap_err();
        let SliceError::CapTooSmall { cap, minimum } = err else {
            panic!("expected CapTooSmall, got {err:?}");
        };
        assert_eq!(cap, 20);
        assert!(minimum > 20, "the floor should exceed the cap it refused");

        // And that floor is honest: at it, the slice succeeds.
        assert!(LogSlicer::new().slice(&raw, minimum).await.is_ok());
    }

    #[tokio::test]
    async fn output_with_no_command_reports_no_exit_status() {
        let slice = slice("just some text\n", 200).await;
        assert!(slice.payload.get("exit").is_none());
        assert!(slice.payload.get("command").is_none());
    }

    // ── what was dropped ────────────────────────────────────────────────────

    /// The criterion: dropped counts are reported so the model knows.
    #[tokio::test]
    async fn dropped_counts_are_reported() {
        let slice = slice(&build_log(), 300).await;
        let dropped = &slice.payload["dropped"];

        assert!(dropped["lines"].as_u64().unwrap() > 900);
        assert_eq!(slice.payload["total_lines"], 1_005);
    }

    /// A model told nothing was dropped will reason as though it has the whole
    /// log, so the flag has to be honest in both directions.
    #[tokio::test]
    async fn a_log_that_fits_entirely_is_not_marked_lossy() {
        let slice = slice("line one\nline two\nline three\n", 500).await;

        assert!(!slice.lossy);
        assert!(slice.payload.get("dropped").is_none());
        assert_eq!(texts(&slice).len(), 3);
    }

    #[tokio::test]
    async fn dropped_errors_are_counted_separately_as_a_hint_to_fetch_the_raw() {
        let mut text = String::new();
        for i in 0..200 {
            text.push_str(&format!("error: failure number {i}\n"));
        }
        let slice = slice(&text, 200).await;

        let dropped = slice.payload["dropped"]["errors"].as_u64().unwrap();
        assert!(
            dropped > 0,
            "not every error fits, and that is worth saying"
        );
    }

    // ── classification ──────────────────────────────────────────────────────

    #[test]
    fn common_error_conventions_are_recognised() {
        for line in [
            "error[E0308]: mismatched types",
            "ERROR: connection refused",
            "  fatal: not a git repository",
            "Traceback (most recent call last):",
            "panic: runtime error",
            "test tests::it_works ... FAILED",
            "assertion failed: left == right",
            "E: Unable to locate package",
        ] {
            assert_eq!(Level::of(line), Level::Error, "{line}");
        }
    }

    #[test]
    fn common_warning_conventions_are_recognised() {
        for line in [
            "warning: unused variable `x`",
            "WARN  stale lockfile",
            "  deprecated: use bar instead",
        ] {
            assert_eq!(Level::of(line), Level::Warning, "{line}");
        }
    }

    /// `src/error.rs` appears in almost every Rust build log, and treating it
    /// as an error line would fill the cap with compiler progress output.
    #[test]
    fn a_path_containing_error_is_not_an_error_line() {
        for line in [
            "   Compiling boundgraph-core v0.1.0 (crates/boundgraph-core/src/error.rs)",
            "   Doc-tests error handling",
            "info: writing errors.log",
        ] {
            assert_eq!(Level::of(line), Level::Info, "{line}");
        }
    }

    #[test]
    fn anything_unrecognised_is_informational() {
        assert_eq!(Level::of(""), Level::Info);
        assert_eq!(Level::of("   Compiling serde v1.0"), Level::Info);
        assert!(Level::Error.is_notable());
        assert!(!Level::Info.is_notable());
    }

    // ── the contract ────────────────────────────────────────────────────────

    /// The guarantee the trait enforces, exercised against a real log.
    #[tokio::test]
    async fn the_output_never_exceeds_the_cap() {
        let store = MemoryStore::new();
        let raw = raw_of(&build_log());

        for cap in [64, 128, 256, 512, 1_024, 4_096] {
            let condensate = LogSlicer::new()
                .condense(&raw, cap, &store)
                .await
                .unwrap_or_else(|e| panic!("cap {cap} should be satisfiable: {e}"));
            assert_eq!(condensate.cap, cap);
        }
    }

    #[tokio::test]
    async fn slicing_is_deterministic() {
        let raw = raw_of(&build_log());
        let first = LogSlicer::new().slice(&raw, 400).await.unwrap();
        for _ in 0..8 {
            assert_eq!(LogSlicer::new().slice(&raw, 400).await.unwrap(), first);
        }
    }

    #[tokio::test]
    async fn empty_output_is_handled_without_ceremony() {
        let slice = slice("", 200).await;
        assert!(!slice.lossy);
        assert_eq!(slice.payload["total_lines"], 0);
        assert!(texts(&slice).is_empty());
    }

    #[tokio::test]
    async fn output_that_is_not_utf8_still_slices() {
        let raw = Raw::new(vec![b'o', b'k', 0xff, b'\n', b'e', b'r', b'r', b'\n']);
        let slice = LogSlicer::new().slice(&raw, 200).await.unwrap();
        assert_eq!(slice.payload["total_lines"], 2);
    }

    #[tokio::test]
    async fn the_anchor_is_configurable() {
        let text: String = (1..=100).map(|i| format!("line {i}\n")).collect();
        let slice = LogSlicer::new()
            .anchored(10, 0)
            .slice(&raw_of(&text), 120)
            .await
            .unwrap();

        let kept = texts(&slice);
        assert!(kept[0].contains("line 1"));
        assert!(
            kept.iter().take(5).any(|l| l.contains("line 5")),
            "a wider head anchor keeps more of the start: {kept:?}"
        );
    }
}