Skip to main content

qualia_client_core/
agent_characteristics.rs

1//! Agent characteristics KB — behaviour-based profiling (T59).
2//!
3//! Logs characteristics of agents (including AI agents) from behaviour.
4//! Local inference first, then packs for jurisdictions. The profile is
5//! built from observed turns, not from self-report.
6
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use std::path::Path;
10
11/// Observed characteristics of an agent (T59). Built from behaviour,
12/// not from self-report. Used for jurisdictional compliance and audit.
13#[derive(Debug, Clone, Default, Serialize, Deserialize)]
14pub struct AgentCharacteristics {
15    /// Agent slug this profile describes.
16    pub agent_slug: String,
17    /// Number of inference turns observed.
18    pub turns_observed: u64,
19    /// Average response length in characters.
20    pub avg_response_chars: f64,
21    /// Total characters across all responses (for running average).
22    pub total_response_chars: u64,
23    /// Capabilities most frequently invoked (top 5).
24    pub frequent_capabilities: Vec<String>,
25    /// Capability invocation counts (for computing top 5).
26    #[serde(default)]
27    pub capability_counts: HashMap<String, u64>,
28    /// Whether this agent has ever produced a disclosure denial.
29    pub has_denied_disclosure: bool,
30    /// Whether this agent has ever triggered a deontic interrupt.
31    pub has_triggered_interrupt: bool,
32    /// Unix timestamp of last observation.
33    pub last_observed_unix: u64,
34}
35
36impl AgentCharacteristics {
37    /// Create a fresh profile for the given agent slug.
38    pub fn new(slug: &str) -> Self {
39        Self {
40            agent_slug: slug.to_string(),
41            ..Self::default()
42        }
43    }
44
45    /// Record an inference turn: updates turn count, response length
46    /// average, and capability frequency.
47    pub fn record_turn(&mut self, capability: &str, response_len: usize) {
48        self.turns_observed += 1;
49        self.total_response_chars += response_len as u64;
50        self.avg_response_chars = self.total_response_chars as f64 / self.turns_observed as f64;
51        *self
52            .capability_counts
53            .entry(capability.to_string())
54            .or_insert(0) += 1;
55        self.recompute_frequent_capabilities();
56        self.last_observed_unix = std::time::SystemTime::now()
57            .duration_since(std::time::UNIX_EPOCH)
58            .map(|d| d.as_secs())
59            .unwrap_or(0);
60    }
61
62    /// Record that this agent produced a disclosure denial.
63    pub fn record_denial(&mut self) {
64        self.has_denied_disclosure = true;
65    }
66
67    /// Record that this agent triggered a deontic interrupt.
68    pub fn record_interrupt(&mut self) {
69        self.has_triggered_interrupt = true;
70    }
71
72    /// Recompute the top-5 frequent capabilities from the counts map.
73    fn recompute_frequent_capabilities(&mut self) {
74        let mut entries: Vec<(String, u64)> = self
75            .capability_counts
76            .iter()
77            .map(|(k, v)| (k.clone(), *v))
78            .collect();
79        entries.sort_by(|a, b| b.1.cmp(&a.1));
80        self.frequent_capabilities = entries.into_iter().take(5).map(|(k, _)| k).collect();
81    }
82
83    /// Serialize to JSON.
84    pub fn to_json(&self) -> Result<String, serde_json::Error> {
85        serde_json::to_string_pretty(self)
86    }
87
88    /// Deserialize from JSON.
89    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
90        serde_json::from_str(json)
91    }
92}
93
94/// A store that persists agent characteristics to a JSON file.
95pub struct CharacteristicsStore {
96    dir: std::path::PathBuf,
97}
98
99impl CharacteristicsStore {
100    /// Create a store rooted at the given directory.
101    pub fn new(dir: impl AsRef<Path>) -> Self {
102        Self {
103            dir: dir.as_ref().to_path_buf(),
104        }
105    }
106
107    /// Path for a given agent slug's profile.
108    fn path_for(&self, slug: &str) -> std::path::PathBuf {
109        self.dir.join(format!("{slug}.json"))
110    }
111
112    /// Save a profile to disk.
113    pub fn save(&self, profile: &AgentCharacteristics) -> std::io::Result<()> {
114        let path = self.path_for(&profile.agent_slug);
115        if let Some(parent) = path.parent() {
116            std::fs::create_dir_all(parent)?;
117        }
118        let json = profile
119            .to_json()
120            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
121        std::fs::write(path, json)
122    }
123
124    /// Load a profile from disk. Returns None if no profile exists.
125    pub fn load(&self, slug: &str) -> std::io::Result<Option<AgentCharacteristics>> {
126        let path = self.path_for(slug);
127        if !path.exists() {
128            return Ok(None);
129        }
130        let json = std::fs::read_to_string(path)?;
131        let profile = AgentCharacteristics::from_json(&json)
132            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
133        Ok(Some(profile))
134    }
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140
141    #[test]
142    fn new_characteristics_empty() {
143        let c = AgentCharacteristics::new("test-agent");
144        assert_eq!(c.agent_slug, "test-agent");
145        assert_eq!(c.turns_observed, 0);
146        assert_eq!(c.avg_response_chars, 0.0);
147        assert!(c.frequent_capabilities.is_empty());
148        assert!(!c.has_denied_disclosure);
149        assert!(!c.has_triggered_interrupt);
150    }
151
152    #[test]
153    fn record_turn_updates_stats() {
154        let mut c = AgentCharacteristics::new("agent-a");
155        c.record_turn("graph.query", 100);
156        c.record_turn("graph.query", 200);
157        c.record_turn("pulse.publish", 50);
158        assert_eq!(c.turns_observed, 3);
159        assert!((c.avg_response_chars - 116.666).abs() < 0.01);
160        assert_eq!(c.frequent_capabilities[0], "graph.query");
161        assert!(c
162            .frequent_capabilities
163            .contains(&"pulse.publish".to_string()));
164    }
165
166    #[test]
167    fn record_denial_sets_flag() {
168        let mut c = AgentCharacteristics::new("agent-b");
169        assert!(!c.has_denied_disclosure);
170        c.record_denial();
171        assert!(c.has_denied_disclosure);
172    }
173
174    #[test]
175    fn record_interrupt_sets_flag() {
176        let mut c = AgentCharacteristics::new("agent-c");
177        assert!(!c.has_triggered_interrupt);
178        c.record_interrupt();
179        assert!(c.has_triggered_interrupt);
180    }
181
182    #[test]
183    fn json_roundtrip() {
184        let mut c = AgentCharacteristics::new("agent-d");
185        c.record_turn("math.abs", 42);
186        c.record_denial();
187        let json = c.to_json().unwrap();
188        let restored = AgentCharacteristics::from_json(&json).unwrap();
189        assert_eq!(restored.agent_slug, "agent-d");
190        assert_eq!(restored.turns_observed, 1);
191        assert!(restored.has_denied_disclosure);
192        assert_eq!(restored.frequent_capabilities, vec!["math.abs"]);
193    }
194
195    #[test]
196    fn store_persists_and_loads() {
197        let tmp =
198            std::env::temp_dir().join(format!("qualia_agent_char_test_{}", std::process::id()));
199        let store = CharacteristicsStore::new(&tmp);
200        let mut c = AgentCharacteristics::new("agent-e");
201        c.record_turn("graph.query", 100);
202        c.record_interrupt();
203        store.save(&c).unwrap();
204        let loaded = store.load("agent-e").unwrap().unwrap();
205        assert_eq!(loaded.agent_slug, "agent-e");
206        assert_eq!(loaded.turns_observed, 1);
207        assert!(loaded.has_triggered_interrupt);
208        // Cleanup
209        let _ = std::fs::remove_dir_all(&tmp);
210    }
211
212    #[test]
213    fn store_load_nonexistent_returns_none() {
214        let tmp =
215            std::env::temp_dir().join(format!("qualia_agent_char_none_{}", std::process::id()));
216        let store = CharacteristicsStore::new(&tmp);
217        let result = store.load("nonexistent").unwrap();
218        assert!(result.is_none());
219        let _ = std::fs::remove_dir_all(&tmp);
220    }
221
222    #[test]
223    fn frequent_capabilities_top_5() {
224        let mut c = AgentCharacteristics::new("agent-f");
225        // Add 7 distinct capabilities with different frequencies.
226        for (cap, count) in [
227            ("a", 10),
228            ("b", 8),
229            ("c", 6),
230            ("d", 4),
231            ("e", 2),
232            ("f", 1),
233            ("g", 1),
234        ] {
235            for _ in 0..count {
236                c.record_turn(cap, 10);
237            }
238        }
239        // Only top 5 should be in frequent_capabilities.
240        assert_eq!(c.frequent_capabilities.len(), 5);
241        assert_eq!(c.frequent_capabilities[0], "a");
242        assert_eq!(c.frequent_capabilities[1], "b");
243        assert_eq!(c.frequent_capabilities[4], "e");
244        assert!(!c.frequent_capabilities.contains(&"f".to_string()));
245    }
246}