1use serde::{Deserialize, Serialize};
30use serde_json::Value;
31
32use crate::schema::Kind;
33
34pub const REPORT_ORIGIN_KEY: &str = "origin";
37
38pub const VIA_EXPLICIT_MERGE: &str = "explicit-merge";
49
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74#[serde(tag = "kind", rename_all = "kebab-case")]
75pub enum ReportOrigin {
76 Agent,
79 Supervisor,
82 RunMerge {
89 #[serde(default, skip_serializing_if = "Option::is_none")]
91 op_id: Option<String>,
92 #[serde(default, skip_serializing_if = "Option::is_none")]
94 worker_oid: Option<String>,
95 #[serde(default, skip_serializing_if = "Option::is_none")]
98 integrated_oid: Option<String>,
99 },
100}
101
102impl ReportOrigin {
103 #[must_use]
117 pub fn from_report(report: &Value) -> Option<Self> {
118 let raw = report.get(REPORT_ORIGIN_KEY)?;
119 serde_json::from_value(raw.clone()).ok()
120 }
121
122 #[must_use]
146 pub fn report_is_confirmed_merge(report: &Value) -> bool {
147 let success = matches!(report.get("success"), Some(Value::Bool(true)));
148 let not_cancelled = matches!(
149 report.get("cancelled"),
150 None | Some(Value::Null | Value::Bool(false))
151 );
152 if !(success && not_cancelled) {
153 return false;
154 }
155 let is_run_merge_origin = matches!(
158 Self::from_report(report),
159 Some(ReportOrigin::RunMerge { .. })
160 );
161 let origin_present = report.get(REPORT_ORIGIN_KEY).is_some();
162 let legacy_via_merge = !origin_present
163 && report.get("via").and_then(Value::as_str) == Some(VIA_EXPLICIT_MERGE);
164 is_run_merge_origin || legacy_via_merge
165 }
166
167 #[must_use]
175 pub fn permits_terminal_merge_recovery(status: crate::Status, report: &Value) -> bool {
176 matches!(status, crate::Status::Failed | crate::Status::Done)
177 && Self::report_is_confirmed_merge(report)
178 }
179
180 pub fn stamp(&self, report: &mut Value) {
185 if let Some(obj) = report.as_object_mut() {
186 if let Ok(v) = serde_json::to_value(self) {
189 obj.insert(REPORT_ORIGIN_KEY.to_string(), v);
190 }
191 }
192 }
193}
194
195#[derive(Debug, thiserror::Error)]
201pub enum ReportValidationError {
202 #[error("report payload must be a JSON object")]
204 NotObject,
205
206 #[error("report payload missing required field `success`")]
208 MissingSuccess,
209
210 #[error("field `success` must be a boolean")]
212 SuccessNotBoolean,
213
214 #[error("field `summary` must be a string")]
216 SummaryNotString,
217
218 #[error("field `cancelled` must be a boolean")]
220 CancelledNotBoolean,
221
222 #[error("field `reason` must be a string")]
224 ReasonNotString,
225
226 #[error("`cancelled: true` requires `success: false`")]
228 CancelledRequiresSuccessFalse,
229
230 #[error("`cancelled: true` requires a non-empty `reason` string")]
232 CancelledRequiresReason,
233
234 #[error("field `discussion_items` must be an array")]
236 DiscussionItemsNotArray,
237
238 #[error("discussion_items[{index}] must be a JSON object")]
240 DiscussionItemNotObject {
241 index: usize,
243 },
244
245 #[error("discussion_items[{index}].topic must be a non-empty string")]
247 DiscussionItemTopicMissing {
248 index: usize,
250 },
251
252 #[error("discussion_items[{index}].severity must be a string")]
254 DiscussionItemSeverityNotString {
255 index: usize,
257 },
258
259 #[error("field `spinoff_proposals` must be an array")]
261 SpinoffProposalsNotArray,
262
263 #[error("spinoff_proposals[{index}] must be a JSON object")]
265 SpinoffProposalNotObject {
266 index: usize,
268 },
269
270 #[error("spinoff_proposals[{index}].proposed_title must be a non-empty string")]
272 SpinoffProposalTitleMissing {
273 index: usize,
275 },
276
277 #[error("spinoff_proposals[{index}].proposed_kind must be a string")]
279 SpinoffProposalKindNotString {
280 index: usize,
282 },
283
284 #[error("spinoff_proposals[{index}].proposed_kind `{kind}` is not a known kind")]
286 SpinoffProposalKindUnknown {
287 index: usize,
289 kind: String,
291 },
292
293 #[error("spinoff_proposals[{index}].rationale must be a string")]
295 SpinoffProposalRationaleNotString {
296 index: usize,
298 },
299
300 #[error("field `{field}` must be an array")]
302 FieldNotArray {
303 field: String,
305 },
306
307 #[error("{field}[{index}] must be a string")]
309 FieldElementNotString {
310 field: String,
312 index: usize,
314 },
315
316 #[error("{path} must be an array")]
318 PathNotArray {
319 path: String,
321 },
322
323 #[error("{path}[{index}] must be a string")]
325 PathElementNotString {
326 path: String,
328 index: usize,
330 },
331}
332
333impl ReportValidationError {
334 #[must_use]
339 pub fn expected(&self) -> Option<Value> {
340 match self {
341 Self::MissingSuccess | Self::SuccessNotBoolean => {
342 Some(serde_json::json!({"field": "success", "type": "boolean"}))
343 }
344 Self::SpinoffProposalKindUnknown { .. } => Some(serde_json::json!(Kind::WIRE_NAMES)),
348 _ => None,
349 }
350 }
351}
352
353pub fn validate_report_payload(data: &Value) -> Result<(), ReportValidationError> {
365 let obj = data.as_object().ok_or(ReportValidationError::NotObject)?;
366
367 validate_required_fields(obj)?;
368
369 if let Some(v) = obj.get("summary") {
370 if !v.is_string() && !v.is_null() {
371 return Err(ReportValidationError::SummaryNotString);
372 }
373 }
374
375 validate_discussion_items(obj.get("discussion_items"))?;
376 validate_spinoff_proposals(obj.get("spinoff_proposals"))?;
377 validate_string_array(
378 obj.get("wrap_up_recommendations"),
379 "wrap_up_recommendations",
380 )?;
381 Ok(())
382}
383
384fn validate_required_fields(
389 obj: &serde_json::Map<String, Value>,
390) -> Result<(), ReportValidationError> {
391 let success = obj
395 .get("success")
396 .ok_or(ReportValidationError::MissingSuccess)?;
397 if !success.is_boolean() {
398 return Err(ReportValidationError::SuccessNotBoolean);
399 }
400
401 let cancelled = match obj.get("cancelled") {
402 None | Some(Value::Null) => false,
403 Some(v) => v
404 .as_bool()
405 .ok_or(ReportValidationError::CancelledNotBoolean)?,
406 };
407 let reason = match obj.get("reason") {
408 None | Some(Value::Null) => None,
409 Some(v) => Some(v.as_str().ok_or(ReportValidationError::ReasonNotString)?),
410 };
411
412 if cancelled {
418 if success
422 .as_bool()
423 .expect("success validated as boolean above")
424 {
425 return Err(ReportValidationError::CancelledRequiresSuccessFalse);
426 }
427 match reason {
428 Some(s) if !s.trim().is_empty() => {}
429 _ => return Err(ReportValidationError::CancelledRequiresReason),
430 }
431 }
432 Ok(())
433}
434
435fn validate_discussion_items(v: Option<&Value>) -> Result<(), ReportValidationError> {
436 let arr = match v {
437 Some(Value::Array(a)) => a,
438 Some(_) => return Err(ReportValidationError::DiscussionItemsNotArray),
439 None => return Ok(()),
440 };
441 for (i, item) in arr.iter().enumerate() {
442 validate_discussion_item(item, i)?;
443 }
444 Ok(())
445}
446
447fn validate_discussion_item(item: &Value, index: usize) -> Result<(), ReportValidationError> {
451 let obj = item
452 .as_object()
453 .ok_or(ReportValidationError::DiscussionItemNotObject { index })?;
454 let topic = obj.get("topic").and_then(Value::as_str);
455 if topic.is_none_or(|t| t.trim().is_empty()) {
456 return Err(ReportValidationError::DiscussionItemTopicMissing { index });
457 }
458 if let Some(sev) = obj.get("severity") {
459 if !sev.is_string() {
460 return Err(ReportValidationError::DiscussionItemSeverityNotString { index });
461 }
462 }
469 if let Some(opts) = obj.get("options") {
470 validate_string_array_at(opts, &format!("discussion_items[{index}].options"))?;
471 }
472 Ok(())
473}
474
475fn validate_spinoff_proposals(v: Option<&Value>) -> Result<(), ReportValidationError> {
476 let arr = match v {
477 Some(Value::Array(a)) => a,
478 Some(_) => return Err(ReportValidationError::SpinoffProposalsNotArray),
479 None => return Ok(()),
480 };
481 for (i, item) in arr.iter().enumerate() {
482 validate_spinoff_proposal(item, i)?;
483 }
484 Ok(())
485}
486
487fn validate_spinoff_proposal(item: &Value, index: usize) -> Result<(), ReportValidationError> {
493 let obj = item
494 .as_object()
495 .ok_or(ReportValidationError::SpinoffProposalNotObject { index })?;
496 let title = obj.get("proposed_title").and_then(Value::as_str);
497 if title.is_none_or(|t| t.trim().is_empty()) {
498 return Err(ReportValidationError::SpinoffProposalTitleMissing { index });
499 }
500 let kind_str = obj
501 .get("proposed_kind")
502 .and_then(Value::as_str)
503 .ok_or(ReportValidationError::SpinoffProposalKindNotString { index })?;
504 if !Kind::WIRE_NAMES.contains(&kind_str) {
512 return Err(ReportValidationError::SpinoffProposalKindUnknown {
513 index,
514 kind: kind_str.to_string(),
515 });
516 }
517 if let Some(rationale) = obj.get("rationale") {
518 if !rationale.is_string() && !rationale.is_null() {
519 return Err(ReportValidationError::SpinoffProposalRationaleNotString { index });
520 }
521 }
522 Ok(())
523}
524
525fn validate_string_array_at(v: &Value, path: &str) -> Result<(), ReportValidationError> {
528 let arr = v
529 .as_array()
530 .ok_or_else(|| ReportValidationError::PathNotArray {
531 path: path.to_string(),
532 })?;
533 for (i, item) in arr.iter().enumerate() {
534 if !item.is_string() {
535 return Err(ReportValidationError::PathElementNotString {
536 path: path.to_string(),
537 index: i,
538 });
539 }
540 }
541 Ok(())
542}
543
544fn validate_string_array(v: Option<&Value>, field: &str) -> Result<(), ReportValidationError> {
545 let arr = match v {
546 Some(Value::Array(a)) => a,
547 Some(_) => {
548 return Err(ReportValidationError::FieldNotArray {
549 field: field.to_string(),
550 })
551 }
552 None => return Ok(()),
553 };
554 for (i, item) in arr.iter().enumerate() {
555 if !item.is_string() {
556 return Err(ReportValidationError::FieldElementNotString {
557 field: field.to_string(),
558 index: i,
559 });
560 }
561 }
562 Ok(())
563}
564
565#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
575pub struct AdvisoryWarning {
576 pub field: String,
578 #[serde(skip_serializing_if = "Option::is_none")]
582 pub index: Option<usize>,
583 pub reason: String,
585}
586
587impl AdvisoryWarning {
588 #[must_use]
591 pub fn to_message(&self) -> String {
592 match self.index {
593 Some(i) => format!("dropped {}[{i}]: {}", self.field, self.reason),
594 None => format!("dropped advisory field `{}`: {}", self.field, self.reason),
595 }
596 }
597}
598
599#[derive(Debug, Clone)]
603pub struct SanitizedReport {
604 pub report: Value,
607 pub warnings: Vec<AdvisoryWarning>,
610}
611
612pub fn sanitize_report_advisory(data: &Value) -> Result<SanitizedReport, ReportValidationError> {
661 let obj = data.as_object().ok_or(ReportValidationError::NotObject)?;
662
663 validate_required_fields(obj)?;
665
666 let mut out = obj.clone();
667 let mut warnings = Vec::new();
668
669 if let Some(v) = obj.get("summary") {
671 if !v.is_string() && !v.is_null() {
672 out.remove("summary");
673 warnings.push(AdvisoryWarning {
674 field: "summary".to_string(),
675 index: None,
676 reason: ReportValidationError::SummaryNotString.to_string(),
677 });
678 }
679 }
680
681 sanitize_element_array(
682 &mut out,
683 "discussion_items",
684 ReportValidationError::DiscussionItemsNotArray,
685 validate_discussion_item,
686 &mut warnings,
687 );
688 sanitize_element_array(
689 &mut out,
690 "spinoff_proposals",
691 ReportValidationError::SpinoffProposalsNotArray,
692 validate_spinoff_proposal,
693 &mut warnings,
694 );
695 sanitize_string_array_field(&mut out, "wrap_up_recommendations", &mut warnings);
696
697 Ok(SanitizedReport {
698 report: Value::Object(out),
699 warnings,
700 })
701}
702
703fn sanitize_element_array(
709 obj: &mut serde_json::Map<String, Value>,
710 field: &str,
711 not_array_err: ReportValidationError,
712 validate: fn(&Value, usize) -> Result<(), ReportValidationError>,
713 warnings: &mut Vec<AdvisoryWarning>,
714) {
715 let Some(v) = obj.get(field) else { return };
716 let Some(arr) = v.as_array() else {
717 obj.remove(field);
718 warnings.push(AdvisoryWarning {
719 field: field.to_string(),
720 index: None,
721 reason: not_array_err.to_string(),
722 });
723 return;
724 };
725 let mut kept = Vec::with_capacity(arr.len());
726 for (i, item) in arr.iter().enumerate() {
727 match validate(item, i) {
728 Ok(()) => kept.push(item.clone()),
729 Err(e) => warnings.push(AdvisoryWarning {
730 field: field.to_string(),
731 index: Some(i),
732 reason: e.to_string(),
733 }),
734 }
735 }
736 obj.insert(field.to_string(), Value::Array(kept));
737}
738
739fn sanitize_string_array_field(
743 obj: &mut serde_json::Map<String, Value>,
744 field: &str,
745 warnings: &mut Vec<AdvisoryWarning>,
746) {
747 let Some(v) = obj.get(field) else { return };
748 let Some(arr) = v.as_array() else {
749 obj.remove(field);
750 warnings.push(AdvisoryWarning {
751 field: field.to_string(),
752 index: None,
753 reason: ReportValidationError::FieldNotArray {
754 field: field.to_string(),
755 }
756 .to_string(),
757 });
758 return;
759 };
760 let mut kept = Vec::with_capacity(arr.len());
761 for (i, item) in arr.iter().enumerate() {
762 if item.is_string() {
763 kept.push(item.clone());
764 } else {
765 warnings.push(AdvisoryWarning {
766 field: field.to_string(),
767 index: Some(i),
768 reason: ReportValidationError::FieldElementNotString {
769 field: field.to_string(),
770 index: i,
771 }
772 .to_string(),
773 });
774 }
775 }
776 obj.insert(field.to_string(), Value::Array(kept));
777}
778
779#[cfg(test)]
780mod tests {
781 use super::*;
782 use serde_json::json;
783
784 #[test]
787 fn validates_minimal_success_payload() {
788 let v = json!({"success": true});
789 assert!(validate_report_payload(&v).is_ok());
790 }
791
792 #[test]
793 fn validates_full_success_payload() {
794 let v = json!({
795 "success": true,
796 "summary": "did the thing",
797 "discussion_items": [
798 {"topic": "naming", "severity": "discuss", "options": ["a", "b"]},
799 ],
800 "spinoff_proposals": [
801 {"proposed_title": "follow-up", "proposed_kind": "spinoff", "rationale": "later"},
802 ],
803 "wrap_up_recommendations": ["rebase", "squash"],
804 });
805 assert!(validate_report_payload(&v).is_ok());
806 }
807
808 #[test]
809 fn discussion_item_unknown_severity_accepted_for_forward_compat() {
810 let v = json!({
813 "success": true,
814 "discussion_items": [{"topic": "x", "severity": "info"}],
815 });
816 assert!(validate_report_payload(&v).is_ok());
817 }
818
819 #[test]
820 fn cancel_synthesized_report_shape_ok() {
821 let v = json!({
823 "success": false,
824 "cancelled": true,
825 "reason": "cancelled by user",
826 "summary": "Run cancelled before agent reported.",
827 "discussion_items": [],
828 "spinoff_proposals": [],
829 "wrap_up_recommendations": [],
830 });
831 assert!(validate_report_payload(&v).is_ok());
832 }
833
834 #[test]
837 fn non_object_root_rejected() {
838 let v = json!([1, 2, 3]);
839 assert!(matches!(
840 validate_report_payload(&v),
841 Err(ReportValidationError::NotObject)
842 ));
843 }
844
845 #[test]
846 fn missing_success_rejected() {
847 let v = json!({"summary": "no success field"});
848 let err = validate_report_payload(&v).unwrap_err();
849 assert!(matches!(err, ReportValidationError::MissingSuccess));
850 assert_eq!(
852 err.expected(),
853 Some(json!({"field": "success", "type": "boolean"}))
854 );
855 }
856
857 #[test]
858 fn success_variants_carry_field_type_hint() {
859 let hint = Some(json!({"field": "success", "type": "boolean"}));
861 assert_eq!(ReportValidationError::MissingSuccess.expected(), hint);
862 assert_eq!(ReportValidationError::SuccessNotBoolean.expected(), hint);
863 }
864
865 #[test]
866 fn summary_must_be_string() {
867 let v = json!({"success": true, "summary": 42});
868 assert!(matches!(
869 validate_report_payload(&v),
870 Err(ReportValidationError::SummaryNotString)
871 ));
872 }
873
874 #[test]
875 fn discussion_item_options_non_array_rejected() {
876 let v = json!({
877 "success": true,
878 "discussion_items": [{"topic": "x", "options": "not-an-array"}],
879 });
880 assert!(matches!(
881 validate_report_payload(&v),
882 Err(ReportValidationError::PathNotArray { .. })
883 ));
884 }
885
886 #[test]
887 fn cancelled_requires_non_whitespace_reason() {
888 let v = json!({"success": false, "cancelled": true, "reason": " "});
889 assert!(matches!(
890 validate_report_payload(&v),
891 Err(ReportValidationError::CancelledRequiresReason)
892 ));
893 }
894
895 #[test]
896 fn non_boolean_success_rejected() {
897 let v = json!({"success": "yes"});
898 assert!(matches!(
899 validate_report_payload(&v),
900 Err(ReportValidationError::SuccessNotBoolean)
901 ));
902 }
903
904 #[test]
905 fn discussion_item_missing_topic_rejected() {
906 let v = json!({
907 "success": true,
908 "discussion_items": [{"severity": "discuss"}],
909 });
910 assert!(matches!(
911 validate_report_payload(&v),
912 Err(ReportValidationError::DiscussionItemTopicMissing { index: 0 })
913 ));
914 }
915
916 #[test]
917 fn discussion_item_non_string_severity_rejected() {
918 let v = json!({
919 "success": true,
920 "discussion_items": [{"topic": "x", "severity": 42}],
921 });
922 assert!(matches!(
923 validate_report_payload(&v),
924 Err(ReportValidationError::DiscussionItemSeverityNotString { index: 0 })
925 ));
926 }
927
928 #[test]
929 fn discussion_item_options_must_be_strings() {
930 let v = json!({
931 "success": true,
932 "discussion_items": [{"topic": "x", "options": [1, 2]}],
933 });
934 assert!(matches!(
935 validate_report_payload(&v),
936 Err(ReportValidationError::PathElementNotString { index: 0, .. })
937 ));
938 }
939
940 #[test]
941 fn spinoff_unknown_proposed_kind_rejected() {
942 let v = json!({
943 "success": true,
944 "spinoff_proposals": [{"proposed_title": "x", "proposed_kind": "not-a-kind"}],
945 });
946 let err = validate_report_payload(&v).unwrap_err();
947 assert!(matches!(
948 err,
949 ReportValidationError::SpinoffProposalKindUnknown { index: 0, .. }
950 ));
951 assert_eq!(err.expected(), Some(json!(crate::schema::Kind::WIRE_NAMES)));
954 assert_eq!(
955 err.expected(),
956 Some(json!([
957 "spinoff",
958 "research",
959 "technical-decision",
960 "fan-out"
961 ]))
962 );
963 }
964
965 #[test]
966 fn spinoff_missing_kind_rejected() {
967 let v = json!({
968 "success": true,
969 "spinoff_proposals": [{"proposed_title": "x"}],
970 });
971 assert!(matches!(
972 validate_report_payload(&v),
973 Err(ReportValidationError::SpinoffProposalKindNotString { index: 0 })
974 ));
975 }
976
977 #[test]
978 fn cancelled_requires_success_false() {
979 let v = json!({"success": true, "cancelled": true, "reason": "x"});
980 assert!(matches!(
981 validate_report_payload(&v),
982 Err(ReportValidationError::CancelledRequiresSuccessFalse)
983 ));
984 }
985
986 #[test]
987 fn cancelled_requires_reason() {
988 let v = json!({"success": false, "cancelled": true});
989 assert!(matches!(
990 validate_report_payload(&v),
991 Err(ReportValidationError::CancelledRequiresReason)
992 ));
993 }
994
995 #[test]
998 fn report_origin_round_trips_through_a_report() {
999 let cases = [
1000 ReportOrigin::Agent,
1001 ReportOrigin::Supervisor,
1002 ReportOrigin::RunMerge {
1003 op_id: Some("op-123".into()),
1004 worker_oid: Some("deadbeef".into()),
1005 integrated_oid: None,
1006 },
1007 ReportOrigin::RunMerge {
1008 op_id: None,
1009 worker_oid: None,
1010 integrated_oid: None,
1011 },
1012 ];
1013 for origin in cases {
1014 let mut report = json!({ "success": true });
1015 origin.stamp(&mut report);
1016 assert_eq!(
1017 ReportOrigin::from_report(&report),
1018 Some(origin.clone()),
1019 "round-trip: {origin:?}"
1020 );
1021 }
1022 }
1023
1024 #[test]
1025 fn legacy_merge_origin_decodes_without_exact_integrated_evidence() {
1026 let report = json!({"origin": {"kind":"run-merge", "op_id":"old", "worker_oid":"old-tip"}});
1027 assert!(matches!(
1028 ReportOrigin::from_report(&report),
1029 Some(ReportOrigin::RunMerge {
1030 integrated_oid: None,
1031 ..
1032 })
1033 ));
1034 let mut modern = report.clone();
1035 modern["origin"]["integrated_oid"] = json!("post-rebase-tip");
1036 let origin = ReportOrigin::from_report(&modern).unwrap();
1037 origin.stamp(&mut modern);
1038 assert_eq!(modern["origin"]["integrated_oid"], "post-rebase-tip");
1039 }
1040
1041 #[test]
1042 fn report_origin_serializes_with_kind_tag() {
1043 let mut report = json!({ "success": true });
1044 ReportOrigin::Agent.stamp(&mut report);
1045 assert_eq!(report["origin"], json!({ "kind": "agent" }));
1046
1047 let mut merge = json!({ "success": true });
1048 ReportOrigin::RunMerge {
1049 op_id: Some("op-9".into()),
1050 worker_oid: Some("abc123".into()),
1051 integrated_oid: None,
1052 }
1053 .stamp(&mut merge);
1054 assert_eq!(
1055 merge["origin"],
1056 json!({ "kind": "run-merge", "op_id": "op-9", "worker_oid": "abc123" })
1057 );
1058
1059 let mut bare = json!({ "success": true });
1061 ReportOrigin::RunMerge {
1062 op_id: None,
1063 worker_oid: None,
1064 integrated_oid: None,
1065 }
1066 .stamp(&mut bare);
1067 assert_eq!(bare["origin"], json!({ "kind": "run-merge" }));
1068 }
1069
1070 #[test]
1071 fn report_origin_absent_or_malformed_is_none() {
1072 assert_eq!(ReportOrigin::from_report(&json!({ "success": true })), None);
1074 assert_eq!(
1077 ReportOrigin::from_report(&json!({ "origin": "not-an-object" })),
1078 None
1079 );
1080 assert_eq!(
1081 ReportOrigin::from_report(&json!({ "origin": { "kind": "bogus" } })),
1082 None
1083 );
1084 }
1085
1086 #[test]
1087 fn report_origin_stamp_overwrites_a_supplied_value() {
1088 let mut report = json!({
1091 "success": true,
1092 "origin": { "kind": "run-merge", "op_id": "spoofed" }
1093 });
1094 ReportOrigin::Agent.stamp(&mut report);
1095 assert_eq!(
1096 ReportOrigin::from_report(&report),
1097 Some(ReportOrigin::Agent)
1098 );
1099 }
1100
1101 #[test]
1102 fn report_is_confirmed_merge_prefers_typed_origin() {
1103 let mut merged = json!({ "success": true });
1105 ReportOrigin::RunMerge {
1106 op_id: Some("op-1".into()),
1107 worker_oid: Some("abc".into()),
1108 integrated_oid: None,
1109 }
1110 .stamp(&mut merged);
1111 assert!(ReportOrigin::report_is_confirmed_merge(&merged));
1112
1113 let mut bare = json!({ "success": true });
1115 ReportOrigin::RunMerge {
1116 op_id: None,
1117 worker_oid: None,
1118 integrated_oid: None,
1119 }
1120 .stamp(&mut bare);
1121 assert!(ReportOrigin::report_is_confirmed_merge(&bare));
1122 }
1123
1124 #[test]
1125 fn report_is_confirmed_merge_legacy_via_only_when_origin_absent() {
1126 assert!(ReportOrigin::report_is_confirmed_merge(&json!({
1128 "success": true, "via": "explicit-merge"
1129 })));
1130
1131 let mut agent = json!({ "success": true, "via": "explicit-merge" });
1134 ReportOrigin::Agent.stamp(&mut agent);
1135 assert!(
1136 !ReportOrigin::report_is_confirmed_merge(&agent),
1137 "an Agent-origin report must not be a merge even with a forged via"
1138 );
1139
1140 assert!(!ReportOrigin::report_is_confirmed_merge(&json!({
1143 "success": true, "via": "explicit-merge", "origin": "garbage-not-an-object"
1144 })));
1145 assert!(!ReportOrigin::report_is_confirmed_merge(&json!({
1146 "success": true, "via": "explicit-merge", "origin": { "kind": "bogus" }
1147 })));
1148 }
1149
1150 #[test]
1151 fn report_is_confirmed_merge_requires_success_and_not_cancelled() {
1152 assert!(!ReportOrigin::report_is_confirmed_merge(&json!({
1154 "success": false, "via": "explicit-merge"
1155 })));
1156 let mut neg = json!({ "success": false });
1158 ReportOrigin::RunMerge {
1159 op_id: None,
1160 worker_oid: None,
1161 integrated_oid: None,
1162 }
1163 .stamp(&mut neg);
1164 assert!(!ReportOrigin::report_is_confirmed_merge(&neg));
1165 let mut cancelled = json!({ "success": false, "cancelled": true, "reason": "x" });
1167 ReportOrigin::RunMerge {
1168 op_id: None,
1169 worker_oid: None,
1170 integrated_oid: None,
1171 }
1172 .stamp(&mut cancelled);
1173 assert!(!ReportOrigin::report_is_confirmed_merge(&cancelled));
1174 assert!(!ReportOrigin::report_is_confirmed_merge(&json!({
1176 "success": "true", "via": "explicit-merge"
1177 })));
1178 }
1179
1180 #[test]
1181 fn report_origin_stamp_on_non_object_is_noop() {
1182 let mut not_obj = json!([1, 2, 3]);
1183 ReportOrigin::Agent.stamp(&mut not_obj);
1184 assert_eq!(not_obj, json!([1, 2, 3]));
1185 }
1186
1187 #[test]
1188 fn wrap_up_must_be_string_array() {
1189 let v = json!({
1190 "success": true,
1191 "wrap_up_recommendations": ["ok", 42],
1192 });
1193 assert!(matches!(
1194 validate_report_payload(&v),
1195 Err(ReportValidationError::FieldElementNotString { index: 1, .. })
1196 ));
1197 }
1198
1199 #[test]
1202 fn sanitize_clean_report_has_no_warnings() {
1203 let v = json!({
1204 "success": true,
1205 "summary": "did the thing",
1206 "discussion_items": [{"topic": "naming", "severity": "discuss"}],
1207 "spinoff_proposals": [
1208 {"proposed_title": "follow-up", "proposed_kind": "spinoff", "rationale": "later"},
1209 ],
1210 "wrap_up_recommendations": ["rebase"],
1211 });
1212 let out = sanitize_report_advisory(&v).unwrap();
1213 assert_eq!(out.warnings.len(), 0);
1214 assert_eq!(out.report, v);
1215 }
1216
1217 #[test]
1218 fn sanitize_drops_typoed_spinoff_proposal_with_warning() {
1219 let v = json!({
1224 "success": true,
1225 "summary": "green, reviewed, committed",
1226 "spinoff_proposals": [{"title": "do X later", "detail": "because Y"}],
1227 });
1228 assert!(validate_report_payload(&v).is_err());
1230 let out = sanitize_report_advisory(&v).unwrap();
1232 assert_eq!(out.warnings.len(), 1);
1233 assert_eq!(out.warnings[0].field, "spinoff_proposals");
1234 assert_eq!(out.warnings[0].index, Some(0));
1235 assert_eq!(out.report["spinoff_proposals"], json!([]));
1236 assert_eq!(out.report["success"], json!(true));
1238 assert_eq!(out.report["summary"], json!("green, reviewed, committed"));
1239 }
1240
1241 #[test]
1242 fn sanitize_keeps_valid_siblings_drops_only_bad_element() {
1243 let v = json!({
1244 "success": true,
1245 "spinoff_proposals": [
1246 {"proposed_title": "keep me", "proposed_kind": "spinoff"},
1247 {"title": "typo, drop me"},
1248 {"proposed_title": "keep me too", "proposed_kind": "research"},
1249 ],
1250 });
1251 let out = sanitize_report_advisory(&v).unwrap();
1252 assert_eq!(out.warnings.len(), 1);
1253 assert_eq!(out.warnings[0].index, Some(1));
1254 let kept = out.report["spinoff_proposals"].as_array().unwrap();
1255 assert_eq!(kept.len(), 2);
1256 assert_eq!(kept[0]["proposed_title"], json!("keep me"));
1257 assert_eq!(kept[1]["proposed_title"], json!("keep me too"));
1258 }
1259
1260 #[test]
1261 fn sanitize_drops_non_array_advisory_field_whole() {
1262 let v = json!({
1263 "success": true,
1264 "discussion_items": "not-an-array",
1265 "wrap_up_recommendations": {"oops": true},
1266 });
1267 let out = sanitize_report_advisory(&v).unwrap();
1268 assert_eq!(out.warnings.len(), 2);
1269 assert!(out.report.get("discussion_items").is_none());
1271 assert!(out.report.get("wrap_up_recommendations").is_none());
1272 let fields: Vec<&str> = out.warnings.iter().map(|w| w.field.as_str()).collect();
1273 assert!(fields.contains(&"discussion_items"));
1274 assert!(fields.contains(&"wrap_up_recommendations"));
1275 assert!(out.warnings.iter().all(|w| w.index.is_none()));
1277 }
1278
1279 #[test]
1280 fn sanitize_drops_non_string_wrap_up_element() {
1281 let v = json!({
1282 "success": true,
1283 "wrap_up_recommendations": ["rebase", 42, "squash"],
1284 });
1285 let out = sanitize_report_advisory(&v).unwrap();
1286 assert_eq!(out.warnings.len(), 1);
1287 assert_eq!(out.warnings[0].index, Some(1));
1288 assert_eq!(
1289 out.report["wrap_up_recommendations"],
1290 json!(["rebase", "squash"])
1291 );
1292 }
1293
1294 #[test]
1295 fn sanitize_drops_malformed_summary() {
1296 let v = json!({"success": true, "summary": 42});
1297 let out = sanitize_report_advisory(&v).unwrap();
1298 assert_eq!(out.warnings.len(), 1);
1299 assert_eq!(out.warnings[0].field, "summary");
1300 assert!(out.report.get("summary").is_none());
1301 }
1302
1303 #[test]
1304 fn sanitize_still_rejects_missing_required_success() {
1305 let v = json!({"summary": "no success field"});
1307 assert!(matches!(
1308 sanitize_report_advisory(&v),
1309 Err(ReportValidationError::MissingSuccess)
1310 ));
1311 }
1312
1313 #[test]
1314 fn sanitize_still_rejects_non_boolean_success() {
1315 let v = json!({"success": "yes", "spinoff_proposals": [{"title": "x"}]});
1316 assert!(matches!(
1317 sanitize_report_advisory(&v),
1318 Err(ReportValidationError::SuccessNotBoolean)
1319 ));
1320 }
1321
1322 #[test]
1323 fn sanitize_still_rejects_cancelled_contradiction() {
1324 let v = json!({"success": true, "cancelled": true, "reason": "x"});
1327 assert!(matches!(
1328 sanitize_report_advisory(&v),
1329 Err(ReportValidationError::CancelledRequiresSuccessFalse)
1330 ));
1331 }
1332
1333 #[test]
1334 fn sanitize_rejects_non_object_root() {
1335 let v = json!([1, 2, 3]);
1336 assert!(matches!(
1337 sanitize_report_advisory(&v),
1338 Err(ReportValidationError::NotObject)
1339 ));
1340 }
1341
1342 #[test]
1343 fn sanitize_preserves_unknown_and_provenance_fields() {
1344 let v = json!({
1349 "success": true,
1350 "origin": {"kind": "agent"},
1351 "via": "explicit-merge",
1352 "custom_agent_key": {"nested": [1, 2, 3]},
1353 "spinoff_proposals": [{"title": "typo, drop me"}],
1354 });
1355 let out = sanitize_report_advisory(&v).unwrap();
1356 assert_eq!(out.warnings.len(), 1, "only the bad proposal is dropped");
1357 assert_eq!(out.report["origin"], json!({"kind": "agent"}));
1358 assert_eq!(out.report["via"], json!("explicit-merge"));
1359 assert_eq!(out.report["custom_agent_key"], json!({"nested": [1, 2, 3]}));
1360 }
1361
1362 #[test]
1363 fn sanitize_nested_options_drops_whole_discussion_item() {
1364 let v = json!({
1367 "success": true,
1368 "discussion_items": [
1369 {"topic": "keep", "severity": "discuss"},
1370 {"topic": "drop me", "options": ["ok", 42]},
1371 ],
1372 });
1373 let out = sanitize_report_advisory(&v).unwrap();
1374 assert_eq!(out.warnings.len(), 1);
1375 assert_eq!(out.warnings[0].index, Some(1));
1376 let kept = out.report["discussion_items"].as_array().unwrap();
1377 assert_eq!(kept.len(), 1);
1378 assert_eq!(kept[0]["topic"], json!("keep"));
1379 }
1380
1381 #[test]
1382 fn advisory_warning_message_shapes() {
1383 let elem = AdvisoryWarning {
1384 field: "spinoff_proposals".to_string(),
1385 index: Some(2),
1386 reason: "boom".to_string(),
1387 };
1388 assert_eq!(elem.to_message(), "dropped spinoff_proposals[2]: boom");
1389 let whole = AdvisoryWarning {
1390 field: "discussion_items".to_string(),
1391 index: None,
1392 reason: "not an array".to_string(),
1393 };
1394 assert_eq!(
1395 whole.to_message(),
1396 "dropped advisory field `discussion_items`: not an array"
1397 );
1398 }
1399}