Skip to main content

ag_protocol/
parse.rs

1//! Structured response parsing and streaming normalization helpers.
2
3use serde_json::Value;
4
5use super::model::{AgentResponse, AgentResponseParseError};
6
7/// Top-level keys the protocol recognizes in a structured response payload.
8const PROTOCOL_KEYS: &[&str] = &[
9    "answer",
10    "questions",
11    "review_comment_outcomes",
12    "subtasks",
13    "verification_verdicts",
14];
15
16/// Parses one raw assistant message strictly as protocol payload.
17///
18/// The final assistant payload must match [`AgentResponse`] and contain at
19/// least one recognized protocol key (`answer`, `questions`,
20/// `review_comment_outcomes`, `subtasks`, or `verification_verdicts`).
21///
22/// When a provider prepends stray prose before the final schema object, this
23/// still recovers the trailing protocol payload as long as nothing except
24/// whitespace follows the JSON object. As a further resilience fallback,
25/// markdown code fences wrapping the JSON object are stripped before parsing
26/// when neither direct parsing nor trailing-object recovery succeeds. An
27/// additional fallback extracts JSON from an embedded code fence preceded by
28/// prose text (e.g., commentary followed by a fenced JSON block).
29/// Top-level fields may rely on the wire type's defaults.
30///
31/// # Errors
32/// Returns [`AgentResponseParseError`] when no valid protocol payload is found.
33pub fn parse_agent_response_strict(raw: &str) -> Result<AgentResponse, AgentResponseParseError> {
34    let trimmed = raw.trim();
35    if trimmed.is_empty() {
36        return Err(AgentResponseParseError::Empty);
37    }
38
39    let direct_parse = parse_structured_json_response_with_reason(trimmed);
40    if let Ok(response) = direct_parse {
41        return Ok(response);
42    }
43
44    let direct_parse_error = match direct_parse {
45        Err(error) => error.to_string(),
46        Ok(_) => unreachable!("direct parse branch already returned successful parse"),
47    };
48
49    if let Some(inner) = strip_markdown_code_fence(trimmed) {
50        if let Some(response) = parse_structured_json_response_with_recovery(inner) {
51            return Ok(response);
52        }
53
54        let fence_parse_error = parse_structured_json_response_with_reason(inner)
55            .err()
56            .map_or_else(
57                || "no protocol payload found in markdown code fence".to_string(),
58                |error| error.to_string(),
59            );
60
61        return Err(AgentResponseParseError::InvalidFormat {
62            reason: format!("markdown code fence extraction failed ({fence_parse_error})"),
63        });
64    }
65
66    if let Some(inner) = find_embedded_code_fence_content(trimmed)
67        && let Some(response) = parse_structured_json_response_with_recovery(inner)
68    {
69        return Ok(response);
70    }
71
72    if let Some(response) = recover_embedded_structured_json_response(trimmed) {
73        return Ok(response);
74    }
75
76    Err(AgentResponseParseError::InvalidFormat {
77        reason: format!(
78            "direct parse failed ({direct_parse_error}); no markdown wrapper/embedded protocol \
79             object found"
80        ),
81    })
82}
83
84/// Builds one multi-line debug report for a protocol parsing failure.
85///
86/// The report summarizes response sizing, markdown wrapping, JSON parse
87/// diagnostics, and any visible top-level keys so schema mismatch errors
88/// include enough context to diagnose malformed provider output quickly.
89///
90/// Every line is *derived* metadata: sizes, parser locations, and key names.
91/// No provider payload text is reproduced. Turn errors are rendered into the
92/// session transcript, so quoting the payload here would print raw provider
93/// output into the chat.
94pub fn format_protocol_parse_debug_details(raw: &str) -> String {
95    let trimmed = raw.trim();
96    let mut detail_lines = vec![
97        format!("response_len: {} chars", raw.chars().count()),
98        format!("response_lines: {}", raw.lines().count()),
99        format!("trimmed_len: {} chars", trimmed.chars().count()),
100        format!(
101            "wrapped_in_markdown_fence: {}",
102            strip_markdown_code_fence(trimmed).is_some()
103        ),
104    ];
105
106    if trimmed.is_empty() {
107        return detail_lines.join("\n");
108    }
109
110    push_character_boundary_debug_lines(&mut detail_lines, trimmed);
111    push_json_debug_lines(&mut detail_lines, "direct_json", trimmed);
112
113    if let Some(inner) = strip_markdown_code_fence(trimmed) {
114        detail_lines.push(format!(
115            "code_fence_inner_len: {} chars",
116            inner.chars().count()
117        ));
118        push_json_debug_lines(&mut detail_lines, "code_fence_json", inner);
119    }
120
121    if let Some(embedded_value) = find_last_embedded_json_value(trimmed) {
122        detail_lines.push("embedded_json_candidate: found".to_string());
123        push_json_value_debug_lines(&mut detail_lines, "embedded_json", &embedded_value);
124    } else {
125        detail_lines.push("embedded_json_candidate: none".to_string());
126    }
127
128    detail_lines.join("\n")
129}
130
131/// Parses one schema-driven JSON response and returns the structured error
132/// detail when the payload cannot be parsed or validated.
133fn parse_structured_json_response_with_reason(
134    raw: &str,
135) -> Result<AgentResponse, AgentResponseParseError> {
136    let value: Value = serde_json::from_str(raw.trim()).map_err(|error| {
137        AgentResponseParseError::InvalidFormat {
138            reason: format!("invalid JSON ({error})"),
139        }
140    })?;
141
142    if !value_has_recognized_protocol_key(&value) {
143        return Err(AgentResponseParseError::InvalidFormat {
144            reason: format!(
145                "json object is missing all protocol keys ({})",
146                PROTOCOL_KEYS.join(", ")
147            ),
148        });
149    }
150
151    serde_json::from_value(value).map_err(|error| AgentResponseParseError::InvalidFormat {
152        reason: format!("schema validation failed ({error})"),
153    })
154}
155
156/// Returns whether a parsed JSON value is an object containing at least one
157/// recognized protocol key.
158fn value_has_recognized_protocol_key(value: &Value) -> bool {
159    value
160        .as_object()
161        .is_some_and(|object| PROTOCOL_KEYS.iter().any(|key| object.contains_key(*key)))
162}
163
164/// Strips a leading markdown code fence and trailing closing fence from a
165/// trimmed response payload, returning the inner content if the pattern
166/// matches.
167fn strip_markdown_code_fence(trimmed: &str) -> Option<&str> {
168    let rest = trimmed.strip_prefix("```")?;
169    let body_start = rest.find('\n').map(|index| index + 1)?;
170    let body = &rest[body_start..];
171    let inner = body.strip_suffix("```")?.trim();
172
173    if inner.is_empty() {
174        return None;
175    }
176
177    Some(inner)
178}
179
180/// Parses one full protocol payload and then falls back to recovering a
181/// trailing schema object from wrapped provider output.
182fn parse_structured_json_response_with_recovery(raw: &str) -> Option<AgentResponse> {
183    parse_structured_json_response(raw).or_else(|| recover_embedded_structured_json_response(raw))
184}
185
186/// Attempts to parse one schema-driven structured JSON response.
187///
188/// The raw text must parse as a JSON object containing at least one
189/// recognized protocol key from [`PROTOCOL_KEYS`]. Returns `None` when parsing
190/// fails or no recognized keys are present.
191fn parse_structured_json_response(raw: &str) -> Option<AgentResponse> {
192    parse_structured_json_response_with_reason(raw).ok()
193}
194
195/// Recovers one trailing protocol payload from provider output that starts
196/// with extra prose before the final JSON object.
197///
198/// This intentionally keeps trailing text strict: once a candidate JSON object
199/// parses successfully, only whitespace may remain after it. The candidate
200/// must also contain at least one recognized protocol key.
201fn recover_embedded_structured_json_response(raw: &str) -> Option<AgentResponse> {
202    let value = find_last_embedded_json_value(raw)?;
203    if !value_has_recognized_protocol_key(&value) {
204        return None;
205    }
206
207    serde_json::from_value(value).ok()
208}
209
210/// Extracts the inner content from the last markdown code fence embedded in a
211/// response that also contains surrounding prose text.
212///
213/// Handles the pattern where a provider prepends commentary before a fenced
214/// JSON payload (e.g., `"Some explanation\n` ` ```json\n{...}\n``` ` `"`).
215fn find_embedded_code_fence_content(raw: &str) -> Option<&str> {
216    let closing_fence_start = raw.rfind("```")?;
217    let before_closing = raw[..closing_fence_start].trim_end();
218
219    let opening_fence_start = before_closing.rfind("```")?;
220    let after_opening_backticks = &before_closing[opening_fence_start + 3..];
221
222    let body_start = after_opening_backticks.find('\n').map(|index| index + 1)?;
223    let inner = &after_opening_backticks[body_start..];
224    let trimmed = inner.trim();
225
226    if trimmed.is_empty() {
227        return None;
228    }
229
230    Some(trimmed)
231}
232
233/// Finds the last JSON object embedded in a response when it consumes the full
234/// trailing suffix except for whitespace.
235fn find_last_embedded_json_value(raw: &str) -> Option<Value> {
236    for (start_index, _) in raw.match_indices('{').rev() {
237        let candidate = &raw[start_index..];
238        let mut deserializer = serde_json::Deserializer::from_str(candidate).into_iter::<Value>();
239        let Some(Ok(value)) = deserializer.next() else {
240            continue;
241        };
242        let trailing_text = &candidate[deserializer.byte_offset()..];
243        if !trailing_text.trim().is_empty() {
244            continue;
245        }
246
247        return Some(value);
248    }
249
250    None
251}
252
253/// Appends stable character-boundary diagnostics for one trimmed response.
254fn push_character_boundary_debug_lines(detail_lines: &mut Vec<String>, trimmed: &str) {
255    if let Some(first_character) = trimmed.chars().next() {
256        detail_lines.push(format!("first_non_whitespace_char: {first_character:?}"));
257    }
258
259    if let Some(last_character) = trimmed.chars().last() {
260        detail_lines.push(format!("last_non_whitespace_char: {last_character:?}"));
261    }
262}
263
264/// Appends either JSON parse failure details or top-level JSON shape details.
265fn push_json_debug_lines(detail_lines: &mut Vec<String>, label: &str, raw: &str) {
266    match serde_json::from_str::<Value>(raw) {
267        Ok(value) => push_json_value_debug_lines(detail_lines, label, &value),
268        Err(error) => {
269            detail_lines.push(format!("{label}_error: {error}"));
270            detail_lines.push(format!(
271                "{label}_error_category: {}",
272                describe_json_error_category(&error)
273            ));
274            detail_lines.push(format!(
275                "{label}_error_location: line {}, column {}",
276                error.line(),
277                error.column()
278            ));
279        }
280    }
281}
282
283/// Appends the top-level JSON type and protocol-key visibility for one value.
284fn push_json_value_debug_lines(detail_lines: &mut Vec<String>, label: &str, value: &Value) {
285    detail_lines.push(format!("{label}_type: {}", describe_json_type(value)));
286
287    if let Some(object) = value.as_object() {
288        let mut keys = object.keys().cloned().collect::<Vec<_>>();
289        keys.sort_unstable();
290
291        let recognized_keys = PROTOCOL_KEYS
292            .iter()
293            .filter(|key| object.contains_key(**key))
294            .map(|key| (*key).to_string())
295            .collect::<Vec<_>>();
296        let missing_keys = PROTOCOL_KEYS
297            .iter()
298            .filter(|key| !object.contains_key(**key))
299            .map(|key| (*key).to_string())
300            .collect::<Vec<_>>();
301
302        detail_lines.push(format!("{label}_keys: {}", format_debug_list(&keys)));
303        detail_lines.push(format!(
304            "{label}_recognized_protocol_keys: {}",
305            format_debug_list(&recognized_keys)
306        ));
307        detail_lines.push(format!(
308            "{label}_missing_protocol_keys: {}",
309            format_debug_list(&missing_keys)
310        ));
311    }
312}
313
314/// Returns one stable label for a top-level JSON value type.
315fn describe_json_type(value: &Value) -> &'static str {
316    match value {
317        Value::Null => "null",
318        Value::Bool(_) => "boolean",
319        Value::Number(_) => "number",
320        Value::String(_) => "string",
321        Value::Array(_) => "array",
322        Value::Object(_) => "object",
323    }
324}
325
326/// Formats one debug list as a comma-separated string or `(none)`.
327fn format_debug_list(items: &[String]) -> String {
328    if items.is_empty() {
329        return "(none)".to_string();
330    }
331
332    items.join(", ")
333}
334
335/// Returns one stable label for the serde JSON error category.
336fn describe_json_error_category(error: &serde_json::Error) -> &'static str {
337    match error.classify() {
338        serde_json::error::Category::Io => "io",
339        serde_json::error::Category::Syntax => "syntax",
340        serde_json::error::Category::Data => "data",
341        serde_json::error::Category::Eof => "eof",
342    }
343}
344
345#[cfg(test)]
346mod tests {
347    use super::*;
348    use crate::{ReviewCommentOutcome, ReviewCommentResolution};
349
350    #[test]
351    /// Strict parsing accepts a complete schema payload.
352    fn test_parse_agent_response_strict_structured_json_payload() {
353        // Arrange
354        let raw = r#"{"answer":"Here is my analysis.","questions":[]}"#;
355
356        // Act
357        let response = parse_agent_response_strict(raw);
358
359        // Assert
360        assert_eq!(
361            response.expect("response should parse").answer,
362            "Here is my analysis."
363        );
364    }
365
366    #[test]
367    /// Strict parsing recovers a trailing protocol payload when a provider
368    /// prepends extra prose before the final JSON object.
369    fn test_parse_agent_response_strict_recovers_wrapped_text() {
370        // Arrange
371        let raw = concat!(
372            "Some wrapper text\n",
373            r#"{"answer":"Recovered payload","questions":[]}"#
374        );
375
376        // Act
377        let response = parse_agent_response_strict(raw);
378
379        // Assert
380        assert_eq!(
381            response.expect("response should parse"),
382            AgentResponse::plain("Recovered payload")
383        );
384    }
385
386    #[test]
387    /// Strict parsing rejects plain text that contains no protocol payload.
388    fn test_parse_agent_response_strict_rejects_plain_text() {
389        // Arrange
390        let raw = "plain text";
391
392        // Act
393        let response = parse_agent_response_strict(raw);
394
395        // Assert
396        assert!(response.is_err());
397    }
398
399    #[test]
400    /// Strict parsing rejects JSON objects with only unrecognized fields
401    /// because at least one protocol key must be present.
402    fn test_parse_agent_response_strict_rejects_unrecognized_only_fields() {
403        // Arrange
404        let raw = r#"{"message":"not the expected shape"}"#;
405
406        // Act
407        let response = parse_agent_response_strict(raw);
408
409        // Assert
410        assert!(response.is_err());
411    }
412
413    #[test]
414    /// Strict parsing rejects an empty JSON object because no recognized
415    /// protocol key is present.
416    fn test_parse_agent_response_strict_rejects_empty_json_object() {
417        // Arrange
418        let raw = "{}";
419
420        // Act
421        let response = parse_agent_response_strict(raw);
422
423        // Assert
424        assert!(response.is_err());
425    }
426
427    #[test]
428    /// Strict parsing rejects an empty code fence instead of treating it as a
429    /// structured response.
430    fn test_parse_agent_response_strict_rejects_empty_code_fence() {
431        // Arrange
432        let raw = "```json\n\n```";
433
434        // Act
435        let response = parse_agent_response_strict(raw);
436
437        // Assert
438        assert!(response.is_err());
439    }
440
441    #[test]
442    /// Strict parsing strips code fences and recovers the inner JSON payload.
443    fn test_parse_agent_response_strict_strips_code_fenced_payload() {
444        // Arrange
445        let raw = concat!(
446            "```json\n",
447            r#"{"answer":"Need details.","questions":[]}"#,
448            "\n```"
449        );
450
451        // Act
452        let response = parse_agent_response_strict(raw);
453
454        // Assert
455        assert_eq!(
456            response.expect("response should parse").answer,
457            "Need details."
458        );
459    }
460
461    #[test]
462    /// Strict parsing strips code fences even when leading/trailing whitespace
463    /// surrounds the fenced block.
464    fn test_parse_agent_response_strict_strips_code_fenced_payload_with_whitespace() {
465        // Arrange
466        let raw = concat!(
467            "\n\n```json\n",
468            r#"{"answer":"Recovered.","questions":[]}"#,
469            "\n```\n"
470        );
471
472        // Act
473        let response = parse_agent_response_strict(raw);
474
475        // Assert
476        assert_eq!(
477            response.expect("response should parse").answer,
478            "Recovered."
479        );
480    }
481
482    #[test]
483    /// Strict parsing strips plain code fences without a language tag.
484    fn test_parse_agent_response_strict_strips_plain_code_fenced_payload() {
485        // Arrange
486        let raw = concat!(
487            "```\n",
488            r#"{"answer":"Plain fence.","questions":[]}"#,
489            "\n```"
490        );
491
492        // Act
493        let response = parse_agent_response_strict(raw);
494
495        // Assert
496        assert_eq!(
497            response.expect("response should parse").answer,
498            "Plain fence."
499        );
500    }
501
502    #[test]
503    /// Strict parsing tolerates extra top-level fields that providers may add
504    /// beyond the protocol schema.
505    fn test_parse_agent_response_strict_tolerates_extra_top_level_fields() {
506        // Arrange
507        let raw = r#"{"answer":"Hello.","questions":[],"reasoning":"internal thought"}"#;
508
509        // Act
510        let response = parse_agent_response_strict(raw);
511
512        // Assert
513        assert_eq!(response.expect("response should parse").answer, "Hello.");
514    }
515
516    #[test]
517    /// Strict parsing tolerates extra fields inside nested question objects.
518    fn test_parse_agent_response_strict_tolerates_extra_question_fields() {
519        // Arrange
520        let raw = r#"{"answer":"","questions":[{"text":"Which approach?","options":["A","B"],"priority":"high"}]}"#;
521
522        // Act
523        let response = parse_agent_response_strict(raw);
524
525        // Assert
526        let questions = response.expect("response should parse").question_items();
527        assert_eq!(questions.len(), 1);
528        assert_eq!(questions[0].text, "Which approach?");
529    }
530
531    #[test]
532    /// Parser accepts a payload with `questions` but no `answer` key,
533    /// exercising the documented asymmetry where the parser is lenient
534    /// (any recognized key suffices) while the prompt schema requires
535    /// `answer`.
536    fn test_parse_agent_response_strict_accepts_questions_without_answer() {
537        // Arrange
538        let raw = r#"{"questions":[{"text":"Which approach?"}]}"#;
539
540        // Act
541        let response = parse_agent_response_strict(raw);
542
543        // Assert
544        let response = response.expect("parser should accept questions-only payload");
545        assert_eq!(response.answer, "");
546        assert_eq!(response.question_items().len(), 1);
547    }
548
549    #[test]
550    /// Parser accepts a review-comment outcome without an `answer` key because
551    /// it is a recognized protocol field.
552    fn test_parse_agent_response_strict_accepts_review_outcome_without_answer() {
553        // Arrange
554        let raw = concat!(
555            r#"{"review_comment_outcomes":[{"reply":"Fixed it.","resolution":"fixed","#,
556            r#""thread_id":"thread-42"}]}"#
557        );
558
559        // Act
560        let response = parse_agent_response_strict(raw);
561
562        // Assert
563        let response = response.expect("parser should accept review-outcome-only payload");
564        assert_eq!(
565            response.review_comment_outcomes,
566            vec![ReviewCommentOutcome {
567                reply: "Fixed it.".to_string(),
568                resolution: ReviewCommentResolution::Fixed,
569                thread_id: "thread-42".to_string(),
570            }]
571        );
572    }
573
574    #[test]
575    /// Recovery path skips non-protocol JSON objects embedded in prose when
576    /// they contain no recognized protocol keys.
577    fn test_parse_agent_response_strict_rejects_wrapped_non_protocol_json() {
578        // Arrange
579        let raw = concat!(
580            "Some wrapper text\n",
581            r#"{"reasoning":"internal thought","confidence":0.9}"#
582        );
583
584        // Act
585        let response = parse_agent_response_strict(raw);
586
587        // Assert
588        assert!(response.is_err());
589    }
590
591    #[test]
592    /// Strict parsing still rejects trailing wrapper text after a recovered
593    /// schema object.
594    fn test_parse_agent_response_strict_rejects_trailing_wrapper_after_payload() {
595        // Arrange
596        let raw = concat!(
597            "Some wrapper text\n",
598            r#"{"answer":"Recovered payload","questions":[]}"#,
599            "\ntrailing wrapper text"
600        );
601
602        // Act
603        let response = parse_agent_response_strict(raw);
604
605        // Assert
606        assert!(response.is_err());
607    }
608
609    #[test]
610    /// Strict parsing recovers protocol JSON from an embedded code fence
611    /// preceded by prose text.
612    fn test_parse_agent_response_strict_recovers_embedded_code_fence_in_prose() {
613        // Arrange
614        let raw = concat!(
615            "The commit message looks good. Let me refine it.\n\n",
616            "```json\n",
617            r#"{"answer":"Refined commit message","questions":[]}"#,
618            "\n```"
619        );
620
621        // Act
622        let response = parse_agent_response_strict(raw);
623
624        // Assert
625        assert_eq!(
626            response.expect("response should parse").answer,
627            "Refined commit message"
628        );
629    }
630
631    #[test]
632    /// The debug report describes the payload without reproducing any of it,
633    /// so a turn error cannot print raw provider output into the transcript.
634    fn test_format_protocol_parse_debug_details_never_quotes_payload() {
635        // Arrange
636        let raw = format!("{} SECRETTAIL", "payload-filler ".repeat(40));
637
638        // Act
639        let details = format_protocol_parse_debug_details(&raw);
640
641        // Assert
642        assert!(!details.contains("payload-filler"));
643        assert!(!details.contains("SECRETTAIL"));
644        assert!(details.contains(&format!("response_len: {} chars", raw.chars().count())));
645        assert!(details.contains("direct_json_error"));
646    }
647
648    #[test]
649    /// Debug formatting reports JSON parser location details for plain-text
650    /// responses that never produced protocol JSON.
651    fn test_format_protocol_parse_debug_details_reports_plain_text_json_error() {
652        // Arrange
653        let raw = "plain text";
654
655        // Act
656        let details = format_protocol_parse_debug_details(raw);
657
658        // Assert
659        assert!(details.contains("response_len: 10 chars"));
660        assert!(details.contains("first_non_whitespace_char: 'p'"));
661        assert!(details.contains("direct_json_error_category: syntax"));
662        assert!(details.contains("direct_json_error_location: line 1, column 1"));
663        assert!(details.contains("embedded_json_candidate: none"));
664    }
665
666    #[test]
667    /// Debug formatting reports visible top-level keys when the response is
668    /// valid JSON but does not include any protocol fields.
669    fn test_format_protocol_parse_debug_details_reports_unrecognized_json_keys() {
670        // Arrange
671        let raw = r#"{"message":"not the expected shape"}"#;
672
673        // Act
674        let details = format_protocol_parse_debug_details(raw);
675
676        // Assert
677        assert!(details.contains("direct_json_type: object"));
678        assert!(details.contains("direct_json_keys: message"));
679        assert!(details.contains("direct_json_recognized_protocol_keys: (none)"));
680        assert!(details.contains(
681            "direct_json_missing_protocol_keys: answer, questions, review_comment_outcomes, \
682             subtasks, verification_verdicts"
683        ));
684    }
685}