roba 0.2.0

Single-prompt CLI runner built on claude-wrapper
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
//! Prompt input + composition.
//!
//! - Input sources: positional string, file (`-f`), editor (`-e`), stdin
//! - Composition: prepend, attachments (`--attach` globs), git context,
//!   main prompt, append
//! - Templating: `{{VAR}}` substitution
//!
//! `resolve_main_prompt` resolves a single input source; `compose_prompt`
//! assembles the final body with the prepend/attach/git slots wired in.

use anyhow::{Context, Result, bail};
use std::io::{IsTerminal, Read};
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::cli::AskArgs;

/// Resolve the main prompt body from one of: editor, file, positional
/// arg, stdin (piped or explicit `-`). Returns `Ok(None)` only when
/// no source was given and stdin is a TTY -- the caller should then
/// rely on prepend/append/attach to supply content, or error if those
/// are also empty.
pub fn resolve_main_prompt(
    positional: Option<&str>,
    file: Option<&Path>,
    editor: bool,
    editor_history: Option<usize>,
) -> Result<Option<String>> {
    if editor {
        if !std::io::stdin().is_terminal() {
            bail!("--editor requires a TTY; pipe-mode input is incompatible");
        }
        let n = editor_history.unwrap_or(1);
        return Ok(Some(compose_in_editor(n)?));
    }
    if let Some(path) = file {
        let content = std::fs::read_to_string(path)
            .with_context(|| format!("reading prompt from {}", path.display()))?;
        let trimmed = content.trim_end().to_string();
        if trimmed.is_empty() {
            bail!("file {} is empty", path.display());
        }
        return Ok(Some(trimmed));
    }
    match positional {
        Some("-") => Ok(Some(read_stdin()?)),
        Some(p) => Ok(Some(p.to_string())),
        None => {
            if std::io::stdin().is_terminal() {
                Ok(None)
            } else {
                Ok(Some(read_stdin()?))
            }
        }
    }
}

/// Assemble the final prompt from all sources, joined by blank lines.
/// Order: prepend files, attachments / git context, main, append files.
pub fn compose_prompt(
    main: Option<String>,
    prepend: &[PathBuf],
    attachments: Option<String>,
    append: &[PathBuf],
) -> Result<String> {
    let mut parts: Vec<String> = Vec::new();
    for path in prepend {
        let content = std::fs::read_to_string(path)
            .with_context(|| format!("reading --prepend {}", path.display()))?;
        parts.push(content.trim_end().to_string());
    }
    if let Some(attach_block) = attachments {
        parts.push(attach_block);
    }
    if let Some(m) = main {
        parts.push(m);
    }
    for path in append {
        let content = std::fs::read_to_string(path)
            .with_context(|| format!("reading --append {}", path.display()))?;
        parts.push(content.trim_end().to_string());
    }
    parts.retain(|p| !p.is_empty());
    if parts.is_empty() {
        bail!(
            "no prompt: pass one as an argument, use -f / -e, --prepend / --append / --attach, pipe via stdin, or use `-` for stdin"
        );
    }
    Ok(parts.join("\n\n"))
}

/// Substitute `{{KEY}}` placeholders in `prompt` with their values.
pub fn apply_vars(mut prompt: String, vars: &[(String, String)]) -> String {
    for (k, v) in vars {
        let placeholder = format!("{{{{{k}}}}}");
        prompt = prompt.replace(&placeholder, v);
    }
    prompt
}

/// Merge two optional strings with a blank line in between.
pub fn merge_optional(a: Option<String>, b: Option<String>) -> Option<String> {
    match (a, b) {
        (Some(a), Some(b)) => Some(format!("{a}\n\n{b}")),
        (Some(s), None) | (None, Some(s)) => Some(s),
        (None, None) => None,
    }
}

/// Walk every `--attach` glob, fence each matched file, and return
/// one combined block. Patterns with no matches log a stderr warning
/// and otherwise continue.
pub fn collect_attachments(patterns: &[String]) -> Result<Option<String>> {
    if patterns.is_empty() {
        return Ok(None);
    }
    let mut blocks: Vec<String> = Vec::new();
    for pat in patterns {
        let matches = glob::glob(pat).with_context(|| format!("invalid glob: {pat}"))?;
        let mut had_any = false;
        for entry in matches {
            let path = entry.with_context(|| format!("walking --attach {pat}"))?;
            if !path.is_file() {
                continue;
            }
            had_any = true;
            let content = std::fs::read_to_string(&path)
                .with_context(|| format!("reading --attach {}", path.display()))?;
            blocks.push(format!(
                "File: {}\n```\n{}\n```",
                path.display(),
                content.trim_end()
            ));
        }
        if !had_any {
            eprintln!("warning: --attach {pat} matched no files");
        }
    }
    if blocks.is_empty() {
        Ok(None)
    } else {
        Ok(Some(blocks.join("\n\n")))
    }
}

/// Build a git-context block from the diff / log / status flags.
pub fn collect_git_context(args: &AskArgs) -> Result<Option<String>> {
    let mut blocks: Vec<String> = Vec::new();
    if args.git_diff
        && let Some(out) = run_git(&["diff"])?
    {
        blocks.push(format!("git diff:\n```diff\n{out}\n```"));
    }
    if let Some(n) = args.git_log
        && let Some(out) = run_git(&["log", "-n", &n.to_string(), "--oneline"])?
    {
        blocks.push(format!("git log -n {n}:\n```\n{out}\n```"));
    }
    if args.git_status
        && let Some(out) = run_git(&["status", "--short"])?
    {
        blocks.push(format!("git status:\n```\n{out}\n```"));
    }
    if blocks.is_empty() {
        Ok(None)
    } else {
        Ok(Some(blocks.join("\n\n")))
    }
}

/// Run `git <args>` and return its trimmed stdout. `None` for empty
/// output (common when there's nothing to diff). Bubbles up non-zero
/// exits with the stderr message.
pub fn run_git(args: &[&str]) -> Result<Option<String>> {
    let output = std::process::Command::new("git")
        .args(args)
        .output()
        .with_context(|| format!("running git {}", args.join(" ")))?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git {} failed: {}", args.join(" "), stderr.trim());
    }
    let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if stdout.is_empty() {
        Ok(None)
    } else {
        Ok(Some(stdout))
    }
}

/// Read every byte from stdin into a trimmed String. Errors on empty
/// input so a stray pipe doesn't ship an empty prompt to claude.
pub fn read_stdin() -> Result<String> {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf)?;
    let trimmed = buf.trim_end().to_string();
    if trimmed.is_empty() {
        bail!("empty stdin");
    }
    Ok(trimmed)
}

/// The scissors line that separates the user's prompt area (above)
/// from the reference block (below). Uses `//` prefix so it reads as
/// a code-style comment in editors that highlight markdown -- a
/// `#`-prefixed scissors would render as a heading in `.md` mode.
const SCISSORS: &str = "// ------------------------ >8 ------------------------";

/// Open `$VISUAL` / `$EDITOR` / `vi` on a `.md` scratch file. With
/// `history_n > 0` and a recent session in cwd, the file is
/// pre-filled in `git commit`-style layout: empty cursor area at the
/// top, scissors line, then the last N responses below as a
/// reference block. On save, everything from the scissors down is
/// stripped, so claude only sees what the user typed above.
///
/// `history_n == 0` (or "no last session in cwd") gives an empty
/// editor, same as the original behavior.
pub fn compose_in_editor(history_n: usize) -> Result<String> {
    let tmp = tempfile::Builder::new()
        .prefix("roba-prompt-")
        .suffix(".md")
        .tempfile()
        .context("creating editor scratch file")?;
    let path = tmp.path().to_path_buf();

    let preamble = if history_n == 0 {
        String::new()
    } else {
        let responses =
            crate::history::last_n_assistant_texts_in_cwd(history_n).unwrap_or_default();
        build_editor_preamble(&responses)
    };
    if !preamble.is_empty() {
        std::fs::write(&path, &preamble).context("writing editor preamble")?;
    }

    let editor = editor_command();
    let status =
        spawn_editor(&editor, &path).with_context(|| format!("running editor `{editor}`"))?;
    if !status.success() {
        bail!("editor exited with {status}");
    }
    let content = std::fs::read_to_string(&path).context("reading editor buffer")?;
    let body = strip_from_scissors(&content);
    let trimmed = body.trim().to_string();
    if trimmed.is_empty() {
        bail!("editor returned an empty prompt");
    }
    Ok(trimmed)
}

/// Build the preamble: empty cursor area at the top, scissors line
/// with `//`-prefixed instructions, then the reference block. The
/// response body itself is *unprefixed* plain text so it's visually
/// distinct from the `//` boilerplate. Returns empty if there are no
/// responses to show.
pub fn build_editor_preamble(responses: &[String]) -> String {
    if responses.is_empty() {
        return String::new();
    }
    let mut out = String::new();
    // Two blank lines for the cursor area. nvim opens on line 1 by
    // default; the user types there, the scissors stays put below.
    out.push('\n');
    out.push('\n');
    out.push_str(SCISSORS);
    out.push('\n');
    out.push_str("// Reference only -- everything from the scissors down is stripped on save.\n");
    out.push_str("// Type your prompt above the scissors line.\n");
    out.push('\n');
    if responses.len() == 1 {
        out.push_str("// --- last response from the most recent session in this dir ---\n");
        out.push('\n');
        out.push_str(responses[0].trim_end());
        out.push('\n');
    } else {
        out.push_str(&format!(
            "// --- last {} responses from the most recent session in this dir (oldest first) ---\n",
            responses.len()
        ));
        for (i, r) in responses.iter().enumerate() {
            out.push('\n');
            out.push_str(&format!("// --- {} of {} ---\n", i + 1, responses.len()));
            out.push('\n');
            out.push_str(r.trim_end());
            out.push('\n');
        }
    }
    out
}

/// Return everything before the scissors line; if no scissors line
/// is found, return the whole content (defensive: a user who
/// deletes the scissors still gets their content sent, not silently
/// lost).
pub fn strip_from_scissors(content: &str) -> String {
    // Find the FIRST scissors line: the user's prompt area is above,
    // so an early match wins.
    let mut idx: Option<usize> = None;
    for (i, line) in content.lines().enumerate() {
        if line == SCISSORS {
            idx = Some(i);
            break;
        }
    }
    let Some(scissors_idx) = idx else {
        return content.to_string();
    };
    content
        .lines()
        .take(scissors_idx)
        .collect::<Vec<_>>()
        .join("\n")
}

fn editor_command() -> String {
    std::env::var("VISUAL")
        .or_else(|_| std::env::var("EDITOR"))
        .unwrap_or_else(|_| "vi".to_string())
}

fn spawn_editor(editor: &str, path: &Path) -> std::io::Result<std::process::ExitStatus> {
    let mut parts = editor.split_whitespace();
    let program = parts.next().expect("editor_command never returns empty");
    let extra_args: Vec<&str> = parts.collect();
    Command::new(program).args(&extra_args).arg(path).status()
}

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

    #[test]
    fn apply_vars_substitutes_named_placeholders() {
        let prompt = "Hello {{NAME}}, ticket {{ID}}".to_string();
        let vars = vec![
            ("NAME".to_string(), "Josh".to_string()),
            ("ID".to_string(), "ABC-123".to_string()),
        ];
        assert_eq!(apply_vars(prompt, &vars), "Hello Josh, ticket ABC-123");
    }

    #[test]
    fn apply_vars_leaves_unknown_placeholders_alone() {
        let prompt = "{{KNOWN}} and {{UNKNOWN}}".to_string();
        let vars = vec![("KNOWN".to_string(), "yes".to_string())];
        assert_eq!(apply_vars(prompt, &vars), "yes and {{UNKNOWN}}");
    }

    #[test]
    fn apply_vars_handles_repeated_placeholders() {
        let prompt = "{{X}} and {{X}} again".to_string();
        let vars = vec![("X".to_string(), "go".to_string())];
        assert_eq!(apply_vars(prompt, &vars), "go and go again");
    }

    #[test]
    fn merge_optional_combines_with_blank_line() {
        assert_eq!(
            merge_optional(Some("a".to_string()), Some("b".to_string())),
            Some("a\n\nb".to_string())
        );
    }

    #[test]
    fn merge_optional_returns_either_when_other_is_none() {
        assert_eq!(
            merge_optional(Some("a".to_string()), None),
            Some("a".to_string())
        );
        assert_eq!(
            merge_optional(None, Some("b".to_string())),
            Some("b".to_string())
        );
    }

    #[test]
    fn merge_optional_returns_none_when_both_none() {
        assert_eq!(merge_optional(None, None), None);
    }

    fn write_temp(content: &str) -> tempfile::NamedTempFile {
        use std::io::Write;
        let mut f = tempfile::NamedTempFile::new().unwrap();
        write!(f, "{content}").unwrap();
        f.flush().unwrap();
        f
    }

    #[test]
    fn compose_prompt_just_main() {
        let out = compose_prompt(Some("hi".to_string()), &[], None, &[]).unwrap();
        assert_eq!(out, "hi");
    }

    #[test]
    fn compose_prompt_prepend_then_main_then_append() {
        let pre = write_temp("SYSTEM");
        let post = write_temp("CONTEXT");
        let out = compose_prompt(
            Some("question".to_string()),
            std::slice::from_ref(&pre.path().to_path_buf()),
            None,
            std::slice::from_ref(&post.path().to_path_buf()),
        )
        .unwrap();
        assert_eq!(out, "SYSTEM\n\nquestion\n\nCONTEXT");
    }

    #[test]
    fn compose_prompt_inserts_attachments_between_prepend_and_main() {
        let pre = write_temp("PREP");
        let attach = "File: foo.rs\n```\nfn x() {}\n```".to_string();
        let out = compose_prompt(
            Some("question".to_string()),
            std::slice::from_ref(&pre.path().to_path_buf()),
            Some(attach.clone()),
            &[],
        )
        .unwrap();
        assert_eq!(out, format!("PREP\n\n{attach}\n\nquestion"));
    }

    #[test]
    fn compose_prompt_main_optional_when_prepend_present() {
        let pre = write_temp("STANDALONE");
        let out = compose_prompt(
            None,
            std::slice::from_ref(&pre.path().to_path_buf()),
            None,
            &[],
        )
        .unwrap();
        assert_eq!(out, "STANDALONE");
    }

    #[test]
    fn compose_prompt_errors_when_everything_empty() {
        let err = compose_prompt(None, &[], None, &[]).expect_err("must error");
        assert!(format!("{err:#}").contains("no prompt"));
    }

    #[test]
    fn compose_prompt_drops_empty_segments() {
        let empty = write_temp("");
        let out = compose_prompt(
            Some("only".to_string()),
            std::slice::from_ref(&empty.path().to_path_buf()),
            None,
            &[],
        )
        .unwrap();
        assert_eq!(out, "only");
    }

    // -- editor preamble + scissors strip ----------------------------------

    #[test]
    fn preamble_empty_for_no_responses() {
        assert_eq!(build_editor_preamble(&[]), "");
    }

    #[test]
    fn preamble_single_response_layout() {
        let p = build_editor_preamble(&["the previous answer".to_string()]);
        // Starts with blank lines so the cursor lands above the scissors.
        assert!(
            p.starts_with("\n\n"),
            "expected leading blank lines for cursor area, got: {p:?}"
        );
        assert!(p.contains(SCISSORS));
        // Hint text is `//`-prefixed and visible.
        assert!(p.contains("// Type your prompt above the scissors line."));
        // Section divider for the response.
        assert!(p.contains("// --- last response"));
        // The response body itself is unprefixed -- visually distinct
        // from the `//` instructions/dividers.
        assert!(
            p.contains("\nthe previous answer\n"),
            "expected unprefixed response body, got:\n{p}"
        );
    }

    #[test]
    fn preamble_multi_response_uses_section_dividers() {
        let p = build_editor_preamble(&["older one".to_string(), "newer one".to_string()]);
        // Header mentions the count
        assert!(p.contains("// --- last 2 responses"));
        // Each response gets a numbered divider
        assert!(p.contains("// --- 1 of 2 ---"));
        assert!(p.contains("// --- 2 of 2 ---"));
        // Bodies are unprefixed
        assert!(p.contains("\nolder one\n"));
        assert!(p.contains("\nnewer one\n"));
        assert!(p.contains(SCISSORS));
    }

    #[test]
    fn preamble_preserves_blank_lines_in_response() {
        let p = build_editor_preamble(&["first\n\nsecond".to_string()]);
        // Response goes in verbatim (unprefixed), blank lines included.
        assert!(
            p.contains("\nfirst\n\nsecond\n"),
            "expected verbatim response with blank line preserved, got:\n{p}"
        );
    }

    #[test]
    fn strip_returns_content_above_scissors() {
        let buf = format!("my prompt line 1\nmy prompt line 2\n\n{SCISSORS}\n// reference");
        assert_eq!(
            strip_from_scissors(&buf),
            "my prompt line 1\nmy prompt line 2\n"
        );
    }

    #[test]
    fn strip_uses_first_scissors_when_multiple_exist() {
        // Defensive: the FIRST scissors wins (user's prompt is above).
        // A stray scissors inside reference content can't hijack the split.
        let buf = format!("real prompt\n{SCISSORS}\n// stuff\n{SCISSORS}\n// more");
        assert_eq!(strip_from_scissors(&buf), "real prompt");
    }

    #[test]
    fn strip_no_scissors_returns_whole_content() {
        // Defensive: if the user deletes the scissors, send what they
        // typed rather than losing it.
        let buf = "just the prompt\nno scissors here";
        assert_eq!(strip_from_scissors(buf), buf);
    }

    #[test]
    fn strip_preserves_markdown_headers_in_prompt() {
        // The whole reason for scissors-based strip over `#`-line
        // filtering: user's markdown headers in the prompt survive.
        let buf = format!("# Real heading\n## Sub\nbody\n{SCISSORS}\n// reference");
        assert_eq!(strip_from_scissors(&buf), "# Real heading\n## Sub\nbody");
    }
}