| 1 | //! `/import-claude`: explicit, reviewable migration from Claude Code (#5557). |
| 2 | //! |
| 3 | //! Reads `~/.claude.json` and `~/.claude/settings.json` (bounded, read-only) |
| 4 | //! and builds a plan — never a silent import: |
| 5 | //! |
| 6 | //! - **MCP servers** are surfaced through the existing external-import consent |
| 7 | //! flow (`/mcp import <name> --approve`); nothing merges automatically. |
| 8 | //! - **Env vars** that are known-safe (timeouts, output caps, editor choices) |
| 9 | //! are proposed as a portable bundle file for `codewhale config import`, |
| 10 | //! which carries its own plan/consent/rollback. Secret-shaped or unknown |
| 11 | //! keys are named but never imported or echoed. |
| 12 | //! - **Permissions** become approval-policy recommendations in a written |
| 13 | //! report (Claude rule grammar does not map 1:1; nothing is auto-applied). |
| 14 | //! - **Hooks** and **paths** (e.g. `~/.claude/CLAUDE.md`) are listed as manual |
| 15 | //! follow-ups with exact target commands. |
| 16 | //! |
| 17 | //! The plan model and all rendering live in the contract and the portable |
| 18 | //! group; this module only reads the Claude sources and builds the plan. |
| 19 | |
| 20 | use codewhale_command_contract::config::{ |
| 21 | CommandClaudePlan, CommandMcpCandidate, CommandSourceStatus, |
| 22 | }; |
| 23 | use serde_json::Value; |
| 24 | use std::path::{Path, PathBuf}; |
| 25 | |
| 26 | /// Maximum size accepted for any single Claude source file. Generous for |
| 27 | /// real `~/.claude.json` files with many projects; bounded so a pathological |
| 28 | /// file cannot exhaust memory. Matches the bundle reader's order of magnitude. |
| 29 | pub const MAX_SOURCE_BYTES: u64 = 5 * 1024 * 1024; |
| 30 | |
| 31 | /// Env keys safe to propose for the portable bundle (lowercase). Deliberately |
| 32 | /// a short allowlist: timeouts, output caps, and editor/telemetry choices. |
| 33 | /// Anything not listed stays out of the bundle and is reported by name only. |
| 34 | const SAFE_ENV_KEYS: &[&str] = &[ |
| 35 | "bash_default_timeout_ms", |
| 36 | "bash_max_timeout_ms", |
| 37 | "bash_max_output_length", |
| 38 | "bash_mcp_timeout_ms", |
| 39 | "mcp_timeout_ms", |
| 40 | "mcp_tools_timeout_ms", |
| 41 | "use_builtin_ripgrep", |
| 42 | "editor", |
| 43 | "max_thinking_tokens", |
| 44 | "disable_cost_warnings", |
| 45 | "disable_nonessential_model_calls", |
| 46 | "disable_telemetry", |
| 47 | ]; |
| 48 | |
| 49 | /// Longest env value accepted into the bundle; guards against blob-shaped |
| 50 | /// values a migration should not carry. |
| 51 | const MAX_ENV_VALUE_LEN: usize = 200; |
| 52 | |
| 53 | fn read_bounded_json(path: &Path) -> Result<Value, CommandSourceStatus> { |
| 54 | use std::io::Read; |
| 55 | |
| 56 | let file = std::fs::File::open(path).map_err(|e| match e.kind() { |
| 57 | std::io::ErrorKind::NotFound => CommandSourceStatus::NotFound, |
| 58 | _ => CommandSourceStatus::Unreadable(e.to_string()), |
| 59 | })?; |
| 60 | let meta = file |
| 61 | .metadata() |
| 62 | .map_err(|e| CommandSourceStatus::Unreadable(e.to_string()))?; |
| 63 | if !meta.is_file() { |
| 64 | return Err(CommandSourceStatus::NotFound); |
| 65 | } |
| 66 | if meta.len() > MAX_SOURCE_BYTES { |
| 67 | return Err(CommandSourceStatus::Oversize(meta.len())); |
| 68 | } |
| 69 | let mut raw = Vec::new(); |
| 70 | file.take(MAX_SOURCE_BYTES + 1) |
| 71 | .read_to_end(&mut raw) |
| 72 | .map_err(|e| CommandSourceStatus::Unreadable(e.to_string()))?; |
| 73 | if raw.len() as u64 > MAX_SOURCE_BYTES { |
| 74 | return Err(CommandSourceStatus::Oversize(raw.len() as u64)); |
| 75 | } |
| 76 | serde_json::from_slice::<Value>(&raw) |
| 77 | .map_err(|e| CommandSourceStatus::InvalidJson(e.to_string())) |
| 78 | } |
| 79 | |
| 80 | /// Read the Claude sources under `home` (usually `~`). |
| 81 | pub fn read_sources( |
| 82 | home: &Path, |
| 83 | ) -> ( |
| 84 | Vec<(PathBuf, CommandSourceStatus)>, |
| 85 | Option<Value>, |
| 86 | Option<Value>, |
| 87 | ) { |
| 88 | let claude_json = home.join(".claude.json"); |
| 89 | let settings = home.join(".claude").join("settings.json"); |
| 90 | let mut sources = Vec::new(); |
| 91 | let mut claude_value = None; |
| 92 | let mut settings_value = None; |
| 93 | match read_bounded_json(&claude_json) { |
| 94 | Ok(value) => { |
| 95 | sources.push((claude_json.clone(), CommandSourceStatus::Found)); |
| 96 | claude_value = Some(value); |
| 97 | } |
| 98 | Err(status) => sources.push((claude_json, status)), |
| 99 | } |
| 100 | match read_bounded_json(&settings) { |
| 101 | Ok(value) => { |
| 102 | sources.push((settings.clone(), CommandSourceStatus::Found)); |
| 103 | settings_value = Some(value); |
| 104 | } |
| 105 | Err(status) => sources.push((settings, status)), |
| 106 | } |
| 107 | (sources, claude_value, settings_value) |
| 108 | } |
| 109 | |
| 110 | fn safe_env_value(value: &Value) -> Option<String> { |
| 111 | let text = match value { |
| 112 | Value::String(text) => { |
| 113 | (text.len() <= MAX_ENV_VALUE_LEN && !text.contains('\n')).then(|| text.clone()) |
| 114 | } |
| 115 | Value::Number(number) => Some(number.to_string()), |
| 116 | Value::Bool(flag) => Some(flag.to_string()), |
| 117 | _ => None, |
| 118 | }?; |
| 119 | (codewhale_config::persistence::redact_secrets(&text) == text).then_some(text) |
| 120 | } |
| 121 | |
| 122 | /// Build the plan from already-read sources plus MCP candidates discovered by |
| 123 | /// the existing external-import machinery (so server parsing stays single-sourced). |
| 124 | pub fn build_plan( |
| 125 | sources: Vec<(PathBuf, CommandSourceStatus)>, |
| 126 | claude: Option<Value>, |
| 127 | settings: Option<Value>, |
| 128 | home: &Path, |
| 129 | mcp_candidates: Vec<CommandMcpCandidate>, |
| 130 | ) -> CommandClaudePlan { |
| 131 | let mut plan = CommandClaudePlan { |
| 132 | sources, |
| 133 | mcp_candidates, |
| 134 | ..CommandClaudePlan::default() |
| 135 | }; |
| 136 | if let Some(claude) = claude.as_ref() |
| 137 | && let Some(projects) = claude.get("projects").and_then(Value::as_object) |
| 138 | { |
| 139 | for (path, project) in projects { |
| 140 | if let Some(servers) = project.get("mcpServers").and_then(Value::as_object) { |
| 141 | for name in servers.keys() { |
| 142 | plan.per_project_mcp |
| 143 | .push(format!("{name} (project {path})")); |
| 144 | } |
| 145 | } |
| 146 | if plan.claude_projects.len() < 8 { |
| 147 | plan.claude_projects.push(path.clone()); |
| 148 | } |
| 149 | } |
| 150 | } |
| 151 | if let Some(settings) = settings.as_ref() { |
| 152 | if let Some(env) = settings.get("env").and_then(Value::as_object) { |
| 153 | for (key, value) in env { |
| 154 | if SAFE_ENV_KEYS.contains(&key.to_ascii_lowercase().as_str()) { |
| 155 | match safe_env_value(value) { |
| 156 | Some(text) => { |
| 157 | plan.env_safe.push((key.clone(), text)); |
| 158 | } |
| 159 | None => plan.env_skipped.push(format!("{key} (value not portable)")), |
| 160 | } |
| 161 | } else { |
| 162 | plan.env_skipped.push(key.clone()); |
| 163 | } |
| 164 | } |
| 165 | } |
| 166 | if let Some(permissions) = settings.get("permissions").and_then(Value::as_object) { |
| 167 | plan.permissions_default_mode = permissions |
| 168 | .get("defaultMode") |
| 169 | .and_then(Value::as_str) |
| 170 | .map(str::to_string); |
| 171 | for (key, target) in [ |
| 172 | ("allow", &mut plan.permissions_allow), |
| 173 | ("ask", &mut plan.permissions_ask), |
| 174 | ("deny", &mut plan.permissions_deny), |
| 175 | ] { |
| 176 | if let Some(rules) = permissions.get(key).and_then(Value::as_array) { |
| 177 | for rule in rules { |
| 178 | if let Some(text) = rule.as_str() { |
| 179 | target.push(codewhale_config::persistence::redact_secrets(text)); |
| 180 | } |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | if let Some(hooks) = settings.get("hooks").and_then(Value::as_object) { |
| 186 | for (event, entries) in hooks { |
| 187 | let count = entries.as_array().map_or(1, Vec::len); |
| 188 | plan.hook_events.push(format!("{event} ({count})")); |
| 189 | } |
| 190 | } |
| 191 | } |
| 192 | plan.has_claude_md = home.join(".claude").join("CLAUDE.md").is_file(); |
| 193 | plan.env_safe.sort(); |
| 194 | plan |
| 195 | } |
| 196 | |
| 197 | #[cfg(test)] |
| 198 | mod tests { |
| 199 | use super::*; |
| 200 | use serde_json::json; |
| 201 | |
| 202 | fn temp_home(tag: &str) -> (tempfile::TempDir, PathBuf) { |
| 203 | let dir = tempfile::tempdir().expect("home"); |
| 204 | let _ = tag; |
| 205 | let home = dir.path().to_path_buf(); |
| 206 | (dir, home) |
| 207 | } |
| 208 | |
| 209 | fn env_safe_value(plan: &CommandClaudePlan, key: &str) -> Option<String> { |
| 210 | plan.env_safe |
| 211 | .iter() |
| 212 | .find(|(k, _)| k == key) |
| 213 | .map(|(_, v)| v.clone()) |
| 214 | } |
| 215 | |
| 216 | #[test] |
| 217 | fn missing_sources_report_not_found_and_plan_is_empty() { |
| 218 | let (dir, home) = temp_home("missing"); |
| 219 | let (sources, claude, settings) = read_sources(&home); |
| 220 | let plan = build_plan(sources, claude, settings, &home, Vec::new()); |
| 221 | assert!(plan.is_empty()); |
| 222 | assert!( |
| 223 | plan.sources |
| 224 | .iter() |
| 225 | .any(|(_, s)| *s == CommandSourceStatus::NotFound) |
| 226 | ); |
| 227 | assert!(dir.path().exists()); |
| 228 | } |
| 229 | |
| 230 | #[test] |
| 231 | fn settings_env_splits_safe_and_skipped_without_ever_inlining_secret_values() { |
| 232 | let (_dir, home) = temp_home("env"); |
| 233 | std::fs::create_dir_all(home.join(".claude")).expect("dir"); |
| 234 | std::fs::write( |
| 235 | home.join(".claude").join("settings.json"), |
| 236 | json!({ |
| 237 | "env": { |
| 238 | "BASH_DEFAULT_TIMEOUT_MS": "120000", |
| 239 | "USE_BUILTIN_RIPGREP": "1", |
| 240 | "EDITOR": "sk-editor-secret-value", |
| 241 | "ANTHROPIC_API_KEY": "sk-ant-secret-value", |
| 242 | "SOMETHING_ELSE": "x" |
| 243 | }, |
| 244 | "permissions": { |
| 245 | "defaultMode": "acceptEdits", |
| 246 | "allow": ["Bash(git status:*)", "WebFetch(domain:github.com)", "mcp__demo__kick", "Bash(curl -H token=sk-rule-secret-value)"] , |
| 247 | "deny": ["Read(./.env)"] |
| 248 | }, |
| 249 | "hooks": { |
| 250 | "PreToolUse": [{"matcher": "Bash", "hooks": [{"type": "command", "command": "echo hi"}]}], |
| 251 | "PostToolUse": [] |
| 252 | } |
| 253 | }) |
| 254 | .to_string(), |
| 255 | ) |
| 256 | .expect("settings"); |
| 257 | |
| 258 | let (sources, _claude, settings) = read_sources(&home); |
| 259 | let plan = build_plan(sources, None, settings, &home, Vec::new()); |
| 260 | assert_eq!( |
| 261 | env_safe_value(&plan, "BASH_DEFAULT_TIMEOUT_MS").as_deref(), |
| 262 | Some("120000") |
| 263 | ); |
| 264 | assert!(env_safe_value(&plan, "USE_BUILTIN_RIPGREP").is_some()); |
| 265 | assert!(env_safe_value(&plan, "EDITOR").is_none()); |
| 266 | assert!(env_safe_value(&plan, "ANTHROPIC_API_KEY").is_none()); |
| 267 | assert!( |
| 268 | plan.env_skipped |
| 269 | .iter() |
| 270 | .any(|k| k.contains("ANTHROPIC_API_KEY")) |
| 271 | ); |
| 272 | assert_eq!( |
| 273 | plan.permissions_default_mode.as_deref(), |
| 274 | Some("acceptEdits") |
| 275 | ); |
| 276 | assert_eq!(plan.permissions_allow.len(), 4); |
| 277 | assert!( |
| 278 | plan.permissions_allow |
| 279 | .iter() |
| 280 | .any(|rule| rule.contains("[redacted]")) |
| 281 | ); |
| 282 | assert_eq!(plan.permissions_deny.len(), 1); |
| 283 | assert_eq!(plan.hook_events.len(), 2); |
| 284 | } |
| 285 | |
| 286 | #[test] |
| 287 | fn claude_json_surfaces_projects_and_per_project_servers() { |
| 288 | let (dir, home) = temp_home("projects"); |
| 289 | std::fs::write( |
| 290 | home.join(".claude.json"), |
| 291 | json!({ |
| 292 | "mcpServers": { |
| 293 | "top": {"command": "node", "args": ["top.js"]} |
| 294 | }, |
| 295 | "projects": { |
| 296 | "/tmp/proj-a": {"mcpServers": {"inner": {"command": "node"}}} |
| 297 | } |
| 298 | }) |
| 299 | .to_string(), |
| 300 | ) |
| 301 | .expect("claude.json"); |
| 302 | |
| 303 | let (sources, claude, _settings) = read_sources(&home); |
| 304 | let candidates = vec![CommandMcpCandidate { |
| 305 | name: "top".to_string(), |
| 306 | summary: "stdio server (node)".to_string(), |
| 307 | hard_blocked: false, |
| 308 | }]; |
| 309 | let plan = build_plan(sources, claude, None, &home, candidates); |
| 310 | assert_eq!(plan.mcp_candidates.len(), 1); |
| 311 | assert_eq!(plan.per_project_mcp.len(), 1); |
| 312 | assert!(plan.per_project_mcp[0].contains("inner")); |
| 313 | assert!(plan.claude_projects.iter().any(|p| p.contains("proj-a"))); |
| 314 | assert!(dir.path().exists()); |
| 315 | } |
| 316 | |
| 317 | #[test] |
| 318 | fn oversize_and_invalid_sources_fail_closed_with_named_status() { |
| 319 | let (_dir, home) = temp_home("bad"); |
| 320 | std::fs::write(home.join(".claude.json"), "not json").expect("bad json"); |
| 321 | let (sources, claude, _settings) = read_sources(&home); |
| 322 | assert!(claude.is_none()); |
| 323 | let status = sources |
| 324 | .iter() |
| 325 | .find_map(|(_, s)| matches!(s, CommandSourceStatus::InvalidJson(_)).then_some(s)) |
| 326 | .expect("invalid json status"); |
| 327 | let rendered = status.describe("~/.claude.json"); |
| 328 | assert!( |
| 329 | rendered.starts_with("invalid JSON: ~/.claude.json ("), |
| 330 | "{rendered}" |
| 331 | ); |
| 332 | assert!(rendered.contains("line 1"), "{rendered}"); |
| 333 | assert!(rendered.contains("column 2"), "{rendered}"); |
| 334 | |
| 335 | let oversize = vec![b' '; (MAX_SOURCE_BYTES + 1) as usize]; |
| 336 | std::fs::write(home.join(".claude.json"), oversize).expect("oversize json"); |
| 337 | let (sources, claude, _settings) = read_sources(&home); |
| 338 | assert!(claude.is_none()); |
| 339 | assert!( |
| 340 | sources.iter().any( |
| 341 | |(_, s)| matches!(s, CommandSourceStatus::Oversize(n) if *n > MAX_SOURCE_BYTES) |
| 342 | ) |
| 343 | ); |
| 344 | } |
| 345 | } |
| 346 |