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
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
//! Condensing patches: whole hunks, or none of them.
//!
//! # Why a truncated diff is worse than no diff
//!
//! Every other slicer here drops information the model can tell is missing. A
//! diff cut at an arbitrary byte does not: it produces something that parses,
//! reads as complete, and describes a change that was never made. A model shown
//! the first half of a hunk sees a deletion with no corresponding insertion and
//! concludes the code was removed.
//!
//! So this slicer never cuts a hunk. Everything it does is at hunk granularity
//! or coarser, and what it drops it names.
//!
//! # The order things are given up
//!
//! 1. **Nothing.** If the whole patch fits, it is kept whole.
//! 2. **Context lines.** The unchanged lines around each change are the
//!    cheapest thing to lose and the least informative — the changed lines are
//!    still there, and the file is still named. Trimmed symmetrically, three
//!    lines to two to one to none.
//! 3. **Whole hunks**, from the end of the patch backwards.
//!
//! Context goes before hunks because a change with no surrounding context is
//! still a true statement about the patch, whereas a missing hunk is a change
//! the model cannot see at all. Which hunks *matter* is explicitly out of scope
//! (US-0704), so the order is positional and predictable rather than clever.
//!
//! # The file list always survives
//!
//! Even a file whose every hunk was dropped keeps its entry, its status, and
//! its `+n/-m` counts. That is the difference between "this patch did not touch
//! `auth.rs`" and "you were not shown what it did to `auth.rs`" — and a review
//! agent that cannot tell those apart is worse than useless.
//!
//! # Binary files are summarised, never inlined
//!
//! A binary patch is megabytes of base85 that no model can read and every model
//! will happily spend a context window on. It becomes one line.

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 diff condensate declares.
pub const DIFF_SCHEMA: &str = "boundgraph.diff.v1";

/// What happened to a file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FileStatus {
    /// The file is new.
    Added,
    /// The file is gone.
    Deleted,
    /// The file changed in place.
    Modified,
    /// The file moved, possibly with changes.
    Renamed,
}

/// One hunk of one file's diff.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Hunk {
    /// The `@@ … @@` header, including the trailing function context git adds.
    pub header: String,
    /// The hunk's lines, each still carrying its leading ` `, `+`, or `-`.
    pub lines: Vec<String>,
    /// Lines added by this hunk.
    pub added: usize,
    /// Lines removed by this hunk.
    pub removed: usize,
}

impl Hunk {
    /// The hunk with at most `context` unchanged lines on each side of every
    /// run of changes.
    ///
    /// Trimming is symmetric and interior: context *between* two nearby changes
    /// is kept when it is short enough to serve both, because dropping it would
    /// imply the changes are adjacent when they are not.
    pub fn with_context(&self, context: usize) -> Self {
        let changed: Vec<usize> = self
            .lines
            .iter()
            .enumerate()
            .filter(|(_, l)| l.starts_with('+') || l.starts_with('-'))
            .map(|(i, _)| i)
            .collect();

        if changed.is_empty() {
            return self.clone();
        }

        let mut keep = vec![false; self.lines.len()];
        for &index in &changed {
            let low = index.saturating_sub(context);
            let high = (index + context).min(self.lines.len() - 1);
            for slot in keep.iter_mut().take(high + 1).skip(low) {
                *slot = true;
            }
        }

        let mut lines = Vec::new();
        let mut skipped = 0usize;
        for (index, line) in self.lines.iter().enumerate() {
            if keep[index] {
                if skipped > 0 {
                    // Say that unchanged lines were removed, so the hunk cannot
                    // be misread as contiguous.
                    lines.push(format!(" … {skipped} unchanged lines"));
                    skipped = 0;
                }
                lines.push(line.clone());
            } else {
                skipped += 1;
            }
        }
        if skipped > 0 {
            lines.push(format!(" … {skipped} unchanged lines"));
        }

        Self {
            header: self.header.clone(),
            lines,
            added: self.added,
            removed: self.removed,
        }
    }
}

/// One file's worth of a patch.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FileDiff {
    /// The path after the change.
    pub path: String,
    /// The path before it, when the file moved.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from: Option<String>,
    /// What happened to it.
    pub status: FileStatus,
    /// Lines added.
    pub added: usize,
    /// Lines removed.
    pub removed: usize,
    /// Whether this is a binary change, summarised rather than shown.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub binary: bool,
    /// The hunks retained for this file. Empty where they were all dropped —
    /// the entry itself always survives.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub hunks: Vec<Hunk>,
}

impl FileDiff {
    /// A summary line, which is what survives when the hunks do not.
    pub fn summary(&self) -> String {
        let kind = match self.status {
            FileStatus::Added => "added",
            FileStatus::Deleted => "deleted",
            FileStatus::Modified => "modified",
            FileStatus::Renamed => "renamed",
        };
        let binary = if self.binary { " binary" } else { "" };
        match &self.from {
            Some(from) => format!(
                "{from} -> {} ({kind}{binary}, +{}/-{})",
                self.path, self.added, self.removed
            ),
            None => format!(
                "{} ({kind}{binary}, +{}/-{})",
                self.path, self.added, self.removed
            ),
        }
    }
}

/// Condenses unified diffs.
///
/// # Example
///
/// ```
/// use boundgraph_slice::{DiffSlicer, MemoryStore, Raw, Slicer};
///
/// let patch = "\
/// diff --git a/src/main.rs b/src/main.rs
/// --- a/src/main.rs
/// +++ b/src/main.rs
/// @@ -1,3 +1,3 @@
///  fn main() {
/// -    println!(\"old\");
/// +    println!(\"new\");
///  }
/// ";
///
/// let condensate = tokio::runtime::Builder::new_current_thread()
///     .build()?
///     .block_on(DiffSlicer::new().condense(&Raw::new(patch), 400, &MemoryStore::new()))?;
///
/// assert!(!condensate.lossy, "a small patch survives whole");
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, Copy)]
pub struct DiffSlicer {
    context: usize,
    min_context: usize,
}

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

impl DiffSlicer {
    /// A slicer keeping three context lines, trimming to none under pressure.
    pub fn new() -> Self {
        Self {
            context: 3,
            min_context: 0,
        }
    }

    /// Keep at most `context` unchanged lines around each change, and never
    /// trim below `min_context`.
    ///
    /// A floor above zero is for a reviewer who needs to see *where* a change
    /// landed even at the cost of dropping more hunks.
    #[must_use]
    pub fn context(mut self, context: usize, min_context: usize) -> Self {
        self.context = context;
        self.min_context = min_context.min(context);
        self
    }

    /// Parse a unified diff into files and hunks.
    ///
    /// Tolerant by design: a patch with an unrecognised header line is still
    /// mostly a patch, and refusing the whole thing over one line git added in
    /// a version nobody here has seen would be worse than ignoring it.
    pub fn parse(text: &str) -> Vec<FileDiff> {
        let mut files: Vec<FileDiff> = Vec::new();
        let mut hunk: Option<Hunk> = None;

        /// Close the hunk being built onto the file being built.
        fn flush(files: &mut [FileDiff], hunk: &mut Option<Hunk>) {
            if let (Some(file), Some(done)) = (files.last_mut(), hunk.take()) {
                file.added += done.added;
                file.removed += done.removed;
                file.hunks.push(done);
            }
        }

        for line in text.lines() {
            if let Some(rest) = line.strip_prefix("diff --git ") {
                flush(&mut files, &mut hunk);
                let path = rest
                    .split_whitespace()
                    .next_back()
                    .unwrap_or("")
                    .strip_prefix("b/")
                    .unwrap_or(rest)
                    .to_string();
                files.push(FileDiff {
                    path,
                    from: None,
                    status: FileStatus::Modified,
                    added: 0,
                    removed: 0,
                    binary: false,
                    hunks: Vec::new(),
                });
                continue;
            }

            if let Some(file) = files.last_mut() {
                if line.starts_with("new file mode") {
                    file.status = FileStatus::Added;
                    continue;
                }
                if line.starts_with("deleted file mode") {
                    file.status = FileStatus::Deleted;
                    continue;
                }
                if let Some(from) = line.strip_prefix("rename from ") {
                    file.status = FileStatus::Renamed;
                    file.from = Some(from.to_string());
                    continue;
                }
                if line.starts_with("rename to ") {
                    continue;
                }
                // Both the textual marker and git's binary patch body.
                if line.starts_with("Binary files ") || line.starts_with("GIT binary patch") {
                    flush(&mut files, &mut hunk);
                    if let Some(file) = files.last_mut() {
                        file.binary = true;
                    }
                    continue;
                }
            }

            if line.starts_with("@@") {
                flush(&mut files, &mut hunk);
                if files.is_empty() {
                    // A bare unified diff with no `diff --git` preamble.
                    files.push(FileDiff {
                        path: "(unnamed)".to_string(),
                        from: None,
                        status: FileStatus::Modified,
                        added: 0,
                        removed: 0,
                        binary: false,
                        hunks: Vec::new(),
                    });
                }
                hunk = Some(Hunk {
                    header: line.to_string(),
                    lines: Vec::new(),
                    added: 0,
                    removed: 0,
                });
                continue;
            }

            // `--- a/x` and `+++ b/x` name the file; they are not hunk content,
            // and mistaking them for it would count them as a removal and an
            // addition in every single file.
            if hunk.is_none() {
                if let Some(path) = line.strip_prefix("+++ b/").or(line.strip_prefix("+++ ")) {
                    if let Some(file) = files.last_mut()
                        && file.path.is_empty()
                    {
                        file.path = path.to_string();
                    }
                }
                continue;
            }

            if let Some(open) = hunk.as_mut() {
                match line.chars().next() {
                    Some('+') => open.added += 1,
                    Some('-') => open.removed += 1,
                    // A context line, or git's "\ No newline at end of file".
                    Some(' ') | Some('\\') | None => {}
                    // Anything else ends the hunk: the next file's preamble.
                    _ => {
                        flush(&mut files, &mut hunk);
                        continue;
                    }
                }
                if let Some(open) = hunk.as_mut() {
                    open.lines.push(line.to_string());
                }
            }
        }

        flush(&mut files, &mut hunk);
        // Binary changes carry no readable hunks, whatever the patch contained.
        for file in &mut files {
            if file.binary {
                file.hunks.clear();
            }
        }
        files
    }

    /// The payload for a given context width and hunk budget.
    ///
    /// `kept` is how many hunks, counted across the whole patch in order,
    /// survive. Every file entry is present regardless.
    fn payload(files: &[FileDiff], context: usize, kept: usize) -> serde_json::Value {
        let mut shown = 0usize;
        let mut dropped_hunks = 0usize;
        let mut dropped_paths: Vec<&str> = Vec::new();

        let rendered: Vec<FileDiff> = files
            .iter()
            .map(|file| {
                let mut out = file.clone();
                out.hunks = Vec::new();
                for hunk in &file.hunks {
                    if shown < kept {
                        out.hunks.push(hunk.with_context(context));
                        shown += 1;
                    } else {
                        dropped_hunks += 1;
                    }
                }
                if !file.hunks.is_empty() && out.hunks.is_empty() {
                    dropped_paths.push(&file.path);
                }
                out
            })
            .collect();

        let mut payload = json!({
            "files": rendered,
            "stats": {
                "files": files.len(),
                "added": files.iter().map(|f| f.added).sum::<usize>(),
                "removed": files.iter().map(|f| f.removed).sum::<usize>(),
                "hunks": files.iter().map(|f| f.hunks.len()).sum::<usize>(),
            },
        });

        if dropped_hunks > 0 {
            payload["dropped"] = json!({
                "hunks": dropped_hunks,
                "files": dropped_paths.len(),
                "paths": dropped_paths,
            });
        }
        if context < 3 {
            payload["context"] = json!(context);
        }
        payload
    }
}

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

    async fn slice(&self, raw: &Raw, cap: usize) -> Result<Slice, SliceError> {
        let text = raw.text();
        let files = Self::parse(&text);
        let schema = SchemaId::new(DIFF_SCHEMA, 1);
        let total_hunks: usize = files.iter().map(|f| f.hunks.len()).sum();

        let counter = self.counter();
        let fits = |value: &serde_json::Value| {
            counter.count(&serde_json::to_string(value).unwrap_or_default()) <= cap
        };

        // The file list and its statistics are retained whatever the cap, so if
        // they alone do not fit there is no slice to make.
        let floor = Self::payload(&files, self.min_context, 0);
        if !fits(&floor) {
            return Err(SliceError::CapTooSmall {
                cap,
                minimum: counter.count(&serde_json::to_string(&floor).unwrap_or_default()),
            });
        }

        // 1 and 2: widest context that fits with every hunk, trimming down.
        for context in (self.min_context..=self.context).rev() {
            let candidate = Self::payload(&files, context, total_hunks);
            if fits(&candidate) {
                return Ok(Slice {
                    schema,
                    lossy: context < self.context || files.iter().any(|f| f.binary),
                    payload: candidate,
                });
            }
        }

        // 3: drop whole hunks from the end, at the tightest context.
        let mut kept = total_hunks;
        while kept > 0 {
            kept -= 1;
            let candidate = Self::payload(&files, self.min_context, kept);
            if fits(&candidate) {
                return Ok(Slice {
                    schema,
                    payload: candidate,
                    lossy: true,
                });
            }
        }

        Ok(Slice {
            schema,
            payload: floor,
            lossy: true,
        })
    }
}

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

    const SMALL: &str = "\
diff --git a/src/main.rs b/src/main.rs
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,5 +1,5 @@
 fn main() {
     let a = 1;
-    println!(\"old\");
+    println!(\"new\");
     let b = 2;
 }
";

    /// Several files, several hunks each, plus a binary and a rename.
    fn big_patch() -> String {
        let mut out = String::new();
        for file in 0..8 {
            out.push_str(&format!(
                "diff --git a/src/mod_{file}.rs b/src/mod_{file}.rs\n--- a/src/mod_{file}.rs\n+++ b/src/mod_{file}.rs\n"
            ));
            for hunk in 0..4 {
                out.push_str(&format!(
                    "@@ -{0},8 +{0},9 @@ fn thing_{hunk}()\n",
                    hunk * 20 + 1
                ));
                for c in 0..3 {
                    out.push_str(&format!(" untouched line {c}\n"));
                }
                out.push_str(&format!("-    let old_{hunk} = 1;\n"));
                out.push_str(&format!("+    let new_{hunk} = 2;\n"));
                out.push_str(&format!("+    let extra_{hunk} = 3;\n"));
                for c in 0..3 {
                    out.push_str(&format!(" trailing line {c}\n"));
                }
            }
        }
        out.push_str("diff --git a/assets/logo.png b/assets/logo.png\nBinary files a/assets/logo.png and b/assets/logo.png differ\n");
        out.push_str("diff --git a/old.rs b/new.rs\nrename from old.rs\nrename to new.rs\n");
        out
    }

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

    async fn slice(text: &str, cap: usize) -> Slice {
        DiffSlicer::new()
            .slice(&raw_of(text), cap)
            .await
            .expect("a satisfiable cap")
    }

    fn hunk_lines(slice: &Slice) -> Vec<String> {
        slice.payload["files"]
            .as_array()
            .unwrap()
            .iter()
            .flat_map(|f| f["hunks"].as_array().cloned().unwrap_or_default())
            .flat_map(|h| h["lines"].as_array().cloned().unwrap_or_default())
            .map(|l| l.as_str().unwrap().to_string())
            .collect()
    }

    // ── parsing ─────────────────────────────────────────────────────────────

    #[test]
    fn a_simple_patch_parses_to_one_file_and_one_hunk() {
        let files = DiffSlicer::parse(SMALL);
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].path, "src/main.rs");
        assert_eq!(files[0].hunks.len(), 1);
        assert_eq!(files[0].added, 1);
        assert_eq!(files[0].removed, 1);
    }

    /// `--- a/x` and `+++ b/x` are not hunk content. Counting them would report
    /// one extra addition and removal in every file in every patch.
    #[test]
    fn the_file_header_is_not_counted_as_a_change() {
        let files = DiffSlicer::parse(SMALL);
        assert_eq!(files[0].added, 1, "exactly the one +line");
        assert_eq!(files[0].removed, 1, "exactly the one -line");
    }

    #[test]
    fn file_status_is_read_from_the_preamble() {
        let patch = "\
diff --git a/new.rs b/new.rs
new file mode 100644
--- /dev/null
+++ b/new.rs
@@ -0,0 +1 @@
+fn main() {}
diff --git a/gone.rs b/gone.rs
deleted file mode 100644
@@ -1 +0,0 @@
-fn main() {}
diff --git a/old.rs b/moved.rs
rename from old.rs
rename to moved.rs
";
        let files = DiffSlicer::parse(patch);
        assert_eq!(files[0].status, FileStatus::Added);
        assert_eq!(files[1].status, FileStatus::Deleted);
        assert_eq!(files[2].status, FileStatus::Renamed);
        assert_eq!(files[2].from.as_deref(), Some("old.rs"));
    }

    // ── hunks are never cut ─────────────────────────────────────────────────

    /// The criterion the whole slicer is built around.
    #[tokio::test]
    async fn a_hunk_is_never_cut_in_half() {
        let patch = big_patch();

        for cap in [320, 400, 800, 1_600, 3_200, 8_000] {
            let slice = slice(&patch, cap).await;
            for file in slice.payload["files"].as_array().unwrap() {
                for hunk in file["hunks"].as_array().cloned().unwrap_or_default() {
                    let header = hunk["header"].as_str().unwrap();
                    assert!(header.starts_with("@@"), "cap {cap}: {header}");
                    assert!(
                        !hunk["lines"].as_array().unwrap().is_empty(),
                        "cap {cap}: a hunk with a header and no lines is a cut hunk"
                    );
                }
            }
        }
    }

    #[tokio::test]
    async fn a_patch_that_fits_is_kept_whole_and_is_not_lossy() {
        let slice = slice(SMALL, 500).await;

        assert!(!slice.lossy);
        assert!(slice.payload.get("dropped").is_none());
        let lines = hunk_lines(&slice);
        assert!(lines.iter().any(|l| l.contains("old")));
        assert!(lines.iter().any(|l| l.contains("new")));
    }

    // ── the file list survives ──────────────────────────────────────────────

    /// The criterion: the file list and per-file stats are always retained.
    /// The difference between "the patch did not touch auth.rs" and "you were
    /// not shown what it did to auth.rs".
    #[tokio::test]
    async fn every_file_keeps_its_entry_and_stats_however_tight_the_cap() {
        let patch = big_patch();
        let all = DiffSlicer::parse(&patch);

        for cap in [320, 400, 600, 1_000] {
            let slice = slice(&patch, cap).await;
            let files = slice.payload["files"].as_array().unwrap();
            assert_eq!(files.len(), all.len(), "at cap {cap}");

            for (shown, parsed) in files.iter().zip(&all) {
                assert_eq!(shown["path"], parsed.path.as_str(), "at cap {cap}");
                assert_eq!(shown["added"], parsed.added, "at cap {cap}");
                assert_eq!(shown["removed"], parsed.removed, "at cap {cap}");
            }
        }
    }

    #[tokio::test]
    async fn the_overall_statistics_are_always_present() {
        let slice = slice(&big_patch(), 320).await;
        let stats = &slice.payload["stats"];

        assert_eq!(stats["files"], 10);
        assert_eq!(stats["hunks"], 32);
        assert!(stats["added"].as_u64().unwrap() > 0);
    }

    /// The criterion: dropped files and counts are reported.
    #[tokio::test]
    async fn dropped_hunks_and_the_files_they_belonged_to_are_named() {
        let slice = slice(&big_patch(), 420).await;
        let dropped = &slice.payload["dropped"];

        assert!(dropped["hunks"].as_u64().unwrap() > 0);
        let paths = dropped["paths"].as_array().unwrap();
        assert!(!paths.is_empty(), "a dropped file should be named");
        assert!(paths[0].as_str().unwrap().contains("src/mod_"));
        assert!(slice.lossy);
    }

    // ── context is trimmed before hunks are dropped ─────────────────────────

    /// The criterion. A change with no context is still a true statement about
    /// the patch; a missing hunk is a change the model cannot see at all.
    #[tokio::test]
    async fn context_is_trimmed_before_any_hunk_is_dropped() {
        let patch = big_patch();
        let total: usize = DiffSlicer::parse(&patch)
            .iter()
            .map(|f| f.hunks.len())
            .sum();

        // A cap where the patch does not fit at full context but does at less.
        let mut trimmed_but_complete = None;
        for cap in (320..6_000).step_by(40) {
            let slice = slice(&patch, cap).await;
            let shown: usize = slice.payload["files"]
                .as_array()
                .unwrap()
                .iter()
                .map(|f| f["hunks"].as_array().map_or(0, |h| h.len()))
                .sum();
            if shown == total && slice.payload.get("context").is_some() {
                trimmed_but_complete = Some((cap, slice));
                break;
            }
        }

        let (cap, slice) =
            trimmed_but_complete.expect("some cap should trim context while keeping every hunk");
        assert!(slice.payload.get("dropped").is_none(), "at cap {cap}");
        assert!(slice.lossy, "trimming context is still lossy");
    }

    #[test]
    fn trimming_keeps_the_changed_lines_and_marks_what_it_removed() {
        let hunk = Hunk {
            header: "@@ -1,9 +1,9 @@".into(),
            lines: vec![
                " a".into(),
                " b".into(),
                " c".into(),
                "-old".into(),
                "+new".into(),
                " d".into(),
                " e".into(),
                " f".into(),
            ],
            added: 1,
            removed: 1,
        };

        let tight = hunk.with_context(1);
        assert!(tight.lines.iter().any(|l| l == "-old"));
        assert!(tight.lines.iter().any(|l| l == "+new"));
        assert!(
            tight.lines.iter().any(|l| l.contains("unchanged lines")),
            "removed context is marked, not silently dropped: {:?}",
            tight.lines
        );
        assert!(tight.lines.len() < hunk.lines.len());
    }

    #[test]
    fn trimming_to_zero_context_keeps_only_the_changes() {
        let hunk = Hunk {
            header: "@@ -1,5 +1,5 @@".into(),
            lines: vec![" a".into(), "-old".into(), "+new".into(), " b".into()],
            added: 1,
            removed: 1,
        };
        let bare = hunk.with_context(0);
        let kept: Vec<_> = bare
            .lines
            .iter()
            .filter(|l| l.starts_with('+') || l.starts_with('-'))
            .collect();
        assert_eq!(kept.len(), 2);
    }

    #[test]
    fn the_context_width_is_configurable() {
        let slicer = DiffSlicer::new().context(5, 2);
        assert_eq!(slicer.context, 5);
        assert_eq!(slicer.min_context, 2);

        // A floor above the width is clamped rather than inverting the range.
        let clamped = DiffSlicer::new().context(2, 9);
        assert_eq!(clamped.min_context, 2);
    }

    // ── binary ──────────────────────────────────────────────────────────────

    /// The criterion: a binary change is a summary, not megabytes of base85 a
    /// model cannot read and will happily spend a window on.
    #[tokio::test]
    async fn a_binary_change_is_summarised_rather_than_inlined() {
        let patch = "\
diff --git a/logo.png b/logo.png
index 1234..5678 100644
GIT binary patch
literal 20480
zcmeI5X;@QNzQ6VHl!yqA000mG000000AyiwXaE2J
";
        let slice = slice(patch, 400).await;
        let file = &slice.payload["files"][0];

        assert_eq!(file["binary"], true);
        assert!(
            file.get("hunks").is_none(),
            "no binary content should reach the payload"
        );
        assert!(
            !serde_json::to_string(&slice.payload)
                .unwrap()
                .contains("zcmeI5"),
            "the base85 body must not survive"
        );
        assert!(slice.lossy);
    }

    #[test]
    fn a_binary_file_still_gets_a_summary_line() {
        let file = FileDiff {
            path: "logo.png".into(),
            from: None,
            status: FileStatus::Modified,
            added: 0,
            removed: 0,
            binary: true,
            hunks: Vec::new(),
        };
        assert!(file.summary().contains("logo.png"));
        assert!(file.summary().contains("binary"));
    }

    #[test]
    fn a_rename_summary_names_both_paths() {
        let file = FileDiff {
            path: "new.rs".into(),
            from: Some("old.rs".into()),
            status: FileStatus::Renamed,
            added: 2,
            removed: 1,
            binary: false,
            hunks: Vec::new(),
        };
        assert!(file.summary().contains("old.rs -> new.rs"));
        assert!(file.summary().contains("+2/-1"));
    }

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

    #[tokio::test]
    async fn the_output_never_exceeds_the_cap() {
        let store = MemoryStore::new();
        let raw = raw_of(&big_patch());

        for cap in [320, 400, 800, 1_600, 3_200, 10_000] {
            let condensate = DiffSlicer::new()
                .condense(&raw, cap, &store)
                .await
                .unwrap_or_else(|e| panic!("cap {cap} should be satisfiable: {e}"));
            assert_eq!(condensate.cap, cap);
        }
    }

    /// A consequence of retaining the file list unconditionally: the floor
    /// grows with the number of files touched. A step that reviews
    /// twenty-file patches needs a bigger `CtxSpec` than one that reviews
    /// single-file patches, and the error says so with a number rather than
    /// leaving the author to work it out.
    #[tokio::test]
    async fn the_floor_grows_with_the_number_of_files() {
        let floor_of = |files: usize| async move {
            let mut patch = String::new();
            for f in 0..files {
                patch.push_str(&format!(
                    "diff --git a/src/f_{f}.rs b/src/f_{f}.rs\n@@ -1 +1 @@\n-a\n+b\n"
                ));
            }
            match DiffSlicer::new().slice(&raw_of(&patch), 1).await {
                Err(SliceError::CapTooSmall { minimum, .. }) => minimum,
                other => panic!("expected a floor, got {other:?}"),
            }
        };

        let one = floor_of(1).await;
        let twenty = floor_of(20).await;
        assert!(
            twenty > one * 5,
            "twenty files ({twenty}) should cost far more than one ({one})"
        );
    }

    #[tokio::test]
    async fn a_cap_below_the_file_list_reports_the_measured_floor() {
        let err = DiffSlicer::new()
            .slice(&raw_of(&big_patch()), 30)
            .await
            .unwrap_err();

        let SliceError::CapTooSmall { minimum, .. } = err else {
            panic!("expected CapTooSmall, got {err:?}");
        };
        assert!(minimum > 30);
    }

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

    #[tokio::test]
    async fn something_that_is_not_a_diff_produces_an_empty_patch_rather_than_failing() {
        let slice = slice("this is just prose, not a patch at all\n", 200).await;
        assert_eq!(slice.payload["stats"]["files"], 0);
        assert!(!slice.lossy);
    }

    #[tokio::test]
    async fn a_bare_unified_diff_without_a_git_preamble_still_parses() {
        let patch = "\
@@ -1,3 +1,3 @@
 fn main() {
-    old();
+    new();
";
        let slice = slice(patch, 300).await;
        assert_eq!(slice.payload["stats"]["files"], 1);
        assert_eq!(slice.payload["stats"]["hunks"], 1);
    }
}