Skip to main content

kanbrain_core/brain/
mod.rs

1//! The brain: every entry in the data folder, and the operations on them. Time is always tracked: each task in `doing`
2//! has its clock running. `doing` holds one task started by a person (starting another is refused, not made room for);
3//! agents', which may run one per subagent, aren't limited. Each brain (the central one, each project repository) has
4//! its own, so work in different projects can run side by side. The command line and the desktop app both go through
5//! it, so tracking rules, tag colors and file names behave the same everywhere. It holds no screen state; the desktop
6//! app keeps its own.
7//!
8//! - [`actions`]: changes to entries and tags, each written to disk immediately.
9//! - [`report`]: time per task or tag over a period, from the tracked sessions.
10//! - [`calendar`]: each day's interactions over a period: sessions, moves, comments, new entries.
11
12mod actions;
13mod calendar;
14mod report;
15#[cfg(test)]
16#[path = "../../tests/brain.rs"]
17mod tests;
18
19pub use actions::NewEntry;
20pub use calendar::{Calendar, CalendarView, Day, Event, Show, What};
21pub use report::{Group, Report, ReportRow, ReportView, Slot};
22
23use crate::api::ApiError;
24use crate::model::{Author, Kind, RepoLink, Status, Task, now};
25use crate::projects::{self, ProjectInfo};
26use crate::store::{self, Store};
27use crate::tags::TagColors;
28use anyhow::{Context, Result};
29use std::path::{Path, PathBuf};
30
31/// Every entry in the data folder, with the tag colors.
32#[derive(Debug)]
33pub struct Brain {
34    /// The data folder entries are read from and written to.
35    pub store: Store,
36    /// Every entry, in no particular order.
37    pub tasks: Vec<Task>,
38    /// Tag → color assignments, kept in `tags.md`.
39    pub tag_colors: TagColors,
40    /// Files skipped by the last load, with why; the desktop app shows them.
41    pub warnings: Vec<String>,
42    /// What a project's repository knows of its project; `None` for the central brain.
43    pub project: Option<ProjectInfo>,
44    /// The central brain, which lists the projects and keeps their shared cards. `None` (as from
45    /// [`Brain::open`]) leaves the project's description and sibling repositories out.
46    pub central: Option<PathBuf>,
47    /// Who the comments and status changes made through this brain are recorded as: a person unless
48    /// the command line found it runs for an agent.
49    pub author: Author,
50}
51
52impl Brain {
53    /// Loads every entry and the tag colors.
54    pub fn open(store: Store) -> Result<Self> {
55        Self::open_with(store, None)
56    }
57
58    /// Loads every entry and the tag colors, knowing the central brain if `central` is given. A brain in an older
59    /// data format is migrated first, as it's opened to be changed (see [`crate::migrate`]).
60    fn open_with(store: Store, central: Option<PathBuf>) -> Result<Self> {
61        crate::migrate::migrate(&store)?;
62        let mut brain = Self {
63            store,
64            tasks: Vec::new(),
65            tag_colors: TagColors::default(),
66            warnings: Vec::new(),
67            project: None,
68            central,
69            author: Author::Human,
70        };
71        brain.reload()?;
72        Ok(brain)
73    }
74
75    /// Loads every entry and the tag colors as the files have them, writing nothing: for reading a brain
76    /// nobody is working in, such as another repository's to show links to it, or to complete a command
77    /// line. [`Brain::open`] also repairs what it finds, in files that may be in another git repository.
78    pub fn read_only(store: Store) -> Result<Self> {
79        let (tasks, warnings) = store.load()?;
80        let tag_colors = store.load_tag_colors()?;
81        Ok(Self { store, tasks, tag_colors, warnings, project: None, central: None, author: Author::Human })
82    }
83
84    /// Loads every entry, knowing the central brain at `central` (see [`Brain::central`]), and so the
85    /// project's other repositories, whose deleted entries' links it drops.
86    pub fn open_in(store: Store, central: &Path) -> Result<Self> {
87        Self::open_with(store, Some(central.to_path_buf()))
88    }
89
90    /// Re-reads every file from disk.
91    pub fn reload(&mut self) -> Result<()> {
92        let (tasks, warnings) = self.store.load()?;
93        self.tasks = tasks;
94        self.warnings = warnings;
95        self.renumber_shared_ids()?;
96        self.keep_one_person_doing()?;
97        self.drop_dangling_links()?;
98        self.remember_highest_id()?;
99        self.tag_colors = self.store.load_tag_colors()?;
100        self.project = projects::info(self.store.dir(), self.central.as_deref());
101        self.drop_dangling_repo_links()?;
102        self.sync_tag_colors()
103    }
104
105    /// The entry with this id.
106    pub fn task(&self, id: u32) -> Option<&Task> {
107        self.tasks.iter().find(|t| t.id == id)
108    }
109
110    /// Index into `tasks` of the entry with this id.
111    pub(crate) fn find(&self, id: u32) -> Option<usize> {
112        self.tasks.iter().position(|t| t.id == id)
113    }
114
115    /// Index into `tasks` of the entry with this id, or `NotFound`: for actions on an entry by its id.
116    pub(crate) fn index_of(&self, id: u32) -> Result<usize, ApiError> {
117        self.find(id).ok_or(ApiError::NotFound(id))
118    }
119
120    /// The tasks whose clock is running: those in `doing`.
121    pub fn running(&self) -> impl Iterator<Item = &Task> {
122        self.tasks.iter().filter(|t| t.is_running())
123    }
124
125    /// The task in `doing` that a person started, if any: there's one at most.
126    pub fn person_doing(&self) -> Option<u32> {
127        self.tasks.iter().find(|t| started_by_person(t)).map(|t| t.id)
128    }
129
130    /// Tasks with `status`, most recently moved there first.
131    pub fn column(&self, status: Status) -> Vec<&Task> {
132        let mut tasks: Vec<&Task> = self.tasks.iter().filter(|t| t.is_task() && t.status == status).collect();
133        tasks.sort_by(|a, b| b.status_since().cmp(&a.status_since()).then(b.id.cmp(&a.id)));
134        tasks
135    }
136
137    /// Entries that link to the one with this id, oldest first.
138    pub fn backlinks(&self, id: u32) -> Vec<&Task> {
139        let mut from: Vec<&Task> = self.tasks.iter().filter(|t| t.links.contains(&id)).collect();
140        from.sort_by_key(|t| t.id);
141        from
142    }
143
144    /// Entries related to the one with this id, whichever side stores the link: notes, then
145    /// decisions, then tasks, newest first within each.
146    pub fn related(&self, id: u32) -> Vec<&Task> {
147        let links = self.task(id).map_or(&[][..], |t| t.links.as_slice());
148        let mut related: Vec<&Task> =
149            self.tasks.iter().filter(|t| t.id != id && (links.contains(&t.id) || t.links.contains(&id))).collect();
150        related.sort_by_key(|t| (related_rank(t.kind), std::cmp::Reverse(t.id)));
151        related
152    }
153
154    /// Whether the two entries are related, whichever side stores the link.
155    pub fn are_related(&self, a: u32, b: u32) -> bool {
156        let links = |x: u32, y: u32| self.task(x).is_some_and(|t| t.links.contains(&y));
157        links(a, b) || links(b, a)
158    }
159
160    /// The brain of the project's repository named `repo`, read from disk without changing it, to check or
161    /// show links to its entries. `None` when this brain isn't in a project, the project has no such other
162    /// repository, or its folder is gone: it's never created here.
163    pub fn sibling(&self, repo: &str) -> Option<Brain> {
164        let (_, dir) = self.project.as_ref()?.siblings.iter().find(|(name, _)| name == repo)?;
165        if !dir.is_dir() {
166            return None;
167        }
168        Brain::read_only(Store::at(dir).ok()?).ok()
169    }
170
171    /// Entries of the project's other repositories related to the one with this id, whichever side
172    /// stores the link, as `(repository, entry)`: by repository, then as [`Brain::related`] orders them.
173    /// A repository that can't be read, or an entry deleted there since, is left out.
174    pub fn repo_related(&self, id: u32) -> Vec<(String, Task)> {
175        let Some(project) = &self.project else { return Vec::new() };
176        let links = self.task(id).map_or(&[][..], |t| t.repo_links.as_slice());
177        let here = RepoLink { repo: project.repo.clone(), id };
178        let mut related = Vec::new();
179        for (name, _) in &project.siblings {
180            let Some(other) = self.sibling(name) else { continue };
181            let mut found: Vec<Task> = other
182                .tasks
183                .into_iter()
184                .filter(|t| links.contains(&RepoLink { repo: name.clone(), id: t.id }) || t.repo_links.contains(&here))
185                .collect();
186            found.sort_by_key(|t| (related_rank(t.kind), std::cmp::Reverse(t.id)));
187            related.extend(found.into_iter().map(|t| (name.clone(), t)));
188        }
189        related
190    }
191
192    /// All tags in use, sorted.
193    pub fn all_tags(&self) -> Vec<String> {
194        let mut tags: Vec<String> = self.tasks.iter().flat_map(|t| t.tags.iter().cloned()).collect();
195        tags.sort();
196        tags.dedup();
197        tags
198    }
199
200    /// Takes the id for a new entry: one more than the highest ever given, by `last-id`, the entries in memory or
201    /// the entry files there are (one that doesn't parse holds its id too), whichever is higher, since another
202    /// program may have added one since this brain loaded.
203    /// It's recorded before the entry is written, so a failure in between leaves a gap, never a reused id.
204    fn take_id(&self) -> Result<u32> {
205        let highest = self.tasks.iter().map(|t| t.id).chain(self.store.file_ids()).max().unwrap_or(0);
206        // A hand-edited `- id:` or `last-id` can be the largest id there is; wrapping to 0 would hand it out again
207        // and again, each new entry over the last's file.
208        let id = highest.max(self.store.last_id()).checked_add(1).context("no ids left: the highest id is taken")?;
209        self.store.save_last_id(id)?;
210        Ok(id)
211    }
212
213    /// Links to entries of the project's other repositories that were deleted there (by hand, or by an
214    /// older version) are removed, as deleting in the app does. Only where that repository can be read:
215    /// one whose folder is missing for now, an unmounted disk say, keeps the links to it. So does an entry whose
216    /// file is there but doesn't parse, and one newer than the repository's `last-id`, as on a branch checked out
217    /// from before it was added: neither was deleted.
218    fn drop_dangling_repo_links(&mut self) -> Result<()> {
219        let mut repos: Vec<&str> = self.tasks.iter().flat_map(|t| &t.repo_links).map(|l| l.repo.as_str()).collect();
220        repos.sort_unstable();
221        repos.dedup();
222        let mut gone: Vec<RepoLink> = Vec::new();
223        for repo in repos {
224            let Some(other) = self.sibling(repo) else { continue };
225            // An older brain may have no `last-id`: the highest id of its files stands in.
226            let files = other.store.file_ids();
227            let last = other.store.last_id().max(files.iter().copied().max().unwrap_or(0));
228            for link in self.tasks.iter().flat_map(|t| &t.repo_links).filter(|l| l.repo == repo) {
229                let deleted = other.task(link.id).is_none() && !files.contains(&link.id) && link.id <= last;
230                if deleted && !gone.contains(link) {
231                    gone.push(link.clone());
232                }
233            }
234        }
235        for link in &gone {
236            self.drop_repo_links_to(link)?;
237        }
238        Ok(())
239    }
240
241    /// Two entries with one id, a sync tool's conflict copy (`0005-title (conflicted copy).md`) or one added on
242    /// two machines at once, would each take commands meant for the other, and saving one could overwrite the
243    /// other's file: all but one get new ids. The one kept is under its own name, else the oldest.
244    fn renumber_shared_ids(&mut self) -> Result<()> {
245        let own_name =
246            |t: &Task| t.path.as_ref().and_then(|p| p.file_name()).is_some_and(|n| *n == *store::file_name(t));
247        let mut order: Vec<usize> = (0..self.tasks.len()).collect();
248        let key = |i: usize| {
249            let t = &self.tasks[i];
250            (t.id, !own_name(t), t.created, t.path.as_ref())
251        };
252        order.sort_by(|&a, &b| key(a).cmp(&key(b)));
253        let mut seen = std::collections::HashSet::new();
254        for i in order {
255            if !seen.insert(self.tasks[i].id) {
256                let id = self.take_id()?;
257                let task = &mut self.tasks[i];
258                task.id = id;
259                self.store.save(task)?;
260            }
261        }
262        Ok(())
263    }
264
265    /// Records the highest id among the entries when `last-id` is behind it (a folder from an older
266    /// version, or entries copied in), so deleting the newest entry can't free its id.
267    fn remember_highest_id(&self) -> Result<()> {
268        let highest = self.tasks.iter().map(|t| t.id).max().unwrap_or(0);
269        if highest > self.store.last_id() {
270            self.store.save_last_id(highest)?;
271        }
272        Ok(())
273    }
274
275    /// `doing` holds one task started by a person: data from older versions, hand edits or a sync conflict
276    /// can leave several there, and all but the most recently started are parked. Agents' tasks are left
277    /// alone.
278    fn keep_one_person_doing(&mut self) -> Result<()> {
279        let doing = |t: &&mut Task| started_by_person(t);
280        let Some(latest) = self.tasks.iter_mut().filter(doing).map(|t| (t.status_since(), t.id)).max() else {
281            return Ok(());
282        };
283        let now = now();
284        for task in self.tasks.iter_mut().filter(doing) {
285            if (task.status_since(), task.id) != latest {
286                task.set_status(Status::Parked, now, self.author);
287                self.store.save(task)?;
288            }
289        }
290        Ok(())
291    }
292
293    /// Entries deleted outside kanbrain (by hand, `rm`, a sync) leave links to them behind; they're
294    /// removed so nothing points at an entry that's gone. One whose file is there but doesn't parse isn't gone.
295    fn drop_dangling_links(&mut self) -> Result<()> {
296        let mut ids = self.store.file_ids();
297        ids.extend(self.tasks.iter().map(|t| t.id));
298        for task in &mut self.tasks {
299            let before = task.links.len();
300            task.links.retain(|link| ids.contains(link));
301            if task.links.len() != before {
302                self.store.save(task)?;
303            }
304        }
305        Ok(())
306    }
307
308    /// Colors any new tags, oldest entries first so earlier tags claim colors first.
309    fn sync_tag_colors(&mut self) -> Result<()> {
310        let mut by_age: Vec<&Task> = self.tasks.iter().collect();
311        by_age.sort_by_key(|t| t.id);
312        if self.tag_colors.assign(by_age.iter().flat_map(|t| &t.tags)) {
313            self.store.save_tag_colors(&self.tag_colors)?;
314        }
315        Ok(())
316    }
317}
318
319/// Whether `task` is in `doing` because a person started it.
320fn started_by_person(task: &Task) -> bool {
321    task.is_task() && task.status == Status::Doing && task.started_by() == Author::Human
322}
323
324/// Where a kind's related entries are listed: notes and decisions (what a task needs to know) before tasks.
325fn related_rank(kind: Kind) -> u8 {
326    match kind {
327        Kind::Note => 0,
328        Kind::Decision => 1,
329        Kind::Task => 2,
330    }
331}