Skip to main content

eclipse_core/
plans.rs

1//! `#657`: the plan a session keeps — the steps, their order, and which one is being done.
2//!
3//! On a job with eight steps there was no list. The steps existed as sentences in the transcript,
4//! and compaction's job was to guess which of them still mattered: `THREAD_WORDS` harvested lines
5//! containing "todo" or "still need" into *Open Threads*, and the order was rebuilt from the last
6//! few messages each turn. What was lost is exactly what a plan is for — the order, and the one
7//! step currently being done.
8//!
9//! A plan is not `/tasks` (a background run is a process) and not `/goal` (one standing objective,
10//! judged per turn, *what* is being achieved rather than *in what order*). A session can hold all
11//! three: the goal is the release, the plan is the eight issues before it, a task is a run.
12//!
13//! This module is the words and the arithmetic; the rows are `session.rs` (two tables, foreign-keyed
14//! to the session so deleting a session deletes its plan) and the tool is `tools_plan.rs`. Nothing
15//! here knows what a terminal or a browser is, so the rules a surface would otherwise each have to
16//! re-invent — one `in_progress`, order is priority, what a merge means — are testable here.
17
18use serde::{Deserialize, Serialize};
19
20/// Where one step stands.
21///
22/// Four, not three: `Cancelled` is not `Done`, and a list that cannot say "this was dropped" makes
23/// a model silently drop it instead, which is the loss the whole table exists to prevent.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "snake_case")]
26pub enum Status {
27    Pending,
28    InProgress,
29    Done,
30    Cancelled,
31}
32
33impl Status {
34    pub fn as_str(self) -> &'static str {
35        match self {
36            Self::Pending => "pending",
37            Self::InProgress => "in_progress",
38            Self::Done => "done",
39            Self::Cancelled => "cancelled",
40        }
41    }
42
43    /// The word from the tool's own vocabulary. `in_progress` also accepts the two spellings a
44    /// model reaches for first, because refusing them teaches it to retry rather than to write.
45    pub fn parse(word: &str) -> Option<Self> {
46        match word.trim().to_ascii_lowercase().as_str() {
47            "pending" | "todo" => Some(Self::Pending),
48            "in_progress" | "in-progress" | "inprogress" | "doing" | "active" => {
49                Some(Self::InProgress)
50            }
51            "done" | "completed" | "complete" => Some(Self::Done),
52            "cancelled" | "canceled" | "dropped" | "skipped" => Some(Self::Cancelled),
53            _ => None,
54        }
55    }
56
57    /// `[ ]`, `[▸]`, `[x]`, `[-]` — one column, so a list reads down the left edge.
58    pub fn mark(self) -> &'static str {
59        match self {
60            Self::Pending => "[ ]",
61            Self::InProgress => "[~]",
62            Self::Done => "[x]",
63            Self::Cancelled => "[-]",
64        }
65    }
66
67    /// Finished, one way or the other: not worth a line in a handoff.
68    pub fn is_finished(self) -> bool {
69        matches!(self, Self::Done | Self::Cancelled)
70    }
71}
72
73/// One step.
74///
75/// `id` is the model's own word for the step and is what a merge patches by, so it is required and
76/// has to be unique: an id invented on its behalf would make the next merge unpredictable.
77/// `parent` groups steps into a phase — the phase is an item too, so a nested list needs no second
78/// shape.
79#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
80pub struct Item {
81    pub id: String,
82    pub content: String,
83    pub status: Status,
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub parent: Option<String>,
86}
87
88impl Item {
89    pub fn new(id: &str, content: &str, status: Status) -> Self {
90        Self {
91            id: id.to_string(),
92            content: content.to_string(),
93            status,
94            parent: None,
95        }
96    }
97}
98
99/// A whole plan: the steps in priority order, and the revision the store is at.
100///
101/// The revision is what keeps two surfaces honest. The dashboard polls and the terminal takes a
102/// live frame, so both can be looking at a snapshot; a client that applied a stale one can tell,
103/// which is the sort of disagreement nobody notices until they act on it.
104#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
105pub struct Plan {
106    pub revision: u64,
107    pub items: Vec<Item>,
108}
109
110/// The four numbers a result carries.
111#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
112pub struct Counts {
113    pub pending: usize,
114    pub in_progress: usize,
115    pub done: usize,
116    pub cancelled: usize,
117}
118
119impl Plan {
120    pub fn new(items: Vec<Item>) -> Self {
121        Self { revision: 0, items }
122    }
123
124    pub fn counts(&self) -> Counts {
125        let mut counts = Counts::default();
126        for item in &self.items {
127            match item.status {
128                Status::Pending => counts.pending += 1,
129                Status::InProgress => counts.in_progress += 1,
130                Status::Done => counts.done += 1,
131                Status::Cancelled => counts.cancelled += 1,
132            }
133        }
134        counts
135    }
136
137    /// The steps still worth showing, in order. Finished ones are left out of a handoff and out of
138    /// the "what is left" count, for the reason Hermes leaves them out of its todo injection: a
139    /// finished step in the handoff invites the model to do it again.
140    pub fn active(&self) -> impl Iterator<Item = &Item> {
141        self.items.iter().filter(|i| !i.status.is_finished())
142    }
143
144    /// The one step being done, if one is marked.
145    pub fn current(&self) -> Option<&Item> {
146        self.items.iter().find(|i| i.status == Status::InProgress)
147    }
148
149    /// `3/8` — finished out of total, which is what a status line reads as.
150    pub fn progress(&self) -> (usize, usize) {
151        let finished = self.items.iter().filter(|i| i.status.is_finished()).count();
152        (finished, self.items.len())
153    }
154}
155
156/// What is wrong with a list the model wrote, if anything.
157///
158/// Every answer names the item by its one-based position *and* its id, because the model wrote both
159/// and a sentence it can act on is a retry that works. An empty list is not an error: clearing a
160/// plan is a legitimate thing to do.
161pub fn validate(items: &[Item]) -> Result<(), String> {
162    for (index, item) in items.iter().enumerate() {
163        let position = index + 1;
164        if item.id.trim().is_empty() {
165            return Err(format!(
166                "item {position} has no `id`; give each step a short unique id, because a merge \
167                 patches by id"
168            ));
169        }
170        if item.content.trim().is_empty() {
171            return Err(format!(
172                "item {position} (`{}`) has no `content`; a step with nothing to do cannot be \
173                 done or dropped",
174                item.id
175            ));
176        }
177        if let Some(earlier) = items[..index].iter().position(|i| i.id == item.id) {
178            return Err(format!(
179                "items {} and {position} share the id `{}`; an id has to name one step",
180                earlier + 1,
181                item.id
182            ));
183        }
184    }
185    Ok(())
186}
187
188/// Patch an existing list by id: what the model names is replaced in place, what is new is
189/// appended, and what it does not mention stays.
190///
191/// In place, because position *is* priority: a model that marks step 5 done must not thereby move
192/// it to the end and reorder the work it has not done yet. That is the difference between this and
193/// a write that replaces the whole list, which is what a caller that passes no `merge` asks for.
194pub fn merge(existing: &[Item], incoming: &[Item]) -> Vec<Item> {
195    let mut out = existing.to_vec();
196    for item in incoming {
197        match out.iter_mut().find(|e| e.id == item.id) {
198            // The status and the words are what a merge is for; the parent goes with them. The
199            // position stays where it was.
200            Some(existing) => {
201                existing.content = item.content.clone();
202                existing.status = item.status;
203                existing.parent = item.parent.clone();
204            }
205            None => out.push(item.clone()),
206        }
207    }
208    out
209}
210
211/// Keep at most one step `in_progress`, the first in list order, and demote the rest to `pending`.
212///
213/// Normalised rather than refused: two steps in progress is a model being helpful, and an error
214/// teaches it to retry the same write. Demoting keeps the list honest and says which ids changed,
215/// so the model is not surprised by a status it did not write.
216pub fn one_in_progress(items: &mut [Item]) -> Vec<String> {
217    let mut seen = false;
218    let mut demoted = Vec::new();
219    for item in items.iter_mut() {
220        if item.status != Status::InProgress {
221            continue;
222        }
223        if seen {
224            item.status = Status::Pending;
225            demoted.push(item.id.clone());
226        } else {
227            seen = true;
228        }
229    }
230    demoted
231}
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236
237    fn item(id: &str, status: Status) -> Item {
238        Item::new(id, &format!("step {id}"), status)
239    }
240
241    #[test]
242    fn a_merge_patches_in_place_and_appends_what_is_new() {
243        let existing = vec![
244            item("a", Status::Pending),
245            item("b", Status::Pending),
246            item("c", Status::Pending),
247        ];
248        let mut done = item("b", Status::Done);
249        done.content = "step b, finished".to_string();
250        let out = merge(&existing, &[done, item("d", Status::Pending)]);
251
252        assert_eq!(
253            out.iter().map(|i| i.id.as_str()).collect::<Vec<_>>(),
254            ["a", "b", "c", "d"],
255            "b is still second: a merge does not reorder the work that is left"
256        );
257        assert_eq!(out[1].status, Status::Done);
258        assert_eq!(out[1].content, "step b, finished");
259        assert_eq!(out[0].status, Status::Pending, "an unmentioned step stays");
260    }
261
262    #[test]
263    fn a_merge_keeps_what_it_does_not_mention() {
264        let existing = vec![item("a", Status::Done), item("b", Status::Pending)];
265        let out = merge(&existing, &[]);
266        assert_eq!(out, existing);
267    }
268
269    #[test]
270    fn one_in_progress_keeps_the_first_and_names_what_it_demoted() {
271        let mut items = vec![
272            item("a", Status::InProgress),
273            item("b", Status::InProgress),
274            item("c", Status::InProgress),
275            item("d", Status::Pending),
276        ];
277        let demoted = one_in_progress(&mut items);
278        assert_eq!(demoted, ["b", "c"]);
279        assert_eq!(items[0].status, Status::InProgress);
280        assert_eq!(items[1].status, Status::Pending);
281        assert_eq!(items[2].status, Status::Pending);
282        assert_eq!(items[3].status, Status::Pending);
283    }
284
285    #[test]
286    fn one_in_progress_leaves_a_single_marked_step_alone() {
287        let mut items = vec![item("a", Status::Pending), item("b", Status::InProgress)];
288        assert!(one_in_progress(&mut items).is_empty());
289        assert_eq!(items[1].status, Status::InProgress);
290    }
291
292    #[test]
293    fn counts_and_progress_are_the_four_numbers_and_finished_over_total() {
294        let plan = Plan::new(vec![
295            item("a", Status::Done),
296            item("b", Status::InProgress),
297            item("c", Status::Pending),
298            item("d", Status::Cancelled),
299            item("e", Status::Pending),
300        ]);
301        assert_eq!(
302            plan.counts(),
303            Counts {
304                pending: 2,
305                in_progress: 1,
306                done: 1,
307                cancelled: 1,
308            }
309        );
310        assert_eq!(plan.progress(), (2, 5));
311        assert_eq!(plan.current().map(|i| i.id.as_str()), Some("b"));
312        assert_eq!(
313            plan.active().map(|i| i.id.as_str()).collect::<Vec<_>>(),
314            ["b", "c", "e"],
315            "a handoff carries what is left, in order"
316        );
317    }
318
319    #[test]
320    fn validation_names_the_item_that_is_wrong() {
321        assert_eq!(
322            validate(&[
323                item("a", Status::Pending),
324                Item::new("b", "  ", Status::Pending)
325            ])
326            .unwrap_err(),
327            "item 2 (`b`) has no `content`; a step with nothing to do cannot be done or dropped"
328        );
329        assert_eq!(
330            validate(&[
331                item("a", Status::Pending),
332                Item::new("", "x", Status::Pending)
333            ])
334            .unwrap_err(),
335            "item 2 has no `id`; give each step a short unique id, because a merge patches by id"
336        );
337        assert_eq!(
338            validate(&[
339                item("a", Status::Pending),
340                item("b", Status::Pending),
341                item("a", Status::Pending)
342            ])
343            .unwrap_err(),
344            "items 1 and 3 share the id `a`; an id has to name one step"
345        );
346        assert!(validate(&[]).is_ok(), "clearing a plan is legitimate");
347    }
348
349    #[test]
350    fn a_status_round_trips_and_accepts_the_spellings_a_model_writes() {
351        for status in [
352            Status::Pending,
353            Status::InProgress,
354            Status::Done,
355            Status::Cancelled,
356        ] {
357            assert_eq!(Status::parse(status.as_str()), Some(status));
358        }
359        assert_eq!(Status::parse("in-progress"), Some(Status::InProgress));
360        assert_eq!(Status::parse("Doing"), Some(Status::InProgress));
361        assert_eq!(Status::parse("completed"), Some(Status::Done));
362        assert_eq!(Status::parse("nonsense"), None);
363    }
364
365    #[test]
366    fn a_parent_groups_steps_without_a_second_shape() {
367        let mut phase = Item::new("p1", "The writer cluster", Status::InProgress);
368        phase.parent = None;
369        let mut step = Item::new("s1", "#535 array header", Status::Pending);
370        step.parent = Some("p1".to_string());
371        let plan = Plan::new(vec![phase, step]);
372        let nested: Vec<&Item> = plan
373            .items
374            .iter()
375            .filter(|i| i.parent.as_deref() == Some("p1"))
376            .collect();
377        assert_eq!(nested.len(), 1);
378        assert_eq!(nested[0].id, "s1");
379    }
380}