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    /// Present iff synthesis failed after the per-job/lane work completed (`text` is empty
24    /// then): the record still carries `jobs`/`lanes`, which would otherwise die with the
25    /// aggregator. Consumers must not render `text` as a verdict when this is set.
26    #[serde(skip_serializing_if = "Option::is_none")]
27    pub error: Option<String>,
28    #[serde(skip_serializing_if = "Option::is_none")]
29    pub rounds: Option<usize>,
30    #[serde(skip_serializing_if = "Option::is_none")]
31    pub converged: Option<bool>,
32    /// Resolved preset names for the run, in order. Absent on pre-preset records and on
33    /// runs without preset fan-out (`ask`), so old sessions keep deserializing.
34    #[serde(skip_serializing_if = "Option::is_none")]
35    pub presets: Option<Vec<String>>,
36    /// Per-lane convergence metadata for preset debate runs; absent elsewhere.
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub lanes: Option<Vec<LaneRecord>>,
39    /// Per-job outcomes for parallel review runs; absent elsewhere. The durable record of
40    /// what actually ran — a failed job is otherwise only a transient log line, and a
41    /// client-build failure writes no trajectory file at all.
42    #[serde(skip_serializing_if = "Option::is_none")]
43    pub jobs: Option<Vec<JobRecord>>,
44}
45
46#[derive(Debug, Serialize, Deserialize)]
47pub struct LaneRecord {
48    pub preset: String,
49    pub rounds: usize,
50    pub converged: bool,
51    pub degraded: bool,
52}
53
54#[derive(Debug, Serialize, Deserialize)]
55pub struct JobRecord {
56    pub label: String,
57    /// Absent on Ask-path jobs, which have no preset dimension.
58    #[serde(skip_serializing_if = "Option::is_none")]
59    pub preset: Option<String>,
60    pub ok: bool,
61}
62
63#[derive(Debug, Serialize, Deserialize)]
64pub struct ToolCallRecord {
65    pub ts_unix_ms: u128,
66    pub agent: String,
67    pub depth: usize,
68    pub turn: usize,
69    pub tool: String,
70    pub args: Value,
71    pub status: String,
72    #[serde(skip_serializing_if = "Option::is_none")]
73    pub spawned_agent: Option<String>,
74    #[serde(skip_serializing_if = "Option::is_none")]
75    pub result: Option<String>,
76    /// Model that produced the turn issuing this call, when the client reports it — the
77    /// only durable per-turn attribution on alloy runs, where each turn may pick a
78    /// different model. Absent on compaction records and pre-0.3.0 sessions.
79    #[serde(skip_serializing_if = "Option::is_none")]
80    pub model: Option<String>,
81}
82
83impl SessionLogger {
84    pub fn maybe_new(enabled: bool) -> Result<Option<Self>> {
85        if !enabled {
86            return Ok(None);
87        }
88
89        let home =
90            dirs::home_dir().ok_or_else(|| eyre::eyre!("failed to resolve home directory"))?;
91        let ts = now_unix_ms();
92        let pid = std::process::id();
93        let root = home
94            .join(".nitpicker")
95            .join("sessions")
96            .join(format!("session-{ts}-{pid}"));
97        std::fs::create_dir_all(&root)
98            .wrap_err_with(|| format!("failed to create session dir {}", root.display()))?;
99        Ok(Some(Self {
100            root: Arc::new(root),
101            write_lock: Arc::new(Mutex::new(())),
102        }))
103    }
104
105    pub fn root(&self) -> &Path {
106        self.root.as_ref()
107    }
108
109    pub fn child(&self, relative_path: impl AsRef<Path>) -> SessionWriter {
110        SessionWriter {
111            root: Arc::clone(&self.root),
112            relative_path: relative_path.as_ref().to_path_buf(),
113            write_lock: Arc::clone(&self.write_lock),
114        }
115    }
116
117    pub async fn write_aggregation(&self, record: &AggregationRecord) -> Result<()> {
118        let path = self.root.join("aggregation.json");
119        let body = serde_json::to_vec_pretty(record)?;
120        tokio::fs::write(&path, body)
121            .await
122            .wrap_err_with(|| format!("failed to write aggregation log {}", path.display()))?;
123        Ok(())
124    }
125}
126
127#[derive(Clone)]
128pub struct SessionWriter {
129    root: Arc<PathBuf>,
130    relative_path: PathBuf,
131    write_lock: Arc<Mutex<()>>,
132}
133
134impl SessionWriter {
135    pub async fn append_tool_call(&self, record: &ToolCallRecord) -> Result<()> {
136        let path = self.root.join(&self.relative_path);
137        if let Some(parent) = path.parent() {
138            tokio::fs::create_dir_all(parent).await.wrap_err_with(|| {
139                format!("failed to create session log dir {}", parent.display())
140            })?;
141        }
142        let mut buf = serde_json::to_vec(record)?;
143        buf.push(b'\n');
144        // hold the lock across open+write so concurrent appends emit whole lines, not interleaved bytes
145        let _guard = self.write_lock.lock().await;
146        let mut file = OpenOptions::new()
147            .create(true)
148            .append(true)
149            .open(&path)
150            .await
151            .wrap_err_with(|| format!("failed to open session log {}", path.display()))?;
152        file.write_all(&buf).await?;
153        // tokio's write_all returns once bytes are handed to the background blocking write;
154        // without the flush a real I/O error is dropped with the file handle, and a
155        // process::exit right after append can lose the final record
156        file.flush().await?;
157        Ok(())
158    }
159}
160
161pub fn now_unix_ms() -> u128 {
162    SystemTime::now()
163        .duration_since(UNIX_EPOCH)
164        .map(|d| d.as_millis())
165        .unwrap_or(0)
166}
167
168pub fn sanitize_path_component(value: &str) -> String {
169    let sanitized: String = value
170        .chars()
171        .map(|ch| match ch {
172            'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' => ch,
173            _ => '-',
174        })
175        .collect();
176    let trimmed = sanitized.trim_matches('-');
177    if trimmed.is_empty() {
178        "agent".to_string()
179    } else {
180        trimmed.to_string()
181    }
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187
188    /// The record must be on disk, whole, by the time `append_tool_call` returns — exit paths
189    /// that skip teardown (`process::exit`) rely on it.
190    #[tokio::test]
191    async fn appended_record_is_durable_and_parseable_on_return() {
192        let dir = tempfile::tempdir().unwrap();
193        let writer = SessionWriter {
194            root: Arc::new(dir.path().to_path_buf()),
195            relative_path: PathBuf::from("agent.jsonl"),
196            write_lock: Arc::new(Mutex::new(())),
197        };
198        let record = ToolCallRecord {
199            ts_unix_ms: 1,
200            agent: "reviewer-1-x".to_string(),
201            depth: 0,
202            turn: 1,
203            tool: "read_file".to_string(),
204            args: serde_json::json!({"path": "a.rs"}),
205            status: "ok".to_string(),
206            spawned_agent: None,
207            result: None,
208            model: Some("kimi-k2".to_string()),
209        };
210        writer.append_tool_call(&record).await.unwrap();
211        writer.append_tool_call(&record).await.unwrap();
212
213        let content = std::fs::read_to_string(dir.path().join("agent.jsonl")).unwrap();
214        let lines: Vec<ToolCallRecord> = content
215            .lines()
216            .map(|l| serde_json::from_str(l).unwrap())
217            .collect();
218        assert_eq!(lines.len(), 2);
219        assert_eq!(lines[0].agent, "reviewer-1-x");
220    }
221
222    /// `reflect` deserializes historical `aggregation.json` files into this exact type and
223    /// discards unparseable ones as incomplete sessions — a legacy record (no presets/lanes
224    /// keys) and a new-shape record must both keep parsing.
225    #[test]
226    fn aggregation_records_parse_across_schema_generations() {
227        let legacy = r#"{"kind":"aggregation","model":"m","text":"t","rounds":2,"converged":true}"#;
228        let parsed: AggregationRecord = serde_json::from_str(legacy).unwrap();
229        assert_eq!(parsed.rounds, Some(2));
230        assert!(parsed.error.is_none());
231        assert!(parsed.presets.is_none());
232        assert!(parsed.lanes.is_none());
233        assert!(parsed.jobs.is_none());
234
235        let current = AggregationRecord {
236            kind: "aggregation".to_string(),
237            model: "m".to_string(),
238            text: String::new(),
239            error: Some("provider 500".to_string()),
240            rounds: None,
241            converged: None,
242            presets: Some(vec!["security".to_string()]),
243            lanes: Some(vec![LaneRecord {
244                preset: "security".to_string(),
245                rounds: 1,
246                converged: true,
247                degraded: false,
248            }]),
249            jobs: Some(vec![JobRecord {
250                label: "security · r".to_string(),
251                preset: Some("security".to_string()),
252                ok: false,
253            }]),
254        };
255        let round_tripped: AggregationRecord =
256            serde_json::from_str(&serde_json::to_string(&current).unwrap()).unwrap();
257        assert_eq!(round_tripped.error.as_deref(), Some("provider 500"));
258        assert_eq!(round_tripped.lanes.unwrap()[0].preset, "security");
259        assert!(!round_tripped.jobs.unwrap()[0].ok);
260
261        // absent options serialize to absent keys, keeping old readers indifferent
262        let legacy_shaped = AggregationRecord {
263            kind: "aggregation".to_string(),
264            model: "m".to_string(),
265            text: "t".to_string(),
266            error: None,
267            rounds: Some(1),
268            converged: Some(false),
269            presets: None,
270            lanes: None,
271            jobs: None,
272        };
273        let json = serde_json::to_string(&legacy_shaped).unwrap();
274        assert!(!json.contains("error"));
275        assert!(!json.contains("presets"));
276        assert!(!json.contains("lanes"));
277        assert!(!json.contains("jobs"));
278    }
279}