1use std::path::{Path, PathBuf};
21use std::process::Command;
22use std::time::{Duration, Instant};
23
24pub const MIN_CLAUDE_VERSION: (u32, u32, u32) = (2, 1, 287);
26pub const MARKETPLACE: &str = "lean-ctx";
28pub const PLUGIN_ID: &str = "lean-ctx@lean-ctx";
29
30pub const REGISTER_TS: &str = include_str!("../../templates/claude_mod/register.ts");
31pub const HOOKS_JSON: &str = include_str!("../../templates/claude_mod/hooks.json");
32pub const PLUGIN_JSON: &str = include_str!("../../templates/claude_mod/plugin.json");
34
35const CLAUDE_TIMEOUT: Duration = Duration::from_mins(1);
36
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub enum ModStatus {
39 ClaudeMissing,
41 ClaudeTooOld(String),
43 NotInstalled,
44 Current(String),
46 Stale(String),
48}
49
50impl ModStatus {
51 #[must_use]
52 pub fn describe(&self) -> String {
53 let want = mod_version();
54 match self {
55 Self::ClaudeMissing => "Claude Code not found on PATH".to_string(),
56 Self::ClaudeTooOld(v) => format!(
57 "Claude Code {v} predates mods (needs {}.{}.{}+)",
58 MIN_CLAUDE_VERSION.0, MIN_CLAUDE_VERSION.1, MIN_CLAUDE_VERSION.2
59 ),
60 Self::NotInstalled => "not installed".to_string(),
61 Self::Current(v) => format!("installed ({v})"),
62 Self::Stale(v) => {
63 format!("installed ({v}), this engine ships {want} — refresh pending")
64 }
65 }
66 }
67}
68
69#[must_use]
72pub fn mod_version() -> String {
73 let mut hasher = blake3::Hasher::new();
74 for part in [REGISTER_TS, HOOKS_JSON, PLUGIN_JSON] {
75 hasher.update(part.as_bytes());
76 hasher.update(&[0]);
77 }
78 let hash = hasher.finalize().to_hex();
79 format!("{}+{}", env!("CARGO_PKG_VERSION"), &hash[..8])
80}
81
82pub fn marketplace_dir() -> Result<PathBuf, String> {
84 crate::core::data_dir::lean_ctx_data_dir().map(|d| d.join("claude-mod"))
85}
86
87pub fn plugin_manifest() -> String {
89 let mut manifest: serde_json::Value =
90 serde_json::from_str(PLUGIN_JSON).expect("templates/claude_mod/plugin.json is valid JSON");
91 manifest["version"] = serde_json::json!(mod_version());
92 serde_json::to_string_pretty(&manifest).expect("manifest serializes") + "\n"
93}
94
95fn marketplace_manifest() -> String {
96 let manifest = serde_json::json!({
97 "name": MARKETPLACE,
98 "description": "lean-ctx's Claude Code mod, installed by the lean-ctx binary that serves it.",
99 "owner": { "name": "Thinkery / Yves Gugger" },
100 "plugins": [{
101 "name": "lean-ctx",
102 "source": "./plugins/lean-ctx",
103 "description": "Wake on background job completion, a focused lean-ctx tool surface, and per-session request usage.",
104 }]
105 });
106 serde_json::to_string_pretty(&manifest).expect("manifest serializes") + "\n"
107}
108
109pub fn materialize(root: &Path) -> Result<bool, String> {
112 let plugin = root.join("plugins").join("lean-ctx");
113 let files: [(PathBuf, String); 4] = [
114 (
115 root.join(".claude-plugin/marketplace.json"),
116 marketplace_manifest(),
117 ),
118 (plugin.join(".claude-plugin/plugin.json"), plugin_manifest()),
119 (plugin.join("hooks/hooks.json"), HOOKS_JSON.to_string()),
120 (plugin.join("hooks/register.ts"), REGISTER_TS.to_string()),
121 ];
122 let mut changed = false;
123 for (path, content) in files {
124 if std::fs::read_to_string(&path).is_ok_and(|on_disk| on_disk == content) {
125 continue;
126 }
127 if let Some(parent) = path.parent() {
128 std::fs::create_dir_all(parent)
129 .map_err(|e| format!("create {}: {e}", parent.display()))?;
130 }
131 std::fs::write(&path, content).map_err(|e| format!("write {}: {e}", path.display()))?;
132 changed = true;
133 }
134 Ok(changed)
135}
136
137#[must_use]
139pub fn parse_claude_version(output: &str) -> Option<(u32, u32, u32)> {
140 let token = output.split_whitespace().next()?;
141 let mut parts = token.split('.').map(|p| p.parse::<u32>().ok());
142 Some((parts.next()??, parts.next()??, parts.next()??))
143}
144
145#[must_use]
147pub fn installed_version(list_json: &str) -> Option<String> {
148 let entries: Vec<serde_json::Value> = serde_json::from_str(list_json).ok()?;
149 entries
150 .iter()
151 .find(|e| e.get("id").and_then(serde_json::Value::as_str) == Some(PLUGIN_ID))
152 .and_then(|e| e.get("version").and_then(serde_json::Value::as_str))
153 .map(str::to_string)
154}
155
156pub fn status() -> ModStatus {
158 let Ok(version_out) = run_claude(&["--version"]) else {
159 return ModStatus::ClaudeMissing;
160 };
161 let version = version_out
162 .split_whitespace()
163 .next()
164 .unwrap_or("")
165 .to_string();
166 match parse_claude_version(&version_out) {
167 Some(v) if v >= MIN_CLAUDE_VERSION => {}
168 _ => return ModStatus::ClaudeTooOld(version),
169 }
170 match run_claude(&["plugin", "list", "--json"])
171 .ok()
172 .and_then(|out| installed_version(&out))
173 {
174 None => ModStatus::NotInstalled,
175 Some(v) if v == mod_version() => ModStatus::Current(v),
176 Some(v) => ModStatus::Stale(v),
177 }
178}
179
180pub fn install() -> Result<String, String> {
183 let before = status();
184 match &before {
185 ModStatus::ClaudeMissing | ModStatus::ClaudeTooOld(_) => {
186 return Err(before.describe());
187 }
188 ModStatus::Current(_) | ModStatus::NotInstalled | ModStatus::Stale(_) => {}
189 }
190 let root = marketplace_dir()?;
191 materialize(&root)?;
192 let root_str = root.to_string_lossy().to_string();
193 run_claude(&["plugin", "marketplace", "add", &root_str])?;
195 match before {
196 ModStatus::NotInstalled => {
197 run_claude(&["plugin", "install", PLUGIN_ID, "--scope", "user"])?;
198 Ok(format!(
199 "installed {PLUGIN_ID} {} — active in new Claude Code sessions (or /reload-plugins)",
200 mod_version()
201 ))
202 }
203 ModStatus::Stale(old) => {
204 run_claude(&["plugin", "marketplace", "update", MARKETPLACE])?;
205 run_claude(&["plugin", "update", PLUGIN_ID, "--scope", "user"])?;
206 Ok(format!(
207 "updated {PLUGIN_ID} {old} → {} — applies in new sessions",
208 mod_version()
209 ))
210 }
211 _ => Ok(format!("{PLUGIN_ID} is current ({})", mod_version())),
212 }
213}
214
215#[must_use]
221pub fn cached_versions(claude_dir: &Path) -> Vec<String> {
222 let mut versions: Vec<String> = std::fs::read_dir(
223 claude_dir
224 .join("plugins/cache")
225 .join(MARKETPLACE)
226 .join("lean-ctx"),
227 )
228 .map(|entries| {
229 entries
230 .filter_map(Result::ok)
231 .filter(|e| e.path().is_dir())
232 .filter_map(|e| e.file_name().to_str().map(str::to_string))
233 .collect()
234 })
235 .unwrap_or_default();
236 versions.sort();
237 versions
238}
239
240#[must_use]
243pub fn cache_dir_name(version: &str) -> String {
244 version.replace('+', "-")
245}
246
247pub fn uninstall() -> Result<String, String> {
253 if matches!(status(), ModStatus::ClaudeMissing) {
254 return Err(ModStatus::ClaudeMissing.describe());
255 }
256 let uninstall = run_claude(&["plugin", "uninstall", PLUGIN_ID, "--scope", "user"]);
257 let remove = run_claude(&["plugin", "marketplace", "remove", MARKETPLACE]);
258 let still_installed =
259 run_claude(&["plugin", "list", "--json"]).map(|out| installed_version(&out).is_some())?;
260 let marketplace_listed = run_claude(&["plugin", "marketplace", "list", "--json"])
261 .map(|out| marketplace_listed(&out))?;
262 if still_installed || marketplace_listed {
263 let cause = uninstall.err().or(remove.err()).unwrap_or_default();
264 return Err(format!(
265 "{PLUGIN_ID} is still registered with Claude Code{}{cause} — local files kept",
266 if cause.is_empty() { "" } else { ": " }
267 ));
268 }
269 if let Ok(root) = marketplace_dir()
270 && root.exists()
271 {
272 std::fs::remove_dir_all(&root).map_err(|e| format!("remove {}: {e}", root.display()))?;
273 }
274 Ok(format!("removed {PLUGIN_ID}"))
275}
276
277#[must_use]
279pub fn marketplace_listed(list_json: &str) -> bool {
280 serde_json::from_str::<Vec<serde_json::Value>>(list_json).is_ok_and(|entries| {
281 entries
282 .iter()
283 .any(|e| e.get("name").and_then(serde_json::Value::as_str) == Some(MARKETPLACE))
284 })
285}
286
287fn run_claude(args: &[&str]) -> Result<String, String> {
292 use std::io::Read as _;
293 let label = || format!("claude {}", args.join(" "));
294 let binary = crate::core::editor_registry::validate_claude_binary()?;
295 let mut child = Command::new(&binary)
296 .args(args)
297 .stdin(std::process::Stdio::null())
298 .stdout(std::process::Stdio::piped())
299 .stderr(std::process::Stdio::piped())
300 .spawn()
301 .map_err(|e| format!("{}: {e}", label()))?;
302 let drain = |pipe: Option<Box<dyn std::io::Read + Send>>| {
303 std::thread::spawn(move || {
304 let mut buf = Vec::new();
305 if let Some(mut p) = pipe {
306 let _ = p.read_to_end(&mut buf);
307 }
308 String::from_utf8_lossy(&buf).into_owned()
309 })
310 };
311 let stdout = drain(child.stdout.take().map(|p| Box::new(p) as Box<_>));
312 let stderr = drain(child.stderr.take().map(|p| Box::new(p) as Box<_>));
313 let start = Instant::now();
314 let status = loop {
315 match child.try_wait() {
316 Ok(Some(status)) => break Ok(status),
317 Ok(None) if start.elapsed() > CLAUDE_TIMEOUT => {
318 break Err(format!("{} timed out", label()));
319 }
320 Ok(None) => std::thread::sleep(Duration::from_millis(50)),
321 Err(e) => break Err(format!("{}: {e}", label())),
322 }
323 };
324 let status = match status {
325 Ok(status) => status,
326 Err(e) => {
327 let _ = child.kill();
328 let _ = child.wait();
329 return Err(e);
330 }
331 };
332 let stdout = stdout.join().unwrap_or_default();
333 let stderr = stderr.join().unwrap_or_default();
334 if status.success() {
335 Ok(stdout)
336 } else {
337 let detail = stderr
338 .trim()
339 .lines()
340 .chain(stdout.trim().lines())
341 .last()
342 .unwrap_or("");
343 Err(format!("{} failed: {detail}", label()))
344 }
345}
346
347#[cfg(test)]
348mod tests {
349 use super::*;
350
351 #[test]
355 fn cache_dir_matches_the_installed_version() {
356 let dir = tempfile::tempdir().unwrap();
357 let cache = dir.path().join("plugins/cache/lean-ctx/lean-ctx");
358 let current = cache_dir_name(&mod_version());
359 for v in ["3.10.5", current.as_str()] {
360 std::fs::create_dir_all(cache.join(v)).unwrap();
361 }
362 assert!(cached_versions(dir.path()).contains(¤t));
363 assert!(!current.contains('+'), "{current}");
364 }
365
366 #[test]
367 fn version_gate_parses_claude_output() {
368 assert_eq!(
369 parse_claude_version("2.1.287 (Claude Code)"),
370 Some((2, 1, 287))
371 );
372 assert!(parse_claude_version("2.1.286 (Claude Code)").unwrap() < MIN_CLAUDE_VERSION);
373 assert!(parse_claude_version("2.2.0 (Claude Code)").unwrap() >= MIN_CLAUDE_VERSION);
374 assert_eq!(parse_claude_version("garbage"), None);
375 }
376
377 #[test]
379 fn installed_version_reads_only_our_plugin() {
380 let list = r#"[{"id":"other@x","version":"9.9.9"},
381 {"id":"lean-ctx@lean-ctx","version":"3.10.5","scope":"user"}]"#;
382 assert_eq!(installed_version(list).as_deref(), Some("3.10.5"));
383 assert_eq!(installed_version("[]"), None);
384 assert_eq!(installed_version("not json"), None);
385 let markets = r#"[{"name":"lean-ctx","source":"directory","path":"/d"}]"#;
388 assert!(marketplace_listed(markets));
389 assert!(!marketplace_listed(r#"[{"name":"other"}]"#));
390 assert!(!marketplace_listed("garbage"));
391 }
392
393 #[test]
398 fn materialize_stamps_engine_version_and_is_idempotent() {
399 let dir = tempfile::tempdir().unwrap();
400 assert!(materialize(dir.path()).unwrap());
401 let manifest: serde_json::Value = serde_json::from_str(
402 &std::fs::read_to_string(
403 dir.path()
404 .join("plugins/lean-ctx/.claude-plugin/plugin.json"),
405 )
406 .unwrap(),
407 )
408 .unwrap();
409 let version = manifest["version"].as_str().unwrap();
410 let (engine, hash) = version.split_once('+').expect("engine+hash version");
411 assert_eq!(engine, env!("CARGO_PKG_VERSION"));
412 assert!(
413 hash.len() == 8 && hash.chars().all(|c| c.is_ascii_hexdigit()),
414 "{version}"
415 );
416 assert_eq!(manifest["name"], "lean-ctx");
417 assert!(
418 std::fs::read_to_string(dir.path().join("plugins/lean-ctx/hooks/register.ts"))
419 .unwrap()
420 .contains("export const register")
421 );
422 assert!(
423 !materialize(dir.path()).unwrap(),
424 "second run must not rewrite"
425 );
426 }
427}