Skip to main content

perspt_coding/
lang.rs

1//! Language adapters (PSP-8 System 5 / Gate D).
2//!
3//! A coding language adapter evolves from a command selector into a verifier
4//! suite: it parses compiler/type-checker/test output into typed
5//! [`ResidualEvent`]s and maps each into a [`CorrectionDirection`]. Actually
6//! *running* the tools is the runtime's job; the testable core here is the
7//! normalization from raw diagnostic text to residual evidence, which is what
8//! makes corrections directed rather than undirected retries.
9
10use std::path::Path;
11
12use perspt_sdk::{
13    CorrectionDirection, IndependenceRoute, ResidualClass, ResidualEvent, ResidualSeverity,
14    SensorRef,
15};
16
17use crate::LanguageId;
18use crate::runtime::{SmokeInvocation, default_classify_runtime};
19
20/// A coding language adapter: a verifier-suite provider for one language.
21pub trait LanguageAdapter: Send + Sync {
22    /// The open, stable language identifier this adapter answers to.
23    fn id(&self) -> LanguageId;
24    /// The primary diagnostic sensor for this language.
25    fn diagnostic_sensor(&self) -> SensorRef;
26    /// Parse raw diagnostic output into typed residuals.
27    fn parse_diagnostics(&self, node_id: &str, generation: u32, raw: &str) -> Vec<ResidualEvent>;
28    /// Map a residual to a correction direction, or `None` when there is none.
29    fn correction_for(&self, residual: &ResidualEvent) -> Option<CorrectionDirection>;
30
31    /// Runtime smoke invocations to exercise the built artifact's entrypoints
32    /// (PSP-8 runtime probe). Default: none — a new adapter opts in by overriding
33    /// this. The runtime executes the returned commands from `workspace`.
34    fn smoke_invocations(&self, _workspace: &Path) -> Vec<SmokeInvocation> {
35        Vec::new()
36    }
37
38    /// Classify the output of a smoke invocation into `Runtime` residuals.
39    /// Default: shared crash-marker + non-zero-exit detection.
40    fn classify_runtime(
41        &self,
42        node_id: &str,
43        generation: u32,
44        invocation: &SmokeInvocation,
45        exit_success: bool,
46        output: &str,
47    ) -> Vec<ResidualEvent> {
48        default_classify_runtime(node_id, generation, invocation, exit_success, output)
49    }
50}
51
52/// Read the `[package] name` from a Cargo.toml, for naming `cargo run -p` targets.
53fn cargo_package_name(manifest: &Path) -> Option<String> {
54    let content = std::fs::read_to_string(manifest).ok()?;
55    let mut in_package = false;
56    for raw in content.lines() {
57        let line = raw.trim();
58        if line.starts_with('[') {
59            in_package = line == "[package]";
60            continue;
61        }
62        if in_package
63            && let Some(rest) = line.strip_prefix("name")
64            && let Some(eq) = rest.trim().strip_prefix('=')
65        {
66            return Some(eq.trim().trim_matches('"').trim_matches('\'').to_string());
67        }
68    }
69    None
70}
71
72fn residual(
73    node_id: &str,
74    generation: u32,
75    class: ResidualClass,
76    sensor: SensorRef,
77    summary: &str,
78) -> ResidualEvent {
79    let mut r = ResidualEvent::new(
80        node_id,
81        generation,
82        class,
83        ResidualSeverity::Error,
84        1.0,
85        sensor,
86    )
87    .expect("unit score is valid");
88    r.evidence.summary = summary.to_string();
89    r
90}
91
92/// The sensor fingerprint: tool identity, parser version, and the cluster
93/// normalization profile (PSP-10 Assumption 2).
94fn fingerprint(parser_id: &str) -> String {
95    format!("{parser_id}+{}", crate::diag::CLUSTER_PROFILE_V1)
96}
97
98/// Fold structured diagnostics into cluster-level residuals with full
99/// evidence (PSP-10 system 26). One residual per root-cause cluster; the
100/// magnitude is the profile-normalized cluster magnitude, never a raw
101/// diagnostic count.
102fn structured_residuals(
103    node_id: &str,
104    generation: u32,
105    diagnostics: Vec<crate::diag::StructuredDiagnostic>,
106    raw: &str,
107    sensor: SensorRef,
108) -> Vec<ResidualEvent> {
109    crate::diag::cluster(diagnostics)
110        .into_iter()
111        .filter_map(|cluster| {
112            let summary = if cluster.members.len() > 1 {
113                format!(
114                    "{} ({} diagnostics in cluster {})",
115                    cluster.root.message,
116                    cluster.members.len(),
117                    cluster.code
118                )
119            } else {
120                format!("{} ({})", cluster.root.message, cluster.code)
121            };
122            crate::diag::cluster_residual(
123                node_id,
124                generation,
125                cluster.class,
126                cluster.magnitude(),
127                sensor.clone(),
128                &summary,
129                raw,
130                &cluster.members,
131            )
132            .ok()
133        })
134        .collect()
135}
136
137// ============================ Rust ============================
138
139/// The Rust verifier-suite adapter (rustc / cargo / rust-analyzer).
140#[derive(Debug, Clone, Default)]
141pub struct RustAdapter;
142
143/// Classify a rustc error code into a residual class.
144pub fn classify_rust_code(code: &str) -> ResidualClass {
145    match code {
146        // Unresolved imports / missing modules.
147        "E0432" | "E0433" | "E0583" | "E0761" => ResidualClass::ImportGraph,
148        // Cannot find name / value / type.
149        "E0412" | "E0425" | "E0422" | "E0531" => ResidualClass::SymbolMismatch,
150        // Type / trait-bound mismatches.
151        "E0308" | "E0277" | "E0599" | "E0061" => ResidualClass::Type,
152        // Borrow / ownership / lifetimes.
153        "E0382" | "E0499" | "E0502" | "E0505" | "E0506" | "E0597" => {
154            ResidualClass::OwnershipViolation
155        }
156        // Visibility / privacy.
157        "E0603" | "E0616" => ResidualClass::InterfaceMismatch,
158        // Anything else compiler-emitted is a generic type/build residual.
159        _ => ResidualClass::Type,
160    }
161}
162
163impl LanguageAdapter for RustAdapter {
164    fn id(&self) -> LanguageId {
165        LanguageId::new("rust")
166    }
167
168    fn diagnostic_sensor(&self) -> SensorRef {
169        SensorRef::new("rustc", IndependenceRoute::Compiler)
170    }
171
172    fn parse_diagnostics(&self, node_id: &str, generation: u32, raw: &str) -> Vec<ResidualEvent> {
173        // The structured plane first: cargo's native JSON stream preserves
174        // codes, spans, and suggestions (PSP-10 system 26).
175        if crate::diag::cargo::looks_like_stream(raw) {
176            let sensor = self
177                .diagnostic_sensor()
178                .with_fingerprint(fingerprint(crate::diag::cargo::PARSER_ID));
179            let mut residuals = structured_residuals(
180                node_id,
181                generation,
182                crate::diag::cargo::parse(raw),
183                raw,
184                sensor,
185            );
186            residuals.extend(rust_test_failures(node_id, generation, raw));
187            return residuals;
188        }
189        // Text fallback under its own parser identity; never pooled with
190        // the JSON parser's measurements.
191        let sensor = self
192            .diagnostic_sensor()
193            .with_fingerprint("rustc-text-v1".to_string());
194        let mut residuals = Vec::new();
195        for line in raw.lines() {
196            let line = line.trim();
197            // `error[E0432]: unresolved import `foo``
198            if let Some(rest) = line.strip_prefix("error[")
199                && let Some(end) = rest.find(']')
200            {
201                let code = &rest[..end];
202                let class = classify_rust_code(code);
203                let summary = rest[end + 1..].trim_start_matches(':').trim();
204                residuals.push(residual(
205                    node_id,
206                    generation,
207                    class,
208                    sensor.clone(),
209                    summary,
210                ));
211            }
212        }
213        residuals.extend(rust_test_failures(node_id, generation, raw));
214        residuals
215    }
216
217    fn correction_for(&self, residual: &ResidualEvent) -> Option<CorrectionDirection> {
218        let summary = &residual.evidence.summary;
219        match residual.class {
220            ResidualClass::ImportGraph => Some(
221                CorrectionDirection::new(
222                    ResidualClass::ImportGraph,
223                    format!(
224                        "resolve the unresolved import ({summary}): add the missing `use` path or \
225                         declare the missing `mod`; do not regenerate unrelated code"
226                    ),
227                )
228                .with_rationale("unresolved imports are structural, not behavioral"),
229            ),
230            ResidualClass::SymbolMismatch => Some(CorrectionDirection::new(
231                ResidualClass::SymbolMismatch,
232                format!(
233                    "define or correct the referenced name ({summary}); check spelling and path"
234                ),
235            )),
236            ResidualClass::Type => Some(CorrectionDirection::new(
237                ResidualClass::Type,
238                format!(
239                    "reconcile the type/trait mismatch ({summary}); keep the public signature stable"
240                ),
241            )),
242            ResidualClass::OwnershipViolation => Some(CorrectionDirection::new(
243                ResidualClass::OwnershipViolation,
244                format!(
245                    "fix the borrow/ownership error ({summary}); clone, borrow, or restructure \
246                    lifetimes"
247                ),
248            )),
249            ResidualClass::InterfaceMismatch => Some(CorrectionDirection::new(
250                ResidualClass::InterfaceMismatch,
251                format!(
252                    "adjust visibility ({summary}); make the item `pub` or use an accessible path"
253                ),
254            )),
255            ResidualClass::TestFailure => Some(CorrectionDirection::new(
256                ResidualClass::TestFailure,
257                "fix the implementation the failing test attributes to; do not weaken the assertion",
258            )),
259            ResidualClass::Runtime => Some(CorrectionDirection::new(
260                ResidualClass::Runtime,
261                format!(
262                    "the built binary failed when actually run ({summary}); fix the runtime logic \
263                     (panics, index/shape mismatches, unwraps) so every entrypoint executes \
264                     cleanly, and add a test/example covering that runtime path"
265                ),
266            )),
267            _ => None,
268        }
269    }
270
271    fn smoke_invocations(&self, workspace: &Path) -> Vec<SmokeInvocation> {
272        let mut out = Vec::new();
273        // Binary crates: `cargo run -p <name> -- --help` exercises startup +
274        // arg parsing without needing real arguments.
275        for (name, _dir) in rust_binary_crates(workspace) {
276            out.push(SmokeInvocation::new(
277                format!("cargo run -q -p {name} -- --help"),
278                format!("{name} --help"),
279            ));
280        }
281        // Examples are the project's own end-to-end smoke; run each one. A good
282        // example exercises the real pipeline (e.g. train→predict), so a runtime
283        // bug there is caught here.
284        for (pkg, example) in rust_examples(workspace) {
285            let cmd = match pkg {
286                Some(ref p) => format!("cargo run -q -p {p} --example {example}"),
287                None => format!("cargo run -q --example {example}"),
288            };
289            out.push(SmokeInvocation::new(cmd, format!("example {example}")));
290        }
291        out
292    }
293}
294
295/// Test-failure lines from `cargo test` text output (both stream shapes).
296fn rust_test_failures(node_id: &str, generation: u32, raw: &str) -> Vec<ResidualEvent> {
297    raw.lines()
298        .map(str::trim)
299        .filter(|line| line.starts_with("test result: FAILED") || line.contains("... FAILED"))
300        .map(|line| {
301            residual(
302                node_id,
303                generation,
304                ResidualClass::TestFailure,
305                SensorRef::new("cargo-test", IndependenceRoute::TestOracle)
306                    .with_fingerprint("cargo-test-text-v1".to_string()),
307                line,
308            )
309        })
310        .collect()
311}
312
313/// Discover binary crates (those with `src/main.rs`) in a Cargo workspace:
314/// the root package and any `crates/*` members. Returns `(package_name, dir)`.
315fn rust_binary_crates(workspace: &Path) -> Vec<(String, std::path::PathBuf)> {
316    let mut out = Vec::new();
317    let mut consider = |dir: std::path::PathBuf| {
318        if dir.join("src/main.rs").exists()
319            && let Some(name) = cargo_package_name(&dir.join("Cargo.toml"))
320        {
321            out.push((name, dir));
322        }
323    };
324    consider(workspace.to_path_buf());
325    if let Ok(entries) = std::fs::read_dir(workspace.join("crates")) {
326        for entry in entries.flatten() {
327            if entry.path().is_dir() {
328                consider(entry.path());
329            }
330        }
331    }
332    out
333}
334
335/// Discover example targets: `examples/*.rs` at the root (no `-p`) and under
336/// each `crates/*` member (with that member's `-p`). Returns `(package, stem)`.
337fn rust_examples(workspace: &Path) -> Vec<(Option<String>, String)> {
338    let mut out = Vec::new();
339    let collect = |dir: &Path, pkg: Option<String>, out: &mut Vec<(Option<String>, String)>| {
340        if let Ok(entries) = std::fs::read_dir(dir.join("examples")) {
341            for entry in entries.flatten() {
342                let path = entry.path();
343                if path.extension().and_then(|e| e.to_str()) == Some("rs")
344                    && let Some(stem) = path.file_stem().and_then(|s| s.to_str())
345                {
346                    out.push((pkg.clone(), stem.to_string()));
347                }
348            }
349        }
350    };
351    collect(workspace, None, &mut out);
352    if let Ok(entries) = std::fs::read_dir(workspace.join("crates")) {
353        for entry in entries.flatten() {
354            if entry.path().is_dir() {
355                let pkg = cargo_package_name(&entry.path().join("Cargo.toml"));
356                collect(&entry.path(), pkg, &mut out);
357            }
358        }
359    }
360    out
361}
362
363// ============================ Python ============================
364
365/// The Python verifier-suite adapter. `ty` is the primary sensor; Pyright
366/// is a separately fingerprinted fallback (PSP-10 resolved decision 15).
367/// Attribution follows the observed output format — the historic
368/// split-brain that stamped every observation "pyright" is gone.
369#[derive(Debug, Clone, Default)]
370pub struct PythonAdapter;
371
372impl LanguageAdapter for PythonAdapter {
373    fn id(&self) -> LanguageId {
374        LanguageId::new("python")
375    }
376
377    fn diagnostic_sensor(&self) -> SensorRef {
378        SensorRef::new("ty", IndependenceRoute::Lsp)
379    }
380
381    fn parse_diagnostics(&self, node_id: &str, generation: u32, raw: &str) -> Vec<ResidualEvent> {
382        // `ty check --output-format concise` (primary text form).
383        let ty_diagnostics = crate::diag::ty::parse_check_text(raw);
384        if !ty_diagnostics.is_empty() {
385            let sensor = SensorRef::new("ty", IndependenceRoute::Lsp)
386                .with_fingerprint(fingerprint(crate::diag::ty::PARSER_ID));
387            let mut residuals =
388                structured_residuals(node_id, generation, ty_diagnostics, raw, sensor);
389            residuals.extend(python_test_failures(node_id, generation, raw));
390            return residuals;
391        }
392        // Pyright JSON fallback, under its own fingerprint — never pooled
393        // with `ty` measurements.
394        let pyright_diagnostics = crate::diag::pyright::parse(raw);
395        if !pyright_diagnostics.is_empty() {
396            let sensor = SensorRef::new("pyright", IndependenceRoute::Lsp)
397                .with_fingerprint(fingerprint(crate::diag::pyright::PARSER_ID));
398            let mut residuals =
399                structured_residuals(node_id, generation, pyright_diagnostics, raw, sensor);
400            residuals.extend(python_test_failures(node_id, generation, raw));
401            return residuals;
402        }
403        // Pytest JUnit XML.
404        let junit = crate::diag::pytest::parse(raw);
405        if !junit.is_empty() {
406            let sensor = SensorRef::new("pytest", IndependenceRoute::TestOracle)
407                .with_fingerprint(fingerprint(crate::diag::pytest::PARSER_ID));
408            return structured_residuals(node_id, generation, junit, raw, sensor);
409        }
410        // Legacy text scrape (stdlib checks, bare tracebacks) under the
411        // honest sensor identity of the interpreter, not a type checker.
412        let sensor = SensorRef::new("python-check", IndependenceRoute::Compiler)
413            .with_fingerprint("python-text-v1".to_string());
414        let mut residuals = Vec::new();
415        for line in raw.lines() {
416            let lower = line.to_lowercase();
417            let class = if lower.contains("could not be resolved")
418                || lower.contains("no module named")
419            {
420                Some(ResidualClass::ImportGraph)
421            } else if lower.contains("is not defined") || lower.contains("is possibly unbound") {
422                Some(ResidualClass::SymbolMismatch)
423            } else if lower.contains("incompatible")
424                || lower.contains("expected type")
425                || lower.contains("has type")
426            {
427                Some(ResidualClass::Type)
428            } else if lower.contains("failed") && lower.contains("test") {
429                Some(ResidualClass::TestFailure)
430            } else {
431                None
432            };
433            if let Some(class) = class {
434                let sensor = if class == ResidualClass::TestFailure {
435                    SensorRef::new("pytest", IndependenceRoute::TestOracle)
436                        .with_fingerprint("pytest-text-v1".to_string())
437                } else {
438                    sensor.clone()
439                };
440                residuals.push(residual(node_id, generation, class, sensor, line.trim()));
441            }
442        }
443        residuals
444    }
445
446    fn correction_for(&self, residual: &ResidualEvent) -> Option<CorrectionDirection> {
447        let summary = &residual.evidence.summary;
448        match residual.class {
449            ResidualClass::ImportGraph => Some(CorrectionDirection::new(
450                ResidualClass::ImportGraph,
451                format!(
452                    "add the missing import or install/declare the package ({summary}); sync the \
453                    environment"
454                ),
455            )),
456            ResidualClass::SymbolMismatch => Some(CorrectionDirection::new(
457                ResidualClass::SymbolMismatch,
458                format!("define the referenced name or fix its binding ({summary})"),
459            )),
460            ResidualClass::Type => Some(CorrectionDirection::new(
461                ResidualClass::Type,
462                format!(
463                    "reconcile the type mismatch ({summary}); adjust the value or the annotation"
464                ),
465            )),
466            ResidualClass::TestFailure => Some(CorrectionDirection::new(
467                ResidualClass::TestFailure,
468                "fix the code under the failing pytest case; preserve the assertion",
469            )),
470            ResidualClass::Runtime => Some(CorrectionDirection::new(
471                ResidualClass::Runtime,
472                format!(
473                    "the package failed when actually run/imported ({summary}); fix the runtime \
474                     error (import-time exceptions, shape/type mismatches) and add a test/example \
475                     covering that path"
476                ),
477            )),
478            _ => None,
479        }
480    }
481
482    fn smoke_invocations(&self, workspace: &Path) -> Vec<SmokeInvocation> {
483        // Import smoke: importing the package executes all module top-level code,
484        // catching import-time errors that unit tests on submodules can miss.
485        python_packages(workspace)
486            .into_iter()
487            .map(|pkg| {
488                SmokeInvocation::new(
489                    format!("uv run python -c \"import {pkg}\""),
490                    format!("import {pkg}"),
491                )
492            })
493            .collect()
494    }
495}
496
497/// Pytest text-output failures (when no JUnit XML was produced).
498fn python_test_failures(node_id: &str, generation: u32, raw: &str) -> Vec<ResidualEvent> {
499    raw.lines()
500        .map(str::trim)
501        .filter(|line| {
502            let lower = line.to_lowercase();
503            lower.contains("failed") && lower.contains("test")
504        })
505        .map(|line| {
506            residual(
507                node_id,
508                generation,
509                ResidualClass::TestFailure,
510                SensorRef::new("pytest", IndependenceRoute::TestOracle)
511                    .with_fingerprint("pytest-text-v1".to_string()),
512                line,
513            )
514        })
515        .collect()
516}
517
518/// Discover importable top-level packages: directories containing `__init__.py`
519/// under `src/` (src-layout) or the workspace root (flat layout).
520fn python_packages(workspace: &Path) -> Vec<String> {
521    let mut out = Vec::new();
522    for base in [workspace.join("src"), workspace.to_path_buf()] {
523        if let Ok(entries) = std::fs::read_dir(&base) {
524            for entry in entries.flatten() {
525                let path = entry.path();
526                if path.is_dir()
527                    && path.join("__init__.py").exists()
528                    && let Some(name) = path.file_name().and_then(|n| n.to_str())
529                    && !out.iter().any(|p| p == name)
530                {
531                    out.push(name.to_string());
532                }
533            }
534        }
535    }
536    out
537}
538
539// ============================ TypeScript ============================
540
541/// The JavaScript/TypeScript verifier-suite adapter (tsc / eslint).
542#[derive(Debug, Clone, Default)]
543pub struct TypeScriptAdapter;
544
545/// Classify a TypeScript diagnostic code (e.g. `TS2307`).
546pub fn classify_ts_code(code: &str) -> ResidualClass {
547    match code {
548        "TS2307" => ResidualClass::ImportGraph, // cannot find module
549        "TS2304" => ResidualClass::SymbolMismatch, // cannot find name
550        "TS2305" | "TS2614" => ResidualClass::InterfaceMismatch, // no exported member
551        "TS2322" | "TS2345" | "TS2769" => ResidualClass::Type, // type mismatches
552        "TS6133" | "TS6192" => ResidualClass::Lint, // unused
553        _ => ResidualClass::Type,
554    }
555}
556
557impl LanguageAdapter for TypeScriptAdapter {
558    fn id(&self) -> LanguageId {
559        LanguageId::new("typescript")
560    }
561
562    fn diagnostic_sensor(&self) -> SensorRef {
563        SensorRef::new("tsc", IndependenceRoute::Compiler)
564    }
565
566    fn parse_diagnostics(&self, node_id: &str, generation: u32, raw: &str) -> Vec<ResidualEvent> {
567        // The versioned `tsc --pretty false` normalizer preserves paths and
568        // positions (PSP-10 system 26).
569        let structured = crate::diag::tsc::parse(raw);
570        if !structured.is_empty() {
571            let sensor = self
572                .diagnostic_sensor()
573                .with_fingerprint(fingerprint(crate::diag::tsc::PARSER_ID));
574            return structured_residuals(node_id, generation, structured, raw, sensor);
575        }
576        // Fallback for lines without the position prefix.
577        let sensor = self
578            .diagnostic_sensor()
579            .with_fingerprint("tsc-loose-text-v1".to_string());
580        let mut residuals = Vec::new();
581        for line in raw.lines() {
582            if let Some(idx) = line.find("error TS") {
583                let rest = &line[idx + "error ".len()..];
584                let code: String = rest
585                    .chars()
586                    .take_while(|c| !c.is_whitespace() && *c != ':')
587                    .collect();
588                let class = classify_ts_code(&code);
589                let summary = rest.split_once(':').map(|(_, s)| s.trim()).unwrap_or(rest);
590                residuals.push(residual(
591                    node_id,
592                    generation,
593                    class,
594                    sensor.clone(),
595                    summary,
596                ));
597            }
598        }
599        residuals
600    }
601
602    fn correction_for(&self, residual: &ResidualEvent) -> Option<CorrectionDirection> {
603        let summary = &residual.evidence.summary;
604        match residual.class {
605            ResidualClass::ImportGraph => Some(CorrectionDirection::new(
606                ResidualClass::ImportGraph,
607                format!(
608                    "fix the module path or add the dependency ({summary}); check tsconfig path \
609                    aliases"
610                ),
611            )),
612            ResidualClass::SymbolMismatch => Some(CorrectionDirection::new(
613                ResidualClass::SymbolMismatch,
614                format!("import or declare the missing name ({summary})"),
615            )),
616            ResidualClass::InterfaceMismatch => Some(CorrectionDirection::new(
617                ResidualClass::InterfaceMismatch,
618                format!("export the missing member or fix the import binding ({summary})"),
619            )),
620            ResidualClass::Type => Some(CorrectionDirection::new(
621                ResidualClass::Type,
622                format!("reconcile the type mismatch ({summary})"),
623            )),
624            ResidualClass::Lint => Some(CorrectionDirection::new(
625                ResidualClass::Lint,
626                format!("remove the unused symbol ({summary})"),
627            )),
628            _ => None,
629        }
630    }
631}
632
633#[cfg(test)]
634mod tests {
635    use super::*;
636
637    #[test]
638    fn rust_unresolved_import_classified_and_directed() {
639        let adapter = RustAdapter;
640        let raw = "error[E0432]: unresolved import `crate::foo::Bar`";
641        let residuals = adapter.parse_diagnostics("n1", 0, raw);
642        assert_eq!(residuals.len(), 1);
643        assert_eq!(residuals[0].class, ResidualClass::ImportGraph);
644        let dir = adapter.correction_for(&residuals[0]).unwrap();
645        assert_eq!(dir.addresses, ResidualClass::ImportGraph);
646        assert!(dir.instruction.contains("use"));
647    }
648
649    #[test]
650    fn rust_classifies_a_spread_of_codes() {
651        assert_eq!(classify_rust_code("E0308"), ResidualClass::Type);
652        assert_eq!(
653            classify_rust_code("E0382"),
654            ResidualClass::OwnershipViolation
655        );
656        assert_eq!(
657            classify_rust_code("E0603"),
658            ResidualClass::InterfaceMismatch
659        );
660        assert_eq!(classify_rust_code("E0425"), ResidualClass::SymbolMismatch);
661    }
662
663    #[test]
664    fn rust_test_failure_parsed() {
665        let adapter = RustAdapter;
666        let raw = "test tests::it_works ... FAILED";
667        let residuals = adapter.parse_diagnostics("n1", 0, raw);
668        assert_eq!(residuals[0].class, ResidualClass::TestFailure);
669        assert_eq!(residuals[0].sensor.route, IndependenceRoute::TestOracle);
670    }
671
672    #[test]
673    fn python_import_and_type_classified() {
674        let adapter = PythonAdapter;
675        let raw = "x.py:1: error: Import \"requests\" could not be resolved\nx.py:2: error: Argument 1 has \
676            incompatible type \"str\"";
677        let residuals = adapter.parse_diagnostics("n1", 0, raw);
678        assert_eq!(residuals.len(), 2);
679        assert_eq!(residuals[0].class, ResidualClass::ImportGraph);
680        assert_eq!(residuals[1].class, ResidualClass::Type);
681    }
682
683    #[test]
684    fn typescript_codes_classified_and_directed() {
685        let adapter = TypeScriptAdapter;
686        let raw = "src/a.ts(3,10): error TS2307: Cannot find module 'foo'.\nsrc/b.ts(4,2): error TS2322: \
687            Type 'string' is not assignable to type 'number'.";
688        let residuals = adapter.parse_diagnostics("n1", 0, raw);
689        assert_eq!(residuals.len(), 2);
690        assert_eq!(residuals[0].class, ResidualClass::ImportGraph);
691        assert_eq!(residuals[1].class, ResidualClass::Type);
692        assert!(adapter.correction_for(&residuals[0]).is_some());
693    }
694
695    #[test]
696    fn rust_smoke_discovers_workspace_binaries_and_examples() {
697        let dir = std::env::temp_dir().join(format!(
698            "perspt-smoke-rust-{}",
699            std::time::SystemTime::now()
700                .duration_since(std::time::UNIX_EPOCH)
701                .unwrap()
702                .as_nanos()
703        ));
704        std::fs::create_dir_all(dir.join("crates/cli/src")).unwrap();
705        std::fs::create_dir_all(dir.join("crates/cli/examples")).unwrap();
706        std::fs::write(
707            dir.join("crates/cli/Cargo.toml"),
708            "[package]\nname = \"weather-cli\"\n",
709        )
710        .unwrap();
711        std::fs::write(dir.join("crates/cli/src/main.rs"), "fn main() {}\n").unwrap();
712        std::fs::write(dir.join("crates/cli/examples/demo.rs"), "fn main() {}\n").unwrap();
713
714        let inv = RustAdapter.smoke_invocations(&dir);
715        assert!(
716            inv.iter()
717                .any(|i| i.command == "cargo run -q -p weather-cli -- --help"),
718            "got {inv:?}"
719        );
720        assert!(
721            inv.iter().any(|i| i.command.contains("--example demo")),
722            "got {inv:?}"
723        );
724        std::fs::remove_dir_all(&dir).ok();
725    }
726
727    #[test]
728    fn python_smoke_discovers_src_layout_package() {
729        let dir = std::env::temp_dir().join(format!(
730            "perspt-smoke-py-{}",
731            std::time::SystemTime::now()
732                .duration_since(std::time::UNIX_EPOCH)
733                .unwrap()
734                .as_nanos()
735        ));
736        std::fs::create_dir_all(dir.join("src/rpncalc")).unwrap();
737        std::fs::write(dir.join("src/rpncalc/__init__.py"), "").unwrap();
738
739        let inv = PythonAdapter.smoke_invocations(&dir);
740        assert!(
741            inv.iter().any(|i| i.command.contains("import rpncalc")),
742            "got {inv:?}"
743        );
744        std::fs::remove_dir_all(&dir).ok();
745    }
746
747    #[test]
748    fn adapter_for_dispatches_by_language() {
749        assert_eq!(RustAdapter.id(), LanguageId::new("rust"));
750        assert_eq!(PythonAdapter.id(), LanguageId::new("python"));
751        assert_eq!(TypeScriptAdapter.id(), LanguageId::new("typescript"));
752    }
753}