//! 檢查點與 /rewind (M1). Before a bot changes a file with edit_file, what the file was is kept, //! under the person's message that started that turn (its time). 「/rewind」 lists those messages; //! 「/rewind N」 puts the files back as they were before the N-th and takes the chat back to just //! before it; 「/rewind N 檔案」 only the files, 「/rewind N 對話」 only the chat. Like Claude //! Code's checkpoints: what commands changed (shell, git, npm…) isn't in them, nor files on //! another AnyBot (裝置連結: that computer's files are its own). Kept a week, in the data folder. use crate::tools::{Place, Target}; use serde::{Deserialize, Serialize}; use std::path::PathBuf; /// Kept this long. const KEEP_DAYS: i64 = 7; /// A file bigger than this isn't kept (it can't be put back; /rewind says so). pub const MAX_FILE_BYTES: usize = 2 * 1024 * 1024; /// One file as it was before a turn changed it. #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] pub struct Entry { /// When it was kept. pub at: i64, /// The person's message that started the turn (its `at`). pub turn: i64, /// The computer's name, to show. pub computer: String, pub place: Place, pub path: String, /// Its content before (the name it is kept under); None: the file wasn't there. pub before: Option, /// Too big to keep: it can't be put back. #[serde(default)] pub too_big: bool, } fn dir() -> PathBuf { crate::model::State::path().parent().map(|d| d.join("checkpoints")).unwrap_or_else(|| std::env::temp_dir().join("anybot-checkpoints")) } fn log_of(bot: u64) -> PathBuf { dir().join(format!("bot-{bot}.jsonl")) } fn blob(name: &str) -> PathBuf { dir().join("blobs").join(name) } /// This bot's kept files, oldest first (a week's). pub fn entries(bot: u64) -> Vec { let since = crate::model::now_ms() - KEEP_DAYS * 86_400_000; std::fs::read_to_string(log_of(bot)).unwrap_or_default().lines().filter_map(|l| serde_json::from_str::(l).ok()).filter(|e| e.at >= since).collect() } fn write_all(bot: u64, list: &[Entry]) -> Result<(), String> { let text: String = list.iter().filter_map(|e| serde_json::to_string(e).ok()).map(|l| l + "\n").collect(); std::fs::create_dir_all(dir()).map_err(|e| e.to_string())?; std::fs::write(log_of(bot), text).map_err(|e| e.to_string()) } /// Before edit_file changes `args`' file on `target` in the turn that `turn` started: keep it as /// it is now (once per turn and file). Nothing on another AnyBot; a failure only goes to the log. pub fn before_edit(bot: u64, turn: i64, target: &Target, args: &str) { if turn == 0 { return; } let path = crate::tools::arg_str(&crate::tools::args_of(args), "path"); if path.trim().is_empty() { return; } let Some(spot) = crate::tools::file_spot(target, &path) else { return }; let (place, path) = match spot { Ok(s) => s, Err(e) => { log::info!("檢查點:{path} 找不到位置:{e}"); return; } }; let mut list = entries(bot); if list.iter().any(|e| e.turn == turn && e.place == place && e.path == path) { return; } let (before, too_big) = match crate::tools::file_now(&place, &path) { Ok(None) => (None, false), Ok(Some(b)) if b.len() > MAX_FILE_BYTES => (None, true), Ok(Some(b)) => match keep(&b) { Ok(name) => (Some(name), false), Err(e) => { log::warn!("檢查點:存不了 {path}:{e}"); return; } }, Err(e) => { log::warn!("檢查點:讀不到 {path}:{e}"); return; } }; list.push(Entry { at: crate::model::now_ms(), turn, computer: target.name.clone(), place, path, before, too_big }); if let Err(e) = write_all(bot, &list) { log::warn!("檢查點:寫不進紀錄:{e}"); } } /// Keep a file's content under the name of its hash (the same content kept once). fn keep(bytes: &[u8]) -> Result { let name: String = ring::digest::digest(&ring::digest::SHA256, bytes).as_ref().iter().map(|x| format!("{x:02x}")).collect(); let p = blob(&name); std::fs::create_dir_all(dir().join("blobs")).map_err(|e| e.to_string())?; // (Written again when already there: its time says it is still in use, for prune.) std::fs::write(&p, bytes).map_err(|e| e.to_string())?; Ok(name) } /// The files the turns from `turn` on changed (each file once), to show. pub fn files_since(list: &[Entry], turn: i64) -> Vec<&Entry> { let mut seen: Vec<&Entry> = vec![]; for e in list.iter().filter(|e| e.turn >= turn) { if !seen.iter().any(|s| s.place == e.place && s.path == e.path) { seen.push(e); } } seen } /// Put back every file the turns from `turn` on changed, as it was before them (newest change /// undone first, so each file ends as it was before the first). Those entries are used up. /// One line per file. pub fn restore(bot: u64, turn: i64) -> Vec { let list = entries(bot); let (undo, keep_list): (Vec, Vec) = list.into_iter().partition(|e| e.turn >= turn); let mut lines: Vec<(String, String)> = vec![]; for e in undo.iter().rev() { let what = if e.computer.is_empty() { e.path.clone() } else { format!("{}({})", e.path, e.computer) }; let r = if e.too_big { Err("太大(超過 2 MB),當時沒有存".to_string()) } else { match &e.before { None => crate::tools::file_put(&e.place, &e.path, None).map(|_| "刪掉了(那時還沒有這個檔案)"), Some(name) => std::fs::read(blob(name)).map_err(|err| format!("存的內容不見了:{err}")).and_then(|b| crate::tools::file_put(&e.place, &e.path, Some(&b))).map(|_| "還原了"), } }; // (Each file is reported once: by the change undone last, the one that counts.) lines.retain(|l| l.0 != what); lines.push((what.clone(), match r { Ok(word) => format!("{what}:{word}"), Err(err) => format!("{what}:沒有還原,{err}"), })); } if let Err(e) = write_all(bot, &keep_list) { log::warn!("檢查點:寫不進紀錄:{e}"); } lines.into_iter().map(|(_, l)| l).collect() } /// Kept content no entry has used for longer than a week goes (at start). pub fn prune() { let Ok(rd) = std::fs::read_dir(dir().join("blobs")) else { return }; let old = std::time::SystemTime::now() - std::time::Duration::from_secs((KEEP_DAYS as u64 + 1) * 86_400); for e in rd.flatten() { if e.metadata().and_then(|m| m.modified()).is_ok_and(|t| t < old) { let _ = std::fs::remove_file(e.path()); } } } /// What 「/rewind …」 asks for. #[derive(Clone, Debug, PartialEq)] pub enum Rewind { /// The list of points. List, /// Back to point N (1 = the newest): files, chat, or both. To { n: usize, files: bool, chat: bool }, } /// 「/rewind」, 「/rewind 2」, 「/rewind 2 檔案」, 「/rewind 2 對話」 (None: not this command; /// Some(Err) when the words after it can't be read). pub fn command(text: &str) -> Option> { let rest = text.trim().strip_prefix("/rewind")?; if !(rest.is_empty() || rest.starts_with(char::is_whitespace)) { return None; } let mut words = rest.split_whitespace(); let Some(n) = words.next() else { return Some(Ok(Rewind::List)) }; let Ok(n) = n.parse::() else { return Some(Err(format!("「{n}」不是編號:先打 /rewind 看有哪些點,再打 /rewind 編號"))) }; if n == 0 { return Some(Err("編號從 1 開始".into())); } let (files, chat) = match words.next() { None => (true, true), Some("檔案" | "files" | "code") => (true, false), Some("對話" | "chat" | "conversation") => (false, true), Some(w) => return Some(Err(format!("「{w}」看不懂:後面可以加「檔案」(只退檔案)或「對話」(只退對話),不加就兩個都退"))), }; Some(Ok(Rewind::To { n, files, chat })) } #[cfg(test)] mod tests { use super::*; #[test] fn the_words_after_rewind() { assert_eq!(command("/rewind"), Some(Ok(Rewind::List))); assert_eq!(command(" /rewind 2 "), Some(Ok(Rewind::To { n: 2, files: true, chat: true }))); assert_eq!(command("/rewind 1 檔案"), Some(Ok(Rewind::To { n: 1, files: true, chat: false }))); assert_eq!(command("/rewind 3 對話"), Some(Ok(Rewind::To { n: 3, files: false, chat: true }))); assert!(matches!(command("/rewind x"), Some(Err(_))) && matches!(command("/rewind 0"), Some(Err(_))) && matches!(command("/rewind 1 全部"), Some(Err(_)))); assert_eq!(command("/rewinder"), None); assert_eq!(command("請 /rewind"), None); } /// Three files changed over two turns: going back to the first puts all three back (one that /// didn't exist goes); going back to the second only what that turn changed. #[test] fn rewinding_puts_the_files_back() { let bot = 900_000 + std::process::id() as u64; let w = std::env::temp_dir().join(format!("anybot-rewind-{}", std::process::id())); let _ = std::fs::remove_dir_all(&w); std::fs::create_dir_all(&w).unwrap(); let _ = std::fs::remove_file(log_of(bot)); let t = Target { name: "這台".into(), place: Place::Local { workdir: w.clone() } }; std::fs::write(w.join("a.txt"), "a0").unwrap(); std::fs::write(w.join("b.txt"), "b0").unwrap(); let edit = |turn: i64, f: &str, text: &str| { before_edit(bot, turn, &t, &serde_json::json!({"path": f, "new_text": text}).to_string()); std::fs::write(w.join(f), text).unwrap(); }; edit(100, "a.txt", "a1"); edit(100, "a.txt", "a2"); // (the same turn: kept once, as it was before the turn) edit(100, "new.txt", "n1"); edit(200, "b.txt", "b1"); edit(200, "a.txt", "a3"); assert_eq!(entries(bot).len(), 4); assert_eq!(files_since(&entries(bot), 100).len(), 3); assert_eq!(files_since(&entries(bot), 200).len(), 2); // Back to the second turn: b and a as they were before it. let lines = restore(bot, 200); assert_eq!(lines.len(), 2, "{lines:?}"); assert_eq!(std::fs::read_to_string(w.join("a.txt")).unwrap(), "a2"); assert_eq!(std::fs::read_to_string(w.join("b.txt")).unwrap(), "b0"); assert_eq!(std::fs::read_to_string(w.join("new.txt")).unwrap(), "n1"); // Then to the first: everything as it was, the new file gone. let lines = restore(bot, 100); assert!(lines.iter().any(|l| l.contains("new.txt") && l.contains("刪掉了")), "{lines:?}"); assert_eq!(std::fs::read_to_string(w.join("a.txt")).unwrap(), "a0"); assert!(!w.join("new.txt").exists()); assert!(entries(bot).is_empty(), "used up"); // Too big to keep: said, not pretended. std::fs::write(w.join("big.bin"), vec![b'x'; MAX_FILE_BYTES + 1]).unwrap(); edit(300, "big.bin", "small"); assert!(restore(bot, 300)[0].contains("太大")); let _ = std::fs::remove_file(log_of(bot)); let _ = std::fs::remove_dir_all(&w); } }