Skip to main content

graphrt_core/
validate.rs

1//! Whole-document validation that collects every finding.
2//!
3//! [`Graph::build`] stops at the first problem, which suits programs. People
4//! editing a document want all of them at once, each pointing at the text
5//! that caused it. [`validate_text`] parses a JSON or YAML document, checks
6//! it against the node catalog and returns every [`Diagnostic`] with its
7//! document path (`graph.nodes[1].template`), source position, and a
8//! "did you mean" suggestion where one is close enough. When nothing is
9//! wrong it also returns the compiled graph.
10//!
11//! Checks, in addition to everything [`Graph::build`] enforces:
12//!
13//! - unknown fields, for the document, graph, nodes, edges, policies and node
14//!   configs whose catalog schema is closed (`additionalProperties: false`;
15//!   every built-in kind). Plugin configs with open schemas take any key;
16//! - required config fields from the catalog schema;
17//! - unknown node types, node ids in edges, parents and selectors, and edge
18//!   handles the source node never selects;
19//! - deprecated spellings (warnings).
20//!
21//! Documents in the import layout (a top-level `workflow` or `app` key, or
22//! nodes wrapped in `data`) are checked leniently: unknown fields are not
23//! reported for them.
24
25use std::collections::{HashMap, HashSet};
26use std::fmt;
27use std::sync::Arc;
28
29use serde::Serialize;
30
31use crate::catalog::{Handles, NodeDescriptor};
32use crate::dsl::{ErrorStrategy, NodeDoc};
33use crate::graph::{FAIL_BRANCH, Graph, GraphError, SOURCE_HANDLE};
34use crate::node::{ConfigError, Node, NodeRole, Registry};
35pub use crate::source_map::{DocPath, PathSegment, SourceMap, SourceSpan};
36
37/// How serious a finding is.
38#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
39#[serde(rename_all = "lowercase")]
40pub enum Severity {
41    /// The document is rejected.
42    Error,
43    /// The document runs, but probably not as intended, or uses a deprecated spelling.
44    Warning,
45}
46
47/// One validation finding.
48#[derive(Clone, Debug, PartialEq, Serialize)]
49#[non_exhaustive]
50pub struct Diagnostic {
51    pub severity: Severity,
52    /// Stable machine-readable category, e.g. `unknown-field`, `unknown-node`.
53    pub code: &'static str,
54    pub message: String,
55    /// Where in the document, e.g. `graph.nodes[1].template`.
56    pub path: DocPath,
57    /// Source position (`line`, `column`, `length`), when known.
58    #[serde(flatten)]
59    pub span: Option<SourceSpan>,
60    /// Id of the node the finding is about.
61    #[serde(skip_serializing_if = "Option::is_none")]
62    pub node: Option<String>,
63    /// Likely intended spelling ("did you mean `template`?").
64    #[serde(skip_serializing_if = "Option::is_none")]
65    pub suggestion: Option<String>,
66    /// Extra guidance.
67    #[serde(skip_serializing_if = "Option::is_none")]
68    pub help: Option<String>,
69    /// Point at the key of `path` rather than its value.
70    #[serde(skip)]
71    pub at_key: bool,
72}
73
74impl Diagnostic {
75    pub fn error(code: &'static str, path: DocPath, message: impl Into<String>) -> Self {
76        Self::new(Severity::Error, code, path, message.into())
77    }
78
79    pub fn warning(code: &'static str, path: DocPath, message: impl Into<String>) -> Self {
80        Self::new(Severity::Warning, code, path, message.into())
81    }
82
83    fn new(severity: Severity, code: &'static str, path: DocPath, message: String) -> Self {
84        Self { severity, code, message, path, span: None, node: None, suggestion: None, help: None, at_key: false }
85    }
86
87    /// Point at the key of the path (for unknown or misspelled fields).
88    #[must_use]
89    pub fn at_key(mut self) -> Self {
90        self.at_key = true;
91        self
92    }
93
94    #[must_use]
95    pub fn with_suggestion(mut self, suggestion: Option<String>) -> Self {
96        self.suggestion = suggestion;
97        self
98    }
99
100    #[must_use]
101    pub fn with_help(mut self, help: impl Into<String>) -> Self {
102        self.help = Some(help.into());
103        self
104    }
105
106    #[must_use]
107    pub fn with_node(mut self, id: &str) -> Self {
108        self.node = Some(id.to_owned());
109        self
110    }
111
112    pub fn is_error(&self) -> bool {
113        self.severity == Severity::Error
114    }
115}
116
117impl fmt::Display for Diagnostic {
118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119        write!(f, "{}: {}", self.path, self.message)?;
120        if let Some(s) = &self.suggestion {
121            write!(f, " (did you mean `{s}`?)")?;
122        }
123        Ok(())
124    }
125}
126
127/// Result of [`validate_text`].
128#[derive(Debug)]
129pub struct Validation {
130    /// Every finding, in document order.
131    pub diagnostics: Vec<Diagnostic>,
132    /// The compiled graph, when there are no errors.
133    pub graph: Option<Graph>,
134}
135
136impl Validation {
137    pub fn has_errors(&self) -> bool {
138        self.diagnostics.iter().any(Diagnostic::is_error)
139    }
140
141    pub fn errors(&self) -> impl Iterator<Item = &Diagnostic> {
142        self.diagnostics.iter().filter(|d| d.is_error())
143    }
144
145    pub fn warnings(&self) -> impl Iterator<Item = &Diagnostic> {
146        self.diagnostics.iter().filter(|d| !d.is_error())
147    }
148}
149
150/// The closest candidate to `word` by edit distance, if it is close enough to
151/// be a likely typo (at most one edit per three characters, minimum one).
152/// A case-insensitive exact match always wins.
153pub fn suggest<'a, I>(word: &str, candidates: I) -> Option<String>
154where
155    I: IntoIterator<Item = &'a str>,
156{
157    let limit = (word.chars().count().max(3) / 3).max(1);
158    let lower = word.to_lowercase();
159    let mut best: Option<(usize, &str)> = None;
160    for candidate in candidates {
161        if candidate == word {
162            continue;
163        }
164        let distance =
165            if candidate.to_lowercase() == lower { 0 } else { edit_distance(&lower, &candidate.to_lowercase()) };
166        if distance <= limit && best.is_none_or(|(d, _)| distance < d) {
167            best = Some((distance, candidate));
168        }
169    }
170    best.map(|(_, c)| c.to_owned())
171}
172
173/// Optimal string alignment distance (Levenshtein plus adjacent transpositions).
174fn edit_distance(a: &str, b: &str) -> usize {
175    let a: Vec<char> = a.chars().collect();
176    let b: Vec<char> = b.chars().collect();
177    let width = b.len() + 1;
178    let mut table = vec![0usize; (a.len() + 1) * width];
179    let at = |i: usize, j: usize| i * width + j;
180    for i in 0..=a.len() {
181        if let Some(cell) = table.get_mut(at(i, 0)) {
182            *cell = i;
183        }
184    }
185    for j in 0..=b.len() {
186        if let Some(cell) = table.get_mut(at(0, j)) {
187            *cell = j;
188        }
189    }
190    for i in 1..=a.len() {
191        for j in 1..=b.len() {
192            let get = |i: usize, j: usize| table.get(at(i, j)).copied().unwrap_or(usize::MAX - 1);
193            let same = a.get(i - 1) == b.get(j - 1);
194            let mut value = (get(i - 1, j) + 1).min(get(i, j - 1) + 1).min(get(i - 1, j - 1) + usize::from(!same));
195            if i > 1 && j > 1 && a.get(i - 1) == b.get(j - 2) && a.get(i - 2) == b.get(j - 1) {
196                value = value.min(get(i - 2, j - 2) + 1);
197            }
198            if let Some(cell) = table.get_mut(at(i, j)) {
199                *cell = value;
200            }
201        }
202    }
203    table.last().copied().unwrap_or(0)
204}
205
206/// Rendered " (did you mean `x`?)" suffix, or nothing.
207pub(crate) fn did_you_mean(suggestion: &Option<String>) -> String {
208    suggestion.as_ref().map(|s| format!("; did you mean `{s}`?")).unwrap_or_default()
209}
210
211/// Parse, check and compile a JSON or YAML document, collecting every finding.
212/// A prompt message that names a `file` is an error: see [`validate_text_with`].
213pub fn validate_text(text: &str, registry: &Registry) -> Validation {
214    validate_text_with(text, registry, None)
215}
216
217/// [`validate_text`] for a document loaded from a file: `read` reads the
218/// prompt files its messages name, relative to the document
219/// ([`crate::prompt_files`]).
220pub fn validate_text_with(
221    text: &str,
222    registry: &Registry,
223    read: Option<crate::prompt_files::ReadFile<'_>>,
224) -> Validation {
225    #[cfg_attr(not(feature = "prompt-files"), allow(unused_mut))]
226    let mut raw = match parse_raw(text) {
227        Ok(raw) => raw,
228        Err(diagnostic) => return Validation { diagnostics: vec![*diagnostic], graph: None },
229    };
230    // Only builds with model nodes have prompts to read.
231    #[cfg(feature = "prompt-files")]
232    let files = crate::prompt_files::inline(&mut raw, read);
233    #[cfg(not(feature = "prompt-files"))]
234    let files: Vec<Diagnostic> = {
235        let _ = read;
236        Vec::new()
237    };
238    let mut validation =
239        if files.is_empty() { validate_value(raw, registry) } else { Validation { diagnostics: files, graph: None } };
240    // Positions are only needed to report findings; a clean document skips the
241    // second, span-tracking parse.
242    if validation.diagnostics.iter().any(|d| d.span.is_none()) {
243        let map = SourceMap::from_text(text);
244        for d in &mut validation.diagnostics {
245            if d.span.is_none() {
246                d.span = map.locate(&d.path, d.at_key);
247            }
248        }
249    }
250    // Document order; findings without a position keep their relative order at the end.
251    validation.diagnostics.sort_by_key(|d| d.span.map_or((u32::MAX, u32::MAX), |s| (s.line, s.column)));
252    validation
253}
254
255/// Check and compile an already-decoded document (no source positions).
256pub fn validate_value(raw: serde_json::Value, registry: &Registry) -> Validation {
257    let decoded = crate::dsl::decode(raw);
258    let mut diagnostics = decoded.diagnostics;
259    let paths = Paths { nodes: decoded.node_paths, edges: decoded.edge_paths };
260    let built = check_graph(&decoded.workflow, &paths, registry, &mut diagnostics);
261    if diagnostics.iter().any(Diagnostic::is_error) {
262        return Validation { diagnostics, graph: None };
263    }
264    let ids: Vec<String> = decoded.workflow.graph.nodes.iter().map(|n| n.id.clone()).collect();
265    let checked: Option<Vec<Arc<dyn Node>>> = built.into_iter().collect();
266    let graph = match checked {
267        Some(nodes) => Graph::build_checked(decoded.workflow, registry, nodes),
268        None => Graph::build(decoded.workflow, registry),
269    };
270    match graph {
271        Ok(graph) => {
272            for warning in graph.warnings() {
273                let path = backticked(warning)
274                    .and_then(|id| ids.iter().position(|n| n == id))
275                    .and_then(|ix| paths.nodes.get(ix).cloned())
276                    .unwrap_or_default();
277                diagnostics.push(Diagnostic::warning("graph", path, warning.clone()));
278            }
279            Validation { diagnostics, graph: Some(graph) }
280        }
281        Err(error) => {
282            let path = backticked(&error.to_string())
283                .and_then(|id| ids.iter().position(|n| n == id))
284                .and_then(|ix| paths.nodes.get(ix).cloned())
285                .unwrap_or_else(|| DocPath::root().key("graph"));
286            diagnostics.push(Diagnostic::error("graph", path, error.to_string()));
287            Validation { diagnostics, graph: None }
288        }
289    }
290}
291
292/// The first `` `quoted` `` word of a message.
293fn backticked(message: &str) -> Option<&str> {
294    let start = message.find('`')? + 1;
295    let len = message.get(start..)?.find('`')?;
296    message.get(start..start + len)
297}
298
299/// Parse JSON (text starting with `{`) or YAML into a JSON value.
300fn parse_raw(text: &str) -> Result<serde_json::Value, Box<Diagnostic>> {
301    let syntax = |message: String, line: usize, column: usize| {
302        let mut d = Diagnostic::error("syntax", DocPath::root(), message);
303        if let (Ok(line), Ok(column)) = (u32::try_from(line), u32::try_from(column))
304            && line > 0
305        {
306            d.span = Some(SourceSpan { line, column: column.max(1), len: 1 });
307        }
308        Box::new(d)
309    };
310    if text.trim_start().starts_with('{') {
311        return serde_json::from_slice(text.as_bytes())
312            .map_err(|e| syntax(format!("invalid JSON: {}", strip_position(&e.to_string())), e.line(), e.column()));
313    }
314    #[cfg(feature = "yaml")]
315    {
316        crate::yaml::to_value(text, true).map_err(|e| {
317            let (line, column) = e
318                .location()
319                .map(|l| (usize::try_from(l.line()).unwrap_or(0), usize::try_from(l.column()).unwrap_or(0)))
320                .unwrap_or((0, 0));
321            let message = e.to_string();
322            let first = message.lines().next().unwrap_or("invalid YAML").trim().to_owned();
323            syntax(format!("invalid YAML: {}", strip_position(&first)), line, column)
324        })
325    }
326    #[cfg(not(feature = "yaml"))]
327    {
328        serde_json::from_slice(text.as_bytes()).map_err(|e| {
329            syntax(
330                format!("invalid JSON (YAML support is not compiled in): {}", strip_position(&e.to_string())),
331                e.line(),
332                e.column(),
333            )
334        })
335    }
336}
337
338/// Drop a trailing " at line X column Y" that the position already carries.
339fn strip_position(message: &str) -> String {
340    match message.rfind(" at line ") {
341        Some(ix) => message.get(..ix).unwrap_or(message).to_owned(),
342        None => message.to_owned(),
343    }
344}
345
346struct Paths {
347    nodes: Vec<DocPath>,
348    edges: Vec<DocPath>,
349}
350
351impl Paths {
352    fn node(&self, ix: usize) -> DocPath {
353        self.nodes.get(ix).cloned().unwrap_or_default()
354    }
355    fn edge(&self, ix: usize) -> DocPath {
356        self.edges.get(ix).cloned().unwrap_or_default()
357    }
358}
359
360/// Graph-level checks over every decoded node and edge.
361/// Check the whole document, collecting every finding in `out`. Returns the node
362/// built for each document node (`None` where it could not be built), so a clean
363/// document can be compiled without building its nodes again.
364fn check_graph(
365    workflow: &crate::Workflow,
366    paths: &Paths,
367    registry: &Registry,
368    out: &mut Vec<Diagnostic>,
369) -> Vec<Option<Arc<dyn Node>>> {
370    let nodes = &workflow.graph.nodes;
371    let ids: Vec<&str> = nodes.iter().map(|n| n.id.as_str()).collect();
372    let mut index: HashMap<&str, usize> = HashMap::with_capacity(nodes.len());
373    for (ix, node) in nodes.iter().enumerate() {
374        let path = paths.node(ix).key("id");
375        if let Err(GraphError::InvalidNodeId { reason, .. }) = crate::graph::validate_node_id(&node.id) {
376            out.push(
377                Diagnostic::error("invalid-node-id", path.clone(), format!("node id `{}` {reason}", node.id))
378                    .with_node(&node.id),
379            );
380        }
381        if let Some(first) = index.insert(&node.id, ix) {
382            index.insert(&node.id, first);
383            out.push(
384                Diagnostic::error("duplicate-node", path, format!("duplicate node id `{}`", node.id))
385                    .with_node(&node.id)
386                    .with_help(format!("first defined at {}", paths.node(first))),
387            );
388        }
389    }
390
391    let mut built: Vec<Option<Arc<dyn Node>>> = Vec::with_capacity(nodes.len());
392    for (ix, doc) in nodes.iter().enumerate() {
393        built.push(check_node(doc, &paths.node(ix), registry, out));
394    }
395
396    check_parents(nodes, &index, &built, paths, out);
397    check_edges(workflow, &index, &ids, &built, paths, registry, out);
398    check_references(nodes, &index, &ids, &built, paths, out);
399    built
400}
401
402/// Type, fields and configuration of one node. Returns the built node.
403fn check_node(doc: &NodeDoc, path: &DocPath, registry: &Registry, out: &mut Vec<Diagnostic>) -> Option<Arc<dyn Node>> {
404    if !registry.contains(&doc.kind) {
405        let mut kinds: Vec<&str> = registry.kinds().collect();
406        kinds.sort_unstable();
407        out.push(
408            Diagnostic::error("unknown-node-type", path.key("type"), format!("unknown node type `{}`", doc.kind))
409                .with_node(&doc.id)
410                .with_suggestion(suggest(&doc.kind, kinds))
411                .with_help("node types come from built-in features and plugins"),
412        );
413        return None;
414    }
415    if doc.strict
416        && let Some(descriptor) = registry.descriptor_ref(&doc.kind)
417    {
418        out.extend(config_diagnostics(doc, descriptor, path));
419    }
420    match registry.build(doc) {
421        Ok(node) => Some(node),
422        Err(error) => {
423            out.push(config_error(&error, path));
424            None
425        }
426    }
427}
428
429fn config_error(error: &ConfigError, base: &DocPath) -> Diagnostic {
430    let path = error.field.as_deref().map(|field| join_dotted(base, field)).unwrap_or_else(|| base.clone());
431    Diagnostic::error(
432        "invalid-config",
433        path,
434        format!("invalid `{}` node `{}`: {}", error.kind, error.node_id, error.message),
435    )
436    .with_node(&error.node_id)
437}
438
439/// `base` extended by a serde-style path such as `variables[0].value_selector`.
440fn join_dotted(base: &DocPath, field: &str) -> DocPath {
441    let mut path = base.clone();
442    for part in field.split('.') {
443        let (key, indices) = match part.find('[') {
444            Some(ix) => (part.get(..ix).unwrap_or(part), part.get(ix..).unwrap_or("")),
445            None => (part, ""),
446        };
447        if !key.is_empty() && key != "?" {
448            path = path.key(key);
449        }
450        for index in indices.split(['[', ']']).filter(|s| !s.is_empty()) {
451            if let Ok(ix) = index.parse() {
452                path = path.index(ix);
453            }
454        }
455    }
456    path
457}
458
459/// Unknown, missing and deprecated config fields of a strict node, judged by its catalog schema.
460pub(crate) fn config_diagnostics(doc: &NodeDoc, descriptor: &NodeDescriptor, base: &DocPath) -> Vec<Diagnostic> {
461    let mut issues = Vec::new();
462    let config = serde_json::Value::Object(doc.config.clone());
463    let scope = Scope { kind: &doc.kind, depth: base.segments().len() };
464    walk_schema(&descriptor.config_schema, &config, base, &scope, &mut issues);
465    for issue in &mut issues {
466        issue.node = Some(doc.id.clone());
467    }
468    issues
469}
470
471/// Report unknown keys (closed object schemas only), missing required keys and
472/// deprecated keys. Composition keywords (`oneOf`, `anyOf`, ...) are not followed.
473fn walk_schema(
474    schema: &serde_json::Value,
475    value: &serde_json::Value,
476    path: &DocPath,
477    scope: &Scope<'_>,
478    out: &mut Vec<Diagnostic>,
479) {
480    let Some(schema) = schema.as_object() else { return };
481    match value {
482        serde_json::Value::Object(map) => {
483            let properties = schema.get("properties").and_then(serde_json::Value::as_object);
484            let closed = schema.get("additionalProperties") == Some(&serde_json::Value::Bool(false))
485                && !schema.contains_key("patternProperties");
486            let extra = schema.get("additionalProperties").filter(|s| s.is_object());
487            let known: Vec<&str> = properties
488                .map(|p| {
489                    p.iter()
490                        .filter(|(_, s)| s.get("deprecated") != Some(&serde_json::Value::Bool(true)))
491                        .map(|(k, _)| k.as_str())
492                        .collect()
493                })
494                .unwrap_or_default();
495            let mut suggested = HashSet::new();
496            for (key, child) in map {
497                let child_path = path.key(key);
498                match properties.and_then(|p| p.get(key)) {
499                    Some(sub) => {
500                        if sub.get("deprecated") == Some(&serde_json::Value::Bool(true)) {
501                            let note = sub.get("description").and_then(serde_json::Value::as_str).unwrap_or("");
502                            let replacement = backticked(note).map(str::to_owned);
503                            out.push(
504                                Diagnostic::warning("deprecated", child_path.clone(), format!("`{key}` is deprecated"))
505                                    .at_key()
506                                    .with_suggestion(replacement),
507                            );
508                        }
509                        walk_schema(sub, child, &child_path, scope, out);
510                    }
511                    None => match extra {
512                        Some(sub) => walk_schema(sub, child, &child_path, scope, out),
513                        None if closed => {
514                            let suggestion = suggest(key, known.iter().copied());
515                            if let Some(s) = &suggestion {
516                                suggested.insert(s.clone());
517                            }
518                            let message = format!("unknown field `{key}` {}", scope.describe(path));
519                            let mut d = Diagnostic::error("unknown-field", child_path, message)
520                                .at_key()
521                                .with_suggestion(suggestion);
522                            if d.suggestion.is_none() && !known.is_empty() {
523                                d = d.with_help(format!("expected one of: {}", known.join(", ")));
524                            }
525                            out.push(d);
526                        }
527                        None => {}
528                    },
529                }
530            }
531            for required in schema.get("required").and_then(serde_json::Value::as_array).into_iter().flatten() {
532                let Some(required) = required.as_str() else { continue };
533                if !map.contains_key(required) && !suggested.contains(required) {
534                    out.push(Diagnostic::error(
535                        "missing-field",
536                        path.clone(),
537                        format!("missing required field `{required}` {}", scope.describe(path)),
538                    ));
539                }
540            }
541        }
542        serde_json::Value::Array(items) => {
543            if let Some(sub) = schema.get("items").filter(|s| s.is_object()) {
544                for (ix, item) in items.iter().enumerate() {
545                    walk_schema(sub, item, &path.index(ix), scope, out);
546                }
547            }
548        }
549        _ => {}
550    }
551}
552
553/// Where a config finding is, for messages.
554struct Scope<'a> {
555    kind: &'a str,
556    /// Path length of the node config root.
557    depth: usize,
558}
559
560impl Scope<'_> {
561    fn describe(&self, path: &DocPath) -> String {
562        let inner = path.segments().get(self.depth..).unwrap_or_default();
563        if inner.is_empty() {
564            return format!("for node type `{}`", self.kind);
565        }
566        format!("in `{}` of a `{}` node", join_segments(&DocPath::root(), inner), self.kind)
567    }
568}
569
570fn check_parents(
571    nodes: &[NodeDoc],
572    index: &HashMap<&str, usize>,
573    built: &[Option<Arc<dyn Node>>],
574    paths: &Paths,
575    out: &mut Vec<Diagnostic>,
576) {
577    let containers: Vec<&str> = nodes
578        .iter()
579        .zip(built)
580        .filter(|(_, n)| n.as_ref().is_some_and(|n| n.role() == NodeRole::Container))
581        .map(|(d, _)| d.id.as_str())
582        .collect();
583    for (ix, doc) in nodes.iter().enumerate() {
584        let Some(parent) = &doc.parent else { continue };
585        let path = paths.node(ix).key("parent");
586        match index.get(parent.as_str()) {
587            None => out.push(
588                Diagnostic::error(
589                    "unknown-node",
590                    path,
591                    format!("parent `{parent}` of node `{}` is not a node id", doc.id),
592                )
593                .with_node(&doc.id)
594                .with_suggestion(suggest(parent, containers.iter().copied())),
595            ),
596            Some(&p) => {
597                let role = built.get(p).and_then(|n| n.as_ref()).map(|n| n.role());
598                if role.is_some_and(|r| r != NodeRole::Container) {
599                    out.push(
600                        Diagnostic::error(
601                            "invalid-parent",
602                            path,
603                            format!("parent `{parent}` of node `{}` is not a container (iteration or loop)", doc.id),
604                        )
605                        .with_node(&doc.id),
606                    );
607                }
608            }
609        }
610    }
611}
612
613fn check_edges(
614    workflow: &crate::Workflow,
615    index: &HashMap<&str, usize>,
616    ids: &[&str],
617    built: &[Option<Arc<dyn Node>>],
618    paths: &Paths,
619    registry: &Registry,
620    out: &mut Vec<Diagnostic>,
621) {
622    let nodes = &workflow.graph.nodes;
623    let mut edge_ids = HashSet::new();
624    for (k, edge) in workflow.graph.edges.iter().enumerate() {
625        let path = paths.edge(k);
626        if let Some(id) = &edge.id
627            && !edge_ids.insert(id.as_str())
628        {
629            out.push(Diagnostic::error("duplicate-edge", path.key("id"), format!("duplicate edge id `{id}`")));
630        }
631        let mut lookup = |end: &str, id: &str| match index.get(id) {
632            Some(&ix) => Some(ix),
633            None => {
634                out.push(
635                    Diagnostic::error("unknown-node", path.key(end), format!("edge {end} `{id}` is not a node id"))
636                        .with_suggestion(suggest(id, ids.iter().copied())),
637                );
638                None
639            }
640        };
641        let (Some(source), Some(target)) = (lookup("source", &edge.source), lookup("target", &edge.target)) else {
642            continue;
643        };
644        let (Some(source_doc), Some(target_doc)) = (nodes.get(source), nodes.get(target)) else { continue };
645        if source_doc.parent != target_doc.parent {
646            let scope = |p: &Option<String>| p.as_deref().map_or("the root graph".to_owned(), |p| format!("`{p}`"));
647            out.push(Diagnostic::error(
648                "cross-scope-edge",
649                path.clone(),
650                format!(
651                    "edge `{}` -> `{}` crosses scopes: `{}` is in {} but `{}` is in {}",
652                    edge.source,
653                    edge.target,
654                    edge.source,
655                    scope(&source_doc.parent),
656                    edge.target,
657                    scope(&target_doc.parent)
658                ),
659            ));
660        }
661        let Some(node) = built.get(source).and_then(|n| n.as_ref()) else { continue };
662        let Some(allowed) = allowed_handles(node.as_ref(), registry.descriptor_ref(&source_doc.kind)) else {
663            continue;
664        };
665        let handle = edge.handle.as_deref().filter(|h| !h.is_empty()).unwrap_or(SOURCE_HANDLE);
666        if let Some(message) = dead_fail_branch(source_doc, handle) {
667            out.push(Diagnostic::warning("dead-edge", path.key("handle"), message).with_node(&source_doc.id));
668        }
669        if !allowed.iter().any(|h| h == handle) {
670            let at = if edge.handle.is_some() { path.key("handle") } else { path.clone() };
671            out.push(
672                Diagnostic::error("unknown-handle", at, handle_message(source_doc, handle, &allowed))
673                    .with_node(&source_doc.id)
674                    .with_suggestion(suggest(handle, allowed.iter().map(String::as_str))),
675            );
676        }
677    }
678}
679
680pub(crate) fn handle_message(source: &NodeDoc, handle: &str, allowed: &[String]) -> String {
681    format!(
682        "node `{}` ({}) has no handle `{handle}`; its handles are: {}",
683        source.id,
684        source.kind,
685        allowed.iter().map(|h| format!("`{h}`")).collect::<Vec<_>>().join(", ")
686    )
687}
688
689/// The handles a node can select, or `None` when they cannot be known statically.
690pub(crate) fn allowed_handles(node: &dyn Node, descriptor: Option<&NodeDescriptor>) -> Option<Vec<String>> {
691    let mut handles = match node.branch_handles() {
692        Some(handles) => handles,
693        None => match descriptor.map(|d| &d.handles) {
694            Some(Handles::Fixed { handles }) => handles.clone(),
695            Some(Handles::Dynamic { .. }) => return None,
696            _ if node.role() == NodeRole::Branch => return None,
697            _ => vec![SOURCE_HANDLE.to_owned()],
698        },
699    };
700    // Always allowed: without `on_error: {strategy: fail-branch}` such an edge is
701    // never taken, which is reported as a warning (see `dead_fail_branch`).
702    handles.push(FAIL_BRANCH.to_owned());
703    Some(handles)
704}
705
706/// Warning text for a `fail-branch` edge whose source does not use that strategy.
707pub(crate) fn dead_fail_branch(source: &NodeDoc, handle: &str) -> Option<String> {
708    (handle == FAIL_BRANCH && source.policy.on_error != ErrorStrategy::FailBranch).then(|| {
709        format!(
710            "edge from `{}` uses handle `fail-branch`, but the node does not set \
711             `on_error: {{strategy: fail-branch}}`; the edge is never taken",
712            source.id
713        )
714    })
715}
716
717fn check_references(
718    nodes: &[NodeDoc],
719    index: &HashMap<&str, usize>,
720    ids: &[&str],
721    built: &[Option<Arc<dyn Node>>],
722    paths: &Paths,
723    out: &mut Vec<Diagnostic>,
724) {
725    let mut candidates: Vec<&str> = ids.to_vec();
726    candidates.extend_from_slice(crate::graph::RESERVED_NAMESPACES);
727    for (ix, (doc, node)) in nodes.iter().zip(built).enumerate() {
728        let Some(node) = node else { continue };
729        let mut seen = HashSet::new();
730        for selector in node.inputs() {
731            let namespace = selector.namespace();
732            if crate::graph::RESERVED_NAMESPACES.contains(&namespace) || index.contains_key(namespace) {
733                continue;
734            }
735            if !seen.insert(selector.to_string()) {
736                continue;
737            }
738            let path = locate_reference(&doc.config, namespace)
739                .map(|rel| join_segments(&paths.node(ix), &rel))
740                .unwrap_or_else(|| paths.node(ix));
741            out.push(
742                Diagnostic::error(
743                    "unknown-reference",
744                    path,
745                    format!("node `{}` references `{selector}`, but there is no node `{namespace}`", doc.id),
746                )
747                .with_node(&doc.id)
748                .with_suggestion(suggest(namespace, candidates.iter().copied()))
749                .with_help("selectors start with a node id or `sys`, `env`, `conversation`"),
750            );
751        }
752    }
753}
754
755fn join_segments(base: &DocPath, rel: &[PathSegment]) -> DocPath {
756    rel.iter().fold(base.clone(), |path, segment| match segment {
757        PathSegment::Key(k) => path.key(k),
758        PathSegment::Index(i) => path.index(*i),
759    })
760}
761
762/// Find where in a config a selector with `namespace` appears: an array whose
763/// first item is the namespace, a dotted string `namespace.x`, or a template
764/// placeholder `{{#namespace.x#}}`.
765fn locate_reference(config: &serde_json::Map<String, serde_json::Value>, namespace: &str) -> Option<Vec<PathSegment>> {
766    fn search(value: &serde_json::Value, namespace: &str, path: &mut Vec<PathSegment>) -> bool {
767        match value {
768            serde_json::Value::String(s) => {
769                s.contains(&format!("{{{{#{namespace}.")) || s.starts_with(&format!("{namespace}."))
770            }
771            serde_json::Value::Array(items) => {
772                let is_selector = items.first().and_then(serde_json::Value::as_str) == Some(namespace)
773                    && items.iter().all(serde_json::Value::is_string)
774                    && items.len() >= 2;
775                if is_selector {
776                    // Point at the namespace part, the one that is wrong.
777                    path.push(PathSegment::Index(0));
778                    return true;
779                }
780                for (ix, item) in items.iter().enumerate() {
781                    path.push(PathSegment::Index(ix));
782                    if search(item, namespace, path) {
783                        return true;
784                    }
785                    path.pop();
786                }
787                false
788            }
789            serde_json::Value::Object(map) => {
790                for (key, item) in map {
791                    path.push(PathSegment::Key(key.clone()));
792                    if search(item, namespace, path) {
793                        return true;
794                    }
795                    path.pop();
796                }
797                false
798            }
799            _ => false,
800        }
801    }
802    let mut path = Vec::new();
803    search(&serde_json::Value::Object(config.clone()), namespace, &mut path).then_some(path)
804}
805
806#[cfg(test)]
807mod tests {
808    use super::*;
809
810    #[test]
811    fn suggestions() {
812        assert_eq!(suggest("templat", ["template", "variables"]), Some("template".into()));
813        assert_eq!(suggest("varaibles", ["template", "variables"]), Some("variables".into()));
814        assert_eq!(suggest("Template", ["template"]), Some("template".into()));
815        assert_eq!(suggest("zzz", ["template", "variables"]), None);
816        assert_eq!(suggest("a", ["b"]), Some("b".into()));
817        assert_eq!(suggest("x", ["x"]), None, "an exact match is not a suggestion");
818        assert_eq!(edit_distance("abc", "acb"), 1);
819        assert_eq!(edit_distance("", "abc"), 3);
820    }
821
822    #[test]
823    fn dotted_paths_join() {
824        let base = DocPath::root().key("graph").key("nodes").index(2);
825        assert_eq!(
826            join_dotted(&base, "variables[0].value_selector").to_string(),
827            "graph.nodes[2].variables[0].value_selector"
828        );
829        assert_eq!(join_dotted(&base, "a[1][2]").to_string(), "graph.nodes[2].a[1][2]");
830    }
831
832    #[test]
833    fn finds_references() {
834        let config = serde_json::json!({"variables": [{"variable": "x", "value_selector": ["strat", "x"]}], "t": "{{#llm.text#}}"});
835        let config = config.as_object().cloned().unwrap_or_default();
836        let path = locate_reference(&config, "strat").unwrap_or_default();
837        assert_eq!(join_segments(&DocPath::root(), &path).to_string(), "variables[0].value_selector[0]");
838        let path = locate_reference(&config, "llm").unwrap_or_default();
839        assert_eq!(join_segments(&DocPath::root(), &path).to_string(), "t");
840    }
841}