session_activity/
query.rs1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::fs;
3use std::path::PathBuf;
4use std::time::UNIX_EPOCH;
5
6use serde::Serialize;
7
8use crate::{FileEvent, Operation, Outcome, SessionKey, Source};
9
10pub fn reconcile(events: impl IntoIterator<Item = FileEvent>) -> Vec<FileEvent> {
14 let events: Vec<_> = events.into_iter().collect();
15 let identity = |e: &FileEvent| {
16 e.tool_call_id
17 .as_ref()
18 .filter(|id| !id.is_empty())
19 .map(|id| (e.session.clone(), id.clone(), e.operation, e.path.clone(), e.previous_path.clone()))
20 };
21 let mut outcomes = HashMap::<_, HashSet<Outcome>>::new();
22 for event in &events {
23 if event.outcome != Outcome::Unknown {
24 if let Some(key) = identity(event) {
25 outcomes.entry(key).or_default().insert(event.outcome);
26 }
27 }
28 }
29 let mut seen = HashSet::new();
30 let mut result = Vec::new();
31 for mut event in events {
32 if let Some(key) = identity(&event) {
33 if event.outcome == Outcome::Unknown {
34 if let Some(known) = outcomes.get(&key).filter(|values| values.len() == 1) {
35 event.outcome = *known.iter().next().unwrap();
36 }
37 }
38 if !seen.insert((key, event.source, event.outcome)) {
39 continue;
40 }
41 }
42 result.push(event);
43 }
44 result
45}
46
47#[derive(Clone, Debug, Serialize)]
48pub struct FileActivity {
49 pub path: PathBuf,
50 pub last_touched_at: i64,
51 pub exists: bool,
52 pub events: Vec<FileEvent>,
55}
56
57pub fn files(events: impl IntoIterator<Item = FileEvent>) -> Vec<FileActivity> {
60 let mut grouped: BTreeMap<PathBuf, Vec<FileEvent>> = BTreeMap::new();
61 for event in reconcile(events) {
62 if let Some(previous) = &event.previous_path {
63 grouped.entry(previous.clone()).or_default().push(event.clone());
64 }
65 grouped.entry(event.path.clone()).or_default().push(event);
66 }
67 let mut result: Vec<_> = grouped
68 .into_iter()
69 .map(|(path, mut events)| {
70 events.sort_by_key(|event| event.timestamp);
71 FileActivity {
72 exists: path.is_file(),
73 path,
74 last_touched_at: events.last().map_or(0, |e| e.timestamp),
75 events,
76 }
77 })
78 .collect();
79 result.sort_by(|a, b| b.last_touched_at.cmp(&a.last_touched_at).then_with(|| a.path.cmp(&b.path)));
80 result
81}
82
83pub struct ScanRoot {
84 pub path: PathBuf,
85 pub since: i64,
86 pub depth: usize,
87 pub source: Source,
88}
89
90#[derive(Debug, Default)]
93pub struct ScanReport {
94 pub events: Vec<FileEvent>,
95 pub entries_visited: usize,
96 pub budget_exhausted: bool,
97 pub depth_limited: bool,
98 pub warnings: Vec<ScanWarning>,
99}
100
101#[derive(Debug)]
102pub struct ScanWarning {
103 pub path: PathBuf,
104 pub message: String,
105}
106
107pub fn scan(session: &SessionKey, cwd: &std::path::Path, roots: &[ScanRoot], budget: usize) -> Vec<FileEvent> {
108 scan_report(session, cwd, roots, budget).events
109}
110
111pub fn scan_report(session: &SessionKey, cwd: &std::path::Path, roots: &[ScanRoot], budget: usize) -> ScanReport {
115 let mut report = ScanReport::default();
116 for root in roots {
117 walk(session, cwd, root, &root.path, root.depth, budget, &mut report);
118 if report.budget_exhausted {
119 break;
120 }
121 }
122 report
123}
124
125fn walk(
126 session: &SessionKey,
127 cwd: &std::path::Path,
128 root: &ScanRoot,
129 dir: &std::path::Path,
130 depth: usize,
131 budget: usize,
132 report: &mut ScanReport,
133) {
134 if depth == 0 {
135 report.depth_limited = true;
136 return;
137 }
138 let entries = match fs::read_dir(dir) {
139 Ok(entries) => entries,
140 Err(e) if dir == root.path && e.kind() == std::io::ErrorKind::NotFound => return,
141 Err(e) => {
142 report.warnings.push(ScanWarning { path: dir.into(), message: e.to_string() });
143 return;
144 }
145 };
146 for entry in entries {
147 if report.entries_visited == budget {
148 report.budget_exhausted = true;
149 return;
150 }
151 report.entries_visited += 1;
152 let entry = match entry {
153 Ok(entry) => entry,
154 Err(e) => {
155 report.warnings.push(ScanWarning { path: dir.into(), message: e.to_string() });
156 continue;
157 }
158 };
159 let path = entry.path();
160 let kind = match entry.file_type() {
161 Ok(kind) => kind,
162 Err(e) => {
163 report.warnings.push(ScanWarning { path, message: e.to_string() });
164 continue;
165 }
166 };
167 let name = entry.file_name();
168 let name = name.to_string_lossy();
169 if kind.is_dir() && !name.starts_with('.') && !["node_modules", "target"].contains(&name.as_ref()) {
170 walk(session, cwd, root, &path, depth - 1, budget, report);
171 if report.budget_exhausted {
172 return;
173 }
174 } else if kind.is_file() {
175 let at = match entry.metadata().and_then(|m| m.modified()) {
176 Ok(at) => at.duration_since(UNIX_EPOCH).map_or(0, |t| t.as_secs() as i64),
177 Err(e) => {
178 report.warnings.push(ScanWarning { path, message: e.to_string() });
179 continue;
180 }
181 };
182 if at >= root.since {
183 report.events.push(FileEvent::new(session, cwd, &path, at, Operation::Observed, root.source));
184 }
185 }
186 }
187}