perspt-core 0.5.7

Core types and LLM provider abstraction for Perspt
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
//! Language Plugin Architecture
//!
//! Provides a trait-based plugin system for polyglot support.
//! Each language (Rust, Python, JS, etc.) implements this trait.
//!
//! PSP-000005 expands plugins from init-only to full runtime verification contracts.

use serde::{Deserialize, Serialize};
use std::path::Path;

/// LSP Configuration for a language
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LspConfig {
    /// LSP server binary name
    pub server_binary: String,
    /// Arguments to pass to the server
    pub args: Vec<String>,
    /// Language ID for textDocument/didOpen
    pub language_id: String,
}

// =============================================================================
// PSP-5 Phase 4: Verifier Capability Declarations
// =============================================================================

/// Verification stage in the plugin-driven pipeline.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum VerifierStage {
    /// Syntax / type check (e.g. `cargo check`, `uvx ty check .`)
    SyntaxCheck,
    /// Build step (e.g. `cargo build`, `npm run build`)
    Build,
    /// Test execution (e.g. `cargo test`, `uv run pytest`)
    Test,
    /// Lint pass (e.g. `cargo clippy`, `uv run ruff check .`)
    Lint,
}

impl std::fmt::Display for VerifierStage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            VerifierStage::SyntaxCheck => write!(f, "syntax_check"),
            VerifierStage::Build => write!(f, "build"),
            VerifierStage::Test => write!(f, "test"),
            VerifierStage::Lint => write!(f, "lint"),
        }
    }
}

/// A single verifier sensor: one stage of the verification pipeline.
///
/// Each capability independently declares its command, host-tool availability,
/// and optional fallback. This replaces the coarse single `host_tool_available()`
/// check with per-sensor probing.
#[derive(Debug, Clone)]
pub struct VerifierCapability {
    /// Which stage this capability covers.
    pub stage: VerifierStage,
    /// Primary command to execute (None if this stage is not supported).
    pub command: Option<String>,
    /// Whether the primary command's host tool is available on this machine.
    pub available: bool,
    /// Fallback command when the primary tool is unavailable.
    pub fallback_command: Option<String>,
    /// Whether the fallback tool is available.
    pub fallback_available: bool,
}

impl VerifierCapability {
    /// True if either the primary or fallback tool is available.
    pub fn any_available(&self) -> bool {
        self.available || self.fallback_available
    }

    /// The best available command, preferring primary over fallback.
    pub fn effective_command(&self) -> Option<&str> {
        if self.available {
            self.command.as_deref()
        } else if self.fallback_available {
            self.fallback_command.as_deref()
        } else {
            None
        }
    }
}

/// LSP availability and fallback for a plugin.
#[derive(Debug, Clone)]
pub struct LspCapability {
    /// Primary LSP configuration.
    pub primary: LspConfig,
    /// Whether the primary LSP binary is available on the host.
    pub primary_available: bool,
    /// Fallback LSP configuration (if any).
    pub fallback: Option<LspConfig>,
    /// Whether the fallback binary is available.
    pub fallback_available: bool,
}

impl LspCapability {
    /// Return the best available LSP config, preferring primary.
    pub fn effective_config(&self) -> Option<&LspConfig> {
        if self.primary_available {
            Some(&self.primary)
        } else if self.fallback_available {
            self.fallback.as_ref()
        } else {
            None
        }
    }
}

/// Complete verifier profile for a plugin.
///
/// Bundles all per-sensor capabilities and LSP availability into one
/// inspectable structure. Built by `LanguagePlugin::verifier_profile()`.
#[derive(Debug, Clone)]
pub struct VerifierProfile {
    /// Name of the plugin that produced this profile.
    pub plugin_name: String,
    /// Per-stage verifier capabilities.
    pub capabilities: Vec<VerifierCapability>,
    /// LSP availability and fallback.
    pub lsp: LspCapability,
}

impl VerifierProfile {
    /// Get the capability for a given stage, if declared.
    pub fn get(&self, stage: VerifierStage) -> Option<&VerifierCapability> {
        self.capabilities.iter().find(|c| c.stage == stage)
    }

    /// Stages that have at least one available tool (primary or fallback).
    pub fn available_stages(&self) -> Vec<VerifierStage> {
        self.capabilities
            .iter()
            .filter(|c| c.any_available())
            .map(|c| c.stage)
            .collect()
    }

    /// True when every declared stage has zero available tools.
    pub fn fully_degraded(&self) -> bool {
        self.capabilities.iter().all(|c| !c.any_available())
    }
}

// =============================================================================
// Utility: host binary probe
// =============================================================================

/// Check whether a given binary name is available on the host PATH.
///
/// Runs `<binary> --version` silently; returns `true` if the process exits
/// successfully. Used by plugins for per-sensor host-tool probing.
pub fn host_binary_available(binary: &str) -> bool {
    std::process::Command::new(binary)
        .arg("--version")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

/// Options for project initialization
#[derive(Debug, Clone, Default)]
pub struct InitOptions {
    /// Project name
    pub name: String,
    /// Whether to use a specific package manager (e.g., "poetry", "pdm", "npm", "pnpm")
    pub package_manager: Option<String>,
    /// Additional flags
    pub flags: Vec<String>,
    /// Whether the target directory is empty
    pub is_empty_dir: bool,
}

/// Action to take for project initialization or tooling sync
#[derive(Debug, Clone)]
pub enum ProjectAction {
    /// Execute a shell command
    ExecCommand {
        /// The command to run
        command: String,
        /// Human-readable description of what this command does
        description: String,
    },
    /// No action needed
    NoAction,
}

/// A plugin for a specific programming language
///
/// PSP-5 expands this trait beyond init/test/run to a full capability-based
/// runtime contract that governs detection, verification, LSP, and ownership.
pub trait LanguagePlugin: Send + Sync {
    /// Name of the language
    fn name(&self) -> &str;

    /// File extensions this plugin handles
    fn extensions(&self) -> &[&str];

    /// Key files that identify this language (e.g., Cargo.toml, pyproject.toml)
    fn key_files(&self) -> &[&str];

    /// Detect if this plugin should handle the given project directory
    fn detect(&self, path: &Path) -> bool {
        // Check for key files
        for key_file in self.key_files() {
            if path.join(key_file).exists() {
                return true;
            }
        }

        // Check for files with handled extensions
        if let Ok(entries) = std::fs::read_dir(path) {
            for entry in entries.flatten() {
                if let Some(ext) = entry.path().extension() {
                    let ext_str = ext.to_string_lossy();
                    if self.extensions().iter().any(|e| *e == ext_str) {
                        return true;
                    }
                }
            }
        }

        false
    }

    /// Get the LSP configuration for this language
    fn get_lsp_config(&self) -> LspConfig;

    /// Get the action to initialize a new project (greenfield)
    fn get_init_action(&self, opts: &InitOptions) -> ProjectAction;

    /// Check if an existing project needs tooling sync (e.g., uv sync, cargo fetch)
    fn check_tooling_action(&self, path: &Path) -> ProjectAction;

    /// Get the command to initialize a new project
    /// DEPRECATED: Use get_init_action instead
    fn init_command(&self, opts: &InitOptions) -> String;

    /// Get the command to run tests
    fn test_command(&self) -> String;

    /// Get the command to run the project (for verification)
    fn run_command(&self) -> String;

    /// Get the command to run the project in a specific directory.
    ///
    /// Override this to inspect pyproject.toml, Cargo.toml, etc. and return a
    /// more appropriate run command than the generic default.
    fn run_command_for_dir(&self, _path: &Path) -> String {
        self.run_command()
    }

    // =========================================================================
    // PSP-5: Capability-Based Runtime Contract
    // =========================================================================

    /// Get the syntax/type check command (e.g., `cargo check`, `uvx ty check .`)
    ///
    /// Returns None if the plugin has no syntax check command (uses LSP only).
    fn syntax_check_command(&self) -> Option<String> {
        None
    }

    /// Get the build command (e.g., `cargo build`, `npm run build`)
    ///
    /// Returns None if the language doesn't have a separate build step.
    fn build_command(&self) -> Option<String> {
        None
    }

    /// Get the lint command (e.g., `cargo clippy -- -D warnings`)
    ///
    /// Used only in VerifierStrictness::Strict mode.
    fn lint_command(&self) -> Option<String> {
        None
    }

    /// File glob patterns this plugin owns (e.g., `["*.rs", "Cargo.toml"]`)
    ///
    /// Used for node ownership matching in multi-language repos.
    fn file_ownership_patterns(&self) -> &[&str] {
        self.extensions()
    }

    /// PSP-5 Phase 2: Check if a file path belongs to this plugin's ownership domain
    ///
    /// Uses `file_ownership_patterns()` for suffix/extension matching.
    fn owns_file(&self, path: &str) -> bool {
        let path_lower = path.to_lowercase();
        self.file_ownership_patterns().iter().any(|pattern| {
            let pattern = pattern.trim_start_matches('*');
            path_lower.ends_with(pattern)
        })
    }

    /// Check if the host has the required build tools available
    ///
    /// Returns true if the plugin's primary toolchain is installed and callable.
    /// When false, the runtime enters degraded-validation mode.
    fn host_tool_available(&self) -> bool {
        true
    }

    /// Required host binaries for this plugin, grouped by role.
    ///
    /// Each entry is `(binary_name, role_description, install_hint)`.
    /// The orchestrator checks these before init and emits install directions
    /// for any that are missing.
    fn required_binaries(&self) -> Vec<(&str, &str, &str)> {
        Vec::new()
    }

    /// Get fallback LSP config when primary is unavailable
    fn lsp_fallback(&self) -> Option<LspConfig> {
        None
    }

    // =========================================================================
    // PSP-5 Phase 4: Verifier Profile Assembly
    // =========================================================================

    /// Build a complete verifier profile by probing each capability.
    ///
    /// The default implementation auto-assembles from the existing
    /// `syntax_check_command()`, `build_command()`, `test_command()`,
    /// `lint_command()`, and `host_tool_available()` methods.
    ///
    /// Plugins override this method to provide per-sensor probing
    /// with distinct fallback commands and independent availability checks.
    fn verifier_profile(&self) -> VerifierProfile {
        let tool_available = self.host_tool_available();

        let mut capabilities = Vec::new();

        if let Some(cmd) = self.syntax_check_command() {
            capabilities.push(VerifierCapability {
                stage: VerifierStage::SyntaxCheck,
                command: Some(cmd),
                available: tool_available,
                fallback_command: None,
                fallback_available: false,
            });
        }

        if let Some(cmd) = self.build_command() {
            capabilities.push(VerifierCapability {
                stage: VerifierStage::Build,
                command: Some(cmd),
                available: tool_available,
                fallback_command: None,
                fallback_available: false,
            });
        }

        // Test always has a command (test_command is required)
        capabilities.push(VerifierCapability {
            stage: VerifierStage::Test,
            command: Some(self.test_command()),
            available: tool_available,
            fallback_command: None,
            fallback_available: false,
        });

        if let Some(cmd) = self.lint_command() {
            capabilities.push(VerifierCapability {
                stage: VerifierStage::Lint,
                command: Some(cmd),
                available: tool_available,
                fallback_command: None,
                fallback_available: false,
            });
        }

        let primary_config = self.get_lsp_config();
        let primary_available = host_binary_available(&primary_config.server_binary);
        let fallback = self.lsp_fallback();
        let fallback_available = fallback
            .as_ref()
            .map(|f| host_binary_available(&f.server_binary))
            .unwrap_or(false);

        VerifierProfile {
            plugin_name: self.name().to_string(),
            capabilities,
            lsp: LspCapability {
                primary: primary_config,
                primary_available,
                fallback,
                fallback_available,
            },
        }
    }
}

/// Rust language plugin
pub struct RustPlugin;

impl LanguagePlugin for RustPlugin {
    fn name(&self) -> &str {
        "rust"
    }

    fn extensions(&self) -> &[&str] {
        &["rs"]
    }

    fn key_files(&self) -> &[&str] {
        &["Cargo.toml", "Cargo.lock"]
    }

    fn required_binaries(&self) -> Vec<(&str, &str, &str)> {
        vec![
            ("cargo", "build/init", "Install Rust via https://rustup.rs"),
            ("rustc", "compiler", "Install Rust via https://rustup.rs"),
            (
                "rust-analyzer",
                "language server",
                "rustup component add rust-analyzer",
            ),
        ]
    }

    fn get_lsp_config(&self) -> LspConfig {
        LspConfig {
            server_binary: "rust-analyzer".to_string(),
            args: vec![],
            language_id: "rust".to_string(),
        }
    }

    fn get_init_action(&self, opts: &InitOptions) -> ProjectAction {
        let command = if opts.is_empty_dir || opts.name == "." || opts.name == "./" {
            "cargo init .".to_string()
        } else {
            format!("cargo new {}", opts.name)
        };
        ProjectAction::ExecCommand {
            command,
            description: "Initialize Rust project with Cargo".to_string(),
        }
    }

    fn check_tooling_action(&self, path: &Path) -> ProjectAction {
        // Check if Cargo.lock exists; if not, suggest cargo fetch
        if !path.join("Cargo.lock").exists() && path.join("Cargo.toml").exists() {
            ProjectAction::ExecCommand {
                command: "cargo fetch".to_string(),
                description: "Fetch Rust dependencies".to_string(),
            }
        } else {
            ProjectAction::NoAction
        }
    }

    fn init_command(&self, opts: &InitOptions) -> String {
        if opts.name == "." || opts.name == "./" {
            "cargo init .".to_string()
        } else {
            format!("cargo new {}", opts.name)
        }
    }

    fn test_command(&self) -> String {
        "cargo test".to_string()
    }

    fn run_command(&self) -> String {
        "cargo run".to_string()
    }

    // PSP-5 capability methods

    fn syntax_check_command(&self) -> Option<String> {
        Some("cargo check".to_string())
    }

    fn build_command(&self) -> Option<String> {
        Some("cargo build".to_string())
    }

    fn lint_command(&self) -> Option<String> {
        Some("cargo clippy -- -D warnings".to_string())
    }

    fn file_ownership_patterns(&self) -> &[&str] {
        &["rs", "Cargo.toml"]
    }

    fn host_tool_available(&self) -> bool {
        host_binary_available("cargo")
    }

    fn verifier_profile(&self) -> VerifierProfile {
        let cargo = host_binary_available("cargo");
        let clippy = cargo; // clippy is a cargo subcommand, same binary

        let capabilities = vec![
            VerifierCapability {
                stage: VerifierStage::SyntaxCheck,
                command: Some("cargo check".to_string()),
                available: cargo,
                fallback_command: None,
                fallback_available: false,
            },
            VerifierCapability {
                stage: VerifierStage::Build,
                command: Some("cargo build".to_string()),
                available: cargo,
                fallback_command: None,
                fallback_available: false,
            },
            VerifierCapability {
                stage: VerifierStage::Test,
                command: Some("cargo test".to_string()),
                available: cargo,
                fallback_command: None,
                fallback_available: false,
            },
            VerifierCapability {
                stage: VerifierStage::Lint,
                command: Some("cargo clippy -- -D warnings".to_string()),
                available: clippy,
                fallback_command: None,
                fallback_available: false,
            },
        ];

        let primary = self.get_lsp_config();
        let primary_available = host_binary_available(&primary.server_binary);

        VerifierProfile {
            plugin_name: self.name().to_string(),
            capabilities,
            lsp: LspCapability {
                primary,
                primary_available,
                fallback: None,
                fallback_available: false,
            },
        }
    }
}

/// Python language plugin (uses ty via uvx)
pub struct PythonPlugin;

impl LanguagePlugin for PythonPlugin {
    fn name(&self) -> &str {
        "python"
    }

    fn extensions(&self) -> &[&str] {
        &["py"]
    }

    fn key_files(&self) -> &[&str] {
        &["pyproject.toml", "setup.py", "requirements.txt", "uv.lock"]
    }

    fn required_binaries(&self) -> Vec<(&str, &str, &str)> {
        vec![
            (
                "uv",
                "package manager",
                "curl -LsSf https://astral.sh/uv/install.sh | sh",
            ),
            (
                "python3",
                "interpreter",
                "uv python install (or install from https://python.org)",
            ),
            (
                "uvx",
                "tool runner/LSP",
                "Installed with uv — curl -LsSf https://astral.sh/uv/install.sh | sh",
            ),
        ]
    }

    fn get_lsp_config(&self) -> LspConfig {
        // Prefer ty (via uvx) as the native Python support
        // Falls back to pyright if ty is not available
        LspConfig {
            server_binary: "uvx".to_string(),
            args: vec!["ty".to_string(), "server".to_string()],
            language_id: "python".to_string(),
        }
    }

    fn get_init_action(&self, opts: &InitOptions) -> ProjectAction {
        let command = match opts.package_manager.as_deref() {
            Some("poetry") => {
                if opts.is_empty_dir || opts.name == "." || opts.name == "./" {
                    "poetry init --no-interaction".to_string()
                } else {
                    format!("poetry new {}", opts.name)
                }
            }
            Some("pdm") => {
                if opts.is_empty_dir || opts.name == "." || opts.name == "./" {
                    "pdm init --non-interactive".to_string()
                } else {
                    format!(
                        "mkdir -p {} && cd {} && pdm init --non-interactive",
                        opts.name, opts.name
                    )
                }
            }
            _ => {
                // Default to uv --lib for src-layout with build-system
                if opts.is_empty_dir || opts.name == "." || opts.name == "./" {
                    "uv init --lib".to_string()
                } else {
                    format!("uv init --lib {}", opts.name)
                }
            }
        };
        let description = match opts.package_manager.as_deref() {
            Some("poetry") => "Initialize Python project with Poetry",
            Some("pdm") => "Initialize Python project with PDM",
            _ => "Initialize Python project with uv",
        };
        ProjectAction::ExecCommand {
            command,
            description: description.to_string(),
        }
    }

    fn check_tooling_action(&self, path: &Path) -> ProjectAction {
        // Check for pyproject.toml but missing .venv or uv.lock
        let has_pyproject = path.join("pyproject.toml").exists();
        let has_venv = path.join(".venv").exists();
        let has_uv_lock = path.join("uv.lock").exists();

        if has_pyproject && (!has_venv || !has_uv_lock) {
            ProjectAction::ExecCommand {
                command: "uv sync".to_string(),
                description: "Sync Python dependencies with uv".to_string(),
            }
        } else {
            ProjectAction::NoAction
        }
    }

    fn init_command(&self, opts: &InitOptions) -> String {
        if opts.package_manager.as_deref() == Some("poetry") {
            if opts.name == "." || opts.name == "./" {
                "poetry init".to_string()
            } else {
                format!("poetry new {}", opts.name)
            }
        } else {
            // uv init --lib for src-layout with build-system
            format!("uv init --lib {}", opts.name)
        }
    }

    fn test_command(&self) -> String {
        "uv run pytest".to_string()
    }

    fn run_command(&self) -> String {
        "uv run python -m main".to_string()
    }

    /// Detect the package name from pyproject.toml or src layout and return
    /// an appropriate run command.
    fn run_command_for_dir(&self, path: &Path) -> String {
        // Check src/<pkg>/__main__.py first
        if let Ok(entries) = std::fs::read_dir(path.join("src")) {
            for entry in entries.flatten() {
                if entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
                    let name = entry.file_name().to_string_lossy().to_string();
                    if !name.starts_with('.') && !name.starts_with('_') {
                        return format!("uv run python -m {}", name);
                    }
                }
            }
        }

        // Check for [project.scripts] in pyproject.toml
        if let Ok(content) = std::fs::read_to_string(path.join("pyproject.toml")) {
            if content.contains("[project.scripts]") {
                // Parse the first script name
                let mut in_scripts = false;
                for raw_line in content.lines() {
                    let line = raw_line.trim();
                    if line == "[project.scripts]" {
                        in_scripts = true;
                        continue;
                    }
                    if in_scripts {
                        if line.starts_with('[') {
                            break;
                        }
                        if let Some((name, _)) = line.split_once('=') {
                            let script = name.trim().trim_matches('"');
                            if !script.is_empty() {
                                return format!("uv run {}", script);
                            }
                        }
                    }
                }
            }
        }

        // Default: run main module
        "uv run python -m main".to_string()
    }

    // PSP-5 capability methods

    fn syntax_check_command(&self) -> Option<String> {
        Some("uvx ty check .".to_string())
    }

    fn lint_command(&self) -> Option<String> {
        Some("uv run ruff check .".to_string())
    }

    fn file_ownership_patterns(&self) -> &[&str] {
        &["py", "pyproject.toml", "setup.py", "requirements.txt"]
    }

    fn host_tool_available(&self) -> bool {
        host_binary_available("uv")
    }

    fn lsp_fallback(&self) -> Option<LspConfig> {
        Some(LspConfig {
            server_binary: "pyright-langserver".to_string(),
            args: vec!["--stdio".to_string()],
            language_id: "python".to_string(),
        })
    }

    fn verifier_profile(&self) -> VerifierProfile {
        let uv = host_binary_available("uv");
        let pyright = host_binary_available("pyright");

        let capabilities = vec![
            VerifierCapability {
                stage: VerifierStage::SyntaxCheck,
                command: Some("uvx ty check .".to_string()),
                available: uv,
                // pyright as CLI fallback for syntax checking
                fallback_command: Some("pyright .".to_string()),
                fallback_available: pyright,
            },
            VerifierCapability {
                stage: VerifierStage::Build,
                // Python has no separate build step; declare the capability
                // so the sensor doesn't appear as Unavailable/degraded.
                command: None,
                available: true,
                fallback_command: None,
                fallback_available: false,
            },
            VerifierCapability {
                stage: VerifierStage::Test,
                command: Some("uv run pytest".to_string()),
                available: uv,
                // bare pytest fallback
                fallback_command: Some("python -m pytest".to_string()),
                fallback_available: host_binary_available("python3")
                    || host_binary_available("python"),
            },
            VerifierCapability {
                stage: VerifierStage::Lint,
                command: Some("uv run ruff check .".to_string()),
                available: uv,
                fallback_command: Some("ruff check .".to_string()),
                fallback_available: host_binary_available("ruff"),
            },
        ];

        let primary = self.get_lsp_config();
        let primary_available = host_binary_available("uvx");
        let fallback = self.lsp_fallback();
        let fallback_available = fallback
            .as_ref()
            .map(|f| host_binary_available(&f.server_binary))
            .unwrap_or(false);

        VerifierProfile {
            plugin_name: self.name().to_string(),
            capabilities,
            lsp: LspCapability {
                primary,
                primary_available,
                fallback,
                fallback_available,
            },
        }
    }
}

/// JavaScript/TypeScript language plugin
pub struct JsPlugin;

impl LanguagePlugin for JsPlugin {
    fn name(&self) -> &str {
        "javascript"
    }

    fn extensions(&self) -> &[&str] {
        &["js", "ts", "jsx", "tsx"]
    }

    fn key_files(&self) -> &[&str] {
        &["package.json", "tsconfig.json"]
    }

    fn required_binaries(&self) -> Vec<(&str, &str, &str)> {
        vec![
            (
                "node",
                "runtime",
                "Install Node.js from https://nodejs.org or via nvm",
            ),
            (
                "npm",
                "package manager",
                "Included with Node.js — install from https://nodejs.org",
            ),
            (
                "typescript-language-server",
                "language server",
                "npm install -g typescript-language-server typescript",
            ),
        ]
    }

    fn get_lsp_config(&self) -> LspConfig {
        LspConfig {
            server_binary: "typescript-language-server".to_string(),
            args: vec!["--stdio".to_string()],
            language_id: "typescript".to_string(),
        }
    }

    fn get_init_action(&self, opts: &InitOptions) -> ProjectAction {
        let command = match opts.package_manager.as_deref() {
            Some("pnpm") => {
                if opts.is_empty_dir || opts.name == "." || opts.name == "./" {
                    "pnpm init".to_string()
                } else {
                    format!("mkdir -p {} && cd {} && pnpm init", opts.name, opts.name)
                }
            }
            Some("yarn") => {
                if opts.is_empty_dir || opts.name == "." || opts.name == "./" {
                    "yarn init -y".to_string()
                } else {
                    format!("mkdir -p {} && cd {} && yarn init -y", opts.name, opts.name)
                }
            }
            _ => {
                // Default to npm
                if opts.is_empty_dir || opts.name == "." || opts.name == "./" {
                    "npm init -y".to_string()
                } else {
                    format!("mkdir -p {} && cd {} && npm init -y", opts.name, opts.name)
                }
            }
        };
        let description = match opts.package_manager.as_deref() {
            Some("pnpm") => "Initialize JavaScript project with pnpm",
            Some("yarn") => "Initialize JavaScript project with Yarn",
            _ => "Initialize JavaScript project with npm",
        };
        ProjectAction::ExecCommand {
            command,
            description: description.to_string(),
        }
    }

    fn check_tooling_action(&self, path: &Path) -> ProjectAction {
        // Check for package.json but missing node_modules
        let has_package_json = path.join("package.json").exists();
        let has_node_modules = path.join("node_modules").exists();

        if has_package_json && !has_node_modules {
            ProjectAction::ExecCommand {
                command: "npm install".to_string(),
                description: "Install Node.js dependencies".to_string(),
            }
        } else {
            ProjectAction::NoAction
        }
    }

    fn init_command(&self, opts: &InitOptions) -> String {
        format!("npm init -y && mv package.json {}/", opts.name)
    }

    fn test_command(&self) -> String {
        "npm test".to_string()
    }

    fn run_command(&self) -> String {
        "npm start".to_string()
    }

    // PSP-5 capability methods

    fn syntax_check_command(&self) -> Option<String> {
        Some("npx tsc --noEmit".to_string())
    }

    fn build_command(&self) -> Option<String> {
        Some("npm run build".to_string())
    }

    fn lint_command(&self) -> Option<String> {
        Some("npx eslint .".to_string())
    }

    fn file_ownership_patterns(&self) -> &[&str] {
        &["js", "ts", "jsx", "tsx", "package.json", "tsconfig.json"]
    }

    fn host_tool_available(&self) -> bool {
        host_binary_available("node")
    }

    fn verifier_profile(&self) -> VerifierProfile {
        let node = host_binary_available("node");
        let npx = host_binary_available("npx");

        let capabilities = vec![
            VerifierCapability {
                stage: VerifierStage::SyntaxCheck,
                command: Some("npx tsc --noEmit".to_string()),
                available: npx,
                fallback_command: None,
                fallback_available: false,
            },
            VerifierCapability {
                stage: VerifierStage::Build,
                command: Some("npm run build".to_string()),
                available: node,
                fallback_command: None,
                fallback_available: false,
            },
            VerifierCapability {
                stage: VerifierStage::Test,
                command: Some("npm test".to_string()),
                available: node,
                fallback_command: None,
                fallback_available: false,
            },
            VerifierCapability {
                stage: VerifierStage::Lint,
                command: Some("npx eslint .".to_string()),
                available: npx,
                fallback_command: None,
                fallback_available: false,
            },
        ];

        let primary = self.get_lsp_config();
        let primary_available = host_binary_available(&primary.server_binary);

        VerifierProfile {
            plugin_name: self.name().to_string(),
            capabilities,
            lsp: LspCapability {
                primary,
                primary_available,
                fallback: None,
                fallback_available: false,
            },
        }
    }
}

/// Plugin registry for dynamic language detection
pub struct PluginRegistry {
    plugins: Vec<Box<dyn LanguagePlugin>>,
}

impl PluginRegistry {
    /// Create a new registry with all built-in plugins
    pub fn new() -> Self {
        Self {
            plugins: vec![
                Box::new(RustPlugin),
                Box::new(PythonPlugin),
                Box::new(JsPlugin),
            ],
        }
    }

    /// Detect which plugin should handle the given path (first match)
    pub fn detect(&self, path: &Path) -> Option<&dyn LanguagePlugin> {
        self.plugins
            .iter()
            .find(|p| p.detect(path))
            .map(|p| p.as_ref())
    }

    /// PSP-5: Detect ALL plugins that match the given path (polyglot support)
    ///
    /// Returns all matching plugins instead of just the first, enabling
    /// multi-language verification in polyglot repositories.
    pub fn detect_all(&self, path: &Path) -> Vec<&dyn LanguagePlugin> {
        self.plugins
            .iter()
            .filter(|p| p.detect(path))
            .map(|p| p.as_ref())
            .collect()
    }

    /// Get a plugin by name
    pub fn get(&self, name: &str) -> Option<&dyn LanguagePlugin> {
        self.plugins
            .iter()
            .find(|p| p.name() == name)
            .map(|p| p.as_ref())
    }

    /// Get all registered plugins
    pub fn all(&self) -> &[Box<dyn LanguagePlugin>] {
        &self.plugins
    }
}

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

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

    #[test]
    fn test_plugin_owns_file() {
        let rust = RustPlugin;
        assert!(rust.owns_file("src/main.rs"));
        assert!(rust.owns_file("crates/core/src/lib.rs"));
        assert!(!rust.owns_file("main.py"));
        assert!(!rust.owns_file("index.js"));

        let python = PythonPlugin;
        assert!(python.owns_file("main.py"));
        assert!(python.owns_file("tests/test_main.py"));
        assert!(!python.owns_file("src/main.rs"));

        let js = JsPlugin;
        assert!(js.owns_file("index.js"));
        assert!(js.owns_file("src/app.ts"));
        assert!(!js.owns_file("main.py"));
        assert!(!js.owns_file("src/main.rs"));
    }

    // =========================================================================
    // Verifier Capability & Profile Tests
    // =========================================================================

    #[test]
    fn test_verifier_capability_effective_command() {
        // Primary available → primary wins
        let cap = VerifierCapability {
            stage: VerifierStage::SyntaxCheck,
            command: Some("cargo check".to_string()),
            available: true,
            fallback_command: Some("rustc --edition 2021".to_string()),
            fallback_available: true,
        };
        assert_eq!(cap.effective_command(), Some("cargo check"));
        assert!(cap.any_available());

        // Primary unavailable, fallback available → fallback wins
        let cap2 = VerifierCapability {
            stage: VerifierStage::Lint,
            command: Some("uv run ruff check .".to_string()),
            available: false,
            fallback_command: Some("ruff check .".to_string()),
            fallback_available: true,
        };
        assert_eq!(cap2.effective_command(), Some("ruff check ."));
        assert!(cap2.any_available());

        // Both unavailable → None
        let cap3 = VerifierCapability {
            stage: VerifierStage::Build,
            command: Some("cargo build".to_string()),
            available: false,
            fallback_command: None,
            fallback_available: false,
        };
        assert_eq!(cap3.effective_command(), None);
        assert!(!cap3.any_available());
    }

    #[test]
    fn test_verifier_profile_get_and_available_stages() {
        let profile = VerifierProfile {
            plugin_name: "test".to_string(),
            capabilities: vec![
                VerifierCapability {
                    stage: VerifierStage::SyntaxCheck,
                    command: Some("check".to_string()),
                    available: true,
                    fallback_command: None,
                    fallback_available: false,
                },
                VerifierCapability {
                    stage: VerifierStage::Build,
                    command: Some("build".to_string()),
                    available: false,
                    fallback_command: None,
                    fallback_available: false,
                },
                VerifierCapability {
                    stage: VerifierStage::Test,
                    command: Some("test".to_string()),
                    available: true,
                    fallback_command: None,
                    fallback_available: false,
                },
            ],
            lsp: LspCapability {
                primary: LspConfig {
                    server_binary: "test-ls".to_string(),
                    args: vec![],
                    language_id: "test".to_string(),
                },
                primary_available: false,
                fallback: None,
                fallback_available: false,
            },
        };

        assert!(profile.get(VerifierStage::SyntaxCheck).is_some());
        assert!(profile.get(VerifierStage::Lint).is_none());

        let available = profile.available_stages();
        assert_eq!(available.len(), 2);
        assert!(available.contains(&VerifierStage::SyntaxCheck));
        assert!(available.contains(&VerifierStage::Test));
        assert!(!available.contains(&VerifierStage::Build));
        assert!(!profile.fully_degraded());
    }

    #[test]
    fn test_verifier_profile_fully_degraded() {
        let profile = VerifierProfile {
            plugin_name: "empty".to_string(),
            capabilities: vec![VerifierCapability {
                stage: VerifierStage::Build,
                command: Some("build".to_string()),
                available: false,
                fallback_command: None,
                fallback_available: false,
            }],
            lsp: LspCapability {
                primary: LspConfig {
                    server_binary: "none".to_string(),
                    args: vec![],
                    language_id: "none".to_string(),
                },
                primary_available: false,
                fallback: None,
                fallback_available: false,
            },
        };
        assert!(profile.fully_degraded());
        assert!(profile.available_stages().is_empty());
    }

    #[test]
    fn test_lsp_capability_effective_config() {
        let lsp = LspCapability {
            primary: LspConfig {
                server_binary: "rust-analyzer".to_string(),
                args: vec![],
                language_id: "rust".to_string(),
            },
            primary_available: true,
            fallback: None,
            fallback_available: false,
        };
        assert_eq!(
            lsp.effective_config().unwrap().server_binary,
            "rust-analyzer"
        );

        // Primary unavailable, fallback available
        let lsp2 = LspCapability {
            primary: LspConfig {
                server_binary: "uvx".to_string(),
                args: vec![],
                language_id: "python".to_string(),
            },
            primary_available: false,
            fallback: Some(LspConfig {
                server_binary: "pyright-langserver".to_string(),
                args: vec!["--stdio".to_string()],
                language_id: "python".to_string(),
            }),
            fallback_available: true,
        };
        assert_eq!(
            lsp2.effective_config().unwrap().server_binary,
            "pyright-langserver"
        );

        // Both unavailable
        let lsp3 = LspCapability {
            primary: LspConfig {
                server_binary: "nope".to_string(),
                args: vec![],
                language_id: "none".to_string(),
            },
            primary_available: false,
            fallback: None,
            fallback_available: false,
        };
        assert!(lsp3.effective_config().is_none());
    }

    #[test]
    fn test_rust_plugin_verifier_profile_shape() {
        let rust = RustPlugin;
        let profile = rust.verifier_profile();
        assert_eq!(profile.plugin_name, "rust");
        // Rust should declare all 4 stages
        assert_eq!(profile.capabilities.len(), 4);
        let stages: Vec<_> = profile.capabilities.iter().map(|c| c.stage).collect();
        assert!(stages.contains(&VerifierStage::SyntaxCheck));
        assert!(stages.contains(&VerifierStage::Build));
        assert!(stages.contains(&VerifierStage::Test));
        assert!(stages.contains(&VerifierStage::Lint));
    }

    #[test]
    fn test_python_plugin_verifier_profile_shape() {
        let py = PythonPlugin;
        let profile = py.verifier_profile();
        assert_eq!(profile.plugin_name, "python");
        // Python: syntax_check, build (no-op), test, lint
        assert_eq!(profile.capabilities.len(), 4);
        let stages: Vec<_> = profile.capabilities.iter().map(|c| c.stage).collect();
        assert!(stages.contains(&VerifierStage::SyntaxCheck));
        assert!(stages.contains(&VerifierStage::Build));
        assert!(stages.contains(&VerifierStage::Test));
        assert!(stages.contains(&VerifierStage::Lint));
        // Python has an LSP fallback declared
        assert!(profile.lsp.fallback.is_some());
    }

    #[test]
    fn test_js_plugin_verifier_profile_shape() {
        let js = JsPlugin;
        let profile = js.verifier_profile();
        assert_eq!(profile.plugin_name, "javascript");
        // JS: all 4 stages
        assert_eq!(profile.capabilities.len(), 4);
    }

    #[test]
    fn test_verifier_stage_display() {
        assert_eq!(format!("{}", VerifierStage::SyntaxCheck), "syntax_check");
        assert_eq!(format!("{}", VerifierStage::Build), "build");
        assert_eq!(format!("{}", VerifierStage::Test), "test");
        assert_eq!(format!("{}", VerifierStage::Lint), "lint");
    }

    #[test]
    fn test_python_run_command_for_dir_src_layout() {
        let dir =
            std::env::temp_dir().join(format!("perspt_test_pyrun_src_{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(dir.join("src/myapp")).unwrap();
        std::fs::write(dir.join("src/myapp/__init__.py"), "").unwrap();

        let plugin = PythonPlugin;
        let cmd = plugin.run_command_for_dir(&dir);
        assert_eq!(cmd, "uv run python -m myapp");

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_python_run_command_for_dir_scripts() {
        let dir = std::env::temp_dir().join(format!(
            "perspt_test_pyrun_scripts_{}",
            uuid::Uuid::new_v4()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("pyproject.toml"),
            "[project]\nname = \"myapp\"\n\n[project.scripts]\nmyapp = \"myapp:main\"\n",
        )
        .unwrap();

        let plugin = PythonPlugin;
        let cmd = plugin.run_command_for_dir(&dir);
        assert_eq!(cmd, "uv run myapp");

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_python_run_command_for_dir_default() {
        let dir = std::env::temp_dir().join(format!(
            "perspt_test_pyrun_default_{}",
            uuid::Uuid::new_v4()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("pyproject.toml"), "[project]\nname = \"myapp\"\n").unwrap();

        let plugin = PythonPlugin;
        let cmd = plugin.run_command_for_dir(&dir);
        assert_eq!(cmd, "uv run python -m main");

        let _ = std::fs::remove_dir_all(&dir);
    }
}