1use std::collections::VecDeque;
5
6use tokio::sync::watch;
7use zeph_common::SecurityEventCategory;
8
9pub use zeph_llm::{ClassifierMetricsSnapshot, TaskMetricsSnapshot};
10pub use zeph_memory::{CategoryScore, ProbeCategory, ProbeVerdict};
11
12#[derive(Debug, Clone)]
14pub struct SecurityEvent {
15 pub timestamp: u64,
17 pub category: SecurityEventCategory,
18 pub source: String,
20 pub detail: String,
22}
23
24impl SecurityEvent {
25 #[must_use]
26 pub fn new(
27 category: SecurityEventCategory,
28 source: impl Into<String>,
29 detail: impl Into<String>,
30 ) -> Self {
31 let source: String = source
33 .into()
34 .chars()
35 .filter(|c| !c.is_ascii_control())
36 .take(64)
37 .collect();
38 let detail = detail.into();
40 let detail = if detail.len() > 128 {
41 let end = detail.floor_char_boundary(127);
42 format!("{}…", &detail[..end])
43 } else {
44 detail
45 };
46 Self {
47 timestamp: std::time::SystemTime::now()
48 .duration_since(std::time::UNIX_EPOCH)
49 .unwrap_or_default()
50 .as_secs(),
51 category,
52 source,
53 detail,
54 }
55 }
56}
57
58pub const SECURITY_EVENT_CAP: usize = 100;
60
61#[derive(Debug, Clone)]
65pub struct TaskSnapshotRow {
66 pub id: u32,
67 pub title: String,
68 pub status: String,
70 pub agent: Option<String>,
71 pub duration_ms: u64,
72 pub error: Option<String>,
74}
75
76#[derive(Debug, Clone, Default)]
78pub struct TaskGraphSnapshot {
79 pub graph_id: String,
80 pub goal: String,
81 pub status: String,
83 pub tasks: Vec<TaskSnapshotRow>,
84 pub completed_at: Option<std::time::Instant>,
85}
86
87impl TaskGraphSnapshot {
88 #[must_use]
91 pub fn is_stale(&self) -> bool {
92 self.completed_at
93 .is_some_and(|t| t.elapsed().as_secs() > 30)
94 }
95}
96
97#[derive(Debug, Clone, Default)]
101pub struct OrchestrationMetrics {
102 pub plans_total: u64,
103 pub tasks_total: u64,
104 pub tasks_completed: u64,
105 pub tasks_failed: u64,
106 pub tasks_skipped: u64,
107}
108
109#[derive(Debug, Clone, PartialEq, Eq)]
111pub enum McpServerConnectionStatus {
112 Connected,
113 Failed,
114}
115
116#[derive(Debug, Clone)]
118pub struct McpServerStatus {
119 pub id: String,
120 pub status: McpServerConnectionStatus,
121 pub tool_count: usize,
123 pub error: String,
125}
126
127#[derive(Debug, Clone, Default)]
129pub struct SkillConfidence {
130 pub name: String,
131 pub posterior: f64,
132 pub total_uses: u32,
133}
134
135#[derive(Debug, Clone, Default)]
137pub struct SubAgentMetrics {
138 pub id: String,
139 pub name: String,
140 pub state: String,
142 pub turns_used: u32,
143 pub max_turns: u32,
144 pub background: bool,
145 pub elapsed_secs: u64,
146 pub permission_mode: String,
149 pub transcript_dir: Option<String>,
152}
153
154#[derive(Debug, Clone, Default)]
159pub struct TurnTimings {
160 pub prepare_context_ms: u64,
161 pub llm_chat_ms: u64,
162 pub tool_exec_ms: u64,
163 pub persist_message_ms: u64,
164}
165
166#[derive(Debug, Clone, Default)]
173#[allow(clippy::struct_excessive_bools)] pub struct MetricsSnapshot {
175 pub prompt_tokens: u64,
176 pub completion_tokens: u64,
177 pub total_tokens: u64,
178 pub context_tokens: u64,
179 pub api_calls: u64,
180 pub active_skills: Vec<String>,
181 pub total_skills: usize,
182 pub mcp_server_count: usize,
184 pub mcp_tool_count: usize,
185 pub mcp_connected_count: usize,
187 pub mcp_servers: Vec<McpServerStatus>,
189 pub active_mcp_tools: Vec<String>,
190 pub sqlite_message_count: u64,
191 pub sqlite_conversation_id: Option<zeph_memory::ConversationId>,
192 pub qdrant_available: bool,
193 pub vector_backend: String,
194 pub embeddings_generated: u64,
195 pub last_llm_latency_ms: u64,
196 pub uptime_seconds: u64,
197 pub provider_name: String,
198 pub model_name: String,
199 pub summaries_count: u64,
200 pub context_compactions: u64,
201 pub compaction_hard_count: u64,
204 pub compaction_turns_after_hard: Vec<u64>,
208 pub compression_events: u64,
209 pub compression_tokens_saved: u64,
210 pub tool_output_prunes: u64,
211 pub compaction_probe_passes: u64,
213 pub compaction_probe_soft_failures: u64,
215 pub compaction_probe_failures: u64,
217 pub compaction_probe_errors: u64,
219 pub last_probe_verdict: Option<zeph_memory::ProbeVerdict>,
221 pub last_probe_score: Option<f32>,
224 pub last_probe_category_scores: Option<Vec<zeph_memory::CategoryScore>>,
226 pub compaction_probe_threshold: f32,
228 pub compaction_probe_hard_fail_threshold: f32,
230 pub cache_read_tokens: u64,
231 pub cache_creation_tokens: u64,
232 pub cost_spent_cents: f64,
233 pub cost_cps_cents: Option<f64>,
235 pub cost_successful_tasks: u64,
237 pub provider_cost_breakdown: Vec<(String, crate::cost::ProviderUsage)>,
239 pub filter_raw_tokens: u64,
240 pub filter_saved_tokens: u64,
241 pub filter_applications: u64,
242 pub filter_total_commands: u64,
243 pub filter_filtered_commands: u64,
244 pub filter_confidence_full: u64,
245 pub filter_confidence_partial: u64,
246 pub filter_confidence_fallback: u64,
247 pub cancellations: u64,
248 pub server_compaction_events: u64,
249 pub sanitizer_runs: u64,
250 pub sanitizer_injection_flags: u64,
251 pub sanitizer_injection_fp_local: u64,
257 pub sanitizer_truncations: u64,
258 pub quarantine_invocations: u64,
259 pub quarantine_failures: u64,
260 pub classifier_tool_blocks: u64,
262 pub classifier_tool_suspicious: u64,
264 pub causal_ipi_flags: u64,
266 pub vigil_flags_total: u64,
268 pub vigil_blocks_total: u64,
270 pub exfiltration_images_blocked: u64,
271 pub exfiltration_tool_urls_flagged: u64,
272 pub exfiltration_memory_guards: u64,
273 pub pii_scrub_count: u64,
274 pub pii_ner_timeouts: u64,
276 pub pii_ner_circuit_breaker_trips: u64,
278 pub memory_validation_failures: u64,
279 pub rate_limit_trips: u64,
280 pub pre_execution_blocks: u64,
281 pub pre_execution_warnings: u64,
282 pub guardrail_enabled: bool,
284 pub guardrail_warn_mode: bool,
286 pub sub_agents: Vec<SubAgentMetrics>,
287 pub skill_confidence: Vec<SkillConfidence>,
288 pub scheduled_tasks: Vec<[String; 4]>,
290 pub router_thompson_stats: Vec<(String, f64, f64)>,
292 pub security_events: VecDeque<SecurityEvent>,
294 pub orchestration: OrchestrationMetrics,
295 pub orchestration_graph: Option<TaskGraphSnapshot>,
297 pub graph_community_detection_failures: u64,
298 pub graph_entities_total: u64,
299 pub graph_edges_total: u64,
300 pub graph_communities_total: u64,
301 pub graph_extraction_count: u64,
302 pub graph_extraction_failures: u64,
303 pub extended_context: bool,
306 pub guidelines_version: u32,
308 pub guidelines_updated_at: String,
310 pub tool_cache_hits: u64,
311 pub tool_cache_misses: u64,
312 pub tool_cache_entries: usize,
313 pub semantic_fact_count: u64,
315 pub stt_model: Option<String>,
317 pub compaction_model: Option<String>,
319 pub provider_temperature: Option<f32>,
321 pub provider_top_p: Option<f32>,
323 pub embedding_model: String,
325 pub token_budget: Option<u64>,
327 pub compaction_threshold: Option<u32>,
329 pub vault_backend: String,
331 pub active_channel: String,
333 pub bg_inflight: u64,
335 pub bg_dropped: u64,
337 pub bg_completed: u64,
339 pub bg_enrichment_inflight: u64,
341 pub bg_telemetry_inflight: u64,
343 pub shell_background_runs: Vec<ShellBackgroundRunRow>,
345 pub self_learning_enabled: bool,
347 pub semantic_cache_enabled: bool,
349 pub cache_enabled: bool,
351 pub autosave_enabled: bool,
353 pub classifier: ClassifierMetricsSnapshot,
355 pub last_turn_timings: TurnTimings,
357 pub avg_turn_timings: TurnTimings,
359 pub max_turn_timings: TurnTimings,
363 pub timing_sample_count: u64,
365 pub egress_requests_total: u64,
367 pub egress_dropped_total: u64,
369 pub egress_blocked_total: u64,
371 pub context_max_tokens: u64,
377 pub compaction_last_before: u64,
379 pub compaction_last_after: u64,
381 pub compaction_last_at_ms: u64,
383 pub active_goal: Option<crate::goal::GoalSnapshot>,
385 pub cocoon_connected: Option<bool>,
388 pub cocoon_worker_count: u32,
390 pub cocoon_model_count: usize,
392 pub cocoon_ton_balance: Option<f64>,
394}
395
396#[derive(Debug, Clone, Default, serde::Serialize)]
402pub struct ShellBackgroundRunRow {
403 pub run_id: String,
405 pub command: String,
407 pub elapsed_secs: u64,
409}
410
411#[derive(Debug, Default)]
429pub struct StaticMetricsInit {
430 pub stt_model: Option<String>,
432 pub compaction_model: Option<String>,
434 pub semantic_cache_enabled: bool,
439 pub embedding_model: String,
441 pub self_learning_enabled: bool,
443 pub active_channel: String,
445 pub token_budget: Option<u64>,
447 pub compaction_threshold: Option<u32>,
449 pub vault_backend: String,
451 pub autosave_enabled: bool,
453 pub model_name_override: Option<String>,
457}
458
459fn strip_ctrl(s: &str) -> String {
465 let mut out = String::with_capacity(s.len());
466 let mut chars = s.chars().peekable();
467 while let Some(c) = chars.next() {
468 if c == '\x1b' {
469 if chars.peek() == Some(&'[') {
471 chars.next(); for inner in chars.by_ref() {
473 if ('\x40'..='\x7e').contains(&inner) {
474 break;
475 }
476 }
477 }
478 } else if c.is_control() && c != '\t' && c != '\n' && c != '\r' {
480 } else {
482 out.push(c);
483 }
484 }
485 out
486}
487
488impl From<&zeph_orchestration::TaskGraph> for TaskGraphSnapshot {
490 fn from(graph: &zeph_orchestration::TaskGraph) -> Self {
491 let tasks = graph
492 .tasks
493 .iter()
494 .map(|t| {
495 let error = t
496 .result
497 .as_ref()
498 .filter(|_| t.status == zeph_orchestration::TaskStatus::Failed)
499 .and_then(|r| {
500 if r.output.is_empty() {
501 None
502 } else {
503 let s = strip_ctrl(&r.output);
505 if s.len() > 80 {
506 let end = s.floor_char_boundary(79);
507 Some(format!("{}…", &s[..end]))
508 } else {
509 Some(s)
510 }
511 }
512 });
513 let duration_ms = t.result.as_ref().map_or(0, |r| r.duration_ms);
514 TaskSnapshotRow {
515 id: t.id.as_u32(),
516 title: strip_ctrl(&t.title),
517 status: t.status.to_string(),
518 agent: t.assigned_agent.as_deref().map(strip_ctrl),
519 duration_ms,
520 error,
521 }
522 })
523 .collect();
524 Self {
525 graph_id: graph.id.to_string(),
526 goal: strip_ctrl(&graph.goal),
527 status: graph.status.to_string(),
528 tasks,
529 completed_at: None,
530 }
531 }
532}
533
534pub struct MetricsCollector {
535 tx: watch::Sender<MetricsSnapshot>,
536}
537
538impl MetricsCollector {
539 #[must_use]
540 pub fn new() -> (Self, watch::Receiver<MetricsSnapshot>) {
541 let (tx, rx) = watch::channel(MetricsSnapshot::default());
542 (Self { tx }, rx)
543 }
544
545 pub fn update(&self, f: impl FnOnce(&mut MetricsSnapshot)) {
546 self.tx.send_modify(f);
547 }
548
549 pub fn set_context_max_tokens(&self, max_tokens: u64) {
564 self.tx.send_modify(|m| m.context_max_tokens = max_tokens);
565 }
566
567 pub fn record_compaction(&self, before: u64, after: u64, at_ms: u64) {
585 self.tx.send_modify(|m| {
586 m.compaction_last_before = before;
587 m.compaction_last_after = after;
588 m.compaction_last_at_ms = at_ms;
589 });
590 }
591
592 #[must_use]
598 pub fn sender(&self) -> watch::Sender<MetricsSnapshot> {
599 self.tx.clone()
600 }
601}
602
603pub trait HistogramRecorder: Send + Sync {
641 fn observe_llm_latency(&self, duration: std::time::Duration);
643
644 fn observe_turn_duration(&self, duration: std::time::Duration);
646
647 fn observe_tool_execution(&self, duration: std::time::Duration);
649
650 fn observe_bg_task(&self, class_label: &str, duration: std::time::Duration);
654}
655
656#[cfg(test)]
657mod tests {
658 #![allow(clippy::field_reassign_with_default)]
659
660 use super::*;
661
662 #[test]
663 fn default_metrics_snapshot() {
664 let m = MetricsSnapshot::default();
665 assert_eq!(m.total_tokens, 0);
666 assert_eq!(m.api_calls, 0);
667 assert!(m.active_skills.is_empty());
668 assert!(m.active_mcp_tools.is_empty());
669 assert_eq!(m.mcp_tool_count, 0);
670 assert_eq!(m.mcp_server_count, 0);
671 assert!(m.provider_name.is_empty());
672 assert_eq!(m.summaries_count, 0);
673 assert!(m.stt_model.is_none());
675 assert!(m.compaction_model.is_none());
676 assert!(m.provider_temperature.is_none());
677 assert!(m.provider_top_p.is_none());
678 assert!(m.active_channel.is_empty());
679 assert!(m.embedding_model.is_empty());
680 assert!(m.token_budget.is_none());
681 assert!(!m.self_learning_enabled);
682 assert!(!m.semantic_cache_enabled);
683 }
684
685 #[test]
686 fn metrics_collector_update_phase2_fields() {
687 let (collector, rx) = MetricsCollector::new();
688 collector.update(|m| {
689 m.stt_model = Some("whisper-1".into());
690 m.compaction_model = Some("haiku".into());
691 m.provider_temperature = Some(0.7);
692 m.provider_top_p = Some(0.95);
693 m.active_channel = "tui".into();
694 m.embedding_model = "nomic-embed-text".into();
695 m.token_budget = Some(200_000);
696 m.self_learning_enabled = true;
697 m.semantic_cache_enabled = true;
698 });
699 let s = rx.borrow();
700 assert_eq!(s.stt_model.as_deref(), Some("whisper-1"));
701 assert_eq!(s.compaction_model.as_deref(), Some("haiku"));
702 assert_eq!(s.provider_temperature, Some(0.7));
703 assert_eq!(s.provider_top_p, Some(0.95));
704 assert_eq!(s.active_channel, "tui");
705 assert_eq!(s.embedding_model, "nomic-embed-text");
706 assert_eq!(s.token_budget, Some(200_000));
707 assert!(s.self_learning_enabled);
708 assert!(s.semantic_cache_enabled);
709 }
710
711 #[test]
712 fn metrics_collector_update() {
713 let (collector, rx) = MetricsCollector::new();
714 collector.update(|m| {
715 m.api_calls = 5;
716 m.total_tokens = 1000;
717 });
718 let snapshot = rx.borrow().clone();
719 assert_eq!(snapshot.api_calls, 5);
720 assert_eq!(snapshot.total_tokens, 1000);
721 }
722
723 #[test]
724 fn metrics_collector_multiple_updates() {
725 let (collector, rx) = MetricsCollector::new();
726 collector.update(|m| m.api_calls = 1);
727 collector.update(|m| m.api_calls += 1);
728 assert_eq!(rx.borrow().api_calls, 2);
729 }
730
731 #[test]
732 fn metrics_snapshot_clone() {
733 let mut m = MetricsSnapshot::default();
734 m.provider_name = "ollama".into();
735 let cloned = m.clone();
736 assert_eq!(cloned.provider_name, "ollama");
737 }
738
739 #[test]
740 fn filter_metrics_tracking() {
741 let (collector, rx) = MetricsCollector::new();
742 collector.update(|m| {
743 m.filter_raw_tokens += 250;
744 m.filter_saved_tokens += 200;
745 m.filter_applications += 1;
746 });
747 collector.update(|m| {
748 m.filter_raw_tokens += 100;
749 m.filter_saved_tokens += 80;
750 m.filter_applications += 1;
751 });
752 let s = rx.borrow();
753 assert_eq!(s.filter_raw_tokens, 350);
754 assert_eq!(s.filter_saved_tokens, 280);
755 assert_eq!(s.filter_applications, 2);
756 }
757
758 #[test]
759 fn filter_confidence_and_command_metrics() {
760 let (collector, rx) = MetricsCollector::new();
761 collector.update(|m| {
762 m.filter_total_commands += 1;
763 m.filter_filtered_commands += 1;
764 m.filter_confidence_full += 1;
765 });
766 collector.update(|m| {
767 m.filter_total_commands += 1;
768 m.filter_confidence_partial += 1;
769 });
770 let s = rx.borrow();
771 assert_eq!(s.filter_total_commands, 2);
772 assert_eq!(s.filter_filtered_commands, 1);
773 assert_eq!(s.filter_confidence_full, 1);
774 assert_eq!(s.filter_confidence_partial, 1);
775 assert_eq!(s.filter_confidence_fallback, 0);
776 }
777
778 #[test]
779 fn summaries_count_tracks_summarizations() {
780 let (collector, rx) = MetricsCollector::new();
781 collector.update(|m| m.summaries_count += 1);
782 collector.update(|m| m.summaries_count += 1);
783 assert_eq!(rx.borrow().summaries_count, 2);
784 }
785
786 #[test]
787 fn cancellations_counter_increments() {
788 let (collector, rx) = MetricsCollector::new();
789 assert_eq!(rx.borrow().cancellations, 0);
790 collector.update(|m| m.cancellations += 1);
791 collector.update(|m| m.cancellations += 1);
792 assert_eq!(rx.borrow().cancellations, 2);
793 }
794
795 #[test]
796 fn security_event_detail_exact_128_not_truncated() {
797 let s = "a".repeat(128);
798 let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, "src", s.clone());
799 assert_eq!(ev.detail, s, "128-char string must not be truncated");
800 }
801
802 #[test]
803 fn security_event_detail_129_is_truncated() {
804 let s = "a".repeat(129);
805 let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, "src", s);
806 assert!(
807 ev.detail.ends_with('…'),
808 "129-char string must end with ellipsis"
809 );
810 assert!(
811 ev.detail.len() <= 130,
812 "truncated detail must be at most 130 bytes"
813 );
814 }
815
816 #[test]
817 fn security_event_detail_multibyte_utf8_no_panic() {
818 let s = "中".repeat(43);
820 let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, "src", s);
821 assert!(ev.detail.ends_with('…'));
822 }
823
824 #[test]
825 fn security_event_source_capped_at_64_chars() {
826 let long_source = "x".repeat(200);
827 let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, long_source, "detail");
828 assert_eq!(ev.source.len(), 64);
829 }
830
831 #[test]
832 fn security_event_source_strips_control_chars() {
833 let source = "tool\x00name\x1b[31m";
834 let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, source, "detail");
835 assert!(!ev.source.contains('\x00'));
836 assert!(!ev.source.contains('\x1b'));
837 }
838
839 #[test]
840 fn security_event_category_as_str() {
841 assert_eq!(SecurityEventCategory::InjectionFlag.as_str(), "injection");
842 assert_eq!(SecurityEventCategory::ExfiltrationBlock.as_str(), "exfil");
843 assert_eq!(SecurityEventCategory::Quarantine.as_str(), "quarantine");
844 assert_eq!(SecurityEventCategory::Truncation.as_str(), "truncation");
845 assert_eq!(
846 SecurityEventCategory::CrossBoundaryMcpToAcp.as_str(),
847 "cross_boundary_mcp_to_acp"
848 );
849 }
850
851 #[test]
852 fn ring_buffer_respects_cap_via_update() {
853 let (collector, rx) = MetricsCollector::new();
854 for i in 0..110u64 {
855 let event = SecurityEvent::new(
856 SecurityEventCategory::InjectionFlag,
857 "src",
858 format!("event {i}"),
859 );
860 collector.update(|m| {
861 if m.security_events.len() >= SECURITY_EVENT_CAP {
862 m.security_events.pop_front();
863 }
864 m.security_events.push_back(event);
865 });
866 }
867 let snap = rx.borrow();
868 assert_eq!(snap.security_events.len(), SECURITY_EVENT_CAP);
869 assert!(snap.security_events.back().unwrap().detail.contains("109"));
871 }
872
873 #[test]
874 fn security_events_empty_by_default() {
875 let m = MetricsSnapshot::default();
876 assert!(m.security_events.is_empty());
877 }
878
879 #[test]
880 fn orchestration_metrics_default_zero() {
881 let m = OrchestrationMetrics::default();
882 assert_eq!(m.plans_total, 0);
883 assert_eq!(m.tasks_total, 0);
884 assert_eq!(m.tasks_completed, 0);
885 assert_eq!(m.tasks_failed, 0);
886 assert_eq!(m.tasks_skipped, 0);
887 }
888
889 #[test]
890 fn metrics_snapshot_includes_orchestration_default_zero() {
891 let m = MetricsSnapshot::default();
892 assert_eq!(m.orchestration.plans_total, 0);
893 assert_eq!(m.orchestration.tasks_total, 0);
894 assert_eq!(m.orchestration.tasks_completed, 0);
895 }
896
897 #[test]
898 fn orchestration_metrics_update_via_collector() {
899 let (collector, rx) = MetricsCollector::new();
900 collector.update(|m| {
901 m.orchestration.plans_total += 1;
902 m.orchestration.tasks_total += 5;
903 m.orchestration.tasks_completed += 3;
904 m.orchestration.tasks_failed += 1;
905 m.orchestration.tasks_skipped += 1;
906 });
907 let s = rx.borrow();
908 assert_eq!(s.orchestration.plans_total, 1);
909 assert_eq!(s.orchestration.tasks_total, 5);
910 assert_eq!(s.orchestration.tasks_completed, 3);
911 assert_eq!(s.orchestration.tasks_failed, 1);
912 assert_eq!(s.orchestration.tasks_skipped, 1);
913 }
914
915 #[test]
916 fn strip_ctrl_removes_escape_sequences() {
917 let input = "hello\x1b[31mworld\x00end";
918 let result = strip_ctrl(input);
919 assert_eq!(result, "helloworldend");
920 }
921
922 #[test]
923 fn strip_ctrl_allows_tab_lf_cr() {
924 let input = "a\tb\nc\rd";
925 let result = strip_ctrl(input);
926 assert_eq!(result, "a\tb\nc\rd");
927 }
928
929 #[test]
930 fn task_graph_snapshot_is_stale_after_30s() {
931 let mut snap = TaskGraphSnapshot::default();
932 assert!(!snap.is_stale());
934 snap.completed_at = Some(std::time::Instant::now());
936 assert!(!snap.is_stale());
937 snap.completed_at = Some(
939 std::time::Instant::now()
940 .checked_sub(std::time::Duration::from_secs(31))
941 .unwrap(),
942 );
943 assert!(snap.is_stale());
944 }
945
946 #[test]
948 fn task_graph_snapshot_from_task_graph_maps_fields() {
949 use zeph_orchestration::{GraphStatus, TaskGraph, TaskNode, TaskResult, TaskStatus};
950
951 let mut graph = TaskGraph::new("My goal");
952 let mut task = TaskNode::new(0, "Do work", "description");
953 task.status = TaskStatus::Failed;
954 task.assigned_agent = Some("agent-1".into());
955 task.result = Some(TaskResult {
956 output: "error occurred here".into(),
957 artifacts: vec![],
958 duration_ms: 1234,
959 agent_id: None,
960 agent_def: None,
961 });
962 graph.tasks.push(task);
963 graph.status = GraphStatus::Failed;
964
965 let snap = TaskGraphSnapshot::from(&graph);
966 assert_eq!(snap.goal, "My goal");
967 assert_eq!(snap.status, "failed");
968 assert_eq!(snap.tasks.len(), 1);
969 let row = &snap.tasks[0];
970 assert_eq!(row.title, "Do work");
971 assert_eq!(row.status, "failed");
972 assert_eq!(row.agent.as_deref(), Some("agent-1"));
973 assert_eq!(row.duration_ms, 1234);
974 assert!(row.error.as_deref().unwrap().contains("error occurred"));
975 }
976
977 #[test]
979 fn task_graph_snapshot_from_compiles_with_feature() {
980 use zeph_orchestration::TaskGraph;
981 let graph = TaskGraph::new("feature flag test");
982 let snap = TaskGraphSnapshot::from(&graph);
983 assert_eq!(snap.goal, "feature flag test");
984 assert!(snap.tasks.is_empty());
985 assert!(!snap.is_stale());
986 }
987
988 #[test]
990 fn task_graph_snapshot_error_truncated_at_80_chars() {
991 use zeph_orchestration::{TaskGraph, TaskNode, TaskResult, TaskStatus};
992
993 let mut graph = TaskGraph::new("goal");
994 let mut task = TaskNode::new(0, "t", "d");
995 task.status = TaskStatus::Failed;
996 task.result = Some(TaskResult {
997 output: "e".repeat(100),
998 artifacts: vec![],
999 duration_ms: 0,
1000 agent_id: None,
1001 agent_def: None,
1002 });
1003 graph.tasks.push(task);
1004
1005 let snap = TaskGraphSnapshot::from(&graph);
1006 let err = snap.tasks[0].error.as_ref().unwrap();
1007 assert!(err.ends_with('…'), "truncated error must end with ellipsis");
1008 assert!(
1009 err.len() <= 83,
1010 "truncated error must not exceed 80 chars + ellipsis"
1011 );
1012 }
1013
1014 #[test]
1016 fn task_graph_snapshot_strips_control_chars_from_title() {
1017 use zeph_orchestration::{TaskGraph, TaskNode};
1018
1019 let mut graph = TaskGraph::new("goal\x1b[31m");
1020 let task = TaskNode::new(0, "title\x00injected", "d");
1021 graph.tasks.push(task);
1022
1023 let snap = TaskGraphSnapshot::from(&graph);
1024 assert!(!snap.goal.contains('\x1b'), "goal must not contain escape");
1025 assert!(
1026 !snap.tasks[0].title.contains('\x00'),
1027 "title must not contain null byte"
1028 );
1029 }
1030
1031 #[test]
1032 fn graph_metrics_default_zero() {
1033 let m = MetricsSnapshot::default();
1034 assert_eq!(m.graph_entities_total, 0);
1035 assert_eq!(m.graph_edges_total, 0);
1036 assert_eq!(m.graph_communities_total, 0);
1037 assert_eq!(m.graph_extraction_count, 0);
1038 assert_eq!(m.graph_extraction_failures, 0);
1039 }
1040
1041 #[test]
1042 fn graph_metrics_update_via_collector() {
1043 let (collector, rx) = MetricsCollector::new();
1044 collector.update(|m| {
1045 m.graph_entities_total = 5;
1046 m.graph_edges_total = 10;
1047 m.graph_communities_total = 2;
1048 m.graph_extraction_count = 7;
1049 m.graph_extraction_failures = 1;
1050 });
1051 let snapshot = rx.borrow().clone();
1052 assert_eq!(snapshot.graph_entities_total, 5);
1053 assert_eq!(snapshot.graph_edges_total, 10);
1054 assert_eq!(snapshot.graph_communities_total, 2);
1055 assert_eq!(snapshot.graph_extraction_count, 7);
1056 assert_eq!(snapshot.graph_extraction_failures, 1);
1057 }
1058
1059 #[test]
1060 fn histogram_recorder_trait_is_object_safe() {
1061 use std::sync::Arc;
1062 use std::time::Duration;
1063
1064 struct NoOpRecorder;
1065 impl HistogramRecorder for NoOpRecorder {
1066 fn observe_llm_latency(&self, _: Duration) {}
1067 fn observe_turn_duration(&self, _: Duration) {}
1068 fn observe_tool_execution(&self, _: Duration) {}
1069 fn observe_bg_task(&self, _: &str, _: Duration) {}
1070 }
1071
1072 let recorder: Arc<dyn HistogramRecorder> = Arc::new(NoOpRecorder);
1074 recorder.observe_llm_latency(Duration::from_millis(500));
1075 recorder.observe_turn_duration(Duration::from_secs(3));
1076 recorder.observe_tool_execution(Duration::from_millis(100));
1077 }
1078}