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