zeptoclaw 0.9.0

Ultra-lightweight personal AI assistant
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
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
//! Git CLI tool for ZeptoClaw.
//!
//! Shells out to the system `git` binary. No libgit2 dependency.
//! All commands run in the configured workspace directory.
//!
//! # Supported actions
//!
//! - `status`      — working-tree status
//! - `log`         — commit history (default 10 entries)
//! - `diff`        — unstaged diff (optionally scoped to a path)
//! - `blame`       — per-line authorship for a file (requires `path`)
//! - `branch_list` — list local branches
//! - `commit`      — stage all tracked changes and commit (requires `message`)
//! - `add`         — stage a file or directory (requires `path`)
//! - `checkout`    — switch branches (requires `branch`)

use std::path::Path;
use std::process::Command;

use async_trait::async_trait;
use serde_json::{json, Value};

use crate::error::{Result, ZeptoError};
use crate::security::ShellSecurityConfig;

use super::{Tool, ToolContext, ToolOutput};

const DEFAULT_LOG_COUNT: u64 = 10;
const MAX_LOG_COUNT: u64 = 200;

/// Tool that exposes common `git` operations by shelling out to the `git` CLI.
///
/// The tool is skipped at registration time when `git` is not found on PATH
/// (checked via `GitTool::is_available()`). All commands run in the workspace
/// directory supplied by `ToolContext`. When no workspace is set the tool
/// returns an error.
///
/// When a `ShellSecurityConfig` is provided, the tool validates that `git` is
/// permitted by the allowlist before executing any command.
pub struct GitTool {
    shell_config: ShellSecurityConfig,
}

impl GitTool {
    /// Create a new GitTool instance with default (blocklist-only) security.
    pub fn new() -> Self {
        Self {
            shell_config: ShellSecurityConfig::new(),
        }
    }

    /// Create a new GitTool with an explicit shell security config.
    ///
    /// When the config uses `ShellAllowlistMode::Strict`, the git binary
    /// must appear in the allowlist or all actions will be rejected.
    pub fn with_security(shell_config: ShellSecurityConfig) -> Self {
        Self { shell_config }
    }

    /// Return `true` if the `git` binary is reachable on PATH.
    pub fn is_available() -> bool {
        Command::new("git")
            .arg("--version")
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .map(|s| s.success())
            .unwrap_or(false)
    }

    /// Run `git <args>` in `dir` and return stdout as a String.
    fn run(args: &[&str], dir: &str) -> Result<String> {
        if !Path::new(dir).is_dir() {
            return Err(ZeptoError::Tool(format!(
                "Workspace '{}' is not a directory",
                dir
            )));
        }

        let output = Command::new("git")
            .args(args)
            .current_dir(dir)
            .output()
            .map_err(|e| ZeptoError::Tool(format!("Failed to run git: {}", e)))?;

        let stdout = String::from_utf8_lossy(&output.stdout).to_string();
        let stderr = String::from_utf8_lossy(&output.stderr).to_string();

        if output.status.success() {
            Ok(stdout)
        } else {
            let detail = if stderr.trim().is_empty() {
                stdout.trim().to_string()
            } else {
                stderr.trim().to_string()
            };
            Err(ZeptoError::Tool(format!("git error: {}", detail)))
        }
    }
}

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

impl std::fmt::Debug for GitTool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GitTool").finish()
    }
}

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

    fn description(&self) -> &str {
        "Run git operations (status, log, diff, blame, branch_list, commit, add, checkout) in the workspace."
    }

    fn compact_description(&self) -> &str {
        "Git operations"
    }

    fn parameters(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "action": {
                    "type": "string",
                    "enum": ["status", "log", "diff", "blame", "branch_list", "commit", "add", "checkout"],
                    "description": "Git operation to perform."
                },
                "path": {
                    "type": "string",
                    "description": "File or directory path. Required for blame and add; optional for diff."
                },
                "message": {
                    "type": "string",
                    "description": "Commit message. Required for commit."
                },
                "branch": {
                    "type": "string",
                    "description": "Branch name. Required for checkout."
                },
                "count": {
                    "type": "integer",
                    "description": "Number of log entries to return (default 10, max 200).",
                    "minimum": 1,
                    "maximum": 200
                }
            },
            "required": ["action"]
        })
    }

    async fn execute(&self, args: Value, ctx: &ToolContext) -> Result<ToolOutput> {
        // Validate that the git binary is permitted by the shell allowlist.
        // This prevents bypassing shell_allowlist restrictions via the git tool.
        self.shell_config
            .validate_command("git")
            .map_err(|e| ZeptoError::Tool(format!("Git blocked by shell allowlist: {}", e)))?;

        let action = args
            .get("action")
            .and_then(Value::as_str)
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .ok_or_else(|| ZeptoError::Tool("Missing 'action' parameter".to_string()))?;

        let workspace = ctx
            .workspace
            .as_deref()
            .filter(|s| !s.is_empty())
            .ok_or_else(|| {
                ZeptoError::Tool(
                    "Workspace not configured; git tool requires a workspace".to_string(),
                )
            })?;

        match action {
            "status" => {
                let out = Self::run(&["status", "--short", "--branch"], workspace)?;
                if out.trim().is_empty() {
                    Ok(ToolOutput::llm_only("Nothing to report (clean working tree).".to_string()))
                } else {
                    Ok(ToolOutput::llm_only(out))
                }
            }

            "log" => {
                let count = args
                    .get("count")
                    .and_then(Value::as_u64)
                    .unwrap_or(DEFAULT_LOG_COUNT)
                    .clamp(1, MAX_LOG_COUNT);

                let count_str = count.to_string();
                let format = "--pretty=format:%h %ad %an: %s";
                let out = Self::run(
                    &["log", &format!("-{}", count_str), "--date=short", format],
                    workspace,
                )?;
                if out.trim().is_empty() {
                    Ok(ToolOutput::llm_only("No commits found.".to_string()))
                } else {
                    Ok(ToolOutput::llm_only(out))
                }
            }

            "diff" => {
                let path = args.get("path").and_then(Value::as_str);
                let out = if let Some(p) = path {
                    Self::run(&["diff", "--", p], workspace)?
                } else {
                    Self::run(&["diff"], workspace)?
                };
                if out.trim().is_empty() {
                    Ok(ToolOutput::llm_only("No differences found.".to_string()))
                } else {
                    Ok(ToolOutput::llm_only(out))
                }
            }

            "blame" => {
                let path = args
                    .get("path")
                    .and_then(Value::as_str)
                    .map(str::trim)
                    .filter(|s| !s.is_empty())
                    .ok_or_else(|| {
                        ZeptoError::Tool(
                            "Missing 'path' parameter; blame requires a file path".to_string(),
                        )
                    })?;
                Self::run(&["blame", "--", path], workspace).map(ToolOutput::llm_only)
            }

            "branch_list" => {
                let out = Self::run(&["branch", "--list", "--sort=-committerdate"], workspace)?;
                if out.trim().is_empty() {
                    Ok(ToolOutput::llm_only("No local branches found.".to_string()))
                } else {
                    Ok(ToolOutput::llm_only(out))
                }
            }

            "commit" => {
                let message = args
                    .get("message")
                    .and_then(Value::as_str)
                    .map(str::trim)
                    .filter(|s| !s.is_empty())
                    .ok_or_else(|| {
                        ZeptoError::Tool(
                            "Missing 'message' parameter; commit requires a commit message"
                                .to_string(),
                        )
                    })?;
                // Only commit tracked changes (no -A to avoid accidentally staging untracked files).
                Self::run(&["commit", "-m", message], workspace).map(ToolOutput::llm_only)
            }

            "add" => {
                let path = args
                    .get("path")
                    .and_then(Value::as_str)
                    .map(str::trim)
                    .filter(|s| !s.is_empty())
                    .ok_or_else(|| {
                        ZeptoError::Tool(
                            "Missing 'path' parameter; add requires a file or directory path"
                                .to_string(),
                        )
                    })?;
                let out = Self::run(&["add", "--", path], workspace)?;
                Ok(ToolOutput::llm_only(if out.trim().is_empty() {
                    format!("Staged '{}'.", path)
                } else {
                    out
                }))
            }

            "checkout" => {
                let branch = args
                    .get("branch")
                    .and_then(Value::as_str)
                    .map(str::trim)
                    .filter(|s| !s.is_empty())
                    .ok_or_else(|| {
                        ZeptoError::Tool(
                            "Missing 'branch' parameter; checkout requires a branch name"
                                .to_string(),
                        )
                    })?;
                Self::run(&["checkout", branch], workspace).map(ToolOutput::llm_only)
            }

            other => Err(ZeptoError::Tool(format!(
                "Unknown git action '{}'. Supported: status, log, diff, blame, branch_list, commit, add, checkout",
                other
            ))),
        }
    }
}

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

    // Repo root used by tests that need a real git workspace.
    fn repo_root() -> String {
        // Walk up from the manifest dir until we find a .git directory.
        let mut dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        loop {
            if dir.join(".git").exists() {
                return dir.to_string_lossy().to_string();
            }
            if !dir.pop() {
                // Fallback: just return manifest dir and let the test handle it.
                return env!("CARGO_MANIFEST_DIR").to_string();
            }
        }
    }

    fn ctx_with_workspace(ws: &str) -> ToolContext {
        ToolContext::new().with_workspace(ws)
    }

    fn ctx_no_workspace() -> ToolContext {
        ToolContext::new()
    }

    // --- Availability ---

    #[test]
    fn test_git_is_available() {
        // git must be on PATH in any dev environment.
        assert!(GitTool::is_available(), "git binary not found on PATH");
    }

    // --- run() helper ---

    #[test]
    fn test_run_git_version() {
        let repo = repo_root();
        let out = GitTool::run(&["--version"], &repo).expect("git --version should succeed");
        assert!(out.contains("git version"), "unexpected output: {}", out);
    }

    #[test]
    fn test_run_git_invalid_dir() {
        let result = GitTool::run(&["status"], "/this/path/does/not/exist/at/all/ever");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("not a directory"),
            "expected 'not a directory' in error, got: {}",
            err
        );
    }

    // --- execute() — action dispatch ---

    #[tokio::test]
    async fn test_execute_missing_action() {
        let tool = GitTool::new();
        let ctx = ctx_no_workspace();
        let result = tool.execute(json!({}), &ctx).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("Missing 'action'"),
            "expected missing action error, got: {}",
            err
        );
    }

    #[tokio::test]
    async fn test_execute_unknown_action() {
        let tool = GitTool::new();
        let ctx = ctx_with_workspace(&repo_root());
        let result = tool.execute(json!({"action": "push"}), &ctx).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("Unknown git action 'push'"),
            "expected unknown action error, got: {}",
            err
        );
    }

    #[tokio::test]
    async fn test_execute_missing_workspace() {
        let tool = GitTool::new();
        let ctx = ctx_no_workspace();
        let result = tool.execute(json!({"action": "status"}), &ctx).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("Workspace not configured"),
            "expected workspace error, got: {}",
            err
        );
    }

    // --- status ---

    #[tokio::test]
    async fn test_execute_status() {
        let tool = GitTool::new();
        let ctx = ctx_with_workspace(&repo_root());
        let result = tool.execute(json!({"action": "status"}), &ctx).await;
        assert!(result.is_ok(), "status failed: {:?}", result);
        // Output is either the short status format or the clean-tree message.
        let out = result.unwrap();
        assert!(!out.for_llm.is_empty());
    }

    // --- log ---

    #[tokio::test]
    async fn test_execute_log() {
        let tool = GitTool::new();
        let ctx = ctx_with_workspace(&repo_root());
        let result = tool
            .execute(json!({"action": "log", "count": 5}), &ctx)
            .await;
        assert!(result.is_ok(), "log failed: {:?}", result);
        let out = result.unwrap();
        // Each log line contains a short hash and a date.
        assert!(!out.for_llm.is_empty());
    }

    // --- branch_list ---

    #[tokio::test]
    async fn test_execute_branch_list() {
        let tool = GitTool::new();
        let ctx = ctx_with_workspace(&repo_root());
        let result = tool.execute(json!({"action": "branch_list"}), &ctx).await;
        assert!(result.is_ok(), "branch_list failed: {:?}", result);
        let out = result.unwrap();
        // There must be at least one branch (we are on one right now).
        assert!(
            !out.for_llm.trim().is_empty(),
            "expected at least one branch, got empty output"
        );
    }

    // --- diff ---

    #[tokio::test]
    async fn test_execute_diff_no_path() {
        let tool = GitTool::new();
        let ctx = ctx_with_workspace(&repo_root());
        let result = tool.execute(json!({"action": "diff"}), &ctx).await;
        // Diff succeeds regardless of whether there are changes.
        assert!(result.is_ok(), "diff failed: {:?}", result);
    }

    // --- blame (requires path) ---

    #[tokio::test]
    async fn test_blame_requires_path() {
        let tool = GitTool::new();
        let ctx = ctx_with_workspace(&repo_root());
        let result = tool.execute(json!({"action": "blame"}), &ctx).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("path"),
            "expected 'path' in error message, got: {}",
            err
        );
    }

    // --- commit (requires message) ---

    #[tokio::test]
    async fn test_commit_requires_message() {
        let tool = GitTool::new();
        let ctx = ctx_with_workspace(&repo_root());
        let result = tool.execute(json!({"action": "commit"}), &ctx).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("message"),
            "expected 'message' in error message, got: {}",
            err
        );
    }

    // --- checkout (requires branch) ---

    #[tokio::test]
    async fn test_checkout_requires_branch() {
        let tool = GitTool::new();
        let ctx = ctx_with_workspace(&repo_root());
        let result = tool.execute(json!({"action": "checkout"}), &ctx).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("branch"),
            "expected 'branch' in error message, got: {}",
            err
        );
    }

    // --- add (requires path) ---

    #[tokio::test]
    async fn test_add_requires_path() {
        let tool = GitTool::new();
        let ctx = ctx_with_workspace(&repo_root());
        let result = tool.execute(json!({"action": "add"}), &ctx).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("path"),
            "expected 'path' in error message, got: {}",
            err
        );
    }

    // --- tool metadata ---

    #[test]
    fn test_tool_name_and_descriptions() {
        let tool = GitTool::new();
        assert_eq!(tool.name(), "git");
        assert!(
            tool.description().len() > tool.compact_description().len(),
            "full description should be longer than compact"
        );
        assert!(tool.compact_description().contains("Git"));
    }

    #[test]
    fn test_tool_parameters_schema() {
        let tool = GitTool::new();
        let params = tool.parameters();
        assert_eq!(params["type"], "object");
        assert!(params["properties"]["action"].is_object());
        assert!(params["properties"]["path"].is_object());
        assert!(params["properties"]["message"].is_object());
        assert!(params["properties"]["branch"].is_object());
        assert!(params["properties"]["count"].is_object());
        // action is the only required field
        let required = params["required"].as_array().unwrap();
        assert_eq!(required.len(), 1);
        assert_eq!(required[0], "action");
    }

    #[test]
    fn test_default_impl() {
        let _tool = GitTool::default();
    }

    // --- Shell allowlist enforcement ---

    #[tokio::test]
    async fn test_git_blocked_by_empty_allowlist() {
        use crate::security::{ShellAllowlistMode, ShellSecurityConfig};

        let config = ShellSecurityConfig::new().with_allowlist(vec![], ShellAllowlistMode::Strict);
        let tool = GitTool::with_security(config);
        let ctx = ctx_with_workspace(&repo_root());

        let result = tool.execute(json!({"action": "status"}), &ctx).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("blocked by shell allowlist"),
            "Expected allowlist rejection, got: {}",
            err
        );
    }

    #[tokio::test]
    async fn test_git_allowed_by_allowlist() {
        use crate::security::{ShellAllowlistMode, ShellSecurityConfig};

        let config =
            ShellSecurityConfig::new().with_allowlist(vec!["git"], ShellAllowlistMode::Strict);
        let tool = GitTool::with_security(config);
        let ctx = ctx_with_workspace(&repo_root());

        let result = tool.execute(json!({"action": "status"}), &ctx).await;
        assert!(result.is_ok(), "git should be allowed: {:?}", result.err());
    }

    #[tokio::test]
    async fn test_git_default_security_allows() {
        let tool = GitTool::new();
        let ctx = ctx_with_workspace(&repo_root());

        let result = tool.execute(json!({"action": "status"}), &ctx).await;
        assert!(
            result.is_ok(),
            "Default security should allow git: {:?}",
            result.err()
        );
    }
}