Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/agent-archive/blob/main/src/core.rs # agent-archive aien-dev/agent-archive Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `agent-archive / src / core.rs` 370 lines · 16587 bytes Raw Blame History 1 //! Record schema, archive store (records, raw mirror, latest views, state cursors). 2 use chrono::{DateTime, SecondsFormat, TimeZone, Utc}; 3 use serde_json::{json, Value}; 4 use std::collections::{HashMap, HashSet, VecDeque}; 5 use std::fs::{self, File, OpenOptions}; 6 use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write}; 7 use std::path::{Path, PathBuf}; 8 use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}; 9 use std::path::Component; 10 11 /// New archive paths are private before they can hold data. Existing paths must 12 /// already belong to this process and exclude group and other users. 13 fn private_check(path: &Path, m: &fs::Metadata, directory: bool) -> std::io::Result<()> { 14 use std::io::{Error, ErrorKind}; 15 if m.uid() != unsafe { libc::geteuid() } 16 || (m.mode() & 0o077) != 0 17 || if directory { !m.file_type().is_dir() } else { !m.file_type().is_file() } 18 { 19 return Err(Error::new(ErrorKind::PermissionDenied, format!("unsafe archive path: {}", path.display()))); 20 } 21 Ok(()) 22 } 23 24 fn private_metadata(path: &Path, directory: bool) -> std::io::Result<()> { 25 private_check(path, &fs::symlink_metadata(path)?, directory) 26 } 27 28 pub fn private_dir(root: &Path, path: &Path) -> std::io::Result<()> { 29 use std::io::{Error, ErrorKind}; 30 if !root.exists() { 31 fs::DirBuilder::new().recursive(true).mode(0o700).create(root)?; 32 } 33 private_metadata(root, true)?; 34 let relative = path.strip_prefix(root).map_err(|_| Error::new(ErrorKind::InvalidInput, "path outside archive"))?; 35 let mut current = root.to_path_buf(); 36 for part in relative.components() { 37 if let Component::Normal(name) = part { 38 current.push(name); 39 if !current.exists() { fs::DirBuilder::new().mode(0o700).create(¤t)?; } 40 private_metadata(¤t, true)?; 41 } else { 42 return Err(Error::new(ErrorKind::InvalidInput, "invalid archive path")); 43 } 44 } 45 Ok(()) 46 } 47 48 /// Check an existing archive directory chain without creating anything. Ok(false) when the root or 49 /// a component does not exist yet; any unsafe component is an error. 50 pub fn private_existing_dir(root: &Path, path: &Path) -> std::io::Result { 51 use std::io::{Error, ErrorKind}; 52 let relative = path.strip_prefix(root).map_err(|_| Error::new(ErrorKind::InvalidInput, "path outside archive"))?; 53 let mut current = root.to_path_buf(); 54 let mut parts = vec![None]; 55 for part in relative.components() { 56 let Component::Normal(name) = part else { return Err(Error::new(ErrorKind::InvalidInput, "invalid archive path")) }; 57 parts.push(Some(name)); 58 } 59 for name in parts { 60 if let Some(name) = name { current.push(name); } 61 match fs::symlink_metadata(¤t) { 62 Ok(m) => private_check(¤t, &m, true)?, 63 Err(e) if e.kind() == ErrorKind::NotFound => return Ok(false), 64 Err(e) => return Err(e), 65 } 66 } 67 Ok(true) 68 } 69 70 /// Open an existing archive file for reading; Ok(None) when absent. The owner, mode and type are 71 /// checked on the opened descriptor, and O_NOFOLLOW refuses a symlink. 72 pub fn private_open(path: &Path) -> std::io::Result> { 73 use std::io::{Error, ErrorKind}; 74 match OpenOptions::new().read(true).custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK).open(path) { 75 Ok(f) => { private_check(path, &f.metadata()?, false)?; Ok(Some(f)) } 76 Err(e) if e.kind() == ErrorKind::NotFound => Ok(None), 77 Err(e) if e.raw_os_error() == Some(libc::ELOOP) => 78 Err(Error::new(ErrorKind::PermissionDenied, format!("unsafe archive path: {}", path.display()))), 79 Err(e) => Err(e), 80 } 81 } 82 83 pub fn private_read_to_string(path: &Path) -> std::io::Result> { 84 let Some(mut f) = private_open(path)? else { return Ok(None) }; 85 let mut s = String::new(); 86 f.read_to_string(&mut s)?; 87 Ok(Some(s)) 88 } 89 90 /// One agent's record date files, sorted; empty when the agent has no record directory yet. 91 pub fn record_files(root: &Path, agent: &str) -> std::io::Result> { 92 let dir = root.join("records").join(agent); 93 if !private_existing_dir(root, &dir)? { return Ok(Vec::new()); } 94 let mut files = Vec::new(); 95 for e in fs::read_dir(&dir)? { files.push(e?.path()); } 96 files.sort(); 97 Ok(files) 98 } 99 100 pub fn private_file(path: &Path) -> std::io::Result<()> { 101 match fs::symlink_metadata(path) { 102 Ok(_) => private_metadata(path, false), 103 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), 104 Err(e) => Err(e), 105 } 106 } 107 108 pub fn private_append(path: &Path) -> std::io::Result { 109 private_file(path)?; 110 OpenOptions::new().create(true).append(true).mode(0o600).open(path) 111 } 112 113 pub fn private_copy(root: &Path, src: &Path, dst: &Path) -> std::io::Result<()> { 114 private_dir(root, dst.parent().unwrap())?; 115 private_file(dst)?; 116 let tmp = dst.with_extension("part"); 117 let mut out = OpenOptions::new().write(true).create_new(true).mode(0o600).open(&tmp)?; 118 let result = File::open(src).and_then(|mut input| std::io::copy(&mut input, &mut out)) 119 .and_then(|_| fs::rename(&tmp, dst)); 120 if result.is_err() { let _ = fs::remove_file(&tmp); } 121 result.map(|_| ()) 122 } 123 124 pub const LATEST_LINES: usize = 20000; 125 pub const TXT_MAX_CHARS: usize = 8000; 126 pub const AGENTS: [&str; 6] = ["claude", "codex", "opencode", "gemini", "muse", "omp"]; 127 128 #[derive(Clone, Debug, PartialEq)] 129 pub struct Record { 130 pub ts: String, 131 pub agent: String, 132 pub host: String, 133 pub session: String, 134 pub role: String, 135 pub text: String, 136 pub model: Option, 137 pub cwd: Option, 138 pub src_path: String, 139 pub src_pos: u64, 140 } 141 142 impl Record { 143 pub fn to_json(&self) -> Value { 144 json!({"ts":self.ts,"agent":self.agent,"host":self.host,"session":self.session, 145 "role":self.role,"text":self.text,"model":self.model,"cwd":self.cwd, 146 "src":{"path":self.src_path,"pos":self.src_pos}}) 147 } 148 pub fn from_json(v: &Value) -> Option { 149 let s = |k: &str| v.get(k).and_then(|x| x.as_str()).map(String::from); 150 Some(Record { 151 ts: s("ts")?, agent: s("agent")?, host: s("host")?, session: s("session")?, 152 role: s("role")?, text: s("text")?, model: s("model"), cwd: s("cwd"), 153 src_path: v.pointer("/src/path")?.as_str()?.to_string(), 154 src_pos: v.pointer("/src/pos")?.as_u64()?, 155 }) 156 } 157 pub fn date(&self) -> &str { &self.ts[..10] } 158 pub fn key(&self) -> u64 { 159 // FNV-1a over the identity (agent, host, session, role, src path, src pos). 160 let mut h: u64 = 0xcbf29ce484222325; 161 for part in [self.agent.as_str(), &self.host, &self.session, &self.role, &self.src_path] { 162 for b in part.bytes().chain(std::iter::once(0u8)) { h ^= b as u64; h = h.wrapping_mul(0x100000001b3); } 163 } 164 for b in self.src_pos.to_le_bytes() { h ^= b as u64; h = h.wrapping_mul(0x100000001b3); } 165 h 166 } 167 pub fn txt_line(&self) -> String { 168 let mut t: String = self.text.chars().take(TXT_MAX_CHARS).collect(); 169 if self.text.chars().count() > TXT_MAX_CHARS { t.push_str(" ...[truncated]"); } 170 let t = t.replace('\r', "").replace('\n', "\\n"); 171 let s8: String = self.session.chars().take(8).collect(); 172 format!("[{} {} {}] {}", self.ts, s8, self.role, t) 173 } 174 } 175 176 /// Normalise an RFC3339 string to millisecond UTC "…Z". None if unparseable. 177 pub fn norm_ts(s: &str) -> Option { 178 DateTime::parse_from_rfc3339(s).ok().map(|d| d.with_timezone(&Utc).to_rfc3339_opts(SecondsFormat::Millis, true)) 179 } 180 pub fn ts_from_ms(ms: i64) -> Option { 181 Utc.timestamp_millis_opt(ms).single().map(|d| d.to_rfc3339_opts(SecondsFormat::Millis, true)) 182 } 183 pub fn ts_from_secs_nanos(s: i64, n: u32) -> Option { 184 Utc.timestamp_opt(s, n).single().map(|d| d.to_rfc3339_opts(SecondsFormat::Millis, true)) 185 } 186 187 pub struct Store { 188 pub root: PathBuf, 189 state: HashMap, 190 state_dirty: HashSet, 191 seen: HashMap>, 192 pub fresh: VecDeque, // unused window staging 193 latest: HashMap>, 194 latest_dirty: HashSet, 195 pub emitted: HashMap, 196 appenders: HashMap, 197 } 198 199 impl Store { 200 pub fn open(root: &Path) -> std::io::Result { 201 for d in ["records", "raw", "latest", "state"] { private_dir(root, &root.join(d))?; } 202 let mut s = Store { root: root.to_path_buf(), state: HashMap::new(), state_dirty: HashSet::new(), 203 seen: HashMap::new(), fresh: VecDeque::new(), latest: HashMap::new(), latest_dirty: HashSet::new(), 204 emitted: HashMap::new(), appenders: HashMap::new() }; 205 for a in AGENTS { 206 if let Some(t) = private_read_to_string(&root.join("state").join(format!("{a}.json")))? { 207 if let Ok(v) = serde_json::from_str::(&t) { s.state.insert(a.to_string(), v); } 208 } 209 } 210 Ok(s) 211 } 212 213 // ---- cursors ---- 214 pub fn cursor(&self, agent: &str, key: &str) -> Option<&Value> { self.state.get(agent)?.get(key) } 215 pub fn set_cursor(&mut self, agent: &str, key: &str, v: Value) { 216 let e = self.state.entry(agent.to_string()).or_insert_with(|| json!({})); 217 e[key] = v; 218 self.state_dirty.insert(agent.to_string()); 219 } 220 pub fn save_state(&mut self) -> std::io::Result<()> { 221 let dirty: Vec = self.state_dirty.drain().collect(); 222 for a in dirty { 223 atomic_write(&self.root, &self.root.join("state").join(format!("{a}.json")), serde_json::to_string(&self.state[&a]).unwrap().as_bytes())?; 224 } 225 Ok(()) 226 } 227 228 // ---- records ---- 229 /// Append a record. `check_dup`: consult the existing date file first (used when a source is re-read after state loss). 230 pub fn emit(&mut self, r: Record, check_dup: bool) -> std::io::Result { 231 let dir = self.root.join("records").join(&r.agent); 232 private_dir(&self.root, &dir)?; 233 let path = dir.join(format!("{}.jsonl", r.date())); 234 if check_dup && !self.seen.contains_key(&path) { 235 let mut set = HashSet::new(); 236 if let Some(f) = private_open(&path)? { 237 for l in BufReader::new(f).lines() { 238 if let Some(rec) = serde_json::from_str::(&l?).ok().and_then(|v| Record::from_json(&v)) { set.insert(rec.key()); } 239 } 240 } 241 self.seen.insert(path.clone(), set); 242 } 243 let key = r.key(); 244 if self.seen.get(&path).is_some_and(|set| set.contains(&key)) { return Ok(false); } 245 // Validate and load the history for the latest view before anything is appended. 246 self.latest_for(&r.agent)?; 247 if !self.appenders.contains_key(&path) { 248 if self.appenders.len() > 64 { self.appenders.clear(); } 249 self.appenders.insert(path.clone(), private_append(&path)?); 250 } 251 let mut line = serde_json::to_string(&r.to_json()).unwrap(); 252 line.push('\n'); 253 self.appenders.get_mut(&path).unwrap().write_all(line.as_bytes())?; 254 if let Some(set) = self.seen.get_mut(&path) { set.insert(key); } 255 *self.emitted.entry(r.agent.clone()).or_insert(0) += 1; 256 let agent = r.agent.clone(); 257 let v = self.latest_for(&agent)?; 258 v.push((r.ts.clone(), r)); 259 if v.len() > LATEST_LINES * 2 { v.sort_by(|a, b| a.0.cmp(&b.0)); let n = v.len() - LATEST_LINES; v.drain(..n); } 260 self.latest_dirty.insert(agent); 261 Ok(true) 262 } 263 264 fn latest_for(&mut self, agent: &str) -> std::io::Result<&mut Vec<(String, Record)>> { 265 if !self.latest.contains_key(agent) { 266 let v = load_tail(&self.root, agent, LATEST_LINES)?; 267 self.latest.insert(agent.to_string(), v); 268 } 269 Ok(self.latest.get_mut(agent).unwrap()) 270 } 271 272 /// End of pass: flush cursors and rewrite latest views for agents that got new records. 273 pub fn finish_pass(&mut self) -> std::io::Result<()> { 274 self.appenders.clear(); 275 self.seen.clear(); 276 let dirty: Vec = self.latest_dirty.drain().collect(); 277 for a in dirty { 278 let v = self.latest.get_mut(&a).unwrap(); 279 v.sort_by(|x, y| x.0.cmp(&y.0)); 280 if v.len() > LATEST_LINES { let n = v.len() - LATEST_LINES; v.drain(..n); } 281 let mut txt = String::new(); 282 let mut js = String::new(); 283 for (_, r) in v.iter() { 284 txt.push_str(&r.txt_line()); txt.push('\n'); 285 js.push_str(&serde_json::to_string(&r.to_json()).unwrap()); js.push('\n'); 286 } 287 atomic_write(&self.root, &self.root.join("latest").join(format!("{a}.txt")), txt.as_bytes())?; 288 atomic_write(&self.root, &self.root.join("latest").join(format!("{a}.jsonl")), js.as_bytes())?; 289 } 290 self.save_state() 291 } 292 } 293 294 pub fn atomic_write(root: &Path, path: &Path, data: &[u8]) -> std::io::Result<()> { 295 private_dir(root, path.parent().unwrap())?; 296 private_file(path)?; 297 let tmp = path.with_extension(format!("tmp{}", std::process::id())); 298 let mut f = OpenOptions::new().write(true).create_new(true).mode(0o600).open(&tmp)?; 299 let result = f.write_all(data).and_then(|_| f.sync_all()).and_then(|_| fs::rename(&tmp, path)); 300 if result.is_err() { let _ = fs::remove_file(&tmp); } 301 result 302 } 303 304 /// Last `n` records for an agent, read from the newest date files backwards. 305 pub fn load_tail(root: &Path, agent: &str, n: usize) -> std::io::Result> { 306 let files = record_files(root, agent)?; 307 let mut out: Vec<(String, Record)> = Vec::new(); 308 for f in files.iter().rev() { 309 let Some(fh) = private_open(f)? else { continue }; 310 for l in BufReader::new(fh).lines() { 311 if let Some(r) = serde_json::from_str::(&l?).ok().and_then(|v| Record::from_json(&v)) { out.push((r.ts.clone(), r)); } 312 } 313 if out.len() >= n { break; } 314 } 315 out.sort_by(|a, b| a.0.cmp(&b.0)); 316 if out.len() > n { let k = out.len() - n; out.drain(..k); } 317 Ok(out) 318 } 319 320 /// Tail an append-only JSONL source from `cursor`: calls `f(line, byte_pos)` for every complete line, mirrors the 321 /// bytes verbatim into `raw_path`, and returns the new cursor. Returns (new_cursor, reset) where reset means the source 322 /// shrank and was re-read from 0. 323 pub fn tail_lines(root: &Path, src: &Path, raw_path: &Path, cursor: u64, mut f: F) -> std::io::Result<(u64, bool)> { 324 let len = fs::metadata(src)?.len(); 325 let (mut pos, reset) = if len < cursor { (0, true) } else { (cursor, false) }; 326 if len == pos { return Ok((pos, reset)); } 327 let mut fh = File::open(src)?; 328 fh.seek(SeekFrom::Start(pos))?; 329 let mut rd = BufReader::with_capacity(1 << 20, fh.take(len - pos)); 330 private_dir(root, raw_path.parent().unwrap())?; 331 let mut raw = private_append(raw_path)?; 332 let mut raw_len = raw.metadata()?.len(); 333 let mut buf = Vec::new(); 334 loop { 335 buf.clear(); 336 let n = rd.read_until(b'\n', &mut buf)?; 337 if n == 0 { break; } 338 if buf.last() != Some(&b'\n') { break; } // partial last line: leave for next pass 339 let start = pos; 340 pos += n as u64; 341 // verbatim mirror: write only the bytes the mirror does not have yet 342 if pos > raw_len { 343 let skip = raw_len.saturating_sub(start) as usize; 344 raw.write_all(&buf[skip.min(buf.len())..])?; 345 raw_len = pos; 346 } 347 let line = String::from_utf8_lossy(&buf[..n - 1]); 348 let line = line.trim_end_matches('\r'); 349 if !line.is_empty() { f(line, start); } 350 } 351 Ok((pos, reset)) 352 } 353 354 pub fn walk(dir: &Path, ext: &str, out: &mut Vec) { 355 let Ok(rd) = fs::read_dir(dir) else { return }; 356 for e in rd.flatten() { 357 let p = e.path(); 358 if p.is_dir() { walk(&p, ext, out); } 359 else if p.extension().map(|x| x == ext).unwrap_or(false) { out.push(p); } 360 } 361 } 362 363 pub fn file_stem(p: &Path) -> String { p.file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default() } 364 365 impl Store { 366 /// Number of real sources tracked for an agent (bookkeeping keys with a "xxx:" prefix are not counted). 367 pub fn state_keys(&self, agent: &str) -> usize { 368 self.state.get(agent).and_then(|v| v.as_object()).map(|o| o.keys().filter(|k| !k.contains(':') || k.as_str() == "parts").count()).unwrap_or(0) 369 } 370 }