Skip to main content

adk_graph/definition/
mod.rs

1//! Graph workflows defined in YAML or JSON.
2//!
3//! A [`WorkflowDefinition`] declares a graph as data — agent and LLM nodes, function, `set`,
4//! action and interrupt nodes, edges with conditional routing, checkpointing — and
5//! [`WorkflowDefinition::build`] compiles it into a [`CompiledGraph`](crate::CompiledGraph)
6//! against a [`WorkflowRegistry`] that supplies the agents, models, tools and functions it names.
7//!
8//! ```yaml
9//! # yaml-language-server: $schema=https://raw.githubusercontent.com/zavora-ai/adk-rust/main/adk-graph/schemas/workflow.schema.json
10//! version: 1
11//! name: refund_desk
12//! models:
13//!   fast: anthropic/claude-haiku-5-5
14//! nodes:
15//!   classify:
16//!     llm:
17//!       model: fast
18//!       instruction: Reply with one word, refund or question.
19//!     output_key: category
20//!   approve:
21//!     interrupt:
22//!       message: "Refund requested: {{input}}. Approve?"
23//!     output_key: approval
24//!   reply:
25//!     llm: { model: fast, instruction: Write a one-line reply to the customer. }
26//! edges:
27//!   - [START, classify]
28//!   - from: classify
29//!     routes:
30//!       - when: { field: category, op: matches, value: "(?i)refund" }
31//!         to: approve
32//!     default: reply
33//!   - [approve, reply, END]
34//! ```
35//!
36//! Conditions are data — a field, an operator and a value, combined with `all`, `any` and
37//! `not` — evaluated by the same operators as `adk-action`'s switch node, so a workflow file
38//! never carries code. Every parse and validation issue names its path in the document and,
39//! for YAML, its line and column.
40
41mod build;
42mod location;
43mod types;
44
45use std::path::Path;
46use std::sync::Arc;
47
48pub use build::{FunctionNodeFn, ModelResolver, WorkflowRegistry};
49pub use location::SourceLocation;
50pub use types::{
51    ChannelDefinition, CheckpointDefinition, CheckpointStore, Condition, ConditionOp,
52    EdgeDefinition, EdgeSpec, InterruptDefinition, LlmDefinition, NodeDefinition, ReducerKind,
53    RouteDefinition, Targets, WORKFLOW_FORMAT_VERSION, WorkflowDefinition,
54};
55
56use location::LocationIndex;
57
58/// One problem with a workflow document.
59#[derive(Debug, Clone, PartialEq, Eq)]
60#[non_exhaustive]
61pub struct WorkflowIssue {
62    /// Where in the document, such as `edges[2].to`; empty for the whole document.
63    pub path: String,
64    /// The line and column, for a YAML document.
65    pub location: Option<SourceLocation>,
66    /// What is wrong, and how to fix it.
67    pub message: String,
68}
69
70impl WorkflowIssue {
71    /// An issue at `path`, optionally located.
72    ///
73    /// # Example
74    ///
75    /// ```rust
76    /// use adk_graph::definition::{SourceLocation, WorkflowIssue};
77    ///
78    /// let issue = WorkflowIssue::new(
79    ///     "edges[0].to",
80    ///     Some(SourceLocation { line: 9, column: 9 }),
81    ///     "unknown node 'b'",
82    /// );
83    /// assert_eq!(issue.to_string(), "9:9: edges[0].to: unknown node 'b'");
84    /// ```
85    pub fn new(
86        path: impl Into<String>,
87        location: Option<SourceLocation>,
88        message: impl Into<String>,
89    ) -> Self {
90        Self { path: path.into(), location, message: message.into() }
91    }
92}
93
94impl std::fmt::Display for WorkflowIssue {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        if let Some(location) = self.location {
97            write!(f, "{location}: ")?;
98        }
99        if !self.path.is_empty() {
100            write!(f, "{}: ", self.path)?;
101        }
102        f.write_str(&self.message)
103    }
104}
105
106/// A workflow document that does not parse, validate or build, with every issue found.
107///
108/// # Example
109///
110/// ```rust
111/// use adk_graph::definition::WorkflowDefinition;
112///
113/// let error = WorkflowDefinition::from_yaml_str(
114///     "version: 1\nname: w\nnodes:\n  a: { set: { x: 1 } }\nedges:\n  - [START, a, b]\n",
115/// )
116/// .unwrap_err();
117/// assert_eq!(error.issues[0].path, "edges[0][2]");
118/// assert_eq!(error.issues[0].location.unwrap().line, 6);
119/// ```
120#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
121#[error("{}", self.render())]
122#[non_exhaustive]
123pub struct WorkflowError {
124    /// The document's name, such as its file path.
125    pub source_name: Option<String>,
126    /// Every issue, in document order where known.
127    pub issues: Vec<WorkflowIssue>,
128}
129
130impl WorkflowError {
131    fn render(&self) -> String {
132        let prefix = self.source_name.as_deref().map(|name| format!("{name}:")).unwrap_or_default();
133        let lines: Vec<String> = self
134            .issues
135            .iter()
136            .map(|issue| match (&prefix, issue.location) {
137                (prefix, Some(_)) if !prefix.is_empty() => format!("{prefix}{issue}"),
138                (prefix, _) if !prefix.is_empty() => format!("{prefix} {issue}"),
139                _ => issue.to_string(),
140            })
141            .collect();
142        lines.join("\n")
143    }
144}
145
146impl From<WorkflowError> for crate::GraphError {
147    fn from(error: WorkflowError) -> Self {
148        crate::GraphError::InvalidGraph(error.to_string())
149    }
150}
151
152impl From<WorkflowError> for adk_core::AdkError {
153    fn from(error: WorkflowError) -> Self {
154        crate::GraphError::from(error).into()
155    }
156}
157
158/// What a document was read from, for issue locations and relative paths.
159#[derive(Debug, Clone, Default)]
160pub(crate) struct SourceInfo {
161    pub(crate) name: Option<String>,
162    pub(crate) index: Option<Arc<LocationIndex>>,
163    #[cfg_attr(
164        not(feature = "sqlite"),
165        expect(dead_code, reason = "only the sqlite store resolves a path against the file")
166    )]
167    pub(crate) base_dir: Option<std::path::PathBuf>,
168}
169
170/// Source information does not take part in equality: two definitions are equal when they
171/// declare the same workflow.
172impl PartialEq for SourceInfo {
173    fn eq(&self, _: &Self) -> bool {
174        true
175    }
176}
177
178impl SourceInfo {
179    pub(crate) fn error(&self, issues: Vec<(String, String)>) -> WorkflowError {
180        let mut issues: Vec<WorkflowIssue> = issues
181            .into_iter()
182            .map(|(path, message)| WorkflowIssue {
183                location: self.index.as_ref().and_then(|index| index.locate(&path)),
184                path,
185                message,
186            })
187            .collect();
188        issues.sort_by_key(|issue| issue.location.map(|l| (l.line, l.column)));
189        WorkflowError { source_name: self.name.clone(), issues }
190    }
191}
192
193impl WorkflowDefinition {
194    /// Parses and validates a YAML workflow.
195    ///
196    /// # Errors
197    ///
198    /// Returns every syntax, type and validation issue, each with its path and its line and
199    /// column.
200    pub fn from_yaml_str(yaml: &str) -> Result<Self, WorkflowError> {
201        Self::parse_yaml(yaml, SourceInfo::default())
202    }
203
204    /// Parses and validates a JSON workflow.
205    ///
206    /// # Errors
207    ///
208    /// Returns the syntax or type issue with its line and column, or every validation issue
209    /// with its path.
210    pub fn from_json_str(json: &str) -> Result<Self, WorkflowError> {
211        Self::parse_json(json, SourceInfo::default())
212    }
213
214    /// Reads, parses and validates a workflow file: JSON when its extension is `.json`, YAML
215    /// otherwise. A SQLite checkpoint path in it is relative to the file.
216    ///
217    /// # Errors
218    ///
219    /// Returns an issue when the file cannot be read, and every parse or validation issue,
220    /// prefixed with the file's path.
221    pub fn from_file(path: impl AsRef<Path>) -> Result<Self, WorkflowError> {
222        let path = path.as_ref();
223        let source = SourceInfo {
224            name: Some(path.display().to_string()),
225            index: None,
226            base_dir: path.parent().map(Path::to_path_buf),
227        };
228        let text = std::fs::read_to_string(path).map_err(|error| {
229            source.error(vec![(String::new(), format!("cannot read the workflow file: {error}"))])
230        })?;
231        if path.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("json")) {
232            Self::parse_json(&text, source)
233        } else {
234            Self::parse_yaml(&text, source)
235        }
236    }
237
238    /// Serializes the workflow as YAML.
239    ///
240    /// # Errors
241    ///
242    /// Returns an issue when a value cannot be written as YAML.
243    pub fn to_yaml_string(&self) -> Result<String, WorkflowError> {
244        serde_saphyr::to_string(self).map_err(|error| {
245            self.source.error(vec![(String::new(), format!("cannot write YAML: {error}"))])
246        })
247    }
248
249    /// Checks the workflow without building it: node kinds, references between nodes and
250    /// edges, conditions, interrupts and checkpointing. [`build`](Self::build) checks the
251    /// references to the registry as well.
252    ///
253    /// # Errors
254    ///
255    /// Returns every issue found.
256    pub fn validate(&self) -> Result<(), WorkflowError> {
257        let issues = validate::issues(self);
258        if issues.is_empty() { Ok(()) } else { Err(self.source.error(issues)) }
259    }
260
261    fn parse_yaml(yaml: &str, mut source: SourceInfo) -> Result<Self, WorkflowError> {
262        let index = Arc::new(LocationIndex::of_yaml(yaml));
263        source.index = Some(index);
264        let mut definition: Self = serde_saphyr::from_str(yaml).map_err(|error| {
265            let location = error
266                .location()
267                .filter(|location| location.line() > 0)
268                .map(|l| SourceLocation { line: l.line() as u32, column: l.column() as u32 });
269            WorkflowError {
270                source_name: source.name.clone(),
271                issues: vec![WorkflowIssue {
272                    path: String::new(),
273                    location,
274                    message: first_line(&error.to_string()),
275                }],
276            }
277        })?;
278        definition.source = source;
279        definition.validate()?;
280        Ok(definition)
281    }
282
283    fn parse_json(json: &str, source: SourceInfo) -> Result<Self, WorkflowError> {
284        let mut definition: Self = serde_json::from_str(json).map_err(|error| WorkflowError {
285            source_name: source.name.clone(),
286            issues: vec![WorkflowIssue {
287                path: String::new(),
288                location: (error.line() > 0).then(|| SourceLocation {
289                    line: error.line() as u32,
290                    column: error.column() as u32,
291                }),
292                message: error.to_string(),
293            }],
294        })?;
295        definition.source = source;
296        definition.validate()?;
297        Ok(definition)
298    }
299}
300
301/// The first line of a parser's message, without the source snippet some parsers append.
302fn first_line(message: &str) -> String {
303    message.lines().next().unwrap_or(message).trim().to_string()
304}
305
306/// The JSON Schema of the workflow format, for editor completion and validation.
307///
308/// The committed copy is `adk-graph/schemas/workflow.schema.json`; a YAML file opts in with
309/// `# yaml-language-server: $schema=<url of that file>`.
310///
311/// # Example
312///
313/// ```rust
314/// let schema = adk_graph::definition::workflow_json_schema();
315/// assert_eq!(schema["title"], "ADK-Rust graph workflow");
316/// ```
317pub fn workflow_json_schema() -> serde_json::Value {
318    serde_json::to_value(schemars::schema_for!(WorkflowDefinition)).unwrap_or_default()
319}
320
321mod validate {
322    //! Structural checks that need no registry.
323
324    use std::collections::{BTreeSet, HashSet, VecDeque};
325
326    use super::types::{
327        CheckpointStore, Condition, ConditionOp, EdgeDefinition, EdgeSpec, NodeDefinition,
328        WORKFLOW_FORMAT_VERSION, WorkflowDefinition,
329    };
330
331    pub(super) const START_ID: &str = "START";
332    pub(super) const END_ID: &str = "END";
333
334    type Issues = Vec<(String, String)>;
335
336    pub(super) fn issues(workflow: &WorkflowDefinition) -> Issues {
337        let mut issues = Issues::new();
338        if workflow.version != WORKFLOW_FORMAT_VERSION {
339            issues.push((
340                "version".into(),
341                format!(
342                    "version {} is not supported; this release reads version {WORKFLOW_FORMAT_VERSION}",
343                    workflow.version
344                ),
345            ));
346        }
347        if workflow.name.trim().is_empty() {
348            issues.push(("name".into(), "the workflow needs a name".into()));
349        }
350        if workflow.nodes.is_empty() {
351            issues.push(("nodes".into(), "the workflow declares no nodes".into()));
352        }
353        for (name, reference) in &workflow.models {
354            if reference.trim().is_empty() {
355                issues.push((format!("models.{name}"), "the model reference is empty".into()));
356            }
357        }
358        for (id, node) in &workflow.nodes {
359            check_node(id, node, &mut issues);
360        }
361
362        let declared: BTreeSet<&str> = workflow.nodes.keys().map(String::as_str).collect();
363        let mut successors: Vec<(&str, &str)> = Vec::new();
364        for (index, edge) in workflow.edges.iter().enumerate() {
365            let path = format!("edges[{index}]");
366            match edge {
367                EdgeDefinition::Chain(ids) => {
368                    if ids.len() < 2 {
369                        issues.push((path.clone(), "a chain needs at least two node ids".into()));
370                    }
371                    for (position, id) in ids.iter().enumerate() {
372                        let is_first = position == 0;
373                        let is_last = position + 1 == ids.len();
374                        check_reference(
375                            &format!("{path}[{position}]"),
376                            id,
377                            &declared,
378                            is_first,
379                            is_last,
380                            &mut issues,
381                        );
382                    }
383                    for pair in ids.windows(2) {
384                        successors.push((pair[0].as_str(), pair[1].as_str()));
385                    }
386                }
387                EdgeDefinition::Edge(spec) => {
388                    for target in check_spec(&path, spec, &declared, &mut issues) {
389                        successors.push((spec.from.as_str(), target));
390                    }
391                }
392            }
393        }
394
395        if !successors.iter().any(|(from, _)| *from == START_ID) {
396            issues.push((
397                "edges".into(),
398                "no edge leaves START; add one such as `- [START, <first node>]`".into(),
399            ));
400        } else {
401            let mut reached: HashSet<&str> = HashSet::from([START_ID]);
402            let mut queue = VecDeque::from([START_ID]);
403            while let Some(node) = queue.pop_front() {
404                for (_, next) in successors.iter().filter(|(from, _)| *from == node) {
405                    if reached.insert(next) {
406                        queue.push_back(next);
407                    }
408                }
409            }
410            for id in &declared {
411                if !reached.contains(id) {
412                    issues.push((
413                        format!("nodes.{id}"),
414                        format!("node '{id}' is unreachable from START; add an edge to it"),
415                    ));
416                }
417            }
418        }
419
420        for (field, ids) in [
421            ("interrupt_before", &workflow.interrupt_before),
422            ("interrupt_after", &workflow.interrupt_after),
423        ] {
424            for (index, id) in ids.iter().enumerate() {
425                if !declared.contains(id.as_str()) {
426                    issues.push((format!("{field}[{index}]"), unknown_node(id, &declared)));
427                }
428            }
429        }
430
431        let pauses = !workflow.interrupt_before.is_empty()
432            || !workflow.interrupt_after.is_empty()
433            || workflow.nodes.values().any(|node| node.interrupt.is_some());
434        match workflow.checkpoint.store {
435            CheckpointStore::None if pauses => issues.push((
436                "checkpoint.store".into(),
437                "a workflow that pauses needs checkpoints to resume from; use `memory` or `sqlite`"
438                    .into(),
439            )),
440            CheckpointStore::Sqlite if workflow.checkpoint.path.is_none() => issues.push((
441                "checkpoint".into(),
442                "a `sqlite` store needs a `path` to the database file".into(),
443            )),
444            CheckpointStore::Memory | CheckpointStore::None
445                if workflow.checkpoint.path.is_some() =>
446            {
447                issues.push((
448                    "checkpoint.path".into(),
449                    "`path` applies only to the `sqlite` store".into(),
450                ));
451            }
452            _ => {}
453        }
454        if workflow.recursion_limit == Some(0) {
455            issues
456                .push(("recursion_limit".into(), "the recursion limit must be at least 1".into()));
457        }
458        issues
459    }
460
461    fn check_node(id: &str, node: &NodeDefinition, issues: &mut Issues) {
462        let path = format!("nodes.{id}");
463        if !valid_id(id) {
464            issues.push((
465                path.clone(),
466                format!(
467                    "'{id}' is not a valid node id; use letters, digits, `_` and `-`, starting \
468                     with a letter or `_`, and not START or END"
469                ),
470            ));
471        }
472        let kinds: Vec<&str> = [
473            ("agent", node.agent.is_some()),
474            ("llm", node.llm.is_some()),
475            ("function", node.function.is_some()),
476            ("set", node.set.is_some()),
477            ("action", node.action.is_some()),
478            ("interrupt", node.interrupt.is_some()),
479        ]
480        .into_iter()
481        .filter_map(|(kind, set)| set.then_some(kind))
482        .collect();
483        match kinds.as_slice() {
484            [] => issues.push((
485                path.clone(),
486                "the node has no kind; set one of agent, llm, function, set, action or interrupt"
487                    .into(),
488            )),
489            [_] => {}
490            many => issues.push((
491                path.clone(),
492                format!("the node sets {}; set exactly one kind", many.join(" and ")),
493            )),
494        }
495        let runs_agent = node.agent.is_some() || node.llm.is_some();
496        if node.input.is_some() && !runs_agent {
497            issues.push((
498                format!("{path}.input"),
499                "`input` applies only to agent and llm nodes".into(),
500            ));
501        }
502        if node.output_key.is_some() && (node.set.is_some() || node.function.is_some()) {
503            issues.push((
504                format!("{path}.output_key"),
505                "`output_key` does not apply to set and function nodes, which name their own keys"
506                    .into(),
507            ));
508        }
509        if node.output_key.as_deref().is_some_and(|key| key.trim().is_empty()) {
510            issues.push((format!("{path}.output_key"), "the output key is empty".into()));
511        }
512        if node.max_attempts == Some(0) {
513            issues
514                .push((format!("{path}.max_attempts"), "a node needs at least one attempt".into()));
515        }
516        if let Some(agent) = &node.agent
517            && agent.trim().is_empty()
518        {
519            issues.push((format!("{path}.agent"), "the agent name is empty".into()));
520        }
521        if let Some(llm) = &node.llm
522            && llm.model.trim().is_empty()
523        {
524            issues.push((format!("{path}.llm.model"), "the model reference is empty".into()));
525        }
526        if let Some(function) = &node.function
527            && function.trim().is_empty()
528        {
529            issues.push((format!("{path}.function"), "the function name is empty".into()));
530        }
531        if let Some(set) = &node.set
532            && set.is_empty()
533        {
534            issues.push((format!("{path}.set"), "`set` names no keys".into()));
535        }
536        if let Some(action) = &node.action
537            && let Err(message) =
538                super::build::action_config(id, action, node.output_key.as_deref())
539        {
540            issues.push((format!("{path}.action"), message));
541        }
542        if let Some(interrupt) = &node.interrupt {
543            if interrupt.message.trim().is_empty() {
544                issues.push((format!("{path}.interrupt.message"), "the message is empty".into()));
545            }
546            if let Some(schema) = &interrupt.response_schema
547                && let Err(error) = jsonschema::validator_for(schema)
548            {
549                issues.push((
550                    format!("{path}.interrupt.response_schema"),
551                    format!("not a valid JSON Schema: {error}"),
552                ));
553            }
554        }
555    }
556
557    /// Checks an edge object; returns the targets it can reach.
558    fn check_spec<'a>(
559        path: &str,
560        spec: &'a EdgeSpec,
561        declared: &BTreeSet<&str>,
562        issues: &mut Issues,
563    ) -> Vec<&'a str> {
564        check_reference(&format!("{path}.from"), &spec.from, declared, true, false, issues);
565        let forms = [spec.to.is_some(), !spec.routes.is_empty(), spec.switch.is_some()];
566        let mut targets: Vec<(String, &'a str)> = Vec::new();
567        match forms.iter().filter(|set| **set).count() {
568            0 => issues.push((
569                path.into(),
570                "the edge has no target; set `to`, `routes`, or `switch` with `cases`".into(),
571            )),
572            1 => {}
573            _ => issues.push((path.into(), "set only one of `to`, `routes` and `switch`".into())),
574        }
575        if let Some(to) = &spec.to {
576            let ids = to.ids();
577            if ids.is_empty() {
578                issues.push((format!("{path}.to"), "`to` lists no nodes".into()));
579            }
580            if ids.len() == 1 {
581                targets.push((format!("{path}.to"), ids[0]));
582            } else {
583                for (index, id) in ids.into_iter().enumerate() {
584                    targets.push((format!("{path}.to[{index}]"), id));
585                }
586            }
587            if spec.default.is_some() {
588                issues.push((
589                    format!("{path}.default"),
590                    "`default` applies only to `routes` and `switch`".into(),
591                ));
592            }
593        }
594        if spec.from == START_ID && (!spec.routes.is_empty() || spec.switch.is_some()) {
595            issues.push((
596                format!("{path}.from"),
597                "edges from START cannot be conditional; route from the first node instead".into(),
598            ));
599        }
600        for (index, route) in spec.routes.iter().enumerate() {
601            check_condition(&format!("{path}.routes[{index}].when"), &route.when, issues);
602            targets.push((format!("{path}.routes[{index}].to"), route.to.as_str()));
603        }
604        if let Some(field) = &spec.switch {
605            if field.trim().is_empty() {
606                issues.push((format!("{path}.switch"), "the state path is empty".into()));
607            }
608            if spec.cases.is_empty() {
609                issues.push((format!("{path}.cases"), "`switch` needs `cases`".into()));
610            }
611        }
612        if !spec.cases.is_empty() && spec.switch.is_none() {
613            issues.push((format!("{path}.cases"), "`cases` applies only with `switch`".into()));
614        }
615        for (value, target) in &spec.cases {
616            targets.push((format!("{path}.cases.{value}"), target.as_str()));
617        }
618        if let Some(default) = &spec.default {
619            targets.push((format!("{path}.default"), default.as_str()));
620        }
621        for (target_path, id) in &targets {
622            check_reference(target_path, id, declared, false, true, issues);
623        }
624        targets.into_iter().map(|(_, id)| id).collect()
625    }
626
627    fn check_condition(path: &str, condition: &Condition, issues: &mut Issues) {
628        let comparison =
629            condition.field.is_some() || condition.op.is_some() || condition.value.is_some();
630        let forms =
631            [comparison, condition.all.is_some(), condition.any.is_some(), condition.not.is_some()];
632        match forms.iter().filter(|set| **set).count() {
633            0 => {
634                issues.push((
635                    path.into(),
636                    "the condition is empty; set `field` and `op`, or `all`, `any` or `not`".into(),
637                ));
638                return;
639            }
640            1 => {}
641            _ => issues.push((
642                path.into(),
643                "set only one of a comparison (`field`, `op`, `value`), `all`, `any` and `not`"
644                    .into(),
645            )),
646        }
647        if comparison {
648            match &condition.field {
649                Some(field) if !field.trim().is_empty() => {}
650                _ => issues.push((format!("{path}.field"), "a comparison needs a `field`".into())),
651            }
652            match condition.op {
653                None => issues.push((format!("{path}.op"), "a comparison needs an `op`".into())),
654                Some(op) if op.takes_value() && condition.value.is_none() => issues
655                    .push((format!("{path}.value"), format!("`{}` needs a `value`", op_name(op)))),
656                Some(op) if !op.takes_value() && condition.value.is_some() => issues
657                    .push((format!("{path}.value"), format!("`{}` takes no `value`", op_name(op)))),
658                Some(ConditionOp::Matches) => {
659                    let pattern = condition.value.as_ref().and_then(|value| value.as_str());
660                    match pattern.map(regex::Regex::new) {
661                        Some(Ok(_)) => {}
662                        Some(Err(error)) => issues.push((
663                            format!("{path}.value"),
664                            format!("not a valid regular expression: {error}"),
665                        )),
666                        None => issues.push((
667                            format!("{path}.value"),
668                            "`matches` needs a regular expression string".into(),
669                        )),
670                    }
671                }
672                Some(_) => {}
673            }
674            if let Some(value) = &condition.value
675                && (value.is_object()
676                    || (value.is_array() && condition.op != Some(ConditionOp::In)))
677            {
678                issues.push((
679                    format!("{path}.value"),
680                    "the value must be a string, number or boolean (a list only for `in`)".into(),
681                ));
682            }
683        }
684        for (key, list) in [("all", &condition.all), ("any", &condition.any)] {
685            if let Some(list) = list {
686                if list.is_empty() {
687                    issues.push((format!("{path}.{key}"), format!("`{key}` lists no conditions")));
688                }
689                for (index, inner) in list.iter().enumerate() {
690                    check_condition(&format!("{path}.{key}[{index}]"), inner, issues);
691                }
692            }
693        }
694        if let Some(inner) = &condition.not {
695            check_condition(&format!("{path}.not"), inner, issues);
696        }
697    }
698
699    fn op_name(op: ConditionOp) -> String {
700        serde_json::to_value(op)
701            .ok()
702            .and_then(|value| value.as_str().map(str::to_string))
703            .unwrap_or_default()
704    }
705
706    fn check_reference(
707        path: &str,
708        id: &str,
709        declared: &BTreeSet<&str>,
710        may_be_start: bool,
711        may_be_end: bool,
712        issues: &mut Issues,
713    ) {
714        match id {
715            START_ID if may_be_start => {}
716            START_ID => issues.push((path.into(), "START can only begin an edge".into())),
717            END_ID if may_be_end => {}
718            END_ID => issues.push((path.into(), "END can only finish an edge".into())),
719            id if declared.contains(id) => {}
720            id => issues.push((path.into(), unknown_node(id, declared))),
721        }
722    }
723
724    fn unknown_node(id: &str, declared: &BTreeSet<&str>) -> String {
725        let known: Vec<&str> = declared.iter().copied().collect();
726        format!("unknown node '{id}'; declared nodes are {}", known.join(", "))
727    }
728
729    pub(super) fn valid_id(id: &str) -> bool {
730        let mut chars = id.chars();
731        chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
732            && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
733            && !matches!(id, START_ID | END_ID | crate::START | crate::END)
734    }
735}