mod doctor;
mod hooks;
mod profile;
pub use doctor::doctor;
use std::ffi::OsString;
use std::fs;
use std::io::{self, BufRead, IsTerminal, Write};
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use ratatui::crossterm::style::{Color, Print, ResetColor, SetForegroundColor};
use ratatui::crossterm::{queue, terminal};
use serde_json::{Value, json};
use unicode_width::UnicodeWidthStr;
use crate::agents::{claude, codex};
use crate::store::Store;
use profile::Profile;
const CLAUDE_HOOK: &str = "kaeru hook claude";
const CODEX_HOOK: &str = "kaeru hook codex";
const CODEX_HOOK_NAME: &str = "kaeru: remember this session's tab";
struct HookFile {
agent: &'static str,
path: PathBuf,
command: &'static str,
name: Option<&'static str>,
}
impl HookFile {
fn agent_is_set_up(&self) -> bool {
self.path.parent().is_some_and(Path::is_dir)
}
}
fn hook_files() -> Vec<HookFile> {
let mut files = Vec::new();
if let Some(dir) = claude::config_dir() {
files.push(HookFile {
agent: "Claude Code",
path: dir.join("settings.json"),
command: CLAUDE_HOOK,
name: None,
});
}
if let Some(home) = codex::home_dir() {
files.push(HookFile {
agent: "Codex",
path: home.join("hooks.json"),
command: CODEX_HOOK,
name: Some(CODEX_HOOK_NAME),
});
}
files
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Outcome {
Ok,
Added,
Skipped,
Note,
Problem,
}
impl Outcome {
fn label(self) -> &'static str {
match self {
Outcome::Ok => "ok",
Outcome::Added => "added",
Outcome::Skipped => "skipped",
Outcome::Note => "note",
Outcome::Problem => "problem",
}
}
fn color(self) -> Color {
match self {
Outcome::Ok | Outcome::Added => Color::Green,
Outcome::Skipped | Outcome::Note => Color::Yellow,
Outcome::Problem => Color::Red,
}
}
}
struct Checklist {
color: bool,
width: usize,
columns: Option<usize>,
problems: usize,
parts: usize,
set_up: usize,
added: usize,
}
impl Checklist {
fn new(names: &[&str]) -> Self {
let terminal = io::stdout().is_terminal();
Self {
color: crate::tui::colors_wanted() && terminal,
width: name_column(names),
columns: terminal
.then(|| terminal::size().ok())
.flatten()
.map(|(columns, _)| usize::from(columns)),
problems: 0,
parts: 0,
set_up: 0,
added: 0,
}
}
fn part(&mut self, outcome: Outcome, name: &str, text: &str) {
self.parts += 1;
if matches!(outcome, Outcome::Ok | Outcome::Added) {
self.set_up += 1;
}
if outcome == Outcome::Added {
self.added += 1;
}
self.line(outcome, name, text);
}
fn line(&mut self, outcome: Outcome, name: &str, text: &str) {
if outcome == Outcome::Problem {
self.problems += 1;
}
let label = format!("{:<9}", outcome.label());
let indent = LABEL_WIDTH + self.width;
let room = self
.columns
.map_or(usize::MAX, |columns| columns.saturating_sub(indent + 1));
let lines: Vec<String> = text.split('\n').flat_map(|part| wrap(part, room)).collect();
let text = lines.join(&format!("\n{}", " ".repeat(indent)));
let rest = format!("{name:<width$}{text}\n", width = self.width);
let mut out = io::stdout().lock();
let _ = if self.color {
queue!(
out,
SetForegroundColor(outcome.color()),
Print(label),
ResetColor,
Print(rest)
)
} else {
queue!(out, Print(label), Print(rest))
};
let _ = out.flush();
}
}
const LABEL_WIDTH: usize = 9;
fn wrap(text: &str, width: usize) -> Vec<String> {
if width < 20 {
return vec![text.to_string()];
}
let mut lines = Vec::new();
let mut line = String::new();
for word in text.split(' ') {
if !line.is_empty() && line.width() + 1 + word.width() > width {
lines.push(std::mem::take(&mut line));
}
if !line.is_empty() {
line.push(' ');
}
line.push_str(word);
}
lines.push(line);
lines
}
fn name_column(names: &[&str]) -> usize {
names
.iter()
.map(|name| name.chars().count())
.max()
.unwrap_or(0)
+ 2
}
fn summary(parts: usize, set_up: usize, added: usize) -> String {
let check = "Open a new tab and run kaeru doctor to check it.";
if set_up < parts {
format!("Set up {set_up} of {parts}. To add the rest, run kaeru install again. {check}")
} else if added == 0 {
format!("Everything was set up already. {check}")
} else {
format!("Everything is set up. {check}")
}
}
fn loads_kaeru(kind: profile::Kind) -> &'static str {
match kind {
profile::Kind::PowerShell => "the profile loads kaeru",
profile::Kind::Bash => "~/.bashrc loads kaeru",
profile::Kind::Zsh => "~/.zshrc loads kaeru",
profile::Kind::Fish => "config.fish loads kaeru",
}
}
fn explain(name: &str, change: &str, path: &Path) {
println!(
"\n{name}: {change}\n {}",
crate::tui::home_as_tilde(&path.display().to_string())
);
}
pub fn install() -> Result<()> {
require_terminal("kaeru install")?;
crate::tui::greet()?;
let profiles = profile::profiles();
let files = hook_files();
let names: Vec<&str> = profiles
.iter()
.map(|profile| profile.shell)
.chain(files.iter().map(|file| file.agent))
.collect();
let mut list = Checklist::new(&names);
if profiles.is_empty() {
list.line(
Outcome::Note,
"Shells",
"none that kaeru sets up: PowerShell, bash, zsh or fish",
);
}
for profile in &profiles {
install_profile(&mut list, profile)?;
}
for file in &files {
if !file.agent_is_set_up() {
list.line(Outcome::Note, file.agent, "isn't set up on this computer");
continue;
}
if file.command == CODEX_HOOK
&& let Some(config) = codex_config_with_hooks()
{
explain_codex_config(&mut list, &config);
continue;
}
if install_hook(&mut list, file)? && file.command == CODEX_HOOK {
list.line(
Outcome::Note,
file.agent,
&format!("trust the hook {CODEX_HOOK_NAME:?} when Codex asks about it"),
);
}
}
if files
.iter()
.any(|file| file.command == CODEX_HOOK && file.agent_is_set_up())
{
install_codex_no_daemon(&mut list)?;
}
println!("\n{}", summary(list.parts, list.set_up, list.added));
Ok(())
}
fn install_codex_no_daemon(list: &mut Checklist) -> Result<()> {
let store = Store::open()?;
let mut config = store.config();
let started = "tracked tabs start it with --no-daemon";
if config.codex_no_daemon {
list.line(Outcome::Ok, "Codex", started);
return Ok(());
}
println!(
"\nCodex: started with --no-daemon, a session runs in its tab, so kaeru knows exactly \
where it is.\n Codex's remote control doesn't work in those sessions."
);
if ask(" Start Codex with --no-daemon in the tabs that kaeru tracks?")? {
config.codex_no_daemon = true;
store.save_config(&config)?;
list.line(Outcome::Added, "Codex", started);
} else {
list.line(
Outcome::Skipped,
"Codex",
"kaeru works out a session's tab from when and where it started",
);
}
Ok(())
}
pub fn uninstall() -> Result<()> {
require_terminal("kaeru uninstall")?;
for profile in profile::profiles() {
let bytes = read_or_empty(&profile.path)?;
if profile::has_line(&bytes, profile.kind)?
&& ask(&format!(
"Remove kaeru's lines from the {} profile, {}?",
profile.shell,
profile.path.display()
))?
{
write_file(&profile.path, &profile::remove_line(&bytes, profile.kind)?)?;
println!("Removed.");
}
}
for file in hook_files() {
let mut root = read_json(&file.path)?;
if hooks::has_hook(&root, file.command)
&& ask(&format!(
"Remove kaeru's hook from {}'s {}?",
file.agent,
file.path.display()
))?
{
hooks::remove_hook(&mut root, file.command);
write_json(&file.path, &root)?;
let _ = fs::remove_file(backup_of(&file.path));
println!("Removed.");
}
}
if let Some(config) = codex_config_with_hooks()
&& fs::read_to_string(&config).is_ok_and(|text| text.contains(CODEX_HOOK))
{
println!(
"{} runs kaeru's hook. Take out its [[hooks.SessionStart]] entry with {CODEX_HOOK:?} \
yourself.",
config.display()
);
}
let store = Store::open()?;
if ask_default_no(&format!(
"Also delete kaeru's notes, log and options, in {}?",
store.dir().display()
))? {
store.delete_all()?;
println!("Deleted.");
}
Ok(())
}
fn install_profile(list: &mut Checklist, profile: &Profile) -> Result<()> {
let bytes = read_or_empty(&profile.path)?;
let loads = loads_kaeru(profile.kind);
if profile::has_line(&bytes, profile.kind)? {
list.part(Outcome::Ok, profile.shell, loads);
} else {
explain(
profile.shell,
"kaeru adds 2 lines to the end of",
&profile.path,
);
if ask(" Add them?")? {
write_file(&profile.path, &profile::add_line(&bytes, profile.kind)?)?;
list.part(Outcome::Added, profile.shell, loads);
} else {
list.part(
Outcome::Skipped,
profile.shell,
"kaeru won't know about its tabs",
);
}
}
if let Some(problem) = bash_profile_problem(profile) {
list.line(Outcome::Problem, profile.shell, &problem);
}
Ok(())
}
fn bash_profile_problem(profile: &Profile) -> Option<String> {
if profile.kind != profile::Kind::Bash {
return None;
}
let bash_profile = profile.path.parent()?.join(".bash_profile");
let text = fs::read_to_string(&bash_profile).ok()?;
(!profile::reads_bashrc(&text)).then(|| {
format!(
"{} doesn't read ~/.bashrc, and login shells, such as Git Bash's, read only that file, so add this line to \
it:\n test -f ~/.bashrc && . ~/.bashrc",
bash_profile.display()
)
})
}
fn install_hook(list: &mut Checklist, file: &HookFile) -> Result<bool> {
let mut root = read_json(&file.path)?;
let runs = "runs kaeru's hook";
if hooks::has_hook(&root, file.command) {
list.part(Outcome::Ok, file.agent, runs);
return Ok(false);
}
explain(
file.agent,
&format!(
"kaeru adds a SessionStart hook that runs {:?} to",
file.command
),
&file.path,
);
if !ask(" Add it?")? {
list.part(
Outcome::Skipped,
file.agent,
"no hook, so its sessions won't come back",
);
return Ok(false);
}
hooks::add_hook(&mut root, file.command, file.name)
.with_context(|| format!("can't add the hook to {}", file.path.display()))?;
if file.path.exists() {
fs::copy(&file.path, backup_of(&file.path))?;
println!(
" The file as it was is kept as {}.",
crate::tui::home_as_tilde(&backup_of(&file.path).display().to_string())
);
}
write_json(&file.path, &root)?;
list.part(Outcome::Added, file.agent, runs);
Ok(true)
}
fn codex_config_with_hooks() -> Option<PathBuf> {
let config = codex::home_dir()?.join("config.toml");
let text = fs::read_to_string(&config).ok()?;
declares_hooks(&text).then_some(config)
}
fn declares_hooks(config: &str) -> bool {
let Ok(config) = config.parse::<toml::Table>() else {
return false;
};
config
.get("hooks")
.and_then(toml::Value::as_table)
.is_some_and(|hooks| {
hooks.iter().any(|(key, value)| {
key != "state" && value.as_array().is_some_and(|groups| !groups.is_empty())
})
})
}
fn explain_codex_config(list: &mut Checklist, config: &Path) {
if fs::read_to_string(config).is_ok_and(|text| text.contains(CODEX_HOOK)) {
list.part(Outcome::Ok, "Codex", "runs kaeru's hook, from config.toml");
return;
}
println!(
"\nCodex: declares hooks in {} already, and warns when hooks.json has hooks too. \
Add this to it yourself, and trust the hook when Codex asks about it:\n\n\
[[hooks.SessionStart]]\n\n[[hooks.SessionStart.hooks]]\ntype = \"command\"\n\
command = {CODEX_HOOK:?}\nstatusMessage = {CODEX_HOOK_NAME:?}\n",
crate::tui::home_as_tilde(&config.display().to_string())
);
list.part(
Outcome::Skipped,
"Codex",
"add the hook to config.toml yourself, as shown above",
);
}
fn require_terminal(command: &str) -> Result<()> {
if !io::stdin().is_terminal() {
bail!("{command} asks before each change, so run it in a terminal.");
}
Ok(())
}
fn ask(question: &str) -> Result<bool> {
Ok(answer(question, "[Y/n]")?.is_none_or(|yes| yes))
}
fn ask_default_no(question: &str) -> Result<bool> {
Ok(answer(question, "[y/N]")?.is_some_and(|yes| yes))
}
fn answer(question: &str, choices: &str) -> Result<Option<bool>> {
loop {
print!("{question} {choices} ");
io::stdout().flush()?;
let mut line = String::new();
if io::stdin().lock().read_line(&mut line)? == 0 {
return Ok(Some(false));
}
match line.trim().to_ascii_lowercase().as_str() {
"" => return Ok(None),
"y" | "yes" => return Ok(Some(true)),
"n" | "no" => return Ok(Some(false)),
_ => {}
}
}
}
fn read_or_empty(path: &Path) -> Result<Vec<u8>> {
match fs::read(path) {
Ok(bytes) => Ok(bytes),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(Vec::new()),
Err(error) => Err(error).with_context(|| format!("can't read {}", path.display())),
}
}
fn read_json(path: &Path) -> Result<Value> {
let bytes = read_or_empty(path)?;
if bytes.iter().all(u8::is_ascii_whitespace) {
return Ok(json!({}));
}
serde_json::from_slice(&bytes).with_context(|| {
format!(
"can't read {} as JSON, so kaeru leaves it alone",
path.display()
)
})
}
fn write_json(path: &Path, value: &Value) -> Result<()> {
let mut text = serde_json::to_string_pretty(value)?;
text.push('\n');
write_file(path, text.as_bytes())
}
fn write_file(path: &Path, bytes: &[u8]) -> Result<()> {
let linked;
let path = if fs::symlink_metadata(path).is_ok_and(|metadata| metadata.file_type().is_symlink())
{
linked = fs::canonicalize(path)
.with_context(|| format!("can't follow the link {}", path.display()))?;
linked.as_path()
} else {
path
};
if let Some(folder) = path.parent() {
fs::create_dir_all(folder).with_context(|| format!("can't create {}", folder.display()))?;
}
let mut temp = path.as_os_str().to_owned();
temp.push(".kaeru-tmp");
let temp = PathBuf::from(temp);
fs::write(&temp, bytes).with_context(|| format!("can't write {}", temp.display()))?;
fs::rename(&temp, path).with_context(|| format!("can't write {}", path.display()))
}
fn backup_of(path: &Path) -> PathBuf {
let mut name: OsString = path.as_os_str().to_owned();
name.push(".kaeru-backup");
PathBuf::from(name)
}
fn on_path(program: &str) -> Option<PathBuf> {
std::env::split_paths(&std::env::var_os("PATH")?)
.map(|folder| folder.join(program))
.find(|candidate| candidate.is_file())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_summary_says_how_much_is_set_up() {
assert!(summary(4, 4, 0).starts_with("Everything was set up already."));
assert!(summary(4, 4, 2).starts_with("Everything is set up."));
assert!(summary(4, 3, 1).starts_with("Set up 3 of 4."));
assert!(summary(4, 3, 1).ends_with("run kaeru doctor to check it."));
}
#[test]
fn long_lines_wrap_at_spaces() {
assert_eq!(
wrap("one two three four five six seven eight", 20),
["one two three four", "five six seven eight"]
);
assert_eq!(wrap("short", 40), ["short"]);
assert_eq!(wrap("a b", 5), ["a b"], "too narrow to wrap");
}
#[test]
fn names_line_up_in_a_column() {
assert_eq!(
name_column(&["Git Bash", "Windows PowerShell", "Codex"]),
20
);
assert_eq!(name_column(&[]), 2);
}
#[test]
fn labels_have_the_doctor_s_colors() {
assert_eq!(Outcome::Ok.color(), Color::Green);
assert_eq!(Outcome::Added.color(), Color::Green);
assert_eq!(Outcome::Skipped.color(), Color::Yellow);
assert_eq!(Outcome::Problem.color(), Color::Red);
assert!(Outcome::Skipped.label().len() < 9);
}
#[test]
fn codex_s_trust_records_declare_no_hooks() {
let trust = r#"
[hooks.state]
[hooks.state.'C:\Users\demo\.codex\hooks.json:session_start:0:0']
trusted_hash = "sha256:0000"
enabled = true
"#;
let inline = r#"
[[hooks.SessionStart]]
[[hooks.SessionStart.hooks]]
type = "command"
command = "kaeru hook codex"
"#;
assert!(!declares_hooks(trust));
assert!(declares_hooks(inline));
assert!(declares_hooks(&format!("{trust}{inline}")));
assert!(!declares_hooks("model = \"some-model\"\n"));
assert!(!declares_hooks("[hooks\n"));
}
#[test]
fn a_file_that_doesn_t_exist_reads_as_empty() {
let dir = tempfile::tempdir().unwrap();
let missing = dir.path().join("missing.json");
assert!(read_or_empty(&missing).unwrap().is_empty());
assert_eq!(read_json(&missing).unwrap(), json!({}));
}
#[test]
fn json_is_written_and_read_back() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("new folder").join("settings.json");
write_json(&path, &json!({ "a": 1 })).unwrap();
assert_eq!(read_json(&path).unwrap(), json!({ "a": 1 }));
assert!(fs::read_to_string(&path).unwrap().ends_with("}\n"));
}
#[test]
fn broken_json_is_left_alone() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("settings.json");
fs::write(&path, "{ not json").unwrap();
assert!(read_json(&path).is_err());
assert_eq!(fs::read_to_string(&path).unwrap(), "{ not json");
}
#[test]
fn writing_through_a_link_keeps_the_link() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("dotfiles-profile.ps1");
let link = dir.path().join("profile.ps1");
fs::write(&target, "old").unwrap();
#[cfg(unix)]
let made = std::os::unix::fs::symlink(&target, &link);
#[cfg(windows)]
let made = std::os::windows::fs::symlink_file(&target, &link);
if made.is_err() {
return;
}
write_file(&link, b"new").unwrap();
assert!(
fs::symlink_metadata(&link)
.unwrap()
.file_type()
.is_symlink()
);
assert_eq!(fs::read_to_string(&target).unwrap(), "new");
}
#[test]
fn the_backup_sits_next_to_the_file() {
assert_eq!(
backup_of(Path::new("settings.json")),
Path::new("settings.json.kaeru-backup")
);
}
}