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 write_lock: Arc<Mutex<()>>,
16}
17
18#[derive(Clone, Debug, Serialize, Deserialize)]
19pub struct SessionAttribution {
20 pub binary_version: String,
22 #[serde(skip_serializing_if = "Option::is_none")]
24 pub binary_revision: Option<String>,
25 pub protocol_prompt_sha256: String,
27}
28
29#[derive(Debug, Serialize, Deserialize)]
30pub struct AggregationRecord {
31 pub kind: String,
32 pub model: String,
33 pub text: String,
34 #[serde(skip_serializing_if = "Option::is_none")]
38 pub error: Option<String>,
39 #[serde(skip_serializing_if = "Option::is_none")]
40 pub rounds: Option<usize>,
41 #[serde(skip_serializing_if = "Option::is_none")]
42 pub converged: Option<bool>,
43 #[serde(skip_serializing_if = "Option::is_none")]
46 pub presets: Option<Vec<String>>,
47 #[serde(skip_serializing_if = "Option::is_none")]
49 pub lanes: Option<Vec<LaneRecord>>,
50 pub verdicts: Vec<VerdictRecord>,
53 #[serde(skip_serializing_if = "Option::is_none")]
57 pub jobs: Option<Vec<JobRecord>>,
58}
59
60#[derive(Debug, Serialize, Deserialize)]
61pub struct VerdictRecord {
62 #[serde(skip_serializing_if = "Option::is_none")]
64 pub lens: Option<String>,
65 pub stage: String,
67 pub text: String,
68 pub ok: bool,
69}
70
71#[derive(Debug, Serialize, Deserialize)]
72pub struct LaneRecord {
73 pub preset: String,
74 pub rounds: usize,
75 pub converged: bool,
76 pub degraded: bool,
77}
78
79#[derive(Debug, Serialize, Deserialize)]
80pub struct JobRecord {
81 pub label: String,
82 #[serde(skip_serializing_if = "Option::is_none")]
84 pub preset: Option<String>,
85 pub ok: bool,
86}
87
88#[derive(Debug, Serialize, Deserialize)]
89pub struct ToolCallRecord {
90 pub ts_unix_ms: u128,
91 pub agent: String,
92 pub depth: usize,
93 pub turn: usize,
94 pub tool: String,
95 pub args: Value,
96 pub status: String,
97 #[serde(skip_serializing_if = "Option::is_none")]
98 pub spawned_agent: Option<String>,
99 #[serde(skip_serializing_if = "Option::is_none")]
100 pub result: Option<String>,
101 #[serde(skip_serializing_if = "Option::is_none")]
105 pub model: Option<String>,
106}
107
108impl SessionLogger {
109 pub fn maybe_new(enabled: bool) -> Result<Option<Self>> {
110 if !enabled {
111 return Ok(None);
112 }
113
114 let home =
115 dirs::home_dir().ok_or_else(|| eyre::eyre!("failed to resolve home directory"))?;
116 let ts = now_unix_ms();
117 let pid = std::process::id();
118 let root = home
119 .join(".nitpicker")
120 .join("sessions")
121 .join(format!("session-{ts}-{pid}"));
122 std::fs::create_dir_all(&root)
123 .wrap_err_with(|| format!("failed to create session dir {}", root.display()))?;
124 Ok(Some(Self {
125 root: Arc::new(root),
126 write_lock: Arc::new(Mutex::new(())),
127 }))
128 }
129
130 pub fn root(&self) -> &Path {
131 self.root.as_ref()
132 }
133
134 pub fn child(&self, relative_path: impl AsRef<Path>) -> SessionWriter {
135 SessionWriter {
136 root: Arc::clone(&self.root),
137 relative_path: relative_path.as_ref().to_path_buf(),
138 write_lock: Arc::clone(&self.write_lock),
139 }
140 }
141
142 pub async fn write_aggregation(&self, record: &AggregationRecord) -> Result<()> {
143 let path = self.root.join("aggregation.json");
144 let body = serde_json::to_vec_pretty(record)?;
145 tokio::fs::write(&path, body)
146 .await
147 .wrap_err_with(|| format!("failed to write aggregation log {}", path.display()))?;
148 Ok(())
149 }
150
151 pub async fn write_attribution(&self, record: &SessionAttribution) -> Result<()> {
152 let path = self.root.join("attribution.json");
153 let body = serde_json::to_vec_pretty(record)?;
154 tokio::fs::write(&path, body)
155 .await
156 .wrap_err_with(|| format!("failed to write session attribution {}", path.display()))?;
157 Ok(())
158 }
159}
160
161#[derive(Clone)]
162pub struct SessionWriter {
163 root: Arc<PathBuf>,
164 relative_path: PathBuf,
165 write_lock: Arc<Mutex<()>>,
166}
167
168impl SessionWriter {
169 pub async fn append_tool_call(&self, record: &ToolCallRecord) -> Result<()> {
170 let path = self.root.join(&self.relative_path);
171 if let Some(parent) = path.parent() {
172 tokio::fs::create_dir_all(parent).await.wrap_err_with(|| {
173 format!("failed to create session log dir {}", parent.display())
174 })?;
175 }
176 let mut buf = serde_json::to_vec(record)?;
177 buf.push(b'\n');
178 let _guard = self.write_lock.lock().await;
180 let mut file = OpenOptions::new()
181 .create(true)
182 .append(true)
183 .open(&path)
184 .await
185 .wrap_err_with(|| format!("failed to open session log {}", path.display()))?;
186 file.write_all(&buf).await?;
187 file.flush().await?;
191 Ok(())
192 }
193}
194
195pub fn now_unix_ms() -> u128 {
196 SystemTime::now()
197 .duration_since(UNIX_EPOCH)
198 .map(|d| d.as_millis())
199 .unwrap_or(0)
200}
201
202pub fn sanitize_path_component(value: &str) -> String {
203 let sanitized: String = value
204 .chars()
205 .map(|ch| match ch {
206 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' => ch,
207 _ => '-',
208 })
209 .collect();
210 let trimmed = sanitized.trim_matches('-');
211 if trimmed.is_empty() {
212 "agent".to_string()
213 } else {
214 trimmed.to_string()
215 }
216}
217
218#[cfg(test)]
219mod tests {
220 use super::*;
221
222 #[tokio::test]
225 async fn appended_record_is_durable_and_parseable_on_return() {
226 let dir = tempfile::tempdir().unwrap();
227 let writer = SessionWriter {
228 root: Arc::new(dir.path().to_path_buf()),
229 relative_path: PathBuf::from("agent.jsonl"),
230 write_lock: Arc::new(Mutex::new(())),
231 };
232 let record = ToolCallRecord {
233 ts_unix_ms: 1,
234 agent: "reviewer-1-x".to_string(),
235 depth: 0,
236 turn: 1,
237 tool: "read_file".to_string(),
238 args: serde_json::json!({"path": "a.rs"}),
239 status: "ok".to_string(),
240 spawned_agent: None,
241 result: None,
242 model: Some("kimi-k2".to_string()),
243 };
244 writer.append_tool_call(&record).await.unwrap();
245 writer.append_tool_call(&record).await.unwrap();
246
247 let content = std::fs::read_to_string(dir.path().join("agent.jsonl")).unwrap();
248 let lines: Vec<ToolCallRecord> = content
249 .lines()
250 .map(|l| serde_json::from_str(l).unwrap())
251 .collect();
252 assert_eq!(lines.len(), 2);
253 assert_eq!(lines[0].agent, "reviewer-1-x");
254 }
255
256 #[test]
259 fn aggregation_records_require_and_round_trip_staged_verdicts() {
260 let current = AggregationRecord {
261 kind: "aggregation".to_string(),
262 model: "m".to_string(),
263 text: String::new(),
264 error: Some("provider 500".to_string()),
265 rounds: None,
266 converged: None,
267 presets: Some(vec!["security".to_string()]),
268 lanes: Some(vec![LaneRecord {
269 preset: "security".to_string(),
270 rounds: 1,
271 converged: true,
272 degraded: false,
273 }]),
274 verdicts: vec![VerdictRecord {
275 lens: Some("security".to_string()),
276 stage: "Reviewer · round 1".to_string(),
277 text: "Looks unsafe.".to_string(),
278 ok: true,
279 }],
280 jobs: Some(vec![JobRecord {
281 label: "security · r".to_string(),
282 preset: Some("security".to_string()),
283 ok: false,
284 }]),
285 };
286 let round_tripped: AggregationRecord =
287 serde_json::from_str(&serde_json::to_string(¤t).unwrap()).unwrap();
288 assert_eq!(round_tripped.error.as_deref(), Some("provider 500"));
289 assert_eq!(round_tripped.lanes.unwrap()[0].preset, "security");
290 assert_eq!(round_tripped.verdicts[0].stage, "Reviewer · round 1");
291 assert!(!round_tripped.jobs.unwrap()[0].ok);
292 let outdated = r#"{"kind":"aggregation","model":"m","text":"t"}"#;
293 assert!(serde_json::from_str::<AggregationRecord>(outdated).is_err());
294 }
295
296 #[tokio::test]
297 async fn session_attribution_round_trips_as_a_sidecar() {
298 let dir = tempfile::tempdir().unwrap();
299 let logger = SessionLogger {
300 root: Arc::new(dir.path().to_path_buf()),
301 write_lock: Arc::new(Mutex::new(())),
302 };
303 let attribution = SessionAttribution {
304 binary_version: "0.9.3".to_string(),
305 binary_revision: Some("abc123-dirty".to_string()),
306 protocol_prompt_sha256: "f".repeat(64),
307 };
308
309 logger.write_attribution(&attribution).await.unwrap();
310
311 let body = std::fs::read_to_string(dir.path().join("attribution.json")).unwrap();
312 let restored: SessionAttribution = serde_json::from_str(&body).unwrap();
313 assert_eq!(restored.binary_version, "0.9.3");
314 assert_eq!(restored.binary_revision.as_deref(), Some("abc123-dirty"));
315 assert_eq!(restored.protocol_prompt_sha256, "f".repeat(64));
316 }
317}