返回 CodeWhale
config_main_import_host.rs
根目录 / crates / tui / src / commands / config_main_import_host.rs
1 //! `/import-claude` host operations (FEAT-028).
2 //!
3 //! The command owns the flow and the messages; this host module builds the plan
4 //! from the Claude sources, persists the rendered artifacts and carries over the
5 //! standing instructions. The plan is the contract model, so the command
6 //! renders it without any host type.
7
8 use crate::tui::app::App;
9 use codewhale_command_contract::config::{
10 CommandClaudeApplyOutcome, CommandClaudeArtifacts, CommandClaudePlan, CommandMcpCandidate,
11 };
12 use std::path::Path;
13
14 /// Build the import plan from the host's home/workspace; `None` when nothing
15 /// was found.
16 pub(in crate::commands) fn build_plan(app: &mut App) -> Option<CommandClaudePlan> {
17 let home = codewhale_paths::user_home().unwrap_or_else(|| std::path::PathBuf::from("."));
18 let (sources, claude, settings) = codewhale_net::import_claude::read_sources(&home);
19
20 // MCP candidates come from the same discovery the `/mcp import` consent
21 // flow uses, filtered to the Claude sources: provenance stays single-sourced.
22 let markets = Vec::new();
23 let mcp_candidates = codewhale_engine::mcp::external_import::discover_external_sources(
24 &home,
25 &app.workspace,
26 &markets,
27 )
28 .into_iter()
29 .filter(|candidate| {
30 matches!(
31 candidate.source_kind,
32 codewhale_engine::mcp::external_import::ExternalMcpSourceKind::ClaudeJson
33 )
34 })
35 .map(|candidate| CommandMcpCandidate {
36 summary: candidate.summary,
37 hard_blocked: candidate.hard_blocked,
38 name: candidate.name,
39 })
40 .collect::<Vec<_>>();
41
42 let plan =
43 codewhale_net::import_claude::build_plan(sources, claude, settings, &home, mcp_candidates);
44 if plan.is_empty() && !plan.has_any_present_or_failed_source() {
45 None
46 } else {
47 Some(plan)
48 }
49 }
50
51 /// Persist the rendered report and optional bundle.
52 pub(in crate::commands) fn write_artifacts(
53 report: &str,
54 bundle: Option<&str>,
55 ) -> CommandClaudeArtifacts {
56 let imports_dir = codewhale_config::codewhale_home()
57 .map(|home| home.join("imports"))
58 .unwrap_or_else(|_| std::path::PathBuf::from(".codewhale/imports"));
59 let report_path = imports_dir.join("claude-import-report.md");
60 let bundle_path = imports_dir.join("claude-portable-bundle.json");
61 let write = |path: &Path, bytes: &[u8]| match codewhale_config::persistence::atomic_write(
62 path, bytes,
63 ) {
64 Ok(_) => true,
65 Err(error) => {
66 tracing::warn!(target: "commands", path = %path.display(), error = %error, "claude import artifact write failed");
67 false
68 }
69 };
70 let wrote_report = write(&report_path, report.as_bytes());
71 let wrote_bundle = bundle.is_some_and(|json| write(&bundle_path, json.as_bytes()));
72 CommandClaudeArtifacts {
73 report_path,
74 bundle_path,
75 wrote_report,
76 wrote_bundle,
77 }
78 }
79
80 /// Carry over the standing instructions and report what remains manual.
81 ///
82 /// `--apply` is the consent: this path never overwrites an existing file, never
83 /// imports MCP servers, and never touches hooks or permission rules — those run
84 /// code, so they stay a human decision.
85 pub(in crate::commands) fn apply_plan(
86 _app: &mut App,
87 plan: &CommandClaudePlan,
88 report_path: &Path,
89 wrote_report: bool,
90 ) -> CommandClaudeApplyOutcome {
91 use codewhale_command_contract::config::CommandImportFollowUp;
92 let mut done: Vec<CommandImportFollowUp> = Vec::new();
93 let mut manual: Vec<CommandImportFollowUp> = Vec::new();
94
95 if plan.has_claude_md {
96 match codewhale_config::codewhale_home() {
97 Ok(home) => {
98 let destination = home.join("instructions.md");
99 let source = codewhale_paths::user_home()
100 .unwrap_or_else(|| std::path::PathBuf::from("."))
101 .join(".claude")
102 .join("CLAUDE.md");
103 if destination.exists() {
104 manual.push(CommandImportFollowUp::InstructionsKeptExisting {
105 destination: codewhale_util::utils::display_path(&destination).to_string(),
106 source: codewhale_util::utils::display_path(&source).to_string(),
107 });
108 } else {
109 let copy_source = source.clone();
110 let copy_home = home.clone();
111 #[cfg(test)]
112 let ticket = crate::test_support::env_scope_ticket();
113 let copied = match tokio::runtime::Handle::try_current() {
114 Ok(handle)
115 if handle.runtime_flavor()
116 == tokio::runtime::RuntimeFlavor::MultiThread =>
117 {
118 crate::commands::contract::run_async(async move {
119 tokio::task::spawn_blocking(move || {
120 #[cfg(test)]
121 let _membership = crate::test_support::join_env_scope(ticket);
122 std::fs::read(&copy_source).is_ok_and(|bytes| {
123 codewhale_config::private_directory::PrivateDirectory::open_trusting_mount(
124 &copy_home,
125 )
126 .and_then(|directory| {
127 directory.write_owned_file(
128 "instructions.md",
129 &bytes,
130 false,
131 )
132 })
133 .is_ok()
134 })
135 })
136 .await
137 .unwrap_or(false)
138 })
139 }
140 Err(_) => std::thread::spawn(move || {
141 #[cfg(test)]
142 let _membership = crate::test_support::join_env_scope(ticket);
143 std::fs::read(&copy_source).is_ok_and(|bytes| {
144 codewhale_config::private_directory::PrivateDirectory::open_trusting_mount(
145 &copy_home,
146 )
147 .and_then(|directory| {
148 directory.write_owned_file("instructions.md", &bytes, false)
149 })
150 .is_ok()
151 })
152 })
153 .join()
154 .unwrap_or(false),
155 Ok(_) => false,
156 };
157 if copied {
158 done.push(CommandImportFollowUp::InstructionsCopied {
159 destination: codewhale_util::utils::display_path(&destination)
160 .to_string(),
161 });
162 } else {
163 manual.push(CommandImportFollowUp::InstructionsCopyFailed {
164 source: codewhale_util::utils::display_path(&source).to_string(),
165 destination: codewhale_util::utils::display_path(&destination)
166 .to_string(),
167 });
168 }
169 }
170 }
171 Err(_) => manual.push(CommandImportFollowUp::HomeUnresolved),
172 }
173 }
174
175 // MCP approval must bind the exact bytes and current managed-config
176 // revision shown by the shared preview. Blanket migration cannot grant it.
177 for candidate in &plan.mcp_candidates {
178 manual.push(if candidate.hard_blocked {
179 CommandImportFollowUp::McpBlocked {
180 name: candidate.name.clone(),
181 }
182 } else {
183 CommandImportFollowUp::McpNeedsReview {
184 name: candidate.name.clone(),
185 }
186 });
187 }
188
189 if !plan.hook_events.is_empty() {
190 manual.push(CommandImportFollowUp::HookEvents {
191 count: plan.hook_events.len(),
192 });
193 }
194 if !plan.permissions_allow.is_empty()
195 || !plan.permissions_ask.is_empty()
196 || !plan.permissions_deny.is_empty()
197 {
198 manual.push(CommandImportFollowUp::PermissionRules);
199 }
200
201 CommandClaudeApplyOutcome {
202 done,
203 manual,
204 report_path: report_path.to_path_buf(),
205 wrote_report,
206 }
207 }
208
209 #[cfg(test)]
210 mod tests {
211 use super::*;
212 use crate::commands::CommandResult;
213 use crate::tui::app::TuiOptions;
214 use codewhale_runtime::config::Config;
215 use std::fs;
216 use tempfile::TempDir;
217
218 /// Run the portable `/import-claude` handler through the real CONFIG
219 /// envelope (the flow and messages now live in the command).
220 fn import_claude_command(app: &mut App, arg: Option<&str>) -> CommandResult {
221 let result = crate::commands::groups::config::config::import_claude(
222 app.command_contexts_with_config(None)
223 .contexts(crate::commands::groups::config::config::CONFIG_ONLY_CAPS),
224 arg,
225 );
226 CommandResult {
227 message: result.message,
228 action: result
229 .action
230 .map(crate::commands::config_host::config_action_to_app_action),
231 is_error: result.is_error,
232 }
233 }
234
235 /// A home with a Claude `CLAUDE.md`, plus a Codewhale home to import into.
236 fn sandbox() -> (TempDir, App) {
237 let temp = TempDir::new().expect("tempdir");
238 let home = temp.path().join("home");
239 let claude = home.join(".claude");
240 fs::create_dir_all(&claude).expect("claude dir");
241 fs::write(claude.join("CLAUDE.md"), b"be excellent\n").expect("CLAUDE.md");
242 fs::write(claude.join("settings.json"), b"{}").expect("settings");
243 fs::write(home.join(".claude.json"), b"{}").expect("claude.json");
244
245 let workspace = temp.path().join("ws");
246 fs::create_dir_all(&workspace).expect("workspace");
247 let options = TuiOptions {
248 config_path: Some(temp.path().join("config.toml")),
249 skills_dir: temp.path().join("skills"),
250 memory_path: temp.path().join("memory.md"),
251 mcp_config_path: temp.path().join("mcp.json"),
252 ..crate::tui::test_support::test_tui_options(&workspace)
253 };
254 let app = App::new(options, &Config::default());
255 (temp, app)
256 }
257
258 #[test]
259 fn the_bare_command_applies_nothing_and_says_how_to_apply() {
260 let _lock = crate::test_support::lock_test_env();
261 let (temp, mut app) = sandbox();
262 let home = temp.path().join("home");
263 let _home = crate::test_support::EnvVarGuard::set("HOME", &home);
264 let _profile = crate::test_support::EnvVarGuard::set("USERPROFILE", &home);
265 let cw_home = temp.path().join("cw");
266 let _cw = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &cw_home);
267
268 let result = import_claude_command(&mut app, None);
269 let message = result.message.expect("a plan");
270 assert!(
271 message.contains("/import-claude --apply"),
272 "the plan must say how to apply it: {message}"
273 );
274 assert!(
275 !cw_home.join("instructions.md").exists(),
276 "the bare command must not write instructions.md"
277 );
278 }
279
280 #[test]
281 fn apply_carries_the_standing_instructions_and_never_clobbers_them() {
282 let _lock = crate::test_support::lock_test_env();
283 let (temp, mut app) = sandbox();
284 let home = temp.path().join("home");
285 let _home = crate::test_support::EnvVarGuard::set("HOME", &home);
286 let _profile = crate::test_support::EnvVarGuard::set("USERPROFILE", &home);
287 let cw_home = temp.path().join("cw");
288 let _cw = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &cw_home);
289
290 let runtime = tokio::runtime::Builder::new_multi_thread()
291 .worker_threads(2)
292 .enable_all()
293 .build()
294 .expect("import runtime");
295 let result = runtime.block_on(async { import_claude_command(&mut app, Some("--apply")) });
296 let message = result.message.expect("an outcome");
297 let destination = cw_home.join("instructions.md");
298 assert!(destination.exists(), "instructions were copied: {message}");
299 assert_eq!(
300 fs::read_to_string(&destination).expect("read"),
301 "be excellent\n"
302 );
303
304 // Running it again must not overwrite the operator's own file.
305 fs::write(&destination, b"mine now\n").expect("overwrite");
306 let again = import_claude_command(&mut app, Some("--apply"));
307 let message = again.message.expect("an outcome");
308 assert_eq!(
309 fs::read_to_string(&destination).expect("read"),
310 "mine now\n",
311 "an existing instructions.md is never clobbered: {message}"
312 );
313 assert!(
314 message.contains("already exists"),
315 "and the reason is said out loud: {message}"
316 );
317 }
318
319 #[test]
320 fn present_empty_or_invalid_sources_are_reported_instead_of_not_found() {
321 let _lock = crate::test_support::lock_test_env();
322 let temp = TempDir::new().expect("tempdir");
323 let home = temp.path().join("home");
324 fs::create_dir_all(&home).expect("home");
325 let workspace = temp.path().join("ws");
326 fs::create_dir_all(&workspace).expect("workspace");
327 let options = TuiOptions {
328 config_path: Some(temp.path().join("config.toml")),
329 skills_dir: temp.path().join("skills"),
330 memory_path: temp.path().join("memory.md"),
331 mcp_config_path: temp.path().join("mcp.json"),
332 ..crate::tui::test_support::test_tui_options(&workspace)
333 };
334 let mut app = App::new(options, &Config::default());
335 let _home = crate::test_support::EnvVarGuard::set("HOME", &home);
336 let _profile = crate::test_support::EnvVarGuard::set("USERPROFILE", &home);
337 let cw_home = temp.path().join("cw");
338 let _cw = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &cw_home);
339
340 let missing = import_claude_command(&mut app, None)
341 .message
342 .expect("missing message");
343 assert!(
344 missing.contains("No Claude configuration found to import"),
345 "all NotFound sources still report missing: {missing}"
346 );
347
348 fs::write(home.join(".claude.json"), b"{}").expect("empty json");
349 let empty = import_claude_command(&mut app, None)
350 .message
351 .expect("empty config message");
352 assert!(
353 !empty.contains("No Claude configuration found to import"),
354 "present empty JSON must not claim missing: {empty}"
355 );
356 assert!(empty.contains("found:"), "{empty}");
357
358 fs::write(home.join(".claude.json"), b"{not-json").expect("invalid json");
359 let invalid = import_claude_command(&mut app, None)
360 .message
361 .expect("invalid json message");
362 assert!(
363 !invalid.contains("No Claude configuration found to import"),
364 "invalid JSON must not claim missing: {invalid}"
365 );
366 assert!(invalid.contains("invalid JSON:"), "{invalid}");
367
368 fs::create_dir_all(&cw_home).expect("cw home");
369 let blocker_dir = temp.path().join("cw-blocked");
370 fs::create_dir_all(&blocker_dir).expect("blocked cw home");
371 fs::write(blocker_dir.join("imports"), b"not-a-dir").expect("block imports dir");
372 let _cw_blocked = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &blocker_dir);
373 let apply_msg = import_claude_command(&mut app, Some("--apply"))
374 .message
375 .expect("apply fallback message");
376 assert!(
377 apply_msg.contains("invalid JSON:"),
378 "apply fallback without written report must include source statuses: {apply_msg}"
379 );
380 assert!(
381 apply_msg.contains("the report could not be written"),
382 "{apply_msg}"
383 );
384 }
385 }
386
386 lines RUST