lingshu-tools 0.10.0

Tool registry, ToolHandler trait, and 50+ tool implementations
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
//! # write_file — Create or overwrite files
//!
//! WHY full-file write: Some operations (generating new files, replacing
//! content entirely) are more natural as full writes. For partial edits,
//! the `patch` tool is preferred.

use async_trait::async_trait;
use serde::Deserialize;
use serde_json::json;

use lingshu_types::{ToolError, ToolSchema};

use crate::edit_contract::{
    DEFAULT_MAX_MUTATION_PAYLOAD_BYTES, DEFAULT_MAX_MUTATION_PAYLOAD_KIB,
    enforce_write_payload_limit_with_max,
};
use crate::path_utils::{jail_write_path, jail_write_path_create_dirs};
use crate::registry::{ToolContext, ToolHandler};
use crate::tools::checkpoint::ensure_checkpoint;

pub struct WriteFileTool;

/// Intent declaration for the existing-file collision case (FP55).
///
/// `Overwrite` (default) preserves the FP51 behavior — rejection
/// includes a content preview and records a session snapshot so the
/// immediate retry succeeds without an extra `read_file` round trip.
///
/// `Abort` is the cheap path: a stat-only rejection (~120 bytes) with
/// no preview and no snapshot. Use when the caller's intent is to
/// create a new file and a collision should pick a different path.
#[derive(Deserialize, Default, Clone, Copy, Debug, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub(crate) enum IfExists {
    #[default]
    Overwrite,
    Abort,
}

#[derive(Deserialize)]
struct Args {
    #[serde(alias = "file_path")]
    path: String,
    #[serde(alias = "file_content", alias = "text", alias = "body")]
    content: String,
    #[serde(default)]
    create_dirs: bool,
    #[serde(default)]
    if_exists: IfExists,
}

#[async_trait]
impl ToolHandler for WriteFileTool {
    fn name(&self) -> &'static str {
        "write_file"
    }

    fn toolset(&self) -> &'static str {
        "file"
    }

    fn emoji(&self) -> &'static str {
        "✏️"
    }

    fn path_arguments(&self) -> &'static [&'static str] {
        &["path"]
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "write_file".into(),
            description: format!(
                "Creates or fully replaces a file. Hard content limit: {DEFAULT_MAX_MUTATION_PAYLOAD_BYTES} bytes ({DEFAULT_MAX_MUTATION_PAYLOAD_KIB} KiB) per call. \
                 \n\
                 WHEN TO USE: \
                 (a) Brand-new file — set if_exists=\"abort\" so a path collision fails CHEAPLY (~120 bytes, no content preview); pick a different path. \
                 (b) Replace an existing file — set if_exists=\"overwrite\" (the default). On collision the rejection includes a short content preview AND records a session snapshot, so calling write_file AGAIN with the same args succeeds — you do NOT need a separate read_file round trip. \
                 \n\
                 PARTIAL EDITS: For ANY targeted modification to an existing file, use patch/apply_patch instead — far more token-efficient and avoids regenerating unchanged content. \
                 \n\
                 CONTRACT: `content` MUST be a string — use \"\" for an empty scaffold. For larger new files, write a small scaffold first then extend with patch/apply_patch."
            ),
            parameters: json!({
                "type": "object",
                "additionalProperties": false,
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "File path relative to working directory"
                    },
                    "content": {
                        "type": "string",
                        "description": "Full content to write to the file. Use an empty string \"\" to create an empty scaffold."
                    },
                    "create_dirs": {
                        "type": "boolean",
                        "description": "Create parent directories if they don't exist. Set explicitly to true or false."
                    },
                    "if_exists": {
                        "type": "string",
                        "enum": ["overwrite", "abort"],
                        "description": "Intent when the file already exists. 'overwrite' (default): rejection on collision returns a content preview and records a session snapshot — retry the SAME call to succeed. 'abort': cheap rejection with no preview and no snapshot — use when intent is to create a NEW file and a different path should be chosen on collision."
                    }
                },
                "required": ["path", "content"]
            }),
            strict: Some(true),
        }
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let args: Args = serde_json::from_value(args).map_err(|e| ToolError::InvalidArgs {
            tool: "write_file".into(),
            message: e.to_string(),
        })?;

        // Auto-checkpoint before mutation
        ensure_checkpoint(ctx, &format!("before write_file: {}", args.path));

        let path_policy = ctx.config.file_path_policy(&ctx.cwd);

        // Path jail check — delegates security concern to path_utils (SRP).
        // For create_dirs=true the helper also creates parent directories.
        let create_dirs = args.create_dirs || ctx.config.local_write_create_dirs;
        let resolved = if create_dirs {
            jail_write_path_create_dirs(&args.path, &path_policy)?
        } else {
            jail_write_path(&args.path, &path_policy)?
        };
        let file_exists = resolved.exists();
        let existing_file_is_empty = file_exists
            && std::fs::metadata(&resolved)
                .map(|meta| meta.is_file() && meta.len() == 0)
                .unwrap_or(false);

        if file_exists
            && !existing_file_is_empty
            && !crate::read_tracker::has_file_snapshot(&ctx.session_id, &resolved)
        {
            match args.if_exists {
                IfExists::Abort => {
                    let size = std::fs::metadata(&resolved).map(|m| m.len()).unwrap_or(0);
                    return Err(crate::recovery_catalog::write_file_path_exists_abort(
                        args.path.clone(),
                        size,
                    ));
                }
                IfExists::Overwrite => {
                    // FP51 + FP55: include the current file content so the model
                    // can immediately compose a patch OR retry the write, AND
                    // record the read-tracker snapshot so the immediate retry
                    // satisfies the freshness guard without an extra read_file
                    // round trip.
                    //
                    // Token budget: cap at 600 chars to keep the rejection error
                    // small. The model only needs enough content to recognise the
                    // file and decide between retry / patch / abort. Full content
                    // remains accessible via read_file when truncation occurs.
                    const PREVIEW_LIMIT: usize = 600;
                    let current_content = std::fs::read_to_string(&resolved).unwrap_or_default();
                    let preview = crate::safe_truncate(&current_content, PREVIEW_LIMIT);
                    let truncated = preview.len() < current_content.len();

                    // Record snapshot BEFORE returning the error so the
                    // immediate retry passes the freshness guard. Failure
                    // here is non-fatal — the model will retry, fail freshness,
                    // and learn to read_file. Logging would be noise.
                    let _ = crate::read_tracker::record_file_snapshot(&ctx.session_id, &resolved);

                    return Err(crate::recovery_catalog::write_file_overwrite_guard(
                        args.path.clone(),
                        preview.to_string(),
                        truncated,
                    ));
                }
            }
        }

        if file_exists {
            crate::read_tracker::guard_file_freshness(
                &ctx.session_id,
                "write_file",
                &args.path,
                &resolved,
            )?;
        }

        // R17: Capture file metadata immediately after the freshness guard so we
        // can detect any external modification in the window between guard and write
        // (TOCTOU). Only relevant when we are overwriting an existing file.
        let pre_write_snap = if file_exists {
            tokio::fs::metadata(&resolved)
                .await
                .ok()
                .map(|m| (m.len(), m.modified().ok()))
        } else {
            None
        };

        let content = args.content;
        let lsp_hook = crate::lsp_gate::LspWriteHook::capture_before(ctx, &resolved).await;

        enforce_write_payload_limit_with_max(
            "write_file",
            &args.path,
            &resolved,
            &content,
            ctx.config.max_write_payload_bytes(),
        )?;

        // R17: Atomic TOCTOU re-check — confirm the file has not changed since
        // the freshness guard above.
        if let Some((size_snap, mtime_snap)) = pre_write_snap
            && let Ok(current) = tokio::fs::metadata(&resolved).await
        {
            let changed = current.len() != size_snap || current.modified().ok() != mtime_snap;
            if changed {
                return Err(crate::recovery_catalog::write_file_content_mismatch(
                    args.path.clone(),
                ));
            }
        }

        let bytes_written = content.len();
        let new_lines = content.lines().count();
        let old_lines = if file_exists {
            tokio::fs::read_to_string(&resolved)
                .await
                .map(|s| s.lines().count())
                .unwrap_or(0)
        } else {
            0
        };

        tokio::fs::write(&resolved, &content)
            .await
            .map_err(|e| ToolError::Other(format!("Cannot write '{}': {}", args.path, e)))?;

        let _ = crate::read_tracker::record_file_snapshot(&ctx.session_id, &resolved);

        ctx.record_mutation(crate::mutations::MutationRecord {
            path: args.path.clone(),
            kind: if file_exists {
                crate::mutations::MutationKind::Modify
            } else {
                crate::mutations::MutationKind::Add
            },
            lines_added: new_lines.saturating_sub(old_lines) as u32,
            lines_removed: old_lines.saturating_sub(new_lines) as u32,
        });

        if bytes_written == 0 {
            Ok(format!(
                "Created empty scaffold at '{}'. Add content next with patch/apply_patch or another write_file call.",
                args.path
            ))
        } else {
            // R18: Structured JSON result (FP57).
            // `lines` gives the agent a measurement signal without a re-read:
            // it can verify the write produced the expected number of lines and
            // decide next action (patch a specific line, read a range, etc.)
            // without a redundant read_file round-trip.
            let action = if file_exists { "overwrite" } else { "create" };
            let lines = new_lines;
            let mut payload = serde_json::json!({
                "ok": true,
                "action": action,
                "bytes": bytes_written,
                "lines": lines,
                "path": args.path,
            });
            lsp_hook
                .attach_after(ctx, &resolved, &mut payload, &content)
                .await;
            Ok(payload.to_string())
        }
    }
}

inventory::submit!(&WriteFileTool as &dyn ToolHandler);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::read_tracker;
    use crate::tools::file_read::ReadFileTool;
    use tempfile::TempDir;
    use uuid::Uuid;

    fn ctx_in(dir: &std::path::Path) -> ToolContext {
        let mut ctx = ToolContext::test_context();
        ctx.cwd = dir.to_path_buf();
        ctx
    }

    fn ctx_with_mutations(dir: &std::path::Path) -> ToolContext {
        let mut ctx = ctx_in(dir);
        ctx.mutation_turn = Some(std::sync::Arc::new(
            crate::mutations::MutationTurnState::new(),
        ));
        ctx
    }

    #[tokio::test]
    async fn write_file_records_mutation_for_footer() {
        let dir = TempDir::new().expect("tmpdir");
        let ctx = ctx_with_mutations(dir.path());
        let turn = ctx.mutation_turn.as_ref().expect("mutation turn");

        WriteFileTool
            .execute(
                json!({"path": "tracked.rs", "content": "line1\nline2\n"}),
                &ctx,
            )
            .await
            .expect("write");

        let records = turn.drain_success();
        assert_eq!(records.len(), 1);
        assert_eq!(records[0].path, "tracked.rs");
        assert_eq!(records[0].kind, crate::mutations::MutationKind::Add);
        assert_eq!(records[0].lines_added, 2);
    }

    #[tokio::test]
    async fn write_file_creates_new() {
        let dir = TempDir::new().expect("tmpdir");
        let ctx = ctx_in(dir.path());

        let result = WriteFileTool
            .execute(json!({"path": "new.txt", "content": "hello world"}), &ctx)
            .await
            .expect("write");

        let v: serde_json::Value = serde_json::from_str(&result).expect("JSON");
        assert_eq!(v["ok"], true);
        assert_eq!(v["bytes"], 11);
        assert_eq!(v["action"], "create");
        // "hello world" has no newlines → 1 line
        assert_eq!(v["lines"], 1, "lines must reflect actual line count");
        let content = std::fs::read_to_string(dir.path().join("new.txt")).expect("read");
        assert_eq!(content, "hello world");
    }

    #[tokio::test]
    async fn write_file_allows_new_empty_scaffold_with_empty_string() {
        let dir = TempDir::new().expect("tmpdir");
        let ctx = ctx_in(dir.path());

        let result = WriteFileTool
            .execute(
                json!({"path": "scaffold.md", "content": "", "create_dirs": false}),
                &ctx,
            )
            .await
            .expect("create scaffold");

        assert!(result.contains("Created empty scaffold"));
        let content = std::fs::read_to_string(dir.path().join("scaffold.md")).expect("read");
        assert_eq!(content, "");
    }

    #[test]
    fn write_file_schema_is_strict_and_content_is_required_string() {
        let schema = WriteFileTool.schema();
        assert_eq!(schema.strict, Some(true));
        assert_eq!(schema.parameters["type"], "object");
        assert_eq!(schema.parameters["additionalProperties"], false);
        assert_eq!(schema.parameters["required"], json!(["path", "content"]));
        // content must be "string" — NOT ["string", "null"]
        assert_eq!(
            schema.parameters["properties"]["content"]["type"],
            json!("string"),
            "content schema type must be 'string', not nullable. \
             See specs/improve_plan/06-write-file-fix.md for rationale."
        );
    }

    #[tokio::test]
    async fn write_file_rejects_missing_content_field() {
        let dir = TempDir::new().expect("tmpdir");
        let ctx = ctx_in(dir.path());

        // Omitting content entirely should fail deserialization
        let result = WriteFileTool
            .execute(json!({"path": "test.txt", "create_dirs": false}), &ctx)
            .await;

        assert!(result.is_err(), "missing content field should be rejected");
    }

    #[tokio::test]
    async fn write_file_allows_empty_string_on_existing_empty_scaffold() {
        let dir = TempDir::new().expect("tmpdir");
        std::fs::write(dir.path().join("audit.md"), "").expect("seed empty scaffold");
        let mut ctx = ctx_in(dir.path());
        ctx.session_id = "write-file-empty-scaffold".into();

        let result = WriteFileTool
            .execute(
                json!({"path": "audit.md", "content": "", "create_dirs": false}),
                &ctx,
            )
            .await
            .expect("existing empty scaffold should be reusable with empty string");

        assert!(result.contains("Created empty scaffold"));
        let content = std::fs::read_to_string(dir.path().join("audit.md")).expect("read");
        assert_eq!(content, "");
    }

    #[tokio::test]
    async fn lh40_local_write_create_dirs_default_writes_nested_path() {
        let dir = TempDir::new().expect("tmpdir");
        let mut ctx = ctx_in(dir.path());
        ctx.config.local_write_create_dirs = true;

        let result = WriteFileTool
            .execute(
                json!({"path": "tmp/pptx_builder/script.py", "content": "print('ok')\n"}),
                &ctx,
            )
            .await
            .expect("nested write with local_write_create_dirs");

        let v: serde_json::Value = serde_json::from_str(&result).expect("JSON");
        assert_eq!(v["ok"], true);
        assert!(
            dir.path()
                .join("tmp/pptx_builder/script.py")
                .exists()
        );
    }

    #[tokio::test]
    async fn write_file_creates_dirs() {
        let dir = TempDir::new().expect("tmpdir");
        let ctx = ctx_in(dir.path());

        let result = WriteFileTool
            .execute(
                json!({"path": "sub/dir/file.txt", "content": "nested", "create_dirs": true}),
                &ctx,
            )
            .await
            .expect("write");

        let v: serde_json::Value = serde_json::from_str(&result).expect("JSON");
        assert_eq!(v["ok"], true);
        assert_eq!(v["bytes"], 6);
        let content = std::fs::read_to_string(dir.path().join("sub/dir/file.txt")).expect("read");
        assert_eq!(content, "nested");
    }

    #[tokio::test]
    async fn write_file_overwrites() {
        let dir = TempDir::new().expect("tmpdir");
        std::fs::write(dir.path().join("existing.txt"), "old").expect("seed");

        let mut ctx = ctx_in(dir.path());
        ctx.session_id = "write-file-overwrite".into();

        ReadFileTool
            .execute(json!({"path": "existing.txt", "line_numbers": false}), &ctx)
            .await
            .expect("read existing file");

        WriteFileTool
            .execute(json!({"path": "existing.txt", "content": "new"}), &ctx)
            .await
            .expect("write");

        let content = std::fs::read_to_string(dir.path().join("existing.txt")).expect("read");
        assert_eq!(content, "new");
    }

    #[tokio::test]
    async fn write_file_allows_absolute_path_in_configured_allowed_root() {
        let dir = TempDir::new().expect("workspace");
        let extra = TempDir::new().expect("extra");
        let target = extra.path().join("shared.txt");

        let mut ctx = ctx_in(dir.path());
        ctx.config.file_allowed_roots = vec![extra.path().to_path_buf()];

        WriteFileTool
            .execute(
                json!({"path": target.to_string_lossy(), "content": "shared write"}),
                &ctx,
            )
            .await
            .expect("write");

        let content = std::fs::read_to_string(&target).expect("read");
        assert_eq!(content, "shared write");
    }

    #[tokio::test]
    async fn write_file_blocks_denylisted_subtree() {
        let dir = TempDir::new().expect("workspace");
        std::fs::create_dir_all(dir.path().join("secrets")).expect("create secrets");

        let mut ctx = ctx_in(dir.path());
        ctx.config.path_restrictions = vec![std::path::PathBuf::from("secrets")];

        let result = WriteFileTool
            .execute(
                json!({"path": "secrets/token.txt", "content": "nope", "create_dirs": true}),
                &ctx,
            )
            .await;

        assert!(matches!(result, Err(ToolError::PermissionDenied(_))));
    }

    #[tokio::test]
    async fn write_file_maps_relative_tmp_files_into_lingshu_temp_root() {
        let dir = TempDir::new().expect("workspace");
        let lingshu_home = TempDir::new().expect("lingshu_home");
        let mut ctx = ctx_in(dir.path());
        ctx.config.lingshu_home = lingshu_home.path().to_path_buf();

        WriteFileTool
            .execute(
                json!({"path": "tmp/files/raphael_osint_report.md", "content": "# OSINT\n"}),
                &ctx,
            )
            .await
            .expect("write relative tmp/files alias");

        let content = std::fs::read_to_string(
            lingshu_home
                .path()
                .join("tmp/files/raphael_osint_report.md"),
        )
        .expect("read mapped tmp file");
        assert_eq!(content, "# OSINT\n");
    }

    #[tokio::test]
    async fn write_file_maps_absolute_tmp_into_lingshu_temp_root() {
        let dir = TempDir::new().expect("workspace");
        let lingshu_home = TempDir::new().expect("lingshu_home");
        let mut ctx = ctx_in(dir.path());
        ctx.config.lingshu_home = lingshu_home.path().to_path_buf();

        WriteFileTool
            .execute(
                json!({"path": "/tmp/summary.md", "content": "hello tmp"}),
                &ctx,
            )
            .await
            .expect("write virtual tmp");

        let content = std::fs::read_to_string(lingshu_home.path().join("tmp/files/summary.md"))
            .expect("read mapped tmp file");
        assert_eq!(content, "hello tmp");
    }

    #[tokio::test]
    async fn write_file_rejects_oversized_payloads() {
        let dir = TempDir::new().expect("workspace");
        let ctx = ctx_in(dir.path());
        let oversized = "x".repeat(DEFAULT_MAX_MUTATION_PAYLOAD_BYTES + 1);

        let result = WriteFileTool
            .execute(json!({"path": "big.rs", "content": oversized}), &ctx)
            .await;

        let err = result.expect_err("oversized write must be rejected");
        assert!(
            err.to_string()
                .contains("Payload exceeds the per-call mutation limit")
        );
    }

    #[tokio::test]
    async fn write_file_rejects_oversized_overwrites() {
        let dir = TempDir::new().expect("workspace");
        std::fs::write(dir.path().join("existing.rs"), "fn main() {}\n").expect("seed");
        let mut ctx = ctx_in(dir.path());
        ctx.session_id = "write-file-oversized-overwrite".into();

        ReadFileTool
            .execute(json!({"path": "existing.rs", "line_numbers": false}), &ctx)
            .await
            .expect("read existing file");

        let oversized = "y".repeat(DEFAULT_MAX_MUTATION_PAYLOAD_BYTES + 10);

        let result = WriteFileTool
            .execute(json!({"path": "existing.rs", "content": oversized}), &ctx)
            .await;

        let err = result.expect_err("oversized overwrite must be rejected");
        assert!(
            err.to_string()
                .contains("Payload exceeds the per-call mutation limit")
        );
    }

    #[tokio::test]
    async fn write_file_rejects_overwrite_when_file_changed_after_read() {
        let dir = TempDir::new().expect("tmpdir");
        std::fs::write(dir.path().join("stale.txt"), "before\n").expect("seed");

        let mut ctx = ctx_in(dir.path());
        ctx.session_id = "write-file-stale-guard".into();

        ReadFileTool
            .execute(json!({"path": "stale.txt", "line_numbers": false}), &ctx)
            .await
            .expect("read");

        std::fs::write(dir.path().join("stale.txt"), "external change\n").expect("modify");

        let err = WriteFileTool
            .execute(
                json!({"path": "stale.txt", "content": "replacement\n"}),
                &ctx,
            )
            .await
            .expect_err("stale overwrite should be rejected");

        assert!(err.to_string().contains("changed since it was last read"));
        let content = std::fs::read_to_string(dir.path().join("stale.txt")).expect("read current");
        assert_eq!(content, "external change\n");
    }

    #[tokio::test]
    async fn write_file_rejects_blind_overwrite_without_prior_read() {
        let dir = TempDir::new().expect("tmpdir");
        std::fs::write(dir.path().join("blind.txt"), "before\n").expect("seed");

        let mut ctx = ctx_in(dir.path());
        ctx.session_id = "write-file-blind-overwrite".into();

        let err = WriteFileTool
            .execute(
                json!({"path": "blind.txt", "content": "replacement\n"}),
                &ctx,
            )
            .await
            .expect_err("blind overwrite should be rejected");

        // FP55: rejection text must teach the model the retry protocol.
        let msg = err.to_string();
        assert!(
            msg.contains("already exists"),
            "expected existence message; got: {msg}"
        );
        assert!(
            msg.contains("Snapshot recorded for freshness"),
            "expected snapshot-recorded directive; got: {msg}"
        );
        // File must NOT be touched on rejection.
        let content = std::fs::read_to_string(dir.path().join("blind.txt")).expect("read current");
        assert_eq!(content, "before\n");
    }

    #[tokio::test]
    async fn write_file_allows_overwrite_after_reread_refreshes_snapshot() {
        let dir = TempDir::new().expect("tmpdir");
        std::fs::write(dir.path().join("fresh.txt"), "before\n").expect("seed");

        let mut ctx = ctx_in(dir.path());
        ctx.session_id = format!("write-file-reread-{}", uuid::Uuid::new_v4().simple()).into();

        ReadFileTool
            .execute(json!({"path": "fresh.txt", "line_numbers": false}), &ctx)
            .await
            .expect("read");

        std::fs::write(dir.path().join("fresh.txt"), "external change\n").expect("modify");

        ReadFileTool
            .execute(json!({"path": "fresh.txt", "line_numbers": false}), &ctx)
            .await
            .expect("reread");

        WriteFileTool
            .execute(
                json!({"path": "fresh.txt", "content": "replacement\n"}),
                &ctx,
            )
            .await
            .expect("fresh overwrite after reread");

        let content = std::fs::read_to_string(dir.path().join("fresh.txt")).expect("read final");
        assert_eq!(content, "replacement\n");
    }

    // ─── FP55 — see specs/improve_plan/32-write-file-fp55.md ──────────────

    #[tokio::test]
    async fn fp55_overwrite_rejection_records_snapshot_so_immediate_retry_succeeds() {
        let dir = TempDir::new().expect("tmpdir");
        std::fs::write(dir.path().join("doc.md"), "# original\nbody\n").expect("seed");

        let mut ctx = ctx_in(dir.path());
        ctx.session_id = "fp55-retry-no-read".into();

        // First call: no prior read, default if_exists=overwrite -> reject + snapshot.
        let err = WriteFileTool
            .execute(
                json!({"path": "doc.md", "content": "# replacement\n", "create_dirs": false}),
                &ctx,
            )
            .await
            .expect_err("first call should be rejected");
        assert!(err.to_string().contains("Snapshot recorded for freshness"));
        assert!(err.to_string().contains("--- preview ---"));
        // File must NOT be modified by the rejection.
        assert_eq!(
            std::fs::read_to_string(dir.path().join("doc.md")).expect("read"),
            "# original\nbody\n"
        );

        // Second call: SAME args, no read_file in between. Must succeed because
        // the snapshot was recorded by the first rejection.
        WriteFileTool
            .execute(
                json!({"path": "doc.md", "content": "# replacement\n", "create_dirs": false}),
                &ctx,
            )
            .await
            .expect("retry should succeed without an extra read_file");

        assert_eq!(
            std::fs::read_to_string(dir.path().join("doc.md")).expect("read final"),
            "# replacement\n"
        );
    }

    #[tokio::test]
    async fn fp55_abort_returns_cheap_error_no_preview_no_snapshot() {
        let dir = TempDir::new().expect("tmpdir");
        let original = "x".repeat(2_000); // larger than the 600-char preview window
        std::fs::write(dir.path().join("taken.txt"), &original).expect("seed");

        let mut ctx = ctx_in(dir.path());
        ctx.session_id = "fp55-abort-cheap".into();

        let err = WriteFileTool
            .execute(
                json!({
                    "path": "taken.txt",
                    "content": "fresh content",
                    "create_dirs": false,
                    "if_exists": "abort",
                }),
                &ctx,
            )
            .await
            .expect_err("abort mode must reject existing path");

        let msg = err.to_string();
        assert!(msg.contains("already exists"), "got: {msg}");
        assert!(msg.contains("2000 bytes"), "must include stat: {msg}");
        // No content preview in cheap-abort path.
        assert!(
            !msg.contains("Current file content"),
            "abort path must NOT include preview; got: {msg}"
        );
        assert!(
            !msg.contains("Snapshot recorded"),
            "abort path must NOT record snapshot; got: {msg}"
        );
        // Snapshot must remain absent so a follow-up overwrite must still
        // pay the read_file cost (or the FP55 overwrite-with-preview cost).
        let resolved = dir.path().join("taken.txt");
        assert!(
            !crate::read_tracker::has_file_snapshot(&ctx.session_id, &resolved),
            "abort mode must not populate snapshot"
        );
    }

    #[tokio::test]
    async fn fp55_abort_then_overwrite_retry_records_snapshot_and_then_succeeds() {
        let dir = TempDir::new().expect("tmpdir");
        std::fs::write(dir.path().join("seq.txt"), "old\n").expect("seed");

        let mut ctx = ctx_in(dir.path());
        ctx.session_id = "fp55-abort-then-overwrite".into();

        // Step 1: abort -> cheap reject, no snapshot.
        WriteFileTool
            .execute(
                json!({
                    "path": "seq.txt",
                    "content": "new\n",
                    "create_dirs": false,
                    "if_exists": "abort",
                }),
                &ctx,
            )
            .await
            .expect_err("abort rejects collision");

        // Step 2: switch intent to overwrite -> reject WITH preview + snapshot.
        WriteFileTool
            .execute(
                json!({
                    "path": "seq.txt",
                    "content": "new\n",
                    "create_dirs": false,
                    "if_exists": "overwrite",
                }),
                &ctx,
            )
            .await
            .expect_err("overwrite first call rejects + snapshots");

        // Step 3: retry overwrite -> succeeds.
        WriteFileTool
            .execute(
                json!({
                    "path": "seq.txt",
                    "content": "new\n",
                    "create_dirs": false,
                    "if_exists": "overwrite",
                }),
                &ctx,
            )
            .await
            .expect("overwrite retry must succeed after snapshot");

        assert_eq!(
            std::fs::read_to_string(dir.path().join("seq.txt")).expect("read"),
            "new\n"
        );
    }

    #[tokio::test]
    async fn fp55_new_file_succeeds_under_either_mode() {
        let dir = TempDir::new().expect("tmpdir");
        let ctx = ctx_in(dir.path());

        WriteFileTool
            .execute(
                json!({"path": "new1.txt", "content": "a", "if_exists": "abort"}),
                &ctx,
            )
            .await
            .expect("abort + new file must succeed");

        WriteFileTool
            .execute(
                json!({"path": "new2.txt", "content": "b", "if_exists": "overwrite"}),
                &ctx,
            )
            .await
            .expect("overwrite + new file must succeed");
    }

    #[tokio::test]
    async fn fp55_external_modification_between_reject_and_retry_fails_freshness() {
        let dir = TempDir::new().expect("tmpdir");
        std::fs::write(dir.path().join("race.txt"), "v1\n").expect("seed");

        let mut ctx = ctx_in(dir.path());
        ctx.session_id = "fp55-race".into();

        // First call: reject + snapshot v1.
        WriteFileTool
            .execute(
                json!({"path": "race.txt", "content": "v2\n", "create_dirs": false}),
                &ctx,
            )
            .await
            .expect_err("first call rejects");

        // External modification between reject and retry. Sleep to ensure
        // mtime differs even on coarse-resolution filesystems.
        std::thread::sleep(std::time::Duration::from_millis(20));
        std::fs::write(dir.path().join("race.txt"), "external\n").expect("modify");

        let err = WriteFileTool
            .execute(
                json!({"path": "race.txt", "content": "v2\n", "create_dirs": false}),
                &ctx,
            )
            .await
            .expect_err("retry must fail because file changed externally");
        assert!(err.to_string().contains("changed since it was last read"));
    }

    #[test]
    fn fp55_schema_includes_if_exists_optional_enum() {
        let schema = WriteFileTool.schema();
        assert_eq!(schema.strict, Some(true));
        let if_exists = &schema.parameters["properties"]["if_exists"];
        assert_eq!(if_exists["type"], "string");
        assert_eq!(if_exists["enum"], json!(["overwrite", "abort"]));
        // if_exists must NOT be in the required list — keeps backward compat.
        let required = schema.parameters["required"]
            .as_array()
            .expect("required arr");
        assert!(
            !required.iter().any(|v| v == "if_exists"),
            "if_exists must remain optional to avoid breaking existing callers"
        );
    }

    #[test]
    fn fp55_schema_description_documents_retry_protocol() {
        let desc = WriteFileTool.schema().description;
        assert!(
            desc.contains("if_exists=\"abort\""),
            "description must document abort mode"
        );
        assert!(
            desc.contains("if_exists=\"overwrite\""),
            "description must document overwrite mode"
        );
        assert!(
            desc.to_lowercase().contains("retry")
                || desc.to_lowercase().contains("again")
                || desc.to_lowercase().contains("call write_file"),
            "description must document the retry protocol"
        );
        assert!(
            desc.contains("patch"),
            "description must still steer toward patch for partial edits"
        );
    }

    #[tokio::test]
    async fn fp55_unknown_if_exists_value_is_rejected() {
        let dir = TempDir::new().expect("tmpdir");
        let ctx = ctx_in(dir.path());

        let err = WriteFileTool
            .execute(
                json!({
                    "path": "x.txt",
                    "content": "v",
                    "create_dirs": false,
                    "if_exists": "skip",   // not in enum
                }),
                &ctx,
            )
            .await
            .expect_err("unknown enum variant must be rejected");
        assert!(matches!(err, ToolError::InvalidArgs { .. }));
    }
}