eclipse-core 0.13.4

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
//! `#657`: the plan a session keeps — the steps, their order, and which one is being done.
//!
//! On a job with eight steps there was no list. The steps existed as sentences in the transcript,
//! and compaction's job was to guess which of them still mattered: `THREAD_WORDS` harvested lines
//! containing "todo" or "still need" into *Open Threads*, and the order was rebuilt from the last
//! few messages each turn. What was lost is exactly what a plan is for — the order, and the one
//! step currently being done.
//!
//! A plan is not `/tasks` (a background run is a process) and not `/goal` (one standing objective,
//! judged per turn, *what* is being achieved rather than *in what order*). A session can hold all
//! three: the goal is the release, the plan is the eight issues before it, a task is a run.
//!
//! This module is the words and the arithmetic; the rows are `session.rs` (two tables, foreign-keyed
//! to the session so deleting a session deletes its plan) and the tool is `tools_plan.rs`. Nothing
//! here knows what a terminal or a browser is, so the rules a surface would otherwise each have to
//! re-invent — one `in_progress`, order is priority, what a merge means — are testable here.

use serde::{Deserialize, Serialize};

/// Where one step stands.
///
/// Four, not three: `Cancelled` is not `Done`, and a list that cannot say "this was dropped" makes
/// a model silently drop it instead, which is the loss the whole table exists to prevent.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Status {
    Pending,
    InProgress,
    Done,
    Cancelled,
}

impl Status {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Pending => "pending",
            Self::InProgress => "in_progress",
            Self::Done => "done",
            Self::Cancelled => "cancelled",
        }
    }

    /// The word from the tool's own vocabulary. `in_progress` also accepts the two spellings a
    /// model reaches for first, because refusing them teaches it to retry rather than to write.
    pub fn parse(word: &str) -> Option<Self> {
        match word.trim().to_ascii_lowercase().as_str() {
            "pending" | "todo" => Some(Self::Pending),
            "in_progress" | "in-progress" | "inprogress" | "doing" | "active" => {
                Some(Self::InProgress)
            }
            "done" | "completed" | "complete" => Some(Self::Done),
            "cancelled" | "canceled" | "dropped" | "skipped" => Some(Self::Cancelled),
            _ => None,
        }
    }

    /// `[ ]`, `[▸]`, `[x]`, `[-]` — one column, so a list reads down the left edge.
    pub fn mark(self) -> &'static str {
        match self {
            Self::Pending => "[ ]",
            Self::InProgress => "[~]",
            Self::Done => "[x]",
            Self::Cancelled => "[-]",
        }
    }

    /// Finished, one way or the other: not worth a line in a handoff.
    pub fn is_finished(self) -> bool {
        matches!(self, Self::Done | Self::Cancelled)
    }
}

/// One step.
///
/// `id` is the model's own word for the step and is what a merge patches by, so it is required and
/// has to be unique: an id invented on its behalf would make the next merge unpredictable.
/// `parent` groups steps into a phase — the phase is an item too, so a nested list needs no second
/// shape.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Item {
    pub id: String,
    pub content: String,
    pub status: Status,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent: Option<String>,
}

impl Item {
    pub fn new(id: &str, content: &str, status: Status) -> Self {
        Self {
            id: id.to_string(),
            content: content.to_string(),
            status,
            parent: None,
        }
    }
}

/// A whole plan: the steps in priority order, and the revision the store is at.
///
/// The revision is what keeps two surfaces honest. The dashboard polls and the terminal takes a
/// live frame, so both can be looking at a snapshot; a client that applied a stale one can tell,
/// which is the sort of disagreement nobody notices until they act on it.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Plan {
    pub revision: u64,
    pub items: Vec<Item>,
}

/// The four numbers a result carries.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Counts {
    pub pending: usize,
    pub in_progress: usize,
    pub done: usize,
    pub cancelled: usize,
}

impl Plan {
    pub fn new(items: Vec<Item>) -> Self {
        Self { revision: 0, items }
    }

    pub fn counts(&self) -> Counts {
        let mut counts = Counts::default();
        for item in &self.items {
            match item.status {
                Status::Pending => counts.pending += 1,
                Status::InProgress => counts.in_progress += 1,
                Status::Done => counts.done += 1,
                Status::Cancelled => counts.cancelled += 1,
            }
        }
        counts
    }

    /// The steps still worth showing, in order. Finished ones are left out of a handoff and out of
    /// the "what is left" count, for the reason Hermes leaves them out of its todo injection: a
    /// finished step in the handoff invites the model to do it again.
    pub fn active(&self) -> impl Iterator<Item = &Item> {
        self.items.iter().filter(|i| !i.status.is_finished())
    }

    /// The one step being done, if one is marked.
    pub fn current(&self) -> Option<&Item> {
        self.items.iter().find(|i| i.status == Status::InProgress)
    }

    /// `3/8` — finished out of total, which is what a status line reads as.
    pub fn progress(&self) -> (usize, usize) {
        let finished = self.items.iter().filter(|i| i.status.is_finished()).count();
        (finished, self.items.len())
    }
}

/// What is wrong with a list the model wrote, if anything.
///
/// Every answer names the item by its one-based position *and* its id, because the model wrote both
/// and a sentence it can act on is a retry that works. An empty list is not an error: clearing a
/// plan is a legitimate thing to do.
pub fn validate(items: &[Item]) -> Result<(), String> {
    for (index, item) in items.iter().enumerate() {
        let position = index + 1;
        if item.id.trim().is_empty() {
            return Err(format!(
                "item {position} has no `id`; give each step a short unique id, because a merge \
                 patches by id"
            ));
        }
        if item.content.trim().is_empty() {
            return Err(format!(
                "item {position} (`{}`) has no `content`; a step with nothing to do cannot be \
                 done or dropped",
                item.id
            ));
        }
        if let Some(earlier) = items[..index].iter().position(|i| i.id == item.id) {
            return Err(format!(
                "items {} and {position} share the id `{}`; an id has to name one step",
                earlier + 1,
                item.id
            ));
        }
    }
    Ok(())
}

/// Patch an existing list by id: what the model names is replaced in place, what is new is
/// appended, and what it does not mention stays.
///
/// In place, because position *is* priority: a model that marks step 5 done must not thereby move
/// it to the end and reorder the work it has not done yet. That is the difference between this and
/// a write that replaces the whole list, which is what a caller that passes no `merge` asks for.
pub fn merge(existing: &[Item], incoming: &[Item]) -> Vec<Item> {
    let mut out = existing.to_vec();
    for item in incoming {
        match out.iter_mut().find(|e| e.id == item.id) {
            // The status and the words are what a merge is for; the parent goes with them. The
            // position stays where it was.
            Some(existing) => {
                existing.content = item.content.clone();
                existing.status = item.status;
                existing.parent = item.parent.clone();
            }
            None => out.push(item.clone()),
        }
    }
    out
}

/// Keep at most one step `in_progress`, the first in list order, and demote the rest to `pending`.
///
/// Normalised rather than refused: two steps in progress is a model being helpful, and an error
/// teaches it to retry the same write. Demoting keeps the list honest and says which ids changed,
/// so the model is not surprised by a status it did not write.
pub fn one_in_progress(items: &mut [Item]) -> Vec<String> {
    let mut seen = false;
    let mut demoted = Vec::new();
    for item in items.iter_mut() {
        if item.status != Status::InProgress {
            continue;
        }
        if seen {
            item.status = Status::Pending;
            demoted.push(item.id.clone());
        } else {
            seen = true;
        }
    }
    demoted
}

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

    fn item(id: &str, status: Status) -> Item {
        Item::new(id, &format!("step {id}"), status)
    }

    #[test]
    fn a_merge_patches_in_place_and_appends_what_is_new() {
        let existing = vec![
            item("a", Status::Pending),
            item("b", Status::Pending),
            item("c", Status::Pending),
        ];
        let mut done = item("b", Status::Done);
        done.content = "step b, finished".to_string();
        let out = merge(&existing, &[done, item("d", Status::Pending)]);

        assert_eq!(
            out.iter().map(|i| i.id.as_str()).collect::<Vec<_>>(),
            ["a", "b", "c", "d"],
            "b is still second: a merge does not reorder the work that is left"
        );
        assert_eq!(out[1].status, Status::Done);
        assert_eq!(out[1].content, "step b, finished");
        assert_eq!(out[0].status, Status::Pending, "an unmentioned step stays");
    }

    #[test]
    fn a_merge_keeps_what_it_does_not_mention() {
        let existing = vec![item("a", Status::Done), item("b", Status::Pending)];
        let out = merge(&existing, &[]);
        assert_eq!(out, existing);
    }

    #[test]
    fn one_in_progress_keeps_the_first_and_names_what_it_demoted() {
        let mut items = vec![
            item("a", Status::InProgress),
            item("b", Status::InProgress),
            item("c", Status::InProgress),
            item("d", Status::Pending),
        ];
        let demoted = one_in_progress(&mut items);
        assert_eq!(demoted, ["b", "c"]);
        assert_eq!(items[0].status, Status::InProgress);
        assert_eq!(items[1].status, Status::Pending);
        assert_eq!(items[2].status, Status::Pending);
        assert_eq!(items[3].status, Status::Pending);
    }

    #[test]
    fn one_in_progress_leaves_a_single_marked_step_alone() {
        let mut items = vec![item("a", Status::Pending), item("b", Status::InProgress)];
        assert!(one_in_progress(&mut items).is_empty());
        assert_eq!(items[1].status, Status::InProgress);
    }

    #[test]
    fn counts_and_progress_are_the_four_numbers_and_finished_over_total() {
        let plan = Plan::new(vec![
            item("a", Status::Done),
            item("b", Status::InProgress),
            item("c", Status::Pending),
            item("d", Status::Cancelled),
            item("e", Status::Pending),
        ]);
        assert_eq!(
            plan.counts(),
            Counts {
                pending: 2,
                in_progress: 1,
                done: 1,
                cancelled: 1,
            }
        );
        assert_eq!(plan.progress(), (2, 5));
        assert_eq!(plan.current().map(|i| i.id.as_str()), Some("b"));
        assert_eq!(
            plan.active().map(|i| i.id.as_str()).collect::<Vec<_>>(),
            ["b", "c", "e"],
            "a handoff carries what is left, in order"
        );
    }

    #[test]
    fn validation_names_the_item_that_is_wrong() {
        assert_eq!(
            validate(&[
                item("a", Status::Pending),
                Item::new("b", "  ", Status::Pending)
            ])
            .unwrap_err(),
            "item 2 (`b`) has no `content`; a step with nothing to do cannot be done or dropped"
        );
        assert_eq!(
            validate(&[
                item("a", Status::Pending),
                Item::new("", "x", Status::Pending)
            ])
            .unwrap_err(),
            "item 2 has no `id`; give each step a short unique id, because a merge patches by id"
        );
        assert_eq!(
            validate(&[
                item("a", Status::Pending),
                item("b", Status::Pending),
                item("a", Status::Pending)
            ])
            .unwrap_err(),
            "items 1 and 3 share the id `a`; an id has to name one step"
        );
        assert!(validate(&[]).is_ok(), "clearing a plan is legitimate");
    }

    #[test]
    fn a_status_round_trips_and_accepts_the_spellings_a_model_writes() {
        for status in [
            Status::Pending,
            Status::InProgress,
            Status::Done,
            Status::Cancelled,
        ] {
            assert_eq!(Status::parse(status.as_str()), Some(status));
        }
        assert_eq!(Status::parse("in-progress"), Some(Status::InProgress));
        assert_eq!(Status::parse("Doing"), Some(Status::InProgress));
        assert_eq!(Status::parse("completed"), Some(Status::Done));
        assert_eq!(Status::parse("nonsense"), None);
    }

    #[test]
    fn a_parent_groups_steps_without_a_second_shape() {
        let mut phase = Item::new("p1", "The writer cluster", Status::InProgress);
        phase.parent = None;
        let mut step = Item::new("s1", "#535 array header", Status::Pending);
        step.parent = Some("p1".to_string());
        let plan = Plan::new(vec![phase, step]);
        let nested: Vec<&Item> = plan
            .items
            .iter()
            .filter(|i| i.parent.as_deref() == Some("p1"))
            .collect();
        assert_eq!(nested.len(), 1);
        assert_eq!(nested[0].id, "s1");
    }
}