agent-archive
aien-dev/agent-archive
Brought by drakestapleton
agent-archive / src / collectors.rs
| 1 | //! One collector per agent. Parsers are pure functions (line -> records) so they can be unit tested on fixtures. |
| 2 | use crate::core::*; |
| 3 | use crate::pb; |
| 4 | use rusqlite::{Connection, OpenFlags}; |
| 5 | use serde_json::{json, Value}; |
| 6 | use std::path::{Path, PathBuf}; |
| 7 | use std::os::unix::fs::OpenOptionsExt; |
| 8 | use std::time::{SystemTime, UNIX_EPOCH}; |
| 9 | |
| 10 | pub struct Cfg { |
| 11 | pub home: PathBuf, |
| 12 | pub host: String, |
| 13 | pub mac: bool, |
| 14 | } |
| 15 | |
| 16 | fn rel(p: &Path, base: &Path) -> String { p.strip_prefix(base).unwrap_or(p).to_string_lossy().to_string() } |
| 17 | |
| 18 | /// Join text blocks of a Claude-style content value (string, or array of {type:text,text}). |
| 19 | fn blocks_text(c: &Value, kinds: &[&str]) -> String { |
| 20 | match c { |
| 21 | Value::String(s) => s.clone(), |
| 22 | Value::Array(a) => a.iter() |
| 23 | .filter(|b| b.get("type").or_else(|| b.get("kind")).and_then(|t| t.as_str()).map(|t| kinds.contains(&t)).unwrap_or(false)) |
| 24 | .filter_map(|b| b.get("text").and_then(|t| t.as_str())) |
| 25 | .collect::<Vec<_>>().join("\n"), |
| 26 | _ => String::new(), |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | // ---------------- generic JSONL driver ---------------- |
| 31 | fn drive_jsonl<F>(store: &mut Store, agent: &str, host: &str, base: &Path, file: &Path, parse: F) -> std::io::Result<()> |
| 32 | where F: FnMut(&str, &str, u64, &mut Value) -> Vec<Record> { |
| 33 | drive_jsonl_key(store, agent, host, &rel(file, base), file, parse) |
| 34 | } |
| 35 | |
| 36 | /// `key` is both the cursor key and the path under `raw/<agent>/<host>/`. |
| 37 | fn drive_jsonl_key<F>(store: &mut Store, agent: &str, host: &str, key: &str, file: &Path, mut parse: F) -> std::io::Result<()> |
| 38 | where F: FnMut(&str, &str, u64, &mut Value) -> Vec<Record> { |
| 39 | let cur = store.cursor(agent, key).cloned(); |
| 40 | let (pos0, mut aux) = match &cur { |
| 41 | Some(Value::Object(o)) => (o.get("pos").and_then(|p| p.as_u64()).unwrap_or(0), cur.clone().unwrap()), |
| 42 | Some(v) => (v.as_u64().unwrap_or(0), json!({})), |
| 43 | None => (0, json!({})), |
| 44 | }; |
| 45 | if let Ok(m) = std::fs::metadata(file) { if m.len() == pos0 && cur.is_some() { return Ok(()); } } |
| 46 | let raw = store.root.join("raw").join(agent).join(host).join(key); |
| 47 | let mut recs: Vec<Record> = Vec::new(); |
| 48 | let path_s = file.to_string_lossy().to_string(); |
| 49 | let (newpos, reset) = tail_lines(&store.root, file, &raw, pos0, |line, pos| { recs.extend(parse(line, &path_s, pos, &mut aux)); })?; |
| 50 | let dup = cur.is_none() || reset; |
| 51 | for r in recs { store.emit(r, dup)?; } |
| 52 | let mut nv = if aux.is_object() { aux } else { json!({}) }; |
| 53 | nv["pos"] = json!(newpos); |
| 54 | store.set_cursor(agent, key, nv); |
| 55 | Ok(()) |
| 56 | } |
| 57 | |
| 58 | // ---------------- claude ---------------- |
| 59 | pub fn parse_claude(line: &str, path: &str, pos: u64, host: &str) -> Vec<Record> { |
| 60 | let Ok(v) = serde_json::from_str::<Value>(line) else { return vec![] }; |
| 61 | let role = match v.get("type").and_then(|t| t.as_str()) { Some(r @ ("user" | "assistant")) => r, _ => return vec![] }; |
| 62 | let Some(ts) = v.get("timestamp").and_then(|t| t.as_str()).and_then(norm_ts) else { return vec![] }; |
| 63 | let text = blocks_text(v.pointer("/message/content").unwrap_or(&Value::Null), &["text"]); |
| 64 | if text.trim().is_empty() { return vec![]; } |
| 65 | let session = Path::new(path).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(); |
| 66 | vec![Record { ts, agent: "claude".into(), host: host.into(), session, role: role.into(), text, |
| 67 | model: v.pointer("/message/model").and_then(|m| m.as_str()).map(String::from), |
| 68 | cwd: v.get("cwd").and_then(|m| m.as_str()).map(String::from), src_path: path.into(), src_pos: pos }] |
| 69 | } |
| 70 | |
| 71 | pub fn collect_claude(store: &mut Store, cfg: &Cfg) -> std::io::Result<()> { |
| 72 | let base = cfg.home.join(".claude/projects"); |
| 73 | let mut files = vec![]; walk(&base, "jsonl", &mut files); |
| 74 | for f in files { |
| 75 | let host = cfg.host.clone(); |
| 76 | drive_jsonl(store, "claude", &cfg.host, &base, &f, |l, p, pos, _| parse_claude(l, p, pos, &host))?; |
| 77 | } |
| 78 | Ok(()) |
| 79 | } |
| 80 | |
| 81 | // ---------------- codex ---------------- |
| 82 | fn codex_session(path: &str) -> String { |
| 83 | let stem = Path::new(path).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(); |
| 84 | let b = stem.as_bytes(); |
| 85 | if b.len() >= 36 { |
| 86 | let t = &stem[stem.len() - 36..]; |
| 87 | if t.chars().enumerate().all(|(i, c)| if [8, 13, 18, 23].contains(&i) { c == '-' } else { c.is_ascii_hexdigit() }) { return t.to_string(); } |
| 88 | } |
| 89 | stem |
| 90 | } |
| 91 | |
| 92 | /// `aux` carries the per-file model/cwd learnt from session_meta / turn_context lines. |
| 93 | pub fn parse_codex(line: &str, path: &str, pos: u64, host: &str, aux: &mut Value) -> Vec<Record> { |
| 94 | let Ok(v) = serde_json::from_str::<Value>(line) else { return vec![] }; |
| 95 | match v.get("type").and_then(|t| t.as_str()) { |
| 96 | Some("turn_context") | Some("session_meta") => { |
| 97 | if let Some(m) = v.pointer("/payload/model").and_then(|x| x.as_str()) { aux["model"] = json!(m); } |
| 98 | if let Some(c) = v.pointer("/payload/cwd").and_then(|x| x.as_str()) { aux["cwd"] = json!(c); } |
| 99 | return vec![]; |
| 100 | } |
| 101 | Some("response_item") => {} |
| 102 | _ => return vec![], |
| 103 | } |
| 104 | let p = &v["payload"]; |
| 105 | if p.get("type").and_then(|t| t.as_str()) != Some("message") { return vec![]; } |
| 106 | let role = match p.get("role").and_then(|r| r.as_str()) { Some("user") => "user", Some("assistant") => "assistant", Some("developer") => "system", _ => return vec![] }; |
| 107 | let Some(ts) = v.get("timestamp").and_then(|t| t.as_str()).and_then(norm_ts) else { return vec![] }; |
| 108 | let text = blocks_text(&p["content"], &["input_text", "output_text"]); |
| 109 | if text.trim().is_empty() { return vec![]; } |
| 110 | vec![Record { ts, agent: "codex".into(), host: host.into(), session: codex_session(path), role: role.into(), text, |
| 111 | model: aux.get("model").and_then(|m| m.as_str()).map(String::from), |
| 112 | cwd: aux.get("cwd").and_then(|m| m.as_str()).map(String::from), src_path: path.into(), src_pos: pos }] |
| 113 | } |
| 114 | |
| 115 | pub fn collect_codex(store: &mut Store, cfg: &Cfg) -> std::io::Result<()> { |
| 116 | let base = cfg.home.join(".codex/sessions"); |
| 117 | let mut files = vec![]; walk(&base, "jsonl", &mut files); |
| 118 | for f in files { |
| 119 | let host = cfg.host.clone(); |
| 120 | drive_jsonl(store, "codex", &cfg.host, &base, &f, |l, p, pos, aux| parse_codex(l, p, pos, &host, aux))?; |
| 121 | } |
| 122 | Ok(()) |
| 123 | } |
| 124 | |
| 125 | // ---------------- muse ---------------- |
| 126 | pub fn parse_muse(line: &str, path: &str, pos: u64, host: &str) -> Vec<Record> { |
| 127 | let Ok(v) = serde_json::from_str::<Value>(line) else { return vec![] }; |
| 128 | let Some(pt) = v.get("payload_type").and_then(|t| t.as_str()) else { return vec![] }; // framed retained lines are skipped; raw keeps them |
| 129 | let Some(ts) = v.get("recorded_at").and_then(|t| t.as_i64()).and_then(|us| ts_from_ms(us / 1000)) else { return vec![] }; |
| 130 | let session = v.pointer("/stream/id").and_then(|s| s.as_str()).unwrap_or("").to_string(); |
| 131 | let mk = |role: &str, text: String| Record { ts: ts.clone(), agent: "muse".into(), host: host.into(), session: session.clone(), |
| 132 | role: role.into(), text, model: None, cwd: None, src_path: path.into(), src_pos: pos }; |
| 133 | if pt == "runtime.user_intent.accepted" { |
| 134 | let mut out = vec![]; |
| 135 | if let Some(ms) = v.pointer("/payload/model_messages").and_then(|m| m.as_array()) { |
| 136 | for m in ms { |
| 137 | let t = blocks_text(&m["content"], &["text"]); |
| 138 | if !t.trim().is_empty() { out.push(mk("user", t)); } |
| 139 | } |
| 140 | } |
| 141 | return out; |
| 142 | } |
| 143 | if pt == "runtime.session" && v.pointer("/payload/event/kind").and_then(|k| k.as_str()) == Some("assistant_message_committed") { |
| 144 | if let Some(t) = v.pointer("/payload/event/text").and_then(|t| t.as_str()) { |
| 145 | if !t.trim().is_empty() { return vec![mk("assistant", t.to_string())]; } |
| 146 | } |
| 147 | } |
| 148 | vec![] |
| 149 | } |
| 150 | |
| 151 | pub fn collect_muse(store: &mut Store, cfg: &Cfg) -> std::io::Result<()> { |
| 152 | let base = cfg.home.join(".local/share/muse/sessions"); |
| 153 | let mut files = vec![]; walk(&base, "jsonl", &mut files); |
| 154 | for f in files { |
| 155 | if f.file_name().map(|n| n != "session.jsonl").unwrap_or(true) { continue; } |
| 156 | let host = cfg.host.clone(); |
| 157 | drive_jsonl(store, "muse", &cfg.host, &base, &f, |l, p, pos, _| parse_muse(l, p, pos, &host))?; |
| 158 | } |
| 159 | Ok(()) |
| 160 | } |
| 161 | |
| 162 | // ---------------- omp ---------------- |
| 163 | /// OMP session JSONL: a `session` line (id, cwd), `model_change` lines, and `message` lines whose |
| 164 | /// `message.role` is user / assistant / developer / toolResult. Only text blocks become records. |
| 165 | /// `aux` carries the per-file session id, cwd and model. |
| 166 | pub fn parse_omp(line: &str, path: &str, pos: u64, host: &str, aux: &mut Value) -> Vec<Record> { |
| 167 | let Ok(v) = serde_json::from_str::<Value>(line) else { return vec![] }; |
| 168 | match v.get("type").and_then(|t| t.as_str()) { |
| 169 | Some("session") => { |
| 170 | if let Some(s) = v.get("id").and_then(|x| x.as_str()) { aux["session"] = json!(s); } |
| 171 | if let Some(c) = v.get("cwd").and_then(|x| x.as_str()) { aux["cwd"] = json!(c); } |
| 172 | return vec![]; |
| 173 | } |
| 174 | Some("model_change") => { |
| 175 | if let Some(m) = v.get("model").and_then(|x| x.as_str()) { aux["model"] = json!(m); } |
| 176 | return vec![]; |
| 177 | } |
| 178 | Some("message") => {} |
| 179 | _ => return vec![], |
| 180 | } |
| 181 | let m = &v["message"]; |
| 182 | let role = match m.get("role").and_then(|r| r.as_str()) { Some("user") => "user", Some("assistant") => "assistant", Some("developer") => "system", _ => return vec![] }; |
| 183 | let Some(ts) = v.get("timestamp").and_then(|t| t.as_str()).and_then(norm_ts) else { return vec![] }; |
| 184 | let text = blocks_text(&m["content"], &["text"]); |
| 185 | if text.trim().is_empty() { return vec![]; } |
| 186 | let session = aux.get("session").and_then(|s| s.as_str()).map(String::from).unwrap_or_else(|| { |
| 187 | let stem = Path::new(path).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(); |
| 188 | stem.rsplit_once('_').map(|(_, id)| id.to_string()).unwrap_or(stem) |
| 189 | }); |
| 190 | let model = match (m.get("provider").and_then(|x| x.as_str()), m.get("model").and_then(|x| x.as_str())) { |
| 191 | (Some(p), Some(md)) => Some(format!("{p}/{md}")), |
| 192 | (None, Some(md)) => Some(md.to_string()), |
| 193 | _ => aux.get("model").and_then(|x| x.as_str()).map(String::from), |
| 194 | }; |
| 195 | vec![Record { ts, agent: "omp".into(), host: host.into(), session, role: role.into(), text, model, |
| 196 | cwd: aux.get("cwd").and_then(|m| m.as_str()).map(String::from), src_path: path.into(), src_pos: pos }] |
| 197 | } |
| 198 | |
| 199 | /// Session roots: `~/.omp/agent/sessions` as profile `default`, and `~/.omp/profiles/<name>/agent/sessions`. |
| 200 | /// Raw copies land in `raw/omp/<host>/<profile>/<path relative to the sessions dir>`. |
| 201 | pub fn collect_omp(store: &mut Store, cfg: &Cfg) -> std::io::Result<()> { |
| 202 | let omp = cfg.home.join(".omp"); |
| 203 | let mut roots = vec![("default".to_string(), omp.join("agent/sessions"))]; |
| 204 | if let Ok(rd) = std::fs::read_dir(omp.join("profiles")) { |
| 205 | let mut named: Vec<(String, PathBuf)> = rd.flatten() |
| 206 | .map(|e| (e.file_name().to_string_lossy().to_string(), e.path().join("agent/sessions"))) |
| 207 | .collect(); |
| 208 | named.sort(); |
| 209 | roots.extend(named); |
| 210 | } |
| 211 | for (profile, base) in roots { |
| 212 | let mut files = vec![]; walk(&base, "jsonl", &mut files); |
| 213 | files.sort(); |
| 214 | for f in files { |
| 215 | let key = format!("{profile}/{}", rel(&f, &base)); |
| 216 | let host = cfg.host.clone(); |
| 217 | // A subagent file deleted between walk and read is skipped; every other error stops the pass. |
| 218 | match drive_jsonl_key(store, "omp", &cfg.host, &key, &f, |l, p, pos, aux| parse_omp(l, p, pos, &host, aux)) { |
| 219 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, |
| 220 | r => r?, |
| 221 | } |
| 222 | } |
| 223 | } |
| 224 | Ok(()) |
| 225 | } |
| 226 | |
| 227 | // ---------------- opencode ---------------- |
| 228 | pub fn collect_opencode(store: &mut Store, cfg: &Cfg) -> std::io::Result<()> { |
| 229 | let dbp = cfg.home.join(".local/share/opencode/opencode.db"); |
| 230 | if !dbp.exists() { return Ok(()); } |
| 231 | let conn = match Connection::open_with_flags(&dbp, OpenFlags::SQLITE_OPEN_READ_ONLY) { Ok(c) => c, Err(_) => return Ok(()) }; |
| 232 | let _ = conn.busy_timeout(std::time::Duration::from_secs(5)); |
| 233 | let cur = store.cursor("opencode", "parts").and_then(|v| v.as_str()).unwrap_or("0|").to_string(); |
| 234 | let (ct, cid) = cur.split_once('|').map(|(a, b)| (a.parse::<i64>().unwrap_or(0), b.to_string())).unwrap_or((0, String::new())); |
| 235 | let fresh = store.cursor("opencode", "parts").is_none(); |
| 236 | let now_ms = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as i64).unwrap_or(0); |
| 237 | let sql = "SELECT p.id, p.time_created, p.time_updated, p.data, m.data, s.id, s.directory, s.model \ |
| 238 | FROM part p JOIN message m ON m.id = p.message_id JOIN session s ON s.id = p.session_id \ |
| 239 | WHERE (p.time_created > ?1 OR (p.time_created = ?1 AND p.id > ?2)) AND json_extract(p.data,'$.type') = 'text' \ |
| 240 | ORDER BY p.time_created, p.id"; |
| 241 | let mut st = match conn.prepare(sql) { Ok(s) => s, Err(_) => return Ok(()) }; |
| 242 | let mut rows = match st.query(rusqlite::params![ct, cid]) { Ok(r) => r, Err(_) => return Ok(()) }; |
| 243 | let raw_path = store.root.join("raw/opencode").join(&cfg.host).join("opencode-rows.jsonl"); |
| 244 | private_dir(&store.root, raw_path.parent().unwrap())?; |
| 245 | let mut raw = private_append(&raw_path)?; |
| 246 | let mut last = (ct, cid.clone()); |
| 247 | while let Ok(Some(r)) = rows.next() { |
| 248 | let id: String = r.get(0).unwrap_or_default(); |
| 249 | let tc: i64 = r.get(1).unwrap_or(0); |
| 250 | let tu: i64 = r.get(2).unwrap_or(0); |
| 251 | if now_ms - tu < 30_000 { break; } // still streaming; take it on a later pass |
| 252 | let pdata: String = r.get(3).unwrap_or_default(); |
| 253 | let mdata: String = r.get(4).unwrap_or_default(); |
| 254 | let sid: String = r.get(5).unwrap_or_default(); |
| 255 | let dir: Option<String> = r.get(6).ok(); |
| 256 | let smodel: Option<String> = r.get(7).ok().flatten(); |
| 257 | let (pv, mv): (Value, Value) = (serde_json::from_str(&pdata).unwrap_or(Value::Null), serde_json::from_str(&mdata).unwrap_or(Value::Null)); |
| 258 | use std::io::Write; |
| 259 | let _ = writeln!(raw, "{}", json!({"part_id":id,"session_id":sid,"time_created":tc,"time_updated":tu,"part":pv,"message":mv})); |
| 260 | last = (tc, id.clone()); |
| 261 | let role = match mv.get("role").and_then(|x| x.as_str()) { Some(r @ ("user" | "assistant")) => r, _ => continue }; |
| 262 | let text = pv.get("text").and_then(|t| t.as_str()).unwrap_or(""); |
| 263 | if text.trim().is_empty() { continue; } |
| 264 | let Some(ts) = ts_from_ms(tc) else { continue }; |
| 265 | let model = mv.get("modelID").and_then(|x| x.as_str()).or_else(|| mv.pointer("/model/modelID").and_then(|x| x.as_str())).map(String::from).or(smodel); |
| 266 | let rec = Record { ts, agent: "opencode".into(), host: cfg.host.clone(), session: sid, role: role.into(), text: text.to_string(), |
| 267 | model, cwd: dir, src_path: "opencode.db#part".into(), src_pos: fnv(&id) }; |
| 268 | store.emit(rec, fresh)?; |
| 269 | } |
| 270 | drop(rows); |
| 271 | store.set_cursor("opencode", "parts", json!(format!("{}|{}", last.0, last.1))); |
| 272 | Ok(()) |
| 273 | } |
| 274 | |
| 275 | fn fnv(s: &str) -> u64 { let mut h = 0xcbf29ce484222325u64; for b in s.bytes() { h ^= b as u64; h = h.wrapping_mul(0x100000001b3); } h >> 11 } |
| 276 | |
| 277 | // ---------------- gemini (Antigravity) ---------------- |
| 278 | /// Step blob layout inferred by inspection (UNVERIFIED against any official schema): |
| 279 | /// step_type 14 = user input (text at field 19.3.1, else 19.2), 15 = model response (text at field 20.1; 20.3 is thinking, skipped), |
| 280 | /// timestamp at 5.1 {seconds,nanos}. |
| 281 | pub fn parse_gemini_step(step_type: i64, blob: &[u8]) -> Option<(String, &'static str, String)> { |
| 282 | use pb::{fields, Val}; |
| 283 | let sub = |b: &[u8], f: u32| -> Option<Vec<u8>> { fields(b)?.into_iter().find_map(|(n, v)| if n == f { if let Val::Bytes(x) = v { Some(x.to_vec()) } else { None } } else { None }) }; |
| 284 | let varint = |b: &[u8], f: u32| -> Option<u64> { fields(b)?.into_iter().find_map(|(n, v)| if n == f { if let Val::Varint(x) = v { Some(x) } else { None } } else { None }) }; |
| 285 | let meta = sub(blob, 5)?; |
| 286 | let t = sub(&meta, 1)?; |
| 287 | let ts = ts_from_secs_nanos(varint(&t, 1)? as i64, varint(&t, 2).unwrap_or(0) as u32)?; |
| 288 | let utf = |b: Vec<u8>| String::from_utf8(b).ok(); |
| 289 | match step_type { |
| 290 | 14 => { |
| 291 | let m = sub(blob, 19)?; |
| 292 | let text = sub(&m, 3).and_then(|x| sub(&x, 1)).and_then(utf).or_else(|| sub(&m, 2).and_then(utf))?; |
| 293 | Some((ts, "user", text)) |
| 294 | } |
| 295 | 15 => { |
| 296 | let m = sub(blob, 20)?; |
| 297 | let text = utf(sub(&m, 1)?)?; |
| 298 | Some((ts, "assistant", text)) |
| 299 | } |
| 300 | _ => None, |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | fn gemini_db(store: &mut Store, host: &str, db: &Path, key: &str) -> std::io::Result<()> { |
| 305 | let session = file_stem(db); |
| 306 | let conn = match Connection::open_with_flags(db, OpenFlags::SQLITE_OPEN_READ_ONLY) { Ok(c) => c, Err(_) => return Ok(()) }; |
| 307 | let _ = conn.busy_timeout(std::time::Duration::from_secs(5)); |
| 308 | let cur = store.cursor("gemini", key).and_then(|v| v.as_i64()); |
| 309 | let after = cur.unwrap_or(-1); |
| 310 | let mut st = match conn.prepare("SELECT idx, step_type, step_payload FROM steps WHERE idx > ?1 AND step_type IN (14,15) ORDER BY idx") { Ok(s) => s, Err(_) => return Ok(()) }; |
| 311 | let mut rows = match st.query([after]) { Ok(r) => r, Err(_) => return Ok(()) }; |
| 312 | let mut max = after; |
| 313 | let mut recs = vec![]; |
| 314 | while let Ok(Some(r)) = rows.next() { |
| 315 | let idx: i64 = r.get(0).unwrap_or(0); |
| 316 | let ty: i64 = r.get(1).unwrap_or(0); |
| 317 | let blob: Vec<u8> = r.get(2).unwrap_or_default(); |
| 318 | max = max.max(idx); |
| 319 | if let Some((ts, role, text)) = parse_gemini_step(ty, &blob) { |
| 320 | if text.trim().is_empty() { continue; } |
| 321 | recs.push(Record { ts, agent: "gemini".into(), host: host.into(), session: session.clone(), role: role.into(), text, |
| 322 | model: None, cwd: None, src_path: key.into(), src_pos: idx as u64 }); |
| 323 | } |
| 324 | } |
| 325 | drop(rows); drop(st); |
| 326 | for r in recs { store.emit(r, cur.is_none())?; } |
| 327 | // Steps are appended with increasing idx, but a running step can be rewritten; keep cursor at max seen. |
| 328 | store.set_cursor("gemini", key, json!(max)); |
| 329 | Ok(()) |
| 330 | } |
| 331 | |
| 332 | fn copy_if_changed(store: &mut Store, src: &Path, dst: &Path, sig_key: &str) -> std::io::Result<bool> { |
| 333 | let m = std::fs::metadata(src)?; |
| 334 | let sig = format!("{}:{}", m.len(), m.modified().ok().and_then(|t| t.duration_since(UNIX_EPOCH).ok()).map(|d| d.as_secs()).unwrap_or(0)); |
| 335 | if store.cursor("gemini", sig_key).and_then(|v| v.as_str()) == Some(sig.as_str()) && dst.exists() { return Ok(false); } |
| 336 | private_copy(&store.root, src, dst)?; |
| 337 | store.set_cursor("gemini", sig_key, json!(sig)); |
| 338 | Ok(true) |
| 339 | } |
| 340 | |
| 341 | pub fn collect_gemini(store: &mut Store, cfg: &Cfg) -> std::io::Result<()> { |
| 342 | let base = cfg.home.join(".gemini"); |
| 343 | for sub in ["antigravity-cli", "antigravity-ide", "antigravity"] { |
| 344 | let dir = base.join(sub).join("conversations"); |
| 345 | let Ok(rd) = std::fs::read_dir(&dir) else { continue }; |
| 346 | let mut dbs: Vec<PathBuf> = rd.flatten().map(|e| e.path()).filter(|p| p.extension().map(|x| x == "db").unwrap_or(false)).collect(); |
| 347 | dbs.sort(); |
| 348 | for db in dbs { |
| 349 | let relp = format!("{sub}/conversations/{}", db.file_name().unwrap().to_string_lossy()); |
| 350 | let dst = store.root.join("raw/gemini").join(&cfg.host).join(&relp); |
| 351 | let mut changed_wal = false; |
| 352 | let changed0 = match copy_if_changed(store, &db, &dst, &format!("sig:{relp}")) { Ok(c) => c, Err(e) => { eprintln!("gemini raw copy {relp}: {e}"); true } }; |
| 353 | let wal = db.with_extension("db-wal"); |
| 354 | if wal.metadata().map(|m| m.len() > 0).unwrap_or(false) { |
| 355 | let wc = copy_if_changed(store, &wal, &dst.with_extension("db-wal"), &format!("sig:{relp}-wal")).unwrap_or(false); changed_wal = wc; |
| 356 | } |
| 357 | let k = format!("spark/{relp}"); |
| 358 | let changed = changed0 || changed_wal; |
| 359 | if changed || store.cursor("gemini", &k).is_none() { gemini_db(store, &cfg.host, &db, &k)?; } |
| 360 | } |
| 361 | } |
| 362 | let hist = base.join("antigravity-cli/history.jsonl"); |
| 363 | if hist.exists() { let _ = copy_if_changed(store, &hist, &store.root.join("raw/gemini").join(&cfg.host).join("antigravity-cli/history.jsonl"), "sig:history"); } |
| 364 | Ok(()) |
| 365 | } |
| 366 | |
| 367 | /// Read-only pull of the MacBook's Antigravity conversation DBs (ssh + scp), at most every `every_s` seconds. |
| 368 | pub fn pull_macbook(store: &mut Store, every_s: u64) -> std::io::Result<()> { |
| 369 | use std::process::Command; |
| 370 | let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); |
| 371 | if let Some(t) = store.cursor("gemini", "macpull:last").and_then(|v| v.as_u64()) { if now < t + every_s { return Ok(()); } } |
| 372 | store.set_cursor("gemini", "macpull:last", json!(now)); |
| 373 | let ssh = ["-o", "BatchMode=yes", "-o", "ConnectTimeout=5", "-o", "ControlMaster=auto", "-o", "ControlPath=/tmp/agent-archive-mac-%C", "-o", "ControlPersist=60"]; |
| 374 | let listing = Command::new("ssh").args(ssh).arg("macbook") |
| 375 | .arg("for d in antigravity-cli antigravity-ide antigravity; do find ~/.gemini/$d/conversations -maxdepth 1 -type f \\( -name \"*.db\" -o -name \"*.db-wal\" \\) -exec stat -f \"$d %N %z %m\" {} + 2>/dev/null; done; find ~/.gemini/antigravity-cli -maxdepth 1 -name history.jsonl -exec stat -f \"hist %N %z %m\" {} + 2>/dev/null; true") |
| 376 | .output(); |
| 377 | let out = match listing { Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).to_string(), _ => { eprintln!("macbook unreachable, skipped"); return Ok(()); } }; |
| 378 | for l in out.lines() { |
| 379 | let p: Vec<&str> = l.split(' ').collect(); |
| 380 | if p.len() != 4 { continue; } |
| 381 | let (sub, path, size, mtime) = (p[0], p[1], p[2], p[3]); |
| 382 | let name = path.rsplit('/').next().unwrap_or(""); |
| 383 | let relp = if sub == "hist" { "antigravity-cli/history.jsonl".to_string() } else { format!("{sub}/conversations/{name}") }; |
| 384 | let dst = store.root.join("raw/gemini/macbook").join(&relp); |
| 385 | let sig = format!("{size}:{mtime}"); |
| 386 | let sk = format!("macsig:{relp}"); |
| 387 | if store.cursor("gemini", &sk).and_then(|v| v.as_str()) == Some(sig.as_str()) && dst.exists() { continue; } |
| 388 | private_dir(&store.root, dst.parent().unwrap())?; |
| 389 | private_file(&dst)?; |
| 390 | let tmp = dst.with_extension("part"); |
| 391 | let _out = std::fs::OpenOptions::new().write(true).create_new(true) |
| 392 | .mode(0o600).open(&tmp)?; |
| 393 | let ok = Command::new("scp").args(ssh).arg("-q").arg(format!("macbook:{path}")).arg(&tmp).status().map(|s| s.success()).unwrap_or(false); |
| 394 | if ok { |
| 395 | private_file(&tmp)?; |
| 396 | std::fs::rename(&tmp, &dst)?; |
| 397 | store.set_cursor("gemini", &sk, json!(sig)); |
| 398 | } else { let _ = std::fs::remove_file(&tmp); eprintln!("scp failed: {relp}"); } |
| 399 | } |
| 400 | Ok(()) |
| 401 | } |
| 402 | |
| 403 | /// Parse the already-pulled MacBook copies (raw/gemini/macbook/**/*.db). |
| 404 | pub fn collect_gemini_mac(store: &mut Store) -> std::io::Result<()> { |
| 405 | let base = store.root.join("raw/gemini/macbook"); |
| 406 | if !private_existing_dir(&store.root, &base)? { return Ok(()); } |
| 407 | let mut dbs = vec![]; walk(&base, "db", &mut dbs); dbs.sort(); |
| 408 | for db in dbs { |
| 409 | private_existing_dir(&store.root, db.parent().unwrap())?; |
| 410 | private_file(&db)?; |
| 411 | let relp = rel(&db, &base); |
| 412 | let k = format!("macbook/{relp}"); |
| 413 | let m = std::fs::symlink_metadata(&db)?; |
| 414 | let sig = format!("{}:{}", m.len(), m.modified().ok().and_then(|t| t.duration_since(UNIX_EPOCH).ok()).map(|d| d.as_secs()).unwrap_or(0)); |
| 415 | let sk = format!("msig:{relp}"); |
| 416 | if store.cursor("gemini", &sk).and_then(|v| v.as_str()) == Some(sig.as_str()) { continue; } |
| 417 | gemini_db(store, "macbook", &db, &k)?; |
| 418 | store.set_cursor("gemini", &sk, json!(sig)); |
| 419 | } |
| 420 | Ok(()) |
| 421 | } |