Skip to main content

session_activity/
query.rs

1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::fs;
3use std::io::Read;
4use std::path::PathBuf;
5use std::time::UNIX_EPOCH;
6
7use serde::Serialize;
8
9use crate::{FileEvent, Operation, Outcome, SessionKey, Source};
10
11/// Reconcile outcome evidence for the same tool invocation and remove retries.
12/// Missing call IDs are not sufficient evidence that two observations are the
13/// same operation. Conflicting known outcomes remain visible to the consumer.
14pub fn reconcile(events: impl IntoIterator<Item = FileEvent>) -> Vec<FileEvent> {
15    let events: Vec<_> = events.into_iter().collect();
16    let identity = |e: &FileEvent| {
17        e.tool_call_id
18            .as_ref()
19            .filter(|id| !id.is_empty())
20            .map(|id| (e.session.clone(), id.clone(), e.operation, e.path.clone(), e.previous_path.clone()))
21    };
22    let mut outcomes = HashMap::<_, HashSet<Outcome>>::new();
23    for event in &events {
24        if event.outcome != Outcome::Unknown {
25            if let Some(key) = identity(event) {
26                outcomes.entry(key).or_default().insert(event.outcome);
27            }
28        }
29    }
30    let mut seen = HashSet::new();
31    let mut result = Vec::new();
32    for mut event in events {
33        if let Some(key) = identity(&event) {
34            if event.outcome == Outcome::Unknown {
35                if let Some(known) = outcomes.get(&key).filter(|values| values.len() == 1) {
36                    event.outcome = *known.iter().next().unwrap();
37                }
38            }
39            if !seen.insert((key, event.source, event.outcome)) {
40                continue;
41            }
42        }
43        result.push(event);
44    }
45    result
46}
47
48/// A separate repository or a linked worktree, which usually has sessions of
49/// its own. A submodule's `.git` file points into the parent's `modules/`, so
50/// submodules stay part of the project.
51fn other_checkout(dir: &std::path::Path) -> bool {
52    let git = dir.join(".git");
53    match fs::symlink_metadata(&git) {
54        Ok(meta) if meta.is_dir() => true,
55        Ok(meta) if meta.is_file() => {
56            let mut head = String::new();
57            fs::File::open(&git).and_then(|file| file.take(4096).read_to_string(&mut head)).is_ok()
58                && head.contains("/worktrees/")
59        }
60        _ => false,
61    }
62}
63
64#[derive(Clone, Debug, Serialize)]
65pub struct FileActivity {
66    pub path: PathBuf,
67    pub last_touched_at: i64,
68    pub exists: bool,
69    /// Keep evidence and outcomes attached to the summary, rather than turning
70    /// filesystem candidates into attributed writes.
71    pub events: Vec<FileEvent>,
72}
73
74impl FileActivity {
75    /// Only scans saw the file: no tool reported touching it.
76    pub fn scan_only(&self) -> bool {
77        self.events.iter().all(|e| e.operation == Operation::Observed)
78    }
79
80    /// Only scans saw it, and one did while another session was working in
81    /// the same place, so either may have changed it.
82    pub fn possibly_shared(&self) -> bool {
83        self.scan_only() && self.events.iter().any(|e| !e.concurrent.is_empty())
84    }
85}
86
87/// Group observations by path; retain deleted paths and both sides of renames.
88/// Filtering by extension, outcome, or operation belongs to the consumer.
89pub fn files(events: impl IntoIterator<Item = FileEvent>) -> Vec<FileActivity> {
90    let mut grouped: BTreeMap<PathBuf, Vec<FileEvent>> = BTreeMap::new();
91    for event in reconcile(events) {
92        if let Some(previous) = &event.previous_path {
93            grouped.entry(previous.clone()).or_default().push(event.clone());
94        }
95        grouped.entry(event.path.clone()).or_default().push(event);
96    }
97    let mut result: Vec<_> = grouped
98        .into_iter()
99        .map(|(path, mut events)| {
100            events.sort_by_key(|event| event.timestamp);
101            FileActivity {
102                exists: path.is_file(),
103                path,
104                last_touched_at: events.last().map_or(0, |e| e.timestamp),
105                events,
106            }
107        })
108        .collect();
109    result.sort_by(|a, b| b.last_touched_at.cmp(&a.last_touched_at).then_with(|| a.path.cmp(&b.path)));
110    result
111}
112
113pub struct ScanRoot {
114    pub path: PathBuf,
115    /// Accepted modification times, inclusive, in Unix seconds.
116    pub since: i64,
117    pub until: i64,
118    pub depth: usize,
119    pub source: Source,
120}
121
122/// Completion metadata for a bounded scan. An empty result alone cannot tell
123/// the caller whether there were no matching files or the scan was incomplete.
124#[derive(Debug, Default)]
125pub struct ScanReport {
126    pub events: Vec<FileEvent>,
127    pub entries_visited: usize,
128    pub budget_exhausted: bool,
129    pub depth_limited: bool,
130    pub warnings: Vec<ScanWarning>,
131}
132
133#[derive(Debug)]
134pub struct ScanWarning {
135    pub path: PathBuf,
136    pub message: String,
137}
138
139pub fn scan(session: &SessionKey, cwd: &std::path::Path, roots: &[ScanRoot], budget: usize) -> Vec<FileEvent> {
140    scan_report(session, cwd, roots, budget).events
141}
142
143/// Hidden/build directories and nested checkouts are excluded by policy,
144/// symlink directories are not followed, and all roots share the entry budget.
145/// A nested checkout is usually another worktree with its own sessions. Missing optional roots
146/// are normal; other read/metadata errors are reported with their paths.
147pub fn scan_report(session: &SessionKey, cwd: &std::path::Path, roots: &[ScanRoot], budget: usize) -> ScanReport {
148    let mut report = ScanReport::default();
149    for root in roots {
150        walk(session, cwd, root, &root.path, root.depth, budget, &mut report);
151        if report.budget_exhausted {
152            break;
153        }
154    }
155    report
156}
157
158fn walk(
159    session: &SessionKey,
160    cwd: &std::path::Path,
161    root: &ScanRoot,
162    dir: &std::path::Path,
163    depth: usize,
164    budget: usize,
165    report: &mut ScanReport,
166) {
167    if depth == 0 {
168        report.depth_limited = true;
169        return;
170    }
171    let entries = match fs::read_dir(dir) {
172        Ok(entries) => entries,
173        Err(e) if dir == root.path && e.kind() == std::io::ErrorKind::NotFound => return,
174        Err(e) => {
175            report.warnings.push(ScanWarning { path: dir.into(), message: e.to_string() });
176            return;
177        }
178    };
179    for entry in entries {
180        if report.entries_visited == budget {
181            report.budget_exhausted = true;
182            return;
183        }
184        report.entries_visited += 1;
185        let entry = match entry {
186            Ok(entry) => entry,
187            Err(e) => {
188                report.warnings.push(ScanWarning { path: dir.into(), message: e.to_string() });
189                continue;
190            }
191        };
192        let path = entry.path();
193        let kind = match entry.file_type() {
194            Ok(kind) => kind,
195            Err(e) => {
196                report.warnings.push(ScanWarning { path, message: e.to_string() });
197                continue;
198            }
199        };
200        let name = entry.file_name();
201        let name = name.to_string_lossy();
202        if kind.is_dir() && !name.starts_with('.') && !["node_modules", "target"].contains(&name.as_ref()) {
203            if other_checkout(&path) {
204                continue;
205            }
206            walk(session, cwd, root, &path, depth - 1, budget, report);
207            if report.budget_exhausted {
208                return;
209            }
210        } else if kind.is_file() {
211            let at = match entry.metadata().and_then(|m| m.modified()) {
212                Ok(at) => at.duration_since(UNIX_EPOCH).map_or(0, |t| t.as_secs() as i64),
213                Err(e) => {
214                    report.warnings.push(ScanWarning { path, message: e.to_string() });
215                    continue;
216                }
217            };
218            if (root.since..=root.until).contains(&at) {
219                report.events.push(FileEvent::new(session, cwd, &path, at, Operation::Observed, root.source));
220            }
221        }
222    }
223}