Skip to main content

perspt_sdk/
domain.rs

1//! Domain-package contract (PSP-8 System 1 / System 5).
2//!
3//! The SDK owns the domain-neutral control plane; a domain package provides
4//! task-specific semantics. This module defines the Phase-0/1 surface of the
5//! [`AgentDomainPackage`] trait — the part exercised by the energy/gate core and
6//! implemented by `perspt-coding` as the first consumer. Later phases extend the
7//! trait with exploration plans, verifier suites, hard gates, context packages,
8//! capability policies, and graph hints; those types are intentionally omitted
9//! here until their owning phases land, so every contract ships with a real
10//! consumer rather than ahead of one.
11
12use serde::{Deserialize, Serialize};
13
14use crate::energy::EnergyModel;
15use crate::residual::{CorrectionDirection, ResidualClass, ResidualEvent};
16
17/// Stable identifier for a domain (e.g. `"coding"`, `"research"`).
18#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
19pub struct DomainId(pub String);
20
21impl DomainId {
22    pub fn new(id: impl Into<String>) -> Self {
23        Self(id.into())
24    }
25}
26
27impl std::fmt::Display for DomainId {
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        f.write_str(&self.0)
30    }
31}
32
33/// A minimal read-only snapshot of the workspace used for domain detection and
34/// domain-native workspace verification.
35#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
36pub struct WorkspaceSnapshot {
37    pub root: String,
38    /// Workspace-relative paths discovered by a read-only scan.
39    pub files: Vec<String>,
40    /// Optional UTF-8 file contents keyed by workspace-relative path.
41    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
42    pub contents: std::collections::BTreeMap<String, String>,
43}
44
45impl WorkspaceSnapshot {
46    pub fn new(root: impl Into<String>, files: Vec<String>) -> Self {
47        Self {
48            root: root.into(),
49            files,
50            contents: std::collections::BTreeMap::new(),
51        }
52    }
53
54    /// Attach in-memory UTF-8 file contents keyed by workspace-relative path.
55    pub fn with_contents(mut self, contents: std::collections::BTreeMap<String, String>) -> Self {
56        self.contents = contents;
57        self
58    }
59
60    /// Read a workspace-relative UTF-8 text file from cached snapshot contents,
61    /// falling back to `root/rel_path` when present.
62    pub fn read_text(&self, rel_path: &str) -> Option<String> {
63        if let Some(text) = self.contents.get(rel_path) {
64            return Some(text.clone());
65        }
66        let rel = std::path::Path::new(rel_path);
67        if self.root.is_empty()
68            || rel.is_absolute()
69            || rel
70                .components()
71                .any(|c| matches!(c, std::path::Component::ParentDir))
72        {
73            return None;
74        }
75        std::fs::read_to_string(std::path::Path::new(&self.root).join(rel)).ok()
76    }
77
78    /// Whether any discovered file ends with the given suffix.
79    pub fn has_file_named(&self, name: &str) -> bool {
80        self.files
81            .iter()
82            .any(|f| f == name || f.ends_with(&format!("/{name}")))
83    }
84}
85
86/// Output of [`AgentDomainPackage::evaluate_workspace`] for domains that run
87/// checks outside coding language plugins.
88#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
89pub struct DomainEvaluation {
90    pub ran_stages: Vec<String>,
91    pub residuals: Vec<ResidualEvent>,
92    pub advisory: Vec<ResidualEvent>,
93}
94
95/// Evidence that a domain package activates for a workspace.
96#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
97pub struct DomainDetection {
98    pub domain: DomainId,
99    pub activated: bool,
100    /// Confidence in `[0, 1]`.
101    pub confidence: f64,
102    pub evidence: Vec<String>,
103}
104
105/// The scope a domain operates over (e.g. a node, a package, a subtree).
106#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
107pub struct DomainScope {
108    pub label: String,
109    pub paths: Vec<String>,
110}
111
112/// The residual schema a domain declares: the classes it can emit and the
113/// allowed sensors per class. Normalization, weights, and rollup mapping live in
114/// the [`EnergyModel`].
115#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
116pub struct ResidualSchema {
117    pub classes: Vec<ResidualClass>,
118}
119
120impl ResidualSchema {
121    pub fn new(classes: Vec<ResidualClass>) -> Self {
122        Self { classes }
123    }
124
125    pub fn allows(&self, class: ResidualClass) -> bool {
126        self.classes.contains(&class)
127    }
128}
129
130/// A bounded adaptive verification cadence (PSP-9 system 6).
131///
132/// Three boundaries are normative: the effect boundary runs at every
133/// mutation and is never debounced; the interleaved evidence boundary runs
134/// after at most `max_mutations_between_checks` admitted mutations (`H`);
135/// the gate boundary runs the complete suite before every gate decision.
136/// Runtime tuning may optimize *within* these bounds; it can never create an
137/// unbounded unchecked interval (Paper II Theorem 3).
138#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
139pub struct VerificationCadence {
140    /// `H`: admitted mutations before touched-scope diagnostics must run.
141    pub max_mutations_between_checks: u32,
142    /// `H` for high/critical-risk effects; the PSP fixes this at 1.
143    pub high_risk_mutations_between_checks: u32,
144}
145
146impl VerificationCadence {
147    /// Validate the bounds: both must be at least 1 and finite by type.
148    pub fn validate(&self) -> Result<(), crate::error::SdkError> {
149        if self.max_mutations_between_checks == 0 || self.high_risk_mutations_between_checks == 0 {
150            return Err(crate::error::SdkError::Domain(
151                "verification cadence bounds must be at least 1".into(),
152            ));
153        }
154        Ok(())
155    }
156}
157
158impl Default for VerificationCadence {
159    fn default() -> Self {
160        Self {
161            max_mutations_between_checks: 4,
162            high_risk_mutations_between_checks: 1,
163        }
164    }
165}
166
167/// The hard predicates a candidate must pass for `HardPass` (PSP-9
168/// system 10). A model validator can be an *additional* necessary condition,
169/// never a sufficient one.
170#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
171pub struct HardGatePolicy {
172    /// Verifier stage names that must all pass (e.g. "build", "test").
173    pub required_stages: Vec<String>,
174}
175
176/// The verifier suite a domain declares for a scope (PSP-9 system 6).
177#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
178pub struct VerifierSuiteSpec {
179    /// Ordered stage names the runtime binds to plugin commands.
180    pub stages: Vec<String>,
181    pub cadence: VerificationCadence,
182}
183
184/// One versioned operational safety channel `h_j` (PSP-9 system 12).
185#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
186pub struct BarrierChannel {
187    pub name: String,
188    pub policy_version: String,
189}
190
191/// A registered operational safety barrier.
192#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
193pub struct BarrierSpec {
194    pub channels: Vec<BarrierChannel>,
195}
196
197/// A domain's barrier position — required even when it is `NotClaimed`, so
198/// no domain inherits a vacuous barrier default (PSP-9).
199#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
200#[serde(rename_all = "snake_case")]
201pub enum SafetyBarrierDisposition {
202    /// The domain declares no barrier; autonomous chance-safety certification
203    /// is unavailable and the reason is recorded.
204    NotClaimed { reason: String },
205    /// The domain registers versioned channels (system 12).
206    Registered(BarrierSpec),
207}
208
209/// The domain-package contract.
210///
211/// A domain package maps verifier evidence into residuals, declares the
212/// residual schema and energy model that gate acceptance, derives correction
213/// directions from dominant residuals, and — since PSP-9 — declares its
214/// governed tools, hard-gate policy, verifier suite, and barrier position.
215pub trait AgentDomainPackage: Send + Sync {
216    /// Stable domain identifier.
217    fn domain_id(&self) -> DomainId;
218
219    /// Detect whether this domain applies to a workspace.
220    fn detect(&self, workspace: &WorkspaceSnapshot) -> DomainDetection;
221
222    /// The residual classes this domain can emit for a scope.
223    fn residual_schema(&self, scope: &DomainScope) -> ResidualSchema;
224
225    /// The energy model (weights, `rho_gate`, tolerance, budget) for a scope.
226    fn energy_model(&self, scope: &DomainScope) -> EnergyModel;
227
228    /// Derive correction directions from dominant residuals. Returning an empty
229    /// vector for residuals that genuinely have no direction is honest; the
230    /// runtime then escalates rather than issuing an undirected retry.
231    fn correction_directions(&self, residuals: &[ResidualEvent]) -> Vec<CorrectionDirection>;
232
233    // --- PSP-9 agent contract. These are required so a domain cannot
234    // silently claim agent support while exposing no governed tools or
235    // hard-gate policy. ---
236
237    /// The domain's tool entries for a scope (joined with the base catalog).
238    fn tool_entries(&self, scope: &DomainScope) -> Vec<crate::toolset::ToolEntry>;
239
240    /// The hard predicates required for `HardPass`.
241    fn hard_gate_policy(&self, scope: &DomainScope) -> HardGatePolicy;
242
243    /// The verifier suite and its bounded cadence.
244    fn verifier_suite(&self, scope: &DomainScope) -> VerifierSuiteSpec;
245
246    /// The barrier position — `NotClaimed { reason }` is a legal, honest
247    /// answer; a vacuous default is not.
248    fn safety_barrier(&self, scope: &DomainScope) -> SafetyBarrierDisposition;
249
250    /// The optional analytic-path extension (Paper I §12). Coding returns
251    /// `None` until a true proxy geometry exists.
252    fn proxy_geometry(&self, _scope: &DomainScope) -> Option<&dyn crate::stability::ProxyGeometry> {
253        None
254    }
255
256    // --- PSP-10 search and prompt contract. Defaulted so existing domains
257    // compile unchanged until they opt in. ---
258
259    /// The domain's compiled prompt section library.
260    fn prompt_library(&self) -> &dyn DomainPromptLibrary {
261        &EMPTY_PROMPT_LIBRARY
262    }
263
264    /// Deliberately diverse branch strategies for a failed attempt
265    /// (PSP-10 system 20). A strategy is a search prior, never authority.
266    fn search_strategies(
267        &self,
268        _context: &crate::search::SearchContext,
269    ) -> Vec<crate::search::SearchStrategy> {
270        Vec::new()
271    }
272
273    /// Fold verifier residuals into one coherent typed correction packet
274    /// (PSP-10 system 26). `None` means the domain has no direction — the
275    /// caller expands or escalates, never blind-retries.
276    fn correction_packet(
277        &self,
278        _residuals: &[crate::residual::ResidualEvent],
279    ) -> Option<crate::residual::CorrectionPacket> {
280        None
281    }
282
283    /// Compare branch candidates against the accepted root under the
284    /// domain's measurement semantics (advisory; Proposition 5's
285    /// deterministic rule selects).
286    fn compare_branch_measurements(
287        &self,
288        _root: &crate::search::DomainMeasurement,
289        _candidates: &[crate::search::BranchMeasurement],
290    ) -> crate::search::BranchSelection {
291        crate::search::BranchSelection::NoneEligible
292    }
293
294    /// Run domain-native deterministic workspace verification when the domain
295    /// owns checks outside coding language plugins.
296    fn evaluate_workspace(
297        &self,
298        _snapshot: &WorkspaceSnapshot,
299        _node_id: &str,
300        _generation: u32,
301    ) -> Option<DomainEvaluation> {
302        None
303    }
304}
305
306/// A domain's compiled prompt sections, keyed by stage directory name.
307/// Object-safe; the empty default serves domains without a section library.
308pub trait DomainPromptLibrary: Send + Sync {
309    /// The base section templates for one stage, in declared order.
310    fn stage_templates(&self, stage: &str) -> Vec<crate::prompt::SectionTemplate> {
311        let _ = stage;
312        Vec::new()
313    }
314}
315
316/// The shared empty library behind the trait default.
317#[derive(Debug)]
318pub struct EmptyDomainPromptLibrary;
319
320impl DomainPromptLibrary for EmptyDomainPromptLibrary {}
321
322static EMPTY_PROMPT_LIBRARY: EmptyDomainPromptLibrary = EmptyDomainPromptLibrary;
323
324/// A registry of domain packages and the routing logic that selects one
325/// (PSP-8 System 1 / Phase 10). Domain selection is a routing decision; it does
326/// not bypass the SDK's residual, scheduler, capability, ledger, or dashboard
327/// contracts — every registered package implements the same trait.
328#[derive(Default)]
329pub struct DomainRegistry {
330    packages: Vec<std::sync::Arc<dyn AgentDomainPackage>>,
331}
332
333impl std::fmt::Debug for DomainRegistry {
334    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
335        f.debug_struct("DomainRegistry")
336            .field(
337                "domains",
338                &self
339                    .packages
340                    .iter()
341                    .map(|p| p.domain_id())
342                    .collect::<Vec<_>>(),
343            )
344            .finish()
345    }
346}
347
348impl DomainRegistry {
349    pub fn new() -> Self {
350        Self::default()
351    }
352
353    /// Register a domain package. The SDK admits any number of domains without
354    /// forking the control plane.
355    pub fn register(&mut self, package: std::sync::Arc<dyn AgentDomainPackage>) {
356        self.packages.push(package);
357    }
358
359    pub fn len(&self) -> usize {
360        self.packages.len()
361    }
362
363    pub fn is_empty(&self) -> bool {
364        self.packages.is_empty()
365    }
366
367    /// All registered domain ids.
368    pub fn domain_ids(&self) -> Vec<DomainId> {
369        self.packages.iter().map(|p| p.domain_id()).collect()
370    }
371
372    /// Look up a package by explicit domain id.
373    pub fn by_id(&self, id: &DomainId) -> Option<std::sync::Arc<dyn AgentDomainPackage>> {
374        self.packages.iter().find(|p| &p.domain_id() == id).cloned()
375    }
376
377    /// The activated package with the highest detection confidence.
378    pub fn detect_best(
379        &self,
380        workspace: &WorkspaceSnapshot,
381    ) -> Option<std::sync::Arc<dyn AgentDomainPackage>> {
382        self.packages
383            .iter()
384            .map(|p| (p, p.detect(workspace)))
385            .filter(|(_, d)| d.activated)
386            .max_by(|(_, a), (_, b)| {
387                a.confidence
388                    .partial_cmp(&b.confidence)
389                    .unwrap_or(std::cmp::Ordering::Equal)
390            })
391            .map(|(p, _)| p.clone())
392    }
393
394    /// Select a domain: an explicit id wins; otherwise detect the best match.
395    pub fn select(
396        &self,
397        explicit: Option<&DomainId>,
398        workspace: &WorkspaceSnapshot,
399    ) -> Option<std::sync::Arc<dyn AgentDomainPackage>> {
400        match explicit {
401            Some(id) => self.by_id(id),
402            None => self.detect_best(workspace),
403        }
404    }
405}
406
407#[cfg(test)]
408mod tests {
409    use super::*;
410    use crate::energy::EnergyModel;
411
412    struct StubDomain {
413        id: &'static str,
414        marker: &'static str,
415        confidence: f64,
416    }
417
418    impl AgentDomainPackage for StubDomain {
419        fn domain_id(&self) -> DomainId {
420            DomainId::new(self.id)
421        }
422        fn detect(&self, ws: &WorkspaceSnapshot) -> DomainDetection {
423            let activated = ws.has_file_named(self.marker);
424            DomainDetection {
425                domain: self.domain_id(),
426                activated,
427                confidence: if activated { self.confidence } else { 0.0 },
428                evidence: vec![],
429            }
430        }
431        fn residual_schema(&self, _: &DomainScope) -> ResidualSchema {
432            ResidualSchema::new(vec![])
433        }
434        fn energy_model(&self, _: &DomainScope) -> EnergyModel {
435            EnergyModel::new(self.id, 0.5)
436        }
437        fn correction_directions(&self, _: &[ResidualEvent]) -> Vec<CorrectionDirection> {
438            vec![]
439        }
440        fn tool_entries(&self, _: &DomainScope) -> Vec<crate::toolset::ToolEntry> {
441            vec![]
442        }
443        fn hard_gate_policy(&self, _: &DomainScope) -> HardGatePolicy {
444            HardGatePolicy::default()
445        }
446        fn verifier_suite(&self, _: &DomainScope) -> VerifierSuiteSpec {
447            VerifierSuiteSpec::default()
448        }
449        fn safety_barrier(&self, _: &DomainScope) -> SafetyBarrierDisposition {
450            SafetyBarrierDisposition::NotClaimed {
451                reason: "stub".into(),
452            }
453        }
454    }
455
456    fn registry() -> DomainRegistry {
457        let mut r = DomainRegistry::new();
458        r.register(std::sync::Arc::new(StubDomain {
459            id: "coding",
460            marker: "Cargo.toml",
461            confidence: 0.9,
462        }));
463        r.register(std::sync::Arc::new(StubDomain {
464            id: "research",
465            marker: "refs.bib",
466            confidence: 0.8,
467        }));
468        r
469    }
470
471    #[test]
472    fn explicit_selection_wins() {
473        let r = registry();
474        let ws = WorkspaceSnapshot::new("/r", vec!["Cargo.toml".into(), "refs.bib".into()]);
475        let chosen = r.select(Some(&DomainId::new("research")), &ws).unwrap();
476        assert_eq!(chosen.domain_id(), DomainId::new("research"));
477    }
478
479    #[test]
480    fn detection_selects_best_when_no_explicit() {
481        let r = registry();
482        let ws = WorkspaceSnapshot::new("/r", vec!["refs.bib".into()]);
483        let chosen = r.select(None, &ws).unwrap();
484        assert_eq!(chosen.domain_id(), DomainId::new("research"));
485    }
486
487    #[test]
488    fn registry_admits_multiple_domains() {
489        let r = registry();
490        assert_eq!(r.len(), 2);
491        assert!(r.by_id(&DomainId::new("coding")).is_some());
492        assert!(r.by_id(&DomainId::new("missing")).is_none());
493    }
494}