Skip to main content

kanbrain_core/brain/
actions.rs

1//! Changes to entries, and writing reports. Every change is written to disk immediately.
2
3use super::{Brain, ReportView};
4use crate::api::ApiError;
5use crate::export;
6use crate::model::{
7    Asked, Author, Comment, DecisionState, Kind, RepoLink, Status, Task, now, one_line, sanitize_comment,
8    sanitize_description,
9};
10use crate::projects;
11use anyhow::Result;
12use std::path::PathBuf;
13
14/// The body a new decision starts with: the usual sections of an architecture decision record.
15const DECISION_TEMPLATE: &str = "### Context\n\nWhat forces us to decide, and what we know.\n\n\
16                                 ### Decision\n\nWhat we chose.\n\n\
17                                 ### Consequences\n\nWhat becomes easier or harder, and what we gave up.";
18
19/// What a new entry starts with, from the desktop app, the command line or an agent.
20#[derive(Debug, Default)]
21pub struct NewEntry {
22    /// Task, note or decision.
23    pub kind: Kind,
24    /// Must not be empty.
25    pub title: String,
26    /// Lowercase, without `#`.
27    pub tags: Vec<String>,
28    /// Ids of related entries.
29    pub links: Vec<u32>,
30    /// Related entries in the project's other repositories.
31    pub repo_links: Vec<RepoLink>,
32    /// `None` leaves it empty, or for a decision, the ADR sections to fill in.
33    pub description: Option<String>,
34    /// Start a task right away (moving it to `doing` and starting its clock).
35    pub start: bool,
36}
37
38impl Brain {
39    /// The index of the task with this id; notes and decisions are refused, since only tasks have a status.
40    fn task_index(&self, id: u32) -> Result<usize, ApiError> {
41        let index = self.index_of(id)?;
42        match self.tasks[index].kind {
43            Kind::Task => Ok(index),
44            kind => Err(ApiError::NotATask(id, kind)),
45        }
46    }
47
48    /// Moves a task to `status`, recording when. `doing` starts its clock; for a person, it's refused while
49    /// `doing` holds a task a person started: making room is their call, never a side effect. Agents start
50    /// as many as they work on. Returns whether anything changed.
51    pub fn set_status(&mut self, id: u32, status: Status) -> Result<bool> {
52        let index = self.task_index(id)?;
53        if status == Status::Doing {
54            return self.start_task(index);
55        }
56        if !self.tasks[index].set_status(status, now(), self.author) {
57            return Ok(false);
58        }
59        self.store.save(&mut self.tasks[index])?;
60        Ok(true)
61    }
62
63    /// Moves the task at `index` to `doing` and opens a session, if `doing` has room. A task already in
64    /// `doing` without a session (from an older version) starts its clock.
65    fn start_task(&mut self, index: usize) -> Result<bool> {
66        if self.tasks[index].is_running() {
67            return Ok(false);
68        }
69        if self.tasks[index].status != Status::Doing {
70            self.check_doing_room(self.author)?;
71        }
72        let now = now();
73        self.tasks[index].set_status(Status::Doing, now, self.author);
74        self.tasks[index].start_session(now);
75        self.store.save(&mut self.tasks[index])?;
76        Ok(true)
77    }
78
79    /// Replaces the project's description, on the card all its repositories share.
80    pub fn set_project_description(&mut self, text: &str) -> Result<()> {
81        let (Some(project), Some(central)) = (&mut self.project, &self.central) else {
82            anyhow::bail!("only a project's repository has a project description");
83        };
84        project.description = text.trim().to_string();
85        projects::write_description(central, &project.name, &project.description)
86    }
87
88    /// Replaces this repository's own notes about itself, on its `.brain/project.md`.
89    pub fn set_repo_notes(&mut self, text: &str) -> Result<()> {
90        let Some(project) = &mut self.project else { anyhow::bail!("the central brain isn't a project's repository") };
91        project.notes = text.trim().to_string();
92        let repo = projects::read_repo_card(self.store.dir()).and_then(|card| card.repo);
93        let card = projects::RepoCard { project: project.name.clone(), repo, notes: project.notes.clone() };
94        projects::write_repo_card(self.store.dir(), &card)
95    }
96
97    /// Refuses with [`ApiError::DoingFull`] a person starting a task while `doing` holds one a person
98    /// started; an agent always has room.
99    fn check_doing_room(&self, by: Author) -> Result<(), ApiError> {
100        match self.person_doing() {
101            Some(doing) if by == Author::Human => Err(ApiError::DoingFull(doing)),
102            _ => Ok(()),
103        }
104    }
105
106    /// Parks every running task a person started, when they stop for the day. Agents' keep running: they may
107    /// still be at work, and each agent closes its own.
108    pub fn park_people_running(&mut self) -> Result<()> {
109        let now = now();
110        for task in self.tasks.iter_mut().filter(|t| t.is_running() && t.started_by() == Author::Human) {
111            task.set_status(Status::Parked, now, self.author);
112            self.store.save(task)?;
113        }
114        Ok(())
115    }
116
117    /// Creates an entry with a new id and returns the id: a `todo` task, a note, or a decision
118    /// that starts from the ADR sections unless it comes with a description. The caller has checked
119    /// the title and links (see `Brain::add`).
120    pub(crate) fn create(&mut self, new: NewEntry) -> Result<u32> {
121        // Before anything is written: a task that can't start isn't created half-way.
122        if new.start && new.kind == Kind::Task {
123            self.check_doing_room(self.author)?;
124        }
125        let mut task = Task::new(self.take_id()?, new.title, now());
126        task.kind = new.kind;
127        task.description = match new.description {
128            Some(text) => sanitize_description(&text).0,
129            None if task.kind == Kind::Decision => DECISION_TEMPLATE.to_string(),
130            None => String::new(),
131        };
132        task.tags = new.tags;
133        task.links = new.links;
134        task.repo_links = new.repo_links;
135        self.store.save(&mut task)?;
136        let id = task.id;
137        self.tasks.push(task);
138        self.sync_tag_colors()?;
139        if new.start && new.kind == Kind::Task {
140            self.set_status(id, Status::Doing)?;
141        }
142        Ok(id)
143    }
144
145    /// Saves a new title and tags (a new title also renames the file).
146    pub fn update(&mut self, id: u32, title: &str, tags: Vec<String>) -> Result<()> {
147        let title = &one_line(title);
148        if title.is_empty() {
149            return Err(ApiError::Empty("title").into());
150        }
151        let index = self.index_of(id)?;
152        title.clone_into(&mut self.tasks[index].title);
153        self.tasks[index].tags = tags;
154        self.store.save(&mut self.tasks[index])?;
155        self.sync_tag_colors()
156    }
157
158    /// Deletes the entry's file, after removing the links other entries have to it. The links go first:
159    /// if a save fails, the entry is still there and nothing points nowhere.
160    pub fn delete(&mut self, id: u32) -> Result<()> {
161        let index = self.index_of(id)?;
162        for task in self.tasks.iter_mut().filter(|t| t.links.contains(&id)) {
163            task.links.retain(|&link| link != id);
164            self.store.save(task)?;
165        }
166        self.store.delete(&self.tasks[index])?;
167        self.tasks.remove(index);
168        Ok(())
169    }
170
171    /// Moves the entry to `to`, another brain (another project or repository, or the central one), and
172    /// returns its id there: a new one, since each brain numbers its own. Everything else comes
173    /// along (status, history, sessions, description, comments, tags) except its links, which name it by
174    /// its id here, so they're dropped on both sides (links to other repositories too). A running task keeps
175    /// its clock; one a person started needs room in `to`'s `doing`, as starting it there would.
176    ///
177    /// The entry is saved in `to` before it's deleted here: if something fails in between, it's in both
178    /// brains rather than in neither.
179    pub fn move_to(&mut self, id: u32, to: &mut Brain) -> Result<u32> {
180        let index = self.index_of(id)?;
181        if projects::same_dir(self.store.dir(), to.store.dir()) {
182            anyhow::bail!("#{id} is already there");
183        }
184        if self.tasks[index].status == Status::Doing {
185            to.check_doing_room(self.tasks[index].started_by())?;
186        }
187        let mut entry = Task {
188            id: to.take_id()?,
189            links: Vec::new(),
190            repo_links: Vec::new(),
191            path: None,
192            ..self.tasks[index].clone()
193        };
194        entry.unknown.links.clear();
195        to.store.save(&mut entry)?;
196        let new_id = entry.id;
197        to.tasks.push(entry);
198        to.sync_tag_colors()?;
199        self.delete(id)?;
200        Ok(new_id)
201    }
202
203    /// Removes every link to `link`, an entry of another repository of the project that's gone.
204    pub fn drop_repo_links_to(&mut self, link: &RepoLink) -> Result<()> {
205        for task in self.tasks.iter_mut().filter(|t| t.repo_links.contains(link)) {
206            task.repo_links.retain(|l| l != link);
207            self.store.save(task)?;
208        }
209        Ok(())
210    }
211
212    /// Relates entry `id` to entry `other_id` of `other`, another repository of this brain's project, or
213    /// unrelates them if they already are: the link is added here, and removed from whichever side stores
214    /// it. Returns whether they are related now.
215    pub fn toggle_repo_link(&mut self, id: u32, other: &mut Brain, other_id: u32) -> Result<bool> {
216        let (Some(here), Some(there)) = (&self.project, &other.project) else {
217            return Err(ApiError::NoRepo(other.store.dir().display().to_string()).into());
218        };
219        if here.name != there.name || here.repo == there.repo {
220            return Err(ApiError::NoRepo(there.repo.clone()).into());
221        }
222        let to = RepoLink { repo: there.repo.clone(), id: other_id };
223        let back = RepoLink { repo: here.repo.clone(), id };
224        let index = self.index_of(id)?;
225        let other_index = other.find(other_id).ok_or_else(|| ApiError::NotFoundIn(to.clone()))?;
226        let related = self.tasks[index].repo_links.contains(&to) || other.tasks[other_index].repo_links.contains(&back);
227        if !related {
228            self.tasks[index].repo_links.push(to);
229            self.store.save(&mut self.tasks[index])?;
230            return Ok(true);
231        }
232        for (brain, index, link) in [(&mut *self, index, &to), (&mut *other, other_index, &back)] {
233            let task = &mut brain.tasks[index];
234            if task.repo_links.contains(link) {
235                task.repo_links.retain(|l| l != link);
236                brain.store.save(task)?;
237            }
238        }
239        Ok(false)
240    }
241
242    /// Relates two entries, or unrelates them if they already are: the link is added to `id`, and
243    /// removed from whichever side stores it. Returns whether they are related now.
244    pub fn toggle_link(&mut self, id: u32, other: u32) -> Result<bool> {
245        if id == other {
246            return Err(ApiError::SelfLink(id).into());
247        }
248        for side in [id, other] {
249            self.find(side).ok_or(ApiError::NotFound(side))?;
250        }
251        let related = self.are_related(id, other);
252        for (from, to) in [(id, other), (other, id)] {
253            let Some(index) = self.find(from) else { continue };
254            let task = &mut self.tasks[index];
255            let before = task.links.len();
256            if related {
257                task.links.retain(|&l| l != to);
258            } else if from == id {
259                task.links.push(to);
260            }
261            if task.links.len() != before {
262                self.store.save(task)?;
263            }
264        }
265        Ok(!related)
266    }
267
268    /// Replaces the description. Returns whether `##` headings had to become `###`.
269    pub fn set_description(&mut self, id: u32, text: &str) -> Result<bool> {
270        let index = self.index_of(id)?;
271        let (text, demoted) = sanitize_description(text);
272        self.tasks[index].description = text;
273        self.store.save(&mut self.tasks[index])?;
274        Ok(demoted)
275    }
276
277    /// Adds a timestamped comment. Returns whether headings had to become `####`.
278    pub fn add_comment(&mut self, id: u32, text: &str) -> Result<bool> {
279        self.push_comment(id, text, Said::Comment)
280    }
281
282    /// Asks the user a question on a task and parks it, until a person answers with a comment (see
283    /// [`Task::asked`]). Returns whether headings had to become `####`.
284    pub fn ask(&mut self, id: u32, question: &str) -> Result<bool> {
285        let index = self.task_index(id)?;
286        let demoted = self.push_comment(id, question, Said::Question)?;
287        if self.tasks[index].set_status(Status::Parked, now(), self.author) {
288            self.store.save(&mut self.tasks[index])?;
289        }
290        Ok(demoted)
291    }
292
293    /// Proposes a decision for task `id`, which waits for a person to accept or reject it: the decision
294    /// is created as proposed, linked to the task, and the task asks about it and is parked. Returns
295    /// the decision's id.
296    pub fn propose(&mut self, id: u32, decision: NewEntry) -> Result<u32> {
297        self.task_index(id)?;
298        let mut links = decision.links;
299        if !links.contains(&id) {
300            links.insert(0, id);
301        }
302        let title = one_line(&decision.title);
303        let new = NewEntry { kind: Kind::Decision, title: title.clone(), links, start: false, ..decision };
304        let decision = self.add(new)?;
305        let index = self.index_of(decision)?;
306        self.tasks[index].decision = DecisionState::Proposed;
307        self.store.save(&mut self.tasks[index])?;
308        self.ask(id, &format!("Proposed decision #{decision}, {title}: accept or reject it."))?;
309        Ok(decision)
310    }
311
312    /// Accepts or rejects decision `id`, with `reason` (needed to reject), and answers the tasks that wait
313    /// on it. A decision can be reconsidered: an accepted one rejected later, and back. Returns false if it
314    /// already was in `state`.
315    pub fn resolve(&mut self, id: u32, state: DecisionState, reason: &str) -> Result<bool> {
316        let index = self.index_of(id)?;
317        let decision = &self.tasks[index];
318        if decision.kind != Kind::Decision {
319            return Err(ApiError::NotADecision(id, decision.kind).into());
320        }
321        if decision.decision == state {
322            return Ok(false);
323        }
324        if state == DecisionState::Rejected && reason.trim().is_empty() {
325            return Err(ApiError::Empty("reason").into());
326        }
327        let title = decision.title.clone();
328        let verdict = match state {
329            DecisionState::Accepted => "Accepted",
330            DecisionState::Rejected => "Rejected",
331            DecisionState::Proposed => "Proposed again",
332        };
333        let said = |what: &str| match reason.trim() {
334            "" => format!("{what}."),
335            reason => format!("{what}: {reason}"),
336        };
337        self.tasks[index].decision = state;
338        self.store.save(&mut self.tasks[index])?;
339        self.push_comment(id, &said(verdict), Said::Comment)?;
340        // The tasks whose question is about this decision, as `propose` asks it ("Proposed decision #5, …"): a task
341        // that only links it waits on something else.
342        let about = format!("#{id}");
343        let waiting: Vec<u32> = self
344            .tasks
345            .iter()
346            .filter(|t| match t.asked() {
347                Some(Asked::Waiting(question)) => {
348                    self.are_related(t.id, id)
349                        // Words as a link is written, so `web#6`, another repository's entry, isn't `#6`.
350                        && question
351                            .body
352                            .split(|c: char| !(c.is_alphanumeric() || matches!(c, '#' | '-' | '_')))
353                            .any(|w| w == about)
354                }
355                _ => false,
356            })
357            .map(|t| t.id)
358            .collect();
359        for task in waiting {
360            self.push_comment(task, &said(&format!("{verdict} decision #{id}, {title}")), Said::Answer)?;
361        }
362        Ok(true)
363    }
364
365    /// Adds a comment by this brain's author, saying what `said` says it is. Returns whether headings had to become
366    /// `####`.
367    fn push_comment(&mut self, id: u32, text: &str, said: Said) -> Result<bool> {
368        let index = self.index_of(id)?;
369        let (body, demoted) = sanitize_comment(text);
370        if body.is_empty() {
371            return Err(ApiError::Empty(if said == Said::Question { "question" } else { "comment" }).into());
372        }
373        let (question, answer) = (said == Said::Question, said == Said::Answer);
374        let comment = Comment { question, answer, ..Comment::new(now(), body, self.author) };
375        self.tasks[index].comments.push(comment);
376        self.store.save(&mut self.tasks[index])?;
377        Ok(demoted)
378    }
379
380    /// Changes a comment's text and marks it edited, unless the text is unchanged.
381    /// Returns whether headings had to become `####`.
382    pub fn update_comment(&mut self, id: u32, comment: usize, text: &str) -> Result<bool> {
383        let index = self.index_of(id)?;
384        let (body, demoted) = sanitize_comment(text);
385        if body.is_empty() {
386            return Err(ApiError::Empty("comment").into());
387        }
388        let task = &mut self.tasks[index];
389        let Some(existing) = task.comments.get_mut(comment) else {
390            return Err(ApiError::NoComment(id, comment).into());
391        };
392        if existing.body != body {
393            existing.body = body;
394            existing.edited = Some(now());
395            self.store.save(task)?;
396        }
397        Ok(demoted)
398    }
399
400    /// Deletes a comment.
401    pub fn delete_comment(&mut self, id: u32, comment: usize) -> Result<()> {
402        let index = self.index_of(id)?;
403        let task = &mut self.tasks[index];
404        if comment >= task.comments.len() {
405            return Err(ApiError::NoComment(id, comment).into());
406        }
407        task.comments.remove(comment);
408        self.store.save(task)
409    }
410
411    /// Where the markdown export of `view` goes: `<data dir>/reports/<name>.md`.
412    pub fn report_path(&self, view: &ReportView) -> PathBuf {
413        self.store.reports_dir().join(export::file_name(view))
414    }
415
416    /// Writes the report as markdown and returns the path.
417    pub fn export_report(&self, view: &ReportView) -> Result<PathBuf> {
418        self.write_report(&self.report(view), view)
419    }
420
421    /// Writes `report`, made for `view`, to this brain's `reports/` as markdown and returns the path;
422    /// for a report computed elsewhere, such as several brains' merged.
423    pub fn write_report(&self, report: &super::Report, view: &ReportView) -> Result<PathBuf> {
424        let markdown = export::to_markdown(report, view, now());
425        let path = self.report_path(view);
426        crate::store::write_file(&path, &markdown)?;
427        Ok(path)
428    }
429}
430
431/// What a comment is to the task it's on.
432#[derive(Clone, Copy, PartialEq, Eq)]
433enum Said {
434    /// Anything said.
435    Comment,
436    /// A question the task then waits on.
437    Question,
438    /// The answer to the question it waits on.
439    Answer,
440}