1use std::path::{Path, PathBuf};
25use std::process::Command;
26use std::time::{Duration, Instant};
27
28pub const MIN_CLAUDE_VERSION: (u32, u32, u32) = (2, 1, 287);
30pub 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");
36pub const COCKPIT_TSX: &str = include_str!("../../templates/claude_mod/cockpit.tsx");
38pub const TYPES_DTS: &str = include_str!("../../templates/claude_mod/cockpit.d.ts");
40pub 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 ClaudeMissing,
49 ClaudeTooOld(String),
51 NotInstalled,
52 Current(String),
54 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#[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
90pub fn marketplace_dir() -> Result<PathBuf, String> {
92 crate::core::data_dir::lean_ctx_data_dir().map(|d| d.join("claude-mod"))
93}
94
95pub 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
102fn declined_marker() -> Result<PathBuf, String> {
105 crate::core::data_dir::lean_ctx_data_dir().map(|d| d.join("claude-mod.declined"))
106}
107
108#[must_use]
110pub fn auto_install_declined() -> bool {
111 declined_marker().is_ok_and(|p| p.exists())
112}
113
114pub 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
136pub 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#[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#[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
185pub 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
209pub 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 run_claude(&["plugin", "marketplace", "add", &root_str])?;
224 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#[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#[must_use]
277pub fn cache_dir_name(version: &str) -> String {
278 version.replace('+', "-")
279}
280
281pub 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 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#[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
331fn 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 #[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(¤t));
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 #[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 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 #[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 #[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 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}