openlatch-client 0.1.18

OpenLatch runtime enforcement node — the capture-and-enforce client for the AI Operations Platform
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
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
//! Would-have transform evaluation (Model Boundary Enforcement Layer, plan I-3-01;
//! owns D-01 rule eval, D-03 L-0 exclusion, one-tuple emit).
//!
//! Inside I-1's boundary listener, evaluate the **removal levers** — L-1
//! (`history_trim`) and L-2 (`prompt_edit`) — on a **clone** of the parsed request
//! body, compute the would-have NET token effect ([`net`]), run would-have
//! structural validation ([`validate`]), and produce **one** [`TransformDecision`]
//! (the highest-net matching rule) per request.
//!
//! > **Prime invariant — observe-only (D-06/D-26).** Nothing here mutates or
//! > re-serialises the request. We never build a trimmed body: we only *measure*
//! > `|T|` (removed) and `|S|` (retained tail) to size the would-have. The forward
//! > path (`proxy.rs`) sends the original `bytes` verbatim, so a matching rule can
//! > never change a forwarded byte. Phase 1 never produces [`Outcome::Applied`] and
//! > never a `ladder_stage` other than `observe`.
//!
//! > **L-0 (`prefix_reorder`) is deliberately absent.** A reorder removes nothing
//! > (`|T| = 0`), so the removal net is always ≤ 0 — applying it here would be a
//! > category error (PRD "`tokens_net` — the derivation"). L-0's Phase-1 value is
//! > prefix-instability *detection* via I-1's churn capture (the `prefix.*`
//! > fields), **not** an `economics_transform_events` row. Because no
//! > `prefix_reorder` rule exists in [`BASELINE_RULES`], an L-0-only request
//! > yields zero transform decisions **by construction**.
//!
//! ## Phase-1 boundary-local baseline (no signed bundle on this stack)
//!
//! The signed policy bundle (D-15) that would carry rules + `W` multipliers does
//! not exist on the I-1 stack. Until it lands (D-26/ABE), the rules ship as a
//! **boundary-local baseline** here: deterministic, network-free, `bundle_revision
//! = 0`. `W` is still read from the **request's own** `cache_control` TTL, never
//! from the (absent) bundle — see [`net::write_multiplier_for`].
//!
//! | id | lever | rule_version | bundle_revision | would-have |
//! | -- | ----- | ------------ | --------------- | ---------- |
//! | `OL-ECO-001` | `history_trim` | 1 | 0 | Trim history messages older than the last [`HISTORY_KEEP_MESSAGES`] turns |
//! | `OL-ECO-002` | `prompt_edit` | 1 | 0 | Strip the first `system` block whose text opens with [`STRIP_MARKER`] |

pub mod net;
pub mod validate;

use serde_json::{json, Value};

use net::WriteMultiplier;

/// L-1 baseline: how many trailing messages the trim would retain. Messages older
/// than the last this-many are the removed region `T`; the retained tail is `S`.
pub const HISTORY_KEEP_MESSAGES: usize = 6;

/// L-2 baseline: the text prefix that marks a `system` block as strippable. A
/// deterministic stand-in for a bundle-authored prompt-edit matcher.
pub const STRIP_MARKER: &str = "[[OL-STRIP]]";

/// ~bytes-per-token for the deterministic, network-free baseline token estimate.
/// The real signed bundle will carry the model's own tokenizer; this is only ever
/// used to *size* a would-have region, never to reconstruct content.
const TOKEN_BYTES: usize = 4;

/// A transform class. Only the two **removal** levers evaluate here; the wire
/// strings are frozen (`lever` enum, PRD "Frozen enums") and must match I-2.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Lever {
    /// L-1 — trim history messages.
    HistoryTrim,
    /// L-2 — edit (strip) a prompt block.
    PromptEdit,
}

impl Lever {
    /// The frozen wire string. **Never** `prefix_reorder` (L-0 is not a removal
    /// lever) or `model_downgrade` (L-3 is out of scope, F-35/B-7).
    pub fn as_str(self) -> &'static str {
        match self {
            Lever::HistoryTrim => "history_trim",
            Lever::PromptEdit => "prompt_edit",
        }
    }
}

/// The outcome of a would-have decision (frozen `transform_outcome` enum).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Outcome {
    /// The transform ran against a live request. **Never produced in Phase 1** —
    /// observe-only (D-26). Present for wire-enum parity with I-2 only.
    Applied,
    /// Valid, but the net token effect is ≤ 0 — trimming would cost more (cache
    /// re-write) than it saves. Recorded, never a saving.
    SkippedNetNegative,
    /// The would-have transform is structurally invalid (would orphan a
    /// `tool_use`/`tool_result`) — it could not have been sent (D-18).
    SkippedInvalid,
    /// Valid and net-positive, but the ladder stage is `observe`, so nothing is
    /// applied (D-26). The Phase-1 outcome for a would-have that *would* fire.
    SkippedStage,
}

impl Outcome {
    /// The frozen wire string.
    pub fn as_str(self) -> &'static str {
        match self {
            Outcome::Applied => "applied",
            Outcome::SkippedNetNegative => "skipped_net_negative",
            Outcome::SkippedInvalid => "skipped_invalid",
            Outcome::SkippedStage => "skipped_stage",
        }
    }
}

/// The promotion-ladder stage a decision was taken at (frozen `ladder_stage`
/// enum). Phase 1 writes **only** `observe` (D-26); `warn`/`act` return with the
/// ladder, so this deliberately has a single variant.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LadderStage {
    /// Evaluate + record the would-have; never modify the live request.
    Observe,
}

impl LadderStage {
    /// The frozen wire string — always `"observe"` in Phase 1.
    pub fn as_str(self) -> &'static str {
        match self {
            LadderStage::Observe => "observe",
        }
    }
}

/// One would-have transform decision — the tuple emitted on the economics event
/// and (platform-side, I-2) inserted into `economics_transform_events`.
#[derive(Clone, Debug, PartialEq)]
pub struct TransformDecision {
    /// The rule that produced this decision (`OL-ECO-001`, …). Half of the replay
    /// tuple with `bundle_revision`.
    pub rule_id: String,
    /// The lever class.
    pub lever: Lever,
    /// What the engine would have done — always a `skipped_*` in Phase 1.
    pub outcome: Outcome,
    /// The rule's own version. Known to the client — it evaluated the rule (B-3).
    pub rule_version: u32,
    /// The bundle the rule came from. `0` = the boundary-local Phase-1 baseline
    /// (no signed bundle on this stack). The other half of the replay tuple.
    pub bundle_revision: u32,
    /// Always [`LadderStage::Observe`] in Phase 1 (D-26).
    pub ladder_stage: LadderStage,
    /// The write multiplier `W` in force, read from the request's TTL (never
    /// assumed) — lets the skip/fire decision replay without re-deriving the TTL.
    pub write_multiplier: WriteMultiplier,
    /// `|T|` — tokens the would-have removes. Recorded regardless of outcome.
    pub tokens_gross: u64,
    /// `tokens_net` scaled to hundredths as an exact `i128` (the fire/skip test is
    /// on the UNROUNDED value — PRD). The wire numeric is
    /// [`net::hundredths_to_numeric`]. Recorded regardless of outcome.
    pub tokens_net_hundredths: i128,
}

/// The `ai.openlatch.transform.*` wire field keys, in the order emit fills them.
/// Used to null the block when no transform ran (the absent-today pattern). Note:
/// `finding_id` is deliberately **not** here — it is not in the contract.
pub const TRANSFORM_WIRE_KEYS: [&str; 9] = [
    "ai.openlatch.transform.rule_id",
    "ai.openlatch.transform.lever",
    "ai.openlatch.transform.outcome",
    "ai.openlatch.transform.rule_version",
    "ai.openlatch.transform.bundle_revision",
    "ai.openlatch.transform.ladder_stage",
    "ai.openlatch.transform.write_multiplier",
    "ai.openlatch.transform.tokens_gross",
    "ai.openlatch.transform.tokens_net",
];

impl TransformDecision {
    /// The nine `ai.openlatch.transform.*` wire fields as a JSON object (all
    /// non-null). Single source of truth for the field names + values — used by
    /// both the emit path (`emit::assemble_data`) and the replay bench. The
    /// contract carries **no** `finding_id`; it is intentionally omitted here.
    pub fn to_wire_object(&self) -> Value {
        json!({
            "ai.openlatch.transform.rule_id": self.rule_id,
            "ai.openlatch.transform.lever": self.lever.as_str(),
            "ai.openlatch.transform.outcome": self.outcome.as_str(),
            "ai.openlatch.transform.rule_version": self.rule_version,
            "ai.openlatch.transform.bundle_revision": self.bundle_revision,
            "ai.openlatch.transform.ladder_stage": self.ladder_stage.as_str(),
            "ai.openlatch.transform.write_multiplier": self.write_multiplier.value(),
            "ai.openlatch.transform.tokens_gross": self.tokens_gross,
            "ai.openlatch.transform.tokens_net": net::hundredths_to_numeric(self.tokens_net_hundredths),
        })
    }
}

/// The concrete would-have logic for a baseline rule.
enum RuleKind {
    /// L-1: retain the last `keep` messages; the older ones are the removed region.
    HistoryTrim { keep: usize },
    /// L-2: strip the first `system` block whose text opens with `marker`.
    PromptEdit { marker: &'static str },
}

/// A baseline rule: the replay-tuple identity plus its matcher/transform logic.
pub struct Rule {
    id: &'static str,
    lever: Lever,
    rule_version: u32,
    bundle_revision: u32,
    kind: RuleKind,
}

impl Rule {
    /// The rule id (`OL-ECO-001`, …).
    pub fn id(&self) -> &'static str {
        self.id
    }

    /// Evaluate this rule against a parsed request body clone. `None` when the rule
    /// does not match (nothing to trim / no marked block) — a non-match produces no
    /// decision, not a zero-saving one. `w` is the request-level write multiplier.
    fn evaluate(&self, body: &Value, w: WriteMultiplier) -> Option<TransformDecision> {
        let (gross, retained_tail, valid) = match &self.kind {
            RuleKind::HistoryTrim { keep } => measure_history_trim(body, *keep)?,
            RuleKind::PromptEdit { marker } => measure_prompt_edit(body, marker)?,
        };
        Some(self.decide(gross, retained_tail, w, valid))
    }

    /// Assemble the decision from the measured region sizes, classifying the
    /// outcome (observe-only: never [`Outcome::Applied`]).
    fn decide(
        &self,
        tokens_gross: u64,
        retained_tail: u64,
        w: WriteMultiplier,
        valid: bool,
    ) -> TransformDecision {
        let (outcome, tokens_net_hundredths) =
            classify_outcome(tokens_gross, retained_tail, w, valid);
        TransformDecision {
            rule_id: self.id.to_string(),
            lever: self.lever,
            outcome,
            rule_version: self.rule_version,
            bundle_revision: self.bundle_revision,
            ladder_stage: LadderStage::Observe,
            write_multiplier: w,
            tokens_gross,
            tokens_net_hundredths,
        }
    }
}

/// Size an L-1 history trim: `(gross T, retained tail S, structurally valid)`.
///
/// `None` when the rule does not match — fewer messages than the tail to keep is
/// a non-match, not a zero-saving decision. Shared by the boundary-local
/// baseline and by bundle-authored rules so the two can never measure the same
/// request differently.
fn measure_history_trim(body: &Value, keep: usize) -> Option<(u64, u64, bool)> {
    let messages = body.get("messages")?.as_array()?;
    if messages.len() <= keep {
        return None; // fewer than a full tail to keep → nothing to trim
    }
    let split = messages.len() - keep;
    let (removed, retained) = messages.split_at(split);
    let gross: u64 = removed.iter().map(estimate_tokens).sum();
    let retained_tail: u64 = retained.iter().map(estimate_tokens).sum();
    // Would trimming the older messages orphan a retained tool_result?
    let valid = validate::history_trim_is_valid(retained);
    Some((gross, retained_tail, valid))
}

/// Size an L-2 prompt edit: `(gross T, retained tail S, structurally valid)`.
///
/// Stripping a `system` block at `idx` removes `T = system[idx]`; the retained
/// tail `S` (which shifts, so it must be re-written) is everything after it —
/// the remaining system blocks plus every message. Messages are untouched, so
/// this can never orphan a tool pair → always structurally valid.
fn measure_prompt_edit(body: &Value, marker: &str) -> Option<(u64, u64, bool)> {
    let system = body.get("system")?.as_array()?;
    let idx = system
        .iter()
        .position(|b| block_text_starts_with(b, marker))?;
    let gross = estimate_tokens(&system[idx]);
    let after_system: u64 = system[idx + 1..].iter().map(estimate_tokens).sum();
    let messages_tokens: u64 = body
        .get("messages")
        .and_then(Value::as_array)
        .map(|m| m.iter().map(estimate_tokens).sum())
        .unwrap_or(0);
    Some((gross, after_system + messages_tokens, true))
}

/// The Phase-1 boundary-local baseline ruleset (D-15 stand-in). One L-1 removal
/// lever and one L-2 removal lever; **no** `prefix_reorder` (L-0) — see the module
/// doc. `bundle_revision = 0` marks these as boundary-local, not bundle-signed.
pub const BASELINE_RULES: &[Rule] = &[
    Rule {
        id: "OL-ECO-001",
        lever: Lever::HistoryTrim,
        rule_version: 1,
        bundle_revision: 0,
        kind: RuleKind::HistoryTrim {
            keep: HISTORY_KEEP_MESSAGES,
        },
    },
    Rule {
        id: "OL-ECO-002",
        lever: Lever::PromptEdit,
        rule_version: 1,
        bundle_revision: 0,
        kind: RuleKind::PromptEdit {
            marker: STRIP_MARKER,
        },
    },
];

/// Evaluate every matching baseline rule against the parsed request body **clone**
/// and return the single highest-net would-have decision (C-17: one row per
/// request). `None` when no rule matches. Synchronous, network-free; the caller
/// runs this inside I-1's `catch_unwind`.
///
/// The body is borrowed immutably and never re-serialised — the observe-only
/// guarantee is structural, not a convention.
pub fn evaluate_would_have(body: &Value) -> Option<TransformDecision> {
    evaluate_would_have_with(body, &[])
}

/// As [`evaluate_would_have`], but evaluating bundle-**authored** request rules
/// when the daemon has a resident bundle.
///
/// Authored rules take precedence over [`BASELINE_RULES`]: the baseline is a
/// D-15 stand-in for "no bundle has arrived yet", so once real rules exist the
/// stand-in must not compete with them for the single decision slot (C-17).
/// An empty slice therefore means "no bundle" and falls back, while a bundle
/// carrying zero request rules correctly yields no decision.
pub fn evaluate_would_have_with(
    body: &Value,
    authored: &[crate::generated::types::PolicyRule],
) -> Option<TransformDecision> {
    // `W` is a request-level property (its `cache_control` TTL), so every rule
    // shares it — read once, never assumed (F-25).
    let w = net::write_multiplier_for(body);

    let decisions: Vec<TransformDecision> = if authored.is_empty() {
        BASELINE_RULES
            .iter()
            .filter_map(|rule| rule.evaluate(body, w))
            .collect()
    } else {
        authored
            .iter()
            .filter_map(|rule| evaluate_authored(rule, body, w))
            .collect()
    };

    decisions
        .into_iter()
        // Highest net wins; a tie breaks to the lexicographically smaller rule_id
        // so selection is fully deterministic (D-05 replay).
        .max_by(|a, b| {
            a.tokens_net_hundredths
                .cmp(&b.tokens_net_hundredths)
                .then_with(|| b.rule_id.cmp(&a.rule_id))
        })
}

/// Evaluate one bundle-authored `kind: request` rule.
///
/// Order matters: `select` narrows **eligibility** and runs first, so a rule the
/// operator scoped away never reaches the sizing logic and produces no decision
/// at all — not a zero-saving one.
///
/// `mode` is not consulted. Every resident request rule has already been coerced
/// to `observe` by `ResidentBundle::from_bundle`, and re-checking here would
/// duplicate a guarantee that is enforced once, at bundle load.
fn evaluate_authored(
    rule: &crate::generated::types::PolicyRule,
    body: &Value,
    w: WriteMultiplier,
) -> Option<TransformDecision> {
    if !select_matches(rule.select.as_ref(), body) {
        return None;
    }

    let params = rule.params.as_ref();
    let (lever, measured) = match rule.action.as_str() {
        "history_trim" => {
            // The gate requires `params.keep_messages` on this action, so a
            // missing value means a rule that should never have activated.
            let keep = usize::try_from(params?.keep_messages?).ok()?;
            (Lever::HistoryTrim, measure_history_trim(body, keep)?)
        }
        "prompt_edit" => {
            // `max_system_tokens` is the other authorable shape for this action;
            // it is a *bounding* edit rather than a marked-span strip and has no
            // sizing logic here yet, so such a rule produces no decision rather
            // than a wrong one.
            let marker = params?.marker.as_deref()?;
            (Lever::PromptEdit, measure_prompt_edit(body, marker)?)
        }
        // `prefix_reorder` (L-0) removes nothing, so the removal net model is a
        // category error for it (C-3) and `Lever` has no variant. Unknown
        // actions cannot reach here — the bundle gate rejects them at load.
        _ => return None,
    };

    let (gross, retained_tail, valid) = measured;
    let (outcome, tokens_net_hundredths) = classify_outcome(gross, retained_tail, w, valid);
    Some(TransformDecision {
        rule_id: rule.rule_id.clone(),
        lever,
        outcome,
        rule_version: u32::try_from(rule.rule_version.unwrap_or(1)).unwrap_or(1),
        bundle_revision: 0,
        ladder_stage: LadderStage::Observe,
        write_multiplier: w,
        tokens_gross: gross,
        tokens_net_hundredths,
    })
}

/// Does this request fall inside the rule's `select` narrowing?
///
/// An absent `select`, or an absent key within it, means "no narrowing on that
/// axis" — never "matches nothing". Every key is ANDed.
///
/// Until this existed, `select` was decorative: the keys were deserialised off
/// the wire and read by nothing, so an operator scoping a rule to one model saw
/// it evaluate against every request.
fn select_matches(
    select: Option<&crate::generated::types::PolicyRuleSelect>,
    body: &Value,
) -> bool {
    let Some(select) = select else {
        return true;
    };

    // `model_in` — matched verbatim against the model string on the wire; no
    // globbing, per the schema's own description.
    if !select.model_in.is_empty() {
        let model = body.get("model").and_then(Value::as_str);
        match model {
            Some(m) if select.model_in.iter().any(|allowed| allowed == m) => {}
            // A request whose model we cannot read cannot be shown to be in the
            // list, so a model-scoped rule does not apply to it.
            _ => return false,
        }
    }

    // `min_messages` — a floor that keeps short sessions untouched.
    if let Some(min) = select.min_messages {
        let len = body
            .get("messages")
            .and_then(Value::as_array)
            .map(|m| m.len())
            .unwrap_or(0);
        if i64::try_from(len).unwrap_or(i64::MAX) < min {
            return false;
        }
    }

    // `exclude_layers` is a `prefix_reorder` safety scope — which layers a
    // reorder may never move. L-0 has no sizing logic here (C-3), so no rule
    // reaching this point can be narrowed by it. Deliberately not treated as a
    // non-match: silently dropping such a rule would be worse than ignoring a
    // key that constrains an unimplemented lever.

    true
}

/// Classify a would-have outcome from its measured region sizes (observe-only).
///
/// Precedence: structural validity first (an invalid transform could not have been
/// sent, so its net is moot), then the sign of `tokens_net` on the **unrounded**
/// value, then — for a valid, net-positive would-have — `skipped_stage`, because
/// `observe` never applies (D-26). **Never** returns [`Outcome::Applied`].
fn classify_outcome(
    tokens_gross: u64,
    retained_tail: u64,
    w: WriteMultiplier,
    structurally_valid: bool,
) -> (Outcome, i128) {
    let net = net::tokens_net_hundredths(tokens_gross, retained_tail, w);
    let outcome = if !structurally_valid {
        Outcome::SkippedInvalid
    } else if net <= 0 {
        Outcome::SkippedNetNegative
    } else {
        Outcome::SkippedStage
    };
    (outcome, net)
}

/// Deterministic, network-free token estimate for a message / system block: its
/// textual byte length over [`TOKEN_BYTES`], rounded up. A Phase-1 baseline — the
/// signed bundle will carry the model's tokenizer. Pure function of the input, so
/// a would-have replays byte-identically (D-05).
fn estimate_tokens(v: &Value) -> u64 {
    text_len(v).div_ceil(TOKEN_BYTES) as u64
}

/// Sum the byte length of the textual payload in a value — string `text`/`content`
/// fields and a serialised `input` (tool-call args). Used only to *size* a
/// would-have region; it never reconstructs or emits content.
fn text_len(v: &Value) -> usize {
    match v {
        Value::String(s) => s.len(),
        Value::Array(a) => a.iter().map(text_len).sum(),
        Value::Object(o) => o
            .iter()
            .map(|(k, val)| match k.as_str() {
                "text" | "content" => text_len(val),
                "input" => val.to_string().len(),
                _ => 0,
            })
            .sum(),
        _ => 0,
    }
}

/// Does a `system` block carry a `text` string that opens with `marker`?
fn block_text_starts_with(block: &Value, marker: &str) -> bool {
    block
        .get("text")
        .and_then(Value::as_str)
        .is_some_and(|t| t.starts_with(marker))
}

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

    // --- outcome classification at the net boundaries (both TTLs) ---------------

    #[test]
    fn classify_5m_boundary_skips_at_and_below_break_even_fires_above() {
        // 5-minute TTL (W = 1.25): break-even is T = 11.5·S. With S = 2, 11.5·S = 23.
        let w = WriteMultiplier::FiveMinute;
        // Just below (T = 22 < 23) and AT (T = 23) → net ≤ 0 → skipped_net_negative.
        assert_eq!(
            classify_outcome(22, 2, w, true).0,
            Outcome::SkippedNetNegative
        );
        assert_eq!(
            classify_outcome(23, 2, w, true).0,
            Outcome::SkippedNetNegative
        );
        // Just above (T = 24 > 23) → net > 0, valid → skipped_stage (never applied).
        assert_eq!(classify_outcome(24, 2, w, true).0, Outcome::SkippedStage);
    }

    #[test]
    fn classify_1h_boundary_skips_at_and_below_break_even_fires_above() {
        // 1-hour TTL (W = 2.0): break-even is T = 19·S. With S = 2, 19·S = 38.
        let w = WriteMultiplier::OneHour;
        assert_eq!(
            classify_outcome(37, 2, w, true).0,
            Outcome::SkippedNetNegative
        );
        assert_eq!(
            classify_outcome(38, 2, w, true).0,
            Outcome::SkippedNetNegative
        );
        assert_eq!(classify_outcome(39, 2, w, true).0, Outcome::SkippedStage);
    }

    #[test]
    fn structural_invalidity_beats_a_positive_net() {
        // A would-have with a huge positive net is STILL skipped_invalid when it
        // would orphan a tool pair — validity is checked before the sign of net.
        let w = WriteMultiplier::FiveMinute;
        let (outcome, net) = classify_outcome(10_000, 1, w, false);
        assert_eq!(outcome, Outcome::SkippedInvalid);
        assert!(net > 0, "net is still recorded regardless of outcome");
    }

    #[test]
    fn phase1_never_applies() {
        // No classification path returns Applied — observe-only (D-26).
        let w = WriteMultiplier::FiveMinute;
        for (g, s, valid) in [
            (0u64, 0u64, true),
            (24, 2, true),
            (22, 2, true),
            (99, 1, false),
        ] {
            assert_ne!(classify_outcome(g, s, w, valid).0, Outcome::Applied);
        }
    }

    // --- rule matching / evaluation ---------------------------------------------

    fn msg(role: &str, content: &str) -> Value {
        json!({ "role": role, "content": content })
    }

    /// A body with `n` messages: the first `n - HISTORY_KEEP_MESSAGES` are large
    /// (the removed region) and the tail is tiny (the retained region).
    fn trimmable_body(large: usize, big_len: usize) -> Value {
        let mut messages = Vec::new();
        for _ in 0..large {
            messages.push(msg("user", &"a".repeat(big_len)));
        }
        for _ in 0..HISTORY_KEEP_MESSAGES {
            messages.push(msg("user", "hi"));
        }
        json!({ "model": "claude-opus-4-8", "messages": messages })
    }

    #[test]
    fn history_trim_matches_and_reports_positive_net_as_skipped_stage() {
        // Two large removed messages (~big) over a tiny 6-message tail → net > 0.
        let body = trimmable_body(2, 400);
        let d = evaluate_would_have(&body).expect("a matching L-1 rule");
        assert_eq!(d.rule_id, "OL-ECO-001");
        assert_eq!(d.lever, Lever::HistoryTrim);
        assert_eq!(d.outcome, Outcome::SkippedStage);
        assert_eq!(d.ladder_stage, LadderStage::Observe);
        assert_eq!(d.write_multiplier, WriteMultiplier::FiveMinute);
        assert!(d.tokens_gross > 0);
        assert!(
            d.tokens_net_hundredths > 0,
            "positive net is recorded, not skipped as negative"
        );
    }

    #[test]
    fn history_trim_with_large_tail_is_net_negative() {
        // One tiny removed message over a large retained tail → net ≤ 0.
        let mut messages = vec![msg("user", "x")]; // removed (tiny)
        for _ in 0..HISTORY_KEEP_MESSAGES {
            messages.push(msg("user", &"b".repeat(400))); // retained (large)
        }
        let body = json!({ "messages": messages });
        let d = evaluate_would_have(&body).expect("a matching L-1 rule");
        assert_eq!(d.outcome, Outcome::SkippedNetNegative);
        assert!(d.tokens_net_hundredths <= 0);
    }

    #[test]
    fn history_trim_does_not_match_a_short_conversation() {
        // Exactly the keep count → nothing older to trim → no decision.
        let mut messages = Vec::new();
        for _ in 0..HISTORY_KEEP_MESSAGES {
            messages.push(msg("user", "hi"));
        }
        let body = json!({ "messages": messages });
        assert!(evaluate_would_have(&body).is_none());
    }

    #[test]
    fn one_hour_ttl_is_read_from_the_request() {
        // A 1h cache_control breakpoint at a legitimate position (a `system` content
        // block) puts the same trim on the W = 2.0 rate. (`cache_control` on the
        // message object itself is not an Anthropic-honored breakpoint and is ignored
        // — see net.rs `w_ignores_ttl_1h_inside_message_text_and_tool_use_input`.)
        let mut messages = vec![
            msg("user", &"a".repeat(400)),
            msg("assistant", &"a".repeat(400)),
        ];
        for _ in 0..HISTORY_KEEP_MESSAGES {
            messages.push(msg("user", "hi"));
        }
        let body = json!({
            "system": [
                { "type": "text", "text": "sys", "cache_control": { "type": "ephemeral", "ttl": "1h" } }
            ],
            "messages": messages
        });
        let d = evaluate_would_have(&body).expect("matching rule");
        assert_eq!(d.write_multiplier, WriteMultiplier::OneHour);
        assert_eq!(
            d.to_wire_object()["ai.openlatch.transform.write_multiplier"],
            2.0
        );
    }

    #[test]
    fn prompt_edit_matches_a_marked_system_block() {
        let body = json!({
            "system": [
                { "type": "text", "text": format!("{STRIP_MARKER} verbose boilerplate {}", "z".repeat(400)) },
                { "type": "text", "text": "keep me" }
            ],
            "messages": [ msg("user", "hi") ]
        });
        let d = evaluate_would_have(&body).expect("a matching L-2 rule");
        assert_eq!(d.rule_id, "OL-ECO-002");
        assert_eq!(d.lever, Lever::PromptEdit);
        assert!(d.tokens_gross > 0);
    }

    // --- L-0 is not here (D-03) --------------------------------------------------

    mod l0_no_event {
        use super::*;

        #[test]
        fn a_reorder_only_request_yields_no_transform_decision() {
            // A well-formed request with a short history and no strip marker matches
            // NO baseline rule. The only conceivable would-have is an L-0 prefix
            // reorder — which is not a removal lever and has no rule here — so the
            // engine emits zero transform decisions (C-3).
            let body = json!({
                "model": "claude-opus-4-8",
                "system": [ { "type": "text", "text": "stable system prompt" } ],
                "messages": [ msg("user", "hello"), msg("assistant", "hi") ]
            });
            assert!(evaluate_would_have(&body).is_none());
        }

        #[test]
        fn no_baseline_rule_is_a_reorder_lever() {
            for rule in BASELINE_RULES {
                assert_ne!(rule.lever.as_str(), "prefix_reorder");
                assert_ne!(rule.lever.as_str(), "model_downgrade");
            }
        }
    }

    // --- observe-only: evaluation never mutates the parsed clone -----------------

    #[test]
    fn evaluate_leaves_the_parsed_body_unchanged() {
        let body = trimmable_body(2, 400);
        let before = body.clone();
        let _ = evaluate_would_have(&body);
        assert_eq!(
            body, before,
            "the parsed clone must be untouched by evaluation"
        );
    }

    // --- wire tuple --------------------------------------------------------------

    #[test]
    fn wire_object_carries_the_frozen_enums_and_no_finding_id() {
        let body = trimmable_body(2, 400);
        let d = evaluate_would_have(&body).unwrap();
        let w = d.to_wire_object();
        assert_eq!(w["ai.openlatch.transform.rule_id"], "OL-ECO-001");
        assert_eq!(w["ai.openlatch.transform.lever"], "history_trim");
        assert_eq!(w["ai.openlatch.transform.outcome"], "skipped_stage");
        assert_eq!(w["ai.openlatch.transform.rule_version"], 1);
        assert_eq!(w["ai.openlatch.transform.bundle_revision"], 0);
        assert_eq!(w["ai.openlatch.transform.ladder_stage"], "observe");
        assert_eq!(w["ai.openlatch.transform.write_multiplier"], 1.25);
        assert!(w["ai.openlatch.transform.tokens_gross"].as_u64().unwrap() > 0);
        assert!(w.get("ai.openlatch.transform.finding_id").is_none());
    }

    #[test]
    fn wire_object_keys_match_the_null_key_list() {
        // Drift guard: `to_wire_object` and `TRANSFORM_WIRE_KEYS` must enumerate
        // the SAME set of `ai.openlatch.transform.*` keys. Emit's None-branch nulls
        // every key in `TRANSFORM_WIRE_KEYS`; if a field is added to one list and
        // not the other, that key would be silently absent-instead-of-null on the
        // no-rule-matched path. This test fails instead of shipping that drift.
        use std::collections::BTreeSet;
        let d = evaluate_would_have(&trimmable_body(2, 400)).expect("a matching rule");
        let wire = d.to_wire_object();
        let object_keys: BTreeSet<&str> = wire
            .as_object()
            .expect("to_wire_object is a JSON object")
            .keys()
            .map(String::as_str)
            .collect();
        let list_keys: BTreeSet<&str> = TRANSFORM_WIRE_KEYS.iter().copied().collect();
        assert_eq!(
            object_keys, list_keys,
            "to_wire_object keys must exactly match TRANSFORM_WIRE_KEYS"
        );
    }

    #[test]
    fn evaluation_is_deterministic() {
        // The same body yields a byte-identical tuple every time (D-05 replay).
        let body = trimmable_body(3, 512);
        let first = evaluate_would_have(&body)
            .unwrap()
            .to_wire_object()
            .to_string();
        for _ in 0..50 {
            assert_eq!(
                evaluate_would_have(&body)
                    .unwrap()
                    .to_wire_object()
                    .to_string(),
                first
            );
        }
    }

    // --- select evaluation (A2/A3) --------------------------------------------
    //
    // Every key here was previously deserialised off the wire and read by
    // NOTHING: a rule scoped to one model evaluated against every request. These
    // tests are the proof that `select` narrows.

    use crate::generated::types::{
        PolicyRule, PolicyRuleMode, PolicyRuleParams, PolicyRuleSelect, PolicyRuleSeverity,
    };

    /// A `history_trim` rule that would match `trimmable_body`, optionally scoped.
    fn authored_trim(select: Option<PolicyRuleSelect>) -> PolicyRule {
        PolicyRule {
            rule_id: "OL-ECO-AUTH".to_string(),
            kind: "request".to_string(),
            action: "history_trim".to_string(),
            conditions: Vec::new(),
            match_pattern: None,
            mode: PolicyRuleMode::Observe,
            severity: PolicyRuleSeverity::Low,
            reason: "authored".to_string(),
            rule_version: Some(4),
            select,
            // `..Default::default()` rather than an exhaustive literal: the
            // params vocabulary grows per action (D-U16), and a fixture that
            // names every field turns each addition into an unrelated
            // compile error here.
            params: Some(PolicyRuleParams {
                keep_messages: Some(2),
                ..Default::default()
            }),
        }
    }

    #[test]
    fn an_authored_rule_is_evaluated_and_carries_its_own_identity() {
        let body = trimmable_body(8, 512);
        let d =
            evaluate_would_have_with(&body, &[authored_trim(None)]).expect("authored rule matches");
        assert_eq!(d.rule_id, "OL-ECO-AUTH");
        assert_eq!(
            d.rule_version, 4,
            "the authored version, not the baseline's"
        );
        assert_eq!(d.lever, Lever::HistoryTrim);
    }

    #[test]
    fn authored_rules_displace_the_baseline() {
        // The baseline is the "no bundle yet" stand-in. Once real rules exist it
        // must not compete for the single decision slot (C-17).
        let body = trimmable_body(8, 512);
        let d = evaluate_would_have_with(&body, &[authored_trim(None)]).unwrap();
        assert_eq!(d.rule_id, "OL-ECO-AUTH");
        assert!(!d.rule_id.starts_with("OL-ECO-00"), "not a baseline rule");
    }

    #[test]
    fn an_empty_authored_set_falls_back_to_the_baseline() {
        let body = trimmable_body(8, 512);
        assert_eq!(
            evaluate_would_have_with(&body, &[]).map(|d| d.rule_id),
            evaluate_would_have(&body).map(|d| d.rule_id),
        );
    }

    #[test]
    fn model_in_narrows_by_model() {
        let mut body = trimmable_body(8, 512);
        body["model"] = json!("claude-opus-5");

        let matching = PolicyRuleSelect {
            model_in: vec!["claude-opus-5".to_string()],
            ..Default::default()
        };
        assert!(evaluate_would_have_with(&body, &[authored_trim(Some(matching))]).is_some());

        let other = PolicyRuleSelect {
            model_in: vec!["claude-haiku-4-5".to_string()],
            ..Default::default()
        };
        assert!(
            evaluate_would_have_with(&body, &[authored_trim(Some(other))]).is_none(),
            "a rule scoped to another model must not evaluate"
        );
    }

    #[test]
    fn a_model_scoped_rule_does_not_apply_to_an_unreadable_model() {
        // No `model` key: the request cannot be shown to be in the list, so the
        // rule does not apply. Failing open here would let a model-scoped rule
        // fire on every malformed body.
        let body = trimmable_body(8, 512); // carries no "model"
        let select = PolicyRuleSelect {
            model_in: vec!["claude-opus-5".to_string()],
            ..Default::default()
        };
        assert!(evaluate_would_have_with(&body, &[authored_trim(Some(select))]).is_none());
    }

    #[test]
    fn min_messages_is_a_floor_that_keeps_short_sessions_untouched() {
        let body = trimmable_body(8, 512);
        let below = PolicyRuleSelect {
            min_messages: Some(40),
            ..Default::default()
        };
        assert!(evaluate_would_have_with(&body, &[authored_trim(Some(below))]).is_none());

        let met = PolicyRuleSelect {
            min_messages: Some(4),
            ..Default::default()
        };
        assert!(evaluate_would_have_with(&body, &[authored_trim(Some(met))]).is_some());
    }

    #[test]
    fn select_keys_are_anded() {
        let mut body = trimmable_body(8, 64);
        body["model"] = json!("claude-opus-5");

        // Both satisfied.
        let both = PolicyRuleSelect {
            model_in: vec!["claude-opus-5".to_string()],
            min_messages: Some(4),
            ..Default::default()
        };
        assert!(evaluate_would_have_with(&body, &[authored_trim(Some(both))]).is_some());

        // History is long enough, model is not in the list → no decision.
        let one = PolicyRuleSelect {
            model_in: vec!["claude-haiku-4-5".to_string()],
            min_messages: Some(4),
            ..Default::default()
        };
        assert!(evaluate_would_have_with(&body, &[authored_trim(Some(one))]).is_none());
    }

    #[test]
    fn a_rule_missing_its_required_params_produces_no_decision() {
        // The gate requires `params.keep_messages` on history_trim, so this
        // shape should never activate — but if it somehow does, it must produce
        // no decision rather than a wrong one.
        let mut rule = authored_trim(None);
        rule.params = None;
        assert!(evaluate_would_have_with(&trimmable_body(8, 512), &[rule]).is_none());
    }

    #[test]
    fn prefix_reorder_produces_no_decision() {
        // L-0 removes nothing, so the removal net model is a category error for
        // it (C-3) and `Lever` has no variant.
        let mut rule = authored_trim(None);
        rule.action = "prefix_reorder".to_string();
        assert!(evaluate_would_have_with(&trimmable_body(8, 512), &[rule]).is_none());
    }

    #[test]
    fn authored_evaluation_is_deterministic() {
        let mut body = trimmable_body(8, 512);
        body["model"] = json!("claude-opus-5");
        let select = PolicyRuleSelect {
            model_in: vec!["claude-opus-5".to_string()],
            ..Default::default()
        };
        let rules = [authored_trim(Some(select))];
        let first = evaluate_would_have_with(&body, &rules)
            .unwrap()
            .to_wire_object()
            .to_string();
        for _ in 0..50 {
            assert_eq!(
                evaluate_would_have_with(&body, &rules)
                    .unwrap()
                    .to_wire_object()
                    .to_string(),
                first
            );
        }
    }

    /// Prompt text must not reach the recorded decision. No `select` key reads
    /// prompt content any more, so this is now a structural property rather than
    /// a matched-needle one — the assertion is kept because the decision is built
    /// from a body that CONTAINS the sentinel, and a future selector that starts
    /// reading content would have to keep it out.
    #[test]
    fn prompt_text_never_appears_in_the_recorded_decision() {
        const SENTINEL: &str = "OPENLATCH-SELECT-SENTINEL-DEADBEEF";
        let mut body = trimmable_body(8, 64);
        body["model"] = json!("claude-opus-5");
        body["system"] = json!([{"type": "text", "text": format!("prefix {SENTINEL} suffix")}]);
        let select = PolicyRuleSelect {
            model_in: vec!["claude-opus-5".to_string()],
            ..Default::default()
        };
        let wire = evaluate_would_have_with(&body, &[authored_trim(Some(select))])
            .expect("the rule matches on the model")
            .to_wire_object()
            .to_string();
        assert!(
            !wire.contains(SENTINEL),
            "prompt text leaked into the transform decision: {wire}"
        );
    }
}