1use anyhow::Result;
2use serde_json::Value;
3use std::io::{self, BufRead, IsTerminal, Write};
4use std::path::{Path, PathBuf};
5use std::process::Command;
6
7pub fn run(root: &Path, no_claude: bool, migrate: bool, with_docker: bool, quiet: bool, yes: bool) -> Result<()> {
8 if migrate {
9 let msgs = apm_core::init::migrate(root)?;
10 for msg in msgs {
11 println!("{msg}");
12 }
13 return Ok(());
14 }
15
16 let is_tty = std::io::stdin().is_terminal();
17 let yes = yes || !is_tty;
18
19 let has_git_host = {
21 let config_path = root.join(".apm/config.toml");
22 config_path.exists() && apm_core::config::Config::load(root)
23 .map(|cfg| cfg.git_host.provider.is_some())
24 .unwrap_or(false)
25 };
26 let local_toml = root.join(".apm/local.toml");
27
28 let username = if !has_git_host && !local_toml.exists() && is_tty {
29 let gh_default = apm_core::github::gh_username();
30 prompt_username(gh_default.as_deref())?
31 } else {
32 String::new()
33 };
34
35 let default_name = root.file_name().and_then(|n| n.to_str()).unwrap_or("project").to_string();
36 let (name, description) = if is_tty && !root.join(".apm/config.toml").exists() {
37 prompt_project_info(&default_name)?
38 } else {
39 (String::new(), String::new())
40 };
41
42 let name_opt = if name.is_empty() { None } else { Some(name.as_str()) };
43 let desc_opt = if description.is_empty() { None } else { Some(description.as_str()) };
44 let user_opt = if username.is_empty() { None } else { Some(username.as_str()) };
45
46 let setup_out = apm_core::init::setup(root, name_opt, desc_opt, user_opt)?;
47 for msg in &setup_out.messages {
48 println!("{msg}");
49 }
50
51 if with_docker {
52 let docker_out = apm_core::init::setup_docker(root)?;
53 for msg in &docker_out.messages {
54 if msg.is_empty() {
55 println!();
56 } else {
57 println!("{msg}");
58 }
59 }
60 }
61 update_claude_settings(root, no_claude, yes)?;
62 update_user_claude_settings(yes)?;
63 warn_if_settings_untracked(root);
64 println!("apm initialized.");
65 if std::io::stdout().is_terminal() && !quiet {
66 println!();
67 println!("Next steps:");
68 println!(" * Commit the config: git add .apm/ && git commit -m 'chore: init apm'");
69 println!(" * Create a ticket: apm new");
70 println!(" * Open the web UI: apm-server");
71 println!(" * Full CLI reference: apm --help");
72 }
73 Ok(())
74}
75
76fn prompt_username(default: Option<&str>) -> Result<String> {
77 let mut stdout = std::io::stdout();
78 let stdin = std::io::stdin();
79 match default {
80 Some(d) => print!("Username [{}]: ", d),
81 None => print!("Username []: "),
82 }
83 stdout.flush()?;
84 let mut input = String::new();
85 stdin.lock().read_line(&mut input)?;
86 let trimmed = input.trim();
87 if trimmed.is_empty() {
88 Ok(default.unwrap_or("").to_string())
89 } else {
90 Ok(trimmed.to_string())
91 }
92}
93
94fn prompt_project_info(default_name: &str) -> Result<(String, String)> {
95 let mut stdout = std::io::stdout();
96 let stdin = std::io::stdin();
97
98 print!("Project name [{}]: ", default_name);
99 stdout.flush()?;
100 let mut name_input = String::new();
101 stdin.lock().read_line(&mut name_input)?;
102 let name = {
103 let trimmed = name_input.trim();
104 if trimmed.is_empty() {
105 default_name.to_string()
106 } else {
107 trimmed.to_string()
108 }
109 };
110
111 print!("Project description []: ");
112 stdout.flush()?;
113 let mut desc_input = String::new();
114 stdin.lock().read_line(&mut desc_input)?;
115 let description = desc_input.trim().to_string();
116
117 Ok((name, description))
118}
119
120fn warn_if_settings_untracked(root: &Path) {
121 let settings = root.join(".claude/settings.json");
122 if !settings.exists() {
123 return;
124 }
125 let tracked = Command::new("git")
126 .args(["ls-files", "--error-unmatch", ".claude/settings.json"])
127 .current_dir(root)
128 .output()
129 .map(|o| o.status.success())
130 .unwrap_or(false);
131 if !tracked {
132 eprintln!(
133 "Warning: .claude/settings.json exists but is not committed. \
134Agent worktrees won't have it — run: git add .claude/settings.json && git commit"
135 );
136 }
137}
138
139const APM_ALLOW_ENTRIES: &[&str] = &[
140 "Bash(apm sync*)",
141 "Bash(apm next*)",
142 "Bash(apm list*)",
143 "Bash(apm show*)",
144 "Bash(apm set *)",
145 "Bash(apm state *)",
146 "Bash(apm start *)",
147 "Bash(apm spec *)",
148 "Bash(apm agents*)",
149 "Bash(apm _hook *)",
150 "Bash(apm verify*)",
151 "Bash(apm new *)",
152 "Bash(apm worktrees*)",
153 "Bash(apm help*)",
154 "Bash(apm review *)",
155 "Bash(apm close *)",
156 "Bash(apm assign *)",
157 "Bash(apm validate*)",
158 "Bash(apm work *)",
159 "Bash(apm move *)",
160 "Bash(apm archive *)",
161 "Bash(apm clean *)",
162 "Bash(apm workers*)",
163 "Bash(apm epic *)",
164 "Bash(apm register *)",
165 "Bash(apm sessions *)",
166 "Bash(apm revoke *)",
167 "Bash(apm version*)",
168 "Edit",
170 "Write",
171 "Bash(git -C *)",
173 "Bash(ls *)",
175 "Bash(rg *)",
176 "Bash(grep *)",
177 "Bash(find *)",
178 "Bash(cat *)",
179 "Bash(head *)",
180 "Bash(tail *)",
181 "Bash(wc *)",
182 "Bash(sort *)",
183 "Bash(uniq *)",
184 "Bash(diff *)",
185 "Bash(which *)",
186 "Bash(sed *)",
188 "Bash(awk *)",
189 "Bash(mv *)",
191 "Bash(cp *)",
192 "Bash(rm /tmp/*)",
193 "Bash(mkdir -p /tmp/*)",
194 "Bash(echo *)",
196 "Bash(test *)",
197 "Bash(true)",
198 "Bash(false)",
199];
200
201const APM_USER_ALLOW_ENTRIES: &[&str] = &[
204 "Bash(git add*)",
205 "Bash(git commit*)",
206 "Bash(git -C*)",
207 "Bash(apm sync*)",
208 "Bash(apm next*)",
209 "Bash(apm list*)",
210 "Bash(apm show*)",
211 "Bash(apm set *)",
212 "Bash(apm state *)",
213 "Bash(apm start *)",
214 "Bash(apm spec *)",
215 "Bash(apm agents*)",
216 "Bash(apm verify*)",
217 "Bash(apm new *)",
218 "Bash(apm worktrees*)",
219 "Bash(apm help*)",
220 "Bash(apm review *)",
221 "Bash(apm close *)",
222 "Bash(apm assign *)",
223 "Bash(apm validate*)",
224 "Bash(apm work *)",
225 "Bash(apm move *)",
226 "Bash(apm archive *)",
227 "Bash(apm clean *)",
228 "Bash(apm workers*)",
229 "Bash(apm epic *)",
230 "Bash(apm register *)",
231 "Bash(apm sessions *)",
232 "Bash(apm revoke *)",
233 "Bash(apm version*)",
234 "Edit",
236 "Write",
237 "Bash(git -C *)",
239 "Bash(ls *)",
241 "Bash(rg *)",
242 "Bash(grep *)",
243 "Bash(find *)",
244 "Bash(cat *)",
245 "Bash(head *)",
246 "Bash(tail *)",
247 "Bash(wc *)",
248 "Bash(sort *)",
249 "Bash(uniq *)",
250 "Bash(diff *)",
251 "Bash(which *)",
252 "Bash(sed *)",
254 "Bash(awk *)",
255 "Bash(mv *)",
257 "Bash(cp *)",
258 "Bash(rm /tmp/*)",
259 "Bash(mkdir -p /tmp/*)",
260 "Bash(echo *)",
262 "Bash(test *)",
263 "Bash(true)",
264 "Bash(false)",
265 "Bash(cargo *)",
267 "Bash(npm *)",
268 "Bash(npx *)",
269 "Bash(python3 *)",
270];
271
272fn update_settings_json(
273 path: &Path,
274 entries: &[&str],
275 prompt_header: &str,
276 prompt_confirm: &str,
277 updated_msg: &str,
278 create_if_missing: bool,
279 yes: bool,
280) -> Result<()> {
281 let mut val: Value = if path.exists() {
282 let raw = std::fs::read_to_string(path)?;
283 serde_json::from_str(&raw).unwrap_or(Value::Object(Default::default()))
284 } else if create_if_missing {
285 Value::Object(Default::default())
286 } else {
287 return Ok(());
288 };
289
290 let allow = val.pointer_mut("/permissions/allow").and_then(|v| v.as_array_mut());
291 let missing: Vec<&str> = if let Some(arr) = allow {
292 entries.iter().filter(|&&e| !arr.iter().any(|v| v.as_str() == Some(e))).copied().collect()
293 } else {
294 entries.to_vec()
295 };
296
297 if missing.is_empty() {
298 return Ok(());
299 }
300
301 if !yes {
302 println!("{prompt_header}");
303 for e in &missing {
304 println!(" {e}");
305 }
306 print!("{prompt_confirm} [y/N] ");
307 io::stdout().flush()?;
308
309 let mut line = String::new();
310 io::stdin().lock().read_line(&mut line)?;
311 if !line.trim().eq_ignore_ascii_case("y") {
312 println!("Skipped.");
313 return Ok(());
314 }
315 }
316
317 if val.pointer("/permissions/allow").is_none() {
318 let perms = val
319 .as_object_mut()
320 .ok_or_else(|| anyhow::anyhow!("settings.json root is not an object"))?
321 .entry("permissions")
322 .or_insert_with(|| Value::Object(Default::default()));
323 perms.as_object_mut().unwrap()
324 .entry("allow")
325 .or_insert_with(|| Value::Array(vec![]));
326 }
327
328 let arr = val.pointer_mut("/permissions/allow")
329 .and_then(|v| v.as_array_mut())
330 .unwrap();
331 for e in missing {
332 arr.push(Value::String(e.to_string()));
333 }
334
335 if let Some(parent) = path.parent() {
336 std::fs::create_dir_all(parent)?;
337 }
338 let updated = serde_json::to_string_pretty(&val)?;
339 std::fs::write(path, updated + "\n")?;
340 println!("{updated_msg}");
341 Ok(())
342}
343
344fn detected_toolchain_entries(root: &Path) -> Vec<&'static str> {
345 let mut entries = Vec::new();
346 if root.join("Cargo.toml").exists() {
347 entries.push("Bash(cargo *)");
348 }
349 if root.join("package.json").exists() {
350 entries.extend_from_slice(&["Bash(npm *)", "Bash(npx *)"]);
351 }
352 if root.join("pyproject.toml").exists() || root.join("requirements.txt").exists() {
353 entries.push("Bash(python3 *)");
354 }
355 entries
356}
357
358fn update_claude_settings(root: &Path, skip: bool, yes: bool) -> Result<()> {
359 if skip {
360 return Ok(());
361 }
362 let claude_dir = root.join(".claude");
363 if !claude_dir.exists() {
364 return Ok(());
365 }
366 let mut entries: Vec<&str> = APM_ALLOW_ENTRIES.to_vec();
367 entries.extend(detected_toolchain_entries(root));
368 update_settings_json(
369 &claude_dir.join("settings.json"),
370 &entries,
371 "The following entries will be added to .claude/settings.json permissions.allow:",
372 "Add apm commands to Claude allow list?",
373 "Updated .claude/settings.json",
374 true,
375 yes,
376 )
377}
378
379fn update_user_claude_settings(yes: bool) -> Result<()> {
380 let home = match std::env::var("HOME") {
381 Ok(h) if !h.is_empty() => h,
382 _ => return Ok(()),
383 };
384 update_settings_json(
385 &PathBuf::from(&home).join(".claude/settings.json"),
386 APM_USER_ALLOW_ENTRIES,
387 "The following entries will be added to ~/.claude/settings.json (user-level,\nrequired so apm subagents in isolated worktrees can run git and apm commands):",
388 "Add to ~/.claude/settings.json?",
389 "Updated ~/.claude/settings.json",
390 true,
391 yes,
392 )
393}