agengo 0.5.1

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
//! Finding the JSON object an agent was asked to end with, in text that may
//! also hold an introduction, a code fence or an afterthought.

use serde_json::Value;

/// The last JSON object in `text` that is not inside another one. The whole
/// text is tried first, then each balanced `{...}` from the end.
pub fn extract_object(text: &str) -> Option<Value> {
    let text = text.trim();
    if let Ok(value @ Value::Object(_)) = serde_json::from_str::<Value>(text) {
        return Some(value);
    }
    let mut spans = Vec::new();
    let mut depth = 0usize;
    let mut start = 0;
    let (mut in_string, mut escaped) = (false, false);
    for (index, character) in text.char_indices() {
        if in_string {
            match character {
                _ if escaped => escaped = false,
                '\\' => escaped = true,
                '"' => in_string = false,
                _ => {}
            }
            continue;
        }
        match character {
            '"' if depth > 0 => in_string = true,
            '{' => {
                if depth == 0 {
                    start = index;
                }
                depth += 1;
            }
            '}' if depth > 0 => {
                depth -= 1;
                if depth == 0 {
                    spans.push(&text[start..=index]);
                }
            }
            _ => {}
        }
    }
    spans
        .iter()
        .rev()
        .find_map(|span| match serde_json::from_str::<Value>(span) {
            Ok(value @ Value::Object(_)) => Some(value),
            _ => None,
        })
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn finds_the_object_in_the_usual_wrappers() {
        let reply = json!({"status": "pass", "summary": "ok"});
        for text in [
            r#"{"status": "pass", "summary": "ok"}"#.to_owned(),
            "  \n{\"status\":\"pass\",\"summary\":\"ok\"}\n".to_owned(),
            "Done.\n```json\n{\"status\":\"pass\",\"summary\":\"ok\"}\n```\n".to_owned(),
            "I checked it. {\"status\":\"pass\",\"summary\":\"ok\"} Hope that helps.".to_owned(),
        ] {
            assert_eq!(extract_object(&text), Some(reply.clone()), "{text}");
        }
    }

    #[test]
    fn takes_the_last_object_and_skips_text_that_only_looks_like_one() {
        let text = r#"Format is {status}. First {"status":"blocked","summary":"a"} then {"status":"pass","summary":"b"}"#;
        assert_eq!(
            extract_object(text),
            Some(json!({"status": "pass", "summary": "b"}))
        );
        assert_eq!(extract_object("see {not json} here"), None);
    }

    #[test]
    fn braces_inside_strings_and_nested_objects_do_not_split_it() {
        let text = r#"x {"summary":"use } and { and \" here","findings":[{"a":{"b":1}}]} y"#;
        assert_eq!(
            extract_object(text),
            Some(json!({"summary": "use } and { and \" here", "findings": [{"a": {"b": 1}}]}))
        );
    }

    #[test]
    fn nothing_to_find() {
        for text in ["", "no json here", "[1, 2]", "{\"open\": "] {
            assert_eq!(extract_object(text), None, "{text}");
        }
    }
}