victauri-plugin 0.1.0

Tauri plugin for Victauri — embedded MCP server with full-stack introspection
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
//! Victauri — full-stack introspection for Tauri apps via an embedded MCP server.
//!
//! Add this plugin to your Tauri app for AI-agent-driven testing and debugging:
//! DOM snapshots, IPC tracing, cross-boundary verification, and 59 more tools —
//! all accessible over the Model Context Protocol.
//!
//! # Quick Start
//!
//! ```ignore
//! tauri::Builder::default()
//!     .plugin(victauri_plugin::init())
//!     .run(tauri::generate_context!())
//!     .unwrap();
//! ```
//!
//! In debug builds this starts an MCP server on port 7373. In release builds
//! the plugin is a no-op with zero overhead.
//!
//! # Configuration
//!
//! ```ignore
//! tauri::Builder::default()
//!     .plugin(
//!         victauri_plugin::VictauriBuilder::new()
//!             .port(8080)
//!             .generate_auth_token()
//!             .strict_privacy_mode()
//!             .build(),
//!     )
//!     .run(tauri::generate_context!())
//!     .unwrap();
//! ```

pub mod bridge;
pub mod error;
mod js_bridge;
pub mod mcp;
mod memory;
pub mod privacy;
pub mod redaction;
pub(crate) mod screenshot;
mod tools;

pub mod auth;

use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::sync::atomic::AtomicU64;
use tauri::plugin::{Builder, TauriPlugin};
use tauri::{Manager, RunEvent, Runtime};
use tokio::sync::{Mutex, oneshot, watch};
use victauri_core::{CommandRegistry, EventLog, EventRecorder};

pub use error::BuilderError;

pub use victauri_macros::inspectable;

const DEFAULT_PORT: u16 = 7373;
const DEFAULT_EVENT_CAPACITY: usize = 10_000;
const DEFAULT_RECORDER_CAPACITY: usize = 50_000;
const DEFAULT_EVAL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);

/// Map of pending JavaScript eval callbacks, keyed by request ID.
/// Each entry holds a oneshot sender that resolves when the webview returns a result.
pub type PendingCallbacks = Arc<Mutex<HashMap<String, oneshot::Sender<String>>>>;

/// Runtime state shared between the MCP server and all tool handlers.
pub struct VictauriState {
    /// Ring-buffer event log for IPC calls, state changes, and DOM mutations.
    pub event_log: EventLog,
    /// Registry of all discovered Tauri commands with metadata.
    pub registry: CommandRegistry,
    /// TCP port the MCP server listens on.
    pub port: u16,
    /// Pending JavaScript eval callbacks awaiting webview responses.
    pub pending_evals: PendingCallbacks,
    /// Session recorder for time-travel debugging.
    pub recorder: EventRecorder,
    /// Privacy configuration (tool disabling, command filtering, output redaction).
    pub privacy: privacy::PrivacyConfig,
    /// Timeout for JavaScript eval operations.
    pub eval_timeout: std::time::Duration,
    /// Sends `true` to signal graceful MCP server shutdown.
    pub shutdown_tx: watch::Sender<bool>,
    /// Instant the plugin was initialized, for uptime tracking.
    pub started_at: std::time::Instant,
    /// Total number of MCP tool invocations since startup.
    pub tool_invocations: AtomicU64,
}

/// Builder for configuring the Victauri plugin before adding it to a Tauri app.
///
/// Supports port selection, authentication, privacy controls, output redaction,
/// and capacity tuning. All settings have sensible defaults and can be overridden
/// via environment variables.
pub struct VictauriBuilder {
    port: Option<u16>,
    event_capacity: usize,
    recorder_capacity: usize,
    eval_timeout: std::time::Duration,
    auth_token: Option<String>,
    disabled_tools: Vec<String>,
    command_allowlist: Option<Vec<String>>,
    command_blocklist: Vec<String>,
    redaction_patterns: Vec<String>,
    redaction_enabled: bool,
    strict_privacy: bool,
    bridge_capacities: js_bridge::BridgeCapacities,
    on_ready: Option<Box<dyn FnOnce(u16) + Send + 'static>>,
}

impl Default for VictauriBuilder {
    fn default() -> Self {
        Self {
            port: None,
            event_capacity: DEFAULT_EVENT_CAPACITY,
            recorder_capacity: DEFAULT_RECORDER_CAPACITY,
            eval_timeout: DEFAULT_EVAL_TIMEOUT,
            auth_token: None,
            disabled_tools: Vec::new(),
            command_allowlist: None,
            command_blocklist: Vec::new(),
            redaction_patterns: Vec::new(),
            redaction_enabled: false,
            strict_privacy: false,
            bridge_capacities: js_bridge::BridgeCapacities::default(),
            on_ready: None,
        }
    }
}

impl VictauriBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the TCP port for the MCP server (default: 7373, env: `VICTAURI_PORT`).
    pub fn port(mut self, port: u16) -> Self {
        self.port = Some(port);
        self
    }

    /// Set the maximum number of events in the ring-buffer log (default: 10,000).
    pub fn event_capacity(mut self, capacity: usize) -> Self {
        self.event_capacity = capacity;
        self
    }

    /// Set the maximum events kept during session recording (default: 50,000).
    pub fn recorder_capacity(mut self, capacity: usize) -> Self {
        self.recorder_capacity = capacity;
        self
    }

    /// Set the timeout for JavaScript eval operations (default: 30s, env: `VICTAURI_EVAL_TIMEOUT`).
    pub fn eval_timeout(mut self, timeout: std::time::Duration) -> Self {
        self.eval_timeout = timeout;
        self
    }

    /// Set an explicit auth token for the MCP server (env: `VICTAURI_AUTH_TOKEN`).
    pub fn auth_token(mut self, token: impl Into<String>) -> Self {
        self.auth_token = Some(token.into());
        self
    }

    /// Generate a random UUID v4 auth token.
    pub fn generate_auth_token(mut self) -> Self {
        self.auth_token = Some(auth::generate_token());
        self
    }

    /// Disable specific MCP tools by name (e.g., `["eval_js", "screenshot"]`).
    pub fn disable_tools(mut self, tools: &[&str]) -> Self {
        self.disabled_tools = tools.iter().map(|s| s.to_string()).collect();
        self
    }

    /// Only allow these Tauri commands to be invoked via MCP (positive allowlist).
    pub fn command_allowlist(mut self, commands: &[&str]) -> Self {
        self.command_allowlist = Some(commands.iter().map(|s| s.to_string()).collect());
        self
    }

    /// Block specific Tauri commands from being invoked via MCP.
    pub fn command_blocklist(mut self, commands: &[&str]) -> Self {
        self.command_blocklist = commands.iter().map(|s| s.to_string()).collect();
        self
    }

    /// Add a regex pattern for output redaction (e.g., `r"SECRET_\w+"`).
    pub fn add_redaction_pattern(mut self, pattern: impl Into<String>) -> Self {
        self.redaction_patterns.push(pattern.into());
        self
    }

    /// Enable output redaction with built-in patterns (API keys, emails, tokens).
    pub fn enable_redaction(mut self) -> Self {
        self.redaction_enabled = true;
        self
    }

    /// Enable strict privacy mode: disables dangerous tools (eval_js, screenshot,
    /// inject_css, set_storage, delete_storage, navigate, set_dialog_response,
    /// fill, type_text), enables output redaction with built-in PII patterns.
    pub fn strict_privacy_mode(mut self) -> Self {
        self.strict_privacy = true;
        self
    }

    /// Set the maximum console log entries kept in the JS bridge (default: 1000).
    pub fn console_log_capacity(mut self, capacity: usize) -> Self {
        self.bridge_capacities.console_logs = capacity;
        self
    }

    /// Set the maximum network log entries kept in the JS bridge (default: 1000).
    pub fn network_log_capacity(mut self, capacity: usize) -> Self {
        self.bridge_capacities.network_log = capacity;
        self
    }

    /// Set the maximum navigation log entries kept in the JS bridge (default: 200).
    pub fn navigation_log_capacity(mut self, capacity: usize) -> Self {
        self.bridge_capacities.navigation_log = capacity;
        self
    }

    /// Register a callback invoked once the MCP server is listening.
    /// The callback receives the port number.
    pub fn on_ready(mut self, f: impl FnOnce(u16) + Send + 'static) -> Self {
        self.on_ready = Some(Box::new(f));
        self
    }

    fn resolve_port(&self) -> u16 {
        self.port
            .or_else(|| std::env::var("VICTAURI_PORT").ok()?.parse().ok())
            .unwrap_or(DEFAULT_PORT)
    }

    fn resolve_auth_token(&self) -> Option<String> {
        self.auth_token
            .clone()
            .or_else(|| std::env::var("VICTAURI_AUTH_TOKEN").ok())
    }

    fn resolve_eval_timeout(&self) -> std::time::Duration {
        std::env::var("VICTAURI_EVAL_TIMEOUT")
            .ok()
            .and_then(|s| s.parse::<u64>().ok())
            .map(std::time::Duration::from_secs)
            .unwrap_or(self.eval_timeout)
    }

    fn build_privacy_config(&self) -> privacy::PrivacyConfig {
        if self.strict_privacy {
            let mut config = privacy::strict_privacy_config();
            for cmd in &self.command_blocklist {
                config.command_blocklist.insert(cmd.clone());
            }
            if let Some(ref allow) = self.command_allowlist {
                config.command_allowlist = Some(allow.iter().cloned().collect());
            }
            for tool in &self.disabled_tools {
                config.disabled_tools.insert(tool.clone());
            }
            if !self.redaction_patterns.is_empty() {
                config.redactor = redaction::Redactor::new(&self.redaction_patterns);
            }
            config
        } else {
            privacy::PrivacyConfig {
                command_allowlist: self
                    .command_allowlist
                    .as_ref()
                    .map(|v| v.iter().cloned().collect::<HashSet<String>>()),
                command_blocklist: self.command_blocklist.iter().cloned().collect(),
                disabled_tools: self.disabled_tools.iter().cloned().collect(),
                redactor: redaction::Redactor::new(&self.redaction_patterns),
                redaction_enabled: self.redaction_enabled,
            }
        }
    }

    fn validate(&self) -> Result<(), BuilderError> {
        let port = self.resolve_port();
        if port == 0 {
            return Err(BuilderError::InvalidPort {
                port,
                reason: "port 0 is reserved".to_string(),
            });
        }

        if self.event_capacity == 0 || self.event_capacity > 1_000_000 {
            return Err(BuilderError::InvalidEventCapacity {
                capacity: self.event_capacity,
                reason: "must be between 1 and 1,000,000".to_string(),
            });
        }

        if self.recorder_capacity == 0 || self.recorder_capacity > 1_000_000 {
            return Err(BuilderError::InvalidRecorderCapacity {
                capacity: self.recorder_capacity,
                reason: "must be between 1 and 1,000,000".to_string(),
            });
        }

        let timeout = self.resolve_eval_timeout();
        if timeout.as_secs() == 0 || timeout.as_secs() > 300 {
            return Err(BuilderError::InvalidEvalTimeout {
                timeout_secs: timeout.as_secs(),
                reason: "must be between 1 and 300 seconds".to_string(),
            });
        }

        Ok(())
    }

    pub fn build<R: Runtime>(self) -> Result<TauriPlugin<R>, BuilderError> {
        #[cfg(not(debug_assertions))]
        {
            Ok(Builder::new("victauri").build())
        }

        #[cfg(debug_assertions)]
        {
            self.validate()?;

            let port = self.resolve_port();
            let event_capacity = self.event_capacity;
            let recorder_capacity = self.recorder_capacity;
            let eval_timeout = self.resolve_eval_timeout();
            let auth_token = self.resolve_auth_token();
            let privacy_config = self.build_privacy_config();
            let on_ready = self.on_ready;
            let js_init = js_bridge::init_script(&self.bridge_capacities);

            Ok(Builder::new("victauri")
                .setup(move |app, _api| {
                    let event_log = EventLog::new(event_capacity);
                    let registry = CommandRegistry::new();
                    let (shutdown_tx, shutdown_rx) = watch::channel(false);

                    let state = Arc::new(VictauriState {
                        event_log,
                        registry,
                        port,
                        pending_evals: Arc::new(Mutex::new(HashMap::new())),
                        recorder: EventRecorder::new(recorder_capacity),
                        privacy: privacy_config,
                        eval_timeout,
                        shutdown_tx,
                        started_at: std::time::Instant::now(),
                        tool_invocations: AtomicU64::new(0),
                    });

                    app.manage(state.clone());

                    if let Some(ref token) = auth_token {
                        tracing::info!(
                            "Victauri MCP server auth token: [REDACTED] (check VICTAURI_AUTH_TOKEN env var)"
                        );
                        tracing::debug!("Auth token value: {token}");
                    }

                    let app_handle = app.clone();
                    tauri::async_runtime::spawn(async move {
                        match mcp::start_server_with_options(
                            app_handle, state, port, auth_token, shutdown_rx,
                        )
                        .await
                        {
                            Ok(()) => {
                                tracing::info!("Victauri MCP server stopped");
                            }
                            Err(e) => {
                                tracing::error!("Victauri MCP server failed: {e}");
                            }
                        }
                    });

                    if let Some(cb) = on_ready {
                        let ready_port = port;
                        tauri::async_runtime::spawn(async move {
                            for _ in 0..50 {
                                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
                                if tokio::net::TcpStream::connect(format!(
                                    "127.0.0.1:{ready_port}"
                                ))
                                .await
                                .is_ok()
                                {
                                    cb(ready_port);
                                    return;
                                }
                            }
                            tracing::warn!("Victauri on_ready: server did not become ready within 5s");
                            cb(ready_port);
                        });
                    }

                    tracing::info!("Victauri plugin initialized — MCP server on port {port}");
                    Ok(())
                })
                .on_event(|app, event| {
                    if let RunEvent::Exit = event
                        && let Some(state) = app.try_state::<Arc<VictauriState>>()
                    {
                        let _ = state.shutdown_tx.send(true);
                        tracing::info!("Victauri shutdown signal sent");
                    }
                })
                .js_init_script(js_init)
                .invoke_handler(tauri::generate_handler![
                    tools::victauri_eval_js,
                    tools::victauri_eval_callback,
                    tools::victauri_get_window_state,
                    tools::victauri_list_windows,
                    tools::victauri_get_ipc_log,
                    tools::victauri_get_registry,
                    tools::victauri_get_memory_stats,
                    tools::victauri_dom_snapshot,
                    tools::victauri_verify_state,
                    tools::victauri_detect_ghost_commands,
                    tools::victauri_check_ipc_integrity,
                ])
                .build())
        }
    }
}

/// Initialize the Victauri plugin with default settings (port 7373 or VICTAURI_PORT env var).
///
/// In debug builds: starts the embedded MCP server, injects the JS bridge, and
/// registers all Tauri command handlers.
///
/// In release builds: returns a no-op plugin. The MCP server, JS bridge, and
/// all introspection tools are completely stripped — zero overhead, zero attack surface.
///
/// For custom configuration, use `VictauriBuilder::new().port(8080).build()`.
pub fn init<R: Runtime>() -> TauriPlugin<R> {
    VictauriBuilder::new()
        .build()
        .expect("default Victauri configuration is always valid")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn builder_default_values() {
        let builder = VictauriBuilder::new();
        assert_eq!(builder.event_capacity, DEFAULT_EVENT_CAPACITY);
        assert_eq!(builder.recorder_capacity, DEFAULT_RECORDER_CAPACITY);
        assert!(builder.auth_token.is_none());
        assert!(builder.disabled_tools.is_empty());
        assert!(builder.command_allowlist.is_none());
        assert!(builder.command_blocklist.is_empty());
        assert!(!builder.redaction_enabled);
        assert!(!builder.strict_privacy);
    }

    #[test]
    fn builder_port_override() {
        let builder = VictauriBuilder::new().port(9090);
        assert_eq!(builder.resolve_port(), 9090);
    }

    #[test]
    fn builder_default_port() {
        let builder = VictauriBuilder::new();
        // Clear env var to test default
        unsafe { std::env::remove_var("VICTAURI_PORT") };
        assert_eq!(builder.resolve_port(), DEFAULT_PORT);
    }

    #[test]
    fn builder_auth_token_explicit() {
        let builder = VictauriBuilder::new().auth_token("my-secret");
        assert_eq!(builder.resolve_auth_token(), Some("my-secret".to_string()));
    }

    #[test]
    fn builder_auth_token_generated() {
        let builder = VictauriBuilder::new().generate_auth_token();
        let token = builder.resolve_auth_token().unwrap();
        assert_eq!(token.len(), 36);
    }

    #[test]
    fn builder_capacities() {
        let builder = VictauriBuilder::new()
            .event_capacity(500)
            .recorder_capacity(2000);
        assert_eq!(builder.event_capacity, 500);
        assert_eq!(builder.recorder_capacity, 2000);
    }

    #[test]
    fn builder_disable_tools() {
        let builder = VictauriBuilder::new().disable_tools(&["eval_js", "screenshot"]);
        assert_eq!(builder.disabled_tools.len(), 2);
        assert!(builder.disabled_tools.contains(&"eval_js".to_string()));
    }

    #[test]
    fn builder_command_allowlist() {
        let builder = VictauriBuilder::new().command_allowlist(&["greet", "increment"]);
        assert!(builder.command_allowlist.is_some());
        assert_eq!(builder.command_allowlist.as_ref().unwrap().len(), 2);
    }

    #[test]
    fn builder_command_blocklist() {
        let builder = VictauriBuilder::new().command_blocklist(&["dangerous_cmd"]);
        assert_eq!(builder.command_blocklist.len(), 1);
    }

    #[test]
    fn builder_redaction() {
        let builder = VictauriBuilder::new()
            .add_redaction_pattern(r"SECRET_\w+")
            .enable_redaction();
        assert!(builder.redaction_enabled);
        assert_eq!(builder.redaction_patterns.len(), 1);
    }

    #[test]
    fn builder_strict_privacy_config() {
        let builder = VictauriBuilder::new().strict_privacy_mode();
        let config = builder.build_privacy_config();
        assert!(config.redaction_enabled);
        assert!(!config.disabled_tools.is_empty());
        assert!(config.disabled_tools.contains("eval_js"));
        assert!(config.disabled_tools.contains("screenshot"));
    }

    #[test]
    fn builder_normal_privacy_config() {
        let builder = VictauriBuilder::new()
            .command_blocklist(&["secret_cmd"])
            .disable_tools(&["eval_js"]);
        let config = builder.build_privacy_config();
        assert!(config.command_blocklist.contains("secret_cmd"));
        assert!(config.disabled_tools.contains("eval_js"));
        assert!(!config.redaction_enabled);
    }

    #[test]
    fn builder_strict_with_extra_blocklist() {
        let builder = VictauriBuilder::new()
            .strict_privacy_mode()
            .command_blocklist(&["extra_dangerous"]);
        let config = builder.build_privacy_config();
        assert!(config.command_blocklist.contains("extra_dangerous"));
        assert!(config.disabled_tools.contains("eval_js"));
    }

    #[test]
    fn builder_bridge_capacities() {
        let builder = VictauriBuilder::new()
            .console_log_capacity(5000)
            .network_log_capacity(2000)
            .navigation_log_capacity(500);
        assert_eq!(builder.bridge_capacities.console_logs, 5000);
        assert_eq!(builder.bridge_capacities.network_log, 2000);
        assert_eq!(builder.bridge_capacities.navigation_log, 500);
        assert_eq!(builder.bridge_capacities.mutation_log, 500);
        assert_eq!(builder.bridge_capacities.dialog_log, 100);
    }

    #[test]
    fn builder_on_ready_sets_callback() {
        let builder = VictauriBuilder::new().on_ready(|_port| {});
        assert!(builder.on_ready.is_some());
    }

    #[test]
    fn init_script_contains_custom_capacities() {
        let caps = js_bridge::BridgeCapacities {
            console_logs: 3000,
            mutation_log: 750,
            network_log: 5000,
            navigation_log: 400,
            dialog_log: 250,
            long_tasks: 200,
        };
        let script = js_bridge::init_script(&caps);
        assert!(script.contains("CAP_CONSOLE = 3000"));
        assert!(script.contains("CAP_MUTATION = 750"));
        assert!(script.contains("CAP_NETWORK = 5000"));
        assert!(script.contains("CAP_NAVIGATION = 400"));
        assert!(script.contains("CAP_DIALOG = 250"));
        assert!(script.contains("CAP_LONG_TASKS = 200"));
    }

    #[test]
    fn init_script_default_contains_standard_capacities() {
        let caps = js_bridge::BridgeCapacities::default();
        let script = js_bridge::init_script(&caps);
        assert!(script.contains("CAP_CONSOLE = 1000"));
        assert!(script.contains("CAP_NETWORK = 1000"));
        assert!(script.contains("window.__VICTAURI__"));
    }

    #[test]
    fn builder_validates_defaults() {
        let builder = VictauriBuilder::new();
        assert!(builder.validate().is_ok());
    }

    #[test]
    fn builder_rejects_zero_port() {
        let builder = VictauriBuilder::new().port(0);
        let err = builder.validate().unwrap_err();
        assert!(matches!(err, BuilderError::InvalidPort { port: 0, .. }));
    }

    #[test]
    fn builder_rejects_zero_event_capacity() {
        let builder = VictauriBuilder::new().event_capacity(0);
        let err = builder.validate().unwrap_err();
        assert!(matches!(
            err,
            BuilderError::InvalidEventCapacity { capacity: 0, .. }
        ));
    }

    #[test]
    fn builder_rejects_excessive_event_capacity() {
        let builder = VictauriBuilder::new().event_capacity(2_000_000);
        assert!(builder.validate().is_err());
    }

    #[test]
    fn builder_rejects_zero_recorder_capacity() {
        let builder = VictauriBuilder::new().recorder_capacity(0);
        assert!(builder.validate().is_err());
    }

    #[test]
    fn builder_rejects_zero_eval_timeout() {
        let builder = VictauriBuilder::new().eval_timeout(std::time::Duration::from_secs(0));
        assert!(builder.validate().is_err());
    }

    #[test]
    fn builder_rejects_excessive_eval_timeout() {
        let builder = VictauriBuilder::new().eval_timeout(std::time::Duration::from_secs(600));
        assert!(builder.validate().is_err());
    }

    #[test]
    fn builder_accepts_edge_values() {
        let builder = VictauriBuilder::new()
            .port(1)
            .event_capacity(1)
            .recorder_capacity(1)
            .eval_timeout(std::time::Duration::from_secs(1));
        assert!(builder.validate().is_ok());

        let builder = VictauriBuilder::new()
            .port(65535)
            .event_capacity(1_000_000)
            .recorder_capacity(1_000_000)
            .eval_timeout(std::time::Duration::from_secs(300));
        assert!(builder.validate().is_ok());
    }
}