intent-engine 0.11.1

A command-line database service for tracking strategic intent, tasks, and events
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
use anyhow::{Context, Result};
use axum::{
    extract::{Path, State},
    http::{header, Method, StatusCode},
    response::{Html, IntoResponse, Json, Response},
    routing::get,
    Router,
};
use rust_embed::RustEmbed;
use serde::Serialize;
use sqlx::SqlitePool;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::RwLock;
use tower_http::{
    cors::{Any, CorsLayer},
    trace::TraceLayer,
};

use super::websocket;

/// Canonicalize a path, falling back to the original if the path does not
/// exist yet.  On Windows, `Path::canonicalize()` prepends the `\\?\`
/// extended-path prefix, so every key stored in `known_projects` and every
/// value stored in `active_project_path` must go through this helper.
///
/// Invariant: ALL keys in `known_projects` and `active_project_path` are
/// canonical.  Methods that write to these data structures call this helper;
/// methods that read from them perform direct lookups.
fn canonical_path(path: &std::path::Path) -> PathBuf {
    path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
}

/// Embedded static assets (HTML, CSS, JS)
#[derive(RustEmbed)]
#[folder = "static/"]
struct StaticAssets;

/// Minimal project info (no connection pool - SQLite is fast enough to open on demand)
#[derive(Clone, Debug)]
pub struct ProjectInfo {
    pub name: String,
    pub path: PathBuf,
    pub db_path: PathBuf,
}

/// Dashboard server state shared across handlers
#[derive(Clone)]
pub struct AppState {
    /// Known projects (path -> info). No connection pools - SQLite opens fast.
    pub known_projects: Arc<RwLock<HashMap<PathBuf, ProjectInfo>>>,
    /// Currently active project path (for UI display)
    pub active_project_path: Arc<RwLock<PathBuf>>,
    /// The project that started the Dashboard (always considered online)
    pub host_project: super::websocket::ProjectInfo,
    pub port: u16,
    /// WebSocket state for real-time connections
    pub ws_state: super::websocket::WebSocketState,
    /// Shutdown signal sender (for graceful shutdown via HTTP)
    pub shutdown_tx: Arc<tokio::sync::Mutex<Option<tokio::sync::oneshot::Sender<()>>>>,
}

impl AppState {
    /// Get database pool for a project (opens on demand - SQLite is fast)
    pub async fn get_db_pool(&self, project_path: &std::path::Path) -> Result<SqlitePool, String> {
        // Normalize the lookup key: known_projects is keyed by canonical paths.
        let key = canonical_path(project_path);
        let projects = self.known_projects.read().await;
        if let Some(info) = projects.get(&key) {
            let db_url = format!("sqlite://{}", info.db_path.display());
            SqlitePool::connect(&db_url)
                .await
                .map_err(|e| format!("Failed to connect to database: {}", e))
        } else {
            Err(format!("Project not found: {}", project_path.display()))
        }
    }

    /// Get database pool for the active project
    pub async fn get_active_db_pool(&self) -> Result<SqlitePool, String> {
        let active_path = self.active_project_path.read().await.clone();
        self.get_db_pool(&active_path).await
    }

    /// Add a new project (or update existing)
    pub async fn add_project(&self, path: PathBuf) -> Result<(), String> {
        if !path.exists() {
            return Err(format!("Project path does not exist: {}", path.display()));
        }

        let db_path = path.join(".intent-engine").join("project.db");
        if !db_path.exists() {
            return Err(format!("Database not found: {}", db_path.display()));
        }

        let name = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("unknown")
            .to_string();

        // Canonicalize before inserting so the key matches all other entries.
        // db_path is also canonicalized: derived paths inherit the Windows \\?\
        // prefix from their base, and future callers may compare db_path values.
        let canonical = canonical_path(&path);
        let db_path = canonical_path(&db_path);
        let info = ProjectInfo {
            name,
            path: canonical.clone(),
            db_path,
        };

        let mut projects = self.known_projects.write().await;
        projects.insert(canonical, info);
        Ok(())
    }

    /// Get active project info
    pub async fn get_active_project(&self) -> Option<ProjectInfo> {
        let active_path = self.active_project_path.read().await;
        let projects = self.known_projects.read().await;
        projects.get(&*active_path).cloned()
    }

    /// Switch active project
    pub async fn switch_active_project(&self, path: PathBuf) -> Result<(), String> {
        let canonical = canonical_path(&path);
        let projects = self.known_projects.read().await;
        if !projects.contains_key(&canonical) {
            return Err(format!("Project not registered: {}", path.display()));
        }
        drop(projects);

        let mut active = self.active_project_path.write().await;
        *active = canonical;
        Ok(())
    }

    /// Remove a project from known projects and global registry
    pub async fn remove_project(&self, path: &std::path::Path) -> Result<(), String> {
        let canonical = canonical_path(path);

        // Don't allow removing the host project. Compare canonical forms on
        // both sides: host_project.path may be a non-canonical display string.
        let host_canonical = canonical_path(std::path::Path::new(&self.host_project.path));
        if canonical == host_canonical {
            return Err("Cannot remove the host project".to_string());
        }

        // Remove from known projects. Use canonical key — non-canonical remove
        // silently returns None and the project stays in the map.
        let mut projects = self.known_projects.write().await;
        projects.remove(&canonical);

        // Remove from global registry.  global_projects::remove_project
        // canonicalizes the path internally, but passing canonical here is
        // harmless and makes the intent explicit.
        let path_str = canonical.to_string_lossy().to_string();
        crate::global_projects::remove_project(&path_str);

        Ok(())
    }

    /// Get active project's db_pool and path (backward compatibility helper)
    /// Returns (db_pool, project_path_string)
    pub async fn get_active_project_context(&self) -> Result<(SqlitePool, String), String> {
        let db_pool = self.get_active_db_pool().await?;
        let project_path = self
            .get_active_project()
            .await
            .map(|p| p.path.to_string_lossy().to_string())
            .unwrap_or_default();
        Ok((db_pool, project_path))
    }
}

/// Dashboard server instance
pub struct DashboardServer {
    port: u16,
    db_path: PathBuf,
    project_name: String,
    project_path: PathBuf,
}

/// Health check response
#[derive(Serialize)]
struct HealthResponse {
    status: String,
    service: String,
    version: String,
}

/// Project info response (for API)
#[derive(Serialize)]
struct ProjectInfoResponse {
    name: String,
    path: String,
    database: String,
    port: u16,
    is_online: bool,
    mcp_connected: bool,
}

impl DashboardServer {
    /// Create a new Dashboard server instance
    pub async fn new(port: u16, project_path: PathBuf, db_path: PathBuf) -> Result<Self> {
        // Determine project name from path
        let project_name = project_path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("unknown")
            .to_string();

        if !db_path.exists() {
            anyhow::bail!(
                "Database not found at {}. Is this an Intent-Engine project?",
                db_path.display()
            );
        }

        Ok(Self {
            port,
            db_path,
            project_name,
            project_path,
        })
    }

    /// Run the Dashboard server
    pub async fn run(self) -> Result<()> {
        // Initialize known projects with the host project.
        // canonical_path() is the single normalization point: every key written
        // into this map goes through it, so all reads can do plain lookups.
        let mut known_projects = HashMap::new();
        let host_canonical = canonical_path(&self.project_path);
        let host_info = ProjectInfo {
            name: self.project_name.clone(),
            path: host_canonical.clone(),
            db_path: self.db_path.clone(),
        };
        known_projects.insert(host_canonical.clone(), host_info);

        // Load projects from global registry
        let registry = crate::global_projects::ProjectsRegistry::load();
        for entry in registry.projects {
            let path = PathBuf::from(&entry.path);
            let key = canonical_path(&path);
            // Skip if already added (e.g. host project)
            if known_projects.contains_key(&key) {
                continue;
            }
            let db_path = path.join(".intent-engine").join("project.db");
            if db_path.exists() {
                let name = entry.name.unwrap_or_else(|| {
                    path.file_name()
                        .and_then(|n| n.to_str())
                        .unwrap_or("unknown")
                        .to_string()
                });
                known_projects.insert(
                    key,
                    ProjectInfo {
                        name,
                        path,
                        db_path,
                    },
                );
            }
        }
        tracing::info!(
            "Loaded {} projects from global registry",
            known_projects.len()
        );

        // Create shared state
        let ws_state = websocket::WebSocketState::new();

        let host_project_info = websocket::ProjectInfo {
            name: self.project_name.clone(),
            path: self.project_path.display().to_string(),
            db_path: self.db_path.display().to_string(),
            agent: None,
            mcp_connected: false, // Will be updated dynamically
            is_online: true,      // Host is always online
        };

        // Create shutdown channel for graceful shutdown
        let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();

        let state = AppState {
            known_projects: Arc::new(RwLock::new(known_projects)),
            // active_project_path must match the HashMap key (already canonical).
            active_project_path: Arc::new(RwLock::new(host_canonical)),
            host_project: host_project_info,
            port: self.port,
            ws_state,
            shutdown_tx: Arc::new(tokio::sync::Mutex::new(Some(shutdown_tx))),
        };

        // Build router
        let app = create_router(state);

        // Bind to address
        // Bind to 0.0.0.0 to allow external access (e.g., from Windows host when running in WSL)
        let addr = format!("0.0.0.0:{}", self.port);
        let listener = tokio::net::TcpListener::bind(&addr)
            .await
            .with_context(|| format!("Failed to bind to {}", addr))?;

        tracing::info!(address = %addr, "Dashboard server listening");
        tracing::warn!(
            port = self.port,
            "⚠️  Dashboard is accessible from external IPs"
        );
        tracing::info!(project = %self.project_name, "Project loaded");
        tracing::info!(db_path = %self.db_path.display(), "Database path");

        // Ignore SIGHUP signal on Unix systems to prevent termination when terminal closes
        #[cfg(unix)]
        {
            unsafe {
                libc::signal(libc::SIGHUP, libc::SIG_IGN);
            }
        }

        // Run server with graceful shutdown
        tracing::info!("Starting server with graceful shutdown support");
        axum::serve(listener, app)
            .with_graceful_shutdown(async {
                shutdown_rx.await.ok();
                tracing::info!("Shutdown signal received, initiating graceful shutdown");
            })
            .await
            .context("Server error")?;

        tracing::info!("Dashboard server shut down successfully");
        Ok(())
    }
}

/// Create the Axum router with all routes and middleware
fn create_router(state: AppState) -> Router {
    use super::routes;

    // Combine basic API routes with full API routes
    let api_routes = Router::new()
        .route("/health", get(health_handler))
        .route("/info", get(info_handler))
        .merge(routes::api_routes());

    // Main router - all routes share the same AppState
    Router::new()
        // Root route - serve index.html
        .route("/", get(serve_index))
        // Static files under /static prefix (embedded)
        .route("/static/*path", get(serve_static))
        // Vite assets under /assets prefix
        .route("/assets/*path", get(serve_assets))
        // API routes under /api prefix
        .nest("/api", api_routes)
        // WebSocket routes (now use full AppState)
        .route("/ws/mcp", get(websocket::handle_mcp_websocket))
        .route("/ws/ui", get(websocket::handle_ui_websocket))
        // Fallback to 404
        .fallback(not_found_handler)
        // Add state
        .with_state(state)
        // Add middleware
        .layer(
            CorsLayer::new()
                .allow_origin(Any)
                .allow_methods([Method::GET, Method::POST, Method::PATCH, Method::DELETE])
                .allow_headers(Any),
        )
        .layer(TraceLayer::new_for_http())
}

/// Serve the main index.html file from embedded assets
async fn serve_index() -> impl IntoResponse {
    match StaticAssets::get("index.html") {
        Some(content) => {
            let body = content.data.to_vec();
            Response::builder()
                .status(StatusCode::OK)
                .header(header::CONTENT_TYPE, "text/html; charset=utf-8")
                .header(header::CACHE_CONTROL, "no-cache, no-store, must-revalidate")
                .header(header::PRAGMA, "no-cache")
                .header(header::EXPIRES, "0")
                .body(body.into())
                .unwrap()
        },
        None => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Html("<h1>Error: index.html not found</h1>".to_string()),
        )
            .into_response(),
    }
}

/// Serve static files from embedded assets
async fn serve_static(Path(path): Path<String>) -> impl IntoResponse {
    // Remove leading slash if present
    let path = path.trim_start_matches('/');

    match StaticAssets::get(path) {
        Some(content) => {
            let mime = mime_guess::from_path(path).first_or_octet_stream();
            let body = content.data.to_vec();
            Response::builder()
                .status(StatusCode::OK)
                .header(header::CONTENT_TYPE, mime.as_ref())
                .header(header::CACHE_CONTROL, "no-cache, no-store, must-revalidate")
                .header(header::PRAGMA, "no-cache")
                .header(header::EXPIRES, "0")
                .body(body.into())
                .unwrap()
        },
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "File not found",
                "code": "NOT_FOUND",
                "path": path
            })),
        )
            .into_response(),
    }
}

/// Serve assets from embedded assets (for Vite)
async fn serve_assets(Path(path): Path<String>) -> impl IntoResponse {
    // Remove leading slash if present
    let path = path.trim_start_matches('/');
    // Prepend "assets/" if not present (though the route is /assets/*path, so path usually won't have it unless we strip it in route)
    // Actually, the route is /assets/*path. If we request /assets/index.css, path is index.css.
    // We need to look up "assets/index.css" in StaticAssets.
    let full_path = format!("assets/{}", path);

    match StaticAssets::get(&full_path) {
        Some(content) => {
            let mime = mime_guess::from_path(&full_path).first_or_octet_stream();
            let body = content.data.to_vec();
            Response::builder()
                .status(StatusCode::OK)
                .header(header::CONTENT_TYPE, mime.as_ref())
                .header(header::CACHE_CONTROL, "public, max-age=31536000, immutable")
                .header(header::PRAGMA, "no-cache")
                .header(header::EXPIRES, "0")
                .body(body.into())
                .unwrap()
        },
        None => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({
                "error": "Asset not found",
                "code": "NOT_FOUND",
                "path": full_path
            })),
        )
            .into_response(),
    }
}

/// Health check handler
async fn health_handler() -> Json<HealthResponse> {
    Json(HealthResponse {
        status: "healthy".to_string(),
        service: "intent-engine-dashboard".to_string(),
        version: env!("CARGO_PKG_VERSION").to_string(),
    })
}

/// Project info handler
/// Returns current Dashboard project info from the single source of truth (WebSocketState)
async fn info_handler(State(state): State<AppState>) -> Json<ProjectInfoResponse> {
    let active_project = state.get_active_project().await;

    match active_project {
        Some(project) => {
            // Get project info from WebSocketState (single source of truth)
            let projects = state
                .ws_state
                .get_online_projects_with_current(
                    &project.name,
                    &project.path,
                    &project.db_path,
                    &state.host_project,
                    state.port,
                )
                .await;

            // Return the first project (which is always the current Dashboard project)
            let current_project = projects.first().expect("Current project must exist");

            Json(ProjectInfoResponse {
                name: current_project.name.clone(),
                path: current_project.path.clone(),
                database: current_project.db_path.clone(),
                port: state.port,
                is_online: current_project.is_online,
                mcp_connected: current_project.mcp_connected,
            })
        },
        None => Json(ProjectInfoResponse {
            name: "unknown".to_string(),
            path: "".to_string(),
            database: "".to_string(),
            port: state.port,
            is_online: false,
            mcp_connected: false,
        }),
    }
}

/// 404 Not Found handler
async fn not_found_handler() -> impl IntoResponse {
    (
        StatusCode::NOT_FOUND,
        Json(serde_json::json!({
            "error": "Not found",
            "code": "NOT_FOUND"
        })),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_health_response_serialization() {
        let response = HealthResponse {
            status: "healthy".to_string(),
            service: "test".to_string(),
            version: "1.0.0".to_string(),
        };

        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("healthy"));
        assert!(json.contains("test"));
    }

    #[test]
    fn test_project_info_response_serialization() {
        let info = ProjectInfoResponse {
            name: "test-project".to_string(),
            path: "/path/to/project".to_string(),
            database: "/path/to/db".to_string(),
            port: 11391,
            is_online: true,
            mcp_connected: false,
        };

        let json = serde_json::to_string(&info).unwrap();
        assert!(json.contains("test-project"));
        assert!(json.contains("11391"));
    }
}