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