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