pawan-core 0.5.22

Pawan (पवन) — Core library: agent, tools, config, healing
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
use super::super::Tool;
use super::run_git;
use async_trait::async_trait;
use serde_json::{json, Value};
use std::path::PathBuf;

/// Tool for listing and managing branches
pub struct GitBranchTool {
    workspace_root: PathBuf,
}

impl GitBranchTool {
    pub fn new(workspace_root: PathBuf) -> Self {
        Self { workspace_root }
    }
}

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

    fn description(&self) -> &str {
        "List branches or get current branch name. Shows local and optionally remote branches."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "all": {
                    "type": "boolean",
                    "description": "Show both local and remote branches (default: false)"
                }
            },
            "required": []
        })
    }

    fn thulp_definition(&self) -> thulp_core::ToolDefinition {
        use thulp_core::{Parameter, ParameterType};
        thulp_core::ToolDefinition::builder("git_branch")
            .description(self.description())
            .parameter(
                Parameter::builder("all")
                    .param_type(ParameterType::Boolean)
                    .required(false)
                    .description("Show both local and remote branches (default: false)")
                    .build(),
            )
            .build()
    }

    async fn execute(&self, args: Value) -> crate::Result<Value> {
        let all = args["all"].as_bool().unwrap_or(false);

        // Get current branch
        let (_, current, _) = run_git(&self.workspace_root, &["branch", "--show-current"]).await?;
        let current_branch = current.trim().to_string();

        // List branches
        let mut git_args = vec!["branch", "--format=%(refname:short)"];
        if all {
            git_args.push("-a");
        }

        let (success, stdout, stderr) = run_git(&self.workspace_root, &git_args).await?;

        if !success {
            return Err(crate::PawanError::Git(format!(
                "git branch failed: {}",
                stderr
            )));
        }

        let branches: Vec<&str> = stdout
            .lines()
            .map(|l| l.trim())
            .filter(|l| !l.is_empty())
            .collect();

        Ok(json!({
            "current": current_branch,
            "branches": branches,
            "count": branches.len(),
            "success": true
        }))
    }
}

/// Tool for git checkout (switch branches or restore files)
pub struct GitCheckoutTool {
    workspace_root: PathBuf,
}

impl GitCheckoutTool {
    pub fn new(workspace_root: PathBuf) -> Self {
        Self { workspace_root }
    }
}

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

    fn description(&self) -> &str {
        "Switch branches or restore working tree files. Can create new branches with create=true."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "target": {
                    "type": "string",
                    "description": "Branch name, commit, or file path to checkout"
                },
                "create": {
                    "type": "boolean",
                    "description": "Create a new branch (git checkout -b)"
                },
                "files": {
                    "type": "array",
                    "items": { "type": "string" },
                    "description": "Specific files to restore (git checkout -- <files>)"
                }
            },
            "required": ["target"]
        })
    }

    fn thulp_definition(&self) -> thulp_core::ToolDefinition {
        use thulp_core::{Parameter, ParameterType};
        thulp_core::ToolDefinition::builder("git_checkout")
            .description(self.description())
            .parameter(
                Parameter::builder("target")
                    .param_type(ParameterType::String)
                    .required(true)
                    .description("Branch name, commit, or file path to checkout")
                    .build(),
            )
            .parameter(
                Parameter::builder("create")
                    .param_type(ParameterType::Boolean)
                    .required(false)
                    .description("Create a new branch (git checkout -b)")
                    .build(),
            )
            .parameter(
                Parameter::builder("files")
                    .param_type(ParameterType::Array)
                    .required(false)
                    .description("Specific files to restore (git checkout -- <files>)")
                    .build(),
            )
            .build()
    }

    async fn execute(&self, args: Value) -> crate::Result<Value> {
        let target = args["target"]
            .as_str()
            .ok_or_else(|| crate::PawanError::Tool("target is required".into()))?;
        let create = args["create"].as_bool().unwrap_or(false);
        let files: Vec<&str> = args["files"]
            .as_array()
            .map(|a| a.iter().filter_map(|v| v.as_str()).collect())
            .unwrap_or_default();

        let mut git_args: Vec<&str> = vec!["checkout"];

        if create {
            git_args.push("-b");
        }

        git_args.push(target);

        if !files.is_empty() {
            git_args.push("--");
            git_args.extend(files.iter());
        }

        let (success, stdout, stderr) = run_git(&self.workspace_root, &git_args).await?;

        if !success {
            return Err(crate::PawanError::Git(format!(
                "git checkout failed: {}",
                stderr
            )));
        }

        Ok(json!({
            "success": true,
            "target": target,
            "created": create,
            "output": format!("{}{}", stdout, stderr).trim().to_string()
        }))
    }
}

/// Tool for git stash operations
pub struct GitStashTool {
    workspace_root: PathBuf,
}

impl GitStashTool {
    pub fn new(workspace_root: PathBuf) -> Self {
        Self { workspace_root }
    }
}

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

    fn description(&self) -> &str {
        "Stash or restore uncommitted changes. Actions: push (default), pop, list, drop."
    }

    fn parameters_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "action": {
                    "type": "string",
                    "enum": ["push", "pop", "list", "drop", "show"],
                    "description": "Stash action (default: push)"
                },
                "message": {
                    "type": "string",
                    "description": "Message for stash push"
                },
                "index": {
                    "type": "integer",
                    "description": "Stash index for pop/drop/show (default: 0)"
                }
            },
            "required": []
        })
    }

    fn thulp_definition(&self) -> thulp_core::ToolDefinition {
        use thulp_core::{Parameter, ParameterType};
        thulp_core::ToolDefinition::builder("git_stash")
            .description(self.description())
            .parameter(
                Parameter::builder("action")
                    .param_type(ParameterType::String)
                    .required(false)
                    .description("Stash action (default: push)")
                    .build(),
            )
            .parameter(
                Parameter::builder("message")
                    .param_type(ParameterType::String)
                    .required(false)
                    .description("Message for stash push")
                    .build(),
            )
            .parameter(
                Parameter::builder("index")
                    .param_type(ParameterType::Integer)
                    .required(false)
                    .description("Stash index for pop/drop/show (default: 0)")
                    .build(),
            )
            .build()
    }

    async fn execute(&self, args: Value) -> crate::Result<Value> {
        let action = args["action"].as_str().unwrap_or("push");
        let message = args["message"].as_str();
        let index = args["index"].as_u64().unwrap_or(0);

        let git_args: Vec<String> = match action {
            "push" => {
                let mut a = vec!["stash".to_string(), "push".to_string()];
                if let Some(msg) = message {
                    a.push("-m".to_string());
                    a.push(msg.to_string());
                }
                a
            }
            "pop" => vec![
                "stash".to_string(),
                "pop".to_string(),
                format!("stash@{{{}}}", index),
            ],
            "list" => vec!["stash".to_string(), "list".to_string()],
            "drop" => vec![
                "stash".to_string(),
                "drop".to_string(),
                format!("stash@{{{}}}", index),
            ],
            "show" => vec![
                "stash".to_string(),
                "show".to_string(),
                "-p".to_string(),
                format!("stash@{{{}}}", index),
            ],
            _ => {
                return Err(crate::PawanError::Tool(format!(
                    "Unknown stash action: {}",
                    action
                )))
            }
        };

        let git_args_ref: Vec<&str> = git_args.iter().map(|s| s.as_str()).collect();
        let (success, stdout, stderr) = run_git(&self.workspace_root, &git_args_ref).await?;

        if !success {
            return Err(crate::PawanError::Git(format!(
                "git stash {} failed: {}",
                action, stderr
            )));
        }

        Ok(json!({
            "success": true,
            "action": action,
            "output": stdout.trim().to_string()
        }))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tools::git::staging::{GitAddTool, GitCommitTool};
    use serde_json::json;
    use tempfile::TempDir;
    use tokio::process::Command;

    async fn setup_git_repo() -> TempDir {
        let temp_dir = TempDir::new().unwrap();

        Command::new("git")
            .args(["init"])
            .current_dir(temp_dir.path())
            .output()
            .await
            .unwrap();

        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(temp_dir.path())
            .output()
            .await
            .unwrap();

        Command::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(temp_dir.path())
            .output()
            .await
            .unwrap();

        temp_dir
    }

    #[tokio::test]
    async fn test_git_branch_list() {
        let temp_dir = setup_git_repo().await;
        std::fs::write(temp_dir.path().join("f.txt"), "init").unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(temp_dir.path())
            .output()
            .await
            .unwrap();
        Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(temp_dir.path())
            .output()
            .await
            .unwrap();

        let tool = GitBranchTool::new(temp_dir.path().into());
        let result = tool.execute(json!({})).await.unwrap();
        assert!(result["success"].as_bool().unwrap());
        let branches = result["branches"].as_array().unwrap();
        assert!(!branches.is_empty(), "Should have at least one branch");
        assert!(result["current"].as_str().is_some());
    }

    #[tokio::test]
    async fn test_git_checkout_create_branch() {
        let temp_dir = setup_git_repo().await;
        std::fs::write(temp_dir.path().join("f.txt"), "init").unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(temp_dir.path())
            .output()
            .await
            .unwrap();
        Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(temp_dir.path())
            .output()
            .await
            .unwrap();

        let tool = GitCheckoutTool::new(temp_dir.path().into());
        let result = tool
            .execute(json!({"target": "feature-test", "create": true}))
            .await
            .unwrap();
        assert!(result["success"].as_bool().unwrap());

        // Verify we're on the new branch
        let branch_tool = GitBranchTool::new(temp_dir.path().into());
        let branches = branch_tool.execute(json!({})).await.unwrap();
        assert_eq!(branches["current"].as_str().unwrap(), "feature-test");
    }

    #[tokio::test]
    async fn test_git_stash_on_clean_repo() {
        let temp_dir = setup_git_repo().await;
        let tool = GitStashTool::new(temp_dir.path().into());
        // List stashes on empty repo
        let result = tool.execute(json!({"action": "list"})).await.unwrap();
        assert!(result["success"].as_bool().unwrap());
    }

    #[tokio::test]
    async fn test_git_stash_on_dirty_repo_saves_changes() {
        let temp_dir = setup_git_repo().await;
        // First commit a base file
        std::fs::write(temp_dir.path().join("base.txt"), "v1").unwrap();
        GitAddTool::new(temp_dir.path().to_path_buf())
            .execute(json!({ "files": ["base.txt"] }))
            .await
            .unwrap();
        GitCommitTool::new(temp_dir.path().to_path_buf())
            .execute(json!({ "message": "base" }))
            .await
            .unwrap();

        // Now modify it so there's something to stash
        std::fs::write(temp_dir.path().join("base.txt"), "v2-dirty").unwrap();

        let stash_tool = GitStashTool::new(temp_dir.path().to_path_buf());
        let result = stash_tool
            .execute(json!({ "action": "push", "message": "test stash" }))
            .await
            .unwrap();
        assert!(result["success"].as_bool().unwrap());

        // Working tree should be clean again (stash popped the change)
        let content = std::fs::read_to_string(temp_dir.path().join("base.txt")).unwrap();
        assert_eq!(content, "v1", "stash push should revert working tree");
    }

    #[tokio::test]
    async fn test_git_checkout_nonexistent_branch_without_create_errors() {
        // Checkout to a non-existent branch WITHOUT create=true must fail,
        // not silently create it. This pins the "safety" contract of the tool.
        let temp_dir = setup_git_repo().await;
        std::fs::write(temp_dir.path().join("init.txt"), "init").unwrap();
        Command::new("git")
            .args(["add", "."])
            .current_dir(temp_dir.path())
            .output()
            .await
            .unwrap();
        Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(temp_dir.path())
            .output()
            .await
            .unwrap();

        let tool = GitCheckoutTool::new(temp_dir.path().to_path_buf());
        let result = tool
            .execute(json!({
                "target": "nonexistent-branch-xyz-abc-9999",
                "create": false
            }))
            .await;
        assert!(
            result.is_err(),
            "checkout to nonexistent branch without create must error"
        );
    }
}