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
//! The contract every slicer meets, and the machinery that makes it hold.
//!
//! # Why the guarantee is in the trait rather than in each implementation
//!
//! Law II says a step receives only the context it declared, and the cost model
//! rests on that: `s_max` is what keeps total cost linear in the number of steps
//! instead of quadratic. A slicer that could exceed its cap would break a bound
//! the compiler has already promised a reviewer — and it would break it
//! silently, four slicers deep, in whichever one was written last.
//!
//! So [`Slicer::condense`] is a **provided** method. An implementation writes
//! [`slice`](Slicer::slice) and never sees the cap enforcement, the CAS write,
//! or the condensate assembly; `condense` does all three around it. Adding a
//! fifth slicer therefore cannot forget any of them, which is the only way a
//! guarantee spread across implementations stays true.
//!
//! # Over the cap is an error, never a truncation
//!
//! [`SliceError::OverCap`] is deliberately not recoverable by chopping the tail
//! off. A slicer that produced too much has misjudged its own output, and
//! silently cutting the excess would be exactly the naive truncation the whole
//! layer exists to avoid — the last thing dropped would be the end of the file,
//! which is where the interesting part usually is. Failing tells the author
//! their slicer is wrong; truncating tells the model a lie.
//!
//! # Counting tokens without a tokeniser
//!
//! Caps are in tokens; nothing here can tokenise. [`TokenCount`] is the seam.
//! The default, [`Estimate`], is deliberately pessimistic — it assumes text
//! costs more tokens per byte than it usually does — because the failure modes
//! are asymmetric: over-estimating wastes a little window, under-estimating
//! breaks Law II at admission time, after the money is spent. A caller with a
//! real tokeniser injects it and gets exact behaviour.
//!
//! # Determinism
//!
//! Slicing is a pure function of `(raw, cap)`. No clock, no randomness, no
//! iteration over a hashed collection. Replay (US-1006) re-slices recorded raw
//! output and compares digests, so a slicer that varied between runs would make
//! a replayed run fail to match for reasons that have nothing to do with the
//! model.

use std::fmt;
use std::time::Duration;

use async_trait::async_trait;
use boundgraph_core::{Condensate, CondensatePayload, Digest, SchemaId, SlicerId};
use serde::{Deserialize, Serialize};

/// Where raw output is kept so that nothing is lost by slicing.
///
/// # Why this is declared here
///
/// `ARCHITECTURE.md` §5 lists `Store` among the nine extension points, and
/// feature 10 will own the durable implementation — the journal references
/// payloads by CAS digest (US-1005) and so does a large condensate payload
/// (US-0104). None of that exists yet, and US-0701 needs exactly one thing from
/// it: somewhere to put the original before the copy is cut down.
///
/// So the boundary is declared here, as narrowly as it can be, exactly as the
/// runtime declares [`LedgerSink`](boundgraph_runtime::LedgerSink) for the log it does
/// not own. Feature 10's store will satisfy it unchanged.
#[async_trait]
pub trait Store: Send + Sync + fmt::Debug {
    /// Write bytes, returning their content address.
    ///
    /// Idempotent by construction: the address *is* the content, so storing the
    /// same bytes twice is storing them once.
    ///
    /// # Errors
    ///
    /// [`StoreError`] if the bytes could not be written. The caller must treat
    /// that as the slice not having happened — a condensate whose `raw` points
    /// at nothing is worse than no condensate, because it claims an original
    /// that cannot be produced.
    async fn put(&self, bytes: &[u8]) -> Result<Digest, StoreError>;

    /// Read bytes back by address.
    ///
    /// # Errors
    ///
    /// [`StoreError`] if the bytes are not there or could not be read.
    async fn get(&self, digest: &Digest) -> Result<Vec<u8>, StoreError>;
}

/// The content-addressed store could not be used.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum StoreError {
    /// Nothing is stored under that address.
    #[error("nothing is stored at {0}")]
    NotFound(Digest),
    /// The store itself failed.
    #[error("the content store failed: {0}")]
    Unavailable(String),
}

/// Turns text into a token count.
///
/// See the module documentation for why the default is pessimistic.
pub trait TokenCount: Send + Sync + fmt::Debug {
    /// How many tokens `text` is worth.
    fn count(&self, text: &str) -> usize;
}

/// The default token estimate: pessimistic, and deterministic.
///
/// # How it counts
///
/// Three bytes per token, rounded up, plus one token per line. Real byte-level
/// BPE averages closer to four bytes per token on prose and rather worse on
/// dense punctuation, which is most of what a slicer handles — code, diffs, and
/// JSON. The per-line term is there because newlines and the indentation after
/// them tokenise poorly and a slicer's output is unusually line-dense.
///
/// It is an estimate and says so. What matters is the direction of its error:
/// over-estimating costs a little unused window, under-estimating overruns
/// `s_max` and breaks Law II after the call has been paid for.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Estimate;

impl TokenCount for Estimate {
    fn count(&self, text: &str) -> usize {
        if text.is_empty() {
            return 0;
        }
        let bytes = text.len();
        let lines = text.lines().count();
        bytes.div_ceil(3) + lines
    }
}

/// Counts a token per byte.
///
/// The only counter that is a genuine upper bound: byte-level BPE never emits
/// more tokens than there are bytes, because merging is all it does. Far too
/// conservative for ordinary use — it would spend a 400-token cap on 400 bytes
/// — but it is the right answer when a cap must not be exceeded under any
/// tokeniser at all.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ByteCeiling;

impl TokenCount for ByteCeiling {
    fn count(&self, text: &str) -> usize {
        text.len()
    }
}

/// What running something produced, beyond its output.
///
/// Carried separately from the bytes because US-0703 requires exit status and
/// timing to survive *regardless of the cap*: they are a handful of tokens and
/// they are the first thing anyone asks about a failed command, so a slicer
/// that dropped them to fit more log lines would have optimised the wrong way.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CommandOutcome {
    /// The command line, as invoked.
    pub command: String,
    /// The process exit status. `None` where it was killed by a signal or never
    /// finished.
    pub exit: Option<i32>,
    /// How long it ran.
    pub duration: Duration,
}

impl CommandOutcome {
    /// Record a command that finished with a status.
    pub fn new(command: impl Into<String>, exit: i32, duration: Duration) -> Self {
        Self {
            command: command.into(),
            exit: Some(exit),
            duration,
        }
    }

    /// Whether it succeeded.
    pub fn succeeded(&self) -> bool {
        self.exit == Some(0)
    }

    /// A one-line summary, always retained.
    pub fn summary(&self) -> String {
        let status = match self.exit {
            Some(0) => "ok".to_string(),
            Some(code) => format!("exit {code}"),
            None => "killed".to_string(),
        };
        format!(
            "$ {} — {status} in {}ms",
            self.command,
            self.duration.as_millis()
        )
    }
}

/// Raw tool output, before slicing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Raw {
    /// The complete, unmodified bytes.
    pub bytes: Vec<u8>,
    /// What produced them, where it was a command.
    pub command: Option<CommandOutcome>,
    /// A hint at the content, e.g. a file name or language, for slicers that
    /// can use one. Never load-bearing: a slicer is chosen by the flow.
    pub hint: Option<String>,
}

impl Raw {
    /// Raw bytes with no provenance.
    pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
        Self {
            bytes: bytes.into(),
            command: None,
            hint: None,
        }
    }

    /// Raw output from a command.
    #[must_use]
    pub fn from_command(mut self, outcome: CommandOutcome) -> Self {
        self.command = Some(outcome);
        self
    }

    /// Hint at what this is.
    #[must_use]
    pub fn hinting(mut self, hint: impl Into<String>) -> Self {
        self.hint = Some(hint.into());
        self
    }

    /// The bytes as text, replacing anything that is not valid UTF-8.
    ///
    /// Lossy rather than failing: tool output is frequently *nearly* UTF-8 —
    /// a stray byte in a filename, a terminal escape — and refusing to slice a
    /// build log over one bad byte would be worse than showing a replacement
    /// character. The original bytes are in the CAS either way.
    pub fn text(&self) -> std::borrow::Cow<'_, str> {
        String::from_utf8_lossy(&self.bytes)
    }

    /// How large the original was.
    pub fn len(&self) -> usize {
        self.bytes.len()
    }

    /// Whether there was any output at all.
    pub fn is_empty(&self) -> bool {
        self.bytes.is_empty()
    }
}

/// What a slicer produced, before it becomes a [`Condensate`].
///
/// The slicer says what it made and whether it dropped anything; `condense`
/// turns that into the addressed, typed value the rest of the system sees.
#[derive(Debug, Clone, PartialEq)]
pub struct Slice {
    /// The shape of the summary.
    pub schema: SchemaId,
    /// The summary itself.
    pub payload: serde_json::Value,
    /// Whether information was dropped.
    ///
    /// Set honestly. A slicer that under-reports this is telling a downstream
    /// step it has the whole picture when it does not, and nothing downstream
    /// can detect the lie — which is why every slicer in this crate has a test
    /// that a lossless slice reports `false` and a dropping one reports `true`.
    pub lossy: bool,
}

impl Slice {
    /// A slice that dropped nothing.
    pub fn complete(schema: SchemaId, payload: serde_json::Value) -> Self {
        Self {
            schema,
            payload,
            lossy: false,
        }
    }

    /// A slice that dropped something.
    pub fn lossy(schema: SchemaId, payload: serde_json::Value) -> Self {
        Self {
            schema,
            payload,
            lossy: true,
        }
    }

    /// The rendered form, which is what the cap is measured against.
    ///
    /// A condensate's payload is structured, but what reaches a model is its
    /// serialisation — so that is what has to fit. Measuring the structure
    /// instead would let a slicer pass the check and overrun the window.
    pub fn rendered(&self) -> String {
        serde_json::to_string(&self.payload).unwrap_or_default()
    }
}

/// Slicing failed.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum SliceError {
    /// The slicer produced more than the cap allows.
    ///
    /// A bug in the slicer, not a condition to handle: see the module
    /// documentation for why this is not silently truncated.
    #[error("slicer {slicer} produced {produced} tokens against a cap of {cap}")]
    OverCap {
        /// Which slicer overran.
        slicer: String,
        /// What it produced.
        produced: usize,
        /// What it was allowed.
        cap: usize,
    },

    /// The cap is too small to say anything at all.
    ///
    /// Distinct from [`OverCap`](Self::OverCap): the slicer did nothing wrong,
    /// the step declared a window that cannot hold even a summary. That is a
    /// flow authoring error and the message says so.
    #[error("a cap of {cap} tokens cannot hold even a summary (needs at least {minimum})")]
    CapTooSmall {
        /// What was allowed.
        cap: usize,
        /// The least that would work.
        minimum: usize,
    },

    /// The raw output could not be preserved.
    #[error("the raw output could not be stored: {0}")]
    Store(#[from] StoreError),

    /// The input was not what this slicer handles.
    ///
    /// Carries the reason so a caller can decide to fall back — which is what
    /// the AST slicer does when a file does not parse (US-0702).
    #[error("{slicer} cannot slice this input: {detail}")]
    Unsuitable {
        /// Which slicer declined.
        slicer: String,
        /// Why.
        detail: String,
    },
}

impl SliceError {
    /// Whether another slicer might succeed where this one did not.
    ///
    /// True only for [`Unsuitable`](Self::Unsuitable). An over-cap slicer is
    /// broken and a too-small cap is a flow error; neither is fixed by trying
    /// something else, and falling back on them would hide a real problem.
    pub fn can_fall_back(&self) -> bool {
        matches!(self, Self::Unsuitable { .. })
    }
}

/// Layer 4: turns raw output into a size-capped, typed summary.
///
/// Implement [`slice`](Self::slice) and [`id`](Self::id). Do not implement
/// [`condense`](Self::condense) — it is what enforces the contract, and the
/// whole design of this module is that an implementation cannot opt out of it.
#[async_trait]
pub trait Slicer: Send + Sync + fmt::Debug {
    /// Which slicer this is, and at what version.
    ///
    /// Recorded into every condensate, so re-slicing the same raw output later
    /// can be checked against the version that originally produced it.
    fn id(&self) -> SlicerId;

    /// How this slicer counts tokens.
    ///
    /// Defaults to [`Estimate`]. Override to inject a real tokeniser.
    fn counter(&self) -> &dyn TokenCount {
        &Estimate
    }

    /// The least a summary from this slicer can cost.
    ///
    /// Used to turn an impossible cap into [`SliceError::CapTooSmall`] before
    /// any work happens, so the author is told their step's window is too small
    /// rather than handed a mysterious over-cap failure.
    fn minimum_cap(&self) -> usize {
        16
    }

    /// Produce the summary. The part an implementation writes.
    ///
    /// Must be a pure function of `(raw, cap)` — see the module documentation
    /// on determinism.
    ///
    /// # Errors
    ///
    /// [`SliceError::Unsuitable`] if this slicer does not handle the input.
    async fn slice(&self, raw: &Raw, cap: usize) -> Result<Slice, SliceError>;

    /// Preserve the original, slice it, and check the result fits.
    ///
    /// In that order, and the order matters: the raw bytes reach the store
    /// *before* anything is dropped, so a slicer that fails part-way through
    /// still leaves the original recoverable.
    ///
    /// # Errors
    ///
    /// [`SliceError::Store`] if the original could not be preserved,
    /// [`SliceError::CapTooSmall`] if the cap cannot hold a summary,
    /// [`SliceError::OverCap`] if the slicer overran it, or whatever
    /// [`slice`](Self::slice) returned.
    async fn condense(
        &self,
        raw: &Raw,
        cap: usize,
        store: &dyn Store,
    ) -> Result<Condensate, SliceError> {
        let minimum = self.minimum_cap();
        if cap < minimum {
            return Err(SliceError::CapTooSmall { cap, minimum });
        }

        // Before slicing, so nothing is lost even if slicing then fails.
        let digest = store.put(&raw.bytes).await?;

        let slice = self.slice(raw, cap).await?;

        let produced = self.counter().count(&slice.rendered());
        if produced > cap {
            return Err(SliceError::OverCap {
                slicer: self.id().name.clone(),
                produced,
                cap,
            });
        }

        Ok(Condensate::new(
            slice.schema,
            CondensatePayload::inline(&slice.payload).map_err(|e| SliceError::Unsuitable {
                slicer: self.id().name.clone(),
                detail: format!("the summary could not be encoded: {e}"),
            })?,
            digest,
            cap,
            slice.lossy,
            self.id(),
        ))
    }
}

/// A store that keeps everything in memory.
///
/// What the M3 milestone runs on, and a first-class part of the crate for the
/// same reason the mock reasoner is: a test, a cassette replay, and a policy
/// check all want a store that needs no filesystem.
#[derive(Debug, Default)]
pub struct MemoryStore {
    blobs: std::sync::Mutex<std::collections::BTreeMap<Digest, Vec<u8>>>,
}

impl MemoryStore {
    /// An empty store.
    pub fn new() -> Self {
        Self::default()
    }

    /// How many distinct blobs are held.
    ///
    /// Distinct, not written: content addressing means storing the same bytes
    /// twice stores them once, and this is how that is asserted.
    pub fn len(&self) -> usize {
        self.blobs.lock().expect("store lock").len()
    }

    /// Whether nothing has been stored.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

#[async_trait]
impl Store for MemoryStore {
    async fn put(&self, bytes: &[u8]) -> Result<Digest, StoreError> {
        let digest = Digest::of(bytes);
        self.blobs
            .lock()
            .expect("store lock")
            .insert(digest, bytes.to_vec());
        Ok(digest)
    }

    async fn get(&self, digest: &Digest) -> Result<Vec<u8>, StoreError> {
        self.blobs
            .lock()
            .expect("store lock")
            .get(digest)
            .cloned()
            .ok_or(StoreError::NotFound(*digest))
    }
}

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

    /// A slicer that emits exactly what it is told to, including too much.
    #[derive(Debug)]
    struct Fixed {
        payload: serde_json::Value,
        lossy: bool,
    }

    impl Fixed {
        fn new(payload: serde_json::Value) -> Self {
            Self {
                payload,
                lossy: false,
            }
        }
    }

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

        async fn slice(&self, _raw: &Raw, _cap: usize) -> Result<Slice, SliceError> {
            Ok(Slice {
                schema: SchemaId::new("test.fixed.v1", 1),
                payload: self.payload.clone(),
                lossy: self.lossy,
            })
        }
    }

    fn raw() -> Raw {
        Raw::new(b"the complete original output".to_vec())
    }

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

    #[tokio::test]
    async fn condense_records_the_slicer_id_and_the_cap() {
        let store = MemoryStore::new();
        let condensate = Fixed::new(json!("small"))
            .condense(&raw(), 100, &store)
            .await
            .unwrap();

        assert_eq!(condensate.slicer, SlicerId::new("fixed", 1));
        assert_eq!(condensate.schema, SchemaId::new("test.fixed.v1", 1));
        assert_eq!(condensate.cap, 100);
    }

    /// The criterion: raw reaches the CAS, so nothing is lost by slicing.
    #[tokio::test]
    async fn the_original_is_preserved_and_addressed_by_the_condensate() {
        let store = MemoryStore::new();
        let raw = raw();
        let condensate = Fixed::new(json!("small"))
            .condense(&raw, 100, &store)
            .await
            .unwrap();

        assert_eq!(condensate.raw, Digest::of(&raw.bytes));
        assert_eq!(store.get(&condensate.raw).await.unwrap(), raw.bytes);
    }

    /// And it gets there *before* slicing, so a slicer that fails still leaves
    /// the original recoverable.
    #[tokio::test]
    async fn the_original_survives_a_slicer_that_fails() {
        #[derive(Debug)]
        struct Fails;

        #[async_trait]
        impl Slicer for Fails {
            fn id(&self) -> SlicerId {
                SlicerId::new("fails", 1)
            }
            async fn slice(&self, _raw: &Raw, _cap: usize) -> Result<Slice, SliceError> {
                Err(SliceError::Unsuitable {
                    slicer: "fails".into(),
                    detail: "not my kind of input".into(),
                })
            }
        }

        let store = MemoryStore::new();
        let raw = raw();
        assert!(Fails.condense(&raw, 100, &store).await.is_err());

        assert_eq!(
            store.get(&Digest::of(&raw.bytes)).await.unwrap(),
            raw.bytes,
            "the original must outlive a failed slice"
        );
    }

    /// The criterion the whole module is built around: over the cap is a typed
    /// error, and it is enforced by the trait rather than by the slicer.
    #[tokio::test]
    async fn a_slicer_that_overruns_its_cap_is_refused_not_truncated() {
        let store = MemoryStore::new();
        let long = json!("x".repeat(4_000));

        let err = Fixed::new(long)
            .condense(&raw(), 50, &store)
            .await
            .unwrap_err();

        let SliceError::OverCap {
            slicer,
            produced,
            cap,
        } = err
        else {
            panic!("expected OverCap, got {err:?}");
        };
        assert_eq!(slicer, "fixed");
        assert_eq!(cap, 50);
        assert!(produced > 50);
        assert!(!err_can_fall_back(produced, cap));
    }

    fn err_can_fall_back(produced: usize, cap: usize) -> bool {
        SliceError::OverCap {
            slicer: "fixed".into(),
            produced,
            cap,
        }
        .can_fall_back()
    }

    #[tokio::test]
    async fn a_cap_too_small_for_any_summary_is_its_own_error() {
        let store = MemoryStore::new();
        let err = Fixed::new(json!("small"))
            .condense(&raw(), 3, &store)
            .await
            .unwrap_err();

        assert!(matches!(err, SliceError::CapTooSmall { cap: 3, .. }));
        assert!(
            !err.can_fall_back(),
            "another slicer has the same window problem"
        );
    }

    #[tokio::test]
    async fn only_an_unsuitable_input_invites_a_fallback() {
        let unsuitable = SliceError::Unsuitable {
            slicer: "ast".into(),
            detail: "does not parse".into(),
        };
        assert!(unsuitable.can_fall_back());
    }

    /// Exactly at the cap is allowed; the check is `>`, not `>=`.
    #[tokio::test]
    async fn a_slice_exactly_at_the_cap_is_accepted() {
        let store = MemoryStore::new();
        let payload = json!("abc");
        let exact = Estimate.count(&serde_json::to_string(&payload).unwrap());

        assert!(
            Fixed::new(payload)
                .condense(&raw(), exact.max(16), &store)
                .await
                .is_ok()
        );
    }

    #[tokio::test]
    async fn lossy_is_carried_through_honestly() {
        let store = MemoryStore::new();

        let clean = Fixed::new(json!("all of it"))
            .condense(&raw(), 100, &store)
            .await
            .unwrap();
        assert!(!clean.lossy);

        let dropped = Fixed {
            payload: json!("some of it"),
            lossy: true,
        }
        .condense(&raw(), 100, &store)
        .await
        .unwrap();
        assert!(dropped.lossy);
        assert!(dropped.needs_raw_for_completeness());
    }

    /// Replay re-slices recorded output and compares digests, so a slicer that
    /// varied between runs would break a replay for no reason.
    #[tokio::test]
    async fn slicing_the_same_input_twice_gives_the_same_condensate() {
        let store = MemoryStore::new();
        let slicer = Fixed::new(json!({ "b": 2, "a": 1 }));

        let first = slicer.condense(&raw(), 100, &store).await.unwrap();
        for _ in 0..8 {
            assert_eq!(slicer.condense(&raw(), 100, &store).await.unwrap(), first);
        }
    }

    // ── counting ────────────────────────────────────────────────────────────

    #[test]
    fn the_default_estimate_is_pessimistic_rather_than_accurate() {
        // Prose really costs about a quarter of its bytes; the estimate says a
        // third plus a line, and being wrong in that direction is the point.
        let prose = "the quick brown fox jumps over the lazy dog";
        assert!(Estimate.count(prose) > prose.len() / 4);
        assert_eq!(Estimate.count(""), 0);
    }

    #[test]
    fn the_estimate_charges_for_lines_because_slicer_output_is_line_dense() {
        let one_line = "aaaaaaaaaaa";
        let three_lines = "aaa\naaa\naaa";
        assert_eq!(
            one_line.len(),
            three_lines.len(),
            "same bytes, different shape"
        );
        assert!(Estimate.count(three_lines) > Estimate.count(one_line));
    }

    /// Byte-level BPE only ever merges, so it cannot emit more tokens than
    /// there are bytes. That makes this the one counter that is a bound rather
    /// than an estimate — and, for the same reason, far too conservative to
    /// use by default.
    #[test]
    fn the_byte_ceiling_is_a_genuine_upper_bound() {
        for text in ["", "a", "hello world", "{\"k\":[1,2,3]}"] {
            assert_eq!(ByteCeiling.count(text), text.len());
            assert!(
                ByteCeiling.count(text) >= Estimate.count(text) || text.len() < 4,
                "the bound should not sit below the estimate for real inputs"
            );
        }
    }

    // ── the store ───────────────────────────────────────────────────────────

    #[tokio::test]
    async fn storing_the_same_bytes_twice_stores_them_once() {
        let store = MemoryStore::new();
        let a = store.put(b"identical").await.unwrap();
        let b = store.put(b"identical").await.unwrap();

        assert_eq!(a, b);
        assert_eq!(store.len(), 1);
    }

    #[tokio::test]
    async fn an_address_nothing_was_stored_at_is_a_typed_miss() {
        let store = MemoryStore::new();
        let err = store.get(&Digest::of(b"never stored")).await.unwrap_err();
        assert!(matches!(err, StoreError::NotFound(_)));
    }

    /// A condensate whose raw points at nothing claims an original that cannot
    /// be produced, which is worse than no condensate.
    #[tokio::test]
    async fn a_store_failure_stops_the_slice() {
        #[derive(Debug)]
        struct Broken;

        #[async_trait]
        impl Store for Broken {
            async fn put(&self, _bytes: &[u8]) -> Result<Digest, StoreError> {
                Err(StoreError::Unavailable("disk full".into()))
            }
            async fn get(&self, digest: &Digest) -> Result<Vec<u8>, StoreError> {
                Err(StoreError::NotFound(*digest))
            }
        }

        let err = Fixed::new(json!("small"))
            .condense(&raw(), 100, &Broken)
            .await
            .unwrap_err();
        assert!(matches!(err, SliceError::Store(_)));
    }

    // ── raw ─────────────────────────────────────────────────────────────────

    #[test]
    fn raw_text_survives_bytes_that_are_not_utf8() {
        let raw = Raw::new(vec![b'o', b'k', 0xff, b'!']);
        assert!(raw.text().contains("ok"));
        assert_eq!(raw.len(), 4);
        assert!(!raw.is_empty());
    }

    #[test]
    fn a_command_outcome_summarises_status_and_timing() {
        let ok = CommandOutcome::new("cargo build", 0, Duration::from_millis(1_200));
        assert!(ok.succeeded());
        assert!(ok.summary().contains("cargo build"));
        assert!(ok.summary().contains("ok"));
        assert!(ok.summary().contains("1200ms"));

        let failed = CommandOutcome::new("cargo test", 101, Duration::from_millis(50));
        assert!(!failed.succeeded());
        assert!(failed.summary().contains("exit 101"));

        let killed = CommandOutcome {
            command: "sleep 100".into(),
            exit: None,
            duration: Duration::from_secs(9),
        };
        assert!(killed.summary().contains("killed"));
    }
}