1use std::collections::{HashMap, HashSet};
24use std::path::{Path, PathBuf};
25use std::sync::Arc;
26
27use crate::backend::attachments::store::{text_cache_ids, Store};
28use crate::backend::continuity_segments::{self as segs, Segment};
29use crate::backend::history::record::AgentRecords;
30use crate::registry::LeaseStore;
31use crate::backend::storage::filestore::FileStore;
32use crate::backend::transcript::provider_end::{end_session, measure, newest_modified_ms, prove_session, FsZone, Hold, SessionFiles, Zone};
33
34pub const KEY_SWEEP: &str = "history:sessionfilesweep";
36pub const KEY_IDLE_DAYS: &str = "agent:rawsessionidledays";
38pub const DEFAULT_IDLE_DAYS: u32 = 7;
39pub const MAX_IDLE_DAYS: u32 = 30;
40const GRACE_MS: i64 = 60 * 60 * 1000;
42const DAY_MS: i64 = 24 * 60 * 60 * 1000;
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub struct Policy {
46 pub enabled: bool,
47 pub idle_days: u32,
48}
49
50impl Policy {
51 pub fn from_extra(extra: &HashMap<String, serde_json::Value>) -> Self {
54 let idle = extra.get(KEY_IDLE_DAYS).and_then(|v| v.as_f64()).filter(|n| n.is_finite()).map_or(DEFAULT_IDLE_DAYS, |n| (n.floor().max(1.0) as u32).min(MAX_IDLE_DAYS));
55 Self { enabled: extra.get(KEY_SWEEP).and_then(|v| v.as_bool()).unwrap_or(false), idle_days: idle }
56 }
57}
58
59pub struct Roots {
61 pub shared: Option<PathBuf>,
62 pub agentmux_home: Option<PathBuf>,
63 pub attachments: Option<PathBuf>,
65 pub definitions: Option<PathBuf>,
67}
68
69impl Roots {
70 pub fn from_env() -> Self {
71 let shared = std::env::var_os("AGENTMUX_SHARED_DIR").map(PathBuf::from).or_else(|| crate::srv_info::agentmux_root().map(|r| r.join("shared")));
72 Self { shared, agentmux_home: crate::srv_info::agentmux_root(), attachments: Some(crate::backend::base::get_mux_data_dir().join("attachments")), definitions: crate::registry::resolve_shared_definitions_dir() }
73 }
74
75 pub fn agent_deleted(&self, definition_id: &str) -> bool {
78 let Some(dir) = self.definitions.as_ref().filter(|d| d.is_dir()) else { return false };
79 crate::registry::DefinitionStore::open(dir.clone()).is_ok_and(|defs| !defs.exists(definition_id) && defs.exists_anywhere(definition_id))
80 }
81
82 pub fn owns(&self, config_dir: &Path) -> bool {
85 let under = |root: &Option<PathBuf>, parts: &[&str]| {
86 root.as_ref().is_some_and(|r| config_dir.starts_with(parts.iter().fold(r.clone(), |p, s| p.join(s))))
87 };
88 if under(&self.shared, &["providers"]) || under(&self.shared, &["identities"]) {
89 return true;
90 }
91 let Some(home) = &self.agentmux_home else { return false };
92 ["channels", "dev"].iter().any(|top| config_dir.starts_with(home.join(top)) && config_dir.components().any(|c| c.as_os_str() == "identities"))
93 }
94}
95
96pub struct Admission {
99 store: Arc<LeaseStore>,
100 boot: Arc<str>,
101 renew_every: std::time::Duration,
103}
104
105struct Held {
108 store: Arc<LeaseStore>,
109 lease: crate::registry::Lease,
110 stop: Arc<std::sync::atomic::AtomicBool>,
111 lost: Arc<std::sync::atomic::AtomicBool>,
112 renewer: Option<std::thread::JoinHandle<()>>,
113}
114
115impl Held {
116 fn new(store: Arc<LeaseStore>, lease: crate::registry::Lease, every: std::time::Duration) -> Self {
117 use std::sync::atomic::{AtomicBool, Ordering};
118 let (stop, lost) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)));
119 let renewer = {
120 let (store, lease, stop, lost) = (Arc::clone(&store), lease.clone(), Arc::clone(&stop), Arc::clone(&lost));
121 std::thread::spawn(move || {
122 let step = std::time::Duration::from_millis(20).min(every);
123 let mut waited = std::time::Duration::ZERO;
124 while !stop.load(Ordering::Relaxed) {
125 std::thread::sleep(step);
126 waited += step;
127 if waited >= every {
128 waited = std::time::Duration::ZERO;
129 if store.renew(&lease).is_err() {
130 lost.store(true, Ordering::Relaxed);
131 }
132 }
133 }
134 })
135 };
136 Self { store, lease, stop, lost, renewer: Some(renewer) }
137 }
138}
139
140impl Hold for Held {
141 fn still_held(&self) -> Result<(), String> {
142 if self.lost.load(std::sync::atomic::Ordering::Relaxed) || self.store.renew(&self.lease).is_err() {
143 self.lost.store(true, std::sync::atomic::Ordering::Relaxed);
144 return Err("the agent's lease was lost during the removal".to_string());
145 }
146 Ok(())
147 }
148}
149
150impl Drop for Held {
151 fn drop(&mut self) {
152 self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
153 if let Some(t) = self.renewer.take() {
154 let _ = t.join();
155 }
156 let _ = self.store.release(&self.lease);
157 }
158}
159
160impl Admission {
161 pub fn new(registry: Option<Arc<crate::registry::Registry>>) -> Option<Self> {
163 Some(Self {
164 store: crate::backend::agent_admission::lease_store_for(registry)?,
165 boot: Arc::from(format!("provider-sweep-{}", uuid::Uuid::new_v4())),
166 renew_every: std::time::Duration::from_secs(2),
167 })
168 }
169
170 #[cfg(test)]
171 fn with_store(store: Arc<LeaseStore>, renew_every: std::time::Duration) -> Self {
172 Self { store, boot: Arc::from("provider-sweep-test"), renew_every }
173 }
174
175 fn hold(&self, uid: &str) -> Option<Held> {
176 let info = crate::backend::agent_admission::claimant_info();
177 let lease = self.store.claim_as(uid, &self.boot, "provider-sweep", None, &info).ok()?;
178 Some(Held::new(Arc::clone(&self.store), lease, self.renew_every))
179 }
180}
181
182#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184pub enum Reason {
185 Replaced,
187 Idle,
189 Deleted,
191 Orphan,
193}
194
195#[derive(Debug, Clone, PartialEq, Eq)]
197pub struct Ended {
198 pub agent_uid: String,
199 pub definition_id: String,
200 pub sid: String,
201 pub project_dir: PathBuf,
202 pub reason: Reason,
203}
204
205fn definition_of(s: &Segment) -> Option<String> {
206 if let Some(d) = s.start.definition_id.as_ref().filter(|d| crate::backend::agent_session::is_valid_definition_id(d)) {
207 return Some(d.clone());
208 }
209 let zone = s.start.zone.as_deref()?;
210 let id = zone.strip_prefix("agent:")?.split(':').next()?;
211 crate::backend::agent_session::is_valid_definition_id(id).then(|| id.to_string())
212}
213
214pub fn ended_sessions(uid: &str, segments: &[Segment], roots: &Roots, policy: &Policy, now_ms: i64) -> Vec<Ended> {
217 let Some(newest) = segments.iter().rev().find_map(|s| s.start.provider_session_id.clone()) else { return Vec::new() };
218 let last_seen = segments.last().map_or(0, |s| s.ended_at_ms.unwrap_or(s.start.started_at_ms));
222 let mut seen = HashSet::new();
223 let mut deleted: HashMap<String, bool> = HashMap::new();
224 let mut out = Vec::new();
225 for s in segments.iter().filter(|s| s.start.provider == "claude") {
226 let (Some(sid), Some(config)) = (s.start.provider_session_id.as_deref(), s.start.config_dir.as_deref()) else { continue };
227 let (Some(def), Some(file)) = (definition_of(s), crate::backend::session_backfill::session_file_path(config, &s.start.cwd, sid)) else { continue };
228 let config_dir = crate::backend::base::expand_home_dir_safe(config);
229 if !roots.owns(&config_dir) || !seen.insert((config_dir, s.start.cwd.clone(), sid.to_string())) {
230 continue;
231 }
232 let Some(project_dir) = file.parent().map(Path::to_path_buf) else { continue };
233 let Some(written) = SessionFiles::at(&project_dir, sid).as_ref().and_then(newest_modified_ms) else { continue };
234 if now_ms - written < GRACE_MS {
235 continue;
236 }
237 let reason = if sid != newest {
238 Reason::Replaced
239 } else if *deleted.entry(def.clone()).or_insert_with(|| roots.agent_deleted(&def)) {
240 Reason::Deleted
241 } else if now_ms - written.max(last_seen) >= i64::from(policy.idle_days) * DAY_MS {
242 Reason::Idle
243 } else {
244 continue;
245 };
246 out.push(Ended { agent_uid: uid.to_string(), definition_id: def, sid: sid.to_string(), project_dir, reason });
247 }
248 out
249}
250
251const RUNNING: &str = "the agent is running or starting";
253
254#[derive(Debug, Default, PartialEq, Eq)]
256pub struct Report {
257 pub agents: usize,
258 pub ended: usize,
259 pub removed_files: usize,
260 pub imported_records: usize,
261 pub imported_files: usize,
262 pub removed_text_caches: usize,
264 pub skipped: usize,
266 pub failed: usize,
267 pub orphans: usize,
269 pub unattributed: usize,
271 pub ambiguous: usize,
273}
274
275impl Report {
276 fn absorb(&mut self, other: Report) {
277 self.ended += other.ended;
278 self.removed_files += other.removed_files;
279 self.imported_records += other.imported_records;
280 self.imported_files += other.imported_files;
281 self.skipped += other.skipped;
282 self.failed += other.failed;
283 self.orphans += other.orphans;
284 self.unattributed += other.unattributed;
285 self.ambiguous += other.ambiguous;
286 }
287}
288
289fn conversation_zones(fs: &FileStore, def: &str) -> Vec<String> {
291 let prefix = format!("agent:{def}:archive:");
292 let mut archives: Vec<(u64, String)> = fs
293 .zone_ids_with_prefix(&prefix)
294 .unwrap_or_default()
295 .into_iter()
296 .filter_map(|z| z.strip_prefix(&prefix).and_then(|t| t.parse::<u64>().ok()).map(|t| (t, z.clone())))
297 .collect();
298 archives.sort();
299 archives.into_iter().map(|(_, z)| z).chain([format!("agent:{def}:current")]).collect()
300}
301
302fn provider_zone(uid: &str) -> Option<String> {
305 crate::backend::agent_session::is_valid_definition_id(uid).then(|| format!("agent-uid:{uid}:provider"))
306}
307
308fn sweep_agent(fs: &FileStore, uid: &str, roots: &Roots, policy: &Policy, now_ms: i64, admit: &Admission, report: &mut Report, text_caches: &mut Vec<String>) {
310 if provider_zone(uid).is_none() {
311 return;
312 }
313 let ended = ended_sessions(uid, &segs::segments(fs, uid), roots, policy, now_ms);
314 report.ended += ended.len();
315 if !ended.is_empty() && admit.hold(uid).is_none() {
317 report.skipped += ended.len();
318 tracing::debug!(agent = %uid, sessions = ended.len(), "provider session sweep: the agent is running or starting");
319 return;
320 }
321 for e in ended {
322 let still_ended = || ended_sessions(uid, &segs::segments(fs, uid), roots, policy, now_ms).iter().any(|x| x.sid == e.sid);
323 end_one(fs, uid, &e, roots, admit, &still_ended, report, text_caches);
324 }
325}
326
327fn end_one(fs: &FileStore, uid: &str, e: &Ended, roots: &Roots, admit: &Admission, still_ended: &dyn Fn() -> bool, report: &mut Report, text_caches: &mut Vec<String>) {
330 let (Some(write_zone), Some(files)) = (provider_zone(uid), SessionFiles::at(&e.project_dir, &e.sid)) else { return };
331 let zone_names = conversation_zones(fs, &e.definition_id);
332 let read: Vec<FsZone> = zone_names.iter().map(|z| FsZone { fs, zone: z }).collect();
333 let read: Vec<&dyn Zone> = read.iter().map(|z| z as &dyn Zone).collect();
334 let mut admit_removal = || -> Result<Box<dyn Hold>, String> {
337 let held = admit.hold(uid).ok_or_else(|| RUNNING.to_string())?;
338 if !still_ended() {
339 return Err("the session is in use again".to_string());
340 }
341 Ok(Box::new(held))
342 };
343 let told = roots.attachments.as_ref().map(|_| text_caches_told(&files)).unwrap_or_default();
345 match end_session(&files, &read, &FsZone { fs, zone: &write_zone }, &mut admit_removal, &mut |_, _| {}) {
346 Ok(o) => {
347 text_caches.extend(told);
348 report.removed_files += o.removed_files;
349 report.imported_records += o.imported_records;
350 report.imported_files += o.imported_files;
351 tracing::info!(agent = %uid, session = %e.sid, reason = ?e.reason, files = o.files, records = o.records, matched = o.matched, imported_records = o.imported_records, imported_files = o.imported_files, "provider session ended");
352 }
353 Err(err) if err == RUNNING => {
354 report.skipped += 1;
355 tracing::debug!(agent = %uid, session = %e.sid, "provider session sweep: the agent started meanwhile");
356 }
357 Err(err) => {
358 report.failed += 1;
359 tracing::warn!(agent = %uid, session = %e.sid, error = %err, "provider session not removed");
360 }
361 }
362}
363
364fn text_caches_told(files: &SessionFiles) -> Vec<String> {
367 use std::io::BufRead;
368 let Ok(file) = std::fs::File::open(&files.jsonl) else { return Vec::new() };
369 let mut ids: Vec<String> = Vec::new();
370 let mut line = Vec::new();
371 let mut reader = std::io::BufReader::new(file);
372 while reader.read_until(b'\n', &mut line).is_ok_and(|n| n > 0) {
373 for id in text_cache_ids(&String::from_utf8_lossy(&line)) {
374 if !ids.contains(&id) {
375 ids.push(id);
376 }
377 }
378 line.clear();
379 }
380 ids
381}
382
383fn agent_uids(fs: &FileStore) -> Vec<String> {
385 let mut uids: Vec<String> = fs
386 .zone_ids_with_prefix("agent-uid:")
387 .unwrap_or_default()
388 .into_iter()
389 .filter_map(|z| z.strip_prefix("agent-uid:").and_then(|r| r.strip_suffix(":segments")).map(str::to_string))
390 .collect();
391 uids.sort();
392 uids
393}
394
395pub fn sweep(fs: &FileStore, roots: &Roots, policy: &Policy, now_ms: i64, admit: &Admission) -> Report {
397 let mut report = Report::default();
398 if !policy.enabled {
399 return report;
400 }
401 let mut text_caches = Vec::new();
402 for uid in agent_uids(fs) {
403 report.agents += 1;
404 sweep_agent(fs, &uid, roots, policy, now_ms, admit, &mut report, &mut text_caches);
405 }
406 report.removed_text_caches = remove_unreferenced_text_caches(fs, roots, text_caches);
407 report
408}
409
410fn remove_unreferenced_text_caches(fs: &FileStore, roots: &Roots, mut ended: Vec<String>) -> usize {
415 let Some(root) = &roots.attachments else { return 0 };
416 ended.sort();
417 ended.dedup();
418 let mut seen = HashSet::new();
419 for uid in agent_uids(fs) {
420 for s in segs::segments(fs, &uid).iter().filter(|s| s.start.provider == "claude") {
421 if ended.is_empty() {
422 return 0;
423 }
424 let (Some(sid), Some(config)) = (s.start.provider_session_id.as_deref(), s.start.config_dir.as_deref()) else { continue };
425 let Some(file) = crate::backend::session_backfill::session_file_path(config, &s.start.cwd, sid) else { continue };
426 let Some(files) = file.parent().and_then(|dir| SessionFiles::at(dir, sid)) else { continue };
427 if files.jsonl.is_file() && seen.insert(files.jsonl.clone()) {
428 let named = text_caches_told(&files);
429 ended.retain(|id| !named.contains(id));
430 }
431 }
432 }
433 Store::new(root.clone()).remove_text_caches(&ended)
434}
435
436pub fn sweep_global(roots: &Roots, policy: &Policy, now_ms: i64, registry: Option<Arc<crate::registry::Registry>>) -> Option<Report> {
439 let global = crate::backend::agent_session::global_transcript_store()?;
440 let admit = Admission::new(registry)?;
441 let mut report = sweep(global, roots, policy, now_ms, &admit);
442 report.absorb(orphans::sweep_orphans(global, roots, policy, now_ms, &admit, global_records()));
443 Some(report)
444}
445
446fn global_records() -> &'static AgentRecords {
448 static RECORDS: std::sync::OnceLock<AgentRecords> = std::sync::OnceLock::new();
449 RECORDS.get_or_init(AgentRecords::global)
450}
451
452pub const KEY_REPORT: &str = "history:sessionfilereport";
454
455pub fn report_enabled(extra: &HashMap<String, serde_json::Value>) -> bool {
457 extra.get(KEY_REPORT).and_then(|v| v.as_bool()).unwrap_or(false)
458}
459
460#[derive(Debug, Default, PartialEq, Eq)]
462pub struct ReportTotals {
463 pub sessions: usize,
464 pub bytes: u64,
465 pub by_why: std::collections::BTreeMap<&'static str, (usize, u64)>,
466}
467
468impl ReportTotals {
469 fn of(lines: &[orphans::Line]) -> Self {
470 let mut t = Self::default();
471 for l in lines {
472 t.sessions += 1;
473 t.bytes += l.bytes;
474 let e = t.by_why.entry(l.why).or_default();
475 e.0 += 1;
476 e.1 += l.bytes;
477 }
478 t
479 }
480
481 pub fn removable_bytes(&self) -> u64 {
483 [orphans::WHY_MATCHED, orphans::WHY_NEEDS_IMPORT].iter().filter_map(|k| self.by_why.get(k)).map(|v| v.1).sum()
484 }
485}
486
487fn report_table(lines: &[orphans::Line]) -> String {
490 let clean = |s: &str| s.replace(['\t', '\n', '\r'], " ");
491 let mut out = String::from("session\tproject\tfiles\tbytes\tidle_days\twhy\trecords\tmatched\tunmatched\n");
492 for l in lines {
493 out.push_str(&format!("{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n", clean(&l.sid), clean(&l.project), l.files, l.bytes, l.idle_days, l.why, l.records, l.matched, l.unmatched));
494 }
495 out
496}
497
498pub fn report_global(roots: &Roots, idle_days: u32, now_ms: i64) -> Option<Result<ReportTotals, &'static str>> {
502 let global = crate::backend::agent_session::global_transcript_store()?;
503 Some(report_to(global, roots, idle_days, now_ms, global_records(), global.path().and_then(|p| p.parent().map(Path::to_path_buf)).as_deref()))
504}
505
506fn report_to(fs: &FileStore, roots: &Roots, idle_days: u32, now_ms: i64, records: &AgentRecords, dir: Option<&Path>) -> Result<ReportTotals, &'static str> {
507 let mut lines = orphans::report_orphans(fs, roots, idle_days, now_ms, records)?;
508 lines.sort_by(|a, b| (b.bytes, &a.sid).cmp(&(a.bytes, &b.sid)));
509 if let Some(dir) = dir {
510 let (tmp, dest) = (dir.join("provider-session-report.tsv.tmp"), dir.join("provider-session-report.tsv"));
511 if std::fs::write(&tmp, report_table(&lines)).and_then(|()| std::fs::rename(&tmp, &dest)).is_err() {
512 tracing::warn!("provider session report: the table could not be written beside the store");
513 }
514 }
515 Ok(ReportTotals::of(&lines))
516}
517
518#[path = "provider_orphans.rs"]
519mod orphans;
520
521#[cfg(test)]
522#[path = "provider_sessions_tests.rs"]
523mod tests;