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 = dirs::home_dir().ok_or_else(|| eyre::eyre!("failed to resolve home directory"))?;
51        let ts = SystemTime::now()
52            .duration_since(UNIX_EPOCH)
53            .map(|d| d.as_millis())
54            .unwrap_or(0);
55        let pid = std::process::id();
56        let root = home
57            .join(".nitpicker")
58            .join("sessions")
59            .join(format!("session-{ts}-{pid}"));
60        std::fs::create_dir_all(&root)
61            .wrap_err_with(|| format!("failed to create session dir {}", root.display()))?;
62        Ok(Some(Self {
63            root: Arc::new(root),
64            write_lock: Arc::new(Mutex::new(())),
65        }))
66    }
67
68    pub fn root(&self) -> &Path {
69        self.root.as_ref()
70    }
71
72    pub fn child(&self, relative_path: impl AsRef<Path>) -> SessionWriter {
73        SessionWriter {
74            root: Arc::clone(&self.root),
75            relative_path: relative_path.as_ref().to_path_buf(),
76            write_lock: Arc::clone(&self.write_lock),
77        }
78    }
79
80    pub async fn write_aggregation(&self, record: &AggregationRecord) -> Result<()> {
81        let path = self.root.join("aggregation.json");
82        let body = serde_json::to_vec_pretty(record)?;
83        tokio::fs::write(&path, body)
84            .await
85            .wrap_err_with(|| format!("failed to write aggregation log {}", path.display()))?;
86        Ok(())
87    }
88}
89
90#[derive(Clone)]
91pub struct SessionWriter {
92    root: Arc<PathBuf>,
93    relative_path: PathBuf,
94    write_lock: Arc<Mutex<()>>,
95}
96
97impl SessionWriter {
98    pub async fn append_tool_call(&self, record: &ToolCallRecord) -> Result<()> {
99        let path = self.root.join(&self.relative_path);
100        if let Some(parent) = path.parent() {
101            tokio::fs::create_dir_all(parent)
102                .await
103                .wrap_err_with(|| format!("failed to create session log dir {}", parent.display()))?;
104        }
105        let mut buf = serde_json::to_vec(record)?;
106        buf.push(b'\n');
107        // hold the lock across open+write so concurrent appends emit whole lines, not interleaved bytes
108        let _guard = self.write_lock.lock().await;
109        let mut file = OpenOptions::new()
110            .create(true)
111            .append(true)
112            .open(&path)
113            .await
114            .wrap_err_with(|| format!("failed to open session log {}", path.display()))?;
115        file.write_all(&buf).await?;
116        Ok(())
117    }
118}
119
120pub fn now_unix_ms() -> u128 {
121    SystemTime::now()
122        .duration_since(UNIX_EPOCH)
123        .map(|d| d.as_millis())
124        .unwrap_or(0)
125}
126
127pub fn sanitize_path_component(value: &str) -> String {
128    let sanitized: String = value
129        .chars()
130        .map(|ch| match ch {
131            'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' => ch,
132            _ => '-',
133        })
134        .collect();
135    let trimmed = sanitized.trim_matches('-');
136    if trimmed.is_empty() {
137        "agent".to_string()
138    } else {
139        trimmed.to_string()
140    }
141}