Skip to main content

agentmux_srv_core/backend/
continuity_sections.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The running summary (`continuity_state.rs`) as sections, so a summary that is
5//! too long is shortened by what it can spare, never by where it happens to end
6//! (SPEC_AGENT_PREP_BEFORE_SESSION_RESTART_2026_11_14.md ยง6).
7//!
8//! The summary is a list of `## ` sections. A plain cut at a character count
9//! lands in whichever section holds that character: with long "Done" lists that
10//! is "In flight", and the identifiers at the end are lost first. Here the
11//! sections that say where the work stands are never cut, and the others lose
12//! their oldest items first, with a count of what went.
13
14/// Only these are ever shortened, in this order, oldest items first. Every other
15/// section is kept whole: the person's goal and last request, what is in flight,
16/// what waits on them, the identifiers and their preferences.
17const SHRINKABLE: [&str; 3] = ["done (unverified)", "done (verified)", "decisions and why"];
18/// The order the packet prints the sections in, whatever order the summarizer
19/// wrote them: where the work stands first, the finished work last.
20const PACKET_ORDER: [&str; 9] = [
21    "current goal",
22    "last user request",
23    "in flight",
24    "waiting on the user",
25    "exact identifiers",
26    "decisions and why",
27    "user preferences",
28    "done (unverified)",
29    "done (verified)",
30];
31
32struct Section {
33    /// The `## ` line, without its newline; empty for text before the first heading.
34    heading: String,
35    /// The lines under it.
36    body: Vec<String>,
37}
38
39impl Section {
40    fn name(&self) -> String {
41        self.heading.trim_start_matches('#').trim().to_ascii_lowercase()
42    }
43    fn is(&self, name: &str) -> bool {
44        self.name().starts_with(name)
45    }
46    fn chars(&self) -> usize {
47        self.render().chars().count()
48    }
49    fn render(&self) -> String {
50        let mut out = String::new();
51        if !self.heading.is_empty() {
52            out.push_str(&self.heading);
53            out.push('\n');
54        }
55        for line in &self.body {
56            out.push_str(line);
57            out.push('\n');
58        }
59        out
60    }
61}
62
63fn parse(text: &str) -> Vec<Section> {
64    let mut sections: Vec<Section> = Vec::new();
65    for line in text.lines() {
66        if line.starts_with("## ") {
67            sections.push(Section { heading: line.to_string(), body: Vec::new() });
68        } else {
69            if sections.is_empty() {
70                sections.push(Section { heading: String::new(), body: Vec::new() });
71            }
72            sections.last_mut().expect("a section was just pushed").body.push(line.to_string());
73        }
74    }
75    sections
76}
77
78fn render(sections: &[Section]) -> String {
79    sections.iter().map(Section::render).collect::<String>().trim_end().to_string()
80}
81
82/// The notice a shortened section carries on its first line.
83fn omitted_line(n: usize) -> String {
84    format!("({n} older items omitted)")
85}
86
87/// `n` from a notice line written by [`omitted_line`].
88fn omitted_count(line: &str) -> Option<usize> {
89    line.trim().strip_prefix('(')?.strip_suffix(" older items omitted)")?.parse().ok()
90}
91
92/// Whether `line` opens a list item, as opposed to continuing the one before it.
93fn starts_item(line: &str) -> bool {
94    let t = line.trim_start();
95    if line.starts_with([' ', '\t']) {
96        return false;
97    }
98    t.starts_with("- ")
99        || t.starts_with("* ")
100        || t.starts_with("+ ")
101        || t.split_once(". ").is_some_and(|(n, _)| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()))
102}
103
104/// `body` as the lines before its first item, then one entry per item (its
105/// wrapped lines with it).
106fn items(body: &[String]) -> (Vec<String>, Vec<Vec<String>>) {
107    let mut lead: Vec<String> = Vec::new();
108    let mut items: Vec<Vec<String>> = Vec::new();
109    for line in body {
110        if starts_item(line) {
111            items.push(vec![line.clone()]);
112        } else if let Some(last) = items.last_mut() {
113            last.push(line.clone());
114        } else {
115            lead.push(line.clone());
116        }
117    }
118    (lead, items)
119}
120
121/// Drop the oldest items of `section` until the whole text is at most `target`
122/// characters, or it has none left; returns how many went (counting a notice it
123/// already carried).
124fn shorten_section(section: &mut Section, text_chars: usize, target: usize) -> usize {
125    let (mut lead, mut items) = items(&section.body);
126    let earlier = lead.first().and_then(|l| omitted_count(l)).unwrap_or(0);
127    if earlier > 0 {
128        lead.remove(0);
129    }
130    let mut over = text_chars.saturating_sub(target);
131    let mut dropped = 0;
132    // A notice costs a line: allow for it up front.
133    over += omitted_line(earlier + items.len()).chars().count() + 1;
134    while over > 0 && !items.is_empty() {
135        let gone = items.remove(0);
136        over = over.saturating_sub(gone.iter().map(|l| l.chars().count() + 1).sum());
137        dropped += 1;
138    }
139    let total = earlier + dropped;
140    section.body = Vec::new();
141    if total > 0 {
142        section.body.push(omitted_line(total));
143    }
144    section.body.extend(lead);
145    section.body.extend(items.into_iter().flatten());
146    dropped
147}
148
149/// `text` shortened to at most `cap` characters when it can be, and how many
150/// list items that took out. Whole sections are never cut mid-line: the
151/// protected ones are kept whole, so when they alone are over `cap` the result
152/// is longer than `cap` rather than cut.
153pub(crate) fn shorten(text: &str, cap: usize) -> (String, usize) {
154    if text.chars().count() <= cap {
155        return (text.to_string(), 0);
156    }
157    let mut sections = parse(text);
158    let mut dropped = 0;
159    for name in SHRINKABLE {
160        let total: usize = sections.iter().map(Section::chars).sum();
161        if total <= cap {
162            break;
163        }
164        for section in sections.iter_mut().filter(|s| s.is(name)) {
165            dropped += shorten_section(section, total, cap);
166        }
167    }
168    (render(&sections), dropped)
169}
170
171/// `text` with its sections in the packet's order (see [`PACKET_ORDER`]): the
172/// ones it names first, any other after them in the order they were written, a
173/// text with no sections as it is.
174pub(crate) fn in_packet_order(text: &str) -> String {
175    let sections = parse(text);
176    if sections.iter().all(|s| s.heading.is_empty()) {
177        return text.to_string();
178    }
179    let rank = |s: &Section| PACKET_ORDER.iter().position(|n| s.is(n)).unwrap_or(PACKET_ORDER.len());
180    let mut ordered: Vec<&Section> = sections.iter().collect();
181    // Text before the first heading stays first; the sort is stable.
182    ordered.sort_by_key(|s| if s.heading.is_empty() { 0 } else { rank(s) + 1 });
183    ordered.into_iter().map(Section::render).collect::<String>().trim_end().to_string()
184}
185
186#[cfg(test)]
187#[path = "continuity_sections_tests.rs"]
188mod tests;