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
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
//! Task-graph persistence, dependency resolution, and state transitions.

use anyhow::{Context, Result, bail};
use chrono::Local;
use std::path::{Path, PathBuf};

use crate::cache;
use crate::model::{Status, Task, TaskGraph};

/// Resolve the task file path relative to a repo root.
///
/// Prefers `.ctx/godmode/tasks.yaml` (new layout). Falls back to the legacy
/// `.ctx/GODMODE.tasks.yaml` if it exists and the new path does not. Fresh
/// projects always get the new path.
pub fn task_file(root: &Path) -> PathBuf {
    let new = root.join(".ctx").join("godmode").join("tasks.yaml");
    if new.exists() {
        return new;
    }
    let legacy = root.join(".ctx").join("GODMODE.tasks.yaml");
    if legacy.exists() {
        return legacy;
    }
    new
}

/// Load the task graph from disk. Returns an empty graph if the file does not exist.
pub fn load(root: &Path) -> Result<TaskGraph> {
    let path = task_file(root);
    if !path.exists() {
        return Ok(TaskGraph::default());
    }
    let raw =
        std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
    serde_yaml::from_str(&raw).with_context(|| format!("parsing {}", path.display()))
}

/// Persist the task graph to disk, creating `.ctx/godmode/` if needed.
pub fn save(root: &Path, graph: &TaskGraph) -> Result<()> {
    let path = task_file(root);
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let raw = serde_yaml::to_string(graph)?;
    std::fs::write(&path, raw).with_context(|| format!("writing {}", path.display()))?;

    // Best-effort: update starship status cache
    let project = root
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("unknown");
    let _ = cache::write_status_cache(graph, project);

    Ok(())
}

/// Return all tasks whose dependencies are all `Done` and whose own status is `Pending`.
/// Uses the cached `done_ids` set on `TaskGraph` to avoid rebuilding on every call.
pub fn runnable(graph: &TaskGraph) -> Vec<&Task> {
    let done_ids = graph.done_ids();

    graph
        .tasks
        .iter()
        .filter(|t| {
            t.status == Status::Pending
                && t.depends_on
                    .iter()
                    .all(|dep| done_ids.contains(dep.as_str()))
        })
        .collect()
}

/// Mark a task as running. Errors if the task is not pending or has unmet deps.
pub fn start(graph: &mut TaskGraph, id: &str) -> Result<()> {
    // Check deps against cached done_ids before mutating.
    let unmet: Vec<String> = {
        let done_ids = graph.done_ids();
        let task = graph
            .tasks
            .iter()
            .find(|t| t.id == id)
            .with_context(|| task_not_found(id))?;
        if task.status != Status::Pending {
            bail!(
                "task '{}' is {} — can only start pending tasks",
                id,
                task.status
            );
        }
        task.depends_on
            .iter()
            .filter(|dep| !done_ids.contains(dep.as_str()))
            .cloned()
            .collect()
    };
    if !unmet.is_empty() {
        bail!(
            "task '{}' has unmet dependencies: {}",
            id,
            unmet
                .iter()
                .map(|s| s.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        );
    }

    {
        let task = graph
            .tasks
            .iter_mut()
            .find(|t| t.id == id)
            .with_context(|| format!("task '{id}' not found"))?;
        task.status = Status::Running;
    }
    graph.invalidate_done_cache();
    Ok(())
}

fn task_not_found(id: &str) -> String {
    format!("task '{id}' not found")
}

/// Mark a running task as done, recording an optional commit SHA.
pub fn complete(
    graph: &mut TaskGraph,
    id: &str,
    commit: Option<&str>,
    notes: Option<&str>,
) -> Result<()> {
    {
        let task = graph
            .tasks
            .iter_mut()
            .find(|t| t.id == id)
            .with_context(|| format!("task '{id}' not found"))?;

        if task.status != Status::Running {
            bail!(
                "task '{}' is {} — can only complete running tasks",
                id,
                task.status
            );
        }
        task.status = Status::Done;
        task.completed = Some(Local::now().date_naive());
        task.completed_at = Some(chrono::Utc::now());
        if let Some(sha) = commit {
            task.commit = Some(sha.to_string());
        }
        if let Some(n) = notes
            && !n.is_empty()
        {
            task.notes = n.to_string();
        }
    }
    graph.invalidate_done_cache();
    Ok(())
}

/// Mark a task as blocked with a reason.
pub fn block(graph: &mut TaskGraph, id: &str, reason: &str) -> Result<()> {
    {
        let task = graph
            .tasks
            .iter_mut()
            .find(|t| t.id == id)
            .with_context(|| format!("task '{id}' not found"))?;
        task.status = Status::Blocked;
        task.notes = reason.to_string();
    }
    graph.invalidate_done_cache();
    Ok(())
}

/// Reset a blocked task back to pending.
pub fn unblock(graph: &mut TaskGraph, id: &str) -> Result<()> {
    {
        let task = graph
            .tasks
            .iter_mut()
            .find(|t| t.id == id)
            .with_context(|| format!("task '{id}' not found"))?;
        if task.status != Status::Blocked {
            bail!(
                "task '{}' is {} — can only unblock blocked tasks",
                id,
                task.status
            );
        }
        task.status = Status::Pending;
        task.notes = String::new();
    }
    graph.invalidate_done_cache();
    Ok(())
}

/// Reset all blocked tasks to pending, clearing their notes.
/// Returns the count of tasks unblocked.
pub fn unblock_all(graph: &mut TaskGraph) -> usize {
    let mut count = 0;
    for task in &mut graph.tasks {
        if task.status == Status::Blocked {
            task.status = Status::Pending;
            task.notes = String::new();
            count += 1;
        }
    }
    if count > 0 {
        graph.invalidate_done_cache();
    }
    count
}

/// Returns `Some(cycle_path)` if adding a task with the given id and deps would
/// create a cycle in the existing graph. `None` means the addition is safe.
///
/// Uses a visited set with parent pointers to avoid O(n^2) path cloning.
/// The cycle path is reconstructed from parent pointers only on detection.
fn would_create_cycle(graph: &TaskGraph, new_id: &str, deps: &[String]) -> Option<String> {
    use std::collections::{HashMap, HashSet};

    let mut adj: HashMap<&str, Vec<&str>> = HashMap::new();
    for t in &graph.tasks {
        adj.insert(
            t.id.as_str(),
            t.depends_on.iter().map(|s| s.as_str()).collect(),
        );
    }
    adj.insert(new_id, deps.iter().map(|s| s.as_str()).collect());

    // DFS from each dep of new_id. Track parent pointers to reconstruct cycle on detection.
    for dep in deps {
        let dep = dep.as_str();
        let mut visited: HashSet<&str> = HashSet::new();
        let mut parent: HashMap<&str, &str> = HashMap::new();
        visited.insert(new_id);
        visited.insert(dep);
        parent.insert(dep, new_id);

        let mut stack = vec![dep];
        while let Some(current) = stack.pop() {
            if current == new_id {
                // Reconstruct cycle path from parent pointers.
                let mut path = vec![];
                let mut trace = current;
                while let Some(&p) = parent.get(trace) {
                    path.push(trace);
                    if p == new_id {
                        path.push(new_id);
                        break;
                    }
                    trace = p;
                }
                path.reverse();
                return Some(path.join(" \u{2192} "));
            }
            if let Some(next_deps) = adj.get(current) {
                for &next in next_deps {
                    if next == new_id {
                        // Found cycle — reconstruct path.
                        let mut path = vec![new_id];
                        let mut trace = current;
                        while let Some(&p) = parent.get(trace) {
                            path.push(trace);
                            if p == new_id {
                                break;
                            }
                            trace = p;
                        }
                        path.push(new_id);
                        path.reverse();
                        // Path is currently reversed from trace; fix order.
                        // new_id -> dep -> ... -> current -> new_id
                        return Some(path.join(" \u{2192} "));
                    }
                    if visited.insert(next) {
                        parent.insert(next, current);
                        stack.push(next);
                    }
                }
            }
        }
    }
    None
}

/// Return the first unused task ID of the form "t1", "t2", …
pub fn next_task_id(g: &TaskGraph) -> Result<String> {
    let used: std::collections::HashSet<&str> = g.tasks.iter().map(|t| t.id.as_str()).collect();
    for n in 1u64.. {
        let candidate = format!("t{}", n);
        if !used.contains(candidate.as_str()) && !g.is_imported_plan_task(&candidate) {
            return Ok(candidate);
        }
    }
    bail!("exhausted u64 task ID space")
}

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

pub(crate) fn add_imported(graph: &mut TaskGraph, task: Task) -> Result<()> {
    add_inner(graph, task, true)
}

fn add_inner(graph: &mut TaskGraph, task: Task, allow_reserved: bool) -> Result<()> {
    if graph.tasks.iter().any(|t| t.id == task.id) {
        bail!("task '{}' already exists", task.id);
    }
    if !allow_reserved && graph.is_imported_plan_task(&task.id) {
        bail!("task '{}' is reserved by an imported plan", task.id);
    }
    if let Some(cycle_path) = would_create_cycle(graph, &task.id, &task.depends_on) {
        bail!("cycle detected: {}", cycle_path);
    }
    graph.tasks.push(task);
    graph.invalidate_done_cache();
    Ok(())
}

/// Remove a task by id, cleaning up any `depends_on` references to it in remaining tasks.
pub fn remove(graph: &mut TaskGraph, id: &str) -> Result<()> {
    let before = graph.tasks.len();
    graph.tasks.retain(|t| t.id != id);
    if graph.tasks.len() == before {
        bail!("task '{id}' not found");
    }
    for task in &mut graph.tasks {
        task.depends_on.retain(|dep| dep != id);
    }
    graph.invalidate_done_cache();
    Ok(())
}

/// Remove tasks from the graph. Returns the count removed.
///
/// - `done_only = true`: remove only tasks with `status: done`
/// - `done_only = false`: remove all tasks
pub fn clear(graph: &mut TaskGraph, done_only: bool) -> usize {
    let before = graph.tasks.len();
    if done_only {
        graph.tasks.retain(|t| t.status != Status::Done);
    } else {
        graph.tasks.clear();
        graph.clear_plan_imports();
    }
    let removed = before - graph.tasks.len();
    if removed > 0 {
        graph.invalidate_done_cache();
    }
    removed
}

/// Convert the task graph to a `petgraph` directed graph.
/// Each node is a task ID string; edges represent dependencies (dep → dependent).
pub fn to_petgraph(graph: &TaskGraph) -> petgraph::stable_graph::StableDiGraph<String, ()> {
    use petgraph::stable_graph::StableDiGraph;
    use std::collections::HashMap;

    let mut pg: StableDiGraph<String, ()> = StableDiGraph::new();
    let mut idx: HashMap<&str, petgraph::stable_graph::NodeIndex> = HashMap::new();

    for task in &graph.tasks {
        let node = pg.add_node(task.id.clone());
        idx.insert(task.id.as_str(), node);
    }

    for task in &graph.tasks {
        for dep in &task.depends_on {
            if let (Some(&from), Some(&to)) = (idx.get(dep.as_str()), idx.get(task.id.as_str())) {
                pg.add_edge(from, to, ());
            }
        }
    }

    pg
}

/// Render the task graph as a DOT-format string.
pub fn to_dot(graph: &TaskGraph) -> String {
    use petgraph::dot::{Config, Dot};
    let pg = to_petgraph(graph);
    format!("{:?}", Dot::with_config(&pg, &[Config::EdgeNoLabel]))
}

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

    fn graph_with_chain() -> TaskGraph {
        let mut g = TaskGraph::default();
        g.tasks.push(Task::new("t1", "First"));
        let mut t2 = Task::new("t2", "Second");
        t2.depends_on = vec!["t1".into()];
        g.tasks.push(t2);
        g
    }

    #[test]
    fn task_file_uses_godmode_subdir() {
        let root = Path::new("/tmp/test-root");
        let path = task_file(root);
        assert_eq!(path, root.join(".ctx/godmode/tasks.yaml"));
    }

    #[test]
    fn task_file_falls_back_to_legacy() {
        let dir = tempfile::tempdir().unwrap();
        let legacy = dir.path().join(".ctx");
        std::fs::create_dir_all(&legacy).unwrap();
        std::fs::write(legacy.join("GODMODE.tasks.yaml"), "tasks: []\n").unwrap();
        let path = task_file(dir.path());
        assert_eq!(path, dir.path().join(".ctx/GODMODE.tasks.yaml"));
    }

    #[test]
    fn task_file_prefers_new_over_legacy() {
        let dir = tempfile::tempdir().unwrap();
        let legacy = dir.path().join(".ctx");
        std::fs::create_dir_all(&legacy).unwrap();
        std::fs::write(legacy.join("GODMODE.tasks.yaml"), "tasks: []\n").unwrap();
        let new_dir = dir.path().join(".ctx").join("godmode");
        std::fs::create_dir_all(&new_dir).unwrap();
        std::fs::write(new_dir.join("tasks.yaml"), "tasks: []\n").unwrap();
        let path = task_file(dir.path());
        assert_eq!(path, dir.path().join(".ctx/godmode/tasks.yaml"));
    }

    #[test]
    fn runnable_returns_tasks_with_no_deps() {
        let g = graph_with_chain();
        let r = runnable(&g);
        assert_eq!(r.len(), 1);
        assert_eq!(r[0].id, "t1");
    }

    #[test]
    fn runnable_unlocks_after_dep_done() {
        let mut g = graph_with_chain();
        start(&mut g, "t1").unwrap();
        complete(&mut g, "t1", None, None).unwrap();
        let r = runnable(&g);
        assert_eq!(r.len(), 1);
        assert_eq!(r[0].id, "t2");
    }

    #[test]
    fn start_fails_on_unmet_deps() {
        let mut g = graph_with_chain();
        let err = start(&mut g, "t2").unwrap_err();
        assert!(err.to_string().contains("unmet dependencies"));
    }

    #[test]
    fn complete_requires_running_status() {
        let mut g = graph_with_chain();
        let err = complete(&mut g, "t1", None, None).unwrap_err();
        assert!(err.to_string().contains("pending"));
    }

    #[test]
    fn block_sets_status_and_notes() {
        let mut g = graph_with_chain();
        start(&mut g, "t1").unwrap();
        // override to running for block test
        g.tasks[0].status = Status::Running;
        block(&mut g, "t1", "three attempts failed").unwrap();
        assert_eq!(g.tasks[0].status, Status::Blocked);
        assert_eq!(g.tasks[0].notes, "three attempts failed");
    }

    #[test]
    fn add_and_remove_task() {
        let mut g = TaskGraph::default();
        add(&mut g, Task::new("t1", "A")).unwrap();
        assert_eq!(g.tasks.len(), 1);
        remove(&mut g, "t1").unwrap();
        assert!(g.tasks.is_empty());
    }

    #[test]
    fn add_duplicate_fails() {
        let mut g = TaskGraph::default();
        add(&mut g, Task::new("t1", "A")).unwrap();
        let err = add(&mut g, Task::new("t1", "B")).unwrap_err();
        assert!(err.to_string().contains("already exists"));
    }

    #[test]
    fn clear_done_only_removes_done_tasks() {
        let mut g = TaskGraph::default();
        let mut t1 = Task::new("t1", "A");
        t1.status = Status::Done;
        g.tasks.push(t1);
        g.tasks.push(Task::new("t2", "B")); // pending
        let removed = clear(&mut g, true);
        assert_eq!(removed, 1);
        assert_eq!(g.tasks.len(), 1);
        assert_eq!(g.tasks[0].id, "t2");
    }

    #[test]
    fn unblock_all_resets_blocked_tasks() {
        let mut g = TaskGraph::default();
        let mut t1 = Task::new("t1", "A");
        t1.status = Status::Blocked;
        t1.notes = "reason".into();
        let mut t2 = Task::new("t2", "B");
        t2.status = Status::Done;
        g.tasks.push(t1);
        g.tasks.push(t2);
        let count = unblock_all(&mut g);
        assert_eq!(count, 1);
        assert_eq!(g.tasks[0].status, Status::Pending);
        assert!(g.tasks[0].notes.is_empty());
        assert_eq!(g.tasks[1].status, Status::Done); // unchanged
    }

    #[test]
    fn clear_all_removes_everything() {
        let mut g = TaskGraph::default();
        g.tasks.push(Task::new("t1", "A"));
        g.tasks.push(Task::new("t2", "B"));
        let removed = clear(&mut g, false);
        assert_eq!(removed, 2);
        assert!(g.tasks.is_empty());
    }

    #[test]
    fn add_rejects_self_cycle() {
        let mut g = TaskGraph::default();
        let mut t = Task::new("t1", "A");
        t.depends_on = vec!["t1".into()];
        let err = add(&mut g, t).unwrap_err();
        assert!(err.to_string().contains("cycle"));
    }

    #[test]
    fn add_rejects_transitive_cycle() {
        let mut g3 = TaskGraph::default();
        let mut existing_b = Task::new("b", "B");
        existing_b.depends_on = vec!["a".into()];
        add(&mut g3, existing_b).unwrap();
        // Now add 'a' with dep on 'b' — this creates a→b→a cycle
        let mut new_a = Task::new("a", "A");
        new_a.depends_on = vec!["b".into()];
        let err = add(&mut g3, new_a).unwrap_err();
        assert!(
            err.to_string().contains("cycle"),
            "expected cycle error, got: {err}"
        );
    }

    #[test]
    fn next_task_id_returns_first_unused() {
        let mut g = TaskGraph::default();
        assert_eq!(next_task_id(&g).unwrap(), "t1");
        add(&mut g, Task::new("t1", "A")).unwrap();
        assert_eq!(next_task_id(&g).unwrap(), "t2");
        add(&mut g, Task::new("t3", "C")).unwrap(); // gap at t2
        assert_eq!(next_task_id(&g).unwrap(), "t2");
    }

    #[test]
    fn imported_plan_ids_remain_reserved_after_task_removal() {
        let mut graph = TaskGraph::default();
        graph.record_plan_import("/repo/plan.md".into(), vec!["t1".into()]);

        assert_eq!(next_task_id(&graph).unwrap(), "t2");
        let error = add(&mut graph, Task::new("t1", "Manual task")).unwrap_err();
        assert!(error.to_string().contains("reserved"));
    }

    #[test]
    fn remove_cleans_up_depends_on_refs() {
        let mut g = TaskGraph::default();
        add(&mut g, Task::new("a", "Task A")).unwrap();
        let mut b = Task::new("b", "Task B");
        b.depends_on = vec!["a".into()];
        add(&mut g, b).unwrap();

        remove(&mut g, "a").unwrap();

        let task_b = g.tasks.iter().find(|t| t.id == "b").unwrap();
        assert!(
            task_b.depends_on.is_empty(),
            "depends_on should be empty after removing dep"
        );
        let r = runnable(&g);
        assert_eq!(r.len(), 1);
        assert_eq!(r[0].id, "b", "b should now be runnable");
    }

    #[test]
    fn to_petgraph_node_and_edge_counts() {
        let g = graph_with_chain();
        let pg = to_petgraph(&g);
        assert_eq!(pg.node_count(), 2, "expected 2 nodes");
        assert_eq!(pg.edge_count(), 1, "expected 1 edge (t1→t2)");
    }

    #[test]
    fn to_dot_contains_task_ids() {
        let g = graph_with_chain();
        let dot = to_dot(&g);
        assert!(dot.contains("t1"), "DOT missing t1: {dot}");
        assert!(dot.contains("t2"), "DOT missing t2: {dot}");
        // Should have a directed edge indicator
        assert!(dot.contains("->"), "DOT missing edge: {dot}");
    }

    #[test]
    fn add_valid_dag_no_false_positive() {
        let mut g = TaskGraph::default();
        add(&mut g, Task::new("t1", "A")).unwrap();
        let mut t2 = Task::new("t2", "B");
        t2.depends_on = vec!["t1".into()];
        add(&mut g, t2).unwrap();
        let mut t3 = Task::new("t3", "C");
        t3.depends_on = vec!["t1".into()];
        add(&mut g, t3).unwrap(); // diamond — valid DAG
        assert_eq!(g.tasks.len(), 3);
    }

    #[test]
    fn done_cache_invalidated_on_state_transitions() {
        let mut g = graph_with_chain();

        // Initially t1 is runnable (no deps), t2 is not (depends on t1).
        let r = runnable(&g);
        assert_eq!(r.len(), 1);
        assert_eq!(r[0].id, "t1");

        // After starting and completing t1, the cache must be invalidated
        // so that runnable() sees t1 as done and unlocks t2.
        start(&mut g, "t1").unwrap();
        complete(&mut g, "t1", None, None).unwrap();

        // If the cache were stale, t2 would still appear blocked.
        let r = runnable(&g);
        assert_eq!(r.len(), 1, "t2 should be runnable after t1 is done");
        assert_eq!(r[0].id, "t2");

        // Adding a new task also invalidates.
        let mut t3 = Task::new("t3", "Third");
        t3.depends_on = vec!["t1".into()];
        add(&mut g, t3).unwrap();
        let r = runnable(&g);
        assert_eq!(r.len(), 2, "both t2 and t3 should be runnable");

        // Removing a done task invalidates.
        remove(&mut g, "t1").unwrap();
        let r = runnable(&g);
        assert_eq!(r.len(), 2, "t2 and t3 still runnable (deps cleaned up)");
    }

    #[test]
    fn would_create_cycle_deep_chain() {
        // Build a chain: t1 <- t2 <- t3 <- t4 <- t5
        let mut g = TaskGraph::default();
        add(&mut g, Task::new("t1", "A")).unwrap();
        for i in 2..=5 {
            let mut t = Task::new(format!("t{i}"), format!("Task {i}"));
            t.depends_on = vec![format!("t{}", i - 1)];
            add(&mut g, t).unwrap();
        }
        assert_eq!(g.tasks.len(), 5);

        // Adding t0 that depends on t5 is fine (no cycle).
        let mut t0 = Task::new("t0", "Root");
        t0.depends_on = vec!["t5".into()];
        add(&mut g, t0).unwrap();

        // Adding t6 that depends on t5, where t1 depends on t6 would create a cycle.
        // But t1 has no deps on t6, so this is fine.
        let mut t6 = Task::new("t6", "Leaf");
        t6.depends_on = vec!["t5".into()];
        add(&mut g, t6).unwrap();

        // Now try to create an actual cycle: add "tx" with dep on t3,
        // and make t1 depend on tx (which would create t1->tx->...->t3->t2->t1).
        // We can't modify t1's deps after add, so instead:
        // try adding "cycle" with dep on t1, where t5 already depends on t4->t3->t2->t1.
        // Then add a task that would close the loop.
        let mut bad = Task::new("bad", "Cycle maker");
        bad.depends_on = vec!["t5".into()];
        // This is valid (no cycle back to bad).
        add(&mut g, bad).unwrap();

        // Self-cycle still detected.
        let mut self_ref = Task::new("self", "Self");
        self_ref.depends_on = vec!["self".into()];
        let err = add(&mut g, self_ref).unwrap_err();
        assert!(err.to_string().contains("cycle"), "got: {err}");
    }
}