Skip to main content

kanbrain_core/model/
mod.rs

1//! Entries (tasks, notes and decisions), their links, status history, time-tracking sessions and comments.
2//!
3//! - [`markdown`]: reading and writing the task file format.
4//! - [`text`]: tags, file-name slugs and heading rules for user text.
5//! - [`time`]: timestamps, ages and durations.
6
7mod markdown;
8mod text;
9mod time;
10
11pub use markdown::{not_a_link, parse_links};
12pub use text::{counted, one_line, parse_tags, sanitize_comment, sanitize_description, slugify};
13#[cfg(test)]
14pub use time::parse_ts;
15pub use time::{covered, fmt_age, fmt_clock, fmt_dur, fmt_ts, now};
16
17use crate::enums::named_enum;
18use chrono::{DateTime, Duration, Local};
19use std::path::PathBuf;
20
21named_enum! {
22    /// Where a task stands. Declared in the order the task list shows them, so
23    /// `position()` is the sort key; the names are what task files contain.
24    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
25    pub enum Status {
26        /// Being worked on.
27        Doing => "doing",
28        /// Not started yet.
29        Todo => "todo",
30        /// Started, then set aside for now.
31        Parked => "parked",
32        /// Finished; hidden from the list by default.
33        Done => "done",
34    }
35}
36
37named_enum! {
38    /// Who made a change: the user, or a coding agent working through `kb`. Comments and status changes
39    /// record it, so the board tells them apart, and so a question an agent asked waits for a person.
40    #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
41    pub enum Author {
42        /// The user: in the kanban app, or `kb` typed at a terminal.
43        #[default]
44        Human => "human",
45        /// A coding agent, as `kb` finds from its environment.
46        Agent => "agent",
47    }
48}
49
50named_enum! {
51    /// Where a decision stands. An agent records the decisions within its task as accepted, and proposes
52    /// those it shouldn't take alone (architecture, dependencies, storage) for a person to accept or reject.
53    #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
54    pub enum DecisionState {
55        /// In force.
56        #[default]
57        Accepted => "accepted",
58        /// Waiting for a person to accept or reject it.
59        Proposed => "proposed",
60        /// Turned down: kept so the same approach isn't proposed again.
61        Rejected => "rejected",
62    }
63}
64
65named_enum! {
66    /// What an entry is. Only tasks have a status, history and sessions; notes and decisions are
67    /// documents that tasks and each other link to. Declared in the order `tab` cycles the list.
68    #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
69    pub enum Kind {
70        /// Something to do.
71        #[default]
72        Task => "task",
73        /// Something to remember: a finding, how something works, a snippet.
74        Note => "note",
75        /// Something decided, with its context and consequences (an ADR).
76        Decision => "decision",
77    }
78}
79
80/// One status change, as kept in the task's history.
81#[derive(Clone, Copy, Debug, PartialEq, Eq)]
82pub struct StatusChange {
83    /// When the status changed.
84    pub at: DateTime<Local>,
85    /// The status before.
86    pub from: Status,
87    /// The status after.
88    pub to: Status,
89    /// Who moved it.
90    pub by: Author,
91}
92
93/// One continuous stretch of tracked work on a task.
94#[derive(Clone, Debug, PartialEq, Eq)]
95pub struct Session {
96    /// When the session started.
97    pub start: DateTime<Local>,
98    /// `None` while the session is still running.
99    pub end: Option<DateTime<Local>>,
100}
101
102impl Session {
103    /// How long the session lasted, or has lasted so far if it's running.
104    pub fn duration(&self, now: DateTime<Local>) -> Duration {
105        (self.end.unwrap_or(now) - self.start).max(Duration::zero())
106    }
107
108    /// Part of this session that falls inside `[from, to)`.
109    pub fn overlap(&self, from: DateTime<Local>, to: DateTime<Local>, now: DateTime<Local>) -> Duration {
110        let (start, end) = self.span(from, to, now);
111        (end - start).max(Duration::zero())
112    }
113
114    /// Where this session starts and ends within `[from, to)`, a running one ending `now`; the end is
115    /// before the start when it falls outside.
116    pub fn span(
117        &self,
118        from: DateTime<Local>,
119        to: DateTime<Local>,
120        now: DateTime<Local>,
121    ) -> (DateTime<Local>, DateTime<Local>) {
122        (self.start.max(from), self.end.unwrap_or(now).min(to))
123    }
124}
125
126/// A timestamped comment on a task, like on a GitHub/GitLab issue.
127#[derive(Clone, Debug, PartialEq, Eq)]
128pub struct Comment {
129    /// When the comment was written.
130    pub created: DateTime<Local>,
131    /// Set when the body was changed after posting.
132    pub edited: Option<DateTime<Local>>,
133    /// The comment text (markdown).
134    pub body: String,
135    /// Who wrote it.
136    pub author: Author,
137    /// A question to the user: the task waits for a person's answer (see [`Task::asked`]).
138    pub question: bool,
139    /// The answer to the question before it, whoever wrote it: a verdict on the decision it asked about, which an
140    /// agent may give on the user's word.
141    pub answer: bool,
142    /// Words of the header's parentheses this version doesn't know, written back as they were.
143    pub unknown: Vec<String>,
144}
145
146impl Comment {
147    /// A plain comment by `author`.
148    pub fn new(created: DateTime<Local>, body: String, author: Author) -> Self {
149        Self { created, edited: None, body, author, question: false, answer: false, unknown: Vec::new() }
150    }
151}
152
153/// Where a question an agent asked on a task stands, while the task is parked waiting on it.
154#[derive(Clone, Copy, Debug, PartialEq, Eq)]
155pub enum Asked<'a> {
156    /// Nobody has answered the question yet.
157    Waiting(&'a Comment),
158    /// A person answered (the latest answer): the task can be picked up again.
159    Answered(&'a Comment),
160}
161
162impl Asked<'_> {
163    /// Where it stands, as the command line's text and JSON say it.
164    pub fn label(self) -> &'static str {
165        match self {
166            Self::Waiting(_) => "waiting for an answer",
167            Self::Answered(_) => "answered",
168        }
169    }
170}
171
172/// An entry in another repository of the same project, written `shop-api#3`: ids repeat across
173/// repositories, so the repository's name goes with it.
174#[derive(Clone, Debug, PartialEq, Eq)]
175pub struct RepoLink {
176    /// The repository's name in the project, as `kb init` registered it.
177    pub repo: String,
178    /// The entry's id there.
179    pub id: u32,
180}
181
182impl std::fmt::Display for RepoLink {
183    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
184        write!(f, "{}#{}", self.repo, self.id)
185    }
186}
187
188/// An entry: a task, note or decision. What it is, how it's tagged and linked, and for tasks,
189/// where it stands and how it got there.
190#[derive(Clone, Debug)]
191pub struct Task {
192    /// Unique number across all kinds, also the start of the file name.
193    pub id: u32,
194    /// Task, note or decision.
195    pub kind: Kind,
196    /// One-line title.
197    pub title: String,
198    /// Lowercase, without the leading `#`.
199    pub tags: Vec<String>,
200    /// Ids of related entries, in the order they were added. Deleting an entry removes the links to it.
201    pub links: Vec<u32>,
202    /// Related entries in the project's other repositories, in the order they were added. Nothing checks
203    /// them once written: the other repository may be elsewhere, or the entry deleted there since.
204    pub repo_links: Vec<RepoLink>,
205    /// Where the task stands.
206    pub status: Status,
207    /// Decisions only: whether it's in force, proposed or rejected.
208    pub decision: DecisionState,
209    /// When the task was created.
210    pub created: DateTime<Local>,
211    /// Free text describing the task.
212    pub description: String,
213    /// Oldest first.
214    pub comments: Vec<Comment>,
215    /// Every status change, oldest first.
216    pub history: Vec<StatusChange>,
217    /// Tracked work, oldest first; only the last one can be open, and only while the task is `doing`.
218    pub sessions: Vec<Session>,
219    /// File this task was loaded from / saved to.
220    pub path: Option<PathBuf>,
221    /// What the file holds that this version doesn't understand, written back as it was.
222    pub unknown: Unknown,
223}
224
225/// Fields, link forms and sections a newer version wrote, kept as written: otherwise an older `kb` or app
226/// saving the entry, for a comment or a status change, would drop them from the file.
227#[derive(Clone, Debug, Default)]
228pub struct Unknown {
229    /// `- key: value` lines before the first section, in file order.
230    pub meta: Vec<String>,
231    /// Words of `- links:` that are neither an id nor `REPO#ID`.
232    pub links: Vec<String>,
233    /// Other `##` sections, each from its heading line, in file order.
234    pub sections: Vec<String>,
235}
236
237impl Task {
238    /// A new `todo` task.
239    pub fn new(id: u32, title: String, now: DateTime<Local>) -> Self {
240        Self {
241            id,
242            kind: Kind::Task,
243            title,
244            tags: Vec::new(),
245            links: Vec::new(),
246            repo_links: Vec::new(),
247            unknown: Unknown::default(),
248            status: Status::Todo,
249            decision: DecisionState::Accepted,
250            created: now,
251            description: String::new(),
252            comments: Vec::new(),
253            history: Vec::new(),
254            sessions: Vec::new(),
255            path: None,
256        }
257    }
258
259    /// Moves the task to `status` and records the change, made `by` someone. Returns false if it already
260    /// was there. Leaving `doing` closes the open session, so a clock never keeps running on a task that
261    /// isn't being worked on.
262    pub fn set_status(&mut self, status: Status, now: DateTime<Local>, by: Author) -> bool {
263        if self.status == status {
264            return false;
265        }
266        if status != Status::Doing {
267            self.stop_session(now);
268        }
269        self.history.push(StatusChange { at: now, from: self.status, to: status, by });
270        self.status = status;
271        true
272    }
273
274    /// Whether the last session is still open.
275    pub fn is_running(&self) -> bool {
276        self.sessions.last().is_some_and(|s| s.end.is_none())
277    }
278
279    /// How long the open session has been running, if any.
280    pub fn running_for(&self, now: DateTime<Local>) -> Option<Duration> {
281        self.sessions.last().filter(|s| s.end.is_none()).map(|s| s.duration(now))
282    }
283
284    /// Opens a session now, unless one is already running. The caller moves the task to `doing`.
285    pub fn start_session(&mut self, now: DateTime<Local>) {
286        if !self.is_running() {
287            self.sessions.push(Session { start: now, end: None });
288        }
289    }
290
291    /// Closes the open session, if any.
292    pub fn stop_session(&mut self, now: DateTime<Local>) {
293        if let Some(session) = self.sessions.last_mut().filter(|s| s.end.is_none()) {
294            session.end = Some(now.max(session.start));
295        }
296    }
297
298    /// Time tracked in all sessions.
299    pub fn total(&self, now: DateTime<Local>) -> Duration {
300        self.sessions.iter().map(|s| s.duration(now)).sum()
301    }
302
303    /// Time tracked inside `[from, to)`: sessions are clipped to the range. For several tasks, see [`worked`].
304    pub fn time_between(&self, from: DateTime<Local>, to: DateTime<Local>, now: DateTime<Local>) -> Duration {
305        self.sessions.iter().map(|s| s.overlap(from, to, now)).sum()
306    }
307
308    /// Who last moved the task to `doing`: a person or an agent. A task in `doing` with no such change (from
309    /// an older version, or edited by hand) counts as a person's.
310    pub fn started_by(&self) -> Author {
311        self.history.iter().rev().find(|c| c.to == Status::Doing).map_or(Author::Human, |c| c.by)
312    }
313
314    /// When the status last changed (or the task was created, if never); used for sorting.
315    pub fn status_since(&self) -> DateTime<Local> {
316        self.history.last().map_or(self.created, |c| c.at)
317    }
318
319    /// The question this parked task waits on, or its answer. A question is the latest comment marked as
320    /// one; a person's comment after it answers it, as does a verdict on the decision it asked about. Starting the
321    /// task after either means it was picked up, so it's neither once the task is parked again for another reason.
322    pub fn asked(&self) -> Option<Asked<'_>> {
323        if !self.is_task() || self.status != Status::Parked {
324            return None;
325        }
326        let at = self.comments.iter().rposition(|c| c.question)?;
327        let question = &self.comments[at];
328        let answer = self.comments[at + 1..].iter().rev().find(|c| c.author == Author::Human || c.answer);
329        // Strictly after: times are whole seconds, and an agent that starts a task and asks at once does
330        // both in the same second, which isn't picking it up again.
331        let picked_up = self.history.iter().any(|c| c.to == Status::Doing && c.at > question.created);
332        match answer {
333            _ if picked_up => None,
334            Some(answer) => Some(Asked::Answered(answer)),
335            None => Some(Asked::Waiting(question)),
336        }
337    }
338
339    /// Whether this entry has a status, history and sessions (only tasks do).
340    pub fn is_task(&self) -> bool {
341        self.kind == Kind::Task
342    }
343
344    /// Search: every whitespace-separated term must match. `#term` matches a tag prefix;
345    /// anything else matches the title or a tag. Case-insensitive.
346    pub fn matches(&self, query: &str) -> bool {
347        query.split_whitespace().all(|term| self.has_term(&term.to_lowercase(), false))
348    }
349
350    /// Whether the entry has `term`, already lowercase: `#tag` (written as a tag is typed anywhere) a tag that
351    /// starts with it; anything else the title or a tag, and with `everywhere`, the description or a comment too.
352    pub(crate) fn has_term(&self, term: &str, everywhere: bool) -> bool {
353        match term.strip_prefix('#') {
354            Some("") => true,
355            Some(tag) => text::parse_tags(tag).first().is_some_and(|tag| self.tags.iter().any(|t| t.starts_with(tag))),
356            None => {
357                self.title.to_lowercase().contains(term)
358                    || self.tags.iter().any(|t| t.contains(term))
359                    || everywhere
360                        && (self.description.to_lowercase().contains(term)
361                            || self.comments.iter().any(|c| c.body.to_lowercase().contains(term)))
362            }
363        }
364    }
365}
366
367/// Time worked on any of `tasks` inside `[from, to)`: time two of them ran at once counts once (see
368/// [`covered`]), so agents' tasks running in parallel don't make a day longer than it was.
369pub fn worked<'a>(
370    tasks: impl IntoIterator<Item = &'a Task>,
371    from: DateTime<Local>,
372    to: DateTime<Local>,
373    now: DateTime<Local>,
374) -> Duration {
375    covered(tasks.into_iter().flat_map(|t| &t.sessions).map(|s| s.span(from, to, now)))
376}
377
378#[cfg(test)]
379#[path = "../../tests/model.rs"]
380mod tests;