use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum SessionEntry {
#[serde(rename = "user")]
User(UserEntry),
#[serde(rename = "assistant")]
Assistant(AssistantEntry),
#[serde(rename = "summary")]
Summary(SummaryEntry),
#[serde(rename = "file-history-snapshot")]
FileHistorySnapshot(serde_json::Value),
#[serde(rename = "progress")]
Progress(serde_json::Value),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserEntry {
pub uuid: String,
#[serde(default)]
pub parent_uuid: Option<String>,
#[serde(default)]
pub session_id: Option<String>,
#[serde(default)]
pub cwd: Option<String>,
#[serde(default)]
pub version: Option<String>,
#[serde(default)]
pub git_branch: Option<String>,
#[serde(default)]
pub timestamp: Option<String>,
pub message: UserMessage,
#[serde(default)]
pub is_sidechain: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserMessage {
pub role: String,
pub content: MessageContent,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MessageContent {
Text(String),
Blocks(Vec<ContentBlock>),
Other(serde_json::Value),
}
impl MessageContent {
pub fn as_text(&self) -> String {
match self {
MessageContent::Text(s) => s.clone(),
MessageContent::Blocks(blocks) => {
let mut parts = Vec::new();
for block in blocks {
match block {
ContentBlock::Text { text } => parts.push(text.clone()),
ContentBlock::ToolResult { content, .. } => {
if let Some(c) = content {
parts.push(c.as_text());
}
}
_ => {}
}
}
parts.join("\n")
}
MessageContent::Other(_) => String::new(),
}
}
pub fn is_tool_result(&self) -> bool {
matches!(self, MessageContent::Blocks(blocks) if blocks.iter().any(|b| matches!(b, ContentBlock::ToolResult { .. })))
}
pub fn is_unknown(&self) -> bool {
matches!(self, MessageContent::Other(_))
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum ContentBlock {
#[serde(rename = "text")]
Text { text: String },
#[serde(rename = "thinking")]
Thinking {
thinking: String,
#[serde(default)]
signature: Option<String>,
},
#[serde(rename = "tool_use")]
ToolUse {
id: String,
name: String,
#[serde(default)]
input: serde_json::Value,
},
#[serde(rename = "tool_result")]
ToolResult {
tool_use_id: String,
#[serde(default)]
content: Option<ToolResultContent>,
},
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ToolResultContent {
Text(String),
Blocks(Vec<serde_json::Value>),
}
impl ToolResultContent {
pub fn as_text(&self) -> String {
match self {
Self::Text(s) => s.clone(),
Self::Blocks(blocks) => {
blocks
.iter()
.filter_map(|b| b.get("text").and_then(|t| t.as_str()))
.collect::<Vec<_>>()
.join("\n")
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AssistantEntry {
pub uuid: String,
#[serde(default)]
pub parent_uuid: Option<String>,
#[serde(default)]
pub session_id: Option<String>,
#[serde(default)]
pub cwd: Option<String>,
#[serde(default)]
pub version: Option<String>,
#[serde(default)]
pub git_branch: Option<String>,
#[serde(default)]
pub timestamp: Option<String>,
pub message: AssistantMessage,
#[serde(default)]
pub is_sidechain: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AssistantMessage {
pub role: String,
#[serde(default)]
pub model: Option<String>,
#[serde(default)]
pub content: Vec<ContentBlock>,
#[serde(default)]
pub stop_reason: Option<String>,
#[serde(default)]
pub usage: Option<Usage>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Usage {
#[serde(default)]
pub input_tokens: u64,
#[serde(default)]
pub output_tokens: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SummaryEntry {
#[serde(default)]
pub uuid: String,
#[serde(default)]
pub parent_uuid: Option<String>,
#[serde(default)]
pub session_id: Option<String>,
#[serde(default)]
pub timestamp: Option<String>,
#[serde(default)]
pub summary: Option<String>,
#[serde(default)]
pub message: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Session {
pub session_id: String,
pub project: String,
pub session_path: String,
pub user_messages: Vec<ParsedUserMessage>,
pub assistant_messages: Vec<ParsedAssistantMessage>,
pub summaries: Vec<String>,
pub tools_used: Vec<String>,
pub errors: Vec<String>,
pub metadata: SessionMetadata,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParsedUserMessage {
pub text: String,
pub timestamp: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParsedAssistantMessage {
pub text: String,
pub thinking_summary: Option<String>,
pub tools: Vec<String>,
pub timestamp: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionMetadata {
pub cwd: Option<String>,
pub version: Option<String>,
pub git_branch: Option<String>,
pub model: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClaudeCliOutput {
#[serde(default)]
pub result: Option<String>,
#[serde(default)]
pub is_error: bool,
#[serde(default)]
pub duration_ms: u64,
#[serde(default)]
pub num_turns: u64,
#[serde(default)]
pub stop_reason: Option<String>,
#[serde(default)]
pub session_id: Option<String>,
#[serde(default)]
pub usage: Option<CliUsage>,
#[serde(default)]
pub structured_output: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CliUsage {
#[serde(default)]
pub input_tokens: u64,
#[serde(default)]
pub output_tokens: u64,
#[serde(default)]
pub cache_creation_input_tokens: u64,
#[serde(default)]
pub cache_read_input_tokens: u64,
}
impl ClaudeCliOutput {
pub fn total_input_tokens(&self) -> u64 {
self.usage.as_ref().map_or(0, |u| {
u.input_tokens + u.cache_creation_input_tokens + u.cache_read_input_tokens
})
}
pub fn total_output_tokens(&self) -> u64 {
self.usage.as_ref().map_or(0, |u| u.output_tokens)
}
}
#[derive(Debug, Clone, Serialize)]
pub struct CompactSession {
pub session_id: String,
pub project: String,
pub user_messages: Vec<CompactUserMessage>,
pub tools_used: Vec<String>,
pub errors: Vec<String>,
pub thinking_highlights: Vec<String>,
pub summaries: Vec<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct CompactUserMessage {
pub text: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub timestamp: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum NodeType {
Preference,
Pattern,
Rule,
Skill,
Memory,
Directive,
}
impl std::fmt::Display for NodeType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Preference => write!(f, "preference"),
Self::Pattern => write!(f, "pattern"),
Self::Rule => write!(f, "rule"),
Self::Skill => write!(f, "skill"),
Self::Memory => write!(f, "memory"),
Self::Directive => write!(f, "directive"),
}
}
}
impl NodeType {
pub fn from_str(s: &str) -> Self {
match s {
"preference" => Self::Preference,
"pattern" => Self::Pattern,
"rule" => Self::Rule,
"skill" => Self::Skill,
"memory" => Self::Memory,
"directive" => Self::Directive,
_ => Self::Pattern,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum NodeScope {
Global,
Project,
}
impl std::fmt::Display for NodeScope {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Global => write!(f, "global"),
Self::Project => write!(f, "project"),
}
}
}
impl NodeScope {
pub fn from_str(s: &str) -> Self {
match s {
"global" => Self::Global,
_ => Self::Project,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum EdgeType {
Supports,
Contradicts,
Supersedes,
DerivedFrom,
AppliesTo,
}
impl std::fmt::Display for EdgeType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Supports => write!(f, "supports"),
Self::Contradicts => write!(f, "contradicts"),
Self::Supersedes => write!(f, "supersedes"),
Self::DerivedFrom => write!(f, "derived_from"),
Self::AppliesTo => write!(f, "applies_to"),
}
}
}
impl EdgeType {
pub fn from_str(s: &str) -> Option<Self> {
match s {
"supports" => Some(Self::Supports),
"contradicts" => Some(Self::Contradicts),
"supersedes" => Some(Self::Supersedes),
"derived_from" => Some(Self::DerivedFrom),
"applies_to" => Some(Self::AppliesTo),
_ => None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KnowledgeNode {
pub id: String,
pub node_type: NodeType,
pub scope: NodeScope,
pub content: String,
pub confidence: f64,
}
#[derive(Debug, Clone)]
pub enum GraphOperation {
CreateNode {
node_type: NodeType,
scope: NodeScope,
project_id: Option<String>,
content: String,
confidence: f64,
},
CreateEdge {
source_id: String,
target_id: String,
edge_type: EdgeType,
},
UpdateNode {
id: String,
confidence: Option<f64>,
content: Option<String>,
},
MergeNodes {
keep_id: String,
remove_id: String,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GraphAnalysisResponse {
#[serde(default)]
pub reasoning: String,
pub operations: Vec<GraphOperationResponse>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GraphOperationResponse {
pub action: String,
#[serde(default)]
pub node_type: Option<String>,
#[serde(default)]
pub scope: Option<String>,
#[serde(default)]
pub project_id: Option<String>,
#[serde(default)]
pub content: Option<String>,
#[serde(default)]
pub confidence: Option<f64>,
#[serde(default)]
pub node_id: Option<String>,
#[serde(default)]
pub new_confidence: Option<f64>,
#[serde(default)]
pub new_content: Option<String>,
#[serde(default)]
pub source_id: Option<String>,
#[serde(default)]
pub target_id: Option<String>,
#[serde(default)]
pub edge_type: Option<String>,
#[serde(default)]
pub keep_id: Option<String>,
#[serde(default)]
pub remove_id: Option<String>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_node_type_display_and_from_str() {
assert_eq!(NodeType::Preference.to_string(), "preference");
assert_eq!(NodeType::Pattern.to_string(), "pattern");
assert_eq!(NodeType::Rule.to_string(), "rule");
assert_eq!(NodeType::Skill.to_string(), "skill");
assert_eq!(NodeType::Memory.to_string(), "memory");
assert_eq!(NodeType::Directive.to_string(), "directive");
assert_eq!(NodeType::from_str("rule"), NodeType::Rule);
assert_eq!(NodeType::from_str("unknown"), NodeType::Pattern); }
#[test]
fn test_node_scope_display_and_from_str() {
assert_eq!(NodeScope::Global.to_string(), "global");
assert_eq!(NodeScope::Project.to_string(), "project");
assert_eq!(NodeScope::from_str("global"), NodeScope::Global);
assert_eq!(NodeScope::from_str("unknown"), NodeScope::Project); }
#[test]
fn test_edge_type_display_and_from_str() {
assert_eq!(EdgeType::Supports.to_string(), "supports");
assert_eq!(EdgeType::Contradicts.to_string(), "contradicts");
assert_eq!(EdgeType::Supersedes.to_string(), "supersedes");
assert_eq!(EdgeType::DerivedFrom.to_string(), "derived_from");
assert_eq!(EdgeType::AppliesTo.to_string(), "applies_to");
assert_eq!(EdgeType::from_str("contradicts"), Some(EdgeType::Contradicts));
assert_eq!(EdgeType::from_str("unknown"), None);
}
#[test]
fn test_knowledge_node_struct() {
let node = KnowledgeNode {
id: "test-id".to_string(),
node_type: NodeType::Rule,
scope: NodeScope::Project,
content: "Always run tests".to_string(),
confidence: 0.85,
};
assert_eq!(node.node_type, NodeType::Rule);
assert_eq!(node.scope, NodeScope::Project);
assert_eq!(node.content, "Always run tests");
}
#[test]
fn test_graph_analysis_response_deserialize() {
let json = r#"{
"reasoning": "Found a recurring pattern",
"operations": [
{
"action": "create_node",
"node_type": "rule",
"scope": "project",
"content": "Always run tests",
"confidence": 0.85
},
{
"action": "update_node",
"node_id": "existing-1",
"new_confidence": 0.9
}
]
}"#;
let resp: GraphAnalysisResponse = serde_json::from_str(json).unwrap();
assert_eq!(resp.operations.len(), 2);
assert_eq!(resp.reasoning, "Found a recurring pattern");
}
}