agentstatedeveloper-cli 1.4.9

asd CLI — command-line interface for AgentStateDeveloper
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! `asd worktree` — plan-scoped git worktrees (agent-worktree-workflow t-001).
//!
//! Mirror of CTXone's `ctx worktree`. Each unit of work gets its own worktree +
//! `plan/<name>` branch, so parallel agents get isolated files + HEAD (they
//! can't clobber each other) while sharing context via the hub. Lifecycle:
//!   asd worktree start <plan>   -> add ../<repo>-wt-<plan> on plan/<plan>
//!   (work there)                -> the CLI can't cd you; open your session in it
//!   asd worktree finish <plan>  -> merge back + MANDATORY teardown
//!
//! The plan<->worktree binding is by CONVENTION (dir `<repo>-wt-<plan>`, branch
//! `plan/<plan>`); `list` recovers it from `git worktree list`.

use std::path::{Path, PathBuf};
use std::process::Command;

use anyhow::{Result, bail};
use clap::Subcommand;

#[derive(Debug, Subcommand)]
pub enum WorktreeCmd {
    /// Create a plan-scoped worktree + `plan/<name>` branch, then print its path.
    Start {
        /// Plan name (kebab-case).
        plan: String,
        /// Ref to branch from.
        #[arg(long, default_value = "main")]
        from: String,
        /// Share one Rust build cache across worktrees: write a
        /// `.cargo/config.toml` pointing `target-dir` at `<repo>/.wt-target`,
        /// avoiding a multi-GB `target/` per worktree. Off by default.
        #[arg(long)]
        shared_target: bool,
        /// Isolate via a fresh CLONE (its own .git) into `../<repo>-clone-<plan>`
        /// instead of a worktree — for remote/cloud agents on another machine.
        /// Merge-back is via origin (push the branch), not a local merge.
        #[arg(long)]
        clone: bool,
        /// Clone URL (default: this repo's `origin` remote). Only with --clone.
        #[arg(long)]
        url: Option<String>,
    },
    /// List this repo's plan-scoped worktrees and clones.
    List,
    /// Merge the plan's branch back, then tear the worktree down (force-remove
    /// + delete branch + prune). Run from anywhere; operates on the main checkout.
    Finish {
        /// Plan name.
        plan: String,
        /// `git push` the target branch after merging.
        #[arg(long)]
        push: bool,
        /// Merge but KEEP the worktree + branch (skip teardown).
        #[arg(long)]
        keep: bool,
        /// Branch to merge into.
        #[arg(long, default_value = "main")]
        into: String,
        /// Finish a --clone workspace: push the branch to origin (with --push),
        /// then remove the clone directory. Merge to main happens on origin/MR.
        #[arg(long)]
        clone: bool,
    },
}

/// Derived worktree layout for a plan. Pure — unit-testable.
#[derive(Debug, PartialEq)]
struct Layout {
    wt_dir: PathBuf,
    branch: String,
}

/// `<parent>/<repo>-wt-<plan>` on branch `plan/<plan>`.
fn layout(root: &Path, plan: &str) -> Layout {
    let repo_name = root
        .file_name()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_else(|| "repo".into());
    let parent = root.parent().unwrap_or(root);
    Layout {
        wt_dir: parent.join(format!("{repo_name}-wt-{plan}")),
        branch: format!("plan/{plan}"),
    }
}

fn git(args: &[&str], cwd: &Path) -> Result<std::process::Output> {
    Ok(Command::new("git").args(args).current_dir(cwd).output()?)
}

fn git_checked(args: &[&str], cwd: &Path) -> Result<()> {
    let out = git(args, cwd)?;
    if !out.status.success() {
        bail!(
            "git {}: {}",
            args.join(" "),
            String::from_utf8_lossy(&out.stderr).trim()
        );
    }
    Ok(())
}

fn git_stdout(args: &[&str], cwd: &Path) -> Result<String> {
    let out = git(args, cwd)?;
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
}

/// The MAIN worktree's path (first entry of `git worktree list`), so `finish`
/// operates on main from anywhere — and never switches a shared checkout's HEAD.
fn main_root(cwd: &Path) -> Result<PathBuf> {
    let list = git_stdout(&["worktree", "list", "--porcelain"], cwd)?;
    for line in list.lines() {
        if let Some(p) = line.strip_prefix("worktree ") {
            return Ok(PathBuf::from(p));
        }
    }
    bail!("not inside a git repository");
}

pub fn run(cmd: WorktreeCmd) -> Result<()> {
    let cwd = std::env::current_dir()?;
    let root = main_root(&cwd)?;
    match cmd {
        WorktreeCmd::Start {
            plan,
            from,
            shared_target,
            clone,
            url,
        } => {
            if clone {
                start_clone(&root, &plan, url.as_deref())
            } else {
                start(&root, &plan, &from, shared_target)
            }
        }
        WorktreeCmd::List => list(&root),
        WorktreeCmd::Finish {
            plan,
            push,
            keep,
            into,
            clone,
        } => {
            if clone {
                finish_clone(&root, &plan, push)
            } else {
                finish(&root, &plan, &into, push, keep)
            }
        }
    }
}

/// `<parent>/<repo>-clone-<plan>` — the isolated clone directory.
fn clone_dir(root: &Path, plan: &str) -> PathBuf {
    let repo_name = root
        .file_name()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_else(|| "repo".into());
    root.parent()
        .unwrap_or(root)
        .join(format!("{repo_name}-clone-{plan}"))
}

fn start_clone(root: &Path, plan: &str, url: Option<&str>) -> Result<()> {
    let dir = clone_dir(root, plan);
    let branch = format!("plan/{plan}");
    if dir.exists() {
        println!("Clone already exists: {}", dir.display());
        println!("  cd {}", dir.display());
        return Ok(());
    }
    let url = match url {
        Some(u) => u.to_string(),
        None => git_stdout(&["remote", "get-url", "origin"], root)?,
    };
    if url.is_empty() {
        bail!("no `origin` remote — pass --url <remote>");
    }
    let parent = dir.parent().unwrap_or(root);
    git_checked(&["clone", &url, &dir.to_string_lossy()], parent)?;
    git_checked(&["checkout", "-b", &branch], &dir)?;
    println!("\u{2713} clone {} on branch {}", dir.display(), branch);
    println!("  Open your agent/session there:  cd {}", dir.display());
    println!("  When done:  asd worktree finish {plan} --clone --push");
    Ok(())
}

fn finish_clone(root: &Path, plan: &str, push: bool) -> Result<()> {
    let dir = clone_dir(root, plan);
    let branch = format!("plan/{plan}");
    if !dir.exists() {
        bail!(
            "no clone at {} — run `asd worktree start {plan} --clone` first",
            dir.display()
        );
    }
    let dirty = git_stdout(&["status", "--porcelain"], &dir)?;
    if !dirty.is_empty() {
        bail!(
            "clone {} has uncommitted changes — commit or stash them first",
            dir.display()
        );
    }
    if push {
        git_checked(&["push", "origin", &branch], &dir)?;
        println!("\u{2713} pushed {branch} to origin (merge it via MR / on the main checkout)");
    } else {
        println!("  (not pushed — pass --push to publish {branch} before teardown)");
    }
    std::fs::remove_dir_all(&dir)?;
    println!("\u{2713} removed clone {}", dir.display());
    Ok(())
}

fn start(root: &Path, plan: &str, from: &str, shared_target: bool) -> Result<()> {
    let l = layout(root, plan);
    if l.wt_dir.exists() {
        println!("Worktree already exists: {}", l.wt_dir.display());
        println!("  cd {}", l.wt_dir.display());
        return Ok(());
    }
    let wt = l.wt_dir.to_string_lossy().into_owned();
    git_checked(&["worktree", "add", &wt, "-b", &l.branch, from], root)?;

    // Auto-enable the repo's tracked git hooks (e.g. the pre-push rustfmt gate)
    // so agent worktrees inherit the same pre-push checks CI runs, without
    // anyone remembering to run scripts/setup-hooks.sh. core.hooksPath lives in
    // the shared config, so setting it once covers every worktree; a relative
    // `.githooks` resolves against each worktree's own tree. No-op for repos
    // that ship no `.githooks/`.
    if l.wt_dir.join(".githooks").is_dir() {
        let _ = git(&["config", "core.hooksPath", ".githooks"], root);
        println!("  Hooks: pre-push fmt gate enabled (.githooks)");
    }

    if shared_target {
        let cargo_dir = l.wt_dir.join(".cargo");
        std::fs::create_dir_all(&cargo_dir)?;
        let target = root.join(".wt-target");
        std::fs::write(
            cargo_dir.join("config.toml"),
            format!("[build]\ntarget-dir = \"{}\"\n", target.display()),
        )?;
    }

    println!(
        "\u{2713} worktree {} on branch {}",
        l.wt_dir.display(),
        l.branch
    );
    println!(
        "  Open your agent/session there:  cd {}",
        l.wt_dir.display()
    );
    if shared_target {
        println!("  Shared build cache: {}/.wt-target", root.display());
    }
    println!("  When done:  asd worktree finish {plan}");
    Ok(())
}

fn list(root: &Path) -> Result<()> {
    let text = git_stdout(&["worktree", "list", "--porcelain"], root)?;
    let prefix = format!(
        "{}-wt-",
        root.file_name()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or_default()
    );

    let mut path: Option<String> = None;
    let mut branch: Option<String> = None;
    let mut rows: Vec<(String, String, String)> = Vec::new();
    let mut flush = |path: &Option<String>, branch: &Option<String>| {
        if let Some(p) = path
            && let Some(name) = Path::new(p)
                .file_name()
                .map(|s| s.to_string_lossy().into_owned())
            && let Some(plan) = name.strip_prefix(&prefix)
        {
            rows.push((
                plan.to_string(),
                branch.clone().unwrap_or_else(|| "?".into()),
                p.clone(),
            ));
        }
    };
    for line in text.lines() {
        if let Some(p) = line.strip_prefix("worktree ") {
            flush(&path, &branch);
            path = Some(p.to_string());
            branch = None;
        } else if let Some(b) = line.strip_prefix("branch ") {
            branch = Some(b.trim_start_matches("refs/heads/").to_string());
        }
    }
    flush(&path, &branch);

    // Clones have their own .git and aren't in `git worktree list`; scan siblings.
    let repo_name = prefix.trim_end_matches("-wt-").to_string();
    let clone_prefix = format!("{repo_name}-clone-");
    let mut clone_rows: Vec<(String, String)> = Vec::new();
    if let Some(parent) = root.parent()
        && let Ok(entries) = std::fs::read_dir(parent)
    {
        for e in entries.flatten() {
            let name = e.file_name().to_string_lossy().into_owned();
            if let Some(plan) = name.strip_prefix(&clone_prefix)
                && e.path().is_dir()
            {
                clone_rows.push((plan.to_string(), e.path().to_string_lossy().into_owned()));
            }
        }
    }
    clone_rows.sort();

    if rows.is_empty() && clone_rows.is_empty() {
        println!("No plan-scoped worktrees or clones for {repo_name}.");
        return Ok(());
    }
    for (plan, branch, p) in rows {
        println!("  wt     {plan:<20} [{branch}]  {p}");
    }
    for (plan, p) in clone_rows {
        println!("  clone  {plan:<20} [plan/{plan}]  {p}");
    }
    Ok(())
}

fn finish(root: &Path, plan: &str, into: &str, push: bool, keep: bool) -> Result<()> {
    let l = layout(root, plan);
    if !l.wt_dir.exists() {
        bail!(
            "no worktree at {} — run `asd worktree start {plan}` first",
            l.wt_dir.display()
        );
    }

    let dirty = git_stdout(&["status", "--porcelain"], &l.wt_dir)?;
    if !dirty.is_empty() {
        bail!(
            "worktree {} has uncommitted changes — commit or stash them first",
            l.wt_dir.display()
        );
    }

    // Never switch the main checkout's HEAD — require it already on `into`.
    let cur = git_stdout(&["rev-parse", "--abbrev-ref", "HEAD"], root)?;
    if cur != into {
        bail!(
            "main checkout {} is on '{cur}', not '{into}' — checkout {into} there first \
             (refusing to switch it: another agent may be using it)",
            root.display()
        );
    }

    let msg = format!("Merge {} ({plan})", l.branch);
    let merge = git(&["merge", "--no-ff", &l.branch, "-m", &msg], root)?;
    if !merge.status.success() {
        let _ = git(&["merge", "--abort"], root);
        bail!(
            "merge conflict merging {} into {into} — resolve manually:\n{}",
            l.branch,
            String::from_utf8_lossy(&merge.stderr).trim()
        );
    }
    println!("\u{2713} merged {} into {into}", l.branch);

    if push {
        git_checked(&["push", "origin", into], root)?;
        println!("\u{2713} pushed {into}");
    }

    if keep {
        println!("  (kept worktree + branch)");
        return Ok(());
    }

    git_checked(
        &["worktree", "remove", "--force", &l.wt_dir.to_string_lossy()],
        root,
    )?;
    git_checked(&["branch", "-D", &l.branch], root)?;
    let _ = git(&["worktree", "prune"], root);
    println!(
        "\u{2713} removed worktree {} and branch {}",
        l.wt_dir.display(),
        l.branch
    );
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn layout_derives_sibling_dir_and_plan_branch() {
        let l = layout(Path::new("/home/me/AgentStateDeveloper"), "cost-model");
        assert_eq!(
            l.wt_dir,
            PathBuf::from("/home/me/AgentStateDeveloper-wt-cost-model")
        );
        assert_eq!(l.branch, "plan/cost-model");
    }
}