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