use eyre::{Result, WrapErr};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::fs::OpenOptions;
use tokio::io::AsyncWriteExt;
use tokio::sync::Mutex;
#[derive(Clone)]
pub struct SessionLogger {
root: Arc<PathBuf>,
id: Arc<str>,
write_lock: Arc<Mutex<()>>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SessionAttribution {
pub binary_version: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub binary_revision: Option<String>,
pub protocol_prompt_sha256: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct AggregationRecord {
pub kind: String,
pub model: String,
pub text: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub rounds: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub converged: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub presets: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub lanes: Option<Vec<LaneRecord>>,
pub verdicts: Vec<VerdictRecord>,
#[serde(skip_serializing_if = "Option::is_none")]
pub jobs: Option<Vec<JobRecord>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct VerdictRecord {
#[serde(skip_serializing_if = "Option::is_none")]
pub lens: Option<String>,
pub stage: String,
pub text: String,
pub ok: bool,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct LaneRecord {
pub preset: String,
pub rounds: usize,
pub converged: bool,
pub degraded: bool,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct JobRecord {
pub label: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub preset: Option<String>,
pub ok: bool,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ToolCallRecord {
pub ts_unix_ms: u128,
pub agent: String,
pub depth: usize,
pub turn: usize,
pub tool: String,
pub args: Value,
pub status: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub spawned_agent: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub result: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub model: Option<String>,
}
impl SessionLogger {
pub fn maybe_new(enabled: bool) -> Result<Option<Self>> {
if !enabled {
return Ok(None);
}
let home =
dirs::home_dir().ok_or_else(|| eyre::eyre!("failed to resolve home directory"))?;
let ts = now_unix_ms();
let pid = std::process::id();
let id = format!("session-{ts}-{pid}");
let root = home.join(".nitpicker").join("sessions").join(&id);
std::fs::create_dir_all(&root)
.wrap_err_with(|| format!("failed to create session dir {}", root.display()))?;
Ok(Some(Self {
root: Arc::new(root),
id: Arc::from(id),
write_lock: Arc::new(Mutex::new(())),
}))
}
pub fn root(&self) -> &Path {
self.root.as_ref()
}
pub fn id(&self) -> &str {
&self.id
}
pub fn child(&self, relative_path: impl AsRef<Path>) -> SessionWriter {
SessionWriter {
root: Arc::clone(&self.root),
relative_path: relative_path.as_ref().to_path_buf(),
write_lock: Arc::clone(&self.write_lock),
}
}
pub async fn write_aggregation(&self, record: &AggregationRecord) -> Result<()> {
let path = self.root.join("aggregation.json");
let body = serde_json::to_vec_pretty(record)?;
tokio::fs::write(&path, body)
.await
.wrap_err_with(|| format!("failed to write aggregation log {}", path.display()))?;
Ok(())
}
pub async fn write_attribution(&self, record: &SessionAttribution) -> Result<()> {
let path = self.root.join("attribution.json");
let body = serde_json::to_vec_pretty(record)?;
tokio::fs::write(&path, body)
.await
.wrap_err_with(|| format!("failed to write session attribution {}", path.display()))?;
Ok(())
}
}
#[derive(Clone)]
pub struct SessionWriter {
root: Arc<PathBuf>,
relative_path: PathBuf,
write_lock: Arc<Mutex<()>>,
}
impl SessionWriter {
pub async fn append_tool_call(&self, record: &ToolCallRecord) -> Result<()> {
let path = self.root.join(&self.relative_path);
if let Some(parent) = path.parent() {
tokio::fs::create_dir_all(parent).await.wrap_err_with(|| {
format!("failed to create session log dir {}", parent.display())
})?;
}
let mut buf = serde_json::to_vec(record)?;
buf.push(b'\n');
let _guard = self.write_lock.lock().await;
let mut file = OpenOptions::new()
.create(true)
.append(true)
.open(&path)
.await
.wrap_err_with(|| format!("failed to open session log {}", path.display()))?;
file.write_all(&buf).await?;
file.flush().await?;
Ok(())
}
}
pub fn now_unix_ms() -> u128 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_millis())
.unwrap_or(0)
}
pub fn sanitize_path_component(value: &str) -> String {
let sanitized: String = value
.chars()
.map(|ch| match ch {
'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' => ch,
_ => '-',
})
.collect();
let trimmed = sanitized.trim_matches('-');
if trimmed.is_empty() {
"agent".to_string()
} else {
trimmed.to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn appended_record_is_durable_and_parseable_on_return() {
let dir = tempfile::tempdir().unwrap();
let writer = SessionWriter {
root: Arc::new(dir.path().to_path_buf()),
relative_path: PathBuf::from("agent.jsonl"),
write_lock: Arc::new(Mutex::new(())),
};
let record = ToolCallRecord {
ts_unix_ms: 1,
agent: "reviewer-1-x".to_string(),
depth: 0,
turn: 1,
tool: "read_file".to_string(),
args: serde_json::json!({"path": "a.rs"}),
status: "ok".to_string(),
spawned_agent: None,
result: None,
model: Some("kimi-k2".to_string()),
};
writer.append_tool_call(&record).await.unwrap();
writer.append_tool_call(&record).await.unwrap();
let content = std::fs::read_to_string(dir.path().join("agent.jsonl")).unwrap();
let lines: Vec<ToolCallRecord> = content
.lines()
.map(|l| serde_json::from_str(l).unwrap())
.collect();
assert_eq!(lines.len(), 2);
assert_eq!(lines[0].agent, "reviewer-1-x");
}
#[test]
fn aggregation_records_require_and_round_trip_staged_verdicts() {
let current = AggregationRecord {
kind: "aggregation".to_string(),
model: "m".to_string(),
text: String::new(),
error: Some("provider 500".to_string()),
rounds: None,
converged: None,
presets: Some(vec!["security".to_string()]),
lanes: Some(vec![LaneRecord {
preset: "security".to_string(),
rounds: 1,
converged: true,
degraded: false,
}]),
verdicts: vec![VerdictRecord {
lens: Some("security".to_string()),
stage: "Reviewer · round 1".to_string(),
text: "Looks unsafe.".to_string(),
ok: true,
}],
jobs: Some(vec![JobRecord {
label: "security · r".to_string(),
preset: Some("security".to_string()),
ok: false,
}]),
};
let round_tripped: AggregationRecord =
serde_json::from_str(&serde_json::to_string(¤t).unwrap()).unwrap();
assert_eq!(round_tripped.error.as_deref(), Some("provider 500"));
assert_eq!(round_tripped.lanes.unwrap()[0].preset, "security");
assert_eq!(round_tripped.verdicts[0].stage, "Reviewer · round 1");
assert!(!round_tripped.jobs.unwrap()[0].ok);
let outdated = r#"{"kind":"aggregation","model":"m","text":"t"}"#;
assert!(serde_json::from_str::<AggregationRecord>(outdated).is_err());
}
#[tokio::test]
async fn session_attribution_round_trips_as_a_sidecar() {
let dir = tempfile::tempdir().unwrap();
let logger = SessionLogger {
root: Arc::new(dir.path().to_path_buf()),
id: Arc::from("session-test"),
write_lock: Arc::new(Mutex::new(())),
};
let attribution = SessionAttribution {
binary_version: "0.9.3".to_string(),
binary_revision: Some("abc123-dirty".to_string()),
protocol_prompt_sha256: "f".repeat(64),
};
logger.write_attribution(&attribution).await.unwrap();
let body = std::fs::read_to_string(dir.path().join("attribution.json")).unwrap();
let restored: SessionAttribution = serde_json::from_str(&body).unwrap();
assert_eq!(restored.binary_version, "0.9.3");
assert_eq!(restored.binary_revision.as_deref(), Some("abc123-dirty"));
assert_eq!(restored.protocol_prompt_sha256, "f".repeat(64));
}
}