Skip to main content

merry_runtime/runtime/
config.rs

1use crate::{
2    AUTO_COMPACT_THRESHOLD_PERCENT, CitationCompactionPolicy, CompactionError, CompactionPrompt,
3};
4use merry_llm::ReasoningEffort;
5use std::num::{NonZeroU64, NonZeroUsize};
6
7/// Policy governing how compacted session history is retained in memory and on disk.
8///
9/// Orthogonal to persistence (`session_store`):
10/// - [`Self::Archive`] (the default) retains compacted history cleanly:
11///   - When a `session_store` is attached, compaction always rotates turns `<= compacted_through`
12///     out of hot memory and live `journal.jsonl` into `<session_dir>/archive/seg_NNNN.jsonl`
13///     (plus a unified deterministic Markdown archive `seg_NNNN.md` + `INDEX.md` when enabled),
14///     keeping startup and hot RAM bounded. By default there is no segment or byte cap, so full
15///     history is preserved; optional `max_segments` / `max_bytes` caps enable rolling eviction
16///     and orphan image GC for long-lived bots.
17///   - When no `session_store` is attached, nothing is written to disk and turns stay in memory
18///     so history is not silently discarded.
19/// - [`Self::ContextOnly`] retains only the active post-compaction tail and checkpoint summary:
20///   prunes compacted turns from hot memory, rewrites `journal.jsonl` when persisted, deletes
21///   unreferenced sidecar images, and writes no `archive/` files.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum HistoryRetention {
24    /// Rotate compacted segments into `<session_dir>/archive/` when persisted
25    /// (unbounded by default; optionally capped via [`ArchiveConfig`]).
26    Archive(ArchiveConfig),
27    /// Retain only the active post-compaction tail and compacted checkpoint summary.
28    ContextOnly,
29}
30
31impl Default for HistoryRetention {
32    fn default() -> Self {
33        Self::Archive(ArchiveConfig::new())
34    }
35}
36
37impl HistoryRetention {
38    /// Retains all compacted history in `<session_dir>/archive/` with no retention cap.
39    #[must_use]
40    pub const fn archive() -> Self {
41        Self::Archive(ArchiveConfig::new())
42    }
43
44    /// Retains compacted history in `<session_dir>/archive/` using custom [`ArchiveConfig`].
45    #[must_use]
46    pub const fn archive_with(config: ArchiveConfig) -> Self {
47        Self::Archive(config)
48    }
49
50    /// Retains only the active context tail and compaction summary.
51    #[must_use]
52    pub const fn context_only() -> Self {
53        Self::ContextOnly
54    }
55
56    /// Whether compacted turns should be pruned from hot memory (and rotated on disk when stored).
57    #[must_use]
58    pub(crate) const fn prunes_compacted_history(&self, has_session_store: bool) -> bool {
59        match self {
60            Self::ContextOnly => true,
61            Self::Archive(_) => has_session_store,
62        }
63    }
64
65    /// Returns archive settings when [`Self::Archive`] is active.
66    #[must_use]
67    pub const fn archive_config(&self) -> Option<ArchiveConfig> {
68        match self {
69            Self::Archive(config) => Some(*config),
70            Self::ContextOnly => None,
71        }
72    }
73}
74
75/// Configuration for [`HistoryRetention::Archive`].
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub struct ArchiveConfig {
78    max_segments: Option<NonZeroUsize>,
79    max_bytes: Option<NonZeroU64>,
80    export_markdown: bool,
81}
82
83impl ArchiveConfig {
84    /// Creates archive settings with deterministic Markdown export enabled and no size cap.
85    #[must_use]
86    pub const fn new() -> Self {
87        Self {
88            max_segments: None,
89            max_bytes: None,
90            export_markdown: true,
91        }
92    }
93
94    /// Sets the maximum number of archived segments to retain on disk.
95    #[must_use]
96    pub const fn with_max_segments(mut self, max_segments: Option<NonZeroUsize>) -> Self {
97        self.max_segments = max_segments;
98        self
99    }
100
101    /// Sets the maximum total byte size across archived segment files.
102    #[must_use]
103    pub const fn with_max_bytes(mut self, max_bytes: Option<NonZeroU64>) -> Self {
104        self.max_bytes = max_bytes;
105        self
106    }
107
108    /// Enables or disables deterministic Markdown archive export (`seg_NNNN.md` + `INDEX.md`).
109    #[must_use]
110    pub const fn with_export_markdown(mut self, export_markdown: bool) -> Self {
111        self.export_markdown = export_markdown;
112        self
113    }
114
115    /// Maximum number of archived segments retained on disk, if bounded.
116    #[must_use]
117    pub const fn max_segments(&self) -> Option<NonZeroUsize> {
118        self.max_segments
119    }
120
121    /// Maximum total bytes retained across archived segment files, if bounded.
122    #[must_use]
123    pub const fn max_bytes(&self) -> Option<NonZeroU64> {
124        self.max_bytes
125    }
126
127    /// Whether deterministic Markdown archives (`seg_NNNN.md` + `INDEX.md`) are written.
128    #[must_use]
129    pub const fn export_markdown(&self) -> bool {
130        self.export_markdown
131    }
132}
133
134impl Default for ArchiveConfig {
135    fn default() -> Self {
136        Self::new()
137    }
138}
139
140fn default_automatic_compaction_policy() -> CitationCompactionPolicy {
141    CitationCompactionPolicy::default()
142}
143
144/// Runtime-owned policy for checkpoint compaction.
145///
146/// `enabled`, `policy`, and `trigger_threshold_percent` drive automatic compaction before
147/// a provider request. Manual [`crate::Runtime::compact_context`] calls default to this
148/// configured policy (and accept a per-call override), while
149/// [`crate::Runtime::compact_context_once`] always requires an explicit
150/// [`CitationCompactionPolicy`].
151///
152/// `reasoning_effort` and `prompt` are not path-specific: they apply to every compaction
153/// request, automatic or manual, which is why this type is named for compaction
154/// rather than for one of its callers.
155///
156/// Compaction is a summarization turn over the whole covered window, so it never
157/// inherits the primary model's reasoning effort: a primary tuned for hard
158/// coding turns can spend its entire output budget reasoning about history and
159/// never write the checkpoint. `None` leaves the provider default in place.
160#[derive(Debug, Clone, PartialEq, Eq)]
161pub struct CompactionConfig {
162    enabled: bool,
163    policy: CitationCompactionPolicy,
164    reasoning_effort: Option<ReasoningEffort>,
165    trigger_threshold_percent: u8,
166    prompt: CompactionPrompt,
167}
168
169impl CompactionConfig {
170    /// Enables automatic compaction with the provided policy.
171    #[must_use]
172    pub fn enabled(policy: CitationCompactionPolicy) -> Self {
173        Self {
174            enabled: true,
175            policy,
176            reasoning_effort: None,
177            trigger_threshold_percent: AUTO_COMPACT_THRESHOLD_PERCENT,
178            prompt: CompactionPrompt::default(),
179        }
180    }
181
182    /// Disables automatic compaction.
183    ///
184    /// The policy remains populated with defaults so disabled configs can be
185    /// inspected or re-enabled by callers without constructing a dummy policy.
186    #[must_use]
187    pub fn disabled() -> Self {
188        Self {
189            enabled: false,
190            policy: default_automatic_compaction_policy(),
191            reasoning_effort: None,
192            trigger_threshold_percent: AUTO_COMPACT_THRESHOLD_PERCENT,
193            prompt: CompactionPrompt::default(),
194        }
195    }
196
197    #[must_use]
198    pub const fn is_enabled(&self) -> bool {
199        self.enabled
200    }
201
202    #[must_use]
203    pub const fn policy(&self) -> CitationCompactionPolicy {
204        self.policy
205    }
206
207    /// Replaces the summary acceptance and retention policy.
208    #[must_use]
209    pub const fn with_policy(mut self, policy: CitationCompactionPolicy) -> Self {
210        self.policy = policy;
211        self
212    }
213
214    /// Returns a copy configured with a reasoning-effort level for compaction.
215    #[must_use]
216    pub fn with_reasoning_effort(mut self, reasoning_effort: Option<ReasoningEffort>) -> Self {
217        self.reasoning_effort = reasoning_effort;
218        self
219    }
220
221    /// Optional reasoning-effort level for compaction model requests.
222    #[must_use]
223    pub fn reasoning_effort(&self) -> Option<&ReasoningEffort> {
224        self.reasoning_effort.as_ref()
225    }
226
227    /// Sets the dynamic-body usage percentage (`1..=100`) that triggers automatic compaction.
228    ///
229    /// Defaults to [`AUTO_COMPACT_THRESHOLD_PERCENT`] (`85`).
230    pub fn with_trigger_threshold_percent(mut self, percent: u8) -> Result<Self, CompactionError> {
231        if !(1..=100).contains(&percent) {
232            return Err(CompactionError::InvalidTriggerThresholdPercent { percent });
233        }
234        self.trigger_threshold_percent = percent;
235        Ok(self)
236    }
237
238    /// Dynamic-body usage percentage (`1..=100`) that triggers automatic compaction.
239    #[must_use]
240    pub const fn trigger_threshold_percent(&self) -> u8 {
241        self.trigger_threshold_percent
242    }
243
244    /// Sets the prompt configuration applied to both automatic and manual compaction requests.
245    #[must_use]
246    pub fn with_prompt(mut self, prompt: CompactionPrompt) -> Self {
247        self.prompt = prompt;
248        self
249    }
250
251    /// Prompt configuration applied to automatic and manual compaction requests.
252    #[must_use]
253    pub fn prompt(&self) -> &CompactionPrompt {
254        &self.prompt
255    }
256}
257
258impl Default for CompactionConfig {
259    fn default() -> Self {
260        Self::enabled(default_automatic_compaction_policy())
261    }
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267
268    #[test]
269    fn compaction_config_validates_trigger_threshold_bounds() {
270        assert_eq!(
271            CompactionConfig::default().with_trigger_threshold_percent(0),
272            Err(CompactionError::InvalidTriggerThresholdPercent { percent: 0 })
273        );
274        assert_eq!(
275            CompactionConfig::default().with_trigger_threshold_percent(101),
276            Err(CompactionError::InvalidTriggerThresholdPercent { percent: 101 })
277        );
278        let low = CompactionConfig::default()
279            .with_trigger_threshold_percent(1)
280            .expect("1% should be valid");
281        assert_eq!(low.trigger_threshold_percent(), 1);
282        let high = CompactionConfig::default()
283            .with_trigger_threshold_percent(100)
284            .expect("100% should be valid");
285        assert_eq!(high.trigger_threshold_percent(), 100);
286    }
287
288    #[test]
289    fn compaction_prompt_sanitizes_fields_and_rejects_blank() {
290        assert_eq!(
291            CompactionPrompt::custom("  \r\n\t\x00 "),
292            Err(CompactionError::EmptyPromptField {
293                field: "instructions"
294            })
295        );
296        assert_eq!(
297            CompactionPrompt::default().with_user_context("  \r\n\t\x00 "),
298            Err(CompactionError::EmptyPromptField {
299                field: "user_context"
300            })
301        );
302        let prompt = CompactionPrompt::custom("Line 1\r\nLine\x00 2")
303            .expect("non-blank instructions should sanitize")
304            .with_user_context("Keep\x00 auth\r\ninvariants")
305            .expect("non-blank user context should sanitize");
306        let configured = CompactionConfig::default().with_prompt(prompt);
307        assert_eq!(configured.prompt().instructions(), Some("Line 1\nLine 2"));
308        assert_eq!(
309            configured.prompt().user_context(),
310            Some("Keep auth\ninvariants")
311        );
312
313        let reset = configured.with_prompt(CompactionPrompt::default());
314        assert_eq!(reset.prompt().instructions(), None);
315        assert_eq!(reset.prompt().user_context(), None);
316    }
317}