Skip to main content

perspt_agent/
measure.rs

1//! Plugin-backed candidate measurement: the full verifier suite at gate
2//! boundaries and the cheap syntax-only pass at mutation boundaries.
3//! Extracted from `candidate.rs` so the reversible overlay and the
4//! measurement plane each stay within the file-size rules.
5
6use std::collections::{BTreeMap, BTreeSet};
7use std::path::Path;
8use std::sync::Arc;
9
10use anyhow::{Context, Result};
11use perspt_coding::{CodingAdapterRegistry, CodingDomain, LanguageId};
12use perspt_sdk::{
13    AgentDomainPackage, CorrectionDirection, DomainScope, IndependenceRoute, ResidualClass,
14    ResidualEvent, ResidualSeverity, SensorRef, score_candidate,
15};
16
17use crate::candidate::{CandidateWorkspace, TestEvidenceWorkspace};
18use crate::toolloop::{CandidateMeasurer, Measured};
19use crate::verifier::{VerifierExecution, VerifierJob, run_governed_verifier};
20
21/// Every verifier process of one candidate shares this target-dir suffix:
22/// gate stages, interactive `run_*` tools, and the incremental syntax pass
23/// warm one another instead of each paying a cold build.
24pub(crate) const SHARED_TARGET_SUFFIX: &str = "shared";
25
26#[derive(Default)]
27struct AdditionalTestEvidence<'a> {
28    regression_root: Option<&'a Path>,
29    external_oracle: Option<(&'a Path, &'a str)>,
30}
31
32#[derive(Default)]
33struct PreparedTestEvidence {
34    regression: Option<TestEvidenceWorkspace>,
35    external: Option<(TestEvidenceWorkspace, String)>,
36}
37
38impl PreparedTestEvidence {
39    fn borrowed(&self) -> AdditionalTestEvidence<'_> {
40        AdditionalTestEvidence {
41            regression_root: self.regression.as_ref().map(|view| view.root.as_path()),
42            external_oracle: self
43                .external
44                .as_ref()
45                .map(|(view, command)| (view.root.as_path(), command.as_str())),
46        }
47    }
48}
49
50/// Execution order within one shared target dir: the cheap check warms the
51/// metadata, the build warms the full artifacts, tests/lints reuse them.
52fn stage_rank(stage: perspt_core::plugin::VerifierStage) -> u8 {
53    use perspt_core::plugin::VerifierStage;
54    match stage {
55        VerifierStage::SyntaxCheck => 0,
56        VerifierStage::Build => 1,
57        VerifierStage::Test => 2,
58        VerifierStage::Lint => 3,
59        VerifierStage::Format => 4,
60    }
61}
62
63/// Complete plugin-backed candidate measurement for one coding node.
64pub struct CodingCandidateMeasurer<'a> {
65    candidate: &'a CandidateWorkspace,
66    node_id: String,
67    generation: u32,
68    domain: Arc<dyn AgentDomainPackage>,
69    adapters: CodingAdapterRegistry,
70    max_parallel: usize,
71    require_format: bool,
72    test_policy: perspt_core::TestPolicy,
73    external_oracle: Option<perspt_core::ExternalOracleConfig>,
74    correction_packets: bool,
75}
76
77impl<'a> CodingCandidateMeasurer<'a> {
78    pub fn new(candidate: &'a CandidateWorkspace, node_id: &str, generation: u32) -> Self {
79        Self {
80            candidate,
81            node_id: node_id.into(),
82            generation,
83            domain: Arc::new(CodingDomain::new()),
84            adapters: CodingAdapterRegistry::with_builtins(),
85            max_parallel: 4,
86            require_format: false,
87            test_policy: perspt_core::TestPolicy::Evolving,
88            external_oracle: None,
89            correction_packets: true,
90        }
91    }
92
93    /// Evaluation ablation: disable typed correction packets (legacy
94    /// first-direction text only).
95    pub fn with_correction_packets(mut self, enabled: bool) -> Self {
96        self.correction_packets = enabled;
97        self
98    }
99
100    /// Enable the declared `format` acceptance stage
101    /// (`[verification] require_format`).
102    pub fn with_require_format(mut self, require_format: bool) -> Self {
103        self.require_format = require_format;
104        self
105    }
106
107    /// Select how test evidence participates in the hard gate. The default is
108    /// `Evolving`: project tests and their configuration may change together
109    /// with the implementation. Stronger policies are explicit.
110    pub fn with_test_policy(
111        mut self,
112        policy: perspt_core::TestPolicy,
113        external_oracle: Option<perspt_core::ExternalOracleConfig>,
114    ) -> Self {
115        self.test_policy = policy;
116        self.external_oracle = external_oracle;
117        self
118    }
119
120    pub fn with_max_parallel(mut self, max_parallel: usize) -> Self {
121        self.max_parallel = max_parallel.max(1);
122        self
123    }
124
125    /// Measure under the selected domain's energy model instead of the
126    /// default coding domain.
127    pub fn with_domain(mut self, domain: Arc<dyn AgentDomainPackage>) -> Self {
128        self.domain = domain;
129        self
130    }
131
132    fn adapter_for(plugin_name: &str) -> LanguageId {
133        match plugin_name.to_ascii_lowercase().as_str() {
134            "js" | "javascript" | "typescript" => LanguageId::new("typescript"),
135            other => LanguageId::new(other),
136        }
137    }
138
139    /// Enumerate every declared verifier capability as a runnable job; a
140    /// capability with no effective command is a blocking sensor residual.
141    /// A declared no-op stage *satisfies* its required-stage obligation —
142    /// the plugin states there is nothing to run, which is a covered
143    /// sensor, not a missing one (Python's build stage would otherwise
144    /// make hard pass unreachable and loop the model forever).
145    fn collect_jobs(
146        &self,
147        test_evidence: AdditionalTestEvidence<'_>,
148        residuals: &mut Vec<ResidualEvent>,
149        advisory: &mut Vec<ResidualEvent>,
150        satisfied_stages: &mut BTreeSet<String>,
151        all_passed: &mut bool,
152        required: &BTreeSet<String>,
153    ) -> Result<Vec<VerifierJob>> {
154        let registry = perspt_core::PluginRegistry::new();
155        let mut jobs = Vec::new();
156        let plugins = registry.detect_all(self.candidate.overlay_root());
157        *all_passed = !plugins.is_empty();
158        for plugin in plugins {
159            let adapter_id = Self::adapter_for(plugin.name());
160            for capability in plugin.verifier_profile().capabilities {
161                // Formatting gates acceptance only when the run declares it
162                // (`[verification] require_format`); otherwise the formatter
163                // stays a governed tool, never a silent gate change.
164                if capability.stage == perspt_core::plugin::VerifierStage::Format
165                    && !self.require_format
166                {
167                    continue;
168                }
169                let Some(command) = capability.effective_command() else {
170                    // A stage the plugin declares as a no-op — no primary or
171                    // fallback command form at all, marked available — has
172                    // nothing to run and is not a missing sensor (e.g.
173                    // Python's build stage). Only a stage that *has* a
174                    // command form with no runnable binary blocks hard pass.
175                    if capability.available
176                        && capability.command.is_none()
177                        && capability.fallback_command.is_none()
178                    {
179                        satisfied_stages.insert(capability.stage.policy_name().to_string());
180                        continue;
181                    }
182                    fold_infra_failure(
183                        &self.node_id,
184                        self.generation,
185                        capability.stage,
186                        &format!("{}:{}", plugin.name(), capability.stage),
187                        residuals,
188                        advisory,
189                        all_passed,
190                        required,
191                    )?;
192                    continue;
193                };
194                jobs.push(VerifierJob {
195                    plugin: plugin.name().to_string(),
196                    adapter_id: adapter_id.clone(),
197                    stage: capability.stage,
198                    command: command.to_string(),
199                    root: self.candidate.overlay_root().to_path_buf(),
200                });
201            }
202            if let Some(root) = test_evidence.regression_root {
203                jobs.push(VerifierJob {
204                    plugin: format!("{}:backward-compatible-tests", plugin.name()),
205                    adapter_id,
206                    stage: perspt_core::plugin::VerifierStage::Test,
207                    command: plugin.test_command(),
208                    root: root.to_path_buf(),
209                });
210            }
211        }
212        if let Some((root, command)) = test_evidence.external_oracle {
213            jobs.push(VerifierJob {
214                plugin: "external-oracle".into(),
215                adapter_id: LanguageId::new("external-oracle"),
216                stage: perspt_core::plugin::VerifierStage::Test,
217                command: command.to_string(),
218                root: root.to_path_buf(),
219            });
220        }
221        Ok(jobs)
222    }
223
224    /// Fold one verifier run. A residual from a stage the domain's
225    /// `HardGatePolicy` does not require (e.g. lint) lands in `advisory` —
226    /// still scored, still steering corrections, never blocking the gate —
227    /// so a pre-existing repository warning cannot make hard pass
228    /// unreachable. Required-stage residuals stay blocking.
229    fn fold_execution(
230        &self,
231        job: &VerifierJob,
232        execution: VerifierExecution,
233        residuals: &mut Vec<ResidualEvent>,
234        advisory: &mut Vec<ResidualEvent>,
235        all_passed: &mut bool,
236        required: &BTreeSet<String>,
237    ) -> Result<()> {
238        let blocking = required.contains(job.stage.policy_name());
239        let sink: &mut Vec<ResidualEvent> = if blocking { residuals } else { advisory };
240        let mut output = execution.output.clone();
241        // A stage that declared a JUnit report file (pytest `--junitxml`)
242        // produced structured evidence on disk: fold it into the raw sensor
243        // text so the structured parser sees it, then drop the file.
244        if let Some(report) = junit_report_path(&job.command) {
245            let path = job.root.join(report);
246            if let Ok(xml) = std::fs::read_to_string(&path) {
247                output.push('\n');
248                output.push_str(&xml);
249                let _ = std::fs::remove_file(&path);
250            }
251        }
252        let execution = VerifierExecution {
253            output,
254            ..execution
255        };
256        if let Some(adapter) = self.adapters.get(&job.adapter_id) {
257            sink.extend(adapter.parse_diagnostics(
258                &self.node_id,
259                self.generation,
260                &execution.output,
261            ));
262        }
263        if !execution.success {
264            if blocking {
265                *all_passed = false;
266            }
267            let class = match job.stage {
268                perspt_core::plugin::VerifierStage::Test => ResidualClass::TestFailure,
269                perspt_core::plugin::VerifierStage::Lint => ResidualClass::Lint,
270                perspt_core::plugin::VerifierStage::Format => ResidualClass::Format,
271                _ => ResidualClass::Build,
272            };
273            if !sink.iter().any(|r| r.class == class) {
274                sink.push(tool_residual(
275                    &self.node_id,
276                    self.generation,
277                    class,
278                    &format!("{} failed: {}", job.stage, concise(&execution.output)),
279                )?);
280            }
281        }
282        Ok(())
283    }
284
285    /// One task per `(root, plugin)` group, its stages run **sequentially**
286    /// in stage order against one shared `CARGO_TARGET_DIR` (suffix
287    /// `shared`, the same warm pool the interactive tools and incremental
288    /// syntax pass use), so a gate pays one cold build plus incrementals
289    /// instead of a cold tree per stage. Groups still run in parallel under
290    /// the `max_parallel` semaphore; any additional regression or protected
291    /// acceptance root is its own group and stays isolated from candidate
292    /// build artifacts.
293    fn spawn_verifier_groups(
294        &self,
295        jobs: Vec<VerifierJob>,
296    ) -> tokio::task::JoinSet<Vec<(VerifierJob, Result<VerifierExecution>)>> {
297        let mut groups: std::collections::BTreeMap<(std::path::PathBuf, String), Vec<VerifierJob>> =
298            std::collections::BTreeMap::new();
299        for job in jobs {
300            groups
301                .entry((job.root.clone(), job.plugin.clone()))
302                .or_default()
303                .push(job);
304        }
305        let semaphore = Arc::new(tokio::sync::Semaphore::new(self.max_parallel));
306        let mut workers = tokio::task::JoinSet::new();
307        for (_, mut group) in groups {
308            group.sort_by_key(|job| stage_rank(job.stage));
309            let semaphore = semaphore.clone();
310            let allow_unisolated = self.candidate.unisolated_verifiers_allowed();
311            let extra_env = self.candidate.verifier_env();
312            let timeouts = self.candidate.verifier_timeouts();
313            workers.spawn(async move {
314                let _permit = semaphore.acquire_owned().await.expect("semaphore closed");
315                let mut results = Vec::with_capacity(group.len());
316                for job in group {
317                    let execution = run_governed_verifier(
318                        job.root.clone(),
319                        job.command.clone(),
320                        allow_unisolated,
321                        SHARED_TARGET_SUFFIX.into(),
322                        extra_env.clone(),
323                        timeouts.for_stage(Some(job.stage)),
324                    )
325                    .await;
326                    results.push((job, execution));
327                }
328                results
329            });
330        }
331        workers
332    }
333
334    /// The stages whose residuals block hard pass: the domain's
335    /// `HardGatePolicy`, plus `format` when the run declares it
336    /// (`[verification] require_format`).
337    fn required_stages(&self) -> BTreeSet<String> {
338        let scope = DomainScope {
339            label: self.node_id.clone(),
340            paths: Vec::new(),
341        };
342        let mut required: BTreeSet<String> = self
343            .domain
344            .hard_gate_policy(&scope)
345            .required_stages
346            .into_iter()
347            .collect();
348        if self.require_format {
349            required.insert("format".into());
350        }
351        required
352    }
353
354    fn prepare_test_evidence(&self) -> Result<PreparedTestEvidence> {
355        anyhow::ensure!(
356            self.test_policy == perspt_core::TestPolicy::ExternalOracle
357                || self.external_oracle.is_none(),
358            "protected external test configuration requires the external-oracle test policy"
359        );
360        let regression = match self.test_policy {
361            perspt_core::TestPolicy::BackwardCompatible => {
362                self.candidate.backward_compatibility_tests()?
363            }
364            _ => None,
365        };
366        let external = match self.test_policy {
367            perspt_core::TestPolicy::ExternalOracle => {
368                let configured = self
369                    .external_oracle
370                    .as_ref()
371                    .context("external-oracle test policy has no protected oracle configuration")?;
372                Some((
373                    self.candidate.external_oracle_tests(&configured.path)?,
374                    configured.command.clone(),
375                ))
376            }
377            _ => None,
378        };
379        Ok(PreparedTestEvidence {
380            regression,
381            external,
382        })
383    }
384
385    /// Gate X / PSP-10 Phase 1: `HardGatePolicy::required_stages` is
386    /// authoritative. A declared stage that no plugin ran is a missing
387    /// sensor: it records `SensorUnavailable` and forces `hard_pass = false`.
388    /// The check only adds a necessary condition; it can never loosen the
389    /// plugin-derived verdict.
390    fn enforce_required_stages(
391        &self,
392        ran_stages: &BTreeSet<String>,
393        residuals: &mut Vec<ResidualEvent>,
394        all_passed: &mut bool,
395    ) -> Result<()> {
396        let scope = DomainScope {
397            label: self.node_id.clone(),
398            paths: Vec::new(),
399        };
400        for stage in self.domain.hard_gate_policy(&scope).required_stages {
401            if !ran_stages.contains(stage.as_str()) {
402                residuals.push(sensor_unavailable(
403                    &self.node_id,
404                    self.generation,
405                    &format!("required-stage:{stage}"),
406                )?);
407                *all_passed = false;
408            }
409        }
410        Ok(())
411    }
412
413    fn apply_domain_evaluation(
414        &self,
415        ran_stages: &mut BTreeSet<String>,
416        residuals: &mut Vec<ResidualEvent>,
417        advisory: &mut Vec<ResidualEvent>,
418        all_passed: &mut bool,
419        no_coding_jobs: bool,
420    ) -> bool {
421        let snapshot = snapshot_overlay_text_files(self.candidate.overlay_root());
422        let Some(eval) = self
423            .domain
424            .evaluate_workspace(&snapshot, &self.node_id, self.generation)
425        else {
426            return false;
427        };
428        let domain_ran = !eval.ran_stages.is_empty();
429        ran_stages.extend(eval.ran_stages);
430        let has_blocking = !eval.residuals.is_empty();
431        residuals.extend(eval.residuals);
432        advisory.extend(eval.advisory);
433        if has_blocking {
434            *all_passed = false;
435        } else if no_coding_jobs && domain_ran {
436            *all_passed = true;
437        }
438        domain_ran
439    }
440
441    #[allow(clippy::type_complexity)]
442    fn score(
443        &self,
444        residuals: &[ResidualEvent],
445    ) -> Result<(
446        f64,
447        Option<CorrectionDirection>,
448        Option<perspt_sdk::CorrectionPacket>,
449    )> {
450        let scope = DomainScope {
451            label: self.node_id.clone(),
452            paths: Vec::new(),
453        };
454        let score = score_candidate(&self.domain.energy_model(&scope), residuals)
455            .map_err(|e| anyhow::anyhow!(e.to_string()))?;
456        // PSP-10 system 26: the typed packet folds every direction with
457        // full paths/symbols/rationale; its rendering through the
458        // `branch_correct` section program becomes the steering message.
459        // Domains without packets keep the legacy first-direction path.
460        let packet = self
461            .correction_packets
462            .then(|| self.domain.correction_packet(residuals))
463            .flatten();
464        let correction = match &packet {
465            Some(packet) if !packet.is_empty() => {
466                let rendered = perspt_coding::prompts::render_correction(packet)
467                    .map_err(|e| anyhow::anyhow!("rendering correction packet: {e}"))?;
468                Some(
469                    CorrectionDirection::new(packet.dominant_cluster.class, rendered)
470                        .with_paths(packet.affected.paths.clone()),
471                )
472            }
473            _ => self
474                .domain
475                .correction_directions(residuals)
476                .into_iter()
477                .next(),
478        };
479        Ok((score.total, correction, packet))
480    }
481}
482
483#[async_trait::async_trait]
484impl CandidateMeasurer for CodingCandidateMeasurer<'_> {
485    async fn measure(&self) -> Result<Measured> {
486        let mut residuals = Vec::new();
487        let mut advisory = Vec::new();
488        let required = self.required_stages();
489        let mut all_passed = false;
490        let mut ran_stages: BTreeSet<String> = BTreeSet::new();
491        let test_evidence = self.prepare_test_evidence()?;
492        let jobs = self.collect_jobs(
493            test_evidence.borrowed(),
494            &mut residuals,
495            &mut advisory,
496            &mut ran_stages,
497            &mut all_passed,
498            &required,
499        )?;
500
501        let ran = jobs.len();
502        ran_stages.extend(jobs.iter().map(|job| job.stage.policy_name().to_string()));
503        let domain_ran = self.apply_domain_evaluation(
504            &mut ran_stages,
505            &mut residuals,
506            &mut advisory,
507            &mut all_passed,
508            ran == 0,
509        );
510        self.enforce_required_stages(&ran_stages, &mut residuals, &mut all_passed)?;
511        let mut workers = self.spawn_verifier_groups(jobs);
512
513        while let Some(result) = workers.join_next().await {
514            for (job, execution) in result.context("verifier worker panicked")? {
515                match execution {
516                    Ok(execution) => self.fold_execution(
517                        &job,
518                        execution,
519                        &mut residuals,
520                        &mut advisory,
521                        &mut all_passed,
522                        &required,
523                    )?,
524                    Err(error) => fold_infra_failure(
525                        &self.node_id,
526                        self.generation,
527                        job.stage,
528                        &format!("{}:{} ({error})", job.plugin, job.stage),
529                        &mut residuals,
530                        &mut advisory,
531                        &mut all_passed,
532                        &required,
533                    )?,
534                }
535            }
536        }
537
538        if ran == 0 && !domain_ran {
539            all_passed = false;
540        }
541        // Only required-stage residuals gate; advisory ones (lint outside
542        // the hard-gate policy) still enter the energy and corrections.
543        let hard_pass = self.candidate.has_mutated() && all_passed && residuals.is_empty();
544        residuals.extend(advisory);
545        let (energy, correction, packet) = self.score(&residuals)?;
546        Ok(Measured {
547            hard_pass,
548            energy,
549            residuals,
550            correction,
551            packet,
552        })
553    }
554
555    /// Per-mutation boundary: a syntax-only pass. The complete suite — every
556    /// build and test, each with its own timeout — belongs to the gate
557    /// boundary (`measure`); running it after every single admitted mutation
558    /// multiplies a turn's cost by its edit count for no additional gate
559    /// evidence. `hard_pass` is never claimed from this cheap pass.
560    async fn measure_incremental(&self) -> Result<Measured> {
561        let registry = perspt_core::PluginRegistry::new();
562        let plugins = registry.detect_all(self.candidate.overlay_root());
563        let mut residuals = Vec::new();
564        if plugins.is_empty() {
565            let snapshot = snapshot_overlay_text_files(self.candidate.overlay_root());
566            if let Some(eval) =
567                self.domain
568                    .evaluate_workspace(&snapshot, &self.node_id, self.generation)
569            {
570                residuals.extend(eval.residuals);
571            }
572        }
573        for plugin in plugins {
574            let Some(command) = plugin.syntax_check_command() else {
575                continue;
576            };
577            let adapter_id = Self::adapter_for(plugin.name());
578            let execution = run_governed_verifier(
579                self.candidate.overlay_root().to_path_buf(),
580                command,
581                self.candidate.unisolated_verifiers_allowed(),
582                SHARED_TARGET_SUFFIX.into(),
583                self.candidate.verifier_env(),
584                self.candidate
585                    .verifier_timeouts()
586                    .for_stage(Some(perspt_core::plugin::VerifierStage::SyntaxCheck)),
587            )
588            .await?;
589            if let Some(adapter) = self.adapters.get(&adapter_id) {
590                residuals.extend(adapter.parse_diagnostics(
591                    &self.node_id,
592                    self.generation,
593                    &execution.output,
594                ));
595            }
596            if !execution.success && !residuals.iter().any(|r| r.class == ResidualClass::Build) {
597                residuals.push(tool_residual(
598                    &self.node_id,
599                    self.generation,
600                    ResidualClass::Build,
601                    &format!("syntax check failed: {}", concise(&execution.output)),
602                )?);
603            }
604        }
605        let (energy, correction, packet) = self.score(&residuals)?;
606        Ok(Measured {
607            hard_pass: false,
608            energy,
609            residuals,
610            correction,
611            packet,
612        })
613    }
614}
615
616fn tool_residual(
617    node: &str,
618    generation: u32,
619    class: ResidualClass,
620    summary: &str,
621) -> Result<ResidualEvent> {
622    let mut residual = ResidualEvent::new(
623        node,
624        generation,
625        class,
626        ResidualSeverity::Error,
627        1.0,
628        SensorRef::new("governed-verifier", IndependenceRoute::DeterministicTool),
629    )
630    .map_err(|e| anyhow::anyhow!(e.to_string()))?;
631    residual.evidence.summary = summary.into();
632    Ok(residual)
633}
634
635/// The report path a verifier command declared via `--junitxml <path>` or
636/// `--junitxml=<path>`.
637fn junit_report_path(command: &str) -> Option<String> {
638    let mut words = command.split_whitespace().peekable();
639    while let Some(word) = words.next() {
640        if word == "--junitxml" {
641            return words.peek().map(|path| (*path).to_string());
642        }
643        if let Some(path) = word.strip_prefix("--junitxml=") {
644            return Some(path.to_string());
645        }
646    }
647    None
648}
649
650/// Route one verifier *infrastructure* failure (unavailable capability,
651/// launch error, timeout) by stage: it blocks hard pass only when the
652/// stage is in the domain's required set — a lint timeout or a missing
653/// lint binary is as advisory as a lint finding (erratum 11: non-required
654/// stages cannot block acceptance), while a build or test failure to run
655/// still blocks.
656#[allow(clippy::too_many_arguments)]
657fn fold_infra_failure(
658    node_id: &str,
659    generation: u32,
660    stage: perspt_core::plugin::VerifierStage,
661    detail: &str,
662    residuals: &mut Vec<ResidualEvent>,
663    advisory: &mut Vec<ResidualEvent>,
664    all_passed: &mut bool,
665    required: &BTreeSet<String>,
666) -> Result<()> {
667    let blocking = required.contains(stage.policy_name());
668    let sink = if blocking { residuals } else { advisory };
669    sink.push(sensor_unavailable(node_id, generation, detail)?);
670    if blocking {
671        *all_passed = false;
672    }
673    Ok(())
674}
675
676fn sensor_unavailable(node: &str, generation: u32, sensor: &str) -> Result<ResidualEvent> {
677    tool_residual(
678        node,
679        generation,
680        ResidualClass::SensorUnavailable,
681        &format!("required sensor unavailable: {sensor}"),
682    )
683}
684
685fn concise(output: &str) -> String {
686    output
687        .lines()
688        .filter(|line| !line.trim().is_empty())
689        .take(8)
690        .collect::<Vec<_>>()
691        .join("\n")
692}
693
694/// Snapshot bounded UTF-8 text files inside a candidate overlay for
695/// domain-native workspace verification.
696pub(crate) fn snapshot_overlay_text_files(root: &Path) -> perspt_sdk::WorkspaceSnapshot {
697    let mut files = Vec::new();
698    let mut contents = BTreeMap::new();
699    let mut total_bytes = 0usize;
700    collect_overlay_files(root, root, &mut files, &mut contents, &mut total_bytes);
701    files.sort();
702    perspt_sdk::WorkspaceSnapshot::new(root.display().to_string(), files).with_contents(contents)
703}
704
705fn collect_overlay_files(
706    base: &Path,
707    dir: &Path,
708    files: &mut Vec<String>,
709    contents: &mut BTreeMap<String, String>,
710    total_bytes: &mut usize,
711) {
712    const MAX_FILE_BYTES: usize = 256 * 1024;
713    const MAX_TOTAL_BYTES: usize = 4 * 1024 * 1024;
714
715    let Ok(entries) = std::fs::read_dir(dir) else {
716        return;
717    };
718    for entry in entries.flatten() {
719        let Ok(file_type) = entry.file_type() else {
720            continue;
721        };
722        if file_type.is_symlink() {
723            continue;
724        }
725        let name = entry.file_name().to_string_lossy().into_owned();
726        if file_type.is_dir() {
727            if matches!(name.as_str(), ".git" | "target" | "node_modules")
728                || name.starts_with(".perspt")
729            {
730                continue;
731            }
732            collect_overlay_files(base, &entry.path(), files, contents, total_bytes);
733        } else if file_type.is_file() {
734            let path = entry.path();
735            let Ok(rel) = path.strip_prefix(base) else {
736                continue;
737            };
738            let rel_str = rel.to_string_lossy().replace('\\', "/");
739            files.push(rel_str.clone());
740            let len = entry
741                .metadata()
742                .map(|m| m.len() as usize)
743                .unwrap_or(usize::MAX);
744            if len <= MAX_FILE_BYTES
745                && *total_bytes + len <= MAX_TOTAL_BYTES
746                && let Ok(text) = std::fs::read_to_string(&path)
747            {
748                *total_bytes += text.len();
749                contents.insert(rel_str, text);
750            }
751        }
752    }
753}
754
755#[cfg(test)]
756mod tests {
757    use super::*;
758
759    fn required() -> BTreeSet<String> {
760        ["syntax", "build", "test"]
761            .into_iter()
762            .map(String::from)
763            .collect()
764    }
765
766    /// Erratum 11 covers infrastructure too: a lint-stage timeout or
767    /// missing lint binary lands in the advisory sink and leaves
768    /// `all_passed` alone, while the same failure on a required stage
769    /// still blocks.
770    #[test]
771    fn infra_failures_block_only_on_required_stages() {
772        use perspt_core::plugin::VerifierStage;
773        let mut residuals = Vec::new();
774        let mut advisory = Vec::new();
775        let mut all_passed = true;
776        fold_infra_failure(
777            "n1",
778            0,
779            VerifierStage::Lint,
780            "rust:lint (deadline elapsed)",
781            &mut residuals,
782            &mut advisory,
783            &mut all_passed,
784            &required(),
785        )
786        .unwrap();
787        assert!(all_passed, "a lint infra failure must not clear all_passed");
788        assert!(residuals.is_empty(), "nothing enters the blocking sink");
789        assert_eq!(advisory.len(), 1, "the failure is still reported");
790        assert_eq!(advisory[0].class, ResidualClass::SensorUnavailable);
791
792        fold_infra_failure(
793            "n1",
794            0,
795            VerifierStage::Test,
796            "rust:test (deadline elapsed)",
797            &mut residuals,
798            &mut advisory,
799            &mut all_passed,
800            &required(),
801        )
802        .unwrap();
803        assert!(!all_passed, "a required-stage infra failure still blocks");
804        assert_eq!(residuals.len(), 1);
805    }
806}