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
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
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
//! 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 — the removal levers never mutate (D-06/D-26).** Nothing
//! > here rewrites the request for L-1 (`history_trim`) or L-2 (`prompt_edit`).
//! > We never build a trimmed body: we only *measure* `|T|` (removed) and `|S|`
//! > (retained tail) to size the would-have. Both are still coerced to `observe`
//! > at bundle load, so a matching L-1/L-2 rule can never change a forwarded
//! > byte, and neither ever produces [`Outcome::Applied`].
//!
//! > **L-0 (`prefix_reorder`) is the one exception, and it is narrow (D-28).**
//! > A reorder removes nothing (`|T| = 0`), so the removal net is always ≤ 0 —
//! > sizing it with that formula would be a category error (PRD
//! > "`tokens_net` — the derivation") and is why `Lever` had no variant for it
//! > until now. It has its own net model over a **measured horizon**
//! > ([`net::insert_breakpoints_net_hundredths`] /
//! > [`net::reorder_blocks_net_hundredths`]) and its own mechanisms
//! > ([`apply`]), and it may rewrite the forwarded request when — and only
//! > when — **all** of the following hold:
//! >
//! > 1. the host has opted in (`[boundary] transforms_act`, ships **off**);
//! > 2. an authored `kind=request` / `action=prefix_reorder` rule is resident
//! >    in `mode: enforce`;
//! > 3. the request's shape makes the transform viable and its net positive;
//! > 4. the rewritten body passes structural validation.
//! >
//! > Miss any one and the original bytes are forwarded. The entry points are
//! > separate rather than parameterised for exactly this reason:
//! > [`evaluate_would_have`] and [`evaluate_would_have_with`] **cannot**
//! > produce a rewritten body — the observe-only guarantee stays structural for
//! > every caller that has not asked to act. Only [`evaluate_acting`] can, and
//! > it is reachable only from the gated seam in `proxy.rs`.
//! >
//! > With the host flag off, an L-0 rule yields **no decision at all**, exactly
//! > as before D-28 — not a `skipped_stage` row. A fleet that has not opted in
//! > sees no change in what it forwards *or* in what it emits.
//!
//! > **No wire key changed.** `prefix_reorder`, `applied` and `act` were all
//! > already members of the frozen `lever` / `transform_outcome` /
//! > `ladder_stage` enums (PRD "Frozen enums") — reserved values this build
//! > could not previously produce. [`TRANSFORM_WIRE_KEYS`] and
//! > [`TransformDecision::to_wire_object`] are untouched.
//!
//! ## 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 apply;
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. 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-0 — inject cache breakpoints, or move a volatile block past one.
    ///
    /// The **only** lever that may act (D-28), and the only one that is not a
    /// removal: its `tokens_gross` is always `0` and its whole magnitude lives
    /// in `tokens_net`.
    PrefixReorder,
    /// L-1 — trim history messages.
    HistoryTrim,
    /// L-2 — edit (strip) a prompt block.
    PromptEdit,
}

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

    /// Is this a **removal** lever — one whose net is the `0.1·T − (W − 0.1)·S`
    /// formula and whose `tokens_gross` means something?
    ///
    /// Exists so a reader (and a reviewer) never has to remember which of the
    /// three the removal derivation applies to. Applying it to
    /// [`Lever::PrefixReorder`] is the C-3 category error.
    pub fn is_removal(self) -> bool {
        matches!(self, Lever::HistoryTrim | Lever::PromptEdit)
    }
}

/// 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 and its bytes were forwarded.
    ///
    /// **Producible only by L-0 (D-28)**, and only with the host flag on, an
    /// authored `enforce` rule, a positive net and a body that passed
    /// structural validation. A removal lever never reaches it — L-1/L-2 are
    /// coerced to `observe` at bundle load, so `Applied` on a `history_trim` or
    /// `prompt_edit` row would be a defect, not a state.
    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 stage does not act — so nothing was
    /// applied. The outcome for a would-have that *would* fire: every L-1/L-2
    /// decision (D-26), and an L-0 decision whose rule is authored `observe`
    /// (D-28).
    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).
///
/// **`warn` is still deliberately absent.** D-28 does not open the ladder — it
/// exempts one lever from the runtime coercion. `warn` needs an in-band channel
/// to tell the developer something was changed, which is a separate piece of
/// design that returns with the ABE D14 binding store alongside `/promote` and
/// `review_token`. A two-variant enum is the honest shape of what this build can
/// produce.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LadderStage {
    /// Evaluate + record the would-have; the live request is untouched.
    Observe,
    /// The transform ran and its bytes were forwarded. L-0 only (D-28).
    Act,
}

impl LadderStage {
    /// The frozen wire string.
    pub fn as_str(self) -> &'static str {
        match self {
            LadderStage::Observe => "observe",
            LadderStage::Act => "act",
        }
    }
}

/// 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 did, or would have done. A `skipped_*` for every
    /// removal-lever decision; possibly [`Outcome::Applied`] for L-0 (D-28).
    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,
    /// [`LadderStage::Act`] exactly when `outcome` is [`Outcome::Applied`];
    /// [`LadderStage::Observe`] otherwise. The two move together by
    /// construction — see [`l0_decision`] — so a row can never claim to have
    /// acted at the observe stage.
    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.
    ///
    /// **Always `0` on an L-0 row**, because a reorder removes nothing. That is
    /// the truthful value and it keeps a consumer that sums gross across levers
    /// correct; an L-0 row's magnitude is entirely in `tokens_net_hundredths`.
    /// A surface reading gross for a `prefix_reorder` row is reading the wrong
    /// column ([`Lever::is_removal`]).
    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.
///
/// **Observe-only by construction.** There is no parameter that could make this
/// act: it hands `None` to the shared core, so the L-0 arm returns before it
/// reaches [`apply`] and no rewritten body exists to return. Every caller that
/// has not explicitly asked to act keeps the pre-D-28 guarantee structurally,
/// not by convention.
pub fn evaluate_would_have_with(
    body: &Value,
    authored: &[crate::generated::types::PolicyRule],
) -> Option<TransformDecision> {
    select_one(evaluate_all(body, authored, None)).map(|e| e.decision)
}

/// One evaluated decision, plus the body to forward when it **acted**.
#[derive(Clone, Debug)]
pub struct Evaluated {
    /// The tuple to record.
    pub decision: TransformDecision,
    /// The rewritten request. `Some` **iff** `decision.outcome` is
    /// [`Outcome::Applied`] — the two are set together in [`l0_decision`], so a
    /// caller cannot forward a rewritten body while recording that nothing
    /// happened, or vice versa.
    pub rewritten: Option<Value>,
}

/// Evaluate authored request rules **with acting enabled** (D-28).
///
/// The only entry point that can produce [`Outcome::Applied`] and a rewritten
/// body. Reachable solely from the gated seam in `proxy.rs`, which calls it only
/// when `[boundary] transforms_act` is on — so "the host did not opt in" is
/// enforced by there being no call, rather than by a flag checked in here.
///
/// `shape` is the measured, cross-request view of this session's prefix
/// ([`crate::boundary::prefix_shape`]); it supplies the horizon `H` that L-0's
/// net model needs and the per-block stability a reorder needs.
///
/// `enforcing` is the bundle's `enforcement_enabled` kill switch. `false` means
/// every rule shadows whatever its authored mode says — the same semantics the
/// command plane applies — so an organization that has pulled it gets decisions
/// recorded and nothing rewritten. Synchronous and network-free, like everything
/// else in this module.
pub fn evaluate_acting(
    body: &Value,
    authored: &[crate::generated::types::PolicyRule],
    shape: &crate::boundary::prefix_shape::PrefixShape,
    enforcing: bool,
) -> Option<Evaluated> {
    select_one(evaluate_all(body, authored, Some((shape, enforcing))))
}

/// Evaluate every matching rule. `acting` present ⇒ the L-0 arm is live.
fn evaluate_all(
    body: &Value,
    authored: &[crate::generated::types::PolicyRule],
    acting: Option<(&crate::boundary::prefix_shape::PrefixShape, bool)>,
) -> Vec<Evaluated> {
    // `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);

    if authored.is_empty() {
        // The baseline stand-in carries no `prefix_reorder` rule, so nothing
        // here can act whatever `acting` is.
        return BASELINE_RULES
            .iter()
            .filter_map(|rule| rule.evaluate(body, w))
            .map(|decision| Evaluated {
                decision,
                rewritten: None,
            })
            .collect();
    }
    authored
        .iter()
        .filter_map(|rule| evaluate_authored(rule, body, w, acting))
        .collect()
}

/// Pick the single decision to record (C-17: one row per request).
///
/// **An `Applied` decision always outranks a skipped one, whatever the nets
/// say.** A skipped L-1 would-have can legitimately measure a larger net than an
/// applied L-0 transform — they are different quantities over different horizons
/// — but recording the would-have while forwarding the rewritten body would
/// report something that did not happen and omit something that did. What
/// actually happened wins; only among equals does net decide.
///
/// Within a rank: highest net wins, and a tie breaks to the lexicographically
/// smaller `rule_id`, so selection is fully deterministic (D-05 replay).
fn select_one(candidates: Vec<Evaluated>) -> Option<Evaluated> {
    candidates.into_iter().max_by(|a, b| {
        let applied = |e: &Evaluated| u8::from(e.decision.outcome == Outcome::Applied);
        applied(a)
            .cmp(&applied(b))
            .then_with(|| {
                a.decision
                    .tokens_net_hundredths
                    .cmp(&b.decision.tokens_net_hundredths)
            })
            .then_with(|| b.decision.rule_id.cmp(&a.decision.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 consulted **only on the L-0 arm**, and only because L-0 is the one
/// lever the client can act on (D-28). For `history_trim` and `prompt_edit` it
/// is still irrelevant: `ResidentBundle::from_bundle` rewrites an authored
/// `enforce` to `observe` for those actions, so re-checking here would duplicate
/// a guarantee enforced once, at bundle load.
///
/// `acting` is `Some` only on the acting path. When it is `None` the L-0 arm
/// returns `None` — an L-0 rule then produces no decision at all, byte-for-byte
/// the pre-D-28 behaviour.
fn evaluate_authored(
    rule: &crate::generated::types::PolicyRule,
    body: &Value,
    w: WriteMultiplier,
    acting: Option<(&crate::boundary::prefix_shape::PrefixShape, bool)>,
) -> Option<Evaluated> {
    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)?)
        }
        // L-0 (D-28) — the one arm that can rewrite the request. It does not
        // share the removal path below at all: `measured` there is
        // `(|T|, |S|, valid)` sized by the removal formula, which is a category
        // error for a lever that removes nothing (C-3). L-0 returns early with
        // its own model, its own validation and its own outcome mapping.
        "prefix_reorder" => {
            // No acting context ⇒ the host did not opt in ⇒ no decision,
            // exactly as before D-28. Not a `skipped_stage` row: a fleet that
            // has not turned this on sees no change in what it emits either.
            let (shape, enforcing) = acting?;
            // The gate requires `params.mechanism` on this action. Absent means
            // the rule names no intervention, and a client that cannot infer
            // one skips it rather than guessing which of the two was meant.
            let mechanism = params?.mechanism.as_deref()?;
            let exclude_layers = rule
                .select
                .as_ref()
                .map(|s| s.exclude_layers.as_slice())
                .unwrap_or(&[]);
            let ctx = apply::ActContext {
                w,
                model: body.get("model").and_then(Value::as_str),
                shape,
                exclude_layers,
            };
            let measured = apply::measure_prefix_reorder(body, mechanism, &ctx)?;
            return Some(l0_decision(rule, mechanism, measured, body, w, enforcing));
        }
        // Unknown actions cannot reach here — the bundle gate rejects them at
        // load — so this is the forward-compatibility floor, not a live branch.
        _ => return None,
    };

    let (gross, retained_tail, valid) = measured;
    let (outcome, tokens_net_hundredths) = classify_outcome(gross, retained_tail, w, valid);
    Some(Evaluated {
        decision: 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,
        },
        rewritten: None,
    })
}

/// Turn a viable L-0 measurement into the decision to record, and — only if it
/// truly acts — the body to forward.
///
/// Precedence mirrors [`classify_outcome`] so the two levers' rows read the same
/// way, but each rung is L-0's own:
///
/// 1. **Structurally invalid → `skipped_invalid`.** Checked first: a body that
///    could not have been sent has no meaningful net. This is the D-18 gate, and
///    for L-0 it is load-bearing rather than defensive — a would-have that fails
///    validation is a row in a report, a *transform* that fails it is a 400 the
///    agent sees. The comparison is against the original document, so it proves
///    content preservation rather than re-deriving structural rules.
/// 2. **Net ≤ 0 → `skipped_net_negative`**, on the **unrounded** value.
/// 3. **Rule not authored `enforce`, or the org kill switch is off →
///    `skipped_stage`.** Either the operator wrote a rule to watch rather than
///    to act, or `enforcement_enabled = false` has put the whole organization
///    into shadow. Both are recorded and neither rewrites anything.
/// 4. Otherwise **`applied`**, at [`LadderStage::Act`], with the rewritten body.
///
/// `tokens_gross` is `0` at every rung — a reorder removes nothing.
fn l0_decision(
    rule: &crate::generated::types::PolicyRule,
    mechanism: &str,
    measured: apply::Measured,
    original: &Value,
    w: WriteMultiplier,
    enforcing: bool,
) -> Evaluated {
    use crate::generated::types::PolicyRuleMode;

    let structurally_valid = match mechanism {
        apply::MECHANISM_INSERT_BREAKPOINTS => {
            validate::insert_is_structurally_valid(original, &measured.rewritten)
        }
        apply::MECHANISM_REORDER_BLOCKS => {
            validate::reorder_is_structurally_valid(original, &measured.rewritten)
        }
        // A mechanism with no validator cannot be proven safe, so it is not
        // sent. `measure_prefix_reorder` already refuses to build one; this is
        // the second half of the same fail-closed posture.
        _ => false,
    };

    let outcome = if !structurally_valid {
        Outcome::SkippedInvalid
    } else if measured.net_hundredths <= 0 {
        Outcome::SkippedNetNegative
    } else if !enforcing || rule.mode != PolicyRuleMode::Enforce {
        Outcome::SkippedStage
    } else {
        Outcome::Applied
    };
    let applied = outcome == Outcome::Applied;

    Evaluated {
        decision: TransformDecision {
            rule_id: rule.rule_id.clone(),
            lever: Lever::PrefixReorder,
            outcome,
            rule_version: u32::try_from(rule.rule_version.unwrap_or(1)).unwrap_or(1),
            bundle_revision: 0,
            ladder_stage: if applied {
                LadderStage::Act
            } else {
                LadderStage::Observe
            },
            write_multiplier: w,
            // A reorder removes nothing. Always zero, at every rung.
            tokens_gross: 0,
            tokens_net_hundredths: measured.net_hundredths,
        },
        rewritten: applied.then_some(measured.rewritten),
    }
}

/// 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 deliberately NOT evaluated here. It is a
    // `prefix_reorder` safety scope — which layers a reorder may never move —
    // so it narrows *what a transform may touch*, not *which requests a rule
    // applies to*. Every other key in this function answers the second
    // question; this one answers the first, and it is read where that question
    // is asked: `apply::measure_prefix_reorder`, which declines outright when
    // the author excluded the only layer either mechanism touches.
    //
    // Treating it as a non-match here would be wrong in both directions: it
    // would drop a rule that excludes a layer this request does not even have,
    // and it would put the safety check somewhere the code doing the moving
    // never has to consult. (Before D-28 the comment here said L-0 had no
    // sizing logic, so no rule could be narrowed by it. That is no longer true,
    // which is why the key now has a reader.)

    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(),
            provenance: None,
            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}"
        );
    }
}