Skip to main content

leviath_core/
layout.rs

1//! Context window layouts and memory maps.
2//!
3//! A layout defines the complete memory structure for an agent's context window,
4//! including all regions, their sizes, and eviction priorities. This is analogous
5//! to a hardware memory map that defines where different types of data live and
6//! how they're managed.
7
8use crate::error::ValidationError;
9use crate::region::{RegionKind, RegionSchema};
10use serde::{Deserialize, Serialize};
11
12/// The region a stage's `system_prompt` is written into, when a blueprint
13/// declares one by this name.
14///
15/// Stage instructions have always been pinned context - that is why they read
16/// as instruction rather than history - but the region holding them was chosen
17/// by accident: whichever pinned region happened to be declared first. That
18/// region then carried the prompt's tokens in the stage ledger under its own
19/// name, could not be sized or scoped, and sat wherever it sat in the cached
20/// prefix (#366).
21///
22/// Declaring a region by this name gives the prompt a handle:
23///
24/// ```toml
25/// [context.regions]
26/// stage_instructions = { kind = "pinned", budget = "3%" }
27/// ```
28///
29/// A blueprint that declares nothing by this name keeps the old behaviour
30/// exactly, so this costs no existing agent anything.
31pub const STAGE_INSTRUCTIONS_REGION: &str = "stage_instructions";
32
33/// Serde default for a flag that is on unless a blueprint turns it off.
34fn default_true() -> bool {
35    true
36}
37
38/// How a region's token ceiling is expressed before it is resolved against a
39/// concrete model context window.
40///
41/// Blueprint authors think in **proportions** (`budget = "35%"`) so their intent
42/// stays correct regardless of the model's context size, while power users can
43/// still pin an exact count. The percentage denominator - the model's context
44/// window - is not known at parse time, so the spec is stored unresolved here and
45/// turned into a concrete token count at window-build time (see
46/// [`BudgetSpec::resolve`] and [`ContextLayout::resolved`]).
47#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
48#[serde(rename_all = "snake_case")]
49pub enum BudgetSpec {
50    /// A fixed token ceiling, independent of the model. Resolving is a no-op.
51    Absolute(usize),
52
53    /// A ceiling expressed as a fraction of the model's context window, with
54    /// optional absolute guard-rails. `percent` is a fraction (`0.35` for
55    /// `"35%"`). `max` caps the resolved value (so e.g. 2% of a 1M window can't
56    /// balloon a task region to 20K tokens); `min` floors it (so a small-context
57    /// model doesn't starve the region below a usable size).
58    Percent {
59        /// Fraction of the model context window (0.35 == "35%").
60        percent: f64,
61        /// Absolute floor for the resolved value, if any.
62        min: Option<usize>,
63        /// Absolute cap for the resolved value, if any.
64        max: Option<usize>,
65    },
66}
67
68impl Default for BudgetSpec {
69    /// Only a serde-deserialize fallback for older persisted blueprints; live
70    /// code always sets the budget explicitly via [`RegionDefinition::new`].
71    fn default() -> Self {
72        BudgetSpec::Absolute(0)
73    }
74}
75
76impl BudgetSpec {
77    /// Parse a percentage string like `"35%"` into its fraction (`0.35`).
78    ///
79    /// Surrounding whitespace is trimmed and decimals are allowed (`"0.6%"`).
80    /// Rejects a missing `%`, a non-numeric value, and anything outside the
81    /// `(0, 100]` range - a single region can't sensibly claim ≤0% or more than
82    /// the whole window (region budgets may *sum* past 100%, but each is a
83    /// fraction of one window). Returns the human-readable reason on failure so
84    /// the caller can surface it at load time.
85    pub fn parse_budget(s: &str) -> std::result::Result<f64, String> {
86        let trimmed = s.trim();
87        let Some(num) = trimmed.strip_suffix('%') else {
88            return Err(format!("budget '{s}' must end with '%' (e.g. \"35%\")"));
89        };
90        let value: f64 = num
91            .trim()
92            .parse()
93            .map_err(|_| format!("budget '{s}' is not a valid number"))?;
94        if !(value > 0.0 && value <= 100.0) {
95            return Err(format!(
96                "budget '{s}' must be greater than 0% and at most 100%"
97            ));
98        }
99        Ok(value / 100.0)
100    }
101
102    /// Resolve this spec to a concrete token count against a model context
103    /// `window`.
104    ///
105    /// [`Absolute`](BudgetSpec::Absolute) ignores the window (idempotent - a
106    /// fully-absolute layout resolves to itself). [`Percent`](BudgetSpec::Percent)
107    /// rounds `window * percent`, then applies the `max` cap, then the `min`
108    /// floor. The floor is applied **last** so that when `min > max` the floor
109    /// wins: a region starved below a usable size is worse than one slightly over
110    /// its cap.
111    pub fn resolve(&self, window: usize) -> usize {
112        match self {
113            BudgetSpec::Absolute(n) => *n,
114            BudgetSpec::Percent { percent, min, max } => {
115                let mut v = (window as f64 * percent).round() as usize;
116                if let Some(max) = max {
117                    v = v.min(*max);
118                }
119                if let Some(min) = min {
120                    v = v.max(*min);
121                }
122                v
123            }
124        }
125    }
126
127    /// Whether this is a percentage budget (needs a model window to resolve).
128    pub fn is_percent(&self) -> bool {
129        matches!(self, BudgetSpec::Percent { .. })
130    }
131}
132
133/// A ContextLayout defines the complete memory map for an agent.
134///
135/// Like SNES VRAM layout - every region has a defined purpose, size, and policy.
136/// The layout specifies:
137/// - Which regions exist and their configurations
138/// - Total token budget across all regions
139/// - Eviction order when space is needed
140///
141/// Layouts are typically defined in an agent's blueprint and remain constant
142/// throughout the agent's lifecycle, though the content within regions changes.
143#[derive(Debug, Clone, Serialize, Deserialize)]
144pub struct ContextLayout {
145    /// All regions in this layout
146    pub regions: Vec<RegionDefinition>,
147
148    /// Total token budget across all regions
149    pub total_budget_tokens: usize,
150
151    /// Region names in eviction priority order (first = evicted first)
152    ///
153    /// When the context window fills up, regions are processed in this order:
154    /// 1. Temporary regions: evict oldest entries
155    /// 2. Compacting regions: trigger summarization
156    /// 3. SlidingWindow regions: reduce window size
157    /// 4. Pinned regions: NEVER touched (if these fill up, it's a config error)
158    pub eviction_order: Vec<String>,
159}
160
161impl ContextLayout {
162    /// Create a new layout with the specified configuration.
163    pub fn new(regions: Vec<RegionDefinition>, total_budget_tokens: usize) -> Self {
164        Self {
165            regions,
166            total_budget_tokens,
167            eviction_order: Vec::new(),
168        }
169    }
170
171    /// Set the eviction order for this layout.
172    pub fn with_eviction_order(mut self, order: Vec<String>) -> Self {
173        self.eviction_order = order;
174        self
175    }
176
177    /// Validate that the layout is well-formed.
178    ///
179    /// Checks:
180    /// - Sum of max_tokens doesn't exceed total_budget_tokens
181    /// - All region names in eviction_order exist
182    /// - No duplicate region names
183    pub fn validate(&self) -> std::result::Result<(), ValidationError> {
184        // Check for duplicate region names
185        let mut names = std::collections::HashSet::new();
186        for region in &self.regions {
187            if !names.insert(region.name.as_str()) {
188                return Err(ValidationError::Region {
189                    region: region.name.clone(),
190                    message: "duplicate region name".to_string(),
191                });
192            }
193        }
194
195        // Check that eviction_order regions exist
196        for name in &self.eviction_order {
197            if !names.contains(name.as_str()) {
198                return Err(ValidationError::Layout(format!(
199                    "eviction order references unknown region: {}",
200                    name
201                )));
202            }
203        }
204
205        // Reject a Custom region whose script path is empty - it could never
206        // resolve to a file, and the runtime would silently fall back to
207        // Temporary-style rendering on every inference.
208        for region in &self.regions {
209            if let RegionKind::Custom { script, .. } = &region.kind
210                && script.trim().is_empty()
211            {
212                return Err(ValidationError::Region {
213                    region: region.name.clone(),
214                    message: "custom region requires a non-empty script path".to_string(),
215                });
216            }
217        }
218
219        // Warn if sum of max tokens exceeds budget (not necessarily an error,
220        // since not all regions will be full simultaneously)
221        // Warn if no SlidingWindow region exists - agents should have a
222        // conversation region for typed message entries, but some agents
223        // (e.g., deep-researcher) use other region kinds exclusively. A Custom
224        // region counts: its script can render typed entries as messages.
225        let has_message_region = self.regions.iter().any(|r| {
226            matches!(
227                r.kind,
228                RegionKind::SlidingWindow { .. } | RegionKind::Custom { .. }
229            )
230        });
231        if !has_message_region {
232            tracing::warn!(
233                "Layout has no SlidingWindow (or custom scripted) region - typed \
234                 conversation entries require one"
235            );
236        }
237
238        // The token-sum warning and the fixed-working-budget hard error below
239        // operate on concrete `max_tokens` values. When percentage budgets are
240        // present those values are provisional placeholders until the layout is
241        // resolved against a model window, so the checks are meaningless here -
242        // skip them and rely on the post-resolution `validate()` call at spawn.
243        if self.has_percent_budgets() {
244            return Ok(());
245        }
246
247        let total_max: usize = self.regions.iter().map(|r| r.max_tokens).sum();
248        if total_max > self.total_budget_tokens {
249            tracing::warn!(
250                "Sum of region max tokens ({}) exceeds total budget ({})",
251                total_max,
252                self.total_budget_tokens
253            );
254        }
255
256        // Ensure the layout leaves a minimum working budget once the fixed,
257        // non-evictable regions are full. Pinned / HashMap / CompactHistory
258        // regions persist for the whole run and consume budget; if they leave
259        // too little room, the conversation/tool-result (evictable) regions have
260        // almost no space and the agent operates "blind". Fail loudly at load
261        // instead of degrading silently at runtime.
262        let fixed_tokens: usize = self
263            .regions
264            .iter()
265            .filter(|r| {
266                matches!(
267                    r.kind,
268                    RegionKind::Pinned
269                        | RegionKind::HashMap { .. }
270                        | RegionKind::CompactHistory { .. }
271                        | RegionKind::Custom {
272                            persistent: true,
273                            ..
274                        }
275                )
276            })
277            .map(|r| r.max_tokens)
278            .sum();
279        // Only enforce the absolute working-budget floor on realistically-sized
280        // layouts. Tiny illustrative layouts (toy examples, unit-test fixtures)
281        // have small budgets by design and are not real agent runs; applying an
282        // absolute floor to them would be nonsensical.
283        let working_tokens = self.total_budget_tokens.saturating_sub(fixed_tokens);
284        if self.total_budget_tokens >= Self::BUDGET_CHECK_MIN_TOTAL
285            && working_tokens < Self::MIN_WORKING_TOKENS
286        {
287            return Err(ValidationError::Layout(format!(
288                "context layout leaves only {working_tokens} working tokens after fixed \
289                 regions (pinned/hashmap/compact_history/persistent custom) consume \
290                 {fixed_tokens} of the {} \
291                 total budget; at least {} are needed for the agent to operate. Reduce the \
292                 fixed regions' max_tokens or increase the total budget.",
293                self.total_budget_tokens,
294                Self::MIN_WORKING_TOKENS
295            )));
296        }
297
298        Ok(())
299    }
300
301    /// Minimum token budget that must remain for evictable/working regions
302    /// (conversation, tool results, scratch) after the fixed regions are full,
303    /// so the agent has room to hold recent context and generate. Below this a
304    /// run would operate with almost no working space.
305    const MIN_WORKING_TOKENS: usize = 8000;
306
307    /// The working-budget floor is only enforced when the layout's total budget
308    /// is at least this large - i.e. it's a realistically-sized agent, not a
309    /// toy/illustrative layout where an absolute floor wouldn't make sense.
310    const BUDGET_CHECK_MIN_TOTAL: usize = 20_000;
311
312    /// Get a region definition by name.
313    pub fn get_region(&self, name: &str) -> Option<&RegionDefinition> {
314        self.regions.iter().find(|r| r.name == name)
315    }
316
317    /// Whether any region uses a percentage budget (and therefore needs a model
318    /// context window to resolve to concrete token counts).
319    pub fn has_percent_budgets(&self) -> bool {
320        self.regions.iter().any(|r| r.budget.is_percent())
321    }
322
323    /// Resolve every region's percentage budget against a concrete model context
324    /// `window`, returning a fully-absolute layout.
325    ///
326    /// Each region's `max_tokens` becomes `budget.resolve(window)`, and each
327    /// [`RegionKind::Compacting`] region's `threshold_tokens` is recomputed from
328    /// its [`compact_at`](RegionDefinition::compact_at) fraction (via the private
329    /// `resolve_compacting_threshold` helper). `eviction_order` is preserved. The
330    /// total budget becomes the model `window` when any percentage budget is
331    /// present (percentage ceilings are relative to the whole window and may sum
332    /// past 100%); a pure-absolute layout keeps its legacy summed total unchanged.
333    ///
334    /// Resolving an already-absolute layout is a no-op, so this is safe to call
335    /// unconditionally at window-build time.
336    pub fn resolved(&self, window: usize) -> ContextLayout {
337        let regions = self
338            .regions
339            .iter()
340            .map(|r| {
341                let max_tokens = r.budget.resolve(window);
342                let kind = match &r.kind {
343                    RegionKind::Compacting { threshold_tokens } => RegionKind::Compacting {
344                        threshold_tokens: Self::resolve_compacting_threshold(
345                            r.compact_at,
346                            *threshold_tokens,
347                            max_tokens,
348                        ),
349                    },
350                    other => other.clone(),
351                };
352                // Emit a fully-absolute region: the percentage has been baked
353                // into `max_tokens` and the compaction threshold into `kind`, so
354                // the resolved layout carries no `Percent` budgets. This makes
355                // `has_percent_budgets()` false on the result, so a post-resolution
356                // `validate()` runs the real token/working-budget checks.
357                RegionDefinition {
358                    kind,
359                    max_tokens,
360                    budget: BudgetSpec::Absolute(max_tokens),
361                    compact_at: None,
362                    ..r.clone()
363                }
364            })
365            .collect();
366
367        let total_budget_tokens = if self.has_percent_budgets() {
368            window
369        } else {
370            self.total_budget_tokens
371        };
372
373        ContextLayout {
374            regions,
375            total_budget_tokens,
376            eviction_order: self.eviction_order.clone(),
377        }
378    }
379
380    /// Compute a Compacting region's concrete compaction threshold from its
381    /// `compact_at` fraction, the absolute `threshold_tokens` guard carried on
382    /// the kind, and the region's resolved budget.
383    ///
384    /// - `compact_at = Some(f)` with an explicit `threshold_tokens` cap (any
385    ///   value below the [`usize::MAX`] sentinel) → `min(round(budget * f), cap)`:
386    ///   compact at the percentage, but never later than the absolute guard-rail.
387    /// - `compact_at = Some(f)` with no cap (`threshold_tokens == usize::MAX`
388    ///   sentinel) → `round(budget * f)`.
389    /// - `compact_at = None` → the absolute `threshold_tokens` as-is (back-compat,
390    ///   including the parser's `max_tokens * 8 / 10` default).
391    ///
392    /// The `usize::MAX` sentinel is safe: a layout is always resolved before any
393    /// [`Region::needs_compaction`](crate::region::Region::needs_compaction) check.
394    fn resolve_compacting_threshold(
395        compact_at: Option<f64>,
396        threshold_tokens: usize,
397        resolved_budget: usize,
398    ) -> usize {
399        match compact_at {
400            Some(fraction) => {
401                let pct = (resolved_budget as f64 * fraction).round() as usize;
402                pct.min(threshold_tokens)
403            }
404            None => threshold_tokens,
405        }
406    }
407}
408
409/// Where a region's initial content comes from at run start.
410///
411/// A region without a seed starts empty and is populated by the agent. A seeded
412/// region is filled before the first inference: `CallerInput` regions are filled
413/// by the run's caller (a CLI `--<name>` flag, an ACP `---region:<name>---`
414/// marker, or the API `regions` map); the remaining variants are resolved by the
415/// daemon from the run's workdir (which is why this type only *declares* the
416/// source - `leviath-core` stays filesystem-agnostic; resolution lives in the
417/// CLI daemon's spawner).
418#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
419#[serde(rename_all = "snake_case")]
420pub enum RegionSeed {
421    /// Filled at run time by the caller, keyed by `name` (defaults to the
422    /// region's own name; the sentinel `task` maps to the `--task`/prompt text).
423    /// When the owning region is `required`, a missing value is a hard error
424    /// before any inference runs.
425    CallerInput {
426        /// The caller-input key this region is filled from.
427        name: String,
428    },
429    /// Concatenated contents of the workdir files matching a glob pattern.
430    Glob {
431        /// Glob pattern, resolved relative to the run's workdir.
432        pattern: String,
433    },
434    /// Concatenated contents of an explicit list of workdir-relative files.
435    Files {
436        /// File paths, resolved relative to the run's workdir.
437        paths: Vec<String>,
438    },
439    /// A static literal string baked into the blueprint.
440    Literal {
441        /// The verbatim seed text.
442        text: String,
443    },
444    /// The `String` returned by running a Rhai script from the workdir.
445    Rhai {
446        /// Script path, resolved relative to the run's workdir.
447        script: String,
448    },
449    /// The combined stdout/stderr of a shell command run in the workdir at spawn.
450    ///
451    /// Unlike every other variant this *executes* something, and it does so
452    /// before the first inference - so before any tool-approval prompt. The
453    /// daemon runs it inside the entry stage's sandbox when one is configured,
454    /// caps its runtime and output, and honours the `[security]
455    /// allow_seed_commands` kill switch. A failure is non-fatal unless the
456    /// owning region is `required`.
457    Command {
458        /// The shell command line, run with the platform shell in the workdir.
459        command: String,
460    },
461}
462
463/// Definition of a region in a layout.
464///
465/// This is the blueprint for creating a Region instance. It specifies the
466/// region's configuration but doesn't contain actual content.
467#[derive(Debug, Clone, Serialize, Deserialize)]
468pub struct RegionDefinition {
469    /// Unique name for this region
470    pub name: String,
471
472    /// Region lifecycle policy
473    pub kind: RegionKind,
474
475    /// **Resolved** maximum tokens for this region. This is the concrete ceiling
476    /// every downstream consumer reads; for a percentage budget it is populated
477    /// when the layout is resolved against a model window (see
478    /// [`ContextLayout::resolved`]). [`Self::budget`] is the source of truth for
479    /// how this value is derived.
480    pub max_tokens: usize,
481
482    /// How this region's ceiling is expressed. Defaults (via [`Self::new`]) to
483    /// [`BudgetSpec::Absolute`] holding `max_tokens`, so a region built the old
484    /// way behaves exactly as before. A percentage budget is resolved against the
485    /// model context window at window-build time.
486    #[serde(default)]
487    pub budget: BudgetSpec,
488
489    /// For [`RegionKind::Compacting`] regions only: compact when the region
490    /// reaches this fraction of its resolved budget (`0.80` for `compact_at =
491    /// "80%"`). `None` keeps the absolute `threshold_tokens` carried on the kind.
492    /// See [`ContextLayout::resolved`] for how this becomes a concrete threshold.
493    #[serde(default)]
494    pub compact_at: Option<f64>,
495
496    /// Optional validation schema
497    pub schema: Option<RegionSchema>,
498
499    /// Human-readable description of this region's purpose
500    pub description: Option<String>,
501
502    /// When true, this region must be non-empty before a stage that can write
503    /// to it is allowed to complete. Guards against an agent skipping a
504    /// context-population step (e.g. never writing the `plan` region). Enforced
505    /// in the run loop, which re-runs the stage with [`Self::required_message`]
506    /// until the region is populated.
507    #[serde(default)]
508    pub required: bool,
509
510    /// Whether an edge transform may hand this region to the summarizer.
511    ///
512    /// `transform = "compact"` reads as "summarize the transcript on the way
513    /// out" and means "summarize every region that is not pinned", which
514    /// includes the ones holding the run's results. Figures that survive a
515    /// paraphrase are no longer figures: a `results` region carrying computed
516    /// values was rewritten into prose before the stage that reports them saw
517    /// it (#369).
518    ///
519    /// Setting this false protects the region wherever it is used, rather than
520    /// at each of the N edges that might touch it. `clear` still applies - this
521    /// says "do not paraphrase my content", not "keep it forever".
522    #[serde(default = "default_true")]
523    pub summarizable: bool,
524
525    /// Optional custom message shown to the agent when this region is required
526    /// but empty. Falls back to a generated default when `None`.
527    #[serde(default)]
528    pub required_message: Option<String>,
529
530    /// Where this region's initial content comes from at run start. `None`
531    /// means the region starts empty (the agent populates it). See
532    /// [`RegionSeed`].
533    #[serde(default)]
534    pub seed: Option<RegionSeed>,
535}
536
537impl RegionDefinition {
538    /// Create a new region definition with an absolute token ceiling.
539    ///
540    /// The `budget` is set to [`BudgetSpec::Absolute`] holding `max_tokens` and
541    /// `compact_at` to `None`, so every existing caller (and every region without
542    /// a percentage budget) is unaffected - resolving such a layout is a no-op.
543    pub fn new(name: String, kind: RegionKind, max_tokens: usize) -> Self {
544        Self {
545            name,
546            kind,
547            max_tokens,
548            budget: BudgetSpec::Absolute(max_tokens),
549            compact_at: None,
550            schema: None,
551            description: None,
552            required: false,
553            required_message: None,
554            summarizable: true,
555            seed: None,
556        }
557    }
558
559    /// Set this region's budget spec (e.g. a percentage of the model window).
560    /// `max_tokens` is left as the provisional/resolved value; it is (re)computed
561    /// from the budget when the owning layout is resolved.
562    pub fn with_budget(mut self, budget: BudgetSpec) -> Self {
563        self.budget = budget;
564        self
565    }
566
567    /// Set the compaction trigger fraction for a [`RegionKind::Compacting`]
568    /// region (`0.80` == compact at 80% of the resolved budget).
569    pub fn with_compact_at(mut self, fraction: f64) -> Self {
570        self.compact_at = Some(fraction);
571        self
572    }
573
574    /// Set this region's seed source.
575    pub fn with_seed(mut self, seed: RegionSeed) -> Self {
576        self.seed = Some(seed);
577        self
578    }
579
580    /// Mark this region as required, with an optional custom nudge message.
581    pub fn with_required(mut self, required: bool, message: Option<String>) -> Self {
582        self.required = required;
583        self.required_message = message;
584        self
585    }
586
587    /// Add a schema to this region definition.
588    pub fn with_schema(mut self, schema: RegionSchema) -> Self {
589        self.schema = Some(schema);
590        self
591    }
592
593    /// Add a description to this region definition.
594    pub fn with_description(mut self, description: String) -> Self {
595        self.description = Some(description);
596        self
597    }
598}
599
600#[cfg(test)]
601mod tests {
602    use super::*;
603    use leviath_testkit::with_tracing;
604
605    #[test]
606    fn test_layout_creation() {
607        let regions = vec![
608            RegionDefinition::new("pinned".to_string(), RegionKind::Pinned, 5000),
609            RegionDefinition::new("temp".to_string(), RegionKind::Temporary, 10000),
610        ];
611        let layout = ContextLayout::new(regions, 20000);
612        assert_eq!(layout.regions.len(), 2);
613        assert_eq!(layout.total_budget_tokens, 20000);
614    }
615
616    #[test]
617    fn test_layout_validation() {
618        let regions = vec![RegionDefinition::new(
619            "test".to_string(),
620            RegionKind::Pinned,
621            5000,
622        )];
623        let layout =
624            ContextLayout::new(regions, 10000).with_eviction_order(vec!["test".to_string()]);
625
626        assert!(layout.validate().is_ok());
627    }
628
629    #[test]
630    fn test_duplicate_region_names() {
631        let regions = vec![
632            RegionDefinition::new("test".to_string(), RegionKind::Pinned, 5000),
633            RegionDefinition::new("test".to_string(), RegionKind::Temporary, 3000),
634        ];
635        let layout = ContextLayout::new(regions, 10000);
636
637        assert!(layout.validate().is_err());
638    }
639
640    #[test]
641    fn test_eviction_order_unknown_region_is_error() {
642        let regions = vec![RegionDefinition::new(
643            "test".to_string(),
644            RegionKind::Pinned,
645            5000,
646        )];
647        let layout =
648            ContextLayout::new(regions, 10000).with_eviction_order(vec!["nonexistent".to_string()]);
649
650        let err = layout.validate().unwrap_err();
651        assert_eq!(
652            err,
653            ValidationError::Layout(
654                "eviction order references unknown region: nonexistent".to_string()
655            )
656        );
657    }
658
659    #[test]
660    fn test_validate_warns_but_does_not_error_when_max_tokens_exceed_budget() {
661        // Sum of region max_tokens (5000 + 10000 = 15000) exceeds the total
662        // budget (10000) - this should only warn, not fail validation, since
663        // not all regions are full simultaneously.
664        let regions = vec![
665            RegionDefinition::new("a".to_string(), RegionKind::Pinned, 5000),
666            RegionDefinition::new("b".to_string(), RegionKind::Temporary, 10000),
667        ];
668        let layout = ContextLayout::new(regions, 10000);
669        with_tracing(|| {
670            assert!(layout.validate().is_ok());
671        });
672    }
673
674    #[test]
675    fn validate_errors_when_fixed_regions_starve_working_budget() {
676        // Realistically-sized layout (>= 20k) where a huge fixed (pinned) region
677        // leaves < 8000 working tokens for conversation/tool-results → hard error.
678        let regions = vec![
679            RegionDefinition::new("big_pinned".to_string(), RegionKind::Pinned, 95_000),
680            RegionDefinition::new("work".to_string(), RegionKind::Temporary, 5_000),
681        ];
682        let layout = ContextLayout::new(regions, 100_000);
683        with_tracing(|| {
684            let err = layout.validate().unwrap_err();
685            assert!(
686                err.to_string().contains("working tokens"),
687                "actionable budget error: {err}"
688            );
689        });
690    }
691
692    #[test]
693    fn validate_ok_for_realistic_layout_with_working_room() {
694        let regions = vec![
695            RegionDefinition::new("task".to_string(), RegionKind::Pinned, 4_000),
696            RegionDefinition::new("conversation".to_string(), RegionKind::Temporary, 40_000),
697        ];
698        let layout = ContextLayout::new(regions, 44_000);
699        with_tracing(|| {
700            assert!(layout.validate().is_ok());
701        });
702    }
703
704    fn custom_kind(script: &str, persistent: bool) -> RegionKind {
705        RegionKind::Custom {
706            script: script.to_string(),
707            persistent,
708        }
709    }
710
711    #[test]
712    fn validate_rejects_custom_region_with_empty_script() {
713        // Whitespace-only counts as empty: it could never resolve to a file
714        // and the runtime would silently fall back on every inference.
715        let regions = vec![RegionDefinition::new(
716            "brain".to_string(),
717            custom_kind("   ", false),
718            5000,
719        )];
720        let layout = ContextLayout::new(regions, 10_000);
721        let err = with_tracing(|| layout.validate().unwrap_err());
722        assert!(
723            err.to_string().contains("non-empty script path"),
724            "actionable error: {err}"
725        );
726    }
727
728    #[test]
729    fn validate_counts_persistent_custom_as_fixed_budget() {
730        // A persistent custom region is Pinned-like: protected from eviction,
731        // so it must count toward the fixed budget that can starve the
732        // working room.
733        let regions = vec![
734            RegionDefinition::new("vault".to_string(), custom_kind("v.rhai", true), 95_000),
735            RegionDefinition::new("work".to_string(), RegionKind::Temporary, 5_000),
736        ];
737        let layout = ContextLayout::new(regions, 100_000);
738        let err = with_tracing(|| layout.validate().unwrap_err());
739        assert!(err.to_string().contains("working tokens"), "{err}");
740    }
741
742    #[test]
743    fn validate_counts_non_persistent_custom_as_working_budget() {
744        // Same shape, but the custom region is evictable - it IS the working
745        // room, so validation passes.
746        let regions = vec![
747            RegionDefinition::new("brain".to_string(), custom_kind("b.rhai", false), 95_000),
748            RegionDefinition::new("task".to_string(), RegionKind::Pinned, 4_000),
749        ];
750        let layout = ContextLayout::new(regions, 100_000);
751        with_tracing(|| {
752            assert!(layout.validate().is_ok());
753        });
754    }
755
756    #[test]
757    fn custom_region_satisfies_the_message_region_check() {
758        // A layout whose only region is custom must not trip the "no
759        // SlidingWindow region" warning path - its script can render typed
760        // entries as messages. (Mirrors the sliding-window-present test: the
761        // skip branch is exercised, validation succeeds.)
762        let regions = vec![RegionDefinition::new(
763            "everything".to_string(),
764            custom_kind("all.rhai", false),
765            9_000,
766        )];
767        let layout = ContextLayout::new(regions, 10_000);
768        with_tracing(|| {
769            assert!(layout.validate().is_ok());
770        });
771    }
772
773    #[test]
774    fn resolved_percent_budget_applies_to_custom_region() {
775        // The "recreate built-ins in Rhai" guarantee: percentage budgets work
776        // on custom regions exactly as on built-in kinds, resolved against
777        // the stage model's context window at spawn.
778        let def = RegionDefinition::new("brain".to_string(), custom_kind("b.rhai", false), 0)
779            .with_budget(BudgetSpec::Percent {
780                percent: 0.40,
781                min: Some(10_000),
782                max: None,
783            });
784        let layout = ContextLayout::new(vec![def], 0);
785        let resolved = layout.resolved(200_000);
786        assert_eq!(resolved.regions[0].max_tokens, 80_000);
787        assert!(matches!(
788            resolved.regions[0].kind,
789            RegionKind::Custom { ref script, persistent: false } if script == "b.rhai"
790        ));
791        // The min floor wins on a small window.
792        let small = layout.resolved(8_192);
793        assert_eq!(small.regions[0].max_tokens, 10_000);
794    }
795
796    #[test]
797    fn test_get_region_found() {
798        let regions = vec![
799            RegionDefinition::new("a".to_string(), RegionKind::Pinned, 5000),
800            RegionDefinition::new("b".to_string(), RegionKind::Temporary, 3000),
801        ];
802        let layout = ContextLayout::new(regions, 10000);
803
804        let found = layout.get_region("b").unwrap();
805        assert_eq!(found.name, "b");
806        assert_eq!(found.max_tokens, 3000);
807    }
808
809    #[test]
810    fn test_get_region_not_found() {
811        let regions = vec![RegionDefinition::new(
812            "a".to_string(),
813            RegionKind::Pinned,
814            5000,
815        )];
816        let layout = ContextLayout::new(regions, 10000);
817        assert!(layout.get_region("missing").is_none());
818    }
819
820    #[test]
821    fn test_region_definition_with_schema() {
822        let schema = crate::region::RegionSchema::new(crate::region::ContentFormat::Json);
823        let def =
824            RegionDefinition::new("a".to_string(), RegionKind::Pinned, 5000).with_schema(schema);
825        assert_eq!(
826            def.schema.as_ref().unwrap().format,
827            crate::region::ContentFormat::Json
828        );
829    }
830
831    #[test]
832    fn test_region_definition_with_description() {
833        let def = RegionDefinition::new("a".to_string(), RegionKind::Pinned, 5000)
834            .with_description("holds architecture notes".to_string());
835        assert_eq!(def.description.as_deref(), Some("holds architecture notes"));
836    }
837
838    #[test]
839    fn parse_budget_accepts_plain_and_decimal_percentages() {
840        assert_eq!(BudgetSpec::parse_budget("35%").unwrap(), 0.35);
841        assert_eq!(BudgetSpec::parse_budget("100%").unwrap(), 1.0);
842        assert!((BudgetSpec::parse_budget("0.6%").unwrap() - 0.006).abs() < 1e-9);
843    }
844
845    #[test]
846    fn parse_budget_trims_surrounding_and_inner_whitespace() {
847        assert_eq!(BudgetSpec::parse_budget("  35 %  ").unwrap(), 0.35);
848    }
849
850    #[test]
851    fn parse_budget_rejects_missing_percent_sign() {
852        let err = BudgetSpec::parse_budget("35").unwrap_err();
853        assert!(err.contains("must end with '%'"), "{err}");
854    }
855
856    #[test]
857    fn parse_budget_rejects_non_numeric() {
858        let err = BudgetSpec::parse_budget("abc%").unwrap_err();
859        assert!(err.contains("not a valid number"), "{err}");
860    }
861
862    #[test]
863    fn parse_budget_rejects_zero_and_negative() {
864        let zero = BudgetSpec::parse_budget("0%").unwrap_err();
865        assert!(zero.contains("greater than 0%"), "{zero}");
866        let neg = BudgetSpec::parse_budget("-10%").unwrap_err();
867        assert!(neg.contains("greater than 0%"), "{neg}");
868    }
869
870    #[test]
871    fn parse_budget_rejects_over_one_hundred() {
872        let err = BudgetSpec::parse_budget("150%").unwrap_err();
873        assert!(err.contains("at most 100%"), "{err}");
874    }
875
876    #[test]
877    fn resolve_absolute_ignores_window() {
878        assert_eq!(BudgetSpec::Absolute(4000).resolve(1_000_000), 4000);
879        assert!(!BudgetSpec::Absolute(4000).is_percent());
880    }
881
882    #[test]
883    fn resolve_percent_of_window() {
884        let spec = BudgetSpec::Percent {
885            percent: 0.35,
886            min: None,
887            max: None,
888        };
889        assert_eq!(spec.resolve(1_000_000), 350_000);
890        assert!(spec.is_percent());
891    }
892
893    #[test]
894    fn resolve_percent_applies_max_cap() {
895        let spec = BudgetSpec::Percent {
896            percent: 0.02,
897            min: None,
898            max: Some(4000),
899        };
900        // 2% of 1M = 20_000, capped to 4000.
901        assert_eq!(spec.resolve(1_000_000), 4000);
902    }
903
904    #[test]
905    fn resolve_percent_applies_min_floor() {
906        let spec = BudgetSpec::Percent {
907            percent: 0.02,
908            min: Some(2000),
909            max: None,
910        };
911        // 2% of 8000 = 160, floored to 2000.
912        assert_eq!(spec.resolve(8000), 2000);
913    }
914
915    #[test]
916    fn resolve_percent_within_bounds_takes_neither_clamp() {
917        let spec = BudgetSpec::Percent {
918            percent: 0.10,
919            min: Some(1000),
920            max: Some(50_000),
921        };
922        // 10% of 200k = 20_000, between the floor and cap.
923        assert_eq!(spec.resolve(200_000), 20_000);
924    }
925
926    #[test]
927    fn resolve_percent_floor_wins_when_min_exceeds_max() {
928        let spec = BudgetSpec::Percent {
929            percent: 0.10,
930            min: Some(9000),
931            max: Some(4000),
932        };
933        // 10% of 200k = 20_000 → capped to 4000 → floored up to 9000 (floor wins).
934        assert_eq!(spec.resolve(200_000), 9000);
935    }
936
937    #[test]
938    fn has_percent_budgets_detects_percentage_regions() {
939        let absolute = ContextLayout::new(
940            vec![RegionDefinition::new(
941                "a".to_string(),
942                RegionKind::Pinned,
943                5000,
944            )],
945            5000,
946        );
947        assert!(!absolute.has_percent_budgets());
948
949        let percent = ContextLayout::new(
950            vec![
951                RegionDefinition::new("a".to_string(), RegionKind::Pinned, 5000).with_budget(
952                    BudgetSpec::Percent {
953                        percent: 0.05,
954                        min: None,
955                        max: None,
956                    },
957                ),
958            ],
959            5000,
960        );
961        assert!(percent.has_percent_budgets());
962    }
963
964    #[test]
965    fn resolved_is_noop_for_absolute_layout() {
966        let layout = ContextLayout::new(
967            vec![RegionDefinition::new(
968                "a".to_string(),
969                RegionKind::Pinned,
970                5000,
971            )],
972            5000,
973        );
974        let resolved = layout.resolved(1_000_000);
975        assert_eq!(resolved.regions[0].max_tokens, 5000);
976        // Absolute layout keeps its legacy summed total, not the window.
977        assert_eq!(resolved.total_budget_tokens, 5000);
978    }
979
980    #[test]
981    fn resolved_percent_layout_uses_window_as_total() {
982        let layout = ContextLayout::new(
983            vec![
984                RegionDefinition::new("a".to_string(), RegionKind::Pinned, 0).with_budget(
985                    BudgetSpec::Percent {
986                        percent: 0.10,
987                        min: None,
988                        max: None,
989                    },
990                ),
991            ],
992            0,
993        )
994        .with_eviction_order(vec!["a".to_string()]);
995        let resolved = layout.resolved(1_000_000);
996        assert_eq!(resolved.regions[0].max_tokens, 100_000);
997        assert_eq!(resolved.total_budget_tokens, 1_000_000);
998        // eviction order carried through.
999        assert_eq!(resolved.eviction_order, vec!["a".to_string()]);
1000    }
1001
1002    #[test]
1003    fn resolved_compacting_threshold_all_cases() {
1004        // compact_at + explicit threshold cap → min(pct, cap).
1005        let both = RegionDefinition::new(
1006            "c".to_string(),
1007            RegionKind::Compacting {
1008                threshold_tokens: 25_000,
1009            },
1010            0,
1011        )
1012        .with_budget(BudgetSpec::Percent {
1013            percent: 0.20,
1014            min: None,
1015            max: None,
1016        })
1017        .with_compact_at(0.80);
1018        let r = ContextLayout::new(vec![both], 0).resolved(200_000);
1019        // budget = 40_000; 80% = 32_000; capped to 25_000.
1020        assert_eq!(
1021            r.regions[0].kind,
1022            RegionKind::Compacting {
1023                threshold_tokens: 25_000
1024            }
1025        );
1026
1027        // compact_at with no cap (usize::MAX sentinel) → pct only.
1028        let pct_only = RegionDefinition::new(
1029            "c".to_string(),
1030            RegionKind::Compacting {
1031                threshold_tokens: usize::MAX,
1032            },
1033            0,
1034        )
1035        .with_budget(BudgetSpec::Percent {
1036            percent: 0.20,
1037            min: None,
1038            max: None,
1039        })
1040        .with_compact_at(0.80);
1041        let r = ContextLayout::new(vec![pct_only], 0).resolved(200_000);
1042        assert_eq!(
1043            r.regions[0].kind,
1044            RegionKind::Compacting {
1045                threshold_tokens: 32_000
1046            }
1047        );
1048
1049        // compact_at = None → absolute threshold passes through unchanged.
1050        let absolute = RegionDefinition::new(
1051            "c".to_string(),
1052            RegionKind::Compacting {
1053                threshold_tokens: 8000,
1054            },
1055            10_000,
1056        );
1057        let r = ContextLayout::new(vec![absolute], 10_000).resolved(1_000_000);
1058        assert_eq!(
1059            r.regions[0].kind,
1060            RegionKind::Compacting {
1061                threshold_tokens: 8000
1062            }
1063        );
1064    }
1065
1066    #[test]
1067    fn validate_skips_token_checks_for_percent_layouts() {
1068        // A percentage layout whose provisional max_tokens are tiny/zero must not
1069        // trip the fixed-working-budget hard error - that check is deferred to
1070        // post-resolution. Wrap in tracing so no warn-arg lines read uncovered.
1071        let regions = vec![
1072            RegionDefinition::new("big_pinned".to_string(), RegionKind::Pinned, 0).with_budget(
1073                BudgetSpec::Percent {
1074                    percent: 0.95,
1075                    min: None,
1076                    max: None,
1077                },
1078            ),
1079        ];
1080        let layout = ContextLayout::new(regions, 100_000);
1081        with_tracing(|| {
1082            assert!(layout.validate().is_ok());
1083        });
1084    }
1085
1086    #[test]
1087    fn region_definition_default_budget_matches_max_tokens() {
1088        let def = RegionDefinition::new("a".to_string(), RegionKind::Pinned, 5000);
1089        assert_eq!(def.budget, BudgetSpec::Absolute(5000));
1090        assert_eq!(def.compact_at, None);
1091    }
1092
1093    #[test]
1094    fn budget_spec_default_is_absolute_zero() {
1095        assert_eq!(BudgetSpec::default(), BudgetSpec::Absolute(0));
1096    }
1097
1098    #[test]
1099    fn test_validate_with_sliding_window_present() {
1100        // A layout that DOES contain a SlidingWindow region exercises the
1101        // has_sliding_window detection returning true, so the "no sliding
1102        // window" warning branch is skipped.
1103        let regions = vec![
1104            RegionDefinition::new("pinned".to_string(), RegionKind::Pinned, 5000),
1105            RegionDefinition::new(
1106                "conv".to_string(),
1107                RegionKind::SlidingWindow {
1108                    max_items: 50,
1109                    eviction_strategy: crate::region::EvictionStrategy::PerItem,
1110                },
1111                5000,
1112            ),
1113        ];
1114        let layout = ContextLayout::new(regions, 20000);
1115        with_tracing(|| {
1116            assert!(layout.validate().is_ok());
1117        });
1118    }
1119}