magellan 3.3.6

Deterministic codebase mapping tool for local development
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
//! Execution log for tracking Magellan runs
//!
//! Records every CLI command execution with execution_id, timestamps,
//! arguments, and outcome. Provides audit trail for correlating outputs.

use anyhow::Result;
use rusqlite::{params, OptionalExtension};
use std::path::Path;
use std::sync::{Arc, Mutex};

/// Execution log entry
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExecutionRecord {
    pub id: i64,
    pub execution_id: String,
    pub tool_version: String,
    pub args: String, // JSON array
    pub root: Option<String>,
    pub db_path: String,
    pub started_at: i64,
    pub finished_at: Option<i64>,
    pub duration_ms: Option<i64>,
    pub outcome: String, // "success", "error", "partial"
    pub error_message: Option<String>,
    pub files_indexed: i64,
    pub symbols_indexed: i64,
    pub references_indexed: i64,
}

/// Backend storage for ExecutionLog
enum ExecutionLogBackend {
    /// SQLite database path (opens new connection per operation)
    Sqlite(std::path::PathBuf),
    /// Shared connection from CodeGraph (avoids opening new connections)
    Shared(Arc<Mutex<rusqlite::Connection>>),
    /// SideTables abstraction (V3 backend)
    SideTables(Arc<dyn super::side_tables::SideTables>),
}

/// Execution log storage
///
/// Uses either:
/// - SQLite connection to database file (legacy)
/// - Shared connection from CodeGraph
/// - SideTables trait abstraction (V3 backend)
pub struct ExecutionLog {
    backend: ExecutionLogBackend,
}

impl ExecutionLog {
    /// Create a new ExecutionLog with the given database path.
    pub fn new(db_path: &Path) -> Self {
        Self {
            backend: ExecutionLogBackend::Sqlite(db_path.to_path_buf()),
        }
    }

    /// Create an ExecutionLog using a shared connection.
    ///
    /// This eliminates redundant connection opens by reusing CodeGraph's side_conn.
    pub fn with_connection(conn: Arc<Mutex<rusqlite::Connection>>) -> Self {
        let log = Self {
            backend: ExecutionLogBackend::Shared(conn),
        };
        if let Err(e) = log.ensure_schema() {
            eprintln!("Warning: Failed to ensure ExecutionLog schema: {}", e);
        }
        log
    }

    /// Create an ExecutionLog using the SideTables abstraction.
    ///
    /// This constructor is used for V3 backend where we want to avoid SQLite
    /// entirely for side tables.
    pub fn with_side_tables(side_tables: Arc<dyn super::side_tables::SideTables>) -> Self {
        Self {
            backend: ExecutionLogBackend::SideTables(side_tables),
        }
    }

    /// Create an in-memory ExecutionLog for testing/stub usage.
    ///
    /// Uses a temporary file so that new connections can access the same data.
    pub fn in_memory() -> Self {
        let temp_dir = std::env::temp_dir();
        let unique_id = format!(
            "{}_{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        );
        let db_path = temp_dir.join(format!("magellan_execution_log_stub_{}.db", unique_id));

        let log = Self {
            backend: ExecutionLogBackend::Sqlite(db_path),
        };

        // Ensure schema exists
        if let Err(e) = log.ensure_schema() {
            eprintln!("Warning: Failed to ensure ExecutionLog schema: {}", e);
        }

        log
    }

    /// Get a connection to the database (SQLite backend only).
    ///
    /// Returns an error when using Shared or SideTables backends.
    pub fn connect(&self) -> Result<rusqlite::Connection, rusqlite::Error> {
        match &self.backend {
            ExecutionLogBackend::Sqlite(path) => rusqlite::Connection::open(path),
            ExecutionLogBackend::Shared(_) => Err(rusqlite::Error::InvalidParameterName(
                "Direct SQLite connection not available for shared backend".to_string(),
            )),
            ExecutionLogBackend::SideTables(_) => Err(rusqlite::Error::InvalidParameterName(
                "SQLite connection not available for SideTables backend".to_string(),
            )),
        }
    }

    fn ensure_schema_sqlite(conn: &rusqlite::Connection) -> Result<(), anyhow::Error> {
        conn.execute(
            "CREATE TABLE IF NOT EXISTS execution_log (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    execution_id TEXT NOT NULL UNIQUE,
                    tool_version TEXT NOT NULL,
                    args TEXT NOT NULL,
                    root TEXT,
                    db_path TEXT NOT NULL,
                    started_at INTEGER NOT NULL,
                    finished_at INTEGER,
                    duration_ms INTEGER,
                    outcome TEXT NOT NULL,
                    error_message TEXT,
                    files_indexed INTEGER DEFAULT 0,
                    symbols_indexed INTEGER DEFAULT 0,
                    references_indexed INTEGER DEFAULT 0
                )",
            [],
        )
        .map_err(|e| anyhow::anyhow!("Failed to create execution_log table: {}", e))?;

        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_execution_log_started_at
                    ON execution_log(started_at DESC)",
            [],
        )
        .map_err(|e| anyhow::anyhow!("Failed to create started_at index: {}", e))?;

        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_execution_log_execution_id
                    ON execution_log(execution_id)",
            [],
        )
        .map_err(|e| anyhow::anyhow!("Failed to create execution_id index: {}", e))?;

        conn.execute(
            "CREATE INDEX IF NOT EXISTS idx_execution_log_outcome
                    ON execution_log(outcome)",
            [],
        )
        .map_err(|e| anyhow::anyhow!("Failed to create outcome index: {}", e))?;

        Ok(())
    }

    pub fn ensure_schema(&self) -> Result<()> {
        match &self.backend {
            ExecutionLogBackend::Sqlite(_) => {
                let conn = self.connect()?;
                Self::ensure_schema_sqlite(&conn)
            }
            ExecutionLogBackend::Shared(conn_arc) => {
                let conn = match conn_arc.lock() {
                    Ok(guard) => guard,
                    Err(poisoned) => poisoned.into_inner(),
                };
                Self::ensure_schema_sqlite(&conn)
            }
            ExecutionLogBackend::SideTables(_) => {
                // V3 backend handles schema automatically
                Ok(())
            }
        }
    }

    fn start_execution_sqlite(
        conn: &rusqlite::Connection,
        execution_id: &str,
        tool_version: &str,
        args: &[String],
        root: Option<&str>,
        db_path: &str,
    ) -> Result<i64> {
        let args_json = serde_json::to_string(args)?;
        let started_at = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs() as i64;

        conn.execute(
            "INSERT INTO execution_log
                    (execution_id, tool_version, args, root, db_path, started_at, outcome)
                    VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'running')",
            params![
                execution_id,
                tool_version,
                args_json,
                root,
                db_path,
                started_at
            ],
        )
        .map_err(|e| anyhow::anyhow!("Failed to insert execution log: {}", e))?;

        Ok(conn.last_insert_rowid())
    }

    pub fn start_execution(
        &self,
        execution_id: &str,
        tool_version: &str,
        args: &[String],
        root: Option<&str>,
        db_path: &str,
    ) -> Result<i64> {
        match &self.backend {
            ExecutionLogBackend::Sqlite(_) => {
                let conn = self.connect()?;
                Self::start_execution_sqlite(&conn, execution_id, tool_version, args, root, db_path)
            }
            ExecutionLogBackend::Shared(conn_arc) => {
                let conn = match conn_arc.lock() {
                    Ok(guard) => guard,
                    Err(poisoned) => poisoned.into_inner(),
                };
                Self::start_execution_sqlite(&conn, execution_id, tool_version, args, root, db_path)
            }
            ExecutionLogBackend::SideTables(side_tables) => {
                side_tables.start_execution(execution_id, tool_version, args, root, db_path)
            }
        }
    }

    fn finish_execution_sqlite(
        conn: &rusqlite::Connection,
        execution_id: &str,
        outcome: &str,
        error_message: Option<&str>,
        files_indexed: usize,
        symbols_indexed: usize,
        references_indexed: usize,
    ) -> Result<()> {
        let now = std::time::SystemTime::now();
        let finished_at_secs = now
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs() as i64;
        let finished_at_ms = now
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis() as i64;

        let started_at_secs: i64 = conn
            .query_row(
                "SELECT started_at FROM execution_log WHERE execution_id = ?1",
                params![execution_id],
                |row| row.get(0),
            )
            .optional()?
            .unwrap_or(finished_at_secs);
        let started_at_ms = started_at_secs * 1000;

        let duration_ms = finished_at_ms - started_at_ms;

        conn.execute(
            "UPDATE execution_log
                    SET finished_at = ?1, outcome = ?2, error_message = ?3,
                        duration_ms = ?4, files_indexed = ?5, symbols_indexed = ?6,
                        references_indexed = ?7
                    WHERE execution_id = ?8",
            params![
                finished_at_secs,
                outcome,
                error_message,
                duration_ms,
                files_indexed as i64,
                symbols_indexed as i64,
                references_indexed as i64,
                execution_id,
            ],
        )
        .map_err(|e| anyhow::anyhow!("Failed to update execution log: {}", e))?;

        Ok(())
    }

    pub fn finish_execution(
        &self,
        execution_id: &str,
        outcome: &str,
        error_message: Option<&str>,
        files_indexed: usize,
        symbols_indexed: usize,
        references_indexed: usize,
    ) -> Result<()> {
        match &self.backend {
            ExecutionLogBackend::Sqlite(_) => {
                let conn = self.connect()?;
                Self::finish_execution_sqlite(
                    &conn,
                    execution_id,
                    outcome,
                    error_message,
                    files_indexed,
                    symbols_indexed,
                    references_indexed,
                )
            }
            ExecutionLogBackend::Shared(conn_arc) => {
                let conn = match conn_arc.lock() {
                    Ok(guard) => guard,
                    Err(poisoned) => poisoned.into_inner(),
                };
                Self::finish_execution_sqlite(
                    &conn,
                    execution_id,
                    outcome,
                    error_message,
                    files_indexed,
                    symbols_indexed,
                    references_indexed,
                )
            }
            ExecutionLogBackend::SideTables(side_tables) => side_tables.finish_execution(
                execution_id,
                outcome,
                error_message,
                files_indexed,
                symbols_indexed,
                references_indexed,
            ),
        }
    }

    fn row_to_execution_record(row: &rusqlite::Row) -> Result<ExecutionRecord, rusqlite::Error> {
        Ok(ExecutionRecord {
            id: row.get(0)?,
            execution_id: row.get(1)?,
            tool_version: row.get(2)?,
            args: row.get(3)?,
            root: row.get(4)?,
            db_path: row.get(5)?,
            started_at: row.get(6)?,
            finished_at: row.get(7)?,
            duration_ms: row.get(8)?,
            outcome: row.get(9)?,
            error_message: row.get(10)?,
            files_indexed: row.get(11)?,
            symbols_indexed: row.get(12)?,
            references_indexed: row.get(13)?,
        })
    }

    /// Get an execution record by execution_id
    pub fn get_by_execution_id(&self, execution_id: &str) -> Result<Option<ExecutionRecord>> {
        match &self.backend {
            ExecutionLogBackend::Sqlite(_) => {
                let conn = self.connect()?;
                let result = conn
                    .query_row(
                        "SELECT id, execution_id, tool_version, args, root, db_path,
                                started_at, finished_at, duration_ms, outcome, error_message,
                                files_indexed, symbols_indexed, references_indexed
                         FROM execution_log
                         WHERE execution_id = ?1",
                        params![execution_id],
                        Self::row_to_execution_record,
                    )
                    .optional()
                    .map_err(|e| anyhow::anyhow!("Failed to query execution log: {}", e))?;
                Ok(result)
            }
            ExecutionLogBackend::Shared(conn_arc) => {
                let conn = match conn_arc.lock() {
                    Ok(guard) => guard,
                    Err(poisoned) => poisoned.into_inner(),
                };
                let result = conn
                    .query_row(
                        "SELECT id, execution_id, tool_version, args, root, db_path,
                                started_at, finished_at, duration_ms, outcome, error_message,
                                files_indexed, symbols_indexed, references_indexed
                         FROM execution_log
                         WHERE execution_id = ?1",
                        params![execution_id],
                        Self::row_to_execution_record,
                    )
                    .optional()
                    .map_err(|e| anyhow::anyhow!("Failed to query execution log: {}", e))?;
                Ok(result)
            }
            ExecutionLogBackend::SideTables(side_tables) => side_tables.get_execution(execution_id),
        }
    }

    /// Get all execution records, ordered by most recent first
    pub fn list_all(&self, limit: Option<usize>) -> Result<Vec<ExecutionRecord>> {
        let limit_clause = limit.map(|l| format!(" LIMIT {}", l)).unwrap_or_default();
        let sql = format!(
            "SELECT id, execution_id, tool_version, args, root, db_path,
                    started_at, finished_at, duration_ms, outcome, error_message,
                    files_indexed, symbols_indexed, references_indexed
             FROM execution_log
             ORDER BY started_at DESC{}",
            limit_clause
        );

        match &self.backend {
            ExecutionLogBackend::Sqlite(_) => {
                let conn = self.connect()?;
                let mut stmt = conn.prepare(&sql)?;
                let records = stmt
                    .query_map([], Self::row_to_execution_record)?
                    .collect::<Result<Vec<_>, _>>()
                    .map_err(|e| anyhow::anyhow!("Failed to collect execution records: {}", e))?;
                Ok(records)
            }
            ExecutionLogBackend::Shared(conn_arc) => {
                let conn = match conn_arc.lock() {
                    Ok(guard) => guard,
                    Err(poisoned) => poisoned.into_inner(),
                };
                let mut stmt = conn.prepare(&sql)?;
                let records = stmt
                    .query_map([], Self::row_to_execution_record)?
                    .collect::<Result<Vec<_>, _>>()
                    .map_err(|e| anyhow::anyhow!("Failed to collect execution records: {}", e))?;
                Ok(records)
            }
            ExecutionLogBackend::SideTables(side_tables) => side_tables.list_executions(limit),
        }
    }
}

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

    #[test]
    fn test_execution_log_schema() {
        let dir = tempdir().unwrap();
        let db_path = dir.path().join("test.db");
        let log = ExecutionLog::new(&db_path);

        // ensure_schema should create table without error
        log.ensure_schema().unwrap();

        // Verify table exists by querying it
        let conn = log.connect().unwrap();
        let table_exists: bool = conn
            .query_row(
                "SELECT 1 FROM sqlite_master WHERE type='table' AND name='execution_log'",
                [],
                |_| Ok(true),
            )
            .optional()
            .unwrap()
            .unwrap_or(false);

        assert!(table_exists, "execution_log table should exist");
    }

    #[test]
    fn test_execution_log_insert_and_update() {
        let dir = tempdir().unwrap();
        let db_path = dir.path().join("test.db");
        let log = ExecutionLog::new(&db_path);

        log.ensure_schema().unwrap();

        // Start an execution
        let row_id = log
            .start_execution(
                "test-exec-001",
                "0.1.0",
                &["magellan".to_string(), "index".to_string()],
                Some("/project"),
                "/project/magellan.db",
            )
            .unwrap();

        assert!(row_id > 0, "Row ID should be positive");

        // Verify initial state
        let record = log.get_by_execution_id("test-exec-001").unwrap();
        assert!(record.is_some());
        let rec = record.unwrap();
        assert_eq!(rec.execution_id, "test-exec-001");
        assert_eq!(rec.tool_version, "0.1.0");
        assert_eq!(rec.outcome, "running");
        assert!(rec.finished_at.is_none());
        assert!(rec.duration_ms.is_none());

        // Finish the execution
        log.finish_execution("test-exec-001", "success", None, 42, 100, 50)
            .unwrap();

        // Verify updated state
        let record = log.get_by_execution_id("test-exec-001").unwrap();
        assert!(record.is_some());
        let rec = record.unwrap();
        assert_eq!(rec.outcome, "success");
        assert!(rec.finished_at.is_some());
        assert!(rec.duration_ms.is_some());
        assert_eq!(rec.files_indexed, 42);
        assert_eq!(rec.symbols_indexed, 100);
        assert_eq!(rec.references_indexed, 50);
    }

    #[test]
    fn test_execution_log_duplicate_id() {
        let dir = tempdir().unwrap();
        let db_path = dir.path().join("test.db");
        let log = ExecutionLog::new(&db_path);

        log.ensure_schema().unwrap();

        // Start first execution
        log.start_execution("dup-exec", "0.1.0", &[], None, "/db")
            .unwrap();

        // Attempt to start second with same ID - should fail
        let result = log.start_execution("dup-exec", "0.1.0", &[], None, "/db");

        assert!(result.is_err(), "Duplicate execution_id should fail");
    }

    #[test]
    fn test_execution_outcome_values() {
        let dir = tempdir().unwrap();
        let db_path = dir.path().join("test.db");
        let log = ExecutionLog::new(&db_path);

        log.ensure_schema().unwrap();

        // Test success outcome
        log.start_execution("exec-success", "0.1.0", &[], None, "/db")
            .unwrap();
        log.finish_execution("exec-success", "success", None, 1, 0, 0)
            .unwrap();

        let rec = log.get_by_execution_id("exec-success").unwrap().unwrap();
        assert_eq!(rec.outcome, "success");

        // Test error outcome
        log.start_execution("exec-error", "0.1.0", &[], None, "/db")
            .unwrap();
        log.finish_execution("exec-error", "error", Some("test error"), 0, 0, 0)
            .unwrap();

        let rec = log.get_by_execution_id("exec-error").unwrap().unwrap();
        assert_eq!(rec.outcome, "error");
        assert_eq!(rec.error_message, Some("test error".to_string()));

        // Test partial outcome
        log.start_execution("exec-partial", "0.1.0", &[], None, "/db")
            .unwrap();
        log.finish_execution("exec-partial", "partial", None, 5, 0, 0)
            .unwrap();

        let rec = log.get_by_execution_id("exec-partial").unwrap().unwrap();
        assert_eq!(rec.outcome, "partial");
    }

    #[test]
    fn test_list_all_executions() {
        let dir = tempdir().unwrap();
        let db_path = dir.path().join("test.db");
        let log = ExecutionLog::new(&db_path);

        log.ensure_schema().unwrap();

        // Create multiple executions
        for i in 0..5 {
            let id = format!("exec-{:03}", i);
            log.start_execution(&id, "0.1.0", &[], None, "/db").unwrap();
            log.finish_execution(&id, "success", None, i, 0, 0).unwrap();
        }

        // List all
        let all = log.list_all(None).unwrap();
        assert_eq!(all.len(), 5);

        // List with limit
        let limited = log.list_all(Some(3)).unwrap();
        assert_eq!(limited.len(), 3);

        // Verify order (most recent first)
        // Due to timing, we just verify the IDs exist
        let ids: Vec<_> = all.iter().map(|r| r.execution_id.as_str()).collect();
        assert!(ids.contains(&"exec-000"));
        assert!(ids.contains(&"exec-004"));
    }

    #[test]
    fn test_duration_calculation() {
        let dir = tempdir().unwrap();
        let db_path = dir.path().join("test.db");
        let log = ExecutionLog::new(&db_path);

        log.ensure_schema().unwrap();

        log.start_execution("exec-duration", "0.1.0", &[], None, "/db")
            .unwrap();

        // Small delay to ensure positive duration
        std::thread::sleep(std::time::Duration::from_millis(50));

        log.finish_execution("exec-duration", "success", None, 0, 0, 0)
            .unwrap();

        let rec = log.get_by_execution_id("exec-duration").unwrap().unwrap();
        assert!(rec.duration_ms.is_some());
        let duration = rec.duration_ms.unwrap();
        assert!(
            duration >= 0,
            "Duration should be non-negative, got {}ms",
            duration
        );
        // Note: Duration can be 0 if execution finishes within the same millisecond as start
        // This is acceptable behavior - we just need to verify the duration field is populated
        assert!(
            duration < 30000,
            "Duration should be less than 30 seconds even under heavy load, got {}ms",
            duration
        );
    }
}