1use serde_json::Value;
4
5use super::model::{AgentResponse, AgentResponseParseError, ProtocolRequestProfile};
6use super::review::{FocusedReview, FocusedReviewSeverity};
7
8const PROTOCOL_KEYS: &[&str] = &[
10 "answer",
11 "questions",
12 "review_comment_outcomes",
13 "subtasks",
14 "verification_verdicts",
15];
16
17pub fn parse_agent_response_strict(raw: &str) -> Result<AgentResponse, AgentResponseParseError> {
35 let trimmed = raw.trim();
36 if trimmed.is_empty() {
37 return Err(AgentResponseParseError::Empty);
38 }
39
40 let direct_parse = parse_structured_json_response_with_reason(trimmed);
41 if let Ok(response) = direct_parse {
42 return Ok(response);
43 }
44
45 let direct_parse_error = match direct_parse {
46 Err(error) => error.to_string(),
47 Ok(_) => unreachable!("direct parse branch already returned successful parse"),
48 };
49
50 if let Some(inner) = strip_markdown_code_fence(trimmed) {
51 if let Some(response) = parse_structured_json_response_with_recovery(inner) {
52 return Ok(response);
53 }
54
55 let fence_parse_error = parse_structured_json_response_with_reason(inner)
56 .err()
57 .map_or_else(
58 || "no protocol payload found in markdown code fence".to_string(),
59 |error| error.to_string(),
60 );
61
62 return Err(AgentResponseParseError::InvalidFormat {
63 reason: format!("markdown code fence extraction failed ({fence_parse_error})"),
64 });
65 }
66
67 if let Some(inner) = find_embedded_code_fence_content(trimmed)
68 && let Some(response) = parse_structured_json_response_with_recovery(inner)
69 {
70 return Ok(response);
71 }
72
73 if let Some(response) = recover_embedded_structured_json_response(trimmed) {
74 return Ok(response);
75 }
76
77 Err(AgentResponseParseError::InvalidFormat {
78 reason: format!(
79 "direct parse failed ({direct_parse_error}); no markdown wrapper/embedded protocol \
80 object found"
81 ),
82 })
83}
84
85pub fn parse_protocol_response_strict(
96 raw: &str,
97 profile: ProtocolRequestProfile,
98) -> Result<AgentResponse, AgentResponseParseError> {
99 if !matches!(profile, ProtocolRequestProfile::FocusedReview) {
100 return parse_agent_response_strict(raw);
101 }
102
103 let trimmed = raw.trim();
104 if trimmed.is_empty() {
105 return Err(AgentResponseParseError::Empty);
106 }
107
108 let review = serde_json::from_str::<FocusedReview>(trimmed).map_err(|error| {
109 AgentResponseParseError::InvalidFormat {
110 reason: format!("focused review parse failed ({error})"),
111 }
112 })?;
113 let answer = focused_review_answer(review);
114
115 Ok(AgentResponse::plain(answer))
116}
117
118fn focused_review_answer(review: FocusedReview) -> String {
120 let project_impact = review
121 .project_impact
122 .into_iter()
123 .map(Value::String)
124 .collect();
125 let suggestions = review
126 .suggestions
127 .into_iter()
128 .map(|suggestion| {
129 let severity = match suggestion.severity {
130 FocusedReviewSeverity::High => "high",
131 FocusedReviewSeverity::Medium => "medium",
132 };
133
134 Value::Object(
135 [
136 ("details".to_string(), Value::String(suggestion.details)),
137 ("severity".to_string(), Value::String(severity.to_string())),
138 ]
139 .into_iter()
140 .collect(),
141 )
142 })
143 .collect();
144
145 Value::Object(
146 [
147 ("project_impact".to_string(), Value::Array(project_impact)),
148 ("suggestions".to_string(), Value::Array(suggestions)),
149 ]
150 .into_iter()
151 .collect(),
152 )
153 .to_string()
154}
155
156pub fn format_protocol_parse_debug_details(raw: &str) -> String {
167 let trimmed = raw.trim();
168 let mut detail_lines = vec![
169 format!("response_len: {} chars", raw.chars().count()),
170 format!("response_lines: {}", raw.lines().count()),
171 format!("trimmed_len: {} chars", trimmed.chars().count()),
172 format!(
173 "wrapped_in_markdown_fence: {}",
174 strip_markdown_code_fence(trimmed).is_some()
175 ),
176 ];
177
178 if trimmed.is_empty() {
179 return detail_lines.join("\n");
180 }
181
182 push_character_boundary_debug_lines(&mut detail_lines, trimmed);
183 push_json_debug_lines(&mut detail_lines, "direct_json", trimmed);
184
185 if let Some(inner) = strip_markdown_code_fence(trimmed) {
186 detail_lines.push(format!(
187 "code_fence_inner_len: {} chars",
188 inner.chars().count()
189 ));
190 push_json_debug_lines(&mut detail_lines, "code_fence_json", inner);
191 }
192
193 if let Some(embedded_value) = find_last_embedded_json_value(trimmed) {
194 detail_lines.push("embedded_json_candidate: found".to_string());
195 push_json_value_debug_lines(&mut detail_lines, "embedded_json", &embedded_value);
196 } else {
197 detail_lines.push("embedded_json_candidate: none".to_string());
198 }
199
200 detail_lines.join("\n")
201}
202
203fn parse_structured_json_response_with_reason(
206 raw: &str,
207) -> Result<AgentResponse, AgentResponseParseError> {
208 let value: Value = serde_json::from_str(raw.trim()).map_err(|error| {
209 AgentResponseParseError::InvalidFormat {
210 reason: format!("invalid JSON ({error})"),
211 }
212 })?;
213
214 if !value_has_recognized_protocol_key(&value) {
215 return Err(AgentResponseParseError::InvalidFormat {
216 reason: format!(
217 "json object is missing all protocol keys ({})",
218 PROTOCOL_KEYS.join(", ")
219 ),
220 });
221 }
222
223 serde_json::from_value(value).map_err(|error| AgentResponseParseError::InvalidFormat {
224 reason: format!("schema validation failed ({error})"),
225 })
226}
227
228fn value_has_recognized_protocol_key(value: &Value) -> bool {
231 value
232 .as_object()
233 .is_some_and(|object| PROTOCOL_KEYS.iter().any(|key| object.contains_key(*key)))
234}
235
236fn strip_markdown_code_fence(trimmed: &str) -> Option<&str> {
240 let rest = trimmed.strip_prefix("```")?;
241 let body_start = rest.find('\n').map(|index| index + 1)?;
242 let body = &rest[body_start..];
243 let inner = body.strip_suffix("```")?.trim();
244
245 if inner.is_empty() {
246 return None;
247 }
248
249 Some(inner)
250}
251
252fn parse_structured_json_response_with_recovery(raw: &str) -> Option<AgentResponse> {
255 parse_structured_json_response(raw).or_else(|| recover_embedded_structured_json_response(raw))
256}
257
258fn parse_structured_json_response(raw: &str) -> Option<AgentResponse> {
264 parse_structured_json_response_with_reason(raw).ok()
265}
266
267fn recover_embedded_structured_json_response(raw: &str) -> Option<AgentResponse> {
274 let value = find_last_embedded_json_value(raw)?;
275 if !value_has_recognized_protocol_key(&value) {
276 return None;
277 }
278
279 serde_json::from_value(value).ok()
280}
281
282fn find_embedded_code_fence_content(raw: &str) -> Option<&str> {
288 let closing_fence_start = raw.rfind("```")?;
289 let before_closing = raw[..closing_fence_start].trim_end();
290
291 let opening_fence_start = before_closing.rfind("```")?;
292 let after_opening_backticks = &before_closing[opening_fence_start + 3..];
293
294 let body_start = after_opening_backticks.find('\n').map(|index| index + 1)?;
295 let inner = &after_opening_backticks[body_start..];
296 let trimmed = inner.trim();
297
298 if trimmed.is_empty() {
299 return None;
300 }
301
302 Some(trimmed)
303}
304
305fn find_last_embedded_json_value(raw: &str) -> Option<Value> {
308 for (start_index, _) in raw.match_indices('{').rev() {
309 let candidate = &raw[start_index..];
310 let mut deserializer = serde_json::Deserializer::from_str(candidate).into_iter::<Value>();
311 let Some(Ok(value)) = deserializer.next() else {
312 continue;
313 };
314 let trailing_text = &candidate[deserializer.byte_offset()..];
315 if !trailing_text.trim().is_empty() {
316 continue;
317 }
318
319 return Some(value);
320 }
321
322 None
323}
324
325fn push_character_boundary_debug_lines(detail_lines: &mut Vec<String>, trimmed: &str) {
327 if let Some(first_character) = trimmed.chars().next() {
328 detail_lines.push(format!("first_non_whitespace_char: {first_character:?}"));
329 }
330
331 if let Some(last_character) = trimmed.chars().last() {
332 detail_lines.push(format!("last_non_whitespace_char: {last_character:?}"));
333 }
334}
335
336fn push_json_debug_lines(detail_lines: &mut Vec<String>, label: &str, raw: &str) {
338 match serde_json::from_str::<Value>(raw) {
339 Ok(value) => push_json_value_debug_lines(detail_lines, label, &value),
340 Err(error) => {
341 detail_lines.push(format!("{label}_error: {error}"));
342 detail_lines.push(format!(
343 "{label}_error_category: {}",
344 describe_json_error_category(&error)
345 ));
346 detail_lines.push(format!(
347 "{label}_error_location: line {}, column {}",
348 error.line(),
349 error.column()
350 ));
351 }
352 }
353}
354
355fn push_json_value_debug_lines(detail_lines: &mut Vec<String>, label: &str, value: &Value) {
357 detail_lines.push(format!("{label}_type: {}", describe_json_type(value)));
358
359 if let Some(object) = value.as_object() {
360 let mut keys = object.keys().cloned().collect::<Vec<_>>();
361 keys.sort_unstable();
362
363 let recognized_keys = PROTOCOL_KEYS
364 .iter()
365 .filter(|key| object.contains_key(**key))
366 .map(|key| (*key).to_string())
367 .collect::<Vec<_>>();
368 let missing_keys = PROTOCOL_KEYS
369 .iter()
370 .filter(|key| !object.contains_key(**key))
371 .map(|key| (*key).to_string())
372 .collect::<Vec<_>>();
373
374 detail_lines.push(format!("{label}_keys: {}", format_debug_list(&keys)));
375 detail_lines.push(format!(
376 "{label}_recognized_protocol_keys: {}",
377 format_debug_list(&recognized_keys)
378 ));
379 detail_lines.push(format!(
380 "{label}_missing_protocol_keys: {}",
381 format_debug_list(&missing_keys)
382 ));
383 }
384}
385
386fn describe_json_type(value: &Value) -> &'static str {
388 match value {
389 Value::Null => "null",
390 Value::Bool(_) => "boolean",
391 Value::Number(_) => "number",
392 Value::String(_) => "string",
393 Value::Array(_) => "array",
394 Value::Object(_) => "object",
395 }
396}
397
398fn format_debug_list(items: &[String]) -> String {
400 if items.is_empty() {
401 return "(none)".to_string();
402 }
403
404 items.join(", ")
405}
406
407fn describe_json_error_category(error: &serde_json::Error) -> &'static str {
409 match error.classify() {
410 serde_json::error::Category::Io => "io",
411 serde_json::error::Category::Syntax => "syntax",
412 serde_json::error::Category::Data => "data",
413 serde_json::error::Category::Eof => "eof",
414 }
415}
416
417#[cfg(test)]
418#[path = "parse_test.rs"]
419mod tests;