trusty_code/llm/tool_call_extractor/schema.rs
1//! JSON-Schema-subset validator for tool-call arguments.
2//!
3//! Why: Every tool's `schema()` (see `tools::traits::ToolExecutor`) emits an
4//! OpenAI-function-style JSON Schema for its `parameters` object. Before a
5//! model-produced tool call is dispatched, its arguments must be checked
6//! against that schema so malformed calls are caught and reported precisely
7//! (#1023) — feeding the bounded repair loop in `super::repair` — instead of
8//! silently degrading to `{}` (the pre-#1023 behaviour in `agent_loop::parse_args`).
9//! What: [`validate_args`] walks `args` against a `parameters` JSON Schema
10//! object, supporting the subset every tool in this crate actually emits:
11//! `type` (object/string/integer/number/boolean/array/null), `properties`,
12//! `required`, `additionalProperties` (bool), `enum`, `minimum`/`maximum`, and
13//! a single `items` schema for arrays. Collects every violation rather than
14//! stopping at the first, so a repair message can address them all at once.
15//! Test: `schema::tests::*`.
16
17use serde_json::Value;
18
19/// One schema-validation failure, with a JSON-pointer-like `path` for context.
20///
21/// Why: A repair message that says "arguments are invalid" is useless to a
22/// model; naming the exact field and what was wrong lets the corrective
23/// message be actionable.
24/// What: `path` is a dotted/bracketed pointer from the argument root (`$`);
25/// `message` is a human-readable description of the mismatch.
26/// Test: `schema::tests::missing_required_property_reports_path`.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct SchemaViolation {
29 /// Location of the offending value, rooted at `$` (the whole arguments object).
30 pub path: String,
31 /// Human-readable description of the violation.
32 pub message: String,
33}
34
35impl SchemaViolation {
36 fn new(path: impl Into<String>, message: impl Into<String>) -> Self {
37 Self {
38 path: path.into(),
39 message: message.into(),
40 }
41 }
42}
43
44impl std::fmt::Display for SchemaViolation {
45 /// Why: `repair::build_corrective_message` renders violations into the
46 /// text sent back to the model; a stable `Display` keeps that formatting
47 /// in one place.
48 /// What: Renders as `"<path>: <message>"`.
49 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50 write!(f, "{}: {}", self.path, self.message)
51 }
52}
53
54/// Validate `args` against a tool's `parameters` JSON Schema object.
55///
56/// Why: This is the single validation entry point shared by every extraction
57/// strategy and every provider (#1023 acceptance criterion: "all providers
58/// share same validation plumbing") — native, fenced-JSON, angle-bracket, and
59/// balanced-scan results all funnel through here before dispatch.
60/// What: Returns `Ok(())` when `args` satisfies `schema`; otherwise `Err` with
61/// every violation found (never just the first).
62/// Test: `schema::tests::*`.
63pub fn validate_args(schema: &Value, args: &Value) -> Result<(), Vec<SchemaViolation>> {
64 let mut violations = Vec::new();
65 validate_value(schema, args, "$", &mut violations);
66 if violations.is_empty() {
67 Ok(())
68 } else {
69 Err(violations)
70 }
71}
72
73/// Recursive worker behind [`validate_args`].
74///
75/// Why: Separating the recursive walk from the public entry point keeps the
76/// `path` threading (for precise violation messages) out of the public API.
77/// What: Checks `type` and `enum` at this node, then recurses into
78/// `properties`/`required`/`additionalProperties` for objects, `items` for
79/// arrays, and `minimum`/`maximum` for numbers. A `type` mismatch stops
80/// descent (there is nothing meaningful left to check underneath).
81/// Test: Exercised via `validate_args` in every test below.
82fn validate_value(schema: &Value, value: &Value, path: &str, out: &mut Vec<SchemaViolation>) {
83 if let Some(expected) = schema.get("type").and_then(Value::as_str)
84 && !type_matches(expected, value)
85 {
86 out.push(SchemaViolation::new(
87 path,
88 format!(
89 "expected type '{expected}', got '{}'",
90 value_type_name(value)
91 ),
92 ));
93 return;
94 }
95
96 if let Some(allowed) = schema.get("enum").and_then(Value::as_array)
97 && !allowed.contains(value)
98 {
99 out.push(SchemaViolation::new(
100 path,
101 format!("value {value} is not one of the allowed enum values {allowed:?}"),
102 ));
103 }
104
105 match value {
106 Value::Object(map) => {
107 let props = schema.get("properties").and_then(Value::as_object);
108 if let Some(props) = props {
109 for (key, subschema) in props {
110 if let Some(v) = map.get(key) {
111 validate_value(subschema, v, &format!("{path}.{key}"), out);
112 }
113 }
114 }
115 if let Some(required) = schema.get("required").and_then(Value::as_array) {
116 for req in required {
117 if let Some(name) = req.as_str()
118 && !map.contains_key(name)
119 {
120 out.push(SchemaViolation::new(
121 path,
122 format!("missing required property '{name}'"),
123 ));
124 }
125 }
126 }
127 if schema.get("additionalProperties") == Some(&Value::Bool(false)) {
128 let allowed_keys = props;
129 for key in map.keys() {
130 let known = allowed_keys.is_some_and(|p| p.contains_key(key));
131 if !known {
132 out.push(SchemaViolation::new(
133 path,
134 format!("unexpected property '{key}' (additionalProperties: false)"),
135 ));
136 }
137 }
138 }
139 }
140 Value::Array(items) => {
141 if let Some(item_schema) = schema.get("items") {
142 for (i, item) in items.iter().enumerate() {
143 validate_value(item_schema, item, &format!("{path}[{i}]"), out);
144 }
145 }
146 }
147 Value::Number(n) => {
148 if let Some(min) = schema.get("minimum").and_then(Value::as_f64)
149 && n.as_f64().is_some_and(|v| v < min)
150 {
151 out.push(SchemaViolation::new(
152 path,
153 format!("value {n} is below minimum {min}"),
154 ));
155 }
156 if let Some(max) = schema.get("maximum").and_then(Value::as_f64)
157 && n.as_f64().is_some_and(|v| v > max)
158 {
159 out.push(SchemaViolation::new(
160 path,
161 format!("value {n} exceeds maximum {max}"),
162 ));
163 }
164 }
165 _ => {}
166 }
167}
168
169/// Whether `value`'s runtime JSON type matches a JSON-Schema `type` keyword.
170///
171/// Why: JSON Schema's `"integer"` has no direct `serde_json::Value` variant —
172/// it is a `Number` with no fractional part — so this needs its own check
173/// rather than a straight enum match.
174/// What: Returns `true` for a matching type; an unrecognised `expected`
175/// string is treated permissively (`true`) rather than rejecting every value,
176/// matching JSON Schema's general laxness toward unknown keywords.
177/// Test: `schema::tests::type_mismatch_is_reported`, `integer_type_rejects_float`.
178fn type_matches(expected: &str, value: &Value) -> bool {
179 match expected {
180 "object" => value.is_object(),
181 "string" => value.is_string(),
182 "integer" => value.is_i64() || value.is_u64(),
183 "number" => value.is_number(),
184 "boolean" => value.is_boolean(),
185 "array" => value.is_array(),
186 "null" => value.is_null(),
187 _ => true,
188 }
189}
190
191/// Human-readable JSON type name for a value, used in violation messages.
192///
193/// Why: Error messages should say "got 'string'" not "got 'Value::String(..)'".
194/// What: Maps each `Value` variant to its JSON Schema type name, distinguishing
195/// `integer` from `number` the same way [`type_matches`] does.
196/// Test: Exercised via violation message assertions in `schema::tests::*`.
197fn value_type_name(value: &Value) -> &'static str {
198 match value {
199 Value::Null => "null",
200 Value::Bool(_) => "boolean",
201 Value::Number(n) if n.is_i64() || n.is_u64() => "integer",
202 Value::Number(_) => "number",
203 Value::String(_) => "string",
204 Value::Array(_) => "array",
205 Value::Object(_) => "object",
206 }
207}
208
209// ── Tests ─────────────────────────────────────────────────────────────────────
210
211#[cfg(test)]
212mod tests {
213 use super::*;
214 use serde_json::json;
215
216 fn bash_schema() -> Value {
217 json!({
218 "type": "object",
219 "properties": {
220 "command": { "type": "string" },
221 "timeout_secs": { "type": "integer", "minimum": 1 }
222 },
223 "required": ["command"],
224 "additionalProperties": false
225 })
226 }
227
228 /// A fully valid argument object passes with no violations.
229 ///
230 /// Why: Guard the happy path before testing failure modes.
231 /// What: Valid `{command, timeout_secs}` against `bash_schema()`.
232 /// Test: this test.
233 #[test]
234 fn valid_args_pass() {
235 let args = json!({"command": "ls", "timeout_secs": 30});
236 assert_eq!(validate_args(&bash_schema(), &args), Ok(()));
237 }
238
239 /// A missing required property is reported with its name and root path.
240 ///
241 /// Why: The repair message must name the exact missing field.
242 /// What: Omit `command`; assert the violation names it.
243 /// Test: this test.
244 #[test]
245 fn missing_required_property_reports_path() {
246 let args = json!({"timeout_secs": 30});
247 let err = validate_args(&bash_schema(), &args).unwrap_err();
248 assert_eq!(err.len(), 1);
249 assert_eq!(err[0].path, "$");
250 assert!(err[0].message.contains("command"));
251 }
252
253 /// A type mismatch on a property is reported with the property's path.
254 ///
255 /// Why: Nested-path reporting lets a repair message point at the exact field.
256 /// What: `command` as a number instead of a string.
257 /// Test: this test.
258 #[test]
259 fn type_mismatch_is_reported() {
260 let args = json!({"command": 123});
261 let err = validate_args(&bash_schema(), &args).unwrap_err();
262 assert!(err.iter().any(|v| v.path == "$.command"));
263 assert!(err.iter().any(|v| v.message.contains("string")));
264 }
265
266 /// JSON Schema's `"integer"` rejects a fractional number.
267 ///
268 /// Why: `serde_json::Value::Number` conflates ints and floats; the
269 /// validator must still distinguish them per JSON Schema semantics.
270 /// What: `timeout_secs: 30.5` against an `"integer"` schema.
271 /// Test: this test.
272 #[test]
273 fn integer_type_rejects_float() {
274 let args = json!({"command": "ls", "timeout_secs": 30.5});
275 let err = validate_args(&bash_schema(), &args).unwrap_err();
276 assert!(err.iter().any(|v| v.path == "$.timeout_secs"));
277 }
278
279 /// A value below `minimum` is reported.
280 ///
281 /// Why: Range constraints must actually be enforced, not just parsed.
282 /// What: `timeout_secs: 0` against `minimum: 1`.
283 /// Test: this test.
284 #[test]
285 fn below_minimum_is_reported() {
286 let args = json!({"command": "ls", "timeout_secs": 0});
287 let err = validate_args(&bash_schema(), &args).unwrap_err();
288 assert!(err.iter().any(|v| v.message.contains("minimum")));
289 }
290
291 /// An unexpected property is reported when `additionalProperties: false`.
292 ///
293 /// Why: Tools declare a closed argument shape; extra hallucinated keys
294 /// should be caught rather than silently ignored.
295 /// What: Add an unknown `foo` key.
296 /// Test: this test.
297 #[test]
298 fn unexpected_property_is_reported() {
299 let args = json!({"command": "ls", "foo": "bar"});
300 let err = validate_args(&bash_schema(), &args).unwrap_err();
301 assert!(err.iter().any(|v| v.message.contains("foo")));
302 }
303
304 /// All violations are collected, not just the first.
305 ///
306 /// Why: A single repair round-trip should let the model fix everything at
307 /// once rather than playing whack-a-mole one violation per turn.
308 /// What: Two independent violations in one payload; both are reported.
309 /// Test: this test.
310 #[test]
311 fn collects_multiple_violations() {
312 let args = json!({"timeout_secs": "not-a-number"});
313 let err = validate_args(&bash_schema(), &args).unwrap_err();
314 // missing `command` AND wrong type for `timeout_secs`.
315 assert!(
316 err.len() >= 2,
317 "expected at least 2 violations, got {err:?}"
318 );
319 }
320
321 /// `enum` restricts a string property to its declared values.
322 ///
323 /// Why: Some future tool schemas may restrict a field to a fixed set;
324 /// validate that path even though no current tool schema uses it yet.
325 /// What: A schema with an `enum` property; an out-of-set value fails.
326 /// Test: this test.
327 #[test]
328 fn enum_violation_is_reported() {
329 let schema = json!({
330 "type": "object",
331 "properties": { "mode": { "type": "string", "enum": ["fast", "slow"] } },
332 "required": ["mode"]
333 });
334 let err = validate_args(&schema, &json!({"mode": "medium"})).unwrap_err();
335 assert!(err.iter().any(|v| v.message.contains("enum")));
336 }
337
338 /// `items` validates each element of an array property.
339 ///
340 /// Why: Guard the array-recursion path even though no current tool uses it.
341 /// What: An array property with a `string` item schema; a numeric element fails.
342 /// Test: this test.
343 #[test]
344 fn array_items_are_validated() {
345 let schema = json!({
346 "type": "object",
347 "properties": { "tags": { "type": "array", "items": { "type": "string" } } }
348 });
349 let err = validate_args(&schema, &json!({"tags": ["a", 1]})).unwrap_err();
350 assert!(err.iter().any(|v| v.path == "$.tags[1]"));
351 }
352
353 /// `SchemaViolation`'s `Display` renders `"path: message"`.
354 ///
355 /// Why: `repair::build_corrective_message` depends on this exact shape.
356 /// What: Format a violation, assert the rendered string.
357 /// Test: this test.
358 #[test]
359 fn violation_display_format() {
360 let v = SchemaViolation::new("$.command", "missing required property 'command'");
361 assert_eq!(
362 v.to_string(),
363 "$.command: missing required property 'command'"
364 );
365 }
366}