openlatch-client 0.3.3

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
//! The two L-0 mechanisms that **act** on a live request (Model Boundary
//! **D-28**).
//!
//! Everything else in [`super`] measures a would-have and forwards the original
//! bytes. This module is the one place that builds a different body — and the
//! only lever allowed to, because L-0 is the only one whose failure modes are
//! structural or economic rather than semantic. `history_trim` and `prompt_edit`
//! are still coerced to `observe` at bundle load and never reach here.
//!
//! ## The two mechanisms, and why the action alone cannot name them
//!
//! `params.mechanism` exists because the platform's detector fires on two
//! different causes that need two different interventions:
//!
//! | mechanism | Cause | Intervention |
//! | --------- | ----- | ------------ |
//! | `insert_breakpoints` | nothing is being cached at all | ADD a `cache_control` marker at the stability seam |
//! | `reorder_blocks` | breakpoints exist, but a volatile block sits ahead of them | MOVE that block past the last one |
//!
//! Their net models are different quantities and are derived in the PRD
//! ("`tokens_net` — the derivation" → L-0), implemented in [`super::net`].
//!
//! ## Scope: `system[]`, and nothing else
//!
//! Both mechanisms touch **only the `system[]` array**. That is a decision, not
//! an omission (I-3 open question 5, resolved by D-28 condition d):
//!
//! - **`messages[]` is never reordered.** Role alternation and conversational
//!   order are semantics, not layout, and a `tool_use`/`tool_result` pair is
//!   both ordered and co-located.
//! - **`tools[]` is never reordered.** It renders at position 0, so any change
//!   invalidates tools *and* system *and* messages — strictly more than a
//!   reorder inside it could save — and tool order affects selection.
//! - **Nothing ever moves across a layer.** The three layers are three cache
//!   tiers; a cross-layer move invalidates more than it saves.
//!
//! One consequence is worth stating because it is what makes validation cheap
//! and total: since `messages` is left **byte-identical**, `tool_use` /
//! `tool_result` pairing and role alternation are *proven* rather than
//! re-derived. [`super::validate::reorder_is_structurally_valid`] asserts the
//! equality directly, which is a stronger claim than re-walking the pairs.
//!
//! ## Content preservation is asserted, never assumed
//!
//! A reorder is byte-preserving but **not unconditionally meaning-preserving**:
//! instruction order carries meaning in a prompt, and moving "always answer in
//! English" after "always answer in French" reverses the answer. So a block is
//! moved only when its changing content classifies as **machine data** —
//! `timestamp`, `counter`, `identifier` or `path_list` per [`super::super::churn`].
//! Free prose (`unknown`) is left where the author put it. That is the honest
//! limit of "content-preserving", and it is enforced here rather than described.

use serde_json::{Map, Value};

use super::net::{
    self, insert_break_even_horizon, insert_breakpoints_net_hundredths,
    reorder_blocks_net_hundredths, BreakpointLayer, WriteMultiplier,
};
use super::validate;
use crate::boundary::churn::ChurnClass;
use crate::boundary::prefix_shape::PrefixShape;
use crate::generated::types::ChurnLayer;

/// The two `params.mechanism` values this build implements.
pub const MECHANISM_INSERT_BREAKPOINTS: &str = "insert_breakpoints";
pub const MECHANISM_REORDER_BLOCKS: &str = "reorder_blocks";

/// How many times a `system[]` block must already have churned before a reorder
/// will move it.
///
/// `2` rather than `1` on purpose: one change is a person editing their prompt,
/// two is a pattern. Moving a block on the strength of a single edit would
/// permanently reorder a prompt because someone fixed a typo once.
const MIN_VOLATILE_CHANGES: u32 = 2;

/// Everything the acting engine needs about *this* request beyond its body.
pub struct ActContext<'a> {
    /// `W`, read from the request's own TTL (never assumed).
    pub w: WriteMultiplier,
    /// The wire model string, for the minimum-cacheable-prefix floor.
    pub model: Option<&'a str>,
    /// The measured, cross-request view of this session's prefix.
    pub shape: &'a PrefixShape,
    /// Layers the rule's author declared off-limits (`select.exclude_layers`).
    pub exclude_layers: &'a [ChurnLayer],
}

/// A viable transform: the body it would produce and what that is worth.
///
/// Produced **before** any decision about whether to send it. The caller
/// classifies the outcome (net sign, structural validity, ladder stage) and
/// only then chooses between `rewritten` and the original bytes — so a body is
/// never half-built and never partially adopted.
#[derive(Clone, Debug)]
pub struct Measured {
    /// The complete rewritten body.
    pub rewritten: Value,
    /// L-0's net over the measured horizon, in hundredths (exact `i128`).
    pub net_hundredths: i128,
}

/// Size and build the transform a `prefix_reorder` rule would perform.
///
/// `None` means **the rule does not apply to this request** — the same
/// "non-match produces no decision, not a zero-saving one" contract the removal
/// levers follow. Structural non-applicability lives here rather than in an
/// outcome: an unknown mechanism, a string-valued `system`, an excluded layer,
/// a prefix under the model's cacheable floor, a request already at the
/// four-breakpoint ceiling, or no volatile block to move are all "this rule has
/// nothing to say about this request".
///
/// What *is* returned is then classified by the caller into `applied`,
/// `skipped_net_negative`, `skipped_invalid` or `skipped_stage`. Deterministic
/// and network-free (D-04/D-05).
pub fn measure_prefix_reorder(body: &Value, mechanism: &str, ctx: &ActContext) -> Option<Measured> {
    // `system` is the only layer either mechanism touches, so an author who
    // excluded it has excluded the rule.
    if ctx.exclude_layers.contains(&ChurnLayer::System) {
        return None;
    }
    // A string-valued `system` has no block positions. Coercing it into an
    // array to create one would be a content change in a lever that makes none.
    let system = body.get("system").and_then(Value::as_array)?;
    if system.is_empty() {
        return None;
    }

    match mechanism {
        MECHANISM_INSERT_BREAKPOINTS => insert_breakpoints(body, system, ctx),
        MECHANISM_REORDER_BLOCKS => reorder_blocks(body, system, ctx),
        // An out-of-vocabulary mechanism is skipped, not guessed. `mechanism` is
        // deliberately an open string on the wire so a newer value fails ONE
        // rule instead of the whole bundle.
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// Mechanism A — insert_breakpoints
// ---------------------------------------------------------------------------

/// Add one `cache_control` marker to the last `system[]` block.
///
/// Preconditions, each of which exists because breaking it costs money or lies
/// about a saving:
///
/// - **The request carries no breakpoint at all.** This mechanism is for the
///   "nothing is being cached" cause; a request that already has a checkpoint
///   is the *other* cause and is `reorder_blocks`' job.
/// - **Under Anthropic's four-breakpoint ceiling** ([`net::MAX_BREAKPOINTS`]).
///   Today that is *implied* by the precondition above — a request with zero
///   markers is trivially under a limit of four — so there is no second runtime
///   check to keep in sync with the first. Loosening "no breakpoint at all"
///   into "room for one more" is therefore the edit that must add the explicit
///   ceiling test back. What is never allowed either way is displacing an
///   existing marker to make room: that would be a removal inside a lever whose
///   whole safety argument is that it removes nothing, and it would silently
///   uncache whatever the displaced marker covered (D-19).
/// - **The whole prefix is stable.** `horizon >= break-even` means the
///   `tools`+`system` bytes repeated; there is no point caching a prefix that
///   changes anyway.
/// - **The prefix clears the model's minimum cacheable size.** Below it the
///   marker is silently ignored. Being wrong here is benign — an ignored marker
///   is billed as ordinary input, with no write premium — so the cost of the
///   conservative default is a missed opportunity, never an overspend. Claiming
///   a saving that cannot materialise is the failure this guards.
fn insert_breakpoints(body: &Value, system: &[Value], ctx: &ActContext) -> Option<Measured> {
    if !net::breakpoint_positions(body).is_empty() {
        return None;
    }

    // The marker goes on the last system block: with the whole prefix stable,
    // that is the stability seam, and `tools` renders before `system` so one
    // marker there caches both layers together.
    let seam = system.len() - 1;
    let prefix_tokens = prefix_token_estimate(body);
    if prefix_tokens < min_cacheable_tokens(ctx.model) {
        return None;
    }

    let net_hundredths = insert_breakpoints_net_hundredths(prefix_tokens, ctx.shape.horizon, ctx.w);

    // Build the body unconditionally once we know the shape is viable; the
    // caller decides whether to adopt it. A net-negative measurement still
    // produces a body so the two paths cannot diverge structurally.
    let mut rewritten = body.clone();
    let blocks = rewritten.get_mut("system")?.as_array_mut()?;
    let block = blocks.get_mut(seam)?.as_object_mut()?;
    block.insert("cache_control".to_string(), ephemeral_marker(ctx.w));

    Some(Measured {
        rewritten,
        net_hundredths,
    })
}

/// The horizon at which `insert_breakpoints` becomes worth its write, for `w`.
/// Re-exported so a caller can explain a decline without re-deriving it.
pub fn insert_horizon_floor(w: WriteMultiplier) -> u32 {
    insert_break_even_horizon(w)
}

// ---------------------------------------------------------------------------
// Mechanism B — reorder_blocks
// ---------------------------------------------------------------------------

/// Move one volatile `system[]` block to the end of the array, past the last
/// breakpoint it currently sits in front of.
///
/// Preconditions, each from the derivation rather than from taste:
///
/// - **The move must cross a breakpoint.** Permuting blocks *inside* one cache
///   segment changes which bytes differ, never whether they differ — it saves
///   exactly zero and costs one write. So a breakpoint must exist at an index
///   after the volatile block.
/// - **It must land on a turn the block changed anyway.** Then the region from
///   its position was already going to be re-written and the transition is
///   free; on a quiet turn the move destroys a cache entry that was about to
///   hit, and break-even jumps to `2 + |V|/|S|` volatile turns.
/// - **The block must be genuinely volatile** — at least [`MIN_VOLATILE_CHANGES`]
///   observed changes — and **machine data**, not prose.
/// - **Everything between it and the last breakpoint must be stable**, because
///   that region `|S|` is precisely what moves from the write side to the read
///   side, and unstable content there would be re-written regardless.
fn reorder_blocks(body: &Value, system: &[Value], ctx: &ActContext) -> Option<Measured> {
    // A breakpoint must exist in `system` for a move to cross.
    let last_bp = net::breakpoint_positions(body)
        .into_iter()
        .filter(|p| p.layer == BreakpointLayer::System)
        .map(|p| p.index)
        .next_back()?;

    // The volatile block: changing on this request, with a history of changing,
    // sitting strictly before the last breakpoint, and carrying machine data.
    let victim = (0..last_bp).find(|&i| {
        ctx.shape.is_volatile_now(i, MIN_VOLATILE_CHANGES) && block_is_machine_data(&system[i])
    })?;

    // `|S|` — the stable content between the volatile block and the breakpoint,
    // inclusive. That is the region the move buys back. Unstable content in the
    // span would be re-written anyway and must not be counted as a saving.
    let span = victim + 1..=last_bp;
    if !span.clone().all(|i| ctx.shape.is_stable(i)) {
        return None;
    }
    let stable_tokens: u64 = span.map(|i| super::estimate_tokens(&system[i])).sum();
    if stable_tokens == 0 {
        return None;
    }

    // `H` — volatile turns already behind us. Landed on a churn turn, the
    // transition is free, so this is positive for any H >= 1.
    let horizon = ctx.shape.changes.get(victim).copied().unwrap_or(0);
    let net_hundredths = reorder_blocks_net_hundredths(stable_tokens, horizon, ctx.w);

    // Move the block to the end of `system[]`. Nothing else in the document is
    // touched — not the block's own bytes, not its `cache_control` if it had
    // one, not `tools`, not `messages`.
    let mut rewritten = body.clone();
    let blocks = rewritten.get_mut("system")?.as_array_mut()?;
    let moved = blocks.remove(victim);
    blocks.push(moved);

    Some(Measured {
        rewritten,
        net_hundredths,
    })
}

/// Does this `system[]` block's text look like machine data rather than prose?
///
/// Reuses the churn classifier's vocabulary so "what a prefix finding calls
/// volatile" and "what a reorder is willing to move" cannot drift apart. A
/// block is movable when its text classifies `timestamp`, `counter`,
/// `identifier` or `path_list`; `unknown` — free prose — is not.
///
/// The classifier reads the whole block text, so a long instruction that merely
/// *contains* a date classifies `unknown` and stays put. That asymmetry is
/// deliberate: the cost of leaving a movable block alone is a missed saving; the
/// cost of moving an instruction is a different answer.
fn block_is_machine_data(block: &Value) -> bool {
    let Some(text) = block.get("text").and_then(Value::as_str) else {
        return false;
    };
    !matches!(
        crate::boundary::churn::classify_text(text),
        ChurnClass::Unknown
    )
}

// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------

/// The `cache_control` value to write, matching the request's own TTL.
///
/// A 1-hour request gets a 1-hour marker: writing a 5-minute marker into a
/// request whose other breakpoints are 1-hour would create a checkpoint that
/// expires first and quietly stops being read.
fn ephemeral_marker(w: WriteMultiplier) -> Value {
    let mut m = Map::new();
    m.insert("type".to_string(), Value::String("ephemeral".to_string()));
    if w == WriteMultiplier::OneHour {
        m.insert("ttl".to_string(), Value::String("1h".to_string()));
    }
    Value::Object(m)
}

/// `|P|` — the token estimate for the region a breakpoint at the end of
/// `system` would cover: `tools` + `system`, the two layers that render before
/// `messages`.
///
/// Uses the module's own [`super::estimate_tokens`], which counts **textual
/// payload only** and therefore *under*-counts total tokens (JSON structure is
/// tokenized too). That is the conservative direction for the floor check
/// below: we may decline a prefix that would in fact have cached, and never the
/// reverse.
fn prefix_token_estimate(body: &Value) -> u64 {
    ["tools", "system"]
        .into_iter()
        .filter_map(|k| body.get(k))
        .map(super::estimate_tokens)
        .sum()
}

/// Anthropic's minimum cacheable prefix for `model`, in tokens.
///
/// Below it a `cache_control` marker is **silently ignored** — no error, just
/// `cache_creation_input_tokens: 0`. The floor is **model-dependent and not
/// monotonic across generations**, so it is looked up rather than assumed:
/// Opus 5 halves Opus 4.8's, while Opus 4.6 and Haiku 4.5 are eight times
/// Opus 5's.
///
/// An unrecognised model gets the **most conservative** floor. The cost of that
/// default is a missed opportunity; the cost of the opposite would be claiming a
/// saving that never materialises, which this codebase treats as a reporting
/// defect rather than a rounding error.
fn min_cacheable_tokens(model: Option<&str>) -> u64 {
    const CONSERVATIVE: u64 = 4096;
    let Some(m) = model.map(str::to_ascii_lowercase) else {
        return CONSERVATIVE;
    };
    let has = |needle: &str| m.contains(needle);

    if has("mythos") {
        return if has("preview") { 2048 } else { 512 };
    }
    if has("fable") {
        return 512;
    }
    if has("haiku") {
        // 3.5 is 2048; 4.5 is 4096. Anything else conservative.
        return if has("3-5") || has("3.5") {
            2048
        } else {
            CONSERVATIVE
        };
    }
    if has("opus") {
        return match opus_generation(&m) {
            Some(g) if g >= 500 => 512,    // Opus 5 and later
            Some(480) => 1024,             // Opus 4.8
            Some(470) => 2048,             // Opus 4.7
            Some(460) | Some(450) => 4096, // Opus 4.6 / 4.5
            Some(_) => 1024,               // Opus 4 / 4.1
            None => CONSERVATIVE,
        };
    }
    if has("sonnet") {
        // Sonnet 5, 4.6, 4.5 and 4 all sit at 1024.
        return 1024;
    }
    CONSERVATIVE
}

/// `major*100 + minor*10` for an Opus model string (`opus-4-8` → 480,
/// `opus-5` → 500). `None` when no version is expressible.
fn opus_generation(m: &str) -> Option<u32> {
    let after = m.split("opus").nth(1)?;
    let digits: Vec<u32> = after
        .split(|c: char| !c.is_ascii_digit())
        .filter(|s| !s.is_empty())
        .take(2)
        .filter_map(|s| s.parse::<u32>().ok())
        .collect();
    match digits.as_slice() {
        [major] => Some(major * 100),
        [major, minor] => Some(major * 100 + minor.min(&9) * 10),
        _ => None,
    }
}

/// Re-exported so the decision path can validate what this module built without
/// reaching across modules for it.
pub use validate::reorder_is_structurally_valid;

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

    fn text(t: &str) -> Value {
        json!({ "type": "text", "text": t })
    }

    fn cached(t: &str) -> Value {
        json!({ "type": "text", "text": t, "cache_control": { "type": "ephemeral" } })
    }

    /// A body whose prefix has been observed `turns` times unchanged.
    fn stable_shape(body: &Value, turns: u32) -> PrefixShape {
        let t = PrefixTracker::default();
        let mut shape = PrefixShape::default();
        for _ in 0..turns {
            shape = t.observe("i", "s", body);
        }
        shape
    }

    fn ctx<'a>(shape: &'a PrefixShape, model: &'a str) -> ActContext<'a> {
        ActContext {
            w: WriteMultiplier::FiveMinute,
            model: Some(model),
            shape,
            exclude_layers: &[],
        }
    }

    /// ~2000 estimated tokens of stable prose — comfortably over the 1024 floor
    /// for `claude-opus-4-8`.
    fn big() -> String {
        "x".repeat(8_000)
    }

    // --- insert_breakpoints ----------------------------------------------------

    #[test]
    fn inserts_one_marker_on_the_last_system_block() {
        let body = json!({
            "model": "claude-opus-4-8",
            "system": [ text(&big()), text("tail") ],
            "messages": [ { "role": "user", "content": "hi" } ]
        });
        let shape = stable_shape(&body, 2);
        let m = measure_prefix_reorder(
            &body,
            MECHANISM_INSERT_BREAKPOINTS,
            &ctx(&shape, "claude-opus-4-8"),
        )
        .expect("a viable insert");

        let bps = net::breakpoint_positions(&m.rewritten);
        assert_eq!(bps.len(), 1, "exactly one marker added");
        assert_eq!(bps[0].layer, BreakpointLayer::System);
        assert_eq!(bps[0].index, 1, "on the LAST block — the stability seam");
        assert!(
            m.net_hundredths > 0,
            "two observed turns clears 5m break-even"
        );
    }

    #[test]
    fn insert_is_content_preserving_apart_from_the_marker() {
        let body = json!({
            "model": "claude-opus-4-8",
            "system": [ text(&big()), text("tail") ],
            "messages": [ { "role": "user", "content": "hi" } ]
        });
        let shape = stable_shape(&body, 2);
        let m = measure_prefix_reorder(
            &body,
            MECHANISM_INSERT_BREAKPOINTS,
            &ctx(&shape, "claude-opus-4-8"),
        )
        .unwrap();
        assert!(validate::insert_is_structurally_valid(&body, &m.rewritten));
        assert_eq!(
            body["messages"], m.rewritten["messages"],
            "messages untouched"
        );
        assert_eq!(
            body["system"][0], m.rewritten["system"][0],
            "the non-seam block is byte-identical"
        );
        assert_eq!(
            body["system"][1]["text"], m.rewritten["system"][1]["text"],
            "the seam block's TEXT is byte-identical — only cache_control was added"
        );
    }

    #[test]
    fn insert_declines_when_a_breakpoint_already_exists() {
        // That request is the OTHER cause — reorder's job, not this one's.
        let body = json!({
            "model": "claude-opus-4-8",
            "system": [ text(&big()), cached("tail") ],
            "messages": []
        });
        let shape = stable_shape(&body, 3);
        assert!(measure_prefix_reorder(
            &body,
            MECHANISM_INSERT_BREAKPOINTS,
            &ctx(&shape, "claude-opus-4-8")
        )
        .is_none());
    }

    #[test]
    fn insert_declines_below_the_models_cacheable_floor() {
        let body = json!({
            "model": "claude-opus-4-8",
            "system": [ text("short") ],
            "messages": []
        });
        let shape = stable_shape(&body, 5);
        assert!(
            measure_prefix_reorder(&body, MECHANISM_INSERT_BREAKPOINTS, &ctx(&shape, "claude-opus-4-8")).is_none(),
            "a marker below the floor is silently ignored — claiming a saving for it would be a lie"
        );
    }

    #[test]
    fn insert_declines_for_a_string_valued_system() {
        // Coercing a string into an array to create a block position would be a
        // content change in a lever that makes none.
        let body = json!({ "model": "claude-opus-4-8", "system": big(), "messages": [] });
        let shape = stable_shape(&body, 5);
        assert!(measure_prefix_reorder(
            &body,
            MECHANISM_INSERT_BREAKPOINTS,
            &ctx(&shape, "claude-opus-4-8")
        )
        .is_none());
    }

    #[test]
    fn insert_declines_when_the_author_excluded_the_system_layer() {
        let body = json!({
            "model": "claude-opus-4-8",
            "system": [ text(&big()) ],
            "messages": []
        });
        let shape = stable_shape(&body, 3);
        let c = ActContext {
            exclude_layers: &[ChurnLayer::System],
            ..ctx(&shape, "claude-opus-4-8")
        };
        assert!(measure_prefix_reorder(&body, MECHANISM_INSERT_BREAKPOINTS, &c).is_none());
    }

    #[test]
    fn insert_on_a_first_turn_is_measured_net_negative_not_applied() {
        // The body is viable, so a decision IS produced — but H = 1 never repays
        // a write, and the caller must record that rather than fire.
        let body = json!({
            "model": "claude-opus-4-8",
            "system": [ text(&big()) ],
            "messages": []
        });
        let shape = stable_shape(&body, 1);
        let m = measure_prefix_reorder(
            &body,
            MECHANISM_INSERT_BREAKPOINTS,
            &ctx(&shape, "claude-opus-4-8"),
        )
        .expect("viable shape");
        assert!(m.net_hundredths < 0, "one turn cannot amortise a write");
    }

    #[test]
    fn a_one_hour_request_gets_a_one_hour_marker() {
        // A 5-minute marker inside a 1-hour request expires first and quietly
        // stops being read.
        let body = json!({
            "model": "claude-opus-4-8",
            "system": [ text(&big()) ],
            "messages": []
        });
        let shape = stable_shape(&body, 4);
        let c = ActContext {
            w: WriteMultiplier::OneHour,
            ..ctx(&shape, "claude-opus-4-8")
        };
        let m = measure_prefix_reorder(&body, MECHANISM_INSERT_BREAKPOINTS, &c).unwrap();
        assert_eq!(m.rewritten["system"][0]["cache_control"]["ttl"], "1h");
    }

    // --- reorder_blocks --------------------------------------------------------

    /// A prompt whose block 0 is a churning timestamp sitting in front of a
    /// large stable block that carries the breakpoint.
    fn churning_body(tick: u32) -> Value {
        json!({
            "model": "claude-opus-4-8",
            "system": [
                text(&format!("2026-08-18T10:00:{tick:02}Z")),
                cached(&big())
            ],
            "messages": [ { "role": "user", "content": "hi" } ]
        })
    }

    fn churned_shape(turns: u32) -> (PrefixShape, Value) {
        let t = PrefixTracker::default();
        let mut shape = PrefixShape::default();
        let mut last = Value::Null;
        for i in 0..turns {
            last = churning_body(i);
            shape = t.observe("i", "s", &last);
        }
        (shape, last)
    }

    #[test]
    fn moves_the_volatile_block_past_the_breakpoint() {
        let (shape, body) = churned_shape(4);
        let m = measure_prefix_reorder(
            &body,
            MECHANISM_REORDER_BLOCKS,
            &ctx(&shape, "claude-opus-4-8"),
        )
        .expect("a viable reorder");

        let sys = m.rewritten["system"].as_array().unwrap();
        assert_eq!(sys.len(), 2, "no block gained or lost");
        assert!(
            sys[1]["text"].as_str().unwrap().starts_with("2026-08-18"),
            "the timestamp moved to the end"
        );
        assert!(
            sys[0].get("cache_control").is_some(),
            "the breakpoint rides with its block and is now ahead of the volatile one"
        );
        assert!(m.net_hundredths > 0);
    }

    #[test]
    fn reorder_is_a_permutation_and_leaves_everything_else_identical() {
        let (shape, body) = churned_shape(4);
        let m = measure_prefix_reorder(
            &body,
            MECHANISM_REORDER_BLOCKS,
            &ctx(&shape, "claude-opus-4-8"),
        )
        .unwrap();
        assert!(validate::reorder_is_structurally_valid(&body, &m.rewritten));
        assert_eq!(body["messages"], m.rewritten["messages"]);
        assert_eq!(body["model"], m.rewritten["model"]);
    }

    #[test]
    fn reorder_declines_when_the_move_would_cross_no_breakpoint() {
        // Permuting inside one cache segment changes WHICH bytes differ, never
        // WHETHER they differ: zero saving, one write.
        let t = PrefixTracker::default();
        let mut shape = PrefixShape::default();
        let mut body = Value::Null;
        for i in 0..4 {
            body = json!({
                "model": "claude-opus-4-8",
                "system": [ text(&format!("2026-08-18T10:00:{i:02}Z")), text(&big()) ],
                "messages": []
            });
            shape = t.observe("i", "s", &body);
        }
        assert!(measure_prefix_reorder(
            &body,
            MECHANISM_REORDER_BLOCKS,
            &ctx(&shape, "claude-opus-4-8")
        )
        .is_none());
    }

    #[test]
    fn reorder_declines_on_a_quiet_turn() {
        // The block did not change this request, so the move would destroy a
        // cache entry that was about to hit.
        let t = PrefixTracker::default();
        for i in 0..4 {
            t.observe("i", "s", &churning_body(i));
        }
        let quiet = churning_body(3); // identical to the last observation
        let shape = t.observe("i", "s", &quiet);
        assert!(measure_prefix_reorder(
            &quiet,
            MECHANISM_REORDER_BLOCKS,
            &ctx(&shape, "claude-opus-4-8")
        )
        .is_none());
    }

    #[test]
    fn reorder_never_moves_prose() {
        // A block whose changing content is free prose is an instruction, and
        // instruction order carries meaning. Left where its author put it.
        let t = PrefixTracker::default();
        let mut shape = PrefixShape::default();
        let mut body = Value::Null;
        for i in 0..4 {
            body = json!({
                "model": "claude-opus-4-8",
                "system": [
                    text(&format!("Always answer in the style of variant {i}, at length, with care.")),
                    cached(&big())
                ],
                "messages": []
            });
            shape = t.observe("i", "s", &body);
        }
        assert!(
            measure_prefix_reorder(
                &body,
                MECHANISM_REORDER_BLOCKS,
                &ctx(&shape, "claude-opus-4-8")
            )
            .is_none(),
            "prose is never reordered, however volatile"
        );
    }

    #[test]
    fn reorder_declines_after_a_single_change() {
        let t = PrefixTracker::default();
        t.observe("i", "s", &churning_body(0));
        let shape = t.observe("i", "s", &churning_body(1));
        let body = churning_body(1);
        assert!(
            measure_prefix_reorder(
                &body,
                MECHANISM_REORDER_BLOCKS,
                &ctx(&shape, "claude-opus-4-8")
            )
            .is_none(),
            "one edit is a person fixing a typo, not a per-request timestamp"
        );
    }

    #[test]
    fn reorder_declines_when_the_span_it_would_buy_back_is_itself_unstable() {
        // Unstable content between the volatile block and the breakpoint is
        // re-written regardless, so it is not a saving.
        let t = PrefixTracker::default();
        let mut shape = PrefixShape::default();
        let mut body = Value::Null;
        for i in 0..5 {
            body = json!({
                "model": "claude-opus-4-8",
                "system": [
                    text(&format!("2026-08-18T10:00:{i:02}Z")),
                    text(&format!("counter {i}")),
                    cached(&big())
                ],
                "messages": []
            });
            shape = t.observe("i", "s", &body);
        }
        assert!(measure_prefix_reorder(
            &body,
            MECHANISM_REORDER_BLOCKS,
            &ctx(&shape, "claude-opus-4-8")
        )
        .is_none());
    }

    // --- shared ----------------------------------------------------------------

    #[test]
    fn an_unknown_mechanism_is_skipped_not_guessed() {
        let body = json!({
            "model": "claude-opus-4-8",
            "system": [ text(&big()) ],
            "messages": []
        });
        let shape = stable_shape(&body, 3);
        assert!(measure_prefix_reorder(
            &body,
            "some_future_mechanism",
            &ctx(&shape, "claude-opus-4-8")
        )
        .is_none());
    }

    #[test]
    fn model_floors_follow_the_documented_non_monotonic_table() {
        assert_eq!(min_cacheable_tokens(Some("claude-opus-5")), 512);
        assert_eq!(min_cacheable_tokens(Some("claude-fable-5")), 512);
        assert_eq!(min_cacheable_tokens(Some("claude-mythos-5")), 512);
        assert_eq!(min_cacheable_tokens(Some("claude-mythos-preview")), 2048);
        assert_eq!(min_cacheable_tokens(Some("claude-opus-4-8")), 1024);
        assert_eq!(min_cacheable_tokens(Some("claude-sonnet-5")), 1024);
        assert_eq!(min_cacheable_tokens(Some("claude-sonnet-4-6")), 1024);
        assert_eq!(min_cacheable_tokens(Some("claude-opus-4-7")), 2048);
        // Not monotonic: 4.6 is EIGHT times Opus 5's floor.
        assert_eq!(min_cacheable_tokens(Some("claude-opus-4-6")), 4096);
        assert_eq!(min_cacheable_tokens(Some("claude-haiku-4-5")), 4096);
        // Unknown / absent → the most conservative floor.
        assert_eq!(min_cacheable_tokens(Some("gpt-4o")), 4096);
        assert_eq!(min_cacheable_tokens(None), 4096);
    }

    #[test]
    fn measurement_is_deterministic() {
        let (shape, body) = churned_shape(4);
        let c = ctx(&shape, "claude-opus-4-8");
        let first = measure_prefix_reorder(&body, MECHANISM_REORDER_BLOCKS, &c).unwrap();
        for _ in 0..25 {
            let again = measure_prefix_reorder(&body, MECHANISM_REORDER_BLOCKS, &c).unwrap();
            assert_eq!(again.rewritten, first.rewritten);
            assert_eq!(again.net_hundredths, first.net_hundredths);
        }
    }

    #[test]
    fn measurement_never_mutates_the_input_body() {
        let (shape, body) = churned_shape(4);
        let before = body.clone();
        let _ = measure_prefix_reorder(
            &body,
            MECHANISM_REORDER_BLOCKS,
            &ctx(&shape, "claude-opus-4-8"),
        );
        let _ = measure_prefix_reorder(
            &body,
            MECHANISM_INSERT_BREAKPOINTS,
            &ctx(&shape, "claude-opus-4-8"),
        );
        assert_eq!(body, before);
    }
}