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