1use 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
17const AGENT_FILES: [&str; 2] = ["CLAUDE.md", "AGENTS.md"];
19const DEFAULT_AGENT_FILE: &str = "CLAUDE.md";
21const START: &str = "<!-- kanbrain:start -->";
24const END: &str = "<!-- kanbrain:end -->";
26
27const 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
73pub 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 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
137pub 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
171fn write_agent_files(root: &Path, targets: &[&str]) -> Result<Vec<(bool, String)>> {
174 let mut done = Vec::new();
175 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 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
212fn 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
218pub 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
270fn 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
279fn 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
292fn 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;