Skip to main content

apm/cmd/
init.rs

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