ralph-coder 0.2.1

An agentic code generation CLI powered by multiple LLM backends
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
use crate::errors::{RalphError, Result};
use ignore::overrides::OverrideBuilder;
use ignore::WalkBuilder;
use regex::Regex;
use std::path::Path;

pub fn read_file(path: &Path) -> Result<String> {
    if !path.exists() {
        return Err(RalphError::FileNotFound(path.display().to_string()));
    }
    std::fs::read_to_string(path).map_err(RalphError::Io)
}

/// Read a file with optional pagination.
///
/// - `offset`: 0-based line index to start from (default: 0).
/// - `limit`:  maximum number of lines to return (default: 150).
///
/// Returns a truncation notice when more lines remain so the caller
/// knows the exact offset to pass in a follow-up call.
pub fn read_file_ranged(
    path: &Path,
    offset: Option<usize>,
    limit: Option<usize>,
) -> Result<String> {
    if !path.exists() {
        return Err(RalphError::FileNotFound(path.display().to_string()));
    }
    let content = std::fs::read_to_string(path).map_err(RalphError::Io)?;

    let all_lines: Vec<&str> = content.lines().collect();
    let total = all_lines.len();

    let start = offset.unwrap_or(0).min(total);
    let max_lines = limit.unwrap_or(150);
    let end = (start + max_lines).min(total);

    let mut out = String::new();
    for line in &all_lines[start..end] {
        out.push_str(line);
        out.push('\n');
    }

    if end < total {
        out.push_str(&format!(
            "\n[...truncated after line {} of {}. \
             To read further use `read_file` with `offset={}`.]",
            end, total, end
        ));
    }

    Ok(out)
}

pub fn list_dir(path: &Path) -> Result<String> {
    if !path.exists() {
        return Err(RalphError::FileNotFound(path.display().to_string()));
    }

    let mut entries = Vec::new();
    let walker = WalkBuilder::new(path)
        .hidden(false)
        .ignore(true)
        .git_ignore(true)
        .max_depth(Some(4))
        .build();

    for entry in walker.flatten() {
        let rel = entry
            .path()
            .strip_prefix(path)
            .unwrap_or(entry.path())
            .display()
            .to_string();
        if rel.is_empty() {
            continue;
        }
        let suffix = if entry.path().is_dir() { "/" } else { "" };
        entries.push(format!("{}{}", rel, suffix));
    }
    entries.sort();
    Ok(entries.join("\n"))
}

pub fn write_file(path: &Path, content: &str) -> Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(path, content).map_err(RalphError::Io)
}

pub fn edit_file(path: &Path, old_string: &str, new_string: &str) -> Result<()> {
    let content = read_file(path)?;
    if !content.contains(old_string) {
        return Err(RalphError::EditNotFound {
            path: path.display().to_string(),
        });
    }
    let updated = content.replacen(old_string, new_string, 1);
    std::fs::write(path, updated).map_err(RalphError::Io)
}

/// Apply multiple (old_string → new_string) replacements to a file in one call.
/// All replacements are validated before any are applied: if any `old_string` is
/// not found, the entire operation fails with an index hint.
pub fn edit_file_multi(path: &Path, edits: &[(String, String)]) -> Result<Vec<String>> {
    let mut content = read_file(path)?;
    let mut applied = Vec::new();
    for (i, (old, new)) in edits.iter().enumerate() {
        if !content.contains(old.as_str()) {
            let hint = find_closest_match_hint(&content, old);
            return Err(RalphError::ToolFailed {
                tool: "edit_file_multi".to_string(),
                message: format!(
                    "edit[{i}]: old_string not found in {}.\n{hint}",
                    path.display()
                ),
            });
        }
        content = content.replacen(old.as_str(), new.as_str(), 1);
        applied.push(format!("edit[{i}] applied"));
    }
    std::fs::write(path, content).map_err(RalphError::Io)?;
    Ok(applied)
}

/// Given a file's content and a failed `old_string`, return a human-readable
/// hint pointing at the closest matching block — helps the LLM fix whitespace
/// or indentation mismatches without re-reading the entire file.
pub fn find_closest_match_hint(content: &str, old_string: &str) -> String {
    let content_lines: Vec<&str> = content.lines().collect();
    let search_lines: Vec<&str> = old_string.lines().collect();

    // Find the first non-blank search line to use as the anchor.
    let anchor = match search_lines.iter().find(|l| !l.trim().is_empty()) {
        Some(l) => l.trim(),
        None => return String::new(),
    };

    // Extract words of length ≥ 3 as "significant tokens".
    let sig_words: Vec<&str> = anchor
        .split(|c: char| !c.is_alphanumeric() && c != '_')
        .filter(|w| w.len() >= 3)
        .collect();

    if sig_words.is_empty() {
        return String::new();
    }

    // Score each content line by how many significant words it shares with the anchor.
    let mut best_score = 0usize;
    let mut best_line = usize::MAX;
    for (i, line) in content_lines.iter().enumerate() {
        let lc = line.to_lowercase();
        let score = sig_words.iter().filter(|w| lc.contains(*w)).count();
        if score > best_score {
            best_score = score;
            best_line = i;
        }
    }

    if best_score == 0 || best_line == usize::MAX {
        return String::new();
    }

    let start = best_line.saturating_sub(2);
    let end = (best_line + search_lines.len() + 3).min(content_lines.len());
    let mut hint = format!("Closest match near line {}:\n", best_line + 1);
    for i in start..end {
        let marker = if i == best_line { ">>>" } else { "   " };
        hint.push_str(&format!("{} {:4}: {}\n", marker, i + 1, content_lines[i]));
    }
    hint
}

/// Return a structural outline of a file — function/class/struct signatures
/// with line numbers, without the bodies. Ideal for surveying a large file
/// before deciding which section to read in full.
pub fn read_file_outline(path: &Path) -> Result<String> {
    if !path.exists() {
        return Err(RalphError::FileNotFound(path.display().to_string()));
    }
    let content = std::fs::read_to_string(path).map_err(RalphError::Io)?;
    let lines: Vec<&str> = content.lines().collect();
    let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");

    // Per-language signature patterns.
    let pats: &[&str] = match ext {
        "rs" => &[
            r"^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+\w+",
            r"^\s*(?:pub(?:\([^)]*\))?\s+)?struct\s+\w+",
            r"^\s*(?:pub(?:\([^)]*\))?\s+)?enum\s+\w+",
            r"^\s*(?:pub(?:\([^)]*\))?\s+)?trait\s+\w+",
            r"^\s*(?:pub(?:\([^)]*\))?\s+)?impl(?:<[^>]*>)?\s+\w+",
        ],
        "py" => &[r"^\s*(?:async\s+)?def\s+\w+", r"^\s*class\s+\w+"],
        "js" | "ts" | "tsx" | "jsx" | "mjs" | "cjs" => &[
            r"^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+\w+",
            r"^\s*(?:export\s+)?(?:default\s+)?class\s+\w+",
            r"^\s*(?:export\s+)?(?:const|let)\s+\w+\s*[=:]",
        ],
        "go" => &[
            r"^\s*func\s+(?:\([^)]*\)\s+)?\w+",
            r"^\s*type\s+\w+\s+(?:struct|interface)",
        ],
        "java" | "kt" => &[
            r"^\s*(?:(?:public|private|protected|static|final|abstract|override)\s+)*\w+\s+\w+\s*\(",
            r"^\s*(?:public\s+|private\s+|protected\s+)?(?:class|interface|enum|object)\s+\w+",
        ],
        "rb" => &[r"^\s*def\s+\w+", r"^\s*class\s+\w+", r"^\s*module\s+\w+"],
        _ => &[],
    };

    let compiled: Vec<Regex> = pats.iter().filter_map(|p| Regex::new(p).ok()).collect();

    if compiled.is_empty() {
        return Ok(format!(
            "{} ({} lines) — unknown file type; use read_file with offset/limit to navigate",
            path.display(),
            lines.len()
        ));
    }

    let mut out = format!("{} ({} lines)\n", path.display(), lines.len());
    for (i, line) in lines.iter().enumerate() {
        if compiled.iter().any(|re| re.is_match(line)) {
            out.push_str(&format!("{:5}: {}\n", i + 1, line.trim_end()));
        }
    }

    if out.trim_end().ends_with(')') {
        // Nothing matched after the header
        out.push_str("(no recognisable top-level definitions found)\n");
    }

    Ok(out)
}

pub fn delete_file(path: &Path) -> Result<()> {
    if !path.exists() {
        return Err(RalphError::FileNotFound(path.display().to_string()));
    }
    std::fs::remove_file(path).map_err(RalphError::Io)
}

/// Load all files matching a glob pattern (e.g. `src/**/*.rs`), returning
/// their contents concatenated with path headers.  Caps at 100 files and
/// 500 KB total to keep context manageable.
pub fn load_files(pattern: &str, root: &Path) -> Result<String> {
    let mut overrides = OverrideBuilder::new(root);
    overrides.add(pattern).map_err(|e| RalphError::ToolFailed {
        tool: "load_files".to_string(),
        message: format!("Invalid glob pattern: {}", e),
    })?;
    let overrides = overrides.build().map_err(|e| RalphError::ToolFailed {
        tool: "load_files".to_string(),
        message: format!("Failed to build override: {}", e),
    })?;

    let walker = WalkBuilder::new(root)
        .hidden(false)
        .ignore(true)
        .git_ignore(true)
        .overrides(overrides)
        .build();

    let mut output = String::new();
    let mut file_count = 0usize;
    const MAX_FILES: usize = 100;
    const MAX_BYTES: usize = 512 * 1024; // 500 KB

    for entry in walker.flatten() {
        let path = entry.path();
        if !path.is_file() {
            continue;
        }
        let rel = path.strip_prefix(root).unwrap_or(path);
        let content = match std::fs::read_to_string(path) {
            Ok(c) => c,
            Err(_) => continue, // skip binary files
        };

        let header = format!("=== {} ===\n", rel.display());
        if output.len() + header.len() + content.len() > MAX_BYTES {
            output.push_str(&format!(
                "\n[load_files] Output truncated at {} files / 500 KB limit.",
                file_count
            ));
            break;
        }

        output.push_str(&header);
        output.push_str(&content);
        output.push('\n');
        file_count += 1;

        if file_count >= MAX_FILES {
            output.push_str("\n[load_files] Reached 100-file limit.");
            break;
        }
    }

    if output.is_empty() {
        Ok(format!("No files matched pattern: {}", pattern))
    } else {
        Ok(output)
    }
}

// ── Project type detection helpers ───────────────────────────────────────────

struct ProjectInfo {
    kind: &'static str,
    manifest: &'static str,
    src_ext: &'static str,
}

const PROJECT_SIGNATURES: &[ProjectInfo] = &[
    ProjectInfo {
        kind: "Rust",
        manifest: "Cargo.toml",
        src_ext: "rs",
    },
    ProjectInfo {
        kind: "Node.js",
        manifest: "package.json",
        src_ext: "js",
    },
    ProjectInfo {
        kind: "TypeScript",
        manifest: "tsconfig.json",
        src_ext: "ts",
    },
    ProjectInfo {
        kind: "Python",
        manifest: "pyproject.toml",
        src_ext: "py",
    },
    ProjectInfo {
        kind: "Python",
        manifest: "setup.py",
        src_ext: "py",
    },
    ProjectInfo {
        kind: "Go",
        manifest: "go.mod",
        src_ext: "go",
    },
    ProjectInfo {
        kind: "Java",
        manifest: "pom.xml",
        src_ext: "java",
    },
    ProjectInfo {
        kind: "Java",
        manifest: "build.gradle",
        src_ext: "java",
    },
    ProjectInfo {
        kind: "Ruby",
        manifest: "Gemfile",
        src_ext: "rb",
    },
    ProjectInfo {
        kind: "PHP",
        manifest: "composer.json",
        src_ext: "php",
    },
];

/// Analyze the code structure at `root` and return a structured summary that
/// the LLM can use to explain the codebase to the user.
pub fn explain_code(root: &Path) -> Result<String> {
    if !root.exists() {
        return Err(RalphError::FileNotFound(root.display().to_string()));
    }

    let mut report = String::new();

    // ── Project type ──────────────────────────────────────────────────────────
    let mut detected_kind = "Unknown";
    let mut src_ext = "";

    for sig in PROJECT_SIGNATURES {
        let manifest_path = root.join(sig.manifest);
        if manifest_path.exists() {
            detected_kind = sig.kind;
            src_ext = sig.src_ext;
            let manifest_content = std::fs::read_to_string(&manifest_path).unwrap_or_default();
            report.push_str(&format!("## Project Type\n{}\n\n", sig.kind));
            report.push_str(&format!(
                "## {} ({})\n```\n{}\n```\n\n",
                sig.manifest,
                sig.kind,
                manifest_content
                    .lines()
                    .take(50)
                    .collect::<Vec<_>>()
                    .join("\n")
            ));
            break;
        }
    }

    if detected_kind == "Unknown" {
        report.push_str("## Project Type\nUnknown (no recognized manifest file found)\n\n");
    }

    // ── Directory tree ────────────────────────────────────────────────────────
    report.push_str("## Directory Structure\n```\n");
    let walker = WalkBuilder::new(root)
        .hidden(false)
        .ignore(true)
        .git_ignore(true)
        .max_depth(Some(3))
        .build();

    let mut entries: Vec<String> = walker
        .flatten()
        .filter_map(|e| {
            let rel = e.path().strip_prefix(root).ok()?.display().to_string();
            if rel.is_empty() {
                return None;
            }
            let suffix = if e.path().is_dir() { "/" } else { "" };
            Some(format!("{}{}", rel, suffix))
        })
        .collect();
    entries.sort();
    report.push_str(&entries.join("\n"));
    report.push_str("\n```\n\n");

    // ── Source file summaries ─────────────────────────────────────────────────
    if !src_ext.is_empty() {
        report.push_str("## Source Files\n");

        let walker2 = WalkBuilder::new(root)
            .hidden(false)
            .ignore(true)
            .git_ignore(true)
            .build();

        let mut source_files: Vec<std::path::PathBuf> = walker2
            .flatten()
            .filter(|e| {
                e.path().is_file()
                    && e.path()
                        .extension()
                        .and_then(|x| x.to_str())
                        .map(|x| x == src_ext)
                        .unwrap_or(false)
            })
            .map(|e| e.into_path())
            .collect();
        source_files.sort();

        for file in &source_files {
            let rel = file.strip_prefix(root).unwrap_or(file.as_path());
            let content = std::fs::read_to_string(file).unwrap_or_default();
            let lines: Vec<&str> = content.lines().collect();
            let preview: String = lines
                .iter()
                .take(30)
                .cloned()
                .collect::<Vec<_>>()
                .join("\n");
            report.push_str(&format!(
                "\n### {} ({} lines)\n```{}\n{}\n```\n",
                rel.display(),
                lines.len(),
                src_ext,
                preview
            ));
        }
        report.push('\n');
    }

    // ── Entry points ──────────────────────────────────────────────────────────
    let entry_candidates = [
        "src/main.rs",
        "src/lib.rs",
        "main.py",
        "app.py",
        "index.js",
        "index.ts",
        "main.go",
        "main.java",
        "app.rb",
        "index.php",
    ];
    let mut found_entries = Vec::new();
    for candidate in &entry_candidates {
        if root.join(candidate).exists() {
            found_entries.push(*candidate);
        }
    }
    if !found_entries.is_empty() {
        report.push_str("## Entry Points\n");
        for ep in found_entries {
            report.push_str(&format!("- `{}`\n", ep));
        }
        report.push('\n');
    }

    Ok(report)
}