1use serde::{Deserialize, Serialize};
13
14use crate::energy::EnergyModel;
15use crate::residual::{CorrectionDirection, ResidualClass, ResidualEvent};
16
17#[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#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
36pub struct WorkspaceSnapshot {
37 pub root: String,
38 pub files: Vec<String>,
40 #[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 pub fn with_contents(mut self, contents: std::collections::BTreeMap<String, String>) -> Self {
56 self.contents = contents;
57 self
58 }
59
60 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 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#[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
97pub struct DomainDetection {
98 pub domain: DomainId,
99 pub activated: bool,
100 pub confidence: f64,
102 pub evidence: Vec<String>,
103}
104
105#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
107pub struct DomainScope {
108 pub label: String,
109 pub paths: Vec<String>,
110}
111
112#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
139pub struct VerificationCadence {
140 pub max_mutations_between_checks: u32,
142 pub high_risk_mutations_between_checks: u32,
144}
145
146impl VerificationCadence {
147 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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
171pub struct HardGatePolicy {
172 pub required_stages: Vec<String>,
174}
175
176#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
178pub struct VerifierSuiteSpec {
179 pub stages: Vec<String>,
181 pub cadence: VerificationCadence,
182}
183
184#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
186pub struct BarrierChannel {
187 pub name: String,
188 pub policy_version: String,
189}
190
191#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
193pub struct BarrierSpec {
194 pub channels: Vec<BarrierChannel>,
195}
196
197#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
200#[serde(rename_all = "snake_case")]
201pub enum SafetyBarrierDisposition {
202 NotClaimed { reason: String },
205 Registered(BarrierSpec),
207}
208
209pub trait AgentDomainPackage: Send + Sync {
216 fn domain_id(&self) -> DomainId;
218
219 fn detect(&self, workspace: &WorkspaceSnapshot) -> DomainDetection;
221
222 fn residual_schema(&self, scope: &DomainScope) -> ResidualSchema;
224
225 fn energy_model(&self, scope: &DomainScope) -> EnergyModel;
227
228 fn correction_directions(&self, residuals: &[ResidualEvent]) -> Vec<CorrectionDirection>;
232
233 fn tool_entries(&self, scope: &DomainScope) -> Vec<crate::toolset::ToolEntry>;
239
240 fn hard_gate_policy(&self, scope: &DomainScope) -> HardGatePolicy;
242
243 fn verifier_suite(&self, scope: &DomainScope) -> VerifierSuiteSpec;
245
246 fn safety_barrier(&self, scope: &DomainScope) -> SafetyBarrierDisposition;
249
250 fn proxy_geometry(&self, _scope: &DomainScope) -> Option<&dyn crate::stability::ProxyGeometry> {
253 None
254 }
255
256 fn prompt_library(&self) -> &dyn DomainPromptLibrary {
261 &EMPTY_PROMPT_LIBRARY
262 }
263
264 fn search_strategies(
267 &self,
268 _context: &crate::search::SearchContext,
269 ) -> Vec<crate::search::SearchStrategy> {
270 Vec::new()
271 }
272
273 fn correction_packet(
277 &self,
278 _residuals: &[crate::residual::ResidualEvent],
279 ) -> Option<crate::residual::CorrectionPacket> {
280 None
281 }
282
283 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 fn evaluate_workspace(
297 &self,
298 _snapshot: &WorkspaceSnapshot,
299 _node_id: &str,
300 _generation: u32,
301 ) -> Option<DomainEvaluation> {
302 None
303 }
304}
305
306pub trait DomainPromptLibrary: Send + Sync {
309 fn stage_templates(&self, stage: &str) -> Vec<crate::prompt::SectionTemplate> {
311 let _ = stage;
312 Vec::new()
313 }
314}
315
316#[derive(Debug)]
318pub struct EmptyDomainPromptLibrary;
319
320impl DomainPromptLibrary for EmptyDomainPromptLibrary {}
321
322static EMPTY_PROMPT_LIBRARY: EmptyDomainPromptLibrary = EmptyDomainPromptLibrary;
323
324#[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 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 pub fn domain_ids(&self) -> Vec<DomainId> {
369 self.packages.iter().map(|p| p.domain_id()).collect()
370 }
371
372 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 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 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}