rpi-tools 0.36.2

Built-in agent tools (read/write/edit/bash/powershell) + ExecutionEnv, Rust port of pi harness tools
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
//! The write tool now returns a real diff in `details` (same shape as edit):
//! `diff` (display-oriented, line-number prefixed), `patch` (unified), and
//! `first_changed_line`. Hosts render collapsed write rows from it instead of
//! guessing `+N` from the content length.
//!
//! Also pins the bash/powershell `description` schema extension: hosts show it
//! in collapsed tool rows, so the property must stay in the tool schema.

use std::sync::Arc;
use std::time::{Duration, Instant};

use rpi_agent::agent_tool::AgentTool;
use rpi_tools::tools::edit_diff::{generate_diff_string_budgeted, generate_unified_patch_budgeted};
use rpi_tools::{
    create_bash_tool, create_powershell_tool, create_write_tool, ExecutionToolContext, FileSystem,
    InMemoryExecutionEnv,
};
use serde_json::json;
use tokio_util::sync::CancellationToken;

fn fresh_context() -> (Arc<InMemoryExecutionEnv>, ExecutionToolContext) {
    let env = Arc::new(InMemoryExecutionEnv::with_cwd("/tmp/work".into()));
    let env_dyn: Arc<dyn rpi_tools::ExecutionEnv> = env.clone();
    let mut_env: Arc<dyn rpi_tools::MutatingEnv> = env.clone();
    let ctx = ExecutionToolContext::new(env_dyn, Some(mut_env));
    (env, ctx)
}

async fn run_write(
    tool: Arc<dyn AgentTool>,
    path: &str,
    content: &str,
) -> rpi_agent::types::AgentToolResult {
    tool.execute(
        "write-x",
        json!({ "path": path, "content": content }),
        CancellationToken::new(),
        Arc::new(|_p| ()),
    )
    .await
    .expect("write succeeds")
}

#[tokio::test]
async fn create_diff_lists_every_line_as_added() {
    let (_env, ctx) = fresh_context();
    let tool = create_write_tool(&ctx);
    let result = run_write(tool, "notes.txt", "alpha\nbeta\n").await;

    let diff = result.details["diff"].as_str().expect("details.diff");
    let added = diff.lines().filter(|l| l.starts_with('+')).count();
    let removed = diff.lines().filter(|l| l.starts_with('-')).count();
    assert_eq!((added, removed), (2, 0), "diff was: {diff}");
    assert!(diff.contains("alpha"));
    assert!(diff.contains("beta"));

    let patch = result.details["patch"].as_str().expect("details.patch");
    assert!(patch.contains("--- notes.txt"), "patch was: {patch}");
    assert!(patch.contains("+++ notes.txt"));
    assert_eq!(result.details["diff_skipped"], serde_json::Value::Null);
}

#[tokio::test]
async fn overwrite_diff_reports_real_adds_and_removes() {
    let (env, ctx) = fresh_context();
    let abs = env.absolute_path("notes.txt", None).await.unwrap();
    env.seed_file(&abs.to_string_lossy(), b"alpha\nbeta\ngamma\n".to_vec())
        .await;

    let tool = create_write_tool(&ctx);
    let result = run_write(tool, "notes.txt", "alpha\nBETA\ngamma\ndelta\n").await;

    let diff = result.details["diff"].as_str().expect("details.diff");
    let added = diff.lines().filter(|l| l.starts_with('+')).count();
    let removed = diff.lines().filter(|l| l.starts_with('-')).count();
    // beta → BETA is a replace (1 removed + 1 added); delta is an insertion.
    assert_eq!((added, removed), (2, 1), "diff was: {diff}");
    assert_eq!(result.details["first_changed_line"], json!(2));
}

#[tokio::test]
async fn native_preview_read_uses_a_byte_limit() {
    let dir = tempfile::tempdir().unwrap();
    let env = rpi_tools::OsExecutionEnv::with_cwd(dir.path().to_path_buf());
    std::fs::write(dir.path().join("note.txt"), "你好").unwrap();
    assert_eq!(
        env.read_text_file_bounded("note.txt", 6, None)
            .await
            .unwrap(),
        Some("你好".into())
    );
    assert_eq!(
        env.read_text_file_bounded("note.txt", 5, None)
            .await
            .unwrap(),
        None
    );
}

#[cfg(unix)]
#[tokio::test]
async fn oversized_symlink_target_is_skipped_before_utf8_decode() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join("target.txt");
    let alias = dir.path().join("alias.txt");
    let mut old = vec![b'a'; 8 * 1024 * 1024];
    old.push(0xff);
    std::fs::write(&target, old).unwrap();
    std::os::unix::fs::symlink("target.txt", &alias).unwrap();

    let env = Arc::new(rpi_tools::OsExecutionEnv::with_cwd(
        dir.path().to_path_buf(),
    ));
    let ctx = ExecutionToolContext::new(env.clone(), Some(env));
    let result = run_write(create_write_tool(&ctx), "alias.txt", "new").await;

    assert_eq!(std::fs::read(&target).unwrap(), b"new");
    assert!(std::fs::symlink_metadata(&alias).unwrap().is_symlink());
    assert_eq!(result.details["diff_skipped"], json!("content_too_large"));
}

#[tokio::test]
async fn unchanged_overwrite_has_empty_diff() {
    let (env, ctx) = fresh_context();
    let abs = env.absolute_path("same.txt", None).await.unwrap();
    env.seed_file(&abs.to_string_lossy(), b"same\n".to_vec())
        .await;

    let tool = create_write_tool(&ctx);
    let result = run_write(tool, "same.txt", "same\n").await;

    assert_eq!(result.details["diff"], json!(""));
    assert_eq!(
        result.details["first_changed_line"],
        serde_json::Value::Null
    );
}

/// 20k lines of completely different content per side (~1 MB total, well
/// under the 2 MiB cap). This is the size class the PR review measured at
/// multiple seconds for two Myers passes.
fn wide_replacement(lines: usize) -> (String, String) {
    let old = (0..lines)
        .map(|i| format!("old line {i:05} lorem ipsum dolor sit amet"))
        .collect::<Vec<_>>()
        .join("\n");
    let new = (0..lines)
        .map(|i| format!("new line {i:05} consectetur adipiscing elit"))
        .collect::<Vec<_>>()
        .join("\n");
    (old, new)
}

#[test]
fn budgeted_diffs_bail_out_on_exhausted_budget() {
    let (old, new) = wide_replacement(20_000);
    assert!(
        old.len() + new.len() < 2 * 1024 * 1024,
        "fixture must stay under MAX_DIFF_INPUT_BYTES"
    );

    let started = Instant::now();
    assert!(
        generate_diff_string_budgeted(&old, &new, 4, Duration::from_millis(1)).is_none(),
        "display diff must be skipped when the budget is exhausted"
    );
    assert!(
        generate_unified_patch_budgeted("big.txt", &old, &new, Duration::from_millis(1)).is_none(),
        "unified patch must be skipped when the budget is exhausted"
    );
    assert!(
        started.elapsed() < Duration::from_secs(2),
        "budgeted diffs must return promptly, took {:?}",
        started.elapsed()
    );
}

#[tokio::test]
async fn write_large_full_replacement_skips_diff() {
    let (env, ctx) = fresh_context();
    let abs = env.absolute_path("big.txt", None).await.unwrap();
    let (old, new) = wide_replacement(20_000);
    env.seed_file(&abs.to_string_lossy(), old.into_bytes())
        .await;

    let tool = create_write_tool(&ctx);
    let started = Instant::now();
    let result = run_write(tool, "big.txt", &new).await;

    assert_eq!(
        result.details["diff_skipped"],
        json!("timeout"),
        "large replacement must report diff_skipped=timeout; details: {}",
        result.details
    );
    assert!(result.details["diff"].is_null());
    assert!(
        started.elapsed() < Duration::from_secs(5),
        "write must not spend unbounded time on the diff, took {:?}",
        started.elapsed()
    );
}

#[tokio::test]
async fn bash_and_powershell_schemas_expose_description() {
    let (_env, ctx) = fresh_context();

    for tool in [create_bash_tool(&ctx, None), create_powershell_tool(&ctx)] {
        let schema = &tool.schema().parameters.0;
        let prop = &schema["properties"]["description"];
        assert!(
            prop.is_object(),
            "{} schema is missing the description property: {schema}",
            tool.schema().name
        );
        assert!(
            prop["description"].as_str().is_some_and(|d| !d.is_empty()),
            "{} description property needs a schema description",
            tool.schema().name
        );
    }
}

#[tokio::test]
async fn mutation_preview_counts_blank_rows() {
    let (env, ctx) = fresh_context();
    env.seed_file("/tmp/work/notes.txt", b"alpha\nbeta\n".to_vec())
        .await;

    let result = run_write(create_write_tool(&ctx), "notes.txt", "alpha\n\nbeta\n").await;
    assert_eq!(result.details["diff"], json!(" 1 alpha\n+2 \n 2 beta"));
    assert_eq!(result.details["first_changed_line"], json!(2));
}

#[tokio::test]
async fn mutation_preview_handles_carriage_return_line_endings() {
    let (env, ctx) = fresh_context();
    env.seed_file("/tmp/work/notes.txt", b"alpha\rbeta\r".to_vec())
        .await;

    let result = run_write(create_write_tool(&ctx), "notes.txt", "alpha\rBETA\rgamma\r").await;
    assert_eq!(
        result.details["diff"],
        json!(" 1 alpha\n-2 beta\n+2 BETA\n+3 gamma"),
        "preview details: {}",
        result.details
    );
    assert_eq!(result.details["first_changed_line"], json!(2));
}

#[tokio::test]
async fn mutation_preview_has_a_combined_output_byte_limit() {
    let (env, ctx) = fresh_context();
    for (path, row, lines) in [
        ("many-lines.txt", "x\n", 50_000),
        ("combined.txt", "abcdefghijklmnop\n", 8_000),
    ] {
        let content = row.repeat(lines);
        let result = run_write(create_write_tool(&ctx), path, &content).await;

        assert_eq!(env.read_text_file(path, None).await.unwrap(), content);
        let display_bytes = result.details["diff"].as_str().map(str::len);
        let patch_bytes = result.details["patch"].as_str().map(str::len);
        assert_eq!(
            result.details["diff_skipped"],
            json!("output_too_large"),
            "{path}: display diff {display_bytes:?} bytes, patch {patch_bytes:?} bytes"
        );
        assert_eq!(
            result.details["line_changes"],
            json!({"added": lines, "removed": 0})
        );
        assert!(display_bytes.is_none());
        assert!(patch_bytes.is_none());
    }
}

fn assert_patch_reproduces_write(original: &str, patched: &str, patch: &str) {
    use std::io::Write;
    use std::process::{Command, Stdio};

    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("note.txt");
    std::fs::write(&file, original).unwrap();
    let mut child = Command::new("git")
        .args(["apply", "--whitespace=nowarn", "-p0", "-"])
        .current_dir(dir.path())
        .stdin(Stdio::piped())
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .take()
        .unwrap()
        .write_all(patch.as_bytes())
        .unwrap();
    let outcome = child.wait_with_output().unwrap();
    assert!(
        outcome.status.success(),
        "git apply rejected preview: {}; patch: {patch:?}",
        String::from_utf8_lossy(&outcome.stderr)
    );
    assert_eq!(std::fs::read(&file).unwrap(), patched.as_bytes());
}

#[tokio::test]
async fn edit_patch_preserves_actual_bom_and_crlf_bytes() {
    let (env, ctx) = fresh_context();
    let original = "\u{feff}alpha\r\nbeta\r\n";
    env.seed_file("/tmp/work/note.txt", original.as_bytes().to_vec())
        .await;
    let tool = rpi_tools::create_edit_tool(&ctx);
    let result = tool
        .execute(
            "edit-crlf",
            json!({"path":"note.txt","edits":[{"oldText":"beta","newText":"BETA"}]}),
            CancellationToken::new(),
            Arc::new(|_| ()),
        )
        .await
        .unwrap();
    let written = env.read_text_file("note.txt", None).await.unwrap();
    assert_eq!(written, "\u{feff}alpha\r\nBETA\r\n");
    assert_eq!(
        result.details["line_changes"],
        json!({"added":1,"removed":1})
    );
    assert_patch_reproduces_write(
        original,
        &written,
        result.details["patch"].as_str().unwrap(),
    );
}

#[tokio::test]
async fn write_patch_reproduces_mixed_and_bare_cr_bytes() {
    let (env, ctx) = fresh_context();
    let original = "alpha\rbeta\nkeep\r";
    env.seed_file("/tmp/work/note.txt", original.as_bytes().to_vec())
        .await;
    let tool = create_write_tool(&ctx);
    let replacement = "alpha\rBETA\nkeep\rgamma\r";
    let result = run_write(tool.clone(), "note.txt", replacement).await;
    let written = env.read_text_file("note.txt", None).await.unwrap();
    assert_eq!(written, replacement);
    assert_eq!(
        result.details["line_changes"],
        json!({"added":2,"removed":1})
    );
    assert_patch_reproduces_write(
        original,
        &written,
        result.details["patch"].as_str().unwrap(),
    );

    let appended = format!("{written}delta\r");
    let result = run_write(tool, "note.txt", &appended).await;
    let actual = env.read_text_file("note.txt", None).await.unwrap();
    assert_eq!(actual, appended);
    assert_eq!(
        result.details["line_changes"],
        json!({"added":1,"removed":0})
    );
    assert_patch_reproduces_write(&written, &actual, result.details["patch"].as_str().unwrap());
}

#[test]
fn identical_write_reports_zero_without_waiting_for_preview_workers() {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .max_blocking_threads(1)
        .build()
        .unwrap();
    runtime.block_on(async {
        let (env, ctx) = fresh_context();
        let content = "x\n".repeat(300_000);
        env.seed_file("/tmp/work/note.txt", content.as_bytes().to_vec())
            .await;

        let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
        let (release_tx, release_rx) = std::sync::mpsc::channel();
        let occupied = tokio::task::spawn_blocking(move || {
            entered_tx.send(()).unwrap();
            release_rx.recv().unwrap();
        });
        entered_rx.await.unwrap();

        let write = run_write(create_write_tool(&ctx), "note.txt", &content);
        tokio::pin!(write);
        let result = futures::poll!(&mut write);
        release_tx.send(()).unwrap();
        occupied.await.unwrap();
        let std::task::Poll::Ready(result) = result else {
            panic!("an identical write waited for the diff worker");
        };
        assert_eq!(
            result.details["line_changes"],
            json!({"added":0,"removed":0})
        );
        assert_eq!(result.details["diff"], "");
        assert_eq!(result.details["patch"], "");
    });
}