aienos.com
Source of www.aienos.com, served from my own hardware
Brought by drakestapleton
aienos.com / crates / hive-feed / src / source.rs
| 1 | use serde_json::Value; |
| 2 | use std::{collections::HashSet, fs::{self, File}, io::{self, BufRead, BufReader, Read, Seek, SeekFrom}, os::unix::fs::MetadataExt, path::{Path, PathBuf}, process::{Command, Stdio}, time::{Duration, Instant}}; |
| 3 | |
| 4 | const MAX_LINE: usize = 8 * 1024 * 1024; |
| 5 | #[derive(Default)] |
| 6 | pub struct Cursor { offset: u64, identity: Option<(u64,u64)>, next_identity: Option<(u64,u64)>, pending: Vec<u8>, discarding: bool, pub damaged: bool } |
| 7 | impl Cursor { |
| 8 | /// Drop the offset and inode. The next open, even at this same identity and length, is a new read. |
| 9 | pub fn forget(&mut self) { self.offset = 0; self.identity = None; self.next_identity = None; self.pending.clear(); self.discarding = false; self.damaged = false; } |
| 10 | #[cfg(test)] |
| 11 | pub fn stored_identity(&self) -> Option<(u64,u64)> { self.identity } |
| 12 | /// Test seam. The next read reports this identity instead of the file's dev and inode. |
| 13 | #[cfg(test)] |
| 14 | pub fn pretend_identity(&mut self, identity: (u64,u64)) { self.next_identity = Some(identity); } |
| 15 | pub fn read(&mut self, path: &Path) -> io::Result<Vec<Value>> { |
| 16 | // poll forgets paths that are already missing. A path can vanish after that |
| 17 | // check, while hosts() blocks, and still reach this open. A failed open or |
| 18 | // read must forget, or the old offset and inode skip the rewind. |
| 19 | let result = self.read_open(path); |
| 20 | if result.is_err() { self.forget(); } |
| 21 | result |
| 22 | } |
| 23 | fn read_open(&mut self, path: &Path) -> io::Result<Vec<Value>> { |
| 24 | let mut file = File::open(path)?; |
| 25 | let meta = file.metadata()?; |
| 26 | let identity = self.next_identity.take().unwrap_or((meta.dev(), meta.ino())); |
| 27 | if self.identity != Some(identity) || meta.len() < self.offset { |
| 28 | self.offset = 0; self.pending.clear(); self.discarding = false; self.damaged = false; |
| 29 | } |
| 30 | self.identity = Some(identity); |
| 31 | let mut values = Vec::new(); |
| 32 | // The fixed-width title can be rewritten without an append or size change. |
| 33 | let mut title = Vec::new(); |
| 34 | BufReader::new((&mut file).take(65536)).read_until(b'\n', &mut title)?; |
| 35 | if let Ok(v) = serde_json::from_slice::<Value>(&title) { if v["type"] == "title" { values.push(v); } } |
| 36 | file.seek(SeekFrom::Start(self.offset))?; |
| 37 | let mut buf = [0u8; 65536]; |
| 38 | loop { |
| 39 | let n = file.read(&mut buf)?; |
| 40 | if n == 0 { break; } |
| 41 | self.offset += n as u64; |
| 42 | for &b in &buf[..n] { |
| 43 | if b == b'\n' { |
| 44 | if !self.discarding && !self.pending.is_empty() { |
| 45 | match serde_json::from_slice(&self.pending) { Ok(v) => values.push(v), Err(_) => self.damaged = true } |
| 46 | } |
| 47 | self.pending.clear(); self.discarding = false; |
| 48 | } else if !self.discarding { |
| 49 | if self.pending.len() == MAX_LINE { self.pending.clear(); self.discarding = true; self.damaged = true; } else { self.pending.push(b); } |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | Ok(values) |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | pub fn hosts(fixture: Option<&Path>) -> io::Result<Value> { |
| 58 | let bytes = if let Some(path) = fixture { fs::read(path)? } else { |
| 59 | // Drain stdout concurrently; never forward raw stderr or source errors. |
| 60 | let mut child = Command::new("omp").args(["collab", "list", "--json"]).stdout(Stdio::piped()).stderr(Stdio::null()).spawn()?; |
| 61 | let stdout = child.stdout.take().ok_or_else(|| io::Error::other("source unavailable"))?; |
| 62 | let reader = std::thread::spawn(move || { let mut bytes = Vec::new(); stdout.take(16 * 1024 * 1024).read_to_end(&mut bytes).map(|_| bytes) }); |
| 63 | let start = Instant::now(); |
| 64 | loop { |
| 65 | if let Some(status) = child.try_wait()? { if !status.success() { let _ = reader.join(); return Err(io::Error::other("source unavailable")); } break; } |
| 66 | if start.elapsed() > Duration::from_secs(10) { let _ = child.kill(); let _ = child.wait(); let _ = reader.join(); return Err(io::Error::other("source timeout")); } |
| 67 | std::thread::sleep(Duration::from_millis(10)); |
| 68 | } |
| 69 | reader.join().map_err(|_| io::Error::other("source unavailable"))?? |
| 70 | }; |
| 71 | let value: Value = serde_json::from_slice(&bytes).map_err(|_| io::Error::other("invalid source"))?; |
| 72 | if value["version"] != 1 || !value["hosts"].is_array() { return Err(io::Error::other("invalid source")); } |
| 73 | Ok(value) |
| 74 | } |
| 75 | |
| 76 | pub fn root_paths(base: &Path, ids: &HashSet<String>) -> io::Result<Vec<(String,PathBuf)>> { |
| 77 | let mut result = Vec::new(); |
| 78 | for dir in fs::read_dir(base)? { |
| 79 | let dir = dir?; |
| 80 | if !dir.file_type()?.is_dir() { continue; } |
| 81 | for entry in fs::read_dir(dir.path())? { |
| 82 | let entry = entry?; |
| 83 | let name = entry.file_name(); let name = name.to_string_lossy(); |
| 84 | if let Some(stem) = name.strip_suffix(".jsonl") { |
| 85 | if let Some((_, id)) = stem.rsplit_once('_') { if ids.contains(id) { result.push((id.to_owned(), entry.path())); } } |
| 86 | } |
| 87 | } |
| 88 | } |
| 89 | Ok(result) |
| 90 | } |
| 91 | |
| 92 | pub fn descendants(base: &Path) -> io::Result<Vec<PathBuf>> { |
| 93 | let mut files = Vec::new(); |
| 94 | if !base.exists() { return Ok(files); } |
| 95 | let mut dirs = vec![base.to_owned()]; |
| 96 | while let Some(dir) = dirs.pop() { |
| 97 | for entry in fs::read_dir(dir)? { |
| 98 | let entry = entry?; let kind = entry.file_type()?; |
| 99 | if kind.is_dir() { dirs.push(entry.path()); } |
| 100 | else if kind.is_file() && entry.path().extension().is_some_and(|x| x == "jsonl") { |
| 101 | // These are mirrored advisory transcript wrappers, not workers. Real |
| 102 | // advisor-spawned workers have normal session_init files and remain. |
| 103 | if !entry.file_name().to_string_lossy().starts_with("__advisor.") { files.push(entry.path()); } |
| 104 | } |
| 105 | } |
| 106 | } |
| 107 | files.sort_by_key(|p| p.components().count()); |
| 108 | Ok(files) |
| 109 | } |
| 110 | |
| 111 | pub struct Process { pub key: String, pub pid: u32, pub parent: u32, pub runtime: &'static str, pub model: String, pub headless: bool } |
| 112 | pub fn processes() -> io::Result<Vec<Process>> { |
| 113 | let mut result = Vec::new(); |
| 114 | for entry in fs::read_dir("/proc")? { |
| 115 | let entry = entry?; |
| 116 | let Ok(pid) = entry.file_name().to_string_lossy().parse::<u32>() else { continue; }; |
| 117 | let path = entry.path(); |
| 118 | let Ok(comm) = fs::read_to_string(path.join("comm")) else { continue; }; |
| 119 | let runtime = match comm.trim() { "omp" => "OMP", "codex" => "Codex", "claude" => "Claude Code", "opencode" => "OpenCode", "grok" => "Grok", "muse" => "Muse", _ => continue }; |
| 120 | let Ok(cmd) = fs::read(path.join("cmdline")) else { continue; }; |
| 121 | let args: Vec<_> = cmd.split(|&b| b == 0).filter_map(|a| std::str::from_utf8(a).ok()).collect(); |
| 122 | if args.iter().any(|a| matches!(*a, "app-server" | "mcp-server" | "--service" | "daemon" | "collab")) { continue; } |
| 123 | let Ok(stat) = fs::read_to_string(path.join("stat")) else { continue; }; |
| 124 | let Some((_, fields)) = stat.rsplit_once(')') else { continue; }; |
| 125 | let fields: Vec<_> = fields.split_whitespace().collect(); |
| 126 | if fields.first() == Some(&"Z") { continue; } |
| 127 | let parent = fields.get(1).and_then(|s| s.parse().ok()).unwrap_or(0); |
| 128 | let born = fields.get(19).copied().unwrap_or("unknown"); |
| 129 | let model = args.windows(2).find(|a| a[0] == "--model").map(|a| a[1]).unwrap_or("unknown").to_owned(); |
| 130 | result.push(Process { key: format!("process:{pid}:{born}"), pid, parent, runtime, model, headless: args.contains(&"-p") || args.contains(&"--print") }); |
| 131 | } |
| 132 | Ok(result) |
| 133 | } |
| 134 | |
| 135 | pub fn nearest_parent(mut pid: u32, known: &std::collections::HashMap<u32,String>) -> Option<String> { |
| 136 | let mut visited = HashSet::new(); |
| 137 | while pid > 1 && visited.insert(pid) { |
| 138 | if let Some(key) = known.get(&pid) { return Some(key.clone()); } |
| 139 | let stat = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; |
| 140 | let (_, fields) = stat.rsplit_once(')')?; |
| 141 | pid = fields.split_whitespace().nth(1)?.parse().ok()?; |
| 142 | } |
| 143 | None |
| 144 | } |
| 145 | |
| 146 | /// Transcript formats read beside OMP collaboration trees. |
| 147 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 148 | pub enum Transcript { Claude, Codex } |
| 149 | impl Transcript { |
| 150 | pub fn runtime(self) -> &'static str { match self { Self::Claude => "Claude Code", Self::Codex => "Codex" } } |
| 151 | } |
| 152 | /// Top-level session transcripts written within `window_ms` of `now_ms`, with |
| 153 | /// their modification time. Claude Code keeps `projects/<project>/<session>.jsonl` |
| 154 | /// (subagent sidechains live deeper and are skipped); Codex keeps |
| 155 | /// `sessions/YYYY/MM/DD/rollout-*.jsonl`. A missing directory is no transcripts. |
| 156 | pub fn recent_transcripts(kind: Transcript, base: &Path, now_ms: i64, window_ms: i64) -> io::Result<Vec<(PathBuf,i64)>> { |
| 157 | let depth = match kind { Transcript::Claude => 1, Transcript::Codex => 3 }; |
| 158 | let mut result = Vec::new(); |
| 159 | if !base.exists() { return Ok(result); } |
| 160 | let mut dirs = vec![(base.to_owned(),0)]; |
| 161 | while let Some((dir,level)) = dirs.pop() { |
| 162 | for entry in fs::read_dir(&dir)? { |
| 163 | let entry = entry?; let kind_of = entry.file_type()?; |
| 164 | if kind_of.is_dir() && level < depth { dirs.push((entry.path(),level + 1)); continue; } |
| 165 | if !kind_of.is_file() || level != depth || entry.path().extension().is_none_or(|e| e != "jsonl") { continue; } |
| 166 | let Ok(meta) = entry.metadata() else { continue; }; |
| 167 | let modified = meta.mtime() * 1000 + meta.mtime_nsec() / 1_000_000; |
| 168 | if now_ms - modified <= window_ms { result.push((entry.path(),modified)); } |
| 169 | } |
| 170 | } |
| 171 | result.sort(); |
| 172 | Ok(result) |
| 173 | } |
| 174 | |
| 175 | #[cfg(test)] |
| 176 | mod tests { |
| 177 | use super::*; |
| 178 | use std::io::Write; |
| 179 | #[test] fn incremental_partial_malformed_and_rotation() { |
| 180 | let dir = std::env::temp_dir().join(format!("hive-cursor-{}", std::process::id())); fs::create_dir_all(&dir).unwrap(); |
| 181 | let p = dir.join("source.jsonl"); fs::write(&p, b"{\"type\":\"title\",\"title\":\"one\"}\n{\"a\":").unwrap(); |
| 182 | let mut c = Cursor::default(); assert_eq!(c.read(&p).unwrap().len(), 2); |
| 183 | fs::OpenOptions::new().append(true).open(&p).unwrap().write_all(b"1}\nbad\n").unwrap(); |
| 184 | let v = c.read(&p).unwrap(); assert_eq!(v.len(), 2); assert_eq!(v[1]["a"], 1); assert!(c.damaged); |
| 185 | fs::write(&p, b"{\"b\":2}\n").unwrap(); let v = c.read(&p).unwrap(); assert_eq!(v[0]["b"], 2); |
| 186 | fs::rename(&p, dir.join("old")).unwrap(); fs::write(&p, b"{\"c\":3}\n").unwrap(); assert_eq!(c.read(&p).unwrap()[0]["c"], 3); |
| 187 | fs::remove_dir_all(dir).unwrap(); |
| 188 | } |
| 189 | /// Mutant: File::open failure does not forget. The recreate keeps the old identity and length, so the record is not reread. |
| 190 | #[test] fn an_open_failure_forgets_before_the_same_identity_returns() { |
| 191 | let dir = std::env::temp_dir().join(format!("hive-cursor-open-{}-{}", std::process::id(), std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos())); |
| 192 | fs::create_dir_all(&dir).unwrap(); |
| 193 | let path = dir.join("session.jsonl"); |
| 194 | let body = b"{\"type\":\"custom\",\"customType\":\"tool_execution_start\"}\n"; |
| 195 | fs::write(&path, body).unwrap(); |
| 196 | let mut cursor = Cursor::default(); |
| 197 | assert_eq!(cursor.read(&path).unwrap().len(), 1); |
| 198 | let identity = cursor.stored_identity().unwrap(); |
| 199 | assert!(cursor.read(&path).unwrap().is_empty()); |
| 200 | fs::remove_file(&path).unwrap(); |
| 201 | assert!(cursor.read(&path).is_err()); |
| 202 | assert!(cursor.stored_identity().is_none()); |
| 203 | fs::write(&path, body).unwrap(); |
| 204 | cursor.pretend_identity(identity); |
| 205 | let again = cursor.read(&path).unwrap(); |
| 206 | assert_eq!(again.len(), 1); |
| 207 | assert_eq!(again[0]["customType"], "tool_execution_start"); |
| 208 | fs::remove_dir_all(dir).unwrap(); |
| 209 | } |
| 210 | } |