1use std::collections::VecDeque;
5
6use tokio::sync::watch;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum SecurityEventCategory {
11 InjectionFlag,
12 ExfiltrationBlock,
13 Quarantine,
14 Truncation,
15}
16
17impl SecurityEventCategory {
18 #[must_use]
19 pub fn as_str(self) -> &'static str {
20 match self {
21 Self::InjectionFlag => "injection",
22 Self::ExfiltrationBlock => "exfil",
23 Self::Quarantine => "quarantine",
24 Self::Truncation => "truncation",
25 }
26 }
27}
28
29#[derive(Debug, Clone)]
31pub struct SecurityEvent {
32 pub timestamp: u64,
34 pub category: SecurityEventCategory,
35 pub source: String,
37 pub detail: String,
39}
40
41impl SecurityEvent {
42 #[must_use]
43 pub fn new(
44 category: SecurityEventCategory,
45 source: impl Into<String>,
46 detail: impl Into<String>,
47 ) -> Self {
48 let source: String = source
50 .into()
51 .chars()
52 .filter(|c| !c.is_ascii_control())
53 .take(64)
54 .collect();
55 let detail = detail.into();
57 let detail = if detail.len() > 128 {
58 let end = detail.floor_char_boundary(127);
59 format!("{}…", &detail[..end])
60 } else {
61 detail
62 };
63 Self {
64 timestamp: std::time::SystemTime::now()
65 .duration_since(std::time::UNIX_EPOCH)
66 .unwrap_or_default()
67 .as_secs(),
68 category,
69 source,
70 detail,
71 }
72 }
73}
74
75pub const SECURITY_EVENT_CAP: usize = 100;
77
78#[derive(Debug, Clone)]
82pub struct TaskSnapshotRow {
83 pub id: u32,
84 pub title: String,
85 pub status: String,
87 pub agent: Option<String>,
88 pub duration_ms: u64,
89 pub error: Option<String>,
91}
92
93#[derive(Debug, Clone, Default)]
95pub struct TaskGraphSnapshot {
96 pub graph_id: String,
97 pub goal: String,
98 pub status: String,
100 pub tasks: Vec<TaskSnapshotRow>,
101 pub completed_at: Option<std::time::Instant>,
102}
103
104impl TaskGraphSnapshot {
105 #[must_use]
108 pub fn is_stale(&self) -> bool {
109 self.completed_at
110 .is_some_and(|t| t.elapsed().as_secs() > 30)
111 }
112}
113
114#[derive(Debug, Clone, Default)]
118pub struct OrchestrationMetrics {
119 pub plans_total: u64,
120 pub tasks_total: u64,
121 pub tasks_completed: u64,
122 pub tasks_failed: u64,
123 pub tasks_skipped: u64,
124}
125
126#[derive(Debug, Clone, Default)]
128pub struct SkillConfidence {
129 pub name: String,
130 pub posterior: f64,
131 pub total_uses: u32,
132}
133
134#[derive(Debug, Clone, Default)]
136pub struct SubAgentMetrics {
137 pub id: String,
138 pub name: String,
139 pub state: String,
141 pub turns_used: u32,
142 pub max_turns: u32,
143 pub background: bool,
144 pub elapsed_secs: u64,
145 pub permission_mode: String,
148}
149
150#[derive(Debug, Clone, Default)]
151pub struct MetricsSnapshot {
152 pub prompt_tokens: u64,
153 pub completion_tokens: u64,
154 pub total_tokens: u64,
155 pub context_tokens: u64,
156 pub api_calls: u64,
157 pub active_skills: Vec<String>,
158 pub total_skills: usize,
159 pub mcp_server_count: usize,
160 pub mcp_tool_count: usize,
161 pub active_mcp_tools: Vec<String>,
162 pub sqlite_message_count: u64,
163 pub sqlite_conversation_id: Option<zeph_memory::ConversationId>,
164 pub qdrant_available: bool,
165 pub vector_backend: String,
166 pub embeddings_generated: u64,
167 pub last_llm_latency_ms: u64,
168 pub uptime_seconds: u64,
169 pub provider_name: String,
170 pub model_name: String,
171 pub summaries_count: u64,
172 pub context_compactions: u64,
173 pub compression_events: u64,
174 pub compression_tokens_saved: u64,
175 pub tool_output_prunes: u64,
176 pub cache_read_tokens: u64,
177 pub cache_creation_tokens: u64,
178 pub cost_spent_cents: f64,
179 pub filter_raw_tokens: u64,
180 pub filter_saved_tokens: u64,
181 pub filter_applications: u64,
182 pub filter_total_commands: u64,
183 pub filter_filtered_commands: u64,
184 pub filter_confidence_full: u64,
185 pub filter_confidence_partial: u64,
186 pub filter_confidence_fallback: u64,
187 pub cancellations: u64,
188 pub sanitizer_runs: u64,
189 pub sanitizer_injection_flags: u64,
190 pub sanitizer_truncations: u64,
191 pub quarantine_invocations: u64,
192 pub quarantine_failures: u64,
193 pub exfiltration_images_blocked: u64,
194 pub exfiltration_tool_urls_flagged: u64,
195 pub exfiltration_memory_guards: u64,
196 pub sub_agents: Vec<SubAgentMetrics>,
197 pub skill_confidence: Vec<SkillConfidence>,
198 pub scheduled_tasks: Vec<[String; 4]>,
200 pub router_thompson_stats: Vec<(String, f64, f64)>,
202 pub security_events: VecDeque<SecurityEvent>,
204 pub orchestration: OrchestrationMetrics,
205 pub orchestration_graph: Option<TaskGraphSnapshot>,
207 pub graph_community_detection_failures: u64,
208 pub graph_entities_total: u64,
209 pub graph_edges_total: u64,
210 pub graph_communities_total: u64,
211 pub graph_extraction_count: u64,
212 pub graph_extraction_failures: u64,
213}
214
215fn strip_ctrl(s: &str) -> String {
221 let mut out = String::with_capacity(s.len());
222 let mut chars = s.chars().peekable();
223 while let Some(c) = chars.next() {
224 if c == '\x1b' {
225 if chars.peek() == Some(&'[') {
227 chars.next(); for inner in chars.by_ref() {
229 if ('\x40'..='\x7e').contains(&inner) {
230 break;
231 }
232 }
233 }
234 } else if c.is_control() && c != '\t' && c != '\n' && c != '\r' {
236 } else {
238 out.push(c);
239 }
240 }
241 out
242}
243
244impl From<&crate::orchestration::TaskGraph> for TaskGraphSnapshot {
246 fn from(graph: &crate::orchestration::TaskGraph) -> Self {
247 let tasks = graph
248 .tasks
249 .iter()
250 .map(|t| {
251 let error = t
252 .result
253 .as_ref()
254 .filter(|_| t.status == crate::orchestration::TaskStatus::Failed)
255 .and_then(|r| {
256 if r.output.is_empty() {
257 None
258 } else {
259 let s = strip_ctrl(&r.output);
261 if s.len() > 80 {
262 let end = s.floor_char_boundary(79);
263 Some(format!("{}…", &s[..end]))
264 } else {
265 Some(s)
266 }
267 }
268 });
269 let duration_ms = t.result.as_ref().map_or(0, |r| r.duration_ms);
270 TaskSnapshotRow {
271 id: t.id.0,
272 title: strip_ctrl(&t.title),
273 status: t.status.to_string(),
274 agent: t.assigned_agent.as_deref().map(strip_ctrl),
275 duration_ms,
276 error,
277 }
278 })
279 .collect();
280 Self {
281 graph_id: graph.id.to_string(),
282 goal: strip_ctrl(&graph.goal),
283 status: graph.status.to_string(),
284 tasks,
285 completed_at: None,
286 }
287 }
288}
289
290pub struct MetricsCollector {
291 tx: watch::Sender<MetricsSnapshot>,
292}
293
294impl MetricsCollector {
295 #[must_use]
296 pub fn new() -> (Self, watch::Receiver<MetricsSnapshot>) {
297 let (tx, rx) = watch::channel(MetricsSnapshot::default());
298 (Self { tx }, rx)
299 }
300
301 pub fn update(&self, f: impl FnOnce(&mut MetricsSnapshot)) {
302 self.tx.send_modify(f);
303 }
304}
305
306#[cfg(test)]
307mod tests {
308 use super::*;
309
310 #[test]
311 fn default_metrics_snapshot() {
312 let m = MetricsSnapshot::default();
313 assert_eq!(m.total_tokens, 0);
314 assert_eq!(m.api_calls, 0);
315 assert!(m.active_skills.is_empty());
316 assert!(m.active_mcp_tools.is_empty());
317 assert_eq!(m.mcp_tool_count, 0);
318 assert_eq!(m.mcp_server_count, 0);
319 assert!(m.provider_name.is_empty());
320 assert_eq!(m.summaries_count, 0);
321 }
322
323 #[test]
324 fn metrics_collector_update() {
325 let (collector, rx) = MetricsCollector::new();
326 collector.update(|m| {
327 m.api_calls = 5;
328 m.total_tokens = 1000;
329 });
330 let snapshot = rx.borrow().clone();
331 assert_eq!(snapshot.api_calls, 5);
332 assert_eq!(snapshot.total_tokens, 1000);
333 }
334
335 #[test]
336 fn metrics_collector_multiple_updates() {
337 let (collector, rx) = MetricsCollector::new();
338 collector.update(|m| m.api_calls = 1);
339 collector.update(|m| m.api_calls += 1);
340 assert_eq!(rx.borrow().api_calls, 2);
341 }
342
343 #[test]
344 fn metrics_snapshot_clone() {
345 let mut m = MetricsSnapshot::default();
346 m.provider_name = "ollama".into();
347 let cloned = m.clone();
348 assert_eq!(cloned.provider_name, "ollama");
349 }
350
351 #[test]
352 fn filter_metrics_tracking() {
353 let (collector, rx) = MetricsCollector::new();
354 collector.update(|m| {
355 m.filter_raw_tokens += 250;
356 m.filter_saved_tokens += 200;
357 m.filter_applications += 1;
358 });
359 collector.update(|m| {
360 m.filter_raw_tokens += 100;
361 m.filter_saved_tokens += 80;
362 m.filter_applications += 1;
363 });
364 let s = rx.borrow();
365 assert_eq!(s.filter_raw_tokens, 350);
366 assert_eq!(s.filter_saved_tokens, 280);
367 assert_eq!(s.filter_applications, 2);
368 }
369
370 #[test]
371 fn filter_confidence_and_command_metrics() {
372 let (collector, rx) = MetricsCollector::new();
373 collector.update(|m| {
374 m.filter_total_commands += 1;
375 m.filter_filtered_commands += 1;
376 m.filter_confidence_full += 1;
377 });
378 collector.update(|m| {
379 m.filter_total_commands += 1;
380 m.filter_confidence_partial += 1;
381 });
382 let s = rx.borrow();
383 assert_eq!(s.filter_total_commands, 2);
384 assert_eq!(s.filter_filtered_commands, 1);
385 assert_eq!(s.filter_confidence_full, 1);
386 assert_eq!(s.filter_confidence_partial, 1);
387 assert_eq!(s.filter_confidence_fallback, 0);
388 }
389
390 #[test]
391 fn summaries_count_tracks_summarizations() {
392 let (collector, rx) = MetricsCollector::new();
393 collector.update(|m| m.summaries_count += 1);
394 collector.update(|m| m.summaries_count += 1);
395 assert_eq!(rx.borrow().summaries_count, 2);
396 }
397
398 #[test]
399 fn cancellations_counter_increments() {
400 let (collector, rx) = MetricsCollector::new();
401 assert_eq!(rx.borrow().cancellations, 0);
402 collector.update(|m| m.cancellations += 1);
403 collector.update(|m| m.cancellations += 1);
404 assert_eq!(rx.borrow().cancellations, 2);
405 }
406
407 #[test]
408 fn security_event_detail_exact_128_not_truncated() {
409 let s = "a".repeat(128);
410 let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, "src", s.clone());
411 assert_eq!(ev.detail, s, "128-char string must not be truncated");
412 }
413
414 #[test]
415 fn security_event_detail_129_is_truncated() {
416 let s = "a".repeat(129);
417 let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, "src", s);
418 assert!(
419 ev.detail.ends_with('…'),
420 "129-char string must end with ellipsis"
421 );
422 assert!(
423 ev.detail.len() <= 130,
424 "truncated detail must be at most 130 bytes"
425 );
426 }
427
428 #[test]
429 fn security_event_detail_multibyte_utf8_no_panic() {
430 let s = "中".repeat(43);
432 let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, "src", s);
433 assert!(ev.detail.ends_with('…'));
434 }
435
436 #[test]
437 fn security_event_source_capped_at_64_chars() {
438 let long_source = "x".repeat(200);
439 let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, long_source, "detail");
440 assert_eq!(ev.source.len(), 64);
441 }
442
443 #[test]
444 fn security_event_source_strips_control_chars() {
445 let source = "tool\x00name\x1b[31m";
446 let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, source, "detail");
447 assert!(!ev.source.contains('\x00'));
448 assert!(!ev.source.contains('\x1b'));
449 }
450
451 #[test]
452 fn security_event_category_as_str() {
453 assert_eq!(SecurityEventCategory::InjectionFlag.as_str(), "injection");
454 assert_eq!(SecurityEventCategory::ExfiltrationBlock.as_str(), "exfil");
455 assert_eq!(SecurityEventCategory::Quarantine.as_str(), "quarantine");
456 assert_eq!(SecurityEventCategory::Truncation.as_str(), "truncation");
457 }
458
459 #[test]
460 fn ring_buffer_respects_cap_via_update() {
461 let (collector, rx) = MetricsCollector::new();
462 for i in 0..110u64 {
463 let event = SecurityEvent::new(
464 SecurityEventCategory::InjectionFlag,
465 "src",
466 format!("event {i}"),
467 );
468 collector.update(|m| {
469 if m.security_events.len() >= SECURITY_EVENT_CAP {
470 m.security_events.pop_front();
471 }
472 m.security_events.push_back(event);
473 });
474 }
475 let snap = rx.borrow();
476 assert_eq!(snap.security_events.len(), SECURITY_EVENT_CAP);
477 assert!(snap.security_events.back().unwrap().detail.contains("109"));
479 }
480
481 #[test]
482 fn security_events_empty_by_default() {
483 let m = MetricsSnapshot::default();
484 assert!(m.security_events.is_empty());
485 }
486
487 #[test]
488 fn orchestration_metrics_default_zero() {
489 let m = OrchestrationMetrics::default();
490 assert_eq!(m.plans_total, 0);
491 assert_eq!(m.tasks_total, 0);
492 assert_eq!(m.tasks_completed, 0);
493 assert_eq!(m.tasks_failed, 0);
494 assert_eq!(m.tasks_skipped, 0);
495 }
496
497 #[test]
498 fn metrics_snapshot_includes_orchestration_default_zero() {
499 let m = MetricsSnapshot::default();
500 assert_eq!(m.orchestration.plans_total, 0);
501 assert_eq!(m.orchestration.tasks_total, 0);
502 assert_eq!(m.orchestration.tasks_completed, 0);
503 }
504
505 #[test]
506 fn orchestration_metrics_update_via_collector() {
507 let (collector, rx) = MetricsCollector::new();
508 collector.update(|m| {
509 m.orchestration.plans_total += 1;
510 m.orchestration.tasks_total += 5;
511 m.orchestration.tasks_completed += 3;
512 m.orchestration.tasks_failed += 1;
513 m.orchestration.tasks_skipped += 1;
514 });
515 let s = rx.borrow();
516 assert_eq!(s.orchestration.plans_total, 1);
517 assert_eq!(s.orchestration.tasks_total, 5);
518 assert_eq!(s.orchestration.tasks_completed, 3);
519 assert_eq!(s.orchestration.tasks_failed, 1);
520 assert_eq!(s.orchestration.tasks_skipped, 1);
521 }
522
523 #[test]
524 fn strip_ctrl_removes_escape_sequences() {
525 let input = "hello\x1b[31mworld\x00end";
526 let result = strip_ctrl(input);
527 assert_eq!(result, "helloworldend");
528 }
529
530 #[test]
531 fn strip_ctrl_allows_tab_lf_cr() {
532 let input = "a\tb\nc\rd";
533 let result = strip_ctrl(input);
534 assert_eq!(result, "a\tb\nc\rd");
535 }
536
537 #[test]
538 fn task_graph_snapshot_is_stale_after_30s() {
539 let mut snap = TaskGraphSnapshot::default();
540 assert!(!snap.is_stale());
542 snap.completed_at = Some(std::time::Instant::now());
544 assert!(!snap.is_stale());
545 snap.completed_at = Some(
547 std::time::Instant::now()
548 .checked_sub(std::time::Duration::from_secs(31))
549 .unwrap(),
550 );
551 assert!(snap.is_stale());
552 }
553
554 #[test]
556 fn task_graph_snapshot_from_task_graph_maps_fields() {
557 use crate::orchestration::{GraphStatus, TaskGraph, TaskNode, TaskResult, TaskStatus};
558
559 let mut graph = TaskGraph::new("My goal");
560 let mut task = TaskNode::new(0, "Do work", "description");
561 task.status = TaskStatus::Failed;
562 task.assigned_agent = Some("agent-1".into());
563 task.result = Some(TaskResult {
564 output: "error occurred here".into(),
565 artifacts: vec![],
566 duration_ms: 1234,
567 agent_id: None,
568 agent_def: None,
569 });
570 graph.tasks.push(task);
571 graph.status = GraphStatus::Failed;
572
573 let snap = TaskGraphSnapshot::from(&graph);
574 assert_eq!(snap.goal, "My goal");
575 assert_eq!(snap.status, "failed");
576 assert_eq!(snap.tasks.len(), 1);
577 let row = &snap.tasks[0];
578 assert_eq!(row.title, "Do work");
579 assert_eq!(row.status, "failed");
580 assert_eq!(row.agent.as_deref(), Some("agent-1"));
581 assert_eq!(row.duration_ms, 1234);
582 assert!(row.error.as_deref().unwrap().contains("error occurred"));
583 }
584
585 #[test]
587 fn task_graph_snapshot_from_compiles_with_feature() {
588 use crate::orchestration::TaskGraph;
589 let graph = TaskGraph::new("feature flag test");
590 let snap = TaskGraphSnapshot::from(&graph);
591 assert_eq!(snap.goal, "feature flag test");
592 assert!(snap.tasks.is_empty());
593 assert!(!snap.is_stale());
594 }
595
596 #[test]
598 fn task_graph_snapshot_error_truncated_at_80_chars() {
599 use crate::orchestration::{TaskGraph, TaskNode, TaskResult, TaskStatus};
600
601 let mut graph = TaskGraph::new("goal");
602 let mut task = TaskNode::new(0, "t", "d");
603 task.status = TaskStatus::Failed;
604 task.result = Some(TaskResult {
605 output: "e".repeat(100),
606 artifacts: vec![],
607 duration_ms: 0,
608 agent_id: None,
609 agent_def: None,
610 });
611 graph.tasks.push(task);
612
613 let snap = TaskGraphSnapshot::from(&graph);
614 let err = snap.tasks[0].error.as_ref().unwrap();
615 assert!(err.ends_with('…'), "truncated error must end with ellipsis");
616 assert!(
617 err.len() <= 83,
618 "truncated error must not exceed 80 chars + ellipsis"
619 );
620 }
621
622 #[test]
624 fn task_graph_snapshot_strips_control_chars_from_title() {
625 use crate::orchestration::{TaskGraph, TaskNode};
626
627 let mut graph = TaskGraph::new("goal\x1b[31m");
628 let task = TaskNode::new(0, "title\x00injected", "d");
629 graph.tasks.push(task);
630
631 let snap = TaskGraphSnapshot::from(&graph);
632 assert!(!snap.goal.contains('\x1b'), "goal must not contain escape");
633 assert!(
634 !snap.tasks[0].title.contains('\x00'),
635 "title must not contain null byte"
636 );
637 }
638
639 #[test]
640 fn graph_metrics_default_zero() {
641 let m = MetricsSnapshot::default();
642 assert_eq!(m.graph_entities_total, 0);
643 assert_eq!(m.graph_edges_total, 0);
644 assert_eq!(m.graph_communities_total, 0);
645 assert_eq!(m.graph_extraction_count, 0);
646 assert_eq!(m.graph_extraction_failures, 0);
647 }
648
649 #[test]
650 fn graph_metrics_update_via_collector() {
651 let (collector, rx) = MetricsCollector::new();
652 collector.update(|m| {
653 m.graph_entities_total = 5;
654 m.graph_edges_total = 10;
655 m.graph_communities_total = 2;
656 m.graph_extraction_count = 7;
657 m.graph_extraction_failures = 1;
658 });
659 let snapshot = rx.borrow().clone();
660 assert_eq!(snapshot.graph_entities_total, 5);
661 assert_eq!(snapshot.graph_edges_total, 10);
662 assert_eq!(snapshot.graph_communities_total, 2);
663 assert_eq!(snapshot.graph_extraction_count, 7);
664 assert_eq!(snapshot.graph_extraction_failures, 1);
665 }
666}