Skip to main content

nenjo_tools/
git_operations.rs

1//! Structured git operations (status, diff, log, branch, commit, etc.) with parsed JSON output.
2
3use crate::security::{AutonomyLevel, SecurityPolicy};
4use crate::{Tool, ToolCategory, ToolResult};
5use async_trait::async_trait;
6use serde_json::json;
7use std::sync::Arc;
8
9/// Git operations tool for structured repository management.
10/// Provides safe, parsed git operations with JSON output.
11pub struct GitOperationsTool {
12    security: Arc<SecurityPolicy>,
13}
14
15impl GitOperationsTool {
16    pub fn new(security: Arc<SecurityPolicy>) -> Self {
17        Self { security }
18    }
19
20    /// The working directory for git commands — delegates to `SecurityPolicy.workspace_dir`
21    /// so it's automatically scoped to the worktree when one is active.
22    fn workspace_dir(&self) -> &std::path::Path {
23        &self.security.workspace_dir
24    }
25
26    /// Sanitize git arguments to prevent injection attacks
27    fn sanitize_git_args(&self, args: &str) -> anyhow::Result<Vec<String>> {
28        let mut result = Vec::new();
29        for arg in args.split_whitespace() {
30            // Block dangerous git options that could lead to command injection
31            let arg_lower = arg.to_lowercase();
32            if arg_lower.starts_with("--exec=")
33                || arg_lower.starts_with("--upload-pack=")
34                || arg_lower.starts_with("--receive-pack=")
35                || arg_lower.contains("$(")
36                || arg_lower.contains('`')
37                || arg.contains('|')
38                || arg.contains(';')
39            {
40                anyhow::bail!("Blocked potentially dangerous git argument: {arg}");
41            }
42            result.push(arg.to_string());
43        }
44        Ok(result)
45    }
46
47    /// Check if an operation requires write access
48    fn requires_write_access(&self, operation: &str) -> bool {
49        matches!(
50            operation,
51            "commit" | "add" | "checkout" | "branch" | "stash" | "reset" | "revert"
52        )
53    }
54
55    /// Check if an operation is read-only
56    #[cfg(test)]
57    fn is_read_only(&self, operation: &str) -> bool {
58        matches!(
59            operation,
60            "status" | "diff" | "log" | "show" | "branch" | "rev-parse"
61        )
62    }
63
64    /// Environment variables safe to pass to git subprocesses.
65    /// Mirrors the shell tool's allowlist to prevent leaking API keys.
66    const SAFE_ENV_VARS: &[&str] = &[
67        "PATH",
68        "HOME",
69        "TERM",
70        "LANG",
71        "LC_ALL",
72        "LC_CTYPE",
73        "USER",
74        "SHELL",
75        "TMPDIR",
76        // Git identity — needed when global .gitconfig isn't available
77        "GIT_AUTHOR_NAME",
78        "GIT_AUTHOR_EMAIL",
79        "GIT_COMMITTER_NAME",
80        "GIT_COMMITTER_EMAIL",
81        // Git config paths — set by harness to use ~/.nenjo/gitconfig
82        "GIT_CONFIG_GLOBAL",
83        "GIT_CONFIG_NOSYSTEM",
84        // XDG config (some systems store .gitconfig here)
85        "XDG_CONFIG_HOME",
86    ];
87
88    async fn run_git_command(&self, args: &[&str]) -> anyhow::Result<String> {
89        let mut cmd = tokio::process::Command::new("git");
90        cmd.args(args).current_dir(self.workspace_dir());
91
92        // Clear env to prevent leaking secrets, then re-add safe vars + forwarded creds
93        cmd.env_clear();
94        for var in Self::SAFE_ENV_VARS {
95            if let Ok(val) = std::env::var(var) {
96                cmd.env(var, val);
97            }
98        }
99        // Default committer identity from author identity if not explicitly set.
100        // Users only need to set GIT_AUTHOR_NAME/EMAIL.
101        if std::env::var("GIT_COMMITTER_NAME").is_err()
102            && let Ok(name) = std::env::var("GIT_AUTHOR_NAME")
103        {
104            cmd.env("GIT_COMMITTER_NAME", name);
105        }
106        if std::env::var("GIT_COMMITTER_EMAIL").is_err()
107            && let Ok(email) = std::env::var("GIT_AUTHOR_EMAIL")
108        {
109            cmd.env("GIT_COMMITTER_EMAIL", email);
110        }
111        for (key, val) in &self.security.forwarded_env {
112            cmd.env(key, val);
113        }
114
115        let output = cmd.output().await?;
116
117        if !output.status.success() {
118            let stderr = String::from_utf8_lossy(&output.stderr);
119            anyhow::bail!("Git command failed: {stderr}");
120        }
121
122        Ok(String::from_utf8_lossy(&output.stdout).to_string())
123    }
124
125    async fn git_status(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {
126        let output = self
127            .run_git_command(&["status", "--porcelain=2", "--branch"])
128            .await?;
129
130        // Parse git status output into structured format
131        let mut result = serde_json::Map::new();
132        let mut branch = String::new();
133        let mut staged = Vec::new();
134        let mut unstaged = Vec::new();
135        let mut untracked = Vec::new();
136
137        for line in output.lines() {
138            if line.starts_with("# branch.head ") {
139                branch = line.trim_start_matches("# branch.head ").to_string();
140            } else if let Some(rest) = line.strip_prefix("1 ") {
141                // Ordinary changed entry
142                let mut parts = rest.splitn(3, ' ');
143                if let (Some(staging), Some(path)) = (parts.next(), parts.next())
144                    && !staging.is_empty()
145                {
146                    let status_char = staging.chars().next().unwrap_or(' ');
147                    if status_char != '.' && status_char != ' ' {
148                        staged.push(json!({"path": path, "status": status_char}));
149                    }
150                    let status_char = staging.chars().nth(1).unwrap_or(' ');
151                    if status_char != '.' && status_char != ' ' {
152                        unstaged.push(json!({"path": path, "status": status_char}));
153                    }
154                }
155            } else if let Some(rest) = line.strip_prefix("? ") {
156                untracked.push(rest.to_string());
157            }
158        }
159
160        result.insert("branch".to_string(), json!(branch));
161        result.insert("staged".to_string(), json!(staged));
162        result.insert("unstaged".to_string(), json!(unstaged));
163        result.insert("untracked".to_string(), json!(untracked));
164        result.insert(
165            "clean".to_string(),
166            json!(staged.is_empty() && unstaged.is_empty() && untracked.is_empty()),
167        );
168
169        Ok(ToolResult {
170            success: true,
171            output: serde_json::to_string_pretty(&result).unwrap_or_default(),
172            error: None,
173        })
174    }
175
176    async fn git_diff(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
177        let files = args.get("files").and_then(|v| v.as_str()).unwrap_or(".");
178        let cached = args
179            .get("cached")
180            .and_then(|v| v.as_bool())
181            .unwrap_or(false);
182
183        let mut git_args = vec!["diff", "--unified=3"];
184        if cached {
185            git_args.push("--cached");
186        }
187        git_args.push("--");
188        git_args.push(files);
189
190        let output = self.run_git_command(&git_args).await?;
191
192        // Parse diff into structured hunks
193        let mut result = serde_json::Map::new();
194        let mut hunks = Vec::new();
195        let mut current_file = String::new();
196        let mut current_hunk = serde_json::Map::new();
197        let mut lines = Vec::new();
198
199        for line in output.lines() {
200            if line.starts_with("diff --git ") {
201                if !lines.is_empty() {
202                    current_hunk.insert("lines".to_string(), json!(lines));
203                    if !current_hunk.is_empty() {
204                        hunks.push(serde_json::Value::Object(current_hunk.clone()));
205                    }
206                    lines = Vec::new();
207                    current_hunk = serde_json::Map::new();
208                }
209                let parts: Vec<&str> = line.split_whitespace().collect();
210                if parts.len() >= 4 {
211                    current_file = parts[3].trim_start_matches("b/").to_string();
212                    current_hunk.insert("file".to_string(), json!(current_file));
213                }
214            } else if line.starts_with("@@ ") {
215                if !lines.is_empty() {
216                    current_hunk.insert("lines".to_string(), json!(lines));
217                    if !current_hunk.is_empty() {
218                        hunks.push(serde_json::Value::Object(current_hunk.clone()));
219                    }
220                    lines = Vec::new();
221                    current_hunk = serde_json::Map::new();
222                    current_hunk.insert("file".to_string(), json!(current_file));
223                }
224                current_hunk.insert("header".to_string(), json!(line));
225            } else if !line.is_empty() {
226                lines.push(json!({
227                    "text": line,
228                    "type": if line.starts_with('+') { "add" }
229                           else if line.starts_with('-') { "delete" }
230                           else { "context" }
231                }));
232            }
233        }
234
235        if !lines.is_empty() {
236            current_hunk.insert("lines".to_string(), json!(lines));
237            if !current_hunk.is_empty() {
238                hunks.push(serde_json::Value::Object(current_hunk));
239            }
240        }
241
242        result.insert("hunks".to_string(), json!(hunks));
243        result.insert("file_count".to_string(), json!(hunks.len()));
244
245        Ok(ToolResult {
246            success: true,
247            output: serde_json::to_string_pretty(&result).unwrap_or_default(),
248            error: None,
249        })
250    }
251
252    async fn git_log(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
253        let limit_raw = args.get("limit").and_then(|v| v.as_u64()).unwrap_or(10);
254        let limit = usize::try_from(limit_raw).unwrap_or(usize::MAX).min(1000);
255        let limit_str = limit.to_string();
256
257        let output = self
258            .run_git_command(&[
259                "log",
260                &format!("-{limit_str}"),
261                "--pretty=format:%H|%an|%ae|%ad|%s",
262                "--date=iso",
263            ])
264            .await?;
265
266        let mut commits = Vec::new();
267
268        for line in output.lines() {
269            let parts: Vec<&str> = line.split('|').collect();
270            if parts.len() >= 5 {
271                commits.push(json!({
272                    "hash": parts[0],
273                    "author": parts[1],
274                    "email": parts[2],
275                    "date": parts[3],
276                    "message": parts[4]
277                }));
278            }
279        }
280
281        Ok(ToolResult {
282            success: true,
283            output: serde_json::to_string_pretty(&json!({ "commits": commits }))
284                .unwrap_or_default(),
285            error: None,
286        })
287    }
288
289    async fn git_branch(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {
290        let output = self
291            .run_git_command(&["branch", "--format=%(refname:short)|%(HEAD)"])
292            .await?;
293
294        let mut branches = Vec::new();
295        let mut current = String::new();
296
297        for line in output.lines() {
298            if let Some((name, head)) = line.split_once('|') {
299                let is_current = head == "*";
300                if is_current {
301                    current = name.to_string();
302                }
303                branches.push(json!({
304                    "name": name,
305                    "current": is_current
306                }));
307            }
308        }
309
310        Ok(ToolResult {
311            success: true,
312            output: serde_json::to_string_pretty(&json!({
313                "current": current,
314                "branches": branches
315            }))
316            .unwrap_or_default(),
317            error: None,
318        })
319    }
320
321    async fn git_commit(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
322        let message = args
323            .get("message")
324            .and_then(|v| v.as_str())
325            .ok_or_else(|| anyhow::anyhow!("Missing 'message' parameter"))?;
326
327        // Sanitize commit message
328        let sanitized = message
329            .lines()
330            .map(|l| l.trim())
331            .filter(|l| !l.is_empty())
332            .collect::<Vec<_>>()
333            .join("\n");
334
335        if sanitized.is_empty() {
336            anyhow::bail!("Commit message cannot be empty");
337        }
338
339        // Limit message length
340        let message = if sanitized.len() > 2000 {
341            format!("{}...", &sanitized[..1997])
342        } else {
343            sanitized
344        };
345
346        let output = self.run_git_command(&["commit", "-m", &message]).await;
347
348        match output {
349            Ok(_) => Ok(ToolResult {
350                success: true,
351                output: format!("Committed: {message}"),
352                error: None,
353            }),
354            Err(e) => Ok(ToolResult {
355                success: false,
356                output: String::new(),
357                error: Some(format!("Commit failed: {e}")),
358            }),
359        }
360    }
361
362    async fn git_add(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
363        let paths = args
364            .get("paths")
365            .and_then(|v| v.as_str())
366            .ok_or_else(|| anyhow::anyhow!("Missing 'paths' parameter"))?;
367
368        let output = self.run_git_command(&["add", "--", paths]).await;
369
370        match output {
371            Ok(_) => Ok(ToolResult {
372                success: true,
373                output: format!("Staged: {paths}"),
374                error: None,
375            }),
376            Err(e) => Ok(ToolResult {
377                success: false,
378                output: String::new(),
379                error: Some(format!("Add failed: {e}")),
380            }),
381        }
382    }
383
384    async fn git_checkout(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
385        let branch = args
386            .get("branch")
387            .and_then(|v| v.as_str())
388            .ok_or_else(|| anyhow::anyhow!("Missing 'branch' parameter"))?;
389
390        // Sanitize branch name
391        let sanitized = self.sanitize_git_args(branch)?;
392
393        if sanitized.is_empty() || sanitized.len() > 1 {
394            anyhow::bail!("Invalid branch specification");
395        }
396
397        let branch_name = &sanitized[0];
398
399        // Block dangerous branch names
400        if branch_name.contains('@') || branch_name.contains('^') || branch_name.contains('~') {
401            anyhow::bail!("Branch name contains invalid characters");
402        }
403
404        let output = self.run_git_command(&["checkout", branch_name]).await;
405
406        match output {
407            Ok(_) => Ok(ToolResult {
408                success: true,
409                output: format!("Switched to branch: {branch_name}"),
410                error: None,
411            }),
412            Err(e) => Ok(ToolResult {
413                success: false,
414                output: String::new(),
415                error: Some(format!("Checkout failed: {e}")),
416            }),
417        }
418    }
419
420    async fn git_stash(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
421        let action = args
422            .get("action")
423            .and_then(|v| v.as_str())
424            .unwrap_or("push");
425
426        let output = match action {
427            "push" | "save" => {
428                self.run_git_command(&["stash", "push", "-m", "auto-stash"])
429                    .await
430            }
431            "pop" => self.run_git_command(&["stash", "pop"]).await,
432            "list" => self.run_git_command(&["stash", "list"]).await,
433            "drop" => {
434                let index_raw = args.get("index").and_then(|v| v.as_u64()).unwrap_or(0);
435                let index = i32::try_from(index_raw)
436                    .map_err(|_| anyhow::anyhow!("stash index too large: {index_raw}"))?;
437                self.run_git_command(&["stash", "drop", &format!("stash@{{{index}}}")])
438                    .await
439            }
440            _ => anyhow::bail!("Unknown stash action: {action}. Use: push, pop, list, drop"),
441        };
442
443        match output {
444            Ok(out) => Ok(ToolResult {
445                success: true,
446                output: out,
447                error: None,
448            }),
449            Err(e) => Ok(ToolResult {
450                success: false,
451                output: String::new(),
452                error: Some(format!("Stash {action} failed: {e}")),
453            }),
454        }
455    }
456}
457
458#[async_trait]
459impl Tool for GitOperationsTool {
460    fn category(&self) -> ToolCategory {
461        ToolCategory::ReadWrite
462    }
463
464    fn name(&self) -> &str {
465        "git_operations"
466    }
467
468    fn description(&self) -> &str {
469        "Perform structured Git operations (status, diff, log, branch, commit, add, checkout, stash). Provides parsed JSON output and integrates with security policy for autonomy controls."
470    }
471
472    fn parameters_schema(&self) -> serde_json::Value {
473        json!({
474            "type": "object",
475            "properties": {
476                "operation": {
477                    "type": "string",
478                    "enum": ["status", "diff", "log", "branch", "commit", "add", "checkout", "stash"],
479                    "description": "Git operation to perform"
480                },
481                "message": {
482                    "type": "string",
483                    "description": "Commit message (for 'commit' operation)"
484                },
485                "paths": {
486                    "type": "string",
487                    "description": "File paths to stage (for 'add' operation)"
488                },
489                "branch": {
490                    "type": "string",
491                    "description": "Branch name (for 'checkout' operation)"
492                },
493                "files": {
494                    "type": "string",
495                    "description": "File or path to diff (for 'diff' operation, default: '.')"
496                },
497                "cached": {
498                    "type": "boolean",
499                    "description": "Show staged changes (for 'diff' operation)"
500                },
501                "limit": {
502                    "type": "integer",
503                    "description": "Number of log entries (for 'log' operation, default: 10)"
504                },
505                "action": {
506                    "type": "string",
507                    "enum": ["push", "pop", "list", "drop"],
508                    "description": "Stash action (for 'stash' operation)"
509                },
510                "index": {
511                    "type": "integer",
512                    "description": "Stash index (for 'stash' with 'drop' action)"
513                }
514            },
515            "required": ["operation"]
516        })
517    }
518
519    async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
520        let operation = match args.get("operation").and_then(|v| v.as_str()) {
521            Some(op) => op,
522            None => {
523                return Ok(ToolResult {
524                    success: false,
525                    output: String::new(),
526                    error: Some("Missing 'operation' parameter".into()),
527                });
528            }
529        };
530
531        // Check if we're in a git repository
532        if !self.workspace_dir().join(".git").exists() {
533            // Try to find .git in parent directories
534            let mut current_dir = self.workspace_dir();
535            let mut found_git = false;
536            while current_dir.parent().is_some() {
537                if current_dir.join(".git").exists() {
538                    found_git = true;
539                    break;
540                }
541                current_dir = current_dir.parent().unwrap();
542            }
543
544            if !found_git {
545                return Ok(ToolResult {
546                    success: false,
547                    output: String::new(),
548                    error: Some("Not in a git repository".into()),
549                });
550            }
551        }
552
553        // Check autonomy level for write operations
554        if self.requires_write_access(operation) {
555            if !self.security.can_act() {
556                return Ok(ToolResult {
557                    success: false,
558                    output: String::new(),
559                    error: Some(
560                        "Action blocked: git write operations require higher autonomy level".into(),
561                    ),
562                });
563            }
564
565            match self.security.autonomy {
566                AutonomyLevel::ReadOnly => {
567                    return Ok(ToolResult {
568                        success: false,
569                        output: String::new(),
570                        error: Some("Action blocked: read-only mode".into()),
571                    });
572                }
573                AutonomyLevel::Supervised | AutonomyLevel::Full => {}
574            }
575        }
576
577        // Record action for rate limiting
578        if !self.security.record_action() {
579            return Ok(ToolResult {
580                success: false,
581                output: String::new(),
582                error: Some("Action blocked: rate limit exceeded".into()),
583            });
584        }
585
586        // Execute the requested operation
587        match operation {
588            "status" => self.git_status(args).await,
589            "diff" => self.git_diff(args).await,
590            "log" => self.git_log(args).await,
591            "branch" => self.git_branch(args).await,
592            "commit" => self.git_commit(args).await,
593            "add" => self.git_add(args).await,
594            "checkout" => self.git_checkout(args).await,
595            "stash" => self.git_stash(args).await,
596            _ => Ok(ToolResult {
597                success: false,
598                output: String::new(),
599                error: Some(format!("Unknown operation: {operation}")),
600            }),
601        }
602    }
603}
604
605#[cfg(test)]
606mod tests {
607    use super::*;
608    use crate::security::SecurityPolicy;
609    use tempfile::TempDir;
610
611    fn test_tool(dir: &std::path::Path) -> GitOperationsTool {
612        let security = Arc::new(SecurityPolicy {
613            autonomy: AutonomyLevel::Supervised,
614            workspace_dir: dir.to_path_buf(),
615            ..SecurityPolicy::default()
616        });
617        GitOperationsTool::new(security)
618    }
619
620    #[test]
621    fn sanitize_git_blocks_injection() {
622        let tmp = TempDir::new().unwrap();
623        let tool = test_tool(tmp.path());
624
625        // Should block dangerous arguments
626        assert!(tool.sanitize_git_args("--exec=rm -rf /").is_err());
627        assert!(tool.sanitize_git_args("$(echo pwned)").is_err());
628        assert!(tool.sanitize_git_args("`malicious`").is_err());
629        assert!(tool.sanitize_git_args("arg | cat").is_err());
630        assert!(tool.sanitize_git_args("arg; rm file").is_err());
631    }
632
633    #[test]
634    fn sanitize_git_allows_safe() {
635        let tmp = TempDir::new().unwrap();
636        let tool = test_tool(tmp.path());
637
638        // Should allow safe arguments
639        assert!(tool.sanitize_git_args("main").is_ok());
640        assert!(tool.sanitize_git_args("feature/test-branch").is_ok());
641        assert!(tool.sanitize_git_args("--cached").is_ok());
642    }
643
644    #[test]
645    fn requires_write_detection() {
646        let tmp = TempDir::new().unwrap();
647        let tool = test_tool(tmp.path());
648
649        assert!(tool.requires_write_access("commit"));
650        assert!(tool.requires_write_access("add"));
651        assert!(tool.requires_write_access("checkout"));
652
653        assert!(!tool.requires_write_access("status"));
654        assert!(!tool.requires_write_access("diff"));
655        assert!(!tool.requires_write_access("log"));
656    }
657
658    #[test]
659    fn is_read_only_detection() {
660        let tmp = TempDir::new().unwrap();
661        let tool = test_tool(tmp.path());
662
663        assert!(tool.is_read_only("status"));
664        assert!(tool.is_read_only("diff"));
665        assert!(tool.is_read_only("log"));
666
667        assert!(!tool.is_read_only("commit"));
668        assert!(!tool.is_read_only("add"));
669    }
670
671    #[tokio::test]
672    async fn blocks_readonly_mode_for_write_ops() {
673        let tmp = TempDir::new().unwrap();
674        // Initialize a git repository
675        std::process::Command::new("git")
676            .args(["init"])
677            .current_dir(tmp.path())
678            .output()
679            .unwrap();
680
681        let security = Arc::new(SecurityPolicy {
682            autonomy: AutonomyLevel::ReadOnly,
683            workspace_dir: tmp.path().to_path_buf(),
684            ..SecurityPolicy::default()
685        });
686        let tool = GitOperationsTool::new(security);
687
688        let result = tool
689            .execute(json!({"operation": "commit", "message": "test"}))
690            .await
691            .unwrap();
692        assert!(!result.success);
693        // can_act() returns false for ReadOnly, so we get the "higher autonomy level" message
694        assert!(
695            result
696                .error
697                .as_deref()
698                .unwrap_or("")
699                .contains("higher autonomy")
700        );
701    }
702
703    #[tokio::test]
704    async fn allows_readonly_ops_in_readonly_mode() {
705        let tmp = TempDir::new().unwrap();
706        let security = Arc::new(SecurityPolicy {
707            autonomy: AutonomyLevel::ReadOnly,
708            workspace_dir: tmp.path().to_path_buf(),
709            ..SecurityPolicy::default()
710        });
711        let tool = GitOperationsTool::new(security);
712
713        // This will fail because there's no git repo, but it shouldn't be blocked by autonomy
714        let result = tool.execute(json!({"operation": "status"})).await.unwrap();
715        // The error should be about not being in a git repo, not about read-only mode
716        let error_msg = result.error.as_deref().unwrap_or("");
717        assert!(error_msg.contains("git repository") || error_msg.contains("Git command failed"));
718    }
719
720    #[tokio::test]
721    async fn rejects_missing_operation() {
722        let tmp = TempDir::new().unwrap();
723        let tool = test_tool(tmp.path());
724
725        let result = tool.execute(json!({})).await.unwrap();
726        assert!(!result.success);
727        assert!(
728            result
729                .error
730                .as_deref()
731                .unwrap_or("")
732                .contains("Missing 'operation'")
733        );
734    }
735
736    #[tokio::test]
737    async fn rejects_unknown_operation() {
738        let tmp = TempDir::new().unwrap();
739        // Initialize a git repository
740        std::process::Command::new("git")
741            .args(["init"])
742            .current_dir(tmp.path())
743            .output()
744            .unwrap();
745
746        let tool = test_tool(tmp.path());
747
748        let result = tool.execute(json!({"operation": "push"})).await.unwrap();
749        assert!(!result.success);
750        assert!(
751            result
752                .error
753                .as_deref()
754                .unwrap_or("")
755                .contains("Unknown operation")
756        );
757    }
758}