Skip to main content

agentmux_srv_core/backend/memory/
fit.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What of an agent's Personal Memory fits in a delivery, and what the agent is told about the rest
5//! (the re-send after a compaction; `memory_delivery` composes and splits what this keeps).
6//!
7//! A delivery carries at most `HOOK_PARTS * MAX_PART_CHARS` characters. Before this, the files went in by
8//! name and the cut fell wherever the budget ended: one stale 50 KB snapshot at the front used it all, and
9//! every later file, including the one the index marks "read first", showed as not sent.
10//!
11//! - Order: newest first (the file's `modified` frontmatter, else its mtime), done where the files are read.
12//! - Index: Personal Memory goes in as an index (`index.rs`), one line per file, always complete. Only files marked
13//!   `deliver: always` (up to [`ALWAYS_MAX_FILES`] files and [`ALWAYS_MAX_CHARS`] characters) go in full.
14//! - Fit: Global Memory entries that still don't fit are left out whole and listed by name with the way to read
15//!   them, never cut at the end of the text.
16//! - Hygiene: on a compaction, one note when Personal Memory is over [`PERSONAL_BUDGET_CHARS`], a file is
17//!   over the cap, or a project file hasn't been touched for [`STALE_DAYS`]. AgentMux never deletes memory:
18//!   it can't tell a stale snapshot from a durable rule, so the agent trims its own.
19
20use super::delivery::{Entry, Tier};
21use super::index::{self, IndexPlan, ALWAYS_MAX_CHARS, ALWAYS_MAX_FILES};
22
23/// The most characters one Personal Memory file contributes.
24pub const FILE_CAP_CHARS: usize = 8_000;
25/// Personal Memory above this (in characters, counted before the cap's cut) is worth pruning.
26pub const PERSONAL_BUDGET_CHARS: usize = 40_000;
27/// A `project` file untouched for this many days is called stale.
28pub const STALE_DAYS: i64 = 7;
29/// A capacity for a delivery that has no part cap (the fallback's one message).
30pub const NO_CAP: usize = usize::MAX / 4;
31/// The characters kept back for the header, the section headings and the part labels.
32const OVERHEAD_CHARS: usize = 1_500;
33/// The most names the hygiene note spells out.
34const MAX_LISTED: usize = 25;
35const DAY_MS: i64 = 86_400_000;
36/// The most Global Memory entries the left-out note names; a name is about 60 characters, so the note stays small.
37const MAX_LEFT_OUT_LISTED: usize = 100;
38
39/// What the model gets to read: everything that fit, and a note about the rest.
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct Fitted {
42    /// Sent in full: the Global Memory that fit, then the Personal files marked always.
43    pub kept: Vec<Entry>,
44    /// Personal files listed in the index, not sent in full.
45    pub indexed: Vec<Entry>,
46    /// Names of files marked always that went over the limit and are in the index with the reason.
47    pub over_limit: Vec<String>,
48    /// How many Personal files went in full because they are marked always.
49    pub always: usize,
50    /// Global Memory entries left out whole because the delivery is full, named in the tail.
51    pub skipped: Vec<Entry>,
52    /// The kept files that went in cut at the cap, with what they were before it.
53    /// The not-sent list and the hygiene note, joined; `None` when there is nothing to say.
54    pub tail: Option<String>,
55}
56
57/// The value of `key` in the frontmatter block at the top of `text` (`---` … `---`), at any indent so a
58/// nested `metadata:` key is found too.
59pub 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
75/// The note naming the Global Memory entries left out of the delivery, with how to read each.
76pub 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/// What a Personal Memory file looks like to the hygiene check.
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub struct Seen {
97    pub name: String,
98    /// The file's size in characters before the cap's cut.
99    pub chars: usize,
100    pub kind: Option<String>,
101    /// Days since it was last modified, if known.
102    pub age_days: Option<i64>,
103}
104
105/// The note asking the agent to trim its Personal Memory, when it needs it: over the budget, a file over the
106/// cap, or a project file stale for [`STALE_DAYS`].
107pub 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
131/// Caps the Personal files and keeps, in the order given (the caller put the newest first), as many as fit in
132/// one delivery after `reserve_chars` (the running summary and anything else that rides along). Global Memory
133/// goes in whole entries only; Personal Memory goes in the index, and the few files marked `deliver: always`
134/// in full within their limit. The tail is the left-out note, and the hygiene note when `hygiene` is set.
135pub 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    // Marked files, oldest marking first (by the modification time, not by whole days: files changed today keep their
149    // order), until a limit is reached; the rest of them go in the index with the reason. A file with no known time
150    // counts as the newest.
151    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    // Leave room for the notes before counting.
168    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    // System entries (Operator Config) are always kept: they are small, and the agent cannot read one back with the
171    // `Memory` tool, so a left-out note could not tell it how to recover it. They count against the budget first.
172    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;