Skip to main content

merry_runtime/compaction/
summary.rs

1//! Prose compaction summary: prompt, salvage, and continuation text.
2//!
3//! The prompt is grok-build's full-replace handoff. The model is asked for one
4//! `<summary>` block. Acceptance does not require the numbered sections,
5//! balanced tags, or JSON. Only an empty cleaned result is retried; a short
6//! summary that still carries the task is installed, because a failed
7//! compaction would block the next turn.
8
9use crate::{CompactionError, normalize_line_endings, sanitize_freeform_text};
10
11/// Optional prompt customization for automatic and manual compaction requests.
12///
13/// By default, compaction uses Merry's built-in handoff summary instructions.
14/// Callers can:
15/// - Keep the built-in instructions and attach persistent [`Self::with_user_context`]
16///   guidance applied to both automatic and manual compactions.
17/// - Replace the summary instructions with [`Self::custom`] (plain text or Markdown;
18///   `<summary>` tags are optional and never required), optionally adding persistent
19///   [`Self::with_user_context`].
20///
21/// When manual compaction also supplies per-call focus text, the runtime merges it
22/// after any persistent `user_context` so caller focus is never lost.
23#[derive(Debug, Clone, Default, PartialEq, Eq)]
24pub struct CompactionPrompt {
25    instructions: Option<String>,
26    user_context: Option<String>,
27}
28
29impl CompactionPrompt {
30    /// Creates a prompt that replaces the built-in summary instructions with custom text.
31    ///
32    /// Line endings are normalized and disallowed control characters are stripped.
33    /// Blank text is rejected.
34    pub fn custom(instructions: impl Into<String>) -> Result<Self, CompactionError> {
35        let cleaned = sanitize_compaction_prompt_text("instructions", instructions.into())?;
36        Ok(Self {
37            instructions: Some(cleaned),
38            user_context: None,
39        })
40    }
41
42    /// Attaches persistent user-context guidance applied to every compaction request.
43    ///
44    /// Works with both the built-in default instructions (`CompactionPrompt::default()`)
45    /// and custom instructions (`CompactionPrompt::custom(...)`). Line endings are
46    /// normalized and disallowed control characters are stripped; blank text is rejected.
47    pub fn with_user_context(
48        mut self,
49        user_context: impl Into<String>,
50    ) -> Result<Self, CompactionError> {
51        let cleaned = sanitize_compaction_prompt_text("user_context", user_context.into())?;
52        self.user_context = Some(cleaned);
53        Ok(self)
54    }
55
56    /// Custom summary instructions, if set (`None` uses the built-in template).
57    #[must_use]
58    pub fn instructions(&self) -> Option<&str> {
59        self.instructions.as_deref()
60    }
61
62    /// Persistent user-context guidance applied to automatic and manual compaction.
63    #[must_use]
64    pub fn user_context(&self) -> Option<&str> {
65        self.user_context.as_deref()
66    }
67}
68
69fn sanitize_compaction_prompt_text(
70    field: &'static str,
71    text: String,
72) -> Result<String, CompactionError> {
73    let cleaned = match normalize_line_endings(&text) {
74        std::borrow::Cow::Borrowed(borrowed) => match sanitize_freeform_text(borrowed) {
75            std::borrow::Cow::Borrowed(_) => text,
76            std::borrow::Cow::Owned(sanitized) => sanitized,
77        },
78        std::borrow::Cow::Owned(normalized) => sanitize_freeform_text(&normalized).into_owned(),
79    };
80    if cleaned.trim().is_empty() {
81        return Err(CompactionError::EmptyPromptField { field });
82    }
83    Ok(cleaned)
84}
85
86/// Instructions appended to a compaction request.
87///
88/// `user_context` is optional text from an explicit compact request. Automatic
89/// compaction passes `None`. The covered conversation is already in the request
90/// ahead of this text, or in the passive history block when the full request
91/// does not fit.
92pub fn citation_compaction_tail_directive(user_context: Option<&str>) -> String {
93    citation_compaction_tail_directive_with_prompt(&CompactionPrompt::default(), user_context)
94}
95
96/// Instructions appended to a compaction request using a typed [`CompactionPrompt`].
97///
98/// Persistent `prompt.user_context()` and any per-call `user_context` (from manual
99/// compaction) are merged automatically into a dedicated user-context section. When
100/// `prompt.instructions()` is `None`, the built-in full-replace summary prompt is used;
101/// otherwise the custom instructions are emitted verbatim followed by any active
102/// user-context section.
103pub(crate) fn citation_compaction_tail_directive_with_prompt(
104    prompt: &CompactionPrompt,
105    user_context: Option<&str>,
106) -> String {
107    const USER_CONTEXT_PLACEHOLDER: &str = "{user_context_section}";
108    let persistent_context = prompt
109        .user_context()
110        .map(str::trim)
111        .filter(|text| !text.is_empty());
112    let call_context = user_context.map(str::trim).filter(|text| !text.is_empty());
113    let combined_context = match (persistent_context, call_context) {
114        (Some(persistent), Some(call)) => Some(format!("{persistent}\n\n{call}")),
115        (Some(persistent), None) => Some(persistent.to_owned()),
116        (None, Some(call)) => Some(call.to_owned()),
117        (None, None) => None,
118    };
119    let user_context_section = match combined_context {
120        Some(context) => format!(
121            "\n\n**User-provided context for this compaction:**\n{context}\n\nPlease incorporate this context into your summary, ensuring it is prominently addressed in the relevant sections.\n\n"
122        ),
123        None => String::new(),
124    };
125    match prompt.instructions() {
126        Some(instructions) if user_context_section.is_empty() => instructions.to_owned(),
127        Some(instructions) => {
128            format!(
129                "{}{}",
130                instructions.trim_end(),
131                user_context_section.trim_end()
132            )
133        }
134        None => include_str!("templates/full_replace_summary_prompt.txt")
135            .replace(USER_CONTEXT_PLACEHOLDER, &user_context_section),
136    }
137}
138
139/// Cleans model output into the text that seeds the next turn.
140///
141/// Leading `<analysis>` scratchpads are removed. A `<summary>` wrapper becomes
142/// plain text. Tags quoted inside the body are neutralized. Plain text with no
143/// tags is kept. Control characters other than newline and tab are stripped so
144/// a messy answer can still be stored.
145pub(crate) fn format_compact_summary(summary: &str) -> String {
146    let mut result = summary.to_string();
147
148    while let Some(start) = result.find("<analysis>") {
149        let is_leading = match result.find("<summary>") {
150            Some(summary_at) => {
151                start < summary_at
152                    || result[summary_at + "<summary>".len()..start]
153                        .trim()
154                        .is_empty()
155            }
156            None => result[..start].trim().is_empty(),
157        };
158        if !is_leading {
159            break;
160        }
161        match result[start..].find("</analysis>") {
162            Some(relative) => {
163                let end = start + relative + "</analysis>".len();
164                result = format!("{}{}", &result[..start], &result[end..]);
165            }
166            None => {
167                let drop_to = result[start..]
168                    .find("<summary>")
169                    .map_or(result.len(), |relative| start + relative);
170                result = format!("{}{}", &result[..start], &result[drop_to..]);
171                break;
172            }
173        }
174    }
175
176    if let Some(start) = result.find("<summary>")
177        && let Some(end) = result.rfind("</summary>")
178        && end > start
179    {
180        let before = result[..start].to_string();
181        let after = result[end + "</summary>".len()..].to_string();
182        let inner = strip_leading_scratchpad(result[start + "<summary>".len()..end].trim());
183        result = format!("{before}Summary:\n{inner}{after}");
184    } else if let Some(start) = result.find("<summary>") {
185        result = result[start + "<summary>".len()..].to_string();
186    }
187
188    result = neutralize_control_tokens(&result);
189    result = strip_disallowed_controls(&result);
190    while result.contains("\n\n\n") {
191        result = result.replace("\n\n\n", "\n\n");
192    }
193    result.trim().to_string()
194}
195
196/// A cleaned summary that is too small to replace the covered conversation.
197pub(crate) fn is_degenerate_summary(raw_summary: &str) -> bool {
198    format_compact_summary(raw_summary).is_empty()
199}
200
201/// Continuation text installed in place of the covered turns.
202pub(crate) fn format_continuation(cleaned_summary: &str, segment_hint: Option<&str>) -> String {
203    let mut text = format!(
204        "This session is being continued from a previous conversation that ran out of context. \
205         The summary below covers the earlier portion of the conversation.\n\n{cleaned_summary}"
206    );
207    if let Some(hint) = segment_hint {
208        text.push_str("\n\n");
209        text.push_str(hint);
210    }
211    text
212}
213
214fn strip_leading_scratchpad(inner: &str) -> String {
215    let mut text = inner.trim();
216    let lead = text.trim_start_matches(['#', '*', '-', '>', ' ', '\t']);
217    if !lead.starts_with(|character: char| character.is_ascii_digit())
218        && let Some(position) = text.rfind("</analysis>")
219    {
220        text = text[position + "</analysis>".len()..].trim_start();
221    }
222    if let Some(rest) = text.strip_prefix("<summary>") {
223        text = rest.trim_start();
224    }
225    text.to_string()
226}
227
228fn neutralize_control_tokens(text: &str) -> String {
229    text.replace("</summary>", "<\u{200b}/summary>")
230        .replace("<summary>", "<\u{200b}summary>")
231        .replace("</analysis>", "<\u{200b}/analysis>")
232        .replace("<analysis>", "<\u{200b}analysis>")
233        .replace("</summary_request>", "<\u{200b}/summary_request>")
234        .replace("<summary_request>", "<\u{200b}summary_request>")
235}
236
237fn strip_disallowed_controls(text: &str) -> String {
238    text.chars()
239        .filter(|character| !character.is_control() || *character == '\n' || *character == '\t')
240        .collect()
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246
247    #[test]
248    fn plain_text_is_kept() {
249        assert_eq!(
250            format_compact_summary("Just plain text summary."),
251            "Just plain text summary."
252        );
253    }
254
255    #[test]
256    fn analysis_scratchpad_is_dropped_and_summary_body_kept() {
257        let input = "<analysis>\nThinking about the problem...\n</analysis>\n\n<summary>\n1. Primary Request: Fix the bug\n</summary>";
258        let result = format_compact_summary(input);
259        assert!(!result.contains("Thinking about the problem"));
260        assert!(result.contains("Summary:\n1. Primary Request: Fix the bug"));
261        assert!(!result.contains("<analysis>"));
262        assert!(!result.contains("<summary>"));
263    }
264
265    #[test]
266    fn unclosed_summary_keeps_the_body() {
267        let result = format_compact_summary(
268            "<summary>\n1. Primary Request: do the thing\n9. Optional Next Step: continue",
269        );
270        assert!(result.contains("1. Primary Request: do the thing"));
271        assert!(result.contains("9. Optional Next Step: continue"));
272    }
273
274    #[test]
275    fn quoted_summary_tag_does_not_truncate_later_sections() {
276        let raw = "<summary>\n1. Primary Request and Intent: build app\n6. All user messages: respond with ONLY the <summary> block.\n9. Optional Next Step: rerun\n</summary>";
277        let result = format_compact_summary(raw);
278        assert!(result.contains("1. Primary Request and Intent: build app"));
279        assert!(result.contains("9. Optional Next Step: rerun"));
280        assert!(!result.contains("<summary>"));
281    }
282
283    #[test]
284    fn empty_summary_is_degenerate_and_a_short_one_is_kept() {
285        assert!(is_degenerate_summary(
286            "<analysis>\nonly scratchpad\n</analysis>"
287        ));
288        assert!(is_degenerate_summary("   \n\t"));
289        assert!(!is_degenerate_summary(
290            "<summary>\n1. Primary Request: q\n</summary>"
291        ));
292    }
293
294    #[test]
295    fn continuation_names_the_segment_directory_when_one_was_written() {
296        let text = format_continuation("kept the auth decision", Some("read /tmp/compaction"));
297        assert!(text.contains("continued from a previous conversation"));
298        assert!(text.contains("kept the auth decision"));
299        assert!(text.contains("read /tmp/compaction"));
300    }
301}