mi6_core/framework/
claude.rs

1//! Claude Code framework adapter.
2//!
3//! mi6 installs as a Claude Code plugin via the official marketplace system.
4//! The plugin files are embedded in the binary and written to `~/.mi6/claude-plugin/`
5//! during installation. This avoids needing a separate GitHub repo for the marketplace.
6//!
7//! # Installation Flow
8//!
9//! 1. `mi6 enable` writes embedded plugin files to `~/.mi6/claude-plugin/`
10//! 2. Registers the local directory as a marketplace via `claude plugin marketplace add`
11//! 3. Installs the plugin to user scope via `claude plugin install mi6@mi6 --scope user`
12//!
13//! # Uninstallation
14//!
15//! `mi6 disable` uninstalls via `claude plugin uninstall mi6@mi6`. It detects the
16//! installation scope to handle legacy project-scope installs correctly.
17
18use super::{FrameworkAdapter, ParsedHookInput, common};
19use crate::model::EventType;
20use crate::model::error::InitError;
21use std::path::{Path, PathBuf};
22use std::process::Command;
23
24/// Plugin identifier in format `plugin@marketplace`.
25const PLUGIN_ID: &str = "mi6@mi6";
26
27/// Embedded marketplace.json content.
28const MARKETPLACE_JSON: &str = include_str!("claude-plugin/marketplace.json");
29
30/// Embedded plugin.json content.
31const PLUGIN_JSON: &str = include_str!("claude-plugin/plugin.json");
32
33/// Embedded hooks.json content.
34const HOOKS_JSON: &str = include_str!("claude-plugin/hooks.json");
35
36/// Claude Code framework adapter.
37pub struct ClaudeAdapter;
38
39impl ClaudeAdapter {
40    /// Run a claude CLI command, optionally ignoring specific error patterns.
41    ///
42    /// When `ignore_patterns` contains strings that match the error output,
43    /// the command is treated as successful (for idempotent operations).
44    fn run_claude_command_opt(
45        args: &[&str],
46        cwd: Option<&Path>,
47        ignore_patterns: &[&str],
48    ) -> Result<(), InitError> {
49        let mut cmd = Command::new("claude");
50        cmd.args(args);
51        if let Some(dir) = cwd {
52            cmd.current_dir(dir);
53        }
54
55        let output = cmd
56            .output()
57            .map_err(|e| InitError::Config(format!("failed to run claude CLI: {e}")))?;
58
59        if !output.status.success() {
60            let stderr = String::from_utf8_lossy(&output.stderr);
61            let stdout = String::from_utf8_lossy(&output.stdout);
62            let combined = format!("{} {}", stderr.trim(), stdout.trim());
63
64            // Check if this is an expected "already done" error
65            if ignore_patterns.iter().any(|p| combined.contains(p)) {
66                return Ok(());
67            }
68
69            return Err(InitError::Config(format!(
70                "claude {} failed: {}",
71                args.first().unwrap_or(&"command"),
72                combined.trim()
73            )));
74        }
75
76        Ok(())
77    }
78
79    /// Run a claude CLI command.
80    fn run_claude_command(args: &[&str]) -> Result<(), InitError> {
81        Self::run_claude_command_opt(args, None, &[])
82    }
83
84    /// Get the path to the local marketplace cache directory (`~/.mi6/claude-plugin/`).
85    fn marketplace_cache_path() -> Result<PathBuf, InitError> {
86        let home = dirs::home_dir()
87            .ok_or_else(|| InitError::Config("could not determine home directory".to_string()))?;
88        Ok(home.join(".mi6/claude-plugin"))
89    }
90
91    /// Write embedded marketplace files to the local cache.
92    ///
93    /// Creates:
94    /// ```text
95    /// ~/.mi6/claude-plugin/
96    /// ├── .claude-plugin/marketplace.json
97    /// └── plugins/mi6/
98    ///     ├── .claude-plugin/plugin.json
99    ///     └── hooks/hooks.json
100    /// ```
101    fn write_marketplace_to_cache() -> Result<PathBuf, InitError> {
102        let cache_path = Self::marketplace_cache_path()?;
103
104        let marketplace_meta = cache_path.join(".claude-plugin");
105        let plugin_meta = cache_path.join("plugins/mi6/.claude-plugin");
106        let hooks_dir = cache_path.join("plugins/mi6/hooks");
107
108        // Create all directories
109        for dir in [&marketplace_meta, &plugin_meta, &hooks_dir] {
110            std::fs::create_dir_all(dir).map_err(|e| {
111                InitError::Config(format!("failed to create {}: {e}", dir.display()))
112            })?;
113        }
114
115        // Write embedded files
116        let files = [
117            (marketplace_meta.join("marketplace.json"), MARKETPLACE_JSON),
118            (plugin_meta.join("plugin.json"), PLUGIN_JSON),
119            (hooks_dir.join("hooks.json"), HOOKS_JSON),
120        ];
121
122        for (path, content) in files {
123            std::fs::write(&path, content).map_err(|e| {
124                InitError::Config(format!("failed to write {}: {e}", path.display()))
125            })?;
126        }
127
128        Ok(cache_path)
129    }
130
131    /// Check if the mi6 plugin is enabled in settings.json.
132    fn is_plugin_installed() -> bool {
133        let Some(home) = dirs::home_dir() else {
134            return false;
135        };
136        let settings_path = home.join(".claude/settings.json");
137        let Ok(contents) = std::fs::read_to_string(&settings_path) else {
138            return false;
139        };
140        let Ok(json) = serde_json::from_str::<serde_json::Value>(&contents) else {
141            return false;
142        };
143        json.get("enabledPlugins")
144            .is_some_and(|enabled| enabled.get(PLUGIN_ID).is_some())
145    }
146
147    /// Get the installation scope and project path from installed_plugins.json.
148    ///
149    /// Returns `Some((scope, project_path))` where:
150    /// - `scope` is "user" or "project"
151    /// - `project_path` is only present for project-scope installs
152    fn get_plugin_install_scope() -> Option<(String, Option<PathBuf>)> {
153        let home = dirs::home_dir()?;
154        let plugins_path = home.join(".claude/plugins/installed_plugins.json");
155        let contents = std::fs::read_to_string(&plugins_path).ok()?;
156        let json: serde_json::Value = serde_json::from_str(&contents).ok()?;
157
158        // Structure: { "plugins": { "mi6@mi6": [{ "scope": "...", "projectPath": "..." }] } }
159        let install = json.get("plugins")?.get(PLUGIN_ID)?.as_array()?.first()?;
160
161        let scope = install.get("scope")?.as_str()?.to_string();
162        let project_path = install
163            .get("projectPath")
164            .and_then(|v| v.as_str())
165            .map(PathBuf::from);
166
167        Some((scope, project_path))
168    }
169}
170
171impl FrameworkAdapter for ClaudeAdapter {
172    fn name(&self) -> &'static str {
173        "claude"
174    }
175
176    fn display_name(&self) -> &'static str {
177        "Claude Code"
178    }
179
180    fn project_config_path(&self) -> PathBuf {
181        // For marketplace plugins, there's no local config to edit
182        // Return a placeholder path
183        PathBuf::from(".claude/plugins/mi6/hooks/hooks.json")
184    }
185
186    fn user_config_path(&self) -> Option<PathBuf> {
187        // For marketplace plugins, Claude manages the installation path
188        None
189    }
190
191    fn generate_hooks_config(
192        &self,
193        enabled_events: &[EventType],
194        mi6_bin: &str,
195        otel_enabled: bool,
196        otel_port: u16,
197    ) -> serde_json::Value {
198        // This is used for --print mode to show what hooks would be configured
199        let mut hooks = serde_json::Map::new();
200
201        for event in enabled_events {
202            let command = if otel_enabled && *event == EventType::SessionStart {
203                format!(
204                    "{} otel start --port {} </dev/null >/dev/null 2>&1; {} ingest event {} --framework claude",
205                    mi6_bin, otel_port, mi6_bin, event
206                )
207            } else {
208                format!("{} ingest event {} --framework claude", mi6_bin, event)
209            };
210
211            let hook_entry = serde_json::json!([{
212                "matcher": "*",
213                "hooks": [{
214                    "type": "command",
215                    "command": command,
216                    "timeout": 10
217                }]
218            }]);
219            hooks.insert(event.to_string(), hook_entry);
220        }
221
222        serde_json::json!({ "hooks": hooks })
223    }
224
225    fn merge_config(
226        &self,
227        generated: serde_json::Value,
228        _existing: Option<serde_json::Value>,
229    ) -> serde_json::Value {
230        generated
231    }
232
233    fn parse_hook_input(
234        &self,
235        _event_type: &str,
236        stdin_json: &serde_json::Value,
237    ) -> ParsedHookInput {
238        ParsedHookInput {
239            session_id: stdin_json
240                .get("session_id")
241                .and_then(|v| v.as_str())
242                .map(String::from),
243            tool_use_id: stdin_json
244                .get("tool_use_id")
245                .and_then(|v| v.as_str())
246                .map(String::from),
247            tool_name: stdin_json
248                .get("tool_name")
249                .and_then(|v| v.as_str())
250                .map(String::from),
251            cwd: stdin_json
252                .get("cwd")
253                .and_then(|v| v.as_str())
254                .map(String::from),
255            permission_mode: stdin_json
256                .get("permission_mode")
257                .and_then(|v| v.as_str())
258                .map(String::from),
259            transcript_path: stdin_json
260                .get("transcript_path")
261                .and_then(|v| v.as_str())
262                .map(String::from),
263            subagent_type: stdin_json
264                .get("tool_input")
265                .and_then(|ti| ti.get("subagent_type"))
266                .and_then(|v| v.as_str())
267                .map(String::from),
268            spawned_agent_id: stdin_json
269                .get("tool_response")
270                .and_then(|tr| tr.get("agentId"))
271                .and_then(|v| v.as_str())
272                .map(String::from),
273            // SessionStart source field (startup, resume, clear)
274            session_source: stdin_json
275                .get("source")
276                .and_then(|v| v.as_str())
277                .map(String::from),
278            // SubagentStart/SubagentStop agent_id field
279            agent_id: stdin_json
280                .get("agent_id")
281                .and_then(|v| v.as_str())
282                .map(String::from),
283            // SubagentStop agent_transcript_path field
284            agent_transcript_path: stdin_json
285                .get("agent_transcript_path")
286                .and_then(|v| v.as_str())
287                .map(String::from),
288            // PreCompact trigger field (manual, auto)
289            compact_trigger: stdin_json
290                .get("trigger")
291                .and_then(|v| v.as_str())
292                .map(String::from),
293        }
294    }
295
296    fn map_event_type(&self, framework_event: &str) -> EventType {
297        framework_event
298            .parse()
299            .unwrap_or_else(|_| EventType::Custom(framework_event.to_string()))
300    }
301
302    fn supported_events(&self) -> Vec<&'static str> {
303        vec![
304            "SessionStart",
305            "SessionEnd",
306            "PreToolUse",
307            "PostToolUse",
308            "PermissionRequest",
309            "PreCompact",
310            "Stop",
311            "SubagentStart",
312            "SubagentStop",
313            "Notification",
314            "UserPromptSubmit",
315        ]
316    }
317
318    fn detection_env_vars(&self) -> &[&'static str] {
319        &["CLAUDE_SESSION_ID", "CLAUDE_PROJECT_DIR"]
320    }
321
322    fn is_installed(&self) -> bool {
323        common::is_framework_installed(dirs::home_dir().map(|h| h.join(".claude")), "claude")
324    }
325
326    fn remove_hooks(&self, _existing: serde_json::Value) -> Option<serde_json::Value> {
327        None
328    }
329
330    // ========================================================================
331    // Marketplace-based installation
332    // ========================================================================
333
334    fn settings_path(&self, _local: bool, _settings_local: bool) -> Result<PathBuf, InitError> {
335        // For marketplace plugins, we don't write to a specific path
336        // Return a placeholder that indicates marketplace installation
337        Ok(PathBuf::from("marketplace://mi6@mi6-plugin"))
338    }
339
340    fn has_mi6_hooks(&self, _local: bool, _settings_local: bool) -> bool {
341        Self::is_plugin_installed()
342    }
343
344    fn install_hooks(
345        &self,
346        _path: &std::path::Path,
347        _hooks: &serde_json::Value,
348        _otel_env: Option<serde_json::Value>,
349        _remove_otel: bool,
350    ) -> Result<(), InitError> {
351        // Write embedded marketplace files to local cache
352        let cache_path = Self::write_marketplace_to_cache()?;
353        let cache_path_str = cache_path.to_string_lossy();
354
355        // Add the marketplace (idempotent - ignore if already registered)
356        Self::run_claude_command_opt(
357            &["plugin", "marketplace", "add", &cache_path_str],
358            None,
359            &["already installed", "already added", "already registered"],
360        )?;
361
362        // Install the plugin to user scope (idempotent - ignore if already installed)
363        Self::run_claude_command_opt(
364            &["plugin", "install", PLUGIN_ID, "--scope", "user"],
365            None,
366            &["already installed", "already enabled"],
367        )?;
368
369        Ok(())
370    }
371
372    fn uninstall_hooks(&self, _local: bool, _settings_local: bool) -> Result<bool, InitError> {
373        if !Self::is_plugin_installed() {
374            return Ok(false);
375        }
376
377        // Determine the installation scope to use the correct uninstall command
378        match Self::get_plugin_install_scope() {
379            Some((scope, Some(project_path))) if scope == "project" => {
380                // Project-scope: must run from the project directory
381                Self::run_claude_command_opt(
382                    &["plugin", "uninstall", PLUGIN_ID, "--scope", "project"],
383                    Some(&project_path),
384                    &[],
385                )?;
386            }
387            _ => {
388                // User scope (default) or unknown - try user scope
389                Self::run_claude_command(&["plugin", "uninstall", PLUGIN_ID, "--scope", "user"])?;
390            }
391        }
392
393        Ok(true)
394    }
395}
396
397#[cfg(test)]
398mod tests {
399    use super::*;
400
401    #[test]
402    fn test_name() {
403        let adapter = ClaudeAdapter;
404        assert_eq!(adapter.name(), "claude");
405        assert_eq!(adapter.display_name(), "Claude Code");
406    }
407
408    #[test]
409    fn test_map_event_type() {
410        let adapter = ClaudeAdapter;
411        assert_eq!(
412            adapter.map_event_type("SessionStart"),
413            EventType::SessionStart
414        );
415        assert_eq!(adapter.map_event_type("PreToolUse"), EventType::PreToolUse);
416        assert_eq!(
417            adapter.map_event_type("CustomEvent"),
418            EventType::Custom("CustomEvent".to_string())
419        );
420    }
421
422    #[test]
423    fn test_parse_hook_input() {
424        let adapter = ClaudeAdapter;
425        let input = serde_json::json!({
426            "session_id": "test-session",
427            "tool_use_id": "tool-123",
428            "tool_name": "Bash",
429            "cwd": "/projects/test",
430            "permission_mode": "default",
431            "tool_input": {
432                "subagent_type": "Explore"
433            },
434            "tool_response": {
435                "agentId": "agent-456"
436            }
437        });
438
439        let parsed = adapter.parse_hook_input("PreToolUse", &input);
440
441        assert_eq!(parsed.session_id, Some("test-session".to_string()));
442        assert_eq!(parsed.tool_use_id, Some("tool-123".to_string()));
443        assert_eq!(parsed.tool_name, Some("Bash".to_string()));
444        assert_eq!(parsed.cwd, Some("/projects/test".to_string()));
445        assert_eq!(parsed.permission_mode, Some("default".to_string()));
446        assert_eq!(parsed.subagent_type, Some("Explore".to_string()));
447        assert_eq!(parsed.spawned_agent_id, Some("agent-456".to_string()));
448    }
449
450    #[test]
451    fn test_parse_hook_input_new_fields() {
452        let adapter = ClaudeAdapter;
453
454        // Test SessionStart with source field
455        let session_start_input = serde_json::json!({
456            "session_id": "test-session",
457            "source": "startup",
458            "cwd": "/projects/test"
459        });
460        let parsed = adapter.parse_hook_input("SessionStart", &session_start_input);
461        assert_eq!(parsed.session_source, Some("startup".to_string()));
462
463        // Test SubagentStop with agent_id and agent_transcript_path
464        let subagent_stop_input = serde_json::json!({
465            "session_id": "parent-session",
466            "agent_id": "subagent-123",
467            "agent_transcript_path": "/tmp/transcripts/subagent.jsonl"
468        });
469        let parsed = adapter.parse_hook_input("SubagentStop", &subagent_stop_input);
470        assert_eq!(parsed.agent_id, Some("subagent-123".to_string()));
471        assert_eq!(
472            parsed.agent_transcript_path,
473            Some("/tmp/transcripts/subagent.jsonl".to_string())
474        );
475
476        // Test PreCompact with trigger field
477        let pre_compact_input = serde_json::json!({
478            "session_id": "test-session",
479            "trigger": "auto"
480        });
481        let parsed = adapter.parse_hook_input("PreCompact", &pre_compact_input);
482        assert_eq!(parsed.compact_trigger, Some("auto".to_string()));
483    }
484
485    #[test]
486    fn test_generate_hooks_config() -> Result<(), String> {
487        let adapter = ClaudeAdapter;
488        let events = vec![EventType::SessionStart, EventType::PreToolUse];
489
490        let config = adapter.generate_hooks_config(&events, "mi6", false, 4318);
491
492        let hooks = config
493            .get("hooks")
494            .ok_or("missing hooks")?
495            .as_object()
496            .ok_or("hooks not an object")?;
497        assert!(hooks.contains_key("SessionStart"));
498        assert!(hooks.contains_key("PreToolUse"));
499
500        let session_start = &hooks["SessionStart"][0]["hooks"][0];
501        let command = session_start["command"].as_str().ok_or("missing command")?;
502        assert!(command.contains("mi6 ingest event SessionStart"));
503        assert!(command.contains("--framework claude"));
504        Ok(())
505    }
506
507    #[test]
508    fn test_generate_hooks_config_with_otel() -> Result<(), String> {
509        let adapter = ClaudeAdapter;
510        let events = vec![EventType::SessionStart];
511
512        let config = adapter.generate_hooks_config(&events, "mi6", true, 4318);
513
514        let hooks = config
515            .get("hooks")
516            .ok_or("missing hooks")?
517            .as_object()
518            .ok_or("hooks not an object")?;
519        let session_start = &hooks["SessionStart"][0]["hooks"][0];
520        let command = session_start["command"].as_str().ok_or("missing command")?;
521
522        assert!(command.contains("otel start"));
523        assert!(command.contains("--port 4318"));
524        assert!(command.contains("--framework claude"));
525        Ok(())
526    }
527
528    #[test]
529    fn test_generate_hooks_config_matcher_structure() -> Result<(), String> {
530        let adapter = ClaudeAdapter;
531        let events = vec![
532            EventType::SessionStart,
533            EventType::PreToolUse,
534            EventType::PostToolUse,
535        ];
536
537        let config = adapter.generate_hooks_config(&events, "mi6", false, 4318);
538        let hooks = config.get("hooks").ok_or("missing hooks")?;
539
540        // All events should have matcher field with "*" for wildcard
541        for event in &events {
542            let hook = &hooks[event.to_string()][0];
543            assert_eq!(
544                hook.get("matcher").and_then(|m| m.as_str()),
545                Some("*"),
546                "{} should have matcher: \"*\"",
547                event
548            );
549        }
550
551        Ok(())
552    }
553
554    #[test]
555    fn test_plugin_constants() {
556        assert_eq!(PLUGIN_ID, "mi6@mi6");
557    }
558
559    #[test]
560    fn test_embedded_marketplace_files() {
561        // Verify embedded files are valid JSON
562        let _: serde_json::Value =
563            serde_json::from_str(MARKETPLACE_JSON).expect("marketplace.json should be valid JSON");
564        let _: serde_json::Value =
565            serde_json::from_str(PLUGIN_JSON).expect("plugin.json should be valid JSON");
566        let _: serde_json::Value =
567            serde_json::from_str(HOOKS_JSON).expect("hooks.json should be valid JSON");
568    }
569}