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    /// VIGIL pre-sanitizer gate flagged a tool output.
30    VigilFlag,
31}
32
33impl SecurityEventCategory {
34    #[must_use]
35    pub fn as_str(self) -> &'static str {
36        match self {
37            Self::InjectionFlag => "injection",
38            Self::InjectionBlocked => "injection_blocked",
39            Self::ExfiltrationBlock => "exfil",
40            Self::Quarantine => "quarantine",
41            Self::Truncation => "truncation",
42            Self::RateLimit => "rate_limit",
43            Self::MemoryValidation => "memory_validation",
44            Self::PreExecutionBlock => "pre_exec_block",
45            Self::PreExecutionWarn => "pre_exec_warn",
46            Self::ResponseVerification => "response_verify",
47            Self::CausalIpiFlag => "causal_ipi",
48            Self::CrossBoundaryMcpToAcp => "cross_boundary_mcp_to_acp",
49            Self::VigilFlag => "vigil",
50        }
51    }
52}
53
54/// A single security event record for TUI display.
55#[derive(Debug, Clone)]
56pub struct SecurityEvent {
57    /// Unix timestamp (seconds since epoch).
58    pub timestamp: u64,
59    pub category: SecurityEventCategory,
60    /// Source that triggered the event (e.g., `web_scrape`, `mcp_response`).
61    pub source: String,
62    /// Short description, capped at 128 chars.
63    pub detail: String,
64}
65
66impl SecurityEvent {
67    #[must_use]
68    pub fn new(
69        category: SecurityEventCategory,
70        source: impl Into<String>,
71        detail: impl Into<String>,
72    ) -> Self {
73        // IMP-1: cap source at 64 chars and strip ASCII control chars.
74        let source: String = source
75            .into()
76            .chars()
77            .filter(|c| !c.is_ascii_control())
78            .take(64)
79            .collect();
80        // CR-1: UTF-8 safe truncation using floor_char_boundary (stable since Rust 1.82).
81        let detail = detail.into();
82        let detail = if detail.len() > 128 {
83            let end = detail.floor_char_boundary(127);
84            format!("{}…", &detail[..end])
85        } else {
86            detail
87        };
88        Self {
89            timestamp: std::time::SystemTime::now()
90                .duration_since(std::time::UNIX_EPOCH)
91                .unwrap_or_default()
92                .as_secs(),
93            category,
94            source,
95            detail,
96        }
97    }
98}
99
100/// Ring buffer capacity for security events.
101pub const SECURITY_EVENT_CAP: usize = 100;
102
103/// Lightweight snapshot of a single task row for TUI display.
104///
105/// Captured from the task graph on each metrics tick; kept minimal on purpose.
106#[derive(Debug, Clone)]
107pub struct TaskSnapshotRow {
108    pub id: u32,
109    pub title: String,
110    /// Stringified `TaskStatus` (e.g. `"pending"`, `"running"`, `"completed"`).
111    pub status: String,
112    pub agent: Option<String>,
113    pub duration_ms: u64,
114    /// Truncated error message (first 80 chars) when the task failed.
115    pub error: Option<String>,
116}
117
118/// Lightweight snapshot of a `TaskGraph` for TUI display.
119#[derive(Debug, Clone, Default)]
120pub struct TaskGraphSnapshot {
121    pub graph_id: String,
122    pub goal: String,
123    /// Stringified `GraphStatus` (e.g. `"created"`, `"running"`, `"completed"`).
124    pub status: String,
125    pub tasks: Vec<TaskSnapshotRow>,
126    pub completed_at: Option<std::time::Instant>,
127}
128
129impl TaskGraphSnapshot {
130    /// Returns `true` if this snapshot represents a terminal plan that finished
131    /// more than 30 seconds ago and should no longer be shown in the TUI.
132    #[must_use]
133    pub fn is_stale(&self) -> bool {
134        self.completed_at
135            .is_some_and(|t| t.elapsed().as_secs() > 30)
136    }
137}
138
139/// Counters for the task orchestration subsystem.
140///
141/// Always present in [`MetricsSnapshot`]; zero-valued when orchestration is inactive.
142#[derive(Debug, Clone, Default)]
143pub struct OrchestrationMetrics {
144    pub plans_total: u64,
145    pub tasks_total: u64,
146    pub tasks_completed: u64,
147    pub tasks_failed: u64,
148    pub tasks_skipped: u64,
149}
150
151/// Connection status of a single MCP server for TUI display.
152#[derive(Debug, Clone, PartialEq, Eq)]
153pub enum McpServerConnectionStatus {
154    Connected,
155    Failed,
156}
157
158/// Per-server MCP status snapshot for TUI display.
159#[derive(Debug, Clone)]
160pub struct McpServerStatus {
161    pub id: String,
162    pub status: McpServerConnectionStatus,
163    /// Number of tools provided by this server (0 when failed).
164    pub tool_count: usize,
165    /// Human-readable failure reason. Empty when connected.
166    pub error: String,
167}
168
169/// Bayesian confidence data for a single skill, used by TUI confidence bar.
170#[derive(Debug, Clone, Default)]
171pub struct SkillConfidence {
172    pub name: String,
173    pub posterior: f64,
174    pub total_uses: u32,
175}
176
177/// Snapshot of a single sub-agent's runtime status.
178#[derive(Debug, Clone, Default)]
179pub struct SubAgentMetrics {
180    pub id: String,
181    pub name: String,
182    /// Stringified `TaskState`: "working", "completed", "failed", "canceled", etc.
183    pub state: String,
184    pub turns_used: u32,
185    pub max_turns: u32,
186    pub background: bool,
187    pub elapsed_secs: u64,
188    /// Stringified `PermissionMode`: `"default"`, `"accept_edits"`, `"dont_ask"`,
189    /// `"bypass_permissions"`, `"plan"`. Empty string when mode is `Default`.
190    pub permission_mode: String,
191    /// Path to the directory containing this agent's JSONL transcript file.
192    /// `None` when transcript writing is disabled for this agent.
193    pub transcript_dir: Option<String>,
194}
195
196/// Per-turn latency breakdown for the four agent hot-path phases.
197///
198/// Populated with `Instant`-based measurements at each phase boundary.
199/// All values are in milliseconds.
200#[derive(Debug, Clone, Default)]
201pub struct TurnTimings {
202    pub prepare_context_ms: u64,
203    pub llm_chat_ms: u64,
204    pub tool_exec_ms: u64,
205    pub persist_message_ms: u64,
206}
207
208/// Live snapshot of agent metrics broadcast via a [`tokio::sync::watch`] channel.
209///
210/// Fields are updated at different rates: some once at startup (static), others every turn
211/// (dynamic). For fields that are known at agent startup and do not change during the session,
212/// use [`StaticMetricsInit`] and `AgentBuilder::with_static_metrics` instead of
213/// adding a raw `send_modify` call in the runner.
214#[derive(Debug, Clone, Default)]
215#[allow(clippy::struct_excessive_bools)]
216pub struct MetricsSnapshot {
217    pub prompt_tokens: u64,
218    pub completion_tokens: u64,
219    pub total_tokens: u64,
220    pub context_tokens: u64,
221    pub api_calls: u64,
222    pub active_skills: Vec<String>,
223    pub total_skills: usize,
224    /// Total configured MCP servers (connected + failed).
225    pub mcp_server_count: usize,
226    pub mcp_tool_count: usize,
227    /// Number of successfully connected MCP servers.
228    pub mcp_connected_count: usize,
229    /// Per-server connection status list.
230    pub mcp_servers: Vec<McpServerStatus>,
231    pub active_mcp_tools: Vec<String>,
232    pub sqlite_message_count: u64,
233    pub sqlite_conversation_id: Option<zeph_memory::ConversationId>,
234    pub qdrant_available: bool,
235    pub vector_backend: String,
236    pub embeddings_generated: u64,
237    pub last_llm_latency_ms: u64,
238    pub uptime_seconds: u64,
239    pub provider_name: String,
240    pub model_name: String,
241    pub summaries_count: u64,
242    pub context_compactions: u64,
243    /// Number of times the agent entered the Hard compaction tier, including cooldown-skipped
244    /// turns. Not equal to the actual LLM summarization count — reflects pressure, not action.
245    pub compaction_hard_count: u64,
246    /// User-message turns elapsed after each hard compaction event.
247    /// Entry i = turns between hard compaction i and hard compaction i+1 (or session end).
248    /// Empty when no hard compaction occurred during the session.
249    pub compaction_turns_after_hard: Vec<u64>,
250    pub compression_events: u64,
251    pub compression_tokens_saved: u64,
252    pub tool_output_prunes: u64,
253    /// Compaction probe outcomes (#1609).
254    pub compaction_probe_passes: u64,
255    /// Compaction probe soft failures (summary borderline — compaction proceeded with warning).
256    pub compaction_probe_soft_failures: u64,
257    /// Compaction probe hard failures (compaction blocked due to lossy summary).
258    pub compaction_probe_failures: u64,
259    /// Compaction probe errors (LLM/timeout — non-blocking, compaction proceeded).
260    pub compaction_probe_errors: u64,
261    /// Last compaction probe verdict. `None` before the first probe completes.
262    pub last_probe_verdict: Option<zeph_memory::ProbeVerdict>,
263    /// Last compaction probe score in [0.0, 1.0]. `None` before the first probe
264    /// completes or after an Error verdict (errors produce no score).
265    pub last_probe_score: Option<f32>,
266    /// Per-category scores from the last completed probe.
267    pub last_probe_category_scores: Option<Vec<zeph_memory::CategoryScore>>,
268    /// Configured pass threshold for the compaction probe. Used by TUI for category color-coding.
269    pub compaction_probe_threshold: f32,
270    /// Configured hard-fail threshold for the compaction probe.
271    pub compaction_probe_hard_fail_threshold: f32,
272    pub cache_read_tokens: u64,
273    pub cache_creation_tokens: u64,
274    pub cost_spent_cents: f64,
275    /// Per-provider cost breakdown, sorted by cost descending.
276    pub provider_cost_breakdown: Vec<(String, crate::cost::ProviderUsage)>,
277    pub filter_raw_tokens: u64,
278    pub filter_saved_tokens: u64,
279    pub filter_applications: u64,
280    pub filter_total_commands: u64,
281    pub filter_filtered_commands: u64,
282    pub filter_confidence_full: u64,
283    pub filter_confidence_partial: u64,
284    pub filter_confidence_fallback: u64,
285    pub cancellations: u64,
286    pub server_compaction_events: u64,
287    pub sanitizer_runs: u64,
288    pub sanitizer_injection_flags: u64,
289    /// Injection pattern hits on `ToolResult` (local) sources — likely false positives.
290    ///
291    /// Counts regex hits that fired on content from `shell`, `read_file`, `search_code`, etc.
292    /// These sources are user-owned and not adversarial; a non-zero value indicates a pattern
293    /// that needs tightening or a source reclassification.
294    pub sanitizer_injection_fp_local: u64,
295    pub sanitizer_truncations: u64,
296    pub quarantine_invocations: u64,
297    pub quarantine_failures: u64,
298    /// ML classifier hard-blocked tool outputs (`enforcement_mode=block` only).
299    pub classifier_tool_blocks: u64,
300    /// ML classifier suspicious tool outputs (both enforcement modes).
301    pub classifier_tool_suspicious: u64,
302    /// `TurnCausalAnalyzer` flags: behavioral deviation detected at tool-return boundary.
303    pub causal_ipi_flags: u64,
304    /// VIGIL pre-sanitizer flags: tool outputs matched injection patterns (any action).
305    pub vigil_flags_total: u64,
306    /// VIGIL pre-sanitizer blocks: tool outputs replaced with sentinel (`strict_mode=true`).
307    pub vigil_blocks_total: u64,
308    pub exfiltration_images_blocked: u64,
309    pub exfiltration_tool_urls_flagged: u64,
310    pub exfiltration_memory_guards: u64,
311    pub pii_scrub_count: u64,
312    /// Number of times the PII NER classifier timed out; input fell back to regex-only.
313    pub pii_ner_timeouts: u64,
314    /// Number of times the PII NER circuit breaker tripped (disabled NER for the session).
315    pub pii_ner_circuit_breaker_trips: u64,
316    pub memory_validation_failures: u64,
317    pub rate_limit_trips: u64,
318    pub pre_execution_blocks: u64,
319    pub pre_execution_warnings: u64,
320    /// `true` when a guardrail filter is active for this session.
321    pub guardrail_enabled: bool,
322    /// `true` when guardrail is in warn-only mode (action = warn).
323    pub guardrail_warn_mode: bool,
324    pub sub_agents: Vec<SubAgentMetrics>,
325    pub skill_confidence: Vec<SkillConfidence>,
326    /// Scheduled task summaries: `[name, kind, mode, next_run]`.
327    pub scheduled_tasks: Vec<[String; 4]>,
328    /// Thompson Sampling distribution snapshots: `(provider, alpha, beta)`.
329    pub router_thompson_stats: Vec<(String, f64, f64)>,
330    /// Ring buffer of recent security events (cap 100, FIFO eviction).
331    pub security_events: VecDeque<SecurityEvent>,
332    pub orchestration: OrchestrationMetrics,
333    /// Live snapshot of the currently active task graph. `None` when no plan is active.
334    pub orchestration_graph: Option<TaskGraphSnapshot>,
335    pub graph_community_detection_failures: u64,
336    pub graph_entities_total: u64,
337    pub graph_edges_total: u64,
338    pub graph_communities_total: u64,
339    pub graph_extraction_count: u64,
340    pub graph_extraction_failures: u64,
341    /// `true` when `config.llm.cloud.enable_extended_context = true`.
342    /// Never set for other providers to avoid false positives.
343    pub extended_context: bool,
344    /// Latest compression-guidelines version (0 = no guidelines yet).
345    pub guidelines_version: u32,
346    /// ISO 8601 timestamp of the latest guidelines update (empty if none).
347    pub guidelines_updated_at: String,
348    pub tool_cache_hits: u64,
349    pub tool_cache_misses: u64,
350    pub tool_cache_entries: usize,
351    /// Number of semantic-tier facts in memory (0 when tier promotion disabled).
352    pub semantic_fact_count: u64,
353    /// STT model name (e.g. "whisper-1"). `None` when STT is not configured.
354    pub stt_model: Option<String>,
355    /// Model used for context compaction/summarization. `None` when no summary provider is set.
356    pub compaction_model: Option<String>,
357    /// Temperature of the active provider when using Candle. `None` for API providers.
358    pub provider_temperature: Option<f32>,
359    /// Top-p of the active provider when using Candle. `None` for API providers.
360    pub provider_top_p: Option<f32>,
361    /// Embedding model name (e.g. `"nomic-embed-text"`). Empty when embeddings are disabled.
362    pub embedding_model: String,
363    /// Token budget for context window. `None` when not configured.
364    pub token_budget: Option<u64>,
365    /// Token threshold that triggers soft compaction. `None` when not configured.
366    pub compaction_threshold: Option<u32>,
367    /// Vault backend identifier: "age", "env", or "none".
368    pub vault_backend: String,
369    /// Active I/O channel name: `"cli"`, `"telegram"`, `"tui"`, `"discord"`, `"slack"`.
370    pub active_channel: String,
371    /// Background supervisor: inflight tasks across all classes.
372    pub bg_inflight: u64,
373    /// Background supervisor: total tasks dropped due to concurrency limit (all classes).
374    pub bg_dropped: u64,
375    /// Background supervisor: total tasks completed (all classes).
376    pub bg_completed: u64,
377    /// Background supervisor: inflight enrichment tasks.
378    pub bg_enrichment_inflight: u64,
379    /// Background supervisor: inflight telemetry tasks.
380    pub bg_telemetry_inflight: u64,
381    /// Whether self-learning (skill evolution) is enabled.
382    pub self_learning_enabled: bool,
383    /// Whether the semantic response cache is enabled.
384    pub semantic_cache_enabled: bool,
385    /// Whether semantic response caching is enabled (alias for `semantic_cache_enabled`).
386    pub cache_enabled: bool,
387    /// Whether assistant messages are auto-saved to memory.
388    pub autosave_enabled: bool,
389    /// Classifier p50/p95 latency metrics per task (injection, pii, feedback).
390    pub classifier: ClassifierMetricsSnapshot,
391    /// Latency breakdown for the most recently completed agent turn.
392    pub last_turn_timings: TurnTimings,
393    /// Rolling average of per-phase latency over the last 10 turns.
394    pub avg_turn_timings: TurnTimings,
395    /// Maximum per-phase latency observed within the rolling window (tail-latency visibility).
396    ///
397    /// M3: exposes `max_in_window` alongside the rolling average for operational monitoring.
398    pub max_turn_timings: TurnTimings,
399    /// Number of turns included in `avg_turn_timings` and `max_turn_timings` (capped at 10).
400    pub timing_sample_count: u64,
401    /// Total egress (outbound HTTP) requests attempted this session.
402    pub egress_requests_total: u64,
403    /// Egress events dropped due to bounded channel backpressure.
404    pub egress_dropped_total: u64,
405    /// Egress requests blocked by scheme/domain/SSRF policy.
406    pub egress_blocked_total: u64,
407}
408
409/// Configuration-derived fields of [`MetricsSnapshot`] that are known at agent startup and do
410/// not change during the session.
411///
412/// Pass this struct to `AgentBuilder::with_static_metrics` immediately after
413/// `AgentBuilder::with_metrics` to initialize all static fields in one place rather than
414/// through scattered `send_modify` calls in the runner.
415///
416/// # Examples
417///
418/// ```no_run
419/// use zeph_core::metrics::StaticMetricsInit;
420///
421/// let init = StaticMetricsInit {
422///     active_channel: "cli".to_owned(),
423///     ..StaticMetricsInit::default()
424/// };
425/// ```
426#[derive(Debug, Default)]
427pub struct StaticMetricsInit {
428    /// STT model name (e.g. `"whisper-1"`). `None` when STT is not configured.
429    pub stt_model: Option<String>,
430    /// Model used for context compaction/summarization. `None` when no summary provider is set.
431    pub compaction_model: Option<String>,
432    /// Whether the semantic response cache is enabled.
433    ///
434    /// This value is also written to [`MetricsSnapshot::cache_enabled`] which is an alias for the
435    /// same concept.
436    pub semantic_cache_enabled: bool,
437    /// Embedding model name (e.g. `"nomic-embed-text"`). Empty when embeddings are disabled.
438    pub embedding_model: String,
439    /// Whether self-learning (skill evolution) is enabled.
440    pub self_learning_enabled: bool,
441    /// Active I/O channel name: `"cli"`, `"telegram"`, `"tui"`, `"discord"`, `"slack"`.
442    pub active_channel: String,
443    /// Token budget for context window. `None` when not configured.
444    pub token_budget: Option<u64>,
445    /// Token threshold that triggers soft compaction. `None` when not configured.
446    pub compaction_threshold: Option<u32>,
447    /// Vault backend identifier: `"age"`, `"env"`, or `"none"`.
448    pub vault_backend: String,
449    /// Whether assistant messages are auto-saved to memory.
450    pub autosave_enabled: bool,
451    /// Override for the active model name. When `Some`, replaces the model name set by the
452    /// builder from `runtime.model_name` (which may be a placeholder) with the effective model
453    /// resolved from the LLM provider configuration.
454    pub model_name_override: Option<String>,
455}
456
457/// Strip ASCII control characters and ANSI escape sequences from a string for safe TUI display.
458///
459/// Allows tab, LF, and CR; removes everything else in the `0x00–0x1F` range including full
460/// ANSI CSI sequences (`ESC[...`). This prevents escape-sequence injection from LLM planner
461/// output into the TUI.
462fn strip_ctrl(s: &str) -> String {
463    let mut out = String::with_capacity(s.len());
464    let mut chars = s.chars().peekable();
465    while let Some(c) = chars.next() {
466        if c == '\x1b' {
467            // Consume an ANSI CSI sequence: ESC [ <params> <final-byte in 0x40–0x7E>
468            if chars.peek() == Some(&'[') {
469                chars.next(); // consume '['
470                for inner in chars.by_ref() {
471                    if ('\x40'..='\x7e').contains(&inner) {
472                        break;
473                    }
474                }
475            }
476            // Drop ESC and any consumed sequence — write nothing.
477        } else if c.is_control() && c != '\t' && c != '\n' && c != '\r' {
478            // drop other control chars
479        } else {
480            out.push(c);
481        }
482    }
483    out
484}
485
486/// Convert a live `TaskGraph` into a lightweight snapshot for TUI display.
487impl From<&zeph_orchestration::TaskGraph> for TaskGraphSnapshot {
488    fn from(graph: &zeph_orchestration::TaskGraph) -> Self {
489        let tasks = graph
490            .tasks
491            .iter()
492            .map(|t| {
493                let error = t
494                    .result
495                    .as_ref()
496                    .filter(|_| t.status == zeph_orchestration::TaskStatus::Failed)
497                    .and_then(|r| {
498                        if r.output.is_empty() {
499                            None
500                        } else {
501                            // Strip control chars, then truncate at 80 chars (SEC-P6-01).
502                            let s = strip_ctrl(&r.output);
503                            if s.len() > 80 {
504                                let end = s.floor_char_boundary(79);
505                                Some(format!("{}…", &s[..end]))
506                            } else {
507                                Some(s)
508                            }
509                        }
510                    });
511                let duration_ms = t.result.as_ref().map_or(0, |r| r.duration_ms);
512                TaskSnapshotRow {
513                    id: t.id.as_u32(),
514                    title: strip_ctrl(&t.title),
515                    status: t.status.to_string(),
516                    agent: t.assigned_agent.as_deref().map(strip_ctrl),
517                    duration_ms,
518                    error,
519                }
520            })
521            .collect();
522        Self {
523            graph_id: graph.id.to_string(),
524            goal: strip_ctrl(&graph.goal),
525            status: graph.status.to_string(),
526            tasks,
527            completed_at: None,
528        }
529    }
530}
531
532pub struct MetricsCollector {
533    tx: watch::Sender<MetricsSnapshot>,
534}
535
536impl MetricsCollector {
537    #[must_use]
538    pub fn new() -> (Self, watch::Receiver<MetricsSnapshot>) {
539        let (tx, rx) = watch::channel(MetricsSnapshot::default());
540        (Self { tx }, rx)
541    }
542
543    pub fn update(&self, f: impl FnOnce(&mut MetricsSnapshot)) {
544        self.tx.send_modify(f);
545    }
546
547    /// Returns a clone of the underlying [`watch::Sender`].
548    ///
549    /// Use this to pass the sender to code that requires a raw
550    /// `watch::Sender<MetricsSnapshot>` while the [`MetricsCollector`] is
551    /// also shared (e.g., passed to a `MetricsBridge` layer).
552    #[must_use]
553    pub fn sender(&self) -> watch::Sender<MetricsSnapshot> {
554        self.tx.clone()
555    }
556}
557
558// ---------------------------------------------------------------------------
559// HistogramRecorder
560// ---------------------------------------------------------------------------
561
562/// Per-event histogram recording contract for the agent loop.
563///
564/// Implementors record individual latency observations into Prometheus histograms
565/// (or any other backend). The trait is object-safe: the agent stores an
566/// `Option<Arc<dyn HistogramRecorder>>` and calls these methods at each measurement
567/// point. When `None`, recording is a no-op with zero overhead.
568///
569/// # Contract for implementors
570///
571/// - All methods must be non-blocking; they must not call async code or acquire
572///   mutexes that may block.
573/// - Implementations must be `Send + Sync` — the agent loop runs on the tokio
574///   thread pool and the recorder may be called from multiple tasks.
575///
576/// # Examples
577///
578/// ```rust
579/// use std::sync::Arc;
580/// use std::time::Duration;
581/// use zeph_core::metrics::HistogramRecorder;
582///
583/// struct NoOpRecorder;
584///
585/// impl HistogramRecorder for NoOpRecorder {
586///     fn observe_llm_latency(&self, _: Duration) {}
587///     fn observe_turn_duration(&self, _: Duration) {}
588///     fn observe_tool_execution(&self, _: Duration) {}
589///     fn observe_bg_task(&self, _: &str, _: Duration) {}
590/// }
591///
592/// let recorder: Arc<dyn HistogramRecorder> = Arc::new(NoOpRecorder);
593/// recorder.observe_llm_latency(Duration::from_millis(500));
594/// ```
595pub trait HistogramRecorder: Send + Sync {
596    /// Record a single LLM API call latency observation.
597    fn observe_llm_latency(&self, duration: std::time::Duration);
598
599    /// Record a full agent turn duration observation (context prep + LLM + tools + persist).
600    fn observe_turn_duration(&self, duration: std::time::Duration);
601
602    /// Record a single tool execution latency observation.
603    fn observe_tool_execution(&self, duration: std::time::Duration);
604
605    /// Record a background task completion latency.
606    ///
607    /// `class_label` is `"enrichment"` or `"telemetry"` (from `TaskClass::name()`).
608    fn observe_bg_task(&self, class_label: &str, duration: std::time::Duration);
609}
610
611#[cfg(test)]
612mod tests {
613    #![allow(clippy::field_reassign_with_default)]
614
615    use super::*;
616
617    #[test]
618    fn default_metrics_snapshot() {
619        let m = MetricsSnapshot::default();
620        assert_eq!(m.total_tokens, 0);
621        assert_eq!(m.api_calls, 0);
622        assert!(m.active_skills.is_empty());
623        assert!(m.active_mcp_tools.is_empty());
624        assert_eq!(m.mcp_tool_count, 0);
625        assert_eq!(m.mcp_server_count, 0);
626        assert!(m.provider_name.is_empty());
627        assert_eq!(m.summaries_count, 0);
628        // Phase 2 fields
629        assert!(m.stt_model.is_none());
630        assert!(m.compaction_model.is_none());
631        assert!(m.provider_temperature.is_none());
632        assert!(m.provider_top_p.is_none());
633        assert!(m.active_channel.is_empty());
634        assert!(m.embedding_model.is_empty());
635        assert!(m.token_budget.is_none());
636        assert!(!m.self_learning_enabled);
637        assert!(!m.semantic_cache_enabled);
638    }
639
640    #[test]
641    fn metrics_collector_update_phase2_fields() {
642        let (collector, rx) = MetricsCollector::new();
643        collector.update(|m| {
644            m.stt_model = Some("whisper-1".into());
645            m.compaction_model = Some("haiku".into());
646            m.provider_temperature = Some(0.7);
647            m.provider_top_p = Some(0.95);
648            m.active_channel = "tui".into();
649            m.embedding_model = "nomic-embed-text".into();
650            m.token_budget = Some(200_000);
651            m.self_learning_enabled = true;
652            m.semantic_cache_enabled = true;
653        });
654        let s = rx.borrow();
655        assert_eq!(s.stt_model.as_deref(), Some("whisper-1"));
656        assert_eq!(s.compaction_model.as_deref(), Some("haiku"));
657        assert_eq!(s.provider_temperature, Some(0.7));
658        assert_eq!(s.provider_top_p, Some(0.95));
659        assert_eq!(s.active_channel, "tui");
660        assert_eq!(s.embedding_model, "nomic-embed-text");
661        assert_eq!(s.token_budget, Some(200_000));
662        assert!(s.self_learning_enabled);
663        assert!(s.semantic_cache_enabled);
664    }
665
666    #[test]
667    fn metrics_collector_update() {
668        let (collector, rx) = MetricsCollector::new();
669        collector.update(|m| {
670            m.api_calls = 5;
671            m.total_tokens = 1000;
672        });
673        let snapshot = rx.borrow().clone();
674        assert_eq!(snapshot.api_calls, 5);
675        assert_eq!(snapshot.total_tokens, 1000);
676    }
677
678    #[test]
679    fn metrics_collector_multiple_updates() {
680        let (collector, rx) = MetricsCollector::new();
681        collector.update(|m| m.api_calls = 1);
682        collector.update(|m| m.api_calls += 1);
683        assert_eq!(rx.borrow().api_calls, 2);
684    }
685
686    #[test]
687    fn metrics_snapshot_clone() {
688        let mut m = MetricsSnapshot::default();
689        m.provider_name = "ollama".into();
690        let cloned = m.clone();
691        assert_eq!(cloned.provider_name, "ollama");
692    }
693
694    #[test]
695    fn filter_metrics_tracking() {
696        let (collector, rx) = MetricsCollector::new();
697        collector.update(|m| {
698            m.filter_raw_tokens += 250;
699            m.filter_saved_tokens += 200;
700            m.filter_applications += 1;
701        });
702        collector.update(|m| {
703            m.filter_raw_tokens += 100;
704            m.filter_saved_tokens += 80;
705            m.filter_applications += 1;
706        });
707        let s = rx.borrow();
708        assert_eq!(s.filter_raw_tokens, 350);
709        assert_eq!(s.filter_saved_tokens, 280);
710        assert_eq!(s.filter_applications, 2);
711    }
712
713    #[test]
714    fn filter_confidence_and_command_metrics() {
715        let (collector, rx) = MetricsCollector::new();
716        collector.update(|m| {
717            m.filter_total_commands += 1;
718            m.filter_filtered_commands += 1;
719            m.filter_confidence_full += 1;
720        });
721        collector.update(|m| {
722            m.filter_total_commands += 1;
723            m.filter_confidence_partial += 1;
724        });
725        let s = rx.borrow();
726        assert_eq!(s.filter_total_commands, 2);
727        assert_eq!(s.filter_filtered_commands, 1);
728        assert_eq!(s.filter_confidence_full, 1);
729        assert_eq!(s.filter_confidence_partial, 1);
730        assert_eq!(s.filter_confidence_fallback, 0);
731    }
732
733    #[test]
734    fn summaries_count_tracks_summarizations() {
735        let (collector, rx) = MetricsCollector::new();
736        collector.update(|m| m.summaries_count += 1);
737        collector.update(|m| m.summaries_count += 1);
738        assert_eq!(rx.borrow().summaries_count, 2);
739    }
740
741    #[test]
742    fn cancellations_counter_increments() {
743        let (collector, rx) = MetricsCollector::new();
744        assert_eq!(rx.borrow().cancellations, 0);
745        collector.update(|m| m.cancellations += 1);
746        collector.update(|m| m.cancellations += 1);
747        assert_eq!(rx.borrow().cancellations, 2);
748    }
749
750    #[test]
751    fn security_event_detail_exact_128_not_truncated() {
752        let s = "a".repeat(128);
753        let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, "src", s.clone());
754        assert_eq!(ev.detail, s, "128-char string must not be truncated");
755    }
756
757    #[test]
758    fn security_event_detail_129_is_truncated() {
759        let s = "a".repeat(129);
760        let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, "src", s);
761        assert!(
762            ev.detail.ends_with('…'),
763            "129-char string must end with ellipsis"
764        );
765        assert!(
766            ev.detail.len() <= 130,
767            "truncated detail must be at most 130 bytes"
768        );
769    }
770
771    #[test]
772    fn security_event_detail_multibyte_utf8_no_panic() {
773        // Each '中' is 3 bytes. 43 chars = 129 bytes — triggers truncation at a multi-byte boundary.
774        let s = "中".repeat(43);
775        let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, "src", s);
776        assert!(ev.detail.ends_with('…'));
777    }
778
779    #[test]
780    fn security_event_source_capped_at_64_chars() {
781        let long_source = "x".repeat(200);
782        let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, long_source, "detail");
783        assert_eq!(ev.source.len(), 64);
784    }
785
786    #[test]
787    fn security_event_source_strips_control_chars() {
788        let source = "tool\x00name\x1b[31m";
789        let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, source, "detail");
790        assert!(!ev.source.contains('\x00'));
791        assert!(!ev.source.contains('\x1b'));
792    }
793
794    #[test]
795    fn security_event_category_as_str() {
796        assert_eq!(SecurityEventCategory::InjectionFlag.as_str(), "injection");
797        assert_eq!(SecurityEventCategory::ExfiltrationBlock.as_str(), "exfil");
798        assert_eq!(SecurityEventCategory::Quarantine.as_str(), "quarantine");
799        assert_eq!(SecurityEventCategory::Truncation.as_str(), "truncation");
800        assert_eq!(
801            SecurityEventCategory::CrossBoundaryMcpToAcp.as_str(),
802            "cross_boundary_mcp_to_acp"
803        );
804    }
805
806    #[test]
807    fn ring_buffer_respects_cap_via_update() {
808        let (collector, rx) = MetricsCollector::new();
809        for i in 0..110u64 {
810            let event = SecurityEvent::new(
811                SecurityEventCategory::InjectionFlag,
812                "src",
813                format!("event {i}"),
814            );
815            collector.update(|m| {
816                if m.security_events.len() >= SECURITY_EVENT_CAP {
817                    m.security_events.pop_front();
818                }
819                m.security_events.push_back(event);
820            });
821        }
822        let snap = rx.borrow();
823        assert_eq!(snap.security_events.len(), SECURITY_EVENT_CAP);
824        // FIFO: earliest events evicted, last one present
825        assert!(snap.security_events.back().unwrap().detail.contains("109"));
826    }
827
828    #[test]
829    fn security_events_empty_by_default() {
830        let m = MetricsSnapshot::default();
831        assert!(m.security_events.is_empty());
832    }
833
834    #[test]
835    fn orchestration_metrics_default_zero() {
836        let m = OrchestrationMetrics::default();
837        assert_eq!(m.plans_total, 0);
838        assert_eq!(m.tasks_total, 0);
839        assert_eq!(m.tasks_completed, 0);
840        assert_eq!(m.tasks_failed, 0);
841        assert_eq!(m.tasks_skipped, 0);
842    }
843
844    #[test]
845    fn metrics_snapshot_includes_orchestration_default_zero() {
846        let m = MetricsSnapshot::default();
847        assert_eq!(m.orchestration.plans_total, 0);
848        assert_eq!(m.orchestration.tasks_total, 0);
849        assert_eq!(m.orchestration.tasks_completed, 0);
850    }
851
852    #[test]
853    fn orchestration_metrics_update_via_collector() {
854        let (collector, rx) = MetricsCollector::new();
855        collector.update(|m| {
856            m.orchestration.plans_total += 1;
857            m.orchestration.tasks_total += 5;
858            m.orchestration.tasks_completed += 3;
859            m.orchestration.tasks_failed += 1;
860            m.orchestration.tasks_skipped += 1;
861        });
862        let s = rx.borrow();
863        assert_eq!(s.orchestration.plans_total, 1);
864        assert_eq!(s.orchestration.tasks_total, 5);
865        assert_eq!(s.orchestration.tasks_completed, 3);
866        assert_eq!(s.orchestration.tasks_failed, 1);
867        assert_eq!(s.orchestration.tasks_skipped, 1);
868    }
869
870    #[test]
871    fn strip_ctrl_removes_escape_sequences() {
872        let input = "hello\x1b[31mworld\x00end";
873        let result = strip_ctrl(input);
874        assert_eq!(result, "helloworldend");
875    }
876
877    #[test]
878    fn strip_ctrl_allows_tab_lf_cr() {
879        let input = "a\tb\nc\rd";
880        let result = strip_ctrl(input);
881        assert_eq!(result, "a\tb\nc\rd");
882    }
883
884    #[test]
885    fn task_graph_snapshot_is_stale_after_30s() {
886        let mut snap = TaskGraphSnapshot::default();
887        // Not stale if no completed_at.
888        assert!(!snap.is_stale());
889        // Not stale if just completed.
890        snap.completed_at = Some(std::time::Instant::now());
891        assert!(!snap.is_stale());
892        // Stale if completed more than 30s ago.
893        snap.completed_at = Some(
894            std::time::Instant::now()
895                .checked_sub(std::time::Duration::from_secs(31))
896                .unwrap(),
897        );
898        assert!(snap.is_stale());
899    }
900
901    // T1: From<&TaskGraph> correctly maps fields including duration_ms and error truncation.
902    #[test]
903    fn task_graph_snapshot_from_task_graph_maps_fields() {
904        use zeph_orchestration::{GraphStatus, TaskGraph, TaskNode, TaskResult, TaskStatus};
905
906        let mut graph = TaskGraph::new("My goal");
907        let mut task = TaskNode::new(0, "Do work", "description");
908        task.status = TaskStatus::Failed;
909        task.assigned_agent = Some("agent-1".into());
910        task.result = Some(TaskResult {
911            output: "error occurred here".into(),
912            artifacts: vec![],
913            duration_ms: 1234,
914            agent_id: None,
915            agent_def: None,
916        });
917        graph.tasks.push(task);
918        graph.status = GraphStatus::Failed;
919
920        let snap = TaskGraphSnapshot::from(&graph);
921        assert_eq!(snap.goal, "My goal");
922        assert_eq!(snap.status, "failed");
923        assert_eq!(snap.tasks.len(), 1);
924        let row = &snap.tasks[0];
925        assert_eq!(row.title, "Do work");
926        assert_eq!(row.status, "failed");
927        assert_eq!(row.agent.as_deref(), Some("agent-1"));
928        assert_eq!(row.duration_ms, 1234);
929        assert!(row.error.as_deref().unwrap().contains("error occurred"));
930    }
931
932    // T2: From impl compiles with orchestration feature active.
933    #[test]
934    fn task_graph_snapshot_from_compiles_with_feature() {
935        use zeph_orchestration::TaskGraph;
936        let graph = TaskGraph::new("feature flag test");
937        let snap = TaskGraphSnapshot::from(&graph);
938        assert_eq!(snap.goal, "feature flag test");
939        assert!(snap.tasks.is_empty());
940        assert!(!snap.is_stale());
941    }
942
943    // T1-extra: long error is truncated with ellipsis.
944    #[test]
945    fn task_graph_snapshot_error_truncated_at_80_chars() {
946        use zeph_orchestration::{TaskGraph, TaskNode, TaskResult, TaskStatus};
947
948        let mut graph = TaskGraph::new("goal");
949        let mut task = TaskNode::new(0, "t", "d");
950        task.status = TaskStatus::Failed;
951        task.result = Some(TaskResult {
952            output: "e".repeat(100),
953            artifacts: vec![],
954            duration_ms: 0,
955            agent_id: None,
956            agent_def: None,
957        });
958        graph.tasks.push(task);
959
960        let snap = TaskGraphSnapshot::from(&graph);
961        let err = snap.tasks[0].error.as_ref().unwrap();
962        assert!(err.ends_with('…'), "truncated error must end with ellipsis");
963        assert!(
964            err.len() <= 83,
965            "truncated error must not exceed 80 chars + ellipsis"
966        );
967    }
968
969    // SEC-P6-01: control chars in task title are stripped.
970    #[test]
971    fn task_graph_snapshot_strips_control_chars_from_title() {
972        use zeph_orchestration::{TaskGraph, TaskNode};
973
974        let mut graph = TaskGraph::new("goal\x1b[31m");
975        let task = TaskNode::new(0, "title\x00injected", "d");
976        graph.tasks.push(task);
977
978        let snap = TaskGraphSnapshot::from(&graph);
979        assert!(!snap.goal.contains('\x1b'), "goal must not contain escape");
980        assert!(
981            !snap.tasks[0].title.contains('\x00'),
982            "title must not contain null byte"
983        );
984    }
985
986    #[test]
987    fn graph_metrics_default_zero() {
988        let m = MetricsSnapshot::default();
989        assert_eq!(m.graph_entities_total, 0);
990        assert_eq!(m.graph_edges_total, 0);
991        assert_eq!(m.graph_communities_total, 0);
992        assert_eq!(m.graph_extraction_count, 0);
993        assert_eq!(m.graph_extraction_failures, 0);
994    }
995
996    #[test]
997    fn graph_metrics_update_via_collector() {
998        let (collector, rx) = MetricsCollector::new();
999        collector.update(|m| {
1000            m.graph_entities_total = 5;
1001            m.graph_edges_total = 10;
1002            m.graph_communities_total = 2;
1003            m.graph_extraction_count = 7;
1004            m.graph_extraction_failures = 1;
1005        });
1006        let snapshot = rx.borrow().clone();
1007        assert_eq!(snapshot.graph_entities_total, 5);
1008        assert_eq!(snapshot.graph_edges_total, 10);
1009        assert_eq!(snapshot.graph_communities_total, 2);
1010        assert_eq!(snapshot.graph_extraction_count, 7);
1011        assert_eq!(snapshot.graph_extraction_failures, 1);
1012    }
1013
1014    #[test]
1015    fn histogram_recorder_trait_is_object_safe() {
1016        use std::sync::Arc;
1017        use std::time::Duration;
1018
1019        struct NoOpRecorder;
1020        impl HistogramRecorder for NoOpRecorder {
1021            fn observe_llm_latency(&self, _: Duration) {}
1022            fn observe_turn_duration(&self, _: Duration) {}
1023            fn observe_tool_execution(&self, _: Duration) {}
1024            fn observe_bg_task(&self, _: &str, _: Duration) {}
1025        }
1026
1027        // Verify the trait can be used as a trait object (object-safe).
1028        let recorder: Arc<dyn HistogramRecorder> = Arc::new(NoOpRecorder);
1029        recorder.observe_llm_latency(Duration::from_millis(500));
1030        recorder.observe_turn_duration(Duration::from_secs(3));
1031        recorder.observe_tool_execution(Duration::from_millis(100));
1032    }
1033}