atomwrite 0.1.30

Atomic file operations CLI for LLM agents — read, write, edit, search, replace with NDJSON output
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
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Batch execution of multiple operations from an NDJSON manifest.
//! Workload: I/O-bound (NDJSON parse + multi-file atomic writes).

use std::io::{Read, Write};
use std::path::PathBuf;
use std::time::Instant;

use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};

use crate::atomic::{AtomicWriteOptions, atomic_write};
use crate::checksum;
use crate::cli::GlobalArgs;
use crate::ndjson_types::{BatchOpResult, BatchSummary, ProgressEvent};
use crate::output::NdjsonWriter;
use crate::signal::ShutdownSignal;

/// A single operation in a batch NDJSON manifest.
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct BatchOp {
    op: String,
    #[serde(default)]
    target: Option<String>,
    #[serde(default)]
    path: Option<String>,
    #[serde(default, alias = "from", alias = "src")]
    source: Option<String>,
    #[serde(default)]
    content: Option<String>,
    #[serde(default)]
    pattern: Option<String>,
    #[serde(default)]
    replacement: Option<String>,
    #[serde(default)]
    backup: bool,
    #[serde(default)]
    old: Option<String>,
    #[serde(default)]
    new: Option<String>,
    /// GAP-108: allow move/copy to overwrite existing target
    #[serde(default)]
    force: Option<bool>,
}

impl BatchOp {
    fn resolve_file_path(&self) -> anyhow::Result<&str> {
        self.target
            .as_deref()
            .or(self.path.as_deref())
            .ok_or_else(|| anyhow::anyhow!("operation requires 'target' or 'path' field"))
    }
}

/// NDJSON event emitted when a transaction is rolled back.
#[derive(Debug, Serialize)]
struct RollbackEvent {
    r#type: &'static str,
    files_restored: u64,
    files_removed: u64,
    total_reverted: u64,
}

/// Emit the JSON Schema for the batch input manifest format.
pub fn emit_input_schema(writer: &mut NdjsonWriter<impl Write>) -> Result<()> {
    let schema = schemars::schema_for!(BatchOp);
    let schema_value = serde_json::to_value(&schema)?;
    writer.write_event(&schema_value)?;
    Ok(())
}

/// Execute multiple operations from an NDJSON manifest in batch mode.
///
/// When `manifest_path` is `Some`, the NDJSON manifest is read from that file
/// instead of from stdin. The path is validated against the workspace jail.
///
/// # Errors
///
/// Returns `AtomwriteError::Io` if reading stdin or writing results fails.
/// Returns `AtomwriteError::InvalidInput` if the manifest contains invalid operations.
#[tracing::instrument(skip_all, fields(command = "batch"))]
#[allow(clippy::too_many_arguments)]
pub fn cmd_batch(
    global: &GlobalArgs,
    stdin: impl Read,
    writer: &mut NdjsonWriter<impl Write>,
    dry_run: bool,
    transaction: bool,
    manifest_path: Option<&std::path::Path>,
    shutdown: &ShutdownSignal,
    backup_opts: &crate::cli_args::BackupOpts,
    defaults: &crate::config::DefaultsSection,
    fuzzy_cfg: &crate::config::FuzzySection,
) -> Result<()> {
    let resolved = crate::commands::resolve_backup(backup_opts, defaults);
    let (batch_fuzzy_mode, batch_fuzzy_threshold) =
        crate::config::resolve_fuzzy(crate::cli::FuzzyMode::Auto, None, fuzzy_cfg)?;
    let retention = resolved.retention;
    let keep_backup = resolved.keep;
    let no_backup = backup_opts.no_backup;
    let backup_explicit = backup_opts.backup == Some(true);
    let start = Instant::now();
    let workspace = global.resolve_workspace()?;

    // Resolve manifest source: file (validated) or stdin
    let mut reader: Box<dyn Read> = if let Some(manifest_path) = manifest_path {
        let validated_manifest = crate::path_safety::validate_path(manifest_path, &workspace)
            .with_context(|| {
                format!(
                    "manifest path escapes workspace: {}",
                    manifest_path.display()
                )
            })?;
        if !validated_manifest.is_file() {
            return Err(crate::error::AtomwriteError::NotFound {
                path: validated_manifest.clone(),
            }
            .into());
        }
        let file = std::fs::File::open(&validated_manifest)
            .with_context(|| format!("cannot open manifest {}", validated_manifest.display()))?;
        Box::new(file)
    } else {
        Box::new(stdin)
    };

    let mut buf_reader =
        std::io::BufReader::with_capacity(crate::constants::BUF_CAPACITY, &mut *reader);
    let mut ops: Vec<BatchOp> = Vec::with_capacity(16);
    let mut line_buf = String::new();
    let mut idx = 0usize;

    loop {
        let n = crate::output::read_limited_line(
            &mut buf_reader,
            &mut line_buf,
            crate::constants::MAX_NDJSON_LINE_SIZE,
        )
        .with_context(|| format!("failed to read manifest line {}", idx + 1))?;
        if n == 0 {
            break;
        }
        let trimmed = line_buf.trim();
        if trimmed.is_empty() {
            idx += 1;
            continue;
        }
        let jd = &mut serde_json::Deserializer::from_str(trimmed);
        let op: BatchOp = serde_path_to_error::deserialize(jd).map_err(|e| {
            if e.inner().classify() == serde_json::error::Category::Io {
                crate::error::AtomwriteError::Io {
                    source: std::io::Error::other(e.to_string()),
                }
            } else {
                crate::error::AtomwriteError::InvalidInput {
                    reason: format!("invalid batch operation at line {}: {e}", idx + 1),
                }
            }
        })?;
        ops.push(op);
        idx += 1;
    }

    if ops.is_empty() {
        return Err(crate::error::AtomwriteError::InvalidInput {
            reason: "empty batch manifest: no operations provided".into(),
        }
        .into());
    }

    // In transaction mode, snapshot all existing files before any mutation.
    let backups: Vec<(PathBuf, PathBuf)> = if transaction && !dry_run {
        let paths = collect_target_paths(&ops, &workspace);
        let mut pairs = Vec::with_capacity(paths.len());
        for path in paths {
            let backup = crate::atomic::create_backup(&path, retention)
                .with_context(|| format!("transaction pre-backup failed for {}", path.display()))?;
            pairs.push((path, backup));
        }
        pairs
    } else {
        Vec::new()
    };

    // Track files created during the transaction so they can be removed on rollback.
    let mut created_files: Vec<PathBuf> = Vec::new();
    // Track moves so they can be reversed (target → source) on rollback.
    let mut moves_to_reverse: Vec<(PathBuf, PathBuf)> = Vec::new();

    let mut succeeded: u64 = 0;
    let mut failed: u64 = 0;
    let total_ops = ops.len() as u64;
    // Progress every ~max(1, total/20) or every 50 ops (P1-3 residual for batch).
    let progress_every = if total_ops == 0 {
        0
    } else {
        (total_ops / 20).clamp(1, 50)
    };

    for (idx, op) in ops.iter().enumerate() {
        if shutdown.is_shutdown() {
            tracing::info!(
                completed = idx,
                total = ops.len(),
                "batch interrupted by signal"
            );
            break;
        }
        if progress_every > 0
            && idx > 0
            && (idx as u64).is_multiple_of(progress_every)
            && global.quiet == 0
        {
            let done = idx as u64;
            let elapsed = start.elapsed().as_secs_f64().max(0.001);
            let rate = done as f64 / elapsed;
            let remaining = total_ops.saturating_sub(done);
            let eta_ms = if rate > 0.0 {
                Some(((remaining as f64 / rate) * 1000.0) as u64)
            } else {
                None
            };
            writer.write_event(&ProgressEvent {
                r#type: "progress",
                done,
                total: total_ops,
                rate_per_s: Some(rate),
                eta_ms,
                phase: "batch".into(),
            })?;
        }

        let op_start = Instant::now();
        // Pre-snapshot existence so we know if the op created a new file at target.
        let creates_target = matches!(op.op.as_str(), "write" | "move" | "copy");
        let was_new_file = if transaction && !dry_run && creates_target {
            op.resolve_file_path()
                .ok()
                .map(std::path::Path::new)
                .and_then(|p| crate::path_safety::validate_path(p, &workspace).ok())
                .map(|p| !p.exists())
                .unwrap_or(false)
        } else {
            false
        };
        let result = execute_op(
            op,
            idx,
            &workspace,
            global,
            dry_run,
            keep_backup,
            no_backup,
            backup_explicit,
            retention,
            batch_fuzzy_mode,
            batch_fuzzy_threshold,
        );

        match result {
            Ok(details) => {
                succeeded += 1;
                if transaction && !dry_run && was_new_file {
                    if let Some(target) = op
                        .resolve_file_path()
                        .ok()
                        .map(std::path::Path::new)
                        .and_then(|p| crate::path_safety::validate_path(p, &workspace).ok())
                    {
                        created_files.push(target);
                    }
                }
                if transaction && !dry_run && op.op == "move" {
                    if let (Some(src), Some(tgt)) = (
                        op.source.as_deref().or(op.path.as_deref()),
                        op.target.as_deref(),
                    ) {
                        if let (Ok(s), Ok(t)) = (
                            crate::path_safety::validate_path(
                                std::path::Path::new(src),
                                &workspace,
                            ),
                            crate::path_safety::validate_path(
                                std::path::Path::new(tgt),
                                &workspace,
                            ),
                        ) {
                            tracing::debug!(source = %s.display(), target = %t.display(), "recorded move for rollback");
                            moves_to_reverse.push((s, t));
                        }
                    }
                }
                let event = BatchOpResult {
                    r#type: "batch_op",
                    index: idx as u64,
                    op: &op.op,
                    status: "ok",
                    details: Some(details),
                    error: None,
                    elapsed_ms: op_start.elapsed().as_millis() as u64,
                };
                writer.write_event(&event)?;
            }
            Err(e) => {
                failed += 1;
                let event = BatchOpResult {
                    r#type: "batch_op",
                    index: idx as u64,
                    op: &op.op,
                    status: "failed",
                    details: None,
                    error: Some(format!("{e:#}")),
                    elapsed_ms: op_start.elapsed().as_millis() as u64,
                };
                writer.write_event(&event)?;

                if transaction {
                    match rollback_transaction(
                        &backups,
                        &created_files,
                        &moves_to_reverse,
                        &workspace,
                    ) {
                        Ok((restored, removed)) => {
                            let rollback_event = RollbackEvent {
                                r#type: "rollback",
                                files_restored: restored,
                                files_removed: removed,
                                total_reverted: restored + removed,
                            };
                            writer.write_event(&rollback_event)?;
                            return Err(crate::error::AtomwriteError::InvalidInput {
                                reason: format!(
                                    "transaction rolled back after failure at operation {idx}: {e:#}"
                                ),
                            }
                            .into());
                        }
                        Err(rb_err) => {
                            tracing::error!(error = %rb_err, "rollback failed");
                            return Err(crate::error::AtomwriteError::InvalidInput {
                                reason: format!("transaction rollback failed: {rb_err:#}"),
                            }
                            .into());
                        }
                    }
                }
            }
        }
    }

    let committed = if transaction { Some(failed == 0) } else { None };
    let summary = BatchSummary {
        r#type: "summary",
        operations: ops.len() as u64,
        succeeded,
        failed,
        dry_run,
        elapsed_ms: start.elapsed().as_millis() as u64,
        transaction: if transaction { Some(true) } else { None },
        committed,
    };
    writer.write_event(&summary)?;

    if failed > 0 {
        return Err(crate::error::AtomwriteError::InvalidInput {
            reason: format!("{failed} batch operation(s) failed"),
        }
        .into());
    }

    Ok(())
}

/// Collect validated paths of existing files that operations will mutate.
fn collect_target_paths(ops: &[BatchOp], workspace: &std::path::Path) -> Vec<PathBuf> {
    let mut paths = Vec::with_capacity(ops.len());
    for op in ops {
        for candidate in [op.target.as_ref(), op.path.as_ref(), op.source.as_ref()]
            .iter()
            .flatten()
        {
            let p = std::path::Path::new(candidate.as_str());
            if let Ok(validated) = crate::path_safety::validate_path(p, workspace) {
                if validated.is_file() {
                    paths.push(validated);
                }
            }
        }
    }
    paths.sort();
    paths.dedup();
    paths
}

/// Restore all pre-transaction backups to their original paths and remove
/// any files that were created during the transaction.
///
/// Returns `(restored, removed)` where `restored` is the count of pre-existing
/// files whose content was rolled back, and `removed` is the count of new
/// files that were created and then deleted.
fn rollback_transaction(
    backups: &[(PathBuf, PathBuf)],
    created_files: &[PathBuf],
    moves_to_reverse: &[(PathBuf, PathBuf)],
    workspace: &std::path::Path,
) -> Result<(u64, u64)> {
    let mut restored = 0u64;

    // Reverse moves first (target → source) before restoring backups.
    for (source, target) in moves_to_reverse.iter().rev() {
        if target.exists() && !source.exists() {
            std::fs::rename(target, source).with_context(|| {
                format!(
                    "cannot reverse move {}{}",
                    target.display(),
                    source.display()
                )
            })?;
            restored += 1;
        }
    }

    for (original, backup) in backups {
        if backup.exists() {
            let content = std::fs::read(backup)
                .with_context(|| format!("cannot read backup {}", backup.display()))?;
            let opts = AtomicWriteOptions::default();
            atomic_write(original, &content, &opts, workspace)
                .with_context(|| format!("cannot restore {}", original.display()))?;
            restored += 1;
        }
    }

    let mut removed = 0u64;
    for path in created_files {
        if path.exists() {
            std::fs::remove_file(path)
                .with_context(|| format!("cannot remove created file {}", path.display()))?;
            removed += 1;
        }
    }

    Ok((restored, removed))
}

#[allow(clippy::too_many_arguments)]
fn execute_op(
    op: &BatchOp,
    _idx: usize,
    workspace: &std::path::Path,
    global: &GlobalArgs,
    dry_run: bool,
    keep_backup: bool,
    no_backup: bool,
    backup_explicit: bool,
    retention: u8,
    fuzzy_mode: crate::cli::FuzzyMode,
    fuzzy_threshold: Option<f64>,
) -> Result<String> {
    let max_size = global.effective_max_filesize();
    match op.op.as_str() {
        "write" => execute_write(
            op,
            workspace,
            dry_run,
            keep_backup,
            no_backup,
            backup_explicit,
            retention,
        ),
        "replace" => execute_replace(
            op,
            workspace,
            dry_run,
            max_size,
            keep_backup,
            no_backup,
            backup_explicit,
            retention,
            fuzzy_mode,
            fuzzy_threshold,
        ),
        "delete" => execute_delete(
            op,
            workspace,
            dry_run,
            max_size,
            keep_backup,
            no_backup,
            backup_explicit,
            retention,
        ),
        "edit" => execute_edit(
            op,
            workspace,
            dry_run,
            max_size,
            keep_backup,
            no_backup,
            backup_explicit,
            retention,
            fuzzy_mode,
            fuzzy_threshold,
        ),
        "hash" => execute_hash(op, workspace, max_size),
        "move" => execute_move(op, workspace, dry_run),
        "copy" => execute_copy(
            op,
            workspace,
            dry_run,
            max_size,
            keep_backup,
            no_backup,
            backup_explicit,
            retention,
        ),
        _ => bail!("unsupported batch operation: {}", op.op),
    }
}

fn execute_write(
    op: &BatchOp,
    workspace: &std::path::Path,
    dry_run: bool,
    keep_backup: bool,
    no_backup: bool,
    backup_explicit: bool,
    retention: u8,
) -> Result<String> {
    let target = op.resolve_file_path()?;
    let content = op
        .content
        .as_deref()
        .ok_or_else(|| anyhow::anyhow!("write operation requires 'content' field"))?;

    let target_path = std::path::Path::new(target);

    if dry_run {
        return Ok(format!("would write {} bytes to {target}", content.len()));
    }

    let opts = AtomicWriteOptions {
        backup: !no_backup && (op.backup || keep_backup || backup_explicit),
        syntax_check: false,
        retention,
        preserve_timestamps: false,
        backup_output_dir: None,
        strategy: None,
        strict_atomic: false,
        wal_policy: crate::wal::WalPolicy::Auto,
        keep_backup,
        durability: crate::platform::Durability::Auto,
    };
    let result = atomic_write(target_path, content.as_bytes(), &opts, workspace)?;
    Ok(format!(
        "wrote {} bytes, checksum={}",
        result.bytes_written, result.checksum
    ))
}

#[allow(clippy::too_many_arguments)]
fn execute_replace(
    op: &BatchOp,
    workspace: &std::path::Path,
    dry_run: bool,
    max_size: u64,
    keep_backup: bool,
    no_backup: bool,
    backup_explicit: bool,
    retention: u8,
    fuzzy_mode: crate::cli::FuzzyMode,
    fuzzy_threshold: Option<f64>,
) -> Result<String> {
    let path_str = op.resolve_file_path()?;
    let pattern =
        op.pattern.as_deref().or(op.old.as_deref()).ok_or_else(|| {
            anyhow::anyhow!("replace operation requires 'pattern' or 'old' field")
        })?;
    let replacement = op
        .replacement
        .as_deref()
        .or(op.new.as_deref())
        .ok_or_else(|| {
            anyhow::anyhow!("replace operation requires 'replacement' or 'new' field")
        })?;

    let path = std::path::Path::new(path_str);
    let validated = crate::path_safety::validate_path(path, workspace)?;
    let content = crate::file_io::read_file_string(&validated, max_size)
        .with_context(|| format!("cannot read {}", validated.display()))?;

    // Prefer exact multi-replace; fall back to fuzzy cascade (v0.1.29).
    let new_content = if content.contains(pattern) {
        content.replace(pattern, replacement)
    } else {
        match crate::fuzzy::match_pair(
            &content,
            pattern,
            replacement,
            fuzzy_mode,
            fuzzy_threshold,
        ) {
            Ok((edited, _)) => edited,
            Err(_) => content.clone(),
        }
    };
    if new_content == content {
        return Ok(format!("no matches in {path_str}"));
    }

    let count = content.matches(pattern).count();

    if dry_run {
        return Ok(format!("would replace {count} occurrence(s) in {path_str}"));
    }

    let checksum_before = checksum::hash_bytes(content.as_bytes());
    let opts = AtomicWriteOptions {
        backup: !no_backup && (op.backup || keep_backup || backup_explicit),
        syntax_check: false,
        retention,
        preserve_timestamps: false,
        backup_output_dir: None,
        strategy: None,
        strict_atomic: false,
        wal_policy: crate::wal::WalPolicy::Auto,
        keep_backup,
        durability: crate::platform::Durability::Auto,
    };
    let result = atomic_write(&validated, new_content.as_bytes(), &opts, workspace)?;
    Ok(format!(
        "replaced {count} occurrence(s), checksum_before={checksum_before}, checksum_after={}",
        result.checksum
    ))
}

#[allow(clippy::too_many_arguments)]
fn execute_delete(
    op: &BatchOp,
    workspace: &std::path::Path,
    dry_run: bool,
    max_size: u64,
    keep_backup: bool,
    no_backup: bool,
    backup_explicit: bool,
    retention: u8,
) -> Result<String> {
    let target = op.resolve_file_path()?;

    let path = std::path::Path::new(target);
    let validated = crate::path_safety::validate_path(path, workspace)?;

    if !validated.exists() {
        return Err(crate::error::AtomwriteError::NotFound {
            path: validated.clone(),
        }
        .into());
    }

    if dry_run {
        return Ok(format!("would delete {target}"));
    }

    if !no_backup && (op.backup || keep_backup || backup_explicit) {
        crate::atomic::create_backup(&validated, retention)
            .with_context(|| format!("cannot backup {target}"))?;
    }

    let checksum = checksum::hash_file(&validated, max_size)?;
    std::fs::remove_file(&validated).with_context(|| format!("cannot delete {target}"))?;

    if let Some(parent) = validated.parent() {
        if let Err(e) = crate::platform::fsync_dir(parent) {
            tracing::warn!(
                path = %parent.display(),
                error = %e,
                "fsync_dir after batch delete failed"
            );
        }
    }

    Ok(format!("deleted {target}, checksum_before={checksum}"))
}

#[allow(clippy::too_many_arguments)]
fn execute_edit(
    op: &BatchOp,
    workspace: &std::path::Path,
    dry_run: bool,
    max_size: u64,
    keep_backup: bool,
    no_backup: bool,
    backup_explicit: bool,
    retention: u8,
    fuzzy_mode: crate::cli::FuzzyMode,
    fuzzy_threshold: Option<f64>,
) -> Result<String> {
    let path_str = op.resolve_file_path()?;
    let old = op
        .old
        .as_deref()
        .ok_or_else(|| anyhow::anyhow!("edit operation requires 'old' field"))?;
    let new = op.new.as_deref().unwrap_or("");

    let path = std::path::Path::new(path_str);
    let validated = crate::path_safety::validate_path(path, workspace)?;
    let content = crate::file_io::read_file_string(&validated, max_size)
        .with_context(|| format!("cannot read {}", validated.display()))?;

    if !content.contains(old) {
        // Still try fuzzy path; exact-only early fail is too strict with config cascade.
        // Fall through to match_pair below.
    }

    if dry_run {
        return Ok(format!("would edit {path_str}"));
    }

    let edited =
        match crate::fuzzy::match_pair(&content, old, new, fuzzy_mode, fuzzy_threshold) {
            Ok((e, _)) => e,
            Err(e) => return Err(e.into()),
        };
    let checksum_before = checksum::hash_bytes(content.as_bytes());
    let opts = AtomicWriteOptions {
        backup: !no_backup && (op.backup || keep_backup || backup_explicit),
        syntax_check: false,
        retention,
        preserve_timestamps: false,
        backup_output_dir: None,
        strategy: None,
        strict_atomic: false,
        wal_policy: crate::wal::WalPolicy::Auto,
        keep_backup,
        durability: crate::platform::Durability::Auto,
    };
    let result = atomic_write(&validated, edited.as_bytes(), &opts, workspace)?;
    Ok(format!(
        "edited {path_str}, checksum_before={checksum_before}, checksum_after={}",
        result.checksum
    ))
}

fn execute_hash(op: &BatchOp, workspace: &std::path::Path, max_size: u64) -> Result<String> {
    let path_str = op.resolve_file_path()?;
    let path = std::path::Path::new(path_str);
    let validated = crate::path_safety::validate_path(path, workspace)?;
    let hash = checksum::hash_file(&validated, max_size)?;
    Ok(format!("hash={hash}"))
}

fn execute_move(op: &BatchOp, workspace: &std::path::Path, dry_run: bool) -> Result<String> {
    let source_str = op
        .source
        .as_deref()
        .or(op.path.as_deref())
        .ok_or_else(|| anyhow::anyhow!("move operation requires 'source' field"))?;
    let dest_str = op
        .target
        .as_deref()
        .ok_or_else(|| anyhow::anyhow!("move operation requires 'target' (destination) field"))?;

    let source = crate::path_safety::validate_path(std::path::Path::new(source_str), workspace)?;
    let dest = crate::path_safety::validate_path(std::path::Path::new(dest_str), workspace)?;

    if !source.exists() {
        return Err(crate::error::AtomwriteError::NotFound { path: source }.into());
    }

    // GAP-108: batch move must check target existence like standalone move
    if dest.exists() && !op.force.unwrap_or(false) {
        return Err(crate::error::AtomwriteError::InvalidInput {
            reason: format!(
                "target {} already exists, use \"force\":true in the batch op to overwrite",
                dest.display()
            ),
        }
        .into());
    }

    if dry_run {
        return Ok(format!("would move {source_str} to {dest_str}"));
    }

    if let Some(parent) = dest.parent() {
        if !parent.exists() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("cannot create parent dir for {dest_str}"))?;
        }
    }
    std::fs::rename(&source, &dest)
        .with_context(|| format!("cannot move {source_str} to {dest_str}"))?;
    if let Some(parent) = dest.parent() {
        let _ = crate::platform::fsync_dir(parent);
    }
    if let Some(parent) = source.parent() {
        let _ = crate::platform::fsync_dir(parent);
    }
    Ok(format!("moved {source_str} to {dest_str}"))
}

#[allow(clippy::too_many_arguments)]
fn execute_copy(
    op: &BatchOp,
    workspace: &std::path::Path,
    dry_run: bool,
    max_size: u64,
    keep_backup: bool,
    no_backup: bool,
    backup_explicit: bool,
    retention: u8,
) -> Result<String> {
    let source_str = op
        .source
        .as_deref()
        .or(op.path.as_deref())
        .ok_or_else(|| anyhow::anyhow!("copy operation requires 'source' field"))?;
    let dest_str = op
        .target
        .as_deref()
        .ok_or_else(|| anyhow::anyhow!("copy operation requires 'target' (destination) field"))?;

    let source = crate::path_safety::validate_path(std::path::Path::new(source_str), workspace)?;
    let dest = crate::path_safety::validate_path(std::path::Path::new(dest_str), workspace)?;

    if !source.exists() {
        return Err(crate::error::AtomwriteError::NotFound { path: source }.into());
    }

    // GAP-108: batch copy must check target existence like standalone copy
    if dest.exists() && !op.force.unwrap_or(false) {
        return Err(crate::error::AtomwriteError::InvalidInput {
            reason: format!(
                "target {} already exists, use \"force\":true in the batch op to overwrite",
                dest.display()
            ),
        }
        .into());
    }

    if dry_run {
        return Ok(format!("would copy {source_str} to {dest_str}"));
    }

    let content = crate::file_io::read_file_bytes(&source, max_size)
        .with_context(|| format!("cannot read {}", source.display()))?;
    let opts = AtomicWriteOptions {
        backup: !no_backup && (op.backup || keep_backup || backup_explicit),
        syntax_check: false,
        retention,
        preserve_timestamps: false,
        backup_output_dir: None,
        strategy: None,
        strict_atomic: false,
        wal_policy: crate::wal::WalPolicy::Auto,
        keep_backup,
        durability: crate::platform::Durability::Auto,
    };
    let result = atomic_write(&dest, &content, &opts, workspace)?;
    Ok(format!(
        "copied {source_str} to {dest_str}, checksum={}",
        result.checksum
    ))
}