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