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
8/// Category of a security event for TUI display.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum SecurityEventCategory {
11    InjectionFlag,
12    ExfiltrationBlock,
13    Quarantine,
14    Truncation,
15}
16
17impl SecurityEventCategory {
18    #[must_use]
19    pub fn as_str(self) -> &'static str {
20        match self {
21            Self::InjectionFlag => "injection",
22            Self::ExfiltrationBlock => "exfil",
23            Self::Quarantine => "quarantine",
24            Self::Truncation => "truncation",
25        }
26    }
27}
28
29/// A single security event record for TUI display.
30#[derive(Debug, Clone)]
31pub struct SecurityEvent {
32    /// Unix timestamp (seconds since epoch).
33    pub timestamp: u64,
34    pub category: SecurityEventCategory,
35    /// Source that triggered the event (e.g., `web_scrape`, `mcp_response`).
36    pub source: String,
37    /// Short description, capped at 128 chars.
38    pub detail: String,
39}
40
41impl SecurityEvent {
42    #[must_use]
43    pub fn new(
44        category: SecurityEventCategory,
45        source: impl Into<String>,
46        detail: impl Into<String>,
47    ) -> Self {
48        // IMP-1: cap source at 64 chars and strip ASCII control chars.
49        let source: String = source
50            .into()
51            .chars()
52            .filter(|c| !c.is_ascii_control())
53            .take(64)
54            .collect();
55        // CR-1: UTF-8 safe truncation using floor_char_boundary (stable since Rust 1.82).
56        let detail = detail.into();
57        let detail = if detail.len() > 128 {
58            let end = detail.floor_char_boundary(127);
59            format!("{}…", &detail[..end])
60        } else {
61            detail
62        };
63        Self {
64            timestamp: std::time::SystemTime::now()
65                .duration_since(std::time::UNIX_EPOCH)
66                .unwrap_or_default()
67                .as_secs(),
68            category,
69            source,
70            detail,
71        }
72    }
73}
74
75/// Ring buffer capacity for security events.
76pub const SECURITY_EVENT_CAP: usize = 100;
77
78/// Lightweight snapshot of a single task row for TUI display.
79///
80/// Cloned from [`TaskGraph`] on each metrics tick; kept minimal on purpose.
81#[derive(Debug, Clone)]
82pub struct TaskSnapshotRow {
83    pub id: u32,
84    pub title: String,
85    /// Stringified `TaskStatus` (e.g. `"pending"`, `"running"`, `"completed"`).
86    pub status: String,
87    pub agent: Option<String>,
88    pub duration_ms: u64,
89    /// Truncated error message (first 80 chars) when the task failed.
90    pub error: Option<String>,
91}
92
93/// Lightweight snapshot of a `TaskGraph` for TUI display.
94#[derive(Debug, Clone, Default)]
95pub struct TaskGraphSnapshot {
96    pub graph_id: String,
97    pub goal: String,
98    /// Stringified `GraphStatus` (e.g. `"created"`, `"running"`, `"completed"`).
99    pub status: String,
100    pub tasks: Vec<TaskSnapshotRow>,
101    pub completed_at: Option<std::time::Instant>,
102}
103
104impl TaskGraphSnapshot {
105    /// Returns `true` if this snapshot represents a terminal plan that finished
106    /// more than 30 seconds ago and should no longer be shown in the TUI.
107    #[must_use]
108    pub fn is_stale(&self) -> bool {
109        self.completed_at
110            .is_some_and(|t| t.elapsed().as_secs() > 30)
111    }
112}
113
114/// Counters for the task orchestration subsystem.
115///
116/// Always present in [`MetricsSnapshot`]; zero-valued when orchestration is inactive.
117#[derive(Debug, Clone, Default)]
118pub struct OrchestrationMetrics {
119    pub plans_total: u64,
120    pub tasks_total: u64,
121    pub tasks_completed: u64,
122    pub tasks_failed: u64,
123    pub tasks_skipped: u64,
124}
125
126/// Bayesian confidence data for a single skill, used by TUI confidence bar.
127#[derive(Debug, Clone, Default)]
128pub struct SkillConfidence {
129    pub name: String,
130    pub posterior: f64,
131    pub total_uses: u32,
132}
133
134/// Snapshot of a single sub-agent's runtime status.
135#[derive(Debug, Clone, Default)]
136pub struct SubAgentMetrics {
137    pub id: String,
138    pub name: String,
139    /// Stringified `TaskState`: "working", "completed", "failed", "canceled", etc.
140    pub state: String,
141    pub turns_used: u32,
142    pub max_turns: u32,
143    pub background: bool,
144    pub elapsed_secs: u64,
145    /// Stringified `PermissionMode`: `"default"`, `"accept_edits"`, `"dont_ask"`,
146    /// `"bypass_permissions"`, `"plan"`. Empty string when mode is `Default`.
147    pub permission_mode: String,
148}
149
150#[derive(Debug, Clone, Default)]
151pub struct MetricsSnapshot {
152    pub prompt_tokens: u64,
153    pub completion_tokens: u64,
154    pub total_tokens: u64,
155    pub context_tokens: u64,
156    pub api_calls: u64,
157    pub active_skills: Vec<String>,
158    pub total_skills: usize,
159    pub mcp_server_count: usize,
160    pub mcp_tool_count: usize,
161    pub active_mcp_tools: Vec<String>,
162    pub sqlite_message_count: u64,
163    pub sqlite_conversation_id: Option<zeph_memory::ConversationId>,
164    pub qdrant_available: bool,
165    pub vector_backend: String,
166    pub embeddings_generated: u64,
167    pub last_llm_latency_ms: u64,
168    pub uptime_seconds: u64,
169    pub provider_name: String,
170    pub model_name: String,
171    pub summaries_count: u64,
172    pub context_compactions: u64,
173    pub compression_events: u64,
174    pub compression_tokens_saved: u64,
175    pub tool_output_prunes: u64,
176    pub cache_read_tokens: u64,
177    pub cache_creation_tokens: u64,
178    pub cost_spent_cents: f64,
179    pub filter_raw_tokens: u64,
180    pub filter_saved_tokens: u64,
181    pub filter_applications: u64,
182    pub filter_total_commands: u64,
183    pub filter_filtered_commands: u64,
184    pub filter_confidence_full: u64,
185    pub filter_confidence_partial: u64,
186    pub filter_confidence_fallback: u64,
187    pub cancellations: u64,
188    pub sanitizer_runs: u64,
189    pub sanitizer_injection_flags: u64,
190    pub sanitizer_truncations: u64,
191    pub quarantine_invocations: u64,
192    pub quarantine_failures: u64,
193    pub exfiltration_images_blocked: u64,
194    pub exfiltration_tool_urls_flagged: u64,
195    pub exfiltration_memory_guards: u64,
196    pub sub_agents: Vec<SubAgentMetrics>,
197    pub skill_confidence: Vec<SkillConfidence>,
198    /// Scheduled task summaries: `[name, kind, mode, next_run]`.
199    pub scheduled_tasks: Vec<[String; 4]>,
200    /// Thompson Sampling distribution snapshots: `(provider, alpha, beta)`.
201    pub router_thompson_stats: Vec<(String, f64, f64)>,
202    /// Ring buffer of recent security events (cap 100, FIFO eviction).
203    pub security_events: VecDeque<SecurityEvent>,
204    pub orchestration: OrchestrationMetrics,
205    /// Live snapshot of the currently active task graph. `None` when no plan is active.
206    pub orchestration_graph: Option<TaskGraphSnapshot>,
207    pub graph_community_detection_failures: u64,
208    pub graph_entities_total: u64,
209    pub graph_edges_total: u64,
210    pub graph_communities_total: u64,
211    pub graph_extraction_count: u64,
212    pub graph_extraction_failures: u64,
213}
214
215/// Strip ASCII control characters and ANSI escape sequences from a string for safe TUI display.
216///
217/// Allows tab, LF, and CR; removes everything else in the `0x00–0x1F` range including full
218/// ANSI CSI sequences (`ESC[...`). This prevents escape-sequence injection from LLM planner
219/// output into the TUI.
220fn strip_ctrl(s: &str) -> String {
221    let mut out = String::with_capacity(s.len());
222    let mut chars = s.chars().peekable();
223    while let Some(c) = chars.next() {
224        if c == '\x1b' {
225            // Consume an ANSI CSI sequence: ESC [ <params> <final-byte in 0x40–0x7E>
226            if chars.peek() == Some(&'[') {
227                chars.next(); // consume '['
228                for inner in chars.by_ref() {
229                    if ('\x40'..='\x7e').contains(&inner) {
230                        break;
231                    }
232                }
233            }
234            // Drop ESC and any consumed sequence — write nothing.
235        } else if c.is_control() && c != '\t' && c != '\n' && c != '\r' {
236            // drop other control chars
237        } else {
238            out.push(c);
239        }
240    }
241    out
242}
243
244/// Convert a live `TaskGraph` into a lightweight snapshot for TUI display.
245impl From<&crate::orchestration::TaskGraph> for TaskGraphSnapshot {
246    fn from(graph: &crate::orchestration::TaskGraph) -> Self {
247        let tasks = graph
248            .tasks
249            .iter()
250            .map(|t| {
251                let error = t
252                    .result
253                    .as_ref()
254                    .filter(|_| t.status == crate::orchestration::TaskStatus::Failed)
255                    .and_then(|r| {
256                        if r.output.is_empty() {
257                            None
258                        } else {
259                            // Strip control chars, then truncate at 80 chars (SEC-P6-01).
260                            let s = strip_ctrl(&r.output);
261                            if s.len() > 80 {
262                                let end = s.floor_char_boundary(79);
263                                Some(format!("{}…", &s[..end]))
264                            } else {
265                                Some(s)
266                            }
267                        }
268                    });
269                let duration_ms = t.result.as_ref().map_or(0, |r| r.duration_ms);
270                TaskSnapshotRow {
271                    id: t.id.0,
272                    title: strip_ctrl(&t.title),
273                    status: t.status.to_string(),
274                    agent: t.assigned_agent.as_deref().map(strip_ctrl),
275                    duration_ms,
276                    error,
277                }
278            })
279            .collect();
280        Self {
281            graph_id: graph.id.to_string(),
282            goal: strip_ctrl(&graph.goal),
283            status: graph.status.to_string(),
284            tasks,
285            completed_at: None,
286        }
287    }
288}
289
290pub struct MetricsCollector {
291    tx: watch::Sender<MetricsSnapshot>,
292}
293
294impl MetricsCollector {
295    #[must_use]
296    pub fn new() -> (Self, watch::Receiver<MetricsSnapshot>) {
297        let (tx, rx) = watch::channel(MetricsSnapshot::default());
298        (Self { tx }, rx)
299    }
300
301    pub fn update(&self, f: impl FnOnce(&mut MetricsSnapshot)) {
302        self.tx.send_modify(f);
303    }
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309
310    #[test]
311    fn default_metrics_snapshot() {
312        let m = MetricsSnapshot::default();
313        assert_eq!(m.total_tokens, 0);
314        assert_eq!(m.api_calls, 0);
315        assert!(m.active_skills.is_empty());
316        assert!(m.active_mcp_tools.is_empty());
317        assert_eq!(m.mcp_tool_count, 0);
318        assert_eq!(m.mcp_server_count, 0);
319        assert!(m.provider_name.is_empty());
320        assert_eq!(m.summaries_count, 0);
321    }
322
323    #[test]
324    fn metrics_collector_update() {
325        let (collector, rx) = MetricsCollector::new();
326        collector.update(|m| {
327            m.api_calls = 5;
328            m.total_tokens = 1000;
329        });
330        let snapshot = rx.borrow().clone();
331        assert_eq!(snapshot.api_calls, 5);
332        assert_eq!(snapshot.total_tokens, 1000);
333    }
334
335    #[test]
336    fn metrics_collector_multiple_updates() {
337        let (collector, rx) = MetricsCollector::new();
338        collector.update(|m| m.api_calls = 1);
339        collector.update(|m| m.api_calls += 1);
340        assert_eq!(rx.borrow().api_calls, 2);
341    }
342
343    #[test]
344    fn metrics_snapshot_clone() {
345        let mut m = MetricsSnapshot::default();
346        m.provider_name = "ollama".into();
347        let cloned = m.clone();
348        assert_eq!(cloned.provider_name, "ollama");
349    }
350
351    #[test]
352    fn filter_metrics_tracking() {
353        let (collector, rx) = MetricsCollector::new();
354        collector.update(|m| {
355            m.filter_raw_tokens += 250;
356            m.filter_saved_tokens += 200;
357            m.filter_applications += 1;
358        });
359        collector.update(|m| {
360            m.filter_raw_tokens += 100;
361            m.filter_saved_tokens += 80;
362            m.filter_applications += 1;
363        });
364        let s = rx.borrow();
365        assert_eq!(s.filter_raw_tokens, 350);
366        assert_eq!(s.filter_saved_tokens, 280);
367        assert_eq!(s.filter_applications, 2);
368    }
369
370    #[test]
371    fn filter_confidence_and_command_metrics() {
372        let (collector, rx) = MetricsCollector::new();
373        collector.update(|m| {
374            m.filter_total_commands += 1;
375            m.filter_filtered_commands += 1;
376            m.filter_confidence_full += 1;
377        });
378        collector.update(|m| {
379            m.filter_total_commands += 1;
380            m.filter_confidence_partial += 1;
381        });
382        let s = rx.borrow();
383        assert_eq!(s.filter_total_commands, 2);
384        assert_eq!(s.filter_filtered_commands, 1);
385        assert_eq!(s.filter_confidence_full, 1);
386        assert_eq!(s.filter_confidence_partial, 1);
387        assert_eq!(s.filter_confidence_fallback, 0);
388    }
389
390    #[test]
391    fn summaries_count_tracks_summarizations() {
392        let (collector, rx) = MetricsCollector::new();
393        collector.update(|m| m.summaries_count += 1);
394        collector.update(|m| m.summaries_count += 1);
395        assert_eq!(rx.borrow().summaries_count, 2);
396    }
397
398    #[test]
399    fn cancellations_counter_increments() {
400        let (collector, rx) = MetricsCollector::new();
401        assert_eq!(rx.borrow().cancellations, 0);
402        collector.update(|m| m.cancellations += 1);
403        collector.update(|m| m.cancellations += 1);
404        assert_eq!(rx.borrow().cancellations, 2);
405    }
406
407    #[test]
408    fn security_event_detail_exact_128_not_truncated() {
409        let s = "a".repeat(128);
410        let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, "src", s.clone());
411        assert_eq!(ev.detail, s, "128-char string must not be truncated");
412    }
413
414    #[test]
415    fn security_event_detail_129_is_truncated() {
416        let s = "a".repeat(129);
417        let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, "src", s);
418        assert!(
419            ev.detail.ends_with('…'),
420            "129-char string must end with ellipsis"
421        );
422        assert!(
423            ev.detail.len() <= 130,
424            "truncated detail must be at most 130 bytes"
425        );
426    }
427
428    #[test]
429    fn security_event_detail_multibyte_utf8_no_panic() {
430        // Each '中' is 3 bytes. 43 chars = 129 bytes — triggers truncation at a multi-byte boundary.
431        let s = "中".repeat(43);
432        let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, "src", s);
433        assert!(ev.detail.ends_with('…'));
434    }
435
436    #[test]
437    fn security_event_source_capped_at_64_chars() {
438        let long_source = "x".repeat(200);
439        let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, long_source, "detail");
440        assert_eq!(ev.source.len(), 64);
441    }
442
443    #[test]
444    fn security_event_source_strips_control_chars() {
445        let source = "tool\x00name\x1b[31m";
446        let ev = SecurityEvent::new(SecurityEventCategory::InjectionFlag, source, "detail");
447        assert!(!ev.source.contains('\x00'));
448        assert!(!ev.source.contains('\x1b'));
449    }
450
451    #[test]
452    fn security_event_category_as_str() {
453        assert_eq!(SecurityEventCategory::InjectionFlag.as_str(), "injection");
454        assert_eq!(SecurityEventCategory::ExfiltrationBlock.as_str(), "exfil");
455        assert_eq!(SecurityEventCategory::Quarantine.as_str(), "quarantine");
456        assert_eq!(SecurityEventCategory::Truncation.as_str(), "truncation");
457    }
458
459    #[test]
460    fn ring_buffer_respects_cap_via_update() {
461        let (collector, rx) = MetricsCollector::new();
462        for i in 0..110u64 {
463            let event = SecurityEvent::new(
464                SecurityEventCategory::InjectionFlag,
465                "src",
466                format!("event {i}"),
467            );
468            collector.update(|m| {
469                if m.security_events.len() >= SECURITY_EVENT_CAP {
470                    m.security_events.pop_front();
471                }
472                m.security_events.push_back(event);
473            });
474        }
475        let snap = rx.borrow();
476        assert_eq!(snap.security_events.len(), SECURITY_EVENT_CAP);
477        // FIFO: earliest events evicted, last one present
478        assert!(snap.security_events.back().unwrap().detail.contains("109"));
479    }
480
481    #[test]
482    fn security_events_empty_by_default() {
483        let m = MetricsSnapshot::default();
484        assert!(m.security_events.is_empty());
485    }
486
487    #[test]
488    fn orchestration_metrics_default_zero() {
489        let m = OrchestrationMetrics::default();
490        assert_eq!(m.plans_total, 0);
491        assert_eq!(m.tasks_total, 0);
492        assert_eq!(m.tasks_completed, 0);
493        assert_eq!(m.tasks_failed, 0);
494        assert_eq!(m.tasks_skipped, 0);
495    }
496
497    #[test]
498    fn metrics_snapshot_includes_orchestration_default_zero() {
499        let m = MetricsSnapshot::default();
500        assert_eq!(m.orchestration.plans_total, 0);
501        assert_eq!(m.orchestration.tasks_total, 0);
502        assert_eq!(m.orchestration.tasks_completed, 0);
503    }
504
505    #[test]
506    fn orchestration_metrics_update_via_collector() {
507        let (collector, rx) = MetricsCollector::new();
508        collector.update(|m| {
509            m.orchestration.plans_total += 1;
510            m.orchestration.tasks_total += 5;
511            m.orchestration.tasks_completed += 3;
512            m.orchestration.tasks_failed += 1;
513            m.orchestration.tasks_skipped += 1;
514        });
515        let s = rx.borrow();
516        assert_eq!(s.orchestration.plans_total, 1);
517        assert_eq!(s.orchestration.tasks_total, 5);
518        assert_eq!(s.orchestration.tasks_completed, 3);
519        assert_eq!(s.orchestration.tasks_failed, 1);
520        assert_eq!(s.orchestration.tasks_skipped, 1);
521    }
522
523    #[test]
524    fn strip_ctrl_removes_escape_sequences() {
525        let input = "hello\x1b[31mworld\x00end";
526        let result = strip_ctrl(input);
527        assert_eq!(result, "helloworldend");
528    }
529
530    #[test]
531    fn strip_ctrl_allows_tab_lf_cr() {
532        let input = "a\tb\nc\rd";
533        let result = strip_ctrl(input);
534        assert_eq!(result, "a\tb\nc\rd");
535    }
536
537    #[test]
538    fn task_graph_snapshot_is_stale_after_30s() {
539        let mut snap = TaskGraphSnapshot::default();
540        // Not stale if no completed_at.
541        assert!(!snap.is_stale());
542        // Not stale if just completed.
543        snap.completed_at = Some(std::time::Instant::now());
544        assert!(!snap.is_stale());
545        // Stale if completed more than 30s ago.
546        snap.completed_at = Some(
547            std::time::Instant::now()
548                .checked_sub(std::time::Duration::from_secs(31))
549                .unwrap(),
550        );
551        assert!(snap.is_stale());
552    }
553
554    // T1: From<&TaskGraph> correctly maps fields including duration_ms and error truncation.
555    #[test]
556    fn task_graph_snapshot_from_task_graph_maps_fields() {
557        use crate::orchestration::{GraphStatus, TaskGraph, TaskNode, TaskResult, TaskStatus};
558
559        let mut graph = TaskGraph::new("My goal");
560        let mut task = TaskNode::new(0, "Do work", "description");
561        task.status = TaskStatus::Failed;
562        task.assigned_agent = Some("agent-1".into());
563        task.result = Some(TaskResult {
564            output: "error occurred here".into(),
565            artifacts: vec![],
566            duration_ms: 1234,
567            agent_id: None,
568            agent_def: None,
569        });
570        graph.tasks.push(task);
571        graph.status = GraphStatus::Failed;
572
573        let snap = TaskGraphSnapshot::from(&graph);
574        assert_eq!(snap.goal, "My goal");
575        assert_eq!(snap.status, "failed");
576        assert_eq!(snap.tasks.len(), 1);
577        let row = &snap.tasks[0];
578        assert_eq!(row.title, "Do work");
579        assert_eq!(row.status, "failed");
580        assert_eq!(row.agent.as_deref(), Some("agent-1"));
581        assert_eq!(row.duration_ms, 1234);
582        assert!(row.error.as_deref().unwrap().contains("error occurred"));
583    }
584
585    // T2: From impl compiles with orchestration feature active.
586    #[test]
587    fn task_graph_snapshot_from_compiles_with_feature() {
588        use crate::orchestration::TaskGraph;
589        let graph = TaskGraph::new("feature flag test");
590        let snap = TaskGraphSnapshot::from(&graph);
591        assert_eq!(snap.goal, "feature flag test");
592        assert!(snap.tasks.is_empty());
593        assert!(!snap.is_stale());
594    }
595
596    // T1-extra: long error is truncated with ellipsis.
597    #[test]
598    fn task_graph_snapshot_error_truncated_at_80_chars() {
599        use crate::orchestration::{TaskGraph, TaskNode, TaskResult, TaskStatus};
600
601        let mut graph = TaskGraph::new("goal");
602        let mut task = TaskNode::new(0, "t", "d");
603        task.status = TaskStatus::Failed;
604        task.result = Some(TaskResult {
605            output: "e".repeat(100),
606            artifacts: vec![],
607            duration_ms: 0,
608            agent_id: None,
609            agent_def: None,
610        });
611        graph.tasks.push(task);
612
613        let snap = TaskGraphSnapshot::from(&graph);
614        let err = snap.tasks[0].error.as_ref().unwrap();
615        assert!(err.ends_with('…'), "truncated error must end with ellipsis");
616        assert!(
617            err.len() <= 83,
618            "truncated error must not exceed 80 chars + ellipsis"
619        );
620    }
621
622    // SEC-P6-01: control chars in task title are stripped.
623    #[test]
624    fn task_graph_snapshot_strips_control_chars_from_title() {
625        use crate::orchestration::{TaskGraph, TaskNode};
626
627        let mut graph = TaskGraph::new("goal\x1b[31m");
628        let task = TaskNode::new(0, "title\x00injected", "d");
629        graph.tasks.push(task);
630
631        let snap = TaskGraphSnapshot::from(&graph);
632        assert!(!snap.goal.contains('\x1b'), "goal must not contain escape");
633        assert!(
634            !snap.tasks[0].title.contains('\x00'),
635            "title must not contain null byte"
636        );
637    }
638
639    #[test]
640    fn graph_metrics_default_zero() {
641        let m = MetricsSnapshot::default();
642        assert_eq!(m.graph_entities_total, 0);
643        assert_eq!(m.graph_edges_total, 0);
644        assert_eq!(m.graph_communities_total, 0);
645        assert_eq!(m.graph_extraction_count, 0);
646        assert_eq!(m.graph_extraction_failures, 0);
647    }
648
649    #[test]
650    fn graph_metrics_update_via_collector() {
651        let (collector, rx) = MetricsCollector::new();
652        collector.update(|m| {
653            m.graph_entities_total = 5;
654            m.graph_edges_total = 10;
655            m.graph_communities_total = 2;
656            m.graph_extraction_count = 7;
657            m.graph_extraction_failures = 1;
658        });
659        let snapshot = rx.borrow().clone();
660        assert_eq!(snapshot.graph_entities_total, 5);
661        assert_eq!(snapshot.graph_edges_total, 10);
662        assert_eq!(snapshot.graph_communities_total, 2);
663        assert_eq!(snapshot.graph_extraction_count, 7);
664        assert_eq!(snapshot.graph_extraction_failures, 1);
665    }
666}