leviath-core 0.6.2

Core types and traits for Leviath: context regions, memory layouts, blueprints, and lifecycle policies
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
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
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
//! Context window layouts and memory maps.
//!
//! A layout defines the complete memory structure for an agent's context window,
//! including all regions, their sizes, and eviction priorities. This is analogous
//! to a hardware memory map that defines where different types of data live and
//! how they're managed.

use crate::error::ValidationError;
use crate::region::{RegionKind, RegionSchema};
use serde::{Deserialize, Serialize};

/// The region a stage's `system_prompt` is written into, when a blueprint
/// declares one by this name.
///
/// Stage instructions are pinned context - that is why they read as
/// instruction rather than history - and a region of their own is what lets
/// the stage ledger bill the prompt's tokens under a name that says what they
/// are, sizes them, and places them in the cached prefix on purpose rather
/// than wherever the first pinned region happens to sit.
///
/// Declaring a region by this name gives the prompt a handle:
///
/// ```toml
/// [context.regions]
/// stage_instructions = { kind = "pinned", budget = "3%" }
/// ```
///
/// A blueprint that declares nothing by this name still gets one: the runtime
/// adds it at spawn, sized to the widest stage prompt the blueprint carries.
pub const STAGE_INSTRUCTIONS_REGION: &str = "stage_instructions";

/// How a region's token ceiling is expressed before it is resolved against a
/// concrete model context window.
///
/// Blueprint authors think in **proportions** (`budget = "35%"`) so their intent
/// stays correct regardless of the model's context size, while power users can
/// still pin an exact count. The percentage denominator - the model's context
/// window - is not known at parse time, so the spec is stored unresolved here and
/// turned into a concrete token count at window-build time (see
/// [`BudgetSpec::resolve`] and [`ContextLayout::resolved`]).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BudgetSpec {
    /// A fixed token ceiling, independent of the model. Resolving is a no-op.
    Absolute(usize),

    /// A ceiling expressed as a fraction of the model's context window, with
    /// optional absolute guard-rails. `percent` is a fraction (`0.35` for
    /// `"35%"`). `max` caps the resolved value (so e.g. 2% of a 1M window can't
    /// balloon a task region to 20K tokens); `min` floors it (so a small-context
    /// model doesn't starve the region below a usable size).
    Percent {
        /// Fraction of the model context window (0.35 == "35%").
        percent: f64,
        /// Absolute floor for the resolved value, if any.
        min: Option<usize>,
        /// Absolute cap for the resolved value, if any.
        max: Option<usize>,
    },
}

impl Default for BudgetSpec {
    /// Only a serde-deserialize fallback for older persisted blueprints; live
    /// code always sets the budget explicitly via [`RegionDefinition::new`].
    fn default() -> Self {
        BudgetSpec::Absolute(0)
    }
}

impl BudgetSpec {
    /// Parse a percentage string like `"35%"` into its fraction (`0.35`).
    ///
    /// Surrounding whitespace is trimmed and decimals are allowed (`"0.6%"`).
    /// Rejects a missing `%`, a non-numeric value, and anything outside the
    /// `(0, 100]` range - a single region can't sensibly claim ≤0% or more than
    /// the whole window (region budgets may *sum* past 100%, but each is a
    /// fraction of one window). Returns the human-readable reason on failure so
    /// the caller can surface it at load time.
    pub fn parse_budget(s: &str) -> std::result::Result<f64, String> {
        let trimmed = s.trim();
        let Some(num) = trimmed.strip_suffix('%') else {
            return Err(format!("budget '{s}' must end with '%' (e.g. \"35%\")"));
        };
        let value: f64 = num
            .trim()
            .parse()
            .map_err(|_| format!("budget '{s}' is not a valid number"))?;
        if !(value > 0.0 && value <= 100.0) {
            return Err(format!(
                "budget '{s}' must be greater than 0% and at most 100%"
            ));
        }
        Ok(value / 100.0)
    }

    /// Resolve this spec to a concrete token count against a model context
    /// `window`.
    ///
    /// [`Absolute`](BudgetSpec::Absolute) ignores the window (idempotent - a
    /// fully-absolute layout resolves to itself). [`Percent`](BudgetSpec::Percent)
    /// rounds `window * percent`, then applies the `max` cap, then the `min`
    /// floor. The floor is applied **last** so that when `min > max` the floor
    /// wins: a region starved below a usable size is worse than one slightly over
    /// its cap.
    pub fn resolve(&self, window: usize) -> usize {
        match self {
            BudgetSpec::Absolute(n) => *n,
            BudgetSpec::Percent { percent, min, max } => {
                let mut v = (window as f64 * percent).round() as usize;
                if let Some(max) = max {
                    v = v.min(*max);
                }
                if let Some(min) = min {
                    v = v.max(*min);
                }
                v
            }
        }
    }

    /// Whether this is a percentage budget (needs a model window to resolve).
    pub fn is_percent(&self) -> bool {
        matches!(self, BudgetSpec::Percent { .. })
    }
}

/// A ContextLayout defines the complete memory map for an agent.
///
/// Like SNES VRAM layout - every region has a defined purpose, size, and policy.
/// The layout specifies:
/// - Which regions exist and their configurations
/// - Total token budget across all regions
/// - Eviction order when space is needed
///
/// Layouts are typically defined in an agent's blueprint and remain constant
/// throughout the agent's lifecycle, though the content within regions changes.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContextLayout {
    /// All regions in this layout
    pub regions: Vec<RegionDefinition>,

    /// Total token budget across all regions
    pub total_budget_tokens: usize,

    /// Region names in eviction priority order (first = evicted first)
    ///
    /// When the context window fills up, regions are processed in this order:
    /// 1. Temporary regions: evict oldest entries
    /// 2. Compacting regions: trigger summarization
    /// 3. SlidingWindow regions: reduce window size
    /// 4. Pinned regions: NEVER touched (if these fill up, it's a config error)
    pub eviction_order: Vec<String>,
}

impl ContextLayout {
    /// Create a new layout with the specified configuration.
    pub fn new(regions: Vec<RegionDefinition>, total_budget_tokens: usize) -> Self {
        Self {
            regions,
            total_budget_tokens,
            eviction_order: Vec::new(),
        }
    }

    /// Set the eviction order for this layout.
    pub fn with_eviction_order(mut self, order: Vec<String>) -> Self {
        self.eviction_order = order;
        self
    }

    /// Validate that the layout is well-formed.
    ///
    /// Checks:
    /// - Sum of max_tokens doesn't exceed total_budget_tokens
    /// - All region names in eviction_order exist
    /// - No duplicate region names
    pub fn validate(&self) -> std::result::Result<(), ValidationError> {
        // Check for duplicate region names
        let mut names = std::collections::HashSet::new();
        for region in &self.regions {
            if !names.insert(region.name.as_str()) {
                return Err(ValidationError::Region {
                    region: region.name.clone(),
                    message: "duplicate region name".to_string(),
                });
            }
        }

        // Check that eviction_order regions exist
        for name in &self.eviction_order {
            if !names.contains(name.as_str()) {
                return Err(ValidationError::Layout(format!(
                    "eviction order references unknown region: {}",
                    name
                )));
            }
        }

        // Reject a Custom region whose script path is empty - it could never
        // resolve to a file, and the runtime would silently fall back to
        // Temporary-style rendering on every inference.
        for region in &self.regions {
            if let RegionKind::Custom { script, .. } = &region.kind
                && script.trim().is_empty()
            {
                return Err(ValidationError::Region {
                    region: region.name.clone(),
                    message: "custom region requires a non-empty script path".to_string(),
                });
            }
        }

        // Warn if sum of max tokens exceeds budget (not necessarily an error,
        // since not all regions will be full simultaneously)
        // Warn if no SlidingWindow region exists - agents should have a
        // conversation region for typed message entries, but some agents
        // (e.g., deep-researcher) use other region kinds exclusively. A Custom
        // region counts: its script can render typed entries as messages.
        let has_message_region = self.regions.iter().any(|r| {
            matches!(
                r.kind,
                RegionKind::SlidingWindow { .. } | RegionKind::Custom { .. }
            )
        });
        if !has_message_region {
            tracing::warn!(
                "Layout has no SlidingWindow (or custom scripted) region - typed \
                 conversation entries require one"
            );
        }

        // The token-sum warning and the fixed-working-budget hard error below
        // operate on concrete `max_tokens` values. When percentage budgets are
        // present those values are provisional placeholders until the layout is
        // resolved against a model window, so the checks are meaningless here -
        // skip them and rely on the post-resolution `validate()` call at spawn.
        if self.has_percent_budgets() {
            return Ok(());
        }

        let total_max = self
            .regions
            .iter()
            .fold(0usize, |acc, r| acc.saturating_add(r.max_tokens));
        if total_max > self.total_budget_tokens {
            tracing::warn!(
                "Sum of region max tokens ({}) exceeds total budget ({})",
                total_max,
                self.total_budget_tokens
            );
        }

        // Ensure the fixed, non-evictable regions leave working room, judged
        // against the whole budget.
        self.validate_working_room(self.total_budget_tokens)
    }

    /// Fail when the fixed (non-evictable) regions would leave less than
    /// `MIN_WORKING_TOKENS` of `window` for the evictable ones.
    ///
    /// Split out from [`validate`](Self::validate) so a caller can judge each
    /// stage against that stage's own context window over just the regions it
    /// can see, rather than one window for the whole layout: a region budgeted
    /// against a wide-window stage must not be counted against a narrow-window
    /// stage that never sees it. Pinned / HashMap / CompactHistory / persistent
    /// custom regions persist for the whole run and consume budget; if they
    /// leave too little, the evictable regions operate "blind", so fail loudly
    /// at load instead of degrading silently at runtime. The floor is only
    /// enforced on realistically-sized windows (`BUDGET_CHECK_MIN_TOTAL`); a toy
    /// fixture's tiny window is left alone.
    pub fn validate_working_room(&self, window: usize) -> std::result::Result<(), ValidationError> {
        let fixed_tokens: usize = self
            .regions
            .iter()
            .filter(|r| {
                matches!(
                    r.kind,
                    RegionKind::Pinned
                        | RegionKind::HashMap { .. }
                        | RegionKind::CompactHistory { .. }
                        | RegionKind::Custom {
                            persistent: true,
                            ..
                        }
                )
            })
            .fold(0usize, |acc, r| acc.saturating_add(r.max_tokens));
        let working_tokens = window.saturating_sub(fixed_tokens);
        if window >= Self::BUDGET_CHECK_MIN_TOTAL && working_tokens < Self::MIN_WORKING_TOKENS {
            return Err(ValidationError::Layout(format!(
                "context layout leaves only {working_tokens} working tokens after fixed \
                 regions (pinned/hashmap/compact_history/persistent custom) consume \
                 {fixed_tokens} of the {window} \
                 window; at least {} are needed for the agent to operate. Reduce the \
                 fixed regions' max_tokens or increase the window.",
                Self::MIN_WORKING_TOKENS
            )));
        }
        Ok(())
    }

    /// Minimum token budget that must remain for evictable/working regions
    /// (conversation, tool results, scratch) after the fixed regions are full,
    /// so the agent has room to hold recent context and generate. Below this a
    /// run would operate with almost no working space.
    const MIN_WORKING_TOKENS: usize = 8000;

    /// The working-budget floor is only enforced when the layout's total budget
    /// is at least this large - i.e. it's a realistically-sized agent, not a
    /// toy/illustrative layout where an absolute floor wouldn't make sense.
    const BUDGET_CHECK_MIN_TOTAL: usize = 20_000;

    /// Get a region definition by name.
    pub fn get_region(&self, name: &str) -> Option<&RegionDefinition> {
        self.regions.iter().find(|r| r.name == name)
    }

    /// Whether any region uses a percentage budget (and therefore needs a model
    /// context window to resolve to concrete token counts).
    pub fn has_percent_budgets(&self) -> bool {
        self.regions.iter().any(|r| r.budget.is_percent())
    }

    /// Resolve every region's percentage budget against a concrete model context
    /// `window`, returning a fully-absolute layout.
    ///
    /// Each region's `max_tokens` becomes `budget.resolve(window)`, and each
    /// [`RegionKind::Compacting`] region's `threshold_tokens` is recomputed from
    /// its [`compact_at`](RegionDefinition::compact_at) fraction (via the private
    /// `resolve_compacting_threshold` helper). `eviction_order` is preserved. The
    /// total budget becomes the model `window` when any percentage budget is
    /// present (percentage ceilings are relative to the whole window and may sum
    /// past 100%); a pure-absolute layout keeps its summed total unchanged.
    ///
    /// Resolving an already-absolute layout is a no-op, so this is safe to call
    /// unconditionally at window-build time.
    pub fn resolved(&self, window: usize) -> ContextLayout {
        let regions = self
            .regions
            .iter()
            .map(|r| {
                let max_tokens = r.budget.resolve(window);
                let kind = match &r.kind {
                    RegionKind::Compacting { threshold_tokens } => RegionKind::Compacting {
                        threshold_tokens: Self::resolve_compacting_threshold(
                            r.compact_at,
                            *threshold_tokens,
                            max_tokens,
                        ),
                    },
                    other => other.clone(),
                };
                // Emit a fully-absolute region: the percentage has been baked
                // into `max_tokens` and the compaction threshold into `kind`, so
                // the resolved layout carries no `Percent` budgets. This makes
                // `has_percent_budgets()` false on the result, so a post-resolution
                // `validate()` runs the real token/working-budget checks.
                RegionDefinition {
                    kind,
                    max_tokens,
                    budget: BudgetSpec::Absolute(max_tokens),
                    compact_at: None,
                    ..r.clone()
                }
            })
            .collect();

        let total_budget_tokens = if self.has_percent_budgets() {
            window
        } else {
            self.total_budget_tokens
        };

        ContextLayout {
            regions,
            total_budget_tokens,
            eviction_order: self.eviction_order.clone(),
        }
    }

    /// Like [`resolved`](Self::resolved), but each region's percentage budget
    /// is sized against a window chosen per region rather than one window for
    /// the whole layout.
    ///
    /// `window_for(region_name)` gives the window a region is budgeted against:
    /// the caller passes the smallest context window among the stages that can
    /// actually see that region, so a region used only in wide-window stages
    /// keeps a wide budget even when a narrow-window stage exists that never
    /// sees it. The layout's `total_budget_tokens` becomes the largest of those
    /// per-region windows; the authoritative fit check is per stage, done by the
    /// caller against each stage's own window over the regions it sees.
    ///
    /// An absolute layout has nothing to resolve, so this is a no-op for it, the
    /// same as [`resolved`](Self::resolved).
    pub fn resolved_per_region(&self, window_for: &dyn Fn(&str) -> usize) -> ContextLayout {
        let regions: Vec<RegionDefinition> = self
            .regions
            .iter()
            .map(|r| {
                let window = window_for(&r.name);
                let max_tokens = r.budget.resolve(window);
                let kind = match &r.kind {
                    RegionKind::Compacting { threshold_tokens } => RegionKind::Compacting {
                        threshold_tokens: Self::resolve_compacting_threshold(
                            r.compact_at,
                            *threshold_tokens,
                            max_tokens,
                        ),
                    },
                    other => other.clone(),
                };
                RegionDefinition {
                    kind,
                    max_tokens,
                    budget: BudgetSpec::Absolute(max_tokens),
                    compact_at: None,
                    ..r.clone()
                }
            })
            .collect();

        let total_budget_tokens = if self.has_percent_budgets() {
            self.regions
                .iter()
                .map(|r| window_for(&r.name))
                .max()
                .unwrap_or(self.total_budget_tokens)
        } else {
            self.total_budget_tokens
        };

        ContextLayout {
            regions,
            total_budget_tokens,
            eviction_order: self.eviction_order.clone(),
        }
    }

    /// A copy holding only the regions (and eviction-order entries) whose name
    /// satisfies `keep`.
    ///
    /// The runtime carries some always-visible regions (conversation, tool
    /// results) that no layout declares, so a stage's visible-region set may
    /// name regions absent here; those are simply not present in the result.
    /// Used to judge a stage's working room over exactly the regions it can see,
    /// rather than every region the layout declares.
    pub fn retaining<F: Fn(&str) -> bool>(&self, keep: F) -> ContextLayout {
        ContextLayout {
            regions: self
                .regions
                .iter()
                .filter(|r| keep(&r.name))
                .cloned()
                .collect(),
            total_budget_tokens: self.total_budget_tokens,
            eviction_order: self
                .eviction_order
                .iter()
                .filter(|n| keep(n))
                .cloned()
                .collect(),
        }
    }

    /// Compute a Compacting region's concrete compaction threshold from its
    /// `compact_at` fraction, the absolute `threshold_tokens` guard carried on
    /// the kind, and the region's resolved budget.
    ///
    /// - `compact_at = Some(f)` with an explicit `threshold_tokens` cap (any
    ///   value below the [`usize::MAX`] sentinel) → `min(round(budget * f), cap)`:
    ///   compact at the percentage, but never later than the absolute guard-rail.
    /// - `compact_at = Some(f)` with no cap (`threshold_tokens == usize::MAX`
    ///   sentinel) → `round(budget * f)`.
    /// - `compact_at = None` → the absolute `threshold_tokens` as-is (back-compat,
    ///   including the parser's `max_tokens * 8 / 10` default).
    ///
    /// The `usize::MAX` sentinel is safe: a layout is always resolved before any
    /// [`Region::needs_compaction`](crate::region::Region::needs_compaction) check.
    fn resolve_compacting_threshold(
        compact_at: Option<f64>,
        threshold_tokens: usize,
        resolved_budget: usize,
    ) -> usize {
        match compact_at {
            Some(fraction) => {
                let pct = (resolved_budget as f64 * fraction).round() as usize;
                pct.min(threshold_tokens)
            }
            None => threshold_tokens,
        }
    }
}

/// Where a region's initial content comes from at run start.
///
/// A region without a seed starts empty and is populated by the agent. A seeded
/// region is filled before the first inference: `CallerInput` regions are filled
/// by the run's caller (a CLI `--<name>` flag, an ACP `---region:<name>---`
/// marker, or the API `regions` map); the remaining variants are resolved by the
/// daemon from the run's workdir (which is why this type only *declares* the
/// source - `leviath-core` stays filesystem-agnostic; resolution lives in the
/// CLI daemon's spawner).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RegionSeed {
    /// Filled at run time by the caller, keyed by `name` (defaults to the
    /// region's own name; the sentinel `task` maps to the `--task`/prompt text).
    /// When the owning region is `required`, a missing value is a hard error
    /// before any inference runs.
    CallerInput {
        /// The caller-input key this region is filled from.
        name: String,
    },
    /// Concatenated contents of the workdir files matching a glob pattern.
    Glob {
        /// Glob pattern, resolved relative to the run's workdir.
        pattern: String,
    },
    /// Concatenated contents of an explicit list of workdir-relative files.
    Files {
        /// File paths, resolved relative to the run's workdir.
        paths: Vec<String>,
    },
    /// A static literal string baked into the blueprint.
    Literal {
        /// The verbatim seed text.
        text: String,
    },
    /// The `String` returned by running a Rhai script from the workdir.
    Rhai {
        /// Script path, resolved relative to the run's workdir.
        script: String,
    },
    /// The combined stdout/stderr of a shell command run in the workdir at spawn.
    ///
    /// Unlike every other variant this *executes* something, and it does so
    /// before the first inference - so before any tool-approval prompt. The
    /// daemon runs it inside the entry stage's sandbox when one is configured,
    /// caps its runtime and output, and honours the `[security]
    /// allow_seed_commands` kill switch. A failure is non-fatal unless the
    /// owning region is `required`.
    Command {
        /// The shell command line, run with the platform shell in the workdir.
        command: String,
    },
    /// The combined output of one or more tool calls, run at spawn.
    ///
    /// Like [`Command`](Self::Command) this *executes* something, but through
    /// the run's own tool layer rather than a shell: any tool the agent could
    /// call is callable here - a built-in, an MCP server's, a Rhai script's -
    /// and each call answers to the same `tool_permissions` and taint rules it
    /// would answer to mid-run. That is what makes an unrestricted list safe:
    /// a seed can reach nothing the agent was not already granted.
    ///
    /// Several calls write into one region, in the order given, each under its
    /// own heading. A failed call is skipped with a warning unless the region is
    /// `required`, so one unavailable tool does not cost the others.
    Tools {
        /// The calls to run, in order.
        calls: Vec<SeedToolCall>,
        /// Whether the calls run once, or again on every stage entry.
        refresh: SeedRefresh,
    },
}

/// When a [`RegionSeed::Tools`] seed runs again.
///
/// Every other seed kind resolves once, at spawn, and this defaults to the
/// same: a region seeded from the filesystem or a literal has no reason to be
/// re-read, and re-running a call on every stage entry costs a tool call and
/// rewrites a region the cache was holding still.
///
/// [`EachStage`](Self::EachStage) is for the seeds where the answer moves.
/// A clock is the clear case: a run that spends an hour in one stage and then
/// enters another should date the second stage from when it started, not from
/// when the run did.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SeedRefresh {
    /// Resolve once, at spawn. The default, and what every other seed does.
    #[default]
    Once,
    /// Resolve again whenever a stage is entered, replacing the region.
    EachStage,
}

impl SeedRefresh {
    /// Parse the manifest spelling, or `None` for a word that is neither.
    ///
    /// A wrong spelling is rejected rather than defaulted, so
    /// `refresh = "each stage"` is reported instead of quietly meaning `once` -
    /// which would read as the feature not working.
    pub fn from_str_loose(value: &str) -> Option<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "once" | "spawn" => Some(Self::Once),
            "each_stage" | "stage" => Some(Self::EachStage),
            _ => None,
        }
    }
}

/// One tool call in a [`RegionSeed::Tools`] seed.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SeedToolCall {
    /// The tool to call, spelled as the agent would spell it (so an MCP tool
    /// keeps its `<server>__<tool>` qualification).
    pub name: String,
    /// The arguments object. Empty for the many tools that take none.
    pub args: serde_json::Value,
}

impl SeedToolCall {
    /// A call with no arguments.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            args: serde_json::Value::Object(serde_json::Map::new()),
        }
    }

    /// A call with an arguments object.
    pub fn with_args(name: impl Into<String>, args: serde_json::Value) -> Self {
        Self {
            name: name.into(),
            args,
        }
    }
}

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

    #[test]
    fn both_spellings_and_their_aliases_parse() {
        assert_eq!(SeedRefresh::from_str_loose("once"), Some(SeedRefresh::Once));
        assert_eq!(
            SeedRefresh::from_str_loose("spawn"),
            Some(SeedRefresh::Once)
        );
        assert_eq!(
            SeedRefresh::from_str_loose("each_stage"),
            Some(SeedRefresh::EachStage)
        );
        assert_eq!(
            SeedRefresh::from_str_loose("stage"),
            Some(SeedRefresh::EachStage)
        );
        // Case and surrounding space are not the author's problem.
        assert_eq!(
            SeedRefresh::from_str_loose("  EACH_STAGE "),
            Some(SeedRefresh::EachStage)
        );
    }

    /// A word that is neither is rejected rather than defaulted. Defaulting
    /// would make `refresh = "each stage"` silently mean `once`, which reads as
    /// the feature not working rather than as a typo.
    #[test]
    fn an_unrecognised_word_is_not_quietly_once() {
        assert_eq!(SeedRefresh::from_str_loose("each stage"), None);
        assert_eq!(SeedRefresh::from_str_loose("always"), None);
        assert_eq!(SeedRefresh::from_str_loose(""), None);
    }

    /// The default matches every other seed kind: resolve at spawn, once.
    #[test]
    fn the_default_is_once() {
        assert_eq!(SeedRefresh::default(), SeedRefresh::Once);
    }
}

/// Definition of a region in a layout.
///
/// This is the blueprint for creating a Region instance. It specifies the
/// region's configuration but doesn't contain actual content.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegionDefinition {
    /// Unique name for this region
    pub name: String,

    /// Region lifecycle policy
    pub kind: RegionKind,

    /// **Resolved** maximum tokens for this region. This is the concrete ceiling
    /// every downstream consumer reads; for a percentage budget it is populated
    /// when the layout is resolved against a model window (see
    /// [`ContextLayout::resolved`]). [`Self::budget`] is the source of truth for
    /// how this value is derived.
    pub max_tokens: usize,

    /// How this region's ceiling is expressed. Defaults (via [`Self::new`]) to
    /// [`BudgetSpec::Absolute`] holding `max_tokens`, so a region that names a
    /// token count directly gets an absolute ceiling. A percentage budget is
    /// resolved against the model context window at window-build time.
    #[serde(default)]
    pub budget: BudgetSpec,

    /// For [`RegionKind::Compacting`] regions only: compact when the region
    /// reaches this fraction of its resolved budget (`0.80` for `compact_at =
    /// "80%"`). `None` keeps the absolute `threshold_tokens` carried on the kind.
    /// See [`ContextLayout::resolved`] for how this becomes a concrete threshold.
    #[serde(default)]
    pub compact_at: Option<f64>,

    /// Optional validation schema
    pub schema: Option<RegionSchema>,

    /// Human-readable description of this region's purpose
    pub description: Option<String>,

    /// Whether `description` is also shown to the model, under the region's
    /// name. Off by default - see [`crate::region::Region::describe_in_prompt`].
    #[serde(default)]
    pub describe_in_prompt: bool,

    /// When true, this region must be non-empty before a stage that can write
    /// to it is allowed to complete. Guards against an agent skipping a
    /// context-population step (e.g. never writing the `plan` region). Enforced
    /// in the run loop, which re-runs the stage with [`Self::required_message`]
    /// until the region is populated.
    #[serde(default)]
    pub required: bool,

    /// Whether an edge transform may hand this region to the summarizer.
    ///
    /// `transform = "compact"` reads as "summarize the transcript on the way
    /// out" and means "summarize every region that is not pinned", which
    /// includes the ones holding the run's results. Figures that survive a
    /// paraphrase are no longer figures: without this, a `results` region
    /// carrying computed values is rewritten into prose before the stage that
    /// reports them ever sees it.
    ///
    /// Setting this false protects the region wherever it is used, rather than
    /// at each of the N edges that might touch it. `clear` still applies - this
    /// says "do not paraphrase my content", not "keep it forever".
    #[serde(default = "crate::default_true")]
    pub summarizable: bool,

    /// What this region does when a write does not fit.
    ///
    /// Declared per region rather than per stage: whether losing the oldest
    /// entry is acceptable is a property of what the region holds, and does not
    /// change depending on which stage is writing to it.
    #[serde(default)]
    pub admission: crate::region::Admission,
    /// How much this region's contents move between requests. See
    /// [`crate::region::Volatility`].
    ///
    /// Defaulted on the wire so a definition written before this existed still
    /// loads, and loads as the pessimistic value - which is what an unclassified
    /// region should be.
    #[serde(default)]
    pub volatility: crate::region::Volatility,

    /// Optional custom message shown to the agent when this region is required
    /// but empty. Falls back to a generated default when `None`.
    #[serde(default)]
    pub required_message: Option<String>,

    /// Where this region's initial content comes from at run start. `None`
    /// means the region starts empty (the agent populates it). See
    /// [`RegionSeed`].
    #[serde(default)]
    pub seed: Option<RegionSeed>,

    /// Mime type patterns this region takes; empty means anything. See
    /// [`crate::region::Region::accepts`].
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub accepts: Vec<String>,
}

impl RegionDefinition {
    /// Create a new region definition with an absolute token ceiling.
    ///
    /// The `budget` is set to [`BudgetSpec::Absolute`] holding `max_tokens` and
    /// `compact_at` to `None`, so every existing caller (and every region without
    /// a percentage budget) is unaffected - resolving such a layout is a no-op.
    pub fn new(name: String, kind: RegionKind, max_tokens: usize) -> Self {
        Self {
            name,
            kind,
            max_tokens,
            budget: BudgetSpec::Absolute(max_tokens),
            compact_at: None,
            schema: None,
            description: None,
            describe_in_prompt: false,
            required: false,
            required_message: None,
            summarizable: true,
            admission: crate::region::Admission::default(),
            volatility: crate::region::Volatility::default(),
            seed: None,
            accepts: Vec::new(),
        }
    }

    /// Set this region's budget spec (e.g. a percentage of the model window).
    /// `max_tokens` is left as the provisional/resolved value; it is (re)computed
    /// from the budget when the owning layout is resolved.
    pub fn with_budget(mut self, budget: BudgetSpec) -> Self {
        self.budget = budget;
        self
    }

    /// Set the compaction trigger fraction for a [`RegionKind::Compacting`]
    /// region (`0.80` == compact at 80% of the resolved budget).
    pub fn with_compact_at(mut self, fraction: f64) -> Self {
        self.compact_at = Some(fraction);
        self
    }

    /// Set this region's seed source.
    pub fn with_seed(mut self, seed: RegionSeed) -> Self {
        self.seed = Some(seed);
        self
    }

    /// Mark this region as required, with an optional custom nudge message.
    pub fn with_required(mut self, required: bool, message: Option<String>) -> Self {
        self.required = required;
        self.required_message = message;
        self
    }

    /// Add a schema to this region definition.
    pub fn with_schema(mut self, schema: RegionSchema) -> Self {
        self.schema = Some(schema);
        self
    }

    /// Add a description to this region definition.
    pub fn with_description(mut self, description: String) -> Self {
        self.description = Some(description);
        self
    }
}

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

    #[test]
    fn test_layout_creation() {
        let regions = vec![
            RegionDefinition::new("pinned".to_string(), RegionKind::Pinned, 5000),
            RegionDefinition::new("temp".to_string(), RegionKind::Temporary, 10000),
        ];
        let layout = ContextLayout::new(regions, 20000);
        assert_eq!(layout.regions.len(), 2);
        assert_eq!(layout.total_budget_tokens, 20000);
    }

    #[test]
    fn test_layout_validation() {
        let regions = vec![RegionDefinition::new(
            "test".to_string(),
            RegionKind::Pinned,
            5000,
        )];
        let layout =
            ContextLayout::new(regions, 10000).with_eviction_order(vec!["test".to_string()]);

        assert!(layout.validate().is_ok());
    }

    #[test]
    fn test_duplicate_region_names() {
        let regions = vec![
            RegionDefinition::new("test".to_string(), RegionKind::Pinned, 5000),
            RegionDefinition::new("test".to_string(), RegionKind::Temporary, 3000),
        ];
        let layout = ContextLayout::new(regions, 10000);

        assert!(layout.validate().is_err());
    }

    #[test]
    fn test_eviction_order_unknown_region_is_error() {
        let regions = vec![RegionDefinition::new(
            "test".to_string(),
            RegionKind::Pinned,
            5000,
        )];
        let layout =
            ContextLayout::new(regions, 10000).with_eviction_order(vec!["nonexistent".to_string()]);

        let err = layout.validate().unwrap_err();
        assert_eq!(
            err,
            ValidationError::Layout(
                "eviction order references unknown region: nonexistent".to_string()
            )
        );
    }

    #[test]
    fn test_validate_warns_but_does_not_error_when_max_tokens_exceed_budget() {
        // Sum of region max_tokens (5000 + 10000 = 15000) exceeds the total
        // budget (10000) - this should only warn, not fail validation, since
        // not all regions are full simultaneously.
        let regions = vec![
            RegionDefinition::new("a".to_string(), RegionKind::Pinned, 5000),
            RegionDefinition::new("b".to_string(), RegionKind::Temporary, 10000),
        ];
        let layout = ContextLayout::new(regions, 10000);
        with_tracing(|| {
            assert!(layout.validate().is_ok());
        });
    }

    #[test]
    fn validate_errors_when_fixed_regions_starve_working_budget() {
        // Realistically-sized layout (>= 20k) where a huge fixed (pinned) region
        // leaves < 8000 working tokens for conversation/tool-results → hard error.
        let regions = vec![
            RegionDefinition::new("big_pinned".to_string(), RegionKind::Pinned, 95_000),
            RegionDefinition::new("work".to_string(), RegionKind::Temporary, 5_000),
        ];
        let layout = ContextLayout::new(regions, 100_000);
        with_tracing(|| {
            let err = layout.validate().unwrap_err();
            assert!(
                err.to_string().contains("working tokens"),
                "actionable budget error: {err}"
            );
        });
    }

    #[test]
    fn validate_ok_for_realistic_layout_with_working_room() {
        let regions = vec![
            RegionDefinition::new("task".to_string(), RegionKind::Pinned, 4_000),
            RegionDefinition::new("conversation".to_string(), RegionKind::Temporary, 40_000),
        ];
        let layout = ContextLayout::new(regions, 44_000);
        with_tracing(|| {
            assert!(layout.validate().is_ok());
        });
    }

    #[test]
    fn validate_working_room_judges_fixed_regions_against_the_passed_window() {
        // The same layout passes against a wide window and fails against a
        // narrow one: the fixed region is fine when the stage seeing it has room
        // and starves the working budget when the stage's window is small. This
        // is what lets each stage be judged against its own model's window over
        // just the regions it can see.
        let regions = vec![
            RegionDefinition::new("task".to_string(), RegionKind::Pinned, 30_000),
            RegionDefinition::new("work".to_string(), RegionKind::Temporary, 10_000),
        ];
        let layout = ContextLayout::new(regions, 200_000);
        with_tracing(|| {
            assert!(layout.validate_working_room(200_000).is_ok());
            let err = layout.validate_working_room(32_000).unwrap_err();
            assert!(err.to_string().contains("working tokens"), "{err}");
            // A tiny (toy-sized) window below the check floor is left alone.
            assert!(layout.validate_working_room(10_000).is_ok());
        });
    }

    fn custom_kind(script: &str, persistent: bool) -> RegionKind {
        RegionKind::Custom {
            script: script.to_string(),
            persistent,
        }
    }

    #[test]
    fn validate_rejects_custom_region_with_empty_script() {
        // Whitespace-only counts as empty: it could never resolve to a file
        // and the runtime would silently fall back on every inference.
        let regions = vec![RegionDefinition::new(
            "brain".to_string(),
            custom_kind("   ", false),
            5000,
        )];
        let layout = ContextLayout::new(regions, 10_000);
        let err = with_tracing(|| layout.validate().unwrap_err());
        assert!(
            err.to_string().contains("non-empty script path"),
            "actionable error: {err}"
        );
    }

    #[test]
    fn validate_counts_persistent_custom_as_fixed_budget() {
        // A persistent custom region is Pinned-like: protected from eviction,
        // so it must count toward the fixed budget that can starve the
        // working room.
        let regions = vec![
            RegionDefinition::new("vault".to_string(), custom_kind("v.rhai", true), 95_000),
            RegionDefinition::new("work".to_string(), RegionKind::Temporary, 5_000),
        ];
        let layout = ContextLayout::new(regions, 100_000);
        let err = with_tracing(|| layout.validate().unwrap_err());
        assert!(err.to_string().contains("working tokens"), "{err}");
    }

    #[test]
    fn validate_counts_non_persistent_custom_as_working_budget() {
        // Same shape, but the custom region is evictable - it IS the working
        // room, so validation passes.
        let regions = vec![
            RegionDefinition::new("brain".to_string(), custom_kind("b.rhai", false), 95_000),
            RegionDefinition::new("task".to_string(), RegionKind::Pinned, 4_000),
        ];
        let layout = ContextLayout::new(regions, 100_000);
        with_tracing(|| {
            assert!(layout.validate().is_ok());
        });
    }

    #[test]
    fn custom_region_satisfies_the_message_region_check() {
        // A layout whose only region is custom must not trip the "no
        // SlidingWindow region" warning path - its script can render typed
        // entries as messages. (Mirrors the sliding-window-present test: the
        // skip branch is exercised, validation succeeds.)
        let regions = vec![RegionDefinition::new(
            "everything".to_string(),
            custom_kind("all.rhai", false),
            9_000,
        )];
        let layout = ContextLayout::new(regions, 10_000);
        with_tracing(|| {
            assert!(layout.validate().is_ok());
        });
    }

    #[test]
    fn resolved_percent_budget_applies_to_custom_region() {
        // The "recreate built-ins in Rhai" guarantee: percentage budgets work
        // on custom regions exactly as on built-in kinds, resolved against
        // the stage model's context window at spawn.
        let def = RegionDefinition::new("brain".to_string(), custom_kind("b.rhai", false), 0)
            .with_budget(BudgetSpec::Percent {
                percent: 0.40,
                min: Some(10_000),
                max: None,
            });
        let layout = ContextLayout::new(vec![def], 0);
        let resolved = layout.resolved(200_000);
        assert_eq!(resolved.regions[0].max_tokens, 80_000);
        assert!(matches!(
            resolved.regions[0].kind,
            RegionKind::Custom { ref script, persistent: false } if script == "b.rhai"
        ));
        // The min floor wins on a small window.
        let small = layout.resolved(8_192);
        assert_eq!(small.regions[0].max_tokens, 10_000);
    }

    #[test]
    fn test_get_region_found() {
        let regions = vec![
            RegionDefinition::new("a".to_string(), RegionKind::Pinned, 5000),
            RegionDefinition::new("b".to_string(), RegionKind::Temporary, 3000),
        ];
        let layout = ContextLayout::new(regions, 10000);

        let found = layout.get_region("b").unwrap();
        assert_eq!(found.name, "b");
        assert_eq!(found.max_tokens, 3000);
    }

    #[test]
    fn test_get_region_not_found() {
        let regions = vec![RegionDefinition::new(
            "a".to_string(),
            RegionKind::Pinned,
            5000,
        )];
        let layout = ContextLayout::new(regions, 10000);
        assert!(layout.get_region("missing").is_none());
    }

    #[test]
    fn test_region_definition_with_schema() {
        let schema = crate::region::RegionSchema::new(crate::region::ContentFormat::Json);
        let def =
            RegionDefinition::new("a".to_string(), RegionKind::Pinned, 5000).with_schema(schema);
        assert_eq!(
            def.schema.as_ref().unwrap().format,
            crate::region::ContentFormat::Json
        );
    }

    #[test]
    fn test_region_definition_with_description() {
        let def = RegionDefinition::new("a".to_string(), RegionKind::Pinned, 5000)
            .with_description("holds architecture notes".to_string());
        assert_eq!(def.description.as_deref(), Some("holds architecture notes"));
    }

    #[test]
    fn parse_budget_accepts_plain_and_decimal_percentages() {
        assert_eq!(BudgetSpec::parse_budget("35%").unwrap(), 0.35);
        assert_eq!(BudgetSpec::parse_budget("100%").unwrap(), 1.0);
        assert!((BudgetSpec::parse_budget("0.6%").unwrap() - 0.006).abs() < 1e-9);
    }

    #[test]
    fn parse_budget_trims_surrounding_and_inner_whitespace() {
        assert_eq!(BudgetSpec::parse_budget("  35 %  ").unwrap(), 0.35);
    }

    #[test]
    fn parse_budget_rejects_missing_percent_sign() {
        let err = BudgetSpec::parse_budget("35").unwrap_err();
        assert!(err.contains("must end with '%'"), "{err}");
    }

    #[test]
    fn parse_budget_rejects_non_numeric() {
        let err = BudgetSpec::parse_budget("abc%").unwrap_err();
        assert!(err.contains("not a valid number"), "{err}");
    }

    #[test]
    fn parse_budget_rejects_zero_and_negative() {
        let zero = BudgetSpec::parse_budget("0%").unwrap_err();
        assert!(zero.contains("greater than 0%"), "{zero}");
        let neg = BudgetSpec::parse_budget("-10%").unwrap_err();
        assert!(neg.contains("greater than 0%"), "{neg}");
    }

    #[test]
    fn parse_budget_rejects_over_one_hundred() {
        let err = BudgetSpec::parse_budget("150%").unwrap_err();
        assert!(err.contains("at most 100%"), "{err}");
    }

    #[test]
    fn resolve_absolute_ignores_window() {
        assert_eq!(BudgetSpec::Absolute(4000).resolve(1_000_000), 4000);
        assert!(!BudgetSpec::Absolute(4000).is_percent());
    }

    #[test]
    fn resolve_percent_of_window() {
        let spec = BudgetSpec::Percent {
            percent: 0.35,
            min: None,
            max: None,
        };
        assert_eq!(spec.resolve(1_000_000), 350_000);
        assert!(spec.is_percent());
    }

    #[test]
    fn resolve_percent_applies_max_cap() {
        let spec = BudgetSpec::Percent {
            percent: 0.02,
            min: None,
            max: Some(4000),
        };
        // 2% of 1M = 20_000, capped to 4000.
        assert_eq!(spec.resolve(1_000_000), 4000);
    }

    #[test]
    fn resolve_percent_applies_min_floor() {
        let spec = BudgetSpec::Percent {
            percent: 0.02,
            min: Some(2000),
            max: None,
        };
        // 2% of 8000 = 160, floored to 2000.
        assert_eq!(spec.resolve(8000), 2000);
    }

    #[test]
    fn resolve_percent_within_bounds_takes_neither_clamp() {
        let spec = BudgetSpec::Percent {
            percent: 0.10,
            min: Some(1000),
            max: Some(50_000),
        };
        // 10% of 200k = 20_000, between the floor and cap.
        assert_eq!(spec.resolve(200_000), 20_000);
    }

    #[test]
    fn resolve_percent_floor_wins_when_min_exceeds_max() {
        let spec = BudgetSpec::Percent {
            percent: 0.10,
            min: Some(9000),
            max: Some(4000),
        };
        // 10% of 200k = 20_000 → capped to 4000 → floored up to 9000 (floor wins).
        assert_eq!(spec.resolve(200_000), 9000);
    }

    #[test]
    fn has_percent_budgets_detects_percentage_regions() {
        let absolute = ContextLayout::new(
            vec![RegionDefinition::new(
                "a".to_string(),
                RegionKind::Pinned,
                5000,
            )],
            5000,
        );
        assert!(!absolute.has_percent_budgets());

        let percent = ContextLayout::new(
            vec![
                RegionDefinition::new("a".to_string(), RegionKind::Pinned, 5000).with_budget(
                    BudgetSpec::Percent {
                        percent: 0.05,
                        min: None,
                        max: None,
                    },
                ),
            ],
            5000,
        );
        assert!(percent.has_percent_budgets());
    }

    #[test]
    fn resolved_is_noop_for_absolute_layout() {
        let layout = ContextLayout::new(
            vec![RegionDefinition::new(
                "a".to_string(),
                RegionKind::Pinned,
                5000,
            )],
            5000,
        );
        let resolved = layout.resolved(1_000_000);
        assert_eq!(resolved.regions[0].max_tokens, 5000);
        // An absolute layout keeps its summed total, not the window.
        assert_eq!(resolved.total_budget_tokens, 5000);
    }

    #[test]
    fn resolved_percent_layout_uses_window_as_total() {
        let layout = ContextLayout::new(
            vec![
                RegionDefinition::new("a".to_string(), RegionKind::Pinned, 0).with_budget(
                    BudgetSpec::Percent {
                        percent: 0.10,
                        min: None,
                        max: None,
                    },
                ),
            ],
            0,
        )
        .with_eviction_order(vec!["a".to_string()]);
        let resolved = layout.resolved(1_000_000);
        assert_eq!(resolved.regions[0].max_tokens, 100_000);
        assert_eq!(resolved.total_budget_tokens, 1_000_000);
        // eviction order carried through.
        assert_eq!(resolved.eviction_order, vec!["a".to_string()]);
    }

    #[test]
    fn resolved_per_region_sizes_each_region_against_its_own_window() {
        let pct = || BudgetSpec::Percent {
            percent: 0.10,
            min: None,
            max: None,
        };
        // A Compacting region whose threshold is a fraction of its resolved
        // budget, so the per-region path must recompute it against the region's
        // own window like `resolved()` does.
        let mut compact = RegionDefinition::new(
            "roll".to_string(),
            RegionKind::Compacting {
                threshold_tokens: usize::MAX,
            },
            0,
        )
        .with_budget(pct());
        compact.compact_at = Some(0.5);
        let layout = ContextLayout::new(
            vec![
                RegionDefinition::new("wide".to_string(), RegionKind::Pinned, 0).with_budget(pct()),
                RegionDefinition::new("narrow".to_string(), RegionKind::Pinned, 0)
                    .with_budget(pct()),
                compact,
            ],
            0,
        );
        let resolved = layout.resolved_per_region(&|name| match name {
            "wide" => 200_000,
            _ => 32_768,
        });
        let max_of = |n: &str| {
            resolved
                .regions
                .iter()
                .find(|r| r.name == n)
                .unwrap()
                .max_tokens
        };
        assert_eq!(max_of("wide"), 20_000); // 10% of 200k
        assert_eq!(max_of("narrow"), 3_277); // 10% of 32768, rounded
        // roll: 10% of 32768 = 3277 budget; threshold = 50% of that, sized
        // against the region's own window, not the widest.
        assert_eq!(max_of("roll"), 3_277);
        let roll = resolved.regions.iter().find(|r| r.name == "roll").unwrap();
        assert!(
            matches!(roll.kind, RegionKind::Compacting { threshold_tokens } if threshold_tokens == 1_639),
            "compacting threshold resolved per region: {:?}",
            roll.kind
        );
        // The total is the largest per-region window; the real fit check is per
        // stage, done by the caller.
        assert_eq!(resolved.total_budget_tokens, 200_000);

        // An absolute layout has nothing to resolve, so this is a no-op.
        let absolute = ContextLayout::new(
            vec![RegionDefinition::new(
                "x".to_string(),
                RegionKind::Pinned,
                5_000,
            )],
            5_000,
        );
        let same = absolute.resolved_per_region(&|_| 999_999);
        assert_eq!(same.regions[0].max_tokens, 5_000);
        assert_eq!(same.total_budget_tokens, 5_000);
    }

    #[test]
    fn retaining_keeps_only_the_named_regions_and_eviction_entries() {
        let layout = ContextLayout {
            regions: vec![
                RegionDefinition::new("keep".to_string(), RegionKind::Pinned, 1_000),
                RegionDefinition::new("drop".to_string(), RegionKind::Temporary, 1_000),
            ],
            total_budget_tokens: 10_000,
            eviction_order: vec!["keep".to_string(), "drop".to_string()],
        };
        let kept = layout.retaining(|name| name == "keep");
        assert_eq!(kept.regions.len(), 1);
        assert_eq!(kept.regions[0].name, "keep");
        assert_eq!(kept.eviction_order, vec!["keep".to_string()]);
        // total_budget rides along unchanged; the working-room check judges
        // against a window the caller passes, not this field.
        assert_eq!(kept.total_budget_tokens, 10_000);
    }

    #[test]
    fn resolved_compacting_threshold_all_cases() {
        // compact_at + explicit threshold cap → min(pct, cap).
        let both = RegionDefinition::new(
            "c".to_string(),
            RegionKind::Compacting {
                threshold_tokens: 25_000,
            },
            0,
        )
        .with_budget(BudgetSpec::Percent {
            percent: 0.20,
            min: None,
            max: None,
        })
        .with_compact_at(0.80);
        let r = ContextLayout::new(vec![both], 0).resolved(200_000);
        // budget = 40_000; 80% = 32_000; capped to 25_000.
        assert_eq!(
            r.regions[0].kind,
            RegionKind::Compacting {
                threshold_tokens: 25_000
            }
        );

        // compact_at with no cap (usize::MAX sentinel) → pct only.
        let pct_only = RegionDefinition::new(
            "c".to_string(),
            RegionKind::Compacting {
                threshold_tokens: usize::MAX,
            },
            0,
        )
        .with_budget(BudgetSpec::Percent {
            percent: 0.20,
            min: None,
            max: None,
        })
        .with_compact_at(0.80);
        let r = ContextLayout::new(vec![pct_only], 0).resolved(200_000);
        assert_eq!(
            r.regions[0].kind,
            RegionKind::Compacting {
                threshold_tokens: 32_000
            }
        );

        // compact_at = None → absolute threshold passes through unchanged.
        let absolute = RegionDefinition::new(
            "c".to_string(),
            RegionKind::Compacting {
                threshold_tokens: 8000,
            },
            10_000,
        );
        let r = ContextLayout::new(vec![absolute], 10_000).resolved(1_000_000);
        assert_eq!(
            r.regions[0].kind,
            RegionKind::Compacting {
                threshold_tokens: 8000
            }
        );
    }

    #[test]
    fn validate_skips_token_checks_for_percent_layouts() {
        // A percentage layout whose provisional max_tokens are tiny/zero must not
        // trip the fixed-working-budget hard error - that check is deferred to
        // post-resolution. Wrap in tracing so no warn-arg lines read uncovered.
        let regions = vec![
            RegionDefinition::new("big_pinned".to_string(), RegionKind::Pinned, 0).with_budget(
                BudgetSpec::Percent {
                    percent: 0.95,
                    min: None,
                    max: None,
                },
            ),
        ];
        let layout = ContextLayout::new(regions, 100_000);
        with_tracing(|| {
            assert!(layout.validate().is_ok());
        });
    }

    #[test]
    fn region_definition_default_budget_matches_max_tokens() {
        let def = RegionDefinition::new("a".to_string(), RegionKind::Pinned, 5000);
        assert_eq!(def.budget, BudgetSpec::Absolute(5000));
        assert_eq!(def.compact_at, None);
    }

    #[test]
    fn budget_spec_default_is_absolute_zero() {
        assert_eq!(BudgetSpec::default(), BudgetSpec::Absolute(0));
    }

    #[test]
    fn test_validate_with_sliding_window_present() {
        // A layout that DOES contain a SlidingWindow region exercises the
        // has_sliding_window detection returning true, so the "no sliding
        // window" warning branch is skipped.
        let regions = vec![
            RegionDefinition::new("pinned".to_string(), RegionKind::Pinned, 5000),
            RegionDefinition::new(
                "conv".to_string(),
                RegionKind::SlidingWindow {
                    max_items: 50,
                    eviction_strategy: crate::region::EvictionStrategy::PerItem,
                },
                5000,
            ),
        ];
        let layout = ContextLayout::new(regions, 20000);
        with_tracing(|| {
            assert!(layout.validate().is_ok());
        });
    }

    /// `validate` sums every region's ceiling to warn when they exceed the
    /// budget. Two saturated ceilings must warn rather than overflow that sum
    /// and abort.
    #[test]
    fn validate_does_not_abort_when_region_ceilings_sum_past_usize_max() {
        let layout = ContextLayout::new(
            vec![
                RegionDefinition::new("a".to_string(), RegionKind::Pinned, usize::MAX),
                RegionDefinition::new("b".to_string(), RegionKind::Pinned, usize::MAX),
            ],
            1_000,
        );
        let _ = layout.validate();
    }
}