use super::recording::{InProgress, Session};
use chrono::{DateTime, TimeZone, Utc};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::path::Path;
use std::time::UNIX_EPOCH;
pub const FILE: &str = ".scan-cache";
const TMP: &str = ".scan-cache.tmp";
const FORMAT: &str = "ironmon.agents-scan/1";
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Probe {
pub version: Option<String>,
pub out: bool,
pub format_json: bool,
pub modified_since: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImportRecord {
pub producer: String,
pub watermark: Option<DateTime<Utc>>,
pub first_since: Option<DateTime<Utc>>,
pub last_at: Option<DateTime<Utc>>,
pub last_ok: bool,
pub last_text: String,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Entry {
pub key: u64,
pub len: u64,
pub mtime_ms: u64,
pub corrupt: bool,
pub refused: BTreeMap<String, usize>,
pub sessions: Vec<StoredSession>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StoredSession {
pub producer: String,
pub started: Option<DateTime<Utc>>,
pub ended: Option<DateTime<Utc>>,
pub in_progress: Option<bool>,
pub model: Option<String>,
pub input_tokens: Option<u64>,
pub output_tokens: Option<u64>,
pub event_count: usize,
pub run_id: u64,
pub parent_key: Option<u64>,
}
impl StoredSession {
pub fn from_session(s: &Session) -> Self {
Self {
producer: s.producer.clone(),
started: s.started,
ended: s.ended,
in_progress: match s.in_progress {
InProgress::True => Some(true),
InProgress::False => Some(false),
InProgress::NotEvidenced => None,
},
model: s.model.clone(),
input_tokens: s.input_tokens,
output_tokens: s.output_tokens,
event_count: s.event_count,
run_id: s.run_id,
parent_key: s.parent_key,
}
}
pub fn into_session(self) -> Session {
Session {
producer: self.producer,
started: self.started,
ended: self.ended,
in_progress: match self.in_progress {
Some(true) => InProgress::True,
Some(false) => InProgress::False,
None => InProgress::NotEvidenced,
},
model: self.model,
input_tokens: self.input_tokens,
output_tokens: self.output_tokens,
event_count: self.event_count,
is_subagent: false,
parent_missing: false,
child_count: 0,
run_id: self.run_id,
parent_key: self.parent_key,
}
}
}
#[derive(Debug, Default)]
pub struct Cache {
pub probe: Option<Probe>,
pub imports: Vec<ImportRecord>,
pub next_at: Option<DateTime<Utc>>,
pub entries: HashMap<u64, Entry>,
}
impl Cache {
pub fn record(&self, producer: &str) -> Option<&ImportRecord> {
self.imports.iter().find(|r| r.producer == producer)
}
pub fn record_mut(&mut self, producer: &str) -> &mut ImportRecord {
if let Some(i) = self.imports.iter().position(|r| r.producer == producer) {
return &mut self.imports[i];
}
self.imports.push(ImportRecord {
producer: producer.to_string(),
watermark: None,
first_since: None,
last_at: None,
last_ok: false,
last_text: String::new(),
});
self.imports.last_mut().expect("just pushed")
}
}
#[derive(Deserialize)]
struct DiskIn {
format: String,
#[serde(default)]
probe: Option<Probe>,
#[serde(default)]
imports: Vec<ImportRecord>,
#[serde(default)]
next_at: Option<DateTime<Utc>>,
#[serde(default)]
entries: Vec<Entry>,
}
#[derive(Serialize)]
struct DiskOut<'a> {
format: &'static str,
probe: &'a Option<Probe>,
imports: &'a [ImportRecord],
next_at: Option<DateTime<Utc>>,
entries: Vec<&'a Entry>,
}
pub fn load(dir: &Path) -> Cache {
let Ok(bytes) = std::fs::read(dir.join(FILE)) else {
return Cache::default();
};
let Ok(disk) = serde_json::from_slice::<DiskIn>(&bytes) else {
return Cache::default();
};
if disk.format != FORMAT {
return Cache::default();
}
Cache {
probe: disk.probe,
imports: disk.imports,
next_at: disk.next_at,
entries: disk.entries.into_iter().map(|e| (e.key, e)).collect(),
}
}
pub fn save(dir: &Path, cache: &Cache) -> Result<(), String> {
let mut entries: Vec<&Entry> = cache.entries.values().collect();
entries.sort_by_key(|e| e.key);
let out = DiskOut {
format: FORMAT,
probe: &cache.probe,
imports: &cache.imports,
next_at: cache.next_at,
entries,
};
let bytes =
serde_json::to_vec(&out).map_err(|_| "could not serialise the scan cache".to_string())?;
let tmp = dir.join(TMP);
std::fs::write(&tmp, bytes).map_err(|_| "could not write the scan cache".to_string())?;
std::fs::rename(&tmp, dir.join(FILE)).map_err(|_| {
let _ = std::fs::remove_file(&tmp);
"could not replace the scan cache".to_string()
})
}
pub fn mtime_ms(meta: &std::fs::Metadata) -> u64 {
meta.modified()
.ok()
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
.and_then(|d| u64::try_from(d.as_millis()).ok())
.unwrap_or(0)
}
pub fn datetime_of_ms(ms: u64) -> Option<DateTime<Utc>> {
Utc.timestamp_millis_opt(i64::try_from(ms).ok()?).single()
}
pub fn parse_file(path: &Path, key: u64, len: u64, mtime_ms: u64) -> Entry {
let mut entry = Entry {
key,
len,
mtime_ms,
..Entry::default()
};
let Ok(bytes) = std::fs::read(path) else {
entry.corrupt = true;
return entry;
};
match super::recording::read_file(&bytes) {
Err(_) => entry.corrupt = true,
Ok(items) => {
for item in items {
match item {
Ok(s) => entry.sessions.push(StoredSession::from_session(&s)),
Err(refusal) => {
*entry.refused.entry(refusal.reason()).or_default() += 1;
}
}
}
}
}
entry
}
#[cfg(test)]
mod tests {
use super::*;
fn dir(name: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("ironmon-cache-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
#[test]
fn a_saved_cache_loads_back_with_its_import_record() {
let d = dir("roundtrip");
let at = Utc.with_ymd_and_hms(2026, 3, 1, 12, 0, 0).single().unwrap();
let mut c = Cache {
probe: Some(Probe {
version: Some("ironobs 0.1.0".into()),
out: true,
format_json: true,
modified_since: true,
}),
next_at: Some(at),
..Cache::default()
};
c.record_mut("claude_code").watermark = Some(at);
save(&d, &c).unwrap();
let back = load(&d);
assert_eq!(back.probe, c.probe);
assert_eq!(back.record("claude_code").unwrap().watermark, Some(at));
assert_eq!(back.next_at, Some(at));
}
#[test]
fn a_foreign_or_damaged_cache_is_an_empty_one() {
let d = dir("damaged");
std::fs::write(d.join(FILE), b"{ not the cache").unwrap();
assert!(load(&d).entries.is_empty());
std::fs::write(d.join(FILE), br#"{"format":"other/9","entries":[]}"#).unwrap();
assert!(load(&d).probe.is_none());
}
#[test]
fn a_record_for_a_producer_is_created_once() {
let mut c = Cache::default();
c.record_mut("codex").last_ok = true;
c.record_mut("codex").last_text = "x".into();
assert_eq!(c.imports.len(), 1);
assert!(c.record("codex").unwrap().last_ok);
}
}