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 lock;
5mod maintenance;
6mod query;
7mod store;
8
9use std::fmt;
10use std::path::{Component, Path, PathBuf};
11
12use serde::{Deserialize, Serialize};
13
14pub use maintenance::MaintenanceReport;
15pub use query::{FileActivity, ScanReport, ScanRoot, ScanWarning, files, reconcile, scan, scan_report};
16pub use store::{BatchWarning, ReadReport, SessionReport, Store};
17
18/// Schema 2 adds `FileEvent::concurrent`. Schema 1 batches remain readable.
19pub const SCHEMA_VERSION: u32 = 2;
20
21/// The namespace of the agent that produced a session, such as `claude`. The
22/// caller chooses it; the library only requires lowercase ASCII letters,
23/// digits and `-`, since it names a directory.
24#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
25#[serde(try_from = "String", into = "String")]
26pub struct AgentId(String);
27
28impl AgentId {
29    pub fn new(id: impl Into<String>) -> anyhow::Result<Self> {
30        let id = id.into();
31        anyhow::ensure!(
32            !id.is_empty() && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-'),
33            "invalid agent id {id:?}"
34        );
35        Ok(Self(id))
36    }
37
38    pub fn as_str(&self) -> &str {
39        &self.0
40    }
41}
42
43impl TryFrom<String> for AgentId {
44    type Error = anyhow::Error;
45
46    fn try_from(id: String) -> anyhow::Result<Self> {
47        Self::new(id)
48    }
49}
50
51impl From<AgentId> for String {
52    fn from(id: AgentId) -> Self {
53        id.0
54    }
55}
56
57impl fmt::Display for AgentId {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        f.write_str(&self.0)
60    }
61}
62
63#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
64pub struct SessionKey {
65    pub agent: AgentId,
66    pub session_id: String,
67}
68
69impl SessionKey {
70    pub fn validate(&self) -> anyhow::Result<()> {
71        anyhow::ensure!(valid_id(&self.session_id), "invalid session id");
72        Ok(())
73    }
74}
75
76pub fn valid_id(id: &str) -> bool {
77    !id.is_empty()
78        && id != "."
79        && id != ".."
80        && id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
81}
82
83#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
84#[serde(rename_all = "snake_case")]
85pub enum Operation {
86    Read,
87    Write,
88    Create,
89    Modify,
90    Delete,
91    Rename,
92    Observed,
93}
94
95#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
96#[serde(rename_all = "snake_case")]
97pub enum Source {
98    Hook,
99    Transcript,
100    ProjectScan,
101    ScratchpadScan,
102    MemoryScan,
103    LegacyRegistry,
104}
105
106#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
107#[serde(rename_all = "snake_case")]
108pub enum Outcome {
109    Succeeded,
110    Failed,
111    Unknown,
112}
113
114/// A metadata-only observation. Renames use `path` for the destination and
115/// `previous_path` for the source. Unknown outcomes are never promoted by a scan.
116#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
117pub struct FileEvent {
118    pub schema_version: u32,
119    pub session: SessionKey,
120    pub timestamp: i64,
121    pub cwd: PathBuf,
122    pub path: PathBuf,
123    pub previous_path: Option<PathBuf>,
124    pub operation: Operation,
125    pub source: Source,
126    pub outcome: Outcome,
127    pub tool_call_id: Option<String>,
128    /// Other sessions that were working where a scan observed this file, so
129    /// the filesystem cannot tell which of them changed it.
130    #[serde(default, skip_serializing_if = "Vec::is_empty")]
131    pub concurrent: Vec<SessionKey>,
132}
133
134impl FileEvent {
135    pub fn new(
136        session: &SessionKey,
137        cwd: &Path,
138        path: &Path,
139        timestamp: i64,
140        operation: Operation,
141        source: Source,
142    ) -> Self {
143        Self {
144            schema_version: SCHEMA_VERSION,
145            session: session.clone(),
146            timestamp,
147            cwd: cwd.to_path_buf(),
148            path: resolve_path(cwd, path),
149            previous_path: None,
150            operation,
151            source,
152            outcome: Outcome::Unknown,
153            tool_call_id: None,
154            concurrent: Vec::new(),
155        }
156    }
157}
158
159/// Lexical normalization preserves paths even after deletion and never needs
160/// to follow symlinks or read the file.
161pub fn resolve_path(cwd: &Path, path: &Path) -> PathBuf {
162    let mut result = PathBuf::new();
163    for component in cwd.join(path).components() {
164        match component {
165            Component::CurDir => {}
166            Component::ParentDir => {
167                result.pop();
168            }
169            part => result.push(part.as_os_str()),
170        }
171    }
172    result
173}
174
175#[cfg(test)]
176mod tests;