normalize-chat-sessions 0.3.1

Session log parsing for AI coding agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Log format plugins.
//!
//! Each format implements the `LogFormat` trait for parsing session logs.
//!
//! # Extensibility
//!
//! Users can register custom formats via [`register()`]:
//!
//! ```ignore
//! use normalize_chat_sessions::{LogFormat, SessionFile, register};
//! use std::path::{Path, PathBuf};
//!
//! struct MyAgentFormat;
//!
//! impl LogFormat for MyAgentFormat {
//!     fn name(&self) -> &'static str { "myagent" }
//!     fn sessions_dir(&self, project: Option<&Path>) -> PathBuf { /* ... */ }
//!     fn list_sessions(&self, project: Option<&Path>) -> Vec<SessionFile> { /* ... */ }
//!     fn detect(&self, path: &Path) -> f64 { /* ... */ }
//! }
//!
//! // Register before first use
//! register(&MyAgentFormat);
//! ```

#[cfg(feature = "format-claude")]
mod claude_code;
#[cfg(feature = "format-codex")]
mod codex;
#[cfg(feature = "format-gemini")]
mod gemini_cli;
#[cfg(feature = "format-normalize")]
mod normalize_agent;

#[cfg(feature = "format-claude")]
pub use claude_code::ClaudeCodeFormat;
#[cfg(feature = "format-codex")]
pub use codex::CodexFormat;
#[cfg(feature = "format-gemini")]
pub use gemini_cli::GeminiCliFormat;
#[cfg(feature = "format-normalize")]
pub use normalize_agent::NormalizeAgentFormat;

use crate::Session;
use std::fs::File;
use std::io::{BufRead, BufReader, Read};
use std::path::{Path, PathBuf};
use std::sync::{OnceLock, RwLock};

/// Error type for session log parsing operations.
#[derive(Debug, thiserror::Error)]
pub enum ParseError {
    /// I/O error reading a session log file.
    #[error("I/O error reading {path}: {source}")]
    Io {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
    /// Structural parse error in a session log file.
    #[error("parse error in {path}: {message}")]
    Format { path: PathBuf, message: String },
    /// Other error (e.g. unknown format, registry failure).
    #[error("{0}")]
    Other(String),
}

/// Global registry of log format plugins.
static FORMATS: RwLock<Vec<&'static dyn LogFormat>> = RwLock::new(Vec::new());
static INITIALIZED: OnceLock<()> = OnceLock::new();

/// Register a custom log format plugin.
///
/// Call this before any parsing operations to add custom formats.
/// Built-in formats are registered automatically on first use.
pub fn register(format: &'static dyn LogFormat) {
    // normalize-syntax-allow: rust/unwrap-in-impl - mutex poison on a global registry is unrecoverable
    FORMATS.write().unwrap().push(format);
}

/// Initialize built-in formats (called automatically on first use).
fn init_builtin() {
    INITIALIZED.get_or_init(|| {
        // normalize-syntax-allow: rust/unwrap-in-impl - mutex poison on a global registry is unrecoverable
        let mut formats = FORMATS.write().unwrap();
        #[cfg(feature = "format-claude")]
        formats.push(&ClaudeCodeFormat);
        #[cfg(feature = "format-codex")]
        formats.push(&CodexFormat);
        #[cfg(feature = "format-gemini")]
        formats.push(&GeminiCliFormat);
        #[cfg(feature = "format-normalize")]
        formats.push(&NormalizeAgentFormat);
    });
}

/// Session file with metadata.
pub struct SessionFile {
    pub path: PathBuf,
    pub mtime: std::time::SystemTime,
    /// Parent session ID (set for subagent sessions).
    pub parent_id: Option<String>,
    /// Agent ID (set for subagent sessions, e.g. "agent-a5c5ccc9c2b61e757").
    pub agent_id: Option<String>,
    /// Subagent type from meta.json (e.g. "general-purpose", "Explore").
    pub subagent_type: Option<String>,
}

/// Trait for session log format plugins.
pub trait LogFormat: Send + Sync {
    /// Format identifier (e.g., "claude", "codex", "gemini", "normalize").
    fn name(&self) -> &'static str;

    /// Get the sessions directory for this format.
    /// Does NOT check if the directory exists - that's handled by list_sessions.
    fn sessions_dir(&self, project: Option<&Path>) -> PathBuf;

    /// List all session files for this format.
    fn list_sessions(&self, project: Option<&Path>) -> Vec<SessionFile>;

    /// List subagent session files for this format.
    /// Default returns empty (only Claude Code supports subagents currently).
    fn list_subagent_sessions(&self, _project: Option<&Path>) -> Vec<SessionFile> {
        Vec::new()
    }

    /// Returns external directories (outside the project root) that belong to this format's
    /// session metadata for the given project. Used by `normalize sync` to copy metadata
    /// alongside the project.
    ///
    /// Default implementation delegates to `sessions_dir`. Override only if your format
    /// stores metadata in multiple locations.
    fn metadata_roots(&self, project: Option<&Path>) -> Vec<PathBuf> {
        vec![self.sessions_dir(project)]
    }

    /// Check if this format can parse the given file.
    /// Returns a confidence score 0.0-1.0.
    fn detect(&self, path: &Path) -> f64;

    /// Parse the log file into a unified Session structure.
    fn parse(&self, path: &Path) -> Result<Session, ParseError>;
}

/// Get a format by name from the global registry.
pub fn get_format(name: &str) -> Option<&'static dyn LogFormat> {
    init_builtin();
    // normalize-syntax-allow: rust/unwrap-in-impl - mutex poison on a global registry is unrecoverable
    FORMATS
        .read()
        .unwrap()
        .iter()
        .find(|f| f.name() == name)
        .copied()
}

/// Auto-detect format for a file using the global registry.
pub fn detect_format(path: &Path) -> Option<&'static dyn LogFormat> {
    init_builtin();
    // normalize-syntax-allow: rust/unwrap-in-impl - mutex poison on a global registry is unrecoverable
    let formats = FORMATS.read().unwrap();
    let mut best: Option<(&'static dyn LogFormat, f64)> = None;
    for fmt in formats.iter() {
        let score = fmt.detect(path);
        if score > 0.0 && best.is_none_or(|(_, best_score)| score > best_score) {
            best = Some((*fmt, score));
        }
    }
    best.map(|(fmt, _)| fmt)
}

/// List all available format names from the global registry.
pub fn list_formats() -> Vec<&'static str> {
    init_builtin();
    // normalize-syntax-allow: rust/unwrap-in-impl - mutex poison on a global registry is unrecoverable
    FORMATS.read().unwrap().iter().map(|f| f.name()).collect()
}

/// Returns all external metadata directories for the given project across all known formats.
///
/// Only directories that actually exist on disk are returned. Used by `normalize sync` to
/// discover what session metadata to copy alongside the project directory.
pub fn project_metadata_roots(project: &Path) -> Vec<PathBuf> {
    init_builtin();
    // normalize-syntax-allow: rust/unwrap-in-impl - mutex poison on a global registry is unrecoverable
    FORMATS
        .read()
        .unwrap()
        .iter()
        .flat_map(|f| f.metadata_roots(Some(project)))
        .filter(|p| p.exists())
        .collect()
}

/// Default implementation: list .jsonl files in a directory.
pub fn list_jsonl_sessions(dir: &Path) -> Vec<SessionFile> {
    let mut sessions = Vec::new();
    if let Ok(entries) = std::fs::read_dir(dir) {
        for entry in entries.filter_map(|e| e.ok()) {
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) == Some("jsonl")
                && let Ok(meta) = path.metadata()
                && let Ok(mtime) = meta.modified()
            {
                sessions.push(SessionFile {
                    path,
                    mtime,
                    parent_id: None,
                    agent_id: None,
                    subagent_type: Some("interactive".into()),
                });
            }
        }
    }
    sessions
}

/// List subagent sessions from `<session-uuid>/subagents/` directories.
///
/// Walks each subdirectory of `dir` looking for a `subagents/` folder containing
/// `agent-<id>.jsonl` files. Also reads the companion `.meta.json` for agent type.
pub fn list_subagent_sessions(dir: &Path) -> Vec<SessionFile> {
    let mut sessions = Vec::new();
    let Ok(entries) = std::fs::read_dir(dir) else {
        return sessions;
    };
    for entry in entries.filter_map(|e| e.ok()) {
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        let parent_id = path.file_name().and_then(|n| n.to_str()).map(String::from);
        let subagents_dir = path.join("subagents");
        if !subagents_dir.is_dir() {
            continue;
        }
        let Ok(sub_entries) = std::fs::read_dir(&subagents_dir) else {
            continue;
        };
        for sub_entry in sub_entries.filter_map(|e| e.ok()) {
            let sub_path = sub_entry.path();
            if sub_path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
                continue;
            }
            let stem = match sub_path.file_stem().and_then(|s| s.to_str()) {
                Some(s) => s.to_string(),
                None => continue,
            };
            if !stem.starts_with("agent-") {
                continue;
            }
            let Ok(meta) = sub_path.metadata() else {
                continue;
            };
            let Ok(mtime) = meta.modified() else {
                continue;
            };
            // Read companion .meta.json for agent type, default to "subagent"
            let meta_path = sub_path.with_extension("meta.json");
            let subagent_type = Some(
                std::fs::read_to_string(&meta_path)
                    .ok()
                    .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
                    .and_then(|v| {
                        v.get("agentType")
                            .and_then(|t| t.as_str())
                            .map(String::from)
                    })
                    .unwrap_or_else(|| "subagent".into()),
            );
            sessions.push(SessionFile {
                path: sub_path,
                mtime,
                parent_id: parent_id.clone(),
                agent_id: Some(stem.clone()),
                subagent_type,
            });
        }
    }
    sessions
}

/// Registry of available log formats.
///
/// For most use cases, prefer the global registry via [`register()`],
/// [`get_format()`], [`detect_format()`], and [`list_formats()`].
///
/// Use `FormatRegistry` when you need an isolated registry (e.g., testing).
pub struct FormatRegistry {
    formats: Vec<Box<dyn LogFormat>>,
}

impl Default for FormatRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl FormatRegistry {
    /// Create a new registry with all built-in formats.
    #[allow(clippy::vec_init_then_push)] // cfg-gated pushes can't use vec![]
    pub fn new() -> Self {
        let mut formats: Vec<Box<dyn LogFormat>> = Vec::new();
        #[cfg(feature = "format-claude")]
        formats.push(Box::new(ClaudeCodeFormat));
        #[cfg(feature = "format-codex")]
        formats.push(Box::new(CodexFormat));
        #[cfg(feature = "format-gemini")]
        formats.push(Box::new(GeminiCliFormat));
        #[cfg(feature = "format-normalize")]
        formats.push(Box::new(NormalizeAgentFormat));
        Self { formats }
    }

    /// Create an empty registry (no built-in formats).
    pub fn empty() -> Self {
        Self { formats: vec![] }
    }

    /// Register a custom format.
    pub fn register(&mut self, format: Box<dyn LogFormat>) {
        self.formats.push(format);
    }

    /// Detect the best format for a file.
    pub fn detect(&self, path: &Path) -> Option<&dyn LogFormat> {
        let mut best: Option<(&dyn LogFormat, f64)> = None;
        for fmt in &self.formats {
            let score = fmt.detect(path);
            if score > 0.0 && best.is_none_or(|(_, best_score)| score > best_score) {
                best = Some((fmt.as_ref(), score));
            }
        }
        best.map(|(fmt, _)| fmt)
    }

    /// Get a format by name.
    pub fn get(&self, name: &str) -> Option<&dyn LogFormat> {
        self.formats
            .iter()
            .find(|f| f.name() == name)
            .map(|f| f.as_ref())
    }

    /// List all available format names.
    pub fn list(&self) -> Vec<&'static str> {
        self.formats.iter().map(|f| f.name()).collect()
    }

    /// List subagent sessions across all registered formats.
    pub fn list_subagent_sessions(&self, project: Option<&Path>) -> Vec<SessionFile> {
        let mut all = Vec::new();
        for fmt in &self.formats {
            all.extend(fmt.list_subagent_sessions(project));
        }
        all
    }
}

/// Parse a session log with auto-format detection.
pub fn parse_session(path: &Path) -> Result<Session, ParseError> {
    let registry = FormatRegistry::new();
    let format = registry
        .detect(path)
        .ok_or_else(|| ParseError::Other(format!("Unknown log format: {}", path.display())))?;
    format.parse(path)
}

/// Parse a session log with explicit format.
pub fn parse_session_with_format(path: &Path, format_name: &str) -> Result<Session, ParseError> {
    let registry = FormatRegistry::new();
    let format = registry
        .get(format_name)
        .ok_or_else(|| ParseError::Other(format!("Unknown format: {}", format_name)))?;
    format.parse(path)
}

/// Helper: read first N lines of a file.
pub(crate) fn peek_lines(path: &Path, n: usize) -> Vec<String> {
    let Ok(file) = File::open(path) else {
        return Vec::new();
    };
    BufReader::new(file)
        .lines()
        .take(n)
        .filter_map(|l| l.ok())
        .collect()
}

/// Helper: read entire file as string.
pub(crate) fn read_file(path: &Path) -> Result<String, ParseError> {
    let mut file = File::open(path).map_err(|e| ParseError::Io {
        path: path.to_path_buf(),
        source: e,
    })?;
    let mut content = String::new();
    file.read_to_string(&mut content)
        .map_err(|e| ParseError::Io {
            path: path.to_path_buf(),
            source: e,
        })?;
    Ok(content)
}