Skip to main content

knot/models/
subgraph.rs

1use serde::{Deserialize, Serialize};
2
3use crate::db::graph::MatchTier;
4
5#[cfg(test)]
6mod tests {
7    //! ยง5.6 disclosure payload tests โ€” additive `root_resolution` field.
8    use super::*;
9
10    #[test]
11    fn test_subgraph_result_serialises_root_resolution_when_present() {
12        let chosen = RootCandidateLite {
13            uuid: "u1".to_string(),
14            name: "UserService".to_string(),
15            fqn: Some("MyApp.Services.UserService".to_string()),
16            kind: Some("csharp_class".to_string()),
17            signature: None,
18            docstring: None,
19            file_path: Some("Services/UserService.cs".to_string()),
20            start_line: Some(12),
21        };
22        let result = SubgraphResult {
23            root_id: Some("u1".to_string()),
24            nodes: vec![],
25            edges: vec![],
26            truncated: false,
27            total_nodes_found: 0,
28            root_resolution: Some(RootResolution {
29                query: "UserService".to_string(),
30                tier: MatchTier::ExactName,
31                total_candidates: 2,
32                chosen: chosen.clone(),
33                candidates: vec![chosen],
34            }),
35        };
36        let json = serde_json::to_string(&result).unwrap();
37        assert!(json.contains("\"root_resolution\""), "got: {json}");
38        assert!(json.contains("\"tier\":\"exact_name\""), "got: {json}");
39        assert!(json.contains("\"total_candidates\":2"), "got: {json}");
40        assert!(json.contains("\"query\":\"UserService\""), "got: {json}");
41    }
42
43    #[test]
44    fn test_subgraph_result_omits_root_resolution_when_none() {
45        // `skip_serializing_if = "Option::is_none"` must drop the key from
46        // the JSON output.
47        let result = SubgraphResult {
48            root_id: Some("u1".to_string()),
49            nodes: vec![],
50            edges: vec![],
51            truncated: false,
52            total_nodes_found: 0,
53            root_resolution: None,
54        };
55        let json = serde_json::to_string(&result).unwrap();
56        assert!(
57            !json.contains("root_resolution"),
58            "root_resolution should be omitted when None, got: {json}"
59        );
60    }
61
62    #[test]
63    fn test_subgraph_result_deserializes_without_root_resolution() {
64        // Older payloads (no `root_resolution` key) must still deserialize.
65        let legacy_json = r#"{
66            "root_id": "u1",
67            "nodes": [],
68            "edges": [],
69            "truncated": false,
70            "total_nodes_found": 0
71        }"#;
72        let result: SubgraphResult = serde_json::from_str(legacy_json).unwrap();
73        assert!(result.root_resolution.is_none());
74        assert_eq!(result.root_id.as_deref(), Some("u1"));
75    }
76}
77
78/// Direction for subgraph traversal from the root entity.
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
80#[serde(rename_all = "snake_case")]
81pub enum SubgraphDirection {
82    /// Follow outgoing edges from the root.
83    Outgoing,
84    /// Follow incoming edges into the root.
85    Incoming,
86    /// Follow both outgoing and incoming edges.
87    #[default]
88    Both,
89}
90
91/// A node in the entity subgraph.
92#[derive(Debug, Clone, Serialize, Deserialize)]
93pub struct SubgraphNode {
94    pub uuid: String,
95    pub name: String,
96    pub kind: Option<String>,
97    pub fqn: Option<String>,
98    pub signature: Option<String>,
99    pub docstring: Option<String>,
100    pub file_path: Option<String>,
101    pub start_line: Option<i64>,
102}
103
104/// An edge connecting two nodes in the subgraph.
105#[derive(Debug, Clone, Serialize, Deserialize)]
106pub struct SubgraphEdge {
107    pub source_uuid: String,
108    pub target_uuid: String,
109    pub relationship: String,
110}
111
112/// Options for querying a subgraph.
113#[derive(Debug, Clone)]
114pub struct SubgraphQueryOptions<'a> {
115    pub entity_name: &'a str,
116    pub repo_name: &'a str,
117    pub depth: u32,
118    pub relationships: &'a [&'a str],
119    pub direction: SubgraphDirection,
120    pub max_nodes: usize,
121    pub entity_uuid: Option<&'a str>,
122    pub visible_kinds: Option<&'a [&'a str]>,
123}
124
125/// How the root was resolved when the subgraph was queried by name.
126///
127/// Additive payload โ€” `serde(default)` keeps older payloads deserializable;
128/// knot-server is not required to surface it.
129#[derive(Debug, Clone, Serialize, Deserialize)]
130pub struct RootResolution {
131    /// The original query string.
132    pub query: String,
133    /// Which tier of the resolution ladder produced the chosen root.
134    pub tier: MatchTier,
135    /// Number of candidates the winning tier yielded before ranking
136    /// (capped at `DEFAULT_MAX_TARGETS` for fairness).
137    pub total_candidates: usize,
138    /// The candidate chosen as the root.
139    pub chosen: RootCandidateLite,
140    /// All candidates the winning tier yielded, in rank order
141    /// (capped at 10 for payload size).
142    pub candidates: Vec<RootCandidateLite>,
143}
144
145/// Alias of [`crate::db::graph::RootCandidate`] โ€” a single source of truth
146/// for the root-candidate shape shared by the db projection and this wire
147/// payload. The db struct and this alias serialize identically, so the wire
148/// format is unchanged.
149pub type RootCandidateLite = crate::db::graph::RootCandidate;
150
151/// Result of a subgraph traversal query.
152#[derive(Debug, Clone, Serialize, Deserialize)]
153pub struct SubgraphResult {
154    pub root_id: Option<String>,
155    pub nodes: Vec<SubgraphNode>,
156    pub edges: Vec<SubgraphEdge>,
157    /// True when the total number of nodes found exceeds the requested limit.
158    pub truncated: bool,
159    /// Total nodes discovered during traversal (before truncation).
160    pub total_nodes_found: usize,
161    /// How the root was resolved when queried by name. `None` when the subgraph
162    /// was queried by UUID or no root was found. Additive: `serde(default)` keeps
163    /// older payloads deserializable; knot-server is not required to surface it.
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    pub root_resolution: Option<RootResolution>,
166}