Skip to main content

zeph_core/
metrics.rs

1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4use std::collections::VecDeque;
5
6use tokio::sync::watch;
7
8pub use zeph_llm::{ClassifierMetricsSnapshot, TaskMetricsSnapshot};
9pub use zeph_memory::{CategoryScore, ProbeCategory, ProbeVerdict};
10
11/// Category of a security event for TUI display.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum SecurityEventCategory {
14    InjectionFlag,
15    /// ML classifier hard-blocked tool output (`enforcement_mode=block` only).
16    InjectionBlocked,
17    ExfiltrationBlock,
18    Quarantine,
19    Truncation,
20    RateLimit,
21    MemoryValidation,
22    PreExecutionBlock,
23    PreExecutionWarn,
24    ResponseVerification,
25    /// `TurnCausalAnalyzer` flagged behavioral deviation at tool-return boundary.
26    CausalIpiFlag,
27    /// MCP tool result crossing into an ACP-serving session boundary.
28    CrossBoundaryMcpToAcp,
29}
30
31impl SecurityEventCategory {
32    #[must_use]
33    pub fn as_str(self) -> &'static str {
34        match self {
35            Self::InjectionFlag => "injection",
36            Self::InjectionBlocked => "injection_blocked",
37            Self::ExfiltrationBlock => "exfil",
38            Self::Quarantine => "quarantine",
39            Self::Truncation => "truncation",
40            Self::RateLimit => "rate_limit",
41            Self::MemoryValidation => "memory_validation",
42            Self::PreExecutionBlock => "pre_exec_block",
43            Self::PreExecutionWarn => "pre_exec_warn",
44            Self::ResponseVerification => "response_verify",
45            Self::CausalIpiFlag => "causal_ipi",
46            Self::CrossBoundaryMcpToAcp => "cross_boundary_mcp_to_acp",
47        }
48    }
49}
50
51/// A single security event record for TUI display.
52#[derive(Debug, Clone)]
53pub struct SecurityEvent {
54    /// Unix timestamp (seconds since epoch).
55    pub timestamp: u64,
56    pub category: SecurityEventCategory,
57    /// Source that triggered the event (e.g., `web_scrape`, `mcp_response`).
58    pub source: String,
59    /// Short description, capped at 128 chars.
60    pub detail: String,
61}
62
63impl SecurityEvent {
64    #[must_use]
65    pub fn new(
66        category: SecurityEventCategory,
67        source: impl Into<String>,
68        detail: impl Into<String>,
69    ) -> Self {
70        // IMP-1: cap source at 64 chars and strip ASCII control chars.
71        let source: String = source
72            .into()
73            .chars()
74            .filter(|c| !c.is_ascii_control())
75            .take(64)
76            .collect();
77        // CR-1: UTF-8 safe truncation using floor_char_boundary (stable since Rust 1.82).
78        let detail = detail.into();
79        let detail = if detail.len() > 128 {
80            let end = detail.floor_char_boundary(127);
81            format!("{}…", &detail[..end])
82        } else {
83            detail
84        };
85        Self {
86            timestamp: std::time::SystemTime::now()
87                .duration_since(std::time::UNIX_EPOCH)
88                .unwrap_or_default()
89                .as_secs(),
90            category,
91            source,
92            detail,
93        }
94    }
95}
96
97/// Ring buffer capacity for security events.
98pub const SECURITY_EVENT_CAP: usize = 100;
99
100/// Lightweight snapshot of a single task row for TUI display.
101///
102/// Cloned from [`TaskGraph`] on each metrics tick; kept minimal on purpose.
103#[derive(Debug, Clone)]
104pub struct TaskSnapshotRow {
105    pub id: u32,
106    pub title: String,
107    /// Stringified `TaskStatus` (e.g. `"pending"`, `"running"`, `"completed"`).
108    pub status: String,
109    pub agent: Option<String>,
110    pub duration_ms: u64,
111    /// Truncated error message (first 80 chars) when the task failed.
112    pub error: Option<String>,
113}
114
115/// Lightweight snapshot of a `TaskGraph` for TUI display.
116#[derive(Debug, Clone, Default)]
117pub struct TaskGraphSnapshot {
118    pub graph_id: String,
119    pub goal: String,
120    /// Stringified `GraphStatus` (e.g. `"created"`, `"running"`, `"completed"`).
121    pub status: String,
122    pub tasks: Vec<TaskSnapshotRow>,
123    pub completed_at: Option<std::time::Instant>,
124}
125
126impl TaskGraphSnapshot {
127    /// Returns `true` if this snapshot represents a terminal plan that finished
128    /// more than 30 seconds ago and should no longer be shown in the TUI.
129    #[must_use]
130    pub fn is_stale(&self) -> bool {
131        self.completed_at
132            .is_some_and(|t| t.elapsed().as_secs() > 30)
133    }
134}
135
136/// Counters for the task orchestration subsystem.
137///
138/// Always present in [`MetricsSnapshot`]; zero-valued when orchestration is inactive.
139#[derive(Debug, Clone, Default)]
140pub struct OrchestrationMetrics {
141    pub plans_total: u64,
142    pub tasks_total: u64,
143    pub tasks_completed: u64,
144    pub tasks_failed: u64,
145    pub tasks_skipped: u64,
146}
147
148/// Connection status of a single MCP server for TUI display.
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub enum McpServerConnectionStatus {
151    Connected,
152    Failed,
153}
154
155/// Per-server MCP status snapshot for TUI display.
156#[derive(Debug, Clone)]
157pub struct McpServerStatus {
158    pub id: String,
159    pub status: McpServerConnectionStatus,
160    /// Number of tools provided by this server (0 when failed).
161    pub tool_count: usize,
162    /// Human-readable failure reason. Empty when connected.
163    pub error: String,
164}
165
166/// Bayesian confidence data for a single skill, used by TUI confidence bar.
167#[derive(Debug, Clone, Default)]
168pub struct SkillConfidence {
169    pub name: String,
170    pub posterior: f64,
171    pub total_uses: u32,
172}
173
174/// Snapshot of a single sub-agent's runtime status.
175#[derive(Debug, Clone, Default)]
176pub struct SubAgentMetrics {
177    pub id: String,
178    pub name: String,
179    /// Stringified `TaskState`: "working", "completed", "failed", "canceled", etc.
180    pub state: String,
181    pub turns_used: u32,
182    pub max_turns: u32,
183    pub background: bool,
184    pub elapsed_secs: u64,
185    /// Stringified `PermissionMode`: `"default"`, `"accept_edits"`, `"dont_ask"`,
186    /// `"bypass_permissions"`, `"plan"`. Empty string when mode is `Default`.
187    pub permission_mode: String,
188    /// Path to the directory containing this agent's JSONL transcript file.
189    /// `None` when transcript writing is disabled for this agent.
190    pub transcript_dir: Option<String>,
191}
192
193#[derive(Debug, Clone, Default)]
194#[allow(clippy::struct_excessive_bools)]
195pub struct MetricsSnapshot {
196    pub prompt_tokens: u64,
197    pub completion_tokens: u64,
198    pub total_tokens: u64,
199    pub context_tokens: u64,
200    pub api_calls: u64,
201    pub active_skills: Vec<String>,
202    pub total_skills: usize,
203    /// Total configured MCP servers (connected + failed).
204    pub mcp_server_count: usize,
205    pub mcp_tool_count: usize,
206    /// Number of successfully connected MCP servers.
207    pub mcp_connected_count: usize,
208    /// Per-server connection status list.
209    pub mcp_servers: Vec<McpServerStatus>,
210    pub active_mcp_tools: Vec<String>,
211    pub sqlite_message_count: u64,
212    pub sqlite_conversation_id: Option<zeph_memory::ConversationId>,
213    pub qdrant_available: bool,
214    pub vector_backend: String,
215    pub embeddings_generated: u64,
216    pub last_llm_latency_ms: u64,
217    pub uptime_seconds: u64,
218    pub provider_name: String,
219    pub model_name: String,
220    pub summaries_count: u64,
221    pub context_compactions: u64,
222    /// Number of times the agent entered the Hard compaction tier, including cooldown-skipped
223    /// turns. Not equal to the actual LLM summarization count — reflects pressure, not action.
224    pub compaction_hard_count: u64,
225    /// User-message turns elapsed after each hard compaction event.
226    /// Entry i = turns between hard compaction i and hard compaction i+1 (or session end).
227    /// Empty when no hard compaction occurred during the session.
228    pub compaction_turns_after_hard: Vec<u64>,
229    pub compression_events: u64,
230    pub compression_tokens_saved: u64,
231    pub tool_output_prunes: u64,
232    /// Compaction probe outcomes (#1609).
233    pub compaction_probe_passes: u64,
234    /// Compaction probe soft failures (summary borderline — compaction proceeded with warning).
235    pub compaction_probe_soft_failures: u64,
236    /// Compaction probe hard failures (compaction blocked due to lossy summary).
237    pub compaction_probe_failures: u64,
238    /// Compaction probe errors (LLM/timeout — non-blocking, compaction proceeded).
239    pub compaction_probe_errors: u64,
240    /// Last compaction probe verdict. `None` before the first probe completes.
241    pub last_probe_verdict: Option<zeph_memory::ProbeVerdict>,
242    /// Last compaction probe score in [0.0, 1.0]. `None` before the first probe
243    /// completes or after an Error verdict (errors produce no score).
244    pub last_probe_score: Option<f32>,
245    /// Per-category scores from the last completed probe.
246    pub last_probe_category_scores: Option<Vec<zeph_memory::CategoryScore>>,
247    /// Configured pass threshold for the compaction probe. Used by TUI for category color-coding.
248    pub compaction_probe_threshold: f32,
249    /// Configured hard-fail threshold for the compaction probe.
250    pub compaction_probe_hard_fail_threshold: f32,
251    pub cache_read_tokens: u64,
252    pub cache_creation_tokens: u64,
253    pub cost_spent_cents: f64,
254    /// Per-provider cost breakdown, sorted by cost descending.
255    pub provider_cost_breakdown: Vec<(String, crate::cost::ProviderUsage)>,
256    pub filter_raw_tokens: u64,
257    pub filter_saved_tokens: u64,
258    pub filter_applications: u64,
259    pub filter_total_commands: u64,
260    pub filter_filtered_commands: u64,
261    pub filter_confidence_full: u64,
262    pub filter_confidence_partial: u64,
263    pub filter_confidence_fallback: u64,
264    pub cancellations: u64,
265    pub server_compaction_events: u64,
266    pub sanitizer_runs: u64,
267    pub sanitizer_injection_flags: u64,
268    /// Injection pattern hits on `ToolResult` (local) sources — likely false positives.
269    ///
270    /// Counts regex hits that fired on content from `shell`, `read_file`, `search_code`, etc.
271    /// These sources are user-owned and not adversarial; a non-zero value indicates a pattern
272    /// that needs tightening or a source reclassification.
273    pub sanitizer_injection_fp_local: u64,
274    pub sanitizer_truncations: u64,
275    pub quarantine_invocations: u64,
276    pub quarantine_failures: u64,
277    /// ML classifier hard-blocked tool outputs (`enforcement_mode=block` only).
278    pub classifier_tool_blocks: u64,
279    /// ML classifier suspicious tool outputs (both enforcement modes).
280    pub classifier_tool_suspicious: u64,
281    /// `TurnCausalAnalyzer` flags: behavioral deviation detected at tool-return boundary.
282    pub causal_ipi_flags: u64,
283    pub exfiltration_images_blocked: u64,
284    pub exfiltration_tool_urls_flagged: u64,
285    pub exfiltration_memory_guards: u64,
286    pub pii_scrub_count: u64,
287    /// Number of times the PII NER classifier timed out; input fell back to regex-only.
288    pub pii_ner_timeouts: u64,
289    /// Number of times the PII NER circuit breaker tripped (disabled NER for the session).
290    pub pii_ner_circuit_breaker_trips: u64,
291    pub memory_validation_failures: u64,
292    pub rate_limit_trips: u64,
293    pub pre_execution_blocks: u64,
294    pub pre_execution_warnings: u64,
295    /// `true` when a guardrail filter is active for this session.
296    pub guardrail_enabled: bool,
297    /// `true` when guardrail is in warn-only mode (action = warn).
298    pub guardrail_warn_mode: bool,
299    pub sub_agents: Vec<SubAgentMetrics>,
300    pub skill_confidence: Vec<SkillConfidence>,
301    /// Scheduled task summaries: `[name, kind, mode, next_run]`.
302    pub scheduled_tasks: Vec<[String; 4]>,
303    /// Thompson Sampling distribution snapshots: `(provider, alpha, beta)`.
304    pub router_thompson_stats: Vec<(String, f64, f64)>,
305    /// Ring buffer of recent security events (cap 100, FIFO eviction).
306    pub security_events: VecDeque<SecurityEvent>,
307    pub orchestration: OrchestrationMetrics,
308    /// Live snapshot of the currently active task graph. `None` when no plan is active.
309    pub orchestration_graph: Option<TaskGraphSnapshot>,
310    pub graph_community_detection_failures: u64,
311    pub graph_entities_total: u64,
312    pub graph_edges_total: u64,
313    pub graph_communities_total: u64,
314    pub graph_extraction_count: u64,
315    pub graph_extraction_failures: u64,
316    /// `true` when `config.llm.cloud.enable_extended_context = true`.
317    /// Never set for other providers to avoid false positives.
318    pub extended_context: bool,
319    /// Latest compression-guidelines version (0 = no guidelines yet).
320    pub guidelines_version: u32,
321    /// ISO 8601 timestamp of the latest guidelines update (empty if none).
322    pub guidelines_updated_at: String,
323    pub tool_cache_hits: u64,
324    pub tool_cache_misses: u64,
325    pub tool_cache_entries: usize,
326    /// Number of semantic-tier facts in memory (0 when tier promotion disabled).
327    pub semantic_fact_count: u64,
328    /// STT model name (e.g. "whisper-1"). `None` when STT is not configured.
329    pub stt_model: Option<String>,
330    /// Model used for context compaction/summarization. `None` when no summary provider is set.
331    pub compaction_model: Option<String>,
332    /// Temperature of the active provider when using Candle. `None` for API providers.
333    pub provider_temperature: Option<f32>,
334    /// Top-p of the active provider when using Candle. `None` for API providers.
335    pub provider_top_p: Option<f32>,
336    /// Embedding model name (e.g. `"nomic-embed-text"`). Empty when embeddings are disabled.
337    pub embedding_model: String,
338    /// Token budget for context window. `None` when not configured.
339    pub token_budget: Option<u64>,
340    /// Token threshold that triggers soft compaction. `None` when not configured.
341    pub compaction_threshold: Option<u32>,
342    /// Vault backend identifier: "age", "env", or "none".
343    pub vault_backend: String,
344    /// Active I/O channel name: `"cli"`, `"telegram"`, `"tui"`, `"discord"`, `"slack"`.
345    pub active_channel: String,
346    /// Whether self-learning (skill evolution) is enabled.
347    pub self_learning_enabled: bool,
348    /// Whether the semantic response cache is enabled.
349    pub semantic_cache_enabled: bool,
350    /// Whether semantic response caching is enabled (alias for `semantic_cache_enabled`).
351    pub cache_enabled: bool,
352    /// Whether assistant messages are auto-saved to memory.
353    pub autosave_enabled: bool,
354    /// Classifier p50/p95 latency metrics per task (injection, pii, feedback).
355    pub classifier: ClassifierMetricsSnapshot,
356}
357
358/// Strip ASCII control characters and ANSI escape sequences from a string for safe TUI display.
359///
360/// Allows tab, LF, and CR; removes everything else in the `0x00–0x1F` range including full
361/// ANSI CSI sequences (`ESC[...`). This prevents escape-sequence injection from LLM planner
362/// output into the TUI.
363fn strip_ctrl(s: &str) -> String {
364    let mut out = String::with_capacity(s.len());
365    let mut chars = s.chars().peekable();
366    while let Some(c) = chars.next() {
367        if c == '\x1b' {
368            // Consume an ANSI CSI sequence: ESC [ <params> <final-byte in 0x40–0x7E>
369            if chars.peek() == Some(&'[') {
370                chars.next(); // consume '['
371                for inner in chars.by_ref() {
372                    if ('\x40'..='\x7e').contains(&inner) {
373                        break;
374                    }
375                }
376            }
377            // Drop ESC and any consumed sequence — write nothing.
378        } else if c.is_control() && c != '\t' && c != '\n' && c != '\r' {
379            // drop other control chars
380        } else {
381            out.push(c);
382        }
383    }
384    out
385}
386
387/// Convert a live `TaskGraph` into a lightweight snapshot for TUI display.
388impl From<&zeph_orchestration::TaskGraph> for TaskGraphSnapshot {
389    fn from(graph: &zeph_orchestration::TaskGraph) -> Self {
390        let tasks = graph
391            .tasks
392            .iter()
393            .map(|t| {
394                let error = t
395                    .result
396                    .as_ref()
397                    .filter(|_| t.status == zeph_orchestration::TaskStatus::Failed)
398                    .and_then(|r| {
399                        if r.output.is_empty() {
400                            None
401                        } else {
402                            // Strip control chars, then truncate at 80 chars (SEC-P6-01).
403                            let s = strip_ctrl(&r.output);
404                            if s.len() > 80 {
405                                let end = s.floor_char_boundary(79);
406                                Some(format!("{}…", &s[..end]))
407                            } else {
408                                Some(s)
409                            }
410                        }
411                    });
412                let duration_ms = t.result.as_ref().map_or(0, |r| r.duration_ms);
413                TaskSnapshotRow {
414                    id: t.id.as_u32(),
415                    title: strip_ctrl(&t.title),
416                    status: t.status.to_string(),
417                    agent: t.assigned_agent.as_deref().map(strip_ctrl),
418                    duration_ms,
419                    error,
420                }
421            })
422            .collect();
423        Self {
424            graph_id: graph.id.to_string(),
425            goal: strip_ctrl(&graph.goal),
426            status: graph.status.to_string(),
427            tasks,
428            completed_at: None,
429        }
430    }
431}
432
433pub struct MetricsCollector {
434    tx: watch::Sender<MetricsSnapshot>,
435}
436
437impl MetricsCollector {
438    #[must_use]
439    pub fn new() -> (Self, watch::Receiver<MetricsSnapshot>) {
440        let (tx, rx) = watch::channel(MetricsSnapshot::default());
441        (Self { tx }, rx)
442    }
443
444    pub fn update(&self, f: impl FnOnce(&mut MetricsSnapshot)) {
445        self.tx.send_modify(f);
446    }
447}
448
449#[cfg(test)]
450mod tests {
451    #![allow(clippy::field_reassign_with_default)]
452
453    use super::*;
454
455    #[test]
456    fn default_metrics_snapshot() {
457        let m = MetricsSnapshot::default();
458        assert_eq!(m.total_tokens, 0);
459        assert_eq!(m.api_calls, 0);
460        assert!(m.active_skills.is_empty());
461        assert!(m.active_mcp_tools.is_empty());
462        assert_eq!(m.mcp_tool_count, 0);
463        assert_eq!(m.mcp_server_count, 0);
464        assert!(m.provider_name.is_empty());
465        assert_eq!(m.summaries_count, 0);
466        // Phase 2 fields
467        assert!(m.stt_model.is_none());
468        assert!(m.compaction_model.is_none());
469        assert!(m.provider_temperature.is_none());
470        assert!(m.provider_top_p.is_none());
471        assert!(m.active_channel.is_empty());
472        assert!(m.embedding_model.is_empty());
473        assert!(m.token_budget.is_none());
474        assert!(!m.self_learning_enabled);
475        assert!(!m.semantic_cache_enabled);
476    }
477
478    #[test]
479    fn metrics_collector_update_phase2_fields() {
480        let (collector, rx) = MetricsCollector::new();
481        collector.update(|m| {
482            m.stt_model = Some("whisper-1".into());
483            m.compaction_model = Some("haiku".into());
484            m.provider_temperature = Some(0.7);
485            m.provider_top_p = Some(0.95);
486            m.active_channel = "tui".into();
487            m.embedding_model = "nomic-embed-text".into();
488            m.token_budget = Some(200_000);
489            m.self_learning_enabled = true;
490            m.semantic_cache_enabled = true;
491        });
492        let s = rx.borrow();
493        assert_eq!(s.stt_model.as_deref(), Some("whisper-1"));
494        assert_eq!(s.compaction_model.as_deref(), Some("haiku"));
495        assert_eq!(s.provider_temperature, Some(0.7));
496        assert_eq!(s.provider_top_p, Some(0.95));
497        assert_eq!(s.active_channel, "tui");
498        assert_eq!(s.embedding_model, "nomic-embed-text");
499        assert_eq!(s.token_budget, Some(200_000));
500        assert!(s.self_learning_enabled);
501        assert!(s.semantic_cache_enabled);
502    }
503
504    #[test]
505    fn metrics_collector_update() {
506        let (collector, rx) = MetricsCollector::new();
507        collector.update(|m| {
508            m.api_calls = 5;
509            m.total_tokens = 1000;
510        });
511        let snapshot = rx.borrow().clone();
512        assert_eq!(snapshot.api_calls, 5);
513        assert_eq!(snapshot.total_tokens, 1000);
514    }
515
516    #[test]
517    fn metrics_collector_multiple_updates() {
518        let (collector, rx) = MetricsCollector::new();
519        collector.update(|m| m.api_calls = 1);
520        collector.update(|m| m.api_calls += 1);
521        assert_eq!(rx.borrow().api_calls, 2);
522    }
523
524    #[test]
525    fn metrics_snapshot_clone() {
526        let mut m = MetricsSnapshot::default();
527        m.provider_name = "ollama".into();
528        let cloned = m.clone();
529        assert_eq!(cloned.provider_name, "ollama");
530    }
531
532    #[test]
533    fn filter_metrics_tracking() {
534        let (collector, rx) = MetricsCollector::new();
535        collector.update(|m| {
536            m.filter_raw_tokens += 250;
537            m.filter_saved_tokens += 200;
538            m.filter_applications += 1;
539        });
540        collector.update(|m| {
541            m.filter_raw_tokens += 100;
542            m.filter_saved_tokens += 80;
543            m.filter_applications += 1;
544        });
545        let s = rx.borrow();
546        assert_eq!(s.filter_raw_tokens, 350);
547        assert_eq!(s.filter_saved_tokens, 280);
548        assert_eq!(s.filter_applications, 2);
549    }
550
551    #[test]
552    fn filter_confidence_and_command_metrics() {
553        let (collector, rx) = MetricsCollector::new();
554        collector.update(|m| {
555            m.filter_total_commands += 1;
556            m.filter_filtered_commands += 1;
557            m.filter_confidence_full += 1;
558        });
559        collector.update(|m| {
560            m.filter_total_commands += 1;
561            m.filter_confidence_partial += 1;
562        });
563        let s = rx.borrow();
564        assert_eq!(s.filter_total_commands, 2);
565        assert_eq!(s.filter_filtered_commands, 1);
566        assert_eq!(s.filter_confidence_full, 1);
567        assert_eq!(s.filter_confidence_partial, 1);
568        assert_eq!(s.filter_confidence_fallback, 0);
569    }
570
571    #[test]
572    fn summaries_count_tracks_summarizations() {
573        let (collector, rx) = MetricsCollector::new();
574        collector.update(|m| m.summaries_count += 1);
575        collector.update(|m| m.summaries_count += 1);
576        assert_eq!(rx.borrow().summaries_count, 2);
577    }
578
579    #[test]
580    fn cancellations_counter_increments() {
581        let (collector, rx) = MetricsCollector::new();
582        assert_eq!(rx.borrow().cancellations, 0);
583        collector.update(|m| m.cancellations += 1);
584        collector.update(|m| m.cancellations += 1);
585        assert_eq!(rx.borrow().cancellations, 2);
586    }
587
588    #[test]
589    fn security_event_detail_exact_128_not_truncated() {
590        let s = "a".repeat(128);
591        let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, "src", s.clone());
592        assert_eq!(ev.detail, s, "128-char string must not be truncated");
593    }
594
595    #[test]
596    fn security_event_detail_129_is_truncated() {
597        let s = "a".repeat(129);
598        let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, "src", s);
599        assert!(
600            ev.detail.ends_with('…'),
601            "129-char string must end with ellipsis"
602        );
603        assert!(
604            ev.detail.len() <= 130,
605            "truncated detail must be at most 130 bytes"
606        );
607    }
608
609    #[test]
610    fn security_event_detail_multibyte_utf8_no_panic() {
611        // Each '中' is 3 bytes. 43 chars = 129 bytes — triggers truncation at a multi-byte boundary.
612        let s = "中".repeat(43);
613        let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, "src", s);
614        assert!(ev.detail.ends_with('…'));
615    }
616
617    #[test]
618    fn security_event_source_capped_at_64_chars() {
619        let long_source = "x".repeat(200);
620        let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, long_source, "detail");
621        assert_eq!(ev.source.len(), 64);
622    }
623
624    #[test]
625    fn security_event_source_strips_control_chars() {
626        let source = "tool\x00name\x1b[31m";
627        let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, source, "detail");
628        assert!(!ev.source.contains('\x00'));
629        assert!(!ev.source.contains('\x1b'));
630    }
631
632    #[test]
633    fn security_event_category_as_str() {
634        assert_eq!(SecurityEventCategory::InjectionFlag.as_str(), "injection");
635        assert_eq!(SecurityEventCategory::ExfiltrationBlock.as_str(), "exfil");
636        assert_eq!(SecurityEventCategory::Quarantine.as_str(), "quarantine");
637        assert_eq!(SecurityEventCategory::Truncation.as_str(), "truncation");
638        assert_eq!(
639            SecurityEventCategory::CrossBoundaryMcpToAcp.as_str(),
640            "cross_boundary_mcp_to_acp"
641        );
642    }
643
644    #[test]
645    fn ring_buffer_respects_cap_via_update() {
646        let (collector, rx) = MetricsCollector::new();
647        for i in 0..110u64 {
648            let event = SecurityEvent::new(
649                SecurityEventCategory::InjectionFlag,
650                "src",
651                format!("event {i}"),
652            );
653            collector.update(|m| {
654                if m.security_events.len() >= SECURITY_EVENT_CAP {
655                    m.security_events.pop_front();
656                }
657                m.security_events.push_back(event);
658            });
659        }
660        let snap = rx.borrow();
661        assert_eq!(snap.security_events.len(), SECURITY_EVENT_CAP);
662        // FIFO: earliest events evicted, last one present
663        assert!(snap.security_events.back().unwrap().detail.contains("109"));
664    }
665
666    #[test]
667    fn security_events_empty_by_default() {
668        let m = MetricsSnapshot::default();
669        assert!(m.security_events.is_empty());
670    }
671
672    #[test]
673    fn orchestration_metrics_default_zero() {
674        let m = OrchestrationMetrics::default();
675        assert_eq!(m.plans_total, 0);
676        assert_eq!(m.tasks_total, 0);
677        assert_eq!(m.tasks_completed, 0);
678        assert_eq!(m.tasks_failed, 0);
679        assert_eq!(m.tasks_skipped, 0);
680    }
681
682    #[test]
683    fn metrics_snapshot_includes_orchestration_default_zero() {
684        let m = MetricsSnapshot::default();
685        assert_eq!(m.orchestration.plans_total, 0);
686        assert_eq!(m.orchestration.tasks_total, 0);
687        assert_eq!(m.orchestration.tasks_completed, 0);
688    }
689
690    #[test]
691    fn orchestration_metrics_update_via_collector() {
692        let (collector, rx) = MetricsCollector::new();
693        collector.update(|m| {
694            m.orchestration.plans_total += 1;
695            m.orchestration.tasks_total += 5;
696            m.orchestration.tasks_completed += 3;
697            m.orchestration.tasks_failed += 1;
698            m.orchestration.tasks_skipped += 1;
699        });
700        let s = rx.borrow();
701        assert_eq!(s.orchestration.plans_total, 1);
702        assert_eq!(s.orchestration.tasks_total, 5);
703        assert_eq!(s.orchestration.tasks_completed, 3);
704        assert_eq!(s.orchestration.tasks_failed, 1);
705        assert_eq!(s.orchestration.tasks_skipped, 1);
706    }
707
708    #[test]
709    fn strip_ctrl_removes_escape_sequences() {
710        let input = "hello\x1b[31mworld\x00end";
711        let result = strip_ctrl(input);
712        assert_eq!(result, "helloworldend");
713    }
714
715    #[test]
716    fn strip_ctrl_allows_tab_lf_cr() {
717        let input = "a\tb\nc\rd";
718        let result = strip_ctrl(input);
719        assert_eq!(result, "a\tb\nc\rd");
720    }
721
722    #[test]
723    fn task_graph_snapshot_is_stale_after_30s() {
724        let mut snap = TaskGraphSnapshot::default();
725        // Not stale if no completed_at.
726        assert!(!snap.is_stale());
727        // Not stale if just completed.
728        snap.completed_at = Some(std::time::Instant::now());
729        assert!(!snap.is_stale());
730        // Stale if completed more than 30s ago.
731        snap.completed_at = Some(
732            std::time::Instant::now()
733                .checked_sub(std::time::Duration::from_secs(31))
734                .unwrap(),
735        );
736        assert!(snap.is_stale());
737    }
738
739    // T1: From<&TaskGraph> correctly maps fields including duration_ms and error truncation.
740    #[test]
741    fn task_graph_snapshot_from_task_graph_maps_fields() {
742        use zeph_orchestration::{GraphStatus, TaskGraph, TaskNode, TaskResult, TaskStatus};
743
744        let mut graph = TaskGraph::new("My goal");
745        let mut task = TaskNode::new(0, "Do work", "description");
746        task.status = TaskStatus::Failed;
747        task.assigned_agent = Some("agent-1".into());
748        task.result = Some(TaskResult {
749            output: "error occurred here".into(),
750            artifacts: vec![],
751            duration_ms: 1234,
752            agent_id: None,
753            agent_def: None,
754        });
755        graph.tasks.push(task);
756        graph.status = GraphStatus::Failed;
757
758        let snap = TaskGraphSnapshot::from(&graph);
759        assert_eq!(snap.goal, "My goal");
760        assert_eq!(snap.status, "failed");
761        assert_eq!(snap.tasks.len(), 1);
762        let row = &snap.tasks[0];
763        assert_eq!(row.title, "Do work");
764        assert_eq!(row.status, "failed");
765        assert_eq!(row.agent.as_deref(), Some("agent-1"));
766        assert_eq!(row.duration_ms, 1234);
767        assert!(row.error.as_deref().unwrap().contains("error occurred"));
768    }
769
770    // T2: From impl compiles with orchestration feature active.
771    #[test]
772    fn task_graph_snapshot_from_compiles_with_feature() {
773        use zeph_orchestration::TaskGraph;
774        let graph = TaskGraph::new("feature flag test");
775        let snap = TaskGraphSnapshot::from(&graph);
776        assert_eq!(snap.goal, "feature flag test");
777        assert!(snap.tasks.is_empty());
778        assert!(!snap.is_stale());
779    }
780
781    // T1-extra: long error is truncated with ellipsis.
782    #[test]
783    fn task_graph_snapshot_error_truncated_at_80_chars() {
784        use zeph_orchestration::{TaskGraph, TaskNode, TaskResult, TaskStatus};
785
786        let mut graph = TaskGraph::new("goal");
787        let mut task = TaskNode::new(0, "t", "d");
788        task.status = TaskStatus::Failed;
789        task.result = Some(TaskResult {
790            output: "e".repeat(100),
791            artifacts: vec![],
792            duration_ms: 0,
793            agent_id: None,
794            agent_def: None,
795        });
796        graph.tasks.push(task);
797
798        let snap = TaskGraphSnapshot::from(&graph);
799        let err = snap.tasks[0].error.as_ref().unwrap();
800        assert!(err.ends_with('…'), "truncated error must end with ellipsis");
801        assert!(
802            err.len() <= 83,
803            "truncated error must not exceed 80 chars + ellipsis"
804        );
805    }
806
807    // SEC-P6-01: control chars in task title are stripped.
808    #[test]
809    fn task_graph_snapshot_strips_control_chars_from_title() {
810        use zeph_orchestration::{TaskGraph, TaskNode};
811
812        let mut graph = TaskGraph::new("goal\x1b[31m");
813        let task = TaskNode::new(0, "title\x00injected", "d");
814        graph.tasks.push(task);
815
816        let snap = TaskGraphSnapshot::from(&graph);
817        assert!(!snap.goal.contains('\x1b'), "goal must not contain escape");
818        assert!(
819            !snap.tasks[0].title.contains('\x00'),
820            "title must not contain null byte"
821        );
822    }
823
824    #[test]
825    fn graph_metrics_default_zero() {
826        let m = MetricsSnapshot::default();
827        assert_eq!(m.graph_entities_total, 0);
828        assert_eq!(m.graph_edges_total, 0);
829        assert_eq!(m.graph_communities_total, 0);
830        assert_eq!(m.graph_extraction_count, 0);
831        assert_eq!(m.graph_extraction_failures, 0);
832    }
833
834    #[test]
835    fn graph_metrics_update_via_collector() {
836        let (collector, rx) = MetricsCollector::new();
837        collector.update(|m| {
838            m.graph_entities_total = 5;
839            m.graph_edges_total = 10;
840            m.graph_communities_total = 2;
841            m.graph_extraction_count = 7;
842            m.graph_extraction_failures = 1;
843        });
844        let snapshot = rx.borrow().clone();
845        assert_eq!(snapshot.graph_entities_total, 5);
846        assert_eq!(snapshot.graph_edges_total, 10);
847        assert_eq!(snapshot.graph_communities_total, 2);
848        assert_eq!(snapshot.graph_extraction_count, 7);
849        assert_eq!(snapshot.graph_extraction_failures, 1);
850    }
851}