Skip to main content

session_activity/
lib.rs

1//! File activity shared by consumers such as Peekback. No viewer, terminal,
2//! Markdown, or global state-directory dependency.
3#![doc = include_str!("../README.md")]
4mod adapters;
5mod lock;
6mod maintenance;
7mod query;
8mod store;
9
10use std::path::{Component, Path, PathBuf};
11
12use serde::{Deserialize, Serialize};
13
14pub use adapters::{hook_events, transcript_events};
15pub use maintenance::MaintenanceReport;
16pub use query::{FileActivity, ScanReport, ScanRoot, ScanWarning, files, reconcile, scan, scan_report};
17pub use store::{BatchWarning, ReadReport, SessionReport, Store};
18
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
20#[serde(rename_all = "snake_case")]
21pub enum Agent {
22    #[default]
23    Claude,
24    Codex,
25}
26
27impl Agent {
28    pub fn name(self) -> &'static str {
29        match self {
30            Self::Claude => "Claude Code",
31            Self::Codex => "Codex",
32        }
33    }
34
35    pub fn slug(self) -> &'static str {
36        match self {
37            Self::Claude => "claude",
38            Self::Codex => "codex",
39        }
40    }
41}
42
43#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
44pub struct SessionKey {
45    pub agent: Agent,
46    pub session_id: String,
47}
48
49impl SessionKey {
50    pub fn validate(&self) -> anyhow::Result<()> {
51        anyhow::ensure!(valid_id(&self.session_id), "invalid session id");
52        Ok(())
53    }
54}
55
56pub fn valid_id(id: &str) -> bool {
57    !id.is_empty()
58        && id != "."
59        && id != ".."
60        && id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
61}
62
63#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
64#[serde(rename_all = "snake_case")]
65pub enum Operation {
66    Read,
67    Write,
68    Create,
69    Modify,
70    Delete,
71    Rename,
72    Observed,
73}
74
75#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
76#[serde(rename_all = "snake_case")]
77pub enum Source {
78    Hook,
79    Transcript,
80    ProjectScan,
81    ScratchpadScan,
82    MemoryScan,
83    LegacyRegistry,
84}
85
86#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
87#[serde(rename_all = "snake_case")]
88pub enum Outcome {
89    Succeeded,
90    Failed,
91    Unknown,
92}
93
94/// A metadata-only observation. Renames use `path` for the destination and
95/// `previous_path` for the source. Unknown outcomes are never promoted by a scan.
96#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
97pub struct FileEvent {
98    pub schema_version: u32,
99    pub session: SessionKey,
100    pub timestamp: i64,
101    pub cwd: PathBuf,
102    pub path: PathBuf,
103    pub previous_path: Option<PathBuf>,
104    pub operation: Operation,
105    pub source: Source,
106    pub outcome: Outcome,
107    pub tool_call_id: Option<String>,
108}
109
110impl FileEvent {
111    pub fn new(
112        session: &SessionKey,
113        cwd: &Path,
114        path: &Path,
115        timestamp: i64,
116        operation: Operation,
117        source: Source,
118    ) -> Self {
119        Self {
120            schema_version: 1,
121            session: session.clone(),
122            timestamp,
123            cwd: cwd.to_path_buf(),
124            path: resolve_path(cwd, path),
125            previous_path: None,
126            operation,
127            source,
128            outcome: Outcome::Unknown,
129            tool_call_id: None,
130        }
131    }
132}
133
134/// Lexical normalization preserves paths even after deletion and never needs
135/// to follow symlinks or read the file.
136pub fn resolve_path(cwd: &Path, path: &Path) -> PathBuf {
137    let mut result = PathBuf::new();
138    for component in cwd.join(path).components() {
139        match component {
140            Component::CurDir => {}
141            Component::ParentDir => {
142                result.pop();
143            }
144            part => result.push(part.as_os_str()),
145        }
146    }
147    result
148}
149
150#[cfg(test)]
151mod tests;