imp-core 0.1.2

Agent engine for imp: loop, tools, sessions, hooks, context, and SDK
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
use async_trait::async_trait;
use imp_llm::truncate_chars_with_suffix;
use serde_json::json;

use super::edit::apply_edit;
use super::{generate_diff, suggest_similar_files, Tool, ToolContext, ToolOutput};
use crate::error::Result;

pub struct MultiEditTool;

#[async_trait]
impl Tool for MultiEditTool {
    fn name(&self) -> &str {
        "multi_edit"
    }
    fn label(&self) -> &str {
        "Multi Edit"
    }
    fn description(&self) -> &str {
        "Legacy compatibility shim for multi-edit transactions. Prefer the canonical edit tool with edits[]."
    }
    fn parameters(&self) -> serde_json::Value {
        json!({
            "type": "object",
            "properties": {
                "path": { "type": "string", "description": "Default path to edit; may be omitted when each edit includes its own path" },
                "dryRun": { "type": "boolean", "description": "Validate and return combined diff without writing files" },
                "edits": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "path": { "type": "string", "description": "Optional per-edit path for multi-file transactions" },
                            "oldText": { "type": "string" },
                            "newText": { "type": "string" }
                        },
                        "required": ["oldText", "newText"]
                    },
                    "description": "Array of {oldText, newText, path?} edits validated before any file is written"
                }
            },
            "required": ["edits"]
        })
    }
    fn is_readonly(&self) -> bool {
        false
    }

    async fn execute(
        &self,
        _call_id: &str,
        params: serde_json::Value,
        ctx: ToolContext,
    ) -> Result<ToolOutput> {
        let raw_path = params["path"].as_str().unwrap_or("");
        let dry_run = params["dryRun"].as_bool().unwrap_or(false);
        let edits = match params["edits"].as_array() {
            Some(e) if !e.is_empty() => e,
            _ => return Ok(ToolOutput::error("Missing or empty edits array")),
        };

        let mut edits_by_path: std::collections::BTreeMap<String, Vec<&serde_json::Value>> =
            std::collections::BTreeMap::new();
        for edit in edits {
            let edit_path = edit["path"].as_str().unwrap_or(raw_path);
            if edit_path.is_empty() {
                return Ok(ToolOutput::error(
                    "Missing required parameter: path (top-level path or per-edit path)",
                ));
            }
            edits_by_path
                .entry(edit_path.to_string())
                .or_default()
                .push(edit);
        }

        let mut prepared = Vec::new();
        let mut any_fuzzy = false;
        let mut total_edits = 0usize;
        let mut warnings = Vec::new();

        for (edit_path, file_edits) in edits_by_path {
            let path = super::resolve_path(&ctx.cwd, &edit_path);
            if !path.exists() {
                let suggestions = suggest_similar_files(&ctx.cwd, &edit_path);
                let mut msg = format!("File not found: {}", path.display());
                if !suggestions.is_empty() {
                    msg.push_str("\n\nDid you mean:");
                    for s in &suggestions {
                        msg.push_str(&format!("\n  {s}"));
                    }
                }
                return Ok(ToolOutput::error(msg));
            }

            if let Some(warning) = tracker_warning(&ctx, &path) {
                warnings.push(warning);
            }

            let raw_content = tokio::fs::read_to_string(&path).await?;
            let original = raw_content.replace("\r\n", "\n");
            let has_crlf = raw_content.contains("\r\n");

            if let Err(error) = reject_overlapping_exact_edits(&edit_path, &original, &file_edits) {
                return Ok(ToolOutput::error(error.to_string()));
            }

            let mut current = original.clone();
            for (i, edit) in file_edits.iter().enumerate() {
                let old_text = edit["oldText"].as_str().unwrap_or("").replace("\r\n", "\n");
                let new_text = edit["newText"].as_str().unwrap_or("").replace("\r\n", "\n");
                if old_text.is_empty() {
                    return Ok(ToolOutput::error(format!(
                        "Edit {} in {edit_path}: missing oldText",
                        i + 1
                    )));
                }
                match apply_edit(&current, &old_text, &new_text) {
                    Ok((new_content, was_fuzzy)) => {
                        any_fuzzy |= was_fuzzy;
                        current = new_content;
                    }
                    Err(_) => {
                        return Ok(ToolOutput::error(format!(
                            "Edit {} of {} failed in {edit_path}: could not find oldText in file (after applying previous edits).\noldText starts with: {:?}",
                            i + 1,
                            file_edits.len(),
                            truncate_chars_with_suffix(&old_text, 80, "")
                        )));
                    }
                }
            }

            total_edits += file_edits.len();
            let diff = generate_diff(&edit_path, &original, &current);
            let final_content = if has_crlf {
                current.replace('\n', "\r\n")
            } else {
                current.clone()
            };
            prepared.push(PreparedEditFile {
                input_path: edit_path,
                path,
                final_content,
                diff,
                edit_count: file_edits.len(),
            });
        }

        let touched_paths = prepared
            .iter()
            .map(|prepared| prepared.path.clone())
            .collect::<Vec<_>>();
        if !dry_run {
            ctx.checkpoint_state
                .snapshot_paths(&touched_paths, Some("multi_edit transaction".to_string()))?;
            for prepared in &prepared {
                tokio::fs::write(&prepared.path, &prepared.final_content).await?;
                if let Ok(mut tracker) = ctx.file_tracker.lock() {
                    tracker.record_read(&prepared.path);
                }
            }
        }

        let combined_diff = prepared
            .iter()
            .map(|prepared| prepared.diff.as_str())
            .collect::<Vec<_>>()
            .join("\n\n");
        let mut msg = format!(
            "Validated {} edits across {} file(s) as one transaction",
            total_edits,
            prepared.len()
        );
        if dry_run {
            msg.push_str(" (dry run: no changes written)");
        } else {
            msg.push_str(" and applied them");
        }
        msg.push_str("\n\n");
        msg.push_str(&combined_diff);
        if any_fuzzy {
            msg.push_str("\n(some edits used fuzzy matching)");
        }
        for warning in &warnings {
            msg.push('\n');
            msg.push_str(warning);
        }

        Ok(ToolOutput {
            content: vec![imp_llm::ContentBlock::Text { text: msg }],
            details: json!({
                "transaction": true,
                "dry_run": dry_run,
                "files": prepared.iter().map(|prepared| json!({
                    "path": prepared.path.display().to_string(),
                    "input_path": prepared.input_path,
                    "edit_count": prepared.edit_count,
                })).collect::<Vec<_>>(),
                "edit_count": total_edits,
                "edits_applied": if dry_run { 0 } else { total_edits },
                "fuzzy_match": any_fuzzy,
                "checkpoint_created": !dry_run,
            }),
            is_error: false,
        })
    }
}

struct PreparedEditFile {
    input_path: String,
    path: std::path::PathBuf,
    final_content: String,
    diff: String,
    edit_count: usize,
}

fn tracker_warning(ctx: &ToolContext, path: &std::path::Path) -> Option<String> {
    let tracker = ctx.file_tracker.lock().ok()?;
    if !tracker.was_read(path) {
        Some(format!(
            "Warning: editing {} without reading it first. Consider reading to verify current content.",
            path.display()
        ))
    } else if tracker.is_stale(path) {
        Some(format!(
            "Warning: {} was modified externally since last read. Re-read to verify current content.",
            path.display()
        ))
    } else {
        None
    }
}

fn reject_overlapping_exact_edits(
    edit_path: &str,
    original: &str,
    file_edits: &[&serde_json::Value],
) -> Result<()> {
    let mut exact_ranges = Vec::new();
    for (i, edit) in file_edits.iter().enumerate() {
        let old_text = edit["oldText"].as_str().unwrap_or("").replace("\r\n", "\n");
        if old_text.is_empty() {
            continue;
        }
        if let Some(pos) = original.find(&old_text) {
            exact_ranges.push((pos, pos + old_text.len(), i + 1));
        }
    }
    exact_ranges.sort_by_key(|(start, _, _)| *start);
    for pair in exact_ranges.windows(2) {
        let (_, prev_end, prev_idx) = pair[0];
        let (next_start, _, next_idx) = pair[1];
        if next_start < prev_end {
            return Err(crate::error::Error::Tool(format!(
                "Overlapping edits rejected in {edit_path}: edit {prev_idx} overlaps edit {next_idx}. No changes made."
            )));
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tools::ToolContext;
    use std::sync::Arc;

    fn test_ctx(dir: &std::path::Path) -> ToolContext {
        let (tx, _rx) = tokio::sync::mpsc::channel(16);
        let (cmd_tx, _cmd_rx) = tokio::sync::mpsc::channel(16);
        ToolContext {
            cwd: dir.to_path_buf(),
            cancelled: Arc::new(std::sync::atomic::AtomicBool::new(false)),
            update_tx: tx,
            command_tx: cmd_tx,
            ui: Arc::new(crate::ui::NullInterface),
            file_cache: Arc::new(crate::tools::FileCache::new()),
            checkpoint_state: Arc::new(crate::tools::CheckpointState::new()),
            file_tracker: Arc::new(std::sync::Mutex::new(crate::tools::FileTracker::new())),
            anchor_store: Arc::new(crate::tools::AnchorStore::new()),
            lua_tool_loader: None,
            mode: crate::config::AgentMode::Full,
            read_max_lines: 500,
            turn_mana_review: Arc::new(std::sync::Mutex::new(
                crate::mana_review::TurnManaReviewAccumulator::default(),
            )),
            config: Arc::new(crate::config::Config::default()),
        }
    }

    #[tokio::test]
    async fn multi_edit_sequential() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("seq.txt");
        std::fs::write(&file, "aaa\nbbb\nccc\n").unwrap();

        let result = MultiEditTool
            .execute(
                "c1",
                json!({
                    "path": "seq.txt",
                    "edits": [
                        {"oldText": "aaa", "newText": "AAA"},
                        {"oldText": "bbb", "newText": "BBB"}
                    ]
                }),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(!result.is_error);
        let written = std::fs::read_to_string(&file).unwrap();
        assert!(written.contains("AAA"));
        assert!(written.contains("BBB"));
        assert!(written.contains("ccc"));
        assert_eq!(result.details["transaction"], true);
    }

    #[tokio::test]
    async fn multi_edit_atomic_rollback() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("atomic.txt");
        std::fs::write(&file, "foo\nbar\nbaz\n").unwrap();

        let result = MultiEditTool
            .execute(
                "c2",
                json!({
                    "path": "atomic.txt",
                    "edits": [
                        {"oldText": "foo", "newText": "FOO"},
                        {"oldText": "nonexistent", "newText": "X"}
                    ]
                }),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(result.is_error);
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "foo\nbar\nbaz\n");
    }

    #[tokio::test]
    async fn multi_edit_sees_previous_results() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("chain.txt");
        std::fs::write(&file, "hello world\n").unwrap();

        let result = MultiEditTool
            .execute(
                "c3",
                json!({
                    "path": "chain.txt",
                    "edits": [
                        {"oldText": "hello", "newText": "goodbye"},
                        {"oldText": "goodbye world", "newText": "farewell"}
                    ]
                }),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(!result.is_error);
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "farewell\n");
    }

    #[tokio::test]
    async fn multi_edit_creates_checkpoint_snapshot() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("checkpoint.txt");
        std::fs::write(&file, "foo\nbar\n").unwrap();

        let ctx = test_ctx(dir.path());
        let checkpoint_state = ctx.checkpoint_state.clone();
        let result = MultiEditTool
            .execute(
                "c-checkpoint",
                json!({
                    "path": "checkpoint.txt",
                    "edits": [
                        {"oldText": "foo", "newText": "FOO"},
                        {"oldText": "bar", "newText": "BAR"}
                    ]
                }),
                ctx,
            )
            .await
            .unwrap();

        assert!(!result.is_error);
        assert_eq!(
            checkpoint_state.original(&file).as_deref(),
            Some("foo\nbar\n")
        );
        assert_eq!(checkpoint_state.checkpoints().len(), 1);
        assert_eq!(result.details["checkpoint_created"], true);
    }

    #[tokio::test]
    async fn multi_edit_empty_edits_error() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("empty_edits.txt");
        std::fs::write(&file, "content\n").unwrap();

        let result = MultiEditTool
            .execute(
                "c5",
                json!({"path": "empty_edits.txt", "edits": []}),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(result.is_error);
    }

    #[tokio::test]
    async fn multi_edit_missing_path_error() {
        let dir = tempfile::tempdir().unwrap();

        let result = MultiEditTool
            .execute(
                "c6",
                json!({"edits": [{"oldText": "a", "newText": "b"}]}),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(result.is_error);
    }

    #[tokio::test]
    async fn multi_edit_chained_three_edits() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("chain3.txt");
        std::fs::write(&file, "apple banana cherry\n").unwrap();

        let result = MultiEditTool
            .execute(
                "c7",
                json!({
                    "path": "chain3.txt",
                    "edits": [
                        {"oldText": "apple", "newText": "APPLE"},
                        {"oldText": "APPLE banana", "newText": "FRUIT"},
                        {"oldText": "cherry", "newText": "CHERRY"}
                    ]
                }),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(!result.is_error);
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "FRUIT CHERRY\n");
    }

    #[tokio::test]
    async fn multi_edit_combined_diff() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("diff.txt");
        std::fs::write(&file, "alpha\nbeta\ngamma\n").unwrap();

        let result = MultiEditTool
            .execute(
                "c4",
                json!({
                    "path": "diff.txt",
                    "edits": [
                        {"oldText": "alpha", "newText": "ALPHA"},
                        {"oldText": "gamma", "newText": "GAMMA"}
                    ]
                }),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(!result.is_error);
        let text = result.text_content().unwrap();
        assert!(text.contains("ALPHA"));
        assert!(text.contains("GAMMA"));
    }

    #[tokio::test]
    async fn multi_edit_can_edit_two_files_transactionally() {
        let dir = tempfile::tempdir().unwrap();
        let one = dir.path().join("one.txt");
        let two = dir.path().join("two.txt");
        std::fs::write(&one, "alpha\n").unwrap();
        std::fs::write(&two, "beta\n").unwrap();

        let result = MultiEditTool
            .execute(
                "c-multi-file",
                json!({
                    "edits": [
                        {"path": "one.txt", "oldText": "alpha", "newText": "ALPHA"},
                        {"path": "two.txt", "oldText": "beta", "newText": "BETA"}
                    ]
                }),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(!result.is_error);
        assert_eq!(std::fs::read_to_string(&one).unwrap(), "ALPHA\n");
        assert_eq!(std::fs::read_to_string(&two).unwrap(), "BETA\n");
        assert_eq!(result.details["files"].as_array().unwrap().len(), 2);
    }

    #[tokio::test]
    async fn multi_edit_rejects_overlaps_without_writing() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("overlap.txt");
        std::fs::write(&file, "abcdef\n").unwrap();

        let result = MultiEditTool
            .execute(
                "c-overlap",
                json!({
                    "path": "overlap.txt",
                    "edits": [
                        {"oldText": "abc", "newText": "ABC"},
                        {"oldText": "bc", "newText": "BC"}
                    ]
                }),
                test_ctx(dir.path()),
            )
            .await
            .unwrap();

        assert!(result.is_error);
        assert!(result.text_content().unwrap().contains("Overlapping edits"));
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "abcdef\n");
    }

    #[tokio::test]
    async fn multi_edit_dry_run_writes_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("dry.txt");
        std::fs::write(&file, "alpha\n").unwrap();
        let ctx = test_ctx(dir.path());

        let result = MultiEditTool
            .execute(
                "c-dry",
                json!({
                    "path": "dry.txt",
                    "dryRun": true,
                    "edits": [{"oldText": "alpha", "newText": "ALPHA"}]
                }),
                ctx.clone(),
            )
            .await
            .unwrap();

        assert!(!result.is_error);
        assert_eq!(std::fs::read_to_string(&file).unwrap(), "alpha\n");
        assert!(ctx.checkpoint_state.checkpoints().is_empty());
        assert_eq!(result.details["dry_run"], true);
    }
}