leankg 0.19.10

Lightweight Knowledge Graph for AI-Assisted Development
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
#![allow(dead_code)]
pub mod file_resolve;
pub mod handlers;

use axum::{
    body::Body,
    http::{header, StatusCode},
    response::{IntoResponse, Response},
    routing::{delete, get, post, put},
    Json, Router,
};
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::sync::RwLock;

use crate::db::schema::{init_db, CozoDb};
use crate::embed;
use crate::graph::GraphEngine;

#[derive(Clone)]
pub struct AppState {
    pub db_path: Arc<RwLock<std::path::PathBuf>>,
    pub current_project_path: Arc<RwLock<std::path::PathBuf>>,
    db: Arc<RwLock<Option<CozoDb>>>,
    graph_engine: Arc<RwLock<Option<GraphEngine>>>,
    pub indexing_state: Arc<RwLock<IndexingState>>,
}

#[derive(Clone, Default)]
pub struct IndexingState {
    pub is_indexing: bool,
    pub progress_percent: usize,
    pub current_file: String,
    pub total_files: usize,
    pub indexed_files: usize,
    pub error: Option<String>,
}

impl Default for AppState {
    fn default() -> Self {
        Self {
            db_path: Arc::new(RwLock::new(std::path::PathBuf::new())),
            current_project_path: Arc::new(RwLock::new(std::path::PathBuf::new())),
            db: Arc::new(RwLock::new(None)),
            graph_engine: Arc::new(RwLock::new(None)),
            indexing_state: Arc::new(RwLock::new(IndexingState::default())),
        }
    }
}

impl AppState {
    pub async fn new(
        db_path: std::path::PathBuf,
        current_project_path: std::path::PathBuf,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        Ok(Self {
            db_path: Arc::new(RwLock::new(db_path)),
            current_project_path: Arc::new(RwLock::new(current_project_path)),
            db: Arc::new(RwLock::new(None)),
            graph_engine: Arc::new(RwLock::new(None)),
            indexing_state: Arc::new(RwLock::new(IndexingState::default())),
        })
    }

    pub async fn reset_indexing_state(&self) {
        let mut state = self.indexing_state.write().await;
        state.is_indexing = false;
        state.progress_percent = 0;
        state.current_file = String::new();
        state.total_files = 0;
        state.indexed_files = 0;
        state.error = None;
    }

    pub async fn set_indexing_started(&self, total_files: usize) {
        let mut state = self.indexing_state.write().await;
        state.is_indexing = true;
        state.progress_percent = 0;
        state.total_files = total_files;
        state.indexed_files = 0;
        state.error = None;
    }

    pub async fn update_indexing_progress(&self, indexed_files: usize, current_file: &str) {
        let mut state = self.indexing_state.write().await;
        state.indexed_files = indexed_files;
        state.current_file = current_file.to_string();
        if state.total_files > 0 {
            state.progress_percent = (indexed_files * 100)
                .checked_div(state.total_files)
                .unwrap_or(0);
        }
    }

    pub async fn set_indexing_error(&self, error: String) {
        let mut state = self.indexing_state.write().await;
        state.is_indexing = false;
        state.error = Some(error);
    }

    pub async fn set_indexing_complete(&self) {
        let mut state = self.indexing_state.write().await;
        state.is_indexing = false;
        state.progress_percent = 100;
        state.current_file = String::new();

        // Invalidate graph engine cache since data changed
        if let Some(graph) = self.graph_engine.read().await.as_ref() {
            graph.invalidate_cache();
        }
        drop(state);

        // FR-ONT-PROC-03: refresh procedural ontology after UI-triggered index.
        let project = self.current_project_path.read().await.clone();
        if let Ok(graph) = self.get_graph_engine().await {
            if let Err(e) = crate::ontology::sync_for_project(&project, &graph) {
                tracing::debug!("Ontology post-index sync skipped: {}", e);
            }
        }
    }

    /// Invalidate the graph engine cache (call after data changes)
    pub async fn invalidate_graph_cache(&self) {
        if let Some(graph) = self.graph_engine.read().await.as_ref() {
            graph.invalidate_cache();
        }
    }

    pub async fn switch_project(
        &self,
        project_path: std::path::PathBuf,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let db_path = project_path.join(".leankg");
        std::fs::create_dir_all(&db_path)
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?;

        let prev_project = self.current_project_path.read().await.clone();
        let prev_db_path = self.db_path.read().await.clone();

        // Drop the open RocksDB handle first so we can open another project key.
        // Updating current_project_path before a successful open caused the UI to
        // show ?project=/workspace while expand still served a sibling mount's graph.
        {
            let mut ge_lock = self.graph_engine.write().await;
            *ge_lock = None;
        }
        {
            let mut db_lock = self.db.write().await;
            *db_lock = None;
        }
        tokio::task::yield_now().await;

        let db_path_for_init = db_path.clone();
        let init_result = tokio::task::spawn_blocking(move || {
            init_db(&db_path_for_init).map_err(|e| e.to_string())
        })
        .await
        .map_err(|e| {
            Box::new(std::io::Error::other(format!("init_db task failed: {}", e)))
                as Box<dyn std::error::Error + Send + Sync>
        })?;

        match init_result {
            Ok(db) => {
                let graph = GraphEngine::new(db.clone());
                {
                    let mut db_lock = self.db.write().await;
                    *db_lock = Some(db);
                }
                {
                    let mut ge_lock = self.graph_engine.write().await;
                    *ge_lock = Some(graph);
                }
                {
                    let mut path_guard = self.db_path.write().await;
                    *path_guard = db_path;
                }
                {
                    let mut proj_guard = self.current_project_path.write().await;
                    *proj_guard = project_path;
                }
                self.reset_indexing_state().await;
                if let Ok(g) = self.get_graph_engine().await {
                    if g.count_elements().unwrap_or(0) > 0 {
                        self.set_indexing_complete().await;
                    }
                }
                Ok(())
            }
            Err(msg) => {
                // Best-effort reopen of the previous project so the API stays usable.
                if !prev_db_path.as_os_str().is_empty() {
                    let prev_db_path_for_init = prev_db_path.clone();
                    if let Ok(Ok(db)) = tokio::task::spawn_blocking(move || {
                        init_db(&prev_db_path_for_init).map_err(|e| e.to_string())
                    })
                    .await
                    {
                        let graph = GraphEngine::new(db.clone());
                        let mut db_lock = self.db.write().await;
                        *db_lock = Some(db);
                        let mut ge_lock = self.graph_engine.write().await;
                        *ge_lock = Some(graph);
                        let mut path_guard = self.db_path.write().await;
                        *path_guard = prev_db_path;
                        let mut proj_guard = self.current_project_path.write().await;
                        *proj_guard = prev_project;
                    }
                }
                Err(Box::new(std::io::Error::other(msg))
                    as Box<dyn std::error::Error + Send + Sync>)
            }
        }
    }

    pub async fn init_db(&self) -> Result<(), Box<dyn std::error::Error>> {
        let db_path = self.db_path.read().await.clone();
        let db = init_db(&db_path)?;
        let graph = GraphEngine::new(db.clone());
        let mut db_lock = self.db.write().await;
        let mut ge_lock = self.graph_engine.write().await;
        *db_lock = Some(db);
        *ge_lock = Some(graph);
        Ok(())
    }

    pub fn get_db(&self) -> Result<CozoDb, Box<dyn std::error::Error + Send + Sync>> {
        crate::runtime::run_blocking(async {
            let lock = self.db.read().await;
            lock.clone()
                .ok_or_else(|| "Database not initialized".into())
        })
    }

    pub async fn get_graph_engine(
        &self,
    ) -> Result<GraphEngine, Box<dyn std::error::Error + Send + Sync>> {
        let lock = self.graph_engine.read().await;
        lock.clone()
            .ok_or_else(|| -> Box<dyn std::error::Error + Send + Sync> {
                "Graph engine not initialized. Call init_db() first.".into()
            })
    }
}

#[derive(serde::Serialize)]
pub struct ApiResponse<T> {
    pub success: bool,
    pub data: Option<T>,
    pub error: Option<String>,
}

impl<T: serde::Serialize> ApiResponse<T> {
    pub fn error(msg: &str) -> Self {
        Self {
            success: false,
            data: None,
            error: Some(msg.to_string()),
        }
    }

    pub fn success(data: T) -> Self {
        Self {
            success: true,
            data: Some(data),
            error: None,
        }
    }
}

impl<T: serde::Serialize> IntoResponse for ApiResponse<T> {
    fn into_response(self) -> Response {
        let status = if self.success {
            StatusCode::OK
        } else {
            StatusCode::BAD_REQUEST
        };
        (status, Json(self)).into_response()
    }
}

fn content_type_for_path(path: &str) -> &'static str {
    if path.ends_with(".html") {
        "text/html"
    } else if path.ends_with(".js") {
        "application/javascript"
    } else if path.ends_with(".css") {
        "text/css"
    } else if path.ends_with(".json") {
        "application/json"
    } else if path.ends_with(".png") {
        "image/png"
    } else if path.ends_with(".jpg") || path.ends_with(".jpeg") {
        "image/jpeg"
    } else if path.ends_with(".svg") {
        "image/svg+xml"
    } else if path.ends_with(".ico") {
        "image/x-icon"
    } else {
        "application/octet-stream"
    }
}

async fn serve_embedded_file(path: &str) -> Response {
    let path = path.trim_start_matches('/');
    let file_path = if path.is_empty() || path == "/" {
        "index.html"
    } else {
        path
    };

    if let Some(data) = embed::get(file_path) {
        let ct = content_type_for_path(file_path);
        let mut builder = Response::builder()
            .status(StatusCode::OK)
            .header(header::CONTENT_TYPE, ct);
        // Prevent CDN/browser from pinning a stale HTML shell to old hashed assets.
        if file_path.ends_with(".html") || file_path == "index.html" {
            builder = builder
                .header(header::CACHE_CONTROL, "no-store, must-revalidate")
                .header("X-LeanKG-UI", "ui-v2");
        }
        builder
            .body(Body::from(data.to_vec()))
            .unwrap_or_else(|_| internal_error())
    } else {
        Response::builder()
            .status(StatusCode::NOT_FOUND)
            .header(header::CONTENT_TYPE, "text/html")
            .body(Body::from(embed::get_404().to_vec()))
            .unwrap_or_else(|_| internal_error())
    }
}

fn internal_error() -> Response {
    Response::builder()
        .status(StatusCode::INTERNAL_SERVER_ERROR)
        .body(Body::from(b"Internal Server Error".to_vec()))
        .unwrap()
}

async fn fallback_handler(path: axum::extract::Path<String>) -> Response {
    serve_embedded_file(&path.0).await
}

async fn root_handler() -> Response {
    serve_embedded_file("index.html").await
}

pub async fn start_server(
    port: u16,
    db_path: std::path::PathBuf,
    _ui_dist_path: Option<std::path::PathBuf>,
) -> Result<(), Box<dyn std::error::Error>> {
    let project_root = db_path
        .parent()
        .map(|p| p.to_path_buf())
        .unwrap_or_else(|| db_path.clone());
    let state = AppState::new(db_path.clone(), project_root.clone()).await?;
    state.init_db().await?;

    // FR-ONT-PROC-01: watch ontology YAML while serve is running.
    // GraphEngine caches are Arc-shared across clones; sync_from_dir invalidates them.
    if let Ok(graph) = state.get_graph_engine().await {
        let _ = crate::ontology::spawn_ontology_yaml_watcher(project_root.clone(), graph, |_| {});
    }

    let app = Router::new()
        .route("/", get(root_handler))
        .route("/api/elements", get(handlers::api_elements))
        .route("/api/relationships", get(handlers::api_relationships))
        .route("/api/annotations", get(handlers::api_annotations))
        .route("/api/annotations", post(handlers::api_create_annotation))
        .route(
            "/api/annotations/:element",
            get(handlers::api_get_annotation),
        )
        .route(
            "/api/annotations/:element",
            put(handlers::api_update_annotation),
        )
        .route("/api/search", get(handlers::api_search))
        .route("/api/graph/data", get(handlers::api_graph_data))
        .route("/api/graph/services", get(handlers::api_service_graph))
        .route(
            "/api/graph/service-topology",
            get(handlers::api_service_topology),
        )
        .route(
            "/api/graph/expand-service",
            get(handlers::api_graph_expand_service),
        )
        .route(
            "/api/graph/expand-cluster",
            get(handlers::api_graph_expand_cluster),
        )
        .route("/api/graph/subgraph", get(handlers::api_graph_subgraph))
        .route("/api/graph/clusters", get(handlers::api_graph_clusters))
        .route("/api/graph/report", get(handlers::api_graph_report))
        .route("/api/graph/children", get(handlers::api_graph_children))
        .route(
            "/api/graph/expand-node",
            get(handlers::api_graph_expand_node),
        )
        .route("/api/graph/layout", get(handlers::api_graph_layout))
        .route("/api/export/graph", get(handlers::api_export_graph))
        .route("/api/query", post(handlers::api_query))
        .route("/api/project/switch", post(handlers::api_switch_path))
        .route("/api/index/status", get(handlers::api_index_status))
        .route("/api/ui-build", get(handlers::api_ui_build))
        .route(
            "/api/cache/invalidate",
            post(handlers::api_invalidate_cache),
        )
        .route("/api/github/clone", post(handlers::api_github_clone))
        .route("/api/file", get(handlers::api_get_file))
        .route("/api/incidents", get(handlers::api_incidents))
        .route("/api/conflicts", get(handlers::api_conflicts))
        .route("/api/teams", get(handlers::api_teams))
        .route("/api/teams", post(handlers::api_create_team))
        .route("/api/teams/:id", get(handlers::api_get_team))
        .route("/api/teams/:id", put(handlers::api_update_team))
        .route("/api/teams/:id", delete(handlers::api_delete_team))
        .route(
            "/api/teams/:id/members",
            post(handlers::api_add_team_member),
        )
        .route(
            "/api/teams/:id/members/:user",
            delete(handlers::api_remove_team_member),
        )
        .route("/api/teams/:id/invites", get(handlers::api_team_invites))
        .route(
            "/api/teams/:id/invites",
            post(handlers::api_create_team_invite),
        )
        .route(
            "/api/teams/invites/:token/accept",
            post(handlers::api_accept_team_invite),
        )
        .route(
            "/api/teams/invites/:token",
            delete(handlers::api_revoke_team_invite),
        )
        .route(
            "/api/teams/:id/permissions",
            get(handlers::api_team_permissions),
        )
        .route("/services", get(handlers::services_page))
        .route("/*path", get(fallback_handler))
        .with_state(state);

    let addr = SocketAddr::from(([0, 0, 0, 0], port));
    println!("LeanKG Web UI listening on http://localhost:{}", port);
    println!("Press Ctrl+C to stop");

    let listener = tokio::net::TcpListener::bind(addr).await?;
    axum::serve(listener, app).await?;

    Ok(())
}