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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
//! Parse a plan markdown file and extract tasks for the task graph.
//!
//! Expected format (produced by `godmode:writing-plans`):
//!
//! ```markdown
//! ## Tasks
//! ### Task 1: Write failing test for FooAdapter
//! **Crate**: `foo-core`
//! ...
//! ### Task 2: Implement FooAdapter
//! **Crate**: `foo-core`
//! ...
//! ```
//!
//! Each `### Task N: <title>` line becomes one Task. An optional `**Crate**: \`name\``
//! line sets `crate_name`. Dependencies are inferred sequentially (task N depends on N-1) unless
//! an explicit `**Depends-on**:` annotation overrides them.

use std::collections::HashMap;

use anyhow::{Result, bail};
use serde::Serialize;

use crate::graph;
use crate::model::{Task, TaskGraph, plan_file_stem};

/// Parse tasks from a plan markdown string.
pub fn parse(markdown: &str) -> Result<Vec<Task>> {
    let mut tasks: Vec<Task> = Vec::new();
    let mut current_title: Option<String> = None;
    let mut current_crate: Option<String> = None;
    let mut current_run: Option<String> = None;
    let mut current_deps: Option<Vec<String>> = None;

    for line in markdown.lines() {
        let trimmed = line.trim();

        // Detect task headings: `### Task N: Title` or `### N. Title`
        if let Some(rest) = trimmed.strip_prefix("### Task ") {
            // flush previous
            if let Some(title) = current_title.take() {
                push_task(
                    &mut tasks,
                    title,
                    current_crate.take(),
                    current_run.take(),
                    current_deps.take(),
                );
            }
            // strip leading "N: " or "N. "
            let title = rest
                .split_once(": ")
                .map(|x| x.1)
                .or_else(|| rest.split_once(". ").map(|x| x.1))
                .unwrap_or(rest)
                .trim()
                .to_string();
            current_title = Some(title);
            current_crate = None;
            current_deps = None;
            continue;
        }

        // Detect crate annotation: `**Crate**: `name``
        if trimmed.starts_with("**Crate**:") {
            let crate_name = trimmed
                .trim_start_matches("**Crate**:")
                .trim()
                .trim_matches('`')
                .to_string();
            current_crate = Some(crate_name);
        }

        // Detect run annotation: `**Run**: `command``
        if trimmed.starts_with("**Run**:") {
            let run_cmd = trimmed
                .trim_start_matches("**Run**:")
                .trim()
                .trim_matches('`')
                .to_string();
            current_run = Some(run_cmd);
        }

        // Detect depends-on annotation: `**Depends-on**: `t1,t2``
        if trimmed.starts_with("**Depends-on**:") {
            let raw = trimmed
                .trim_start_matches("**Depends-on**:")
                .trim()
                .trim_matches('`');
            let ids: Vec<String> = raw
                .split(',')
                .map(|s| s.trim().trim_matches('`').to_string())
                .filter(|s| !s.is_empty())
                .collect();
            current_deps = Some(ids);
        }
    }

    // flush last
    if let Some(title) = current_title.take() {
        push_task(
            &mut tasks,
            title,
            current_crate.take(),
            current_run.take(),
            current_deps.take(),
        );
    }

    Ok(tasks)
}

/// Result of importing one parsed plan into a task graph.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct IngestReport {
    /// Number of tasks parsed from the plan.
    pub parsed: usize,
    /// Number of tasks added to the graph.
    pub added: usize,
    /// Number of tasks already present from the same plan.
    pub skipped: usize,
    /// Stable IDs assigned to every parsed task, in plan order.
    pub ids: Vec<String>,
}

/// Decides whether a recorded plan path has disappeared from disk.
///
/// Injected into the graph's relocation queries rather than stat'd inside them, so the data model
/// stays free of filesystem access and relocation stays testable without one.
pub(crate) type SourceGone<'a> = &'a dyn Fn(&str) -> bool;

/// Reports whether a plan source is absent from disk.
///
/// Only an explicit `NotFound` counts as deletion. `Path::exists` answers `false` for *any* stat
/// error, including `PermissionDenied` on an unreadable parent directory, and treating that as proof
/// a plan was moved would hand its provenance to an unrelated file.
fn plan_source_is_gone(source: &str) -> bool {
    matches!(
        std::fs::metadata(source),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound
    )
}

/// Reports whether a recorded import describes this plan at its former path.
///
/// Mirrors `TaskGraph::relocated_plan_task_ids`, which requires the same stem, the same live task
/// ids, and a path that has disappeared. Repeating the stem conjunct here matters because the write
/// side *replaces* the entry it selects: matching on task ids alone would let a plan absorb a
/// look-alike entry and destroy its provenance.
fn is_relocated_entry(
    source: &str,
    task_ids: &[String],
    candidate_source: &str,
    candidate_ids: &[String],
    is_gone: SourceGone<'_>,
) -> bool {
    plan_file_stem(candidate_source) == plan_file_stem(source)
        && candidate_ids == task_ids
        && is_gone(candidate_source)
}

/// Import parsed plan tasks into an existing graph.
pub fn ingest(graph: &mut TaskGraph, tasks: Vec<Task>, source: &str) -> Result<IngestReport> {
    ingest_with(graph, tasks, source, &plan_source_is_gone)
}

/// Import parsed plan tasks, deciding relocation with the supplied probe.
pub(crate) fn ingest_with(
    graph: &mut TaskGraph,
    tasks: Vec<Task>,
    source: &str,
    is_gone: SourceGone<'_>,
) -> Result<IngestReport> {
    if tasks.is_empty() {
        bail!("no tasks found in plan");
    }
    let tasks = prepare_for_ingest_with(tasks, graph, source, is_gone)?;
    let parsed = tasks.len();
    let ids: Vec<String> = tasks.iter().map(|task| task.id.clone()).collect();
    let mut added = 0;
    let mut skipped = 0;
    let mut updated = graph.clone();

    for task in tasks {
        if graph_contains_same_task(&updated, &task) {
            skipped += 1;
        } else {
            graph::add_imported(&mut updated, task)?;
            added += 1;
        }
    }

    // Rebinding a relocated plan moves its existing entry onto the new path rather than leaving the
    // old provenance behind. Both halves of that decision are evaluated here so the model stays
    // free of filesystem access.
    let rebound = updated.adopt_relocated_plan_import(source, ids.clone(), |old, old_ids| {
        is_relocated_entry(source, &ids, old, old_ids, is_gone)
    });
    if !rebound {
        updated.record_plan_import(source.to_string(), ids.clone());
    }
    *graph = updated;

    Ok(IngestReport {
        parsed,
        added,
        skipped,
        ids,
    })
}

/// Prepare parsed tasks for insertion into an existing graph.
///
/// Tasks keep short `tN` IDs when those IDs are unused. Colliding plans use a deterministic
/// namespace. Graph-level plan provenance makes repeated ingestion idempotent even when distinct
/// plans contain identical task content.
pub fn prepare_for_ingest(tasks: Vec<Task>, graph: &TaskGraph, source: &str) -> Result<Vec<Task>> {
    prepare_for_ingest_with(tasks, graph, source, &plan_source_is_gone)
}

/// Prepare parsed tasks, deciding relocation with the supplied probe.
pub(crate) fn prepare_for_ingest_with(
    mut tasks: Vec<Task>,
    graph: &TaskGraph,
    source: &str,
    is_gone: SourceGone<'_>,
) -> Result<Vec<Task>> {
    // The namespace must come from the same stem the relocation match uses, so a plan's id prefix and
    // its identity cannot disagree about what a plan file is called.
    let namespace = normalize_namespace(plan_file_stem(source));
    if namespace.is_empty() {
        bail!("plan namespace must contain at least one letter or digit");
    }

    // A live candidate recorded at the plan's former path wins, which is what makes relocation
    // idempotent. It is content-checked because a stem match alone cannot separate a moved plan from
    // a distinct plan that merely shares a file name; `depends_on` is excluded since parsed tasks
    // hold pre-remap ids while graph tasks hold remapped ones.
    //
    // The check covers the id PREFIX rather than demanding equal lengths, so a plan that grew after
    // the move keeps its existing ids and mints an id only for the task appended since. `zip`
    // truncates at the shorter side, which is what lets a shorter plan reach the length guard below
    // and be rejected instead of forking a namespaced duplicate chain.
    //
    // Otherwise fall back to the exact-path entry, unfiltered, so re-ingesting a plan in place keeps
    // its reserved ids even after its tasks were removed, and edited content still reports a
    // conflict rather than forking a new chain.
    let existing_ids = graph
        .relocated_plan_task_ids(source, is_gone)
        .filter(|ids| {
            ids.iter().zip(tasks.iter()).all(|(id, candidate)| {
                graph
                    .tasks
                    .iter()
                    .find(|existing| &existing.id == id)
                    .is_some_and(|existing| {
                        existing.title == candidate.title
                            && existing.crate_name == candidate.crate_name
                            && existing.run == candidate.run
                    })
            })
        })
        .or_else(|| graph.plan_task_ids(source));
    if existing_ids.is_some_and(|ids| tasks.len() < ids.len()) {
        bail!(
            "plan now contains fewer tasks than its existing import; remove or reconcile old tasks explicitly"
        );
    }
    let legacy_plan_match = existing_ids.is_none()
        && tasks.iter().all(|candidate| {
            graph
                .tasks
                .iter()
                .find(|task| task.id == candidate.id)
                .is_some_and(|task| {
                    !graph.is_imported_plan_task(&task.id) && same_task_content(task, candidate)
                })
        });
    let short_ids_available = existing_ids.is_none()
        && (legacy_plan_match
            || tasks.iter().all(|candidate| {
                graph.tasks.iter().all(|task| task.id != candidate.id)
                    && !graph.is_imported_plan_task(&candidate.id)
            }));
    let namespace_collides = existing_ids.is_none()
        && !short_ids_available
        && tasks.iter().any(|task| {
            let candidate = format!("{namespace}-{}", task.id);
            graph.tasks.iter().any(|existing| existing.id == candidate)
                || graph.is_imported_plan_task(&candidate)
        });
    let namespace = if namespace_collides {
        format!("{namespace}-{:016x}", stable_source_hash(source))
    } else {
        namespace
    };

    let id_map: HashMap<String, String> = tasks
        .iter()
        .enumerate()
        .map(|(index, task)| {
            let id = existing_ids
                .and_then(|ids| ids.get(index))
                .cloned()
                .unwrap_or_else(|| {
                    if short_ids_available {
                        task.id.clone()
                    } else {
                        format!("{namespace}-{}", task.id)
                    }
                });
            (task.id.clone(), id)
        })
        .collect();

    for task in &mut tasks {
        task.id = id_map[&task.id].clone();
        for dependency in &mut task.depends_on {
            if let Some(external) = dependency.strip_prefix("graph:") {
                if external.is_empty() || graph.tasks.iter().all(|task| task.id != external) {
                    bail!("external dependency '{dependency}' does not exist in the graph");
                }
                *dependency = external.to_string();
            } else if let Some(rebased) = id_map.get(dependency) {
                *dependency = rebased.clone();
            }
        }
    }

    for task in &tasks {
        if existing_ids.is_none() && graph.is_imported_plan_task(&task.id) {
            bail!(
                "task '{}' is reserved by another imported plan; rename the plan file",
                task.id
            );
        }
        if let Some(existing) = graph.tasks.iter().find(|existing| existing.id == task.id)
            && !same_task_identity(existing, task)
            && !(legacy_plan_match && same_task_content(existing, task))
        {
            bail!(
                "task '{}' already exists with different plan content; rename the plan file",
                task.id
            );
        }
    }

    Ok(tasks)
}

fn graph_contains_same_task(graph: &TaskGraph, candidate: &Task) -> bool {
    graph
        .tasks
        .iter()
        .find(|task| task.id == candidate.id)
        .is_some_and(|task| same_task_identity(task, candidate))
}

fn same_task_identity(left: &Task, right: &Task) -> bool {
    same_task_content(left, right)
}

fn same_task_content(left: &Task, right: &Task) -> bool {
    left.title == right.title
        && left.crate_name == right.crate_name
        && left.run == right.run
        && left.depends_on == right.depends_on
}

fn stable_source_hash(source: &str) -> u64 {
    source
        .as_bytes()
        .iter()
        .fold(0xcbf29ce484222325, |hash, byte| {
            (hash ^ u64::from(*byte)).wrapping_mul(0x100000001b3)
        })
}

fn normalize_namespace(namespace: &str) -> String {
    let mut normalized = String::new();
    let mut previous_dash = false;
    for character in namespace.chars() {
        if character.is_ascii_alphanumeric() || character == '_' {
            normalized.push(character.to_ascii_lowercase());
            previous_dash = false;
        } else if !previous_dash && !normalized.is_empty() {
            normalized.push('-');
            previous_dash = true;
        }
    }
    normalized.trim_end_matches('-').to_string()
}

fn push_task(
    tasks: &mut Vec<Task>,
    title: String,
    crate_name: Option<String>,
    run: Option<String>,
    deps: Option<Vec<String>>,
) {
    let idx = tasks.len() + 1;
    let id = format!("t{idx}");
    let mut task = Task::new(id, title);
    task.crate_name = crate_name;
    task.run = run;
    task.depends_on = if let Some(explicit) = deps {
        explicit
    } else if idx > 1 {
        // Sequential dependency: each task depends on the previous one.
        vec![format!("t{}", idx - 1)]
    } else {
        vec![]
    };
    tasks.push(task);
}

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

    const SAMPLE: &str = r#"
# Plan: Foo feature

## Tasks

### Task 1: Write failing test for FooAdapter
**Crate**: `foo-core`

Some description here.

### Task 2: Implement FooAdapter
**Crate**: `foo-core`

### Task 3: Wire into service layer
**Crate**: `foo-service`
"#;

    #[test]
    fn parses_task_count() {
        let tasks = parse(SAMPLE).unwrap();
        assert_eq!(tasks.len(), 3);
    }

    #[test]
    fn parses_titles() {
        let tasks = parse(SAMPLE).unwrap();
        assert_eq!(tasks[0].title, "Write failing test for FooAdapter");
        assert_eq!(tasks[1].title, "Implement FooAdapter");
        assert_eq!(tasks[2].title, "Wire into service layer");
    }

    #[test]
    fn parses_crate_names() {
        let tasks = parse(SAMPLE).unwrap();
        assert_eq!(tasks[0].crate_name.as_deref(), Some("foo-core"));
        assert_eq!(tasks[2].crate_name.as_deref(), Some("foo-service"));
    }

    #[test]
    fn sequential_deps() {
        let tasks = parse(SAMPLE).unwrap();
        assert!(tasks[0].depends_on.is_empty());
        assert_eq!(tasks[1].depends_on, vec!["t1"]);
        assert_eq!(tasks[2].depends_on, vec!["t2"]);
    }

    #[test]
    fn prepare_for_ingest_namespaces_colliding_plan() {
        let first = parse(SAMPLE).unwrap();
        let mut graph = TaskGraph::default();
        graph.tasks = first;
        let second =
            parse("### Task 1: Other alpha\n### Task 2: Other beta\n**Crate**: `other-core`")
                .unwrap();

        let prepared = prepare_for_ingest(second, &graph, "Second Plan").unwrap();

        assert_eq!(prepared[0].id, "second-plan-t1");
        assert_eq!(prepared[1].id, "second-plan-t2");
        assert_eq!(prepared[1].depends_on, vec!["second-plan-t1"]);
    }

    #[test]
    fn prepare_for_ingest_keeps_identical_plan_idempotent() {
        let tasks = parse(SAMPLE).unwrap();
        let mut graph = TaskGraph::default();
        ingest(&mut graph, tasks.clone(), "same-plan").unwrap();

        let prepared = prepare_for_ingest(tasks, &graph, "same-plan").unwrap();

        assert_eq!(prepared[0].id, "t1");
        assert_eq!(prepared[1].depends_on, vec!["t1"]);
    }

    #[test]
    fn identical_content_from_distinct_plans_gets_distinct_ids() {
        let tasks = parse(SAMPLE).unwrap();
        let mut graph = TaskGraph::default();
        ingest(&mut graph, tasks.clone(), "first-plan").unwrap();

        let prepared = prepare_for_ingest(tasks, &graph, "second-plan").unwrap();

        assert_eq!(prepared[0].id, "second-plan-t1");
        assert_eq!(prepared[1].depends_on, vec!["second-plan-t1"]);
    }

    #[test]
    fn explicit_graph_dependency_is_not_rebased() {
        let mut graph = TaskGraph::default();
        graph.tasks.push(Task::new("t1", "Existing task"));
        let tasks = parse("### Task 1: New task\n**Depends-on**: `graph:t1`").unwrap();

        let prepared = prepare_for_ingest(tasks, &graph, "dependent-plan").unwrap();

        assert_eq!(prepared[0].id, "dependent-plan-t1");
        assert_eq!(prepared[0].depends_on, vec!["t1"]);
    }

    #[test]
    fn namespaced_plan_remains_idempotent_after_short_ids_are_removed() {
        let mut graph = TaskGraph::default();
        ingest(&mut graph, parse(SAMPLE).unwrap(), "first-plan").unwrap();
        let second = parse("### Task 1: Second alpha\n### Task 2: Second beta").unwrap();
        ingest(&mut graph, second.clone(), "second-plan").unwrap();
        graph
            .tasks
            .retain(|task| task.id.starts_with("second-plan-"));

        let report = ingest(&mut graph, second, "second-plan").unwrap();

        assert_eq!(report.added, 0);
        assert_eq!(report.skipped, 2);
        assert_eq!(report.ids, ["second-plan-t1", "second-plan-t2"]);
    }

    #[test]
    fn relocated_plan_reuses_its_task_ids() {
        let mut graph = TaskGraph::default();
        let tasks = parse(SAMPLE).unwrap();
        ingest(
            &mut graph,
            tasks.clone(),
            "/repo/.ctx/godmode/plans/alpha.md",
        )
        .unwrap();

        let report = ingest(&mut graph, tasks, "/repo/docs/plans/alpha.md").unwrap();

        assert_eq!(report.added, 0);
        assert_eq!(report.skipped, 3);
        assert_eq!(graph.tasks.len(), 3);
        assert!(graph.plan_task_ids("/repo/docs/plans/alpha.md").is_some());
    }

    #[test]
    fn relocated_plan_rebinds_provenance_to_the_new_path() {
        let mut graph = TaskGraph::default();
        let tasks = parse(SAMPLE).unwrap();
        ingest(&mut graph, tasks.clone(), "/repo/old/alpha.md").unwrap();

        ingest(&mut graph, tasks, "/repo/new/alpha.md").unwrap();

        assert!(graph.plan_task_ids("/repo/old/alpha.md").is_none());
        assert_eq!(graph.plan_task_ids("/repo/new/alpha.md").unwrap().len(), 3);
    }

    #[test]
    fn relocated_plan_with_changed_content_is_ingested_as_a_distinct_plan() {
        let mut graph = TaskGraph::default();
        ingest(&mut graph, parse(SAMPLE).unwrap(), "/repo/one/alpha.md").unwrap();
        ingest(
            &mut graph,
            parse("### Task 1: Unrelated task\n### Task 2: Another task").unwrap(),
            "/repo/two/alpha.md",
        )
        .unwrap();

        let report = ingest(&mut graph, parse(SAMPLE).unwrap(), "/repo/three/alpha.md").unwrap();

        // Same stem but different content: a distinct plan that must neither inherit the other
        // plan's task ids nor collide with them.
        assert_eq!(report.added, 3);
        assert_eq!(report.skipped, 0);
        assert_eq!(report.ids.len(), 3);
        for id in &report.ids {
            assert_ne!(id, "t1");
            assert_ne!(id, "alpha-t1");
        }
        assert_eq!(
            graph.plan_task_ids("/repo/one/alpha.md").unwrap(),
            ["t1", "t2", "t3"]
        );
        assert_eq!(
            graph.plan_task_ids("/repo/three/alpha.md").unwrap(),
            report.ids
        );
    }

    #[test]
    fn relocated_plan_is_recognized_after_stale_provenance_loses_its_tasks() {
        let mut graph = TaskGraph::default();
        let tasks = parse(SAMPLE).unwrap();
        ingest(&mut graph, tasks.clone(), "/repo/old/alpha.md").unwrap();
        // Provenance outlives its tasks: a stale entry for the new path points at an id that no
        // longer exists, exactly as `task remove` leaves behind.
        graph.record_plan_import(
            "/repo/new/alpha.md".to_string(),
            vec!["alpha-stale-t1".to_string()],
        );

        let report = ingest(&mut graph, tasks, "/repo/new/alpha.md").unwrap();

        assert_eq!(report.added, 0);
        assert_eq!(report.skipped, 3);
        assert_eq!(report.ids, ["t1", "t2", "t3"]);
    }

    #[test]
    fn grown_relocated_plan_reuses_its_task_ids_and_appends_only_the_new_one() {
        let mut graph = TaskGraph::default();
        ingest(
            &mut graph,
            parse(SAMPLE).unwrap(),
            "/repo/.ctx/godmode/plans/probe-alpha.md",
        )
        .unwrap();

        let grown = parse(&format!("{SAMPLE}\n### Task 4: Announce the release\n")).unwrap();
        let report = ingest(&mut graph, grown, "/repo/docs/plans/probe-alpha.md").unwrap();

        assert_eq!(report.added, 1);
        assert_eq!(report.skipped, 3);
        assert_eq!(report.ids[0], "t1");
        assert_eq!(report.ids[1], "t2");
        assert_eq!(report.ids[2], "t3");
        let ids: Vec<&str> = graph.tasks.iter().map(|task| task.id.as_str()).collect();
        assert_eq!(ids.len(), 4, "relocation must not orphan the old chain");
        for reused in ["t1", "t2", "t3"] {
            assert!(ids.contains(&reused), "expected {reused} to be reused");
            let forked = format!("probe-alpha-{reused}");
            assert!(
                !ids.contains(&forked.as_str()),
                "forked a duplicate chain entry {forked}"
            );
        }
    }

    #[test]
    fn shrunk_relocated_plan_is_rejected_instead_of_forking_a_chain() {
        let mut graph = TaskGraph::default();
        ingest(
            &mut graph,
            parse(SAMPLE).unwrap(),
            "/repo/old/probe-alpha.md",
        )
        .unwrap();

        // The surviving task matches the original verbatim, so the relocation prefix check accepts
        // the candidate and the length guard is what rejects the edit.
        let shrunk =
            parse("### Task 1: Write failing test for FooAdapter\n**Crate**: `foo-core`").unwrap();
        let before = serde_yaml::to_string(&graph).unwrap();
        let error = ingest(&mut graph, shrunk, "/repo/new/probe-alpha.md").unwrap_err();

        assert!(error.to_string().contains("fewer tasks"), "{error}");
        assert_eq!(serde_yaml::to_string(&graph).unwrap(), before);
    }

    #[test]
    fn a_plan_file_still_on_disk_prevents_relocation() {
        let dir = tempfile::tempdir().unwrap();
        let old = dir.path().join("old").join("probe-alpha.md");
        let new = dir.path().join("new").join("probe-alpha.md");
        std::fs::create_dir_all(old.parent().unwrap()).unwrap();
        std::fs::create_dir_all(new.parent().unwrap()).unwrap();
        std::fs::write(&old, SAMPLE).unwrap();
        std::fs::write(&new, SAMPLE).unwrap();
        let (old, new) = (old.to_str().unwrap(), new.to_str().unwrap());

        let mut graph = TaskGraph::default();
        ingest(&mut graph, parse(SAMPLE).unwrap(), old).unwrap();

        // Both files are on disk, so the second is a copy of the plan, not a relocation of it.
        let report = ingest(&mut graph, parse(SAMPLE).unwrap(), new).unwrap();

        assert_eq!(report.added, 3);
        assert_eq!(report.skipped, 0);
        for id in &report.ids {
            assert_ne!(id, "t1", "the original chain must not be inherited");
        }
        assert_eq!(graph.tasks.len(), 6);
        assert_eq!(graph.plan_task_ids(old).unwrap(), ["t1", "t2", "t3"]);
        assert_eq!(graph.plan_task_ids(new).unwrap(), report.ids);
    }

    #[test]
    fn relocation_requires_stem_task_ids_and_an_absent_old_path() {
        let ids = vec!["t1".to_string()];
        let other_ids = vec!["t9".to_string()];
        let gone: &dyn Fn(&str) -> bool = &|_| true;

        assert!(is_relocated_entry(
            "/new/alpha.md",
            &ids,
            "/old/alpha.md",
            &ids,
            gone
        ));
        // A different stem is a different plan, even when the ids coincide: the write side replaces
        // the entry it picks, so a wrong pick would destroy the other plan's provenance.
        assert!(!is_relocated_entry(
            "/new/omega.md",
            &ids,
            "/old/alpha.md",
            &ids,
            gone
        ));
        assert!(!is_relocated_entry(
            "/new/alpha.md",
            &ids,
            "/old/alpha.md",
            &other_ids,
            gone
        ));
        assert!(!is_relocated_entry(
            "/new/alpha.md",
            &ids,
            "/old/alpha.md",
            &ids,
            &|_| false
        ));
    }

    #[cfg(unix)]
    #[test]
    fn an_unstattable_path_is_not_treated_as_deleted() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let locked = dir.path().join("locked");
        std::fs::create_dir_all(&locked).unwrap();
        let plan = locked.join("probe-alpha.md");
        std::fs::write(&plan, SAMPLE).unwrap();

        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
        let unstattable = plan_source_is_gone(plan.to_str().unwrap());
        let missing = plan_source_is_gone("/definitely/absent/probe-alpha.md");
        std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o700)).unwrap();

        assert!(
            !unstattable,
            "an unreadable parent must not read as proof the plan was deleted"
        );
        assert!(missing, "a genuinely absent path must read as deleted");
    }

    #[test]
    fn relocation_is_decided_by_the_injected_probe_not_the_filesystem() {
        let mut graph = TaskGraph::default();
        ingest(
            &mut graph,
            parse(SAMPLE).unwrap(),
            "/repo/old/probe-alpha.md",
        )
        .unwrap();

        // No path here exists on disk, so only the probe can decide these two outcomes.
        let blocked = prepare_for_ingest_with(
            parse(SAMPLE).unwrap(),
            &graph,
            "/repo/new/probe-alpha.md",
            &|_| false,
        )
        .unwrap();
        assert_eq!(blocked[0].id, "probe-alpha-t1");

        let relocated = prepare_for_ingest_with(
            parse(SAMPLE).unwrap(),
            &graph,
            "/repo/new/probe-alpha.md",
            &|_| true,
        )
        .unwrap();
        assert_eq!(relocated[0].id, "t1");
        assert_eq!(relocated[1].depends_on, vec!["t1"]);
    }

    #[test]
    fn legacy_matching_tasks_are_adopted_without_duplication() {
        let tasks = parse(SAMPLE).unwrap();
        let mut graph = TaskGraph::default();
        graph.tasks = tasks.clone();

        let report = ingest(&mut graph, tasks, "/repo/plans/legacy.md").unwrap();

        assert_eq!(report.added, 0);
        assert_eq!(report.skipped, 3);
        assert_eq!(graph.tasks.len(), 3);
        assert_eq!(
            graph.plan_task_ids("/repo/plans/legacy.md").unwrap(),
            ["t1", "t2", "t3"]
        );
    }

    #[test]
    fn failed_ingest_leaves_graph_unchanged() {
        let mut graph = TaskGraph::default();
        ingest(&mut graph, parse(SAMPLE).unwrap(), "/repo/plans/same.md").unwrap();
        let before = serde_yaml::to_string(&graph).unwrap();
        let changed = parse(
            "### Task 1: Changed task\n### Task 2: Implement FooAdapter\n### Task 3: Wire into service layer",
        )
        .unwrap();

        let error = ingest(&mut graph, changed, "/repo/plans/same.md").unwrap_err();

        assert!(error.to_string().contains("different plan content"));
        assert_eq!(serde_yaml::to_string(&graph).unwrap(), before);
    }

    #[test]
    fn missing_external_graph_dependency_is_rejected() {
        let graph = TaskGraph::default();
        let tasks = parse("### Task 1: New task\n**Depends-on**: `graph:missing`").unwrap();

        let error = prepare_for_ingest(tasks, &graph, "/repo/plan.md").unwrap_err();

        assert!(error.to_string().contains("does not exist"));
    }

    #[test]
    fn removed_imported_ids_remain_reserved_for_their_source() {
        let mut graph = TaskGraph::default();
        ingest(&mut graph, parse(SAMPLE).unwrap(), "/repo/first.md").unwrap();
        graph.tasks.clear();
        let other = parse("### Task 1: Other task").unwrap();

        let prepared = prepare_for_ingest(other, &graph, "/repo/other.md").unwrap();

        assert_eq!(prepared[0].id, "other-t1");
        let restored = ingest(&mut graph, parse(SAMPLE).unwrap(), "/repo/first.md").unwrap();
        assert_eq!(restored.ids, ["t1", "t2", "t3"]);
    }

    #[test]
    fn shortening_an_imported_plan_is_rejected_atomically() {
        let mut graph = TaskGraph::default();
        ingest(&mut graph, parse(SAMPLE).unwrap(), "/repo/plan.md").unwrap();
        let before = serde_yaml::to_string(&graph).unwrap();
        let shortened = parse("### Task 1: Write failing test for FooAdapter").unwrap();

        let error = ingest(&mut graph, shortened, "/repo/plan.md").unwrap_err();

        assert!(error.to_string().contains("fewer tasks"));
        assert_eq!(serde_yaml::to_string(&graph).unwrap(), before);
    }

    #[test]
    fn empty_plan_is_rejected_without_recording_an_import() {
        let mut graph = TaskGraph::default();

        let error = ingest(&mut graph, Vec::new(), "/repo/empty.md").unwrap_err();

        assert!(error.to_string().contains("no tasks"));
        assert!(graph.plan_task_ids("/repo/empty.md").is_none());
    }
}