anesis 0.12.3

CLI for scaffolding projects from remote templates and extending them with project addons
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
use std::{collections::HashMap, fs, path::Path};

use anyhow::{Context, Result, anyhow};
use colored::Colorize;
use inquire::{Confirm, Select, Text};

use crate::{
  context::AppContext,
  manifest::AnesisManifest,
  templates::generator::{to_camel_case, to_kebab_case, to_pascal_case, to_snake_case},
  utils::{
    picker::{ItemKind, PickItem, pick_one},
    ui::spinner,
  },
};

use super::{
  detect::detect_variant,
  install::{fetch_latest_version, install_addon, read_cached_manifest, record_addon_use},
  lock::{LockEntry, LockFile},
  manifest::{AddonCommand, InputDef, InputType},
  steps::{
    Rollback, append::execute_append, copy::execute_copy, create::execute_create,
    delete::execute_delete, inject::execute_inject, move_step::execute_move,
    packages::execute_packages, rename::execute_rename, replace::execute_replace, run::execute_run,
  },
};
use crate::addons::manifest::Step;

pub async fn run_addon_command(
  ctx: &AppContext,
  addon_id: &str,
  command_name: &str,
  project_root: &Path,
  presets: &HashMap<String, String>,
  non_interactive: bool,
  dry_run: bool,
) -> Result<()> {
  // A dry run never prompts and never writes; it collects inputs from presets
  // and defaults, then prints the plan.
  let non_interactive = non_interactive || dry_run;
  let addon_dir = ctx.paths.addons.join(addon_id);
  let cached = super::cache::get_cached_addon(&ctx.paths.addons, addon_id)?;

  // If the addon is already cached, run from cache immediately and check for a newer
  // version in the background — the network round-trip then overlaps with the
  // interactive prompts below instead of blocking before anything runs.
  // ponytail: this invocation runs the cached addon; a newer version (if any) is
  // pulled into the cache at the end and used on the next run (npx-style).
  let (manifest, update_check) = if let Some(cached) = cached.filter(|_| addon_dir.exists()) {
    let manifest = read_cached_manifest(&ctx.paths.addons, addon_id)?;
    let handle = tokio::spawn(super::install::check_addon_update(
      ctx.client.clone(),
      ctx.backend_url.clone(),
      ctx.paths.auth.clone(),
      addon_id.to_string(),
      cached.commit_sha,
    ));
    (manifest, Some(handle))
  } else {
    // Not cached yet: we must download before we can run anything.
    let sp = spinner(format!("Fetching addon '{addon_id}'..."));
    let install_result = install_addon(ctx, addon_id)
      .await
      .inspect_err(|_| sp.finish_and_clear())?;
    sp.finish_and_clear();
    if let Some(message) = install_result.message(addon_id) {
      println!("{message}");
    }
    (install_result.into_manifest(), None)
  };

  let mut lock = LockFile::load(project_root)?;

  for dep_id in &manifest.requires {
    if !lock.addons.iter().any(|e| &e.id == dep_id) {
      return Err(anyhow!(
        "Addon '{}' requires '{}' to be applied in this project first. Run: anesis use {} <command>",
        addon_id,
        dep_id,
        dep_id
      ));
    }
  }

  let detected_id = detect_variant(&manifest.detect, project_root);

  let variant = manifest
    .variants
    .iter()
    .find(|v| v.when.as_deref() == detected_id.as_deref())
    .or_else(|| manifest.variants.iter().find(|v| v.when.is_none()))
    .ok_or_else(|| anyhow!("No matching variant found for addon '{}'", addon_id))?;

  let command = variant
    .commands
    .iter()
    .find(|c| c.name == command_name)
    .ok_or_else(|| {
      anyhow!(
        "Command '{}' not found in addon '{}'",
        command_name,
        addon_id
      )
    })?;

  if !dry_run && command.once && lock.is_command_executed(addon_id, command_name) {
    if let Some(prompt_message) = rerun_prompt_message(
      command_name,
      lock.addon_version(addon_id),
      &manifest.version,
    ) {
      let rerun = if non_interactive {
        false
      } else {
        Confirm::new(&prompt_message).with_default(false).prompt()?
      };
      if !rerun {
        println!("Skipping command '{}'.", command_name);
        return Ok(());
      }
    } else {
      println!(
        "Command '{}' has already been executed, skipping.",
        command_name
      );
      return Ok(());
    }
  }

  for req_cmd in &command.requires_commands {
    if !lock.is_command_executed(addon_id, req_cmd) {
      return Err(anyhow!(
        "Command '{}' requires '{}' to be run first. Run: anesis use {} {}",
        command_name,
        req_cmd,
        addon_id,
        req_cmd
      ));
    }
  }

  // Prompt for inputs only after the variant/command are resolved and the `once`
  // and prerequisite-command checks have passed, so the user is never asked to
  // fill in values for a command that will be skipped or rejected.
  let mut tera_ctx = tera::Context::new();

  let mut input_values: HashMap<String, String> = HashMap::new();
  collect_inputs(
    &manifest.inputs,
    presets,
    non_interactive,
    &mut input_values,
  )?;
  insert_with_derived(&mut tera_ctx, &input_values);

  let mut cmd_input_values: HashMap<String, String> = HashMap::new();
  collect_inputs(
    &command.inputs,
    presets,
    non_interactive,
    &mut cmd_input_values,
  )?;
  insert_with_derived(&mut tera_ctx, &cmd_input_values);

  if dry_run {
    print_dry_run_plan(
      addon_id,
      command_name,
      detected_id.as_deref(),
      &input_values,
      &cmd_input_values,
      &command.steps,
    );
    return Ok(());
  }

  if !confirm_addon_execution(addon_id, command_name, &command.steps, non_interactive)? {
    println!("Aborted. No changes were made.");
    return Ok(());
  }

  let addon_dir = ctx.paths.addons.join(addon_id);
  let total = command.steps.len();
  let mut completed_rollbacks: Vec<Rollback> = Vec::new();
  for (idx, step) in command.steps.iter().enumerate() {
    let label = step_label(step);
    // Announce each step before it runs so the user can see exactly where an
    // addon stalls or fails, rather than staring at a silent hang.
    println!("{} {}", format!("[{}/{}]", idx + 1, total).dimmed(), label);

    let result = match step {
      Step::Copy(s) => execute_copy(s, &addon_dir, project_root),
      Step::Create(s) => execute_create(s, project_root, &tera_ctx),
      Step::Inject(s) => execute_inject(s, project_root, &tera_ctx),
      Step::Replace(s) => execute_replace(s, project_root, &tera_ctx),
      Step::Append(s) => execute_append(s, project_root, &tera_ctx),
      Step::Delete(s) => execute_delete(s, project_root),
      Step::Rename(s) => execute_rename(s, project_root, &tera_ctx),
      Step::Move(s) => execute_move(s, project_root, &tera_ctx),
      Step::Packages(s) => execute_packages(s, project_root),
      Step::Run(s) => execute_run(s, project_root, &tera_ctx, non_interactive),
    }
    // Naming the step here upgrades every bare error a step can raise (e.g. a
    // `std::fs::read` "No such file or directory") into one that says which
    // step and file it came from, so the user knows what to fix.
    .with_context(|| format!("step {} ({}) failed", idx + 1, label));

    match result {
      Ok(rollbacks) => completed_rollbacks.extend(rollbacks),
      Err(err) => {
        eprintln!("{} {:#}", "".red().bold(), err);
        // Non-interactive runs can't prompt; roll back to leave a clean tree.
        let choice = if non_interactive {
          "Rollback all changes"
        } else {
          Select::new(
            "How would you like to proceed?",
            vec!["Keep changes made so far", "Rollback all changes"],
          )
          .prompt()?
        };

        if choice == "Rollback all changes" {
          for rollback in completed_rollbacks.into_iter().rev() {
            let _ = apply_rollback(rollback, project_root);
          }
          println!("Rolled back all changes made by this command.");
        }

        return Err(err);
      }
    }
  }

  let variant_id = detected_id.unwrap_or_else(|| "universal".to_string());
  // Accumulate this run's inversions and inputs onto the addon's entry rather than
  // replacing them, so `undo` reverts every command that ran and `update` can
  // replay them all with the same inputs. Journal stays in execution order across
  // commands, so reversing the whole thing unwinds them last-first.
  if let Some(existing) = lock.addons.iter_mut().find(|e| e.id == addon_id) {
    existing.version = manifest.version.clone();
    existing.variant = variant_id;
    existing.journal.extend(completed_rollbacks);
    existing.inputs.extend(
      input_values
        .iter()
        .chain(&cmd_input_values)
        .map(|(k, v)| (k.clone(), v.clone())),
    );
  } else {
    let mut inputs = input_values.clone();
    inputs.extend(cmd_input_values.iter().map(|(k, v)| (k.clone(), v.clone())));
    lock.addons.push(LockEntry {
      id: addon_id.to_string(),
      version: manifest.version.clone(),
      variant: variant_id,
      commands_executed: Vec::new(),
      journal: completed_rollbacks,
      inputs,
    });
  }
  lock.mark_command_executed(addon_id, command_name);
  lock.save(project_root)?;

  record_addon_use(ctx, addon_id).await;

  if let Err(err) = AnesisManifest::add_addon(addon_id, project_root) {
    eprintln!("Note: could not update anesis.json ({err}).");
  }
  println!("✓ Command '{}' completed successfully.", command_name);

  // The command ran on the cached addon; if the background check found a newer
  // version, pull it into the cache now (execution is finished, so re-extracting is
  // safe) so the next run picks it up.
  if let Some(handle) = update_check
    && matches!(handle.await, Ok(Some(_)))
  {
    let sp = spinner(format!(
      "A newer version of '{addon_id}' is available, updating..."
    ));
    let updated = install_addon(ctx, addon_id).await;
    sp.finish_and_clear();
    match updated {
      Ok(result) => {
        if let Some(message) = result.update_message(addon_id) {
          println!("{message} (will be used next time)");
        }
      }
      Err(err) => eprintln!("Note: could not update addon '{addon_id}' ({err})."),
    }
  }

  Ok(())
}

/// Prints the commands an addon exposes for the current project. Used by
/// `anesis use <addon>` when no command name is given, so users can discover
/// what's runnable without having to read the manifest.
pub async fn list_addon_commands(
  ctx: &AppContext,
  addon_id: &str,
  project_root: &Path,
  presets: &HashMap<String, String>,
  non_interactive: bool,
  dry_run: bool,
) -> Result<()> {
  let addon_dir = ctx.paths.addons.join(addon_id);
  let cached = super::cache::get_cached_addon(&ctx.paths.addons, addon_id)?;
  let manifest = if cached.is_some() && addon_dir.exists() {
    read_cached_manifest(&ctx.paths.addons, addon_id)?
  } else {
    let sp = spinner(format!("Fetching addon '{addon_id}'..."));
    let result = install_addon(ctx, addon_id)
      .await
      .inspect_err(|_| sp.finish_and_clear())?;
    sp.finish_and_clear();
    result.into_manifest()
  };

  // Show commands for the variant matching this project; fall back to every
  // command across all variants when nothing matches (e.g. run outside a project).
  let detected_id = detect_variant(&manifest.detect, project_root);
  let matched = manifest
    .variants
    .iter()
    .find(|v| v.when.as_deref() == detected_id.as_deref())
    .or_else(|| manifest.variants.iter().find(|v| v.when.is_none()));
  let commands: Vec<&AddonCommand> = match matched {
    Some(variant) => variant.commands.iter().collect(),
    None => manifest.variants.iter().flat_map(|v| &v.commands).collect(),
  };

  if commands.is_empty() {
    println!("Addon '{addon_id}' has no commands available for this project.");
    return Ok(());
  }

  // Let the user pick a command interactively, then run the chosen one.
  let items: Vec<PickItem> = commands
    .iter()
    .map(|c| PickItem {
      kind: ItemKind::Addon,
      id: c.name.clone(),
      name: c.name.clone(),
      meta: String::new(),
      description: c.description.clone(),
      haystack: format!("{} {}", c.name, c.description).to_lowercase(),
    })
    .collect();

  match pick_one(
    items,
    format!("Commands for {addon_id}"),
    false,
    String::new(),
  )
  .await?
  {
    Some((_, command_name, _)) => {
      run_addon_command(
        ctx,
        addon_id,
        &command_name,
        project_root,
        presets,
        non_interactive,
        dry_run,
      )
      .await
    }
    None => Ok(()),
  }
}

/// A short human-readable description of what a step does, used both for the
/// per-step progress line and for error context so the user can see which file
/// a failure came from.
fn step_label(step: &Step) -> String {
  use crate::addons::manifest::Target;
  fn target(t: &Target) -> &str {
    match t {
      Target::File { file } => file,
      Target::Glob { glob } => glob,
    }
  }
  match step {
    Step::Copy(s) => format!("copy '{}' → '{}'", s.src, s.dest),
    Step::Create(s) => format!("create '{}'", s.path),
    Step::Inject(s) => format!("inject into '{}'", target(&s.target)),
    Step::Replace(s) => format!("replace in '{}'", target(&s.target)),
    Step::Append(s) => format!("append to '{}'", target(&s.target)),
    Step::Delete(s) => format!("delete '{}'", target(&s.target)),
    Step::Rename(s) => format!("rename '{}' → '{}'", s.from, s.to),
    Step::Move(s) => format!("move '{}' → '{}'", s.from, s.to),
    Step::Packages(s) => format!(
      "install {} package(s)",
      s.dependencies.len() + s.dev_dependencies.len()
    ),
    Step::Run(s) => format!("run '{}'", s.command),
  }
}

/// Prints the resolved plan for `--dry-run`: the selected variant, the inputs
/// that were collected (from presets/defaults), and each step in order. Writes
/// nothing to disk.
fn print_dry_run_plan(
  addon_id: &str,
  command_name: &str,
  variant: Option<&str>,
  addon_inputs: &HashMap<String, String>,
  cmd_inputs: &HashMap<String, String>,
  steps: &[Step],
) {
  println!(
    "{} {} {}",
    "Dry run:".bold(),
    addon_id.cyan(),
    command_name.cyan()
  );
  println!(
    "  {} {}",
    "variant:".dimmed(),
    variant.unwrap_or("universal")
  );

  let mut inputs: Vec<(&String, &String)> = addon_inputs.iter().chain(cmd_inputs.iter()).collect();
  inputs.sort_by(|a, b| a.0.cmp(b.0));
  if inputs.is_empty() {
    println!("  {} (none)", "inputs:".dimmed());
  } else {
    println!("  {}", "inputs:".dimmed());
    for (k, v) in inputs {
      println!("    {k} = {v}");
    }
  }

  println!("  {} {} step(s)", "steps:".dimmed(), steps.len());
  for (idx, step) in steps.iter().enumerate() {
    println!(
      "    {} {}",
      format!("[{}/{}]", idx + 1, steps.len()).dimmed(),
      step_label(step)
    );
  }
  println!("\nNo files were changed.");
}

fn confirm_addon_execution(
  addon_id: &str,
  command_name: &str,
  steps: &[Step],
  non_interactive: bool,
) -> Result<bool> {
  if non_interactive {
    return Ok(true);
  }
  let (mut writes, mut edits, mut removes) = (0usize, 0usize, 0usize);
  for step in steps {
    match step {
      Step::Create(_) | Step::Copy(_) => writes += 1,
      Step::Inject(_) | Step::Replace(_) | Step::Append(_) | Step::Packages(_) | Step::Run(_) => {
        edits += 1
      }
      Step::Delete(_) | Step::Rename(_) | Step::Move(_) => removes += 1,
    }
  }

  println!(
    "⚠ Addon '{addon_id}' command '{command_name}' will modify files in this project \
     ({writes} created/copied, {edits} edited, {removes} deleted/moved)."
  );
  println!(
    "  Addons run unsandboxed and can overwrite source files or 'package.json'. \
     Only run addons you trust."
  );

  Ok(Confirm::new("Proceed?").with_default(false).prompt()?)
}

fn rerun_prompt_message(
  command_name: &str,
  locked_version: Option<&str>,
  current_version: &str,
) -> Option<String> {
  let locked_version = locked_version.filter(|version| !version.is_empty())?;
  if locked_version == current_version {
    return None;
  }

  Some(format!(
    "Command '{}' was last run with v{} of this add-on. A new version (v{}) is available. Re-run it now?",
    command_name, locked_version, current_version
  ))
}

#[doc(hidden)]
pub fn rerun_prompt_message_for_tests(
  command_name: &str,
  locked_version: Option<&str>,
  current_version: &str,
) -> Option<String> {
  rerun_prompt_message(command_name, locked_version, current_version)
}

/// Resolves input values: a preset (`--input`) wins, else the default; in
/// interactive mode a missing value is prompted, otherwise a required input with
/// no default is an error. Shared by the addon runner and template scaffolding.
pub fn collect_inputs(
  inputs: &[InputDef],
  presets: &HashMap<String, String>,
  non_interactive: bool,
  map: &mut HashMap<String, String>,
) -> Result<()> {
  let mut missing: Vec<&str> = Vec::new();
  for input in inputs {
    // A value passed via --input always wins, in both interactive and
    // non-interactive modes, and is never re-prompted.
    if let Some(preset) = presets.get(&input.name) {
      map.insert(input.name.clone(), preset.clone());
      continue;
    }
    if non_interactive {
      // No preset: fall back to the default. A required input without a
      // default can't be resolved without a prompt, so collect it and error.
      match &input.default {
        Some(default) => {
          map.insert(input.name.clone(), default.clone());
        }
        None if input.required => missing.push(&input.name),
        None => {
          let fallback = match input.input_type {
            InputType::Boolean => "false".to_string(),
            _ => String::new(),
          };
          map.insert(input.name.clone(), fallback);
        }
      }
      continue;
    }
    let value = match input.input_type {
      InputType::Text => loop {
        let mut prompt = Text::new(&input.description);
        if let Some(ref default) = input.default {
          prompt = prompt.with_default(default);
        }
        let value = prompt.prompt()?;
        if input.required && value.trim().is_empty() {
          eprintln!("'{}' is required; please enter a value.", input.name);
          continue;
        }
        break value;
      },
      InputType::Boolean => {
        let default = input
          .default
          .as_deref()
          .map(|d| d == "true")
          .unwrap_or(false);
        Confirm::new(&input.description)
          .with_default(default)
          .prompt()?
          .to_string()
      }
      InputType::Select => Select::new(&input.description, input.options.clone())
        .prompt()?
        .to_string(),
    };
    map.insert(input.name.clone(), value);
  }
  if !missing.is_empty() {
    return Err(anyhow!(
      "Missing required input(s) in non-interactive mode: {}. Provide them with --input NAME=VALUE.",
      missing.join(", ")
    ));
  }
  Ok(())
}

fn insert_with_derived(ctx: &mut tera::Context, map: &HashMap<String, String>) {
  for (k, v) in map {
    ctx.insert(k.as_str(), v);
    ctx.insert(format!("{k}_pascal"), &to_pascal_case(v));
    ctx.insert(format!("{k}_camel"), &to_camel_case(v));
    ctx.insert(format!("{k}_kebab"), &to_kebab_case(v));
    ctx.insert(format!("{k}_snake"), &to_snake_case(v));
  }
}

/// Removes now-empty directories walking up from `start` toward (but not
/// including) `project_root`, stopping at the first non-empty or undeletable
/// directory. Used to clean up parent directories that a step's
/// `create_dir_all` left behind once its file is removed/moved back.
fn prune_empty_dirs(start: Option<&Path>, project_root: &Path) {
  let mut dir = start;
  while let Some(d) = dir {
    if d == project_root || fs::remove_dir(d).is_err() {
      break;
    }
    dir = d.parent();
  }
}

/// Reverts the last applied command-set of `addon_id` by replaying its stored
/// inversion journal in reverse. Any file that no longer exists is reported as a
/// conflict; unless `non_interactive`, the user is asked to confirm before the
/// journal is applied.
// ponytail: conflict detection is existence-only — we don't store post-apply
// hashes, so a file edited-in-place after the addon ran is silently overwritten
// back to its pre-addon content. Store an expected-content hash per RestoreFile
// if that ceiling ever bites.
pub fn undo_addon(addon_id: &str, project_root: &Path, non_interactive: bool) -> Result<()> {
  let mut lock = LockFile::load(project_root)?;
  let entry = lock
    .addons
    .iter()
    .find(|e| e.id == addon_id)
    .filter(|e| !e.journal.is_empty())
    .ok_or_else(|| {
      anyhow!("Addon '{addon_id}' has no undoable changes recorded in this project.")
    })?;

  let mut conflicts: Vec<String> = Vec::new();
  for rollback in &entry.journal {
    match rollback {
      Rollback::DeleteCreatedFile { path } if !path.exists() => {
        conflicts.push(format!("{} (already deleted)", path.display()));
      }
      Rollback::RestoreFile { path, .. } if !path.exists() => {
        conflicts.push(format!("{} (missing)", path.display()));
      }
      Rollback::RenameFile { to, .. } if !to.exists() => {
        conflicts.push(format!("{} (missing)", to.display()));
      }
      _ => {}
    }
  }

  if !conflicts.is_empty() {
    eprintln!(
      "{} some files changed since '{addon_id}' was applied:",
      "".yellow().bold()
    );
    for c in &conflicts {
      eprintln!("  {c}");
    }
  }

  if !non_interactive
    && !Confirm::new(&format!("Undo addon '{addon_id}'?"))
      .with_default(conflicts.is_empty())
      .prompt()?
  {
    println!("Aborted. No changes were made.");
    return Ok(());
  }

  let entry = lock.addons.iter_mut().find(|e| e.id == addon_id).unwrap();
  let journal = std::mem::take(&mut entry.journal);
  for rollback in journal.into_iter().rev() {
    apply_rollback(rollback, project_root)?;
  }

  lock.remove_addon(addon_id);
  lock.save(project_root)?;

  if let Err(err) = AnesisManifest::remove_addon(addon_id, project_root) {
    eprintln!("Note: could not update anesis.json ({err}).");
  }

  println!("✓ Reverted addon '{addon_id}'.");
  Ok(())
}

/// True if `latest` is a strictly newer semver than `current`. Falls back to a
/// plain string inequality if either version can't be parsed as semver, so a
/// non-standard version scheme still flags *some* change rather than none.
fn is_newer(latest: &str, current: &str) -> bool {
  match (
    semver::Version::parse(latest),
    semver::Version::parse(current),
  ) {
    (Ok(l), Ok(c)) => l > c,
    _ => latest != current,
  }
}

#[doc(hidden)]
pub fn is_newer_for_tests(latest: &str, current: &str) -> bool {
  is_newer(latest, current)
}

/// Compares each applied addon's locked version against the registry's latest and
/// prints the ones that have a newer version available.
pub async fn outdated(ctx: &AppContext, project_root: &Path) -> Result<()> {
  let lock = LockFile::load(project_root)?;
  if lock.addons.is_empty() {
    println!("No addons applied in this project.");
    return Ok(());
  }

  let mut any = false;
  for entry in &lock.addons {
    match fetch_latest_version(ctx, &entry.id).await {
      Ok(latest) if is_newer(&latest, &entry.version) => {
        any = true;
        println!(
          "  {} v{} → v{}",
          entry.id.cyan(),
          entry.version,
          latest.green()
        );
      }
      Ok(_) => {}
      Err(err) => eprintln!("  {} (could not check: {err:#})", entry.id.dimmed()),
    }
  }
  if !any {
    println!("All addons are up to date.");
  } else {
    println!("\nRun `anesis update <addon_id>` to upgrade.");
  }
  Ok(())
}

/// Upgrades an applied addon to the registry's latest version: reverts the old
/// version's changes, installs the new one, then replays the same commands with
/// the inputs saved in `anesis.lock`.
pub async fn update_addon(
  ctx: &AppContext,
  addon_id: &str,
  project_root: &Path,
  non_interactive: bool,
) -> Result<()> {
  let (current, commands, saved_inputs, had_journal) = {
    let lock = LockFile::load(project_root)?;
    let entry = lock
      .addons
      .iter()
      .find(|e| e.id == addon_id)
      .ok_or_else(|| anyhow!("Addon '{addon_id}' is not applied in this project."))?;
    (
      entry.version.clone(),
      entry.commands_executed.clone(),
      entry.inputs.clone(),
      !entry.journal.is_empty(),
    )
  };

  let latest = fetch_latest_version(ctx, addon_id).await?;
  if !is_newer(&latest, &current) {
    println!("Addon '{addon_id}' is already up to date (v{current}).");
    return Ok(());
  }

  println!("Updating '{addon_id}' v{current} → v{latest}...");

  // Revert the old version (implied by the update, so don't re-prompt), then make
  // sure the new version is in the cache before replaying.
  if had_journal {
    undo_addon(addon_id, project_root, true)?;
  } else {
    // No reversible changes recorded — just drop the stale lock entry so the
    // replay below isn't skipped by the `once` guard.
    let mut lock = LockFile::load(project_root)?;
    lock.remove_addon(addon_id);
    lock.save(project_root)?;
    let _ = AnesisManifest::remove_addon(addon_id, project_root);
  }
  install_addon(ctx, addon_id).await?;

  for cmd in &commands {
    run_addon_command(
      ctx,
      addon_id,
      cmd,
      project_root,
      &saved_inputs,
      non_interactive,
      false,
    )
    .await?;
  }

  println!("✓ Updated '{addon_id}' to v{latest}.");
  Ok(())
}

fn apply_rollback(rollback: Rollback, project_root: &Path) -> Result<()> {
  match rollback {
    Rollback::DeleteCreatedFile { path } => {
      let _ = std::fs::remove_file(&path);
      prune_empty_dirs(path.parent(), project_root);
    }
    Rollback::RestoreFile { path, original } => {
      std::fs::write(path, original)?;
    }
    Rollback::RenameFile { from, to } => {
      std::fs::rename(&from, to)?;
      // `from` was the move/copy destination; its parent dirs may have been
      // created just for it and are now empty.
      prune_empty_dirs(from.parent(), project_root);
    }
    Rollback::IrreversibleRun { command } => {
      eprintln!(
        "{} could not undo shell command '{}' — its effects remain.",
        "".yellow().bold(),
        command
      );
    }
  }
  Ok(())
}