Skip to main content

merry_runtime/runtime/
config.rs

1use crate::CitationCompactionPolicy;
2use merry_llm::ReasoningEffort;
3use std::num::{NonZeroU64, NonZeroUsize};
4
5/// Policy governing how compacted session history is retained in memory and on disk.
6///
7/// Orthogonal to persistence (`session_store`):
8/// - [`Self::Archive`] (the default) retains compacted history cleanly:
9///   - When a `session_store` is attached, compaction always rotates turns `<= compacted_through`
10///     out of hot memory and live `journal.jsonl` into `<session_dir>/archive/seg_NNNN.jsonl`
11///     (plus a unified deterministic Markdown archive `seg_NNNN.md` + `INDEX.md` when enabled),
12///     keeping startup and hot RAM bounded. By default there is no segment or byte cap, so full
13///     history is preserved; optional `max_segments` / `max_bytes` caps enable rolling eviction
14///     and orphan image GC for long-lived bots.
15///   - When no `session_store` is attached, nothing is written to disk and turns stay in memory
16///     so history is not silently discarded.
17/// - [`Self::ContextOnly`] retains only the active post-compaction tail and checkpoint summary:
18///   prunes compacted turns from hot memory, rewrites `journal.jsonl` when persisted, deletes
19///   unreferenced sidecar images, and writes no `archive/` files.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum HistoryRetention {
22    /// Rotate compacted segments into `<session_dir>/archive/` when persisted
23    /// (unbounded by default; optionally capped via [`ArchiveConfig`]).
24    Archive(ArchiveConfig),
25    /// Retain only the active post-compaction tail and compacted checkpoint summary.
26    ContextOnly,
27}
28
29impl Default for HistoryRetention {
30    fn default() -> Self {
31        Self::Archive(ArchiveConfig::new())
32    }
33}
34
35impl HistoryRetention {
36    /// Retains all compacted history in `<session_dir>/archive/` with no retention cap.
37    #[must_use]
38    pub const fn archive() -> Self {
39        Self::Archive(ArchiveConfig::new())
40    }
41
42    /// Retains compacted history in `<session_dir>/archive/` using custom [`ArchiveConfig`].
43    #[must_use]
44    pub const fn archive_with(config: ArchiveConfig) -> Self {
45        Self::Archive(config)
46    }
47
48    /// Retains only the active context tail and compaction summary.
49    #[must_use]
50    pub const fn context_only() -> Self {
51        Self::ContextOnly
52    }
53
54    /// Whether compacted turns should be pruned from hot memory (and rotated on disk when stored).
55    #[must_use]
56    pub(crate) const fn prunes_compacted_history(&self, has_session_store: bool) -> bool {
57        match self {
58            Self::ContextOnly => true,
59            Self::Archive(_) => has_session_store,
60        }
61    }
62
63    /// Returns archive settings when [`Self::Archive`] is active.
64    #[must_use]
65    pub const fn archive_config(&self) -> Option<ArchiveConfig> {
66        match self {
67            Self::Archive(config) => Some(*config),
68            Self::ContextOnly => None,
69        }
70    }
71}
72
73/// Configuration for [`HistoryRetention::Archive`].
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub struct ArchiveConfig {
76    max_segments: Option<NonZeroUsize>,
77    max_bytes: Option<NonZeroU64>,
78    export_markdown: bool,
79}
80
81impl ArchiveConfig {
82    /// Creates archive settings with deterministic Markdown export enabled and no size cap.
83    #[must_use]
84    pub const fn new() -> Self {
85        Self {
86            max_segments: None,
87            max_bytes: None,
88            export_markdown: true,
89        }
90    }
91
92    /// Sets the maximum number of archived segments to retain on disk.
93    #[must_use]
94    pub const fn with_max_segments(mut self, max_segments: Option<NonZeroUsize>) -> Self {
95        self.max_segments = max_segments;
96        self
97    }
98
99    /// Sets the maximum total byte size across archived segment files.
100    #[must_use]
101    pub const fn with_max_bytes(mut self, max_bytes: Option<NonZeroU64>) -> Self {
102        self.max_bytes = max_bytes;
103        self
104    }
105
106    /// Enables or disables deterministic Markdown archive export (`seg_NNNN.md` + `INDEX.md`).
107    #[must_use]
108    pub const fn with_export_markdown(mut self, export_markdown: bool) -> Self {
109        self.export_markdown = export_markdown;
110        self
111    }
112
113    /// Maximum number of archived segments retained on disk, if bounded.
114    #[must_use]
115    pub const fn max_segments(&self) -> Option<NonZeroUsize> {
116        self.max_segments
117    }
118
119    /// Maximum total bytes retained across archived segment files, if bounded.
120    #[must_use]
121    pub const fn max_bytes(&self) -> Option<NonZeroU64> {
122        self.max_bytes
123    }
124
125    /// Whether deterministic Markdown archives (`seg_NNNN.md` + `INDEX.md`) are written.
126    #[must_use]
127    pub const fn export_markdown(&self) -> bool {
128        self.export_markdown
129    }
130}
131
132impl Default for ArchiveConfig {
133    fn default() -> Self {
134        Self::new()
135    }
136}
137
138fn default_automatic_compaction_policy() -> CitationCompactionPolicy {
139    CitationCompactionPolicy::default()
140}
141
142/// Runtime-owned policy for checkpoint compaction.
143///
144/// `enabled` and `policy` drive automatic compaction before a provider request. Manual
145/// [`crate::Runtime::compact_context_once`] calls still take an explicit
146/// [`CitationCompactionPolicy`] so tests and callers can run one-off compaction
147/// passes without mutating runtime construction policy.
148///
149/// `reasoning_effort` is not path-specific: it applies to every compaction
150/// request, automatic or manual, which is why this type is named for compaction
151/// rather than for one of its callers.
152///
153/// Compaction is a summarization turn over the whole covered window, so it never
154/// inherits the primary model's reasoning effort: a primary tuned for hard
155/// coding turns can spend its entire output budget reasoning about history and
156/// never write the checkpoint. `None` leaves the provider default in place.
157#[derive(Debug, Clone, PartialEq, Eq)]
158pub struct CompactionConfig {
159    enabled: bool,
160    policy: CitationCompactionPolicy,
161    reasoning_effort: Option<ReasoningEffort>,
162}
163
164impl CompactionConfig {
165    /// Enables automatic compaction with the provided policy.
166    #[must_use]
167    pub fn enabled(policy: CitationCompactionPolicy) -> Self {
168        Self {
169            enabled: true,
170            policy,
171            reasoning_effort: None,
172        }
173    }
174
175    /// Disables automatic compaction.
176    ///
177    /// The policy remains populated with defaults so disabled configs can be
178    /// inspected or re-enabled by callers without constructing a dummy policy.
179    #[must_use]
180    pub fn disabled() -> Self {
181        Self {
182            enabled: false,
183            policy: default_automatic_compaction_policy(),
184            reasoning_effort: None,
185        }
186    }
187
188    #[must_use]
189    pub const fn is_enabled(&self) -> bool {
190        self.enabled
191    }
192
193    #[must_use]
194    pub const fn policy(&self) -> CitationCompactionPolicy {
195        self.policy
196    }
197
198    /// Returns a copy configured with a reasoning-effort level for compaction.
199    #[must_use]
200    pub fn with_reasoning_effort(mut self, reasoning_effort: Option<ReasoningEffort>) -> Self {
201        self.reasoning_effort = reasoning_effort;
202        self
203    }
204
205    /// Optional reasoning-effort level for compaction model requests.
206    #[must_use]
207    pub fn reasoning_effort(&self) -> Option<&ReasoningEffort> {
208        self.reasoning_effort.as_ref()
209    }
210}
211
212impl Default for CompactionConfig {
213    fn default() -> Self {
214        Self::enabled(default_automatic_compaction_policy())
215    }
216}