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
//! Task, task-graph, status, priority, provenance, and summary data types.

#![allow(clippy::items_after_test_module)]

use chrono::{DateTime, NaiveDate, Utc};
use serde::{Deserialize, Serialize};

/// Task scheduling priority.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum Priority {
    High,
    #[default]
    Normal,
    Low,
}

impl Priority {
    /// Returns `true` when the priority is `Normal` — used by serde skip predicate.
    pub fn is_normal(&self) -> bool {
        matches!(self, Priority::Normal)
    }
}

impl std::str::FromStr for Priority {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_ascii_lowercase().as_str() {
            "high" => Ok(Priority::High),
            "normal" => Ok(Priority::Normal),
            "low" => Ok(Priority::Low),
            other => anyhow::bail!("unknown priority '{other}'; expected high, normal, or low"),
        }
    }
}

impl std::fmt::Display for Priority {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Priority::High => write!(f, "high"),
            Priority::Normal => write!(f, "normal"),
            Priority::Low => write!(f, "low"),
        }
    }
}

/// Task execution status.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Status {
    Pending,
    Running,
    Done,
    Blocked,
}

impl Status {
    /// Returns the lowercase status name.
    pub fn as_str(&self) -> &'static str {
        match self {
            Status::Pending => "pending",
            Status::Running => "running",
            Status::Done => "done",
            Status::Blocked => "blocked",
        }
    }
}

impl std::fmt::Display for Status {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// External-system provenance retained for synchronization.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TaskProvenance {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub doob: Option<DoobProvenance>,
}

impl TaskProvenance {
    fn is_empty(&self) -> bool {
        self.doob.is_none()
    }
}

/// Provenance for a task published to or imported from Doob.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DoobProvenance {
    pub id: String,
}

/// A single task in the execution graph.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Task {
    pub id: String,
    pub title: String,
    pub status: Status,
    #[serde(default)]
    pub depends_on: Vec<String>,
    #[serde(default)]
    pub notes: String,
    /// Structured identifiers assigned by external task systems.
    #[serde(default, skip_serializing_if = "TaskProvenance::is_empty")]
    pub provenance: TaskProvenance,
    /// Crate targeted by this task, if applicable.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub crate_name: Option<String>,
    /// Commit SHA recorded on completion.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub commit: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub completed: Option<NaiveDate>,
    /// Shell command to run for this task. Prefix with `rx:` to invoke via rx registry.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub run: Option<String>,
    /// Wall-clock time when the task was last started. Used to compute duration_ms.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub started_at: Option<DateTime<Utc>>,
    /// Wall-clock time when the task was completed. Used to bound duration_ms.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub completed_at: Option<DateTime<Utc>>,
    /// Scheduling priority. Defaults to Normal; omitted from YAML when Normal.
    #[serde(default, skip_serializing_if = "Priority::is_normal")]
    pub priority: Priority,
    /// Freeform tags for flexible grouping beyond `crate_name`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
}

impl Task {
    /// Creates a pending task with normal priority and empty optional metadata.
    pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            title: title.into(),
            status: Status::Pending,
            depends_on: vec![],
            notes: String::new(),
            provenance: TaskProvenance::default(),
            crate_name: None,
            commit: None,
            completed: None,
            run: None,
            started_at: None,
            completed_at: None,
            priority: Priority::Normal,
            tags: vec![],
        }
    }

    /// Returns the task's Doob identifier, if present.
    pub fn doob_id(&self) -> Option<&str> {
        self.provenance.doob.as_ref().map(|value| value.id.as_str())
    }

    /// Associates the task with a Doob todo identifier.
    pub fn set_doob_id(&mut self, id: impl Into<String>) {
        self.provenance.doob = Some(DoobProvenance { id: id.into() });
    }
}

/// The full task graph stored in `.ctx/godmode/tasks.yaml`.
#[derive(Debug, Serialize, Deserialize)]
pub struct TaskGraph {
    pub tasks: Vec<Task>,
    /// Stable source-to-task-ID mappings for idempotent plan ingestion.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    plan_imports: Vec<PlanImport>,
    /// Cached set of task IDs with `Status::Done`. Invalidated on any state transition.
    #[serde(skip)]
    done_cache: std::cell::RefCell<Option<std::collections::HashSet<String>>>,
}

impl Default for TaskGraph {
    fn default() -> Self {
        Self {
            tasks: Vec::new(),
            plan_imports: Vec::new(),
            done_cache: std::cell::RefCell::new(None),
        }
    }
}

impl Clone for TaskGraph {
    fn clone(&self) -> Self {
        Self {
            tasks: self.tasks.clone(),
            plan_imports: self.plan_imports.clone(),
            done_cache: std::cell::RefCell::new(None),
        }
    }
}

/// Returns a plan source's file stem: its final path segment without the `.md` suffix.
///
/// This is a plan's identity across directories, and the single definition used both to match a
/// relocated plan and to derive the id namespace in `plan`, so the two cannot drift apart.
pub(crate) fn plan_file_stem(source: &str) -> &str {
    let file_name = source.rsplit(['/', '\\']).next().unwrap_or(source);
    file_name.strip_suffix(".md").unwrap_or(file_name)
}

impl TaskGraph {
    pub(crate) fn plan_task_ids(&self, source: &str) -> Option<&[String]> {
        self.plan_imports
            .iter()
            .find(|import| import.source == source)
            .map(|import| import.task_ids.as_slice())
    }

    /// Resolve an import's task ids for a plan whose recorded location no longer exists on disk.
    ///
    /// A relocated plan is the same plan, so it keeps its existing task ids instead of minting a
    /// fresh namespaced chain. Relocation is inferred from the recorded path having disappeared: if
    /// that file is gone, the recorded import is this plan under its old location. The stem must
    /// also be unambiguous — if two recorded imports share it, `None` is returned.
    ///
    /// Provenance outlives its tasks, because `task remove` keeps ids reserved for their source. A
    /// candidate therefore only counts when every id it records still exists in the graph.
    ///
    /// `is_gone` answers whether a recorded path has disappeared. It is a parameter rather than an
    /// inline `Path::exists` call so this data model performs no filesystem access and the check can
    /// be substituted by callers and tests.
    pub(crate) fn relocated_plan_task_ids(
        &self,
        source: &str,
        is_gone: impl Fn(&str) -> bool,
    ) -> Option<&[String]> {
        let stem = plan_file_stem(source);
        let mut matches = self.plan_imports.iter().filter(|import| {
            plan_file_stem(&import.source) == stem
                && is_gone(&import.source)
                && self.plan_import_has_live_tasks(import)
        });
        let only = matches.next()?;
        matches.next().is_none().then_some(only.task_ids.as_slice())
    }

    fn plan_import_has_live_tasks(&self, import: &PlanImport) -> bool {
        import
            .task_ids
            .iter()
            .all(|id| self.tasks.iter().any(|task| &task.id == id))
    }

    pub(crate) fn is_imported_plan_task(&self, id: &str) -> bool {
        self.plan_imports
            .iter()
            .any(|import| import.task_ids.iter().any(|task_id| task_id == id))
    }

    /// Records `source` as the origin of `task_ids`, replacing any entry already at that path.
    pub(crate) fn record_plan_import(&mut self, source: String, task_ids: Vec<String>) {
        if let Some(import) = self
            .plan_imports
            .iter_mut()
            .find(|import| import.source == source)
        {
            import.task_ids = task_ids;
            return;
        }
        self.plan_imports.push(PlanImport { source, task_ids });
    }

    /// Rebinds the entry describing this plan at its former path onto `source`, reporting whether it
    /// found one.
    ///
    /// A relocated plan keeps a single provenance entry, so `is_relocated` selects the entry that
    /// records this plan under its old location; it is a parameter so the relocation test is supplied
    /// by the caller rather than performed here. An entry already recorded at `source` always wins,
    /// because re-ingesting a plan in place must update its ids without discarding its identity.
    pub(crate) fn adopt_relocated_plan_import(
        &mut self,
        source: &str,
        task_ids: Vec<String>,
        is_relocated: impl Fn(&str, &[String]) -> bool,
    ) -> bool {
        if self.plan_task_ids(source).is_some() {
            return false;
        }
        let Some(index) = self
            .plan_imports
            .iter()
            .position(|import| is_relocated(&import.source, &import.task_ids))
        else {
            return false;
        };
        self.plan_imports[index] = PlanImport {
            source: source.to_string(),
            task_ids,
        };
        true
    }

    pub(crate) fn clear_plan_imports(&mut self) {
        self.plan_imports.clear();
    }

    /// Returns the cached done-ID set, rebuilding if invalidated.
    pub fn done_ids(&self) -> std::cell::Ref<'_, std::collections::HashSet<String>> {
        {
            let cache = self.done_cache.borrow();
            if cache.is_some() {
                return std::cell::Ref::map(cache, |c| c.as_ref().unwrap());
            }
        }
        let set: std::collections::HashSet<String> = self
            .tasks
            .iter()
            .filter(|t| t.status == Status::Done)
            .map(|t| t.id.clone())
            .collect();
        *self.done_cache.borrow_mut() = Some(set);
        std::cell::Ref::map(self.done_cache.borrow(), |c| c.as_ref().unwrap())
    }

    /// Invalidate the done-ID cache. Must be called after any task state change.
    pub fn invalidate_done_cache(&mut self) {
        *self.done_cache.get_mut() = None;
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct PlanImport {
    source: String,
    task_ids: Vec<String>,
}

/// Summary counts for display.
#[derive(Debug, Default)]
pub struct GraphSummary {
    pub done: usize,
    pub running: usize,
    pub pending: usize,
    pub blocked: usize,
}

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

    #[test]
    fn task_started_at_roundtrips_yaml() {
        let mut t = Task::new("t1", "A");
        t.started_at = Some(Utc::now());
        let yaml = serde_yaml::to_string(&t).unwrap();
        let back: Task = serde_yaml::from_str(&yaml).unwrap();
        assert!(back.started_at.is_some());
    }

    // --- Priority tests (RED — fail before implementation) ---

    #[test]
    fn priority_default_is_normal() {
        let t = Task::new("t1", "A");
        assert_eq!(t.priority, Priority::Normal);
    }

    #[test]
    fn priority_serializes_as_lowercase() {
        let mut t = Task::new("t1", "A");
        t.priority = Priority::High;
        let yaml = serde_yaml::to_string(&t).unwrap();
        assert!(yaml.contains("priority: high"), "got: {yaml}");
    }

    #[test]
    fn priority_normal_is_skipped_in_yaml() {
        let t = Task::new("t1", "A");
        let yaml = serde_yaml::to_string(&t).unwrap();
        assert!(
            !yaml.contains("priority"),
            "Normal priority should be omitted from YAML: {yaml}"
        );
    }

    #[test]
    fn priority_roundtrips_all_variants() {
        for priority in [Priority::High, Priority::Normal, Priority::Low] {
            let mut t = Task::new("t1", "A");
            t.priority = priority.clone();
            let yaml = serde_yaml::to_string(&t).unwrap();
            let back: Task = serde_yaml::from_str(&yaml).unwrap();
            assert_eq!(back.priority, priority);
        }
    }

    #[test]
    fn tags_roundtrip_yaml() {
        let mut t = Task::new("t1", "A");
        t.tags = vec!["frontend".into(), "urgent".into()];
        let yaml = serde_yaml::to_string(&t).unwrap();
        assert!(
            yaml.contains("tags:"),
            "tags field missing from YAML: {yaml}"
        );
        let back: Task = serde_yaml::from_str(&yaml).unwrap();
        assert_eq!(back.tags, vec!["frontend", "urgent"]);
    }

    #[test]
    fn tags_empty_skipped_in_yaml() {
        let t = Task::new("t1", "A");
        let yaml = serde_yaml::to_string(&t).unwrap();
        assert!(
            !yaml.contains("tags"),
            "Empty tags should be omitted from YAML: {yaml}"
        );
    }

    #[test]
    fn tags_deserializes_missing_field_as_empty() {
        let yaml = "id: t1\ntitle: A\nstatus: pending\n";
        let t: Task = serde_yaml::from_str(yaml).unwrap();
        assert!(t.tags.is_empty());
    }

    #[test]
    fn completed_at_none_by_default_and_roundtrips() {
        let t = Task::new("t1", "A");
        assert!(t.completed_at.is_none());

        let mut t2 = Task::new("t2", "B");
        t2.completed_at = Some(Utc::now());
        let yaml = serde_yaml::to_string(&t2).unwrap();
        assert!(yaml.contains("completed_at"), "got: {yaml}");
        let back: Task = serde_yaml::from_str(&yaml).unwrap();
        assert!(back.completed_at.is_some());
    }

    #[test]
    fn completed_at_skipped_when_none() {
        let t = Task::new("t1", "A");
        let yaml = serde_yaml::to_string(&t).unwrap();
        assert!(
            !yaml.contains("completed_at"),
            "None completed_at should be omitted: {yaml}"
        );
    }

    #[test]
    fn priority_deserializes_missing_field_as_normal() {
        let yaml = "id: t1\ntitle: A\nstatus: pending\n";
        let t: Task = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(t.priority, Priority::Normal);
    }

    #[test]
    fn priority_display() {
        assert_eq!(Priority::High.to_string(), "high");
        assert_eq!(Priority::Normal.to_string(), "normal");
        assert_eq!(Priority::Low.to_string(), "low");
    }
}

impl TaskGraph {
    /// Counts tasks by status.
    pub fn summary(&self) -> GraphSummary {
        let mut s = GraphSummary::default();
        for t in &self.tasks {
            match t.status {
                Status::Done => s.done += 1,
                Status::Running => s.running += 1,
                Status::Pending => s.pending += 1,
                Status::Blocked => s.blocked += 1,
            }
        }
        s
    }
}