agent-archive
aien-dev/agent-archive
Brought by drakestapleton
agent-archive / src / main.rs
| 1 | mod collectors; |
| 2 | mod core; |
| 3 | mod pb; |
| 4 | |
| 5 | use collectors::*; |
| 6 | use core::*; |
| 7 | use regex::Regex; |
| 8 | use std::path::PathBuf; |
| 9 | use std::time::{Duration, Instant}; |
| 10 | |
| 11 | fn home() -> PathBuf { PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| "/root".into())) } |
| 12 | fn default_root() -> PathBuf { |
| 13 | std::env::var("AGENT_ARCHIVE_ROOT").map(PathBuf::from).unwrap_or_else(|_| home().join("archive/agent-chats")) |
| 14 | } |
| 15 | |
| 16 | pub fn pass(store: &mut Store, cfg: &Cfg, mac: bool) { |
| 17 | type C = fn(&mut Store, &Cfg) -> std::io::Result<()>; |
| 18 | let steps: [(&str, C); 6] = [("claude", collect_claude), ("codex", collect_codex), ("opencode", collect_opencode), |
| 19 | ("gemini", collect_gemini), ("muse", collect_muse), ("omp", collect_omp)]; |
| 20 | for (name, f) in steps { |
| 21 | if let Err(e) = f(store, cfg) { eprintln!("collector {name} failed: {e}"); } |
| 22 | } |
| 23 | if mac { |
| 24 | if let Err(e) = pull_macbook(store, 300) { eprintln!("macbook pull failed: {e}"); } |
| 25 | if let Err(e) = collect_gemini_mac(store) { eprintln!("gemini macbook parse failed: {e}"); } |
| 26 | } |
| 27 | if let Err(e) = store.finish_pass() { eprintln!("finish_pass failed: {e}"); } |
| 28 | } |
| 29 | |
| 30 | fn summary(store: &mut Store) -> String { |
| 31 | let mut v: Vec<String> = store.emitted.iter().map(|(a, n)| format!("{a}={n}")).collect(); |
| 32 | v.sort(); |
| 33 | store.emitted.clear(); |
| 34 | v.join(" ") |
| 35 | } |
| 36 | |
| 37 | fn arg(args: &[String], name: &str) -> Option<String> { |
| 38 | args.iter().position(|a| a == name).and_then(|i| args.get(i + 1).cloned()) |
| 39 | } |
| 40 | |
| 41 | fn status(root: &std::path::Path) -> std::io::Result<()> { |
| 42 | let today = format!("{}.jsonl", chrono::Utc::now().format("%Y-%m-%d")); |
| 43 | let st = Store::open(root)?; |
| 44 | println!("{:<9} {:<26} {:>12} {:>8} preview", "agent", "last record", "today", "sources"); |
| 45 | for a in AGENTS { |
| 46 | let tail = load_tail(root, a, 1)?; |
| 47 | let (last, prev) = tail.last().map(|(t, r)| (t.clone(), r.text.chars().take(80).collect::<String>().replace('\n', " "))).unwrap_or(("-".into(), String::new())); |
| 48 | let (mut todayn, mut total) = (0, 0); |
| 49 | for f in record_files(root, a)? { |
| 50 | let n = private_read_to_string(&f)?.map(|s| s.lines().count()).unwrap_or(0); |
| 51 | total += n; |
| 52 | if f.file_name().is_some_and(|name| name == today.as_str()) { todayn = n; } |
| 53 | } |
| 54 | let sources = st.state_keys(a); |
| 55 | println!("{:<9} {:<26} {:>6}/{:<6} {:>8} {}", a, last, todayn, total, sources, prev); |
| 56 | } |
| 57 | println!("(today/total records)"); |
| 58 | Ok(()) |
| 59 | } |
| 60 | |
| 61 | fn query(root: &std::path::Path, args: &[String]) -> std::io::Result<()> { |
| 62 | let agent = arg(args, "--agent"); |
| 63 | let since = arg(args, "--since").unwrap_or_default(); |
| 64 | let re = arg(args, "--grep").map(|g| Regex::new(&g).unwrap_or_else(|e| { eprintln!("bad --grep: {e}"); std::process::exit(2) })); |
| 65 | let limit: usize = arg(args, "--limit").and_then(|l| l.parse().ok()).unwrap_or(50); |
| 66 | let json = args.iter().any(|a| a == "--json"); |
| 67 | let agents: Vec<String> = match agent { Some(a) => vec![a], None => AGENTS.iter().map(|s| s.to_string()).collect() }; |
| 68 | let mut hits: Vec<(String, Record)> = vec![]; |
| 69 | for a in agents { |
| 70 | for f in record_files(root, &a)? { |
| 71 | let day = f.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(); |
| 72 | if !since.is_empty() && day.as_str() < &since[..since.len().min(10)] { continue; } |
| 73 | let Some(t) = private_read_to_string(&f)? else { continue }; |
| 74 | for l in t.lines() { |
| 75 | let Some(r) = serde_json::from_str(l).ok().and_then(|v| Record::from_json(&v)) else { continue }; |
| 76 | if !since.is_empty() && r.ts.as_str() < since.as_str() { continue; } |
| 77 | if let Some(re) = &re { if !re.is_match(&r.text) { continue; } } |
| 78 | hits.push((r.ts.clone(), r)); |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | hits.sort_by(|a, b| a.0.cmp(&b.0)); |
| 83 | let skip = hits.len().saturating_sub(limit); |
| 84 | for (_, r) in hits.into_iter().skip(skip) { |
| 85 | if json { println!("{}", serde_json::to_string(&r.to_json()).unwrap()); } else { println!("{} {}", r.agent, r.txt_line()); } |
| 86 | } |
| 87 | Ok(()) |
| 88 | } |
| 89 | |
| 90 | fn refuse(cmd: &str, result: std::io::Result<()>) { |
| 91 | if let Err(e) = result { eprintln!("{cmd} refused: {e}"); std::process::exit(1); } |
| 92 | } |
| 93 | |
| 94 | fn main() { |
| 95 | let args: Vec<String> = std::env::args().skip(1).collect(); |
| 96 | let root = default_root(); |
| 97 | let cmd = args.first().map(|s| s.as_str()).unwrap_or("help"); |
| 98 | let cfg = Cfg { home: home(), host: "spark".into(), mac: true }; |
| 99 | match cmd { |
| 100 | "once" => { |
| 101 | let t = Instant::now(); |
| 102 | let mut st = Store::open(&root).expect("open archive"); |
| 103 | pass(&mut st, &cfg, cfg.mac && !args.iter().any(|a| a == "--no-mac")); |
| 104 | println!("once done in {:.1}s: {}", t.elapsed().as_secs_f64(), summary(&mut st)); |
| 105 | } |
| 106 | "collect" => { |
| 107 | let mut st = Store::open(&root).expect("open archive"); |
| 108 | loop { |
| 109 | pass(&mut st, &cfg, cfg.mac); |
| 110 | let s = summary(&mut st); |
| 111 | if !s.is_empty() { eprintln!("{} +{s}", chrono::Utc::now().format("%H:%M:%S")); } |
| 112 | std::thread::sleep(Duration::from_secs(10)); |
| 113 | } |
| 114 | } |
| 115 | "query" => refuse("query", query(&root, &args[1..])), |
| 116 | "status" => refuse("status", status(&root)), |
| 117 | "debug-pb" => { let b = std::fs::read(&args[1]).expect("read file"); let mut s = String::new(); pb::dump(&b, 0, "", &mut s); print!("{s}"); } |
| 118 | _ => { |
| 119 | println!("agent-archive collect | once [--no-mac] | status | debug-pb FILE | query [--agent A] [--since TS] [--grep RE] [--limit N] [--json]\nroot: {} (override with AGENT_ARCHIVE_ROOT)", root.display()); |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | #[cfg(test)] |
| 125 | mod tests { |
| 126 | use super::*; |
| 127 | use std::fs; |
| 128 | |
| 129 | fn tmp(name: &str) -> PathBuf { |
| 130 | let p = std::env::temp_dir().join(format!("aa-test-{}-{}", name, std::process::id())); |
| 131 | let _ = fs::remove_dir_all(&p); |
| 132 | fs::create_dir_all(&p).unwrap(); |
| 133 | #[cfg(unix)] |
| 134 | fs::set_permissions(&p, std::os::unix::fs::PermissionsExt::from_mode(0o700)).unwrap(); |
| 135 | p |
| 136 | } |
| 137 | fn fixture(n: &str) -> String { fs::read_to_string(format!("{}/tests/fixtures/{n}", env!("CARGO_MANIFEST_DIR"))).unwrap() } |
| 138 | fn count(root: &std::path::Path, agent: &str) -> usize { |
| 139 | fs::read_dir(root.join("records").join(agent)).map(|d| d.flatten().map(|e| fs::read_to_string(e.path()).unwrap().lines().count()).sum()).unwrap_or(0) |
| 140 | } |
| 141 | |
| 142 | #[test] |
| 143 | fn claude_parser_keeps_text_only() { |
| 144 | let lines: Vec<String> = fixture("claude.jsonl").lines().map(String::from).collect(); |
| 145 | let recs: Vec<_> = lines.iter().enumerate().flat_map(|(i, l)| parse_claude(l, "/x/eb18088a.jsonl", i as u64, "spark")).collect(); |
| 146 | assert_eq!(recs.len(), 2); |
| 147 | assert_eq!(recs[0].role, "user"); |
| 148 | assert_eq!(recs[1].text, "Looking now."); |
| 149 | assert_eq!(recs[1].model.as_deref(), Some("claude-opus-5-5")); |
| 150 | assert_eq!(recs[0].ts, "2026-09-26T09:35:16.500Z"); |
| 151 | assert_eq!(recs[0].session, "eb18088a"); |
| 152 | } |
| 153 | |
| 154 | #[test] |
| 155 | fn codex_parser_roles_and_session() { |
| 156 | let mut aux = serde_json::json!({}); |
| 157 | let p = "/s/rollout-2026-09-05T12-11-22-01a0728d-ae40-7261-b95b-8cdb98c5bc5f.jsonl"; |
| 158 | let recs: Vec<_> = fixture("codex.jsonl").lines().flat_map(|l| parse_codex(l, p, 0, "spark", &mut aux)).collect(); |
| 159 | let roles: Vec<&str> = recs.iter().map(|r| r.role.as_str()).collect(); |
| 160 | assert_eq!(roles, ["system", "user", "assistant"]); |
| 161 | assert_eq!(recs[0].session, "01a0728d-ae40-7261-b95b-8cdb98c5bc5f"); |
| 162 | assert_eq!(recs[2].model.as_deref(), Some("gpt-6-astra")); |
| 163 | } |
| 164 | |
| 165 | #[test] |
| 166 | fn muse_parser_user_and_assistant() { |
| 167 | let recs: Vec<_> = fixture("muse.jsonl").lines().flat_map(|l| parse_muse(l, "/m/session.jsonl", 0, "spark")).collect(); |
| 168 | assert_eq!(recs.len(), 2); |
| 169 | assert_eq!((recs[0].role.as_str(), recs[0].text.as_str()), ("user", "ls")); |
| 170 | assert_eq!((recs[1].role.as_str(), recs[1].text.as_str()), ("assistant", "225")); |
| 171 | assert!(recs[0].ts.starts_with("2026-09-20T")); |
| 172 | } |
| 173 | |
| 174 | // Blob built to the layout observed in a real Antigravity step (field numbers: 5.1 time, 19.3.1 user text, 20.1 reply text). |
| 175 | fn tag(f: u32, w: u32) -> Vec<u8> { let mut o = vec![]; let mut v = (f << 3) | w; loop { let c = (v & 0x7f) as u8; v >>= 7; if v == 0 { o.push(c); break; } o.push(c | 0x80); } o } |
| 176 | fn enc_len(f: u32, b: &[u8]) -> Vec<u8> { |
| 177 | let mut o = tag(f, 2); |
| 178 | let mut n = b.len(); |
| 179 | loop { let c = (n & 0x7f) as u8; n >>= 7; if n == 0 { o.push(c); break; } o.push(c | 0x80); } |
| 180 | o.extend_from_slice(b); o |
| 181 | } |
| 182 | fn enc_var(f: u32, mut v: u64) -> Vec<u8> { |
| 183 | let mut o = tag(f, 0); |
| 184 | loop { let c = (v & 0x7f) as u8; v >>= 7; if v == 0 { o.push(c); break; } o.push(c | 0x80); } |
| 185 | o |
| 186 | } |
| 187 | fn step(top: u32, inner: Vec<u8>) -> Vec<u8> { |
| 188 | let time = [enc_var(1, 1790836387), enc_var(2, 593377033)].concat(); |
| 189 | let meta = enc_len(1, &time); |
| 190 | [enc_var(1, 14), enc_len(5, &meta), enc_len(top, &inner)].concat() |
| 191 | } |
| 192 | |
| 193 | #[test] |
| 194 | fn gemini_step_user_and_assistant() { |
| 195 | let user = step(19, [enc_len(2, b"/plan raw"), enc_len(3, &enc_len(1, b" cleaned text"))].concat()); |
| 196 | let (ts, role, text) = parse_gemini_step(14, &user).unwrap(); |
| 197 | assert_eq!((role, text.as_str()), ("user", " cleaned text")); |
| 198 | assert_eq!(ts, "2026-10-01T06:33:07.593Z"); |
| 199 | let asst = step(20, [enc_len(1, b"the answer"), enc_len(3, b"thinking")].concat()); |
| 200 | let (_, role, text) = parse_gemini_step(15, &asst).unwrap(); |
| 201 | assert_eq!((role, text.as_str()), ("assistant", "the answer")); |
| 202 | assert!(parse_gemini_step(132, &asst).is_none()); |
| 203 | } |
| 204 | |
| 205 | #[test] |
| 206 | fn full_pass_incremental_and_dedupe_after_state_loss() { |
| 207 | let home = tmp("home"); |
| 208 | let root = tmp("root"); |
| 209 | let proj = home.join(".claude/projects/-p"); |
| 210 | fs::create_dir_all(&proj).unwrap(); |
| 211 | let f = proj.join("sess1.jsonl"); |
| 212 | let fx = fixture("claude.jsonl"); |
| 213 | fs::write(&f, &fx).unwrap(); |
| 214 | let cfg = Cfg { home: home.clone(), host: "spark".into(), mac: false }; |
| 215 | let mut st = Store::open(&root).unwrap(); |
| 216 | pass(&mut st, &cfg, false); |
| 217 | assert_eq!(count(&root, "claude"), 2); |
| 218 | // raw mirror is byte-identical |
| 219 | assert_eq!(fs::read_to_string(root.join("raw/claude/spark/-p/sess1.jsonl")).unwrap(), fx); |
| 220 | // latest views exist |
| 221 | let txt = fs::read_to_string(root.join("latest/claude.txt")).unwrap(); |
| 222 | assert!(txt.contains("[2026-09-26T09:35:16.500Z sess1 user] Check the live")); |
| 223 | // second pass: nothing new |
| 224 | pass(&mut st, &cfg, false); |
| 225 | assert_eq!(count(&root, "claude"), 2); |
| 226 | // append one complete line and one partial line |
| 227 | let mut more = fx.clone(); |
| 228 | let extra = "{\"type\":\"user\",\"message\":{\"role\":\"user\",\"content\":\"second\"},\"timestamp\":\"2026-09-26T10:00:00.000Z\"}\n"; |
| 229 | more.push_str(extra); |
| 230 | more.push_str("{\"type\":\"user\",\"mess"); |
| 231 | let more_complete_len = fx.len() + extra.len(); |
| 232 | fs::write(&f, &more).unwrap(); |
| 233 | pass(&mut st, &cfg, false); |
| 234 | assert_eq!(count(&root, "claude"), 3); |
| 235 | // lose all cursors: re-read must not duplicate records |
| 236 | fs::remove_dir_all(root.join("state")).unwrap(); |
| 237 | let mut st2 = Store::open(&root).unwrap(); |
| 238 | pass(&mut st2, &cfg, false); |
| 239 | assert_eq!(count(&root, "claude"), 3); |
| 240 | // raw never doubled either |
| 241 | assert!(fs::read_to_string(root.join("raw/claude/spark/-p/sess1.jsonl")).unwrap().starts_with(&fx)); |
| 242 | assert_eq!(fs::metadata(root.join("raw/claude/spark/-p/sess1.jsonl")).unwrap().len() as usize, more_complete_len); |
| 243 | } |
| 244 | |
| 245 | #[test] |
| 246 | fn omp_parser_text_roles_session_cwd_model() { |
| 247 | let mut aux = serde_json::json!({}); |
| 248 | let p = "/s/-tmp/2026-10-27T15-28-55-484Z_01a17dfa-90bc-74e6-a642-d39b97cce56c.jsonl"; |
| 249 | let recs: Vec<_> = fixture("omp.jsonl").lines().flat_map(|l| parse_omp(l, p, 0, "spark", &mut aux)).collect(); |
| 250 | let got: Vec<(&str, &str)> = recs.iter().map(|r| (r.role.as_str(), r.text.as_str())).collect(); |
| 251 | assert_eq!(got, [("user", "testing"), ("assistant", "DONE")]); |
| 252 | assert_eq!(recs[0].session, "01a17dfa-90bc-74e6-a642-d39b97cce56c"); |
| 253 | assert_eq!(recs[0].cwd.as_deref(), Some("/tmp")); |
| 254 | assert_eq!(recs[0].model.as_deref(), Some("spark/qwen3.6-35b-a3b-fp8")); |
| 255 | assert_eq!(recs[1].model.as_deref(), Some("spark/qwen3.6-35b-a3b-fp8")); |
| 256 | assert_eq!(recs[1].ts, "2026-10-27T15:29:55.275Z"); |
| 257 | } |
| 258 | |
| 259 | #[test] |
| 260 | fn omp_pass_profiles_and_nested_subagents() { |
| 261 | let home = tmp("omphome"); |
| 262 | let root = tmp("omproot"); |
| 263 | let fx = fixture("omp.jsonl"); |
| 264 | let def = home.join(".omp/agent/sessions/-tmp/2026-10-27T15-28-55-484Z_aaaa"); |
| 265 | let named = home.join(".omp/profiles/work/agent/sessions/-p"); |
| 266 | fs::create_dir_all(&def).unwrap(); |
| 267 | fs::create_dir_all(&named).unwrap(); |
| 268 | fs::create_dir_all(home.join(".omp/profiles/empty/agent")).unwrap(); |
| 269 | fs::write(def.with_extension("jsonl"), &fx).unwrap(); |
| 270 | fs::write(def.join("0-Sub.jsonl"), &fx).unwrap(); |
| 271 | fs::write(def.join("0-Sub.log"), "not a transcript").unwrap(); |
| 272 | fs::write(named.join("s.jsonl"), &fx).unwrap(); |
| 273 | let cfg = Cfg { home, host: "spark".into(), mac: false }; |
| 274 | let mut st = Store::open(&root).unwrap(); |
| 275 | pass(&mut st, &cfg, false); |
| 276 | // the three files share one session id but differ in src.path, so all six records are kept |
| 277 | assert_eq!(count(&root, "omp"), 6); |
| 278 | let raw = root.join("raw/omp/spark"); |
| 279 | assert_eq!(fs::read_to_string(raw.join("default/-tmp/2026-10-27T15-28-55-484Z_aaaa.jsonl")).unwrap(), fx); |
| 280 | assert_eq!(fs::read_to_string(raw.join("default/-tmp/2026-10-27T15-28-55-484Z_aaaa/0-Sub.jsonl")).unwrap(), fx); |
| 281 | assert_eq!(fs::read_to_string(raw.join("work/-p/s.jsonl")).unwrap(), fx); |
| 282 | assert!(!raw.join("default/-tmp/2026-10-27T15-28-55-484Z_aaaa/0-Sub.log").exists()); |
| 283 | pass(&mut st, &cfg, false); |
| 284 | assert_eq!(count(&root, "omp"), 6); |
| 285 | } |
| 286 | |
| 287 | #[test] |
| 288 | fn missing_harness_dirs_are_a_silent_no_op() { |
| 289 | let home = tmp("emptyhome"); |
| 290 | let root = tmp("emptyroot"); |
| 291 | let cfg = Cfg { home, host: "spark".into(), mac: false }; |
| 292 | let mut st = Store::open(&root).unwrap(); |
| 293 | for a in AGENTS { |
| 294 | let r = match a { |
| 295 | "claude" => collect_claude(&mut st, &cfg), "codex" => collect_codex(&mut st, &cfg), |
| 296 | "opencode" => collect_opencode(&mut st, &cfg), "gemini" => collect_gemini(&mut st, &cfg), |
| 297 | "muse" => collect_muse(&mut st, &cfg), "omp" => collect_omp(&mut st, &cfg), |
| 298 | _ => unreachable!(), |
| 299 | }; |
| 300 | assert!(r.is_ok(), "{a}: {r:?}"); |
| 301 | assert_eq!(count(&root, a), 0); |
| 302 | } |
| 303 | assert_eq!(fs::read_dir(root.join("raw")).unwrap().count(), 0); |
| 304 | } |
| 305 | |
| 306 | #[test] |
| 307 | fn opencode_collects_text_parts() { |
| 308 | let home = tmp("ochome"); |
| 309 | let root = tmp("ocroot"); |
| 310 | let d = home.join(".local/share/opencode"); |
| 311 | fs::create_dir_all(&d).unwrap(); |
| 312 | let c = rusqlite::Connection::open(d.join("opencode.db")).unwrap(); |
| 313 | c.execute_batch("create table session(id text primary key, directory text, model text); |
| 314 | create table message(id text primary key, session_id text, time_created integer, data text); |
| 315 | create table part(id text primary key, message_id text, session_id text, time_created integer, time_updated integer, data text); |
| 316 | insert into session values('ses_1','/home/x',null); |
| 317 | insert into message values('msg_1','ses_1',1790977000000,'{\"role\":\"user\",\"model\":{\"modelID\":\"m1\"}}'); |
| 318 | insert into message values('msg_2','ses_1',1790977001000,'{\"role\":\"assistant\",\"modelID\":\"m1\"}'); |
| 319 | insert into part values('prt_1','msg_1','ses_1',1790977000000,1790977000100,'{\"type\":\"text\",\"text\":\"hi there\"}'); |
| 320 | insert into part values('prt_2','msg_2','ses_1',1790977001000,1790977001100,'{\"type\":\"reasoning\",\"text\":\"think\"}'); |
| 321 | insert into part values('prt_3','msg_2','ses_1',1790977002000,1790977002100,'{\"type\":\"text\",\"text\":\"hello\"}');").unwrap(); |
| 322 | drop(c); |
| 323 | let cfg = Cfg { home, host: "spark".into(), mac: false }; |
| 324 | let mut st = Store::open(&root).unwrap(); |
| 325 | pass(&mut st, &cfg, false); |
| 326 | assert_eq!(count(&root, "opencode"), 2); |
| 327 | let recs = load_tail(&root, "opencode", 10).unwrap(); |
| 328 | assert_eq!(recs[0].1.text, "hi there"); |
| 329 | assert_eq!(recs[0].1.model.as_deref(), Some("m1")); |
| 330 | assert_eq!(recs[1].1.role, "assistant"); |
| 331 | pass(&mut st, &cfg, false); |
| 332 | assert_eq!(count(&root, "opencode"), 2); |
| 333 | } |
| 334 | |
| 335 | #[test] |
| 336 | fn gemini_db_pass() { |
| 337 | let home = tmp("gmhome"); |
| 338 | let root = tmp("gmroot"); |
| 339 | let d = home.join(".gemini/antigravity-cli/conversations"); |
| 340 | fs::create_dir_all(&d).unwrap(); |
| 341 | let c = rusqlite::Connection::open(d.join("conv-1.db")).unwrap(); |
| 342 | c.execute_batch("create table steps(idx integer primary key, step_type integer, step_payload blob);").unwrap(); |
| 343 | let u = step(19, enc_len(3, &enc_len(1, b"question"))); |
| 344 | let a = step(20, enc_len(1, b"answer")); |
| 345 | c.execute("insert into steps values(0,14,?1)", [u]).unwrap(); |
| 346 | c.execute("insert into steps values(1,15,?1)", [a]).unwrap(); |
| 347 | drop(c); |
| 348 | let cfg = Cfg { home, host: "spark".into(), mac: false }; |
| 349 | let mut st = Store::open(&root).unwrap(); |
| 350 | pass(&mut st, &cfg, false); |
| 351 | assert_eq!(count(&root, "gemini"), 2); |
| 352 | assert!(root.join("raw/gemini/spark/antigravity-cli/conversations/conv-1.db").exists()); |
| 353 | pass(&mut st, &cfg, false); |
| 354 | assert_eq!(count(&root, "gemini"), 2); |
| 355 | } |
| 356 | |
| 357 | #[test] |
| 358 | fn latest_window_is_capped_and_sorted() { |
| 359 | let root = tmp("latest"); |
| 360 | let mut st = Store::open(&root).unwrap(); |
| 361 | for i in 0..(LATEST_LINES + 50) { |
| 362 | let r = Record { ts: format!("2026-10-04T00:{:02}:{:02}.{:03}Z", (i / 60000) % 60, (i / 1000) % 60, i % 1000), agent: "claude".into(), host: "spark".into(), |
| 363 | session: "s".into(), role: "user".into(), text: format!("m{i}"), model: None, cwd: None, src_path: "p".into(), src_pos: i as u64 }; |
| 364 | st.emit(r, false).unwrap(); |
| 365 | } |
| 366 | st.finish_pass().unwrap(); |
| 367 | let t = fs::read_to_string(root.join("latest/claude.txt")).unwrap(); |
| 368 | assert_eq!(t.lines().count(), LATEST_LINES); |
| 369 | assert!(t.lines().last().unwrap().ends_with(&format!("m{}", LATEST_LINES + 49))); |
| 370 | assert!(!t.contains("] m0\n")); |
| 371 | } |
| 372 | |
| 373 | #[cfg(unix)] |
| 374 | #[test] |
| 375 | fn archive_files_are_private_with_permissive_umask() { |
| 376 | use std::os::unix::fs::PermissionsExt; |
| 377 | let base = tmp("private-archive"); |
| 378 | let root = base.join("archive"); |
| 379 | let mut st = Store::open(&root).unwrap(); |
| 380 | let r = Record { ts: "2026-10-04T00:00:00.000Z".into(), agent: "claude".into(), |
| 381 | host: "spark".into(), session: "s".into(), role: "user".into(), |
| 382 | text: "synthetic private message".into(), model: None, cwd: None, |
| 383 | src_path: "fixture.jsonl".into(), src_pos: 0 }; |
| 384 | st.emit(r, false).unwrap(); |
| 385 | let source = base.join("source.jsonl"); |
| 386 | fs::write(&source, b"synthetic raw line\n").unwrap(); |
| 387 | tail_lines(&root, &source, &root.join("raw/claude/spark/source.jsonl"), 0, |_, _| {}).unwrap(); |
| 388 | private_copy(&root, &source, &root.join("raw/claude/spark/copied.jsonl")).unwrap(); |
| 389 | st.set_cursor("claude", "source", serde_json::json!(1)); |
| 390 | st.finish_pass().unwrap(); |
| 391 | for dir in ["", "records", "records/claude", "raw", "raw/claude", |
| 392 | "raw/claude/spark", "latest", "state"] { |
| 393 | assert_eq!(fs::metadata(root.join(dir)).unwrap().permissions().mode() & 0o777, 0o700, "{dir}"); |
| 394 | } |
| 395 | for file in ["records/claude/2026-10-04.jsonl", "raw/claude/spark/source.jsonl", |
| 396 | "raw/claude/spark/copied.jsonl", "latest/claude.txt", |
| 397 | "latest/claude.jsonl", "state/claude.json"] { |
| 398 | assert_eq!(fs::metadata(root.join(file)).unwrap().permissions().mode() & 0o777, 0o600, "{file}"); |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | #[cfg(unix)] |
| 403 | #[test] |
| 404 | fn unsafe_archive_root_is_rejected() { |
| 405 | use std::os::unix::fs::PermissionsExt; |
| 406 | let root = tmp("unsafe-archive"); |
| 407 | fs::set_permissions(&root, fs::Permissions::from_mode(0o755)).unwrap(); |
| 408 | assert!(Store::open(&root).is_err()); |
| 409 | let parent = tmp("unsafe-root-link"); |
| 410 | let link = parent.join("archive"); |
| 411 | std::os::unix::fs::symlink(&root, &link).unwrap(); |
| 412 | assert!(Store::open(&link).is_err()); |
| 413 | } |
| 414 | |
| 415 | #[cfg(unix)] |
| 416 | #[test] |
| 417 | fn unsafe_archive_descendant_and_file_are_rejected() { |
| 418 | use std::os::unix::fs::{symlink, PermissionsExt}; |
| 419 | let root = tmp("unsafe-descendant"); |
| 420 | let mut st = Store::open(&root).unwrap(); |
| 421 | let dir = root.join("records/claude"); |
| 422 | fs::create_dir(&dir).unwrap(); |
| 423 | fs::set_permissions(&dir, fs::Permissions::from_mode(0o755)).unwrap(); |
| 424 | let r = Record { ts: "2026-10-04T00:00:00.000Z".into(), agent: "claude".into(), |
| 425 | host: "spark".into(), session: "s".into(), role: "user".into(), text: "private".into(), |
| 426 | model: None, cwd: None, src_path: "synthetic".into(), src_pos: 0 }; |
| 427 | assert!(st.emit(r.clone(), false).is_err()); |
| 428 | fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap(); |
| 429 | let file = dir.join("2026-10-04.jsonl"); |
| 430 | fs::write(&file, b"old\n").unwrap(); |
| 431 | fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).unwrap(); |
| 432 | assert!(st.emit(r.clone(), false).is_err()); |
| 433 | assert_eq!(fs::read(&file).unwrap(), b"old\n"); |
| 434 | fs::remove_file(&file).unwrap(); |
| 435 | symlink(root.join("latest"), &file).unwrap(); |
| 436 | assert!(st.emit(r, false).is_err()); |
| 437 | let victim = root.join("latest/victim"); |
| 438 | fs::write(&victim, b"unchanged").unwrap(); |
| 439 | let target = root.join("latest/claude.txt"); |
| 440 | let tmp = target.with_extension(format!("tmp{}", std::process::id())); |
| 441 | symlink(&victim, &tmp).unwrap(); |
| 442 | assert!(atomic_write(&root, &target, b"private").is_err()); |
| 443 | assert_eq!(fs::read(&victim).unwrap(), b"unchanged"); |
| 444 | } |
| 445 | |
| 446 | #[cfg(unix)] |
| 447 | fn synthetic(src_pos: u64) -> Record { |
| 448 | Record { ts: "2026-10-04T00:00:00.000Z".into(), agent: "claude".into(), host: "spark".into(), |
| 449 | session: "s".into(), role: "user".into(), text: "synthetic".into(), model: None, cwd: None, |
| 450 | src_path: "synthetic".into(), src_pos } |
| 451 | } |
| 452 | |
| 453 | #[cfg(unix)] |
| 454 | #[test] |
| 455 | fn unsafe_state_file_is_refused_before_cursors_load() { |
| 456 | use std::os::unix::fs::{symlink, PermissionsExt}; |
| 457 | let root = tmp("unsafe-state"); |
| 458 | Store::open(&root).unwrap(); |
| 459 | let state = root.join("state/claude.json"); |
| 460 | fs::write(&state, b"{\"source\":7}").unwrap(); |
| 461 | fs::set_permissions(&state, fs::Permissions::from_mode(0o644)).unwrap(); |
| 462 | assert!(Store::open(&root).is_err()); |
| 463 | fs::remove_file(&state).unwrap(); |
| 464 | let outside = tmp("unsafe-state-target").join("cursor.json"); |
| 465 | fs::write(&outside, b"{\"source\":7}").unwrap(); |
| 466 | fs::set_permissions(&outside, fs::Permissions::from_mode(0o600)).unwrap(); |
| 467 | symlink(&outside, &state).unwrap(); |
| 468 | assert!(Store::open(&root).is_err()); |
| 469 | // Control: the same cursor in a private state file loads. |
| 470 | fs::remove_file(&state).unwrap(); |
| 471 | fs::write(&state, b"{\"source\":7}").unwrap(); |
| 472 | fs::set_permissions(&state, fs::Permissions::from_mode(0o600)).unwrap(); |
| 473 | assert_eq!(Store::open(&root).unwrap().cursor("claude", "source"), Some(&serde_json::json!(7))); |
| 474 | } |
| 475 | |
| 476 | #[cfg(unix)] |
| 477 | #[test] |
| 478 | fn unsafe_duplicate_record_is_refused_before_dedup() { |
| 479 | use std::os::unix::fs::{symlink, PermissionsExt}; |
| 480 | let root = tmp("unsafe-dedup"); |
| 481 | let mut st = Store::open(&root).unwrap(); |
| 482 | let dir = root.join("records/claude"); |
| 483 | fs::create_dir(&dir).unwrap(); |
| 484 | fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap(); |
| 485 | let file = dir.join("2026-10-04.jsonl"); |
| 486 | let line = format!("{}\n", serde_json::to_string(&synthetic(0).to_json()).unwrap()); |
| 487 | let outside = tmp("unsafe-dedup-target").join("records.jsonl"); |
| 488 | fs::write(&outside, &line).unwrap(); |
| 489 | fs::set_permissions(&outside, fs::Permissions::from_mode(0o600)).unwrap(); |
| 490 | symlink(&outside, &file).unwrap(); |
| 491 | assert!(st.emit(synthetic(0), true).is_err()); |
| 492 | fs::remove_file(&file).unwrap(); |
| 493 | fs::write(&file, &line).unwrap(); |
| 494 | fs::set_permissions(&file, fs::Permissions::from_mode(0o640)).unwrap(); |
| 495 | assert!(st.emit(synthetic(0), true).is_err()); |
| 496 | assert_eq!(fs::read_to_string(&file).unwrap(), line); |
| 497 | // Control: the same duplicate in a private file is recognised, not appended. |
| 498 | fs::set_permissions(&file, fs::Permissions::from_mode(0o600)).unwrap(); |
| 499 | assert!(!st.emit(synthetic(0), true).unwrap()); |
| 500 | assert_eq!(fs::read_to_string(&file).unwrap(), line); |
| 501 | } |
| 502 | |
| 503 | #[cfg(unix)] |
| 504 | #[test] |
| 505 | fn unsafe_history_record_is_refused_before_latest_view() { |
| 506 | use std::os::unix::fs::PermissionsExt; |
| 507 | let root = tmp("unsafe-history"); |
| 508 | let mut st = Store::open(&root).unwrap(); |
| 509 | let dir = root.join("records/claude"); |
| 510 | fs::create_dir(&dir).unwrap(); |
| 511 | fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap(); |
| 512 | let old = dir.join("2026-10-03.jsonl"); |
| 513 | fs::write(&old, format!("{}\n", serde_json::to_string(&synthetic(1).to_json()).unwrap())).unwrap(); |
| 514 | fs::set_permissions(&old, fs::Permissions::from_mode(0o644)).unwrap(); |
| 515 | assert!(load_tail(&root, "claude", 10).is_err()); |
| 516 | assert!(st.emit(synthetic(2), false).is_err()); |
| 517 | assert!(!dir.join("2026-10-04.jsonl").exists()); |
| 518 | assert!(!root.join("latest/claude.txt").exists()); |
| 519 | // Control: once private, the historical record is read and the new record is accepted. |
| 520 | fs::set_permissions(&old, fs::Permissions::from_mode(0o600)).unwrap(); |
| 521 | assert_eq!(load_tail(&root, "claude", 10).unwrap().len(), 1); |
| 522 | assert!(st.emit(synthetic(2), false).unwrap()); |
| 523 | } |
| 524 | |
| 525 | #[cfg(unix)] |
| 526 | #[test] |
| 527 | fn query_and_status_refuse_unsafe_root_and_records() { |
| 528 | use std::os::unix::fs::{symlink, PermissionsExt}; |
| 529 | let args: Vec<String> = vec![]; |
| 530 | let root = tmp("unsafe-query"); |
| 531 | fs::create_dir_all(root.join("records/claude")).unwrap(); |
| 532 | for d in ["records", "records/claude"] { fs::set_permissions(root.join(d), fs::Permissions::from_mode(0o700)).unwrap(); } |
| 533 | let file = root.join("records/claude/2026-10-04.jsonl"); |
| 534 | fs::write(&file, format!("{}\n", serde_json::to_string(&synthetic(0).to_json()).unwrap())).unwrap(); |
| 535 | fs::set_permissions(&file, fs::Permissions::from_mode(0o600)).unwrap(); |
| 536 | // Controls: a private archive is readable. |
| 537 | assert!(query(&root, &args).is_ok()); |
| 538 | assert!(status(&root).is_ok()); |
| 539 | fs::set_permissions(&root, fs::Permissions::from_mode(0o755)).unwrap(); |
| 540 | assert!(query(&root, &args).is_err()); |
| 541 | assert!(status(&root).is_err()); |
| 542 | fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap(); |
| 543 | let link = tmp("unsafe-query-link").join("archive"); |
| 544 | symlink(&root, &link).unwrap(); |
| 545 | assert!(query(&link, &args).is_err()); |
| 546 | fs::set_permissions(&file, fs::Permissions::from_mode(0o604)).unwrap(); |
| 547 | assert!(query(&root, &args).is_err()); |
| 548 | assert!(status(&root).is_err()); |
| 549 | fs::set_permissions(&file, fs::Permissions::from_mode(0o600)).unwrap(); |
| 550 | let traversal: Vec<String> = ["--agent", "../records"].iter().map(|s| s.to_string()).collect(); |
| 551 | assert!(query(&root, &traversal).is_err()); |
| 552 | } |
| 553 | } |