niwa-core 0.1.0

Core library for NIWA Expertise Graph management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! Graph operations for managing Expertise relations

use crate::{Error, Result};
use serde::{Deserialize, Serialize};
use sqlx::SqlitePool;
use std::collections::{HashMap, HashSet};
use std::str::FromStr;
use tracing::debug;

/// Relation type between expertises
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RelationType {
    /// One expertise uses another
    Uses,
    /// One expertise extends another
    Extends,
    /// Two expertises conflict
    Conflicts,
    /// One expertise requires another
    Requires,
}

impl FromStr for RelationType {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        match s.to_lowercase().as_str() {
            "uses" => Ok(RelationType::Uses),
            "extends" => Ok(RelationType::Extends),
            "conflicts" => Ok(RelationType::Conflicts),
            "requires" => Ok(RelationType::Requires),
            _ => Err(Error::InvalidRelationType(s.to_string())),
        }
    }
}

impl RelationType {
    /// Convert to string representation
    pub fn as_str(&self) -> &'static str {
        match self {
            RelationType::Uses => "uses",
            RelationType::Extends => "extends",
            RelationType::Conflicts => "conflicts",
            RelationType::Requires => "requires",
        }
    }

    /// Get all relation types
    pub fn all() -> &'static [RelationType] {
        &[
            RelationType::Uses,
            RelationType::Extends,
            RelationType::Conflicts,
            RelationType::Requires,
        ]
    }
}

impl std::fmt::Display for RelationType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// A relation between two expertises
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Relation {
    pub from_id: String,
    pub to_id: String,
    pub relation_type: RelationType,
    pub metadata: Option<String>,
    pub created_at: i64,
}

/// Graph operations for managing relations
#[derive(Clone)]
pub struct GraphOperations {
    pool: SqlitePool,
}

impl GraphOperations {
    /// Create a new GraphOperations instance
    pub(crate) fn new(pool: SqlitePool) -> Self {
        Self { pool }
    }

    /// Create a relation between two expertises
    ///
    /// # Arguments
    ///
    /// * `from_id` - Source expertise ID
    /// * `to_id` - Target expertise ID
    /// * `relation_type` - Type of relation
    /// * `metadata` - Optional JSON metadata
    ///
    /// # Example
    ///
    /// ```no_run
    /// use niwa_core::{Database, RelationType};
    ///
    /// #[tokio::main]
    /// async fn main() -> anyhow::Result<()> {
    ///     let db = Database::open_default().await?;
    ///
    ///     db.graph().create_relation(
    ///         "rust-expert",
    ///         "error-handling",
    ///         RelationType::Uses,
    ///         None
    ///     ).await?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn create_relation(
        &self,
        from_id: &str,
        to_id: &str,
        relation_type: RelationType,
        metadata: Option<String>,
    ) -> Result<()> {
        debug!(
            "Creating relation: {} -[{}]-> {}",
            from_id, relation_type, to_id
        );

        // Check for circular dependency
        if self.would_create_cycle(from_id, to_id).await? {
            return Err(Error::CircularDependency {
                from: from_id.to_string(),
                to: to_id.to_string(),
            });
        }

        let created_at = chrono::Utc::now().timestamp();

        sqlx::query(
            r#"
            INSERT OR REPLACE INTO relations (from_id, to_id, relation_type, metadata, created_at)
            VALUES (?, ?, ?, ?, ?)
            "#,
        )
        .bind(from_id)
        .bind(to_id)
        .bind(relation_type.as_str())
        .bind(&metadata)
        .bind(created_at)
        .execute(&self.pool)
        .await?;

        debug!("Created relation successfully");
        Ok(())
    }

    /// Delete a relation
    pub async fn delete_relation(
        &self,
        from_id: &str,
        to_id: &str,
        relation_type: RelationType,
    ) -> Result<()> {
        debug!(
            "Deleting relation: {} -[{}]-> {}",
            from_id, relation_type, to_id
        );

        sqlx::query(
            r#"
            DELETE FROM relations
            WHERE from_id = ? AND to_id = ? AND relation_type = ?
            "#,
        )
        .bind(from_id)
        .bind(to_id)
        .bind(relation_type.as_str())
        .execute(&self.pool)
        .await?;

        Ok(())
    }

    /// Get outgoing relations from an expertise
    pub async fn get_outgoing(&self, from_id: &str) -> Result<Vec<Relation>> {
        debug!("Getting outgoing relations for: {}", from_id);

        let rows: Vec<(String, String, String, Option<String>, i64)> = sqlx::query_as(
            r#"
            SELECT from_id, to_id, relation_type, metadata, created_at
            FROM relations
            WHERE from_id = ?
            ORDER BY created_at DESC
            "#,
        )
        .bind(from_id)
        .fetch_all(&self.pool)
        .await?;

        let mut relations = Vec::with_capacity(rows.len());
        for (from_id, to_id, relation_type, metadata, created_at) in rows {
            relations.push(Relation {
                from_id,
                to_id,
                relation_type: RelationType::from_str(&relation_type)?,
                metadata,
                created_at,
            });
        }

        Ok(relations)
    }

    /// Get incoming relations to an expertise
    pub async fn get_incoming(&self, to_id: &str) -> Result<Vec<Relation>> {
        debug!("Getting incoming relations for: {}", to_id);

        let rows: Vec<(String, String, String, Option<String>, i64)> = sqlx::query_as(
            r#"
            SELECT from_id, to_id, relation_type, metadata, created_at
            FROM relations
            WHERE to_id = ?
            ORDER BY created_at DESC
            "#,
        )
        .bind(to_id)
        .fetch_all(&self.pool)
        .await?;

        let mut relations = Vec::with_capacity(rows.len());
        for (from_id, to_id, relation_type, metadata, created_at) in rows {
            relations.push(Relation {
                from_id,
                to_id,
                relation_type: RelationType::from_str(&relation_type)?,
                metadata,
                created_at,
            });
        }

        Ok(relations)
    }

    /// Get all relations for an expertise (both incoming and outgoing)
    pub async fn get_all_relations(&self, id: &str) -> Result<Vec<Relation>> {
        debug!("Getting all relations for: {}", id);

        let rows: Vec<(String, String, String, Option<String>, i64)> = sqlx::query_as(
            r#"
            SELECT from_id, to_id, relation_type, metadata, created_at
            FROM relations
            WHERE from_id = ? OR to_id = ?
            ORDER BY created_at DESC
            "#,
        )
        .bind(id)
        .bind(id)
        .fetch_all(&self.pool)
        .await?;

        let mut relations = Vec::with_capacity(rows.len());
        for (from_id, to_id, relation_type, metadata, created_at) in rows {
            relations.push(Relation {
                from_id,
                to_id,
                relation_type: RelationType::from_str(&relation_type)?,
                metadata,
                created_at,
            });
        }

        Ok(relations)
    }

    /// Get dependencies (expertises that this expertise depends on)
    pub async fn get_dependencies(&self, id: &str) -> Result<Vec<String>> {
        debug!("Getting dependencies for: {}", id);

        let rows: Vec<(String,)> = sqlx::query_as(
            r#"
            SELECT DISTINCT to_id
            FROM relations
            WHERE from_id = ? AND relation_type IN ('uses', 'requires', 'extends')
            "#,
        )
        .bind(id)
        .fetch_all(&self.pool)
        .await?;

        Ok(rows.into_iter().map(|(id,)| id).collect())
    }

    /// Get dependents (expertises that depend on this expertise)
    pub async fn get_dependents(&self, id: &str) -> Result<Vec<String>> {
        debug!("Getting dependents for: {}", id);

        let rows: Vec<(String,)> = sqlx::query_as(
            r#"
            SELECT DISTINCT from_id
            FROM relations
            WHERE to_id = ? AND relation_type IN ('uses', 'requires', 'extends')
            "#,
        )
        .bind(id)
        .fetch_all(&self.pool)
        .await?;

        Ok(rows.into_iter().map(|(id,)| id).collect())
    }

    /// Check if adding a relation would create a cycle
    async fn would_create_cycle(&self, from_id: &str, to_id: &str) -> Result<bool> {
        // If we're creating from -> to, check if there's already a path from to -> from
        // This would create a cycle

        let reachable = self.get_reachable_nodes(to_id).await?;
        Ok(reachable.contains(from_id))
    }

    /// Get all nodes reachable from a given node (DFS)
    async fn get_reachable_nodes(&self, start_id: &str) -> Result<HashSet<String>> {
        let mut reachable = HashSet::new();
        let mut to_visit = vec![start_id.to_string()];

        while let Some(current) = to_visit.pop() {
            if reachable.contains(&current) {
                continue;
            }

            reachable.insert(current.clone());

            let deps = self.get_dependencies(&current).await?;
            for dep in deps {
                if !reachable.contains(&dep) {
                    to_visit.push(dep);
                }
            }
        }

        Ok(reachable)
    }

    /// Build a full dependency graph
    pub async fn build_graph(&self) -> Result<HashMap<String, Vec<String>>> {
        debug!("Building full dependency graph");

        let rows: Vec<(String, String)> = sqlx::query_as(
            r#"
            SELECT DISTINCT from_id, to_id
            FROM relations
            WHERE relation_type IN ('uses', 'requires', 'extends')
            "#,
        )
        .fetch_all(&self.pool)
        .await?;

        let mut graph: HashMap<String, Vec<String>> = HashMap::new();

        for (from_id, to_id) in rows {
            graph.entry(from_id).or_default().push(to_id);
        }

        Ok(graph)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Database, Expertise, Scope, StorageOperations};
    use tempfile::TempDir;

    async fn setup_db() -> (Database, TempDir) {
        let temp_dir = TempDir::new().unwrap();
        let db_path = temp_dir.path().join("test.db");
        let db = Database::open(&db_path).await.unwrap();
        (db, temp_dir)
    }

    async fn create_test_expertise(db: &Database, id: &str) {
        let mut exp = Expertise::new(id, "1.0.0");
        exp.metadata.scope = Scope::Personal;
        db.storage().create(exp).await.unwrap();
    }

    #[tokio::test]
    async fn test_create_relation() {
        let (db, _temp) = setup_db().await;

        create_test_expertise(&db, "exp-1").await;
        create_test_expertise(&db, "exp-2").await;

        db.graph()
            .create_relation("exp-1", "exp-2", RelationType::Uses, None)
            .await
            .unwrap();

        let outgoing = db.graph().get_outgoing("exp-1").await.unwrap();
        assert_eq!(outgoing.len(), 1);
        assert_eq!(outgoing[0].to_id, "exp-2");
        assert_eq!(outgoing[0].relation_type, RelationType::Uses);
    }

    #[tokio::test]
    async fn test_circular_dependency_detection() {
        let (db, _temp) = setup_db().await;

        create_test_expertise(&db, "exp-1").await;
        create_test_expertise(&db, "exp-2").await;
        create_test_expertise(&db, "exp-3").await;

        // Create chain: 1 -> 2 -> 3
        db.graph()
            .create_relation("exp-1", "exp-2", RelationType::Uses, None)
            .await
            .unwrap();
        db.graph()
            .create_relation("exp-2", "exp-3", RelationType::Uses, None)
            .await
            .unwrap();

        // Try to create cycle: 3 -> 1 (should fail)
        let result = db
            .graph()
            .create_relation("exp-3", "exp-1", RelationType::Uses, None)
            .await;

        assert!(matches!(result, Err(Error::CircularDependency { .. })));
    }

    #[tokio::test]
    async fn test_get_dependencies() {
        let (db, _temp) = setup_db().await;

        create_test_expertise(&db, "exp-1").await;
        create_test_expertise(&db, "exp-2").await;
        create_test_expertise(&db, "exp-3").await;

        db.graph()
            .create_relation("exp-1", "exp-2", RelationType::Uses, None)
            .await
            .unwrap();
        db.graph()
            .create_relation("exp-1", "exp-3", RelationType::Requires, None)
            .await
            .unwrap();

        let deps = db.graph().get_dependencies("exp-1").await.unwrap();
        assert_eq!(deps.len(), 2);
        assert!(deps.contains(&"exp-2".to_string()));
        assert!(deps.contains(&"exp-3".to_string()));
    }

    #[tokio::test]
    async fn test_get_dependents() {
        let (db, _temp) = setup_db().await;

        create_test_expertise(&db, "exp-1").await;
        create_test_expertise(&db, "exp-2").await;
        create_test_expertise(&db, "exp-3").await;

        db.graph()
            .create_relation("exp-2", "exp-1", RelationType::Uses, None)
            .await
            .unwrap();
        db.graph()
            .create_relation("exp-3", "exp-1", RelationType::Requires, None)
            .await
            .unwrap();

        let dependents = db.graph().get_dependents("exp-1").await.unwrap();
        assert_eq!(dependents.len(), 2);
        assert!(dependents.contains(&"exp-2".to_string()));
        assert!(dependents.contains(&"exp-3".to_string()));
    }

    #[tokio::test]
    async fn test_delete_relation() {
        let (db, _temp) = setup_db().await;

        create_test_expertise(&db, "exp-1").await;
        create_test_expertise(&db, "exp-2").await;

        db.graph()
            .create_relation("exp-1", "exp-2", RelationType::Uses, None)
            .await
            .unwrap();

        db.graph()
            .delete_relation("exp-1", "exp-2", RelationType::Uses)
            .await
            .unwrap();

        let outgoing = db.graph().get_outgoing("exp-1").await.unwrap();
        assert_eq!(outgoing.len(), 0);
    }
}