Skip to main content

kanbrain_core/api/
mod.rs

1//! Operations by entry id, for the command line: what an agent (or a script)
2//! does without a screen. They go through the same `Brain` actions as the desktop app, so tracking
3//! rules, tag colors and file names behave exactly as there.
4//!
5//! - [`json`]: entries as JSON, for scripts.
6//! - [`text`]: entries as compact text, for agents.
7//! - [`context`]: the markdown summary an agent reads at the start of a session.
8
9mod context;
10pub mod json;
11pub mod text;
12
13use crate::brain::{Brain, NewEntry};
14use crate::model::{Kind, RepoLink, Status, Task, one_line};
15use anyhow::Result;
16use std::fmt;
17
18/// Why an operation by id was refused, as the CLI prints it.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum ApiError {
21    /// No entry has this id.
22    NotFound(u32),
23    /// Only tasks have a status; this entry is a note or decision.
24    NotATask(u32, Kind),
25    /// Only decisions are accepted or rejected; this entry is a task or note.
26    NotADecision(u32, Kind),
27    /// A title, comment or description that is empty once trimmed.
28    Empty(&'static str),
29    /// A link from an entry to itself.
30    SelfLink(u32),
31    /// The entry has no comment at this index (counting from 0).
32    NoComment(u32, usize),
33    /// A link to a repository that isn't another one of this brain's project, or can't be read.
34    NoRepo(String),
35    /// A link to an entry that the other repository doesn't have.
36    NotFoundIn(RepoLink),
37    /// A person starting a task while `doing` holds the one a person started: its id.
38    DoingFull(u32),
39}
40
41impl fmt::Display for ApiError {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        match self {
44            ApiError::NotFound(id) => write!(f, "no entry #{id}"),
45            ApiError::NotATask(id, kind) => write!(f, "#{id} is a {}: only tasks have a status", kind.as_str()),
46            ApiError::NotADecision(id, kind) => {
47                write!(f, "#{id} is a {}: only decisions are accepted or rejected", kind.as_str())
48            }
49            ApiError::Empty(what) => write!(f, "the {what} is empty"),
50            ApiError::SelfLink(id) => write!(f, "#{id} can't link to itself"),
51            ApiError::NoComment(id, index) => write!(f, "#{id} has no comment {}", index + 1),
52            ApiError::NoRepo(repo) => write!(f, "`{repo}` isn't another repository of this project"),
53            ApiError::NotFoundIn(link) => write!(f, "no entry {link}"),
54            ApiError::DoingFull(id) => {
55                write!(f, "#{id} is in doing, and a person works on one task at a time: park or finish it first")
56            }
57        }
58    }
59}
60
61impl std::error::Error for ApiError {}
62
63impl Brain {
64    /// The entry with this id, or `NotFound`.
65    pub fn entry(&self, id: u32) -> Result<&Task, ApiError> {
66        self.task(id).ok_or(ApiError::NotFound(id))
67    }
68
69    /// Creates an entry and returns its id. Links must point at existing entries.
70    pub fn add(&mut self, new: NewEntry) -> Result<u32> {
71        if new.title.trim().is_empty() {
72            return Err(ApiError::Empty("title").into());
73        }
74        for &link in &new.links {
75            self.entry(link)?;
76        }
77        self.check_repo_links(&new.repo_links)?;
78        let new = NewEntry { title: one_line(&new.title), ..new };
79        self.create(new)
80    }
81
82    /// Moves a task to `status`; `doing` starts its clock (refused for a person who already runs a task).
83    pub fn change_status(&mut self, id: u32, status: Status) -> Result<()> {
84        self.set_status(id, status).map(drop)
85    }
86
87    /// Adds a timestamped comment, e.g. progress notes from an agent.
88    pub fn comment(&mut self, id: u32, text: &str) -> Result<()> {
89        self.add_comment(id, text).map(drop)
90    }
91
92    /// Replaces the description.
93    pub fn describe(&mut self, id: u32, text: &str) -> Result<()> {
94        self.set_description(id, text).map(drop)
95    }
96
97    /// Adds links from `id` to each of `others` and of `repo_links` (entries of the project's other
98    /// repositories), skipping ones it already has.
99    pub fn link(&mut self, id: u32, others: &[u32], repo_links: &[RepoLink]) -> Result<()> {
100        for &other in others {
101            if other == id {
102                return Err(ApiError::SelfLink(id).into());
103            }
104            self.entry(other)?;
105        }
106        self.check_repo_links(repo_links)?;
107        let index = self.index_of(id)?;
108        let task = &mut self.tasks[index];
109        for &other in others {
110            if !task.links.contains(&other) {
111                task.links.push(other);
112            }
113        }
114        for link in repo_links {
115            if !task.repo_links.contains(link) {
116                task.repo_links.push(link.clone());
117            }
118        }
119        self.store.save(task)
120    }
121
122    /// Checks that each link names another repository of this project, and an entry it has.
123    fn check_repo_links(&self, links: &[RepoLink]) -> Result<(), ApiError> {
124        for link in links {
125            let other = self.sibling(&link.repo).ok_or_else(|| ApiError::NoRepo(link.repo.clone()))?;
126            other.task(link.id).ok_or_else(|| ApiError::NotFoundIn(link.clone()))?;
127        }
128        Ok(())
129    }
130
131    /// Entries matching every whitespace-separated term in their title, tags, description or comments
132    /// (`#term` matches a tag prefix only), case-insensitive; tasks not done first, then newest first.
133    pub fn search(&self, query: &str) -> Vec<&Task> {
134        let terms: Vec<String> = query.split_whitespace().map(str::to_lowercase).collect();
135        let mut found: Vec<&Task> =
136            self.tasks.iter().filter(|t| terms.iter().all(|term| t.has_term(term, true))).collect();
137        found.sort_by_key(|t| (t.is_task() && t.status == Status::Done, std::cmp::Reverse(t.id)));
138        found
139    }
140}
141
142#[cfg(test)]
143#[path = "../../tests/api.rs"]
144mod tests;