git clone https://garage44.eu/jeroen/midas.git.. /src/claude.rs
//! `midas claude install`: put the shared workflow skills (`skills/`) and the
//! session hooks (`hooks/`) into `~/.claude`, where Claude Code finds them in
//! every project, and wire the hooks into `~/.claude/settings.json`.
//!
//! They are carried in the binary, so they are as current as the midas that
//! installs them: `deploy.sh` and `midas update` install them, and the
//! session-start hook runs this at every start, so a machine whose midas moved
//! on has the skills of that midas from its next session on.
//!
//! What is the person's stays theirs. `~/.claude/midas-installed.json` lists
//! what midas wrote and what it was; a skill directory midas did not write is
//! left alone (a project may also keep a skill of the same name, which Claude
//! Code prefers), a file changed since midas wrote it is copied to
//! `~/.claude/backups/midas-<time>/` before it is replaced or removed, and
//! settings.json is backed up beside itself before a hook is added to it.
//! `midas claude uninstall` takes back what the list names.
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use serde_json::{json, Value};
/// One file midas installs: where it goes under `~/.claude`, and what it is.
struct File {
to: &'static str,
body: &'static str,
exec: bool,
}
macro_rules! file {
($to:literal, $from:literal, $exec:literal) => {
File { to: $to, body: include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/", $from)), exec: $exec }
};
}
/// Everything in `skills/`, and the agent hooks in `hooks/` (a test holds this
/// to the directories, so a new file cannot be left out).
const FILES: &[File] = &[
file!("skills/commit/SKILL.md", "skills/commit/SKILL.md", false),
file!("skills/finish-branch/SKILL.md", "skills/finish-branch/SKILL.md", false),
file!("skills/finish-branch/land", "skills/finish-branch/land", true),
file!("skills/handover/SKILL.md", "skills/handover/SKILL.md", false),
file!("skills/handover/hand-over", "skills/handover/hand-over", true),
file!("hooks/midas-session-start", "hooks/session-start", true),
file!("hooks/midas-session-end", "hooks/session-end", true),
file!("hooks/midas-prompt-submit", "hooks/prompt-submit", true),
file!("hooks/midas-post-tool-use", "hooks/post-tool-use", true),
file!("hooks/midas-pre-tool-use", "hooks/pre-tool-use", true),
];
/// Which hook each Claude Code event runs, its timeout in seconds, and the
/// tools it is for (none: every one).
const EVENTS: &[(&str, &str, u32, Option<&str>)] = &[
("SessionStart", "session-start", 15, None),
("SessionEnd", "session-end", 20, None),
("UserPromptSubmit", "prompt-submit", 10, None),
("PostToolUse", "post-tool-use", 5, None),
("PreToolUse", "pre-tool-use", 5, Some("AskUserQuestion")),
];
const MANIFEST: &str = "midas-installed.json";
fn sha(s: &str) -> String {
crate::accounts::sha256(s)
}
/// The skill a path under `~/.claude` belongs to, if it is a skill's.
fn skill_of(rel: &str) -> Option<&str> {
rel.strip_prefix("skills/")?.split('/').next()
}
/// Install, or bring up to date. Prints what changed (nothing, with `quiet`,
/// when nothing did).
pub fn install(home: &Path, quiet: bool) -> Result<i32> {
let dir = home.join(".claude");
let manifest = read_manifest(&dir);
let had: BTreeMap<String, String> = manifest["files"].as_object().into_iter().flatten()
.filter_map(|(k, v)| Some((k.clone(), v.as_str()?.to_string()))).collect();
let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string();
let backups = dir.join("backups").join(format!("midas-{stamp}"));
let mut said = vec![];
let mut kept: BTreeMap<String, String> = BTreeMap::new();
// A skill directory that was there before midas wrote any of it is the
// person's own. Decided before writing anything, or the first file
// written would make the skill's directory look like theirs.
let theirs: BTreeSet<&str> = FILES.iter().filter_map(|f| skill_of(f.to))
.filter(|s| dir.join("skills").join(s).exists() && !had.keys().any(|k| skill_of(k) == Some(*s)))
.collect();
let mut said_theirs = BTreeSet::new();
for f in FILES {
let to = dir.join(f.to);
if let Some(skill) = skill_of(f.to).filter(|s| theirs.contains(s)) {
if !quiet && said_theirs.insert(skill) {
said.push(format!("left ~/.claude/skills/{skill} alone: it is not midas's"));
}
continue;
}
let now = fs::read_to_string(&to).ok();
if now.as_deref() != Some(f.body) {
if let Some(n) = &now {
if had.get(f.to) != Some(&sha(n)) {
backup(&to, &backups.join(f.to))?;
said.push(format!("{} had changes of its own: kept in {}", f.to, backups.display()));
}
}
write(&to, f.body, f.exec)?;
said.push(format!("{} {}", if now.is_some() { "updated" } else { "installed" }, f.to));
} else if f.exec {
write_mode(&to, true)?;
}
kept.insert(f.to.to_string(), sha(f.body));
}
// What an older midas installed and this one does not.
for (rel, was) in &had {
if kept.contains_key(rel) || FILES.iter().any(|f| f.to == rel) {
continue;
}
let at = dir.join(rel);
let Ok(now) = fs::read_to_string(&at) else { continue };
if &sha(&now) != was {
backup(&at, &backups.join(rel))?;
}
fs::remove_file(&at).ok();
if let Some(parent) = at.parent() {
fs::remove_dir(parent).ok(); // only when empty
}
said.push(format!("removed {rel}, which midas no longer ships"));
}
let added = wire_settings(&dir, &stamp)?;
for (event, hook) in &added {
said.push(format!("settings.json: {event} runs {hook}"));
}
let mut wired: Vec<Value> = manifest["settings"].as_array().cloned().unwrap_or_default();
wired.extend(added.iter().map(|(e, h)| json!({"event": e, "command": h})));
let m = json!({"build": crate::VERSION, "files": kept, "settings": wired});
if m != manifest {
write(&dir.join(MANIFEST), &serde_json::to_string_pretty(&m)?, false)?;
}
if !quiet || !said.is_empty() {
for s in &said {
println!("{s}");
}
if said.is_empty() {
println!("~/.claude has midas {}'s skills and hooks", crate::VERSION);
} else if backups.exists() {
println!("what was replaced is in {}", backups.display());
}
}
Ok(0)
}
/// Take back what the manifest names: the files (a changed one is backed up
/// first) and the hooks midas added to settings.json.
pub fn uninstall(home: &Path) -> Result<i32> {
let dir = home.join(".claude");
let manifest = read_manifest(&dir);
let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string();
let backups = dir.join("backups").join(format!("midas-{stamp}"));
for (rel, was) in manifest["files"].as_object().into_iter().flatten() {
let at = dir.join(rel);
let Ok(now) = fs::read_to_string(&at) else { continue };
if Some(sha(&now).as_str()) != was.as_str() {
backup(&at, &backups.join(rel))?;
println!("{rel} had changes of its own: kept in {}", backups.display());
}
fs::remove_file(&at)?;
if let Some(parent) = at.parent() {
fs::remove_dir(parent).ok();
}
println!("removed {rel}");
}
let settings = dir.join("settings.json");
if let (Some(added), Ok(text)) = (manifest["settings"].as_array(), fs::read_to_string(&settings)) {
let mut s: Value = serde_json::from_str(&text).context("~/.claude/settings.json is not JSON")?;
let mut changed = false;
for a in added {
let (Some(event), Some(cmd)) = (a["event"].as_str(), a["command"].as_str()) else { continue };
if let Some(groups) = s["hooks"][event].as_array_mut() {
let before = groups.len();
groups.retain(|g| !g["hooks"].as_array().is_some_and(|h| h.iter().any(|h| h["command"] == cmd)));
changed |= groups.len() != before;
}
}
if changed {
fs::copy(&settings, dir.join(format!("settings.json.bak-midas-{stamp}")))?;
write(&settings, &(serde_json::to_string_pretty(&s)? + "\n"), false)?;
println!("settings.json: the hooks midas added are gone (backup beside it)");
}
}
fs::remove_file(dir.join(MANIFEST)).ok();
Ok(0)
}
fn read_manifest(dir: &Path) -> Value {
fs::read_to_string(dir.join(MANIFEST)).ok()
.and_then(|t| serde_json::from_str(&t).ok())
.unwrap_or_else(|| json!({}))
}
/// Add each event's hook to settings.json unless something already runs it —
/// `midas-<hook>` here, or `<hook>` from a checkout of midas, as a workstation
/// may have it. Returns what was added.
fn wire_settings(dir: &Path, stamp: &str) -> Result<Vec<(String, String)>> {
let path = dir.join("settings.json");
let text = match fs::read_to_string(&path) {
Ok(t) => t,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => "{}".into(),
Err(e) => return Err(e).context("reading ~/.claude/settings.json"),
};
let mut s: Value = serde_json::from_str(&text).context("~/.claude/settings.json is not JSON; not touching it")?;
let added = add_hooks(&mut s, &dir.join("hooks"));
if !added.is_empty() {
if path.exists() {
fs::copy(&path, dir.join(format!("settings.json.bak-midas-{stamp}")))?;
}
write(&path, &(serde_json::to_string_pretty(&s)? + "\n"), false)?;
}
Ok(added)
}
fn add_hooks(s: &mut Value, hooks: &Path) -> Vec<(String, String)> {
let mut added = vec![];
if !s.is_object() {
return added;
}
for (event, hook, timeout, matcher) in EVENTS {
let runs = |c: &str| {
let base = c.trim_matches('"').rsplit('/').next().unwrap_or("");
base == *hook || base == format!("midas-{hook}")
};
let groups = &s["hooks"][*event];
let wired = groups.as_array().into_iter().flatten()
.flat_map(|g| g["hooks"].as_array().into_iter().flatten())
.any(|h| h["command"].as_str().is_some_and(runs));
if wired {
continue;
}
let cmd = hooks.join(format!("midas-{hook}")).display().to_string();
if !s["hooks"].is_object() {
s["hooks"] = json!({});
}
if !s["hooks"][*event].is_array() {
s["hooks"][*event] = json!([]);
}
s["hooks"][*event].as_array_mut().unwrap()
.push(match matcher {
Some(m) => json!({"matcher": m, "hooks": [{"type": "command", "command": cmd, "timeout": timeout}]}),
None => json!({"hooks": [{"type": "command", "command": cmd, "timeout": timeout}]}),
});
added.push((event.to_string(), cmd));
}
added
}
fn backup(from: &Path, to: &Path) -> Result<()> {
fs::create_dir_all(to.parent().unwrap())?;
fs::copy(from, to).with_context(|| format!("backing up {}", from.display()))?;
Ok(())
}
/// Beside it, then renamed over it: a hook or a landing running from the old
/// file keeps reading the old file (bash reads a script as it goes).
fn write(to: &Path, body: &str, exec: bool) -> Result<()> {
fs::create_dir_all(to.parent().unwrap())?;
let tmp: PathBuf = to.with_extension(format!("midas-new-{}", std::process::id()));
fs::write(&tmp, body).with_context(|| format!("writing {}", tmp.display()))?;
write_mode(&tmp, exec)?;
fs::rename(&tmp, to).with_context(|| format!("installing {}", to.display()))
}
fn write_mode(at: &Path, exec: bool) -> Result<()> {
let mode = if exec { 0o755 } else { 0o644 };
if fs::metadata(at)?.permissions().mode() & 0o777 != mode {
fs::set_permissions(at, fs::Permissions::from_mode(mode))?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn listed(dir: &str) -> Vec<String> {
let root = Path::new(env!("CARGO_MANIFEST_DIR"));
let mut out = vec![];
let mut stack = vec![root.join(dir)];
while let Some(d) = stack.pop() {
for e in fs::read_dir(&d).unwrap().flatten() {
if e.path().is_dir() {
stack.push(e.path());
} else {
out.push(e.path().strip_prefix(root).unwrap().display().to_string());
}
}
}
out.sort();
out
}
#[test]
fn every_skill_and_agent_hook_is_carried() {
let carried: Vec<String> = FILES.iter().map(|f| f.to.to_string()).collect();
for s in listed("skills") {
assert!(carried.contains(&s), "{s} is in skills/ but not in claude::FILES");
}
for h in listed("hooks") {
// The git server's hook is the hub's, not an agent's.
if h == "hooks/git-post-receive" {
continue;
}
let to = format!("hooks/midas-{}", h.trim_start_matches("hooks/"));
assert!(carried.contains(&to), "{h} is in hooks/ but not in claude::FILES");
}
for f in FILES {
assert_eq!(f.exec, f.body.starts_with("#!"), "{}: a script is installed executable, and only a script", f.to);
}
}
#[test]
fn install_keeps_what_is_the_persons_and_takes_back_only_its_own() {
let home = tempfile::tempdir().unwrap();
let dir = home.path().join(".claude");
// The person's own skill of the same name, their own settings, and a
// hand-placed copy of a hook (as deploy.sh used to put there).
fs::create_dir_all(dir.join("skills/commit")).unwrap();
fs::write(dir.join("skills/commit/SKILL.md"), "mine").unwrap();
fs::create_dir_all(dir.join("hooks")).unwrap();
fs::write(dir.join("hooks/midas-session-end"), "old copy").unwrap();
fs::write(dir.join("settings.json"), r#"{"theme": "dark", "hooks": {"UserPromptSubmit": [{"hooks": [{"type": "command", "command": "/src/midas/hooks/prompt-submit"}]}]}}"#).unwrap();
install(home.path(), true).unwrap();
assert_eq!(fs::read_to_string(dir.join("skills/commit/SKILL.md")).unwrap(), "mine", "their own skill is left alone");
assert!(dir.join("skills/finish-branch/land").exists());
let land = fs::metadata(dir.join("skills/finish-branch/land")).unwrap().permissions().mode();
assert_eq!(land & 0o777, 0o755);
let backed: Vec<_> = fs::read_dir(dir.join("backups")).unwrap().flatten().collect();
assert_eq!(backed.len(), 1, "the hand-placed hook was kept before it was replaced");
let s: Value = serde_json::from_str(&fs::read_to_string(dir.join("settings.json")).unwrap()).unwrap();
assert_eq!(s["theme"], "dark");
assert_eq!(s["hooks"]["UserPromptSubmit"].as_array().unwrap().len(), 1, "a checkout's hook already runs it");
assert_eq!(s["hooks"]["SessionStart"].as_array().unwrap().len(), 1);
assert!(fs::read_dir(&dir).unwrap().flatten().any(|e| e.file_name().to_string_lossy().starts_with("settings.json.bak-midas-")));
// Again: nothing to do, nothing added twice.
install(home.path(), true).unwrap();
let again: Value = serde_json::from_str(&fs::read_to_string(dir.join("settings.json")).unwrap()).unwrap();
assert_eq!(again, s);
uninstall(home.path()).unwrap();
assert!(!dir.join("skills/finish-branch").exists());
assert!(!dir.join("hooks/midas-session-start").exists());
assert_eq!(fs::read_to_string(dir.join("skills/commit/SKILL.md")).unwrap(), "mine");
let after: Value = serde_json::from_str(&fs::read_to_string(dir.join("settings.json")).unwrap()).unwrap();
assert!(after["hooks"]["SessionStart"].as_array().unwrap().is_empty());
assert_eq!(after["hooks"]["UserPromptSubmit"].as_array().unwrap().len(), 1, "theirs stays");
}
}