1#![forbid(unsafe_code)]
8
9mod verify;
10
11use perspt_sdk::{
12 AgentDomainPackage, CorrectionDirection, CorrectionPacket, DomainDetection, DomainEvaluation,
13 DomainId, DomainScope, EnergyComponent, EnergyModel, HardGatePolicy, ResidualClass,
14 ResidualEvent, ResidualSchema, ResidualWeight, SafetyBarrierDisposition, StabilityClaim,
15 VerificationCadence, VerifierSuiteSpec, WorkspaceSnapshot,
16};
17
18#[derive(Debug, Clone, Default)]
20pub struct ResearchDomain;
21
22impl ResearchDomain {
23 pub fn new() -> Self {
24 Self
25 }
26}
27
28impl AgentDomainPackage for ResearchDomain {
29 fn domain_id(&self) -> DomainId {
30 DomainId::new("research")
31 }
32
33 fn detect(&self, workspace: &WorkspaceSnapshot) -> DomainDetection {
34 let mut evidence = Vec::new();
35 for marker in [
36 "references.bib",
37 "refs.bib",
38 "bibliography.bib",
39 "sources.md",
40 "references.md",
41 ] {
42 if workspace.has_file_named(marker) {
43 evidence.push(format!("found {marker}"));
44 }
45 }
46 let activated = !evidence.is_empty();
47 DomainDetection {
48 domain: self.domain_id(),
49 activated,
50 confidence: if activated { 0.85 } else { 0.0 },
51 evidence,
52 }
53 }
54
55 fn residual_schema(&self, _scope: &DomainScope) -> ResidualSchema {
56 ResidualSchema::new(vec![
57 ResidualClass::Syntax, ResidualClass::TestFailure, ResidualClass::InterfaceMismatch, ResidualClass::ImportGraph, ResidualClass::SymbolMismatch, ResidualClass::ContextDrift, ResidualClass::SheafInconsistency, ResidualClass::SensorUnavailable,
65 ResidualClass::ToolFailure,
66 ])
67 }
68
69 fn energy_model(&self, scope: &DomainScope) -> EnergyModel {
70 use EnergyComponent::*;
71 use ResidualClass::*;
72 let mut model = EnergyModel::new("research", 0.5).with_correction_budget(4);
73 model.residual_weights = vec![
74 ResidualWeight::new(Syntax, Syn, 3.0).with_hard_threshold(0.0),
75 ResidualWeight::new(TestFailure, Log, 3.0),
76 ResidualWeight::new(InterfaceMismatch, Str, 2.0),
77 ResidualWeight::new(ImportGraph, Str, 2.0),
78 ResidualWeight::new(SymbolMismatch, Str, 2.0),
79 ResidualWeight::new(ContextDrift, Sheaf, 1.5),
80 ResidualWeight::new(SheafInconsistency, Sheaf, 2.5),
81 ResidualWeight::new(SensorUnavailable, Boot, 1.0),
82 ResidualWeight::new(ToolFailure, Boot, 1.0),
83 ResidualWeight::new(ToolArgumentInvalid, Str, 1.0),
85 ResidualWeight::new(WitnessStale, Str, 1.0),
86 ResidualWeight::new(ToolThrash, Str, 1.0),
87 ResidualWeight::new(ToolBatchConflict, Str, 1.0),
88 ResidualWeight::new(UnreadEdit, Str, 1.0),
89 ResidualWeight::new(BudgetPressure, Str, 1.0),
90 ResidualWeight::new(AdjudicatorObjection, Log, 2.0),
91 ResidualWeight::new(ProviderUnavailable, Boot, 1.0),
92 ];
93 model.energy_tolerance = 0.0;
94 model.stability_claim = Some(StabilityClaim::not_claimed(format!(
95 "research scope: {}",
96 scope.label
97 )));
98 model
99 }
100
101 fn correction_directions(&self, residuals: &[ResidualEvent]) -> Vec<CorrectionDirection> {
102 residuals
103 .iter()
104 .filter_map(|r| {
105 let mut dir = match r.class {
106 ResidualClass::Syntax => Some(CorrectionDirection::new(
107 ResidualClass::Syntax,
108 "fix the malformed BibTeX entry or unbalanced braces in the bibliography",
109 )),
110 ResidualClass::TestFailure => Some(CorrectionDirection::new(
111 ResidualClass::TestFailure,
112 "support or retract the claim: cite a primary source or weaken the statement",
113 )),
114 ResidualClass::ImportGraph | ResidualClass::SymbolMismatch => {
115 Some(CorrectionDirection::new(
116 r.class,
117 "define the missing citation key in the bibliography \
118 (or cite an existing entry)",
119 ))
120 }
121 ResidualClass::InterfaceMismatch => Some(CorrectionDirection::new(
122 ResidualClass::InterfaceMismatch,
123 "align source metadata and citation attributes with the bibliography entry",
124 )),
125 ResidualClass::ContextDrift => Some(CorrectionDirection::new(
126 ResidualClass::ContextDrift,
127 "refresh the stale evidence: re-fetch the source and re-validate quote bounds",
128 )),
129 _ => None,
130 }?;
131 dir.target_paths = r.affected_paths.clone();
132 dir.target_symbols = r.affected_symbols.clone();
133 dir.rationale = r.evidence.summary.clone();
134 Some(dir)
135 })
136 .collect()
137 }
138
139 fn correction_packet(&self, residuals: &[ResidualEvent]) -> Option<CorrectionPacket> {
140 verify::build_correction_packet(self, residuals)
141 }
142
143 fn tool_entries(&self, _scope: &DomainScope) -> Vec<perspt_sdk::ToolEntry> {
144 Vec::new()
145 }
146
147 fn hard_gate_policy(&self, _scope: &DomainScope) -> HardGatePolicy {
148 HardGatePolicy {
149 required_stages: vec!["citation-check".into()],
150 }
151 }
152
153 fn verifier_suite(&self, _scope: &DomainScope) -> VerifierSuiteSpec {
154 VerifierSuiteSpec {
155 stages: vec!["citation-check".into()],
156 cadence: VerificationCadence::default(),
157 }
158 }
159
160 fn safety_barrier(&self, _scope: &DomainScope) -> SafetyBarrierDisposition {
161 SafetyBarrierDisposition::NotClaimed {
162 reason: "the research domain declares no operational unsafe set yet; \
163 chance-safety certification is unavailable"
164 .into(),
165 }
166 }
167
168 fn evaluate_workspace(
169 &self,
170 snapshot: &WorkspaceSnapshot,
171 node_id: &str,
172 generation: u32,
173 ) -> Option<DomainEvaluation> {
174 verify::evaluate_research_workspace(snapshot, node_id, generation)
175 }
176}
177
178#[cfg(test)]
179mod tests {
180 use std::collections::BTreeMap;
181
182 use super::*;
183 use perspt_sdk::{
184 DomainRegistry, IndependenceRoute, ResidualSeverity, SensorRef, score_candidate,
185 };
186
187 #[test]
188 fn research_domain_detects_bibliography() {
189 let domain = ResearchDomain::new();
190 let ws = WorkspaceSnapshot::new("/paper", vec!["refs.bib".into(), "draft.md".into()]);
191 assert!(domain.detect(&ws).activated);
192 }
193
194 #[test]
195 fn research_energy_model_validates_and_is_not_claimed() {
196 let model = ResearchDomain::new().energy_model(&DomainScope::default());
197 assert!(model.validate().is_ok());
198 assert!(!model.stability_claim.unwrap().claims_floor());
199 }
200
201 #[test]
202 fn research_scores_an_unsupported_claim() {
203 let domain = ResearchDomain::new();
204 let model = domain.energy_model(&DomainScope::default());
205 let claim = ResidualEvent::new(
206 "claim-7",
207 0,
208 ResidualClass::TestFailure,
209 ResidualSeverity::Error,
210 1.0,
211 SensorRef::new("claim-checker", IndependenceRoute::SeparateModel),
212 )
213 .unwrap();
214 let score = score_candidate(&model, &[claim]).unwrap();
215 assert_eq!(score.total, 3.0);
216 }
217
218 #[test]
219 fn registry_admits_research_alongside_other_domains() {
220 let mut registry = DomainRegistry::new();
221 registry.register(std::sync::Arc::new(ResearchDomain::new()));
222 assert_eq!(registry.len(), 1);
223 assert!(registry.by_id(&DomainId::new("research")).is_some());
224 }
225
226 #[test]
227 fn evaluate_workspace_passes_valid_bib_and_md_citations() {
228 let domain = ResearchDomain::new();
229 let mut contents = BTreeMap::new();
230 contents.insert(
231 "refs.bib".to_string(),
232 "@article{smith2024,\n title={Stability}\n}\n".to_string(),
233 );
234 contents.insert(
235 "draft.md".to_string(),
236 "Prior work [@smith2024] proves convergence.\n".to_string(),
237 );
238 let ws = WorkspaceSnapshot::new("/paper", vec!["draft.md".into(), "refs.bib".into()])
239 .with_contents(contents);
240
241 let eval = domain.evaluate_workspace(&ws, "n1", 0).unwrap();
242 assert_eq!(eval.ran_stages, vec!["citation-check"]);
243 assert!(eval.residuals.is_empty(), "{:?}", eval.residuals);
244 }
245
246 #[test]
247 fn evaluate_workspace_flags_missing_citations_and_builds_packet() {
248 let domain = ResearchDomain::new();
249 let mut contents = BTreeMap::new();
250 contents.insert(
251 "refs.bib".to_string(),
252 "@article{known2023,\n}\n".to_string(),
253 );
254 contents.insert(
255 "draft.md".to_string(),
256 "See [@known2023; @missing2026] and \\cite{also_missing}.\n".to_string(),
257 );
258 let ws = WorkspaceSnapshot::new("/paper", vec!["draft.md".into(), "refs.bib".into()])
259 .with_contents(contents);
260
261 let eval = domain.evaluate_workspace(&ws, "n1", 0).unwrap();
262 assert_eq!(eval.residuals.len(), 1);
263 assert_eq!(eval.residuals[0].class, ResidualClass::ImportGraph);
264 let symbols: Vec<&str> = eval.residuals[0]
265 .affected_symbols
266 .iter()
267 .map(|s| s.name.as_str())
268 .collect();
269 assert_eq!(symbols, vec!["missing2026", "also_missing"]);
270
271 let packet = domain.correction_packet(&eval.residuals).unwrap();
272 assert_eq!(packet.affected.paths, vec!["draft.md"]);
273 assert!(!packet.is_empty());
274 }
275
276 #[test]
277 fn evaluate_workspace_flags_malformed_bibtex() {
278 let domain = ResearchDomain::new();
279 let mut contents = BTreeMap::new();
280 contents.insert(
281 "refs.bib".to_string(),
282 "@article{broken\n title={Missing comma and brace}\n".to_string(),
283 );
284 let ws = WorkspaceSnapshot::new("/paper", vec!["refs.bib".into()]).with_contents(contents);
285
286 let eval = domain.evaluate_workspace(&ws, "n1", 0).unwrap();
287 assert_eq!(eval.residuals.len(), 1);
288 assert_eq!(eval.residuals[0].class, ResidualClass::Syntax);
289 }
290}