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 RENDER_TSX: &str = include_str!("../../templates/claude_mod/render.tsx");
41pub const TYPES_DTS: &str = include_str!("../../templates/claude_mod/cockpit.d.ts");
43pub 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 ClaudeMissing(String),
53 ClaudeTooOld(String),
55 NotInstalled,
56 Current(String),
58 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#[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
101pub fn marketplace_dir() -> Result<PathBuf, String> {
103 crate::core::data_dir::lean_ctx_data_dir().map(|d| d.join("claude-mod"))
104}
105
106pub 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
113fn declined_marker() -> Result<PathBuf, String> {
116 crate::core::data_dir::lean_ctx_data_dir().map(|d| d.join("claude-mod.declined"))
117}
118
119#[must_use]
121pub fn auto_install_declined() -> bool {
122 declined_marker().is_ok_and(|p| p.exists())
123}
124
125pub 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
147pub 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#[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#[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
197pub 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
222pub 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 run_claude(&["plugin", "marketplace", "add", &root_str])?;
237 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#[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#[must_use]
290pub fn cache_dir_name(version: &str) -> String {
291 version.replace('+', "-")
292}
293
294pub 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 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#[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
344fn 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 #[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(¤t));
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 #[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 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 #[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 #[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 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 #[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}