asupersync 0.3.1

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
//! Analyzer plugin API and schema/version contract for diagnostics pipelines.
//!
//! This module defines deterministic extension points for third-party analyzers
//! without introducing ambient authority. Plugins are registered explicitly,
//! schema negotiation is deterministic, and execution is isolated so one plugin
//! cannot prevent the rest of a pack from running.

use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet};
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use thiserror::Error;

/// Contract version for the analyzer plugin API.
pub const ANALYZER_PLUGIN_CONTRACT_VERSION: &str = "doctor-analyzer-plugin-v1";

/// Semantic schema version used by plugin input/output contracts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct AnalyzerSchemaVersion {
    /// Breaking-compatibility version line.
    pub major: u16,
    /// Additive/backward-compatible increment within a major line.
    pub minor: u16,
}

impl AnalyzerSchemaVersion {
    /// Creates a semantic analyzer schema version.
    #[must_use]
    pub const fn new(major: u16, minor: u16) -> Self {
        Self { major, minor }
    }
}

impl PartialOrd for AnalyzerSchemaVersion {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for AnalyzerSchemaVersion {
    fn cmp(&self, other: &Self) -> Ordering {
        self.major
            .cmp(&other.major)
            .then(self.minor.cmp(&other.minor))
    }
}

/// Explicit capability required by plugins.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum AnalyzerCapability {
    /// Read workspace source/manifests.
    WorkspaceRead,
    /// Read structured evidence artifacts.
    EvidenceRead,
    /// Read replay/trace data.
    TraceRead,
    /// Emit structured lifecycle and finding events.
    StructuredEventEmit,
}

/// Plugin runtime isolation profile.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AnalyzerSandboxPolicy {
    /// Plugin is pure/read-only and must not mutate external state.
    DeterministicReadOnly,
    /// Plugin may call bounded external adapters but must remain deterministic.
    DeterministicBounded,
}

/// Plugin metadata used for registration and compatibility checks.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AnalyzerPluginDescriptor {
    /// Stable plugin identifier (`slug-like`) used in reports and logs.
    pub plugin_id: String,
    /// Human-readable plugin display name.
    pub display_name: String,
    /// Plugin implementation version.
    pub plugin_version: String,
    /// Input schemas this plugin can read, sorted lexically and unique.
    pub supported_input_schemas: Vec<AnalyzerSchemaVersion>,
    /// Output schema emitted by this plugin.
    pub output_schema: AnalyzerSchemaVersion,
    /// Capabilities required to run this plugin.
    pub required_capabilities: Vec<AnalyzerCapability>,
    /// Sandbox profile required by this plugin.
    pub sandbox_policy: AnalyzerSandboxPolicy,
}

/// One diagnostics finding emitted by a plugin.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AnalyzerFinding {
    /// Stable finding identifier within a plugin namespace.
    pub finding_id: String,
    /// Severity class for prioritization.
    pub severity: AnalyzerSeverity,
    /// Human-readable summary.
    pub summary: String,
    /// Confidence score in basis points (0..=10000).
    pub confidence_bps: u16,
}

/// Severity class for plugin findings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum AnalyzerSeverity {
    /// Informational finding.
    Info,
    /// Non-blocking warning.
    Warn,
    /// Actionable high-severity finding.
    Error,
}

/// Plugin output envelope.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AnalyzerOutput {
    /// Output schema version used by this payload.
    pub schema_version: AnalyzerSchemaVersion,
    /// Deterministic findings list (normalized by the host before aggregation).
    pub findings: Vec<AnalyzerFinding>,
    /// Optional summary metadata.
    pub summary: String,
}

/// Input passed to plugins.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AnalyzerRequest {
    /// Deterministic run identifier.
    pub run_id: String,
    /// Correlation id linking logs/traces/reports.
    pub correlation_id: String,
    /// Workspace root path for context.
    pub workspace_root: String,
    /// Host schema version offered for negotiation.
    pub host_schema_version: AnalyzerSchemaVersion,
    /// Capabilities granted for this run.
    pub granted_capabilities: Vec<AnalyzerCapability>,
}

impl AnalyzerRequest {
    /// Creates a normalized request where capability grants are sorted and unique.
    #[must_use]
    pub fn new(
        run_id: String,
        correlation_id: String,
        workspace_root: String,
        host_schema_version: AnalyzerSchemaVersion,
        mut granted_capabilities: Vec<AnalyzerCapability>,
    ) -> Self {
        granted_capabilities.sort_unstable();
        granted_capabilities.dedup();
        Self {
            run_id,
            correlation_id,
            workspace_root,
            host_schema_version,
            granted_capabilities,
        }
    }
}

/// Third-party analyzer plugin interface.
pub trait AnalyzerPlugin: Send + Sync {
    /// Returns immutable plugin metadata.
    fn descriptor(&self) -> AnalyzerPluginDescriptor;

    /// Executes plugin analysis under the negotiated input schema.
    fn analyze(
        &self,
        request: &AnalyzerRequest,
        negotiated_input_schema: AnalyzerSchemaVersion,
    ) -> Result<AnalyzerOutput, AnalyzerPluginRunError>;
}

/// Lifecycle phase emitted during plugin execution.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PluginLifecyclePhase {
    /// Plugin passed registration checks.
    Registered,
    /// Schema negotiation completed.
    Negotiated,
    /// Plugin started execution.
    Started,
    /// Plugin completed successfully.
    Completed,
    /// Plugin execution skipped by policy/compatibility checks.
    Skipped,
    /// Plugin returned a typed execution error.
    Failed,
    /// Plugin panicked and was isolated.
    Panicked,
    /// Host detected a contract violation.
    ContractViolation,
}

/// Schema negotiation outcome.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SchemaDecision {
    /// Plugin supports the host schema exactly.
    Exact,
    /// Plugin accepted by downgrading to a lower compatible minor version.
    BackwardCompatibleFallback,
    /// Plugin incompatible because host major is unsupported.
    IncompatibleMajor,
    /// Plugin incompatible because host minor is older than plugin requirements.
    HostMinorTooOld,
}

/// Detailed schema negotiation result.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SchemaNegotiation {
    /// Negotiation decision category.
    pub decision: SchemaDecision,
    /// Selected schema for execution, if compatible.
    pub selected_schema: Option<AnalyzerSchemaVersion>,
    /// Deterministic rationale for logging.
    pub rationale: String,
}

/// Lifecycle event emitted during registration and pack execution.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PluginLifecycleEvent {
    /// Plugin identifier.
    pub plugin_id: String,
    /// Lifecycle phase.
    pub phase: PluginLifecyclePhase,
    /// Optional schema decision for negotiation/skip paths.
    pub schema_decision: Option<SchemaDecision>,
    /// Deterministic run identifier.
    pub run_id: String,
    /// Correlation identifier.
    pub correlation_id: String,
    /// Human-readable event message.
    pub message: String,
}

/// Per-plugin execution state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PluginExecutionState {
    /// Plugin completed and emitted output.
    Succeeded,
    /// Plugin returned a typed error.
    Failed,
    /// Plugin panicked and was isolated.
    Panicked,
    /// Plugin was skipped because input schema is incompatible.
    SkippedIncompatibleSchema,
    /// Plugin was skipped due to missing capability grants.
    SkippedMissingCapabilities,
    /// Requested plugin id was unknown to the registry.
    SkippedUnknownPlugin,
}

/// Per-plugin execution record used in aggregated reports.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PluginExecutionRecord {
    /// Plugin id.
    pub plugin_id: String,
    /// Plugin implementation version (or `unknown`).
    pub plugin_version: String,
    /// Final execution state.
    pub state: PluginExecutionState,
    /// Negotiated input schema, if compatible.
    pub negotiated_input_schema: Option<AnalyzerSchemaVersion>,
    /// Output schema from plugin output, if any.
    pub output_schema: Option<AnalyzerSchemaVersion>,
    /// Number of findings emitted by this plugin.
    pub finding_count: usize,
    /// Optional error code for failed/violating paths.
    pub error_code: Option<String>,
}

/// Aggregated finding with source plugin provenance.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AggregatedAnalyzerFinding {
    /// Source plugin id.
    pub plugin_id: String,
    /// Normalized finding payload.
    pub finding: AnalyzerFinding,
}

/// Deterministic plugin-pack execution report.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AnalyzerPluginPackReport {
    /// API contract version used by this report.
    pub contract_version: String,
    /// Host schema presented for negotiation.
    pub host_schema_version: AnalyzerSchemaVersion,
    /// Execution order after deterministic sorting/selection.
    pub execution_order: Vec<String>,
    /// Per-plugin execution records.
    pub executions: Vec<PluginExecutionRecord>,
    /// Aggregated findings across successful plugins.
    pub aggregated_findings: Vec<AggregatedAnalyzerFinding>,
    /// Structured lifecycle log for registration/negotiation/execution.
    pub lifecycle_events: Vec<PluginLifecycleEvent>,
}

/// Registration-time validation failures.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum PluginRegistrationError {
    /// A required descriptor field is empty or invalid.
    #[error("invalid descriptor for plugin `{plugin_id}`: {reason}")]
    InvalidDescriptor {
        /// Plugin id (or placeholder when absent).
        plugin_id: String,
        /// Deterministic reason string.
        reason: String,
    },
    /// Registry already contains this plugin id.
    #[error("plugin id `{plugin_id}` is already registered")]
    DuplicatePluginId {
        /// Duplicate plugin id.
        plugin_id: String,
    },
}

/// Typed plugin execution error.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Error)]
#[error("{code}: {message}")]
pub struct AnalyzerPluginRunError {
    /// Stable error code for deterministic diagnostics.
    pub code: String,
    /// Human-readable message.
    pub message: String,
}

impl AnalyzerPluginRunError {
    /// Creates a typed plugin error.
    #[must_use]
    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            message: message.into(),
        }
    }
}

/// Registry for analyzer plugins.
#[derive(Default)]
pub struct AnalyzerPluginRegistry {
    plugins: BTreeMap<String, Arc<dyn AnalyzerPlugin>>,
}

impl AnalyzerPluginRegistry {
    /// Creates an empty plugin registry.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns sorted plugin ids currently registered.
    #[must_use]
    pub fn plugin_ids(&self) -> Vec<String> {
        self.plugins.keys().cloned().collect()
    }

    /// Registers one plugin after descriptor validation.
    pub fn register(
        &mut self,
        plugin: Arc<dyn AnalyzerPlugin>,
    ) -> Result<AnalyzerPluginDescriptor, PluginRegistrationError> {
        let descriptor = plugin.descriptor();
        validate_descriptor(&descriptor)?;
        if self.plugins.contains_key(&descriptor.plugin_id) {
            return Err(PluginRegistrationError::DuplicatePluginId {
                plugin_id: descriptor.plugin_id,
            });
        }
        self.plugins.insert(descriptor.plugin_id.clone(), plugin);
        Ok(descriptor)
    }

    /// Executes a plugin pack deterministically with schema negotiation and isolation.
    #[must_use]
    #[allow(clippy::too_many_lines)]
    pub fn run_pack(
        &self,
        request: &AnalyzerRequest,
        requested_plugins: &[String],
    ) -> AnalyzerPluginPackReport {
        let run_id = request.run_id.clone();
        let correlation_id = request.correlation_id.clone();
        let mut lifecycle_events = Vec::new();
        let execution_order = normalized_execution_order(self, requested_plugins);
        let mut executions = Vec::new();
        let mut aggregated_findings = Vec::new();

        for plugin_id in &execution_order {
            let Some(plugin) = self.plugins.get(plugin_id) else {
                lifecycle_events.push(PluginLifecycleEvent {
                    plugin_id: plugin_id.clone(),
                    phase: PluginLifecyclePhase::Skipped,
                    schema_decision: None,
                    run_id: run_id.clone(),
                    correlation_id: correlation_id.clone(),
                    message: "plugin is not registered".to_string(),
                });
                executions.push(PluginExecutionRecord {
                    plugin_id: plugin_id.clone(),
                    plugin_version: "unknown".to_string(),
                    state: PluginExecutionState::SkippedUnknownPlugin,
                    negotiated_input_schema: None,
                    output_schema: None,
                    finding_count: 0,
                    error_code: Some("plugin_not_registered".to_string()),
                });
                continue;
            };

            let descriptor = plugin.descriptor();
            lifecycle_events.push(PluginLifecycleEvent {
                plugin_id: descriptor.plugin_id.clone(),
                phase: PluginLifecyclePhase::Registered,
                schema_decision: None,
                run_id: run_id.clone(),
                correlation_id: correlation_id.clone(),
                message: "plugin descriptor loaded".to_string(),
            });

            let missing_caps = missing_capabilities(
                &request.granted_capabilities,
                &descriptor.required_capabilities,
            );
            if !missing_caps.is_empty() {
                lifecycle_events.push(PluginLifecycleEvent {
                    plugin_id: descriptor.plugin_id.clone(),
                    phase: PluginLifecyclePhase::Skipped,
                    schema_decision: None,
                    run_id: run_id.clone(),
                    correlation_id: correlation_id.clone(),
                    message: format!(
                        "missing capabilities: {}",
                        missing_caps
                            .iter()
                            .map(|cap| format!("{cap:?}"))
                            .collect::<Vec<_>>()
                            .join(",")
                    ),
                });
                executions.push(PluginExecutionRecord {
                    plugin_id: descriptor.plugin_id,
                    plugin_version: descriptor.plugin_version,
                    state: PluginExecutionState::SkippedMissingCapabilities,
                    negotiated_input_schema: None,
                    output_schema: None,
                    finding_count: 0,
                    error_code: Some("missing_capability".to_string()),
                });
                continue;
            }

            let negotiation = negotiate_schema_version(
                request.host_schema_version,
                &descriptor.supported_input_schemas,
            );
            lifecycle_events.push(PluginLifecycleEvent {
                plugin_id: descriptor.plugin_id.clone(),
                phase: PluginLifecyclePhase::Negotiated,
                schema_decision: Some(negotiation.decision),
                run_id: run_id.clone(),
                correlation_id: correlation_id.clone(),
                message: negotiation.rationale.clone(),
            });
            let Some(selected_schema) = negotiation.selected_schema else {
                lifecycle_events.push(PluginLifecycleEvent {
                    plugin_id: descriptor.plugin_id.clone(),
                    phase: PluginLifecyclePhase::Skipped,
                    schema_decision: Some(negotiation.decision),
                    run_id: run_id.clone(),
                    correlation_id: correlation_id.clone(),
                    message: "plugin skipped due to schema incompatibility".to_string(),
                });
                executions.push(PluginExecutionRecord {
                    plugin_id: descriptor.plugin_id,
                    plugin_version: descriptor.plugin_version,
                    state: PluginExecutionState::SkippedIncompatibleSchema,
                    negotiated_input_schema: None,
                    output_schema: None,
                    finding_count: 0,
                    error_code: Some("incompatible_schema".to_string()),
                });
                continue;
            };

            lifecycle_events.push(PluginLifecycleEvent {
                plugin_id: descriptor.plugin_id.clone(),
                phase: PluginLifecyclePhase::Started,
                schema_decision: Some(negotiation.decision),
                run_id: run_id.clone(),
                correlation_id: correlation_id.clone(),
                message: "plugin execution started".to_string(),
            });

            let run_result = catch_unwind(AssertUnwindSafe(|| {
                plugin.analyze(request, selected_schema)
            }));
            match run_result {
                Ok(Ok(mut output)) => {
                    if output.schema_version != descriptor.output_schema {
                        lifecycle_events.push(PluginLifecycleEvent {
                            plugin_id: descriptor.plugin_id.clone(),
                            phase: PluginLifecyclePhase::ContractViolation,
                            schema_decision: Some(negotiation.decision),
                            run_id: run_id.clone(),
                            correlation_id: correlation_id.clone(),
                            message: format!(
                                "plugin output schema mismatch: expected {:?}, got {:?}",
                                descriptor.output_schema, output.schema_version
                            ),
                        });
                        executions.push(PluginExecutionRecord {
                            plugin_id: descriptor.plugin_id,
                            plugin_version: descriptor.plugin_version,
                            state: PluginExecutionState::Failed,
                            negotiated_input_schema: Some(selected_schema),
                            output_schema: Some(output.schema_version),
                            finding_count: 0,
                            error_code: Some("output_schema_mismatch".to_string()),
                        });
                        continue;
                    }

                    if let Err(err) =
                        normalize_plugin_findings(&descriptor.plugin_id, &mut output.findings)
                    {
                        lifecycle_events.push(PluginLifecycleEvent {
                            plugin_id: descriptor.plugin_id.clone(),
                            phase: PluginLifecyclePhase::ContractViolation,
                            schema_decision: Some(negotiation.decision),
                            run_id: run_id.clone(),
                            correlation_id: correlation_id.clone(),
                            message: err.message.clone(),
                        });
                        executions.push(PluginExecutionRecord {
                            plugin_id: descriptor.plugin_id,
                            plugin_version: descriptor.plugin_version,
                            state: PluginExecutionState::Failed,
                            negotiated_input_schema: Some(selected_schema),
                            output_schema: Some(output.schema_version),
                            finding_count: 0,
                            error_code: Some(err.code),
                        });
                        continue;
                    }

                    lifecycle_events.push(PluginLifecycleEvent {
                        plugin_id: descriptor.plugin_id.clone(),
                        phase: PluginLifecyclePhase::Completed,
                        schema_decision: Some(negotiation.decision),
                        run_id: run_id.clone(),
                        correlation_id: correlation_id.clone(),
                        message: format!(
                            "plugin completed with {} finding(s)",
                            output.findings.len()
                        ),
                    });
                    let finding_count = output.findings.len();
                    aggregated_findings.extend(output.findings.into_iter().map(|finding| {
                        AggregatedAnalyzerFinding {
                            plugin_id: descriptor.plugin_id.clone(),
                            finding,
                        }
                    }));
                    executions.push(PluginExecutionRecord {
                        plugin_id: descriptor.plugin_id,
                        plugin_version: descriptor.plugin_version,
                        state: PluginExecutionState::Succeeded,
                        negotiated_input_schema: Some(selected_schema),
                        output_schema: Some(output.schema_version),
                        finding_count,
                        error_code: None,
                    });
                }
                Ok(Err(err)) => {
                    lifecycle_events.push(PluginLifecycleEvent {
                        plugin_id: descriptor.plugin_id.clone(),
                        phase: PluginLifecyclePhase::Failed,
                        schema_decision: Some(negotiation.decision),
                        run_id: run_id.clone(),
                        correlation_id: correlation_id.clone(),
                        message: format!("plugin returned error: {}", err.code),
                    });
                    executions.push(PluginExecutionRecord {
                        plugin_id: descriptor.plugin_id,
                        plugin_version: descriptor.plugin_version,
                        state: PluginExecutionState::Failed,
                        negotiated_input_schema: Some(selected_schema),
                        output_schema: None,
                        finding_count: 0,
                        error_code: Some(err.code),
                    });
                }
                Err(_) => {
                    lifecycle_events.push(PluginLifecycleEvent {
                        plugin_id: descriptor.plugin_id.clone(),
                        phase: PluginLifecyclePhase::Panicked,
                        schema_decision: Some(negotiation.decision),
                        run_id: run_id.clone(),
                        correlation_id: correlation_id.clone(),
                        message: "plugin panicked; isolation preserved".to_string(),
                    });
                    executions.push(PluginExecutionRecord {
                        plugin_id: descriptor.plugin_id,
                        plugin_version: descriptor.plugin_version,
                        state: PluginExecutionState::Panicked,
                        negotiated_input_schema: Some(selected_schema),
                        output_schema: None,
                        finding_count: 0,
                        error_code: Some("plugin_panicked".to_string()),
                    });
                }
            }
        }

        aggregated_findings.sort_unstable_by(|left, right| {
            left.plugin_id
                .cmp(&right.plugin_id)
                .then(left.finding.finding_id.cmp(&right.finding.finding_id))
                .then(left.finding.severity.cmp(&right.finding.severity))
                .then(left.finding.summary.cmp(&right.finding.summary))
                .then(
                    left.finding
                        .confidence_bps
                        .cmp(&right.finding.confidence_bps),
                )
        });

        AnalyzerPluginPackReport {
            contract_version: ANALYZER_PLUGIN_CONTRACT_VERSION.to_string(),
            host_schema_version: request.host_schema_version,
            execution_order,
            executions,
            aggregated_findings,
            lifecycle_events,
        }
    }
}

/// Runs a deterministic smoke flow for a provided plugin set.
#[must_use]
pub fn run_analyzer_plugin_pack_smoke(
    registry: &AnalyzerPluginRegistry,
    request: &AnalyzerRequest,
) -> AnalyzerPluginPackReport {
    registry.run_pack(request, &registry.plugin_ids())
}

/// Negotiates a plugin input schema against the host schema.
#[must_use]
pub fn negotiate_schema_version(
    host_schema: AnalyzerSchemaVersion,
    supported: &[AnalyzerSchemaVersion],
) -> SchemaNegotiation {
    if supported.is_empty() {
        return SchemaNegotiation {
            decision: SchemaDecision::IncompatibleMajor,
            selected_schema: None,
            rationale: "plugin provides no supported input schema".to_string(),
        };
    }
    if supported.contains(&host_schema) {
        return SchemaNegotiation {
            decision: SchemaDecision::Exact,
            selected_schema: Some(host_schema),
            rationale: "exact schema match".to_string(),
        };
    }
    let mut same_major: Vec<AnalyzerSchemaVersion> = supported
        .iter()
        .copied()
        .filter(|schema| schema.major == host_schema.major)
        .collect();
    if same_major.is_empty() {
        return SchemaNegotiation {
            decision: SchemaDecision::IncompatibleMajor,
            selected_schema: None,
            rationale: "host schema major is unsupported".to_string(),
        };
    }
    same_major.sort_unstable();
    if let Some(candidate) = same_major
        .iter()
        .rev()
        .find(|schema| schema.minor <= host_schema.minor)
    {
        return SchemaNegotiation {
            decision: SchemaDecision::BackwardCompatibleFallback,
            selected_schema: Some(*candidate),
            rationale: "falling back to highest compatible minor version".to_string(),
        };
    }
    SchemaNegotiation {
        decision: SchemaDecision::HostMinorTooOld,
        selected_schema: None,
        rationale: "host schema minor is older than plugin minimum".to_string(),
    }
}

fn validate_descriptor(
    descriptor: &AnalyzerPluginDescriptor,
) -> Result<(), PluginRegistrationError> {
    if descriptor.plugin_id.trim().is_empty() {
        return Err(PluginRegistrationError::InvalidDescriptor {
            plugin_id: "<empty>".to_string(),
            reason: "plugin_id must be non-empty".to_string(),
        });
    }
    if !is_slug_like(&descriptor.plugin_id) {
        return Err(PluginRegistrationError::InvalidDescriptor {
            plugin_id: descriptor.plugin_id.clone(),
            reason: "plugin_id must be slug-like".to_string(),
        });
    }
    if descriptor.display_name.trim().is_empty() {
        return Err(PluginRegistrationError::InvalidDescriptor {
            plugin_id: descriptor.plugin_id.clone(),
            reason: "display_name must be non-empty".to_string(),
        });
    }
    if descriptor.plugin_version.trim().is_empty() {
        return Err(PluginRegistrationError::InvalidDescriptor {
            plugin_id: descriptor.plugin_id.clone(),
            reason: "plugin_version must be non-empty".to_string(),
        });
    }
    if descriptor.supported_input_schemas.is_empty() {
        return Err(PluginRegistrationError::InvalidDescriptor {
            plugin_id: descriptor.plugin_id.clone(),
            reason: "supported_input_schemas must be non-empty".to_string(),
        });
    }
    let mut schema_copy = descriptor.supported_input_schemas.clone();
    schema_copy.sort_unstable();
    if schema_copy != descriptor.supported_input_schemas {
        return Err(PluginRegistrationError::InvalidDescriptor {
            plugin_id: descriptor.plugin_id.clone(),
            reason: "supported_input_schemas must be lexically sorted".to_string(),
        });
    }
    let unique_schema_count = schema_copy.iter().collect::<BTreeSet<_>>().len();
    if unique_schema_count != schema_copy.len() {
        return Err(PluginRegistrationError::InvalidDescriptor {
            plugin_id: descriptor.plugin_id.clone(),
            reason: "supported_input_schemas must be unique".to_string(),
        });
    }
    let mut capability_copy = descriptor.required_capabilities.clone();
    capability_copy.sort_unstable();
    capability_copy.dedup();
    if capability_copy != descriptor.required_capabilities {
        return Err(PluginRegistrationError::InvalidDescriptor {
            plugin_id: descriptor.plugin_id.clone(),
            reason: "required_capabilities must be sorted and unique".to_string(),
        });
    }
    Ok(())
}

fn normalized_execution_order(
    registry: &AnalyzerPluginRegistry,
    requested_plugins: &[String],
) -> Vec<String> {
    if requested_plugins.is_empty() {
        return registry.plugin_ids();
    }
    let mut normalized = requested_plugins.to_vec();
    normalized.sort_unstable();
    normalized.dedup();
    normalized
}

fn missing_capabilities(
    granted: &[AnalyzerCapability],
    required: &[AnalyzerCapability],
) -> Vec<AnalyzerCapability> {
    let granted: BTreeSet<AnalyzerCapability> = granted.iter().copied().collect();
    required
        .iter()
        .copied()
        .filter(|required_capability| !granted.contains(required_capability))
        .collect()
}

fn normalize_plugin_findings(
    plugin_id: &str,
    findings: &mut [AnalyzerFinding],
) -> Result<(), AnalyzerPluginRunError> {
    findings.sort_unstable_by(|left, right| {
        left.finding_id
            .cmp(&right.finding_id)
            .then(left.severity.cmp(&right.severity))
            .then(left.summary.cmp(&right.summary))
            .then(left.confidence_bps.cmp(&right.confidence_bps))
    });

    for pair in findings.windows(2) {
        if pair[0].finding_id == pair[1].finding_id {
            return Err(AnalyzerPluginRunError::new(
                "duplicate_finding_id",
                format!(
                    "plugin `{plugin_id}` emitted duplicate finding_id `{}`",
                    pair[0].finding_id
                ),
            ));
        }
    }

    Ok(())
}

fn is_slug_like(value: &str) -> bool {
    value
        .chars()
        .all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '-')
}

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

    #[derive(Debug, Clone)]
    enum TestMode {
        Success(Vec<AnalyzerFinding>),
        Error(AnalyzerPluginRunError),
        Panic,
    }

    struct TestPlugin {
        descriptor: AnalyzerPluginDescriptor,
        mode: TestMode,
    }

    impl AnalyzerPlugin for TestPlugin {
        fn descriptor(&self) -> AnalyzerPluginDescriptor {
            self.descriptor.clone()
        }

        fn analyze(
            &self,
            _request: &AnalyzerRequest,
            negotiated_input_schema: AnalyzerSchemaVersion,
        ) -> Result<AnalyzerOutput, AnalyzerPluginRunError> {
            match &self.mode {
                TestMode::Success(findings) => Ok(AnalyzerOutput {
                    schema_version: self.descriptor.output_schema,
                    findings: findings.clone(),
                    summary: format!("schema {negotiated_input_schema:?}"),
                }),
                TestMode::Error(err) => Err(err.clone()),
                TestMode::Panic => panic!("plugin panic for test"), // ubs:ignore - test logic
            }
        }
    }

    fn init_test(name: &str) {
        crate::test_utils::init_test_logging();
        crate::test_phase!(name);
    }

    fn descriptor(
        plugin_id: &str,
        supported_input_schemas: Vec<AnalyzerSchemaVersion>,
        required_capabilities: Vec<AnalyzerCapability>,
    ) -> AnalyzerPluginDescriptor {
        AnalyzerPluginDescriptor {
            plugin_id: plugin_id.to_string(),
            display_name: format!("{plugin_id} display"),
            plugin_version: "1.0.0".to_string(),
            supported_input_schemas,
            output_schema: AnalyzerSchemaVersion::new(1, 0),
            required_capabilities,
            sandbox_policy: AnalyzerSandboxPolicy::DeterministicReadOnly,
        }
    }

    fn request_with_caps(granted_capabilities: Vec<AnalyzerCapability>) -> AnalyzerRequest {
        AnalyzerRequest::new(
            "run-analyzer-pack".to_string(),
            "corr-001".to_string(),
            ".".to_string(),
            AnalyzerSchemaVersion::new(1, 2),
            granted_capabilities,
        )
    }

    #[test]
    fn register_rejects_duplicate_plugin_id() {
        init_test("register_rejects_duplicate_plugin_id");
        let mut registry = AnalyzerPluginRegistry::new();
        let plugin_a = Arc::new(TestPlugin {
            descriptor: descriptor(
                "alpha-plugin",
                vec![AnalyzerSchemaVersion::new(1, 0)],
                vec![AnalyzerCapability::WorkspaceRead],
            ),
            mode: TestMode::Success(Vec::new()),
        });
        let plugin_b = Arc::new(TestPlugin {
            descriptor: descriptor(
                "alpha-plugin",
                vec![AnalyzerSchemaVersion::new(1, 0)],
                vec![AnalyzerCapability::WorkspaceRead],
            ),
            mode: TestMode::Success(Vec::new()),
        });
        registry
            .register(plugin_a)
            .expect("first registration succeeds");
        let err = registry
            .register(plugin_b)
            .expect_err("duplicate registration must fail");
        assert!(matches!(
            err,
            PluginRegistrationError::DuplicatePluginId { .. }
        ));
        crate::test_complete!("register_rejects_duplicate_plugin_id");
    }

    #[test]
    fn schema_negotiation_prefers_exact_then_fallback() {
        init_test("schema_negotiation_prefers_exact_then_fallback");
        let supported = vec![
            AnalyzerSchemaVersion::new(1, 0),
            AnalyzerSchemaVersion::new(1, 1),
            AnalyzerSchemaVersion::new(1, 3),
        ];

        let exact = negotiate_schema_version(AnalyzerSchemaVersion::new(1, 1), &supported);
        assert_eq!(exact.decision, SchemaDecision::Exact);
        assert_eq!(
            exact.selected_schema,
            Some(AnalyzerSchemaVersion::new(1, 1))
        );

        let fallback = negotiate_schema_version(AnalyzerSchemaVersion::new(1, 2), &supported);
        assert_eq!(
            fallback.decision,
            SchemaDecision::BackwardCompatibleFallback
        );
        assert_eq!(
            fallback.selected_schema,
            Some(AnalyzerSchemaVersion::new(1, 1))
        );

        let incompatible = negotiate_schema_version(AnalyzerSchemaVersion::new(2, 0), &supported);
        assert_eq!(incompatible.decision, SchemaDecision::IncompatibleMajor);
        assert!(incompatible.selected_schema.is_none());
        crate::test_complete!("schema_negotiation_prefers_exact_then_fallback");
    }

    #[test]
    fn run_pack_is_deterministic_and_aggregates_findings() {
        init_test("run_pack_is_deterministic_and_aggregates_findings");
        let mut registry = AnalyzerPluginRegistry::new();

        registry
            .register(Arc::new(TestPlugin {
                descriptor: descriptor(
                    "zeta-plugin",
                    vec![
                        AnalyzerSchemaVersion::new(1, 0),
                        AnalyzerSchemaVersion::new(1, 2),
                    ],
                    vec![AnalyzerCapability::WorkspaceRead],
                ),
                mode: TestMode::Success(vec![AnalyzerFinding {
                    finding_id: "zeta-002".to_string(),
                    severity: AnalyzerSeverity::Warn,
                    summary: "zeta warning".to_string(),
                    confidence_bps: 8300,
                }]),
            }))
            .expect("register zeta");
        registry
            .register(Arc::new(TestPlugin {
                descriptor: descriptor(
                    "alpha-plugin",
                    vec![
                        AnalyzerSchemaVersion::new(1, 0),
                        AnalyzerSchemaVersion::new(1, 2),
                    ],
                    vec![AnalyzerCapability::WorkspaceRead],
                ),
                mode: TestMode::Success(vec![AnalyzerFinding {
                    finding_id: "alpha-001".to_string(),
                    severity: AnalyzerSeverity::Error,
                    summary: "alpha error".to_string(),
                    confidence_bps: 9200,
                }]),
            }))
            .expect("register alpha");

        let report = run_analyzer_plugin_pack_smoke(
            &registry,
            &request_with_caps(vec![AnalyzerCapability::WorkspaceRead]),
        );
        assert_eq!(
            report.execution_order,
            vec!["alpha-plugin".to_string(), "zeta-plugin".to_string()]
        );
        assert_eq!(report.executions.len(), 2);
        assert_eq!(
            report
                .executions
                .iter()
                .map(|record| record.state)
                .collect::<Vec<_>>(),
            vec![
                PluginExecutionState::Succeeded,
                PluginExecutionState::Succeeded
            ]
        );
        assert_eq!(report.aggregated_findings.len(), 2);
        assert_eq!(report.aggregated_findings[0].plugin_id, "alpha-plugin");
        assert_eq!(report.aggregated_findings[1].plugin_id, "zeta-plugin");
        crate::test_complete!("run_pack_is_deterministic_and_aggregates_findings");
    }

    #[test]
    fn run_pack_isolates_error_and_panic_plugins() {
        init_test("run_pack_isolates_error_and_panic_plugins");
        let mut registry = AnalyzerPluginRegistry::new();

        registry
            .register(Arc::new(TestPlugin {
                descriptor: descriptor(
                    "ok-plugin",
                    vec![AnalyzerSchemaVersion::new(1, 0)],
                    vec![AnalyzerCapability::WorkspaceRead],
                ),
                mode: TestMode::Success(vec![AnalyzerFinding {
                    finding_id: "ok-001".to_string(),
                    severity: AnalyzerSeverity::Info,
                    summary: "ok".to_string(),
                    confidence_bps: 7000,
                }]),
            }))
            .expect("register ok");
        registry
            .register(Arc::new(TestPlugin {
                descriptor: descriptor(
                    "error-plugin",
                    vec![AnalyzerSchemaVersion::new(1, 0)],
                    vec![AnalyzerCapability::WorkspaceRead],
                ),
                mode: TestMode::Error(AnalyzerPluginRunError::new(
                    "plugin_failed",
                    "typed failure",
                )),
            }))
            .expect("register error");
        registry
            .register(Arc::new(TestPlugin {
                descriptor: descriptor(
                    "panic-plugin",
                    vec![AnalyzerSchemaVersion::new(1, 0)],
                    vec![AnalyzerCapability::WorkspaceRead],
                ),
                mode: TestMode::Panic,
            }))
            .expect("register panic");

        let report = run_analyzer_plugin_pack_smoke(
            &registry,
            &request_with_caps(vec![AnalyzerCapability::WorkspaceRead]),
        );
        assert_eq!(report.executions.len(), 3);
        let states: BTreeMap<&str, PluginExecutionState> = report
            .executions
            .iter()
            .map(|record| (record.plugin_id.as_str(), record.state))
            .collect();
        assert_eq!(
            states.get("ok-plugin"),
            Some(&PluginExecutionState::Succeeded)
        );
        assert_eq!(
            states.get("error-plugin"),
            Some(&PluginExecutionState::Failed)
        );
        assert_eq!(
            states.get("panic-plugin"),
            Some(&PluginExecutionState::Panicked)
        );
        assert_eq!(report.aggregated_findings.len(), 1);
        assert_eq!(report.aggregated_findings[0].plugin_id, "ok-plugin");
        assert!(
            report
                .lifecycle_events
                .iter()
                .any(|event| event.phase == PluginLifecyclePhase::Panicked),
            "panic should be surfaced via lifecycle events"
        );
        crate::test_complete!("run_pack_isolates_error_and_panic_plugins");
    }

    #[test]
    fn run_pack_skips_missing_capabilities_and_incompatible_schema() {
        init_test("run_pack_skips_missing_capabilities_and_incompatible_schema");
        let mut registry = AnalyzerPluginRegistry::new();

        registry
            .register(Arc::new(TestPlugin {
                descriptor: descriptor(
                    "cap-plugin",
                    vec![AnalyzerSchemaVersion::new(1, 0)],
                    vec![AnalyzerCapability::EvidenceRead],
                ),
                mode: TestMode::Success(Vec::new()),
            }))
            .expect("register cap-plugin");

        registry
            .register(Arc::new(TestPlugin {
                descriptor: descriptor(
                    "schema-plugin",
                    vec![AnalyzerSchemaVersion::new(2, 0)],
                    vec![AnalyzerCapability::WorkspaceRead],
                ),
                mode: TestMode::Success(Vec::new()),
            }))
            .expect("register schema-plugin");

        let report = run_analyzer_plugin_pack_smoke(
            &registry,
            &request_with_caps(vec![AnalyzerCapability::WorkspaceRead]),
        );
        let states: BTreeMap<&str, PluginExecutionState> = report
            .executions
            .iter()
            .map(|record| (record.plugin_id.as_str(), record.state))
            .collect();
        assert_eq!(
            states.get("cap-plugin"),
            Some(&PluginExecutionState::SkippedMissingCapabilities)
        );
        assert_eq!(
            states.get("schema-plugin"),
            Some(&PluginExecutionState::SkippedIncompatibleSchema)
        );
        assert!(report.aggregated_findings.is_empty());
        crate::test_complete!("run_pack_skips_missing_capabilities_and_incompatible_schema");
    }

    #[test]
    fn run_pack_rejects_duplicate_finding_ids_as_contract_violation() {
        init_test("run_pack_rejects_duplicate_finding_ids_as_contract_violation");
        let mut registry = AnalyzerPluginRegistry::new();

        registry
            .register(Arc::new(TestPlugin {
                descriptor: descriptor(
                    "dup-plugin",
                    vec![AnalyzerSchemaVersion::new(1, 0)],
                    vec![AnalyzerCapability::WorkspaceRead],
                ),
                mode: TestMode::Success(vec![
                    AnalyzerFinding {
                        finding_id: "dup-001".to_string(),
                        severity: AnalyzerSeverity::Warn,
                        summary: "first duplicate".to_string(),
                        confidence_bps: 6100,
                    },
                    AnalyzerFinding {
                        finding_id: "dup-001".to_string(),
                        severity: AnalyzerSeverity::Error,
                        summary: "second duplicate".to_string(),
                        confidence_bps: 9200,
                    },
                ]),
            }))
            .expect("register dup-plugin");

        let report = run_analyzer_plugin_pack_smoke(
            &registry,
            &request_with_caps(vec![AnalyzerCapability::WorkspaceRead]),
        );
        assert_eq!(report.executions.len(), 1);
        assert_eq!(report.executions[0].plugin_id, "dup-plugin");
        assert_eq!(report.executions[0].state, PluginExecutionState::Failed);
        assert_eq!(
            report.executions[0].error_code.as_deref(),
            Some("duplicate_finding_id")
        );
        assert!(report.aggregated_findings.is_empty());
        assert!(
            report.lifecycle_events.iter().any(|event| {
                event.plugin_id == "dup-plugin"
                    && event.phase == PluginLifecyclePhase::ContractViolation
                    && event.message.contains("duplicate finding_id")
            }),
            "duplicate finding ids should surface as a contract violation"
        );
        crate::test_complete!("run_pack_rejects_duplicate_finding_ids_as_contract_violation");
    }
}