Skip to main content

agentmux_srv_core/backend/memory/
index.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Personal Memory as an index: one line per file, so the agent knows what it has and opens a file when it
5//! applies (docs/specs/SPEC_MEMORY_DELIVERY_INDEX_NOT_FULL_TEXT_2026_11_17.md §3.2, §3.3).
6//!
7//! Every file appears once, in the index or, when marked `deliver: always` and within the limit, in full. A long
8//! index shortens its descriptions, then drops them. Past about a thousand files even the names do not fit: the index
9//! then lists as many as fit and says how many more there are and how to list them, and the pane shows those files as
10//! not listed. It goes first in a delivery and stays under [`INDEX_BUDGET_CHARS`], so it sits whole in the first
11//! part whatever order the parts arrive in.
12
13use super::delivery::Entry;
14use super::fit::frontmatter_value;
15
16/// The most characters the index takes.
17pub const INDEX_BUDGET_CHARS: usize = 8_000;
18/// The most files marked `deliver: always` that go in full.
19pub const ALWAYS_MAX_FILES: usize = 5;
20/// The most characters of those files, together.
21pub const ALWAYS_MAX_CHARS: usize = 6_000;
22/// A description's longest form, then its shortened form once the index is over budget.
23const DESCRIPTION_CHARS: [usize; 3] = [110, 60, 0];
24
25/// Whether a file's frontmatter marks it to be sent in full every time (`deliver: always`, at any indent).
26pub fn is_always(text: &str) -> bool {
27    frontmatter_value(text, "deliver").is_some_and(|v| v.eq_ignore_ascii_case("always"))
28}
29
30/// What the index lists and how it tells the agent to read a file.
31pub struct IndexPlan<'a> {
32    /// Every Personal file that is not delivered in full.
33    pub files: &'a [Entry],
34    /// Names of files marked always that went over the limit, so their line says why.
35    pub over_limit: &'a [String],
36    /// Files delivered in full because they are marked always.
37    pub always: usize,
38    /// A container agent can't open the host's folder: its lines give the `Memory` tool's form only.
39    pub tool_only: bool,
40}
41
42impl IndexPlan<'_> {
43    pub fn is_empty(&self) -> bool {
44        self.files.is_empty()
45    }
46}
47
48fn description_of(e: &Entry) -> String {
49    if let Some(d) = frontmatter_value(&e.text, "description") {
50        return d.split_whitespace().collect::<Vec<_>>().join(" ");
51    }
52    let body = e.text.split_once("\n---").filter(|_| e.text.starts_with("---")).map_or(e.text.as_str(), |(_, rest)| rest);
53    body.lines().map(str::trim).find(|l| !l.is_empty() && !l.starts_with('#') && *l != "---").unwrap_or("").to_string()
54}
55
56fn line(e: &Entry, over_limit: bool, desc_chars: usize) -> String {
57    let kind = frontmatter_value(&e.text, "type").unwrap_or_else(|| "unlisted".to_string());
58    let stem = e.name.strip_suffix(".md").unwrap_or(&e.name);
59    let title = frontmatter_value(&e.text, "name").filter(|n| n != stem && *n != e.name);
60    let mut out = format!("- {}", e.name);
61    if let Some(t) = title {
62        out.push_str(&format!(" · {t}"));
63    }
64    out.push_str(&format!(" ({kind})"));
65    let mut desc: String = description_of(e).chars().take(desc_chars).collect();
66    if !desc.is_empty() {
67        if description_of(e).chars().count() > desc_chars {
68            desc = desc.trim_end().to_string() + "…";
69        }
70        out.push_str(&format!(" — {desc}"));
71    }
72    if over_limit {
73        out.push_str(&format!(
74            " [marked always, but over the limit of {ALWAYS_MAX_FILES} files and {ALWAYS_MAX_CHARS} characters; read it]"
75        ));
76    }
77    out
78}
79
80/// What the index shows of its files.
81pub struct Listing {
82    /// `(entry name, line)` for each file listed, in the order given.
83    pub lines: Vec<(String, String)>,
84    /// How many files came after the last one that fit, with no line of their own.
85    pub unlisted: usize,
86}
87
88fn lines_len(lines: &[(String, String)]) -> usize {
89    lines.iter().map(|(_, l)| l.chars().count() + 1).sum()
90}
91
92/// The note that stands for the files that did not fit.
93fn unlisted_line(n: usize) -> String {
94    let noun = if n == 1 { "file is" } else { "files are" };
95    format!("- … {n} more {noun} not listed here (too many for the index). List them with the Memory tool (action list, scope personal).")
96}
97
98/// The index's lines at the longest description that fits [`INDEX_BUDGET_CHARS`]. When even the names do not fit
99/// (about a thousand files), as many files as fit are listed, in the order given, and the rest are counted in a line
100/// that says how to list them; the delivery and the pane both say so, so no file reads as listed that was not.
101pub fn listing(plan: &IndexPlan) -> Listing {
102    let mut lines = Vec::new();
103    for chars in DESCRIPTION_CHARS {
104        lines = plan.files.iter().map(|e| (e.name.clone(), line(e, plan.over_limit.contains(&e.name), chars))).collect();
105        if lines_len(&lines) <= INDEX_BUDGET_CHARS {
106            return Listing { lines, unlisted: 0 };
107        }
108    }
109    let room = INDEX_BUDGET_CHARS - unlisted_line(plan.files.len()).chars().count() - 1;
110    let mut used = 0;
111    let fits = lines
112        .iter()
113        .take_while(|(_, l)| {
114            used += l.chars().count() + 1;
115            used <= room
116        })
117        .count();
118    let unlisted = lines.len() - fits;
119    lines.truncate(fits);
120    Listing { lines, unlisted }
121}
122
123/// [`listing`]'s lines.
124pub fn lines(plan: &IndexPlan) -> Vec<(String, String)> {
125    listing(plan).lines
126}
127
128/// The folder the index files live in, when they share one.
129fn folder_of(files: &[Entry]) -> Option<String> {
130    let first = files.first()?.path.as_deref()?;
131    let dir = std::path::Path::new(first).parent()?.to_string_lossy().replace('\\', "/");
132    files
133        .iter()
134        .all(|e| e.path.as_deref().and_then(|p| std::path::Path::new(p).parent()).is_some_and(|d| d.to_string_lossy().replace('\\', "/") == dir))
135        .then_some(dir)
136}
137
138/// The index section: heading, the instruction to read before acting, then a line per file. `None` when no
139/// file is listed.
140pub fn render(plan: &IndexPlan) -> Option<String> {
141    if plan.is_empty() {
142        return None;
143    }
144    let n = plan.files.len();
145    let noun = if n == 1 { "file" } else { "files" };
146    let mut out = format!("# Personal Memory ({n} {noun}, listed as an index)\n");
147    out.push_str("Read a file before you act on what its line describes: the line is all you have until you do.\n");
148    let folder = if plan.tool_only { None } else { folder_of(plan.files) };
149    match folder {
150        Some(dir) => out.push_str(&format!(
151            "Read one with the Memory tool (action read, scope personal, filename <file>) or open it in {dir}.\n"
152        )),
153        None => out.push_str("Read one with the Memory tool (action read, scope personal, filename <file>).\n"),
154    }
155    if plan.always > 0 {
156        let noun = if plan.always == 1 { "file is" } else { "files are" };
157        out.push_str(&format!("{} more {noun} marked always and follow in full.\n", plan.always));
158    }
159    let listing = listing(plan);
160    for (_, l) in &listing.lines {
161        out.push_str(l);
162        out.push('\n');
163    }
164    if listing.unlisted > 0 {
165        out.push_str(&unlisted_line(listing.unlisted));
166        out.push('\n');
167    }
168    Some(out)
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174    use crate::backend::memory::delivery::Tier;
175
176    fn file(name: &str, text: &str) -> Entry {
177        Entry { label: name.into(), tier: Tier::Personal, text: text.into(), name: name.into(), system: false, bundle_id: None, path: Some(format!("/mem/{name}")) }
178    }
179
180    fn doc(name: &str, kind: &str, desc: &str) -> String {
181        format!("---\nname: {name}\ndescription: {desc}\nmetadata:\n  type: {kind}\n---\n\nbody of {name}\n")
182    }
183
184    #[test]
185    fn a_line_has_the_file_the_type_and_the_description() {
186        let f = file("rule-one.md", &doc("rule-one", "feedback", "When a build slot is busy, wait for it"));
187        let plan = IndexPlan { files: &[f], over_limit: &[], always: 0, tool_only: false };
188        let text = render(&plan).unwrap();
189        assert!(text.contains("- rule-one.md (feedback) — When a build slot is busy, wait for it"), "{text}");
190        assert!(text.contains("open it in /mem."), "{text}");
191        assert!(!text.contains("body of rule-one"), "the body is not in the index");
192    }
193
194    #[test]
195    fn a_container_is_given_the_tool_form_only() {
196        let f = file("a.md", &doc("a", "user", "d"));
197        let text = render(&IndexPlan { files: &[f], over_limit: &[], always: 0, tool_only: true }).unwrap();
198        assert!(!text.contains("/mem"), "{text}");
199        assert!(text.contains("Memory tool"));
200    }
201
202    #[test]
203    fn a_file_without_frontmatter_is_listed_by_its_first_line() {
204        let f = file("loose.md", "# Heading\n\nthe first real line\nmore\n");
205        let text = render(&IndexPlan { files: &[f], over_limit: &[], always: 0, tool_only: false }).unwrap();
206        assert!(text.contains("- loose.md (unlisted) — the first real line"), "{text}");
207    }
208
209    #[test]
210    fn the_index_is_complete_and_inside_its_budget_for_any_number_of_files() {
211        for n in [0usize, 1, 9, 40, 120, 400] {
212            let files: Vec<Entry> = (0..n).map(|i| file(&format!("memory-file-number-{i:03}.md"), &doc(&format!("m{i}"), "project", &"long description words ".repeat(20)))).collect();
213            let plan = IndexPlan { files: &files, over_limit: &[], always: 0, tool_only: false };
214            let Some(text) = render(&plan) else {
215                assert_eq!(n, 0);
216                continue;
217            };
218            let listing = listing(&plan);
219            assert_eq!(listing.lines.len() + listing.unlisted, n, "every file is listed or counted at n={n}");
220            for (name, _) in &listing.lines {
221                assert_eq!(text.matches(&format!("- {name} ")).count(), 1, "{name} listed once at n={n}");
222            }
223            assert!(lines_len(&listing.lines) <= INDEX_BUDGET_CHARS, "n={n}");
224            if n <= 120 {
225                assert_eq!(listing.unlisted, 0, "n={n}");
226            }
227        }
228    }
229
230    #[test]
231    fn a_thousand_long_names_are_cut_at_the_budget_and_the_rest_is_counted() {
232        let files: Vec<Entry> = (0..1_000).map(|i| file(&format!("{}-{i:04}.md", "n".repeat(77)), &doc("x", "project", "d"))).collect();
233        assert!(files[0].name.chars().count() >= 83);
234        let plan = IndexPlan { files: &files, over_limit: &[], always: 0, tool_only: false };
235        let listing = listing(&plan);
236        assert!(listing.unlisted > 0 && listing.lines.len() + listing.unlisted == 1_000, "{} listed, {} not", listing.lines.len(), listing.unlisted);
237        assert_eq!(listing.lines[0].0, files[0].name, "the files given first are the ones listed");
238        let text = render(&plan).unwrap();
239        let body = text.split_once("\n- ").map_or(0, |(_, rest)| rest.chars().count());
240        assert!(body <= INDEX_BUDGET_CHARS, "the lines stay inside the budget: {body}");
241        assert!(text.contains(&format!("{} more files are not listed here", listing.unlisted)), "{}", &text[text.len().saturating_sub(300)..]);
242        assert!(text.contains("action list, scope personal"));
243    }
244
245    #[test]
246    fn an_index_that_fits_lists_every_file_and_counts_none_as_unlisted() {
247        let files: Vec<Entry> = (0..150).map(|i| file(&format!("memory-file-number-{i:03}.md"), &doc("x", "project", &"words ".repeat(30)))).collect();
248        let listing = listing(&IndexPlan { files: &files, over_limit: &[], always: 0, tool_only: false });
249        assert_eq!((listing.lines.len(), listing.unlisted), (150, 0));
250    }
251
252    #[test]
253    fn a_long_description_is_shortened_before_a_file_is_dropped() {
254        let files: Vec<Entry> = (0..60).map(|i| file(&format!("f{i:02}.md"), &doc("x", "feedback", &"word ".repeat(40)))).collect();
255        let plan = IndexPlan { files: &files, over_limit: &[], always: 0, tool_only: false };
256        assert_eq!(lines(&plan).len(), 60);
257        assert!(lines(&plan).iter().all(|(_, l)| l.chars().count() < 160));
258    }
259
260    #[test]
261    fn an_over_limit_always_file_says_why() {
262        let f = file("big.md", &doc("big", "feedback", "d"));
263        let text = render(&IndexPlan { files: &[f], over_limit: &["big.md".to_string()], always: 2, tool_only: false }).unwrap();
264        assert!(text.contains("marked always, but over the limit"), "{text}");
265        assert!(text.contains("2 more files are marked always"), "{text}");
266    }
267
268    #[test]
269    fn deliver_always_is_found_at_any_indent_and_only_as_always() {
270        assert!(is_always("---\nname: a\nmetadata:\n  deliver: always\n---\nx"));
271        assert!(is_always("---\ndeliver: Always\n---\nx"));
272        assert!(!is_always("---\ndeliver: never\n---\nx"));
273        assert!(!is_always("no frontmatter, deliver: always"));
274    }
275}