procyon 0.3.0

Terminal development harness for Stellar and Soroban smart contracts, driven by a language model
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
use async_trait::async_trait;
use ignore::WalkBuilder;
use regex::RegexBuilder;
use serde_json::{json, Value};
use std::path::{Path, PathBuf};

use super::paths::resolve_in_workspace;
use super::Tool;

// Enough to answer a question without flooding the model's context.
const MAX_RESULTS: usize = 200;
const MAX_MATCH_LINE: usize = 240;

fn walk(root: &Path) -> ignore::Walk {
    WalkBuilder::new(root)
        // .gitignore already excludes target/ and node_modules in these projects.
        .git_ignore(true)
        .hidden(true)
        .build()
}

fn relative(path: &Path, root: &Path) -> String {
    path.strip_prefix(root)
        .unwrap_or(path)
        .display()
        .to_string()
}

// Supports the subset of glob that matters here: `*` within a segment and `**` across segments.
fn glob_to_regex(pattern: &str) -> String {
    let mut out = String::from("^");
    let bytes: Vec<char> = pattern.chars().collect();
    let mut i = 0;

    while i < bytes.len() {
        match bytes[i] {
            '*' => {
                if bytes.get(i + 1) == Some(&'*') {
                    // `**/` may also match zero directories.
                    if bytes.get(i + 2) == Some(&'/') {
                        out.push_str("(?:.*/)?");
                        i += 3;
                        continue;
                    }
                    out.push_str(".*");
                    i += 2;
                    continue;
                }
                out.push_str("[^/]*");
                i += 1;
            }
            '?' => {
                out.push_str("[^/]");
                i += 1;
            }
            c => {
                out.push_str(&regex::escape(&c.to_string()));
                i += 1;
            }
        }
    }

    out.push('$');
    out
}

pub struct ListDirTool;

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

    fn capability(&self) -> crate::risk::Capability {
        crate::risk::Capability::ReadOnly
    }

    fn description(&self) -> &str {
        "List the entries of a directory in the workspace (one level, not recursive)"
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Directory to list, relative to the workspace (default: .)"
                }
            },
            "required": []
        })
    }

    async fn execute(&self, input: Value) -> Result<String, String> {
        let requested = input.get("path").and_then(|v| v.as_str()).unwrap_or(".");
        let dir = resolve_in_workspace(requested)?;

        let mut entries = tokio::fs::read_dir(&dir)
            .await
            .map_err(|e| format!("Failed to read {}: {}", requested, e))?;

        let mut dirs = Vec::new();
        let mut files = Vec::new();

        while let Some(entry) = entries
            .next_entry()
            .await
            .map_err(|e| format!("Failed to read {}: {}", requested, e))?
        {
            let name = entry.file_name().to_string_lossy().to_string();
            if name.starts_with('.') {
                continue;
            }
            let is_dir = entry.file_type().await.map(|t| t.is_dir()).unwrap_or(false);
            if is_dir {
                dirs.push(format!("{}/", name));
            } else {
                files.push(name);
            }
        }

        dirs.sort();
        files.sort();

        if dirs.is_empty() && files.is_empty() {
            return Ok(format!("{} is empty", requested));
        }

        let mut out = format!("{}:\n", requested);
        for entry in dirs.into_iter().chain(files) {
            out.push_str(&format!("  {}\n", entry));
        }
        Ok(out)
    }
}

pub struct GlobTool;

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

    fn capability(&self) -> crate::risk::Capability {
        crate::risk::Capability::ReadOnly
    }

    fn description(&self) -> &str {
        "Find files in the workspace by glob pattern, e.g. 'contracts/**/*.rs' or '**/Cargo.toml'"
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "pattern": {
                    "type": "string",
                    "description": "Glob pattern matched against workspace-relative paths. Supports * and **"
                },
                "path": {
                    "type": "string",
                    "description": "Directory to search under, relative to the workspace (default: .)"
                }
            },
            "required": ["pattern"]
        })
    }

    async fn execute(&self, input: Value) -> Result<String, String> {
        let pattern = input
            .get("pattern")
            .and_then(|v| v.as_str())
            .ok_or("Missing 'pattern' parameter")?;

        let requested = input.get("path").and_then(|v| v.as_str()).unwrap_or(".");
        let root = resolve_in_workspace(requested)?;

        let regex = RegexBuilder::new(&glob_to_regex(pattern))
            .build()
            .map_err(|e| format!("Invalid pattern '{}': {}", pattern, e))?;

        let (matches, truncated) = tokio::task::spawn_blocking(move || {
            let mut found: Vec<String> = Vec::new();
            let mut truncated = false;
            for entry in walk(&root).flatten() {
                if !entry.file_type().map(|t| t.is_file()).unwrap_or(false) {
                    continue;
                }
                let rel = relative(entry.path(), &root);
                if regex.is_match(&rel) {
                    if found.len() >= MAX_RESULTS {
                        truncated = true;
                        break;
                    }
                    found.push(rel);
                }
            }
            found.sort();
            (found, truncated)
        })
        .await
        .map_err(|e| format!("Search failed: {}", e))?;

        if matches.is_empty() {
            return Ok(format!("No files match '{}' under {}", pattern, requested));
        }

        let mut out = format!("{} file(s) matching '{}':\n", matches.len(), pattern);
        for path in matches {
            out.push_str(&format!("  {}\n", path));
        }
        if truncated {
            out.push_str(&format!("(stopped at {} results)\n", MAX_RESULTS));
        }
        Ok(out)
    }
}

pub struct GrepTool;

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

    fn capability(&self) -> crate::risk::Capability {
        crate::risk::Capability::ReadOnly
    }

    fn description(&self) -> &str {
        "Search file contents in the workspace with a regular expression"
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "pattern": {
                    "type": "string",
                    "description": "Regular expression to search for"
                },
                "path": {
                    "type": "string",
                    "description": "Directory to search under, relative to the workspace (default: .)"
                },
                "glob": {
                    "type": "string",
                    "description": "Optional glob restricting which files are searched, e.g. '**/*.rs'"
                },
                "case_sensitive": {
                    "type": "boolean",
                    "description": "Match case-sensitively (default: false)"
                }
            },
            "required": ["pattern"]
        })
    }

    async fn execute(&self, input: Value) -> Result<String, String> {
        let pattern = input
            .get("pattern")
            .and_then(|v| v.as_str())
            .ok_or("Missing 'pattern' parameter")?;

        let requested = input.get("path").and_then(|v| v.as_str()).unwrap_or(".");
        let root = resolve_in_workspace(requested)?;

        let case_sensitive = input
            .get("case_sensitive")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let regex = RegexBuilder::new(pattern)
            .case_insensitive(!case_sensitive)
            .build()
            .map_err(|e| format!("Invalid pattern '{}': {}", pattern, e))?;

        let file_filter = match input.get("glob").and_then(|v| v.as_str()) {
            Some(glob) => Some(
                RegexBuilder::new(&glob_to_regex(glob))
                    .build()
                    .map_err(|e| format!("Invalid glob '{}': {}", glob, e))?,
            ),
            None => None,
        };

        let (hits, truncated) =
            tokio::task::spawn_blocking(move || search_files(&root, &regex, file_filter.as_ref()))
                .await
                .map_err(|e| format!("Search failed: {}", e))?;

        if hits.is_empty() {
            return Ok(format!("No matches for '{}' under {}", pattern, requested));
        }

        let mut out = format!("{} match(es) for '{}':\n", hits.len(), pattern);
        for hit in hits {
            out.push_str(&hit);
            out.push('\n');
        }
        if truncated {
            out.push_str(&format!("(stopped at {} matches)\n", MAX_RESULTS));
        }
        Ok(out)
    }
}

fn search_files(
    root: &Path,
    regex: &regex::Regex,
    file_filter: Option<&regex::Regex>,
) -> (Vec<String>, bool) {
    let mut hits = Vec::new();

    for entry in walk(root).flatten() {
        if !entry.file_type().map(|t| t.is_file()).unwrap_or(false) {
            continue;
        }

        let path: PathBuf = entry.path().to_path_buf();
        let rel = relative(&path, root);

        if let Some(filter) = file_filter {
            if !filter.is_match(&rel) {
                continue;
            }
        }

        // Binary files and unreadable paths are skipped rather than reported as errors.
        let Ok(content) = std::fs::read_to_string(&path) else {
            continue;
        };

        for (number, line) in content.lines().enumerate() {
            if !regex.is_match(line) {
                continue;
            }
            if hits.len() >= MAX_RESULTS {
                return (hits, true);
            }
            let shown: String = if line.chars().count() > MAX_MATCH_LINE {
                line.chars().take(MAX_MATCH_LINE).collect::<String>() + "…"
            } else {
                line.to_string()
            };
            hits.push(format!("  {}:{}: {}", rel, number + 1, shown.trim_end()));
        }
    }

    (hits, false)
}

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

    #[test]
    fn glob_translates_star_within_a_segment() {
        let re = RegexBuilder::new(&glob_to_regex("*.rs")).build().unwrap();
        assert!(re.is_match("main.rs"));
        assert!(!re.is_match("src/main.rs"), "* must not cross a separator");
    }

    #[test]
    fn glob_translates_double_star_across_segments() {
        let re = RegexBuilder::new(&glob_to_regex("**/*.rs"))
            .build()
            .unwrap();
        assert!(re.is_match("src/tools/search.rs"));
        assert!(
            re.is_match("main.rs"),
            "**/ must also match zero directories"
        );
    }

    #[test]
    fn glob_anchors_the_whole_path() {
        let re = RegexBuilder::new(&glob_to_regex("src/*.rs"))
            .build()
            .unwrap();
        assert!(re.is_match("src/app.rs"));
        assert!(!re.is_match("other/src/app.rs"));
    }

    #[test]
    fn glob_escapes_regex_metacharacters() {
        let re = RegexBuilder::new(&glob_to_regex("Cargo.toml"))
            .build()
            .unwrap();
        assert!(re.is_match("Cargo.toml"));
        assert!(!re.is_match("CargoXtoml"), "the dot must be literal");
    }

    #[tokio::test]
    async fn glob_finds_this_crates_sources() {
        let out = GlobTool
            .execute(json!({"pattern": "src/tools/*.rs"}))
            .await
            .unwrap();
        assert!(out.contains("src/tools/search.rs"), "got {}", out);
        assert!(
            !out.contains("src/main.rs"),
            "pattern was too loose: {}",
            out
        );
    }

    #[tokio::test]
    async fn glob_skips_gitignored_paths() {
        let out = GlobTool
            .execute(json!({"pattern": "**/*.rs"}))
            .await
            .unwrap();
        assert!(
            !out.contains("target/"),
            "target/ is gitignored and must not be walked: {}",
            out
        );
    }

    #[tokio::test]
    async fn grep_finds_a_known_symbol_with_line_numbers() {
        let out = GrepTool
            .execute(json!({"pattern": "fn resolve_in_workspace", "glob": "**/*.rs"}))
            .await
            .unwrap();
        assert!(out.contains("src/tools/paths.rs:"), "got {}", out);
    }

    #[tokio::test]
    async fn grep_rejects_an_invalid_regex() {
        let err = GrepTool.execute(json!({"pattern": "("})).await.unwrap_err();
        assert!(err.contains("Invalid pattern"), "got {}", err);
    }

    #[tokio::test]
    async fn search_tools_are_confined_to_the_workspace() {
        for path in ["/etc", "../../.."] {
            assert!(
                ListDirTool.execute(json!({"path": path})).await.is_err(),
                "list_dir escaped to {}",
                path
            );
            assert!(
                GlobTool
                    .execute(json!({"pattern": "*", "path": path}))
                    .await
                    .is_err(),
                "glob escaped to {}",
                path
            );
            assert!(
                GrepTool
                    .execute(json!({"pattern": "x", "path": path}))
                    .await
                    .is_err(),
                "grep escaped to {}",
                path
            );
        }
    }

    #[tokio::test]
    async fn list_dir_separates_directories_from_files() {
        let out = ListDirTool.execute(json!({"path": "src"})).await.unwrap();
        assert!(
            out.contains("tools/"),
            "directories need a trailing slash: {}",
            out
        );
        assert!(out.contains("main.rs"), "got {}", out);
    }
}