agentmux_srv_core/backend/
record_carry.rs1use std::path::{Path, PathBuf};
18
19const EXT: &str = "jsonl";
20const ROLLUP_PREFIX: &str = "rollup-";
21const TRIES: usize = 3;
24
25#[derive(Debug, Default, PartialEq, Eq)]
27pub struct Brought {
28 pub moved: usize,
30 pub merged: usize,
32 pub failed: usize,
34}
35
36pub fn old_dirs(instance_dir: &Path) -> Vec<PathBuf> {
39 let mut dirs = vec![instance_dir.join("data").join("record")];
40 if let Ok(entries) = std::fs::read_dir(instance_dir.join("versions")) {
41 let mut versions: Vec<PathBuf> = entries.flatten().map(|e| e.path().join("data").join("record")).collect();
42 versions.sort();
43 dirs.extend(versions);
44 }
45 dirs.retain(|d| d.is_dir());
46 dirs
47}
48
49fn time_of(line: &str, field: &str) -> Option<u64> {
51 serde_json::from_str::<serde_json::Value>(line).ok()?.get(field)?.as_u64()
52}
53
54fn merged(ours: &str, theirs: &str, field: &str) -> String {
58 let have: std::collections::HashSet<&str> = ours.lines().collect();
59 let mut lines: Vec<(u64, &str)> = Vec::new();
60 for (text, is_theirs) in [(ours, false), (theirs, true)] {
61 let mut last = 0;
62 for line in text.lines().filter(|l| !l.trim().is_empty()) {
63 if is_theirs && have.contains(line) {
64 continue;
65 }
66 if let Some(t) = time_of(line, field) {
67 last = t;
68 }
69 lines.push((last, line));
70 }
71 }
72 lines.sort_by_key(|(t, _)| *t);
74 let mut out = String::with_capacity(ours.len() + theirs.len());
75 for (_, line) in lines {
76 out.push_str(line);
77 out.push('\n');
78 }
79 out
80}
81
82fn len_of(path: &Path) -> Option<u64> {
83 std::fs::metadata(path).ok().map(|m| m.len())
84}
85
86fn bring_file(from: &Path, to: &Path, name: &str) -> std::io::Result<bool> {
89 if !to.exists() && std::fs::rename(from, to).is_ok() {
90 return Ok(true);
91 }
92 let field = if name.starts_with(ROLLUP_PREFIX) { "h" } else { "t" };
93 let theirs = std::fs::read_to_string(from)?;
94 let tmp = to.with_file_name(format!("{name}.tmp"));
95 for _ in 0..TRIES {
96 let before = len_of(to);
97 let ours = match std::fs::read_to_string(to) {
98 Ok(text) => text,
99 Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
100 Err(e) => return Err(e),
101 };
102 std::fs::write(&tmp, merged(&ours, &theirs, field))?;
103 if len_of(to) != before {
104 continue;
106 }
107 std::fs::rename(&tmp, to)?;
108 std::fs::remove_file(from)?;
109 return Ok(false);
110 }
111 let _ = std::fs::remove_file(&tmp);
112 Err(std::io::Error::other("the record's file kept changing"))
113}
114
115pub fn bring_over(instance_dir: &Path, dest: &Path) -> Brought {
119 let mut brought = Brought::default();
120 for dir in old_dirs(instance_dir) {
121 if dir == dest {
122 continue;
123 }
124 let Ok(entries) = std::fs::read_dir(&dir) else { continue };
125 let mut names: Vec<String> = entries
126 .flatten()
127 .filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
128 .filter_map(|e| e.file_name().to_str().map(str::to_string))
129 .filter(|n| n.ends_with(&format!(".{EXT}")))
130 .collect();
131 names.sort();
132 if names.is_empty() {
133 continue;
134 }
135 if let Err(e) = std::fs::create_dir_all(dest) {
136 tracing::warn!(error = %e, "[record] the record's folder could not be made");
137 brought.failed += names.len();
138 continue;
139 }
140 for name in names {
141 match bring_file(&dir.join(&name), &dest.join(&name), &name) {
142 Ok(true) => brought.moved += 1,
143 Ok(false) => brought.merged += 1,
144 Err(e) => {
145 brought.failed += 1;
146 tracing::warn!(error = %e, file = %name, "[record] an older build's file could not be brought into the record");
147 }
148 }
149 }
150 let _ = std::fs::remove_dir(&dir);
152 }
153 if brought != Brought::default() {
154 tracing::info!(moved = brought.moved, merged = brought.merged, failed = brought.failed, "[record] brought over what older builds kept");
155 }
156 brought
157}
158
159pub fn bring_over_here() -> Brought {
162 let Some(paths) = agentmux_common::data_paths::DataPaths::from_env() else { return Brought::default() };
163 let Some(dest) = agentmux_common::record_events::record_dir() else { return Brought::default() };
164 bring_over(&paths.instance_dir, &dest)
165}
166
167#[cfg(test)]
168mod tests {
169 use super::*;
170 use crate::backend::record;
171 use serde_json::json;
172
173 const NOON: u64 = 1_794_830_400_000;
175 const HOUR: u64 = 3_600_000;
176
177 fn write(path: &Path, lines: &[serde_json::Value]) {
178 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
179 let text: String = lines.iter().map(|l| format!("{l}\n")).collect();
180 std::fs::write(path, text).unwrap();
181 }
182
183 fn times(path: &Path, field: &str) -> Vec<u64> {
184 std::fs::read_to_string(path).unwrap().lines().map(|l| time_of(l, field).unwrap()).collect()
185 }
186
187 fn old(home: &Path, version: &str) -> PathBuf {
188 home.join("versions").join(version).join("data").join("record")
189 }
190
191 #[test]
192 fn the_old_folders_are_each_versions_and_a_dev_builds_own() {
193 let tmp = tempfile::tempdir().unwrap();
194 let home = tmp.path();
195 assert!(old_dirs(home).is_empty());
196 std::fs::create_dir_all(old(home, "0.60.34")).unwrap();
197 std::fs::create_dir_all(old(home, "0.60.35")).unwrap();
198 std::fs::create_dir_all(home.join("versions").join("0.60.30").join("data")).unwrap();
200 std::fs::write(home.join("versions").join("notes.txt"), "x").unwrap();
201 std::fs::create_dir_all(home.join("data").join("record")).unwrap();
202 assert_eq!(old_dirs(home), vec![home.join("data").join("record"), old(home, "0.60.34"), old(home, "0.60.35")]);
203 }
204
205 #[test]
206 fn lines_are_put_in_time_order_and_one_already_there_is_not_added_twice() {
207 let a = format!("{}\n{}\n", json!({ "t": 10, "kind": "x" }), json!({ "t": 30, "kind": "x" }));
208 let b = format!("{}\n{}\n\n{}\n", json!({ "t": 20, "kind": "y" }), json!({ "t": 30, "kind": "x" }), json!({ "t": 5, "kind": "y" }));
209 let out = merged(&a, &b, "t");
210 let got: Vec<(u64, String)> =
211 out.lines().map(|l| serde_json::from_str::<serde_json::Value>(l).unwrap()).map(|v| (v["t"].as_u64().unwrap(), v["kind"].as_str().unwrap().to_string())).collect();
212 assert_eq!(got, [(5, "y".into()), (10, "x".into()), (20, "y".into()), (30, "x".into())]);
213 assert!(out.ends_with('\n'));
214 let torn = format!("{}\n{{\"t\": 4\n{}\n", json!({ "t": 40 }), json!({ "t": 50 }));
216 let out = merged(&a, &torn, "t");
217 let lines: Vec<&str> = out.lines().collect();
218 assert_eq!(lines.len(), 5);
219 assert_eq!(lines[3], "{\"t\": 4");
220 let out = merged(&format!("{}\n", json!({ "h": 7, "last_t": 1 })), &format!("{}\n", json!({ "h": 3, "last_t": 9 })), "h");
222 assert!(out.starts_with("{\"h\":3"));
223 }
224
225 #[test]
226 fn each_versions_record_becomes_one_record_in_time_order() {
227 let tmp = tempfile::tempdir().unwrap();
228 let home = tmp.path();
229 let dest = home.join("record");
230 let v34 = old(home, "0.60.34");
232 write(&v34.join("2026-11-15.jsonl"), &[json!({ "t": NOON - 24 * HOUR })]);
233 write(&v34.join("2026-11-16.jsonl"), &[json!({ "t": NOON - 3 * HOUR }), json!({ "t": NOON - 2 * HOUR })]);
234 write(&v34.join("rollup-2026-11.jsonl"), &[json!({ "h": NOON - 24 * HOUR }), json!({ "h": NOON - 3 * HOUR })]);
235 write(&v34.join("events-2026-11.jsonl"), &[json!({ "t": NOON - 2 * HOUR, "kind": "ui_stall", "ms": 6_000 })]);
236 let v35 = old(home, "0.60.35");
238 write(&v35.join("2026-11-16.jsonl"), &[json!({ "t": NOON + HOUR })]);
239 write(&v35.join("rollup-2026-11.jsonl"), &[json!({ "h": NOON })]);
240 std::fs::write(v35.join("notes.txt"), "x").unwrap();
242 write(&dest.join("events-2026-11.jsonl"), &[json!({ "t": NOON + 2 * HOUR, "kind": "srv_stall", "ms": 5_500 })]);
244
245 assert_eq!(bring_over(home, &dest), Brought { moved: 3, merged: 3, failed: 0 });
246
247 assert_eq!(times(&dest.join("2026-11-15.jsonl"), "t"), [NOON - 24 * HOUR]);
248 assert_eq!(times(&dest.join("2026-11-16.jsonl"), "t"), [NOON - 3 * HOUR, NOON - 2 * HOUR, NOON + HOUR]);
249 assert_eq!(times(&dest.join("rollup-2026-11.jsonl"), "h"), [NOON - 24 * HOUR, NOON - 3 * HOUR, NOON]);
250 assert_eq!(times(&dest.join("events-2026-11.jsonl"), "t"), [NOON - 2 * HOUR, NOON + 2 * HOUR]);
251 assert!(!v34.exists());
253 assert_eq!(std::fs::read_dir(&v35).unwrap().count(), 1);
254 assert!(std::fs::read_dir(&dest).unwrap().flatten().all(|e| e.file_name().to_str().unwrap().ends_with(".jsonl")));
255 let (total, events) = record::read_events(&dest, 0, u64::MAX, 10);
257 assert_eq!(total, 2);
258 assert_eq!(events[0]["kind"], "ui_stall");
259 assert_eq!(bring_over(home, &dest), Brought::default());
261 }
262
263 #[test]
264 fn a_dev_builds_record_moves_out_of_its_data_folder_and_no_old_record_is_nothing() {
265 let tmp = tempfile::tempdir().unwrap();
266 let home = tmp.path();
267 let dest = home.join("record");
268 assert_eq!(bring_over(home, &dest), Brought::default());
269 assert!(!dest.exists());
270 write(&home.join("data").join("record").join("2026-11-16.jsonl"), &[json!({ "t": NOON })]);
271 assert_eq!(bring_over(home, &dest), Brought { moved: 1, merged: 0, failed: 0 });
272 assert_eq!(times(&dest.join("2026-11-16.jsonl"), "t"), [NOON]);
273 assert!(!home.join("data").join("record").exists());
274 }
275
276 #[test]
277 fn a_merge_run_again_after_being_cut_short_adds_nothing_twice() {
278 let tmp = tempfile::tempdir().unwrap();
279 let home = tmp.path();
280 let dest = home.join("record");
281 let lines = [json!({ "t": NOON }), json!({ "t": NOON + HOUR })];
282 write(&dest.join("2026-11-16.jsonl"), &lines);
284 write(&old(home, "0.60.34").join("2026-11-16.jsonl"), &lines);
285 assert_eq!(bring_over(home, &dest), Brought { moved: 0, merged: 1, failed: 0 });
286 assert_eq!(times(&dest.join("2026-11-16.jsonl"), "t"), [NOON, NOON + HOUR]);
287 }
288}