use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TokenUsage {
pub prompt_tokens: u32,
pub completion_tokens: u32,
pub cache_read_tokens: u32,
pub cache_creation_tokens: u32,
}
impl TokenUsage {
pub fn new(prompt: u32, completion: u32, cache_read: u32, cache_creation: u32) -> Self {
Self {
prompt_tokens: prompt,
completion_tokens: completion,
cache_read_tokens: cache_read,
cache_creation_tokens: cache_creation,
}
}
pub fn add(&mut self, other: &TokenUsage) {
self.prompt_tokens = self.prompt_tokens.saturating_add(other.prompt_tokens);
self.completion_tokens = self
.completion_tokens
.saturating_add(other.completion_tokens);
self.cache_read_tokens = self
.cache_read_tokens
.saturating_add(other.cache_read_tokens);
self.cache_creation_tokens = self
.cache_creation_tokens
.saturating_add(other.cache_creation_tokens);
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PhaseRecord {
pub name: String,
pub duration_ms: u64,
pub prompt_tokens: u32,
pub completion_tokens: u32,
pub cache_read_tokens: u32,
pub cache_creation_tokens: u32,
pub cost_usd: f64,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PerfTotals {
pub prompt_tokens: u32,
pub completion_tokens: u32,
pub cache_read_tokens: u32,
pub cache_creation_tokens: u32,
pub cost_usd: f64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerfRecord {
pub build: u64,
pub version: String,
pub workflow: String,
pub task_preview: String,
pub started_at: String,
pub total_duration_ms: u64,
pub phases: Vec<PhaseRecord>,
pub totals: PerfTotals,
#[serde(default = "default_status")]
pub status: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub failed_phase: Option<String>,
#[serde(default)]
pub skills_used: Vec<String>,
#[serde(default)]
pub skills_considered: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tests_passed: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tests_failed: Option<u64>,
}
fn default_status() -> String {
"success".to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn token_usage_accumulates() {
let mut a = TokenUsage::new(10, 5, 2, 1);
a.add(&TokenUsage::new(3, 7, 0, 4));
assert_eq!(a, TokenUsage::new(13, 12, 2, 5));
}
#[test]
fn perf_record_status_defaults_to_success() {
let rec = PerfRecord {
build: 1,
version: "0.1.0".to_string(),
workflow: "test".to_string(),
task_preview: "task".to_string(),
started_at: "2026-01-01T00:00:00Z".to_string(),
total_duration_ms: 100,
phases: vec![],
totals: PerfTotals::default(),
status: default_status(),
failed_phase: None,
skills_used: vec![],
skills_considered: vec![],
tests_passed: None,
tests_failed: None,
};
assert_eq!(rec.status, "success");
assert!(rec.failed_phase.is_none());
}
}