Skip to main content

agentmux_srv_core/backend/
provider_sessions.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The end of a provider session, found from the segment index (`SPEC_HISTORY_COMPACT_FORM_ONLY_2026_11_23.md` 5.4).
5//!
6//! AgentMux records every provider session it starts, per agent (`continuity_segments`: the session id, the config
7//! folder, the working folder). A session has **ended** when
8//! - the agent has moved on to another session (a fresh start, or an id that could not be resumed): it is no longer
9//!   the newest session the agent's segments name; or
10//! - it is the agent's newest session, no process holds it, and nothing has written to it for the idle limit
11//!   (`agent:rawsessionidledays`, 7 days, at most 30); or
12//! - the agent was deleted (provably: its definition is retired and no longer active), which ends its newest session
13//!   at once.
14//!
15//! A stop, a restart and a quit do not end a session: the agent resumes it. Only sessions AgentMux started are ever
16//! looked at (the ids in its own segment log), only inside folders AgentMux owns (never a person's own CLI home), and
17//! only by exact session id: `<project folder>/<id>.jsonl` and `<id>/`. For each ended session
18//! [`provider_end::end_session`](super::transcript::provider_end::end_session) proves, imports and removes.
19//!
20//! A sweep removes files, so it runs only when `history:sessionfilesweep` is on. It is off by default and is
21//! switched on with the migration of existing stores (spec 9), after the earlier steps have soaked.
22
23use 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
34/// The sweep's switch: off until the migration turns it on.
35pub const KEY_SWEEP: &str = "history:sessionfilesweep";
36/// How long the newest session may go unwritten before it ends. A person's setting; the word stays internal.
37pub const KEY_IDLE_DAYS: &str = "agent:rawsessionidledays";
38pub const DEFAULT_IDLE_DAYS: u32 = 7;
39pub const MAX_IDLE_DAYS: u32 = 30;
40/// A session file written to this recently is never touched.
41const 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    /// What the settings ask for. A missing or mistyped key keeps its default; the idle limit is at least one day and
52    /// at most [`MAX_IDLE_DAYS`].
53    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
59/// The folders AgentMux owns provider homes in.
60pub struct Roots {
61    pub shared: Option<PathBuf>,
62    pub agentmux_home: Option<PathBuf>,
63    /// The attachment store, whose extracted-text cache goes with the session that was told of it.
64    pub attachments: Option<PathBuf>,
65    /// The shared definition folder, which says an agent was deleted (its record moved to `retired/`).
66    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    /// Whether the agent's definition is provably deleted: gone from the active definitions and present among the
76    /// retired ones. A folder that cannot be read, or an agent that was never recorded there, is not deleted.
77    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    /// Whether `config_dir` is a provider home AgentMux made: under the shared `providers` or `identities`, or a
83    /// channel's or dev build's `identities`. A person's own `~/.claude` is none of these.
84    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
96/// What keeps an agent from starting while its session files are removed: the agent's single-live-instance lease,
97/// taken for the removal only. An agent that is running (or starting) holds it, so its sessions are not touched.
98pub struct Admission {
99    store: Arc<LeaseStore>,
100    boot: Arc<str>,
101    /// How often a held lease is renewed (the lease lapses after 15 seconds).
102    renew_every: std::time::Duration,
103}
104
105/// A lease held for the removal. A thread renews it until the hold is dropped, so a long removal cannot outlast it;
106/// [`Hold::still_held`] renews it too and fails once it belongs to someone else. Let go on drop.
107struct 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    /// `None` when there is no lease store (no shared registry): nothing can then be proved safe, so nothing is swept.
162    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/// Why a session ended.
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184pub enum Reason {
185    /// The agent is in another session now.
186    Replaced,
187    /// The newest session went unwritten for the idle limit.
188    Idle,
189    /// The agent was deleted.
190    Deleted,
191    /// No segment log names the session; the store says whose it is ([`orphans`]).
192    Orphan,
193}
194
195/// An ended session whose files are there.
196#[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
214/// The agent's ended sessions whose file is there, from its segments (oldest first). The newest session is
215/// ended when it has been idle for the limit; whether the agent is running now is for the lease to say.
216pub 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    // A segment with no end event is not proof that the agent runs: a crash, a kill or a power loss never
219    // writes one. Whether the agent runs is the lease's to say, which the sweep holds before it removes
220    // anything and looks at again under the removal. An unclosed segment counts from the time it started.
221    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
251/// Why a removal was left for later: not a failure.
252const RUNNING: &str = "the agent is running or starting";
253
254/// What a sweep did, in counts.
255#[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    /// Extracted-text files of attachments that the ended sessions told their agents of.
263    pub removed_text_caches: usize,
264    /// Left for later: the agent is running or starting.
265    pub skipped: usize,
266    pub failed: usize,
267    /// Session files no segment log names.
268    pub orphans: usize,
269    /// Of those, the ones the store holds no line of: left as they are.
270    pub unattributed: usize,
271    /// Of those, the ones several agents' zones hold: left as they are.
272    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
289/// The zones that may hold an agent's conversation, oldest first: its archives, then its current one.
290fn 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
302/// Where what the store lacks is imported: a zone of the agent's own, not its transcript zone, so a new conversation
303/// (which clears that) never erases it.
304fn provider_zone(uid: &str) -> Option<String> {
305    crate::backend::agent_session::is_valid_definition_id(uid).then(|| format!("agent-uid:{uid}:provider"))
306}
307
308/// End the sessions of one agent. Every failure is counted and logged and removes nothing.
309fn 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    // An agent that is running holds its lease: look before the proof, which is the long part.
316    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
327/// Prove, import and remove one ended session. `still_ended` is asked again under the agent's lease, just before
328/// any file is touched.
329fn 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    // After the proof and the import, and before any file is touched: hold the agent's lease, so it cannot
335    // resume this session now, and look again under it that the session is still ended.
336    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    // The session's own file says which text versions its agent was told of; read before it is removed.
344    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
364/// The attachments whose extracted text the session's file names (the message that gave the agent its files says
365/// where each text version is). Empty when the file cannot be read: nothing is then deleted.
366fn 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
383/// The agent uids that have a segment log.
384fn 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
395/// End every ended session, when the policy is on. A pass that is not enabled reads nothing and removes nothing.
396pub 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
410/// Delete the text caches of `ended` that no session file left on disk names. An attachment's id is its content hash,
411/// so one cache is shared by every session that was given the same document, of this agent and of any other: it goes
412/// only when the last session that names it has gone. Every agent's remaining session files are read for that (after
413/// the sweep, so the files just removed are not among them), and only when there is something to delete.
414fn 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
436/// [`sweep`] over the global transcript store, where the segment logs, the conversation zones and the agent's provider
437/// zone live (the per-channel store holds none of them). `None` when there is no global store: nothing is swept then.
438pub 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
446/// The agents' records in the global store, read incrementally, so an hourly pass reads only what was appended.
447fn global_records() -> &'static AgentRecords {
448    static RECORDS: std::sync::OnceLock<AgentRecords> = std::sync::OnceLock::new();
449    RECORDS.get_or_init(AgentRecords::global)
450}
451
452/// The switch of the report-only pass: off unless set, and it never removes anything.
453pub const KEY_REPORT: &str = "history:sessionfilereport";
454
455/// Whether the report-only pass is asked for.
456pub 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/// What the report-only pass found, by why: how many session files and how many bytes.
461#[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    /// Removable with nothing lost: every record is in the store, or an end would import what the store lacks first.
482    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
487/// The report as a table, one session per line: session, project folder, files, bytes, idle days, why, records,
488/// matched, unmatched. Names and counts only: no conversation text.
489fn 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
498/// The report-only pass over the global store: for every provider session file no segment log names, the sweep's own
499/// owner test and proof, and the result written beside the store (`provider-session-report.tsv`, replaced each time)
500/// with its totals returned. It removes, imports and locks nothing, and runs only when asked for.
501pub 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;