koda-core 0.2.19

Core engine for the Koda AI coding agent (macOS and Linux only)
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
//! Pre-flight validation for tool calls.
//!
//! Runs **before** the approval prompt so we never ask the user to approve
//! an operation that will inevitably fail. Cheap checks only — no mutations.
//!
//! ## What it validates
//!
//! - **Write**: target path resolves within project root
//! - **Write (overwrite)**: file exists and `overwrite: true` is set
//! - **Edit**: file exists, `old_str` is found, `old_str` is unique
//!   (unless `replace_all: true`), `new_str` does not contain omission
//!   placeholders (e.g. `// rest of code ...`)
//! - **Delete**: file exists
//! - **Bash**: command is non-empty
//!
//! Validation errors are returned as tool results (not panics), so the
//! model sees the error and can self-correct.

use super::safe_resolve_path;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::time::SystemTime;

/// Format a duration into a compact human-readable age string.
///
/// ```text
/// <5s  → "just now"
/// <60s → "12s ago"
/// else → "3m ago"
/// ```
fn fmt_age(age: std::time::Duration) -> String {
    let secs = age.as_secs();
    if secs < 5 {
        "just now".to_string()
    } else if secs < 60 {
        format!("{secs}s ago")
    } else {
        format!("{}m ago", secs / 60)
    }
}

/// Validate a tool call before approval.
///
/// `read_cache` is the session file-read cache.  When provided, `validate_edit`
/// uses it to detect files that have been modified on disk since the model last
/// read them — catching the most common source of lost-context edits.
///
/// `last_writer` and `last_bash` add context to staleness errors: instead of a
/// generic "file was modified" message the model sees which tool was responsible
/// and how long ago it ran (#804 item 7).
///
/// Returns `None` if the call looks valid, or `Some(error_message)` describing
/// why it will fail. The error message is fed back to the model so it can
/// self-correct without consuming an approval prompt.
pub async fn validate_tool_call(
    tool_name: &str,
    args: &serde_json::Value,
    project_root: &Path,
    read_cache: Option<&super::FileReadCache>,
    last_writer: Option<&super::LastWriterCache>,
    last_bash: Option<&super::LastBashCache>,
) -> Option<String> {
    match tool_name {
        "Edit" => validate_edit(args, project_root, read_cache, last_writer, last_bash).await,
        "Write" => validate_write(args, project_root).await,
        "Delete" => validate_delete(args, project_root).await,
        "Bash" => validate_bash(args),
        _ => None,
    }
}

/// DRY wrapper: pull the three caches from a `ToolRegistry` and run
/// the standard pre-flight validation against the given root.
///
/// Three call sites used to inline the same 9-line cache-pull-then-
/// call-validate dance:
///
///   * `tool_dispatch::validate_then_execute_one_tool` (parallel +
///     split-batch arms, validates after auto-approval)
///   * `tool_dispatch::execute_tools_sequential` (sequential arm,
///     validates before approval prompting so we don't bother the
///     user with doomed prompts)
///   * `sub_agent_dispatch::execute_sub_agent` (sub-agent loop,
///     validates before per-tool approval branch)
///
/// `project_root` is taken explicitly because the sub-agent path
/// validates against its (possibly worktree-shifted) effective root,
/// not the registry's `project_root`. Everything else is mechanical
/// cache plumbing that's identical across call sites.
pub async fn validate_with_registry(
    registry: &super::ToolRegistry,
    tool_name: &str,
    args: &serde_json::Value,
    project_root: &Path,
) -> Option<String> {
    let read_cache = registry.file_read_cache();
    let last_writer = registry.last_writer_cache();
    let last_bash = registry.last_bash_cache();
    validate_tool_call(
        tool_name,
        args,
        project_root,
        Some(&read_cache),
        Some(&last_writer),
        Some(&last_bash),
    )
    .await
}

/// Build a parenthetical hint describing what tool last modified a file.
///
/// Priority:
/// 1. A recorded Write/Edit entry for this exact path  → " (last written by Edit 3s ago)"
/// 2. A recent Bash invocation (possible indirect modifier) → " (Bash ran 2s ago: `cargo fmt ...`)"
/// 3. Neither known                                        → "" (empty; generic message is fine)
fn writer_hint(
    resolved: &PathBuf,
    last_writer: Option<&super::LastWriterCache>,
    last_bash: Option<&super::LastBashCache>,
) -> String {
    // Check for a direct Write/Edit record for this path.
    if let Some(lw) = last_writer
        && let Ok(guard) = lw.lock()
        && let Some((tool, when)) = guard.get(resolved)
    {
        return format!(" (last written by {} {})", tool, fmt_age(when.elapsed()));
    }
    // Fall back to the most recent Bash call — it may have modified the file
    // indirectly (formatter, build script, etc.).
    if let Some(lb) = last_bash
        && let Ok(guard) = lb.lock()
        && let Some((snippet, when)) = guard.as_ref()
    {
        return format!(" (Bash ran {}: `{}`)", fmt_age(when.elapsed()), snippet);
    }
    String::new()
}

/// Edit: file must exist, replacements must be non-empty, each old_str must
/// be non-empty and actually present in the file.  Also warns if the file has
/// been modified on disk since the model last read it.
async fn validate_edit(
    args: &serde_json::Value,
    project_root: &Path,
    read_cache: Option<&super::FileReadCache>,
    last_writer: Option<&super::LastWriterCache>,
    last_bash: Option<&super::LastBashCache>,
) -> Option<String> {
    let path_str = args["file_path"]
        .as_str()
        .or_else(|| args["path"].as_str())
        .unwrap_or("");
    if path_str.is_empty() {
        return Some("Missing 'file_path' argument.".into());
    }

    let resolved = match safe_resolve_path(project_root, path_str) {
        Ok(p) => p,
        Err(e) => return Some(format!("Invalid path: {e}")),
    };

    let replacements = match args["replacements"].as_array() {
        Some(arr) if !arr.is_empty() => arr,
        Some(_) => return Some("'replacements' array is empty.".into()),
        None => return Some("Missing 'replacements' argument.".into()),
    };

    // File must exist (Edit is not Write)
    let content = match tokio::fs::read_to_string(&resolved).await {
        Ok(c) => c,
        Err(e) => {
            return Some(format!(
                "Cannot read '{}': {e}. Use Write to create new files.",
                path_str
            ));
        }
    };

    // Stale-file detection: warn if the file has been modified on disk since
    // the model last read it.  Only fires when a full-read cache entry exists
    // and the current mtime differs from the cached one.
    if let Some(cache) = read_cache
        && let Ok(meta) = tokio::fs::metadata(&resolved).await
    {
        let current_mtime = meta.modified().unwrap_or(SystemTime::UNIX_EPOCH);
        let cache_key = format!("{}:None:None", resolved.display());
        let cached_mtime = cache
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .get(&cache_key)
            .map(|(_, mtime, _)| *mtime);
        if let Some(cm) = cached_mtime
            && cm != current_mtime
        {
            // Build a context hint naming the responsible tool so the model
            // doesn't have to guess why the file changed (#804 item 7).
            let hint = writer_hint(&resolved, last_writer, last_bash);
            return Some(format!(
                "File '{path_str}' has been modified on disk since you last read it{hint}. \
                 Read it again to get the current content before editing.",
            ));
        }
    }

    // Validate each replacement
    for (i, replacement) in replacements.iter().enumerate() {
        let old_str = match replacement["old_str"].as_str() {
            Some(s) if !s.is_empty() => s,
            Some(_) => {
                return Some(format!("Replacement {i}: 'old_str' cannot be empty."));
            }
            None => {
                return Some(format!("Replacement {i}: missing 'old_str'."));
            }
        };

        let new_str = match replacement["new_str"].as_str() {
            Some(s) => s,
            None => {
                return Some(format!("Replacement {i}: missing 'new_str'."));
            }
        };

        // Omission placeholder detection: catch lazy model output like
        // "// rest of code ..." or "(unchanged methods ...)" before it
        // silently replaces real code with a comment.
        if let Some(msg) = detect_new_omission_placeholder(old_str, new_str, i) {
            return Some(msg);
        }

        if !content.contains(old_str) {
            // Try fuzzy (whitespace-normalized) before hard-failing.
            let ranges = super::fuzzy::fuzzy_match_ranges(old_str, &content);
            if ranges.is_empty() {
                return Some(format!(
                    "Replacement {i}: 'old_str' not found in '{}'. \
                     Read the file first to get the exact text.",
                    path_str
                ));
            }
            // 2+ fuzzy matches is also a problem — flag it now so the model
            // can tighten the snippet before burning an approval prompt.
            if ranges.len() > 1 {
                return Some(format!(
                    "Replacement {i}: 'old_str' is ambiguous — {} fuzzy matches in '{}'. \
                     Use a more specific snippet.",
                    ranges.len(),
                    path_str
                ));
            }
        }
    }

    None
}

/// Write: catch overwrite-without-flag before approval.
async fn validate_write(args: &serde_json::Value, project_root: &Path) -> Option<String> {
    let path_str = args["file_path"]
        .as_str()
        .or_else(|| args["path"].as_str())
        .unwrap_or("");
    if path_str.is_empty() {
        return Some("Missing 'file_path' argument.".into());
    }

    if args["content"].as_str().is_none() {
        return Some("Missing 'content' argument.".into());
    }

    let resolved = match safe_resolve_path(project_root, path_str) {
        Ok(p) => p,
        Err(e) => return Some(format!("Invalid path: {e}")),
    };

    let overwrite = args["overwrite"].as_bool().unwrap_or(false);
    if resolved.exists() && !overwrite {
        return Some(format!(
            "File '{}' already exists. Set overwrite=true to replace it, \
             or use Edit for targeted changes.",
            path_str
        ));
    }

    None
}

/// Delete: path must exist.
async fn validate_delete(args: &serde_json::Value, project_root: &Path) -> Option<String> {
    let path_str = args["file_path"]
        .as_str()
        .or_else(|| args["path"].as_str())
        .unwrap_or("");
    if path_str.is_empty() {
        return Some("Missing 'file_path' argument.".into());
    }

    let resolved = match safe_resolve_path(project_root, path_str) {
        Ok(p) => p,
        Err(e) => return Some(format!("Invalid path: {e}")),
    };

    if !resolved.exists() {
        return Some(format!("Path not found: '{path_str}'. Nothing to delete."));
    }

    // Non-empty dir without recursive flag
    if resolved.is_dir() {
        let is_empty = resolved
            .read_dir()
            .map(|mut d| d.next().is_none())
            .unwrap_or(false);
        let recursive = args["recursive"].as_bool().unwrap_or(false);
        if !is_empty && !recursive {
            return Some(format!(
                "Directory '{}' is not empty. Set recursive=true to delete it.",
                path_str
            ));
        }
    }

    None
}

/// Bash: command must be non-empty.
fn validate_bash(args: &serde_json::Value) -> Option<String> {
    let cmd = args["command"]
        .as_str()
        .or_else(|| args["cmd"].as_str())
        .unwrap_or("");
    if cmd.trim().is_empty() {
        return Some("Missing or empty 'command' argument.".into());
    }
    None
}

// ── Omission placeholder detection ────────────────────────────

/// Known omission phrase prefixes (lowercase, before the `...`).
const OMISSION_PREFIXES: &[&str] = &[
    "rest of",
    "rest of code",
    "rest of method",
    "rest of methods",
    "rest of file",
    "rest of function",
    "rest of implementation",
    "existing code",
    "existing implementation",
    "unchanged code",
    "unchanged method",
    "unchanged methods",
    "remaining code",
    "remaining implementation",
];

/// Check if `new_str` introduces an omission placeholder not present in `old_str`.
///
/// Returns an error message if the model is being lazy, or `None` if clean.
fn detect_new_omission_placeholder(
    old_str: &str,
    new_str: &str,
    replacement_idx: usize,
) -> Option<String> {
    let new_placeholders = detect_omission_placeholders(new_str);
    if new_placeholders.is_empty() {
        return None;
    }
    // If old_str already had the same placeholder, the model is preserving
    // an existing comment — that's fine.
    let old_set: HashSet<String> = detect_omission_placeholders(old_str).into_iter().collect();
    for p in &new_placeholders {
        if !old_set.contains(p) {
            return Some(format!(
                "Replacement {replacement_idx}: 'new_str' contains an omission placeholder \
                 ('{p}'). Write the actual code instead of abbreviating with comments."
            ));
        }
    }
    None
}

/// Scan text for lines that look like omission placeholders.
///
/// Recognized patterns:
/// - `// rest of code ...`
/// - `# unchanged methods ...`
/// - `(rest of implementation ...)`
/// - `// (existing code ...)`
///
/// Returns normalized placeholder strings (e.g. `"rest of code ..."`).
fn detect_omission_placeholders(text: &str) -> Vec<String> {
    let mut found = Vec::new();
    for line in text.lines() {
        if let Some(normalized) = normalize_placeholder_line(line) {
            found.push(normalized);
        }
    }
    found
}

/// Try to parse a single line as an omission placeholder.
///
/// Strips comment prefixes (`//`, `#`), optional parentheses, then checks
/// for a known phrase followed by `...`.
fn normalize_placeholder_line(line: &str) -> Option<String> {
    let mut text = line.trim();
    if text.is_empty() {
        return None;
    }

    // Strip comment prefix
    if let Some(rest) = text.strip_prefix("//") {
        text = rest.trim();
    } else if let Some(rest) = text.strip_prefix('#') {
        text = rest.trim();
    }

    // Strip optional parentheses: (rest of code ...)
    if text.starts_with('(') && text.ends_with(')') {
        text = &text[1..text.len() - 1];
        text = text.trim();
    }

    // Must contain "..."
    let ellipsis_pos = text.find("...")?;
    let prefix = text[..ellipsis_pos].trim();
    let suffix = text[ellipsis_pos + 3..].trim();

    // Suffix must be empty or all dots ("...." is fine)
    if !suffix.is_empty() && !suffix.chars().all(|c| c == '.') {
        return None;
    }

    // Normalize whitespace in prefix and check against known phrases
    let normalized: String = prefix.split_whitespace().collect::<Vec<_>>().join(" ");
    let lower = normalized.to_lowercase();

    if OMISSION_PREFIXES.contains(&lower.as_str()) {
        Some(format!("{lower} ..."))
    } else {
        None
    }
}

// ── Tests ─────────────────────────────────────────────────────

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

    fn setup() -> TempDir {
        let dir = TempDir::new().unwrap();
        std::fs::write(
            dir.path().join("hello.txt"),
            "line one\nline two\nline three\n",
        )
        .unwrap();
        std::fs::create_dir(dir.path().join("subdir")).unwrap();
        std::fs::write(dir.path().join("subdir/nested.txt"), "nested").unwrap();
        dir
    }

    // ── Edit validation ───────────────────────────────────────

    #[tokio::test]
    async fn edit_valid_replacement() {
        let dir = setup();
        let args = json!({
            "path": "hello.txt",
            "replacements": [{"old_str": "line two", "new_str": "line TWO"}]
        });
        assert!(
            validate_edit(&args, dir.path(), None, None, None)
                .await
                .is_none()
        );
    }

    #[tokio::test]
    async fn edit_missing_path() {
        let dir = setup();
        let args = json!({"replacements": [{"old_str": "x", "new_str": "y"}]});
        let err = validate_edit(&args, dir.path(), None, None, None)
            .await
            .unwrap();
        assert!(err.contains("path"), "{err}");
    }

    #[tokio::test]
    async fn edit_file_not_found() {
        let dir = setup();
        let args = json!({
            "path": "nope.txt",
            "replacements": [{"old_str": "x", "new_str": "y"}]
        });
        let err = validate_edit(&args, dir.path(), None, None, None)
            .await
            .unwrap();
        assert!(err.contains("Cannot read"), "{err}");
        assert!(err.contains("Write"), "{err}"); // suggests Write
    }

    #[tokio::test]
    async fn edit_empty_replacements() {
        let dir = setup();
        let args = json!({"path": "hello.txt", "replacements": []});
        let err = validate_edit(&args, dir.path(), None, None, None)
            .await
            .unwrap();
        assert!(err.contains("empty"), "{err}");
    }

    #[tokio::test]
    async fn edit_empty_old_str() {
        let dir = setup();
        let args = json!({
            "path": "hello.txt",
            "replacements": [{"old_str": "", "new_str": "y"}]
        });
        let err = validate_edit(&args, dir.path(), None, None, None)
            .await
            .unwrap();
        assert!(err.contains("empty"), "{err}");
    }

    #[tokio::test]
    async fn edit_old_str_fuzzy_match_passes_validation() {
        // File has trailing spaces; model sends clean needle — should pass pre-flight.
        let dir = TempDir::new().unwrap();
        std::fs::write(
            dir.path().join("hello.txt"),
            "line one   \nline two   \nline three\n",
        )
        .unwrap();
        let args = json!({
            "path": "hello.txt",
            "replacements": [{"old_str": "line two", "new_str": "LINE TWO"}]
        });
        assert!(
            validate_edit(&args, dir.path(), None, None, None)
                .await
                .is_none(),
            "fuzzy match should pass validation"
        );
    }

    #[tokio::test]
    async fn edit_old_str_not_found() {
        let dir = setup();
        let args = json!({
            "path": "hello.txt",
            "replacements": [{"old_str": "does not exist", "new_str": "y"}]
        });
        let err = validate_edit(&args, dir.path(), None, None, None)
            .await
            .unwrap();
        assert!(err.contains("not found"), "{err}");
    }

    #[tokio::test]
    async fn edit_missing_new_str() {
        let dir = setup();
        let args = json!({
            "path": "hello.txt",
            "replacements": [{"old_str": "line one"}]
        });
        let err = validate_edit(&args, dir.path(), None, None, None)
            .await
            .unwrap();
        assert!(err.contains("new_str"), "{err}");
    }

    // ── Write validation ──────────────────────────────────────

    #[tokio::test]
    async fn write_new_file_valid() {
        let dir = setup();
        let args = json!({"path": "brand_new.txt", "content": "hello"});
        assert!(validate_write(&args, dir.path()).await.is_none());
    }

    #[tokio::test]
    async fn write_existing_without_overwrite() {
        let dir = setup();
        let args = json!({"path": "hello.txt", "content": "replaced"});
        let err = validate_write(&args, dir.path()).await.unwrap();
        assert!(err.contains("already exists"), "{err}");
        assert!(err.contains("overwrite=true"), "{err}");
    }

    #[tokio::test]
    async fn write_existing_with_overwrite() {
        let dir = setup();
        let args = json!({"path": "hello.txt", "content": "replaced", "overwrite": true});
        assert!(validate_write(&args, dir.path()).await.is_none());
    }

    #[tokio::test]
    async fn write_missing_content() {
        let dir = setup();
        let args = json!({"path": "foo.txt"});
        let err = validate_write(&args, dir.path()).await.unwrap();
        assert!(err.contains("content"), "{err}");
    }

    // ── Delete validation ─────────────────────────────────────

    #[tokio::test]
    async fn delete_valid_file() {
        let dir = setup();
        let args = json!({"path": "hello.txt"});
        assert!(validate_delete(&args, dir.path()).await.is_none());
    }

    #[tokio::test]
    async fn delete_not_found() {
        let dir = setup();
        let args = json!({"path": "nope.txt"});
        let err = validate_delete(&args, dir.path()).await.unwrap();
        assert!(err.contains("not found"), "{err}");
    }

    #[tokio::test]
    async fn delete_nonempty_dir_without_recursive() {
        let dir = setup();
        let args = json!({"path": "subdir"});
        let err = validate_delete(&args, dir.path()).await.unwrap();
        assert!(err.contains("recursive"), "{err}");
    }

    #[tokio::test]
    async fn delete_nonempty_dir_with_recursive() {
        let dir = setup();
        let args = json!({"path": "subdir", "recursive": true});
        assert!(validate_delete(&args, dir.path()).await.is_none());
    }

    // ── file_path alias acceptance ──────────────────────────

    #[tokio::test]
    async fn edit_accepts_file_path_param() {
        let dir = setup();
        let args = json!({
            "file_path": "hello.txt",
            "replacements": [{"old_str": "line two", "new_str": "LINE TWO"}]
        });
        assert!(
            validate_edit(&args, dir.path(), None, None, None)
                .await
                .is_none()
        );
    }

    #[tokio::test]
    async fn write_accepts_file_path_param() {
        let dir = setup();
        let args = json!({"file_path": "brand_new.txt", "content": "hello"});
        assert!(validate_write(&args, dir.path()).await.is_none());
    }

    #[tokio::test]
    async fn delete_accepts_file_path_param() {
        let dir = setup();
        let args = json!({"file_path": "hello.txt"});
        assert!(validate_delete(&args, dir.path()).await.is_none());
    }

    // ── Bash validation ───────────────────────────────────────

    #[test]
    fn bash_valid_command() {
        let args = json!({"command": "echo hello"});
        assert!(validate_bash(&args).is_none());
    }

    #[test]
    fn bash_empty_command() {
        let args = json!({"command": ""});
        assert!(validate_bash(&args).unwrap().contains("empty"));
    }

    #[test]
    fn bash_missing_command() {
        let args = json!({});
        assert!(validate_bash(&args).unwrap().contains("empty"));
    }

    #[test]
    fn bash_cmd_alias() {
        let args = json!({"cmd": "ls"});
        assert!(validate_bash(&args).is_none());
    }

    // ── Stale-file detection ──────────────────────────────────

    fn make_cache(path: &std::path::Path, mtime: SystemTime) -> super::super::FileReadCache {
        let cache = super::super::FileReadCache::default();
        let key = format!("{}:None:None", path.display());
        cache.lock().unwrap().insert(key, (0, mtime, String::new()));
        cache
    }

    #[tokio::test]
    async fn edit_stale_file_detected() {
        let dir = setup();
        let file = dir.path().join("hello.txt");
        // Populate cache with a deliberately old mtime (epoch = definitely stale).
        let cache = make_cache(&file, SystemTime::UNIX_EPOCH);
        let args = json!({
            "path": "hello.txt",
            "replacements": [{"old_str": "line two", "new_str": "LINE TWO"}]
        });
        let err = validate_edit(&args, dir.path(), Some(&cache), None, None)
            .await
            .unwrap();
        assert!(err.contains("modified on disk"), "{err}");
        assert!(err.contains("Read it again"), "{err}");
    }

    #[tokio::test]
    async fn edit_fresh_file_no_stale_warning() {
        let dir = setup();
        let file = dir.path().join("hello.txt");
        // Populate cache with the real current mtime.
        let current_mtime = std::fs::metadata(&file).unwrap().modified().unwrap();
        let cache = make_cache(&file, current_mtime);
        let args = json!({
            "path": "hello.txt",
            "replacements": [{"old_str": "line two", "new_str": "LINE TWO"}]
        });
        assert!(
            validate_edit(&args, dir.path(), Some(&cache), None, None)
                .await
                .is_none(),
            "up-to-date file should not trigger stale warning"
        );
    }

    #[tokio::test]
    async fn edit_no_cache_entry_no_stale_warning() {
        // File was never read via Read tool — empty cache, no stale warning.
        let dir = setup();
        let empty_cache = super::super::FileReadCache::default();
        let args = json!({
            "path": "hello.txt",
            "replacements": [{"old_str": "line two", "new_str": "LINE TWO"}]
        });
        assert!(
            validate_edit(&args, dir.path(), Some(&empty_cache), None, None)
                .await
                .is_none(),
            "no cache entry should not trigger stale warning"
        );
    }

    // ── Staleness hint messages (#804 item 7) ─────────────────

    #[tokio::test]
    async fn stale_file_hints_last_writer_tool() {
        let dir = setup();
        let file = dir.path().join("hello.txt");
        let cache = make_cache(&file, SystemTime::UNIX_EPOCH);

        // Populate last_writer with an Edit entry for this file.
        let last_writer = super::super::LastWriterCache::default();
        last_writer.lock().unwrap().insert(
            file.clone(),
            ("Edit".to_string(), std::time::Instant::now()),
        );

        let args = json!({
            "path": "hello.txt",
            "replacements": [{"old_str": "line two", "new_str": "LINE TWO"}]
        });
        let err = validate_edit(&args, dir.path(), Some(&cache), Some(&last_writer), None)
            .await
            .unwrap();
        assert!(err.contains("modified on disk"), "{err}");
        assert!(err.contains("last written by Edit"), "{err}");
    }

    #[tokio::test]
    async fn stale_file_hints_bash_when_no_writer_entry() {
        let dir = setup();
        let file = dir.path().join("hello.txt");
        let cache = make_cache(&file, SystemTime::UNIX_EPOCH);

        // No last_writer entry for this file — fall through to last_bash.
        let last_writer = super::super::LastWriterCache::default();
        let last_bash = super::super::LastBashCache::default();
        *last_bash.lock().unwrap() = Some((
            "cargo fmt -- src/bash_safety.rs".to_string(),
            std::time::Instant::now(),
        ));

        let args = json!({
            "path": "hello.txt",
            "replacements": [{"old_str": "line two", "new_str": "LINE TWO"}]
        });
        let err = validate_edit(
            &args,
            dir.path(),
            Some(&cache),
            Some(&last_writer),
            Some(&last_bash),
        )
        .await
        .unwrap();
        assert!(err.contains("modified on disk"), "{err}");
        assert!(err.contains("Bash ran"), "{err}");
        assert!(err.contains("cargo fmt"), "{err}");
    }

    // ── Omission placeholder detection ────────────────────────

    #[test]
    fn omission_detects_comment_style() {
        let cases = vec![
            "// rest of code ...",
            "// rest of methods ...",
            "# rest of implementation ...",
            "// unchanged code ...",
            "# existing code ...",
            "// remaining code ...",
        ];
        for input in cases {
            let found = detect_omission_placeholders(input);
            assert!(!found.is_empty(), "should detect: {input}");
        }
    }

    #[test]
    fn omission_detects_paren_style() {
        let found = detect_omission_placeholders("(rest of code ...)");
        assert_eq!(found.len(), 1);
        assert_eq!(found[0], "rest of code ...");
    }

    #[test]
    fn omission_detects_comment_plus_parens() {
        let found = detect_omission_placeholders("// (existing implementation ...)");
        assert_eq!(found.len(), 1);
    }

    #[test]
    fn omission_ignores_normal_code() {
        let cases = vec![
            "let x = 42;",
            "// TODO: fix this later",
            "# This is a normal comment",
            "fn rest_of_things() {}",
            "use std::rest::of::things;",
            "println!(\"...\");", // "..." not after a known prefix
            "// See the rest of the docs at ...", // not a known prefix
        ];
        for input in cases {
            let found = detect_omission_placeholders(input);
            assert!(found.is_empty(), "false positive on: {input}");
        }
    }

    #[test]
    fn omission_case_insensitive() {
        let found = detect_omission_placeholders("// Rest Of Code ...");
        assert_eq!(found.len(), 1);
        assert_eq!(found[0], "rest of code ...");
    }

    #[test]
    fn omission_extra_dots_ok() {
        // "// rest of code ......" should still match
        let found = detect_omission_placeholders("// rest of code ......");
        assert_eq!(found.len(), 1);
    }

    #[test]
    fn omission_suffix_text_rejects() {
        // "// rest of code ... here" has non-dot suffix — not a placeholder
        let found = detect_omission_placeholders("// rest of code ... here");
        assert!(found.is_empty());
    }

    #[test]
    fn omission_preserving_existing_placeholder_is_fine() {
        // old_str already has the placeholder — model is preserving, not creating.
        let old = "fn foo() {\n    // rest of code ...\n}";
        let new = "fn foo() {\n    do_thing();\n    // rest of code ...\n}";
        assert!(detect_new_omission_placeholder(old, new, 0).is_none());
    }

    #[test]
    fn omission_introducing_new_placeholder_rejected() {
        let old = "fn foo() {\n    real_code();\n    more_code();\n}";
        let new = "fn foo() {\n    real_code();\n    // rest of code ...\n}";
        let err = detect_new_omission_placeholder(old, new, 0).unwrap();
        assert!(err.contains("omission placeholder"), "{err}");
        assert!(err.contains("actual code"), "{err}");
    }

    #[tokio::test]
    async fn edit_rejects_omission_in_new_str() {
        let dir = setup();
        let args = json!({
            "path": "hello.txt",
            "replacements": [{
                "old_str": "line two",
                "new_str": "// rest of code ..."
            }]
        });
        let err = validate_edit(&args, dir.path(), None, None, None)
            .await
            .unwrap();
        assert!(err.contains("omission placeholder"), "{err}");
    }

    #[tokio::test]
    async fn edit_allows_normal_new_str() {
        let dir = setup();
        let args = json!({
            "path": "hello.txt",
            "replacements": [{
                "old_str": "line two",
                "new_str": "line TWO\n// This comment has dots: ..."
            }]
        });
        // "..." without a known prefix should NOT be detected
        assert!(
            validate_edit(&args, dir.path(), None, None, None)
                .await
                .is_none()
        );
    }

    // ── fmt_age boundary values (#819) ───────────────────────

    #[test]
    fn fmt_age_under_5s_is_just_now() {
        assert_eq!(fmt_age(std::time::Duration::from_secs(0)), "just now");
        assert_eq!(fmt_age(std::time::Duration::from_secs(4)), "just now");
    }

    #[test]
    fn fmt_age_exactly_5s() {
        // Boundary: 5s is the first value that produces "Xs ago".
        assert_eq!(fmt_age(std::time::Duration::from_secs(5)), "5s ago");
    }

    #[test]
    fn fmt_age_under_60s() {
        assert_eq!(fmt_age(std::time::Duration::from_secs(30)), "30s ago");
        assert_eq!(fmt_age(std::time::Duration::from_secs(59)), "59s ago");
    }

    #[test]
    fn fmt_age_exactly_60s() {
        // Boundary: 60s is the first value that produces "Xm ago".
        assert_eq!(fmt_age(std::time::Duration::from_secs(60)), "1m ago");
    }

    #[test]
    fn fmt_age_minutes() {
        assert_eq!(fmt_age(std::time::Duration::from_secs(90)), "1m ago");
        assert_eq!(fmt_age(std::time::Duration::from_secs(120)), "2m ago");
        assert_eq!(fmt_age(std::time::Duration::from_secs(3600)), "60m ago");
    }
}