Skip to main content

ag_protocol/
schema.rs

1//! JSON Schema generation and transport-compatibility normalization for the
2//! structured response protocol.
3
4use serde_json::Value;
5
6use super::model::{AgentResponse, questions_field_description, subtasks_field_description};
7use super::review::FocusedReview;
8
9/// Selects how a provider transport lists `required` schema properties.
10///
11/// Providers disagree on what a valid schema looks like. Codex rejects schemas
12/// whose `properties` contain keys missing from `required`, so it needs every
13/// key listed. Validators that enforce `required` literally, such as Claude,
14/// must only demand `answer`; listing optional keys there rejects ordinary
15/// replies that omit optional array fields, even though the parser accepts
16/// them through `#[serde(default)]`.
17#[derive(Clone, Copy, Debug, Eq, PartialEq)]
18pub enum SchemaRequiredPolicy {
19    /// Lists every `properties` key in `required` for Codex compatibility.
20    AllProperties,
21    /// Lists only the minimum protocol keys the parser insists on.
22    MinimumProtocolKeys,
23}
24
25/// Returns the JSON Schema used for structured assistant output.
26///
27/// The returned value is passed directly to providers that support enforced
28/// output schemas. It starts from the self-descriptive response schema and then
29/// applies compatibility normalization required by schema-enforcing agents.
30/// `required_policy` selects how strictly optional protocol keys are demanded.
31pub fn agent_response_output_schema(required_policy: SchemaRequiredPolicy) -> Value {
32    let mut value = agent_response_json_schema();
33    normalize_schema_for_transport(&mut value, required_policy);
34
35    value
36}
37
38/// Returns a pretty-printed JSON Schema string for prompt instruction
39/// templating.
40///
41/// This keeps the raw `schemars` metadata intact so inline prompt guidance can
42/// show a fully self-descriptive schema document.
43pub fn agent_response_json_schema_json() -> String {
44    let schema = agent_response_json_schema();
45
46    stringify_schema_json(&schema)
47}
48
49/// Returns a pretty-printed, transport-normalized JSON Schema string.
50///
51/// Provider adapters use this serialized schema document when their native
52/// structured-output API accepts JSON text. `required_policy` selects the
53/// provider-compatible `required` field normalization.
54pub fn agent_response_output_schema_json(required_policy: SchemaRequiredPolicy) -> String {
55    let schema = agent_response_output_schema(required_policy);
56
57    stringify_schema_json(&schema)
58}
59
60/// Returns a pretty-printed JSON Schema string for focused-review prompt
61/// instructions.
62///
63/// Focused review uses the shared top-level [`AgentResponse`] transport and
64/// carries this request-specific object inside `answer`. Embedding the
65/// self-descriptive schema in the utility prompt keeps its structured fields
66/// explicit without adding focused-review-only fields to every agent turn.
67pub fn focused_review_json_schema_json() -> String {
68    let schema = schemars::schema_for!(FocusedReview);
69    let mut schema_value = serde_json::to_value(schema).unwrap_or(Value::Null);
70
71    inject_additional_properties_false(&mut schema_value);
72
73    stringify_schema_json(&schema_value)
74}
75
76/// Returns the self-descriptive JSON Schema for the response payload.
77///
78/// This preserves the raw `schemars` output, including metadata such as
79/// `title` and `description`, so prompt templates can show models the richest
80/// possible schema contract.
81fn agent_response_json_schema() -> Value {
82    let schema = schemars::schema_for!(AgentResponse);
83    let mut schema_value = serde_json::to_value(schema).unwrap_or(Value::Null);
84
85    inject_dynamic_schema_guidance(&mut schema_value);
86    inject_additional_properties_false(&mut schema_value);
87    inject_minimum_required_protocol_key(&mut schema_value);
88
89    schema_value
90}
91
92/// Injects dynamic prompt guidance that depends on runtime constants into the
93/// schema metadata shown to providers.
94fn inject_dynamic_schema_guidance(schema: &mut Value) {
95    let Some(properties) = schema.get_mut("properties").and_then(Value::as_object_mut) else {
96        return;
97    };
98
99    for (property_name, description) in [
100        ("questions", questions_field_description()),
101        ("subtasks", subtasks_field_description()),
102    ] {
103        let Some(property) = properties
104            .get_mut(property_name)
105            .and_then(Value::as_object_mut)
106        else {
107            continue;
108        };
109
110        property.insert("description".to_string(), Value::String(description));
111    }
112}
113
114/// Recursively injects `additionalProperties: false` into every schema object
115/// that declares `properties` and does not already set `additionalProperties`.
116///
117/// The wire-format structs omit `#[serde(deny_unknown_fields)]` so
118/// deserialization tolerates extra fields that LLM providers sometimes add.
119/// This function restores the `additionalProperties: false` constraint in the
120/// generated JSON Schema so prompt-level guidance still tells models not to
121/// add extra fields. Pre-existing `additionalProperties` values (e.g. on
122/// map-like schema fields) are preserved.
123fn inject_additional_properties_false(value: &mut Value) {
124    match value {
125        Value::Object(object) => {
126            if object.contains_key("properties") && !object.contains_key("additionalProperties") {
127                object.insert("additionalProperties".to_string(), Value::Bool(false));
128            }
129
130            for nested_value in object.values_mut() {
131                inject_additional_properties_false(nested_value);
132            }
133        }
134        Value::Array(array) => {
135            for nested_value in array {
136                inject_additional_properties_false(nested_value);
137            }
138        }
139        _ => {}
140    }
141}
142
143/// Ensures the top-level `required` array includes `answer` so the prompt
144/// schema rejects `{}` the same way the parser does.
145///
146/// The parser requires at least one recognized protocol key. The schema is
147/// intentionally stricter: it
148/// requires `answer` specifically, because models should always include it.
149/// If a model omits `answer` but includes another recognized key, the
150/// parser still accepts the payload gracefully thanks to `#[serde(default)]`.
151fn inject_minimum_required_protocol_key(schema: &mut Value) {
152    let Some(object) = schema.as_object_mut() else {
153        return;
154    };
155
156    let required = object
157        .entry("required")
158        .or_insert_with(|| Value::Array(Vec::new()));
159
160    let Some(required_array) = required.as_array_mut() else {
161        return;
162    };
163
164    let already_listed = required_array
165        .iter()
166        .any(|value| value.as_str() == Some("answer"));
167
168    if !already_listed {
169        required_array.push(Value::String("answer".to_string()));
170    }
171}
172
173/// Normalizes one schema tree for transport-level provider compatibility.
174///
175/// Claude rejects schemas with a top-level `$schema` URI when its validator
176/// cannot resolve that meta-schema. Codex rejects schemas that use `oneOf` for
177/// enum-like constants. Schemars can emit both shapes, so this normalizer
178/// strips transport-only metadata and rewrites enum fragments to string `enum`
179/// definitions. `required_policy` decides whether optional properties are also
180/// forced into `required`.
181fn normalize_schema_for_transport(value: &mut Value, required_policy: SchemaRequiredPolicy) {
182    match value {
183        Value::Object(object) => {
184            object.remove("$schema");
185
186            for nested_value in object.values_mut() {
187                normalize_schema_for_transport(nested_value, required_policy);
188            }
189
190            normalize_ref_object_for_codex(object);
191            if required_policy == SchemaRequiredPolicy::AllProperties {
192                normalize_required_for_codex(object);
193            }
194
195            let one_of_values = object
196                .get("oneOf")
197                .and_then(Value::as_array)
198                .map(|items| {
199                    items
200                        .iter()
201                        .filter_map(Value::as_object)
202                        .map(|item| item.get("const").and_then(Value::as_str))
203                        .collect::<Option<Vec<_>>>()
204                })
205                .map(|option| {
206                    option.map(|values| {
207                        values
208                            .into_iter()
209                            .map(ToString::to_string)
210                            .collect::<Vec<_>>()
211                    })
212                });
213
214            if let Some(Some(enum_variants)) = one_of_values {
215                object.remove("oneOf");
216                object.insert("type".to_string(), Value::String("string".to_string()));
217                object.insert(
218                    "enum".to_string(),
219                    Value::Array(enum_variants.into_iter().map(Value::String).collect()),
220                );
221            }
222        }
223        Value::Array(array) => {
224            for nested_value in array {
225                normalize_schema_for_transport(nested_value, required_policy);
226            }
227        }
228        _ => {}
229    }
230}
231
232/// Rewrites one `$ref` schema object to Codex-compatible form.
233///
234/// Codex rejects sibling keywords alongside `$ref` (for example
235/// `{ "$ref": "...", "description": "..." }`), so this keeps only the
236/// reference key when present.
237fn normalize_ref_object_for_codex(object: &mut serde_json::Map<String, Value>) {
238    let Some(reference) = object.get("$ref").cloned() else {
239        return;
240    };
241
242    object.clear();
243    object.insert("$ref".to_string(), reference);
244}
245
246/// Ensures all `properties` keys appear in `required` for Codex compatibility.
247///
248/// Codex rejects schemas where `properties` contains keys not listed in
249/// `required`. Schemars omits optional fields from `required`, so this
250/// normalizer adds any missing property keys.
251fn normalize_required_for_codex(object: &mut serde_json::Map<String, Value>) {
252    let Some(properties) = object.get("properties").and_then(Value::as_object) else {
253        return;
254    };
255
256    let property_keys: Vec<String> = properties.keys().cloned().collect();
257    if property_keys.is_empty() {
258        return;
259    }
260
261    let required = object
262        .entry("required")
263        .or_insert_with(|| Value::Array(Vec::new()));
264
265    let Some(required_array) = required.as_array_mut() else {
266        return;
267    };
268
269    for key in &property_keys {
270        let already_listed = required_array
271            .iter()
272            .any(|value| value.as_str() == Some(key));
273
274        if !already_listed {
275            required_array.push(Value::String(key.clone()));
276        }
277    }
278}
279
280/// Pretty-prints one schema document for prompt or transport wiring.
281fn stringify_schema_json(schema: &Value) -> String {
282    serde_json::to_string_pretty(schema).unwrap_or("null".to_string())
283}
284
285#[cfg(test)]
286mod tests {
287    use super::*;
288
289    #[test]
290    /// Builds a schema object with required top-level response fields.
291    fn test_agent_response_output_schema_contains_required_fields() {
292        // Arrange / Act
293        let schema = agent_response_output_schema(SchemaRequiredPolicy::AllProperties);
294        let required_fields = schema
295            .get("required")
296            .and_then(Value::as_array)
297            .expect("schema required fields should exist");
298        let properties = schema
299            .get("properties")
300            .and_then(Value::as_object)
301            .expect("schema properties should exist");
302
303        // Assert
304        assert!(
305            required_fields
306                .iter()
307                .any(|value| value.as_str() == Some("answer"))
308        );
309        assert!(
310            required_fields
311                .iter()
312                .any(|value| value.as_str() == Some("questions"))
313        );
314        assert!(
315            required_fields
316                .iter()
317                .any(|value| value.as_str() == Some("review_comment_outcomes"))
318        );
319        assert!(
320            required_fields
321                .iter()
322                .any(|value| value.as_str() == Some("subtasks"))
323        );
324        assert!(properties.contains_key("answer"));
325        assert!(properties.contains_key("questions"));
326        assert!(properties.contains_key("review_comment_outcomes"));
327        assert!(properties.contains_key("subtasks"));
328    }
329
330    #[test]
331    /// Leaves a schema untouched when a guidance-carrying property is absent,
332    /// so injection cannot panic or invent properties for partial schemas.
333    fn test_inject_dynamic_schema_guidance_skips_absent_properties() {
334        // Arrange
335        let mut schema = serde_json::json!({
336            "properties": {
337                "answer": { "type": "string" }
338            }
339        });
340
341        // Act
342        inject_dynamic_schema_guidance(&mut schema);
343
344        // Assert
345        assert_eq!(
346            schema,
347            serde_json::json!({
348                "properties": {
349                    "answer": { "type": "string" }
350                }
351            })
352        );
353    }
354
355    #[test]
356    /// Routes the `subtasks` schema description through the shared template
357    /// helper so the prompt-visible cap cannot drift from the parser cap.
358    fn test_agent_response_json_schema_injects_subtasks_description() {
359        // Arrange / Act
360        let schema = agent_response_json_schema();
361        let response_properties = schema
362            .get("properties")
363            .and_then(Value::as_object)
364            .expect("response properties should exist");
365        let subtask_properties = schema_definition_properties(&schema, "SubtaskItem");
366
367        // Assert
368        assert_eq!(
369            response_properties
370                .get("subtasks")
371                .and_then(|value| value.get("description"))
372                .and_then(Value::as_str),
373            Some(subtasks_field_description().as_str())
374        );
375        assert!(subtask_properties.contains_key("prompt"));
376        assert!(subtask_properties.contains_key("kind"));
377        assert!(subtask_properties.contains_key("task_key"));
378        assert!(subtask_properties.contains_key("title"));
379        assert!(subtask_properties.contains_key("touched_areas"));
380    }
381
382    #[test]
383    /// Ensures all transport schema object properties are listed in
384    /// `required`.
385    fn test_agent_response_output_schema_all_properties_are_required() {
386        // Arrange / Act
387        let schema = agent_response_output_schema(SchemaRequiredPolicy::AllProperties);
388
389        // Assert
390        assert!(
391            all_properties_in_required(&schema),
392            "every object with `properties` should list all keys in `required`"
393        );
394    }
395
396    #[test]
397    /// Ensures the minimum-key policy demands only `answer`, so validators that
398    /// enforce `required` literally still accept replies that omit optional
399    /// protocol keys.
400    fn test_agent_response_output_schema_minimum_policy_requires_only_answer() {
401        // Arrange / Act
402        let schema = agent_response_output_schema(SchemaRequiredPolicy::MinimumProtocolKeys);
403        let required_fields = schema
404            .get("required")
405            .and_then(Value::as_array)
406            .expect("schema required fields should exist");
407
408        // Assert
409        assert_eq!(
410            required_fields,
411            &vec![Value::String("answer".to_string())],
412            "only `answer` should be required; demanding optional response fields rejects \
413             ordinary replies that omit them"
414        );
415    }
416
417    #[test]
418    /// Ensures generated schema avoids `oneOf` so Codex `outputSchema`
419    /// validation accepts the payload.
420    fn test_agent_response_output_schema_does_not_contain_one_of() {
421        // Arrange / Act
422        let schema = agent_response_output_schema(SchemaRequiredPolicy::AllProperties);
423
424        // Assert
425        assert!(!contains_schema_key(&schema, "oneOf"));
426    }
427
428    #[test]
429    /// Ensures generated transport schemas omit `$schema` metadata so Claude
430    /// native schema validation does not need a bundled meta-schema resolver.
431    fn test_agent_response_output_schema_does_not_contain_schema_metadata() {
432        // Arrange / Act
433        let schema = agent_response_output_schema(SchemaRequiredPolicy::MinimumProtocolKeys);
434
435        // Assert
436        assert!(!contains_schema_key(&schema, "$schema"));
437    }
438
439    #[test]
440    /// Ensures the prompt schema requires `answer` so empty objects are
441    /// rejected by schema validation the same way the parser rejects them.
442    fn test_agent_response_json_schema_requires_answer_key() {
443        // Arrange / Act
444        let schema = agent_response_json_schema();
445        let required_fields = schema
446            .get("required")
447            .and_then(Value::as_array)
448            .expect("schema required fields should exist");
449
450        // Assert
451        assert!(
452            required_fields
453                .iter()
454                .any(|value| value.as_str() == Some("answer")),
455            "prompt schema should require `answer` to align with parser key-presence check"
456        );
457    }
458
459    #[test]
460    /// Ensures every schema object with `properties` declares
461    /// `additionalProperties: false` so prompt guidance and transport
462    /// enforcement tell models not to add extra fields.
463    fn test_agent_response_json_schema_sets_additional_properties_false() {
464        // Arrange / Act
465        let schema = agent_response_json_schema();
466
467        // Assert
468        assert!(
469            all_properties_objects_deny_additional(&schema),
470            "every object with `properties` should set `additionalProperties: false`"
471        );
472    }
473
474    #[test]
475    /// `inject_additional_properties_false` preserves a pre-existing
476    /// `additionalProperties` value instead of overwriting it.
477    fn test_inject_additional_properties_false_preserves_existing_value() {
478        // Arrange
479        let mut schema = serde_json::json!({
480            "type": "object",
481            "properties": {
482                "extra": { "type": "object", "additionalProperties": { "type": "string" } }
483            }
484        });
485
486        // Act
487        inject_additional_properties_false(&mut schema);
488
489        // Assert - top-level gets injected (was absent)
490        assert_eq!(schema["additionalProperties"], Value::Bool(false));
491        // Assert - nested keeps its original map-type constraint (was present)
492        assert_eq!(
493            schema["properties"]["extra"]["additionalProperties"],
494            serde_json::json!({ "type": "string" })
495        );
496    }
497
498    #[test]
499    /// Ensures no schema object uses `$ref` with sibling keys.
500    fn test_agent_response_output_schema_ref_objects_have_no_sibling_keywords() {
501        // Arrange / Act
502        let schema = agent_response_output_schema(SchemaRequiredPolicy::AllProperties);
503
504        // Assert
505        assert!(!contains_ref_with_sibling_keywords(&schema));
506    }
507
508    #[test]
509    /// Exposes a parseable pretty JSON schema string for prompt templating.
510    fn test_agent_response_json_schema_json_is_parseable_value() {
511        // Arrange / Act
512        let schema_json = agent_response_json_schema_json();
513        let parsed_schema: Value =
514            serde_json::from_str(&schema_json).expect("schema string should parse as JSON");
515        let schema_value = agent_response_json_schema();
516
517        // Assert
518        assert_eq!(parsed_schema, schema_value);
519    }
520
521    #[test]
522    fn focused_review_json_schema_describes_structured_findings() {
523        // Arrange / Act
524        let schema_json = focused_review_json_schema_json();
525        let schema: Value =
526            serde_json::from_str(&schema_json).expect("focused review schema should parse");
527        let properties = schema
528            .get("properties")
529            .and_then(Value::as_object)
530            .expect("focused review properties should exist");
531        let suggestion_properties =
532            schema_definition_properties(&schema, "FocusedReviewSuggestion");
533
534        // Assert
535        assert_eq!(
536            schema.get("title").and_then(Value::as_str),
537            Some("FocusedReview")
538        );
539        assert_eq!(
540            schema.get("additionalProperties"),
541            Some(&Value::Bool(false))
542        );
543        assert!(properties.contains_key("project_impact"));
544        assert!(properties.contains_key("suggestions"));
545        assert_eq!(
546            suggestion_properties.get("additionalProperties"),
547            None,
548            "definition properties should contain only fields"
549        );
550        assert!(suggestion_properties.contains_key("details"));
551        assert!(suggestion_properties.contains_key("severity"));
552        assert_eq!(
553            schema["$defs"]["FocusedReviewSuggestion"]["additionalProperties"],
554            Value::Bool(false)
555        );
556    }
557
558    #[test]
559    /// Keeps response schemas self-descriptive so inline schema docs include
560    /// explicit top-level `schemars` metadata.
561    fn test_agent_response_json_schema_preserves_explicit_payload_metadata() {
562        // Arrange / Act
563        let schema = agent_response_json_schema();
564
565        // Assert
566        assert_eq!(
567            schema.get("title").and_then(Value::as_str),
568            Some("AgentResponse")
569        );
570        assert_eq!(
571            schema.get("description").and_then(Value::as_str),
572            Some(
573                "Wire-format protocol payload used for schema-driven provider output. Return this \
574                 object as the entire assistant response payload. Providers that support output \
575                 schemas (for example, Codex app-server) are asked to emit this object directly."
576            )
577        );
578    }
579
580    #[test]
581    /// Keeps nested response-schema models self-descriptive for inline docs.
582    fn test_agent_response_json_schema_preserves_nested_metadata() {
583        // Arrange / Act
584        let schema = agent_response_json_schema();
585        let question_definition = schema
586            .get("$defs")
587            .and_then(|value| value.get("QuestionItem"))
588            .and_then(Value::as_object)
589            .expect("question definition should exist");
590        let review_comment_outcome_definition = schema
591            .get("$defs")
592            .and_then(|value| value.get("ReviewCommentOutcome"))
593            .and_then(Value::as_object)
594            .expect("review comment outcome definition should exist");
595        let review_comment_resolution_definition = schema
596            .get("$defs")
597            .and_then(|value| value.get("ReviewCommentResolution"))
598            .and_then(Value::as_object)
599            .expect("review comment resolution definition should exist");
600
601        // Assert
602        assert_eq!(
603            question_definition.get("title").and_then(Value::as_str),
604            Some("QuestionItem")
605        );
606        assert_eq!(
607            review_comment_outcome_definition
608                .get("title")
609                .and_then(Value::as_str),
610            Some("ReviewCommentOutcome")
611        );
612        assert_eq!(
613            review_comment_resolution_definition
614                .get("title")
615                .and_then(Value::as_str),
616            Some("ReviewCommentResolution")
617        );
618    }
619
620    #[test]
621    /// Keeps response-schema fields self-descriptive for inline schema docs.
622    fn test_agent_response_json_schema_preserves_field_metadata() {
623        // Arrange / Act
624        let schema = agent_response_json_schema();
625        let response_properties = schema
626            .get("properties")
627            .and_then(Value::as_object)
628            .expect("response properties should exist");
629        let question_properties = schema_definition_properties(&schema, "QuestionItem");
630        let review_comment_outcome_properties =
631            schema_definition_properties(&schema, "ReviewCommentOutcome");
632        let expected_questions_description = questions_field_description();
633
634        // Assert
635        assert_schema_property_title_and_description(
636            response_properties,
637            "answer",
638            "answer",
639            "Markdown answer text for delivered work, status updates, or concise completion \
640             notes. Keep clarification requests out of this field and emit them through \
641             `questions` instead.",
642        );
643        assert_eq!(
644            response_properties
645                .get("questions")
646                .and_then(|value| value.get("description"))
647                .and_then(Value::as_str),
648            Some(expected_questions_description.as_str())
649        );
650        assert_schema_property_title_and_description(
651            response_properties,
652            "review_comment_outcomes",
653            "review_comment_outcomes",
654            "Per-thread outcomes for an agent-driven forge comment-resolution turn. Emit an empty \
655             array unless the prompt explicitly supplies forge thread IDs. Copy each reported \
656             `thread_id` exactly from the prompt.",
657        );
658        assert_schema_property_title_and_description(
659            question_properties,
660            "text",
661            "text",
662            "Human-readable markdown text for this question. Ask one specific actionable question \
663             instead of bundling multiple decisions into one item.",
664        );
665        assert_schema_property_title(question_properties, "options", "options");
666        assert_schema_property_title_and_description(
667            review_comment_outcome_properties,
668            "reply",
669            "reply",
670            "Concise reply suitable for posting to the forge review thread.",
671        );
672        assert_schema_property_title_and_description(
673            review_comment_outcome_properties,
674            "resolution",
675            "resolution",
676            "Whether the targeted thread was fixed or required no change.",
677        );
678        assert_schema_property_title_and_description(
679            review_comment_outcome_properties,
680            "thread_id",
681            "thread_id",
682            "Opaque forge thread identifier copied exactly from the turn prompt.",
683        );
684    }
685
686    #[test]
687    /// Preserves optional prompt fields in the raw schema instead of forcing
688    /// transport-only requirements into prompt docs.
689    fn test_agent_response_json_schema_keeps_optional_question_options() {
690        // Arrange / Act
691        let schema = agent_response_json_schema();
692        let question_definition = schema
693            .get("$defs")
694            .and_then(|value| value.get("QuestionItem"))
695            .and_then(Value::as_object)
696            .expect("question definition should exist");
697        let question_required_fields = question_definition
698            .get("required")
699            .and_then(Value::as_array)
700            .cloned()
701            .unwrap_or_default();
702
703        // Assert
704        assert!(
705            question_required_fields
706                .iter()
707                .all(|field| field.as_str() != Some("options")),
708            "question schema should keep `options` optional for omitted empty lists"
709        );
710    }
711
712    #[test]
713    /// Exposes a parseable pretty JSON schema string for transport-level
714    /// schema enforcement.
715    fn test_agent_response_output_schema_json_is_parseable_value() {
716        // Arrange / Act
717        let schema_json =
718            agent_response_output_schema_json(SchemaRequiredPolicy::MinimumProtocolKeys);
719        let parsed_schema: Value =
720            serde_json::from_str(&schema_json).expect("schema string should parse as JSON");
721        let schema_value = agent_response_output_schema(SchemaRequiredPolicy::MinimumProtocolKeys);
722
723        // Assert
724        assert_eq!(parsed_schema, schema_value);
725    }
726
727    /// Recursively checks whether one JSON value tree contains a schema key.
728    fn contains_schema_key(value: &Value, key: &str) -> bool {
729        match value {
730            Value::Object(object) => {
731                if object.contains_key(key) {
732                    return true;
733                }
734
735                object
736                    .values()
737                    .any(|nested_value| contains_schema_key(nested_value, key))
738            }
739            Value::Array(array) => array
740                .iter()
741                .any(|nested_value| contains_schema_key(nested_value, key)),
742            _ => false,
743        }
744    }
745
746    /// Recursively checks whether any `$ref` object has extra sibling keys.
747    fn contains_ref_with_sibling_keywords(value: &Value) -> bool {
748        match value {
749            Value::Object(object) => {
750                if object.contains_key("$ref") && object.len() > 1 {
751                    return true;
752                }
753
754                object.values().any(contains_ref_with_sibling_keywords)
755            }
756            Value::Array(array) => array.iter().any(contains_ref_with_sibling_keywords),
757            _ => false,
758        }
759    }
760
761    /// Recursively checks that every object with `properties` lists all
762    /// property keys in `required`.
763    fn all_properties_in_required(value: &Value) -> bool {
764        match value {
765            Value::Object(object) => {
766                if let Some(properties) = object.get("properties").and_then(Value::as_object) {
767                    let required_keys: Vec<&str> = object
768                        .get("required")
769                        .and_then(Value::as_array)
770                        .map(|array| array.iter().filter_map(Value::as_str).collect())
771                        .unwrap_or_default();
772
773                    for key in properties.keys() {
774                        if !required_keys.contains(&key.as_str()) {
775                            return false;
776                        }
777                    }
778                }
779
780                object.values().all(all_properties_in_required)
781            }
782            Value::Array(array) => array.iter().all(all_properties_in_required),
783            _ => true,
784        }
785    }
786
787    /// Recursively checks that every object with `properties` sets
788    /// `additionalProperties: false`.
789    fn all_properties_objects_deny_additional(value: &Value) -> bool {
790        match value {
791            Value::Object(object) => {
792                if object.contains_key("properties")
793                    && object.get("additionalProperties") != Some(&Value::Bool(false))
794                {
795                    return false;
796                }
797
798                object.values().all(all_properties_objects_deny_additional)
799            }
800            Value::Array(array) => array.iter().all(all_properties_objects_deny_additional),
801            _ => true,
802        }
803    }
804
805    /// Returns the properties object for one named schema definition.
806    fn schema_definition_properties<'a>(
807        schema: &'a Value,
808        definition_name: &str,
809    ) -> &'a serde_json::Map<String, Value> {
810        schema
811            .get("$defs")
812            .and_then(|value| value.get(definition_name))
813            .and_then(|value| value.get("properties"))
814            .and_then(Value::as_object)
815            .expect("schema definition properties should exist")
816    }
817
818    /// Asserts one property schema has the expected `title`.
819    fn assert_schema_property_title(
820        properties: &serde_json::Map<String, Value>,
821        property_name: &str,
822        expected_title: &str,
823    ) {
824        assert_eq!(
825            properties
826                .get(property_name)
827                .and_then(|value| value.get("title"))
828                .and_then(Value::as_str),
829            Some(expected_title)
830        );
831    }
832
833    /// Asserts one property schema has the expected `title` and
834    /// `description`.
835    fn assert_schema_property_title_and_description(
836        properties: &serde_json::Map<String, Value>,
837        property_name: &str,
838        expected_title: &str,
839        expected_description: &str,
840    ) {
841        assert_schema_property_title(properties, property_name, expected_title);
842        assert_eq!(
843            properties
844                .get(property_name)
845                .and_then(|value| value.get("description"))
846                .and_then(Value::as_str),
847            Some(expected_description)
848        );
849    }
850}