1use std::path::Path;
7
8use lean_ctx::core::editor_registry::EditorTarget;
9use lean_ctx::core::setup_report::{SetupItem, SetupReport, SetupStepReport};
10
11use super::agent_selection::AgentScope;
12use super::helpers::shorten_path;
13use super::options::SetupOptions;
14use super::with_options::{deselected_items, setup_step};
15
16pub(super) struct PlanInput<'a> {
17 pub opts: &'a SetupOptions,
18 pub home: &'a Path,
19 pub scope: &'a AgentScope,
20 pub targets: &'a [EditorTarget],
21 pub deselected: &'a [EditorTarget],
22 pub update_mcp: bool,
23 pub inject_rules: bool,
24 pub inject_skills: bool,
25}
26
27fn item(name: &str, status: &str, path: Option<String>, note: Option<String>) -> SetupItem {
28 SetupItem {
29 name: name.to_string(),
30 status: status.to_string(),
31 path,
32 note,
33 }
34}
35
36pub(super) fn plan_steps(input: &PlanInput<'_>) -> Vec<SetupStepReport> {
37 let home_str = input.home.to_string_lossy().to_string();
38 let short = |p: &Path| shorten_path(&p.to_string_lossy(), &home_str);
39 let allows = |key: &str| input.scope.allows(key);
40 let cfg = lean_ctx::core::config::Config::load();
41
42 let mut selection = setup_step("agent_selection");
43 let (status, note) = match input.scope {
44 AgentScope::All => ("all_detected", "no selection recorded".to_string()),
45 AgentScope::Only(keys) if keys.is_empty() => ("selected", "none".to_string()),
46 AgentScope::Only(keys) => (
47 "selected",
48 keys.iter().cloned().collect::<Vec<_>>().join(","),
49 ),
50 };
51 selection
52 .items
53 .push(item("scope", status, None, Some(note)));
54 if let Some(keys) = &input.opts.agents {
55 selection.items.push(item(
56 "setup.agents",
57 "would_save",
58 None,
59 Some(keys.iter().cloned().collect::<Vec<_>>().join(",")),
60 ));
61 }
62
63 let mut shell = setup_step("shell_hook");
64 if input.opts.non_interactive && !input.opts.yes {
65 shell.items.push(item(
66 "init --global",
67 "skipped",
68 None,
69 Some("requires --yes in --non-interactive mode".to_string()),
70 ));
71 } else if cfg.shell_hook_disabled_effective() {
72 shell.items.push(item(
73 "shell hook",
74 "skipped",
75 None,
76 Some("shell_hook_disabled=true".to_string()),
77 ));
78 } else {
79 for rc in [".zshenv", ".bashenv"] {
80 shell.items.push(item(
81 "shell hook",
82 "would_update",
83 Some(format!("~/{rc}")),
84 Some("only if that shell is installed".to_string()),
85 ));
86 }
87 let (status, note) = if cfg.skip_agent_aliases {
88 ("would_remove", "skip_agent_aliases=true")
89 } else {
90 ("would_update", "claude/codex/gemini aliases")
91 };
92 for rc in [".zshrc", ".bashrc"] {
93 shell.items.push(item(
94 "agent aliases",
95 status,
96 Some(format!("~/{rc}")),
97 Some(note.to_string()),
98 ));
99 }
100 }
101
102 let mut daemon = setup_step("daemon");
103 let status = if lean_ctx::daemon::is_daemon_running() {
104 "would_restart"
105 } else {
106 "would_start"
107 };
108 daemon
109 .items
110 .push(item("serve --daemon", status, None, None));
111
112 let mut editors = setup_step("editors");
113 for target in input.targets {
114 let path = short(&target.config_path);
115 let (status, note) = if !target.detect_path.exists() {
116 ("not_detected", None)
117 } else if !input.update_mcp {
118 ("skipped", Some("auto_update_mcp=false".to_string()))
119 } else if !target.config_path.exists() {
120 ("would_create", None)
121 } else if std::fs::read_to_string(&target.config_path).is_ok_and(|c| c.contains("lean-ctx"))
122 {
123 (
124 "would_refresh",
125 Some("lean-ctx entry present; rewritten only if it differs".to_string()),
126 )
127 } else {
128 ("would_add", Some("adds the lean-ctx MCP entry".to_string()))
129 };
130 editors
131 .items
132 .push(item(target.name, status, Some(path), note));
133 }
134 editors
135 .items
136 .extend(deselected_items(input.deselected, &home_str));
137
138 let mut hooks = setup_step("agent_hooks");
139 for target in input
140 .targets
141 .iter()
142 .filter(|t| t.detect_path.exists() && !t.agent_key.is_empty())
143 {
144 hooks.items.push(item(
145 &format!("{} hooks", target.name),
146 "would_install",
147 Some(short(&target.detect_path)),
148 Some("merge-based; preserves other hooks/plugins".to_string()),
149 ));
150 }
151
152 let mut rules = setup_step("agent_rules");
153 if input.inject_rules {
154 for (name, path) in lean_ctx::rules_inject::planned_rules_files(input.home, &allows) {
155 rules.items.push(item(
156 &name,
157 "would_write",
158 Some(short(&path)),
159 Some("marker-delimited lean-ctx block".to_string()),
160 ));
161 }
162 } else {
163 rules.items.push(item(
164 "agent_rules",
165 "skipped",
166 None,
167 Some(if input.opts.skip_rules {
168 "--skip-rules".to_string()
169 } else {
170 "auto_inject_rules not enabled".to_string()
171 }),
172 ));
173 }
174
175 let mut skills = setup_step("skill_files");
176 if input.inject_skills {
177 for (name, path) in lean_ctx::rules_inject::planned_skill_files(input.home, &allows) {
178 skills
179 .items
180 .push(item(&name, "would_write", Some(short(&path)), None));
181 }
182 } else {
183 skills.items.push(item(
184 "skill_files",
185 "skipped",
186 None,
187 Some("auto_inject_skills not enabled".to_string()),
188 ));
189 }
190
191 let mut steps = vec![selection, shell, daemon, editors, hooks, rules, skills];
192
193 if input
194 .targets
195 .iter()
196 .any(|t| t.agent_key == "claude" && t.detect_path.exists())
197 {
198 let mut claude_mod = setup_step("claude_mod");
199 claude_mod.items.push(item(
200 lean_ctx_hooks::hooks::agents::claude_mod::PLUGIN_ID,
201 "would_install_or_refresh",
202 None,
203 Some("skipped if you removed it (lean-ctx claude-mod uninstall)".to_string()),
204 ));
205 steps.push(claude_mod);
206 }
207
208 let mut proxy = setup_step("proxy");
209 if !input.opts.skip_proxy && cfg.proxy_enabled == Some(true) {
210 proxy.items.push(item(
211 "proxy_autostart",
212 "would_install",
213 None,
214 Some("LaunchAgent/systemd auto-start + base-URL env".to_string()),
215 ));
216 } else {
217 proxy.items.push(item(
218 "proxy",
219 "skipped",
220 None,
221 Some("not enabled".to_string()),
222 ));
223 }
224 steps.push(proxy);
225
226 if input.opts.yes && !input.opts.fix && cfg.allow_ide_config_dirs.is_none() {
227 let mut config = setup_step("config");
228 config.items.push(item(
229 "allow_ide_config_dirs",
230 "would_set",
231 None,
232 Some("true".to_string()),
233 ));
234 steps.push(config);
235 }
236
237 steps
238}
239
240pub fn print_plan(report: &SetupReport) {
242 let dim = "\x1b[2m";
243 let bold = "\x1b[1m";
244 let rst = "\x1b[0m";
245 println!();
246 println!(" {bold}Dry run — nothing was written.{rst} This run would:");
247 for step in &report.steps {
248 let items: Vec<&SetupItem> = step
249 .items
250 .iter()
251 .filter(|i| i.status != "not_detected")
252 .collect();
253 if items.is_empty() {
254 continue;
255 }
256 println!();
257 println!(" {bold}{}{rst}", step.name);
258 for i in items {
259 let path = i
260 .path
261 .as_deref()
262 .map(|p| format!(" {p}"))
263 .unwrap_or_default();
264 let note = i
265 .note
266 .as_deref()
267 .map(|n| format!(" {dim}({n}){rst}"))
268 .unwrap_or_default();
269 println!(" {:<24} {:<26}{path}{note}", i.status, i.name);
270 }
271 }
272 println!();
273}
274
275#[cfg(test)]
276mod tests {
277 use super::super::options::SetupOptions;
278 use super::super::with_options::run_setup_with_options;
279
280 #[test]
284 fn dry_run_reports_the_selection_without_recording_it() {
285 let _data = lean_ctx::core::data_dir::isolated_data_dir();
286 let home = tempfile::tempdir().unwrap();
287 std::fs::create_dir_all(home.path().join(".cursor")).unwrap();
288 std::fs::create_dir_all(home.path().join(".codeium/windsurf")).unwrap();
289 let _home = lean_ctx::test_env::EnvVarGuard::set("HOME", home.path().to_str().unwrap());
290
291 let report = run_setup_with_options(&SetupOptions {
292 non_interactive: true,
293 yes: true,
294 fix: true,
295 json: true,
296 dry_run: true,
297 agents: Some(["cursor".to_string()].into_iter().collect()),
298 ..Default::default()
299 })
300 .expect("dry run");
301
302 let editors = report.steps.iter().find(|s| s.name == "editors").unwrap();
303 let status = |name: &str| {
304 editors
305 .items
306 .iter()
307 .find(|i| i.name == name)
308 .map(|i| i.status.clone())
309 };
310 assert_eq!(status("Cursor").as_deref(), Some("would_create"));
311 assert_eq!(status("Windsurf").as_deref(), Some("deselected"));
312 assert!(
313 !home.path().join(".cursor/mcp.json").exists(),
314 "dry run registered the MCP server"
315 );
316
317 let selection = report
318 .steps
319 .iter()
320 .find(|s| s.name == "agent_selection")
321 .unwrap();
322 assert!(
323 selection
324 .items
325 .iter()
326 .any(|i| i.name == "setup.agents" && i.status == "would_save")
327 );
328 assert!(
329 lean_ctx::core::config::Config::load_global()
330 .setup
331 .agents
332 .is_none(),
333 "dry run must not record the selection"
334 );
335 }
336}