1use std::time::Duration;
9
10use serde::Deserialize;
11
12use crate::active_plans::PlanRuntime;
13use crate::config::VerificationRule;
14use crate::dispatch;
15use crate::pb::pilot::{CapabilityCall, CapabilityCallResult};
16use crate::rtdl_events::NodeEventContext;
17use robonix_atlas::client::AtlasClient;
18use robonix_scribe::{info, warn};
19
20pub const VERIFY_CONTRACT_ID: &str = "robonix/service/verifier/verify";
21const VLM_VERIFIER_PROVIDER_ID: &str = "vlm_verifier";
22const VERIFICATION_TIMEOUT: Duration = Duration::from_secs(60);
23
24#[derive(Clone, Debug, Default)]
26pub struct VerificationPolicy {
27 overlap: bool,
29 rules: Vec<VerificationRule>,
31}
32
33impl VerificationPolicy {
34 pub fn new(overlap: bool, rules: Vec<VerificationRule>) -> Self {
35 Self { overlap, rules }
36 }
37
38 pub fn len(&self) -> usize {
39 self.rules.len()
40 }
41
42 pub fn overlap(&self) -> bool {
43 self.overlap
44 }
45
46 pub fn rule_for(&self, call: &CapabilityCall) -> Option<&VerificationRule> {
48 self.rules
49 .iter()
50 .find(|rule| {
51 rule.target_contract_id == call.contract_id
52 && rule.target_provider_id.as_deref() == Some(call.provider_id.as_str())
53 })
54 .or_else(|| {
55 self.rules.iter().find(|rule| {
56 rule.target_contract_id == call.contract_id && rule.target_provider_id.is_none()
57 })
58 })
59 }
60}
61
62#[derive(Debug, Deserialize)]
64struct VerifyResponse {
65 passed: bool,
67 detail: String,
69}
70
71pub async fn capture_before(
73 policy: &VerificationPolicy,
74 call: &CapabilityCall,
75 node: &NodeEventContext,
76 self_provider_id: &str,
77 atlas: &mut AtlasClient,
78 runtime: &PlanRuntime,
79) -> Result<(), String> {
80 let Some(rule) = policy.rule_for(call) else {
81 return Ok(());
82 };
83 if rule.verifier_provider_id != VLM_VERIFIER_PROVIDER_ID {
84 return Ok(());
85 }
86 let verifier_call = build_verifier_call(rule, call, &node.description, None);
87 let response = request_verdict(&verifier_call, node, self_provider_id, atlas, runtime).await?;
88 if !response.passed {
89 return Err(format!(
90 "before image capture rejected: {}",
91 response.detail
92 ));
93 }
94 Ok(())
95}
96
97pub async fn verify_result(
100 policy: &VerificationPolicy,
101 call: &CapabilityCall,
102 node: &NodeEventContext,
103 original: CapabilityCallResult,
104 self_provider_id: &str,
105 atlas: &mut AtlasClient,
106 runtime: &PlanRuntime,
107) -> CapabilityCallResult {
108 let Some(rule) = policy.rule_for(call) else {
109 return original;
110 };
111
112 let verifier_call = build_verifier_call(rule, call, &node.description, Some(&original));
113 match request_verdict(&verifier_call, node, self_provider_id, atlas, runtime).await {
114 Ok(verdict) => apply_verdict(original, verdict),
115 Err(reason) => unavailable(original, reason),
116 }
117}
118
119async fn request_verdict(
120 verifier_call: &CapabilityCall,
121 node: &NodeEventContext,
122 self_provider_id: &str,
123 atlas: &mut AtlasClient,
124 runtime: &PlanRuntime,
125) -> Result<VerifyResponse, String> {
126 info!(
127 "[executor/verification] call_id={} verifier='{}'",
128 verifier_call.call_id, verifier_call.provider_id
129 );
130 let response = dispatch::dispatch_with_timeout(
131 verifier_call,
132 self_provider_id,
133 atlas,
134 runtime,
135 &node.plan_id,
136 Some(VERIFICATION_TIMEOUT),
137 )
138 .await;
139 if !response.success {
140 return Err(format!(
141 "verifier '{}' failed: {}",
142 verifier_call.provider_id, response.error
143 ));
144 }
145
146 serde_json::from_str(&response.output).map_err(|error| {
147 format!(
148 "verifier '{}' returned invalid response: {error}",
149 verifier_call.provider_id
150 )
151 })
152}
153
154fn build_verifier_call(
157 rule: &VerificationRule,
158 call: &CapabilityCall,
159 description: &str,
160 result: Option<&CapabilityCallResult>,
161) -> CapabilityCall {
162 let mut payload = serde_json::json!({
163 "target_provider_id": call.provider_id,
164 "target_contract_id": call.contract_id,
165 "target_description": description,
166 "target_args": json_or_string(&call.args_json),
167 "target_output": result.map(|result| json_or_string(&result.output)),
168 "verifier_args": rule.verifier_args,
169 });
170 let before = result.is_none();
171 if rule.verifier_provider_id == VLM_VERIFIER_PROVIDER_ID {
172 payload["phase"] = serde_json::json!(if before { "before" } else { "after" });
173 }
174 CapabilityCall {
175 call_id: if before {
176 format!("{}:verify:before", call.call_id)
177 } else {
178 format!("{}:verify", call.call_id)
179 },
180 provider_id: rule.verifier_provider_id.clone(),
181 contract_id: VERIFY_CONTRACT_ID.to_string(),
182 args_json: serde_json::json!({
183 "call_id": call.call_id,
184 "args_json": payload.to_string(),
185 })
186 .to_string(),
187 }
188}
189
190fn json_or_string(raw: &str) -> serde_json::Value {
191 serde_json::from_str(raw).unwrap_or_else(|_| serde_json::Value::String(raw.to_string()))
192}
193
194fn apply_verdict(
195 mut original: CapabilityCallResult,
196 verdict: VerifyResponse,
197) -> CapabilityCallResult {
198 if verdict.passed {
199 info!(
200 "[executor/verification] call_id={} passed: {}",
201 original.call_id, verdict.detail
202 );
203 return original;
204 }
205 let detail = if verdict.detail.trim().is_empty() {
206 "verifier rejected the capability result".to_string()
207 } else {
208 verdict.detail
209 };
210 warn!(
211 "[executor/verification] call_id={} rejected: {}",
212 original.call_id, detail
213 );
214 original.success = false;
215 original.error = format!("result verification failed: capability reported success. {detail}");
216 original
217}
218
219fn unavailable(mut original: CapabilityCallResult, reason: String) -> CapabilityCallResult {
220 warn!(
221 "[executor/verification] call_id={} unavailable: {}",
222 original.call_id, reason
223 );
224 original.success = false;
225 original.error =
226 format!("result verification unavailable: capability reported success. {reason}");
227 original
228}
229
230#[cfg(test)]
231mod tests {
232 use super::*;
233 use robonix_atlas::service::{AtlasRegistry, serve_atlas};
234 use std::net::SocketAddr;
235 use std::sync::Arc;
236
237 fn rule(provider: Option<&str>, verifier: &str) -> VerificationRule {
238 VerificationRule {
239 target_contract_id: "cap/target".to_string(),
240 target_provider_id: provider.map(str::to_string),
241 verifier_provider_id: verifier.to_string(),
242 verifier_args: serde_json::json!({"camera_provider_id":"front_camera"}),
243 }
244 }
245
246 fn call() -> CapabilityCall {
247 CapabilityCall {
248 call_id: "p:0".to_string(),
249 provider_id: "arm".to_string(),
250 contract_id: "cap/target".to_string(),
251 args_json: r#"{"object":"bottle"}"#.to_string(),
252 }
253 }
254
255 fn result() -> CapabilityCallResult {
256 CapabilityCallResult {
257 call_id: "p:0".to_string(),
258 provider_id: "arm".to_string(),
259 contract_id: "cap/target".to_string(),
260 success: true,
261 output: r#"{"accepted":true}"#.to_string(),
262 error: String::new(),
263 }
264 }
265
266 fn node() -> NodeEventContext {
267 NodeEventContext {
268 plan_id: "p".to_string(),
269 node_index: 0,
270 node_kind: 0,
271 op_id: "op".to_string(),
272 description: "place bottle".to_string(),
273 }
274 }
275
276 fn reserve_address() -> SocketAddr {
277 let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("reserve port");
278 listener.local_addr().expect("reserved address")
279 }
280
281 #[test]
282 fn exact_provider_rule_wins_over_contract_fallback() {
283 let policy = VerificationPolicy::new(
284 false,
285 vec![rule(None, "fallback"), rule(Some("arm"), "exact")],
286 );
287 assert_eq!(
288 policy.rule_for(&call()).unwrap().verifier_provider_id,
289 "exact"
290 );
291 }
292
293 #[test]
294 fn verifier_request_contains_runtime_context_and_opaque_args() {
295 let verify = build_verifier_call(
296 &rule(None, "vlm_verifier"),
297 &call(),
298 "place bottle",
299 Some(&result()),
300 );
301 let outer: serde_json::Value = serde_json::from_str(&verify.args_json).unwrap();
302 let payload: serde_json::Value =
303 serde_json::from_str(outer["args_json"].as_str().unwrap()).unwrap();
304 assert_eq!(verify.contract_id, VERIFY_CONTRACT_ID);
305 assert_eq!(payload["target_args"]["object"], "bottle");
306 assert_eq!(payload["target_output"]["accepted"], true);
307 assert_eq!(payload["target_description"], "place bottle");
308 assert_eq!(payload["phase"], "after");
309 assert_eq!(
310 payload["verifier_args"]["camera_provider_id"],
311 "front_camera"
312 );
313 }
314
315 #[test]
316 fn before_request_uses_same_target_identity_without_a_result() {
317 let request =
318 build_verifier_call(&rule(None, "vlm_verifier"), &call(), "place bottle", None);
319 let outer: serde_json::Value = serde_json::from_str(&request.args_json).unwrap();
320 let payload: serde_json::Value =
321 serde_json::from_str(outer["args_json"].as_str().unwrap()).unwrap();
322 assert_eq!(outer["call_id"], call().call_id);
323 assert_eq!(payload["phase"], "before");
324 assert!(payload["target_output"].is_null());
325 assert_eq!(payload["target_args"]["object"], "bottle");
326 let other = build_verifier_call(
327 &rule(None, "scene_verifier"),
328 &call(),
329 "place bottle",
330 Some(&result()),
331 );
332 let outer: serde_json::Value = serde_json::from_str(&other.args_json).unwrap();
333 let payload: serde_json::Value =
334 serde_json::from_str(outer["args_json"].as_str().unwrap()).unwrap();
335 assert!(payload.get("phase").is_none());
336 }
337
338 #[test]
339 fn rejected_verdict_preserves_output_and_fails_original_call() {
340 let output = result().output;
341 let verified = apply_verdict(
342 result(),
343 VerifyResponse {
344 passed: false,
345 detail: "bottle is outside the box".to_string(),
346 },
347 );
348 assert!(!verified.success);
349 assert_eq!(verified.output, output);
350 assert!(verified.error.contains("result verification failed"));
351 }
352
353 #[test]
354 fn passed_verdict_keeps_original_result_unchanged() {
355 let original = result();
356 let verified = apply_verdict(
357 original.clone(),
358 VerifyResponse {
359 passed: true,
360 detail: "visible".to_string(),
361 },
362 );
363 assert_eq!(verified, original);
364 }
365
366 #[test]
367 fn unavailable_verifier_preserves_output_but_fails_closed() {
368 let output = result().output;
369 let verified = unavailable(result(), "not registered".to_string());
370 assert!(!verified.success);
371 assert_eq!(verified.output, output);
372 assert!(verified.error.contains("result verification unavailable"));
373 }
374
375 #[tokio::test]
376 async fn missing_verifier_provider_fails_closed_over_atlas() {
377 let atlas_addr = reserve_address();
378 let contracts =
379 robonix_atlas::contract_registry::ContractRegistry::load_from_capabilities_dir(
380 &std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../capabilities"),
381 )
382 .unwrap();
383 let registry = Arc::new(AtlasRegistry::with_contracts(contracts));
384 let atlas_server = tokio::spawn(serve_atlas(registry, atlas_addr));
385 let mut atlas = AtlasClient::connect_with_retry(
386 format!("http://{atlas_addr}"),
387 50,
388 Duration::from_millis(10),
389 )
390 .await
391 .expect("connect test Atlas");
392 let policy = VerificationPolicy::new(false, vec![rule(None, "missing_verifier")]);
393 let verified = verify_result(
394 &policy,
395 &call(),
396 &node(),
397 result(),
398 "executor",
399 &mut atlas,
400 &PlanRuntime::default(),
401 )
402 .await;
403 assert!(!verified.success);
404 assert!(verified.error.contains("result verification unavailable"));
405 assert!(verified.error.contains("ConnectCapability failed"));
406 atlas_server.abort();
407 }
408}