Skip to main content

lean_ctx/hooks/agents/
claude_mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The lean-ctx Claude Code mod (`integrations/claude-code-mod`): distribution
3//! and lifecycle.
4//!
5//! The binary carries the mod and installs it from a local marketplace in the
6//! lean-ctx data dir, so the installed mod always matches the engine that
7//! serves it and nothing is fetched from the network. Claude Code caches a
8//! plugin per version string, so the version is the engine version plus a
9//! content hash (`3.10.5+1a2b3c4d`, semver build metadata): any change to the
10//! mod's sources — a release or a `dev-install` — rolls it forward, an
11//! unchanged mod never churns. The lifecycle is driven through Claude Code's
12//! own `claude plugin` CLI — verified against 2.1.287: `marketplace add` and
13//! `install` are idempotent, `marketplace update` + `update` move between
14//! versions, including ones that differ only in build metadata.
15//!
16//! Setup and update install the mod where Claude Code can host it, say so in
17//! their report (what it does, that it applies in new sessions, how to remove
18//! it), and roll an installed mod forward. The mod is code that runs inside
19//! Claude Code with the user's permissions, so removing it is a standing
20//! decision: `lean-ctx claude-mod uninstall` leaves a marker that keeps every
21//! later setup or update from installing it again, until an explicit
22//! `lean-ctx claude-mod install` clears it.
23
24use std::path::{Path, PathBuf};
25use std::process::Command;
26use std::time::{Duration, Instant};
27
28/// First Claude Code release with mods (`hooks.json` `modules`).
29pub const MIN_CLAUDE_VERSION: (u32, u32, u32) = (2, 1, 287);
30/// Marketplace and plugin name; the plugin id is `lean-ctx@lean-ctx`.
31pub const MARKETPLACE: &str = "lean-ctx";
32pub const PLUGIN_ID: &str = "lean-ctx@lean-ctx";
33
34pub const REGISTER_TS: &str = include_str!("../../templates/claude_mod/register.ts");
35pub const HOOKS_JSON: &str = include_str!("../../templates/claude_mod/hooks.json");
36/// The cockpit (sidebar, pulse line, overlays), imported by `register.ts`.
37pub const COCKPIT_TSX: &str = include_str!("../../templates/claude_mod/cockpit.tsx");
38/// The `$.state` contract the manifest names as `types`.
39pub const TYPES_DTS: &str = include_str!("../../templates/claude_mod/cockpit.d.ts");
40/// Source manifest; [`plugin_manifest`] stamps the engine version into it.
41pub const PLUGIN_JSON: &str = include_str!("../../templates/claude_mod/plugin.json");
42
43const CLAUDE_TIMEOUT: Duration = Duration::from_mins(1);
44
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub enum ModStatus {
47    /// No `claude` binary on PATH.
48    ClaudeMissing,
49    /// Claude Code is older than [`MIN_CLAUDE_VERSION`].
50    ClaudeTooOld(String),
51    NotInstalled,
52    /// Installed and matching this engine.
53    Current(String),
54    /// Installed from an older (or newer) engine; `install` refreshes it.
55    Stale(String),
56}
57
58impl ModStatus {
59    #[must_use]
60    pub fn describe(&self) -> String {
61        let want = mod_version();
62        match self {
63            Self::ClaudeMissing => "Claude Code not found on PATH".to_string(),
64            Self::ClaudeTooOld(v) => format!(
65                "Claude Code {v} predates mods (needs {}.{}.{}+)",
66                MIN_CLAUDE_VERSION.0, MIN_CLAUDE_VERSION.1, MIN_CLAUDE_VERSION.2
67            ),
68            Self::NotInstalled => "not installed".to_string(),
69            Self::Current(v) => format!("installed ({v})"),
70            Self::Stale(v) => {
71                format!("installed ({v}), this engine ships {want} — refresh pending")
72            }
73        }
74    }
75}
76
77/// The installed plugin version: engine version + 8 hex of the mod sources'
78/// BLAKE3 (`3.10.5+1a2b3c4d`). Deterministic per build.
79#[must_use]
80pub fn mod_version() -> String {
81    let mut hasher = blake3::Hasher::new();
82    for part in [REGISTER_TS, COCKPIT_TSX, TYPES_DTS, HOOKS_JSON, PLUGIN_JSON] {
83        hasher.update(part.as_bytes());
84        hasher.update(&[0]);
85    }
86    let hash = hasher.finalize().to_hex();
87    format!("{}+{}", env!("CARGO_PKG_VERSION"), &hash[..8])
88}
89
90/// `<data dir>/claude-mod` — the local marketplace root.
91pub fn marketplace_dir() -> Result<PathBuf, String> {
92    crate::core::data_dir::lean_ctx_data_dir().map(|d| d.join("claude-mod"))
93}
94
95/// Printed when setup or update installs the mod: what it is, when it applies,
96/// how to remove it.
97pub const INSTALLED_NOTICE: &str = "Installed the LeanCTX plugin for Claude Code: the cockpit (what Claude saw, \
98tokens kept out, the two checks, receipts), wake on background jobs and a focused lean-ctx tool \
99surface. Active in new Claude Code sessions (or /reload-plugins). Remove anytime with \
100`lean-ctx claude-mod uninstall` — it then stays removed.";
101
102/// `<data dir>/claude-mod.declined`: written by `uninstall`, outside the
103/// marketplace root that uninstall deletes, so the decision outlives it.
104fn declined_marker() -> Result<PathBuf, String> {
105    crate::core::data_dir::lean_ctx_data_dir().map(|d| d.join("claude-mod.declined"))
106}
107
108/// Whether the user removed the mod: setup and update then never install it.
109#[must_use]
110pub fn auto_install_declined() -> bool {
111    declined_marker().is_ok_and(|p| p.exists())
112}
113
114/// The plugin manifest with `version` set to [`mod_version`].
115pub fn plugin_manifest() -> String {
116    let mut manifest: serde_json::Value =
117        serde_json::from_str(PLUGIN_JSON).expect("templates/claude_mod/plugin.json is valid JSON");
118    manifest["version"] = serde_json::json!(mod_version());
119    serde_json::to_string_pretty(&manifest).expect("manifest serializes") + "\n"
120}
121
122fn marketplace_manifest() -> String {
123    let manifest = serde_json::json!({
124        "name": MARKETPLACE,
125        "description": "lean-ctx's Claude Code mod, installed by the lean-ctx binary that serves it.",
126        "owner": { "name": "Thinkery / Yves Gugger" },
127        "plugins": [{
128            "name": "lean-ctx",
129            "source": "./plugins/lean-ctx",
130            "description": "The LeanCTX cockpit, wake on background job completion, a focused lean-ctx tool surface, and per-session request usage.",
131        }]
132    });
133    serde_json::to_string_pretty(&manifest).expect("manifest serializes") + "\n"
134}
135
136/// Write the marketplace (manifest + plugin files) under `root`; only files
137/// whose bytes differ are rewritten. Returns whether anything changed.
138pub fn materialize(root: &Path) -> Result<bool, String> {
139    let plugin = root.join("plugins").join("lean-ctx");
140    let files: [(PathBuf, String); 6] = [
141        (
142            root.join(".claude-plugin/marketplace.json"),
143            marketplace_manifest(),
144        ),
145        (plugin.join(".claude-plugin/plugin.json"), plugin_manifest()),
146        (plugin.join("hooks/hooks.json"), HOOKS_JSON.to_string()),
147        (plugin.join("hooks/register.ts"), REGISTER_TS.to_string()),
148        (plugin.join("hooks/cockpit.tsx"), COCKPIT_TSX.to_string()),
149        (plugin.join("types/index.d.ts"), TYPES_DTS.to_string()),
150    ];
151    let mut changed = false;
152    for (path, content) in files {
153        if std::fs::read_to_string(&path).is_ok_and(|on_disk| on_disk == content) {
154            continue;
155        }
156        if let Some(parent) = path.parent() {
157            std::fs::create_dir_all(parent)
158                .map_err(|e| format!("create {}: {e}", parent.display()))?;
159        }
160        std::fs::write(&path, content).map_err(|e| format!("write {}: {e}", path.display()))?;
161        changed = true;
162    }
163    Ok(changed)
164}
165
166/// Parse `claude --version` output (`2.1.287 (Claude Code)`).
167#[must_use]
168pub fn parse_claude_version(output: &str) -> Option<(u32, u32, u32)> {
169    let token = output.split_whitespace().next()?;
170    let mut parts = token.split('.').map(|p| p.parse::<u32>().ok());
171    Some((parts.next()??, parts.next()??, parts.next()??))
172}
173
174/// Version of an installed `lean-ctx@lean-ctx` from `claude plugin list --json`.
175#[must_use]
176pub fn installed_version(list_json: &str) -> Option<String> {
177    let entries: Vec<serde_json::Value> = serde_json::from_str(list_json).ok()?;
178    entries
179        .iter()
180        .find(|e| e.get("id").and_then(serde_json::Value::as_str) == Some(PLUGIN_ID))
181        .and_then(|e| e.get("version").and_then(serde_json::Value::as_str))
182        .map(str::to_string)
183}
184
185/// Current lifecycle state. Runs `claude --version` and `claude plugin list`.
186pub fn status() -> ModStatus {
187    let Ok(version_out) = run_claude(&["--version"]) else {
188        return ModStatus::ClaudeMissing;
189    };
190    let version = version_out
191        .split_whitespace()
192        .next()
193        .unwrap_or("")
194        .to_string();
195    match parse_claude_version(&version_out) {
196        Some(v) if v >= MIN_CLAUDE_VERSION => {}
197        _ => return ModStatus::ClaudeTooOld(version),
198    }
199    match run_claude(&["plugin", "list", "--json"])
200        .ok()
201        .and_then(|out| installed_version(&out))
202    {
203        None => ModStatus::NotInstalled,
204        Some(v) if v == mod_version() => ModStatus::Current(v),
205        Some(v) => ModStatus::Stale(v),
206    }
207}
208
209/// Install, or refresh an existing install to this engine's version.
210/// Idempotent; returns a one-line human summary.
211pub fn install() -> Result<String, String> {
212    let before = status();
213    match &before {
214        ModStatus::ClaudeMissing | ModStatus::ClaudeTooOld(_) => {
215            return Err(before.describe());
216        }
217        ModStatus::Current(_) | ModStatus::NotInstalled | ModStatus::Stale(_) => {}
218    }
219    let root = marketplace_dir()?;
220    materialize(&root)?;
221    let root_str = root.to_string_lossy().to_string();
222    // Idempotent: re-adding an existing local marketplace is a no-op success.
223    run_claude(&["plugin", "marketplace", "add", &root_str])?;
224    // An install (explicit, or by setup while nothing was declined) lifts an
225    // earlier removal: from here on, updates keep the mod current again.
226    if let Ok(marker) = declined_marker() {
227        let _ = std::fs::remove_file(marker);
228    }
229    match before {
230        ModStatus::NotInstalled => {
231            run_claude(&["plugin", "install", PLUGIN_ID, "--scope", "user"])?;
232            Ok(format!(
233                "installed {PLUGIN_ID} {} — active in new Claude Code sessions (or /reload-plugins)",
234                mod_version()
235            ))
236        }
237        ModStatus::Stale(old) => {
238            run_claude(&["plugin", "marketplace", "update", MARKETPLACE])?;
239            run_claude(&["plugin", "update", PLUGIN_ID, "--scope", "user"])?;
240            Ok(format!(
241                "updated {PLUGIN_ID} {old} → {} — applies in new sessions",
242                mod_version()
243            ))
244        }
245        _ => Ok(format!("{PLUGIN_ID} is current ({})", mod_version())),
246    }
247}
248
249/// Installed plugin versions read from Claude Code's plugin cache
250/// (`<claude dir>/plugins/cache/lean-ctx/lean-ctx/<version>/`) — a file-only
251/// probe for `doctor`, which must not spawn `claude`. Directory names are as
252/// Claude Code writes them: it replaces the `+` of build metadata with `-`
253/// (`3.10.5+5ed30c51` is cached as `3.10.5-5ed30c51`), see [`cache_dir_name`].
254#[must_use]
255pub fn cached_versions(claude_dir: &Path) -> Vec<String> {
256    let mut versions: Vec<String> = std::fs::read_dir(
257        claude_dir
258            .join("plugins/cache")
259            .join(MARKETPLACE)
260            .join("lean-ctx"),
261    )
262    .map(|entries| {
263        entries
264            .filter_map(Result::ok)
265            .filter(|e| e.path().is_dir())
266            .filter_map(|e| e.file_name().to_str().map(str::to_string))
267            .collect()
268    })
269    .unwrap_or_default();
270    versions.sort();
271    versions
272}
273
274/// The cache directory Claude Code (2.1.287) creates for a plugin version:
275/// `+` is not kept in the path, so build metadata appears as `-…`.
276#[must_use]
277pub fn cache_dir_name(version: &str) -> String {
278    version.replace('+', "-")
279}
280
281/// Remove the plugin, the marketplace, and the materialized files.
282///
283/// Success is verified, not assumed: the local files are only deleted once
284/// Claude Code no longer lists the plugin — deleting them first would leave a
285/// registered plugin pointing at a missing directory.
286pub fn uninstall() -> Result<String, String> {
287    if matches!(status(), ModStatus::ClaudeMissing) {
288        return Err(ModStatus::ClaudeMissing.describe());
289    }
290    let uninstall = run_claude(&["plugin", "uninstall", PLUGIN_ID, "--scope", "user"]);
291    let remove = run_claude(&["plugin", "marketplace", "remove", MARKETPLACE]);
292    let still_installed =
293        run_claude(&["plugin", "list", "--json"]).map(|out| installed_version(&out).is_some())?;
294    let marketplace_listed = run_claude(&["plugin", "marketplace", "list", "--json"])
295        .map(|out| marketplace_listed(&out))?;
296    if still_installed || marketplace_listed {
297        let cause = uninstall.err().or(remove.err()).unwrap_or_default();
298        return Err(format!(
299            "{PLUGIN_ID} is still registered with Claude Code{}{cause} — local files kept",
300            if cause.is_empty() { "" } else { ": " }
301        ));
302    }
303    if let Ok(root) = marketplace_dir()
304        && root.exists()
305    {
306        std::fs::remove_dir_all(&root).map_err(|e| format!("remove {}: {e}", root.display()))?;
307    }
308    // A removal is a standing decision: no later setup or update reinstalls it.
309    if let Ok(marker) = declined_marker() {
310        if let Some(parent) = marker.parent() {
311            let _ = std::fs::create_dir_all(parent);
312        }
313        std::fs::write(&marker, "removed with `lean-ctx claude-mod uninstall`; `lean-ctx claude-mod install` lifts this\n")
314            .map_err(|e| format!("write {}: {e}", marker.display()))?;
315    }
316    Ok(format!(
317        "removed {PLUGIN_ID} — setup and update will not reinstall it (lean-ctx claude-mod install brings it back)"
318    ))
319}
320
321/// Whether `claude plugin marketplace list --json` names our marketplace.
322#[must_use]
323pub fn marketplace_listed(list_json: &str) -> bool {
324    serde_json::from_str::<Vec<serde_json::Value>>(list_json).is_ok_and(|entries| {
325        entries
326            .iter()
327            .any(|e| e.get("name").and_then(serde_json::Value::as_str) == Some(MARKETPLACE))
328    })
329}
330
331/// Run `claude <args>` with a hard timeout; stdout on success. stdout/stderr
332/// are drained on their own threads (a full pipe would otherwise stall the
333/// child until the timeout), and the child is killed and reaped on every
334/// failure path so no zombie outlives the call.
335fn run_claude(args: &[&str]) -> Result<String, String> {
336    use std::io::Read as _;
337    let label = || format!("claude {}", args.join(" "));
338    let binary = crate::core::editor_registry::validate_claude_binary()?;
339    let mut child = Command::new(&binary)
340        .args(args)
341        .stdin(std::process::Stdio::null())
342        .stdout(std::process::Stdio::piped())
343        .stderr(std::process::Stdio::piped())
344        .spawn()
345        .map_err(|e| format!("{}: {e}", label()))?;
346    let drain = |pipe: Option<Box<dyn std::io::Read + Send>>| {
347        std::thread::spawn(move || {
348            let mut buf = Vec::new();
349            if let Some(mut p) = pipe {
350                let _ = p.read_to_end(&mut buf);
351            }
352            String::from_utf8_lossy(&buf).into_owned()
353        })
354    };
355    let stdout = drain(child.stdout.take().map(|p| Box::new(p) as Box<_>));
356    let stderr = drain(child.stderr.take().map(|p| Box::new(p) as Box<_>));
357    let start = Instant::now();
358    let status = loop {
359        match child.try_wait() {
360            Ok(Some(status)) => break Ok(status),
361            Ok(None) if start.elapsed() > CLAUDE_TIMEOUT => {
362                break Err(format!("{} timed out", label()));
363            }
364            Ok(None) => std::thread::sleep(Duration::from_millis(50)),
365            Err(e) => break Err(format!("{}: {e}", label())),
366        }
367    };
368    let status = match status {
369        Ok(status) => status,
370        Err(e) => {
371            let _ = child.kill();
372            let _ = child.wait();
373            return Err(e);
374        }
375    };
376    let stdout = stdout.join().unwrap_or_default();
377    let stderr = stderr.join().unwrap_or_default();
378    if status.success() {
379        Ok(stdout)
380    } else {
381        let detail = stderr
382            .trim()
383            .lines()
384            .chain(stdout.trim().lines())
385            .last()
386            .unwrap_or("");
387        Err(format!("{} failed: {detail}", label()))
388    }
389}
390
391#[cfg(test)]
392mod tests {
393    use super::*;
394
395    /// Observed on a real install (2.1.287): Claude Code caches
396    /// `3.10.5+5ed30c51` as `…/3.10.5-5ed30c51/` next to the older `3.10.5/`;
397    /// doctor compared against the `+` form and reported a current mod stale.
398    #[test]
399    fn cache_dir_matches_the_installed_version() {
400        let dir = tempfile::tempdir().unwrap();
401        let cache = dir.path().join("plugins/cache/lean-ctx/lean-ctx");
402        let current = cache_dir_name(&mod_version());
403        for v in ["3.10.5", current.as_str()] {
404            std::fs::create_dir_all(cache.join(v)).unwrap();
405        }
406        assert!(cached_versions(dir.path()).contains(&current));
407        assert!(!current.contains('+'), "{current}");
408    }
409
410    #[test]
411    fn version_gate_parses_claude_output() {
412        assert_eq!(
413            parse_claude_version("2.1.287 (Claude Code)"),
414            Some((2, 1, 287))
415        );
416        assert!(parse_claude_version("2.1.286 (Claude Code)").unwrap() < MIN_CLAUDE_VERSION);
417        assert!(parse_claude_version("2.2.0 (Claude Code)").unwrap() >= MIN_CLAUDE_VERSION);
418        assert_eq!(parse_claude_version("garbage"), None);
419    }
420
421    /// Shape observed from `claude plugin list --json` (2.1.287).
422    #[test]
423    fn installed_version_reads_only_our_plugin() {
424        let list = r#"[{"id":"other@x","version":"9.9.9"},
425                       {"id":"lean-ctx@lean-ctx","version":"3.10.5","scope":"user"}]"#;
426        assert_eq!(installed_version(list).as_deref(), Some("3.10.5"));
427        assert_eq!(installed_version("[]"), None);
428        assert_eq!(installed_version("not json"), None);
429        // `claude plugin marketplace list --json` (2.1.287); uninstall only
430        // deletes local files once this no longer names our marketplace.
431        let markets = r#"[{"name":"lean-ctx","source":"directory","path":"/d"}]"#;
432        assert!(marketplace_listed(markets));
433        assert!(!marketplace_listed(r#"[{"name":"other"}]"#));
434        assert!(!marketplace_listed("garbage"));
435    }
436
437    /// A removal is a standing decision; an explicit install lifts it. Checked
438    /// through the marker path itself (the CLI round-trips need `claude`).
439    #[test]
440    fn removal_marker_lives_outside_the_marketplace_root() {
441        let marker = declined_marker().unwrap();
442        let root = marketplace_dir().unwrap();
443        assert!(
444            !marker.starts_with(&root),
445            "{} inside {}",
446            marker.display(),
447            root.display()
448        );
449        assert_eq!(marker.parent(), root.parent());
450    }
451
452    /// The installed manifest must carry the engine version plus a content
453    /// hash (Claude caches plugins by version string; a version that ignores
454    /// the mod's sources froze dev-installs and same-version patches), and a
455    /// second materialize must be a no-op.
456    #[test]
457    fn materialize_stamps_engine_version_and_is_idempotent() {
458        let dir = tempfile::tempdir().unwrap();
459        assert!(materialize(dir.path()).unwrap());
460        let manifest: serde_json::Value = serde_json::from_str(
461            &std::fs::read_to_string(
462                dir.path()
463                    .join("plugins/lean-ctx/.claude-plugin/plugin.json"),
464            )
465            .unwrap(),
466        )
467        .unwrap();
468        let version = manifest["version"].as_str().unwrap();
469        let (engine, hash) = version.split_once('+').expect("engine+hash version");
470        assert_eq!(engine, env!("CARGO_PKG_VERSION"));
471        assert!(
472            hash.len() == 8 && hash.chars().all(|c| c.is_ascii_hexdigit()),
473            "{version}"
474        );
475        assert_eq!(manifest["name"], "lean-ctx");
476        assert!(
477            std::fs::read_to_string(dir.path().join("plugins/lean-ctx/hooks/register.ts"))
478                .unwrap()
479                .contains("export const register")
480        );
481        // The cockpit and the `$.state` contract the manifest points at ship too.
482        let plugin = dir.path().join("plugins/lean-ctx");
483        assert_eq!(
484            std::fs::read_to_string(plugin.join("hooks/cockpit.tsx")).unwrap(),
485            COCKPIT_TSX
486        );
487        assert_eq!(manifest["types"], "./types/index.d.ts");
488        assert_eq!(
489            std::fs::read_to_string(plugin.join("types/index.d.ts")).unwrap(),
490            TYPES_DTS
491        );
492        assert!(
493            !materialize(dir.path()).unwrap(),
494            "second run must not rewrite"
495        );
496    }
497}