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:
2//! each task in `doing` has its clock running. `doing` holds one task started by a person (starting
3//! another is refused, not made room for); agents', which may run one per subagent, aren't limited. Each brain (the central one, each
4//! project repository) has its own, so work in different projects can run side by side. The command line and
5//! the desktop app both go through it, so tracking rules, tag colors and file names behave
6//! the same everywhere. It holds no screen state; the desktop 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::Store;
27use crate::tags::TagColors;
28use anyhow::Result;
29use std::path::{Path, PathBuf};
30
31/// Every entry in the data folder, with the tag colors and settings.
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 settings.
54    pub fn open(store: Store) -> Result<Self> {
55        Self::open_with(store, None)
56    }
57
58    /// Loads every entry and the settings, 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 settings 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.keep_one_person_doing()?;
96        self.drop_dangling_links()?;
97        self.remember_highest_id()?;
98        self.tag_colors = self.store.load_tag_colors()?;
99        self.project = projects::info(self.store.dir(), self.central.as_deref());
100        self.drop_dangling_repo_links()?;
101        self.sync_tag_colors()
102    }
103
104    /// The entry with this id.
105    pub fn task(&self, id: u32) -> Option<&Task> {
106        self.tasks.iter().find(|t| t.id == id)
107    }
108
109    /// Index into `tasks` of the entry with this id.
110    pub(crate) fn find(&self, id: u32) -> Option<usize> {
111        self.tasks.iter().position(|t| t.id == id)
112    }
113
114    /// Index into `tasks` of the entry with this id, or `NotFound`: for actions on an entry by its id.
115    pub(crate) fn index_of(&self, id: u32) -> Result<usize, ApiError> {
116        self.find(id).ok_or(ApiError::NotFound(id))
117    }
118
119    /// The tasks whose clock is running: those in `doing`, as many as the limit at most.
120    pub fn running(&self) -> impl Iterator<Item = &Task> {
121        self.tasks.iter().filter(|t| t.is_running())
122    }
123
124    /// The task in `doing` that a person started, if any: there's one at most.
125    pub fn person_doing(&self) -> Option<u32> {
126        self.tasks.iter().find(|t| started_by_person(t)).map(|t| t.id)
127    }
128
129    /// Tasks with `status`, most recently moved there first.
130    pub fn column(&self, status: Status) -> Vec<&Task> {
131        let mut tasks: Vec<&Task> = self.tasks.iter().filter(|t| t.is_task() && t.status == status).collect();
132        tasks.sort_by(|a, b| b.status_since().cmp(&a.status_since()).then(b.id.cmp(&a.id)));
133        tasks
134    }
135
136    /// Entries that link to the one with this id, oldest first.
137    pub fn backlinks(&self, id: u32) -> Vec<&Task> {
138        let mut from: Vec<&Task> = self.tasks.iter().filter(|t| t.links.contains(&id)).collect();
139        from.sort_by_key(|t| t.id);
140        from
141    }
142
143    /// Entries related to the one with this id, whichever side stores the link: notes, then
144    /// decisions, then tasks, newest first within each.
145    pub fn related(&self, id: u32) -> Vec<&Task> {
146        let links = self.task(id).map_or(&[][..], |t| t.links.as_slice());
147        let mut related: Vec<&Task> =
148            self.tasks.iter().filter(|t| t.id != id && (links.contains(&t.id) || t.links.contains(&id))).collect();
149        related.sort_by_key(|t| (related_rank(t.kind), std::cmp::Reverse(t.id)));
150        related
151    }
152
153    /// Whether the two entries are related, whichever side stores the link.
154    pub fn are_related(&self, a: u32, b: u32) -> bool {
155        let links = |x: u32, y: u32| self.task(x).is_some_and(|t| t.links.contains(&y));
156        links(a, b) || links(b, a)
157    }
158
159    /// The brain of the project's repository named `repo`, read from disk without changing it, to check or
160    /// show links to its entries. `None` when this brain isn't in a project, the project has no such other
161    /// repository, or its folder is gone: it's never created here.
162    pub fn sibling(&self, repo: &str) -> Option<Brain> {
163        let (_, dir) = self.project.as_ref()?.siblings.iter().find(|(name, _)| name == repo)?;
164        if !dir.is_dir() {
165            return None;
166        }
167        Brain::read_only(Store::at(dir).ok()?).ok()
168    }
169
170    /// Entries of the project's other repositories related to the one with this id, whichever side
171    /// stores the link, as `(repository, entry)`: by repository, then as [`Brain::related`] orders them.
172    /// A repository that can't be read, or an entry deleted there since, is left out.
173    pub fn repo_related(&self, id: u32) -> Vec<(String, Task)> {
174        let Some(project) = &self.project else { return Vec::new() };
175        let links = self.task(id).map_or(&[][..], |t| t.repo_links.as_slice());
176        let here = RepoLink { repo: project.repo.clone(), id };
177        let mut related = Vec::new();
178        for (name, _) in &project.siblings {
179            let Some(other) = self.sibling(name) else { continue };
180            let mut found: Vec<Task> = other
181                .tasks
182                .into_iter()
183                .filter(|t| links.contains(&RepoLink { repo: name.clone(), id: t.id }) || t.repo_links.contains(&here))
184                .collect();
185            found.sort_by_key(|t| (related_rank(t.kind), std::cmp::Reverse(t.id)));
186            related.extend(found.into_iter().map(|t| (name.clone(), t)));
187        }
188        related
189    }
190
191    /// All tags in use, sorted.
192    pub fn all_tags(&self) -> Vec<String> {
193        let mut tags: Vec<String> = self.tasks.iter().flat_map(|t| t.tags.iter().cloned()).collect();
194        tags.sort();
195        tags.dedup();
196        tags
197    }
198
199    /// Takes the id for a new entry: one more than the highest ever given, by `last-id` or by the entries
200    /// in memory, whichever is higher, since another program may have added one since this brain loaded.
201    /// It's recorded before the entry is written, so a failure in between leaves a gap, never a reused id.
202    fn take_id(&self) -> Result<u32> {
203        let highest = self.tasks.iter().map(|t| t.id).max().unwrap_or(0);
204        let id = highest.max(self.store.last_id()) + 1;
205        self.store.save_last_id(id)?;
206        Ok(id)
207    }
208
209    /// Links to entries of the project's other repositories that were deleted there (by hand, or by an
210    /// older version) are removed, as deleting in the app does. Only where that repository can be read:
211    /// one whose folder is missing for now, an unmounted disk say, keeps the links to it.
212    fn drop_dangling_repo_links(&mut self) -> Result<()> {
213        let mut repos: Vec<&str> = self.tasks.iter().flat_map(|t| &t.repo_links).map(|l| l.repo.as_str()).collect();
214        repos.sort_unstable();
215        repos.dedup();
216        let mut gone: Vec<RepoLink> = Vec::new();
217        for repo in repos {
218            let Some(other) = self.sibling(repo) else { continue };
219            for link in self.tasks.iter().flat_map(|t| &t.repo_links).filter(|l| l.repo == repo) {
220                if other.task(link.id).is_none() && !gone.contains(link) {
221                    gone.push(link.clone());
222                }
223            }
224        }
225        for link in &gone {
226            self.drop_repo_links_to(link)?;
227        }
228        Ok(())
229    }
230
231    /// Records the highest id among the entries when `last-id` is behind it (a folder from an older
232    /// version, or entries copied in), so deleting the newest entry can't free its id.
233    fn remember_highest_id(&self) -> Result<()> {
234        let highest = self.tasks.iter().map(|t| t.id).max().unwrap_or(0);
235        if highest > self.store.last_id() {
236            self.store.save_last_id(highest)?;
237        }
238        Ok(())
239    }
240
241    /// `doing` holds one task started by a person: data from older versions, hand edits or a sync conflict
242    /// can leave several there, and all but the most recently started are parked. Agents' tasks are left
243    /// alone.
244    fn keep_one_person_doing(&mut self) -> Result<()> {
245        let doing = |t: &&mut Task| started_by_person(t);
246        let Some(latest) = self.tasks.iter_mut().filter(doing).map(|t| (t.status_since(), t.id)).max() else {
247            return Ok(());
248        };
249        let now = now();
250        for task in self.tasks.iter_mut().filter(doing) {
251            if (task.status_since(), task.id) != latest {
252                task.set_status(Status::Parked, now, self.author);
253                self.store.save(task)?;
254            }
255        }
256        Ok(())
257    }
258
259    /// Entries deleted outside kanbrain (by hand, `rm`, a sync) leave links to them behind; they're
260    /// removed so nothing points at an entry that's gone.
261    fn drop_dangling_links(&mut self) -> Result<()> {
262        let ids: std::collections::HashSet<u32> = self.tasks.iter().map(|t| t.id).collect();
263        for task in &mut self.tasks {
264            let before = task.links.len();
265            task.links.retain(|link| ids.contains(link));
266            if task.links.len() != before {
267                self.store.save(task)?;
268            }
269        }
270        Ok(())
271    }
272
273    /// Colors any new tags, oldest entries first so earlier tags claim colors first.
274    fn sync_tag_colors(&mut self) -> Result<()> {
275        let mut by_age: Vec<&Task> = self.tasks.iter().collect();
276        by_age.sort_by_key(|t| t.id);
277        if self.tag_colors.assign(by_age.iter().flat_map(|t| &t.tags)) {
278            self.store.save_tag_colors(&self.tag_colors)?;
279        }
280        Ok(())
281    }
282}
283
284/// Whether `task` is in `doing` because a person started it.
285fn started_by_person(task: &Task) -> bool {
286    task.is_task() && task.status == Status::Doing && task.started_by() == Author::Human
287}
288
289/// Where a kind's related entries are listed: notes and decisions (what a task needs to know) before tasks.
290fn related_rank(kind: Kind) -> u8 {
291    match kind {
292        Kind::Note => 0,
293        Kind::Decision => 1,
294        Kind::Task => 2,
295    }
296}