1use serde_json::Value;
5
6use super::model::{AgentResponse, questions_field_description, subtasks_field_description};
7use super::review::FocusedReview;
8
9#[derive(Clone, Copy, Debug, Eq, PartialEq)]
18pub enum SchemaRequiredPolicy {
19 AllProperties,
21 MinimumProtocolKeys,
23}
24
25pub 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
38pub fn agent_response_json_schema_json() -> String {
44 let schema = agent_response_json_schema();
45
46 stringify_schema_json(&schema)
47}
48
49pub 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
60pub fn focused_review_json_schema_json() -> String {
66 let schema_value = focused_review_json_schema();
67
68 stringify_schema_json(&schema_value)
69}
70
71pub 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
80pub 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
92pub(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
101fn 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
111fn 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
127fn 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
149fn 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
180fn 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
210fn 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
269fn 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
283fn 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
317fn 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 fn test_agent_response_output_schema_contains_required_fields() {
329 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!(
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 fn test_inject_dynamic_schema_guidance_skips_absent_properties() {
371 let mut schema = serde_json::json!({
373 "properties": {
374 "answer": { "type": "string" }
375 }
376 });
377
378 inject_dynamic_schema_guidance(&mut schema);
380
381 assert_eq!(
383 schema,
384 serde_json::json!({
385 "properties": {
386 "answer": { "type": "string" }
387 }
388 })
389 );
390 }
391
392 #[test]
393 fn test_agent_response_json_schema_injects_subtasks_description() {
396 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_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 fn test_agent_response_output_schema_all_properties_are_required() {
423 let schema = agent_response_output_schema(SchemaRequiredPolicy::AllProperties);
425
426 assert!(
428 all_properties_in_required(&schema),
429 "every object with `properties` should list all keys in `required`"
430 );
431 }
432
433 #[test]
434 fn test_agent_response_output_schema_minimum_policy_requires_only_answer() {
438 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_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 fn test_agent_response_output_schema_does_not_contain_one_of() {
458 let schema = agent_response_output_schema(SchemaRequiredPolicy::AllProperties);
460
461 assert!(!contains_schema_key(&schema, "oneOf"));
463 }
464
465 #[test]
466 fn test_agent_response_output_schema_does_not_contain_schema_metadata() {
469 let schema = agent_response_output_schema(SchemaRequiredPolicy::MinimumProtocolKeys);
471
472 assert!(!contains_schema_key(&schema, "$schema"));
474 }
475
476 #[test]
477 fn test_agent_response_json_schema_requires_answer_key() {
480 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!(
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 fn test_agent_response_json_schema_sets_additional_properties_false() {
501 let schema = agent_response_json_schema();
503
504 assert!(
506 all_properties_objects_deny_additional(&schema),
507 "every object with `properties` should set `additionalProperties: false`"
508 );
509 }
510
511 #[test]
512 fn test_inject_additional_properties_false_preserves_existing_value() {
515 let mut schema = serde_json::json!({
517 "type": "object",
518 "properties": {
519 "extra": { "type": "object", "additionalProperties": { "type": "string" } }
520 }
521 });
522
523 inject_additional_properties_false(&mut schema);
525
526 assert_eq!(schema["additionalProperties"], Value::Bool(false));
528 assert_eq!(
530 schema["properties"]["extra"]["additionalProperties"],
531 serde_json::json!({ "type": "string" })
532 );
533 }
534
535 #[test]
536 fn test_agent_response_output_schema_ref_objects_have_no_sibling_keywords() {
538 let schema = agent_response_output_schema(SchemaRequiredPolicy::AllProperties);
540
541 assert!(!contains_ref_with_sibling_keywords(&schema));
543 }
544
545 #[test]
546 fn test_agent_response_json_schema_json_is_parseable_value() {
548 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_eq!(parsed_schema, schema_value);
556 }
557
558 #[test]
559 fn focused_review_json_schema_describes_structured_findings() {
560 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_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 let schema = focused_review_output_schema();
599
600 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 fn test_agent_response_json_schema_preserves_explicit_payload_metadata() {
614 let schema = agent_response_json_schema();
616
617 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 fn test_agent_response_json_schema_preserves_nested_metadata() {
635 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_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 fn test_agent_response_json_schema_preserves_field_metadata() {
675 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_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 fn test_agent_response_json_schema_keeps_optional_question_options() {
742 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!(
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 fn test_agent_response_output_schema_json_is_parseable_value() {
768 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_eq!(parsed_schema, schema_value);
777 }
778
779 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 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 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 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 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 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 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}