pluggable 0.1.0

A comprehensive, async plugin system for Rust applications with dependency management and security
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
//! Plugin executor for orchestrating plugin execution with dependency management

use std::collections::HashMap;
use std::path::PathBuf;
use std::time::Instant;
use tokio::task::JoinSet;

use crate::core::{
    system_events, Event, EventBus, Plugin, PluginContext, PluginError, PluginOutput,
    PluginRegistry, PluginResult, PluginSystemConfig, RetryConfig, SandboxManager, SecurityManager,
};
use std::sync::Arc;

/// Executor for orchestrating plugin execution with dependency management
pub struct PluginExecutor {
    registry: PluginRegistry,
    workspace: PathBuf,
    security_manager: SecurityManager,
    sandbox_manager: SandboxManager,
    config: PluginSystemConfig,
    event_bus: Arc<EventBus>,
}

/// Result of executing a plugin pipeline
#[derive(Debug)]
pub struct ExecutionResult {
    pub success: bool,
    pub plugin_outputs: HashMap<String, PluginOutput>,
    pub execution_order: Vec<Vec<String>>,
    pub total_duration: std::time::Duration,
    pub failed_plugins: Vec<String>,
}

impl PluginExecutor {
    /// Create a new plugin executor with the given registry
    pub fn new(registry: PluginRegistry, workspace: PathBuf) -> Self {
        Self {
            registry,
            workspace,
            security_manager: SecurityManager::new(),
            sandbox_manager: SandboxManager::new(),
            config: PluginSystemConfig::default(),
            event_bus: Arc::new(EventBus::new()),
        }
    }

    /// Create a new plugin executor with configuration
    pub fn with_config(registry: PluginRegistry, config: PluginSystemConfig) -> Self {
        let workspace = config
            .system
            .workspace
            .clone()
            .unwrap_or_else(|| std::env::temp_dir().join("pluggable-workspace"));

        Self {
            registry,
            workspace,
            security_manager: SecurityManager::new(),
            sandbox_manager: SandboxManager::new(),
            config,
            event_bus: Arc::new(EventBus::new()),
        }
    }

    /// Create a new plugin executor with custom security manager
    pub fn with_security_manager(
        registry: PluginRegistry,
        workspace: PathBuf,
        security_manager: SecurityManager,
    ) -> Self {
        Self {
            registry,
            workspace,
            security_manager,
            sandbox_manager: SandboxManager::new(),
            config: PluginSystemConfig::default(),
            event_bus: Arc::new(EventBus::new()),
        }
    }

    /// Create a new plugin executor with custom security and sandbox managers
    pub fn with_managers(
        registry: PluginRegistry,
        workspace: PathBuf,
        security_manager: SecurityManager,
        sandbox_manager: SandboxManager,
    ) -> Self {
        Self {
            registry,
            workspace,
            security_manager,
            sandbox_manager,
            config: PluginSystemConfig::default(),
            event_bus: Arc::new(EventBus::new()),
        }
    }

    /// Create a new plugin executor with full configuration
    pub fn with_full_config(
        registry: PluginRegistry,
        config: PluginSystemConfig,
        security_manager: SecurityManager,
        sandbox_manager: SandboxManager,
    ) -> Self {
        let workspace = config
            .system
            .workspace
            .clone()
            .unwrap_or_else(|| std::env::temp_dir().join("pluggable-workspace"));

        Self {
            registry,
            workspace,
            security_manager,
            sandbox_manager,
            config,
            event_bus: Arc::new(EventBus::new()),
        }
    }

    /// Execute all plugins in the registry according to their dependencies
    pub async fn execute_pipeline(&mut self) -> PluginResult<ExecutionResult> {
        let start_time = Instant::now();

        // Publish pipeline started event
        if let Err(e) = self
            .event_bus
            .publish(Event::new(
                system_events::PIPELINE_STARTED,
                serde_json::json!({
                    "plugin_count": self.registry.len()
                }),
            ))
            .await
        {
            eprintln!("Warning: Failed to publish pipeline started event: {e}");
        }

        // Validate dependencies before execution
        self.registry.validate_dependencies()?;

        // Get execution order
        let execution_order = self.registry.resolve_execution_order()?;

        let mut plugin_outputs = HashMap::new();
        let mut failed_plugins = Vec::new();
        let mut global_success = true;

        // Execute plugins in batches
        for batch in &execution_order {
            let batch_result = self.execute_batch(batch, &plugin_outputs).await;

            match batch_result {
                Ok(batch_outputs) => {
                    // Add successful outputs to global results
                    for (plugin_name, output) in batch_outputs {
                        plugin_outputs.insert(plugin_name, output);
                    }
                }
                Err(batch_errors) => {
                    // Handle batch failures
                    global_success = false;
                    for (plugin_name, error) in batch_errors {
                        failed_plugins.push(plugin_name.clone());
                        // Create failure output for failed plugin
                        plugin_outputs.insert(
                            plugin_name,
                            PluginOutput::failure(format!("Execution failed: {error}")),
                        );
                    }
                    // Stop execution on first batch failure
                    break;
                }
            }
        }

        let total_duration = start_time.elapsed();

        // Publish pipeline completion event
        let pipeline_event = if global_success {
            Event::new(
                system_events::PIPELINE_COMPLETED,
                serde_json::json!({
                    "success": true,
                    "duration_ms": total_duration.as_millis(),
                    "plugin_count": plugin_outputs.len(),
                    "failed_plugins": failed_plugins.len()
                }),
            )
        } else {
            Event::new(
                system_events::PIPELINE_FAILED,
                serde_json::json!({
                    "success": false,
                    "duration_ms": total_duration.as_millis(),
                    "plugin_count": plugin_outputs.len(),
                    "failed_plugins": failed_plugins.clone()
                }),
            )
            .with_priority(crate::core::events::EventPriority::High)
        };

        if let Err(e) = self.event_bus.publish(pipeline_event).await {
            eprintln!("Warning: Failed to publish pipeline completion event: {e}");
        }

        Ok(ExecutionResult {
            success: global_success,
            plugin_outputs,
            execution_order,
            total_duration,
            failed_plugins,
        })
    }

    /// Execute a single batch of plugins (can run in parallel)
    async fn execute_batch(
        &mut self,
        batch: &[String],
        previous_outputs: &HashMap<String, PluginOutput>,
    ) -> Result<HashMap<String, PluginOutput>, HashMap<String, PluginError>> {
        let mut join_set = JoinSet::new();
        let mut plugin_handles = HashMap::new();
        let max_parallel = self.config.system.max_parallel_plugins;

        // Limit batch size to configured maximum parallel plugins
        let batch_size = std::cmp::min(batch.len(), max_parallel);
        let batch_slice = &batch[..batch_size];

        // Start plugins in the batch (up to max_parallel_plugins)
        for plugin_name in batch_slice {
            // Take ownership of the plugin for execution
            if let Some(plugin) = self.registry.take_plugin(plugin_name) {
                // Get plugin permissions from configuration or plugin itself
                let plugin_permissions =
                    if let Some(plugin_config) = self.config.plugins.get(plugin_name) {
                        if !plugin_config.permissions.is_empty() {
                            plugin_config.permissions.clone()
                        } else {
                            plugin.permissions()
                        }
                    } else {
                        plugin.permissions()
                    };

                // Validate plugin permissions before execution
                if let Err(e) = self
                    .security_manager
                    .validate_plugin_permissions(plugin_name, &plugin_permissions)
                {
                    let mut errors = HashMap::new();
                    errors.insert(plugin_name.clone(), e);
                    return Err(errors);
                }

                // Grant permissions to the plugin
                self.security_manager
                    .grant_permissions(plugin_name, plugin_permissions);

                // Create security context
                let security_context = match self.security_manager.create_context(plugin_name) {
                    Ok(ctx) => ctx,
                    Err(e) => {
                        let mut errors = HashMap::new();
                        errors.insert(plugin_name.clone(), e);
                        return Err(errors);
                    }
                };

                // Create sandbox for plugin isolation
                if let Err(e) = self
                    .sandbox_manager
                    .create_sandbox(plugin_name.clone(), security_context.clone())
                    .await
                {
                    let mut errors = HashMap::new();
                    errors.insert(plugin_name.clone(), e);
                    return Err(errors);
                }

                // Create plugin context with security and event bus
                let mut context = PluginContext::with_security_and_events(
                    plugin_name.clone(),
                    self.workspace.clone(),
                    security_context,
                    self.event_bus.clone(),
                );

                // Add dependency outputs to context
                let plugin_metadata = plugin.metadata();
                for dependency in &plugin_metadata.dependencies {
                    if let Some(dep_output) = previous_outputs.get(dependency) {
                        context.add_dependency_output(dependency.clone(), dep_output.clone());
                    }
                }

                // Get plugin configuration from system config
                let plugin_config = self
                    .config
                    .plugins
                    .get(plugin_name)
                    .map(|pc| pc.config.clone())
                    .unwrap_or_else(|| serde_json::json!({}));

                // Get retry configuration for the plugin
                let retry_config = self
                    .config
                    .plugins
                    .get(plugin_name)
                    .map(|pc| &pc.retry)
                    .cloned()
                    .unwrap_or_default();

                // Spawn plugin execution with retry logic
                let handle = join_set.spawn(async move {
                    Self::execute_single_plugin_with_retry(
                        plugin,
                        plugin_config,
                        context,
                        retry_config,
                    )
                    .await
                });

                plugin_handles.insert(plugin_name.clone(), handle);

                // If we've reached the parallel limit, break
                if plugin_handles.len() >= max_parallel {
                    break;
                }
            } else {
                // Plugin not found in registry
                let mut errors = HashMap::new();
                errors.insert(
                    plugin_name.clone(),
                    PluginError::PluginNotFound(plugin_name.clone()),
                );
                return Err(errors);
            }
        }

        // Collect results
        let mut batch_outputs = HashMap::new();
        let mut batch_errors = HashMap::new();

        while let Some(result) = join_set.join_next().await {
            match result {
                Ok((plugin_name, plugin_result, plugin_box)) => {
                    // Cleanup sandbox after plugin execution
                    if let Err(e) = self.sandbox_manager.remove_sandbox(&plugin_name).await {
                        eprintln!("Warning: Failed to cleanup sandbox for '{plugin_name}': {e}");
                    }

                    // Put plugin back in registry
                    if let Err(e) = self.registry.put_plugin(plugin_box) {
                        batch_errors.insert(plugin_name.clone(), e);
                        continue;
                    }

                    match plugin_result {
                        Ok(output) => {
                            batch_outputs.insert(plugin_name, output);
                        }
                        Err(error) => {
                            batch_errors.insert(plugin_name, error);
                        }
                    }
                }
                Err(join_error) => {
                    // Task join error (panic or cancellation)
                    batch_errors.insert(
                        "unknown".to_string(),
                        PluginError::ExecutionFailed(format!("Task join error: {join_error}")),
                    );
                }
            }
        }

        if batch_errors.is_empty() {
            Ok(batch_outputs)
        } else {
            Err(batch_errors)
        }
    }

    /// Execute a single plugin with retry logic
    async fn execute_single_plugin_with_retry(
        plugin: Box<dyn Plugin>,
        config: serde_json::Value,
        context: PluginContext,
        retry_config: RetryConfig,
    ) -> (String, PluginResult<PluginOutput>, Box<dyn Plugin>) {
        let plugin_name = plugin.metadata().name.clone();
        let mut current_plugin = plugin;
        let mut last_error = None;

        for attempt in 0..retry_config.max_attempts {
            let result =
                Self::execute_single_plugin(current_plugin, config.clone(), context.clone()).await;

            match &result.1 {
                Ok(_) => return result, // Success, return immediately
                Err(e) => {
                    last_error = Some(e.clone());
                    current_plugin = result.2;

                    if attempt < retry_config.max_attempts - 1 {
                        // Calculate delay with exponential backoff
                        let delay = std::cmp::min(
                            (retry_config.delay_ms as f64
                                * retry_config.backoff_multiplier.powi(attempt as i32))
                                as u64,
                            retry_config.max_delay_ms,
                        );

                        tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
                    }
                }
            }
        }

        // All retries failed, return the last error
        (plugin_name, Err(last_error.unwrap()), current_plugin)
    }

    /// Execute a single plugin through its full lifecycle with hooks and events
    async fn execute_single_plugin(
        mut plugin: Box<dyn Plugin>,
        config: serde_json::Value,
        mut context: PluginContext,
    ) -> (String, PluginResult<PluginOutput>, Box<dyn Plugin>) {
        let plugin_name = plugin.metadata().name.clone();
        let start_time = Instant::now();

        // Publish plugin execution started event
        if let Err(e) = context
            .publish_event(system_events::plugin_execution_started(&plugin_name))
            .await
        {
            eprintln!("Warning: Failed to publish execution started event: {e}");
        }

        let result = async {
            // === INITIALIZATION PHASE ===

            // Call before_initialize hook
            plugin.before_initialize(&context).await?;

            // Initialize plugin
            plugin.initialize(config, &context).await?;

            // Call after_initialize hook
            plugin.after_initialize(&context).await?;

            // Publish initialized event
            if let Err(e) = context
                .publish_event(system_events::plugin_initialized(&plugin_name))
                .await
            {
                eprintln!("Warning: Failed to publish initialized event: {e}");
            }

            // === EXECUTION PHASE ===

            // Call before_execute hook
            plugin.before_execute(&context).await?;

            // Execute plugin
            let mut output = plugin.execute(&mut context).await?;

            // Update execution time
            output.execution_time = start_time.elapsed();

            // Call after_execute hook
            plugin.after_execute(&context, &output).await?;

            // Call on_success hook
            plugin.on_success(&context, &output).await?;

            Ok(output)
        }
        .await;

        // Handle result and call appropriate hooks
        let final_result = match &result {
            Ok(_output) => {
                // Publish execution completed event
                if let Err(e) = context
                    .publish_event(system_events::plugin_execution_completed(
                        &plugin_name,
                        start_time.elapsed(),
                    ))
                    .await
                {
                    eprintln!("Warning: Failed to publish execution completed event: {e}");
                }
                result
            }
            Err(error) => {
                // Call on_error hook
                if let Err(hook_error) = plugin.on_error(&context, error).await {
                    eprintln!("Warning: on_error hook failed for {plugin_name}: {hook_error}");
                }

                // Publish execution failed event
                if let Err(e) = context
                    .publish_event(system_events::plugin_execution_failed(&plugin_name, error))
                    .await
                {
                    eprintln!("Warning: Failed to publish execution failed event: {e}");
                }
                result
            }
        };

        // === CLEANUP PHASE ===

        // Publish cleanup started event
        if let Err(e) = context
            .publish_event(system_events::plugin_cleanup_started(&plugin_name))
            .await
        {
            eprintln!("Warning: Failed to publish cleanup started event: {e}");
        }

        // Call before_cleanup hook
        if let Err(hook_error) = plugin.before_cleanup(&context).await {
            eprintln!("Warning: before_cleanup hook failed for {plugin_name}: {hook_error}");
        }

        // Cleanup regardless of success/failure
        let cleanup_result = plugin.cleanup(&context).await;

        // Call after_cleanup hook if cleanup succeeded
        if cleanup_result.is_ok() {
            if let Err(hook_error) = plugin.after_cleanup(&context).await {
                eprintln!("Warning: after_cleanup hook failed for {plugin_name}: {hook_error}");
            }
        }

        // Publish cleanup completed event
        if let Err(e) = context
            .publish_event(system_events::plugin_cleanup_completed(&plugin_name))
            .await
        {
            eprintln!("Warning: Failed to publish cleanup completed event: {e}");
        }

        // Handle cleanup errors
        if let Err(cleanup_error) = cleanup_result {
            if final_result.is_ok() {
                // If execution succeeded but cleanup failed, return cleanup error
                return (
                    plugin_name,
                    Err(PluginError::CleanupFailed(cleanup_error.to_string())),
                    plugin,
                );
            }
            // If execution already failed, log cleanup error but return original error
            eprintln!("Warning: Plugin cleanup failed: {cleanup_error}");
        }

        (plugin_name, final_result, plugin)
    }

    /// Execute a single plugin by name (using configuration)
    pub async fn execute_plugin(&mut self, plugin_name: &str) -> PluginResult<PluginOutput> {
        let plugin = self
            .registry
            .take_plugin(plugin_name)
            .ok_or_else(|| PluginError::PluginNotFound(plugin_name.to_string()))?;

        // Validate plugin permissions
        let plugin_permissions = plugin.permissions();
        self.security_manager
            .validate_plugin_permissions(plugin_name, &plugin_permissions)?;

        // Grant permissions to the plugin
        self.security_manager
            .grant_permissions(plugin_name, plugin_permissions);

        // Create security context
        let security_context = self.security_manager.create_context(plugin_name)?;

        // Create sandbox for plugin isolation
        self.sandbox_manager
            .create_sandbox(plugin_name.to_string(), security_context.clone())
            .await?;

        // Create plugin context with security and event bus
        let context = PluginContext::with_security_and_events(
            plugin_name,
            self.workspace.clone(),
            security_context,
            self.event_bus.clone(),
        );

        // Get plugin configuration and retry settings
        let plugin_config = self
            .config
            .plugins
            .get(plugin_name)
            .map(|pc| pc.config.clone())
            .unwrap_or_else(|| serde_json::json!({}));

        let retry_config = self
            .config
            .plugins
            .get(plugin_name)
            .map(|pc| &pc.retry)
            .cloned()
            .unwrap_or_default();

        let (_, result, plugin_box) =
            Self::execute_single_plugin_with_retry(plugin, plugin_config, context, retry_config)
                .await;

        // Cleanup sandbox after plugin execution
        if let Err(e) = self.sandbox_manager.remove_sandbox(plugin_name).await {
            eprintln!("Warning: Failed to cleanup sandbox for '{plugin_name}': {e}");
        }

        // Put plugin back
        self.registry.put_plugin(plugin_box)?;

        result
    }

    /// Get the underlying registry
    pub fn registry(&self) -> &PluginRegistry {
        &self.registry
    }

    /// Get a mutable reference to the underlying registry
    pub fn registry_mut(&mut self) -> &mut PluginRegistry {
        &mut self.registry
    }

    /// Get a mutable reference to the underlying security manager
    pub fn security_manager_mut(&mut self) -> &mut SecurityManager {
        &mut self.security_manager
    }

    /// Get a reference to the underlying sandbox manager
    pub fn sandbox_manager(&self) -> &SandboxManager {
        &self.sandbox_manager
    }

    /// Get a mutable reference to the underlying sandbox manager
    pub fn sandbox_manager_mut(&mut self) -> &mut SandboxManager {
        &mut self.sandbox_manager
    }

    /// Get a reference to the event bus
    pub fn event_bus(&self) -> &Arc<EventBus> {
        &self.event_bus
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{Permission, PluginMetadata, PluginRegistry, SecurityManager};
    use async_trait::async_trait;
    use serde_json::json;
    use tempfile::TempDir;

    // Test plugin implementations
    struct TestPluginA {
        metadata: PluginMetadata,
        execution_count: std::sync::Arc<std::sync::Mutex<u32>>,
    }

    impl TestPluginA {
        fn new(execution_count: std::sync::Arc<std::sync::Mutex<u32>>) -> Self {
            let mut metadata = PluginMetadata::new("plugin-a", "1.0.0");
            metadata.dependencies = vec![];
            Self {
                metadata,
                execution_count,
            }
        }
    }

    #[async_trait]
    impl Plugin for TestPluginA {
        fn metadata(&self) -> &PluginMetadata {
            &self.metadata
        }

        fn schema(&self) -> serde_json::Value {
            json!({})
        }

        async fn initialize(
            &mut self,
            _config: serde_json::Value,
            _context: &PluginContext,
        ) -> PluginResult<()> {
            Ok(())
        }

        async fn execute(&mut self, _context: &mut PluginContext) -> PluginResult<PluginOutput> {
            let mut count = self.execution_count.lock().unwrap();
            *count += 1;
            Ok(PluginOutput::success(
                json!({"plugin": "a", "count": *count}),
            ))
        }

        async fn cleanup(&mut self, _context: &PluginContext) -> PluginResult<()> {
            Ok(())
        }
    }

    struct TestPluginB {
        metadata: PluginMetadata,
        execution_count: std::sync::Arc<std::sync::Mutex<u32>>,
    }

    impl TestPluginB {
        fn new(execution_count: std::sync::Arc<std::sync::Mutex<u32>>) -> Self {
            let mut metadata = PluginMetadata::new("plugin-b", "1.0.0");
            metadata.dependencies = vec!["plugin-a".to_string()];
            Self {
                metadata,
                execution_count,
            }
        }
    }

    #[async_trait]
    impl Plugin for TestPluginB {
        fn metadata(&self) -> &PluginMetadata {
            &self.metadata
        }

        fn schema(&self) -> serde_json::Value {
            json!({})
        }

        async fn initialize(
            &mut self,
            _config: serde_json::Value,
            _context: &PluginContext,
        ) -> PluginResult<()> {
            Ok(())
        }

        async fn execute(&mut self, context: &mut PluginContext) -> PluginResult<PluginOutput> {
            // Verify dependency output is available
            let dep_output = context.get_dependency_output("plugin-a");
            assert!(dep_output.is_some());

            let mut count = self.execution_count.lock().unwrap();
            *count += 1;
            Ok(PluginOutput::success(
                json!({"plugin": "b", "count": *count}),
            ))
        }

        async fn cleanup(&mut self, _context: &PluginContext) -> PluginResult<()> {
            Ok(())
        }
    }

    struct FailingPlugin {
        metadata: PluginMetadata,
    }

    impl FailingPlugin {
        fn new() -> Self {
            let metadata = PluginMetadata::new("failing-plugin", "1.0.0");
            Self { metadata }
        }
    }

    #[async_trait]
    impl Plugin for FailingPlugin {
        fn metadata(&self) -> &PluginMetadata {
            &self.metadata
        }

        fn schema(&self) -> serde_json::Value {
            json!({})
        }

        async fn initialize(
            &mut self,
            _config: serde_json::Value,
            _context: &PluginContext,
        ) -> PluginResult<()> {
            Ok(())
        }

        async fn execute(&mut self, _context: &mut PluginContext) -> PluginResult<PluginOutput> {
            Err(PluginError::ExecutionFailed(
                "Intentional failure".to_string(),
            ))
        }

        async fn cleanup(&mut self, _context: &PluginContext) -> PluginResult<()> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn test_executor_creation() {
        let registry = PluginRegistry::new();
        let temp_dir = TempDir::new().unwrap();
        let executor = PluginExecutor::new(registry, temp_dir.path().to_path_buf());

        assert_eq!(executor.registry().len(), 0);
    }

    #[tokio::test]
    async fn test_single_plugin_execution() {
        let mut registry = PluginRegistry::new();
        let execution_count = std::sync::Arc::new(std::sync::Mutex::new(0));
        let plugin = TestPluginA::new(execution_count.clone());

        registry.register(plugin).unwrap();

        let temp_dir = TempDir::new().unwrap();
        let mut executor = PluginExecutor::new(registry, temp_dir.path().to_path_buf());

        let result = executor.execute_plugin("plugin-a").await.unwrap();

        assert!(result.success);
        assert_eq!(result.data["plugin"], "a");
        assert_eq!(*execution_count.lock().unwrap(), 1);
    }

    #[tokio::test]
    async fn test_pipeline_execution_with_dependencies() {
        let mut registry = PluginRegistry::new();
        let execution_count = std::sync::Arc::new(std::sync::Mutex::new(0));

        let plugin_a = TestPluginA::new(execution_count.clone());
        let plugin_b = TestPluginB::new(execution_count.clone());

        registry.register(plugin_a).unwrap();
        registry.register(plugin_b).unwrap();

        let temp_dir = TempDir::new().unwrap();
        let mut executor = PluginExecutor::new(registry, temp_dir.path().to_path_buf());

        let result = executor.execute_pipeline().await.unwrap();

        assert!(result.success);
        assert_eq!(result.plugin_outputs.len(), 2);
        assert_eq!(result.execution_order.len(), 2); // Two batches
        assert_eq!(result.execution_order[0], vec!["plugin-a"]);
        assert_eq!(result.execution_order[1], vec!["plugin-b"]);
        assert_eq!(*execution_count.lock().unwrap(), 2);
    }

    #[tokio::test]
    async fn test_pipeline_execution_with_failure() {
        let mut registry = PluginRegistry::new();
        let execution_count = std::sync::Arc::new(std::sync::Mutex::new(0));

        let plugin_a = TestPluginA::new(execution_count.clone());
        let failing_plugin = FailingPlugin::new();

        registry.register(plugin_a).unwrap();
        registry.register(failing_plugin).unwrap();

        let temp_dir = TempDir::new().unwrap();
        let mut executor = PluginExecutor::new(registry, temp_dir.path().to_path_buf());

        let result = executor.execute_pipeline().await.unwrap();

        assert!(!result.success);
        assert_eq!(result.failed_plugins.len(), 1);
        assert!(result
            .failed_plugins
            .contains(&"failing-plugin".to_string()));
    }

    #[tokio::test]
    async fn test_executor_with_config() {
        let config = PluginSystemConfig::default();
        assert_eq!(config.system.max_parallel_plugins, 4);
        assert!(config.plugins.is_empty());

        let mut custom_config = PluginSystemConfig::default();
        custom_config.system.max_parallel_plugins = 8;
        let plugin_config = crate::core::config::PluginConfig {
            config: json!({"key": "value"}),
            ..Default::default()
        };
        custom_config
            .plugins
            .insert("test".to_string(), plugin_config);

        assert_eq!(custom_config.system.max_parallel_plugins, 8);
        assert_eq!(custom_config.plugins.len(), 1);
    }

    // Security-aware plugin for testing
    struct SecuredTestPlugin {
        metadata: PluginMetadata,
        permissions: Vec<Permission>,
    }

    impl SecuredTestPlugin {
        fn new(name: &str, permissions: Vec<Permission>) -> Self {
            let metadata = PluginMetadata::new(name, "1.0.0");
            Self {
                metadata,
                permissions,
            }
        }
    }

    #[async_trait]
    impl Plugin for SecuredTestPlugin {
        fn metadata(&self) -> &PluginMetadata {
            &self.metadata
        }

        fn schema(&self) -> serde_json::Value {
            json!({})
        }

        fn permissions(&self) -> Vec<Permission> {
            self.permissions.clone()
        }

        async fn initialize(
            &mut self,
            _config: serde_json::Value,
            _context: &PluginContext,
        ) -> PluginResult<()> {
            Ok(())
        }

        async fn execute(&mut self, context: &mut PluginContext) -> PluginResult<PluginOutput> {
            // Test that security context is available
            if let Some(security_ctx) = context.security_context() {
                assert_eq!(security_ctx.plugin_name(), self.metadata.name);
            }

            Ok(PluginOutput::success(
                json!({"message": "Secured execution"}),
            ))
        }

        async fn cleanup(&mut self, _context: &PluginContext) -> PluginResult<()> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn test_plugin_execution_with_permissions() {
        let mut registry = PluginRegistry::new();
        let permissions = vec![Permission::fs_read("/tmp"), Permission::TempDir];
        let plugin = SecuredTestPlugin::new("secured-plugin", permissions);

        registry.register(plugin).unwrap();

        let temp_dir = TempDir::new().unwrap();
        let mut executor = PluginExecutor::new(registry, temp_dir.path().to_path_buf());

        let result = executor.execute_plugin("secured-plugin").await.unwrap();

        assert!(result.success);
        assert_eq!(result.data["message"], "Secured execution");
    }

    #[tokio::test]
    async fn test_plugin_execution_with_restricted_permissions() {
        let mut registry = PluginRegistry::new();
        let permissions = vec![Permission::fs_read("/etc")];
        let plugin = SecuredTestPlugin::new("secured-plugin", permissions);

        registry.register(plugin).unwrap();

        let temp_dir = TempDir::new().unwrap();
        let mut executor = PluginExecutor::new(registry, temp_dir.path().to_path_buf());

        // Add global restriction
        executor
            .security_manager_mut()
            .add_global_restriction(Permission::fs_read("/etc"));

        let result = executor.execute_plugin("secured-plugin").await;

        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            PluginError::PermissionDenied { .. }
        ));
    }

    #[tokio::test]
    async fn test_pipeline_execution_with_security() {
        let mut registry = PluginRegistry::new();
        let _execution_count = std::sync::Arc::new(std::sync::Mutex::new(0));

        // Create plugins with permissions
        let plugin_a = SecuredTestPlugin::new("secured-plugin-a", vec![Permission::TempDir]);
        let plugin_b =
            SecuredTestPlugin::new("secured-plugin-b", vec![Permission::fs_read("/tmp")]);

        registry.register(plugin_a).unwrap();
        registry.register(plugin_b).unwrap();

        let temp_dir = TempDir::new().unwrap();
        let mut executor = PluginExecutor::new(registry, temp_dir.path().to_path_buf());

        let result = executor.execute_pipeline().await.unwrap();

        assert!(result.success);
        assert_eq!(result.plugin_outputs.len(), 2);
    }

    #[tokio::test]
    async fn test_executor_with_custom_security_manager() {
        let mut registry = PluginRegistry::new();
        let plugin = SecuredTestPlugin::new("secured-plugin", vec![Permission::fs_read("/tmp")]);
        registry.register(plugin).unwrap();

        let temp_dir = TempDir::new().unwrap();
        let mut security_manager = SecurityManager::new();

        // Pre-grant some permissions
        security_manager.grant_permissions("secured-plugin", vec![Permission::fs_read("/tmp")]);

        let mut executor = PluginExecutor::with_security_manager(
            registry,
            temp_dir.path().to_path_buf(),
            security_manager,
        );

        let result = executor.execute_plugin("secured-plugin").await.unwrap();

        assert!(result.success);
    }

    #[tokio::test]
    async fn test_executor_with_sandbox_integration() {
        let mut registry = PluginRegistry::new();
        let plugin = SecuredTestPlugin::new("sandbox-test-plugin", vec![Permission::TempDir]);
        registry.register(plugin).unwrap();

        let temp_dir = TempDir::new().unwrap();
        let mut executor = PluginExecutor::new(registry, temp_dir.path().to_path_buf());

        // Verify no sandboxes exist initially
        assert_eq!(executor.sandbox_manager().active_sandboxes().await.len(), 0);

        let result = executor
            .execute_plugin("sandbox-test-plugin")
            .await
            .unwrap();

        assert!(result.success);
        assert_eq!(result.data["message"], "Secured execution");

        // Verify sandbox was cleaned up after execution
        assert_eq!(executor.sandbox_manager().active_sandboxes().await.len(), 0);
    }

    #[tokio::test]
    async fn test_pipeline_execution_with_sandbox_cleanup() {
        let mut registry = PluginRegistry::new();

        let plugin_a = SecuredTestPlugin::new("sandbox-plugin-a", vec![Permission::TempDir]);
        let plugin_b =
            SecuredTestPlugin::new("sandbox-plugin-b", vec![Permission::fs_read("/tmp")]);

        registry.register(plugin_a).unwrap();
        registry.register(plugin_b).unwrap();

        let temp_dir = TempDir::new().unwrap();
        let mut executor = PluginExecutor::new(registry, temp_dir.path().to_path_buf());

        // Verify no sandboxes exist initially
        assert_eq!(executor.sandbox_manager().active_sandboxes().await.len(), 0);

        let result = executor.execute_pipeline().await.unwrap();

        assert!(result.success);
        assert_eq!(result.plugin_outputs.len(), 2);

        // Verify all sandboxes were cleaned up after execution
        assert_eq!(executor.sandbox_manager().active_sandboxes().await.len(), 0);
    }

    #[tokio::test]
    async fn test_configuration_driven_execution() {
        let mut registry = PluginRegistry::new();
        let execution_count = std::sync::Arc::new(std::sync::Mutex::new(0));

        let plugin_a = TestPluginA::new(execution_count.clone());
        registry.register(plugin_a).unwrap();

        // Create system configuration with custom settings
        let mut config = PluginSystemConfig::default();
        config.system.max_parallel_plugins = 2;
        config.system.debug = true;

        // Configure plugin-specific settings
        let plugin_config = crate::core::config::PluginConfig {
            enabled: true,
            config: json!({"custom_setting": "test_value"}),
            permissions: vec![Permission::TempDir],
            retry: crate::core::config::RetryConfig {
                max_attempts: 2,
                ..Default::default()
            },
            ..Default::default()
        };
        config.plugins.insert("plugin-a".to_string(), plugin_config);

        let mut executor = PluginExecutor::with_config(registry, config.clone());

        // Test single plugin execution with configuration
        let result = executor.execute_plugin("plugin-a").await.unwrap();
        assert!(result.success);
        assert_eq!(*execution_count.lock().unwrap(), 1);

        // Test pipeline execution
        let pipeline_result = executor.execute_pipeline().await.unwrap();
        assert!(pipeline_result.success);
        assert_eq!(pipeline_result.plugin_outputs.len(), 1);
        assert_eq!(*execution_count.lock().unwrap(), 2);

        // Verify configuration is applied
        assert_eq!(executor.config.system.max_parallel_plugins, 2);
        assert!(executor.config.system.debug);
        assert!(executor.config.plugins.contains_key("plugin-a"));
    }

    #[tokio::test]
    async fn test_configuration_permission_override() {
        let mut registry = PluginRegistry::new();

        // Plugin requests file system permission, but config overrides it
        let plugin = SecuredTestPlugin::new("test-plugin", vec![Permission::fs_read("/etc")]);
        registry.register(plugin).unwrap();

        let mut config = PluginSystemConfig::default();
        // Override plugin permissions in configuration
        let plugin_config = crate::core::config::PluginConfig {
            permissions: vec![Permission::TempDir], // Different permission
            ..Default::default()
        };
        config
            .plugins
            .insert("test-plugin".to_string(), plugin_config);

        let _temp_dir = TempDir::new().unwrap();
        let mut executor = PluginExecutor::with_config(registry, config);

        // Should use configuration permissions (TempDir) instead of plugin permissions ("/etc")
        let result = executor.execute_plugin("test-plugin").await.unwrap();
        assert!(result.success);
    }
}