Skip to main content

agentmux_srv_core/backend/agent_archive/
build.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What goes into an agent archive, and from where (spec section 4): the definition through the allowlist, Personal
5//! Memory refreshed from the live folder, and the conversation in the history store's compact form, newest first
6//! under the cap of decision 12, plus the conversation as one readable file and the rolling state. A value srv holds
7//! secret is withheld from every part that holds text from the store; `scrub_shape` also withholds anything shaped
8//! like a key, which a saved file does and a move does not. Nothing here reads a provider's own session file.
9
10use std::io::{Seek, Write};
11
12use serde_json::Value;
13
14use super::definition::{PortableDefinition, RouteChoice};
15use super::manifest::{AgentInfo, Manifest, Source};
16use super::writer::{ArchiveWriter, Signer};
17use super::{transcript_md, ArchiveError, Limits};
18use crate::backend::bundle_conversation::{conversations, render};
19use crate::backend::storage::filestore::FileStore;
20use crate::backend::storage::store::Store;
21use crate::backend::storage::AgentDefinition;
22use crate::backend::transcript::withhold;
23
24/// The most raw conversation a saved file takes until the store's compact form is the only form (decision 12): the
25/// newest sessions that fit. A session that does not fit is left out and said so.
26pub const MAX_HISTORY_RAW_BYTES: i64 = 200 << 20;
27/// The most of the readable conversation file.
28const MAX_TRANSCRIPT_BYTES: usize = 20 << 20;
29
30/// What to put in.
31#[derive(Debug, Clone)]
32pub struct Options {
33    pub memory: bool,
34    pub history: bool,
35    /// Also withhold anything shaped like a key or token (a saved file; not a move, which would change tool output
36    /// the agent may rely on).
37    pub scrub_shape: bool,
38    pub app_version: String,
39    pub instance_id: String,
40    pub host_hint: String,
41}
42
43/// Where it comes from.
44pub struct Inputs<'a> {
45    /// The channel's own store: definitions and the model route.
46    pub mstore: &'a Store,
47    /// The identity store: Personal Memory's mirror.
48    pub id_store: &'a Store,
49    /// The shared transcript store, when this install has one.
50    pub transcripts: Option<&'a FileStore>,
51}
52
53/// What was written and what was not.
54#[derive(Debug, Clone)]
55pub struct Report {
56    pub manifest: Manifest,
57    /// What the person should know: a file that was cut, a session left out, a name skipped.
58    pub warnings: Vec<String>,
59    pub memory_files: usize,
60    pub sessions: usize,
61}
62
63/// Writes the archive of `def` to `out`. On an error `out` holds a partial file, which the caller discards.
64pub fn build<W: Write + Seek>(
65    out: W,
66    def: &AgentDefinition,
67    inputs: &Inputs<'_>,
68    opts: &Options,
69    limits: Limits,
70    signer: Option<Signer<'_>>,
71) -> Result<(Report, W), ArchiveError> {
72    let mut w = ArchiveWriter::new(out, limits);
73    let mut warnings = Vec::new();
74
75    let route = crate::backend::model_gateway::launch::choice_of(inputs.mstore, &def.id).map(|c| RouteChoice { route: c.route, model: c.model });
76    // The seat lives in the shared definition record, not in the row a channel's store returns.
77    let mut stored = def.clone();
78    if stored.seat.is_none() {
79        stored.seat = inputs.mstore.agent_seat_get(&def.id);
80    }
81    let mut portable = PortableDefinition::from_definition(&stored, route);
82    // Text a person wrote into the definition is cleaned like memory and history: a held value or a key-shaped word in the
83    // description does not leave in the file.
84    portable.description = clean(&portable.description, opts);
85    portable.branch_label = clean(&portable.branch_label, opts);
86    w.add_bytes("agent.json", &portable.to_json()?)?;
87
88    let memory_files = if opts.memory { add_memory(&mut w, def, inputs, opts, &mut warnings)? } else { 0 };
89    let sessions = if opts.history { add_history(&mut w, def, inputs, opts, &mut warnings)? } else { 0 };
90
91    let info = AgentInfo { uid: def.id.clone(), name: def.name.clone(), slug: def.slug.clone() };
92    let source = Source { instance_id: opts.instance_id.clone(), host_hint: opts.host_hint.clone(), app_version: opts.app_version.clone(), os: std::env::consts::OS.to_string() };
93    let (manifest, out) = w.finish(info, source, agentmux_common::time::now_ms(), signer)?;
94    Ok((Report { manifest, warnings, memory_files, sessions }, out))
95}
96
97fn add_memory<W: Write + Seek>(w: &mut ArchiveWriter<W>, def: &AgentDefinition, inputs: &Inputs<'_>, opts: &Options, warnings: &mut Vec<String>) -> Result<usize, ArchiveError> {
98    // The mirror is refreshed from the live folder first: it is as old as the last time someone looked at it.
99    if let Some(dir) = crate::backend::memory::native_files::memory_dir_for_agent_by_id(inputs.mstore, def) {
100        match crate::backend::memory::native_files::refresh_memory_mirror_from_live_fs(&def.id, &dir, inputs.id_store) {
101            Ok(truncated) => warnings.extend(truncated.into_iter().map(|f| format!("{f}: larger than the memory size limit and cut; the saved copy is incomplete"))),
102            Err(e) => warnings.push(format!("Personal Memory could not be refreshed from its folder; the last mirrored copy is saved: {e}")),
103        }
104    }
105    let rows = inputs.id_store.agent_native_memory_list_meta(&def.id).map_err(|e| ArchiveError::Io(e.to_string()))?;
106    let mut count = 0;
107    for row in rows {
108        let path = format!("memory/{}", row.filename);
109        if !super::manifest::valid_part_path(&path) {
110            warnings.push(format!("a memory file named {:?} was left out: its name is not a plain file name", row.filename));
111            continue;
112        }
113        match inputs.id_store.agent_native_memory_read(&def.id, &row.filename) {
114            Ok(Some(content)) => {
115                let text = clean(&content, opts);
116                w.add_bytes(&path, text.as_bytes())?;
117                count += 1;
118            }
119            Ok(None) => {}
120            Err(e) => warnings.push(format!("memory file {} could not be read and was left out: {e}", row.filename)),
121        }
122    }
123    Ok(count)
124}
125
126fn add_history<W: Write + Seek>(w: &mut ArchiveWriter<W>, def: &AgentDefinition, inputs: &Inputs<'_>, opts: &Options, warnings: &mut Vec<String>) -> Result<usize, ArchiveError> {
127    let Some(store) = inputs.transcripts else {
128        warnings.push("this install has no history store, so no conversation is saved".to_string());
129        return Ok(0);
130    };
131    let found = conversations(store, &def.id).map_err(|e| ArchiveError::Io(e.to_string()))?;
132    let mut taken = 0i64;
133    let mut kept = Vec::new();
134    for conv in found {
135        if taken + conv.size > MAX_HISTORY_RAW_BYTES {
136            warnings.push(format!("{} ({} MiB) was left out: a saved file holds the newest {} MiB of a conversation until its history is kept in the compact form only", conv.path, conv.size >> 20, MAX_HISTORY_RAW_BYTES >> 20));
137            continue;
138        }
139        taken += conv.size;
140        kept.push(conv);
141    }
142    // One session is in memory at a time: it is rendered, written to the file and turned into its readable piece, and
143    // the session is dropped before the next is read. The pieces are small.
144    let mut pieces: Vec<String> = Vec::new();
145    for conv in &kept {
146        let mut compact = render(store, &conv.zone).map_err(|e| ArchiveError::Io(e.to_string()))?;
147        if opts.scrub_shape {
148            compact = scrub_lines(compact);
149        }
150        w.add_bytes(&conv.path, compact.as_bytes())?;
151        let title = format!("Conversation of {} ({})", def.name, conv.path.trim_start_matches("history/").trim_end_matches(".jsonl"));
152        pieces.push(transcript_md::render(&title, &compact));
153    }
154    // The readable file keeps the newest sessions: they are what a fresh thread needs most. The budget is filled from the
155    // newest, each piece is checked before it is added, and the kept pieces are written oldest first.
156    let (chosen, cut) = choose_pieces(&pieces, MAX_TRANSCRIPT_BYTES);
157    if cut {
158        warnings.push("the readable conversation file holds the newest sessions up to 20 MiB; the session files hold all of it".to_string());
159    }
160    let readable: String = chosen.iter().rev().map(|p| format!("{p}
161")).collect();
162    if !readable.is_empty() {
163        w.add_bytes("history/transcript.md", readable.as_bytes())?;
164    }
165    let zone = crate::backend::agent_session::agent_current_zone(&def.id);
166    if let Ok(mut files) = store.read_files_consistent(&zone, &[crate::backend::continuity_state::STATE_FILE]) {
167        if let Some(Some(state)) = files.pop() {
168            let text = clean(&String::from_utf8_lossy(&state), opts);
169            w.add_bytes("history/continuity.state.jsonl", text.as_bytes())?;
170        }
171    }
172    Ok(kept.len())
173}
174
175/// Text from the store or a memory file with the values srv holds secret withheld, and, for a saved file, every
176/// word shaped like a key.
177fn clean(text: &str, opts: &Options) -> String {
178    let text = withhold::text(text);
179    if opts.scrub_shape {
180        agentmux_common::secret_shape::scrub(&text)
181    } else {
182        text.into_owned()
183    }
184}
185
186/// Every JSON string of every line scrubbed for key shapes. A line that is not JSON is scrubbed as text. A line is
187/// never left as it was when scrubbing it would break it: the scrub works on the strings, not the syntax.
188pub fn scrub_lines(compact: String) -> String {
189    let mut out = String::with_capacity(compact.len());
190    for line in compact.lines() {
191        match serde_json::from_str::<Value>(line) {
192            Ok(mut v) => {
193                scrub_value(&mut v);
194                out.push_str(&v.to_string());
195            }
196            Err(_) => out.push_str(&agentmux_common::secret_shape::scrub(line)),
197        }
198        out.push_str("\n");
199    }
200    out
201}
202
203/// The pieces (newest first) that fit in `max` bytes, newest first, and whether any was left out. The newest piece alone
204/// over the budget is cut to its last sections rather than dropped.
205fn choose_pieces(pieces: &[String], max: usize) -> (Vec<&str>, bool) {
206    let mut chosen: Vec<&str> = Vec::new();
207    let mut size = 0usize;
208    for piece in pieces {
209        if size + piece.len() > max {
210            if chosen.is_empty() {
211                chosen.push(tail_of(piece, max));
212            }
213            return (chosen, true);
214        }
215        size += piece.len();
216        chosen.push(piece);
217    }
218    (chosen, false)
219}
220
221/// The last `max` bytes of `piece`, from the start of a section.
222pub(super) fn tail_of(piece: &str, max: usize) -> &str {
223    if piece.len() <= max {
224        return piece;
225    }
226    let mut start = piece.len() - max;
227    while !piece.is_char_boundary(start) {
228        start += 1;
229    }
230    match piece[start..].find("
231## ") {
232        Some(at) => &piece[start + at + 1..],
233        None => &piece[start..],
234    }
235}
236
237fn scrub_value(v: &mut Value) {
238    match v {
239        Value::String(s) => {
240            let cleaned = agentmux_common::secret_shape::scrub(s);
241            if cleaned != *s {
242                *s = cleaned;
243            }
244        }
245        Value::Array(a) => a.iter_mut().for_each(scrub_value),
246        Value::Object(m) => m.values_mut().for_each(scrub_value),
247        _ => {}
248    }
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254
255    #[test]
256    fn the_readable_file_keeps_the_newest_sessions_when_the_budget_runs_out() {
257        let pieces = ["# newest
258
259## Person
260
261aaaa
262".to_string(), "# middle
263bbbbbbbbbbbb
264".to_string(), "# oldest
265cccccccccccc
266".to_string()];
267        let (fits, cut) = choose_pieces(&pieces, 1000);
268        assert_eq!((fits.len(), cut), (3, false));
269        let (kept, cut) = choose_pieces(&pieces, pieces[0].len() + pieces[1].len());
270        assert!(cut);
271        assert_eq!(kept, [pieces[0].as_str(), pieces[1].as_str()], "the oldest is the one left out, and no piece passes the budget");
272        let (kept, cut) = choose_pieces(&pieces, 10);
273        assert!(cut && kept.len() == 1 && kept[0].len() <= 10, "{kept:?}");
274        let big = format!("# s
275
276## Person
277
278{}
279
280## Agent
281
282the end
283", "x".repeat(100));
284        assert!(tail_of(&big, 40).starts_with("## Agent"), "cut at a section: {:?}", tail_of(&big, 40));
285    }
286
287    #[test]
288    fn a_key_in_a_json_string_is_withheld_and_the_line_stays_json() {
289        let key = format!("ghp_{}", "a1B2c3D4e5F6g7H8i9J0");
290        let line = serde_json::json!({ "type": "user", "message": { "content": format!("use {key} for the push") } }).to_string();
291        let out = scrub_lines(format!("{line}\nnot json {key} here\n"));
292        assert!(!out.contains(&key), "{out}");
293        let first: Value = serde_json::from_str(out.lines().next().unwrap()).expect("still one JSON value");
294        assert!(first["message"]["content"].as_str().unwrap().contains("for the push"));
295        assert_eq!(out.lines().count(), 2);
296    }
297}