| 1 | //! Portable `/import-claude` plan rendering (FEAT-028). |
| 2 | //! |
| 3 | //! Pure formatting over the contract-owned [`CommandClaudePlan`]: no `App`, no |
| 4 | //! filesystem. The host builds the plan and performs the writes; the command |
| 5 | //! owns the flow and the messages. |
| 6 | |
| 7 | use codewhale_command_contract::config::CommandClaudePlan; |
| 8 | use std::collections::BTreeMap; |
| 9 | use std::fmt::Write as _; |
| 10 | |
| 11 | /// Claude `permissions.defaultMode` → the Codewhale approval-posture |
| 12 | /// recommendation (report text only; nothing is applied). |
| 13 | pub(crate) fn approval_posture_recommendation(mode: Option<&str>) -> &'static str { |
| 14 | match mode { |
| 15 | Some("acceptEdits") => "Accept Edits posture (/permissions) matches acceptEdits", |
| 16 | Some("plan") => "plan mode matches Claude's plan default", |
| 17 | Some("bypassPermissions") => { |
| 18 | "Full Access (yolo) matches bypassPermissions — confirm you want it" |
| 19 | } |
| 20 | _ => "the default Ask posture matches Claude's default", |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | /// One-line migration guidance for a Claude permission rule. |
| 25 | pub(crate) fn permission_rule_guidance(rule: &str) -> String { |
| 26 | let rule = rule.trim(); |
| 27 | if rule.starts_with("Bash(") { |
| 28 | format!("{rule} → an execpolicy rule for that command family (/permissions)") |
| 29 | } else if rule.starts_with("WebFetch(domain:") || rule.starts_with("WebSearch(") { |
| 30 | format!("{rule} → a fetch/network rule for that host or surface") |
| 31 | } else if rule.starts_with("mcp__") { |
| 32 | format!("{rule} → enable that MCP tool in your mcp.json enabled_tools") |
| 33 | } else if rule.starts_with("Read(") || rule.starts_with("Edit(") || rule.starts_with("Write(") { |
| 34 | format!("{rule} → a path-scoped ask rule (reads stay workspace-bounded by default)") |
| 35 | } else { |
| 36 | format!("{rule} → review against /permissions before mapping") |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | /// The unapplied portable bundle document for the safe env entries. |
| 41 | pub(crate) fn portable_bundle_json(plan: &CommandClaudePlan) -> String { |
| 42 | let global: BTreeMap<&str, &str> = plan |
| 43 | .env_safe |
| 44 | .iter() |
| 45 | .map(|(k, v)| (k.as_str(), v.as_str())) |
| 46 | .collect(); |
| 47 | serde_json::json!({ |
| 48 | "schema_version": 1, |
| 49 | "kind": "codewhale.portable-config", |
| 50 | "metadata": { |
| 51 | "name": "claude-import", |
| 52 | "generator": "codewhale /import-claude", |
| 53 | }, |
| 54 | "global": global, |
| 55 | }) |
| 56 | .to_string() |
| 57 | } |
| 58 | |
| 59 | /// Render the reviewable plan shown in the transcript. |
| 60 | pub(crate) fn render_plan( |
| 61 | plan: &CommandClaudePlan, |
| 62 | display: &dyn Fn(&std::path::Path) -> String, |
| 63 | ) -> String { |
| 64 | let mut out = String::new(); |
| 65 | out.push_str("Claude import plan (nothing is applied without its own consent):\n"); |
| 66 | for (path, status) in &plan.sources { |
| 67 | let _ = writeln!(out, " · {}", status.describe(&display(path))); |
| 68 | } |
| 69 | if !plan.mcp_candidates.is_empty() { |
| 70 | out.push_str("\nMCP servers (apply each with `/mcp import <name> --approve`):\n"); |
| 71 | for candidate in &plan.mcp_candidates { |
| 72 | let blocked = if candidate.hard_blocked { |
| 73 | " [blocked]" |
| 74 | } else { |
| 75 | "" |
| 76 | }; |
| 77 | let _ = writeln!( |
| 78 | out, |
| 79 | " · {}{blocked} — {}", |
| 80 | candidate.name, candidate.summary |
| 81 | ); |
| 82 | } |
| 83 | } |
| 84 | if !plan.per_project_mcp.is_empty() { |
| 85 | out.push_str("\nProject-scoped MCP servers (listed for provenance only):\n"); |
| 86 | for name in plan.per_project_mcp.iter().take(8) { |
| 87 | let _ = writeln!(out, " · {name}"); |
| 88 | } |
| 89 | } |
| 90 | if !plan.env_safe.is_empty() { |
| 91 | out.push_str("\nSafe env settings proposed for the portable bundle:\n"); |
| 92 | for (key, _) in &plan.env_safe { |
| 93 | let _ = writeln!(out, " · {key}"); |
| 94 | } |
| 95 | } |
| 96 | if !plan.env_skipped.is_empty() { |
| 97 | out.push_str("\nEnv keys not imported (secret-shaped or unmapped; values never shown):\n"); |
| 98 | for key in plan.env_skipped.iter().take(12) { |
| 99 | let _ = writeln!(out, " · {key}"); |
| 100 | } |
| 101 | } |
| 102 | let _ = writeln!( |
| 103 | out, |
| 104 | "\nApproval posture: {}.", |
| 105 | approval_posture_recommendation(plan.permissions_default_mode.as_deref()) |
| 106 | ); |
| 107 | for (label, rules) in [ |
| 108 | ("Allow", &plan.permissions_allow), |
| 109 | ("Ask", &plan.permissions_ask), |
| 110 | ("Deny", &plan.permissions_deny), |
| 111 | ] { |
| 112 | if !rules.is_empty() { |
| 113 | let _ = writeln!(out, "\n{label} rules (map manually; not auto-applied):"); |
| 114 | for rule in rules.iter().take(8) { |
| 115 | let _ = writeln!(out, " · {}", permission_rule_guidance(rule)); |
| 116 | } |
| 117 | } |
| 118 | } |
| 119 | if !plan.hook_events.is_empty() { |
| 120 | out.push_str("\nHook events (map manually with /hooks):\n"); |
| 121 | for event in &plan.hook_events { |
| 122 | let _ = writeln!(out, " · {event}"); |
| 123 | } |
| 124 | } |
| 125 | if plan.has_claude_md { |
| 126 | out.push_str("\nStanding instructions: ~/.claude/CLAUDE.md found — copy it to ~/.codewhale/instructions.md (or the repo's AGENTS.md) to carry it over.\n"); |
| 127 | } |
| 128 | out |
| 129 | } |
| 130 | |
| 131 | /// The written follow-through report (markdown). |
| 132 | pub(crate) fn report_markdown( |
| 133 | plan: &CommandClaudePlan, |
| 134 | display: &dyn Fn(&std::path::Path) -> String, |
| 135 | ) -> String { |
| 136 | let mut out = String::from( |
| 137 | "# Claude import report\n\nGenerated by `/import-claude`. Nothing was applied automatically.\n\n", |
| 138 | ); |
| 139 | out.push_str(&render_plan(plan, display)); |
| 140 | if !plan.env_safe.is_empty() { |
| 141 | out.push_str("\n## Apply the portable bundle\n\nReview the generated bundle, then run:\n\n codewhale config import <bundle path>\n\n"); |
| 142 | } |
| 143 | out.push_str("\n## Manual follow-ups\n\n- MCP: `/mcp import <name> --approve` per server (consent is recorded).\n- Permissions: map rules in /permissions and execpolicy.\n- Hooks: re-create matching hooks with /hooks.\n- Paths: copy CLAUDE.md if you want those standing instructions.\n"); |
| 144 | out |
| 145 | } |
| 146 | |
| 147 | #[cfg(test)] |
| 148 | mod tests { |
| 149 | use super::*; |
| 150 | use codewhale_command_contract::config::{CommandMcpCandidate, CommandSourceStatus}; |
| 151 | use std::path::PathBuf; |
| 152 | |
| 153 | fn sample_plan() -> CommandClaudePlan { |
| 154 | CommandClaudePlan { |
| 155 | sources: vec![(PathBuf::from("~/.claude.json"), CommandSourceStatus::Found)], |
| 156 | mcp_candidates: vec![CommandMcpCandidate { |
| 157 | name: "top".into(), |
| 158 | summary: "stdio server (node)".into(), |
| 159 | hard_blocked: false, |
| 160 | }], |
| 161 | per_project_mcp: vec!["inner (project /tmp/p)".into()], |
| 162 | env_safe: vec![("BASH_DEFAULT_TIMEOUT_MS".into(), "120000".into())], |
| 163 | env_skipped: vec!["ANTHROPIC_API_KEY".into()], |
| 164 | permissions_default_mode: Some("acceptEdits".into()), |
| 165 | permissions_allow: vec!["Bash(git status:*)".into(), "[redacted]".into()], |
| 166 | permissions_ask: vec![], |
| 167 | permissions_deny: vec!["Read(./.env)".into()], |
| 168 | hook_events: vec!["PreToolUse (1)".into()], |
| 169 | has_claude_md: true, |
| 170 | claude_projects: vec!["/tmp/proj-a".into()], |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | #[test] |
| 175 | fn render_plan_never_echoes_secret_values_and_maps_rules() { |
| 176 | let plan = sample_plan(); |
| 177 | let rendered = render_plan(&plan, &|path| path.display().to_string()); |
| 178 | assert!(!rendered.contains("sk-"), "{rendered}"); |
| 179 | assert!(rendered.contains("[redacted]"), "{rendered}"); |
| 180 | assert!(rendered.contains("Bash(git status:*) → an execpolicy rule")); |
| 181 | assert!(rendered.contains("acceptEdits")); |
| 182 | assert!(rendered.contains("Standing instructions: ~/.claude/CLAUDE.md found")); |
| 183 | } |
| 184 | |
| 185 | #[test] |
| 186 | fn portable_bundle_is_the_portable_config_document() { |
| 187 | let plan = sample_plan(); |
| 188 | let bundle = portable_bundle_json(&plan); |
| 189 | assert!(bundle.contains("codewhale.portable-config")); |
| 190 | assert!(bundle.contains("BASH_DEFAULT_TIMEOUT_MS")); |
| 191 | assert!(bundle.contains("120000")); |
| 192 | } |
| 193 | |
| 194 | #[test] |
| 195 | fn report_markdown_includes_the_plan_and_manual_follow_ups() { |
| 196 | let plan = sample_plan(); |
| 197 | let report = report_markdown(&plan, &|path| path.display().to_string()); |
| 198 | assert!(report.starts_with("# Claude import report")); |
| 199 | assert!(report.contains("## Manual follow-ups")); |
| 200 | assert!(report.contains("## Apply the portable bundle")); |
| 201 | } |
| 202 | |
| 203 | #[test] |
| 204 | fn posture_recommendations_cover_the_four_claude_modes() { |
| 205 | assert!(approval_posture_recommendation(Some("acceptEdits")).contains("Accept Edits")); |
| 206 | assert!(approval_posture_recommendation(Some("plan")).contains("plan")); |
| 207 | assert!(approval_posture_recommendation(Some("bypassPermissions")).contains("Full Access")); |
| 208 | assert!(approval_posture_recommendation(None).contains("Ask")); |
| 209 | } |
| 210 | |
| 211 | #[test] |
| 212 | fn source_status_wording_matches_the_baseline() { |
| 213 | assert_eq!( |
| 214 | CommandSourceStatus::Found.describe("~/.claude.json"), |
| 215 | "found: ~/.claude.json" |
| 216 | ); |
| 217 | assert_eq!( |
| 218 | CommandSourceStatus::NotFound.describe("~/.claude.json"), |
| 219 | "not found: ~/.claude.json" |
| 220 | ); |
| 221 | assert_eq!( |
| 222 | CommandSourceStatus::Oversize(5).describe("~/.claude.json"), |
| 223 | "skipped, too large (5 bytes): ~/.claude.json" |
| 224 | ); |
| 225 | assert_eq!( |
| 226 | CommandSourceStatus::InvalidJson("expected value at line 1 column 1".into()) |
| 227 | .describe("~/.claude.json"), |
| 228 | "invalid JSON: ~/.claude.json (expected value at line 1 column 1)" |
| 229 | ); |
| 230 | assert_eq!( |
| 231 | CommandSourceStatus::Unreadable("boom".into()).describe("~/.claude.json"), |
| 232 | "unreadable: ~/.claude.json (boom)" |
| 233 | ); |
| 234 | } |
| 235 | |
| 236 | #[test] |
| 237 | fn render_plan_uses_the_host_display_projection_not_an_absolute_home_path() { |
| 238 | let plan = CommandClaudePlan { |
| 239 | sources: vec![( |
| 240 | PathBuf::from("/home/review-user/.claude.json"), |
| 241 | CommandSourceStatus::Found, |
| 242 | )], |
| 243 | ..Default::default() |
| 244 | }; |
| 245 | let rendered = render_plan(&plan, &|path| { |
| 246 | path.display().to_string().replace("/home/review-user", "~") |
| 247 | }); |
| 248 | assert!(rendered.contains("found: ~/.claude.json"), "{rendered}"); |
| 249 | assert!( |
| 250 | !rendered.contains("/home/review-user"), |
| 251 | "the OS account name must not leak: {rendered}" |
| 252 | ); |
| 253 | } |
| 254 | } |
| 255 |