victauri-plugin 0.5.6

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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
//! Backend introspection and chaos engineering types.
//!
//! These types support Victauri's intervention capabilities — features that exploit
//! the plugin's position inside the Rust process to provide insights and control
//! that browser-external tools like CDP cannot access.

use std::collections::{HashMap, VecDeque};
use std::sync::RwLock;
use std::sync::atomic::AtomicBool;
use std::time::{Duration, Instant};

use serde::Serialize;

/// Per-command timing statistics aggregated from IPC invocations.
#[derive(Debug, Clone, Serialize)]
pub struct CommandTimingStats {
    /// Command name.
    pub command: String,
    /// Number of invocations recorded.
    pub count: u64,
    /// Minimum execution time in milliseconds.
    pub min_ms: f64,
    /// Maximum execution time in milliseconds.
    pub max_ms: f64,
    /// Mean execution time in milliseconds.
    pub avg_ms: f64,
    /// 95th percentile execution time in milliseconds.
    pub p95_ms: f64,
    /// Total execution time across all invocations.
    pub total_ms: f64,
}

/// Accumulated raw timing samples for a single command.
#[derive(Debug, Default)]
pub struct TimingSamples {
    /// Duration of each invocation, in order.
    pub samples: Vec<Duration>,
}

impl TimingSamples {
    /// Add a timing sample.
    pub fn record(&mut self, duration: Duration) {
        self.samples.push(duration);
    }

    /// Compute aggregate statistics.
    #[must_use]
    pub fn stats(&self, command: &str) -> CommandTimingStats {
        if self.samples.is_empty() {
            return CommandTimingStats {
                command: command.to_string(),
                count: 0,
                min_ms: 0.0,
                max_ms: 0.0,
                avg_ms: 0.0,
                p95_ms: 0.0,
                total_ms: 0.0,
            };
        }
        let mut sorted: Vec<f64> = self
            .samples
            .iter()
            .map(|d| d.as_secs_f64() * 1000.0)
            .collect();
        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

        let count = sorted.len() as u64;
        let total: f64 = sorted.iter().sum();
        let min = sorted[0];
        let max = sorted[sorted.len() - 1];
        let avg = total / sorted.len() as f64;
        let p95_idx = ((sorted.len() as f64) * 0.95).ceil() as usize;
        let p95 = sorted[p95_idx.min(sorted.len() - 1)];

        CommandTimingStats {
            command: command.to_string(),
            count,
            min_ms: (min * 100.0).round() / 100.0,
            max_ms: (max * 100.0).round() / 100.0,
            avg_ms: (avg * 100.0).round() / 100.0,
            p95_ms: (p95 * 100.0).round() / 100.0,
            total_ms: (total * 100.0).round() / 100.0,
        }
    }
}

/// Thread-safe store for per-command timing data.
pub struct CommandTimings {
    inner: RwLock<HashMap<String, TimingSamples>>,
}

impl CommandTimings {
    /// Create a new empty store.
    #[must_use]
    pub fn new() -> Self {
        Self {
            inner: RwLock::new(HashMap::new()),
        }
    }

    /// Record a timing sample for a command.
    pub fn record(&self, command: &str, duration: Duration) {
        let mut map = self
            .inner
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        map.entry(command.to_string()).or_default().record(duration);
    }

    /// Get stats for all commands, sorted by total time descending.
    #[must_use]
    pub fn all_stats(&self) -> Vec<CommandTimingStats> {
        let map = self
            .inner
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let mut stats: Vec<CommandTimingStats> =
            map.iter().map(|(name, s)| s.stats(name)).collect();
        stats.sort_by(|a, b| {
            b.total_ms
                .partial_cmp(&a.total_ms)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        stats
    }

    /// Get stats for a single command.
    #[must_use]
    pub fn stats_for(&self, command: &str) -> Option<CommandTimingStats> {
        let map = self
            .inner
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        map.get(command).map(|s| s.stats(command))
    }

    /// Clear all timing data.
    pub fn clear(&self) {
        let mut map = self
            .inner
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        map.clear();
    }
}

impl Default for CommandTimings {
    fn default() -> Self {
        Self::new()
    }
}

// ── Fault Injection ─────────────────────────────────────────────────────────

/// The type of fault to inject into a command.
#[derive(Debug, Clone, Serialize)]
pub enum FaultType {
    /// Add artificial latency before command execution.
    Delay {
        /// Delay in milliseconds.
        delay_ms: u64,
    },
    /// Return an error without executing the command.
    Error {
        /// Error message to return.
        message: String,
    },
    /// Drop the response entirely (return empty/timeout-like response).
    Drop,
    /// Execute normally but corrupt the response (randomize field values).
    Corrupt,
}

/// Configuration for a single fault injection rule.
#[derive(Debug, Clone, Serialize)]
pub struct FaultConfig {
    /// Target command name.
    pub command: String,
    /// Type of fault to inject.
    pub fault_type: FaultType,
    /// Number of times this fault has been triggered.
    pub trigger_count: u64,
    /// Maximum number of times to trigger (0 = unlimited).
    pub max_triggers: u64,
    /// When this fault was created.
    #[serde(skip)]
    pub created_at: Instant,
}

impl FaultConfig {
    /// Check if this fault should still trigger (based on `max_triggers`).
    #[must_use]
    pub fn should_trigger(&self) -> bool {
        self.max_triggers == 0 || self.trigger_count < self.max_triggers
    }
}

/// Thread-safe registry of active fault injection rules.
pub struct FaultRegistry {
    inner: RwLock<HashMap<String, FaultConfig>>,
}

impl FaultRegistry {
    /// Create an empty registry.
    #[must_use]
    pub fn new() -> Self {
        Self {
            inner: RwLock::new(HashMap::new()),
        }
    }

    /// Register a fault for a command.
    pub fn inject(&self, config: FaultConfig) {
        let mut map = self
            .inner
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        map.insert(config.command.clone(), config);
    }

    /// Look up and optionally trigger a fault for a command.
    /// Returns the fault type if one is active and should trigger.
    pub fn check_and_trigger(&self, command: &str) -> Option<FaultType> {
        let mut map = self
            .inner
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(config) = map.get_mut(command)
            && config.should_trigger()
        {
            config.trigger_count += 1;
            return Some(config.fault_type.clone());
        }
        None
    }

    /// List all active fault rules.
    #[must_use]
    pub fn list(&self) -> Vec<FaultConfig> {
        let map = self
            .inner
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        map.values().cloned().collect()
    }

    /// Remove a fault rule for a command.
    pub fn clear(&self, command: &str) -> bool {
        let mut map = self
            .inner
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        map.remove(command).is_some()
    }

    /// Remove all fault rules.
    pub fn clear_all(&self) -> usize {
        let mut map = self
            .inner
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let count = map.len();
        map.clear();
        count
    }
}

impl Default for FaultRegistry {
    fn default() -> Self {
        Self::new()
    }
}

// ── IPC Contract Testing ────────────────────────────────────────────────────

/// Describes the shape of a JSON value for contract comparison.
#[derive(Debug, Clone, Serialize, PartialEq)]
pub enum JsonShape {
    /// null
    Null,
    /// boolean
    Bool,
    /// number (integer or float)
    Number,
    /// string
    String,
    /// array with element shape (from first element, or Null if empty)
    Array(Box<Self>),
    /// object with field names and their shapes
    Object(HashMap<String, Self>),
}

impl JsonShape {
    /// Extract the shape of a JSON value.
    #[must_use]
    pub fn from_value(value: &serde_json::Value) -> Self {
        match value {
            serde_json::Value::Null => Self::Null,
            serde_json::Value::Bool(_) => Self::Bool,
            serde_json::Value::Number(_) => Self::Number,
            serde_json::Value::String(_) => Self::String,
            serde_json::Value::Array(arr) => {
                let elem = arr.first().map_or(Self::Null, Self::from_value);
                Self::Array(Box::new(elem))
            }
            serde_json::Value::Object(obj) => {
                let fields: HashMap<String, Self> = obj
                    .iter()
                    .map(|(k, v)| (k.clone(), Self::from_value(v)))
                    .collect();
                Self::Object(fields)
            }
        }
    }

    /// Human-readable type name.
    #[must_use]
    pub fn type_name(&self) -> &'static str {
        match self {
            Self::Null => "null",
            Self::Bool => "bool",
            Self::Number => "number",
            Self::String => "string",
            Self::Array(_) => "array",
            Self::Object(_) => "object",
        }
    }
}

/// A recorded contract baseline for a command's response.
#[derive(Debug, Clone, Serialize)]
pub struct ContractBaseline {
    /// Command name.
    pub command: String,
    /// Arguments used when recording.
    pub args: serde_json::Value,
    /// Shape of the response.
    pub shape: JsonShape,
    /// Raw sample response (first 4KB).
    pub sample: String,
    /// When this baseline was recorded.
    pub recorded_at: String,
}

/// Differences found when checking a contract against baseline.
#[derive(Debug, Clone, Serialize)]
pub struct ContractDrift {
    /// Command name.
    pub command: String,
    /// Fields present in current but not in baseline.
    pub new_fields: Vec<String>,
    /// Fields present in baseline but not in current.
    pub removed_fields: Vec<String>,
    /// Fields whose type changed.
    pub type_changes: Vec<TypeChange>,
    /// Whether the overall shape matches.
    pub shape_matches: bool,
}

/// A single field type change between baseline and current.
#[derive(Debug, Clone, Serialize)]
pub struct TypeChange {
    /// Dot-separated field path.
    pub path: String,
    /// Type in the baseline.
    pub baseline_type: String,
    /// Type in the current response.
    pub current_type: String,
}

/// Compare two JSON shapes and report differences.
#[must_use]
pub fn diff_shapes(baseline: &JsonShape, current: &JsonShape, prefix: &str) -> ContractDrift {
    let mut new_fields = Vec::new();
    let mut removed_fields = Vec::new();
    let mut type_changes = Vec::new();

    diff_shapes_inner(
        baseline,
        current,
        prefix,
        &mut new_fields,
        &mut removed_fields,
        &mut type_changes,
    );

    let shape_matches =
        new_fields.is_empty() && removed_fields.is_empty() && type_changes.is_empty();
    ContractDrift {
        command: prefix.to_string(),
        new_fields,
        removed_fields,
        type_changes,
        shape_matches,
    }
}

fn diff_shapes_inner(
    baseline: &JsonShape,
    current: &JsonShape,
    prefix: &str,
    new_fields: &mut Vec<String>,
    removed_fields: &mut Vec<String>,
    type_changes: &mut Vec<TypeChange>,
) {
    match (baseline, current) {
        (JsonShape::Object(b_fields), JsonShape::Object(c_fields)) => {
            for (key, b_shape) in b_fields {
                let path = if prefix.is_empty() {
                    key.clone()
                } else {
                    format!("{prefix}.{key}")
                };
                if let Some(c_shape) = c_fields.get(key) {
                    diff_shapes_inner(
                        b_shape,
                        c_shape,
                        &path,
                        new_fields,
                        removed_fields,
                        type_changes,
                    );
                } else {
                    removed_fields.push(path);
                }
            }
            for key in c_fields.keys() {
                if !b_fields.contains_key(key) {
                    let path = if prefix.is_empty() {
                        key.clone()
                    } else {
                        format!("{prefix}.{key}")
                    };
                    new_fields.push(path);
                }
            }
        }
        (JsonShape::Array(b_elem), JsonShape::Array(c_elem)) => {
            let path = format!("{prefix}[]");
            diff_shapes_inner(
                b_elem,
                c_elem,
                &path,
                new_fields,
                removed_fields,
                type_changes,
            );
        }
        (b, c) if b.type_name() != c.type_name() => {
            type_changes.push(TypeChange {
                path: prefix.to_string(),
                baseline_type: b.type_name().to_string(),
                current_type: c.type_name().to_string(),
            });
        }
        _ => {}
    }
}

/// Thread-safe store for IPC contract baselines.
pub struct ContractStore {
    inner: RwLock<HashMap<String, ContractBaseline>>,
}

impl ContractStore {
    /// Create an empty store.
    #[must_use]
    pub fn new() -> Self {
        Self {
            inner: RwLock::new(HashMap::new()),
        }
    }

    /// Record a baseline for a command.
    pub fn record(&self, baseline: ContractBaseline) {
        let mut map = self
            .inner
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        map.insert(baseline.command.clone(), baseline);
    }

    /// Get the baseline for a command.
    #[must_use]
    pub fn get(&self, command: &str) -> Option<ContractBaseline> {
        let map = self
            .inner
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        map.get(command).cloned()
    }

    /// Get all baselines.
    #[must_use]
    pub fn all(&self) -> Vec<ContractBaseline> {
        let map = self
            .inner
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        map.values().cloned().collect()
    }

    /// Clear all baselines.
    pub fn clear(&self) -> usize {
        let mut map = self
            .inner
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let count = map.len();
        map.clear();
        count
    }
}

impl Default for ContractStore {
    fn default() -> Self {
        Self::new()
    }
}

// ── Startup Profiling ───────────────────────────────────────────────────────

/// A single phase in the startup timeline.
#[derive(Debug, Clone, Serialize)]
pub struct StartupPhase {
    /// Phase name.
    pub name: String,
    /// Duration of this phase in milliseconds.
    pub duration_ms: f64,
    /// Cumulative time from plugin init start.
    pub cumulative_ms: f64,
}

/// Records timestamps at key phases during plugin initialization.
pub struct StartupTimeline {
    start: Instant,
    phases: RwLock<Vec<(String, Instant)>>,
}

impl StartupTimeline {
    /// Begin recording from now.
    #[must_use]
    pub fn new() -> Self {
        Self {
            start: Instant::now(),
            phases: RwLock::new(Vec::new()),
        }
    }

    /// Mark a phase as completed.
    pub fn mark(&self, name: &str) {
        let mut phases = self
            .phases
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        phases.push((name.to_string(), Instant::now()));
    }

    /// Get the timeline as a list of phases with durations.
    #[must_use]
    pub fn report(&self) -> Vec<StartupPhase> {
        let phases = self
            .phases
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let mut result = Vec::new();
        let mut prev = self.start;

        for (name, instant) in phases.iter() {
            let duration = instant.duration_since(prev);
            let cumulative = instant.duration_since(self.start);
            result.push(StartupPhase {
                name: name.clone(),
                duration_ms: (duration.as_secs_f64() * 1000.0 * 100.0).round() / 100.0,
                cumulative_ms: (cumulative.as_secs_f64() * 1000.0 * 100.0).round() / 100.0,
            });
            prev = *instant;
        }
        result
    }

    /// Total time from start to last recorded phase.
    #[must_use]
    pub fn total_ms(&self) -> f64 {
        let phases = self
            .phases
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some((_, last)) = phases.last() {
            (last.duration_since(self.start).as_secs_f64() * 1000.0 * 100.0).round() / 100.0
        } else {
            0.0
        }
    }
}

impl Default for StartupTimeline {
    fn default() -> Self {
        Self::new()
    }
}

// ── Tauri Event Bus Monitor ─────────────────────────────────────────────

/// A Tauri event captured from the application's native event bus.
#[derive(Debug, Clone, Serialize)]
pub struct CapturedTauriEvent {
    /// Event name (e.g. "notification-added", `tauri://focus`).
    pub name: String,
    /// Serialized event payload.
    pub payload: String,
    /// ISO 8601 timestamp.
    pub timestamp: String,
}

const DEFAULT_EVENT_BUS_CAPACITY: usize = 1000;

/// Thread-safe ring buffer for captured Tauri events.
#[derive(Clone)]
pub struct EventBusMonitor {
    inner: std::sync::Arc<RwLock<VecDeque<CapturedTauriEvent>>>,
    capacity: usize,
}

impl EventBusMonitor {
    /// Create a new monitor with the given capacity.
    #[must_use]
    pub fn new(capacity: usize) -> Self {
        Self {
            inner: std::sync::Arc::new(RwLock::new(VecDeque::with_capacity(capacity))),
            capacity,
        }
    }

    /// Record a captured event.
    pub fn push(&self, event: CapturedTauriEvent) {
        let mut buf = self
            .inner
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if buf.len() >= self.capacity {
            buf.pop_front();
        }
        buf.push_back(event);
    }

    /// Get all captured events.
    #[must_use]
    pub fn events(&self) -> Vec<CapturedTauriEvent> {
        self.inner
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .iter()
            .cloned()
            .collect()
    }

    /// Get the number of captured events.
    #[must_use]
    pub fn len(&self) -> usize {
        self.inner
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .len()
    }

    /// Returns true if no events have been captured.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Clear all captured events, returning how many were removed.
    pub fn clear(&self) -> usize {
        let mut buf = self
            .inner
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let count = buf.len();
        buf.clear();
        count
    }
}

impl Default for EventBusMonitor {
    fn default() -> Self {
        Self::new(DEFAULT_EVENT_BUS_CAPACITY)
    }
}

// ── Internal Task Tracker ──────────────────────────────────────────────

/// Info about a tracked async task spawned by Victauri.
#[derive(Debug, Clone, Serialize)]
pub struct TrackedTaskInfo {
    /// Human-readable task name.
    pub name: String,
    /// ISO 8601 timestamp when the task was spawned.
    pub spawned_at: String,
    /// Whether the task has finished (completed or errored).
    pub is_finished: bool,
    /// How long the task has been running in seconds.
    pub uptime_secs: u64,
}

struct TrackedTaskEntry {
    name: String,
    spawned_at: Instant,
    spawned_at_wall: String,
    finished: std::sync::Arc<AtomicBool>,
}

/// Tracks Victauri's own spawned async tasks for observability.
pub struct TaskTracker {
    tasks: RwLock<Vec<TrackedTaskEntry>>,
}

impl TaskTracker {
    /// Create a new empty tracker.
    #[must_use]
    pub fn new() -> Self {
        Self {
            tasks: RwLock::new(Vec::new()),
        }
    }

    /// Register a new task. Returns a flag that the task should set to `true` when it finishes.
    pub fn track(&self, name: &str) -> std::sync::Arc<AtomicBool> {
        let finished = std::sync::Arc::new(AtomicBool::new(false));
        let entry = TrackedTaskEntry {
            name: name.to_string(),
            spawned_at: Instant::now(),
            spawned_at_wall: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
            finished: finished.clone(),
        };
        self.tasks
            .write()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .push(entry);
        finished
    }

    /// List all tracked tasks with their current status.
    #[must_use]
    pub fn list(&self) -> Vec<TrackedTaskInfo> {
        let tasks = self
            .tasks
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        tasks
            .iter()
            .map(|t| TrackedTaskInfo {
                name: t.name.clone(),
                spawned_at: t.spawned_at_wall.clone(),
                is_finished: t.finished.load(std::sync::atomic::Ordering::Relaxed),
                uptime_secs: t.spawned_at.elapsed().as_secs(),
            })
            .collect()
    }

    /// Count of active (non-finished) tasks.
    #[must_use]
    pub fn active_count(&self) -> usize {
        let tasks = self
            .tasks
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        tasks
            .iter()
            .filter(|t| !t.finished.load(std::sync::atomic::Ordering::Relaxed))
            .count()
    }
}

impl Default for TaskTracker {
    fn default() -> Self {
        Self::new()
    }
}

// ── Child Process Enumeration ──────────────────────────────────────────

/// Information about a child process of the Tauri application.
#[derive(Debug, Clone, Serialize)]
pub struct ChildProcessInfo {
    /// Process ID.
    pub pid: u32,
    /// Parent process ID.
    pub ppid: u32,
    /// Executable name (not full path).
    pub name: String,
    /// Memory usage in bytes (working set / RSS), if available.
    pub memory_bytes: Option<u64>,
}

/// Enumerate child processes of the current process.
///
/// Uses platform-native APIs:
/// - Windows: `CreateToolhelp32Snapshot` + `Process32First/Next`
/// - Linux: `/proc/` filesystem
/// - macOS: `proc_listpids` + `proc_pidinfo`
#[must_use]
pub fn enumerate_child_processes() -> Vec<ChildProcessInfo> {
    let my_pid = std::process::id();

    #[cfg(windows)]
    {
        enumerate_children_windows(my_pid)
    }

    #[cfg(target_os = "linux")]
    {
        enumerate_children_linux(my_pid)
    }

    #[cfg(target_os = "macos")]
    {
        enumerate_children_macos(my_pid)
    }

    #[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
    {
        let _ = my_pid;
        Vec::new()
    }
}

#[cfg(windows)]
#[allow(unsafe_code)]
fn enumerate_children_windows(parent_pid: u32) -> Vec<ChildProcessInfo> {
    use windows::Win32::Foundation::CloseHandle;
    use windows::Win32::System::Diagnostics::ToolHelp::{
        CreateToolhelp32Snapshot, PROCESSENTRY32, Process32First, Process32Next, TH32CS_SNAPPROCESS,
    };

    let mut children = Vec::new();

    // SAFETY: `CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)` creates a
    // read-only snapshot of all running processes. The returned handle is
    // closed via `CloseHandle` when we're done. `Process32First/Next` iterate
    // the snapshot entries.
    unsafe {
        let Ok(snapshot) = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) else {
            return children;
        };

        let mut entry: PROCESSENTRY32 = std::mem::zeroed();
        entry.dwSize = std::mem::size_of::<PROCESSENTRY32>() as u32;

        if Process32First(snapshot, &mut entry).is_ok() {
            loop {
                if entry.th32ParentProcessID == parent_pid && entry.th32ProcessID != parent_pid {
                    let name_bytes: Vec<u8> = entry
                        .szExeFile
                        .iter()
                        .take_while(|&&b| b != 0)
                        .map(|&b| b as u8)
                        .collect();
                    let name = String::from_utf8_lossy(&name_bytes).to_string();

                    let memory_bytes = get_process_memory_windows(entry.th32ProcessID);

                    children.push(ChildProcessInfo {
                        pid: entry.th32ProcessID,
                        ppid: entry.th32ParentProcessID,
                        name,
                        memory_bytes,
                    });
                }

                if Process32Next(snapshot, &mut entry).is_err() {
                    break;
                }
            }
        }

        let _ = CloseHandle(snapshot);
    }

    children
}

#[cfg(windows)]
#[allow(unsafe_code)]
fn get_process_memory_windows(pid: u32) -> Option<u64> {
    use windows::Win32::System::ProcessStatus::{GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
    use windows::Win32::System::Threading::{
        OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_VM_READ,
    };

    // SAFETY: `OpenProcess` with `PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ`
    // opens a limited handle for reading memory stats. The process handle is closed
    // automatically when dropped (windows crate handles this).
    unsafe {
        let process = OpenProcess(
            PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ,
            false,
            pid,
        )
        .ok()?;

        let mut counters: PROCESS_MEMORY_COUNTERS = std::mem::zeroed();
        counters.cb = std::mem::size_of::<PROCESS_MEMORY_COUNTERS>() as u32;

        if GetProcessMemoryInfo(process, &mut counters, counters.cb).is_ok() {
            Some(counters.WorkingSetSize as u64)
        } else {
            None
        }
    }
}

#[cfg(target_os = "linux")]
fn enumerate_children_linux(parent_pid: u32) -> Vec<ChildProcessInfo> {
    let mut children = Vec::new();
    let Ok(entries) = std::fs::read_dir("/proc") else {
        return children;
    };

    for entry in entries.flatten() {
        let file_name = entry.file_name();
        let Some(pid_str) = file_name.to_str() else {
            continue;
        };
        let Ok(pid) = pid_str.parse::<u32>() else {
            continue;
        };

        let status_path = format!("/proc/{pid}/status");
        let Ok(status) = std::fs::read_to_string(&status_path) else {
            continue;
        };

        let mut ppid: Option<u32> = None;
        let mut name = String::new();
        let mut vm_rss_kb: u64 = 0;

        for line in status.lines() {
            if let Some(v) = line.strip_prefix("PPid:\t") {
                ppid = v.trim().parse().ok();
            } else if let Some(v) = line.strip_prefix("Name:\t") {
                name = v.trim().to_string();
            } else if let Some(v) = line.strip_prefix("VmRSS:") {
                vm_rss_kb = v
                    .split_whitespace()
                    .next()
                    .and_then(|n| n.parse().ok())
                    .unwrap_or(0);
            }
        }

        if ppid == Some(parent_pid) {
            children.push(ChildProcessInfo {
                pid,
                ppid: parent_pid,
                name,
                memory_bytes: if vm_rss_kb > 0 {
                    Some(vm_rss_kb * 1024)
                } else {
                    None
                },
            });
        }
    }

    children
}

#[cfg(target_os = "macos")]
#[allow(unsafe_code)]
fn enumerate_children_macos(parent_pid: u32) -> Vec<ChildProcessInfo> {
    use std::mem;

    unsafe extern "C" {
        fn proc_listchildpids(ppid: i32, buffer: *mut i32, buffersize: i32) -> i32;
        fn proc_pidinfo(pid: i32, flavor: i32, arg: u64, buffer: *mut u8, buffersize: i32) -> i32;
        fn proc_name(pid: i32, buffer: *mut u8, buffersize: u32) -> i32;
    }

    const PROC_PIDTASKINFO: i32 = 4;

    #[repr(C)]
    struct ProcTaskInfo {
        pti_virtual_size: u64,
        pti_resident_size: u64,
        pti_total_user: u64,
        pti_total_system: u64,
        pti_threads_user: u64,
        pti_threads_system: u64,
        pti_policy: i32,
        pti_faults: i32,
        pti_pageins: i32,
        pti_cow_faults: i32,
        pti_messages_sent: i32,
        pti_messages_received: i32,
        pti_syscalls_mach: i32,
        pti_syscalls_unix: i32,
        pti_csw: i32,
        pti_threadnum: i32,
        pti_numrunning: i32,
        pti_priority: i32,
    }

    let mut children = Vec::new();

    // SAFETY: `proc_listchildpids` populates a buffer of child PIDs for the given
    // parent PID. We first call with a zero buffer to get the count, then allocate
    // and call again. `proc_name` and `proc_pidinfo` read metadata for a given PID.
    unsafe {
        let ppid = parent_pid as i32;
        let count = proc_listchildpids(ppid, std::ptr::null_mut(), 0);
        if count <= 0 {
            return children;
        }

        let mut pids = vec![0i32; count as usize];
        let buf_size = (count as usize * mem::size_of::<i32>()) as i32;
        let actual = proc_listchildpids(ppid, pids.as_mut_ptr(), buf_size);
        if actual <= 0 {
            return children;
        }

        let n = actual as usize / mem::size_of::<i32>();
        for &pid in &pids[..n] {
            if pid <= 0 {
                continue;
            }

            let mut name_buf = [0u8; 256];
            let name_len = proc_name(pid, name_buf.as_mut_ptr(), 256);
            let name = if name_len > 0 {
                String::from_utf8_lossy(&name_buf[..name_len as usize]).to_string()
            } else {
                String::from("<unknown>")
            };

            let mut task_info: ProcTaskInfo = mem::zeroed();
            let info_size = mem::size_of::<ProcTaskInfo>() as i32;
            let ret = proc_pidinfo(
                pid,
                PROC_PIDTASKINFO,
                0,
                &mut task_info as *mut _ as *mut u8,
                info_size,
            );

            let memory_bytes = if ret == info_size {
                Some(task_info.pti_resident_size)
            } else {
                None
            };

            children.push(ChildProcessInfo {
                pid: pid as u32,
                ppid: parent_pid,
                name,
                memory_bytes,
            });
        }
    }

    children
}

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

    #[test]
    fn event_bus_push_and_read() {
        let bus = EventBusMonitor::new(3);
        assert!(bus.is_empty());
        bus.push(CapturedTauriEvent {
            name: "test".to_string(),
            payload: "{}".to_string(),
            timestamp: "2026-01-01T00:00:00Z".to_string(),
        });
        assert_eq!(bus.len(), 1);
        assert_eq!(bus.events()[0].name, "test");
    }

    #[test]
    fn event_bus_ring_buffer_eviction() {
        let bus = EventBusMonitor::new(2);
        for i in 0..5 {
            bus.push(CapturedTauriEvent {
                name: format!("event_{i}"),
                payload: String::new(),
                timestamp: String::new(),
            });
        }
        assert_eq!(bus.len(), 2);
        assert_eq!(bus.events()[0].name, "event_3");
        assert_eq!(bus.events()[1].name, "event_4");
    }

    #[test]
    fn event_bus_clear() {
        let bus = EventBusMonitor::new(10);
        bus.push(CapturedTauriEvent {
            name: "a".to_string(),
            payload: String::new(),
            timestamp: String::new(),
        });
        assert_eq!(bus.clear(), 1);
        assert!(bus.is_empty());
    }

    #[test]
    fn task_tracker_lifecycle() {
        let tracker = TaskTracker::new();
        let flag = tracker.track("mcp_server");
        let tasks = tracker.list();
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0].name, "mcp_server");
        assert!(!tasks[0].is_finished);
        assert_eq!(tracker.active_count(), 1);

        flag.store(true, std::sync::atomic::Ordering::Relaxed);
        let tasks = tracker.list();
        assert!(tasks[0].is_finished);
        assert_eq!(tracker.active_count(), 0);
    }

    #[test]
    fn timing_samples_basic() {
        let mut samples = TimingSamples::default();
        samples.record(Duration::from_millis(10));
        samples.record(Duration::from_millis(20));
        samples.record(Duration::from_millis(30));
        let stats = samples.stats("test_cmd");
        assert_eq!(stats.count, 3);
        assert!((stats.min_ms - 10.0).abs() < 1.0);
        assert!((stats.max_ms - 30.0).abs() < 1.0);
        assert!((stats.avg_ms - 20.0).abs() < 1.0);
    }

    #[test]
    fn timing_samples_empty() {
        let samples = TimingSamples::default();
        let stats = samples.stats("empty");
        assert_eq!(stats.count, 0);
        assert_eq!(stats.min_ms, 0.0);
    }

    #[test]
    fn command_timings_thread_safe() {
        let timings = CommandTimings::new();
        timings.record("cmd_a", Duration::from_millis(5));
        timings.record("cmd_a", Duration::from_millis(15));
        timings.record("cmd_b", Duration::from_millis(100));

        let all = timings.all_stats();
        assert_eq!(all.len(), 2);
        assert_eq!(all[0].command, "cmd_b");

        let a = timings.stats_for("cmd_a").unwrap();
        assert_eq!(a.count, 2);
    }

    #[test]
    fn fault_registry_lifecycle() {
        let registry = FaultRegistry::new();
        registry.inject(FaultConfig {
            command: "slow_cmd".to_string(),
            fault_type: FaultType::Delay { delay_ms: 500 },
            trigger_count: 0,
            max_triggers: 2,
            created_at: Instant::now(),
        });

        assert!(registry.check_and_trigger("slow_cmd").is_some());
        assert!(registry.check_and_trigger("slow_cmd").is_some());
        assert!(registry.check_and_trigger("slow_cmd").is_none());

        assert_eq!(registry.list().len(), 1);
        assert!(registry.clear("slow_cmd"));
        assert_eq!(registry.list().len(), 0);
    }

    #[test]
    fn fault_registry_unlimited() {
        let registry = FaultRegistry::new();
        registry.inject(FaultConfig {
            command: "always_fail".to_string(),
            fault_type: FaultType::Error {
                message: "injected".to_string(),
            },
            trigger_count: 0,
            max_triggers: 0,
            created_at: Instant::now(),
        });

        for _ in 0..100 {
            assert!(registry.check_and_trigger("always_fail").is_some());
        }
    }

    #[test]
    fn json_shape_extraction() {
        let value = serde_json::json!({
            "name": "test",
            "count": 42,
            "active": true,
            "items": [{"id": 1}],
            "meta": null
        });
        let shape = JsonShape::from_value(&value);
        match &shape {
            JsonShape::Object(fields) => {
                assert_eq!(fields.len(), 5);
                assert_eq!(*fields.get("name").unwrap(), JsonShape::String);
                assert_eq!(*fields.get("count").unwrap(), JsonShape::Number);
                assert_eq!(*fields.get("active").unwrap(), JsonShape::Bool);
                assert_eq!(*fields.get("meta").unwrap(), JsonShape::Null);
            }
            _ => panic!("expected object"),
        }
    }

    #[test]
    fn contract_diff_detects_changes() {
        let baseline = serde_json::json!({"name": "old", "count": 1});
        let current = serde_json::json!({"name": "new", "count": "not_a_number", "extra": true});

        let b_shape = JsonShape::from_value(&baseline);
        let c_shape = JsonShape::from_value(&current);
        let drift = diff_shapes(&b_shape, &c_shape, "test_cmd");

        assert!(!drift.shape_matches);
        assert_eq!(drift.new_fields, vec!["test_cmd.extra"]);
        assert_eq!(drift.type_changes.len(), 1);
        assert_eq!(drift.type_changes[0].path, "test_cmd.count");
    }

    #[test]
    fn contract_store_crud() {
        let store = ContractStore::new();
        let baseline = ContractBaseline {
            command: "get_user".to_string(),
            args: serde_json::json!({}),
            shape: JsonShape::Object(HashMap::new()),
            sample: "{}".to_string(),
            recorded_at: "2026-05-26".to_string(),
        };
        store.record(baseline);
        assert!(store.get("get_user").is_some());
        assert_eq!(store.all().len(), 1);
        assert_eq!(store.clear(), 1);
        assert!(store.get("get_user").is_none());
    }

    #[test]
    fn startup_timeline_records_phases() {
        let timeline = StartupTimeline::new();
        std::thread::sleep(Duration::from_millis(5));
        timeline.mark("phase_1");
        std::thread::sleep(Duration::from_millis(5));
        timeline.mark("phase_2");

        let report = timeline.report();
        assert_eq!(report.len(), 2);
        assert_eq!(report[0].name, "phase_1");
        assert!(report[1].cumulative_ms >= report[0].cumulative_ms);
        assert!(timeline.total_ms() > 0.0);
    }

    #[test]
    fn enumerate_child_processes_returns_vec() {
        let children = enumerate_child_processes();
        // The test process itself may or may not have children, but the
        // function must not panic and must return a well-formed Vec.
        for child in &children {
            assert_ne!(child.pid, 0, "child PID should be non-zero");
            assert_eq!(
                child.ppid,
                std::process::id(),
                "parent PID should match current process"
            );
            assert!(!child.name.is_empty(), "child name should not be empty");
        }
    }

    #[test]
    fn enumerate_child_processes_with_spawned_child() {
        // Spawn a short-lived child process and verify we can enumerate it.
        let child = std::process::Command::new(if cfg!(windows) { "cmd.exe" } else { "sleep" })
            .args(if cfg!(windows) {
                &["/c", "timeout /t 10 /nobreak >nul"][..]
            } else {
                &["10"][..]
            })
            .spawn();

        if let Ok(mut child_proc) = child {
            let children = enumerate_child_processes();
            assert!(
                !children.is_empty(),
                "should find at least one child process"
            );

            let found = children.iter().any(|c| c.pid == child_proc.id());
            assert!(
                found,
                "spawned child (PID {}) should appear in enumeration",
                child_proc.id()
            );

            let _ = child_proc.kill();
            let _ = child_proc.wait();
        }
    }

    #[test]
    fn child_process_info_serializes() {
        let info = ChildProcessInfo {
            pid: 1234,
            ppid: 5678,
            name: "test-sidecar".to_string(),
            memory_bytes: Some(1_048_576),
        };
        let json = serde_json::to_value(&info).unwrap();
        assert_eq!(json["pid"], 1234);
        assert_eq!(json["ppid"], 5678);
        assert_eq!(json["name"], "test-sidecar");
        assert_eq!(json["memory_bytes"], 1_048_576);
    }

    #[test]
    fn child_process_info_serializes_no_memory() {
        let info = ChildProcessInfo {
            pid: 42,
            ppid: 1,
            name: "zombie".to_string(),
            memory_bytes: None,
        };
        let json = serde_json::to_value(&info).unwrap();
        assert!(json["memory_bytes"].is_null());
    }
}