j-cli 12.9.11

A fast CLI tool for alias management, daily reports, and productivity
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
use crate::command::chat::tools::{
    PlanDecision, Tool, ToolResult, parse_tool_args, schema_to_tool_params,
};
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::Value;
use std::path::PathBuf;
use std::process::Command;
use std::sync::{Arc, Mutex, atomic::AtomicBool};

// ========== Worktree Session State ==========

/// 当前 worktree 会话信息
#[derive(Clone, Debug)]
pub struct WorktreeSession {
    /// 进入 worktree 前的工作目录
    pub original_cwd: PathBuf,
    /// worktree 路径
    pub worktree_path: PathBuf,
    /// worktree 分支名
    pub branch: String,
    /// 进入时的 HEAD commit(用于检测新 commits)
    pub original_head_commit: Option<String>,
}

/// 跨工具共享的 worktree 状态
#[derive(Debug)]
pub struct WorktreeState {
    session: Mutex<Option<WorktreeSession>>,
}

impl Default for WorktreeState {
    fn default() -> Self {
        Self::new()
    }
}

impl WorktreeState {
    pub fn new() -> Self {
        Self {
            session: Mutex::new(None),
        }
    }

    pub fn get_session(&self) -> Option<WorktreeSession> {
        self.session.lock().ok()?.clone()
    }

    pub fn set_session(&self, session: WorktreeSession) {
        if let Ok(mut s) = self.session.lock() {
            *s = Some(session);
        }
    }

    pub fn clear_session(&self) -> Option<WorktreeSession> {
        self.session.lock().ok()?.take()
    }
}

// ========== Helpers ==========

/// 获取 git 仓库根目录
fn git_root() -> Result<PathBuf, String> {
    let output = Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .output()
        .map_err(|e| format!("执行 git 失败: {}", e))?;
    if !output.status.success() {
        return Err("当前目录不在 git 仓库中".to_string());
    }
    let root = String::from_utf8_lossy(&output.stdout).trim().to_string();
    Ok(PathBuf::from(root))
}

/// 获取当前 HEAD commit SHA
fn head_commit() -> Option<String> {
    Command::new("git")
        .args(["rev-parse", "HEAD"])
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
}

/// 验证 worktree 名称
fn validate_slug(name: &str) -> Result<(), String> {
    if name.is_empty() {
        return Err("名称不能为空".to_string());
    }
    if name.len() > 64 {
        return Err("名称不能超过 64 个字符".to_string());
    }
    if name.contains("..") {
        return Err("名称不能包含 '..'".to_string());
    }
    for ch in name.chars() {
        if !ch.is_alphanumeric() && ch != '.' && ch != '_' && ch != '-' {
            return Err(format!("名称包含非法字符: '{}'", ch));
        }
    }
    Ok(())
}

/// 生成随机 slug
fn random_slug() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let ts = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis();
    format!("wt-{:x}", ts & 0xFFFFFF)
}

/// 统计 worktree 中的变更
fn count_changes(worktree_path: &str, original_head: Option<&str>) -> (usize, usize) {
    // 未提交文件数
    let changed_files = Command::new("git")
        .args(["-C", worktree_path, "status", "--porcelain"])
        .output()
        .ok()
        .map(|o| {
            String::from_utf8_lossy(&o.stdout)
                .lines()
                .filter(|l| !l.trim().is_empty())
                .count()
        })
        .unwrap_or(0);

    // 新 commits 数
    let commits = original_head
        .and_then(|base| {
            Command::new("git")
                .args([
                    "-C",
                    worktree_path,
                    "rev-list",
                    "--count",
                    &format!("{}..HEAD", base),
                ])
                .output()
                .ok()
                .filter(|o| o.status.success())
                .map(|o| {
                    String::from_utf8_lossy(&o.stdout)
                        .trim()
                        .parse::<usize>()
                        .unwrap_or(0)
                })
        })
        .unwrap_or(0);

    (changed_files, commits)
}

// ========== Agent Worktree Helpers ==========
// 供 CreateTeammate / AgentTool 调用,自动为并行 agent 创建/删除 worktree

/// 为 agent 创建专用 worktree。
/// - `agent_name`: 用于生成目录名和分支名(会被 slug 化)
/// - 返回 `(worktree_path, branch_name)`
pub fn create_agent_worktree(agent_name: &str) -> Result<(PathBuf, String), String> {
    let repo_root = git_root()?;

    // slug 化:只保留字母数字、连字符、下划线
    let slug: String = agent_name
        .chars()
        .map(|c| {
            if c.is_alphanumeric() || c == '-' || c == '_' {
                c.to_ascii_lowercase()
            } else {
                '-'
            }
        })
        .collect();
    let slug = format!("agent-{}", slug);
    let branch = format!("worktree-{}", slug);
    let wt_path = repo_root.join(".jcli").join("worktrees").join(&slug);

    // 如果 worktree 目录已存在,直接复用
    if wt_path.exists() {
        return Ok((wt_path, branch));
    }

    let worktrees_dir = repo_root.join(".jcli").join("worktrees");
    std::fs::create_dir_all(&worktrees_dir)
        .map_err(|e| format!("创建 worktrees 目录失败: {}", e))?;

    let output = Command::new("git")
        .current_dir(&repo_root)
        .args([
            "worktree",
            "add",
            "-B",
            &branch,
            &wt_path.to_string_lossy(),
            "HEAD",
        ])
        .output()
        .map_err(|e| format!("执行 git worktree add 失败: {}", e))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(format!("创建 worktree 失败: {}", stderr.trim()));
    }

    Ok((wt_path, branch))
}

/// 删除 agent worktree(最大努力,忽略错误)
pub fn remove_agent_worktree(worktree_path: &std::path::Path, branch: &str) {
    let wt_str = worktree_path.to_string_lossy().to_string();
    let _ = Command::new("git")
        .args(["worktree", "remove", "--force", &wt_str])
        .output();
    // 等 git 释放内部锁
    std::thread::sleep(std::time::Duration::from_millis(200));
    let _ = Command::new("git").args(["branch", "-D", branch]).output();
}

// ========== EnterWorktreeTool ==========

#[derive(Deserialize, JsonSchema)]
struct EnterWorktreeParams {
    /// Optional name for the worktree. Only letters, digits, dots, underscores, dashes allowed; max 64 chars. A random name is generated if not provided.
    #[serde(default)]
    name: Option<String>,
}

#[derive(Debug)]
pub struct EnterWorktreeTool {
    pub state: Arc<WorktreeState>,
}

impl EnterWorktreeTool {
    pub const NAME: &'static str = "EnterWorktree";
}

impl Tool for EnterWorktreeTool {
    fn name(&self) -> &str {
        Self::NAME
    }

    fn description(&self) -> &str {
        r#"
        Creates an isolated git worktree and switches the session into it.
        Use this when you need to work on code in isolation — for example, when multiple
        sessions may be editing the same repository simultaneously.

        The worktree is created at .jcli/worktrees/{name} under the git root,
        with a branch named worktree-{name}.

        Use ExitWorktree to leave the worktree (keep or remove it).
        "#
    }

    fn parameters_schema(&self) -> Value {
        schema_to_tool_params::<EnterWorktreeParams>()
    }

    fn execute(&self, arguments: &str, _cancelled: &Arc<AtomicBool>) -> ToolResult {
        let params: EnterWorktreeParams = match parse_tool_args(arguments) {
            Ok(p) => p,
            Err(e) => return e,
        };

        // 检查是否已在 worktree 中
        if self.state.get_session().is_some() {
            return ToolResult {
                output: "已在 worktree 会话中,请先使用 ExitWorktree 退出".to_string(),
                is_error: true,
                images: vec![],
                plan_decision: PlanDecision::None,
            };
        }

        // 获取 git 根目录
        let repo_root = match git_root() {
            Ok(r) => r,
            Err(e) => {
                return ToolResult {
                    output: e,
                    is_error: true,
                    images: vec![],
                    plan_decision: PlanDecision::None,
                };
            }
        };

        let slug = params.name.unwrap_or_else(random_slug);
        if let Err(e) = validate_slug(&slug) {
            return ToolResult {
                output: format!("无效的 worktree 名称: {}", e),
                is_error: true,
                images: vec![],
                plan_decision: PlanDecision::None,
            };
        }

        let branch = format!("worktree-{}", slug);
        let wt_path = repo_root.join(".jcli").join("worktrees").join(&slug);

        // 如果目录已存在,说明 worktree 可能已存在
        if wt_path.exists() {
            return ToolResult {
                output: format!(
                    "Worktree 目录已存在: {}。请使用其他名称或先手动清理。",
                    wt_path.display()
                ),
                is_error: true,
                images: vec![],
                plan_decision: PlanDecision::None,
            };
        }

        // 确保 .jcli/worktrees 目录存在
        let worktrees_dir = repo_root.join(".jcli").join("worktrees");
        if let Err(e) = std::fs::create_dir_all(&worktrees_dir) {
            return ToolResult {
                output: format!("创建 worktrees 目录失败: {}", e),
                is_error: true,
                images: vec![],
                plan_decision: PlanDecision::None,
            };
        }

        // 记录原始工作目录和 HEAD
        let original_cwd = std::env::current_dir().unwrap_or_default();
        let orig_head = head_commit();

        // 创建 worktree: git worktree add -B <branch> <path> HEAD
        let output = Command::new("git")
            .current_dir(&repo_root)
            .args([
                "worktree",
                "add",
                "-B",
                &branch,
                &wt_path.to_string_lossy(),
                "HEAD",
            ])
            .output();

        match output {
            Ok(o) if o.status.success() => {}
            Ok(o) => {
                let stderr = String::from_utf8_lossy(&o.stderr);
                return ToolResult {
                    output: format!("创建 worktree 失败: {}", stderr.trim()),
                    is_error: true,
                    images: vec![],
                    plan_decision: PlanDecision::None,
                };
            }
            Err(e) => {
                return ToolResult {
                    output: format!("执行 git worktree add 失败: {}", e),
                    is_error: true,
                    images: vec![],
                    plan_decision: PlanDecision::None,
                };
            }
        }

        // 切换工作目录
        if let Err(e) = std::env::set_current_dir(&wt_path) {
            return ToolResult {
                output: format!("切换到 worktree 目录失败: {}", e),
                is_error: true,
                images: vec![],
                plan_decision: PlanDecision::None,
            };
        }

        // 保存会话状态
        self.state.set_session(WorktreeSession {
            original_cwd,
            worktree_path: wt_path.clone(),
            branch: branch.clone(),
            original_head_commit: orig_head,
        });

        ToolResult {
            output: format!(
                "已创建并进入 worktree:\n  路径: {}\n  分支: {}\n\n当前会话在隔离的工作目录中,所有文件操作不会影响主仓库。\n完成后使用 ExitWorktree 退出(可选择保留或删除)。",
                wt_path.display(),
                branch,
            ),
            is_error: false,
            images: vec![],
            plan_decision: PlanDecision::None,
        }
    }

    fn requires_confirmation(&self) -> bool {
        true
    }

    fn confirmation_message(&self, arguments: &str) -> String {
        let name = serde_json::from_str::<EnterWorktreeParams>(arguments)
            .ok()
            .and_then(|p| p.name)
            .unwrap_or_else(|| "(auto)".to_string());
        format!("创建并进入 git worktree: {}", name)
    }
}

// ========== ExitWorktreeTool ==========

#[derive(Deserialize, JsonSchema)]
struct ExitWorktreeParams {
    /// "keep" preserves the worktree and branch on disk; "remove" deletes both.
    action: String,
    /// Required true when action is "remove" and the worktree has uncommitted files or unmerged commits.
    #[serde(default)]
    discard_changes: bool,
}

#[derive(Debug)]
pub struct ExitWorktreeTool {
    pub state: Arc<WorktreeState>,
}

impl ExitWorktreeTool {
    pub const NAME: &'static str = "ExitWorktree";
}

impl Tool for ExitWorktreeTool {
    fn name(&self) -> &str {
        Self::NAME
    }

    fn description(&self) -> &str {
        r#"
        Exit the current worktree session created by EnterWorktree.
        - action "keep": preserves the worktree directory and branch for later use
        - action "remove": deletes the worktree and its branch (requires discard_changes: true if there are uncommitted changes or new commits)
        "#
    }

    fn parameters_schema(&self) -> Value {
        schema_to_tool_params::<ExitWorktreeParams>()
    }

    fn execute(&self, arguments: &str, _cancelled: &Arc<AtomicBool>) -> ToolResult {
        let params: ExitWorktreeParams = match parse_tool_args(arguments) {
            Ok(p) => p,
            Err(e) => return e,
        };

        let session = match self.state.get_session() {
            Some(s) => s,
            None => {
                return ToolResult {
                    output: "当前不在 worktree 会话中(仅对 EnterWorktree 创建的 worktree 有效)"
                        .to_string(),
                    is_error: true,
                    images: vec![],
                    plan_decision: PlanDecision::None,
                };
            }
        };

        let wt_path_str = session.worktree_path.to_string_lossy().to_string();

        match params.action.as_str() {
            "keep" => {
                // 切回原目录
                if let Err(e) = std::env::set_current_dir(&session.original_cwd) {
                    return ToolResult {
                        output: format!("切换回原目录失败: {}", e),
                        is_error: true,
                        images: vec![],
                        plan_decision: PlanDecision::None,
                    };
                }
                self.state.clear_session();

                ToolResult {
                    output: format!(
                        "已退出 worktree,工作已保留:\n  路径: {}\n  分支: {}\n\n已切回原目录: {}",
                        wt_path_str,
                        session.branch,
                        session.original_cwd.display(),
                    ),
                    is_error: false,
                    images: vec![],
                    plan_decision: PlanDecision::None,
                }
            }
            "remove" => {
                // 检查变更
                let (changed_files, commits) =
                    count_changes(&wt_path_str, session.original_head_commit.as_deref());

                if (changed_files > 0 || commits > 0) && !params.discard_changes {
                    let mut parts = Vec::new();
                    if changed_files > 0 {
                        parts.push(format!("{} 个未提交的文件", changed_files));
                    }
                    if commits > 0 {
                        parts.push(format!("{} 个新 commit", commits));
                    }
                    return ToolResult {
                        output: format!(
                            "Worktree 中有 {}。删除将永久丢弃这些工作。\n请向用户确认后,使用 discard_changes: true 重新调用;或使用 action: \"keep\" 保留 worktree。",
                            parts.join(""),
                        ),
                        is_error: true,
                        images: vec![],
                        plan_decision: PlanDecision::None,
                    };
                }

                // 切回原目录
                if let Err(e) = std::env::set_current_dir(&session.original_cwd) {
                    return ToolResult {
                        output: format!("切换回原目录失败: {}", e),
                        is_error: true,
                        images: vec![],
                        plan_decision: PlanDecision::None,
                    };
                }

                // 删除 worktree
                let remove_result = Command::new("git")
                    .args(["worktree", "remove", "--force", &wt_path_str])
                    .output();

                let mut messages = Vec::new();

                match remove_result {
                    Ok(o) if o.status.success() => {
                        messages.push(format!("已删除 worktree: {}", wt_path_str));
                    }
                    Ok(o) => {
                        let stderr = String::from_utf8_lossy(&o.stderr);
                        messages.push(format!("删除 worktree 警告: {}", stderr.trim()));
                        // 尝试强制删除目录
                        let _ = std::fs::remove_dir_all(&session.worktree_path);
                    }
                    Err(e) => {
                        messages.push(format!("执行 git worktree remove 失败: {}", e));
                    }
                }

                // 等待 git 释放锁
                std::thread::sleep(std::time::Duration::from_millis(100));

                // 删除分支
                let branch_result = Command::new("git")
                    .args(["branch", "-D", &session.branch])
                    .output();

                match branch_result {
                    Ok(o) if o.status.success() => {
                        messages.push(format!("已删除分支: {}", session.branch));
                    }
                    Ok(o) => {
                        let stderr = String::from_utf8_lossy(&o.stderr);
                        messages.push(format!("删除分支警告: {}", stderr.trim()));
                    }
                    Err(_) => {}
                }

                self.state.clear_session();

                let mut output = messages.join("\n");
                if changed_files > 0 || commits > 0 {
                    output.push_str(&format!(
                        "\n已丢弃 {} 个未提交文件和 {} 个 commit。",
                        changed_files, commits
                    ));
                }
                output.push_str(&format!(
                    "\n已切回原目录: {}",
                    session.original_cwd.display()
                ));

                ToolResult {
                    output,
                    is_error: false,
                    images: vec![],
                    plan_decision: PlanDecision::None,
                }
            }
            other => ToolResult {
                output: format!(
                    "无效的 action: \"{}\",只支持 \"keep\"\"remove\"",
                    other
                ),
                is_error: true,
                images: vec![],
                plan_decision: PlanDecision::None,
            },
        }
    }

    fn requires_confirmation(&self) -> bool {
        true
    }

    fn confirmation_message(&self, arguments: &str) -> String {
        let action = serde_json::from_str::<ExitWorktreeParams>(arguments)
            .ok()
            .map(|p| p.action)
            .unwrap_or_else(|| "?".to_string());
        match action.as_str() {
            "keep" => "退出 worktree(保留工作目录和分支)".to_string(),
            "remove" => "退出并删除 worktree(包括工作目录和分支)".to_string(),
            _ => format!("退出 worktree (action: {})", action),
        }
    }
}