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