Skip to main content

agentic_graph_spec/
parse.rs

1use std::{fs, path::Path};
2
3use serde::{
4    Deserialize, Deserializer,
5    de::{MapAccess, SeqAccess, Visitor},
6};
7use serde_json::{Map, Number, Value};
8use thiserror::Error;
9
10use crate::Document;
11
12/// AGS parsing failure with a stable diagnostic code.
13#[derive(Debug, Error)]
14#[error("{message}")]
15pub struct ParseError {
16    /// `AG001` for general parse failures or `AG005` for duplicate keys.
17    pub code: &'static str,
18    /// Human-readable parsing failure.
19    pub message: String,
20}
21
22/// Parses a JSON or YAML AGS document with duplicate-key rejection.
23///
24/// `format` is matched case-insensitively; `json` selects JSON and all other
25/// values select YAML.
26pub fn parse(input: &str, format: &str) -> Result<Document, ParseError> {
27    if input.trim().is_empty() {
28        return Err(ParseError {
29            code: "AG001",
30            message: "parse error: empty document".into(),
31        });
32    }
33    let value: Value = if format.eq_ignore_ascii_case("json") {
34        serde_json::from_str(input).map_err(|error| ParseError {
35            code: "AG001",
36            message: format!("parse error: {error}"),
37        })?
38    } else {
39        serde_yaml_ng::from_str::<UniqueValue>(input)
40            .map(|value| value.0)
41            .map_err(|error| {
42                let text = error.to_string();
43                let code = if text.to_lowercase().contains("duplicate") {
44                    "AG005"
45                } else {
46                    "AG001"
47                };
48                ParseError {
49                    code,
50                    message: format!("parse error: {text}"),
51                }
52            })?
53    };
54    value.as_object().cloned().ok_or(ParseError {
55        code: "AG001",
56        message: "document root must be an object".into(),
57    })
58}
59
60struct UniqueValue(Value);
61
62impl<'de> Deserialize<'de> for UniqueValue {
63    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
64        struct ValueVisitor;
65        impl<'de> Visitor<'de> for ValueVisitor {
66            type Value = UniqueValue;
67            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
68                formatter.write_str("a JSON-compatible YAML value")
69            }
70            fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E> {
71                Ok(UniqueValue(Value::Bool(value)))
72            }
73            fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E> {
74                Ok(UniqueValue(Value::Number(value.into())))
75            }
76            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> {
77                Ok(UniqueValue(Value::Number(value.into())))
78            }
79            fn visit_f64<E: serde::de::Error>(self, value: f64) -> Result<Self::Value, E> {
80                Number::from_f64(value)
81                    .map(Value::Number)
82                    .map(UniqueValue)
83                    .ok_or_else(|| E::custom("non-finite number"))
84            }
85            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> {
86                Ok(UniqueValue(Value::String(value.into())))
87            }
88            fn visit_string<E>(self, value: String) -> Result<Self::Value, E> {
89                Ok(UniqueValue(Value::String(value)))
90            }
91            fn visit_none<E>(self) -> Result<Self::Value, E> {
92                Ok(UniqueValue(Value::Null))
93            }
94            fn visit_unit<E>(self) -> Result<Self::Value, E> {
95                Ok(UniqueValue(Value::Null))
96            }
97            fn visit_seq<A: SeqAccess<'de>>(
98                self,
99                mut sequence: A,
100            ) -> Result<Self::Value, A::Error> {
101                let mut values = vec![];
102                while let Some(value) = sequence.next_element::<UniqueValue>()? {
103                    values.push(value.0);
104                }
105                Ok(UniqueValue(Value::Array(values)))
106            }
107            fn visit_map<A: MapAccess<'de>>(self, mut mapping: A) -> Result<Self::Value, A::Error> {
108                let mut values = Map::new();
109                while let Some((key, value)) = mapping.next_entry::<String, UniqueValue>()? {
110                    if values.contains_key(&key) {
111                        return Err(serde::de::Error::custom(format!("duplicate key {key:?}")));
112                    }
113                    values.insert(key, value.0);
114                }
115                Ok(UniqueValue(Value::Object(values)))
116            }
117        }
118        deserializer.deserialize_any(ValueVisitor)
119    }
120}
121
122/// Loads an AGS document, selecting JSON for `.json` paths and YAML otherwise.
123pub fn load(path: impl AsRef<Path>) -> Result<Document, ParseError> {
124    let path = path.as_ref();
125    let input = fs::read_to_string(path).map_err(|error| ParseError {
126        code: "AG001",
127        message: error.to_string(),
128    })?;
129    let format = if path
130        .extension()
131        .is_some_and(|extension| extension.eq_ignore_ascii_case("json"))
132    {
133        "json"
134    } else {
135        "yaml"
136    };
137    parse(&input, format)
138}