arcature-cli 2026.1.1

Developer lifecycle CLI for Arcature applications.
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
//! Transactional generator plan (PROGRAM.md AP2.1-11): plan → conflict-detect
//! → dry-run → stage → validate → rollback-on-failure.
//!
//! A [`Plan`] is a small multi-file transaction used by the `arc make`
//! generators. It never silently overwrites user files: every create is
//! conflict-checked before any file is touched, a dry run reports exactly
//! what would happen without touching the filesystem, and a staged write
//! that fails a caller-provided validation step rolls back — removing only
//! the files the plan created and restoring any file it modified.
//!
//! # Why a transaction
//!
//! Before this, [`super::write::write_file`] handled one file at a time with
//! a per-file refuse-overwrite guard. A generator that writes several files
//! (a source file *and* a `pub mod` declaration appended to the module's
//! `mod.rs`) could fail halfway through, leaving the project in a partial
//! state. [`Plan`] makes that multi-file write atomic from the caller's view:
//! either every op lands, or — on conflict or validation failure — the
//! project is left as it was.
//!
//! # Rollback scope
//!
//! Rollback only ever touches files the plan itself created or modified. It
//! never deletes a file the plan did not write, and it restores the exact
//! original content of a file it overwrote or appended to. A pre-existing
//! user file is therefore always recoverable to its pre-plan state.
//!
//! # Validation
//!
//! The optional validation step runs *after* staging, with every planned
//! file on disk, so a validator can compile-check or read back what was
//! written. On failure the plan rolls back and returns
//! [`PlanError::Validation`]. The shipped generators pass `None` (the
//! conflict checks are their safety boundary this wave); the hook is the seam
//! future schema-aware generators (model/crud/api-resource) plug a real
//! compile check into once `#[model]` freezes in AP2.1-6.
//!
//! # Path safety
//!
//! Each operation's path must already be validated by the generator (the
//! [`super::naming`] helpers enforce containment within the project root and
//! reject path traversal). The plan does not re-canonicalize; it owns the
//! transactional write/rollback mechanics, not path validation.

use std::path::{Path, PathBuf};

#[cfg(test)]
use super::naming;

/// One staged filesystem operation in a [`Plan`].
#[derive(Debug, Clone)]
pub(crate) enum PlannedOp {
    /// Create a new file at `path` with `content`.
    Create {
        /// The absolute destination path (already validated by the generator).
        path: PathBuf,
        /// The full file content to write.
        content: String,
    },
    /// Append `declaration` to `path` if it is not already present
    /// (idempotent — the same declaration is never appended twice). Creates
    /// the file if it does not exist. This is how a generator adds a
    /// `pub mod <name>;` line to a module's `mod.rs`.
    Append {
        /// The destination file (e.g. `src/<module>/mod.rs`).
        path: PathBuf,
        /// The line to append if absent (e.g. `pub mod links_mail;`).
        declaration: String,
    },
}

/// The overwrite policy for create operations. Set per execution from the
/// CLI `--force` flag; the shipped generators always use [`Refuse`](Self::Refuse).
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub(crate) enum OverwritePolicy {
    /// Refuse to create a file that already exists. The default; user files
    /// are never silently overwritten.
    Refuse,
    /// Overwrite an existing file. Explicit only (CLI `--force`). The
    /// original content is captured before writing so rollback can restore it.
    Overwrite,
}

/// A caller-provided validation step run after staging. Receives the paths
/// the plan just wrote, in stage order. Returning `Err` triggers rollback.
pub(crate) type Validator = Box<dyn FnOnce(&[PathBuf]) -> Result<(), String>>;

/// A typed failure from a [`Plan`] execution (AGENTS.md §18: no raw `String`
/// errors at the API boundary).
#[derive(Debug)]
pub(crate) enum PlanError {
    /// A create operation refused to overwrite an existing file. Carries the
    /// exact conflicting path so the CLI can report it verbatim.
    Conflict(PathBuf),
    /// A filesystem operation (create directory, read, write, remove) failed.
    Io {
        /// The path the operation targeted.
        path: PathBuf,
        /// The underlying error message.
        error: String,
    },
    /// The post-stage validation step failed; the plan rolled back. Carries
    /// the validator's message.
    Validation(String),
}

impl PlanError {
    fn io(path: PathBuf, error: impl Into<String>) -> Self {
        Self::Io {
            path,
            error: error.into(),
        }
    }
}

impl std::fmt::Display for PlanError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Conflict(path) => write!(
                formatter,
                "refusing to overwrite existing file: {}",
                path.display()
            ),
            Self::Io { path, error } => {
                write!(formatter, "filesystem error at {}: {error}", path.display())
            }
            Self::Validation(message) => {
                write!(formatter, "validation failed; rolled back: {message}")
            }
        }
    }
}

impl std::error::Error for PlanError {}

/// A multi-file generator transaction.
pub(crate) struct Plan {
    ops: Vec<PlannedOp>,
    /// Rollback bookkeeping, populated during [`stage`]. Each entry records
    /// exactly how to undo one op: delete a file the plan created, or restore
    /// the original content of a file the plan modified.
    rollback: Vec<RollbackStep>,
}

/// One undo step captured during staging.
#[derive(Debug)]
enum RollbackStep {
    /// The plan created this file (it did not exist before); rollback deletes it.
    DeleteCreated(PathBuf),
    /// The plan modified or overwrote this file; rollback restores `original`.
    /// `original` is `None` when the plan created the file via an append (the
    /// file did not exist before) — rollback then deletes it.
    Restore {
        path: PathBuf,
        original: Option<String>,
    },
}

impl Plan {
    /// An empty plan.
    pub(crate) fn new() -> Self {
        Self {
            ops: Vec::new(),
            rollback: Vec::new(),
        }
    }

    /// Add a create op. The path must already be validated by the generator.
    pub(crate) fn create(mut self, path: PathBuf, content: String) -> Self {
        self.ops.push(PlannedOp::Create { path, content });
        self
    }

    /// Add an idempotent append op. `declaration` is appended to `path` only
    /// if not already present.
    pub(crate) fn append(mut self, path: PathBuf, declaration: String) -> Self {
        self.ops.push(PlannedOp::Append { path, declaration });
        self
    }

    /// Whether the plan has any operations.
    pub(crate) fn is_empty(&self) -> bool {
        self.ops.is_empty()
    }

    /// The operations in stage order (for inspection / dry-run reporting).
    /// Test-only: the shipped generators call `execute` / `dry_run_report`
    /// directly; this accessor exists so unit tests can assert the plan's
    /// shape before committing it.
    #[cfg(test)]
    pub(crate) fn ops(&self) -> &[PlannedOp] {
        &self.ops
    }

    /// Detect create-op conflicts against the current filesystem. Returns
    /// [`PlanError::Conflict`] with the exact conflicting path on the first
    /// create that would overwrite under [`OverwritePolicy::Refuse`]. Append
    /// ops never conflict (appending is always allowed; idempotency is
    /// resolved at stage time).
    fn detect_conflicts(&self, overwrite: OverwritePolicy) -> Result<(), PlanError> {
        if overwrite == OverwritePolicy::Overwrite {
            return Ok(());
        }
        for op in &self.ops {
            if let PlannedOp::Create { path, .. } = op
                && path.exists()
            {
                return Err(PlanError::Conflict(path.clone()));
            }
        }
        Ok(())
    }

    /// Build a human-readable dry-run report. Touches no files. Conflict
    /// detection runs first so a conflicting dry run reports the exact file
    /// rather than pretending it would succeed.
    pub(crate) fn dry_run_report(&self, overwrite: OverwritePolicy) -> Result<String, PlanError> {
        self.detect_conflicts(overwrite)?;
        let mut lines = Vec::with_capacity(self.ops.len() + 1);
        lines.push("dry run: no files will be written".to_owned());
        for op in &self.ops {
            lines.push(describe_op(op));
        }
        Ok(lines.join("\n"))
    }

    /// Execute the plan as a commit: conflict-detect → stage → validate (if
    /// provided) → rollback on validation failure. Returns the list of paths
    /// the plan wrote, in stage order.
    ///
    /// For a dry run, call [`Plan::dry_run_report`] instead — it reports
    /// conflicts and the planned actions without touching the filesystem.
    ///
    /// # Errors
    ///
    /// [`PlanError::Conflict`] — a create op would overwrite under
    /// [`OverwritePolicy::Refuse`]. [`PlanError::Io`] — a filesystem op
    /// failed (the plan rolls back what it staged so far). [`PlanError::Validation`]
    /// — the validator failed and the plan rolled back.
    pub(crate) fn execute(
        &mut self,
        overwrite: OverwritePolicy,
        validate: Option<Validator>,
    ) -> Result<Vec<PathBuf>, PlanError> {
        self.detect_conflicts(overwrite)?;
        let written = self.stage(overwrite)?;
        if let Some(validator) = validate
            && let Err(message) = validator(&written)
        {
            // Rollback swallows its own IO errors only to surface the
            // validation failure (the primary cause); a rollback IO
            // failure is appended to the returned message so it is not
            // silently lost.
            let rollback_note = match self.rollback() {
                Ok(()) => String::new(),
                Err(PlanError::Io { path, error }) => {
                    format!(" (rollback also failed at {}: {error})", path.display())
                }
                Err(other) => format!(" (rollback also failed: {other})"),
            };
            return Err(PlanError::Validation(format!("{message}{rollback_note}")));
        }
        Ok(written)
    }

    /// Stage every op to disk, recording rollback steps. Returns the paths
    /// written, in stage order. On an IO failure mid-stage, the plan rolls
    /// back what it has staged so far and returns the IO error.
    fn stage(&mut self, overwrite: OverwritePolicy) -> Result<Vec<PathBuf>, PlanError> {
        // Take ownership of the ops so we can call `&mut self` stage helpers
        // without borrowing `self.ops` immutably at the same time. The ops
        // are cheap `Clone`s (path + content strings); correctness matters
        // more than the one allocation here.
        let ops = std::mem::take(&mut self.ops);
        let mut written = Vec::with_capacity(ops.len());
        for op in &ops {
            match op {
                PlannedOp::Create { path, content } => {
                    match self.stage_create(path, content, overwrite) {
                        Ok(()) => written.push(path.clone()),
                        Err(error) => {
                            // Restore the ops so a retry is possible; surface
                            // the primary IO error after rolling back.
                            self.ops = ops;
                            let _ = self.rollback();
                            return Err(error);
                        }
                    }
                }
                PlannedOp::Append { path, declaration } => {
                    match self.stage_append(path, declaration) {
                        Ok(Some(())) => written.push(path.clone()),
                        Ok(None) => {} // idempotent no-op: nothing written
                        Err(error) => {
                            self.ops = ops;
                            let _ = self.rollback();
                            return Err(error);
                        }
                    }
                }
            }
        }
        self.ops = ops;
        Ok(written)
    }

    /// Stage one create op. Captures rollback info: delete if the plan
    /// created the file, restore the original if it overwrote an existing
    /// file (only under [`OverwritePolicy::Overwrite`]).
    fn stage_create(
        &mut self,
        path: &Path,
        content: &str,
        overwrite: OverwritePolicy,
    ) -> Result<(), PlanError> {
        let existed = path.exists();
        if existed && overwrite == OverwritePolicy::Refuse {
            return Err(PlanError::Conflict(path.to_path_buf()));
        }
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| PlanError::io(path.to_path_buf(), e.to_string()))?;
        }
        if existed {
            // Overwrite path: capture the original so rollback can restore it.
            let original = std::fs::read_to_string(path)
                .map_err(|e| PlanError::io(path.to_path_buf(), e.to_string()))?;
            self.rollback.push(RollbackStep::Restore {
                path: path.to_path_buf(),
                original: Some(original),
            });
        } else {
            self.rollback
                .push(RollbackStep::DeleteCreated(path.to_path_buf()));
        }
        std::fs::write(path, content)
            .map_err(|e| PlanError::io(path.to_path_buf(), e.to_string()))?;
        Ok(())
    }

    /// Stage one append op, idempotently. If `declaration` is already in the
    /// file, this is a no-op (no rollback step recorded). Otherwise the
    /// original content (or `None` if the file did not exist) is captured for
    /// rollback and the declaration is appended.
    fn stage_append(&mut self, path: &Path, declaration: &str) -> Result<Option<()>, PlanError> {
        let original: Option<String> = std::fs::read_to_string(path).ok();
        let existed = original.is_some();
        if let Some(existing) = &original
            && existing.contains(declaration)
        {
            return Ok(None);
        }
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| PlanError::io(path.to_path_buf(), e.to_string()))?;
        }
        // Capture the rollback original (the pre-plan content if the file
        // existed, else `None` to signal "the plan created this file").
        let rollback_original = if existed { original.clone() } else { None };
        let mut content = original.unwrap_or_default();
        if !content.is_empty() && !content.ends_with('\n') {
            content.push('\n');
        }
        content.push_str(declaration);
        content.push('\n');
        std::fs::write(path, content)
            .map_err(|e| PlanError::io(path.to_path_buf(), e.to_string()))?;
        self.rollback.push(RollbackStep::Restore {
            path: path.to_path_buf(),
            original: rollback_original,
        });
        Ok(Some(()))
    }

    /// Roll back every staged op, in reverse stage order. Only touches files
    /// the plan created or modified. A rollback failure does not abort the
    /// remaining undo steps (best-effort full undo) but is returned.
    fn rollback(&mut self) -> Result<(), PlanError> {
        let mut last_err: Option<PlanError> = None;
        while let Some(step) = self.rollback.pop() {
            if let Err(e) = self.undo(step) {
                last_err = Some(e);
            }
        }
        match last_err {
            Some(e) => Err(e),
            None => Ok(()),
        }
    }

    /// Undo one rollback step.
    fn undo(&self, step: RollbackStep) -> Result<(), PlanError> {
        match step {
            RollbackStep::DeleteCreated(path) => {
                // Only delete if the file still exists and matches a file we
                // created. We never delete a path we did not stage.
                std::fs::remove_file(&path).map_err(|e| PlanError::io(path, e.to_string()))
            }
            RollbackStep::Restore { path, original } => match original {
                Some(content) => {
                    std::fs::write(&path, content).map_err(|e| PlanError::io(path, e.to_string()))
                }
                None => {
                    // The plan created the file via an append (it did not
                    // exist before). Remove it to restore the pre-plan state.
                    if path.exists() {
                        std::fs::remove_file(&path).map_err(|e| PlanError::io(path, e.to_string()))
                    } else {
                        Ok(())
                    }
                }
            },
        }
    }
}

impl Default for Plan {
    fn default() -> Self {
        Self::new()
    }
}

/// Describe one op for a dry-run report, touching no files.
fn describe_op(op: &PlannedOp) -> String {
    match op {
        PlannedOp::Create { path, .. } => {
            format!("would create {}", path.display())
        }
        PlannedOp::Append { path, declaration } => {
            let existing = std::fs::read_to_string(path).unwrap_or_default();
            if existing.contains(declaration) {
                format!(
                    "{} already declares `{declaration}` — no change",
                    path.display()
                )
            } else {
                format!("would append `{declaration}` to {}", path.display())
            }
        }
    }
}

/// Append a `pub mod <stem>;` declaration to a module's `mod.rs` as an
/// idempotent [`Plan`] op. The declaration is derived and validated by
/// [`naming`]; this is the transactional counterpart of the direct
/// [`naming::append_mod_declaration`] used by the per-file generators.
///
/// Test-only: the shipped generators build their append ops inline via
/// `Plan::append`; this helper exists so the plan's mod-declaration op is
/// constructable in one place for tests. A future UAG-aware generator may
/// promote it to non-test use.
#[cfg(test)]
pub(crate) fn append_mod_declaration_op(
    root: &Path,
    module: &str,
    file_stem: &str,
) -> Result<PlannedOp, String> {
    let mod_rs = super::write::module_mod_rs(root, module);
    let declaration = naming::mod_declaration(file_stem)?;
    Ok(PlannedOp::Append {
        path: mod_rs,
        declaration,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::path::PathBuf;

    fn temp_root(label: &str) -> PathBuf {
        let root = std::env::temp_dir().join(format!(
            "arcature-cli-plan-{label}-{}-{}",
            std::process::id(),
            unique_suffix()
        ));
        fs::create_dir_all(&root).expect("temp root should be created");
        root
    }

    fn unique_suffix() -> u128 {
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_nanos())
    }

    fn cleanup(root: &Path) {
        let _ = fs::remove_dir_all(root);
    }

    #[test]
    fn dry_run_writes_nothing_and_reports() {
        let root = temp_root("dry-run");
        let target = root.join("src").join("links").join("links_mail.rs");
        let plan = Plan::new().create(target.clone(), "pub fn x() {}".to_owned());
        let report = plan
            .dry_run_report(OverwritePolicy::Refuse)
            .expect("dry-run report should succeed");
        assert!(report.contains("dry run: no files will be written"));
        assert!(report.contains("would create"));
        assert!(report.contains(&target.display().to_string()));
        assert!(!target.exists(), "dry run must not create the file");
        assert!(
            !root.join("src").exists(),
            "dry run must not create directories"
        );
        cleanup(&root);
    }

    #[test]
    fn commit_creates_file_and_dirs() {
        let root = temp_root("commit");
        let target = root.join("src").join("links").join("links_mail.rs");
        let mut plan = Plan::new().create(target.clone(), "pub fn x() {}".to_owned());
        let written = plan
            .execute(OverwritePolicy::Refuse, None)
            .expect("commit should succeed");
        assert_eq!(written, vec![target.clone()]);
        assert!(target.is_file());
        assert_eq!(fs::read_to_string(&target).unwrap(), "pub fn x() {}");
        cleanup(&root);
    }

    #[test]
    fn conflict_reports_exact_file_and_writes_nothing() {
        let root = temp_root("conflict");
        let target = root.join("src").join("existing.rs");
        fs::create_dir_all(target.parent().unwrap()).unwrap();
        fs::write(&target, "user content").unwrap();
        let mut plan = Plan::new().create(target.clone(), "generated".to_owned());
        let err = plan
            .execute(OverwritePolicy::Refuse, None)
            .expect_err("should refuse to overwrite");
        assert!(matches!(err, PlanError::Conflict(p) if p == target));
        // The user file is untouched.
        assert_eq!(fs::read_to_string(&target).unwrap(), "user content");
        cleanup(&root);
    }

    #[test]
    fn dry_run_on_conflict_reports_exact_file() {
        let root = temp_root("dry-conflict");
        let target = root.join("existing.rs");
        fs::write(&target, "user content").unwrap();
        let plan = Plan::new().create(target.clone(), "generated".to_owned());
        let report_result = plan.dry_run_report(OverwritePolicy::Refuse);
        let err = report_result.expect_err("dry-run on conflict should error");
        assert!(matches!(err, PlanError::Conflict(p) if p == target));
        assert_eq!(fs::read_to_string(&target).unwrap(), "user content");
        cleanup(&root);
    }

    #[test]
    fn force_overwrites_and_rollback_restores() {
        let root = temp_root("force");
        let target = root.join("existing.rs");
        fs::write(&target, "user content").unwrap();
        let mut plan = Plan::new().create(target.clone(), "generated".to_owned());
        let _ = plan
            .execute(OverwritePolicy::Overwrite, None)
            .expect("force should overwrite");
        assert_eq!(fs::read_to_string(&target).unwrap(), "generated");
        // Rollback restores the original content (not deletes the file).
        plan.rollback().expect("rollback should restore");
        assert_eq!(fs::read_to_string(&target).unwrap(), "user content");
        cleanup(&root);
    }

    #[test]
    fn validation_failure_rolls_back_leaving_no_partial_files() {
        let root = temp_root("validation-rollback");
        let a = root.join("src").join("a.rs");
        let b = root.join("src").join("b.rs");
        let mut plan = Plan::new()
            .create(a.clone(), "a".to_owned())
            .create(b.clone(), "b".to_owned());
        let result = plan.execute(
            OverwritePolicy::Refuse,
            Some(Box::new(|_| Err("simulated compile failure".to_owned()))),
        );
        let err = result.expect_err("validator failure should error");
        assert!(matches!(err, PlanError::Validation(m) if m.contains("simulated compile failure")));
        assert!(!a.exists(), "rolled-back file must not remain");
        assert!(!b.exists(), "rolled-back file must not remain");
        cleanup(&root);
    }

    #[test]
    fn validation_failure_rolls_back_appends_restoring_original() {
        let root = temp_root("append-rollback");
        let mod_rs = root.join("src").join("links").join("mod.rs");
        fs::create_dir_all(mod_rs.parent().unwrap()).unwrap();
        fs::write(&mod_rs, "pub mod existing;\n").unwrap();
        let original = fs::read_to_string(&mod_rs).unwrap();
        let mut plan = Plan::new()
            .create(
                root.join("src").join("links").join("links_mail.rs"),
                "x".to_owned(),
            )
            .append(mod_rs.clone(), "pub mod links_mail;".to_owned());
        let _ = plan
            .execute(
                OverwritePolicy::Refuse,
                Some(Box::new(|_| Err("fail".to_owned()))),
            )
            .expect_err("validator should fail");
        // The append is undone: mod.rs restored to its original content.
        assert_eq!(fs::read_to_string(&mod_rs).unwrap(), original);
        // The created file is gone.
        assert!(
            !root
                .join("src")
                .join("links")
                .join("links_mail.rs")
                .exists()
        );
        cleanup(&root);
    }

    #[test]
    fn append_is_idempotent_and_creates_file_if_missing() {
        let root = temp_root("append-idempotent");
        let mod_rs = root.join("src").join("fresh").join("mod.rs");
        let mut plan = Plan::new().append(mod_rs.clone(), "pub mod fresh;".to_owned());
        let written = plan
            .execute(OverwritePolicy::Refuse, None)
            .expect("first append should create mod.rs");
        assert_eq!(written, vec![mod_rs.clone()]);
        assert_eq!(fs::read_to_string(&mod_rs).unwrap(), "pub mod fresh;\n");

        // Second append of the same declaration is a no-op (idempotent).
        let mut plan2 = Plan::new().append(mod_rs.clone(), "pub mod fresh;".to_owned());
        let written2 = plan2
            .execute(OverwritePolicy::Refuse, None)
            .expect("second append should succeed");
        assert!(written2.is_empty(), "idempotent append writes nothing");
        assert_eq!(
            fs::read_to_string(&mod_rs).unwrap(),
            "pub mod fresh;\n",
            "declaration appears exactly once"
        );
        cleanup(&root);
    }

    #[test]
    fn rollback_of_created_append_deletes_the_file() {
        let root = temp_root("append-delete-rollback");
        let mod_rs = root.join("src").join("fresh").join("mod.rs");
        // The file does not exist; an append would create it.
        let mut plan = Plan::new().append(mod_rs.clone(), "pub mod fresh;".to_owned());
        let _ = plan
            .execute(
                OverwritePolicy::Refuse,
                Some(Box::new(|_| Err("fail".to_owned()))),
            )
            .expect_err("validator should fail");
        assert!(
            !mod_rs.exists(),
            "created-by-append file must be removed on rollback"
        );
        cleanup(&root);
    }

    #[test]
    fn empty_plan_is_empty_and_commits_nothing() {
        let mut plan = Plan::new();
        assert!(plan.is_empty());
        let written = plan
            .execute(OverwritePolicy::Refuse, None)
            .expect("empty plan commits cleanly");
        assert!(written.is_empty());
    }

    #[test]
    fn multi_file_transaction_is_atomic_on_success() {
        let root = temp_root("multi");
        let file = root.join("src").join("links").join("links_mail.rs");
        let mod_rs = root.join("src").join("links").join("mod.rs");
        let mut plan = Plan::new()
            .create(file.clone(), "pub fn build() {}".to_owned())
            .append(mod_rs.clone(), "pub mod links_mail;".to_owned());
        let written = plan
            .execute(OverwritePolicy::Refuse, None)
            .expect("multi-file commit should succeed");
        assert_eq!(written.len(), 2);
        assert!(file.is_file());
        assert!(mod_rs.is_file());
        assert!(
            fs::read_to_string(&mod_rs)
                .unwrap()
                .contains("pub mod links_mail;")
        );
        cleanup(&root);
    }

    #[test]
    fn append_mod_declaration_op_builds_valid_op() {
        let root = temp_root("mod-op");
        let op = append_mod_declaration_op(&root.join("src"), "links", "links_mail")
            .expect("op should build");
        match op {
            PlannedOp::Append { path, declaration } => {
                assert_eq!(path, root.join("src").join("links").join("mod.rs"));
                assert_eq!(declaration, "pub mod links_mail;");
            }
            PlannedOp::Create { .. } => panic!("expected an Append op"),
        }
        cleanup(&root);
    }
}