Skip to main content

perspt_research/
lib.rs

1//! # Perspt Research Domain Package (skeleton)
2//!
3//! This crate is the PSP-8 Phase 10 *second-domain readiness check*: it proves
4//! the [`perspt_sdk`] contracts admit a second domain package **without forking**
5//! the scheduler, admissibility kernel, residual model, replay ledger, or
6//! dashboard event model. A research agent reuses the same SRBN control plane;
7//! only the residual classes, energy model, and correction directions differ.
8//!
9//! Research residuals cover unsupported claims, stale evidence, source
10//! mismatch, and citation gaps, mapped onto the same energy components the SDK
11//! defines. The verifier suites (source discovery, citation provenance, claim
12//! extraction) are out of scope for the skeleton; the point is contract
13//! conformance.
14
15#![forbid(unsafe_code)]
16
17use perspt_sdk::{
18    AgentDomainPackage, CorrectionDirection, DomainDetection, DomainId, DomainScope,
19    EnergyComponent, EnergyModel, HardGatePolicy, ResidualClass, ResidualEvent, ResidualSchema,
20    ResidualWeight, SafetyBarrierDisposition, StabilityClaim, VerificationCadence,
21    VerifierSuiteSpec, WorkspaceSnapshot,
22};
23
24/// The research domain package.
25#[derive(Debug, Clone, Default)]
26pub struct ResearchDomain;
27
28impl ResearchDomain {
29    pub fn new() -> Self {
30        Self
31    }
32}
33
34impl AgentDomainPackage for ResearchDomain {
35    fn domain_id(&self) -> DomainId {
36        DomainId::new("research")
37    }
38
39    fn detect(&self, workspace: &WorkspaceSnapshot) -> DomainDetection {
40        let mut evidence = Vec::new();
41        for marker in [
42            "references.bib",
43            "refs.bib",
44            "bibliography.bib",
45            "sources.md",
46        ] {
47            if workspace.has_file_named(marker) {
48                evidence.push(format!("found {marker}"));
49            }
50        }
51        let activated = !evidence.is_empty();
52        DomainDetection {
53            domain: self.domain_id(),
54            activated,
55            confidence: if activated { 0.85 } else { 0.0 },
56            evidence,
57        }
58    }
59
60    fn residual_schema(&self, _scope: &DomainScope) -> ResidualSchema {
61        // Research reuses SDK residual classes; an unsupported claim maps to a
62        // logic residual, a citation gap to a structural one, stale evidence to
63        // context drift, and a contradiction to a sheaf inconsistency.
64        ResidualSchema::new(vec![
65            ResidualClass::TestFailure,        // unsupported / contradicted claim
66            ResidualClass::InterfaceMismatch,  // source mismatch
67            ResidualClass::ImportGraph,        // citation gap (missing source link)
68            ResidualClass::ContextDrift,       // stale evidence
69            ResidualClass::SheafInconsistency, // cross-source contradiction
70            ResidualClass::SensorUnavailable,
71        ])
72    }
73
74    fn energy_model(&self, scope: &DomainScope) -> EnergyModel {
75        use EnergyComponent::*;
76        use ResidualClass::*;
77        let mut model = EnergyModel::new("research", 0.5).with_correction_budget(4);
78        model.residual_weights = vec![
79            ResidualWeight::new(TestFailure, Log, 3.0), // unsupported claim is severe
80            ResidualWeight::new(InterfaceMismatch, Str, 2.0),
81            ResidualWeight::new(ImportGraph, Str, 2.0),
82            ResidualWeight::new(ContextDrift, Sheaf, 1.5),
83            ResidualWeight::new(SheafInconsistency, Sheaf, 2.5),
84            ResidualWeight::new(SensorUnavailable, Boot, 1.0),
85        ];
86        model.energy_tolerance = 0.0;
87        model.stability_claim = Some(StabilityClaim::not_claimed(format!(
88            "research scope: {}",
89            scope.label
90        )));
91        model
92    }
93
94    fn correction_directions(&self, residuals: &[ResidualEvent]) -> Vec<CorrectionDirection> {
95        residuals
96            .iter()
97            .filter_map(|r| match r.class {
98                ResidualClass::TestFailure => Some(CorrectionDirection::new(
99                    ResidualClass::TestFailure,
100                    "support or retract the claim: cite a primary source or weaken the statement",
101                )),
102                ResidualClass::ImportGraph => Some(CorrectionDirection::new(
103                    ResidualClass::ImportGraph,
104                    "add the missing citation linking the claim to its source",
105                )),
106                ResidualClass::ContextDrift => Some(CorrectionDirection::new(
107                    ResidualClass::ContextDrift,
108                    "refresh the stale evidence: re-fetch the source and re-validate the quote bounds",
109                )),
110                _ => None,
111            })
112            .collect()
113    }
114
115    fn tool_entries(&self, _scope: &DomainScope) -> Vec<perspt_sdk::ToolEntry> {
116        // Research-specific tools (source discovery, citation fetch) arrive
117        // with the research tool loop; the base catalog already covers
118        // reading, searching, and editing notes.
119        Vec::new()
120    }
121
122    fn hard_gate_policy(&self, _scope: &DomainScope) -> HardGatePolicy {
123        HardGatePolicy {
124            required_stages: vec!["citation-check".into()],
125        }
126    }
127
128    fn verifier_suite(&self, _scope: &DomainScope) -> VerifierSuiteSpec {
129        VerifierSuiteSpec {
130            stages: vec!["citation-check".into()],
131            cadence: VerificationCadence::default(),
132        }
133    }
134
135    fn safety_barrier(&self, _scope: &DomainScope) -> SafetyBarrierDisposition {
136        SafetyBarrierDisposition::NotClaimed {
137            reason: "the research domain declares no operational unsafe set yet; \
138                     chance-safety certification is unavailable"
139                .into(),
140        }
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147    use perspt_sdk::{
148        score_candidate, DomainRegistry, IndependenceRoute, ResidualSeverity, SensorRef,
149    };
150
151    #[test]
152    fn research_domain_detects_bibliography() {
153        let domain = ResearchDomain::new();
154        let ws = WorkspaceSnapshot::new("/paper", vec!["refs.bib".into(), "draft.md".into()]);
155        assert!(domain.detect(&ws).activated);
156    }
157
158    #[test]
159    fn research_energy_model_validates_and_is_not_claimed() {
160        let model = ResearchDomain::new().energy_model(&DomainScope::default());
161        assert!(model.validate().is_ok());
162        assert!(!model.stability_claim.unwrap().claims_floor());
163    }
164
165    #[test]
166    fn research_scores_an_unsupported_claim() {
167        let domain = ResearchDomain::new();
168        let model = domain.energy_model(&DomainScope::default());
169        let claim = ResidualEvent::new(
170            "claim-7",
171            0,
172            ResidualClass::TestFailure,
173            ResidualSeverity::Error,
174            1.0,
175            SensorRef::new("claim-checker", IndependenceRoute::SeparateModel),
176        )
177        .unwrap();
178        // TestFailure weight 3.0 -> 3.0 * 1^2 = 3.0 in V_log.
179        let score = score_candidate(&model, &[claim]).unwrap();
180        assert_eq!(score.total, 3.0);
181    }
182
183    #[test]
184    fn registry_admits_research_alongside_other_domains() {
185        // The SDK control plane admits a second domain without forking.
186        let mut registry = DomainRegistry::new();
187        registry.register(std::sync::Arc::new(ResearchDomain::new()));
188        assert_eq!(registry.len(), 1);
189        assert!(registry.by_id(&DomainId::new("research")).is_some());
190    }
191}