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 {
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
76fn 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
92fn 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
114fn 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
143fn 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
173fn 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
232fn 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
246fn 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
280fn 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 fn test_agent_response_output_schema_contains_required_fields() {
292 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!(
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 fn test_inject_dynamic_schema_guidance_skips_absent_properties() {
334 let mut schema = serde_json::json!({
336 "properties": {
337 "answer": { "type": "string" }
338 }
339 });
340
341 inject_dynamic_schema_guidance(&mut schema);
343
344 assert_eq!(
346 schema,
347 serde_json::json!({
348 "properties": {
349 "answer": { "type": "string" }
350 }
351 })
352 );
353 }
354
355 #[test]
356 fn test_agent_response_json_schema_injects_subtasks_description() {
359 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_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 fn test_agent_response_output_schema_all_properties_are_required() {
386 let schema = agent_response_output_schema(SchemaRequiredPolicy::AllProperties);
388
389 assert!(
391 all_properties_in_required(&schema),
392 "every object with `properties` should list all keys in `required`"
393 );
394 }
395
396 #[test]
397 fn test_agent_response_output_schema_minimum_policy_requires_only_answer() {
401 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_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 fn test_agent_response_output_schema_does_not_contain_one_of() {
421 let schema = agent_response_output_schema(SchemaRequiredPolicy::AllProperties);
423
424 assert!(!contains_schema_key(&schema, "oneOf"));
426 }
427
428 #[test]
429 fn test_agent_response_output_schema_does_not_contain_schema_metadata() {
432 let schema = agent_response_output_schema(SchemaRequiredPolicy::MinimumProtocolKeys);
434
435 assert!(!contains_schema_key(&schema, "$schema"));
437 }
438
439 #[test]
440 fn test_agent_response_json_schema_requires_answer_key() {
443 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!(
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 fn test_agent_response_json_schema_sets_additional_properties_false() {
464 let schema = agent_response_json_schema();
466
467 assert!(
469 all_properties_objects_deny_additional(&schema),
470 "every object with `properties` should set `additionalProperties: false`"
471 );
472 }
473
474 #[test]
475 fn test_inject_additional_properties_false_preserves_existing_value() {
478 let mut schema = serde_json::json!({
480 "type": "object",
481 "properties": {
482 "extra": { "type": "object", "additionalProperties": { "type": "string" } }
483 }
484 });
485
486 inject_additional_properties_false(&mut schema);
488
489 assert_eq!(schema["additionalProperties"], Value::Bool(false));
491 assert_eq!(
493 schema["properties"]["extra"]["additionalProperties"],
494 serde_json::json!({ "type": "string" })
495 );
496 }
497
498 #[test]
499 fn test_agent_response_output_schema_ref_objects_have_no_sibling_keywords() {
501 let schema = agent_response_output_schema(SchemaRequiredPolicy::AllProperties);
503
504 assert!(!contains_ref_with_sibling_keywords(&schema));
506 }
507
508 #[test]
509 fn test_agent_response_json_schema_json_is_parseable_value() {
511 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_eq!(parsed_schema, schema_value);
519 }
520
521 #[test]
522 fn focused_review_json_schema_describes_structured_findings() {
523 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_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 fn test_agent_response_json_schema_preserves_explicit_payload_metadata() {
562 let schema = agent_response_json_schema();
564
565 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 fn test_agent_response_json_schema_preserves_nested_metadata() {
583 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_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 fn test_agent_response_json_schema_preserves_field_metadata() {
623 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_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 fn test_agent_response_json_schema_keeps_optional_question_options() {
690 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!(
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 fn test_agent_response_output_schema_json_is_parseable_value() {
716 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_eq!(parsed_schema, schema_value);
725 }
726
727 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 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 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 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 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 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 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}