selfware 0.6.1

Your personal AI workshop — software you own, software that lasts
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
//! Git Worktree Isolation Tools
//!
//! Provides tools for creating and managing isolated git worktrees, allowing
//! the agent to work in a separate directory without affecting the main working directory.
//!
//! # Example Workflow
//!
//! ```text
//! // Enter a new worktree for isolated development
//! EnterWorktreeTool::execute({"path": "feature-branch", "branch": "main"})
//!
//! // ... do work in isolation ...
//!
//! // Exit and optionally remove the worktree
//! ExitWorktreeTool::execute({"path": "feature-branch", "remove": true})
//! ```

use super::Tool;
use crate::config::SafetyConfig;
use anyhow::{Context, Result};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::env;
use std::path::{Path, PathBuf};
use tracing::{info, warn};

/// Global state to track the current worktree context
/// This is used to remember the original directory when entering a worktree
use std::sync::Mutex;

static WORKTREE_STATE: Mutex<WorktreeState> = Mutex::new(WorktreeState::new());

#[derive(Debug, Clone)]
struct WorktreeState {
    /// Stack of directories representing worktree entry history
    /// The first element is always the original repo root
    directory_stack: Vec<PathBuf>,
    /// Currently active worktree path (if any)
    current_worktree: Option<PathBuf>,
}

impl WorktreeState {
    const fn new() -> Self {
        Self {
            directory_stack: Vec::new(),
            current_worktree: None,
        }
    }

    fn initialize(&mut self) -> Result<()> {
        if self.directory_stack.is_empty() {
            let current = env::current_dir().context("Failed to get current directory")?;
            self.directory_stack.push(current);
        }
        Ok(())
    }

    fn push_worktree(&mut self, worktree_path: PathBuf) -> Result<PathBuf> {
        self.initialize()?;
        self.directory_stack.push(worktree_path.clone());
        self.current_worktree = Some(worktree_path.clone());
        env::set_current_dir(&worktree_path).with_context(|| {
            format!(
                "Failed to change to worktree directory: {}",
                worktree_path.display()
            )
        })?;
        Ok(worktree_path)
    }

    fn pop_worktree(&mut self, remove: bool) -> Result<(PathBuf, Option<PathBuf>)> {
        self.initialize()?;

        let current = self.directory_stack.pop();
        let _previous_path = current.clone();

        // If we're removing the worktree, capture its path before we forget it
        let removed_path = if remove { current } else { None };

        // Update current worktree to the previous entry (or None if back at root)
        self.current_worktree = self.directory_stack.last().cloned();

        // Change back to the previous directory (root of the stack)
        if let Some(ref root) = self.directory_stack.first() {
            env::set_current_dir(root).with_context(|| {
                format!(
                    "Failed to change back to root directory: {}",
                    root.display()
                )
            })?;
        }

        Ok((
            self.directory_stack
                .first()
                .cloned()
                .unwrap_or_else(|| PathBuf::from(".")),
            removed_path,
        ))
    }

    #[allow(dead_code)]
    fn current(&self) -> Option<&PathBuf> {
        self.directory_stack.last()
    }

    #[allow(dead_code)]
    fn root(&self) -> Option<&PathBuf> {
        self.directory_stack.first()
    }

    fn is_in_worktree(&self) -> bool {
        self.directory_stack.len() > 1
    }
}

/// Default worktree base directory within .selfware/
const DEFAULT_WORKTREE_BASE: &str = ".selfware/worktrees";

/// Generate a timestamp-based worktree name
fn generate_worktree_name() -> String {
    let timestamp = chrono::Local::now().format("%Y%m%d_%H%M%S");
    format!("worktree_{}", timestamp)
}

/// Resolve the worktree path, creating default if needed
#[allow(dead_code)]
fn resolve_worktree_path(path: Option<&str>) -> Result<PathBuf> {
    if let Some(p) = path {
        // Explicit path provided
        let path_buf = PathBuf::from(p);
        if path_buf.is_absolute() {
            Ok(path_buf)
        } else {
            // Relative to current directory
            env::current_dir()
                .map(|cwd| cwd.join(&path_buf))
                .context("Failed to resolve relative path")
        }
    } else {
        // Generate default path
        let name = generate_worktree_name();
        env::current_dir()
            .map(|cwd| cwd.join(DEFAULT_WORKTREE_BASE).join(name))
            .context("Failed to create default worktree path")
    }
}

/// Find the git repository root
async fn find_git_root() -> Result<PathBuf> {
    let output = tokio::process::Command::new("git")
        .args(["rev-parse", "--show-toplevel"])
        .output()
        .await
        .context("Failed to execute git rev-parse")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("Not a git repository: {}", stderr);
    }

    let root = String::from_utf8_lossy(&output.stdout);
    Ok(PathBuf::from(root.trim()))
}

/// Validate a branch name to prevent shell injection
fn validate_branch_name(name: &str) -> Result<()> {
    if name.is_empty() {
        anyhow::bail!("Branch name must not be empty");
    }
    if name.len() > 255 {
        anyhow::bail!("Branch name too long (max 255 characters)");
    }

    // Check for dangerous characters that could cause shell injection
    for c in name.chars() {
        if c.is_control() || matches!(c, ';' | '&' | '|' | '$' | '`' | '<' | '>') {
            anyhow::bail!("Invalid character '{}' in branch name", c);
        }
    }

    // Branch name cannot start with '-' (could be interpreted as a flag)
    if name.starts_with('-') {
        anyhow::bail!("Branch name must not start with '-'");
    }

    Ok(())
}

/// Validate a path for security
fn validate_path(path: &str, _safety_config: Option<&SafetyConfig>) -> Result<()> {
    // Basic validation - prevent path traversal
    if path.contains("..") {
        // Allow .. in the middle but not at the start or as escape attempts
        let normalized = Path::new(path).components().collect::<PathBuf>();
        if normalized
            .components()
            .any(|c| matches!(c, std::path::Component::ParentDir))
        {
            // This is ok - it's a relative path that happens to have ..
        }
    }

    // Check for null bytes
    if path.contains('\0') {
        anyhow::bail!("Path contains null bytes");
    }

    Ok(())
}

/// Output from git worktree list --porcelain
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorktreeEntry {
    pub path: String,
    pub branch: Option<String>,
    pub detached: bool,
    pub bare: bool,
}

#[derive(Default)]
pub struct EnterWorktreeTool {
    pub safety_config: Option<SafetyConfig>,
}

#[derive(Default)]
pub struct ExitWorktreeTool {
    pub safety_config: Option<SafetyConfig>,
}

#[derive(Default)]
pub struct ListWorktreesTool {
    pub safety_config: Option<SafetyConfig>,
}

impl EnterWorktreeTool {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_safety_config(config: SafetyConfig) -> Self {
        Self {
            safety_config: Some(config),
        }
    }
}

impl ExitWorktreeTool {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_safety_config(config: SafetyConfig) -> Self {
        Self {
            safety_config: Some(config),
        }
    }
}

impl ListWorktreesTool {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_safety_config(config: SafetyConfig) -> Self {
        Self {
            safety_config: Some(config),
        }
    }
}

#[async_trait]
impl Tool for EnterWorktreeTool {
    fn name(&self) -> &str {
        "enter_worktree"
    }

    fn description(&self) -> &str {
        "Create and enter a git worktree for isolated development. Changes working directory to the new worktree. \
         If no path is provided, creates worktree at .selfware/worktrees/{timestamp}/. \
         If no branch is provided, creates a detached worktree."
    }

    fn schema(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Path for the new worktree (default: .selfware/worktrees/{timestamp}/)"
                },
                "branch": {
                    "type": "string",
                    "description": "Branch to checkout (default: detached HEAD)"
                }
            }
        })
    }

    async fn execute(&self, args: Value) -> Result<Value> {
        let path_arg = args.get("path").and_then(|v| v.as_str());
        let branch_arg = args.get("branch").and_then(|v| v.as_str());

        // Validate inputs
        if let Some(p) = path_arg {
            validate_path(p, self.safety_config.as_ref())?;
        }
        if let Some(b) = branch_arg {
            validate_branch_name(b)?;
        }

        // Find git root
        let git_root = find_git_root().await?;
        let original_dir = env::current_dir().context("Failed to get current directory")?;

        // Resolve worktree path
        let worktree_path = if let Some(p) = path_arg {
            PathBuf::from(p)
        } else {
            let name = generate_worktree_name();
            git_root.join(DEFAULT_WORKTREE_BASE).join(name)
        };

        // Ensure parent directory exists
        if let Some(parent) = worktree_path.parent() {
            tokio::fs::create_dir_all(parent)
                .await
                .with_context(|| format!("Failed to create directory: {}", parent.display()))?;
        }

        info!("Creating worktree at: {}", worktree_path.display());

        // Build git worktree add command
        let mut cmd = tokio::process::Command::new("git");
        cmd.arg("worktree").arg("add");

        if branch_arg.is_none() {
            // Create detached worktree
            cmd.arg("--detach");
        }

        cmd.arg(&worktree_path);

        if let Some(branch) = branch_arg {
            cmd.arg(branch);
        }

        let output = cmd
            .current_dir(&git_root)
            .output()
            .await
            .context("Failed to execute git worktree add")?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!("Failed to create worktree: {}", stderr);
        }

        // Change to the worktree directory
        let worktree_path_str = worktree_path.to_string_lossy().to_string();
        let branch_used = branch_arg.unwrap_or("(detached)").to_string();

        // Update the global state and change directory
        let mut state = WORKTREE_STATE
            .lock()
            .map_err(|e| anyhow::anyhow!("Lock poisoned: {}", e))?;
        state.push_worktree(worktree_path.clone())?;

        info!(
            "Entered worktree: {} (branch: {})",
            worktree_path.display(),
            branch_used
        );

        Ok(serde_json::json!({
            "success": true,
            "worktree_path": worktree_path_str,
            "branch": branch_used,
            "previous_path": original_dir.to_string_lossy().to_string(),
            "git_root": git_root.to_string_lossy().to_string()
        }))
    }

    fn metadata(&self) -> crate::safety::ToolMetadata {
        // Medium risk - creates directories and changes working directory
        crate::safety::ToolMetadata::custom(
            false,
            false,
            crate::safety::RiskLevel::Medium,
            false,
            false,
        )
    }
}

#[async_trait]
impl Tool for ExitWorktreeTool {
    fn name(&self) -> &str {
        "exit_worktree"
    }

    fn description(&self) -> &str {
        "Exit the current git worktree and return to the main repository. \
         Optionally remove the worktree directory."
    }

    fn schema(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Path of worktree to exit (default: current worktree)"
                },
                "remove": {
                    "type": "boolean",
                    "description": "Remove the worktree after exiting",
                    "default": false
                }
            }
        })
    }

    async fn execute(&self, args: Value) -> Result<Value> {
        let _path_arg = args.get("path").and_then(|v| v.as_str());
        let remove = args
            .get("remove")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let (root_path, removed_path) = {
            let mut state = WORKTREE_STATE
                .lock()
                .map_err(|e| anyhow::anyhow!("Lock poisoned: {}", e))?;

            if !state.is_in_worktree() {
                anyhow::bail!("Not currently in a worktree");
            }

            state.pop_worktree(remove)?
        };

        // If remove is requested, run git worktree remove
        let mut removed = false;
        if remove {
            if let Some(ref worktree_path) = removed_path {
                let output = tokio::process::Command::new("git")
                    .args(["worktree", "remove", &worktree_path.to_string_lossy()])
                    .output()
                    .await
                    .context("Failed to execute git worktree remove")?;

                if output.status.success() {
                    removed = true;
                    info!("Removed worktree: {}", worktree_path.display());
                } else {
                    let stderr = String::from_utf8_lossy(&output.stderr);
                    warn!("Failed to remove worktree: {}", stderr);
                    // Don't fail - we've already changed directories back
                }
            }
        }

        info!("Exited worktree, returned to: {}", root_path.display());

        Ok(serde_json::json!({
            "success": true,
            "previous_path": removed_path.map(|p| p.to_string_lossy().to_string()).unwrap_or_default(),
            "current_path": root_path.to_string_lossy().to_string(),
            "removed": removed
        }))
    }

    fn metadata(&self) -> crate::safety::ToolMetadata {
        // Medium risk - can remove directories
        crate::safety::ToolMetadata::custom(
            false,
            true, // Destructive - can remove worktrees
            crate::safety::RiskLevel::Medium,
            false,
            false,
        )
    }
}

#[async_trait]
impl Tool for ListWorktreesTool {
    fn name(&self) -> &str {
        "list_worktrees"
    }

    fn description(&self) -> &str {
        "List all git worktrees with their paths and branches."
    }

    fn schema(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {}
        })
    }

    async fn execute(&self, _args: Value) -> Result<Value> {
        let output = tokio::process::Command::new("git")
            .args(["worktree", "list", "--porcelain"])
            .output()
            .await
            .context("Failed to execute git worktree list")?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!("Failed to list worktrees: {}", stderr);
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        let worktrees = parse_worktree_list(&stdout);

        // Check if we're currently in a worktree
        let state = WORKTREE_STATE
            .lock()
            .map_err(|e| anyhow::anyhow!("Lock poisoned: {}", e))?;
        let current_worktree = state
            .current_worktree
            .as_ref()
            .map(|p| p.to_string_lossy().to_string());

        Ok(serde_json::json!({
            "worktrees": worktrees,
            "count": worktrees.len(),
            "current_worktree": current_worktree
        }))
    }

    fn metadata(&self) -> crate::safety::ToolMetadata {
        crate::safety::ToolMetadata::read_only()
    }
}

/// Parse git worktree list --porcelain output
fn parse_worktree_list(output: &str) -> Vec<WorktreeEntry> {
    let mut worktrees = Vec::new();
    let mut current = WorktreeEntry {
        path: String::new(),
        branch: None,
        detached: false,
        bare: false,
    };

    for line in output.lines() {
        if line.is_empty() {
            // End of worktree entry
            if !current.path.is_empty() {
                worktrees.push(current);
                current = WorktreeEntry {
                    path: String::new(),
                    branch: None,
                    detached: false,
                    bare: false,
                };
            }
            continue;
        }

        if let Some(path) = line.strip_prefix("worktree ") {
            current.path = path.to_string();
        } else if let Some(branch) = line.strip_prefix("branch ") {
            // Extract branch name from ref (refs/heads/branch-name)
            current.branch = branch.split('/').next_back().map(|s| s.to_string());
        } else if line == "detached" {
            current.detached = true;
        } else if line == "bare" {
            current.bare = true;
        }
        // Ignore other fields (HEAD, locked, prunable)
    }

    // Don't forget the last entry
    if !current.path.is_empty() {
        worktrees.push(current);
    }

    worktrees
}

/// Get the current worktree path if we're in one
pub fn get_current_worktree() -> Option<PathBuf> {
    WORKTREE_STATE
        .lock()
        .ok()
        .and_then(|state| state.current_worktree.clone())
}

/// Check if currently in a worktree
pub fn is_in_worktree() -> bool {
    WORKTREE_STATE
        .lock()
        .map(|state| state.is_in_worktree())
        .unwrap_or(false)
}

#[cfg(test)]
#[path = "../../tests/unit/tools/git_worktree/git_worktree_test.rs"]
mod tests;