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.
212pub fn validate_text(text: &str, registry: &Registry) -> Validation {
213    let raw = match parse_raw(text) {
214        Ok(raw) => raw,
215        Err(diagnostic) => return Validation { diagnostics: vec![*diagnostic], graph: None },
216    };
217    let mut validation = validate_value(raw, registry);
218    // Positions are only needed to report findings; a clean document skips the
219    // second, span-tracking parse.
220    if validation.diagnostics.iter().any(|d| d.span.is_none()) {
221        let map = SourceMap::from_text(text);
222        for d in &mut validation.diagnostics {
223            if d.span.is_none() {
224                d.span = map.locate(&d.path, d.at_key);
225            }
226        }
227    }
228    // Document order; findings without a position keep their relative order at the end.
229    validation.diagnostics.sort_by_key(|d| d.span.map_or((u32::MAX, u32::MAX), |s| (s.line, s.column)));
230    validation
231}
232
233/// Check and compile an already-decoded document (no source positions).
234pub fn validate_value(raw: serde_json::Value, registry: &Registry) -> Validation {
235    let decoded = crate::dsl::decode(raw);
236    let mut diagnostics = decoded.diagnostics;
237    let paths = Paths { nodes: decoded.node_paths, edges: decoded.edge_paths };
238    let built = check_graph(&decoded.workflow, &paths, registry, &mut diagnostics);
239    if diagnostics.iter().any(Diagnostic::is_error) {
240        return Validation { diagnostics, graph: None };
241    }
242    let ids: Vec<String> = decoded.workflow.graph.nodes.iter().map(|n| n.id.clone()).collect();
243    let checked: Option<Vec<Arc<dyn Node>>> = built.into_iter().collect();
244    let graph = match checked {
245        Some(nodes) => Graph::build_checked(decoded.workflow, registry, nodes),
246        None => Graph::build(decoded.workflow, registry),
247    };
248    match graph {
249        Ok(graph) => {
250            for warning in graph.warnings() {
251                let path = backticked(warning)
252                    .and_then(|id| ids.iter().position(|n| n == id))
253                    .and_then(|ix| paths.nodes.get(ix).cloned())
254                    .unwrap_or_default();
255                diagnostics.push(Diagnostic::warning("graph", path, warning.clone()));
256            }
257            Validation { diagnostics, graph: Some(graph) }
258        }
259        Err(error) => {
260            let path = backticked(&error.to_string())
261                .and_then(|id| ids.iter().position(|n| n == id))
262                .and_then(|ix| paths.nodes.get(ix).cloned())
263                .unwrap_or_else(|| DocPath::root().key("graph"));
264            diagnostics.push(Diagnostic::error("graph", path, error.to_string()));
265            Validation { diagnostics, graph: None }
266        }
267    }
268}
269
270/// The first `` `quoted` `` word of a message.
271fn backticked(message: &str) -> Option<&str> {
272    let start = message.find('`')? + 1;
273    let len = message.get(start..)?.find('`')?;
274    message.get(start..start + len)
275}
276
277/// Parse JSON (text starting with `{`) or YAML into a JSON value.
278fn parse_raw(text: &str) -> Result<serde_json::Value, Box<Diagnostic>> {
279    let syntax = |message: String, line: usize, column: usize| {
280        let mut d = Diagnostic::error("syntax", DocPath::root(), message);
281        if let (Ok(line), Ok(column)) = (u32::try_from(line), u32::try_from(column))
282            && line > 0
283        {
284            d.span = Some(SourceSpan { line, column: column.max(1), len: 1 });
285        }
286        Box::new(d)
287    };
288    if text.trim_start().starts_with('{') {
289        return serde_json::from_str(text)
290            .map_err(|e| syntax(format!("invalid JSON: {}", strip_position(&e.to_string())), e.line(), e.column()));
291    }
292    #[cfg(feature = "yaml")]
293    {
294        let options = serde_saphyr::options! { strict_booleans: true };
295        serde_saphyr::from_str_with_options(text, options).map_err(|e| {
296            let (line, column) = e
297                .location()
298                .map(|l| (usize::try_from(l.line()).unwrap_or(0), usize::try_from(l.column()).unwrap_or(0)))
299                .unwrap_or((0, 0));
300            let message = e.to_string();
301            let first = message.lines().next().unwrap_or("invalid YAML").trim().to_owned();
302            syntax(format!("invalid YAML: {}", strip_position(&first)), line, column)
303        })
304    }
305    #[cfg(not(feature = "yaml"))]
306    {
307        serde_json::from_str(text).map_err(|e| {
308            syntax(
309                format!("invalid JSON (YAML support is not compiled in): {}", strip_position(&e.to_string())),
310                e.line(),
311                e.column(),
312            )
313        })
314    }
315}
316
317/// Drop a trailing " at line X column Y" that the position already carries.
318fn strip_position(message: &str) -> String {
319    match message.rfind(" at line ") {
320        Some(ix) => message.get(..ix).unwrap_or(message).to_owned(),
321        None => message.to_owned(),
322    }
323}
324
325struct Paths {
326    nodes: Vec<DocPath>,
327    edges: Vec<DocPath>,
328}
329
330impl Paths {
331    fn node(&self, ix: usize) -> DocPath {
332        self.nodes.get(ix).cloned().unwrap_or_default()
333    }
334    fn edge(&self, ix: usize) -> DocPath {
335        self.edges.get(ix).cloned().unwrap_or_default()
336    }
337}
338
339/// Graph-level checks over every decoded node and edge.
340/// Check the whole document, collecting every finding in `out`. Returns the node
341/// built for each document node (`None` where it could not be built), so a clean
342/// document can be compiled without building its nodes again.
343fn check_graph(
344    workflow: &crate::Workflow,
345    paths: &Paths,
346    registry: &Registry,
347    out: &mut Vec<Diagnostic>,
348) -> Vec<Option<Arc<dyn Node>>> {
349    let nodes = &workflow.graph.nodes;
350    let ids: Vec<&str> = nodes.iter().map(|n| n.id.as_str()).collect();
351    let mut index: HashMap<&str, usize> = HashMap::with_capacity(nodes.len());
352    for (ix, node) in nodes.iter().enumerate() {
353        let path = paths.node(ix).key("id");
354        if let Err(GraphError::InvalidNodeId { reason, .. }) = crate::graph::validate_node_id(&node.id) {
355            out.push(
356                Diagnostic::error("invalid-node-id", path.clone(), format!("node id `{}` {reason}", node.id))
357                    .with_node(&node.id),
358            );
359        }
360        if let Some(first) = index.insert(&node.id, ix) {
361            index.insert(&node.id, first);
362            out.push(
363                Diagnostic::error("duplicate-node", path, format!("duplicate node id `{}`", node.id))
364                    .with_node(&node.id)
365                    .with_help(format!("first defined at {}", paths.node(first))),
366            );
367        }
368    }
369
370    let mut built: Vec<Option<Arc<dyn Node>>> = Vec::with_capacity(nodes.len());
371    for (ix, doc) in nodes.iter().enumerate() {
372        built.push(check_node(doc, &paths.node(ix), registry, out));
373    }
374
375    check_parents(nodes, &index, &built, paths, out);
376    check_edges(workflow, &index, &ids, &built, paths, registry, out);
377    check_references(nodes, &index, &ids, &built, paths, out);
378    built
379}
380
381/// Type, fields and configuration of one node. Returns the built node.
382fn check_node(doc: &NodeDoc, path: &DocPath, registry: &Registry, out: &mut Vec<Diagnostic>) -> Option<Arc<dyn Node>> {
383    if !registry.contains(&doc.kind) {
384        let mut kinds: Vec<&str> = registry.kinds().collect();
385        kinds.sort_unstable();
386        out.push(
387            Diagnostic::error("unknown-node-type", path.key("type"), format!("unknown node type `{}`", doc.kind))
388                .with_node(&doc.id)
389                .with_suggestion(suggest(&doc.kind, kinds))
390                .with_help("node types come from built-in features and plugins"),
391        );
392        return None;
393    }
394    if doc.strict
395        && let Some(descriptor) = registry.descriptor_ref(&doc.kind)
396    {
397        out.extend(config_diagnostics(doc, descriptor, path));
398    }
399    match registry.build(doc) {
400        Ok(node) => Some(node),
401        Err(error) => {
402            out.push(config_error(&error, path));
403            None
404        }
405    }
406}
407
408fn config_error(error: &ConfigError, base: &DocPath) -> Diagnostic {
409    let path = error.field.as_deref().map(|field| join_dotted(base, field)).unwrap_or_else(|| base.clone());
410    Diagnostic::error(
411        "invalid-config",
412        path,
413        format!("invalid `{}` node `{}`: {}", error.kind, error.node_id, error.message),
414    )
415    .with_node(&error.node_id)
416}
417
418/// `base` extended by a serde-style path such as `variables[0].value_selector`.
419fn join_dotted(base: &DocPath, field: &str) -> DocPath {
420    let mut path = base.clone();
421    for part in field.split('.') {
422        let (key, indices) = match part.find('[') {
423            Some(ix) => (part.get(..ix).unwrap_or(part), part.get(ix..).unwrap_or("")),
424            None => (part, ""),
425        };
426        if !key.is_empty() && key != "?" {
427            path = path.key(key);
428        }
429        for index in indices.split(['[', ']']).filter(|s| !s.is_empty()) {
430            if let Ok(ix) = index.parse() {
431                path = path.index(ix);
432            }
433        }
434    }
435    path
436}
437
438/// Unknown, missing and deprecated config fields of a strict node, judged by its catalog schema.
439pub(crate) fn config_diagnostics(doc: &NodeDoc, descriptor: &NodeDescriptor, base: &DocPath) -> Vec<Diagnostic> {
440    let mut issues = Vec::new();
441    let config = serde_json::Value::Object(doc.config.clone());
442    let scope = Scope { kind: &doc.kind, depth: base.segments().len() };
443    walk_schema(&descriptor.config_schema, &config, base, &scope, &mut issues);
444    for issue in &mut issues {
445        issue.node = Some(doc.id.clone());
446    }
447    issues
448}
449
450/// Report unknown keys (closed object schemas only), missing required keys and
451/// deprecated keys. Composition keywords (`oneOf`, `anyOf`, ...) are not followed.
452fn walk_schema(
453    schema: &serde_json::Value,
454    value: &serde_json::Value,
455    path: &DocPath,
456    scope: &Scope<'_>,
457    out: &mut Vec<Diagnostic>,
458) {
459    let Some(schema) = schema.as_object() else { return };
460    match value {
461        serde_json::Value::Object(map) => {
462            let properties = schema.get("properties").and_then(serde_json::Value::as_object);
463            let closed = schema.get("additionalProperties") == Some(&serde_json::Value::Bool(false))
464                && !schema.contains_key("patternProperties");
465            let extra = schema.get("additionalProperties").filter(|s| s.is_object());
466            let known: Vec<&str> = properties
467                .map(|p| {
468                    p.iter()
469                        .filter(|(_, s)| s.get("deprecated") != Some(&serde_json::Value::Bool(true)))
470                        .map(|(k, _)| k.as_str())
471                        .collect()
472                })
473                .unwrap_or_default();
474            let mut suggested = HashSet::new();
475            for (key, child) in map {
476                let child_path = path.key(key);
477                match properties.and_then(|p| p.get(key)) {
478                    Some(sub) => {
479                        if sub.get("deprecated") == Some(&serde_json::Value::Bool(true)) {
480                            let note = sub.get("description").and_then(serde_json::Value::as_str).unwrap_or("");
481                            let replacement = backticked(note).map(str::to_owned);
482                            out.push(
483                                Diagnostic::warning("deprecated", child_path.clone(), format!("`{key}` is deprecated"))
484                                    .at_key()
485                                    .with_suggestion(replacement),
486                            );
487                        }
488                        walk_schema(sub, child, &child_path, scope, out);
489                    }
490                    None => match extra {
491                        Some(sub) => walk_schema(sub, child, &child_path, scope, out),
492                        None if closed => {
493                            let suggestion = suggest(key, known.iter().copied());
494                            if let Some(s) = &suggestion {
495                                suggested.insert(s.clone());
496                            }
497                            let message = format!("unknown field `{key}` {}", scope.describe(path));
498                            let mut d = Diagnostic::error("unknown-field", child_path, message)
499                                .at_key()
500                                .with_suggestion(suggestion);
501                            if d.suggestion.is_none() && !known.is_empty() {
502                                d = d.with_help(format!("expected one of: {}", known.join(", ")));
503                            }
504                            out.push(d);
505                        }
506                        None => {}
507                    },
508                }
509            }
510            for required in schema.get("required").and_then(serde_json::Value::as_array).into_iter().flatten() {
511                let Some(required) = required.as_str() else { continue };
512                if !map.contains_key(required) && !suggested.contains(required) {
513                    out.push(Diagnostic::error(
514                        "missing-field",
515                        path.clone(),
516                        format!("missing required field `{required}` {}", scope.describe(path)),
517                    ));
518                }
519            }
520        }
521        serde_json::Value::Array(items) => {
522            if let Some(sub) = schema.get("items").filter(|s| s.is_object()) {
523                for (ix, item) in items.iter().enumerate() {
524                    walk_schema(sub, item, &path.index(ix), scope, out);
525                }
526            }
527        }
528        _ => {}
529    }
530}
531
532/// Where a config finding is, for messages.
533struct Scope<'a> {
534    kind: &'a str,
535    /// Path length of the node config root.
536    depth: usize,
537}
538
539impl Scope<'_> {
540    fn describe(&self, path: &DocPath) -> String {
541        let inner = path.segments().get(self.depth..).unwrap_or_default();
542        if inner.is_empty() {
543            return format!("for node type `{}`", self.kind);
544        }
545        format!("in `{}` of a `{}` node", join_segments(&DocPath::root(), inner), self.kind)
546    }
547}
548
549fn check_parents(
550    nodes: &[NodeDoc],
551    index: &HashMap<&str, usize>,
552    built: &[Option<Arc<dyn Node>>],
553    paths: &Paths,
554    out: &mut Vec<Diagnostic>,
555) {
556    let containers: Vec<&str> = nodes
557        .iter()
558        .zip(built)
559        .filter(|(_, n)| n.as_ref().is_some_and(|n| n.role() == NodeRole::Container))
560        .map(|(d, _)| d.id.as_str())
561        .collect();
562    for (ix, doc) in nodes.iter().enumerate() {
563        let Some(parent) = &doc.parent else { continue };
564        let path = paths.node(ix).key("parent");
565        match index.get(parent.as_str()) {
566            None => out.push(
567                Diagnostic::error(
568                    "unknown-node",
569                    path,
570                    format!("parent `{parent}` of node `{}` is not a node id", doc.id),
571                )
572                .with_node(&doc.id)
573                .with_suggestion(suggest(parent, containers.iter().copied())),
574            ),
575            Some(&p) => {
576                let role = built.get(p).and_then(|n| n.as_ref()).map(|n| n.role());
577                if role.is_some_and(|r| r != NodeRole::Container) {
578                    out.push(
579                        Diagnostic::error(
580                            "invalid-parent",
581                            path,
582                            format!("parent `{parent}` of node `{}` is not a container (iteration or loop)", doc.id),
583                        )
584                        .with_node(&doc.id),
585                    );
586                }
587            }
588        }
589    }
590}
591
592fn check_edges(
593    workflow: &crate::Workflow,
594    index: &HashMap<&str, usize>,
595    ids: &[&str],
596    built: &[Option<Arc<dyn Node>>],
597    paths: &Paths,
598    registry: &Registry,
599    out: &mut Vec<Diagnostic>,
600) {
601    let nodes = &workflow.graph.nodes;
602    let mut edge_ids = HashSet::new();
603    for (k, edge) in workflow.graph.edges.iter().enumerate() {
604        let path = paths.edge(k);
605        if let Some(id) = &edge.id
606            && !edge_ids.insert(id.as_str())
607        {
608            out.push(Diagnostic::error("duplicate-edge", path.key("id"), format!("duplicate edge id `{id}`")));
609        }
610        let mut lookup = |end: &str, id: &str| match index.get(id) {
611            Some(&ix) => Some(ix),
612            None => {
613                out.push(
614                    Diagnostic::error("unknown-node", path.key(end), format!("edge {end} `{id}` is not a node id"))
615                        .with_suggestion(suggest(id, ids.iter().copied())),
616                );
617                None
618            }
619        };
620        let (Some(source), Some(target)) = (lookup("source", &edge.source), lookup("target", &edge.target)) else {
621            continue;
622        };
623        let (Some(source_doc), Some(target_doc)) = (nodes.get(source), nodes.get(target)) else { continue };
624        if source_doc.parent != target_doc.parent {
625            let scope = |p: &Option<String>| p.as_deref().map_or("the root graph".to_owned(), |p| format!("`{p}`"));
626            out.push(Diagnostic::error(
627                "cross-scope-edge",
628                path.clone(),
629                format!(
630                    "edge `{}` -> `{}` crosses scopes: `{}` is in {} but `{}` is in {}",
631                    edge.source,
632                    edge.target,
633                    edge.source,
634                    scope(&source_doc.parent),
635                    edge.target,
636                    scope(&target_doc.parent)
637                ),
638            ));
639        }
640        let Some(node) = built.get(source).and_then(|n| n.as_ref()) else { continue };
641        let Some(allowed) = allowed_handles(node.as_ref(), registry.descriptor_ref(&source_doc.kind)) else {
642            continue;
643        };
644        let handle = edge.handle.as_deref().filter(|h| !h.is_empty()).unwrap_or(SOURCE_HANDLE);
645        if let Some(message) = dead_fail_branch(source_doc, handle) {
646            out.push(Diagnostic::warning("dead-edge", path.key("handle"), message).with_node(&source_doc.id));
647        }
648        if !allowed.iter().any(|h| h == handle) {
649            let at = if edge.handle.is_some() { path.key("handle") } else { path.clone() };
650            out.push(
651                Diagnostic::error("unknown-handle", at, handle_message(source_doc, handle, &allowed))
652                    .with_node(&source_doc.id)
653                    .with_suggestion(suggest(handle, allowed.iter().map(String::as_str))),
654            );
655        }
656    }
657}
658
659pub(crate) fn handle_message(source: &NodeDoc, handle: &str, allowed: &[String]) -> String {
660    format!(
661        "node `{}` ({}) has no handle `{handle}`; its handles are: {}",
662        source.id,
663        source.kind,
664        allowed.iter().map(|h| format!("`{h}`")).collect::<Vec<_>>().join(", ")
665    )
666}
667
668/// The handles a node can select, or `None` when they cannot be known statically.
669pub(crate) fn allowed_handles(node: &dyn Node, descriptor: Option<&NodeDescriptor>) -> Option<Vec<String>> {
670    let mut handles = match node.branch_handles() {
671        Some(handles) => handles,
672        None => match descriptor.map(|d| &d.handles) {
673            Some(Handles::Fixed { handles }) => handles.clone(),
674            Some(Handles::Dynamic { .. }) => return None,
675            _ if node.role() == NodeRole::Branch => return None,
676            _ => vec![SOURCE_HANDLE.to_owned()],
677        },
678    };
679    // Always allowed: without `on_error: {strategy: fail-branch}` such an edge is
680    // never taken, which is reported as a warning (see `dead_fail_branch`).
681    handles.push(FAIL_BRANCH.to_owned());
682    Some(handles)
683}
684
685/// Warning text for a `fail-branch` edge whose source does not use that strategy.
686pub(crate) fn dead_fail_branch(source: &NodeDoc, handle: &str) -> Option<String> {
687    (handle == FAIL_BRANCH && source.policy.on_error != ErrorStrategy::FailBranch).then(|| {
688        format!(
689            "edge from `{}` uses handle `fail-branch`, but the node does not set \
690             `on_error: {{strategy: fail-branch}}`; the edge is never taken",
691            source.id
692        )
693    })
694}
695
696fn check_references(
697    nodes: &[NodeDoc],
698    index: &HashMap<&str, usize>,
699    ids: &[&str],
700    built: &[Option<Arc<dyn Node>>],
701    paths: &Paths,
702    out: &mut Vec<Diagnostic>,
703) {
704    let mut candidates: Vec<&str> = ids.to_vec();
705    candidates.extend_from_slice(crate::graph::RESERVED_NAMESPACES);
706    for (ix, (doc, node)) in nodes.iter().zip(built).enumerate() {
707        let Some(node) = node else { continue };
708        let mut seen = HashSet::new();
709        for selector in node.inputs() {
710            let namespace = selector.namespace();
711            if crate::graph::RESERVED_NAMESPACES.contains(&namespace) || index.contains_key(namespace) {
712                continue;
713            }
714            if !seen.insert(selector.to_string()) {
715                continue;
716            }
717            let path = locate_reference(&doc.config, namespace)
718                .map(|rel| join_segments(&paths.node(ix), &rel))
719                .unwrap_or_else(|| paths.node(ix));
720            out.push(
721                Diagnostic::error(
722                    "unknown-reference",
723                    path,
724                    format!("node `{}` references `{selector}`, but there is no node `{namespace}`", doc.id),
725                )
726                .with_node(&doc.id)
727                .with_suggestion(suggest(namespace, candidates.iter().copied()))
728                .with_help("selectors start with a node id or `sys`, `env`, `conversation`"),
729            );
730        }
731    }
732}
733
734fn join_segments(base: &DocPath, rel: &[PathSegment]) -> DocPath {
735    rel.iter().fold(base.clone(), |path, segment| match segment {
736        PathSegment::Key(k) => path.key(k),
737        PathSegment::Index(i) => path.index(*i),
738    })
739}
740
741/// Find where in a config a selector with `namespace` appears: an array whose
742/// first item is the namespace, a dotted string `namespace.x`, or a template
743/// placeholder `{{#namespace.x#}}`.
744fn locate_reference(config: &serde_json::Map<String, serde_json::Value>, namespace: &str) -> Option<Vec<PathSegment>> {
745    fn search(value: &serde_json::Value, namespace: &str, path: &mut Vec<PathSegment>) -> bool {
746        match value {
747            serde_json::Value::String(s) => {
748                s.contains(&format!("{{{{#{namespace}.")) || s.starts_with(&format!("{namespace}."))
749            }
750            serde_json::Value::Array(items) => {
751                let is_selector = items.first().and_then(serde_json::Value::as_str) == Some(namespace)
752                    && items.iter().all(serde_json::Value::is_string)
753                    && items.len() >= 2;
754                if is_selector {
755                    // Point at the namespace part, the one that is wrong.
756                    path.push(PathSegment::Index(0));
757                    return true;
758                }
759                for (ix, item) in items.iter().enumerate() {
760                    path.push(PathSegment::Index(ix));
761                    if search(item, namespace, path) {
762                        return true;
763                    }
764                    path.pop();
765                }
766                false
767            }
768            serde_json::Value::Object(map) => {
769                for (key, item) in map {
770                    path.push(PathSegment::Key(key.clone()));
771                    if search(item, namespace, path) {
772                        return true;
773                    }
774                    path.pop();
775                }
776                false
777            }
778            _ => false,
779        }
780    }
781    let mut path = Vec::new();
782    search(&serde_json::Value::Object(config.clone()), namespace, &mut path).then_some(path)
783}
784
785#[cfg(test)]
786mod tests {
787    use super::*;
788
789    #[test]
790    fn suggestions() {
791        assert_eq!(suggest("templat", ["template", "variables"]), Some("template".into()));
792        assert_eq!(suggest("varaibles", ["template", "variables"]), Some("variables".into()));
793        assert_eq!(suggest("Template", ["template"]), Some("template".into()));
794        assert_eq!(suggest("zzz", ["template", "variables"]), None);
795        assert_eq!(suggest("a", ["b"]), Some("b".into()));
796        assert_eq!(suggest("x", ["x"]), None, "an exact match is not a suggestion");
797        assert_eq!(edit_distance("abc", "acb"), 1);
798        assert_eq!(edit_distance("", "abc"), 3);
799    }
800
801    #[test]
802    fn dotted_paths_join() {
803        let base = DocPath::root().key("graph").key("nodes").index(2);
804        assert_eq!(
805            join_dotted(&base, "variables[0].value_selector").to_string(),
806            "graph.nodes[2].variables[0].value_selector"
807        );
808        assert_eq!(join_dotted(&base, "a[1][2]").to_string(), "graph.nodes[2].a[1][2]");
809    }
810
811    #[test]
812    fn finds_references() {
813        let config = serde_json::json!({"variables": [{"variable": "x", "value_selector": ["strat", "x"]}], "t": "{{#llm.text#}}"});
814        let config = config.as_object().cloned().unwrap_or_default();
815        let path = locate_reference(&config, "strat").unwrap_or_default();
816        assert_eq!(join_segments(&DocPath::root(), &path).to_string(), "variables[0].value_selector[0]");
817        let path = locate_reference(&config, "llm").unwrap_or_default();
818        assert_eq!(join_segments(&DocPath::root(), &path).to_string(), "t");
819    }
820}