Skip to main content

kanbrain_core/cli/
init.rs

1//! `kb init`: makes the current folder a project. It gets its own `.brain/` with a card
2//! (`project.md`: its name and what it's about), is registered in the central brain so the kanban app
3//! shows it and can filter by it, and its coding agents are told how to use it, by a short section in
4//! their instructions file (`CLAUDE.md`, `AGENTS.md`). Without that section an agent doesn't know the
5//! brain exists until someone pastes it by hand.
6//!
7//! `kb deinit` undoes it, except for `.brain/` itself: its tasks, notes and decisions are the
8//! repository's, often committed with it, so deleting them is left to the user.
9
10use super::claude;
11use crate::projects;
12use crate::store::{self, PROJECT_DIR, Store};
13use anyhow::{Context, Result, bail};
14use std::fs;
15use std::path::Path;
16
17/// Instructions files agents read at the start of a session: Claude Code's, and the cross-agent one.
18const AGENT_FILES: [&str; 2] = ["CLAUDE.md", "AGENTS.md"];
19/// Created when the project has none of `AGENT_FILES`.
20const DEFAULT_AGENT_FILE: &str = "CLAUDE.md";
21/// Marks where the section starts and ends, so running `init` again updates it in place instead of
22/// adding another, and everything around it is left alone.
23const START: &str = "<!-- kanbrain:start -->";
24/// See [`START`].
25const END: &str = "<!-- kanbrain:end -->";
26
27/// The section. Read at the start of every session, so it's short, yet the whole CLI an agent needs is
28/// here. It has to win over the agent's own habits: Claude Code, for one, has a built-in to-do list,
29/// and works through a plan without a word to the board unless told the board is watched live.
30const SECTION: &str = concat!(
31    "\
32## Project memory: kanbrain
33
34This project's tasks, to-dos, decisions and notes live in `.brain/`, managed only with `kb`, kanbrain's CLI.
35The user follows them live on a kanban board: keep it showing what you're doing as you go, not at the end.
36
37- Start of session: `kb context`, unless its output is already above (a session hook adds it).
38- Work that changes the repository, or that the user should see, gets a task; questions and lookups don't. Find it
39  (`search WORDS`) or create it (`add TITLE`), then `start ID` (`add --start TITLE` does both). \"Todos\", a plan or
40  what's pending, in any language, are tasks here, one `add` each; your built-in to-do list isn't on the board, so
41  keep it for steps within the task you've started. A task with real work gets a body, `add --body - TITLE`:
42  **Goal** (what and why, a line or two) and **Done when** (what the user will check).
43- While working: `comment ID TEXT` when a step is done, when you find a cause, and before you stop (one or two
44  lines: what changed, what's next); `done ID` as soon as one is finished. Stopping before it is: `comment`, then
45  `park ID`. Doing isn't limited for you: several of your tasks can run at once. Never park, finish or move a task
46  you didn't start (the user's, or another session's).
47- Splitting work between subagents: give each part that changes the repository its own task, and run the board
48  yourself: `add --start` it before launching the subagent, then `comment` its result and `done` it. Subagents
49  only do the work; lookups and research get no task. `kb` commands can run in parallel.
50- Blocked on the user (a requirement, access, a choice that's theirs): `ask ID TEXT` parks the task with the
51  question; don't guess. A choice you shouldn't make alone and weren't asked to (architecture, a dependency,
52  storage, a public interface): `propose ID --body - TITLE`, Context / Options / Recommendation on stdin; it parks
53  the task until the user accepts or rejects it. Then, unless the user said they're away, if your tool can run a
54  command in the background and wake you when it exits, run `kb wait ID` (the task) that way and end your turn: it
55  prints the answer, or that there's none yet (then stop, don't wait again). Otherwise go on with other work or
56  stop; answers come first in `context`, under Answered: `show ID`, then pick the task up. If the user answers in
57  the chat instead, `start` the task (that ends the wait). `accept`/`reject` a decision only when the user tells
58  you to.
59- Choosing between approaches within your task: `search` for earlier decisions (only accepted ones are in force),
60  then `add --decision --link ID --body - TITLE` with Context / Decision / Consequences on stdin. Non-obvious findings: `add --note --link ID --body - TITLE`;
61  a problem someone has to fix is a task instead, in the repository that has to change.
62- `## Project` in `context` is the application's shared context. If it isn't described, or you're asked to set up
63  or load the brain, describe it first, from the README and manifests: `project describe -` (",
64    crate::projects::description_scope!(),
65    "). Rewrite it when the big picture changes (a service added, another storage), not after every change. With
66  several repositories, this one's role too: `project notes -`. How to build, test and run this repository, and its
67  code style, go in this file, outside this section: add them as you learn them.
68- Also: `show ID` (one entry in full), `describe ID TEXT`, `link ID OTHER…` (an id here, or `REPO#ID` in another
69  repository of the project); `-` reads text from stdin. Never edit the files in `.brain/` by hand: `kb` keeps
70  them consistent.",
71);
72
73/// Makes `root` a repository of project `name` (else the one its card names, else one named after
74/// the folder): creates its `.brain/` and card, registers it in `central` (joining the project's
75/// other repositories if it has some), creates the project's shared card if it's new, and writes or
76/// refreshes the section in each agent file of `root` (creating `CLAUDE.md` if there's none).
77/// Returns what it did, one line each.
78pub fn init(root: &Path, name: Option<&str>, central: &Path) -> Result<Vec<String>> {
79    let mut done = Vec::new();
80    let dir = root.join(PROJECT_DIR);
81    if dir.is_dir() {
82        done.push(format!("{} already exists", dir.display()));
83    } else {
84        Store::at(&dir)?;
85        done.push(format!("created {}: kanbrain uses it from here and every folder below", dir.display()));
86        done.push("commit it to share tasks, notes and decisions with the project, or add it to .gitignore".into());
87    }
88    // Registered by its absolute path, so the kanban app finds it from anywhere.
89    let dir = dir.canonicalize().with_context(|| format!("reading {}", dir.display()))?;
90    let folder = root.canonicalize().ok().and_then(|r| Some(r.file_name()?.to_string_lossy().into_owned()));
91    let card = projects::read_repo_card(&dir);
92    let project = match (name, &card, folder) {
93        (Some(name), _, _) => name.to_string(),
94        (None, Some((card, _)), _) => card.clone(),
95        (None, None, Some(folder)) => folder,
96        (None, None, None) => bail!("this folder has no name to give the project: `kb init NAME`"),
97    };
98    projects::register(central, &project, &dir)?;
99    match &card {
100        Some((name, _)) if *name == project => {}
101        Some((_, notes)) => projects::write_repo_card(&dir, &project, notes)?,
102        None => projects::write_repo_card(&dir, &project, "")?,
103    }
104    if projects::ensure_description(central, &project)? {
105        done.push(format!(
106            "created project `{project}`'s card in the central brain: describe the project with `kb project \
107             describe` or from the kanban app (or let the agent do it); all its repositories share it"
108        ));
109    }
110    let repos = projects::load(central)?;
111    let here = repos.iter().find(|r| r.dir == dir).map_or_else(|| project.clone(), |r| r.label(&repos));
112    let others: Vec<String> =
113        repos.iter().filter(|r| r.project == project && r.dir != dir).map(projects::Repo::name).collect();
114    if others.is_empty() {
115        done.push(format!(
116            "registered as project `{here}`: the kanban app shows it, and `--project {here}` reaches it"
117        ));
118    } else {
119        done.push(format!(
120            "registered as `{here}`, a repository of project `{project}` with {}: they share its card",
121            others.join(", ")
122        ));
123    }
124    let existing: Vec<&str> = AGENT_FILES.into_iter().filter(|name| root.join(name).is_file()).collect();
125    let targets = if existing.is_empty() { vec![DEFAULT_AGENT_FILE] } else { existing };
126    done.extend(write_agent_files(root, &targets)?.into_iter().map(|(_, line)| line));
127    if !on_path(std::env::var_os("PATH"), "kb") {
128        done.push(
129            "`kb` isn't on your PATH, and agents and the hooks run it: install the command line too \
130             (the installer's `--app both`)"
131                .into(),
132        );
133    }
134    Ok(done)
135}
136
137/// Brings every registered repository's agent instructions up to this version's: the section in each of its
138/// agent files that has one, and Claude Code's hooks where `CLAUDE.md` has it. A repository whose files have no
139/// section (taken out by hand) is left alone, and so is one whose folder is gone. Returns what changed, one
140/// line each, naming the repository.
141pub fn init_all(central: &Path) -> Result<Vec<String>> {
142    let repos = projects::load(central)?;
143    let mut done = Vec::new();
144    let mut current = 0;
145    for repo in repos.iter().filter(|r| r.dir.is_dir()) {
146        let Some(root) = repo.dir.parent() else { continue };
147        let targets: Vec<&str> = AGENT_FILES
148            .into_iter()
149            .filter(|name| fs::read_to_string(root.join(name)).is_ok_and(|text| text.contains(START)))
150            .collect();
151        if targets.is_empty() {
152            continue;
153        }
154        let changes: Vec<String> = write_agent_files(root, &targets)?
155            .into_iter()
156            .filter(|(changed, _)| *changed)
157            .map(|(_, line)| line)
158            .collect();
159        if changes.is_empty() {
160            current += 1;
161        }
162        let label = repo.label(&repos);
163        done.extend(changes.into_iter().map(|line| format!("{label}: {line}")));
164    }
165    if current > 0 {
166        done.push(format!("{current} more already had this version's instructions"));
167    }
168    Ok(done)
169}
170
171/// Writes or updates the section in each of `targets`, agent files of `root`, and Claude Code's hooks when
172/// `CLAUDE.md` is one of them. Returns what it did, one line each, and whether that changed anything.
173fn write_agent_files(root: &Path, targets: &[&str]) -> Result<Vec<(bool, String)>> {
174    let mut done = Vec::new();
175    // Claude Code's hooks go with its file; agents that read only AGENTS.md have no use for them.
176    if targets.contains(&"CLAUDE.md") {
177        done.push(match claude::add_hooks(root) {
178            Ok(claude::Change::Unchanged) => (false, format!("{} already has kanbrain's hooks", claude::SETTINGS)),
179            Ok(_) => (
180                true,
181                format!(
182                    "added kanbrain's hooks to {}: Claude Code reads `kb context` when a session starts and \
183                     after compaction, and an agent can't end its turn while the project isn't described",
184                    claude::SETTINGS
185                ),
186            ),
187            // The section still works without them, so a settings file it can't read doesn't stop init.
188            Err(e) => (false, format!("left out the Claude Code hooks: {e:#}")),
189        });
190    }
191    for &name in targets {
192        let path = root.join(name);
193        let before = fs::read_to_string(&path).unwrap_or_default();
194        let after = with_section(&before);
195        if after == before {
196            done.push((false, format!("{name} already tells agents about kanbrain")));
197            continue;
198        }
199        store::write_file(&path, &after)?;
200        let what = if before.is_empty() {
201            "created"
202        } else if before.contains(START) {
203            "updated"
204        } else {
205            "added to"
206        };
207        done.push((true, format!("{what} {name}: the \"Project memory\" section tells agents how to use the brain")));
208    }
209    Ok(done)
210}
211
212/// Whether a program named `name` is in one of the folders of `path`, a `PATH` value.
213fn on_path(path: Option<std::ffi::OsString>, name: &str) -> bool {
214    let file = format!("{name}{}", std::env::consts::EXE_SUFFIX);
215    path.is_some_and(|path| std::env::split_paths(&path).any(|dir| dir.join(&file).is_file()))
216}
217
218/// Takes the repository whose `.brain/` is `dir` out of the project registry, deleting the project's
219/// card if it was its last repository, and takes the section out of each agent file of the repository
220/// (deleting a file left empty, which `init` created). `.brain/` is kept. Returns what it did, one
221/// line each.
222pub fn deinit(dir: &Path, central: &Path) -> Result<Vec<String>> {
223    let Some(repo) = projects::unregister(central, dir)? else {
224        bail!("{} isn't a registered project: there's nothing to deinit", dir.display());
225    };
226    let mut done = vec![format!("unregistered {}: the kanban app no longer shows it", repo.dir.display())];
227    let others: Vec<String> =
228        projects::load(central)?.iter().filter(|r| r.project == repo.project).map(projects::Repo::name).collect();
229    if !others.is_empty() {
230        done.push(format!(
231            "project `{}` keeps its card for its other repositories: {}",
232            repo.project,
233            others.join(", ")
234        ));
235    } else if projects::remove_description(central, &repo.project)? {
236        done.push(format!("removed project `{}`'s card from the central brain", repo.project));
237    }
238    let Some(root) = repo.dir.parent().filter(|_| repo.dir.is_dir()) else {
239        done.push(format!("{} is gone, so there was nothing else to undo", repo.dir.display()));
240        return Ok(done);
241    };
242    match claude::remove_hooks(root) {
243        Ok(claude::Change::Unchanged) => {}
244        Ok(claude::Change::Written) => done.push(format!("removed kanbrain's hooks from {}", claude::SETTINGS)),
245        Ok(claude::Change::Removed) => done.push(format!("removed {}: it only held the hooks", claude::SETTINGS)),
246        Err(e) => done.push(format!("left the Claude Code hooks in place: {e:#}")),
247    }
248    for name in AGENT_FILES {
249        let path = root.join(name);
250        let Ok(before) = fs::read_to_string(&path) else { continue };
251        let after = without_section(&before);
252        if after == before {
253            continue;
254        }
255        if after.trim().is_empty() {
256            fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
257            done.push(format!("removed {name}: it only held the \"Project memory\" section"));
258        } else {
259            store::write_file(&path, &after)?;
260            done.push(format!("removed the \"Project memory\" section from {name}"));
261        }
262    }
263    done.push(format!(
264        "kept {}: commands run here still use it; delete it to drop its tasks, notes and decisions",
265        repo.dir.display()
266    ));
267    Ok(done)
268}
269
270/// Where the section is in `text`, with the line break after its end marker. It's the last start
271/// marker before the first end marker, so a stray unclosed start marker above it is never taken for
272/// the start and the text after it is kept.
273fn section(text: &str) -> Option<(usize, usize)> {
274    let end = text.find(END)? + END.len();
275    let start = text[..end].rfind(START)?;
276    Some((start, if text[end..].starts_with('\n') { end + 1 } else { end }))
277}
278
279/// `text` with the section between the markers: replaced where it already is, else appended after
280/// a blank line.
281fn with_section(text: &str) -> String {
282    let block = format!("{START}\n{SECTION}\n{END}\n");
283    if let Some((start, end)) = section(text) {
284        return format!("{}{block}{}", &text[..start], &text[end..]);
285    }
286    match text.trim_end() {
287        "" => block,
288        kept => format!("{kept}\n\n{block}"),
289    }
290}
291
292/// `text` without the section, and without the blank line `with_section` put before it.
293fn without_section(text: &str) -> String {
294    let Some((start, end)) = section(text) else { return text.to_string() };
295    let before = text[..start].trim_end();
296    let after = text[end..].trim_start_matches('\n');
297    match (before, after) {
298        ("", after) => after.to_string(),
299        (before, "") => format!("{before}\n"),
300        (before, after) => format!("{before}\n\n{after}"),
301    }
302}
303
304#[cfg(test)]
305#[path = "../../tests/cli/init.rs"]
306mod tests;