Skip to main content

llm_kernel/graph/
types.rs

1//! Core types for the knowledge graph.
2
3use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5
6/// Default importance for new nodes.
7pub fn default_importance() -> f64 {
8    0.5
9}
10
11/// A node in the knowledge graph.
12///
13/// Represents a discrete piece of knowledge — a decision, concept, pattern, etc.
14/// Stored as a single row in the `nodes` SQLite table.
15///
16/// Derives `Default` so callers can future-proof field additions with struct
17/// update syntax: `GraphNode { id, node_type, ..Default::default() }`.
18#[derive(Debug, Clone, Serialize, Deserialize, Default)]
19pub struct GraphNode {
20    /// Unique node identifier (UUID).
21    pub id: String,
22    /// Node type (e.g. "decision", "concept", "pattern", "error", "session").
23    #[serde(rename = "type")]
24    pub node_type: String,
25    /// Short title summarizing the node's content.
26    pub title: String,
27    /// Full text body of the node.
28    #[serde(default)]
29    pub body: String,
30    /// Classification tags for filtering and search.
31    #[serde(default)]
32    pub tags: Vec<String>,
33    /// Projects this node belongs to.
34    #[serde(default)]
35    pub projects: Vec<String>,
36    /// Agents that contributed to or own this node.
37    #[serde(default)]
38    pub agents: Vec<String>,
39    /// ISO 8601 creation timestamp.
40    pub created: String,
41    /// ISO 8601 last-updated timestamp.
42    pub updated: String,
43    /// Importance score (0.0–1.0). Higher = more valuable for recall.
44    #[serde(default = "default_importance")]
45    pub importance: f64,
46    /// How many times this node has been retrieved via recall/search.
47    #[serde(default)]
48    pub access_count: i64,
49    /// Last time this node was accessed (ISO 8601).
50    #[serde(default)]
51    pub accessed_at: String,
52}
53
54/// A directed, weighted edge between two nodes.
55#[derive(Debug, Clone, Serialize, Deserialize, Default)]
56pub struct GraphEdge {
57    /// Unique edge identifier (UUID).
58    pub id: String,
59    /// Source node ID.
60    pub source: String,
61    /// Target node ID.
62    pub target: String,
63    /// Relationship type (e.g. "related", "solves", "derived_from").
64    pub relation: String,
65    /// Edge weight (0.0–1.0); higher values indicate stronger relationships.
66    pub weight: f64,
67    /// ISO 8601 creation timestamp.
68    pub ts: String,
69}
70
71/// Direction filter for directed edge lookups.
72///
73/// Historical edge queries were bidirectional (`source = ? OR target = ?`).
74/// `EdgeDirection` restricts a lookup to outgoing or incoming edges only —
75/// required for inherently directed graphs such as legal citation networks
76/// (`A` cites `B`) or document wikilinks/backlinks.
77///
78/// [`Both`](Self::Both) is the default and preserves the historical behavior.
79#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
80pub enum EdgeDirection {
81    /// Out-edges only: the node is the edge `source`.
82    Out,
83    /// In-edges only: the node is the edge `target`.
84    In,
85    /// Both directions (default; preserves the historical bidirectional behavior).
86    #[default]
87    Both,
88}
89
90/// Summary of a node for serialization (web viewer, API responses).
91/// Omits body and metadata fields for compact payloads.
92#[non_exhaustive]
93#[derive(Debug, Clone, Serialize, Deserialize, Default)]
94pub struct GraphNodeSummary {
95    /// Unique node identifier.
96    pub id: String,
97    /// Short title.
98    pub title: String,
99    /// Node type.
100    #[serde(rename = "type")]
101    pub node_type: String,
102    /// Classification tags.
103    #[serde(default)]
104    pub tags: Vec<String>,
105    /// Importance score (0.0–1.0).
106    #[serde(default = "default_importance")]
107    pub importance: f64,
108}
109
110/// A graph snapshot containing nodes (summaries) and edges.
111#[derive(Debug, Clone, Serialize, Deserialize, Default)]
112pub struct Graph {
113    /// All nodes in the snapshot.
114    pub nodes: Vec<GraphNodeSummary>,
115    /// All edges in the snapshot.
116    pub edges: Vec<GraphEdge>,
117}
118
119/// A node scored by relevance for recall ranking.
120#[derive(Debug, Clone)]
121pub struct ScoredNode {
122    /// The graph node.
123    pub node: GraphNode,
124    /// Composite relevance score.
125    pub score: f64,
126}
127
128/// Aggregate statistics about the knowledge graph.
129#[non_exhaustive]
130#[derive(Debug, Clone, Serialize, Deserialize, Default)]
131pub struct GraphStats {
132    /// Total number of nodes.
133    pub total_nodes: i64,
134    /// Total number of edges.
135    pub total_edges: i64,
136    /// Mean importance score across all nodes.
137    pub avg_importance: f64,
138    /// Node count broken down by node type.
139    pub by_type: HashMap<String, i64>,
140}
141
142// ── CSV helpers (tags, projects, agents stored as comma-separated strings) ──
143
144pub(crate) fn join_csv(v: &[String]) -> String {
145    v.join(",")
146}
147
148pub(crate) fn split_csv(s: &str) -> Vec<String> {
149    s.split(',')
150        .map(|x| x.trim().to_string())
151        .filter(|x| !x.is_empty())
152        .collect()
153}
154
155/// Escape SQL LIKE wildcards (`%`, `_`, `\`) in a bound value.
156///
157/// Used with `LIKE '%,' || ? ESCAPE '\' || ',%'` patterns to prevent
158/// project names or tags containing `%` or `_` from matching unintended rows.
159pub(crate) fn escape_like(value: &str) -> String {
160    let mut out = String::with_capacity(value.len());
161    for ch in value.chars() {
162        match ch {
163            '%' | '_' | '\\' => {
164                out.push('\\');
165                out.push(ch);
166            }
167            _ => out.push(ch),
168        }
169    }
170    out
171}
172
173/// Validate a UUID v4 string (strict format: `xxxxxxxx-xxxx-4xxx-[89ab]xxx-xxxxxxxxxxxx`).
174///
175/// Pure byte inspection — zero dependencies. Useful for validating node and edge IDs
176/// before writing to the graph.
177pub fn validate_uuid(id: &str) -> bool {
178    let b = id.as_bytes();
179    b.len() == 36
180        && b[8] == b'-'
181        && b[13] == b'-'
182        && b[18] == b'-'
183        && b[23] == b'-'
184        && b[14] == b'4'
185        && matches!(b[19], b'8'..=b'9' | b'a'..=b'b' | b'A'..=b'B')
186        && b.iter()
187            .enumerate()
188            .all(|(i, &c)| matches!(i, 8 | 13 | 18 | 23) || c.is_ascii_hexdigit())
189}
190
191// ── Row mapping ───────────────────────────────────────
192
193/// Standard SELECT columns for node queries.
194pub(crate) const NODE_COLUMNS: &str = "id, type, title, tags, projects, agents, created, updated, body, importance, access_count, accessed_at";
195
196/// Same columns but table-prefixed for JOIN queries.
197pub(crate) const NODE_COLUMNS_PREFIXED: &str = "id, n.type, n.title, n.tags, n.projects, n.agents, n.created, n.updated, n.body, n.importance, n.access_count, n.accessed_at";
198
199pub(crate) fn row_to_node(row: &rusqlite::Row<'_>) -> rusqlite::Result<GraphNode> {
200    let tags: String = row.get(3)?;
201    let projects: String = row.get(4)?;
202    let agents: String = row.get(5)?;
203    Ok(GraphNode {
204        id: row.get(0)?,
205        node_type: row.get(1)?,
206        title: row.get(2)?,
207        tags: split_csv(&tags),
208        projects: split_csv(&projects),
209        agents: split_csv(&agents),
210        created: row.get(6)?,
211        updated: row.get(7)?,
212        body: row.get(8)?,
213        importance: row.get(9).unwrap_or(0.5),
214        access_count: row.get::<_, i64>(10).unwrap_or(0),
215        accessed_at: row.get(11).unwrap_or_default(),
216    })
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222
223    #[test]
224    fn escape_like_escapes_percent() {
225        assert_eq!(escape_like("100%"), r"100\%");
226    }
227
228    #[test]
229    fn escape_like_escapes_underscore() {
230        assert_eq!(escape_like("a_b"), r"a\_b");
231    }
232
233    #[test]
234    fn escape_like_passthrough_normal() {
235        assert_eq!(escape_like("hello"), "hello");
236    }
237
238    #[test]
239    fn escape_like_escapes_backslash() {
240        assert_eq!(escape_like(r"\"), r"\\");
241    }
242
243    #[test]
244    fn escape_like_empty() {
245        assert_eq!(escape_like(""), "");
246    }
247
248    #[test]
249    fn validate_uuid_accepts_valid_v4() {
250        assert!(validate_uuid("550e8400-e29b-41d4-a716-446655440000"));
251        assert!(validate_uuid("00000000-0000-4000-8000-000000000000"));
252        assert!(validate_uuid("ffffffff-ffff-4fff-bfff-ffffffffffff"));
253    }
254
255    #[test]
256    fn validate_uuid_rejects_wrong_version() {
257        // version byte (position 14) is '3', not '4'
258        assert!(!validate_uuid("550e8400-e29b-31d4-a716-446655440000"));
259    }
260
261    #[test]
262    fn validate_uuid_rejects_wrong_variant() {
263        // variant byte (position 19) is 'c', not in [89abAB]
264        assert!(!validate_uuid("550e8400-e29b-41d4-c716-446655440000"));
265    }
266
267    #[test]
268    fn validate_uuid_rejects_short() {
269        assert!(!validate_uuid(""));
270        assert!(!validate_uuid("550e8400"));
271    }
272
273    #[test]
274    fn validate_uuid_rejects_missing_dashes() {
275        assert!(!validate_uuid("550e8400e29b41d4a716446655440000"));
276    }
277
278    #[test]
279    fn validate_uuid_rejects_non_hex() {
280        assert!(!validate_uuid("550g8400-e29b-41d4-a716-446655440000"));
281    }
282
283    #[test]
284    fn edge_direction_default_is_both() {
285        assert_eq!(EdgeDirection::default(), EdgeDirection::Both);
286    }
287}