Skip to main content

nitpicker_agent/
session.rs

1use eyre::{Result, WrapErr};
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use std::time::{SystemTime, UNIX_EPOCH};
7use tokio::fs::OpenOptions;
8use tokio::io::AsyncWriteExt;
9use tokio::sync::Mutex;
10
11#[derive(Clone)]
12pub struct SessionLogger {
13    root: Arc<PathBuf>,
14    // serializes appends so concurrent subagents sharing a writer don't interleave lines
15    write_lock: Arc<Mutex<()>>,
16}
17
18#[derive(Debug, Serialize, Deserialize)]
19pub struct AggregationRecord {
20    pub kind: String,
21    pub model: String,
22    pub text: String,
23    #[serde(skip_serializing_if = "Option::is_none")]
24    pub rounds: Option<usize>,
25    #[serde(skip_serializing_if = "Option::is_none")]
26    pub converged: Option<bool>,
27}
28
29#[derive(Debug, Serialize, Deserialize)]
30pub struct ToolCallRecord {
31    pub ts_unix_ms: u128,
32    pub agent: String,
33    pub depth: usize,
34    pub turn: usize,
35    pub tool: String,
36    pub args: Value,
37    pub status: String,
38    #[serde(skip_serializing_if = "Option::is_none")]
39    pub spawned_agent: Option<String>,
40    #[serde(skip_serializing_if = "Option::is_none")]
41    pub result: Option<String>,
42}
43
44impl SessionLogger {
45    pub fn maybe_new(enabled: bool) -> Result<Option<Self>> {
46        if !enabled {
47            return Ok(None);
48        }
49
50        let home =
51            dirs::home_dir().ok_or_else(|| eyre::eyre!("failed to resolve home directory"))?;
52        let ts = now_unix_ms();
53        let pid = std::process::id();
54        let root = home
55            .join(".nitpicker")
56            .join("sessions")
57            .join(format!("session-{ts}-{pid}"));
58        std::fs::create_dir_all(&root)
59            .wrap_err_with(|| format!("failed to create session dir {}", root.display()))?;
60        Ok(Some(Self {
61            root: Arc::new(root),
62            write_lock: Arc::new(Mutex::new(())),
63        }))
64    }
65
66    pub fn root(&self) -> &Path {
67        self.root.as_ref()
68    }
69
70    pub fn child(&self, relative_path: impl AsRef<Path>) -> SessionWriter {
71        SessionWriter {
72            root: Arc::clone(&self.root),
73            relative_path: relative_path.as_ref().to_path_buf(),
74            write_lock: Arc::clone(&self.write_lock),
75        }
76    }
77
78    pub async fn write_aggregation(&self, record: &AggregationRecord) -> Result<()> {
79        let path = self.root.join("aggregation.json");
80        let body = serde_json::to_vec_pretty(record)?;
81        tokio::fs::write(&path, body)
82            .await
83            .wrap_err_with(|| format!("failed to write aggregation log {}", path.display()))?;
84        Ok(())
85    }
86}
87
88#[derive(Clone)]
89pub struct SessionWriter {
90    root: Arc<PathBuf>,
91    relative_path: PathBuf,
92    write_lock: Arc<Mutex<()>>,
93}
94
95impl SessionWriter {
96    pub async fn append_tool_call(&self, record: &ToolCallRecord) -> Result<()> {
97        let path = self.root.join(&self.relative_path);
98        if let Some(parent) = path.parent() {
99            tokio::fs::create_dir_all(parent).await.wrap_err_with(|| {
100                format!("failed to create session log dir {}", parent.display())
101            })?;
102        }
103        let mut buf = serde_json::to_vec(record)?;
104        buf.push(b'\n');
105        // hold the lock across open+write so concurrent appends emit whole lines, not interleaved bytes
106        let _guard = self.write_lock.lock().await;
107        let mut file = OpenOptions::new()
108            .create(true)
109            .append(true)
110            .open(&path)
111            .await
112            .wrap_err_with(|| format!("failed to open session log {}", path.display()))?;
113        file.write_all(&buf).await?;
114        // tokio's write_all returns once bytes are handed to the background blocking write;
115        // without the flush a real I/O error is dropped with the file handle, and a
116        // process::exit right after append can lose the final record
117        file.flush().await?;
118        Ok(())
119    }
120}
121
122pub fn now_unix_ms() -> u128 {
123    SystemTime::now()
124        .duration_since(UNIX_EPOCH)
125        .map(|d| d.as_millis())
126        .unwrap_or(0)
127}
128
129pub fn sanitize_path_component(value: &str) -> String {
130    let sanitized: String = value
131        .chars()
132        .map(|ch| match ch {
133            'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' => ch,
134            _ => '-',
135        })
136        .collect();
137    let trimmed = sanitized.trim_matches('-');
138    if trimmed.is_empty() {
139        "agent".to_string()
140    } else {
141        trimmed.to_string()
142    }
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148
149    /// The record must be on disk, whole, by the time `append_tool_call` returns — exit paths
150    /// that skip teardown (`process::exit`) rely on it.
151    #[tokio::test]
152    async fn appended_record_is_durable_and_parseable_on_return() {
153        let dir = tempfile::tempdir().unwrap();
154        let writer = SessionWriter {
155            root: Arc::new(dir.path().to_path_buf()),
156            relative_path: PathBuf::from("agent.jsonl"),
157            write_lock: Arc::new(Mutex::new(())),
158        };
159        let record = ToolCallRecord {
160            ts_unix_ms: 1,
161            agent: "reviewer-1-x".to_string(),
162            depth: 0,
163            turn: 1,
164            tool: "read_file".to_string(),
165            args: serde_json::json!({"path": "a.rs"}),
166            status: "ok".to_string(),
167            spawned_agent: None,
168            result: None,
169        };
170        writer.append_tool_call(&record).await.unwrap();
171        writer.append_tool_call(&record).await.unwrap();
172
173        let content = std::fs::read_to_string(dir.path().join("agent.jsonl")).unwrap();
174        let lines: Vec<ToolCallRecord> = content
175            .lines()
176            .map(|l| serde_json::from_str(l).unwrap())
177            .collect();
178        assert_eq!(lines.len(), 2);
179        assert_eq!(lines[0].agent, "reviewer-1-x");
180    }
181}