car-validator 0.54.0

Precondition checking and action validation for Common Agent Runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! Action validation — precondition checking and invariant enforcement.

use car_ir::precondition;
use car_ir::{Action, Precondition, ToolSchema};
use car_state::StateStore;
use std::collections::HashMap;

/// A single validation failure.
#[derive(Debug, Clone)]
pub struct ValidationError {
    pub action_id: String,
    pub reason: String,
}

/// Aggregate result of validating an action.
#[derive(Debug)]
pub struct ValidationResult {
    pub action_id: String,
    pub errors: Vec<ValidationError>,
}

impl ValidationResult {
    pub fn valid(&self) -> bool {
        self.errors.is_empty()
    }
}

/// Check a single precondition against state.
pub fn check_precondition(pre: &Precondition, state: &StateStore) -> Option<String> {
    precondition::check_precondition(pre, state)
}

/// Validate `action.parameters` against a tool's registered schema.
///
/// Two paths run side-by-side for backwards compatibility with the
/// schemaless `register_tool(name)` registration path:
///
/// 1. **Required-key check** — kept for the legacy case where the
///    schema is an empty object (no constraints) but a sibling
///    `required` array is somehow present. Cheap, no-op when no
///    `required` field exists.
/// 2. **Full JSON Schema validation** via `jsonschema` — runs only
///    when the schema is a non-trivial object (has `type` /
///    `properties` / `required` / `enum` / etc.). Catches type
///    mismatches like `{path: 42}` for a tool wanting
///    `{path: string}` — which the legacy required-only check let
///    through.
///
/// Tools registered via the schemaless API have an empty `{}` schema
/// → both checks are no-ops → existing callers see no behavior change.
fn validate_parameters(
    action: &car_ir::Action,
    tool: &str,
    schema: &ToolSchema,
    result: &mut ValidationResult,
) {
    // 1. Cheap required-key check (LLM may send unexpected extras —
    // we intentionally do NOT reject unknown properties).
    if let Some(required) = schema.parameters.get("required") {
        if let Some(required_arr) = required.as_array() {
            for req in required_arr {
                if let Some(param_name) = req.as_str() {
                    if !action.parameters.contains_key(param_name) {
                        result.errors.push(ValidationError {
                            action_id: action.id.clone(),
                            reason: format!(
                                "missing required parameter '{}' for tool '{}'",
                                param_name, tool
                            ),
                        });
                    }
                }
            }
        }
    }

    // 2. Full JSON Schema validation when the schema actually carries
    // constraints. An empty object schema (the schemaless registration
    // case) trivially validates everything — skip the work.
    if !schema_is_empty_object(&schema.parameters) {
        let params_value = parameters_to_value(&action.parameters);
        match jsonschema::validator_for(&schema.parameters) {
            Ok(validator) => {
                for err in validator.iter_errors(&params_value) {
                    result.errors.push(ValidationError {
                        action_id: action.id.clone(),
                        reason: format!(
                            "tool '{}' parameter validation: {} (at {})",
                            tool, err, err.instance_path
                        ),
                    });
                }
            }
            Err(e) => {
                result.errors.push(ValidationError {
                    action_id: action.id.clone(),
                    reason: format!(
                        "tool '{}' has an invalid registered JSON Schema: {}",
                        tool, e
                    ),
                });
            }
        }
    }
}

fn schema_is_empty_object(schema: &serde_json::Value) -> bool {
    match schema {
        serde_json::Value::Object(map) => map.is_empty(),
        _ => true,
    }
}

fn parameters_to_value(params: &HashMap<String, serde_json::Value>) -> serde_json::Value {
    let map: serde_json::Map<String, serde_json::Value> =
        params.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
    serde_json::Value::Object(map)
}

/// Validate a tool result against its declared return schema.
///
/// Return schemas are optional, so callers invoke this only when a schema is
/// present. Keeping compilation and error formatting beside parameter-schema
/// validation prevents callback transports from growing subtly different JSON
/// Schema implementations.
pub fn validate_tool_output(
    tool: &str,
    schema: &serde_json::Value,
    output: &serde_json::Value,
) -> Result<(), String> {
    if schema_is_empty_object(schema) {
        return Ok(());
    }
    let validator = jsonschema::validator_for(schema)
        .map_err(|error| format!("tool '{tool}' has an invalid return JSON Schema: {error}"))?;
    let errors: Vec<String> = validator
        .iter_errors(output)
        .map(|error| format!("{error} (at {})", error.instance_path))
        .collect();
    if errors.is_empty() {
        Ok(())
    } else {
        Err(format!(
            "tool '{tool}' output validation: {}",
            errors.join("; ")
        ))
    }
}

/// Validate a single action against state and registered tools.
pub fn validate_action(
    action: &Action,
    state: &StateStore,
    registered_tools: &HashMap<String, ToolSchema>,
) -> ValidationResult {
    let mut result = ValidationResult {
        action_id: action.id.clone(),
        errors: Vec::new(),
    };

    // Check tool exists and validate parameters against schema
    if let Some(ref tool) = action.tool {
        if let Some(schema) = registered_tools.get(tool) {
            validate_parameters(action, tool, schema, &mut result);
        } else {
            result.errors.push(ValidationError {
                action_id: action.id.clone(),
                reason: format!("tool '{}' is not registered", tool),
            });
        }
    }

    // A declared compensation is the whole basis for calling an effect
    // recoverable, so an undo naming a tool that does not exist is a rollback
    // plan that cannot run. Resolved here against the same registry as
    // `action.tool` — `Compensation::ActionRef` needs the sibling actions and
    // is resolved at proposal level by `car_verify`'s
    // `compensation_resolution` check instead.
    if let Some(car_ir::Compensation::Tool { tool, .. }) = &action.compensation {
        if !registered_tools.contains_key(tool) {
            result.errors.push(ValidationError {
                action_id: action.id.clone(),
                reason: format!("compensation tool '{}' is not registered", tool),
            });
        }
    }

    // Check preconditions
    for pre in &action.preconditions {
        if let Some(error) = check_precondition(pre, state) {
            result.errors.push(ValidationError {
                action_id: action.id.clone(),
                reason: error,
            });
        }
    }

    // Check state dependencies
    for dep in &action.state_dependencies {
        if !state.exists(dep) {
            result.errors.push(ValidationError {
                action_id: action.id.clone(),
                reason: format!("state dependency '{}' not found", dep),
            });
        }
    }

    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use car_ir::{ActionType, Precondition, ToolSchema};
    use serde_json::Value;
    use std::collections::HashMap;

    fn make_tool_call(tool: &str) -> Action {
        {
            let mut a = Action::new(ActionType::ToolCall);
            a.id = "test".to_string();
            a.tool = Some(tool.to_string());
            a
        }
    }

    fn simple_schema(name: &str) -> ToolSchema {
        ToolSchema {
            name: name.to_string(),
            source: car_ir::ToolSourceKind::UserDefined,
            description: String::new(),
            parameters: Value::Object(Default::default()),
            returns: None,
            idempotent: false,
            cache_ttl_secs: None,
            rate_limit: None,
        }
    }

    fn tools_map(names: &[&str]) -> HashMap<String, ToolSchema> {
        names
            .iter()
            .map(|n| (n.to_string(), simple_schema(n)))
            .collect()
    }

    #[test]
    fn compensation_tool_is_resolved_against_the_registry() {
        // A declared undo naming a tool that does not exist is a rollback plan
        // that cannot run — and the action itself is perfectly valid, so
        // nothing else in the pipeline would have caught it.
        let state = StateStore::new();
        let tools = tools_map(&["echo"]);
        let mut action = make_tool_call("echo");
        action.reversibility = car_ir::Reversibility::Compensable;
        action.compensation = Some(car_ir::Compensation::Tool {
            tool: "unecho".to_string(),
            parameters: HashMap::new(),
        });
        let result = validate_action(&action, &state, &tools);
        assert!(!result.valid());
        assert!(result.errors.iter().any(|e| e
            .reason
            .contains("compensation tool 'unecho' is not registered")));

        // Registered compensation passes.
        let tools = tools_map(&["echo", "unecho"]);
        assert!(validate_action(&action, &state, &tools).valid());

        // An `ActionRef` compensation is not this function's to resolve — it
        // needs the sibling actions, which `car_verify` has and this does not.
        let mut action = make_tool_call("echo");
        action.compensation = Some(car_ir::Compensation::ActionRef {
            action_id: "whatever".to_string(),
        });
        assert!(validate_action(&action, &state, &tools_map(&["echo"])).valid());
    }

    #[test]
    fn unknown_tool_rejected() {
        let state = StateStore::new();
        let tools = tools_map(&["echo"]);
        let action = make_tool_call("nonexistent");
        let result = validate_action(&action, &state, &tools);
        assert!(!result.valid());
        assert!(result.errors[0].reason.contains("not registered"));
    }

    #[test]
    fn known_tool_passes() {
        let state = StateStore::new();
        let tools = tools_map(&["echo"]);
        let action = make_tool_call("echo");
        let result = validate_action(&action, &state, &tools);
        assert!(result.valid());
    }

    #[test]
    fn precondition_eq_fails() {
        let state = StateStore::new();
        let pre = Precondition {
            key: "auth".to_string(),
            operator: "eq".to_string(),
            value: Value::Bool(true),
            description: String::new(),
        };
        assert!(check_precondition(&pre, &state).is_some());
    }

    #[test]
    fn precondition_eq_passes() {
        let state = StateStore::new();
        state.set("auth", Value::Bool(true), "setup");
        let pre = Precondition {
            key: "auth".to_string(),
            operator: "eq".to_string(),
            value: Value::Bool(true),
            description: String::new(),
        };
        assert!(check_precondition(&pre, &state).is_none());
    }

    #[test]
    fn precondition_exists() {
        let state = StateStore::new();
        let pre = Precondition {
            key: "x".to_string(),
            operator: "exists".to_string(),
            value: Value::Null,
            description: String::new(),
        };
        assert!(check_precondition(&pre, &state).is_some());

        state.set("x", Value::from(1), "setup");
        assert!(check_precondition(&pre, &state).is_none());
    }

    #[test]
    fn state_dependency_missing() {
        let state = StateStore::new();
        let tools: HashMap<String, ToolSchema> = HashMap::new();
        let mut action = make_tool_call("echo");
        action.tool = None;
        action.action_type = ActionType::StateRead;
        action.state_dependencies = vec!["missing".to_string()];
        let result = validate_action(&action, &state, &tools);
        assert!(!result.valid());
        assert!(result.errors[0].reason.contains("not found"));
    }

    #[test]
    fn precondition_gt() {
        let state = StateStore::new();
        state.set("count", Value::from(10), "setup");
        let pre = Precondition {
            key: "count".to_string(),
            operator: "gt".to_string(),
            value: Value::from(5),
            description: String::new(),
        };
        assert!(check_precondition(&pre, &state).is_none());

        let pre_fail = Precondition {
            key: "count".to_string(),
            operator: "gt".to_string(),
            value: Value::from(20),
            description: String::new(),
        };
        assert!(check_precondition(&pre_fail, &state).is_some());
    }

    #[test]
    fn missing_required_parameter_rejected() {
        let state = StateStore::new();
        let mut schema = simple_schema("add");
        schema.parameters = serde_json::json!({
            "type": "object",
            "properties": {
                "a": {"type": "number"},
                "b": {"type": "number"}
            },
            "required": ["a", "b"]
        });
        let tools: HashMap<String, ToolSchema> =
            [("add".to_string(), schema)].into_iter().collect();

        let action = make_tool_call("add"); // no parameters
        let result = validate_action(&action, &state, &tools);
        assert!(!result.valid());
        assert!(result
            .errors
            .iter()
            .any(|e| e.reason.contains("missing required parameter 'a'")));
        assert!(result
            .errors
            .iter()
            .any(|e| e.reason.contains("missing required parameter 'b'")));
    }

    #[test]
    fn required_parameters_provided_passes() {
        let state = StateStore::new();
        let mut schema = simple_schema("add");
        schema.parameters = serde_json::json!({
            "type": "object",
            "properties": {
                "a": {"type": "number"},
                "b": {"type": "number"}
            },
            "required": ["a", "b"]
        });
        let tools: HashMap<String, ToolSchema> =
            [("add".to_string(), schema)].into_iter().collect();

        let mut action = make_tool_call("add");
        action.parameters = [
            ("a".to_string(), Value::from(1)),
            ("b".to_string(), Value::from(2)),
        ]
        .into();
        let result = validate_action(&action, &state, &tools);
        assert!(result.valid());
    }

    #[test]
    fn type_mismatch_rejected_when_schema_registered() {
        let state = StateStore::new();
        let mut schema = simple_schema("read");
        schema.parameters = serde_json::json!({
            "type": "object",
            "properties": {
                "path": {"type": "string"}
            },
            "required": ["path"]
        });
        let tools: HashMap<String, ToolSchema> =
            [("read".to_string(), schema)].into_iter().collect();

        let mut action = make_tool_call("read");
        action.parameters = [("path".to_string(), Value::from(42))].into();
        let result = validate_action(&action, &state, &tools);
        assert!(!result.valid(), "type mismatch should be rejected");
        assert!(
            result
                .errors
                .iter()
                .any(|e| e.reason.contains("parameter validation")),
            "expected jsonschema parameter validation failure, got: {:?}",
            result.errors
        );
    }

    #[test]
    fn empty_object_schema_is_treated_as_legacy() {
        // Defense-in-depth: a future refactor that "improves"
        // schema_is_empty_object must not silently turn the legacy
        // schemaless registration into a hard rejection.
        assert!(schema_is_empty_object(&Value::Object(Default::default())));
    }

    #[test]
    fn tool_output_uses_declared_return_schema() {
        let schema = serde_json::json!({
            "type":"object",
            "properties":{"report_id":{"type":"string"}},
            "required":["report_id"],
            "additionalProperties":false
        });
        assert!(validate_tool_output(
            "report_source",
            &schema,
            &serde_json::json!({"report_id":"r-1"})
        )
        .is_ok());
        let error = validate_tool_output(
            "report_source",
            &schema,
            &serde_json::json!({"report_id":42}),
        )
        .expect_err("wrong return type must fail");
        assert!(error.contains("output validation"), "{error}");
    }

    #[test]
    fn empty_return_schema_preserves_legacy_output() {
        assert!(validate_tool_output(
            "legacy",
            &serde_json::json!({}),
            &serde_json::json!({"anything":true})
        )
        .is_ok());
    }

    #[test]
    fn legacy_schemaless_tool_accepts_any_parameters() {
        let state = StateStore::new();
        let tools = tools_map(&["echo"]); // simple_schema → empty object
        let mut action = make_tool_call("echo");
        action.parameters = [
            ("anything".to_string(), Value::from(42)),
            ("else".to_string(), Value::from("string")),
        ]
        .into();
        let result = validate_action(&action, &state, &tools);
        assert!(
            result.valid(),
            "schemaless registration must accept anything"
        );
    }

    #[test]
    fn extra_parameters_allowed() {
        let state = StateStore::new();
        let mut schema = simple_schema("echo");
        schema.parameters = serde_json::json!({
            "type": "object",
            "properties": {
                "message": {"type": "string"}
            },
            "required": ["message"]
        });
        let tools: HashMap<String, ToolSchema> =
            [("echo".to_string(), schema)].into_iter().collect();

        let mut action = make_tool_call("echo");
        action.parameters = [
            ("message".to_string(), Value::from("hi")),
            ("unexpected_extra".to_string(), Value::from(true)),
        ]
        .into();
        let result = validate_action(&action, &state, &tools);
        assert!(result.valid()); // extra params should NOT cause rejection
    }
}