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, subagent_transcripts, transcript_events, transcript_last_activity};
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/// Schema 2 adds `FileEvent::concurrent`. Schema 1 batches remain readable.
20pub const SCHEMA_VERSION: u32 = 2;
21
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
23#[serde(rename_all = "snake_case")]
24pub enum Agent {
25    #[default]
26    Claude,
27    Codex,
28}
29
30impl Agent {
31    pub fn name(self) -> &'static str {
32        match self {
33            Self::Claude => "Claude Code",
34            Self::Codex => "Codex",
35        }
36    }
37
38    pub fn slug(self) -> &'static str {
39        match self {
40            Self::Claude => "claude",
41            Self::Codex => "codex",
42        }
43    }
44}
45
46#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
47pub struct SessionKey {
48    pub agent: Agent,
49    pub session_id: String,
50}
51
52impl SessionKey {
53    pub fn validate(&self) -> anyhow::Result<()> {
54        anyhow::ensure!(valid_id(&self.session_id), "invalid session id");
55        Ok(())
56    }
57}
58
59pub fn valid_id(id: &str) -> bool {
60    !id.is_empty()
61        && id != "."
62        && id != ".."
63        && id.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
64}
65
66#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
67#[serde(rename_all = "snake_case")]
68pub enum Operation {
69    Read,
70    Write,
71    Create,
72    Modify,
73    Delete,
74    Rename,
75    Observed,
76}
77
78#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
79#[serde(rename_all = "snake_case")]
80pub enum Source {
81    Hook,
82    Transcript,
83    ProjectScan,
84    ScratchpadScan,
85    MemoryScan,
86    LegacyRegistry,
87}
88
89#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
90#[serde(rename_all = "snake_case")]
91pub enum Outcome {
92    Succeeded,
93    Failed,
94    Unknown,
95}
96
97/// A metadata-only observation. Renames use `path` for the destination and
98/// `previous_path` for the source. Unknown outcomes are never promoted by a scan.
99#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
100pub struct FileEvent {
101    pub schema_version: u32,
102    pub session: SessionKey,
103    pub timestamp: i64,
104    pub cwd: PathBuf,
105    pub path: PathBuf,
106    pub previous_path: Option<PathBuf>,
107    pub operation: Operation,
108    pub source: Source,
109    pub outcome: Outcome,
110    pub tool_call_id: Option<String>,
111    /// Other sessions that were working where a scan observed this file, so
112    /// the filesystem cannot tell which of them changed it.
113    #[serde(default, skip_serializing_if = "Vec::is_empty")]
114    pub concurrent: Vec<SessionKey>,
115}
116
117impl FileEvent {
118    pub fn new(
119        session: &SessionKey,
120        cwd: &Path,
121        path: &Path,
122        timestamp: i64,
123        operation: Operation,
124        source: Source,
125    ) -> Self {
126        Self {
127            schema_version: SCHEMA_VERSION,
128            session: session.clone(),
129            timestamp,
130            cwd: cwd.to_path_buf(),
131            path: resolve_path(cwd, path),
132            previous_path: None,
133            operation,
134            source,
135            outcome: Outcome::Unknown,
136            tool_call_id: None,
137            concurrent: Vec::new(),
138        }
139    }
140}
141
142/// Lexical normalization preserves paths even after deletion and never needs
143/// to follow symlinks or read the file.
144pub fn resolve_path(cwd: &Path, path: &Path) -> PathBuf {
145    let mut result = PathBuf::new();
146    for component in cwd.join(path).components() {
147        match component {
148            Component::CurDir => {}
149            Component::ParentDir => {
150                result.pop();
151            }
152            part => result.push(part.as_os_str()),
153        }
154    }
155    result
156}
157
158#[cfg(test)]
159mod tests;