mycelium-manager 0.2.7

A robust, production-grade task/plan manager CLI (binary: myc)
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 crate::commands::{ERROR_PREFIX, INFO_PREFIX, SUCCESS_PREFIX, WARNING_PREFIX};
use crate::db::Database;
use crate::error::Result;
use colored::Colorize;
use std::fs;

pub struct CheckResult {
    pub name: String,
    pub status: CheckStatus,
    pub message: String,
    pub fixable: bool,
}

pub enum CheckStatus {
    Ok,
    Warning,
    Error,
}

impl CheckResult {
    fn ok(name: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            status: CheckStatus::Ok,
            message: message.into(),
            fixable: false,
        }
    }

    fn warning(name: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            status: CheckStatus::Warning,
            message: message.into(),
            fixable: false,
        }
    }

    fn error(name: impl Into<String>, message: impl Into<String>, fixable: bool) -> Self {
        Self {
            name: name.into(),
            status: CheckStatus::Error,
            message: message.into(),
            fixable,
        }
    }
}

pub fn execute(fix: bool, quiet: bool) -> Result<()> {
    if !quiet {
        println!("{} Running mycelium health checks...", INFO_PREFIX.blue());
        println!();
    }

    let mut results = Vec::new();
    let mut fixed_count = 0;
    let mut fixable_count = 0;

    // Run all checks
    results.push(check_project_initialized()?);
    results.push(check_database_accessible()?);
    results.push(check_database_integrity()?);
    results.push(check_orphaned_tasks()?);
    results.push(check_circular_dependencies()?);
    results.push(check_gitignore()?);
    results.push(check_wal_files()?);
    results.push(check_schema_version()?);

    // Count fixable issues
    for result in &results {
        if matches!(result.status, CheckStatus::Error) && result.fixable {
            fixable_count += 1;
        }
    }

    // Try to fix issues if requested
    if fix && fixable_count > 0 {
        if !quiet {
            println!(
                "{} Attempting to fix {} issue(s)...",
                INFO_PREFIX.blue(),
                fixable_count
            );
            println!();
        }

        for result in &results {
            if matches!(result.status, CheckStatus::Error) && result.fixable {
                match try_fix(&result.name) {
                    Ok(true) => {
                        fixed_count += 1;
                        if !quiet {
                            println!("{} Fixed: {}", SUCCESS_PREFIX.green(), result.name);
                        }
                    }
                    Ok(false) => {
                        if !quiet {
                            println!("{} Could not fix: {}", WARNING_PREFIX.yellow(), result.name);
                        }
                    }
                    Err(e) => {
                        if !quiet {
                            println!("{} Error fixing {}: {}", ERROR_PREFIX.red(), result.name, e);
                        }
                    }
                }
            }
        }

        if !quiet {
            println!();
        }
    }

    // Display results
    if !quiet {
        display_results(&results);
    }

    // Summary
    let ok_count = results
        .iter()
        .filter(|r| matches!(r.status, CheckStatus::Ok))
        .count();
    let warning_count = results
        .iter()
        .filter(|r| matches!(r.status, CheckStatus::Warning))
        .count();
    let error_count = results
        .iter()
        .filter(|r| matches!(r.status, CheckStatus::Error))
        .count();

    if !quiet {
        println!();
        println!(
            "Summary: {} OK, {} warnings, {} errors",
            ok_count.to_string().green(),
            warning_count.to_string().yellow(),
            error_count.to_string().red()
        );

        if fixable_count > 0 && !fix {
            println!();
            println!(
                "{} {} issue(s) can be fixed automatically. Run with --fix to apply.",
                INFO_PREFIX.blue(),
                fixable_count
            );
        }

        if fix && fixed_count > 0 {
            println!();
            println!("{} Fixed {} issue(s)", SUCCESS_PREFIX.green(), fixed_count);
        }
    }

    // Exit with error code if there are unfixable errors
    if error_count > fixed_count {
        std::process::exit(1);
    }

    Ok(())
}

fn display_results(results: &[CheckResult]) {
    for result in results {
        let (icon, color) = match result.status {
            CheckStatus::Ok => ("✓", "green"),
            CheckStatus::Warning => ("âš ", "yellow"),
            CheckStatus::Error => ("✗", "red"),
        };

        let fix_indicator = if result.fixable { " [fixable]" } else { "" };

        println!(
            "{} {}: {}{}",
            icon.color(color),
            result.name.bold(),
            result.message,
            fix_indicator.dimmed()
        );
    }
}

fn check_project_initialized() -> Result<CheckResult> {
    let mycelium_dir = std::env::current_dir()
        .unwrap_or_else(|_| std::path::PathBuf::from("."))
        .join(".mycelium");

    if !mycelium_dir.exists() {
        return Ok(CheckResult::error(
            "Project initialized",
            "No .mycelium/ directory found. Run 'myc init' first.",
            false,
        ));
    }

    Ok(CheckResult::ok(
        "Project initialized",
        ".mycelium/ directory exists",
    ))
}

fn check_database_accessible() -> Result<CheckResult> {
    let db_path = std::env::current_dir()
        .unwrap_or_else(|_| std::path::PathBuf::from("."))
        .join(".mycelium")
        .join("mycelium.db");

    if !db_path.exists() {
        // Not auto-fixable: silently creating an empty database here would
        // mask what is usually a wrong working directory or a project that
        // was never initialized, and `fix_database` used to do exactly that
        // by calling `Database::open` (which creates-on-open).
        return Ok(CheckResult::error(
            "Database accessible",
            "Database file not found. Run `myc init`, or check that you're in the right directory.",
            false,
        ));
    }

    match Database::open(&db_path) {
        Ok(_) => Ok(CheckResult::ok("Database accessible", "Can open database")),
        Err(e) => Ok(CheckResult::error(
            "Database accessible",
            format!("Cannot open database: {}", e),
            false,
        )),
    }
}

fn check_database_integrity() -> Result<CheckResult> {
    let db_path = std::env::current_dir()
        .unwrap_or_else(|_| std::path::PathBuf::from("."))
        .join(".mycelium")
        .join("mycelium.db");

    if !db_path.exists() {
        return Ok(CheckResult::warning(
            "Database integrity",
            "Database doesn't exist, skipping check",
        ));
    }

    match Database::open(&db_path) {
        Ok(db) => {
            // Try to query each table to verify integrity
            let conn = db.get_conn();

            for table in mycelium_core::db::EXPECTED_TABLES {
                // Check if table exists by querying sqlite_master
                let exists: bool = conn
                    .query_row(
                        "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name=?)",
                        [table],
                        |row| row.get(0),
                    )
                    .unwrap_or(false);

                if !exists {
                    return Ok(CheckResult::error(
                        "Database integrity",
                        format!("Table '{}' does not exist", table),
                        false,
                    ));
                }

                // Try to get column info to verify structure
                let result: std::result::Result<String, rusqlite::Error> = conn.query_row(
                    &format!(
                        "SELECT sql FROM sqlite_master WHERE type='table' AND name='{}'",
                        table
                    ),
                    [],
                    |row| row.get(0),
                );

                if let Err(e) = result {
                    return Ok(CheckResult::error(
                        "Database integrity",
                        format!("Table '{}' structure check failed: {}", table, e),
                        false,
                    ));
                }
            }

            Ok(CheckResult::ok(
                "Database integrity",
                "All tables accessible",
            ))
        }
        Err(e) => Ok(CheckResult::error(
            "Database integrity",
            format!("Cannot verify: {}", e),
            false,
        )),
    }
}

fn check_orphaned_tasks() -> Result<CheckResult> {
    let db_path = std::env::current_dir()
        .unwrap_or_else(|_| std::path::PathBuf::from("."))
        .join(".mycelium")
        .join("mycelium.db");

    if !db_path.exists() {
        return Ok(CheckResult::warning(
            "Orphaned tasks",
            "Database doesn't exist, skipping check",
        ));
    }

    match Database::open(&db_path) {
        Ok(db) => {
            let conn = db.get_conn();

            // "Orphaned" in this codebase means a task with no epic assigned
            // (epic_id IS NULL) — see Database::list_orphan_tasks. Tasks can't
            // actually reference a deleted epic: the FK is
            // `ON DELETE SET NULL`, so a dangling-FK check (the old query)
            // could never fire and always reported zero orphans.
            let orphaned: i64 = conn
                .query_row(
                    "SELECT COUNT(*) FROM tasks WHERE epic_id IS NULL",
                    [],
                    |row| row.get(0),
                )
                .unwrap_or(0);

            if orphaned > 0 {
                Ok(CheckResult::warning(
                    "Orphaned tasks",
                    format!(
                        "{} task(s) have no epic assigned. Review with `myc task batch-op delete-orphans`.",
                        orphaned
                    ),
                ))
            } else {
                Ok(CheckResult::ok("Orphaned tasks", "No orphaned tasks found"))
            }
        }
        Err(_) => Ok(CheckResult::warning("Orphaned tasks", "Cannot check")),
    }
}

fn check_circular_dependencies() -> Result<CheckResult> {
    let db_path = std::env::current_dir()
        .unwrap_or_else(|_| std::path::PathBuf::from("."))
        .join(".mycelium")
        .join("mycelium.db");

    if !db_path.exists() {
        return Ok(CheckResult::warning(
            "Circular dependencies",
            "Database doesn't exist, skipping check",
        ));
    }

    match Database::open(&db_path) {
        Ok(db) => {
            let tasks = db.list_tasks(None, None, None, None, false, false, None)?;

            for task in &tasks {
                if let Ok(chain) = db.get_all_dependencies(task.id) {
                    if chain.all_dependencies.contains(&task.id) {
                        // Not auto-fixable: breaking a dependency cycle requires
                        // deciding which link to remove, which needs human
                        // judgment. `fix_circular_deps` always returned Ok(false)
                        // here, so `fixable: true` was a lie about the --fix path.
                        return Ok(CheckResult::error(
                            "Circular dependencies",
                            format!(
                                "Task #{} has circular dependency. Resolve manually via `myc deps show {}` and `myc deps unlink <task_id> <blocked_task_id>`.",
                                task.id, task.id
                            ),
                            false,
                        ));
                    }
                }
            }

            Ok(CheckResult::ok(
                "Circular dependencies",
                "No circular dependencies found",
            ))
        }
        Err(_) => Ok(CheckResult::warning(
            "Circular dependencies",
            "Cannot check",
        )),
    }
}

fn check_gitignore() -> Result<CheckResult> {
    let gitignore_path = std::env::current_dir()
        .unwrap_or_else(|_| std::path::PathBuf::from("."))
        .join(".mycelium")
        .join(".gitignore");

    if !gitignore_path.exists() {
        return Ok(CheckResult::error(
            "Gitignore",
            ".mycelium/.gitignore not found",
            true,
        ));
    }

    match fs::read_to_string(&gitignore_path) {
        Ok(content) => {
            if content.contains("*.db-wal") && content.contains("*.db-shm") {
                Ok(CheckResult::ok("Gitignore", "WAL files are ignored"))
            } else {
                Ok(CheckResult::error(
                    "Gitignore",
                    ".gitignore missing WAL file entries",
                    true,
                ))
            }
        }
        Err(_) => Ok(CheckResult::error(
            "Gitignore",
            "Cannot read .gitignore",
            false,
        )),
    }
}

fn check_wal_files() -> Result<CheckResult> {
    let mycelium_dir = std::env::current_dir()
        .unwrap_or_else(|_| std::path::PathBuf::from("."))
        .join(".mycelium");

    let wal_exists = mycelium_dir.join("mycelium.db-wal").exists();
    let shm_exists = mycelium_dir.join("mycelium.db-shm").exists();

    if wal_exists || shm_exists {
        Ok(CheckResult::warning(
            "WAL files",
            "WAL files present (normal during operation, can be checkpointed)",
        ))
    } else {
        Ok(CheckResult::ok("WAL files", "No WAL files (clean)"))
    }
}

fn check_schema_version() -> Result<CheckResult> {
    let db_path = std::env::current_dir()
        .unwrap_or_else(|_| std::path::PathBuf::from("."))
        .join(".mycelium")
        .join("mycelium.db");

    if !db_path.exists() {
        return Ok(CheckResult::warning(
            "Schema version",
            "Database doesn't exist",
        ));
    }

    // Note: opening the DB runs migrations, so a healthy path is normally
    // already current here. We still compare the recorded version against the
    // build's latest so a genuinely stuck/downgraded schema is reported, and we
    // report the ACTUAL version instead of a hard-coded one.
    match Database::open(&db_path) {
        Ok(db) => match db.schema_version() {
            Ok(version) if version >= mycelium_core::db::LATEST_SCHEMA_VERSION => Ok(CheckResult::ok(
                "Schema version",
                format!("Database schema is up to date (v{version})"),
            )),
            Ok(version) => Ok(CheckResult::error(
                "Schema version",
                format!(
                    "Database schema is outdated (v{version}, expected v{}). Run `myc doctor --fix`.",
                    mycelium_core::db::LATEST_SCHEMA_VERSION
                ),
                true,
            )),
            Err(e) => Ok(CheckResult::error(
                "Schema version",
                format!("Cannot read schema version: {}", e),
                false,
            )),
        },
        Err(e) => Ok(CheckResult::error(
            "Schema version",
            format!("Cannot check: {}", e),
            false,
        )),
    }
}

fn try_fix(check_name: &str) -> Result<bool> {
    match check_name {
        "Database accessible" => fix_database(),
        "Gitignore" => fix_gitignore(),
        "Schema version" => fix_schema(),
        _ => Ok(false),
    }
}

fn fix_database() -> Result<bool> {
    let db_path = std::env::current_dir()
        .unwrap_or_else(|_| std::path::PathBuf::from("."))
        .join(".mycelium")
        .join("mycelium.db");

    // Never silently create a database here: `Database::open` creates the
    // file if it's missing, which would mask data loss (wrong cwd, deleted
    // db, uninitialized project) as a "Fixed" checkmark. This check is no
    // longer marked fixable, but guard defensively in case it's ever called
    // directly.
    if !db_path.exists() {
        return Ok(false);
    }

    Database::open(&db_path)?;
    Ok(true)
}

fn fix_gitignore() -> Result<bool> {
    let gitignore_path = std::env::current_dir()
        .unwrap_or_else(|_| std::path::PathBuf::from("."))
        .join(".mycelium")
        .join(".gitignore");

    let content = r#"# Mycelium database
# The database file is git-trackable but WAL files are not
*.db-wal
*.db-shm
# Temporary files
*.tmp
"#;

    fs::write(gitignore_path, content)?;
    Ok(true)
}

fn fix_schema() -> Result<bool> {
    let db_path = std::env::current_dir()
        .unwrap_or_else(|_| std::path::PathBuf::from("."))
        .join(".mycelium")
        .join("mycelium.db");

    if !db_path.exists() {
        return Ok(false);
    }

    let mut db = Database::open(&db_path)?;

    // Re-run migrations
    db.migrate()?;

    // Verify the migration actually landed instead of unconditionally
    // reporting success: migrate() can no-op or partially apply if a
    // migration step silently fails to raise, so re-read the recorded
    // version and only claim success if it's truly current.
    let version = db.schema_version()?;
    Ok(version >= mycelium_core::db::LATEST_SCHEMA_VERSION)
}