agentmux_srv_core/backend/memory/
fit.rs1use super::delivery::{Entry, Tier};
21use super::index::{self, IndexPlan, ALWAYS_MAX_CHARS, ALWAYS_MAX_FILES};
22
23pub const FILE_CAP_CHARS: usize = 8_000;
25pub const PERSONAL_BUDGET_CHARS: usize = 40_000;
27pub const STALE_DAYS: i64 = 7;
29pub const NO_CAP: usize = usize::MAX / 4;
31const OVERHEAD_CHARS: usize = 1_500;
33const MAX_LISTED: usize = 25;
35const DAY_MS: i64 = 86_400_000;
36const MAX_LEFT_OUT_LISTED: usize = 100;
38
39#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct Fitted {
42 pub kept: Vec<Entry>,
44 pub indexed: Vec<Entry>,
46 pub over_limit: Vec<String>,
48 pub always: usize,
50 pub skipped: Vec<Entry>,
52 pub tail: Option<String>,
55}
56
57pub fn frontmatter_value(text: &str, key: &str) -> Option<String> {
60 let rest = text.strip_prefix("---")?.strip_prefix(['\r', '\n'])?;
61 let mut prefix = String::from(key);
62 prefix.push(':');
63 for line in rest.lines() {
64 if line.trim_end() == "---" {
65 return None;
66 }
67 if let Some(value) = line.trim_start().strip_prefix(prefix.as_str()) {
68 let value = value.trim().trim_matches('"').trim();
69 return (!value.is_empty()).then(|| value.to_string());
70 }
71 }
72 None
73}
74
75pub fn skipped_note(skipped: &[Entry]) -> Option<String> {
77 if skipped.is_empty() {
78 return None;
79 }
80 let noun = if skipped.len() == 1 { "entry was" } else { "entries were" };
81 let mut out = format!(
82 "[AgentMux] {} Global Memory {noun} left out here (the delivery is full). Read each with the Memory tool (action read, scope global, id <id>):\n",
83 skipped.len()
84 );
85 for e in skipped.iter().take(MAX_LEFT_OUT_LISTED) {
86 out.push_str(&format!("- {} ({})\n", e.name, e.bundle_id.as_deref().unwrap_or("no id")));
87 }
88 if skipped.len() > MAX_LEFT_OUT_LISTED {
89 out.push_str(&format!("- … and {} more: list them with the Memory tool (action list, scope global)\n", skipped.len() - MAX_LEFT_OUT_LISTED));
90 }
91 Some(out)
92}
93
94#[derive(Debug, Clone, PartialEq, Eq)]
96pub struct Seen {
97 pub name: String,
98 pub chars: usize,
100 pub kind: Option<String>,
101 pub age_days: Option<i64>,
103}
104
105pub fn hygiene_note(files: &[Seen]) -> Option<String> {
108 let total: usize = files.iter().map(|f| f.chars).sum();
109 let big: Vec<&Seen> = files.iter().filter(|f| f.chars > FILE_CAP_CHARS).collect();
110 let stale: Vec<&Seen> = files.iter().filter(|f| f.kind.as_deref() == Some("project") && f.age_days.is_some_and(|d| d >= STALE_DAYS)).collect();
111 if total <= PERSONAL_BUDGET_CHARS && big.is_empty() && stale.is_empty() {
112 return None;
113 }
114 let mut lines = vec![format!(
115 "[AgentMux] Your Personal Memory is {} KB ({} files; over about {} KB it is worth trimming).",
116 total.div_ceil(1024),
117 files.len(),
118 PERSONAL_BUDGET_CHARS / 1024
119 )];
120 let list = |v: &[&Seen], how: &dyn Fn(&Seen) -> String| v.iter().take(MAX_LISTED).map(|f| format!("{} ({})", f.name, how(f))).collect::<Vec<_>>().join(", ");
121 if !big.is_empty() {
122 lines.push(format!("Over {} KB each, so their index line is all you see until you read them; worth splitting: {}.", FILE_CAP_CHARS / 1000, list(&big, &|f| format!("{} KB", f.chars.div_ceil(1024)))));
123 }
124 if !stale.is_empty() {
125 lines.push(format!("Project files not touched for {STALE_DAYS}+ days: {}.", list(&stale, &|f| format!("{} days", f.age_days.unwrap_or(0)))));
126 }
127 lines.push("Trim or archive what is done or out of date. AgentMux never deletes memory, so what you leave stays.".to_string());
128 Some(lines.join(" "))
129}
130
131pub fn fit(entries: Vec<Entry>, capacity_chars: usize, reserve_chars: usize, hygiene: bool, modified_ms: &dyn Fn(&Entry) -> Option<i64>, now_ms: i64) -> Fitted {
136 let seen: Vec<Seen> = entries
137 .iter()
138 .filter(|e| e.tier == Tier::Personal)
139 .map(|e| Seen {
140 name: e.name.clone(),
141 chars: e.text.chars().count(),
142 kind: frontmatter_value(&e.text, "type"),
143 age_days: modified_ms(e).map(|m| (now_ms - m).max(0) / DAY_MS),
144 })
145 .collect();
146 let (global, personal): (Vec<Entry>, Vec<Entry>) = entries.into_iter().partition(|e| e.tier == Tier::Global);
147
148 let mut marked: Vec<&Entry> = personal.iter().filter(|e| index::is_always(&e.text)).collect();
152 marked.sort_by_key(|e| modified_ms(e).unwrap_or(i64::MAX));
153 let (mut always, mut over_limit, mut always_chars) = (Vec::<Entry>::new(), Vec::<String>::new(), 0usize);
154 for e in marked {
155 let n = e.text.chars().count() + 5;
156 if always.len() < ALWAYS_MAX_FILES && always_chars + n <= ALWAYS_MAX_CHARS {
157 always_chars += n;
158 always.push(e.clone());
159 } else {
160 over_limit.push(e.name.clone());
161 }
162 }
163 let indexed: Vec<Entry> = personal.into_iter().filter(|e| !always.iter().any(|o| o.name == e.name)).collect();
164 let index_chars = index::render(&IndexPlan { files: &indexed, over_limit: &over_limit, always: always.len(), tool_only: false })
165 .map_or(0, |t| t.chars().count());
166
167 let notes_room = 1_200 + MAX_LEFT_OUT_LISTED * 80;
169 let budget = capacity_chars.saturating_sub(OVERHEAD_CHARS + reserve_chars + notes_room + index_chars + always_chars);
170 let weight = |e: &Entry| e.text.chars().count() + 5;
173 let mut used: usize = global.iter().filter(|e| e.system).map(weight).sum();
174 let (mut kept, mut skipped) = (Vec::new(), Vec::new());
175 for e in global {
176 let n = weight(&e);
177 if e.system {
178 kept.push(e);
179 } else if used + n <= budget {
180 used += n;
181 kept.push(e);
182 } else {
183 skipped.push(e);
184 }
185 }
186 let always_count = always.len();
187 kept.extend(always);
188
189 let mut tail: Vec<String> = Vec::new();
190 tail.extend(skipped_note(&skipped));
191 if hygiene {
192 tail.extend(hygiene_note(&seen));
193 }
194 Fitted { kept, indexed, over_limit, always: always_count, skipped, tail: (!tail.is_empty()).then(|| tail.join("\n")) }
195}
196
197#[cfg(test)]
198#[path = "fit_tests.rs"]
199mod tests;