sgr-agent-tools 0.4.2

14 reusable file-system tools for sgr-agent based AI agents
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
//! ApplyPatchTool — Codex-compatible diff-based file editing via FileBackend.
//!
//! Patch DSL parser adapted from Codex (Apache-2.0 license, Copyright OpenAI).
//! See: https://github.com/openai/codex
//!
//! Requires the `patch` feature flag.

use std::sync::Arc;

use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::Value;
use sgr_agent_core::agent_tool::{Tool, ToolError, ToolOutput, parse_args};
use sgr_agent_core::context::AgentContext;
use sgr_agent_core::schema::json_schema_for;

use crate::backend::FileBackend;
use crate::helpers::backend_err;

pub struct ApplyPatchTool<B: FileBackend>(pub Arc<B>);

#[derive(Deserialize, JsonSchema)]
struct ApplyPatchArgs {
    /// The patch in Codex apply_patch DSL format
    patch: String,
}

// ---------------------------------------------------------------------------
// Patch data types
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq)]
pub enum Hunk {
    AddFile {
        path: String,
        contents: String,
    },
    DeleteFile {
        path: String,
    },
    UpdateFile {
        path: String,
        move_path: Option<String>,
        chunks: Vec<Chunk>,
    },
}

#[derive(Debug, Clone, PartialEq)]
pub struct Chunk {
    /// The @@ context line (without the @@ prefix).
    pub context: Option<String>,
    pub old_lines: Vec<String>,
    pub new_lines: Vec<String>,
}

// ---------------------------------------------------------------------------
// Parser
// ---------------------------------------------------------------------------

/// Parse a Codex apply_patch DSL string into a list of hunks.
pub fn parse_patch(text: &str) -> Result<Vec<Hunk>, String> {
    let lines: Vec<&str> = text.lines().collect();
    let mut hunks = Vec::new();
    let mut i = 0;

    // Skip to "*** Begin Patch"
    while i < lines.len() {
        if lines[i].trim() == "*** Begin Patch" {
            i += 1;
            break;
        }
        i += 1;
    }

    while i < lines.len() {
        let line = lines[i].trim();

        if line == "*** End Patch" {
            break;
        }

        if let Some(path) = line.strip_prefix("*** Add File: ") {
            let path = path.trim().to_string();
            i += 1;
            let mut contents = String::new();
            while i < lines.len() {
                let l = lines[i];
                if l.starts_with("*** ") {
                    break;
                }
                if let Some(rest) = l.strip_prefix('+') {
                    if !contents.is_empty() {
                        contents.push('\n');
                    }
                    contents.push_str(rest);
                }
                i += 1;
            }
            hunks.push(Hunk::AddFile { path, contents });
        } else if let Some(path) = line.strip_prefix("*** Delete File: ") {
            hunks.push(Hunk::DeleteFile {
                path: path.trim().to_string(),
            });
            i += 1;
        } else if let Some(path) = line.strip_prefix("*** Update File: ") {
            let path = path.trim().to_string();
            i += 1;
            let mut move_path: Option<String> = None;
            let mut chunks: Vec<Chunk> = Vec::new();

            // Check for *** Move to:
            if i < lines.len() {
                let next = lines[i].trim();
                if let Some(mp) = next.strip_prefix("*** Move to: ") {
                    move_path = Some(mp.trim().to_string());
                    i += 1;
                }
            }

            // Parse chunks (each starts with @@ or with -/+ lines)
            while i < lines.len() {
                let l = lines[i];
                if l.starts_with("*** ") {
                    break;
                }

                if l.starts_with("@@") {
                    let ctx = l.strip_prefix("@@").map(|s| s.trim().to_string());
                    let context = if ctx.as_deref() == Some("") {
                        None
                    } else {
                        ctx
                    };
                    i += 1;

                    let mut old_lines = Vec::new();
                    let mut new_lines = Vec::new();

                    while i < lines.len() {
                        let cl = lines[i];
                        if cl.starts_with("*** ") || cl.starts_with("@@") {
                            break;
                        }
                        if let Some(rest) = cl.strip_prefix('-') {
                            old_lines.push(rest.to_string());
                        } else if let Some(rest) = cl.strip_prefix('+') {
                            new_lines.push(rest.to_string());
                        } else if let Some(rest) = cl.strip_prefix(' ') {
                            // Context line — appears in both old and new
                            old_lines.push(rest.to_string());
                            new_lines.push(rest.to_string());
                        } else if cl.is_empty() {
                            // Empty line treated as context
                            old_lines.push(String::new());
                            new_lines.push(String::new());
                        } else {
                            // Unrecognized line — treat as context
                            old_lines.push(cl.to_string());
                            new_lines.push(cl.to_string());
                        }
                        i += 1;
                    }

                    chunks.push(Chunk {
                        context,
                        old_lines,
                        new_lines,
                    });
                } else {
                    // Skip unrecognized lines between chunks
                    i += 1;
                }
            }

            hunks.push(Hunk::UpdateFile {
                path,
                move_path,
                chunks,
            });
        } else {
            i += 1;
        }
    }

    if hunks.is_empty() {
        return Err("No hunks found in patch".to_string());
    }

    Ok(hunks)
}

// ---------------------------------------------------------------------------
// Seek sequence — fuzzy line matching with 4 levels
// ---------------------------------------------------------------------------

/// Normalize a string: trim whitespace, normalize unicode (NFKC-like ASCII fold).
fn normalize_line(s: &str) -> String {
    s.chars()
        .map(|c| {
            // Fold common unicode variants to ASCII equivalents
            match c {
                '\u{00A0}' => ' ',               // non-breaking space
                '\u{2018}' | '\u{2019}' => '\'', // smart quotes
                '\u{201C}' | '\u{201D}' => '"',
                '\u{2013}' | '\u{2014}' => '-', // en/em dash
                '\u{2026}' => '.',              // ellipsis (simplify)
                _ => c,
            }
        })
        .collect::<String>()
        .trim()
        .to_string()
}

/// Find the position of `needle` lines within `haystack` lines,
/// starting search from `start_pos`. Uses 4-level fuzzy matching.
///
/// Returns the index in haystack where the match begins, or None.
fn seek_sequence(haystack: &[String], needle: &[String], start_pos: usize) -> Option<usize> {
    if needle.is_empty() {
        return Some(start_pos);
    }
    if haystack.is_empty() || start_pos + needle.len() > haystack.len() {
        return None;
    }

    // Level 0: exact match
    for i in start_pos..=haystack.len() - needle.len() {
        if haystack[i..i + needle.len()]
            .iter()
            .zip(needle.iter())
            .all(|(h, n)| h == n)
        {
            return Some(i);
        }
    }

    // Level 1: trim_end match
    for i in start_pos..=haystack.len() - needle.len() {
        if haystack[i..i + needle.len()]
            .iter()
            .zip(needle.iter())
            .all(|(h, n)| h.trim_end() == n.trim_end())
        {
            return Some(i);
        }
    }

    // Level 2: trim (both ends) match
    for i in start_pos..=haystack.len() - needle.len() {
        if haystack[i..i + needle.len()]
            .iter()
            .zip(needle.iter())
            .all(|(h, n)| h.trim() == n.trim())
        {
            return Some(i);
        }
    }

    // Level 3: unicode-normalized + trimmed match
    for i in start_pos..=haystack.len() - needle.len() {
        if haystack[i..i + needle.len()]
            .iter()
            .zip(needle.iter())
            .all(|(h, n)| normalize_line(h) == normalize_line(n))
        {
            return Some(i);
        }
    }

    None
}

/// Apply chunks to file content. Returns the new file content.
fn apply_chunks(content: &str, chunks: &[Chunk]) -> Result<String, String> {
    let lines: Vec<String> = content.lines().map(|l| l.to_string()).collect();
    let mut result_lines: Vec<String> = Vec::new();
    let mut pos: usize = 0;

    for chunk in chunks {
        // Find context line first, if present
        let search_start = if let Some(ref ctx) = chunk.context {
            let ctx_needle = vec![ctx.clone()];
            match seek_sequence(&lines, &ctx_needle, pos) {
                Some(found) => found,
                None => {
                    return Err(format!("Could not find context line: '{}'", ctx));
                }
            }
        } else {
            pos
        };

        // Find the old_lines sequence starting from context position
        if chunk.old_lines.is_empty() {
            // Pure insertion at context point
            // Copy everything up to search_start (inclusive of context line)
            let insert_at = if chunk.context.is_some() {
                search_start + 1
            } else {
                search_start
            };
            // Copy lines from pos to insert_at
            for line in &lines[pos..insert_at] {
                result_lines.push(line.clone());
            }
            // Insert new lines
            for line in &chunk.new_lines {
                result_lines.push(line.clone());
            }
            pos = insert_at;
        } else {
            // Find old_lines in the file
            let match_start =
                seek_sequence(&lines, &chunk.old_lines, search_start).ok_or_else(|| {
                    let preview: String = chunk
                        .old_lines
                        .iter()
                        .take(3)
                        .cloned()
                        .collect::<Vec<_>>()
                        .join("\n");
                    format!("Could not find old lines starting with: '{}'", preview)
                })?;

            // Copy everything from current pos to match start
            for line in &lines[pos..match_start] {
                result_lines.push(line.clone());
            }

            // Replace old lines with new lines
            for line in &chunk.new_lines {
                result_lines.push(line.clone());
            }

            pos = match_start + chunk.old_lines.len();
        }
    }

    // Copy remaining lines
    for line in &lines[pos..] {
        result_lines.push(line.clone());
    }

    Ok(result_lines.join("\n"))
}

// ---------------------------------------------------------------------------
// Tool implementation
// ---------------------------------------------------------------------------

#[async_trait::async_trait]
impl<B: FileBackend> Tool for ApplyPatchTool<B> {
    fn name(&self) -> &str {
        "apply_patch"
    }
    fn description(&self) -> &str {
        "Apply a diff patch to files. Uses Codex apply_patch DSL format:\n\
         *** Begin Patch\n\
         *** Update File: path\n\
         @@ context_line\n\
         -old line\n\
         +new line\n\
          context line\n\
         *** End Patch\n\n\
         Supports: Add File, Delete File, Update File (with Move to).\n\
         Fuzzy matching: handles trailing whitespace and unicode variants."
    }
    fn parameters_schema(&self) -> Value {
        json_schema_for::<ApplyPatchArgs>()
    }
    async fn execute(&self, args: Value, _ctx: &mut AgentContext) -> Result<ToolOutput, ToolError> {
        let a: ApplyPatchArgs = parse_args(&args)?;

        let hunks = parse_patch(&a.patch).map_err(|e| ToolError::Execution(e))?;

        let mut added: Vec<String> = Vec::new();
        let mut modified: Vec<String> = Vec::new();
        let mut deleted: Vec<String> = Vec::new();
        let mut moved: Vec<(String, String)> = Vec::new();

        for hunk in &hunks {
            match hunk {
                Hunk::AddFile { path, contents } => {
                    self.0
                        .write(path, contents, 0, 0)
                        .await
                        .map_err(backend_err)?;
                    added.push(path.clone());
                }
                Hunk::DeleteFile { path } => {
                    self.0.delete(path).await.map_err(backend_err)?;
                    deleted.push(path.clone());
                }
                Hunk::UpdateFile {
                    path,
                    move_path,
                    chunks,
                } => {
                    let content = self.0.read(path, false, 0, 0).await.map_err(backend_err)?;

                    let new_content =
                        apply_chunks(&content, chunks).map_err(|e| ToolError::Execution(e))?;

                    let target = move_path.as_deref().unwrap_or(path);
                    self.0
                        .write(target, &new_content, 0, 0)
                        .await
                        .map_err(backend_err)?;

                    if let Some(mp) = move_path {
                        self.0.delete(path).await.map_err(backend_err)?;
                        moved.push((path.clone(), mp.clone()));
                    } else {
                        modified.push(path.clone());
                    }
                }
            }
        }

        let mut summary = Vec::new();
        if !modified.is_empty() {
            summary.push(format!("Modified: {}", modified.join(", ")));
        }
        if !added.is_empty() {
            summary.push(format!("Added: {}", added.join(", ")));
        }
        if !deleted.is_empty() {
            summary.push(format!("Deleted: {}", deleted.join(", ")));
        }
        for (from, to) in &moved {
            summary.push(format!("Moved: {} -> {}", from, to));
        }

        Ok(ToolOutput::text(summary.join("\n")))
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn parse_add_file() {
        let patch = "\
*** Begin Patch
*** Add File: hello.txt
+Hello
+World
*** End Patch";

        let hunks = parse_patch(patch).unwrap();
        assert_eq!(hunks.len(), 1);
        match &hunks[0] {
            Hunk::AddFile { path, contents } => {
                assert_eq!(path, "hello.txt");
                assert_eq!(contents, "Hello\nWorld");
            }
            _ => panic!("Expected AddFile"),
        }
    }

    #[test]
    fn parse_delete_file() {
        let patch = "\
*** Begin Patch
*** Delete File: old.txt
*** End Patch";

        let hunks = parse_patch(patch).unwrap();
        assert_eq!(hunks.len(), 1);
        match &hunks[0] {
            Hunk::DeleteFile { path } => assert_eq!(path, "old.txt"),
            _ => panic!("Expected DeleteFile"),
        }
    }

    #[test]
    fn parse_update_file() {
        let patch = "\
*** Begin Patch
*** Update File: src/main.rs
@@ fn main() {
-    println!(\"old\");
+    println!(\"new\");
*** End Patch";

        let hunks = parse_patch(patch).unwrap();
        assert_eq!(hunks.len(), 1);
        match &hunks[0] {
            Hunk::UpdateFile {
                path,
                move_path,
                chunks,
            } => {
                assert_eq!(path, "src/main.rs");
                assert!(move_path.is_none());
                assert_eq!(chunks.len(), 1);
                assert_eq!(chunks[0].context.as_deref(), Some("fn main() {"));
                assert_eq!(chunks[0].old_lines, vec!["    println!(\"old\");"]);
                assert_eq!(chunks[0].new_lines, vec!["    println!(\"new\");"]);
            }
            _ => panic!("Expected UpdateFile"),
        }
    }

    #[test]
    fn parse_move_file() {
        let patch = "\
*** Begin Patch
*** Update File: old/path.rs
*** Move to: new/path.rs
@@ use std;
-old line
+new line
*** End Patch";

        let hunks = parse_patch(patch).unwrap();
        assert_eq!(hunks.len(), 1);
        match &hunks[0] {
            Hunk::UpdateFile {
                path,
                move_path,
                chunks,
            } => {
                assert_eq!(path, "old/path.rs");
                assert_eq!(move_path.as_deref(), Some("new/path.rs"));
                assert_eq!(chunks.len(), 1);
            }
            _ => panic!("Expected UpdateFile with move"),
        }
    }

    #[test]
    fn parse_multi_hunk() {
        let patch = "\
*** Begin Patch
*** Add File: new.txt
+content
*** Delete File: old.txt
*** Update File: src/lib.rs
@@ fn foo() {
-    old();
+    new();
*** End Patch";

        let hunks = parse_patch(patch).unwrap();
        assert_eq!(hunks.len(), 3);
        assert!(matches!(&hunks[0], Hunk::AddFile { .. }));
        assert!(matches!(&hunks[1], Hunk::DeleteFile { .. }));
        assert!(matches!(&hunks[2], Hunk::UpdateFile { .. }));
    }

    #[test]
    fn parse_empty_patch_fails() {
        let patch = "*** Begin Patch\n*** End Patch";
        assert!(parse_patch(patch).is_err());
    }

    #[test]
    fn seek_exact() {
        let haystack: Vec<String> = vec!["a", "b", "c", "d"]
            .into_iter()
            .map(String::from)
            .collect();
        let needle: Vec<String> = vec!["b", "c"].into_iter().map(String::from).collect();
        assert_eq!(seek_sequence(&haystack, &needle, 0), Some(1));
    }

    #[test]
    fn seek_trim_end() {
        let haystack: Vec<String> = vec!["a  ", "b  "].into_iter().map(String::from).collect();
        let needle: Vec<String> = vec!["a", "b"].into_iter().map(String::from).collect();
        assert_eq!(seek_sequence(&haystack, &needle, 0), Some(0));
    }

    #[test]
    fn seek_trim_both() {
        let haystack: Vec<String> = vec!["  a  ", "  b  "]
            .into_iter()
            .map(String::from)
            .collect();
        let needle: Vec<String> = vec!["a", "b"].into_iter().map(String::from).collect();
        assert_eq!(seek_sequence(&haystack, &needle, 0), Some(0));
    }

    #[test]
    fn seek_unicode_normalize() {
        // Smart quotes vs straight quotes
        let haystack: Vec<String> = vec!["\u{201C}hello\u{201D}"]
            .into_iter()
            .map(String::from)
            .collect();
        let needle: Vec<String> = vec!["\"hello\""].into_iter().map(String::from).collect();
        assert_eq!(seek_sequence(&haystack, &needle, 0), Some(0));
    }

    #[test]
    fn seek_not_found() {
        let haystack: Vec<String> = vec!["a", "b"].into_iter().map(String::from).collect();
        let needle: Vec<String> = vec!["x"].into_iter().map(String::from).collect();
        assert_eq!(seek_sequence(&haystack, &needle, 0), None);
    }

    #[test]
    fn apply_simple_replacement() {
        let content = "line1\nline2\nline3";
        let chunks = vec![Chunk {
            context: None,
            old_lines: vec!["line2".to_string()],
            new_lines: vec!["replaced".to_string()],
        }];
        let result = apply_chunks(content, &chunks).unwrap();
        assert_eq!(result, "line1\nreplaced\nline3");
    }

    #[test]
    fn apply_with_context() {
        let content = "fn main() {\n    println!(\"old\");\n}";
        let chunks = vec![Chunk {
            context: Some("fn main() {".to_string()),
            old_lines: vec!["    println!(\"old\");".to_string()],
            new_lines: vec!["    println!(\"new\");".to_string()],
        }];
        let result = apply_chunks(content, &chunks).unwrap();
        assert_eq!(result, "fn main() {\n    println!(\"new\");\n}");
    }

    #[test]
    fn apply_multi_line_replacement() {
        let content = "a\nb\nc\nd\ne";
        let chunks = vec![Chunk {
            context: None,
            old_lines: vec!["b".to_string(), "c".to_string(), "d".to_string()],
            new_lines: vec!["x".to_string(), "y".to_string()],
        }];
        let result = apply_chunks(content, &chunks).unwrap();
        assert_eq!(result, "a\nx\ny\ne");
    }

    #[test]
    fn apply_deletion_chunk() {
        let content = "a\nb\nc";
        let chunks = vec![Chunk {
            context: None,
            old_lines: vec!["b".to_string()],
            new_lines: vec![],
        }];
        let result = apply_chunks(content, &chunks).unwrap();
        assert_eq!(result, "a\nc");
    }

    #[test]
    fn apply_insertion_with_context() {
        let content = "a\nb\nc";
        let chunks = vec![Chunk {
            context: Some("b".to_string()),
            old_lines: vec![],
            new_lines: vec!["inserted".to_string()],
        }];
        let result = apply_chunks(content, &chunks).unwrap();
        assert_eq!(result, "a\nb\ninserted\nc");
    }

    #[test]
    fn parse_context_lines_in_chunk() {
        let patch = "\
*** Begin Patch
*** Update File: test.rs
@@ fn example() {
 fn example() {
-    old();
+    new();
 }
*** End Patch";

        let hunks = parse_patch(patch).unwrap();
        match &hunks[0] {
            Hunk::UpdateFile { chunks, .. } => {
                assert_eq!(chunks.len(), 1);
                let c = &chunks[0];
                // Context lines appear in both old and new
                assert_eq!(c.old_lines, vec!["fn example() {", "    old();", "}"]);
                assert_eq!(c.new_lines, vec!["fn example() {", "    new();", "}"]);
            }
            _ => panic!("Expected UpdateFile"),
        }
    }
}