godmode-core 0.8.1

Core library for godmode: task graphs, session state, dispatch, and Claude Code plugin integrations.
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
//! Session-owned task transitions, persistence, tracing, and handoff summaries.

use std::path::{Path, PathBuf};

use anyhow::Result;
use chrono::Utc;
use serde::Serialize;

use crate::config::Config;
use crate::graph;
use crate::integrations::{crux, rx};
use crate::model::{GraphSummary, Status, Task, TaskGraph};
use crate::plan::{self, IngestReport};
use crate::templates;

// Public types

pub struct Session {
    root: PathBuf,
    graph: TaskGraph,
    config: Config,
}

#[derive(Debug, Default, Serialize)]
pub struct SessionSummary {
    pub done: usize,
    pub running: usize,
    pub pending: usize,
    pub blocked: usize,
    pub total_duration_ms: u64,
    pub tasks: Vec<TaskTiming>,
}

#[derive(Debug, Serialize)]
pub struct TaskTiming {
    pub id: String,
    pub title: String,
    pub duration_ms: u64,
}

// Session impl

impl Session {
    /// Load (or create) a session rooted at `root`, using default config.
    pub fn open(root: &Path) -> Result<Self> {
        Self::open_with_config(root, &Config::load(root))
    }

    /// Load (or create) a session rooted at `root` with explicit config.
    pub fn open_with_config(root: &Path, config: &Config) -> Result<Self> {
        let graph = graph::load(root)?;
        Ok(Self {
            root: root.to_path_buf(),
            graph,
            config: config.clone(),
        })
    }

    /// Returns the session's current task graph.
    pub fn graph(&self) -> &TaskGraph {
        &self.graph
    }

    /// Escape hatch for direct graph mutation. Prefer typed Session methods
    /// (clear_tasks, apply_template) which maintain auto-save and trace invariants.
    // qual:test_helper
    #[doc(hidden)]
    pub fn graph_mut(&mut self) -> &mut TaskGraph {
        &mut self.graph
    }

    /// Clear tasks from the graph. Returns the count removed.
    /// `done_only = true` removes only completed tasks; `false` removes all.
    pub fn clear_tasks(&mut self, done_only: bool) -> usize {
        let count = graph::clear(&mut self.graph, done_only);
        if count > 0 {
            self.auto_save();
        }
        count
    }

    /// Apply a template into the task graph. Returns `(applied, skipped)`.
    pub fn apply_template(&mut self, template: templates::Template) -> Result<(usize, usize)> {
        let result = templates::apply(&mut self.graph, template)?;
        if result.0 > 0 {
            self.auto_save();
        }
        Ok(result)
    }

    /// Add a task to the graph.
    pub fn add_task(&mut self, task: Task) -> Result<()> {
        graph::add(&mut self.graph, task)
    }

    /// Import parsed plan tasks and persist the complete graph atomically from the caller's view.
    pub fn ingest_plan(&mut self, tasks: Vec<Task>, source: &str) -> Result<IngestReport> {
        let previous = self.graph.clone();
        let report = plan::ingest(&mut self.graph, tasks, source)?;
        if let Err(error) = self.save() {
            self.graph = previous;
            return Err(error);
        }
        Ok(report)
    }

    /// Remove a task from the graph.
    pub fn remove_task(&mut self, id: &str) -> Result<()> {
        graph::remove(&mut self.graph, id)
    }

    /// Start a task: validate rx script if applicable, set started_at, emit trace Step.
    pub fn start_task(&mut self, id: &str) -> Result<()> {
        if self.config.integrations.rx
            && let Some(task) = self.graph.tasks.iter().find(|t| t.id == id)
            && let Some(run) = &task.run
        {
            rx::validate_run(run)?;
        }
        graph::start(&mut self.graph, id)?;
        if let Some(task) = self.graph.tasks.iter_mut().find(|t| t.id == id) {
            task.started_at = Some(Utc::now());
        }
        if self.config.integrations.crux {
            let _ = self.append_step(crux::step_started(id));
        }
        self.auto_save();
        Ok(())
    }

    /// Complete a task: compute duration_ms from started_at, emit trace Step.
    pub fn complete_task(
        &mut self,
        id: &str,
        commit: Option<&str>,
        notes: Option<&str>,
    ) -> Result<()> {
        let duration_ms = self
            .graph
            .tasks
            .iter()
            .find(|t| t.id == id)
            .and_then(|t| t.started_at)
            .map(|start| {
                Utc::now()
                    .signed_duration_since(start)
                    .num_milliseconds()
                    .max(0) as u64
            })
            .unwrap_or(0);

        graph::complete(&mut self.graph, id, commit, notes)?;

        if self.config.integrations.crux {
            let mut step = crux::step_completed(id, commit, notes);
            step.duration_ms = duration_ms;
            if duration_ms < 100 {
                let warn = serde_json::json!({
                    "warn": "suspiciously short duration — was this a real task?"
                });
                step.output = Some(match step.output.take() {
                    Some(serde_json::Value::Object(mut map)) => {
                        map.extend(warn.as_object().unwrap().clone());
                        serde_json::Value::Object(map)
                    }
                    _ => warn,
                });
            }
            let _ = self.append_step(step);
        }
        self.auto_save();
        Ok(())
    }

    /// Block a task with a reason.
    pub fn block_task(&mut self, id: &str, reason: &str) -> Result<()> {
        graph::block(&mut self.graph, id, reason)?;
        if self.config.integrations.crux {
            let _ = self.append_step(crux::step_blocked(id, Some(reason)));
        }
        self.auto_save();
        Ok(())
    }

    /// Unblock a task.
    pub fn unblock_task(&mut self, id: &str) -> Result<()> {
        graph::unblock(&mut self.graph, id)?;
        self.auto_save();
        Ok(())
    }

    /// Unblock all blocked tasks. Returns count unblocked.
    pub fn unblock_all(&mut self) -> usize {
        let count = graph::unblock_all(&mut self.graph);
        if count > 0 {
            self.auto_save();
        }
        count
    }

    /// Aggregate counts and per-task durations.
    pub fn summary(&self) -> SessionSummary {
        let mut s = SessionSummary::default();
        for task in &self.graph.tasks {
            match task.status {
                Status::Done => s.done += 1,
                Status::Running => s.running += 1,
                Status::Pending => s.pending += 1,
                Status::Blocked => s.blocked += 1,
            }
            let end = task.completed_at.unwrap_or_else(Utc::now);
            let duration_ms = task
                .started_at
                .map(|start| end.signed_duration_since(start).num_milliseconds().max(0) as u64)
                .unwrap_or(0);
            s.tasks.push(TaskTiming {
                id: task.id.clone(),
                title: task.title.clone(),
                duration_ms,
            });
            s.total_duration_ms += duration_ms;
        }
        s
    }

    /// Persist the graph to disk. Caller decides when to call.
    pub fn save(&self) -> Result<()> {
        graph::save(&self.root, &self.graph)
    }

    /// Write a summary record to the summary JSONL file. Non-fatal.
    pub fn write_summary_jsonl(&self, summary: &SessionSummary) -> Result<()> {
        let dir = crux::sessions_dir(&self.root);
        let date = chrono::Local::now().format("%Y-%m-%d").to_string();
        append_jsonl(&dir.join(format!("{date}-summary.jsonl")), summary)
    }

    // Private helpers

    /// Best-effort flush of graph state to disk after each transition.
    /// Errors are logged but never abort the caller.
    fn auto_save(&self) {
        if let Err(e) = graph::save(&self.root, &self.graph) {
            eprintln!("godmode: auto-save failed: {e}");
        }
    }

    fn append_step(&self, step: crux_runtime::types::step::Step) -> Result<()> {
        let dir = crux::sessions_dir(&self.root);
        let date = chrono::Local::now().format("%Y-%m-%d").to_string();
        append_jsonl(&dir.join(format!("{date}.jsonl")), &step)
    }
}

// Module-level helpers

/// Append a JSON-serialised value as a single line to a JSONL file.
fn append_jsonl(path: &std::path::Path, value: &impl serde::Serialize) -> Result<()> {
    use std::io::Write;
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let mut f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)?;
    writeln!(f, "{}", serde_json::to_string(value)?)?;
    Ok(())
}

// Backward-compat free functions (thin wrappers)

/// Print a triage summary to stdout. Called at session start.
pub fn handon(root: &Path) -> Result<()> {
    let s = Session::open(root)?;
    let graph = s.graph();
    if graph.tasks.is_empty() {
        println!("No tasks. Run `godmode plan ingest <plan>` or `godmode task add`.");
        return Ok(());
    }
    let summary = s.summary();
    println!(
        "Tasks: {} done, {} running, {} pending, {} blocked",
        summary.done, summary.running, summary.pending, summary.blocked
    );
    let running: Vec<_> = graph
        .tasks
        .iter()
        .filter(|t| t.status == Status::Running)
        .collect();
    if !running.is_empty() {
        println!("\nIn progress:");
        for t in &running {
            println!("  [{}] {}", t.id, t.title);
        }
    }
    let next = graph::runnable(graph);
    if !next.is_empty() {
        println!("\nNext runnable:");
        for t in &next {
            let tag = t
                .crate_name
                .as_deref()
                .map(|c| format!(" ({})", c))
                .unwrap_or_default();
            let stale_hint = if t.started_at.is_none() {
                " [never started]"
            } else {
                ""
            };
            println!("  [{}] {}{}{}", t.id, t.title, tag, stale_hint);
        }
    }
    let blocked: Vec<_> = graph
        .tasks
        .iter()
        .filter(|t| t.status == Status::Blocked)
        .collect();
    if !blocked.is_empty() {
        println!("\nBlocked:");
        for t in &blocked {
            println!("  [{}] {} — {}", t.id, t.title, t.notes);
        }
    }

    Ok(())
}

/// Validate session end state and emit summary.
pub fn handoff(root: &Path) -> Result<GraphSummary> {
    let s = Session::open(root)?;
    let graph = s.graph();
    let running: Vec<_> = graph
        .tasks
        .iter()
        .filter(|t| t.status == Status::Running)
        .collect();
    if !running.is_empty() {
        eprintln!("Warning: {} task(s) still running:", running.len());
        for t in &running {
            eprintln!("  [{}] {}", t.id, t.title);
        }
        eprintln!("Mark them done or blocked before closing.");
    }
    let session_summary = s.summary();
    println!(
        "\nSession: {} done, {} blocked, total {}ms",
        session_summary.done, session_summary.blocked, session_summary.total_duration_ms
    );
    let _ = s.write_summary_jsonl(&session_summary);
    Ok(graph.summary())
}

// Session file pruning

/// Delete session JSONL files in `dir` that are older than `days` days.
/// If `dry_run` is true, prints what would be deleted but makes no changes.
/// Returns the list of paths that were (or would be) deleted.
pub fn prune_sessions_older_than(dir: &Path, days: u64, dry_run: bool) -> Result<Vec<PathBuf>> {
    use std::time::{Duration, SystemTime};

    let cutoff = SystemTime::now()
        .checked_sub(Duration::from_secs(days * 24 * 3600))
        .unwrap_or(SystemTime::UNIX_EPOCH);

    let mut pruned = Vec::new();

    if !dir.exists() {
        return Ok(pruned);
    }

    for entry in std::fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
            continue;
        }
        let meta = std::fs::metadata(&path)?;
        let modified = meta.modified()?;
        if modified < cutoff {
            if dry_run {
                println!("would delete: {}", path.display());
            } else {
                std::fs::remove_file(&path)?;
            }
            pruned.push(path);
        }
    }

    Ok(pruned)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph;
    use crate::model::Task;
    use tempfile::TempDir;

    #[test]
    fn handon_empty_graph_prints_message() {
        let dir = TempDir::new().unwrap();
        handon(dir.path()).unwrap();
    }

    #[test]
    fn handoff_warns_on_running_tasks() {
        let dir = TempDir::new().unwrap();
        let mut g = crate::model::TaskGraph::default();
        let mut t = Task::new("t1", "Unfinished");
        t.status = Status::Running;
        g.tasks.push(t);
        graph::save(dir.path(), &g).unwrap();
        let summary = handoff(dir.path()).unwrap();
        assert_eq!(summary.running, 1);
    }

    #[test]
    fn session_open_returns_empty_for_missing_file() {
        let dir = TempDir::new().unwrap();
        let s = Session::open(dir.path()).unwrap();
        assert!(s.graph().tasks.is_empty());
    }

    #[test]
    fn session_start_sets_started_at() {
        let dir = TempDir::new().unwrap();
        let mut s = Session::open(dir.path()).unwrap();
        s.add_task(Task::new("t1", "A")).unwrap();
        s.start_task("t1").unwrap();
        let task = s.graph().tasks.iter().find(|t| t.id == "t1").unwrap();
        assert!(task.started_at.is_some());
        assert_eq!(task.status, Status::Running);
    }

    #[test]
    fn session_complete_computes_duration() {
        let dir = TempDir::new().unwrap();
        let mut s = Session::open(dir.path()).unwrap();
        s.add_task(Task::new("t1", "A")).unwrap();
        s.start_task("t1").unwrap();
        s.complete_task("t1", None, None).unwrap();
        let task = s.graph().tasks.iter().find(|t| t.id == "t1").unwrap();
        assert_eq!(task.status, Status::Done);
        let summary = s.summary();
        assert_eq!(summary.done, 1);
        assert_eq!(summary.tasks.len(), 1);
        let _ = summary.tasks[0].duration_ms;
    }

    #[test]
    fn session_save_and_reload() {
        let dir = TempDir::new().unwrap();
        let mut s = Session::open(dir.path()).unwrap();
        s.add_task(Task::new("t1", "A")).unwrap();
        s.save().unwrap();
        let s2 = Session::open(dir.path()).unwrap();
        assert_eq!(s2.graph().tasks.len(), 1);
    }

    #[test]
    fn prune_deletes_old_files_keeps_new() {
        use std::time::{Duration, SystemTime};
        let dir = TempDir::new().unwrap();
        let sessions = dir.path().join("sessions");
        std::fs::create_dir_all(&sessions).unwrap();

        // Write an "old" file and backdate its mtime to 10 days ago.
        let old_file = sessions.join("2020-01-01.jsonl");
        std::fs::write(&old_file, b"old").unwrap();
        let old_time = SystemTime::now()
            .checked_sub(Duration::from_secs(10 * 24 * 3600))
            .unwrap();
        filetime::set_file_mtime(&old_file, filetime::FileTime::from_system_time(old_time))
            .unwrap();

        // Write a "new" file (mtime = now).
        let new_file = sessions.join("2099-01-01.jsonl");
        std::fs::write(&new_file, b"new").unwrap();

        let pruned = prune_sessions_older_than(&sessions, 7, false).unwrap();
        assert_eq!(pruned.len(), 1);
        assert_eq!(pruned[0], old_file);
        assert!(!old_file.exists());
        assert!(new_file.exists());
    }

    #[test]
    fn prune_dry_run_makes_no_changes() {
        use std::time::{Duration, SystemTime};
        let dir = TempDir::new().unwrap();
        let sessions = dir.path().join("sessions");
        std::fs::create_dir_all(&sessions).unwrap();

        let old_file = sessions.join("2020-01-01.jsonl");
        std::fs::write(&old_file, b"old").unwrap();
        let old_time = SystemTime::now()
            .checked_sub(Duration::from_secs(10 * 24 * 3600))
            .unwrap();
        filetime::set_file_mtime(&old_file, filetime::FileTime::from_system_time(old_time))
            .unwrap();

        let pruned = prune_sessions_older_than(&sessions, 7, true).unwrap();
        assert_eq!(pruned.len(), 1);
        // File must still exist after dry-run.
        assert!(old_file.exists());
    }

    #[test]
    fn prune_missing_dir_returns_empty() {
        let dir = TempDir::new().unwrap();
        let sessions = dir.path().join("no-such-dir");
        let pruned = prune_sessions_older_than(&sessions, 7, false).unwrap();
        assert!(pruned.is_empty());
    }

    #[test]
    fn completed_at_set_on_task_done() {
        let dir = TempDir::new().unwrap();
        let mut s = Session::open(dir.path()).unwrap();
        s.add_task(Task::new("t1", "A")).unwrap();
        assert!(
            s.graph().tasks[0].completed_at.is_none(),
            "completed_at should be None before completion"
        );
        s.start_task("t1").unwrap();
        s.complete_task("t1", None, None).unwrap();
        let task = s.graph().tasks.iter().find(|t| t.id == "t1").unwrap();
        assert!(
            task.completed_at.is_some(),
            "completed_at should be set after completion"
        );
    }

    #[test]
    fn summary_uses_completed_at_for_done_tasks() {
        use chrono::Duration;

        let dir = TempDir::new().unwrap();
        let mut s = Session::open(dir.path()).unwrap();
        let mut task = Task::new("t1", "A");
        // Simulate: started 10 seconds ago, completed 5 seconds ago.
        let now = Utc::now();
        task.status = Status::Done;
        task.started_at = Some(now - Duration::seconds(10));
        task.completed_at = Some(now - Duration::seconds(5));
        s.graph_mut().tasks.push(task);

        let summary = s.summary();
        let timing = &summary.tasks[0];
        // Duration should be ~5000ms (completed_at - started_at), NOT ~10000ms (now - started_at).
        assert!(
            timing.duration_ms < 7000,
            "duration_ms should use completed_at, got {}",
            timing.duration_ms
        );
        assert!(
            timing.duration_ms >= 4000,
            "duration_ms too small: {}",
            timing.duration_ms
        );
    }

    #[test]
    fn start_task_auto_flushes_to_disk() {
        let dir = TempDir::new().unwrap();
        let mut s = Session::open(dir.path()).unwrap();
        s.add_task(Task::new("t1", "A")).unwrap();
        s.start_task("t1").unwrap();
        // No explicit save() — reload from disk and verify state was flushed.
        let reloaded = graph::load(dir.path()).unwrap();
        let task = reloaded.tasks.iter().find(|t| t.id == "t1").unwrap();
        assert_eq!(task.status, Status::Running);
    }

    #[test]
    fn complete_task_auto_flushes_to_disk() {
        let dir = TempDir::new().unwrap();
        let mut s = Session::open(dir.path()).unwrap();
        s.add_task(Task::new("t1", "A")).unwrap();
        s.start_task("t1").unwrap();
        s.complete_task("t1", None, None).unwrap();
        let reloaded = graph::load(dir.path()).unwrap();
        let task = reloaded.tasks.iter().find(|t| t.id == "t1").unwrap();
        assert_eq!(task.status, Status::Done);
    }

    #[test]
    fn block_task_auto_flushes_to_disk() {
        let dir = TempDir::new().unwrap();
        let mut s = Session::open(dir.path()).unwrap();
        s.add_task(Task::new("t1", "A")).unwrap();
        s.start_task("t1").unwrap();
        s.block_task("t1", "stuck").unwrap();
        let reloaded = graph::load(dir.path()).unwrap();
        let task = reloaded.tasks.iter().find(|t| t.id == "t1").unwrap();
        assert_eq!(task.status, Status::Blocked);
    }

    #[test]
    fn unblock_task_auto_flushes_to_disk() {
        let dir = TempDir::new().unwrap();
        let mut s = Session::open(dir.path()).unwrap();
        s.add_task(Task::new("t1", "A")).unwrap();
        s.start_task("t1").unwrap();
        s.block_task("t1", "stuck").unwrap();
        s.unblock_task("t1").unwrap();
        let reloaded = graph::load(dir.path()).unwrap();
        let task = reloaded.tasks.iter().find(|t| t.id == "t1").unwrap();
        assert_eq!(task.status, Status::Pending);
    }

    #[test]
    fn session_summary_counts_correctly() {
        let dir = TempDir::new().unwrap();
        let mut s = Session::open(dir.path()).unwrap();
        s.add_task(Task::new("t1", "A")).unwrap();
        s.add_task(Task::new("t2", "B")).unwrap();
        s.start_task("t1").unwrap();
        let sum = s.summary();
        assert_eq!(sum.pending, 1);
        assert_eq!(sum.running, 1);
        assert_eq!(sum.done, 0);
    }

    // --- Config gating tests (fix #1: Session respects config) ---

    #[test]
    fn start_task_skips_rx_validation_when_disabled() {
        let dir = TempDir::new().unwrap();
        let mut cfg = crate::config::Config::default();
        cfg.integrations.rx = false;
        let mut s = Session::open_with_config(dir.path(), &cfg).unwrap();
        let mut task = Task::new("t1", "A");
        task.run = Some("rx:nonexistent-script".into());
        s.add_task(task).unwrap();
        // Should succeed — rx validation skipped when disabled
        assert!(s.start_task("t1").is_ok());
    }

    #[test]
    fn start_task_skips_crux_trace_when_disabled() {
        let dir = TempDir::new().unwrap();
        let mut cfg = crate::config::Config::default();
        cfg.integrations.crux = false;
        let mut s = Session::open_with_config(dir.path(), &cfg).unwrap();
        s.add_task(Task::new("t1", "A")).unwrap();
        s.start_task("t1").unwrap();
        // No session JSONL should exist when crux is disabled
        let sessions_dir = dir.path().join(".ctx").join("godmode").join("sessions");
        assert!(
            !sessions_dir.exists() || std::fs::read_dir(&sessions_dir).unwrap().count() == 0,
            "no trace files should be written when crux is disabled"
        );
    }

    // --- Session::clear_tasks test (fix #3) ---

    #[test]
    fn clear_tasks_auto_saves() {
        let dir = TempDir::new().unwrap();
        let mut s = Session::open(dir.path()).unwrap();
        s.add_task(Task::new("t1", "A")).unwrap();
        s.start_task("t1").unwrap();
        s.complete_task("t1", None, None).unwrap();
        let count = s.clear_tasks(true);
        assert_eq!(count, 1);
        let reloaded = graph::load(dir.path()).unwrap();
        assert!(reloaded.tasks.is_empty(), "clear_tasks should auto-save");
    }

    #[test]
    fn clear_tasks_done_only_keeps_pending() {
        let dir = TempDir::new().unwrap();
        let mut s = Session::open(dir.path()).unwrap();
        s.add_task(Task::new("t1", "A")).unwrap();
        s.add_task(Task::new("t2", "B")).unwrap();
        s.start_task("t1").unwrap();
        s.complete_task("t1", None, None).unwrap();
        let count = s.clear_tasks(true);
        assert_eq!(count, 1);
        assert_eq!(s.graph().tasks.len(), 1);
        assert_eq!(s.graph().tasks[0].id, "t2");
    }
}