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