Skip to main content

calcit_cli/cli_handlers/
edit.rs

1//! Edit and Tree subcommand handlers and shared utilities
2//!
3//! Handles: calcit edit - code editing operations (definitions, namespaces, modules, configs)
4//! Shared by: calcit tree - fine-grained tree operations (replace, insert, delete, swap, wrap)
5//!
6//! Supports code input via:
7//! - `--file <path>` - read from file
8//! - `--code <string>` - inline text
9//! - stdin - pipe or redirect input
10//!
11//! Syntax-node commands select `cirru` or `json-ast` explicitly; `auto` remains for compatibility.
12
13use crate::cli_args::{
14  EditAddImportCommand, EditAddNsCommand, EditAddTestCommand, EditCommand, EditDefCommand, EditFfiCommand, EditFormatCommand,
15  EditImportsCommand, EditMergeCommand, EditMetaCommand, EditMvDefCommand, EditRenameCommand, EditRmDefCommand, EditRmImportCommand,
16  EditRmNsCommand, EditSchemaCommand, EditSplitDefCommand, EditSubcommand, EditTransactionCommand, SyntaxInputFormat,
17};
18use crate::program_diff::{CirruEditStrategy, analyze_cirru_edit_advice};
19use calcit_core::calcit::{CalcitTypeAnnotation, DYNAMIC_TYPE};
20use calcit_core::program::validate_import_rules;
21use calcit_core::snapshot::{
22  self, CodeEntry, FileInSnapShot, NsEntry, Snapshot, TestEntry, render_snapshot_content, save_snapshot_to_file,
23};
24use cirru_edn::{Edn, EdnMapView, EdnStructView, EdnTag};
25use cirru_parser::Cirru;
26use colored::Colorize;
27use md5::{Digest, Md5};
28#[cfg(test)]
29use semver::Version;
30use serde::Serialize;
31use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
32use std::ffi::OsString;
33use std::fs;
34use std::path::Path;
35use std::process::Command;
36use std::sync::Arc;
37
38use calcit_core::util::string::strip_shebang;
39
40use super::atomic_write::stage_atomic_file;
41use super::common::{
42  ERR_CODE_INPUT_REQUIRED, decode_mutation_syntax_input, format_path, guard_snapshot_mutation_toolchain, parse_input_to_cirru,
43  parse_path, parse_quoted_cirru_nodes, print_cli_warning_block, read_code_input, resolve_definition_lookup, shell_quote,
44};
45use super::cursor::{
46  maintain_cursor_after_any_mutation, maintain_cursor_after_definition_delete, maintain_cursor_after_definition_move,
47  maintain_cursor_after_definition_replace, maintain_cursor_after_namespace_delete, maintain_cursor_after_node_move,
48  maintain_cursor_after_split_definition, maintain_cursor_after_tree_mutation, resolve_active_cursor_reference,
49  resolve_cursor_path_argument, resolve_cursor_target_argument,
50};
51use super::handle_scaffold_command;
52use super::structured_output::{StructuredOutputFormat, format_json_value_as_edn};
53use super::tips::{Tips, command_guidance_enabled};
54use super::tree_mutation::{TreeCursorMutation, TreeOperation, adjusted_source_path_after_insertion, path_is_strict_descendant};
55
56/// Parse "namespace/definition" format into (namespace, definition)
57/// Splits at the FIRST '/' so operator definitions like '/' and '/=' are handled correctly.
58pub(crate) fn parse_target(target: &str) -> Result<(&str, &str), String> {
59  target
60    .split_once('/')
61    .ok_or_else(|| format!("Invalid target format: '{target}'. Expected 'namespace/definition' (e.g. 'app.core/main')"))
62}
63
64/// Process a node by replacing placeholders with references to original node or its branches
65pub(crate) fn process_node_with_references(
66  node: &Cirru,
67  references: &std::collections::BTreeMap<String, Cirru>,
68) -> Result<Cirru, String> {
69  match node {
70    Cirru::Leaf(s) => {
71      // Check if this leaf matches any of the placeholders
72      if let Some(replacement) = references.get(s.as_ref()) {
73        return Ok(replacement.clone());
74      }
75      Ok(node.clone())
76    }
77    Cirru::List(items) => {
78      let processed_items: Result<Vec<Cirru>, String> =
79        items.iter().map(|item| process_node_with_references(item, references)).collect();
80      Ok(Cirru::List(processed_items?))
81    }
82  }
83}
84
85pub fn handle_edit_command(cmd: &EditCommand, snapshot_file: &str) -> Result<(), String> {
86  let _writer = if edit_mutates_snapshot(&cmd.subcommand) {
87    Some(calcit_core::util::atomic_write::SnapshotWriteGuard::acquire(snapshot_file)?)
88  } else {
89    None
90  };
91  if edit_mutates_snapshot(&cmd.subcommand) {
92    guard_snapshot_mutation_toolchain(snapshot_file)?;
93  }
94  let mut resolved = cmd.clone();
95  resolve_edit_cursor_references(&mut resolved, snapshot_file)?;
96  let result = match &resolved.subcommand {
97    EditSubcommand::Format(opts) => handle_format(opts, snapshot_file),
98    EditSubcommand::Merge(opts) => handle_merge(opts, snapshot_file),
99    EditSubcommand::Transaction(opts) => handle_transaction(opts, snapshot_file),
100    EditSubcommand::Scaffold(opts) => handle_scaffold_command(opts, snapshot_file),
101    EditSubcommand::Def(opts) => handle_def(opts, snapshot_file),
102    EditSubcommand::MvDef(opts) => handle_mv_def(opts, snapshot_file),
103    EditSubcommand::RmDef(opts) => handle_rm_def(opts, snapshot_file),
104    EditSubcommand::Rename(opts) => handle_rename(opts, snapshot_file),
105    EditSubcommand::SplitDef(opts) => handle_split_def(opts, snapshot_file),
106    EditSubcommand::Meta(opts) => handle_meta(opts, snapshot_file),
107    EditSubcommand::Schema(opts) => handle_schema(opts, snapshot_file),
108    EditSubcommand::Ffi(opts) => handle_ffi(opts, snapshot_file),
109    EditSubcommand::AddTest(opts) => handle_add_test(opts, snapshot_file),
110    EditSubcommand::AddNs(opts) => handle_add_ns(opts, snapshot_file),
111    EditSubcommand::RmNs(opts) => handle_rm_ns(opts, snapshot_file),
112    EditSubcommand::Ns(opts) => super::ns_view::handle_edit_ns(opts, snapshot_file),
113    EditSubcommand::Imports(opts) => handle_imports(opts, snapshot_file),
114    EditSubcommand::AddImport(opts) => handle_add_import(opts, snapshot_file),
115    EditSubcommand::RmImport(opts) => handle_rm_import(opts, snapshot_file),
116  };
117  result?;
118  maintain_cursor_after_edit(&resolved, snapshot_file)
119}
120
121fn edit_mutates_snapshot(cmd: &EditSubcommand) -> bool {
122  match cmd {
123    EditSubcommand::Transaction(opts) => !opts.dry_run,
124    EditSubcommand::Scaffold(opts) => !opts.dry_run,
125    EditSubcommand::Ns(opts) => !opts.dry_run,
126    EditSubcommand::Meta(opts) => !opts.dry_run,
127    // Git owns the merge driver's temporary files; no other writer can race on them.
128    EditSubcommand::Merge(_) => false,
129    _ => true,
130  }
131}
132
133fn resolve_edit_cursor_references(cmd: &mut EditCommand, snapshot_file: &str) -> Result<(), String> {
134  let target = match &mut cmd.subcommand {
135    EditSubcommand::Def(opts) => Some(&mut opts.target),
136    EditSubcommand::MvDef(opts) => Some(&mut opts.source),
137    EditSubcommand::RmDef(opts) => Some(&mut opts.target),
138    EditSubcommand::Meta(opts) => Some(&mut opts.target),
139    EditSubcommand::Schema(opts) => Some(&mut opts.target),
140    EditSubcommand::Ffi(opts) => Some(&mut opts.target),
141    EditSubcommand::AddTest(opts) => Some(&mut opts.target),
142    EditSubcommand::Rename(opts) => Some(&mut opts.source),
143    EditSubcommand::SplitDef(opts) => Some(&mut opts.target),
144    EditSubcommand::Format(_)
145    | EditSubcommand::Merge(_)
146    | EditSubcommand::Transaction(_)
147    | EditSubcommand::Scaffold(_)
148    | EditSubcommand::AddNs(_)
149    | EditSubcommand::RmNs(_)
150    | EditSubcommand::Ns(_)
151    | EditSubcommand::Imports(_)
152    | EditSubcommand::AddImport(_)
153    | EditSubcommand::RmImport(_) => None,
154  };
155  let active_reference = if target.as_deref().is_some_and(|target| target == "@cursor") {
156    Some(resolve_active_cursor_reference(snapshot_file)?)
157  } else {
158    None
159  };
160  if let Some(target) = target {
161    *target = match &active_reference {
162      Some((active_target, _)) => active_target.clone(),
163      None => resolve_cursor_target_argument(snapshot_file, target)?,
164    };
165  }
166
167  let resolve_path = |target: &str, path: &str| -> Result<String, String> {
168    if path == "@cursor"
169      && let Some((active_target, active_path)) = &active_reference
170    {
171      if active_target != target {
172        return Err(format!(
173          "Cursor target mismatch: cursor points to '{active_target}', but command targets '{target}'."
174        ));
175      }
176      Ok(active_path.clone())
177    } else {
178      resolve_cursor_path_argument(snapshot_file, target, path)
179    }
180  };
181
182  if let EditSubcommand::SplitDef(opts) = &mut cmd.subcommand {
183    opts.path = resolve_path(&opts.target, &opts.path)?;
184  }
185  Ok(())
186}
187
188fn maintain_cursor_after_edit(cmd: &EditCommand, snapshot_file: &str) -> Result<(), String> {
189  match &cmd.subcommand {
190    EditSubcommand::Def(opts) => maintain_cursor_after_definition_replace(snapshot_file, &opts.target),
191    EditSubcommand::MvDef(opts) => maintain_cursor_after_definition_move(snapshot_file, &opts.source, &opts.target),
192    EditSubcommand::RmDef(opts) => maintain_cursor_after_definition_delete(snapshot_file, &opts.target),
193    EditSubcommand::RmNs(opts) => maintain_cursor_after_namespace_delete(snapshot_file, &opts.namespace),
194    EditSubcommand::Rename(opts) => {
195      let (namespace, _) = parse_target(&opts.source)?;
196      maintain_cursor_after_definition_move(snapshot_file, &opts.source, &format!("{namespace}/{}", opts.new_name))
197    }
198    EditSubcommand::SplitDef(opts) => {
199      let (namespace, _) = parse_target(&opts.target)?;
200      maintain_cursor_after_split_definition(
201        snapshot_file,
202        &opts.target,
203        &parse_path(&opts.path)?,
204        &format!("{namespace}/{}", opts.new_name),
205      )
206    }
207    EditSubcommand::Meta(opts) if !opts.dry_run => {
208      maintain_cursor_after_tree_mutation(snapshot_file, &opts.target, &TreeCursorMutation::NoPathShift)
209    }
210    EditSubcommand::Schema(opts) => maintain_cursor_after_tree_mutation(snapshot_file, &opts.target, &TreeCursorMutation::NoPathShift),
211    EditSubcommand::Ffi(opts) => maintain_cursor_after_tree_mutation(snapshot_file, &opts.target, &TreeCursorMutation::NoPathShift),
212    EditSubcommand::AddTest(opts) => maintain_cursor_after_tree_mutation(snapshot_file, &opts.target, &TreeCursorMutation::NoPathShift),
213    EditSubcommand::Transaction(opts) if !opts.dry_run => {
214      maintain_cursor_after_any_mutation(snapshot_file, "validated after edit transaction")
215    }
216    EditSubcommand::Scaffold(opts) if !opts.dry_run => {
217      maintain_cursor_after_any_mutation(snapshot_file, "validated after scaffold apply")
218    }
219    EditSubcommand::Ns(opts) if !opts.dry_run => maintain_cursor_after_any_mutation(snapshot_file, "validated after edit ns"),
220    _ => Ok(()),
221  }
222}
223
224/// Merge `--theirs` into this Snapshot relative to `--base`, one definition at a time.
225/// The result is written in canonical format; conflicting units keep our version
226/// and make the command fail so Git reports the conflict.
227fn handle_merge(opts: &EditMergeCommand, snapshot_file: &str) -> Result<(), String> {
228  let base = load_snapshot(&opts.base)?;
229  let ours = load_snapshot(snapshot_file)?;
230  let theirs = load_snapshot(&opts.theirs)?;
231  let result = super::snapshot_scope::merge_snapshots(&base, &ours, &theirs)?;
232  let content = render_snapshot_content(&result.merged)?;
233  fs::write(snapshot_file, content.as_bytes()).map_err(|error| format!("Failed to write merged Snapshot {snapshot_file}: {error}"))?;
234  if result.conflicts.is_empty() {
235    println!("{} Merged Snapshot per definition into '{}'", "✓".green(), snapshot_file.cyan());
236    println!("Run `calcit --check-only` and the project tests before committing the merge.");
237    return Ok(());
238  }
239  println!("# Snapshot merge conflicts\n");
240  println!("Both sides changed these units differently; the file keeps our version of each:\n");
241  for unit in &result.conflicts {
242    println!("- `{unit}`");
243    if let Some(path) = unit.strip_prefix("def:")
244      && let Some((namespace, definition)) = path.split_once('/')
245    {
246      for (label, side) in [("base", &base), ("ours", &ours), ("theirs", &theirs)] {
247        match side.files.get(namespace).and_then(|file| file.defs.get(definition)) {
248          Some(entry) => println!(
249            "  - {label}: `{}`",
250            entry.code.format_one_liner().unwrap_or_else(|_| "(unprintable)".to_owned())
251          ),
252          None => println!("  - {label}: _(absent)_"),
253        }
254      }
255    }
256  }
257  Err(format!(
258    "{} Snapshot unit(s) conflict; resolve them with `calcit edit`, then run `calcit --check-only`",
259    result.conflicts.len()
260  ))
261}
262
263/// Namespaces of every module the snapshot's entries load, so `edit format`
264/// does not shorten a type name to an alias that a dependency namespace
265/// shadows. `None` when a module cannot be loaded.
266fn load_dependency_namespaces(snapshot: &snapshot::Snapshot, snapshot_file: &str) -> Option<HashSet<String>> {
267  let base_dir = Path::new(snapshot_file).parent().unwrap_or_else(|| Path::new("."));
268  let module_folder = calcit_core::project_module_folder(base_dir);
269  let mut namespaces = HashSet::new();
270  let mut seen = HashSet::new();
271  for entry in snapshot.entries.values() {
272    for module_path in &entry.modules {
273      if !seen.insert(module_path.clone()) {
274        continue;
275      }
276      let module = calcit_core::load_module(module_path, base_dir, &module_folder).ok()?;
277      namespaces.extend(module.files.keys().cloned());
278    }
279  }
280  Some(namespaces)
281}
282
283fn handle_format(opts: &EditFormatCommand, snapshot_file: &str) -> Result<(), String> {
284  let original_content = fs::read_to_string(snapshot_file).map_err(|e| format!("Failed to read {snapshot_file}: {e}"))?;
285  let mut original_edn = cirru_edn::parse(&original_content).map_err(|e| format!("Failed to parse EDN: {e}"))?;
286  let dropped_fields = snapshot::drop_legacy_entry_fields(&mut original_edn, &opts.drop_legacy_entry_fields)?;
287  let (mut snapshot, legacy_migration) =
288    snapshot::load_snapshot_data_for_format(&original_edn, snapshot_file).map_err(|e| format!("Failed to load snapshot: {e}"))?;
289  let advisories = collect_format_advisories(snapshot_file, &snapshot);
290  let stripped_require_lists = snapshot::canonicalize_snapshot_require_lists(&mut snapshot);
291  let canonicalized_type_forms = snapshot::canonicalize_snapshot_type_syntax(&mut snapshot);
292  let shortened_options = snapshot::shorten_snapshot_option_constructors(&mut snapshot);
293  let dependency_namespaces = load_dependency_namespaces(&snapshot, snapshot_file);
294  let shortened_type_names = snapshot::shorten_snapshot_type_names(&mut snapshot, dependency_namespaces.as_ref());
295  let formatted_content = render_snapshot_content(&snapshot)?;
296
297  if formatted_content == original_content {
298    println!("{} No formatting changes for '{}'", "·".dimmed(), snapshot_file.dimmed());
299  } else {
300    calcit_core::util::atomic_write::write_snapshot(snapshot_file, formatted_content.as_bytes())?;
301    println!("{} Formatted snapshot file '{}'", "✓".green(), snapshot_file.cyan());
302  }
303  if stripped_require_lists > 0 {
304    println!(
305      "{} Stripped legacy `[]` marker(s) from {stripped_require_lists} `:require` rule(s)",
306      "✓".green()
307    );
308  }
309  if canonicalized_type_forms > 0 {
310    println!(
311      "{} Rewrote {canonicalized_type_forms} type form(s) to the current type syntax",
312      "✓".green()
313    );
314  }
315  if shortened_options > 0 {
316    println!(
317      "{} Rewrote {shortened_options} `Option :some` / `Option :none` form(s) to `Some` / `None`",
318      "✓".green()
319    );
320  }
321  if shortened_type_names > 0 {
322    println!(
323      "{} Shortened {shortened_type_names} fully qualified type name(s) in schemas to the name the namespace resolves",
324      "✓".green()
325    );
326  }
327  for (field, value) in &dropped_fields {
328    println!("{} Dropped legacy entry field `{field}`: {value}", "✓".green());
329  }
330  if legacy_migration.happened() {
331    println!(
332      "{} Migrated legacy Snapshot data: {} namespace quote(s), {} definition quote(s), configs={}",
333      "✓".green(),
334      legacy_migration.direct_quote_namespaces,
335      legacy_migration.direct_quote_definitions,
336      legacy_migration.legacy_configs
337    );
338  }
339
340  for advisory in advisories {
341    print_cli_warning_block(&advisory);
342  }
343  Ok(())
344}
345
346fn collect_format_advisories(snapshot_file: &str, snapshot: &Snapshot) -> Vec<String> {
347  let mut advisories = vec![];
348  let snapshot_arg = shell_quote(snapshot_file);
349
350  let selected = std::collections::BTreeSet::from([
351    crate::type_coverage::WeakTypeKind::SchemaDynamic,
352    crate::type_coverage::WeakTypeKind::UnresolvedTypeSlot,
353    crate::type_coverage::WeakTypeKind::CodeDynamic,
354  ]);
355  let mut unresolved_dynamic_occurrences = 0usize;
356  let mut unresolved_dynamic_definitions = 0usize;
357  for (namespace, file) in &snapshot.files {
358    if namespace.ends_with(".$meta") || !(namespace == &snapshot.package || namespace.starts_with(&format!("{}.", snapshot.package))) {
359      continue;
360    }
361    for (definition, entry) in &file.defs {
362      if let Some(row) = crate::type_coverage::analyze_weak_types_entry(namespace, definition, entry, &selected) {
363        let hits = row
364          .occurrences
365          .iter()
366          .filter(|occurrence| occurrence.intent == crate::type_coverage::WeakTypeIntent::Unresolved)
367          .count();
368        if hits > 0 {
369          unresolved_dynamic_definitions += 1;
370          unresolved_dynamic_occurrences += hits;
371        }
372      }
373    }
374  }
375  if unresolved_dynamic_occurrences > 0 {
376    advisories.push(format!(
377      "[W_DYNAMIC_TYPE_DEBT] Found {unresolved_dynamic_occurrences} unresolved dynamic or unbound type-slot occurrence(s) in {unresolved_dynamic_definitions} local definition(s); formatting does not guess or rewrite semantic type contracts.\n\
378       Next: run `calcit {snapshot_arg} analyze weak-types --only schema-dynamic,unresolved-type-slot,code-dynamic --intent unresolved --summary-only`, then rerun without `--summary-only` for paths and recommendations."
379    ));
380  }
381
382  advisories
383}
384
385fn edn_key_matches(value: &Edn, expected: &str) -> bool {
386  match value {
387    Edn::Tag(tag) => tag.ref_str() == expected,
388    Edn::Str(text) | Edn::Symbol(text) => text.as_ref() == expected,
389    _ => false,
390  }
391}
392
393#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
394pub(crate) struct TransactionOperationReport {
395  pub(crate) index: usize,
396  pub(crate) args: Vec<String>,
397  pub(crate) stdout: String,
398  pub(crate) stderr: String,
399}
400
401#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
402pub(crate) struct TransactionReport {
403  schema_version: u8,
404  command: &'static str,
405  dry_run: bool,
406  pub(crate) changed: bool,
407  pub(crate) original_revision: String,
408  pub(crate) new_revision: String,
409  /// Pre-edit fingerprints of only the units this transaction changes; pass it
410  /// to `--expect-revision` so edits to other definitions do not invalidate it.
411  pub(crate) scoped_revision: Option<String>,
412  operations: Vec<TransactionOperationReport>,
413}
414
415pub(crate) fn snapshot_content_revision(content: &str) -> String {
416  let mut hasher = Md5::new();
417  hasher.update(content.as_bytes());
418  format!("md5:{}", hex::encode(hasher.finalize()))
419}
420
421fn transaction_edn_arg(value: &cirru_edn::Edn) -> Result<String, String> {
422  match value {
423    cirru_edn::Edn::Str(value) | cirru_edn::Edn::Symbol(value) => Ok(value.to_string()),
424    cirru_edn::Edn::Tag(value) => Ok(format!(":{}", value.ref_str())),
425    cirru_edn::Edn::Bool(value) => Ok(value.to_string()),
426    cirru_edn::Edn::Number(value) => Ok(value.to_string()),
427    cirru_edn::Edn::Nil => Ok("nil".to_string()),
428    cirru_edn::Edn::Quote(code) => {
429      let quoted = Cirru::List(vec![Cirru::leaf("quote"), code.clone()]);
430      cirru_parser::format(
431        std::slice::from_ref(&quoted),
432        // Transaction arguments are fed back through `--code`. Inline mode is
433        // required for leaf and empty-list payloads: the multiline writer can
434        // render `quote ()` as `quote $\n()`, which changes the quoted AST.
435        cirru_parser::CirruWriterOptions { use_inline: true },
436      )
437      .map_err(|error| format!("Failed to format quoted transaction code argument: {error}"))
438    }
439    other => Err(format!("Transaction arguments must be scalar values or quoted code, got: {other}")),
440  }
441}
442
443fn parse_transaction_operations(raw: &str) -> Result<Vec<Vec<String>>, String> {
444  let trimmed = raw.trim();
445  if trimmed.is_empty() {
446    return Err("Transaction input is empty. Provide a Cirru EDN list of command argument lists (JSON is also accepted).".to_string());
447  }
448
449  let operations = if trimmed.starts_with('[') && !trimmed.starts_with("[]") {
450    serde_json::from_str::<Vec<Vec<String>>>(trimmed)
451      .map_err(|error| format!("Failed to parse transaction JSON as a list of argument lists: {error}"))?
452  } else {
453    let value = cirru_edn::parse(trimmed).map_err(|error| format!("Failed to parse transaction Cirru EDN: {error}"))?;
454    let cirru_edn::Edn::List(outer) = value else {
455      return Err("Transaction Cirru EDN must be a list (`[]`) of command argument lists.".to_string());
456    };
457    outer
458      .0
459      .iter()
460      .enumerate()
461      .map(|(index, operation)| {
462        let cirru_edn::Edn::List(args) = operation else {
463          return Err(format!(
464            "Transaction operation {} must be a list (`[]`) of CLI arguments.",
465            index + 1
466          ));
467        };
468        args.0.iter().map(transaction_edn_arg).collect::<Result<Vec<_>, _>>()
469      })
470      .collect::<Result<Vec<_>, _>>()?
471  };
472
473  if operations.is_empty() {
474    return Err("Transaction must contain at least one operation.".to_string());
475  }
476  for (index, operation) in operations.iter().enumerate() {
477    let Some(group) = operation.first().map(String::as_str) else {
478      return Err(format!("Transaction operation {} is empty.", index + 1));
479    };
480    if !matches!(group, "edit" | "tree" | "config") {
481      return Err(format!(
482        "Transaction operation {} starts with unsupported command group '{group}'. Only edit, tree, and config mutations are allowed.",
483        index + 1
484      ));
485    }
486    if group == "edit" && operation.get(1).is_some_and(|subcommand| subcommand == "transaction") {
487      return Err(format!(
488        "Transaction operation {} cannot contain a nested edit transaction.",
489        index + 1
490      ));
491    }
492    let Some(subcommand) = operation.get(1).map(String::as_str) else {
493      return Err(format!(
494        "Transaction operation {} is missing a subcommand after '{group}'.",
495        index + 1
496      ));
497    };
498    let supported = match group {
499      "edit" => matches!(
500        subcommand,
501        "format"
502          | "def"
503          | "mv-def"
504          | "rm-def"
505          | "meta"
506          | "schema"
507          | "ffi"
508          | "add-test"
509          | "add-ns"
510          | "rm-ns"
511          | "ns"
512          | "imports"
513          | "add-import"
514          | "rm-import"
515          | "rename"
516          | "split-def"
517      ),
518      "tree" => matches!(
519        subcommand,
520        "rewrite" | "search-replace" | "replace" | "replace-leaf" | "delete" | "insert" | "swap" | "unwrap" | "raise" | "wrap"
521      ),
522      "config" => matches!(
523        subcommand,
524        "set" | "unset" | "add-entry" | "add-module" | "rm-module" | "set-type-slot" | "rm-type-slot"
525      ),
526      _ => false,
527    };
528    if let Some(error) = super::normalize::removed_transaction_operation_error(index, group, subcommand) {
529      return Err(error);
530    }
531    if !supported {
532      return Err(format!(
533        "Transaction operation {} uses unsupported staged mutation '{group} {subcommand}'. Read-only commands and unsupported edits must run outside the transaction.",
534        index + 1
535      ));
536    }
537  }
538  Ok(operations)
539}
540
541#[cfg(test)]
542fn run_staged_transaction_with<F>(
543  snapshot_file: &Path,
544  operations: &[Vec<String>],
545  expected_revision: Option<&str>,
546  dry_run: bool,
547  run_operation: F,
548) -> Result<TransactionReport, String>
549where
550  F: FnMut(&Path, usize, &[String]) -> Result<TransactionOperationReport, String>,
551{
552  run_staged_transaction_with_options(snapshot_file, operations, expected_revision, dry_run, false, run_operation)
553}
554
555fn run_staged_transaction_with_preserving_schemas<F>(
556  snapshot_file: &Path,
557  operations: &[Vec<String>],
558  expected_revision: Option<&str>,
559  dry_run: bool,
560  run_operation: F,
561) -> Result<TransactionReport, String>
562where
563  F: FnMut(&Path, usize, &[String]) -> Result<TransactionOperationReport, String>,
564{
565  run_staged_transaction_with_options(snapshot_file, operations, expected_revision, dry_run, true, run_operation)
566}
567
568pub(crate) fn run_staged_transaction_with_options<F>(
569  snapshot_file: &Path,
570  operations: &[Vec<String>],
571  expected_revision: Option<&str>,
572  dry_run: bool,
573  preserve_untouched_schemas: bool,
574  mut run_operation: F,
575) -> Result<TransactionReport, String>
576where
577  F: FnMut(&Path, usize, &[String]) -> Result<TransactionOperationReport, String>,
578{
579  let original_content =
580    fs::read_to_string(snapshot_file).map_err(|error| format!("Failed to read snapshot '{}': {error}", snapshot_file.display()))?;
581  let original_revision = snapshot_content_revision(&original_content);
582  // Legacy snapshots that only `edit format` can read have no unit view.
583  let original_units = load_snapshot_for_metadata(&snapshot_file.to_string_lossy())
584    .ok()
585    .map(|snapshot| super::snapshot_scope::snapshot_units(&snapshot))
586    .transpose()?;
587  // A scoped revision guards only the units the previewed transaction touched.
588  let guarded_units = match expected_revision {
589    Some(expected) if super::snapshot_scope::is_scoped_revision(expected) => {
590      let units = original_units
591        .as_ref()
592        .ok_or("A scoped revision needs a Snapshot the current CLI can load; use the full revision instead.")?;
593      Some(super::snapshot_scope::check_scoped_revision(expected, units)?)
594    }
595    Some(expected) if expected != original_revision => {
596      return Err(format!(
597        "Snapshot revision mismatch: expected '{expected}', current revision is '{original_revision}'. Re-run the query and rebuild the transaction."
598      ));
599    }
600    _ => None,
601  };
602
603  let staged = stage_atomic_file(snapshot_file, original_content.as_bytes(), "transaction snapshot")?;
604  let mut operation_reports = Vec::with_capacity(operations.len());
605  for (index, operation) in operations.iter().enumerate() {
606    operation_reports.push(run_operation(staged.path(), index, operation)?);
607  }
608
609  let staged_path = staged.path().to_string_lossy();
610  let staged_snapshot = load_snapshot(&staged_path)?;
611  let staged_units = super::snapshot_scope::snapshot_units(&staged_snapshot)?;
612  // Namespace views describe semantic edits, not a request to canonicalize
613  // retained root fields or source layout. Explicit format/schema commands
614  // keep their existing canonicalization behavior.
615  let unchanged_namespace_views = operations
616    .iter()
617    .all(|operation| operation.first().is_some_and(|group| group == "edit") && operation.get(1).is_some_and(|name| name == "ns"))
618    && original_units.as_ref().is_some_and(|units| units == &staged_units);
619  let staged_content = if unchanged_namespace_views {
620    original_content.clone()
621  } else {
622    let rendered_content = render_snapshot_content(&staged_snapshot)?;
623    if preserve_untouched_schemas
624      && !operations.iter().any(|operation| {
625        operation.first().is_some_and(|group| group == "edit") && operation.get(1).is_some_and(|name| name == "format")
626      })
627    {
628      restore_untouched_schema_forms(&original_content, &rendered_content, &staged_snapshot, &staged_path, operations)?
629    } else {
630      rendered_content
631    }
632  };
633  staged.write_and_sync(staged_content.as_bytes(), "transaction snapshot")?;
634
635  let new_revision = snapshot_content_revision(&staged_content);
636  let changed = original_content != staged_content;
637  let touched = original_units
638    .as_ref()
639    .map(|units| (units, super::snapshot_scope::changed_units(units, &staged_units)));
640  if let (Some(guarded), Some((_, touched))) = (&guarded_units, &touched) {
641    let unguarded = touched.iter().filter(|unit| !guarded.contains(*unit)).cloned().collect::<Vec<_>>();
642    if !unguarded.is_empty() {
643      return Err(format!(
644        "Definition conflict: the transaction now also changes {}, which the scoped revision does not cover. Re-run the dry-run and review the new plan.",
645        unguarded.join(", ")
646      ));
647    }
648  }
649  let scoped_revision = touched.map(|(units, touched)| super::snapshot_scope::scoped_revision(units, &touched));
650
651  let current_content =
652    fs::read_to_string(snapshot_file).map_err(|error| format!("Failed to re-read snapshot '{}': {error}", snapshot_file.display()))?;
653  let current_revision = snapshot_content_revision(&current_content);
654  if current_revision != original_revision {
655    return Err(format!(
656      "Snapshot changed while transaction was running: started at '{original_revision}', now '{current_revision}'. No transaction changes were written."
657    ));
658  }
659
660  if !dry_run && changed {
661    staged.commit()?;
662  }
663
664  Ok(TransactionReport {
665    schema_version: 1,
666    command: "edit.transaction",
667    dry_run,
668    changed,
669    original_revision,
670    new_revision,
671    scoped_revision,
672    operations: operation_reports,
673  })
674}
675
676fn run_transaction_child(stage_path: &Path, index: usize, args: &[String]) -> Result<TransactionOperationReport, String> {
677  let executable = std::env::current_exe().map_err(|error| format!("Failed to locate current calcit executable: {error}"))?;
678  let output = Command::new(&executable)
679    .arg("--tips-level")
680    .arg("none")
681    .env("CALCIT_CURSOR_MAINTENANCE", "disabled")
682    .arg(stage_path)
683    .args(args)
684    .output()
685    .map_err(|error| format!("Failed to run transaction operation {} ({args:?}): {error}", index + 1))?;
686  let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
687  let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
688  if !output.status.success() {
689    return Err(format!(
690      "Transaction operation {} failed: {}\nstdout:\n{}\nstderr:\n{}",
691      index + 1,
692      args.join(" "),
693      stdout.trim_end(),
694      stderr.trim_end()
695    ));
696  }
697  Ok(TransactionOperationReport {
698    index,
699    args: args.to_vec(),
700    stdout,
701    stderr,
702  })
703}
704
705#[derive(Debug, Clone, PartialEq, Eq)]
706pub(crate) struct StagedFixReport {
707  pub(crate) changed: bool,
708  pub(crate) original_revision: String,
709  pub(crate) new_revision: String,
710}
711
712pub(crate) fn run_staged_fix_transaction(
713  snapshot_file: &Path,
714  operations: &[Vec<String>],
715  expected_revision: Option<&str>,
716  dry_run: bool,
717  validation_entry: &str,
718  validation_args: &[String],
719  allowed_warning_identities: Option<&[String]>,
720) -> Result<StagedFixReport, String> {
721  if operations.is_empty() {
722    let content =
723      fs::read_to_string(snapshot_file).map_err(|error| format!("Failed to read snapshot '{}': {error}", snapshot_file.display()))?;
724    let revision = snapshot_content_revision(&content);
725    if let Some(expected) = expected_revision
726      && expected != revision
727    {
728      return Err(format!(
729        "Snapshot revision mismatch: expected '{expected}', current revision is '{revision}'. Re-run `calcit fix` and review the new plan."
730      ));
731    }
732    return Ok(StagedFixReport {
733      changed: false,
734      original_revision: revision.clone(),
735      new_revision: revision,
736    });
737  }
738
739  guard_snapshot_mutation_toolchain(&snapshot_file.to_string_lossy())?;
740  let operation_count = operations.len();
741  let report = run_staged_transaction_with_preserving_schemas(
742    snapshot_file,
743    operations,
744    expected_revision,
745    dry_run,
746    |stage_path, index, args| {
747      let operation = run_transaction_child(stage_path, index, args)?;
748      if index + 1 == operation_count {
749        validate_staged_fix(stage_path, validation_entry, validation_args, allowed_warning_identities)?;
750      }
751      Ok(operation)
752    },
753  )?;
754  Ok(StagedFixReport {
755    changed: report.changed,
756    original_revision: report.original_revision,
757    new_revision: report.new_revision,
758  })
759}
760
761fn validate_staged_fix(
762  stage_path: &Path,
763  validation_entry: &str,
764  validation_args: &[String],
765  allowed_warning_identities: Option<&[String]>,
766) -> Result<(), String> {
767  let executable = std::env::current_exe().map_err(|error| format!("Failed to locate current calcit executable: {error}"))?;
768  let output = Command::new(&executable)
769    .args(staged_fix_validation_args(stage_path, validation_entry, validation_args))
770    .env("CALCIT_FIX_VALIDATE_ONLY", "1")
771    .output()
772    .map_err(|error| format!("Failed to validate staged fixes: {error}"))?;
773  if output.status.success() {
774    if let Some(allowed) = allowed_warning_identities {
775      let current = serde_json::from_slice::<Vec<String>>(&output.stdout).map_err(|error| {
776        format!(
777          "Staged fix validation returned invalid warning evidence: {error}\nstdout:\n{}\nstderr:\n{}",
778          String::from_utf8_lossy(&output.stdout).trim_end(),
779          String::from_utf8_lossy(&output.stderr).trim_end()
780        )
781      })?;
782      let unexpected = staged_warning_difference(allowed, &current);
783      if !unexpected.is_empty() {
784        return Err(format!(
785          "Staged fix introduced compiler warnings; no changes were written:\n{}",
786          unexpected.join("\n")
787        ));
788      }
789    }
790    Ok(())
791  } else {
792    Err(format!(
793      "Staged fixes failed preprocessing; no changes were written.\nstdout:\n{}\nstderr:\n{}",
794      String::from_utf8_lossy(&output.stdout).trim_end(),
795      String::from_utf8_lossy(&output.stderr).trim_end()
796    ))
797  }
798}
799
800/// Recreate the top-level entry selection before invoking staged `fix` validation.
801fn staged_fix_validation_args(stage_path: &Path, validation_entry: &str, validation_args: &[String]) -> Vec<OsString> {
802  let mut args = vec![
803    OsString::from("--tips-level"),
804    OsString::from("none"),
805    OsString::from("--entry"),
806    OsString::from(validation_entry),
807    stage_path.as_os_str().to_owned(),
808    OsString::from("fix"),
809  ];
810  args.extend(validation_args.iter().map(OsString::from));
811  args
812}
813
814/// Return warning identities whose staged multiplicity exceeds the pre-edit baseline.
815fn staged_warning_difference(allowed: &[String], current: &[String]) -> Vec<String> {
816  let mut remaining = BTreeMap::<&str, usize>::new();
817  for warning in allowed {
818    *remaining.entry(warning).or_default() += 1;
819  }
820  let mut unexpected = Vec::new();
821  for warning in current {
822    match remaining.get_mut(warning.as_str()) {
823      Some(count) if *count > 0 => *count -= 1,
824      _ => unexpected.push(warning.clone()),
825    }
826  }
827  unexpected
828}
829
830fn handle_transaction(opts: &EditTransactionCommand, snapshot_file: &str) -> Result<(), String> {
831  let output_format = StructuredOutputFormat::parse(&opts.format, "transaction")?;
832  let _structured_guard = super::common::StructuredMutationOutputGuard::new(output_format != StructuredOutputFormat::Human);
833  let raw = read_code_input(&opts.file, &opts.code)?.ok_or(
834    "Transaction input required: use --file, --code, or pipe a Cirru EDN list of argument lists via stdin (JSON is also accepted)",
835  )?;
836  let operations = parse_transaction_operations(&raw)?;
837  let report = run_staged_transaction_with_preserving_schemas(
838    Path::new(snapshot_file),
839    &operations,
840    opts.expect_revision.as_deref(),
841    opts.dry_run,
842    run_transaction_child,
843  )?;
844
845  match output_format {
846    StructuredOutputFormat::Json => println!(
847      "{}",
848      serde_json::to_string(&report).map_err(|error| format!("Failed to serialize transaction result: {error}"))?
849    ),
850    StructuredOutputFormat::Edn => {
851      let value = serde_json::to_value(&report).map_err(|error| format!("Failed to encode transaction result: {error}"))?;
852      println!("{}", format_json_value_as_edn(&value)?);
853    }
854    StructuredOutputFormat::Human => {
855      println!("# Edit transaction\n");
856      println!("- mode: `{}`", if opts.dry_run { "preview" } else { "apply" });
857      println!("- original revision: `{}`", report.original_revision);
858      println!("- new revision: `{}`", report.new_revision);
859      if let Some(scoped) = &report.scoped_revision {
860        println!("- scoped revision: `{scoped}`");
861      }
862      println!("- changed: `{}`", report.changed);
863      println!("- operations: `{}`", report.operations.len());
864      for operation in &report.operations {
865        println!("\n## Operation {}\n", operation.index + 1);
866        println!("```text");
867        println!("{}", operation.args.join(" "));
868        println!("```");
869      }
870    }
871  }
872  Ok(())
873}
874
875// ═══════════════════════════════════════════════════════════════════════════════
876// Utility functions
877// ═══════════════════════════════════════════════════════════════════════════════
878
879pub(crate) fn load_snapshot(snapshot_file: &str) -> Result<Snapshot, String> {
880  let edn = read_snapshot_edn(snapshot_file)?;
881  snapshot::load_snapshot_data(&edn, snapshot_file).map_err(|e| format!("Failed to load snapshot: {e}"))
882}
883
884fn load_snapshot_for_metadata(snapshot_file: &str) -> Result<Snapshot, String> {
885  let edn = read_snapshot_edn(snapshot_file)?;
886  snapshot::load_snapshot_data_for_metadata(&edn, snapshot_file, None)
887}
888
889fn read_snapshot_edn(snapshot_file: &str) -> Result<Edn, String> {
890  let mut content = fs::read_to_string(snapshot_file).map_err(|e| format!("Failed to read {snapshot_file}: {e}"))?;
891  strip_shebang(&mut content);
892  cirru_edn::parse(&content).map_err(|e| format!("Failed to parse EDN: {e}"))
893}
894
895pub(crate) fn save_snapshot(snapshot: &Snapshot, snapshot_file: &str) -> Result<(), String> {
896  save_snapshot_to_file(snapshot_file, snapshot)
897}
898
899/// Check if namespace belongs to the current package (can be edited)
900pub(crate) fn check_ns_editable(snapshot: &Snapshot, namespace: &str) -> Result<(), String> {
901  let pkg = &snapshot.package;
902  // Namespace must match package name or start with "package."
903  if namespace == pkg || namespace.starts_with(&format!("{pkg}.")) {
904    Ok(())
905  } else {
906    Err(format!(
907      "Cannot modify namespace '{namespace}': only namespaces under package '{pkg}' can be edited.\nThis namespace belongs to a dependency or core library."
908    ))
909  }
910}
911
912// ═══════════════════════════════════════════════════════════════════════════════
913// Definition operations
914// ═══════════════════════════════════════════════════════════════════════════════
915
916fn source_declares_macro(entry: &CodeEntry) -> bool {
917  matches!(&entry.code, Cirru::List(items) if items.first().is_some_and(|head| head.eq_leaf("defmacro")))
918}
919
920pub(crate) fn definition_head_is_macro(snapshot_file: &str, snapshot: &Snapshot, namespace: &str, head: &str) -> Result<bool, String> {
921  definition_head_macro_code(snapshot_file, snapshot, namespace, head).map(|found| found.is_some())
922}
923
924/// Resolve a call head like `definition_head_is_macro`, returning the `defmacro` source and its
925/// defining namespace file when it is one.
926pub(crate) fn definition_head_macro_code(
927  snapshot_file: &str,
928  snapshot: &Snapshot,
929  namespace: &str,
930  head: &str,
931) -> Result<Option<(Cirru, FileInSnapShot)>, String> {
932  let macro_code = |file: &FileInSnapShot, name: &str| {
933    file
934      .defs
935      .get(name)
936      .filter(|entry| source_declares_macro(entry))
937      .map(|entry| (entry.code.clone(), file.clone()))
938  };
939  let file = &snapshot.files[namespace];
940  let imports = calcit_core::program::extract_import_map(&file.ns.code, namespace)?;
941  let (source_ns, source_def) = if let Some((prefix, name)) = head.split_once('/') {
942    let source_ns = match imports.get(prefix).map(|rule| rule.as_ref()) {
943      Some(calcit_core::program::ImportRule::NsAs(target)) => target.as_ref(),
944      Some(_) => return Ok(None),
945      None => prefix,
946    };
947    (source_ns, name)
948  } else if file.defs.contains_key(head) {
949    (namespace, head)
950  } else if let Some(rule) = imports.get(head) {
951    match rule.as_ref() {
952      calcit_core::program::ImportRule::NsReferDef(target, name) => (target.as_ref(), name.as_ref()),
953      _ => return Ok(None),
954    }
955  } else {
956    (calcit_core::calcit::CORE_NS, head)
957  };
958  if let Some(file) = snapshot.files.get(source_ns) {
959    return Ok(macro_code(file, source_def));
960  }
961  if source_ns == calcit_core::calcit::CORE_NS {
962    let core = calcit_core::load_core_snapshot()?;
963    return Ok(macro_code(&core.files[source_ns], source_def));
964  }
965  // Read source only, across all configured entries; do not expand macros or
966  // activate unrelated definitions while validating a mutation.
967  let base_dir = Path::new(snapshot_file).parent().unwrap_or_else(|| Path::new("."));
968  let module_folder = calcit_core::project_module_folder(base_dir);
969  let modules = snapshot
970    .entries
971    .values()
972    .flat_map(|entry| entry.modules.iter())
973    .collect::<std::collections::BTreeSet<_>>();
974  let mut load_errors = Vec::new();
975  for module in modules {
976    match super::load_module_with_sources_silent(module, base_dir, &module_folder) {
977      Ok(loaded) => {
978        if let Some(file) = loaded.snapshot.files.get(source_ns) {
979          return Ok(macro_code(file, source_def));
980        }
981      }
982      Err(error) => load_errors.push(format!("{module}: {error}")),
983    }
984  }
985  if !load_errors.is_empty() {
986    return Err(format!(
987      "Unrecognized definition head '{head}': cannot resolve namespace '{source_ns}'; module load failures:\n{}\nRepair the dependency sources and retry this edit.",
988      load_errors.join("\n")
989    ));
990  }
991  Ok(None)
992}
993
994/// Replace a definition's code and apply the metadata rules that follow from it.
995/// `derived_macro_schema` comes from `snapshot::conservative_macro_schema` on the new code.
996fn replace_definition_code(entry: &mut CodeEntry, code: Cirru, derived_macro_schema: Option<Arc<CalcitTypeAnnotation>>) {
997  entry.code = code;
998  // The shorthand fully determines external-object metadata, and the loader
999  // regenerates it. Carrying a retained `:ffi` would write an invalid
1000  // `defexternal` + explicit `:ffi` pair that the next load rejects.
1001  if snapshot::code_declares_defexternal(&entry.code) {
1002    entry.ffi = None;
1003  }
1004  // A macro gets a conservative schema unless it already declares a Macro contract.
1005  if let Some(schema) = derived_macro_schema
1006    && !matches!(entry.schema.as_ref(), CalcitTypeAnnotation::Macro(_))
1007  {
1008    entry.schema = schema;
1009  }
1010}
1011
1012fn is_core_defimpl(snapshot_file: &str, snapshot: &Snapshot, namespace: &str, head: &str) -> Result<bool, String> {
1013  if head != "defimpl" && !head.ends_with("/defimpl") {
1014    return Ok(false);
1015  }
1016  Ok(
1017    definition_head_macro_code(snapshot_file, snapshot, namespace, head)?.is_some_and(|(_, source)| {
1018      matches!(&source.ns.code, Cirru::List(items)
1019      if items.get(1).is_some_and(|name| name.eq_leaf(calcit_core::calcit::CORE_NS)))
1020    }),
1021  )
1022}
1023
1024pub(crate) fn validate_definition_shape(
1025  snapshot_file: &str,
1026  snapshot: &Snapshot,
1027  namespace: &str,
1028  definition: &str,
1029  code: &Cirru,
1030  allow_unknown_head: bool,
1031) -> Result<(), String> {
1032  snapshot::validate_definition_root(code, &format!("{namespace}/{definition}"))?;
1033  let Cirru::List(items) = code else {
1034    return Err(format!(
1035      "Definition '{namespace}/{definition}' must be a named definition expression, not a leaf."
1036    ));
1037  };
1038  // A top-level anonymous function is named by the Snapshot definition key,
1039  // not by a second leaf in its source expression.
1040  if items.first().is_some_and(|head| head.eq_leaf("fn")) {
1041    return if matches!(items.get(1), Some(Cirru::List(_))) && items.len() >= 3 {
1042      Ok(())
1043    } else {
1044      Err(format!(
1045        "Definition '{namespace}/{definition}': fn requires a parameter list and a body."
1046      ))
1047    };
1048  }
1049  // Type slots carry an independent slot name, not the Snapshot key.
1050  if items.first().is_some_and(|head| head.eq_leaf("deftype-slot")) {
1051    return if items.len() == 2 && matches!(&items[1], Cirru::Leaf(name) if name.starts_with(':') || name.starts_with('|')) {
1052      Ok(())
1053    } else {
1054      Err(format!(
1055        "Definition '{namespace}/{definition}': deftype-slot requires exactly one tag or string slot name."
1056      ))
1057    };
1058  }
1059  // A core defimpl names the receiver and trait, while the CodeEntry key
1060  // identifies the implementation independently of either declaration.
1061  if let Some(Cirru::Leaf(head)) = items.first()
1062    && is_core_defimpl(snapshot_file, snapshot, namespace, head)?
1063  {
1064    let is_symbol = |index| {
1065      matches!(items.get(index), Some(node @ Cirru::Leaf(_))
1066        if matches!(calcit_core::data::cirru::code_to_calcit(node, namespace, definition, vec![]), Ok(calcit_core::Calcit::Symbol { .. })))
1067    };
1068    return if is_symbol(1) && is_symbol(2) {
1069      Ok(())
1070    } else {
1071      Err(format!(
1072        "Definition '{namespace}/{definition}': defimpl requires a receiver type symbol and a trait symbol."
1073      ))
1074    };
1075  }
1076  let (Some(Cirru::Leaf(head)), Some(Cirru::Leaf(name))) = (items.first(), items.get(1)) else {
1077    return Err(format!(
1078      "Definition '{namespace}/{definition}' requires a definition head and a symbol name."
1079    ));
1080  };
1081  // Preserve an unchanged historical expression; this cannot introduce a new
1082  // name mismatch, and avoids renaming nominal types during a source round-trip.
1083  let unchanged = snapshot.files[namespace]
1084    .defs
1085    .get(definition)
1086    .is_some_and(|entry| &entry.code == code);
1087  if name.as_ref() != definition && !unchanged {
1088    return Err(format!(
1089      "Definition name mismatch: expected '{definition}', got '{name}' in '{namespace}/{definition}'."
1090    ));
1091  }
1092  if !allow_unknown_head
1093    && !snapshot::DEFINITION_HEADS.contains(&head.as_ref())
1094    && !definition_head_is_macro(snapshot_file, snapshot, namespace, head)?
1095  {
1096    return Err(format!(
1097      "Unrecognized definition head '{head}' for '{namespace}/{definition}'. Expected {}, or a source-declared macro from this namespace, imports or core. Use --allow-unknown-head only for an intentional custom definition form.",
1098      snapshot::DEFINITION_HEADS.join(", ")
1099    ));
1100  }
1101  Ok(())
1102}
1103
1104fn handle_def(opts: &EditDefCommand, snapshot_file: &str) -> Result<(), String> {
1105  let (namespace, definition) = parse_target(&opts.target)?;
1106
1107  let raw = read_code_input(&opts.file, &opts.code)?.ok_or(ERR_CODE_INPUT_REQUIRED)?;
1108
1109  let syntax_tree = decode_mutation_syntax_input(&raw, opts.input_format)?;
1110  let derived_macro_schema = snapshot::conservative_macro_schema(&syntax_tree, &format!("definition '{namespace}/{definition}'"))?;
1111  snapshot::validate_defexternal_shorthand(&syntax_tree, &format!("{namespace}/{definition}"))?;
1112
1113  let mut snapshot = load_snapshot(snapshot_file)?;
1114
1115  // Check if namespace can be edited
1116  check_ns_editable(&snapshot, namespace)?;
1117
1118  // Check if namespace exists
1119  let file_data = snapshot
1120    .files
1121    .get(namespace)
1122    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
1123
1124  // Creation addresses the exact requested name; nearby shell-sensitive names may coexist.
1125  // Keep typo resolution for lookups and update-only commands, never redirect a write here.
1126  let resolved_definition = definition;
1127
1128  let exists = file_data.defs.contains_key(resolved_definition);
1129  let previous_entry = if exists {
1130    file_data.defs.get(resolved_definition).cloned()
1131  } else {
1132    None
1133  };
1134  validate_definition_shape(
1135    snapshot_file,
1136    &snapshot,
1137    namespace,
1138    resolved_definition,
1139    &syntax_tree,
1140    opts.allow_unknown_head,
1141  )?;
1142  let existing_edit_advice = previous_entry
1143    .as_ref()
1144    .and_then(|entry| format_existing_definition_advice(namespace, resolved_definition, &entry.code, &syntax_tree));
1145
1146  if opts.overwrite
1147    && let Some(advice) = existing_edit_advice.as_deref()
1148  {
1149    print_cli_warning_block(advice);
1150  }
1151
1152  if exists && !opts.overwrite {
1153    if let Some(advice) = existing_edit_advice.as_deref() {
1154      print_cli_warning_block(advice);
1155    }
1156    return Err(format!(
1157      "Definition '{resolved_definition}' already exists in namespace '{namespace}'.\n\
1158       Use --overwrite to replace it. For full-definition rewrites, prefer: calcit edit def {namespace}/{resolved_definition} --overwrite --file <file>"
1159    ));
1160  }
1161
1162  // Create or overwrite definition.
1163  // For overwrite, preserve existing metadata (doc/examples/schema) and only replace code.
1164  let mut code_entry = previous_entry.unwrap_or_else(|| CodeEntry::from_code(syntax_tree.clone()));
1165  replace_definition_code(&mut code_entry, syntax_tree, derived_macro_schema);
1166  snapshot
1167    .files
1168    .get_mut(namespace)
1169    .expect("validated local namespace")
1170    .defs
1171    .insert(resolved_definition.to_string(), code_entry);
1172
1173  save_snapshot(&snapshot, snapshot_file)?;
1174
1175  let action_label = if exists { "Updated" } else { "Created" };
1176
1177  println!(
1178    "{} {} definition '{}' in namespace '{}'",
1179    "✓".green(),
1180    action_label,
1181    resolved_definition.cyan(),
1182    namespace
1183  );
1184  if command_guidance_enabled() {
1185    println!();
1186    println!("{}", "Next steps:".blue().bold());
1187    println!(
1188      "  • View definition: {} '{}/{}'",
1189      "calcit query def".cyan(),
1190      namespace,
1191      resolved_definition
1192    );
1193    println!("  • Check errors: {}", "calcit query error".cyan());
1194    println!(
1195      "  • Find usages: {} '{}/{}'",
1196      "calcit query usages".cyan(),
1197      namespace,
1198      resolved_definition
1199    );
1200    println!(
1201      "  • Add to imports: {} <target-ns> '{}' --refer '{}'",
1202      "calcit edit add-import".cyan(),
1203      namespace,
1204      resolved_definition
1205    );
1206    println!();
1207    let mut tips = Tips::new();
1208    tips.add(format!(
1209      "Use single quotes around '{namespace}/{resolved_definition}' to avoid shell escaping issues."
1210    ));
1211    tips.add(format!("Example: calcit tree show '{namespace}/{resolved_definition}'"));
1212    tips.print();
1213  }
1214  Ok(())
1215}
1216
1217fn format_existing_definition_advice(namespace: &str, definition: &str, existing: &Cirru, incoming: &Cirru) -> Option<String> {
1218  let advice = analyze_cirru_edit_advice(existing, incoming)?;
1219  let changed_nodes = advice.stats.added + advice.stats.removed + advice.stats.modified;
1220  let target = format!("{namespace}/{definition}");
1221  let mut lines = vec![format!(
1222    "Incoming code is {:.0}% structurally similar to the existing definition (changed nodes: ~{} +{} -{}).",
1223    advice.similarity * 100.0,
1224    advice.stats.modified,
1225    advice.stats.added,
1226    advice.stats.removed,
1227  )];
1228
1229  match advice.strategy {
1230    CirruEditStrategy::Identical => {
1231      lines.push("The incoming definition is identical. Prefer skipping the write and inspect the current code first.".to_string());
1232      lines.push(format!("Inspect: calcit query def '{target}'"));
1233    }
1234    CirruEditStrategy::Replace => {
1235      lines.push("Most differences are replacements. Prefer a local tree edit instead of a full overwrite.".to_string());
1236      lines.push(format!(
1237        "Try: calcit tree search-replace '{target}' --pattern '<leaf>' --code '(quote |<new-leaf>')"
1238      ));
1239      lines.push(format!(
1240        "Or: calcit tree replace '{target}' --path '<path>' --code '(quote |<code>)'"
1241      ));
1242    }
1243    CirruEditStrategy::Insert => {
1244      lines.push("Most differences are additive. Prefer inserting nodes into the existing tree.".to_string());
1245      lines.push(format!(
1246        "Try: calcit tree insert '{target}' --at before --path '<path>' --code '<node>'"
1247      ));
1248      lines.push(format!(
1249        "Or: calcit tree insert '{target}' --at after --path '<path>' --code '<node>' / calcit tree insert '{target}' --at append-child --path '<path>' --code '<node>'"
1250      ));
1251    }
1252    CirruEditStrategy::Delete => {
1253      lines.push("Most differences are removals. Prefer deleting or lifting nodes from the existing tree.".to_string());
1254      lines.push(format!("Try: calcit tree delete '{target}' --path '<path>'"));
1255      lines.push(format!("Or: calcit tree raise '{target}' --path '<child-path>'"));
1256    }
1257    CirruEditStrategy::Rewrite => {
1258      lines.push("The trees are still close, but the change mixes insert/remove/replace. Prefer a structural rewrite over a blind full overwrite.".to_string());
1259      lines.push(format!(
1260        "Try: calcit tree rewrite '{target}' --path '<path>' --with self=. --code '<code>'"
1261      ));
1262      lines.push(format!("Or: calcit tree replace '{target}' --path '<path>' --code '<code>'"));
1263    }
1264  }
1265
1266  if advice.strategy != CirruEditStrategy::Identical || changed_nodes > 0 {
1267    lines.push(format!(
1268      "Locate the smallest path first: calcit query search '<keyword>' --filter '{target}' && calcit tree show '{target}' --path '<path>'"
1269    ));
1270  }
1271
1272  Some(lines.join("\n"))
1273}
1274
1275// ═══════════════════════════════════════════════════════════════════════════════
1276// AST node copy / move helpers
1277// ═══════════════════════════════════════════════════════════════════════════════
1278
1279fn map_at_to_operation(at: &str) -> Result<TreeOperation, String> {
1280  TreeOperation::from_insert_position(at)
1281    .ok_or_else(|| format!("Unsupported position '{at}'. Use: before, after, prepend-child, append-child, replace"))
1282}
1283
1284/// Move one AST node inside a definition; used by `cursor apply` paredit rewrites.
1285pub(super) fn move_node(target: &str, from: &str, path: &str, at: &str, snapshot_file: &str) -> Result<(), String> {
1286  guard_snapshot_mutation_toolchain(snapshot_file)?;
1287  let (namespace, definition) = parse_target(target)?;
1288  let from_path = parse_path(from)?;
1289  let to_path = parse_path(path)?;
1290
1291  if from_path.is_empty() {
1292    return Err("Cannot move root node".to_string());
1293  }
1294  if from_path == to_path {
1295    return Err("Source and destination paths are identical; nothing to move.".to_string());
1296  }
1297  if path_is_strict_descendant(&from_path, &to_path) {
1298    return Err(format!("Cannot move node at [{from}] into its own subtree at [{path}]"));
1299  }
1300
1301  let operation = map_at_to_operation(at)?;
1302
1303  let mut snapshot = load_snapshot(snapshot_file)?;
1304  check_ns_editable(&snapshot, namespace)?;
1305
1306  let file_data = snapshot
1307    .files
1308    .get_mut(namespace)
1309    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
1310
1311  let resolved_definition =
1312    resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), false)?.resolved;
1313
1314  let code_entry = file_data
1315    .defs
1316    .get_mut(resolved_definition.as_str())
1317    .expect("resolved definition exists");
1318
1319  let source_node = navigate_to_path(&code_entry.code, &from_path)?;
1320  let append_index = if operation == TreeOperation::AppendChild {
1321    match navigate_to_path(&code_entry.code, &to_path)? {
1322      Cirru::List(children) => children.len(),
1323      Cirru::Leaf(_) => 0,
1324    }
1325  } else {
1326    0
1327  };
1328
1329  let after_insert = apply_operation_at_path(&code_entry.code, &to_path, operation, Some(&source_node))?;
1330  let adjusted_from = adjusted_source_path_after_insertion(&from_path, &to_path, operation);
1331  let final_code = apply_operation_at_path(&after_insert, &adjusted_from, TreeOperation::Delete, None)?;
1332  code_entry.code = final_code;
1333
1334  save_snapshot(&snapshot, snapshot_file)?;
1335
1336  maintain_cursor_after_node_move(
1337    snapshot_file,
1338    &format!("{namespace}/{resolved_definition}"),
1339    &from_path,
1340    &to_path,
1341    operation,
1342    append_index,
1343  )?;
1344
1345  println!(
1346    "{} Moved node from [{}] to [{}] ({}) in '{}/{}'",
1347    "✓".green(),
1348    from,
1349    path,
1350    at,
1351    namespace,
1352    resolved_definition
1353  );
1354  Ok(())
1355}
1356
1357pub(crate) fn rename_definition_declaration(
1358  snapshot_file: &str,
1359  snapshot: &Snapshot,
1360  namespace: &str,
1361  code: &Cirru,
1362  old_name: &str,
1363  new_name: &str,
1364) -> Result<(Cirru, bool), String> {
1365  let Cirru::List(items) = code else {
1366    return Ok((code.clone(), false));
1367  };
1368  let Some(Cirru::Leaf(head)) = items.first() else {
1369    return Ok((code.clone(), false));
1370  };
1371  if is_core_defimpl(snapshot_file, snapshot, namespace, head)? {
1372    return Ok((code.clone(), false));
1373  }
1374  if !head.starts_with("def") {
1375    return Ok((code.clone(), false));
1376  }
1377
1378  let Some(name_node) = items.get(1) else {
1379    return Err(format!("Definition form `{head}` has no declaration name"));
1380  };
1381  let Cirru::Leaf(declared_name) = name_node else {
1382    return Err(format!("Definition form `{head}` has a non-leaf declaration name"));
1383  };
1384  if declared_name.as_ref() != old_name {
1385    return Err(format!(
1386      "Definition key `{old_name}` does not match declaration name `{declared_name}`. Repair the mismatch before renaming."
1387    ));
1388  }
1389
1390  let mut next_items = items.clone();
1391  next_items[1] = Cirru::Leaf(Arc::from(new_name));
1392  Ok((Cirru::List(next_items), true))
1393}
1394
1395fn handle_rename(opts: &EditRenameCommand, snapshot_file: &str) -> Result<(), String> {
1396  let (namespace, definition) = parse_target(&opts.source)?;
1397
1398  let mut snapshot = load_snapshot(snapshot_file)?;
1399  check_ns_editable(&snapshot, namespace)?;
1400
1401  let file_data = snapshot
1402    .files
1403    .get(namespace)
1404    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
1405
1406  let resolved_definition =
1407    resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), false)?.resolved;
1408  if file_data.defs.contains_key(&opts.new_name) {
1409    return Err(format!(
1410      "Definition '{}' already exists in namespace '{}'. Use 'calcit edit mv-def' to move to a different namespace.",
1411      opts.new_name, namespace
1412    ));
1413  }
1414
1415  let (renamed_code, _) = rename_definition_declaration(
1416    snapshot_file,
1417    &snapshot,
1418    namespace,
1419    &file_data.defs[resolved_definition.as_str()].code,
1420    &resolved_definition,
1421    &opts.new_name,
1422  )?;
1423  let before = defimpl_edit_baseline(
1424    snapshot_file,
1425    &snapshot,
1426    namespace,
1427    &file_data.defs[resolved_definition.as_str()].code,
1428  )?;
1429  let file_data = snapshot.files.get_mut(namespace).expect("resolved namespace exists");
1430  let mut entry = file_data
1431    .defs
1432    .remove(resolved_definition.as_str())
1433    .expect("resolved definition exists");
1434  entry.code = renamed_code;
1435  file_data.defs.insert(opts.new_name.clone(), entry);
1436
1437  if let Some(before) = before {
1438    check_defimpl_destination(
1439      snapshot_file,
1440      &before,
1441      &snapshot,
1442      namespace,
1443      namespace,
1444      &snapshot.files[namespace].defs[&opts.new_name].code,
1445    )?;
1446  }
1447  save_snapshot(&snapshot, snapshot_file)?;
1448
1449  println!(
1450    "{} Renamed '{}' to '{}' in namespace '{}'",
1451    "✓".green(),
1452    resolved_definition.cyan(),
1453    opts.new_name.cyan(),
1454    namespace
1455  );
1456
1457  Ok(())
1458}
1459
1460fn handle_split_def(opts: &EditSplitDefCommand, snapshot_file: &str) -> Result<(), String> {
1461  let (namespace, definition) = parse_target(&opts.target)?;
1462  let path = parse_path(&opts.path)?;
1463  let new_name = opts.new_name.trim();
1464
1465  if path.is_empty() {
1466    return Err(
1467      "Cannot split at the root path: the root IS the definition. Use 'calcit edit def' to create a new definition from scratch."
1468        .to_string(),
1469    );
1470  }
1471  if new_name.is_empty() {
1472    return Err("New definition name cannot be empty".to_string());
1473  }
1474
1475  let mut snapshot = load_snapshot(snapshot_file)?;
1476  check_ns_editable(&snapshot, namespace)?;
1477
1478  let file_data = snapshot
1479    .files
1480    .get_mut(namespace)
1481    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
1482
1483  let resolved_definition =
1484    resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), false)?.resolved;
1485  if file_data.defs.contains_key(new_name) {
1486    return Err(format!(
1487      "Definition '{new_name}' already exists in namespace '{namespace}'. Choose a different name or remove the existing one first."
1488    ));
1489  }
1490
1491  // Extract the sub-expression at path
1492  let extracted = navigate_to_path(&file_data.defs[resolved_definition.as_str()].code, &path)?;
1493
1494  // Replace the path in the original definition with the new name (a leaf)
1495  let new_ref = Cirru::Leaf(Arc::from(new_name));
1496  let updated_code = apply_operation_at_path(
1497    &file_data.defs[resolved_definition.as_str()].code,
1498    &path,
1499    TreeOperation::Replace,
1500    Some(&new_ref),
1501  )?;
1502
1503  // Write updated code back to original definition
1504  file_data
1505    .defs
1506    .get_mut(resolved_definition.as_str())
1507    .expect("resolved definition exists")
1508    .code = updated_code;
1509
1510  // Create the new definition with the extracted sub-expression as its body
1511  let new_entry = CodeEntry::from_code(extracted);
1512  file_data.defs.insert(new_name.to_string(), new_entry);
1513
1514  save_snapshot(&snapshot, snapshot_file)?;
1515
1516  println!(
1517    "{} Extracted node at [{}] from '{}/{}' → new definition '{}'",
1518    "✓".green(),
1519    opts.path,
1520    namespace,
1521    resolved_definition.cyan(),
1522    new_name.cyan()
1523  );
1524  if command_guidance_enabled() {
1525    println!();
1526    println!("{}", "Next steps:".blue().bold());
1527    println!("  • Inspect new def:  {} '{}/{}'", "calcit query def".cyan(), namespace, new_name);
1528    println!(
1529      "  • Inspect source:   {} '{}/{}'",
1530      "calcit query def".cyan(),
1531      namespace,
1532      resolved_definition
1533    );
1534    println!(
1535      "  • Wrap in defn:     {} '{}/{}' --path '' --code 'quote (defn {} ...)'",
1536      "calcit tree replace".cyan(),
1537      namespace,
1538      new_name,
1539      new_name
1540    );
1541  }
1542  Ok(())
1543}
1544
1545fn handle_rm_def(opts: &EditRmDefCommand, snapshot_file: &str) -> Result<(), String> {
1546  let (namespace, definition) = parse_target(&opts.target)?;
1547
1548  let mut snapshot = load_snapshot(snapshot_file)?;
1549
1550  // Check if namespace can be edited
1551  check_ns_editable(&snapshot, namespace)?;
1552
1553  let file_data = snapshot
1554    .files
1555    .get_mut(namespace)
1556    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
1557
1558  let resolved_definition =
1559    resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), false)?.resolved;
1560  file_data
1561    .defs
1562    .remove(resolved_definition.as_str())
1563    .expect("resolved definition exists");
1564
1565  save_snapshot(&snapshot, snapshot_file)?;
1566
1567  println!(
1568    "{} Deleted definition '{}' from namespace '{}'",
1569    "✓".green(),
1570    resolved_definition.cyan(),
1571    namespace
1572  );
1573
1574  Ok(())
1575}
1576
1577fn check_defimpl_destination(
1578  snapshot_file: &str,
1579  before: &Snapshot,
1580  staged: &Snapshot,
1581  source_ns: &str,
1582  target_ns: &str,
1583  code: &Cirru,
1584) -> Result<(), String> {
1585  let Cirru::List(items) = code else { return Ok(()) };
1586  let Some(Cirru::Leaf(head)) = items.first() else { return Ok(()) };
1587  if !is_core_defimpl(snapshot_file, before, source_ns, head)? {
1588    return Ok(());
1589  }
1590  let (Some(Cirru::Leaf(receiver)), Some(Cirru::Leaf(trait_name))) = (items.get(1), items.get(2)) else {
1591    return Err("A core defimpl must name its receiver and trait before it can be moved.".to_owned());
1592  };
1593
1594  let source_file = &before.files[source_ns];
1595  let target_file = &staged.files[target_ns];
1596  let source_imports = calcit_core::program::extract_import_map(&source_file.ns.code, source_ns)?;
1597  let target_imports = calcit_core::program::extract_import_map(&target_file.ns.code, target_ns)?;
1598  let resolve =
1599    |file: &FileInSnapShot, imports: &_, namespace: &str, symbol: &str| resolve_defimpl_symbol(file, imports, namespace, symbol);
1600  let receiver_key = resolve(source_file, &source_imports, source_ns, receiver);
1601  let trait_key = resolve(source_file, &source_imports, source_ns, trait_name);
1602  if source_ns != target_ns && target_ns != receiver_key.0 && target_ns != trait_key.0 {
1603    return Err(format!(
1604      "Cannot move this defimpl to '{target_ns}': its receiver and trait are declared in '{}' and '{}'.",
1605      receiver_key.0, trait_key.0
1606    ));
1607  }
1608  if !is_core_defimpl(snapshot_file, staged, target_ns, head)? {
1609    return Err(format!(
1610      "Cannot change the definition key: '{head}' would no longer resolve to the core defimpl in '{target_ns}'."
1611    ));
1612  }
1613
1614  // Compare source symbols conservatively. A symbol under a local binding or a
1615  // macro may need qualification before the move if its global binding changes.
1616  for node in items.iter().skip(1) {
1617    let expression = calcit_core::data::cirru::code_to_calcit(node, source_ns, "", vec![])?;
1618    check_defimpl_references(&expression, &|sym| {
1619      if resolve(source_file, &source_imports, source_ns, sym) != resolve(target_file, &target_imports, target_ns, sym) {
1620        return Err(format!(
1621          "Cannot move or rename this defimpl in '{target_ns}': symbol '{sym}' would resolve differently. Qualify the reference before editing."
1622        ));
1623      }
1624      Ok(())
1625    })?;
1626  }
1627  Ok(())
1628}
1629
1630fn check_defimpl_references(expression: &calcit_core::Calcit, check: &impl Fn(&str) -> Result<(), String>) -> Result<(), String> {
1631  match expression {
1632    calcit_core::Calcit::Symbol { sym, .. } => check(sym),
1633    calcit_core::Calcit::List(items) => items.traverse_result(&mut |item| check_defimpl_references(item, check)),
1634    _ => Ok(()),
1635  }
1636}
1637
1638fn resolve_defimpl_symbol(
1639  file: &FileInSnapShot,
1640  imports: &std::collections::HashMap<Arc<str>, Arc<calcit_core::program::ImportRule>>,
1641  namespace: &str,
1642  symbol: &str,
1643) -> (String, String) {
1644  use calcit_core::program::ImportRule;
1645  if let Some((prefix, name)) = symbol.split_once('/') {
1646    let owner = match imports.get(prefix).map(AsRef::as_ref) {
1647      Some(ImportRule::NsAs(target)) => target.as_ref(),
1648      _ => prefix,
1649    };
1650    return (owner.to_owned(), name.to_owned());
1651  }
1652  if file.defs.contains_key(symbol) {
1653    return (namespace.to_owned(), symbol.to_owned());
1654  }
1655  match imports.get(symbol).map(AsRef::as_ref) {
1656    Some(ImportRule::NsReferDef(owner, name)) => (owner.to_string(), name.to_string()),
1657    Some(ImportRule::NsDefault(module)) => (module.to_string(), "default".to_owned()),
1658    _ => (calcit_core::calcit::CORE_NS.to_owned(), symbol.to_owned()),
1659  }
1660}
1661
1662fn defimpl_edit_baseline(snapshot_file: &str, snapshot: &Snapshot, namespace: &str, code: &Cirru) -> Result<Option<Snapshot>, String> {
1663  if let Cirru::List(items) = code
1664    && let Some(Cirru::Leaf(head)) = items.first()
1665    && is_core_defimpl(snapshot_file, snapshot, namespace, head)?
1666  {
1667    return Ok(Some(snapshot.clone()));
1668  }
1669  Ok(None)
1670}
1671
1672fn handle_mv_def(opts: &EditMvDefCommand, snapshot_file: &str) -> Result<(), String> {
1673  let (source_ns, source_def) = parse_target(&opts.source)?;
1674  let (target_ns, target_def) = parse_target(&opts.target)?;
1675
1676  let mut snapshot = load_snapshot(snapshot_file)?;
1677  check_ns_editable(&snapshot, source_ns)?;
1678  check_ns_editable(&snapshot, target_ns)?;
1679
1680  let source_file = snapshot
1681    .files
1682    .get(source_ns)
1683    .ok_or_else(|| format!("Namespace '{source_ns}' not found"))?;
1684  let resolved_source_def =
1685    resolve_definition_lookup(source_ns, source_def, source_file.defs.keys().map(|name| name.as_str()), false)?.resolved;
1686  if source_ns == target_ns && resolved_source_def == target_def {
1687    return Err("Source and target are identical; nothing to move.".to_string());
1688  }
1689
1690  let target_file = snapshot
1691    .files
1692    .get(target_ns)
1693    .ok_or_else(|| format!("Namespace '{target_ns}' not found"))?;
1694  if target_file.defs.contains_key(target_def) {
1695    return Err(format!("Definition '{target_def}' already exists in namespace '{target_ns}'"));
1696  }
1697
1698  let code = &source_file.defs[resolved_source_def.as_str()].code;
1699  let before = defimpl_edit_baseline(snapshot_file, &snapshot, source_ns, code)?;
1700  let (renamed_code, _) = rename_definition_declaration(snapshot_file, &snapshot, source_ns, code, &resolved_source_def, target_def)?;
1701  let mut entry = snapshot
1702    .files
1703    .get_mut(source_ns)
1704    .expect("resolved namespace exists")
1705    .defs
1706    .remove(resolved_source_def.as_str())
1707    .expect("resolved definition exists");
1708  entry.code = renamed_code;
1709  snapshot
1710    .files
1711    .get_mut(target_ns)
1712    .expect("resolved namespace exists")
1713    .defs
1714    .insert(target_def.to_string(), entry);
1715
1716  if let Some(before) = before {
1717    check_defimpl_destination(
1718      snapshot_file,
1719      &before,
1720      &snapshot,
1721      source_ns,
1722      target_ns,
1723      &snapshot.files[target_ns].defs[target_def].code,
1724    )?;
1725  }
1726  save_snapshot(&snapshot, snapshot_file)?;
1727
1728  println!(
1729    "{} Moved definition '{}' from '{}' to '{}'",
1730    "✓".green(),
1731    resolved_source_def.cyan(),
1732    source_ns.cyan(),
1733    format!("{target_ns}/{target_def}").cyan()
1734  );
1735
1736  Ok(())
1737}
1738
1739#[derive(Serialize)]
1740struct MetaReport {
1741  schema_version: u32,
1742  command: &'static str,
1743  target: String,
1744  dry_run: bool,
1745  revision: String,
1746  original_revision: String,
1747  new_revision: String,
1748  doc: String,
1749  tags: Vec<String>,
1750  examples_count: usize,
1751  tests_count: usize,
1752  #[serde(skip_serializing_if = "Vec::is_empty")]
1753  removed_tests: Vec<String>,
1754}
1755
1756fn sorted_tag_strings(tags: &HashSet<EdnTag>) -> Vec<String> {
1757  let mut items: Vec<String> = tags.iter().map(|tag| format!(":{}", tag.ref_str())).collect();
1758  items.sort();
1759  items
1760}
1761
1762/// Update definition metadata (`:doc`, `:tags`, `:examples`, or test removal) in one command.
1763fn handle_meta(opts: &EditMetaCommand, snapshot_file: &str) -> Result<(), String> {
1764  let output_format = StructuredOutputFormat::parse(&opts.format, "edit meta")?;
1765  let _structured_guard = super::common::StructuredMutationOutputGuard::new(output_format != StructuredOutputFormat::Human);
1766
1767  let has_doc = opts.doc.is_some();
1768  let has_tags_replace = opts.tags.is_some();
1769  let has_tags_delta = !opts.add_tags.is_empty() || !opts.rm_tags.is_empty();
1770  let has_tags_clear = opts.clear_tags;
1771  if (has_tags_replace as u8 + has_tags_delta as u8 + has_tags_clear as u8) > 1 {
1772    return Err("Tag flags conflict: use either --tags, --clear-tags, or --add-tag/--rm-tag".to_owned());
1773  }
1774
1775  let has_examples_replace = opts.examples;
1776  let has_examples_add = opts.add_example;
1777  let has_examples_clear = opts.clear_examples;
1778  if (has_examples_replace as u8 + has_examples_add as u8 + has_examples_clear as u8) > 1 {
1779    return Err("Example flags conflict: use at most one of --examples, --add-example, or --clear-examples".to_owned());
1780  }
1781  if opts.at.is_some() && !has_examples_add {
1782    return Err("`--at` can only be used with `--add-example`".to_owned());
1783  }
1784  if (opts.file.is_some() || opts.code.is_some()) && !has_examples_replace && !has_examples_add {
1785    return Err("`--file` and `--code` require `--examples` or `--add-example`".to_owned());
1786  }
1787
1788  let has_rm_test = !opts.rm_tests.is_empty();
1789  if !has_doc
1790    && !has_tags_replace
1791    && !has_tags_delta
1792    && !has_tags_clear
1793    && !has_examples_replace
1794    && !has_examples_add
1795    && !has_examples_clear
1796    && !has_rm_test
1797  {
1798    return Err(
1799      "No metadata changes requested. Pass --doc, --tags/--add-tag/--rm-tag/--clear-tags, --examples/--add-example/--clear-examples, or --rm-test."
1800        .to_owned(),
1801    );
1802  }
1803
1804  let (namespace, definition) = parse_target(&opts.target)?;
1805  let original_content =
1806    fs::read_to_string(snapshot_file).map_err(|error| format!("Failed to read snapshot '{snapshot_file}': {error}"))?;
1807  let before_revision = snapshot_content_revision(&original_content);
1808  let mut snapshot = load_snapshot(snapshot_file)?;
1809
1810  let mut guarded_units: Option<BTreeSet<String>> = None;
1811  if let Some(expected) = opts.expect_revision.as_deref() {
1812    if super::snapshot_scope::is_scoped_revision(expected) {
1813      let units = super::snapshot_scope::snapshot_units(&snapshot)?;
1814      guarded_units = Some(super::snapshot_scope::check_scoped_revision(expected, &units)?);
1815    } else if expected != before_revision {
1816      return Err(format!(
1817        "Snapshot revision mismatch: expected '{expected}', current revision is '{before_revision}'. Re-run `query` and retry `edit meta`."
1818      ));
1819    }
1820  }
1821
1822  let code_input = if has_examples_replace || has_examples_add {
1823    read_code_input(&opts.file, &opts.code)?
1824  } else {
1825    None
1826  };
1827
1828  let (resolved_definition, code_entry) = get_code_entry_mut(&mut snapshot, namespace, definition)?;
1829  let target_name = format!("{namespace}/{resolved_definition}");
1830  if let Some(guarded) = &guarded_units {
1831    let target_unit = format!("def:{target_name}");
1832    if !guarded.contains(&target_unit) {
1833      return Err(format!(
1834        "Definition conflict: `edit meta` targets {target_unit}, which the scoped revision does not cover. Re-run the dry-run and review the new plan."
1835      ));
1836    }
1837  }
1838
1839  if let Some(doc) = &opts.doc {
1840    code_entry.doc.clone_from(doc);
1841  }
1842
1843  if has_tags_clear {
1844    code_entry.tags.clear();
1845  } else if let Some(raw_tags) = &opts.tags {
1846    code_entry.tags = parse_tags_csv(raw_tags)?;
1847  } else if has_tags_delta {
1848    for raw in &opts.add_tags {
1849      for tag in parse_tags_csv(raw)? {
1850        code_entry.tags.insert(tag);
1851      }
1852    }
1853    for raw in &opts.rm_tags {
1854      for tag in parse_tags_csv(raw)? {
1855        code_entry.tags.remove(&tag);
1856      }
1857    }
1858  }
1859
1860  if has_examples_clear {
1861    code_entry.examples.clear();
1862  } else if has_examples_replace {
1863    let raw = code_input
1864      .as_deref()
1865      .ok_or("Examples input required: use --file, --code, or pipe input via stdin")?;
1866    code_entry.examples = parse_examples_input(raw)?;
1867  } else if has_examples_add {
1868    let raw = code_input
1869      .as_deref()
1870      .ok_or("Example input required: use --file, --code, or pipe via stdin")?;
1871    let example = decode_mutation_syntax_input(raw, opts.input_format)?;
1872    let position = opts.at.unwrap_or(code_entry.examples.len());
1873    if position > code_entry.examples.len() {
1874      return Err(format!("Position {} out of range (max: {})", position, code_entry.examples.len()));
1875    }
1876    code_entry.examples.insert(position, example);
1877  }
1878
1879  let mut removed_tests = Vec::new();
1880  for test_name in &opts.rm_tests {
1881    let Some(index) = code_entry.tests.iter().position(|test| test.name == *test_name) else {
1882      let mut available = code_entry.tests.iter().map(|test| test.name.as_str()).collect::<Vec<_>>();
1883      available.sort_unstable();
1884      return Err(format!(
1885        "Test `{test_name}` not found on `{target_name}`{}",
1886        if available.is_empty() {
1887          String::new()
1888        } else {
1889          format!("; available tests: {}", available.join(", "))
1890        }
1891      ));
1892    };
1893    code_entry.tests.remove(index);
1894    removed_tests.push(test_name.clone());
1895  }
1896
1897  let doc_snapshot = code_entry.doc.clone();
1898  let tags_snapshot = sorted_tag_strings(&code_entry.tags);
1899  let examples_count = code_entry.examples.len();
1900  let tests_count = code_entry.tests.len();
1901
1902  let new_revision = if opts.dry_run {
1903    before_revision.clone()
1904  } else {
1905    save_snapshot(&snapshot, snapshot_file)?;
1906    let updated_content =
1907      fs::read_to_string(snapshot_file).map_err(|error| format!("Failed to read snapshot '{snapshot_file}': {error}"))?;
1908    snapshot_content_revision(&updated_content)
1909  };
1910
1911  if let Some(doc) = &opts.doc
1912    && doc.starts_with('|')
1913  {
1914    eprintln!(
1915      "{} Documentation is stored verbatim, so the leading `|` is kept as text; pass the plain text without the Cirru string prefix.",
1916      "⚠".yellow()
1917    );
1918  }
1919
1920  let report = MetaReport {
1921    schema_version: 1,
1922    command: "edit.meta",
1923    target: target_name,
1924    dry_run: opts.dry_run,
1925    revision: before_revision.clone(),
1926    original_revision: before_revision,
1927    new_revision,
1928    doc: doc_snapshot,
1929    tags: tags_snapshot.clone(),
1930    examples_count,
1931    tests_count,
1932    removed_tests,
1933  };
1934
1935  match output_format {
1936    StructuredOutputFormat::Json => {
1937      println!(
1938        "{}",
1939        serde_json::to_string(&report).map_err(|error| format!("Failed to serialize edit meta result: {error}"))?
1940      );
1941    }
1942    StructuredOutputFormat::Edn => {
1943      let value = serde_json::to_value(&report).map_err(|error| format!("Failed to encode edit meta result: {error}"))?;
1944      println!("{}", format_json_value_as_edn(&value)?);
1945    }
1946    StructuredOutputFormat::Human => {
1947      let tags_display = if tags_snapshot.is_empty() {
1948        "none".to_owned()
1949      } else {
1950        tags_snapshot.join(",")
1951      };
1952      if opts.dry_run {
1953        println!(
1954          "{} [dry-run] Would update metadata for '{}' in namespace '{}' (tags: {}, examples: {}, tests: {})",
1955          "✓".green(),
1956          resolved_definition.cyan(),
1957          namespace,
1958          tags_display,
1959          examples_count,
1960          tests_count
1961        );
1962      } else {
1963        println!(
1964          "{} Updated metadata for '{}' in namespace '{}' (tags: {}, examples: {}, tests: {})",
1965          "✓".green(),
1966          resolved_definition.cyan(),
1967          namespace,
1968          tags_display,
1969          examples_count,
1970          tests_count
1971        );
1972      }
1973    }
1974  }
1975
1976  Ok(())
1977}
1978
1979fn parse_schema_input(raw: &str, input_format: SyntaxInputFormat) -> Result<Cirru, String> {
1980  decode_mutation_syntax_input(raw, input_format)
1981    .map_err(|error| format!("Failed to parse schema code input: {error}\nSchema examples: `quote String` or `quote $ Ref Bool`."))
1982}
1983
1984fn strip_name_field_from_schema(schema: Cirru) -> Cirru {
1985  match schema {
1986    Cirru::List(items) => {
1987      if items.is_empty() {
1988        return Cirru::List(items);
1989      }
1990
1991      if let Some(Cirru::Leaf(head)) = items.first() {
1992        if &**head == ":optional" && items.len() == 2 {
1993          return Cirru::List(vec![items[0].clone(), strip_name_field_from_schema(items[1].clone())]);
1994        }
1995        if &**head == "::" && items.len() == 3 && matches!(items.get(1), Some(Cirru::Leaf(tag)) if &**tag == ":optional") {
1996          return Cirru::List(vec![
1997            items[0].clone(),
1998            items[1].clone(),
1999            strip_name_field_from_schema(items[2].clone()),
2000          ]);
2001        }
2002
2003        if &**head == "{}" {
2004          let mut next_items = vec![items[0].clone()];
2005          for pair in items.iter().skip(1) {
2006            if let Cirru::List(xs) = pair
2007              && xs.len() == 2
2008              && matches!(xs.first(), Some(Cirru::Leaf(key)) if &**key == ":name")
2009            {
2010              continue;
2011            }
2012            next_items.push(pair.clone());
2013          }
2014          return Cirru::List(next_items);
2015        }
2016
2017        if &**head == "&{}" {
2018          let mut next_items = vec![items[0].clone()];
2019          let mut idx = 1usize;
2020          while idx < items.len() {
2021            if idx + 1 < items.len() && matches!(&items[idx], Cirru::Leaf(key) if &**key == ":name") {
2022              idx += 2;
2023              continue;
2024            }
2025            next_items.push(items[idx].clone());
2026            idx += 1;
2027          }
2028          return Cirru::List(next_items);
2029        }
2030      }
2031
2032      Cirru::List(items)
2033    }
2034    other => other,
2035  }
2036}
2037
2038fn handle_ffi(opts: &EditFfiCommand, snapshot_file: &str) -> Result<(), String> {
2039  let (namespace, definition) = parse_target(&opts.target)?;
2040  let snapshot = load_snapshot(snapshot_file)?;
2041  check_ns_editable(&snapshot, namespace)?;
2042  let file_data = snapshot
2043    .files
2044    .get(namespace)
2045    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
2046  let resolved_definition =
2047    resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), false)?.resolved;
2048
2049  let ffi = if opts.clear {
2050    None
2051  } else {
2052    let raw = read_code_input(&opts.file, &opts.code)?.ok_or(ERR_CODE_INPUT_REQUIRED)?;
2053    let value = cirru_edn::parse(&raw).map_err(|error| format!("FFI metadata must be valid Cirru EDN: {error}"))?;
2054    if !matches!(value, Edn::Map(_) | Edn::Struct(_)) {
2055      return Err("FFI metadata must be an EDN map (for example `{}` with :backend/:kind entries)".to_owned());
2056    }
2057    Some(value)
2058  };
2059
2060  save_ffi_preserving_snapshot(snapshot_file, namespace, &resolved_definition, ffi)?;
2061  if opts.clear {
2062    println!(
2063      "{} Cleared FFI metadata for '{}' in namespace '{}'",
2064      "✓".green(),
2065      resolved_definition.cyan(),
2066      namespace
2067    );
2068  } else {
2069    println!(
2070      "{} Updated FFI metadata for '{}' in namespace '{}'",
2071      "✓".green(),
2072      resolved_definition.cyan(),
2073      namespace
2074    );
2075  }
2076  Ok(())
2077}
2078
2079/// A bare nominal value schema such as `Point` resolves in the definition's
2080/// namespace (#2677). Check that it names something there, so a typo is not
2081/// stored as a new nominal type: a local definition, a `:refer` import, or a
2082/// `calcit.core` definition.
2083fn reject_unresolved_bare_value_schema(
2084  snapshot: &snapshot::Snapshot,
2085  namespace: &str,
2086  schema: &CalcitTypeAnnotation,
2087) -> Result<(), String> {
2088  let CalcitTypeAnnotation::TypeRef(name, args) = schema else {
2089    return Ok(());
2090  };
2091  let bare = name.trim_start_matches('\'');
2092  if !args.is_empty() || bare.contains('/') {
2093    return Ok(());
2094  }
2095  let Some(file) = snapshot.files.get(namespace) else {
2096    return Ok(());
2097  };
2098  if file.defs.contains_key(bare) {
2099    return Ok(());
2100  }
2101  let referred = calcit_core::program::extract_import_map(&file.ns.code, namespace)
2102    .ok()
2103    .and_then(|imports| imports.get(bare).cloned())
2104    .is_some_and(|rule| matches!(rule.as_ref(), calcit_core::program::ImportRule::NsReferDef(..)));
2105  let in_core = calcit_core::load_core_snapshot()
2106    .ok()
2107    .and_then(|core| {
2108      core
2109        .files
2110        .get(calcit_core::calcit::CORE_NS)
2111        .map(|file| file.defs.contains_key(bare))
2112    })
2113    .unwrap_or(false);
2114  if referred || in_core {
2115    return Ok(());
2116  }
2117  Err(format!(
2118    "Schema validation failed: `{bare}` is not defined in `{namespace}` and not brought in with `:refer`; define it, add `(target.ns :refer $ {bare})` to the ns form, or write `alias/{bare}` / `target.ns/{bare}`"
2119  ))
2120}
2121
2122fn handle_schema(opts: &EditSchemaCommand, snapshot_file: &str) -> Result<(), String> {
2123  let (namespace, definition) = parse_target(&opts.target)?;
2124
2125  let snapshot = load_snapshot_for_metadata(snapshot_file)?;
2126  check_ns_editable(&snapshot, namespace)?;
2127
2128  let file_data = snapshot
2129    .files
2130    .get(namespace)
2131    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
2132
2133  let resolved_definition =
2134    resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), false)?.resolved;
2135
2136  if let Some(feature) = &opts.add_feature {
2137    if opts.clear || opts.file.is_some() || opts.code.is_some() {
2138      return Err("`edit schema --add-feature` cannot be combined with --clear, --file, or --code".to_owned());
2139    }
2140    if !matches!(feature.as_str(), "js-ffi" | "erased-cache" | "state" | "io") {
2141      return Err(format!(
2142        "Unsupported schema feature `{feature}`; --add-feature supports `js-ffi`, `erased-cache`, `state` and `io`"
2143      ));
2144    }
2145    let existing = &file_data.defs[&resolved_definition].schema;
2146    let CalcitTypeAnnotation::Fn(signature) = existing.as_ref() else {
2147      return Err(format!(
2148        "`{namespace}/{resolved_definition}` needs a structured Fn schema before `--add-feature {feature}`; declare its arguments and return type with `calcit edit schema`, then add the feature. `calcit edit ffi` changes export metadata, not lexical feature permission."
2149      ));
2150    };
2151    if signature.features.iter().any(|item| item.ref_str() == feature) {
2152      println!(
2153        "{} Schema feature :{feature} is already present for '{namespace}/{resolved_definition}'",
2154        "✓".green()
2155      );
2156      return Ok(());
2157    }
2158    let mut updated = signature.as_ref().clone();
2159    let mut features = updated.features.as_ref().clone();
2160    features.insert(EdnTag::new(feature.as_str()));
2161    updated.features = Arc::new(features);
2162    save_schema_preserving_snapshot(
2163      snapshot_file,
2164      namespace,
2165      &resolved_definition,
2166      Some(&CalcitTypeAnnotation::Fn(Arc::new(updated))),
2167    )?;
2168    println!(
2169      "{} Added schema feature :{feature} to '{namespace}/{resolved_definition}'",
2170      "✓".green()
2171    );
2172    return Ok(());
2173  }
2174
2175  let schema = if opts.clear {
2176    DYNAMIC_TYPE.clone()
2177  } else {
2178    let raw = read_code_input(&opts.file, &opts.code)?.ok_or(ERR_CODE_INPUT_REQUIRED)?;
2179    let schema_payload = strip_name_field_from_schema(parse_schema_input(&raw, opts.input_format)?);
2180
2181    // The retired spelling is still accepted as input and stored compactly;
2182    // the note teaches the spelling a Snapshot keeps.
2183    if let Err(note) = snapshot::reject_legacy_schema_input(&schema_payload) {
2184      eprintln!(
2185        "⚠️  {}",
2186        note.replace(snapshot::LEGACY_TYPE_SYNTAX_CODE, snapshot::LEGACY_TYPE_SYNTAX_WARNING)
2187      );
2188    }
2189    let schema = snapshot::parse_schema_annotation_for_write(&schema_payload).map_err(|e| format!("Schema validation failed: {e}"))?;
2190    reject_unresolved_bare_value_schema(&snapshot, namespace, &schema)?;
2191    // Only calcit.core may rely on a checker built-in rule; `--check-only`
2192    // would reject the saved schema with E_OPEN_WITHOUT_REASON.
2193    if !calcit_core::calcit::is_bundled_core_ns(namespace) && snapshot::schema_uses_intrinsic_reason(&schema) {
2194      let hit = snapshot::OpenWithoutReasonHit {
2195        ns: namespace.to_owned(),
2196        def: resolved_definition,
2197        families: vec![],
2198        reserved_intrinsic: true,
2199      };
2200      return Err(format!(
2201        "Schema validation failed ({}): {}",
2202        snapshot::OPEN_WITHOUT_REASON_ERROR,
2203        hit.message()
2204      ));
2205    }
2206    schema
2207  };
2208
2209  save_schema_preserving_snapshot(
2210    snapshot_file,
2211    namespace,
2212    &resolved_definition,
2213    (!opts.clear).then_some(schema.as_ref()),
2214  )?;
2215
2216  if opts.clear {
2217    println!(
2218      "{} Cleared schema for '{}' in namespace '{}'",
2219      "✓".green(),
2220      resolved_definition.cyan(),
2221      namespace
2222    );
2223    return Ok(());
2224  }
2225
2226  println!(
2227    "{} Updated schema for '{}' in namespace '{}'",
2228    "✓".green(),
2229    resolved_definition.cyan(),
2230    namespace
2231  );
2232
2233  Ok(())
2234}
2235
2236pub(crate) fn find_edn_map_value_mut<'a>(map: &'a mut EdnMapView, expected: &str) -> Option<&'a mut Edn> {
2237  map
2238    .0
2239    .iter_mut()
2240    .find_map(|(key, value)| edn_key_matches(key, expected).then_some(value))
2241}
2242
2243fn find_edn_struct_value_mut<'a>(struct_value: &'a mut EdnStructView, expected: &str) -> Option<&'a mut Edn> {
2244  struct_value
2245    .pairs
2246    .iter_mut()
2247    .find_map(|(key, value)| (key.ref_str() == expected).then_some(value))
2248}
2249
2250fn snapshot_file_form<'a>(root: &'a mut Edn, namespace: &str) -> Option<&'a mut Edn> {
2251  let Edn::Map(root) = root else { return None };
2252  let Edn::Map(files) = find_edn_map_value_mut(root, "files")? else {
2253    return None;
2254  };
2255  find_edn_map_value_mut(files, namespace)
2256}
2257
2258fn snapshot_schema_form(root: &mut Edn, namespace: &str, definition: &str) -> Option<Option<Edn>> {
2259  let Edn::Struct(file) = snapshot_file_form(root, namespace)? else {
2260    return None;
2261  };
2262  let Edn::Map(defs) = find_edn_struct_value_mut(file, "defs")? else {
2263    return None;
2264  };
2265  let Edn::Struct(entry) = find_edn_map_value_mut(defs, definition)? else {
2266    return None;
2267  };
2268  Some(find_edn_struct_value_mut(entry, "schema").cloned())
2269}
2270
2271fn replace_snapshot_schema_form(root: &mut Edn, namespace: &str, definition: &str, schema: Option<Edn>) -> Result<(), String> {
2272  let Edn::Map(root) = root else {
2273    return Err("Staged Snapshot root must be an EDN map".to_owned());
2274  };
2275  let Edn::Map(files) = find_edn_map_value_mut(root, "files").ok_or("Staged Snapshot is missing :files")? else {
2276    return Err("Staged Snapshot :files must be an EDN map".to_owned());
2277  };
2278  let Edn::Struct(file) =
2279    find_edn_map_value_mut(files, namespace).ok_or_else(|| format!("Staged namespace '{namespace}' not found"))?
2280  else {
2281    return Err(format!("Staged namespace '{namespace}' must be a FileEntry struct"));
2282  };
2283  let Edn::Map(defs) =
2284    find_edn_struct_value_mut(file, "defs").ok_or_else(|| format!("Staged namespace '{namespace}' is missing :defs"))?
2285  else {
2286    return Err(format!("Staged namespace '{namespace}' :defs must be an EDN map"));
2287  };
2288  let Edn::Struct(entry) =
2289    find_edn_map_value_mut(defs, definition).ok_or_else(|| format!("Staged definition '{namespace}/{definition}' not found"))?
2290  else {
2291    return Err(format!("Staged definition '{namespace}/{definition}' must be a CodeEntry struct"));
2292  };
2293  if let Some(schema) = schema {
2294    if let Some(value) = find_edn_struct_value_mut(entry, "schema") {
2295      *value = schema;
2296    } else {
2297      entry.pairs.push((EdnTag::new("schema"), schema));
2298    }
2299  } else {
2300    entry.pairs.retain(|(key, _)| key.ref_str() != "schema");
2301  }
2302  Ok(())
2303}
2304
2305/// Preserve untouched file/schema forms and metadata after typed staged edits.
2306fn restore_untouched_schema_forms(
2307  original_content: &str,
2308  rendered_content: &str,
2309  staged_snapshot: &Snapshot,
2310  staged_path: &str,
2311  operations: &[Vec<String>],
2312) -> Result<String, String> {
2313  let mut original_source = original_content.to_owned();
2314  strip_shebang(&mut original_source);
2315  let mut original_edn =
2316    cirru_edn::parse(&original_source).map_err(|error| format!("Failed to parse original Snapshot EDN: {error}"))?;
2317  let original_snapshot = snapshot::load_snapshot_data_for_metadata(&original_edn, "staged original", None)
2318    .map_err(|error| format!("Failed to load original Snapshot for schema preservation: {error}"))?;
2319  let mut rendered_source = rendered_content.to_owned();
2320  let shebang = original_content
2321    .lines()
2322    .next()
2323    .filter(|line| line.starts_with("#!"))
2324    .map(str::to_owned);
2325  strip_shebang(&mut rendered_source);
2326  let mut rendered_edn = cirru_edn::parse(&rendered_source).map_err(|error| format!("Failed to parse staged Snapshot EDN: {error}"))?;
2327
2328  // Rendering inserts a canonical hint, but preservation must retain metadata
2329  // from the staged source rather than turn that hint into an unrelated edit.
2330  if let Edn::Map(root) = &mut rendered_edn {
2331    root.0.retain(|key, _| !edn_key_matches(key, "about"));
2332    if let Some(about) = &staged_snapshot.about {
2333      root.insert_key("about", Edn::Str(about.as_str().into()));
2334    }
2335  }
2336
2337  for (namespace, file) in &original_snapshot.files {
2338    let Some(staged_file) = staged_snapshot.files.get(namespace) else {
2339      continue;
2340    };
2341    if file.ns != staged_file.ns {
2342      continue;
2343    }
2344    // A metadata-only transaction must retain the entire untouched file form.
2345    // Explicit schema edits still request canonicalization even if types match.
2346    if file == staged_file
2347      && !operations.iter().any(|operation| {
2348        operation.first().is_some_and(|group| group == "edit")
2349          && operation.get(1).is_some_and(|name| name == "schema")
2350          && operation
2351            .get(2)
2352            .is_some_and(|target| target.split_once('/').is_some_and(|(ns, _)| ns == namespace))
2353      })
2354    {
2355      if let (Edn::Map(original_root), Edn::Map(rendered_root)) = (&mut original_edn, &mut rendered_edn)
2356        && let Some(Edn::Map(original_files)) = find_edn_map_value_mut(original_root, "files")
2357        && let Some(Edn::Map(rendered_files)) = find_edn_map_value_mut(rendered_root, "files")
2358        && let Some((key, value)) = original_files.0.iter().find(|(key, _)| edn_key_matches(key, namespace))
2359      {
2360        rendered_files.0.retain(|key, _| !edn_key_matches(key, namespace));
2361        rendered_files.insert(key.clone(), value.clone());
2362      }
2363      continue;
2364    }
2365    for (definition, entry) in &file.defs {
2366      let Some(staged_entry) = staged_file.defs.get(definition) else {
2367        continue;
2368      };
2369      if entry.schema != staged_entry.schema
2370        || operations.iter().any(|operation| {
2371          operation.first().is_some_and(|group| group == "edit")
2372            && operation.get(1).is_some_and(|name| name == "schema")
2373            && operation
2374              .get(2)
2375              .is_some_and(|target| target == &format!("{namespace}/{definition}"))
2376        })
2377      {
2378        continue;
2379      }
2380      if let Some(original_schema) = snapshot_schema_form(&mut original_edn, namespace, definition) {
2381        replace_snapshot_schema_form(&mut rendered_edn, namespace, definition, original_schema)?;
2382      }
2383    }
2384  }
2385
2386  let restored_snapshot = snapshot::load_snapshot_data(&rendered_edn, staged_path)
2387    .map_err(|error| format!("Failed to reload schema-preserving staged Snapshot: {error}"))?;
2388  if &restored_snapshot != staged_snapshot {
2389    return Err("Restoring unselected schema forms changed the staged Snapshot semantics; no changes were written.".to_owned());
2390  }
2391  let formatted = cirru_edn::format(&rendered_edn, true).map_err(|error| format!("Failed to format staged Snapshot EDN: {error}"))?;
2392  Ok(match shebang {
2393    Some(line) => format!("{line}\n{formatted}"),
2394    None => formatted,
2395  })
2396}
2397
2398/// Save only one definition schema against the original EDN tree. Rendering the
2399/// typed Snapshot would otherwise canonicalize unrelated legacy schemas.
2400fn save_schema_preserving_snapshot(
2401  snapshot_file: &str,
2402  namespace: &str,
2403  definition: &str,
2404  schema: Option<&calcit_core::calcit::CalcitTypeAnnotation>,
2405) -> Result<(), String> {
2406  let original = fs::read_to_string(snapshot_file).map_err(|e| format!("Failed to read {snapshot_file}: {e}"))?;
2407  let shebang = original.lines().next().filter(|line| line.starts_with("#!")).map(str::to_owned);
2408  let mut content = original;
2409  strip_shebang(&mut content);
2410  let mut data = cirru_edn::parse(&content).map_err(|e| format!("Failed to parse EDN: {e}"))?;
2411  let Edn::Map(root) = &mut data else {
2412    return Err("Snapshot root must be an EDN map".to_owned());
2413  };
2414  let files_value = find_edn_map_value_mut(root, "files").ok_or_else(|| "Snapshot is missing :files".to_owned())?;
2415  let Edn::Map(files) = files_value else {
2416    return Err("Snapshot :files must be an EDN map".to_owned());
2417  };
2418  let file_value = find_edn_map_value_mut(files, namespace).ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
2419  let Edn::Struct(file) = file_value else {
2420    return Err(format!("Namespace '{namespace}' must be a FileEntry struct"));
2421  };
2422  let defs_value = find_edn_struct_value_mut(file, "defs").ok_or_else(|| format!("Namespace '{namespace}' is missing :defs"))?;
2423  let Edn::Map(defs) = defs_value else {
2424    return Err(format!("Namespace '{namespace}' :defs must be an EDN map"));
2425  };
2426  let definition_value =
2427    find_edn_map_value_mut(&mut *defs, definition).ok_or_else(|| format!("Definition '{namespace}/{definition}' not found"))?;
2428  let Edn::Struct(entry) = definition_value else {
2429    return Err(format!("Definition '{namespace}/{definition}' must be a CodeEntry struct"));
2430  };
2431  if let Some(schema) = schema {
2432    let schema_edn = snapshot::schema_annotation_to_storage_edn(schema);
2433    if let Some(value) = find_edn_struct_value_mut(entry, "schema") {
2434      *value = schema_edn;
2435    } else {
2436      entry.pairs.push((EdnTag::new("schema"), schema_edn));
2437    }
2438  } else {
2439    entry.pairs.retain(|(key, _)| key.ref_str() != "schema");
2440  }
2441
2442  // Validate the selected contract before saving; other source contracts can
2443  // still need explicit repairs. Execution and transaction completion stay strict.
2444  let checked = snapshot::load_snapshot_data_for_metadata(&data, snapshot_file, Some((namespace, definition))).map_err(|e| {
2445    format!("Schema validation failed: `{namespace}/{definition}` would make the snapshot unloadable, nothing was written: {e}")
2446  })?;
2447  validate_selected_js_ffi(&checked, snapshot_file, namespace, definition)?;
2448
2449  let formatted = cirru_edn::format(&data, true).map_err(|e| format!("Failed to format snapshot EDN: {e}"))?;
2450  let output = match shebang {
2451    Some(line) => format!("{line}\n{formatted}"),
2452    None => formatted,
2453  };
2454  calcit_core::util::atomic_write::write_snapshot(snapshot_file, output.as_bytes())
2455}
2456
2457fn save_ffi_preserving_snapshot(snapshot_file: &str, namespace: &str, definition: &str, ffi: Option<Edn>) -> Result<(), String> {
2458  let original = fs::read_to_string(snapshot_file).map_err(|e| format!("Failed to read {snapshot_file}: {e}"))?;
2459  let shebang = original.lines().next().filter(|line| line.starts_with("#!")).map(str::to_owned);
2460  let mut content = original;
2461  strip_shebang(&mut content);
2462  let mut data = cirru_edn::parse(&content).map_err(|e| format!("Failed to parse EDN: {e}"))?;
2463  let Edn::Map(root) = &mut data else {
2464    return Err("Snapshot root must be an EDN map".to_owned());
2465  };
2466  let files_value = find_edn_map_value_mut(root, "files").ok_or_else(|| "Snapshot is missing :files".to_owned())?;
2467  let Edn::Map(files) = files_value else {
2468    return Err("Snapshot :files must be an EDN map".to_owned());
2469  };
2470  let file_value = find_edn_map_value_mut(files, namespace).ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
2471  let Edn::Struct(file) = file_value else {
2472    return Err(format!("Namespace '{namespace}' must be a FileEntry struct"));
2473  };
2474  let defs_value = find_edn_struct_value_mut(file, "defs").ok_or_else(|| format!("Namespace '{namespace}' is missing :defs"))?;
2475  let Edn::Map(defs) = defs_value else {
2476    return Err(format!("Namespace '{namespace}' :defs must be an EDN map"));
2477  };
2478  let definition_value =
2479    find_edn_map_value_mut(&mut *defs, definition).ok_or_else(|| format!("Definition '{namespace}/{definition}' not found"))?;
2480  let Edn::Struct(entry) = definition_value else {
2481    return Err(format!("Definition '{namespace}/{definition}' must be a CodeEntry struct"));
2482  };
2483  if let Some(value) = ffi {
2484    if let Some(existing) = find_edn_struct_value_mut(entry, "ffi") {
2485      *existing = value;
2486    } else {
2487      entry.pairs.push((EdnTag::new("ffi"), value));
2488    }
2489  } else {
2490    entry.pairs.retain(|(key, _)| key.ref_str() != "ffi");
2491  }
2492
2493  let checked = snapshot::load_snapshot_data_for_metadata(&data, snapshot_file, Some((namespace, definition)))?;
2494  validate_selected_js_ffi(&checked, snapshot_file, namespace, definition)?;
2495
2496  let formatted = cirru_edn::format(&data, true).map_err(|e| format!("Failed to format snapshot EDN: {e}"))?;
2497  let output = match shebang {
2498    Some(line) => format!("{line}\n{formatted}"),
2499    None => formatted,
2500  };
2501  calcit_core::util::atomic_write::write_snapshot(snapshot_file, output.as_bytes())
2502}
2503
2504fn validate_selected_js_ffi(snapshot: &Snapshot, snapshot_file: &str, namespace: &str, definition: &str) -> Result<(), String> {
2505  let base_dir = Path::new(snapshot_file).parent().unwrap_or_else(|| Path::new("."));
2506  let dependencies = std::cell::OnceCell::new();
2507  let entry = &snapshot.files[namespace].defs[definition];
2508  if entry.ffi.is_none() {
2509    return Ok(());
2510  }
2511  let imports = calcit_core::program::extract_import_map(&snapshot.files[namespace].ns.code, namespace)?;
2512  let load = || {
2513    dependencies.get_or_init(|| {
2514      let folder = calcit_core::project_module_folder(base_dir);
2515      let mut modules = Vec::new();
2516      let mut errors = Vec::new();
2517      for path in snapshot
2518        .entries
2519        .values()
2520        .flat_map(|entry| &entry.modules)
2521        .collect::<std::collections::BTreeSet<_>>()
2522      {
2523        match super::load_module_with_sources_silent(path, base_dir, &folder) {
2524          Ok(module) => modules.push(module),
2525          Err(error) => errors.push(format!("{path}: {error}")),
2526        }
2527      }
2528      (modules, errors)
2529    })
2530  };
2531  let resolve = |ty: &calcit_core::calcit::CalcitTypeAnnotation, target| {
2532    let Some((ns, def)) = calcit_core::js_ffi_source::ffi_host_type_path(ty, namespace, &imports, |ns, def| {
2533      if let Some(file) = snapshot.files.get(ns) {
2534        return file.defs.contains_key(def);
2535      }
2536      load()
2537        .0
2538        .iter()
2539        .any(|module| module.snapshot.files.get(ns).is_some_and(|file| file.defs.contains_key(def)))
2540    }) else {
2541      return false;
2542    };
2543    let is_host = |file: &snapshot::FileInSnapShot| {
2544      file
2545        .defs
2546        .get(def)
2547        .is_some_and(|host| calcit_core::js_ffi_source::is_ffi_host_entry(host, target))
2548    };
2549    if let Some(file) = snapshot.files.get(ns) {
2550      return is_host(file);
2551    }
2552    let loaded = load();
2553    let mut owners = loaded.0.iter().filter_map(|module| module.snapshot.files.get(ns));
2554    owners
2555      .next()
2556      .is_some_and(|first| is_host(first) && owners.all(|other| other == first))
2557  };
2558  calcit_core::js_ffi_source::validate_js_definition_with(&snapshot.files[namespace].defs[definition], &resolve).map_err(|error| {
2559    match dependencies.get() {
2560      Some((_, errors)) if !errors.is_empty() => {
2561        let detail = errors.join("\n");
2562        format!("{namespace}/{definition}: {error}; failed to resolve declared modules: {detail}; no changes were written")
2563      }
2564      _ => format!("{namespace}/{definition}: {error}; no changes were written"),
2565    }
2566  })?;
2567  Ok(())
2568}
2569
2570fn parse_examples_input(raw: &str) -> Result<Vec<Cirru>, String> {
2571  parse_quoted_cirru_nodes(raw).map_err(|error| {
2572    format!(
2573      "Failed to parse examples: {error}\nEach top-level example needs its own `quote`, so both leaves and expressions remain representable."
2574    )
2575  })
2576}
2577
2578fn parse_tag_token(raw: &str) -> Result<EdnTag, String> {
2579  let trimmed = raw.trim();
2580  if trimmed.is_empty() {
2581    return Err("empty tag".to_string());
2582  }
2583  let name = trimmed.strip_prefix(':').unwrap_or(trimmed);
2584  if name.is_empty() {
2585    return Err(format!("invalid tag: {raw}"));
2586  }
2587  Ok(EdnTag::new(name))
2588}
2589
2590fn parse_tags_csv(raw: &str) -> Result<HashSet<EdnTag>, String> {
2591  let trimmed = raw.trim();
2592  if trimmed.is_empty() {
2593    return Ok(HashSet::new());
2594  }
2595  let mut tags = HashSet::new();
2596  for token in trimmed.split(',') {
2597    let piece = token.trim();
2598    if piece.is_empty() {
2599      return Err("tags must be comma-separated without empty items".to_string());
2600    }
2601    tags.insert(parse_tag_token(piece)?);
2602  }
2603  Ok(tags)
2604}
2605
2606fn get_code_entry_mut<'a>(
2607  snapshot: &'a mut Snapshot,
2608  namespace: &str,
2609  definition: &str,
2610) -> Result<(String, &'a mut CodeEntry), String> {
2611  check_ns_editable(snapshot, namespace)?;
2612  let file_data = snapshot
2613    .files
2614    .get_mut(namespace)
2615    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
2616  let resolved_definition =
2617    resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), false)?.resolved;
2618  let code_entry = file_data
2619    .defs
2620    .get_mut(resolved_definition.as_str())
2621    .ok_or_else(|| format!("Definition '{resolved_definition}' not found in namespace '{namespace}'"))?;
2622  Ok((resolved_definition, code_entry))
2623}
2624
2625fn handle_add_test(opts: &EditAddTestCommand, snapshot_file: &str) -> Result<(), String> {
2626  let (namespace, definition) = parse_target(&opts.target)?;
2627  snapshot::validate_test_names([opts.name.as_str()], "Test")?;
2628  let code_input = read_code_input(&opts.file, &opts.code)?;
2629  let raw = code_input
2630    .as_deref()
2631    .ok_or("Test input required: use --file, --code, or pipe via stdin")?;
2632  let code = decode_mutation_syntax_input(raw, opts.input_format)?;
2633  let tags = parse_tags_csv(opts.tags.as_deref().unwrap_or(""))?;
2634
2635  let mut snapshot = load_snapshot(snapshot_file)?;
2636  let (resolved_definition, entry) = get_code_entry_mut(&mut snapshot, namespace, definition)?;
2637  let new_test = TestEntry {
2638    name: opts.name.clone(),
2639    code,
2640    tags,
2641  };
2642  if let Some(index) = entry.tests.iter().position(|test| test.name == opts.name) {
2643    if !opts.overwrite {
2644      return Err(format!(
2645        "Test `{}` already exists on `{namespace}/{resolved_definition}`; pass --overwrite to replace it explicitly",
2646        opts.name
2647      ));
2648    }
2649    entry.tests[index] = new_test;
2650  } else {
2651    entry.tests.push(new_test);
2652  }
2653  save_snapshot(&snapshot, snapshot_file)?;
2654  println!(
2655    "{} Added test '{}' to '{}/{}'",
2656    "✓".green(),
2657    opts.name.cyan(),
2658    namespace,
2659    resolved_definition
2660  );
2661  Ok(())
2662}
2663
2664pub(crate) fn apply_operation_at_path(
2665  code: &Cirru,
2666  path: &[usize],
2667  operation: TreeOperation,
2668  new_node: Option<&Cirru>,
2669) -> Result<Cirru, String> {
2670  if path.is_empty() {
2671    // Operating on root
2672    return match operation {
2673      TreeOperation::Replace => {
2674        let node = new_node.ok_or("Code input required for replace operation")?;
2675        Ok(node.clone())
2676      }
2677      TreeOperation::Delete => Err("Cannot delete root node".to_string()),
2678      _ => Err(format!(
2679        "`{}` is not supported at the definition root; use a non-empty --path",
2680        operation.command_form()
2681      )),
2682    };
2683  }
2684
2685  // Navigate to parent and operate on child
2686  apply_operation_recursive(code, path, 0, operation, new_node)
2687}
2688
2689fn apply_operation_recursive(
2690  code: &Cirru,
2691  path: &[usize],
2692  depth: usize,
2693  operation: TreeOperation,
2694  new_node: Option<&Cirru>,
2695) -> Result<Cirru, String> {
2696  match code {
2697    Cirru::Leaf(_) => Err(format!("Cannot navigate into leaf node at depth {depth}")),
2698    Cirru::List(items) => {
2699      let idx = path[depth];
2700      if idx >= items.len() {
2701        return Err(format!("Path index {} out of bounds (list has {} items)", idx, items.len()));
2702      }
2703
2704      if depth == path.len() - 1 {
2705        // At target position, apply operation
2706        let mut new_items = items.clone();
2707
2708        match operation {
2709          TreeOperation::Delete => {
2710            new_items.remove(idx);
2711          }
2712          TreeOperation::Replace => {
2713            let newn = new_node.ok_or("Code input required for replace operation")?;
2714            new_items[idx] = newn.clone();
2715          }
2716          TreeOperation::InsertBefore => {
2717            let newn = new_node.ok_or_else(|| format!("Code input required for `{}`", TreeOperation::InsertBefore.command_form()))?;
2718            new_items.insert(idx, newn.clone());
2719          }
2720          TreeOperation::InsertAfter => {
2721            let newn = new_node.ok_or_else(|| format!("Code input required for `{}`", TreeOperation::InsertAfter.command_form()))?;
2722            new_items.insert(idx + 1, newn.clone());
2723          }
2724          TreeOperation::InsertChild => {
2725            // Insert as first child of the node at idx
2726            let newn = new_node.ok_or_else(|| format!("Code input required for `{}`", TreeOperation::InsertChild.command_form()))?;
2727            match &new_items[idx] {
2728              Cirru::List(children) => {
2729                let mut new_children = vec![newn.clone()];
2730                new_children.extend(children.clone());
2731                new_items[idx] = Cirru::List(new_children);
2732              }
2733              Cirru::Leaf(_) => {
2734                return Err("Cannot insert child into leaf node".to_string());
2735              }
2736            }
2737          }
2738          TreeOperation::AppendChild => {
2739            // Insert as last child of the node at idx
2740            let newn = new_node.ok_or_else(|| format!("Code input required for `{}`", TreeOperation::AppendChild.command_form()))?;
2741            match &new_items[idx] {
2742              Cirru::List(children) => {
2743                let mut new_children = children.clone();
2744                new_children.push(newn.clone());
2745                new_items[idx] = Cirru::List(new_children);
2746              }
2747              Cirru::Leaf(_) => {
2748                return Err("Cannot append child to leaf node".to_string());
2749              }
2750            }
2751          }
2752          TreeOperation::SwapNextSibling => {
2753            // Swap current node with next sibling
2754            if idx + 1 >= new_items.len() {
2755              return Err(format!("Cannot swap: no next sibling at index {idx}"));
2756            }
2757            new_items.swap(idx, idx + 1);
2758          }
2759          TreeOperation::SwapPrevSibling => {
2760            // Swap current node with previous sibling
2761            if idx == 0 {
2762              return Err("Cannot swap: no previous sibling at index 0".to_string());
2763            }
2764            new_items.swap(idx - 1, idx);
2765          }
2766        }
2767
2768        Ok(Cirru::List(new_items))
2769      } else {
2770        // Continue navigating
2771        let mut new_items = items.clone();
2772        new_items[idx] = apply_operation_recursive(&items[idx], path, depth + 1, operation, new_node)?;
2773        Ok(Cirru::List(new_items))
2774      }
2775    }
2776  }
2777}
2778
2779pub(crate) fn navigate_to_path(code: &Cirru, path: &[usize]) -> Result<Cirru, String> {
2780  if path.is_empty() {
2781    return Ok(code.clone());
2782  }
2783
2784  let mut current = code;
2785  for (depth, &idx) in path.iter().enumerate() {
2786    match current {
2787      Cirru::Leaf(_) => {
2788        let partial = format_path(&path[..depth]);
2789        return Err(format!(
2790          "Cannot navigate into leaf node at depth {depth}\n   Valid path stops at: {}\n   Tip: Use 'calcit tree show --path {}' to explore the tree structure (use dot-separated indices, e.g. '@2.1.0')",
2791          format_path(&path[..depth]),
2792          partial,
2793        ));
2794      }
2795      Cirru::List(items) => {
2796        if idx >= items.len() {
2797          let partial = format_path(&path[..depth]);
2798          return Err(format!(
2799            "Path index {} out of bounds at depth {} (list has {} items)\n   Attempted path: {}\n   Valid path up to: {}\n   Valid index range at this level: 0-{}\n   Tip: Use 'calcit tree show --path {}' to see available children",
2800            idx,
2801            depth,
2802            items.len(),
2803            format_path(path),
2804            format_path(&path[..depth]),
2805            items.len().saturating_sub(1),
2806            partial,
2807          ));
2808        }
2809        current = &items[idx];
2810      }
2811    }
2812  }
2813
2814  Ok(current.clone())
2815}
2816
2817// ═══════════════════════════════════════════════════════════════════════════════
2818// Namespace operations
2819// ═══════════════════════════════════════════════════════════════════════════════
2820
2821fn handle_add_ns(opts: &EditAddNsCommand, snapshot_file: &str) -> Result<(), String> {
2822  let mut snapshot = load_snapshot(snapshot_file)?;
2823
2824  // Check if namespace can be edited (must be under current package)
2825  check_ns_editable(&snapshot, &opts.namespace)?;
2826
2827  if snapshot.files.contains_key(&opts.namespace) {
2828    return Err(format!("Namespace '{}' already exists", opts.namespace));
2829  }
2830
2831  // Create ns code
2832  let ns_code = if let Some(raw) = read_code_input(&opts.file, &opts.code)? {
2833    let code = decode_mutation_syntax_input(&raw, opts.input_format)?;
2834    // Validate: if input looks like a `ns` expression, the name inside must match
2835    if let Cirru::List(ref items) = code
2836      && let Some(Cirru::Leaf(kw)) = items.first()
2837      && kw.as_ref() == "ns"
2838      && let Some(Cirru::Leaf(ns_in_expr)) = items.get(1)
2839      && ns_in_expr.as_ref() != opts.namespace.as_str()
2840    {
2841      return Err(format!(
2842        "Namespace name mismatch: positional argument is '{}' but ns expression contains '{}'. They must be identical.",
2843        opts.namespace, ns_in_expr
2844      ));
2845    }
2846    code
2847  } else {
2848    // Default minimal ns declaration: (ns namespace-name)
2849    Cirru::List(vec![Cirru::Leaf(Arc::from("ns")), Cirru::Leaf(Arc::from(opts.namespace.as_str()))])
2850  };
2851
2852  let file_entry = FileInSnapShot {
2853    ns: NsEntry {
2854      doc: String::new(),
2855      code: ns_code,
2856    },
2857    defs: HashMap::new(),
2858  };
2859
2860  snapshot.files.insert(opts.namespace.clone(), file_entry);
2861
2862  save_snapshot(&snapshot, snapshot_file)?;
2863
2864  println!("{} Created namespace '{}'", "✓".green(), opts.namespace.cyan());
2865
2866  Ok(())
2867}
2868
2869fn handle_rm_ns(opts: &EditRmNsCommand, snapshot_file: &str) -> Result<(), String> {
2870  let mut snapshot = load_snapshot(snapshot_file)?;
2871
2872  // Check if namespace can be edited
2873  check_ns_editable(&snapshot, &opts.namespace)?;
2874
2875  if snapshot.files.remove(&opts.namespace).is_none() {
2876    return Err(format!("Namespace '{}' not found", opts.namespace));
2877  }
2878
2879  save_snapshot(&snapshot, snapshot_file)?;
2880
2881  println!("{} Deleted namespace '{}'", "✓".green(), opts.namespace.cyan());
2882
2883  Ok(())
2884}
2885
2886fn handle_imports(opts: &EditImportsCommand, snapshot_file: &str) -> Result<(), String> {
2887  let raw = read_code_input(&opts.file, &opts.code)?.ok_or("Imports input required: use --file, --code, or pipe via stdin")?;
2888
2889  let mut snapshot = load_snapshot(snapshot_file)?;
2890
2891  // Check if namespace can be edited
2892  check_ns_editable(&snapshot, &opts.namespace)?;
2893
2894  let file_data = snapshot
2895    .files
2896    .get_mut(&opts.namespace)
2897    .ok_or_else(|| format!("Namespace '{}' not found", opts.namespace))?;
2898
2899  // Build new ns code with imports.
2900  // Always use build_ns_code to produce the correct nested structure:
2901  //   ["ns", "namespace", [":require", rule1, rule2, ...]]
2902  let ns_name = &opts.namespace;
2903  let rules = parse_import_rules_input(&raw, opts.input_format)?;
2904
2905  for warning in validate_import_rules(&rules)? {
2906    eprintln!("{} in namespace '{}': {warning}", "Warning:".yellow(), opts.namespace);
2907  }
2908
2909  // Extract old imports for comparison
2910  let old_imports = extract_require_list(&file_data.ns.code);
2911
2912  file_data.ns.code = build_ns_code(ns_name, &rules);
2913
2914  // Extract new imports
2915  let new_imports = extract_require_list(&file_data.ns.code);
2916
2917  save_snapshot(&snapshot, snapshot_file)?;
2918
2919  // Show what changed
2920  println!("{} Updated imports for namespace '{}'", "✓".green(), opts.namespace.cyan());
2921
2922  // Show removed imports
2923  let removed: Vec<_> = old_imports.iter().filter(|old| !new_imports.contains(old)).collect();
2924  if !removed.is_empty() {
2925    println!("  {} Removed:", "-".red());
2926    for import in removed {
2927      println!("    {}", import.dimmed());
2928    }
2929  }
2930
2931  // Show added imports
2932  let added: Vec<_> = new_imports.iter().filter(|new| !old_imports.contains(new)).collect();
2933  let mut added_namespaces = Vec::new();
2934  if !added.is_empty() {
2935    println!("  {} Added:", "+".green());
2936    for import in &added {
2937      println!("    {import}");
2938      // Extract namespace from import (first token before :refer or :as)
2939      if let Some(first_token) = import.split_whitespace().next() {
2940        let ns = first_token.strip_prefix('(').unwrap_or(first_token);
2941        added_namespaces.push(ns.to_owned());
2942      }
2943    }
2944  }
2945
2946  // Show unchanged count if there are any
2947  let unchanged_count = old_imports.iter().filter(|old| new_imports.contains(old)).count();
2948  if unchanged_count > 0 {
2949    println!("  {} {} unchanged", "·".dimmed(), format!("{unchanged_count}").dimmed());
2950  }
2951
2952  // Show detailed tips for newly added imports
2953  if !added.is_empty() {
2954    println!();
2955    println!("{}", "Usage tips for new imports:".dimmed());
2956
2957    // Parse each added import string to provide tips
2958    for added_str in &added {
2959      // Parse the import string back to Cirru to analyze it
2960      if let Ok(parsed) = cirru_parser::parse(added_str)
2961        && let Some(rule) = parsed.first()
2962        && let Some(source_ns) = get_require_source_ns(rule)
2963      {
2964        print_import_usage_tips(rule, &source_ns);
2965      }
2966    }
2967  }
2968
2969  Ok(())
2970}
2971
2972fn import_rules_from_json(value: &serde_json::Value) -> Result<Vec<Cirru>, String> {
2973  use super::common::json_value_to_cirru;
2974
2975  let serde_json::Value::Array(elems) = value else {
2976    return Err("Imports must be a Cirru EDN list or JSON array of import rules.".to_string());
2977  };
2978  if elems.is_empty() {
2979    return Ok(vec![]);
2980  }
2981
2982  // Detect: array-of-arrays => multiple rules; array-of-strings => single flat rule.
2983  if elems.first().is_some_and(serde_json::Value::is_array) {
2984    return elems.iter().map(json_value_to_cirru).collect::<Result<Vec<_>, _>>();
2985  }
2986
2987  // Guard: user may have accidentally included ':require' prefix.
2988  if let Some(serde_json::Value::String(first_str)) = elems.first()
2989    && first_str == ":require"
2990  {
2991    return Err(
2992      "Do not include ':require' as a prefix in the imports input. \
2993       Pass rules directly, e.g. --code 'src-ns :refer $ sym' or use --file for multiple rules."
2994        .to_string(),
2995    );
2996  }
2997  Ok(vec![json_value_to_cirru(value)?])
2998}
2999
3000/// Validate one decoded imports-vector syntax node and return its rule expressions.
3001fn import_rules_from_syntax_node(node: &Cirru, selected_format: SyntaxInputFormat) -> Result<Vec<Cirru>, String> {
3002  let Cirru::List(items) = node else {
3003    return Err(format!(
3004      "Imports input format `{selected_format}` expected an imports vector node headed by `[]`, received a leaf."
3005    ));
3006  };
3007  if !matches!(items.first(), Some(Cirru::Leaf(head)) if &**head == "[]") {
3008    return Err(format!(
3009      "Imports input format `{selected_format}` expected an imports vector node headed by `[]`."
3010    ));
3011  }
3012
3013  items
3014    .iter()
3015    .skip(1)
3016    .enumerate()
3017    .map(|(index, rule)| {
3018      if !matches!(rule, Cirru::List(_)) {
3019        return Err(format!("Import rule {} inside the `[]` node must be an expression.", index + 1));
3020      }
3021      Ok(rule.clone())
3022    })
3023    .collect()
3024}
3025
3026/// Decode bulk imports through the explicit syntax contract or the legacy auto-compatible path.
3027fn parse_import_rules_input(raw: &str, requested_format: SyntaxInputFormat) -> Result<Vec<Cirru>, String> {
3028  let trimmed = raw.trim();
3029  if trimmed.is_empty() {
3030    return Err(
3031      "Imports input is empty. Provide one imports vector node as quoted Cirru or JSON AST; use --input-format to select the transport."
3032        .to_string(),
3033    );
3034  }
3035
3036  if requested_format != SyntaxInputFormat::Auto {
3037    let node = super::common::decode_mutation_syntax_input(trimmed, requested_format)?;
3038    return import_rules_from_syntax_node(&node, requested_format);
3039  }
3040
3041  if trimmed.starts_with('[') {
3042    let value = serde_json::from_str(trimmed).map_err(|error| format!("Failed to parse imports JSON: {error}"))?;
3043    return import_rules_from_json(&value);
3044  }
3045  let cirru_node = parse_input_to_cirru(trimmed)?;
3046  import_rules_from_syntax_node(&cirru_node, SyntaxInputFormat::Cirru)
3047}
3048
3049/// Extract formatted import list from ns code for comparison
3050fn extract_require_list(ns_code: &Cirru) -> Vec<String> {
3051  let mut imports = Vec::new();
3052
3053  if let Cirru::List(items) = ns_code {
3054    let mut in_require = false;
3055    for item in items {
3056      if let Cirru::Leaf(s) = item
3057        && s.as_ref() == ":require"
3058      {
3059        in_require = true;
3060        continue;
3061      }
3062      if in_require {
3063        // Format each import as one-liner
3064        if let Ok(formatted) = item.format_one_liner() {
3065          imports.push(formatted);
3066        }
3067      }
3068    }
3069  }
3070
3071  imports
3072}
3073
3074/// Extract the source namespace from a require rule
3075/// Accept the same optional legacy `[]` prefix as the program import parser.
3076fn get_require_source_ns(rule: &Cirru) -> Option<String> {
3077  match rule {
3078    Cirru::List(items) => {
3079      let items = match items.first() {
3080        Some(head) if head.eq_leaf("[]") => &items[1..],
3081        _ => items.as_slice(),
3082      };
3083      match items.first() {
3084        Some(Cirru::Leaf(source)) => Some(source.to_string()),
3085        _ => None,
3086      }
3087    }
3088    _ => None,
3089  }
3090}
3091
3092/// Extract existing require rules from ns code
3093/// Handles structure: ["ns", "namespace", [":require", rule1, rule2, ...]]
3094pub(crate) fn extract_require_rules(ns_code: &Cirru) -> Vec<Cirru> {
3095  let mut rules = vec![];
3096  if let Cirru::List(items) = ns_code {
3097    for item in items.iter().skip(2) {
3098      // skip "ns" and namespace name
3099      if let Cirru::List(inner) = item
3100        && let Some(Cirru::Leaf(first)) = inner.first()
3101        && first.as_ref() == ":require"
3102      {
3103        // Found [:require rule1 rule2 ...]
3104        rules.extend(inner.iter().skip(1).cloned());
3105        break;
3106      }
3107    }
3108  }
3109  rules
3110}
3111
3112/// Build ns code from namespace name and require rules
3113/// Produces structure: ["ns", "namespace", [":require", rule1, rule2, ...]]
3114fn build_ns_code(ns_name: &str, rules: &[Cirru]) -> Cirru {
3115  let mut items = vec![Cirru::Leaf(Arc::from("ns")), Cirru::Leaf(Arc::from(ns_name))];
3116
3117  if !rules.is_empty() {
3118    let mut require_list = vec![Cirru::Leaf(Arc::from(":require"))];
3119    require_list.extend(rules.iter().cloned());
3120    items.push(Cirru::List(require_list));
3121  }
3122
3123  Cirru::List(items)
3124}
3125
3126fn handle_add_import(opts: &EditAddImportCommand, snapshot_file: &str) -> Result<(), String> {
3127  let raw = read_code_input(&opts.file, &opts.code)?.ok_or("Import rule input required: use --file, --code, or pipe via stdin")?;
3128
3129  let new_rule = decode_mutation_syntax_input(&raw, opts.input_format)?;
3130
3131  let _ = validate_import_rules(std::slice::from_ref(&new_rule))?;
3132
3133  // Validate that the rule has a source namespace
3134  let new_source_ns =
3135    get_require_source_ns(&new_rule).ok_or("Invalid require rule: first element must be a namespace name (e.g. 'calcit.core')")?;
3136
3137  let mut snapshot = load_snapshot(snapshot_file)?;
3138
3139  // Check if namespace can be edited
3140  check_ns_editable(&snapshot, &opts.namespace)?;
3141
3142  let file_data = snapshot
3143    .files
3144    .get_mut(&opts.namespace)
3145    .ok_or_else(|| format!("Namespace '{}' not found", opts.namespace))?;
3146
3147  // Extract existing rules
3148  let mut rules = extract_require_rules(&file_data.ns.code);
3149
3150  // Check if rule for this source namespace already exists
3151  let existing_idx = rules
3152    .iter()
3153    .position(|r| get_require_source_ns(r).as_deref() == Some(&new_source_ns));
3154
3155  let replaced = if let Some(idx) = existing_idx {
3156    if opts.overwrite {
3157      rules[idx] = new_rule.clone();
3158      true
3159    } else {
3160      return Err(format!(
3161        "Require rule for '{}' already exists in namespace '{}'. Use --overwrite to replace.",
3162        new_source_ns, opts.namespace
3163      ));
3164    }
3165  } else {
3166    rules.push(new_rule.clone());
3167    false
3168  };
3169
3170  for warning in validate_import_rules(&rules)? {
3171    eprintln!("{} in namespace '{}': {warning}", "Warning:".yellow(), opts.namespace);
3172  }
3173
3174  if replaced {
3175    println!(
3176      "{} Replaced require rule for '{}' in namespace '{}'",
3177      "✓".green(),
3178      new_source_ns.cyan(),
3179      opts.namespace
3180    );
3181  } else {
3182    println!(
3183      "{} Added require rule for '{}' in namespace '{}'",
3184      "✓".green(),
3185      new_source_ns.cyan(),
3186      opts.namespace
3187    );
3188  }
3189
3190  // Rebuild ns code
3191  file_data.ns.code = build_ns_code(&opts.namespace, &rules);
3192
3193  save_snapshot(&snapshot, snapshot_file)?;
3194
3195  // Show usage tips based on import type
3196  print_import_usage_tips(&new_rule, &new_source_ns);
3197
3198  Ok(())
3199}
3200
3201fn handle_rm_import(opts: &EditRmImportCommand, snapshot_file: &str) -> Result<(), String> {
3202  let mut snapshot = load_snapshot(snapshot_file)?;
3203
3204  // Check if namespace can be edited
3205  check_ns_editable(&snapshot, &opts.namespace)?;
3206
3207  let file_data = snapshot
3208    .files
3209    .get_mut(&opts.namespace)
3210    .ok_or_else(|| format!("Namespace '{}' not found", opts.namespace))?;
3211
3212  // Extract existing rules
3213  let mut rules = extract_require_rules(&file_data.ns.code);
3214
3215  // Find and remove the rule for the specified source namespace
3216  let original_len = rules.len();
3217  rules.retain(|r| get_require_source_ns(r).as_deref() != Some(&opts.source_ns));
3218
3219  if rules.len() == original_len {
3220    return Err(format!(
3221      "No require rule found for '{}' in namespace '{}'",
3222      opts.source_ns, opts.namespace
3223    ));
3224  }
3225
3226  // Rebuild ns code
3227  file_data.ns.code = build_ns_code(&opts.namespace, &rules);
3228
3229  save_snapshot(&snapshot, snapshot_file)?;
3230
3231  println!(
3232    "{} Removed require rule for '{}' from namespace '{}'",
3233    "✓".green(),
3234    opts.source_ns.cyan(),
3235    opts.namespace
3236  );
3237
3238  Ok(())
3239}
3240
3241// ═══════════════════════════════════════════════════════════════════════════════
3242// Semver helpers used by edit tests
3243// ═══════════════════════════════════════════════════════════════════════════════
3244
3245#[cfg(test)]
3246fn parse_semver_value(v: &str) -> Result<Version, String> {
3247  if v.starts_with('|') {
3248    return Err(format!(
3249      "Invalid version '{v}': do not include the '|' Cirru string prefix; use bare semver, e.g. '0.0.17'"
3250    ));
3251  }
3252  Version::parse(v).map_err(|_| format!("Invalid version '{v}': expected semver format, e.g. '0.0.17'"))
3253}
3254
3255#[cfg(test)]
3256fn bump_semver_value(current: &str, level: &str) -> Result<String, String> {
3257  let mut version = parse_semver_value(current)?;
3258  match level {
3259    "patch" => {
3260      version.patch += 1;
3261    }
3262    "minor" => {
3263      version.minor += 1;
3264      version.patch = 0;
3265    }
3266    "major" => {
3267      version.major += 1;
3268      version.minor = 0;
3269      version.patch = 0;
3270    }
3271    _ => {
3272      return Err(format!("Unknown bump level '{level}'. Valid levels: patch, minor, major"));
3273    }
3274  }
3275  version.pre = semver::Prerelease::EMPTY;
3276  version.build = semver::BuildMetadata::EMPTY;
3277  Ok(version.to_string())
3278}
3279
3280/// Print usage tips based on the import rule type
3281fn print_import_usage_tips(rule: &Cirru, source_ns: &str) {
3282  // Analyze the import rule to determine its type
3283  if let Cirru::List(items) = rule {
3284    let mut import_type = None;
3285    let mut symbols = Vec::new();
3286    let mut alias = None;
3287
3288    // Parse the import rule: (namespace :refer [symbols...]) or (namespace :as alias) or (namespace :default symbol)
3289    let mut i = 1; // Skip the namespace (first element)
3290    while i < items.len() {
3291      if let Cirru::Leaf(tag) = &items[i] {
3292        match tag.as_ref() {
3293          ":refer" => {
3294            import_type = Some("refer");
3295            // Next item should be a list of symbols or a single symbol
3296            if i + 1 < items.len() {
3297              match &items[i + 1] {
3298                Cirru::List(syms) => {
3299                  for sym in syms {
3300                    if let Cirru::Leaf(s) = sym {
3301                      symbols.push(s.to_string());
3302                    }
3303                  }
3304                }
3305                Cirru::Leaf(s) => symbols.push(s.to_string()),
3306              }
3307            }
3308            break;
3309          }
3310          ":as" => {
3311            import_type = Some("as");
3312            if i + 1 < items.len()
3313              && let Cirru::Leaf(a) = &items[i + 1]
3314            {
3315              alias = Some(a.to_string());
3316            }
3317            break;
3318          }
3319          ":default" => {
3320            import_type = Some("default");
3321            if i + 1 < items.len()
3322              && let Cirru::Leaf(s) = &items[i + 1]
3323            {
3324              symbols.push(s.to_string());
3325            }
3326            break;
3327          }
3328          _ => {}
3329        }
3330      }
3331      i += 1;
3332    }
3333
3334    // Print tips based on import type
3335    println!();
3336    println!("{}", "Usage tips:".dimmed());
3337
3338    match import_type {
3339      Some("refer") => {
3340        if symbols.is_empty() {
3341          println!(
3342            "  {} Use imported symbols directly: {}",
3343            "·".dimmed(),
3344            "(symbol-name ...)".to_string().cyan()
3345          );
3346        } else {
3347          println!("  {} Use imported symbols directly:", "·".dimmed());
3348          for symbol in symbols.iter().take(3) {
3349            println!("    {}", format!("({symbol} ...)").cyan());
3350          }
3351          if symbols.len() > 3 {
3352            println!("    {}", format!("... and {} more", symbols.len() - 3).dimmed());
3353          }
3354        }
3355      }
3356      Some("as") => {
3357        if let Some(a) = alias {
3358          println!("  {} Use with alias: {}", "·".dimmed(), format!("({a}/symbol-name ...)").cyan());
3359          println!(
3360            "  {} List definitions: {}",
3361            "·".dimmed(),
3362            format!("calcit query defs {source_ns}").cyan()
3363          );
3364        }
3365      }
3366      Some("default") => {
3367        if !symbols.is_empty() {
3368          println!(
3369            "  {} Default import available as: {}",
3370            "·".dimmed(),
3371            format!("({} ...)", symbols[0]).cyan()
3372          );
3373        }
3374      }
3375      None => {
3376        // Plain import without :refer/:as/:default
3377        println!(
3378          "  {} Use with full namespace: {}",
3379          "·".dimmed(),
3380          format!("({source_ns}/symbol-name ...)").cyan()
3381        );
3382        println!(
3383          "  {} List definitions: {}",
3384          "·".dimmed(),
3385          format!("calcit query defs {source_ns}").cyan()
3386        );
3387      }
3388      _ => {
3389        // Unknown import type
3390        println!(
3391          "  {} Use with full namespace: {}",
3392          "·".dimmed(),
3393          format!("({source_ns}/symbol-name ...)").cyan()
3394        );
3395      }
3396    }
3397  }
3398}
3399
3400#[cfg(test)]
3401mod tests {
3402  use super::{
3403    TransactionOperationReport, bump_semver_value, collect_format_advisories, handle_add_import, handle_add_test, handle_format,
3404    handle_imports, handle_meta, handle_schema, load_snapshot, parse_examples_input, parse_import_rules_input, parse_input_to_cirru,
3405    parse_schema_input, parse_transaction_operations, rename_definition_declaration, run_staged_fix_transaction,
3406    run_staged_transaction_with, save_schema_preserving_snapshot, save_snapshot, staged_fix_validation_args, staged_warning_difference,
3407  };
3408  use crate::cli_args::{
3409    EditAddImportCommand, EditAddTestCommand, EditFormatCommand, EditImportsCommand, EditMetaCommand, EditSchemaCommand,
3410    SyntaxInputFormat,
3411  };
3412  use crate::cli_handlers::test_support::TestProject;
3413  use calcit_core::calcit::CalcitTypeAnnotation;
3414  use cirru_edn::Edn;
3415  use cirru_parser::Cirru;
3416  use std::ffi::OsString;
3417  use std::fs;
3418  use std::path::Path;
3419  use std::sync::Arc;
3420
3421  type TestSnapshot = TestProject;
3422
3423  #[test]
3424  fn defimpl_uses_a_separate_storage_key() {
3425    let project = TestSnapshot::from_fixture();
3426    let path = project.snapshot_string();
3427    let mut snapshot = load_snapshot(&path).expect("load fixture");
3428    let validate = |snapshot: &calcit_core::snapshot::Snapshot, source: &str| {
3429      let code = parse_input_to_cirru(source).expect("read quoted definition");
3430      super::validate_definition_shape(&path, snapshot, "app.main", "PointLabelImpl", &code, false)
3431    };
3432    validate(&snapshot, "quote $ defimpl model/Point Label (.label label-point)").expect("receiver and storage key can differ");
3433    validate(&snapshot, "quote $ calcit.core/defimpl Point Label (.label label-point)").expect("qualified core macro");
3434    for source in [
3435      "quote $ defimpl Point",
3436      "quote $ defimpl :Point Label",
3437      "quote $ defimpl Point |Label",
3438    ] {
3439      let error = validate(&snapshot, source).expect_err("reject malformed implementation");
3440      assert!(error.contains("requires a receiver type symbol and a trait symbol"), "{error}");
3441    }
3442    assert!(
3443      validate(&snapshot, "quote $ defn Point () 1")
3444        .expect_err("ordinary definitions still declare their key")
3445        .contains("Definition name mismatch")
3446    );
3447    let core = calcit_core::load_core_snapshot().expect("load bundled core");
3448    let local_macro = core.files[calcit_core::calcit::CORE_NS].defs["defimpl"].clone();
3449    snapshot
3450      .files
3451      .get_mut("app.main")
3452      .expect("fixture namespace")
3453      .defs
3454      .insert("defimpl".into(), local_macro);
3455    assert!(
3456      validate(&snapshot, "quote $ defimpl Point Label (.label label-point)")
3457        .expect_err("a shadowing macro retains ordinary shape validation")
3458        .contains("Definition name mismatch")
3459    );
3460    let code = parse_input_to_cirru("quote $ defimpl Point Label (.label label-point)").expect("read shadowed macro call");
3461    let error = rename_definition_declaration(&path, &snapshot, "app.main", &code, "PointLabelImpl", "RenamedImpl")
3462      .expect_err("a shadowing macro retains declaration-name validation");
3463    assert!(error.contains("does not match declaration name"), "{error}");
3464  }
3465
3466  // Snapshot serialization normalizes the format version, so use package as an
3467  // observable staged mutation when testing transaction change detection.
3468  fn fake_package_operation(stage_path: &Path, index: usize, args: &[String]) -> Result<TransactionOperationReport, String> {
3469    let package = args.get(2).ok_or_else(|| "fake operation needs package at index 2".to_string())?;
3470    let mut snapshot = load_snapshot(&stage_path.to_string_lossy())?;
3471    snapshot.package = package.to_string();
3472    save_snapshot(&snapshot, &stage_path.to_string_lossy())?;
3473    Ok(TransactionOperationReport {
3474      index,
3475      args: args.to_vec(),
3476      stdout: String::new(),
3477      stderr: String::new(),
3478    })
3479  }
3480
3481  fn leaf(value: &str) -> Cirru {
3482    Cirru::Leaf(value.into())
3483  }
3484
3485  fn list(items: Vec<Cirru>) -> Cirru {
3486    Cirru::List(items)
3487  }
3488
3489  #[test]
3490  fn format_advisories_cover_dynamic_debt() {
3491    let snapshot =
3492      load_snapshot(concat!(env!("CARGO_MANIFEST_DIR"), "/../../calcit/test.cirru")).expect("fixture snapshot should load");
3493    let advisories = collect_format_advisories("calcit.cirru", &snapshot).join("\n");
3494
3495    assert!(!advisories.contains("W_LEGACY_ANY"), "advisories: {advisories}");
3496    assert!(advisories.contains("W_DYNAMIC_TYPE_DEBT"), "advisories: {advisories}");
3497    assert!(advisories.contains("analyze weak-types"), "advisories: {advisories}");
3498  }
3499
3500  #[test]
3501  fn canonical_typed_snapshot_has_no_format_advisories() {
3502    let original_edn = cirru_edn::parse(
3503      "{} (:package |mini) (:version |0.0.1)\n  :entries $ {}\n    :default $ {} (:description |) (:init-fn 'mini/main!) (:mode :native) (:reload-fn 'mini/reload!)\n      :modules $ []\n      :type-slots $ {}\n  :files $ {}",
3504    )
3505    .expect("canonical fixture should parse");
3506    let snapshot = calcit_core::snapshot::load_snapshot_data(&original_edn, "calcit.cirru").expect("canonical fixture should load");
3507
3508    assert!(collect_format_advisories("calcit.cirru", &snapshot).is_empty());
3509  }
3510
3511  #[test]
3512  fn format_loader_rejects_retired_any_in_schema_but_allows_any_tag_data() {
3513    let retired = cirru_edn::parse(
3514      "{} (:package |mini) (:version |0.0.1)\n  :entries $ {}\n    :default $ {} (:description |) (:init-fn 'mini/main!) (:mode :native) (:reload-fn 'mini/reload!)\n      :modules $ []\n      :type-slots $ {}\n  :files $ {}\n    |mini $ %{} :FileEntry\n      :ns $ %{} :CodeEntry (:doc |) (:code $ quote (ns mini)) (:examples $ []) (:schema nil)\n      :defs $ {}\n        |main! $ %{} :CodeEntry (:doc |) (:code $ quote (def main! 1)) (:examples $ []) (:schema :any)",
3515    )
3516    .expect("fixture should parse");
3517    let err = calcit_core::snapshot::load_snapshot_data_for_format(&retired, "calcit.cirru")
3518      .expect_err("format loader must reject retired :any schema");
3519    assert!(err.contains("E_LEGACY_TYPE_SYNTAX"), "err: {err}");
3520
3521    let data_tag = cirru_edn::parse(
3522      "{} (:package |mini) (:version |0.0.1)\n  :entries $ {}\n    :default $ {} (:description |) (:init-fn 'mini/main!) (:mode :native) (:reload-fn 'mini/reload!)\n      :modules $ []\n      :type-slots $ {}\n  :files $ {}\n    |mini $ %{} :FileEntry\n      :ns $ %{} :CodeEntry (:doc |) (:code $ quote (ns mini)) (:examples $ []) (:schema nil)\n      :defs $ {}\n        |main! $ %{} :CodeEntry (:doc |) (:code $ quote (def main! $ {} (:any :dynamic))) (:examples $ []) (:schema $ quote $ Map Tag Tag)",
3523    )
3524    .expect("data tag fixture should parse");
3525    calcit_core::snapshot::load_snapshot_data_for_format(&data_tag, "calcit.cirru")
3526      .expect("ordinary :any tag in data literal stays valid");
3527  }
3528
3529  #[test]
3530  fn imports_rejects_malformed_rule_without_writing_snapshot() {
3531    let fixture = TestSnapshot::from_fixture();
3532    let original = fs::read(&fixture.path).expect("fixture should read");
3533    let opts = EditImportsCommand {
3534      namespace: "app.main".to_string(),
3535      file: None,
3536      code: Some("quote $ []\n  audit.invalid :as".to_string()),
3537      input_format: SyntaxInputFormat::Auto,
3538    };
3539
3540    let error = handle_imports(&opts, &fixture.snapshot_string()).expect_err("malformed import rule should fail");
3541
3542    assert!(error.contains("import rule 1"), "error: {error}");
3543    assert!(error.contains("exactly 3 items"), "error: {error}");
3544    assert_eq!(fs::read(&fixture.path).expect("fixture should remain"), original);
3545  }
3546
3547  #[test]
3548  fn imports_parse_quoted_rule_list_and_keep_json_compatibility() {
3549    let cirru = "quote $ []\n  respo.core :refer $ div span\n  respo-ui.core :as ui";
3550    let json = r#"[["respo.core",":refer",["div","span"]],["respo-ui.core",":as","ui"]]"#;
3551    let expected = vec![
3552      list(vec![leaf("respo.core"), leaf(":refer"), list(vec![leaf("div"), leaf("span")])]),
3553      list(vec![leaf("respo-ui.core"), leaf(":as"), leaf("ui")]),
3554    ];
3555
3556    assert_eq!(
3557      parse_import_rules_input(cirru, SyntaxInputFormat::Auto).expect("quoted Cirru imports should parse"),
3558      expected
3559    );
3560    assert_eq!(
3561      parse_import_rules_input(json, SyntaxInputFormat::Auto).expect("JSON imports should remain supported"),
3562      expected
3563    );
3564  }
3565
3566  #[test]
3567  fn imports_explicit_formats_decode_one_imports_vector_node() {
3568    let cirru = "quote $ []\n  respo.core :refer $ div span";
3569    let json_ast = r#"["[]",["respo.core",":refer",["div","span"]]]"#;
3570    let expected = vec![list(vec![
3571      leaf("respo.core"),
3572      leaf(":refer"),
3573      list(vec![leaf("div"), leaf("span")]),
3574    ])];
3575
3576    assert_eq!(
3577      parse_import_rules_input(cirru, SyntaxInputFormat::Cirru).expect("explicit Cirru imports should parse"),
3578      expected
3579    );
3580    assert_eq!(
3581      parse_import_rules_input(json_ast, SyntaxInputFormat::JsonAst).expect("explicit JSON AST imports should parse"),
3582      expected
3583    );
3584  }
3585
3586  #[test]
3587  fn imports_explicit_json_ast_rejects_legacy_rule_array_shape() {
3588    let error = parse_import_rules_input(r#"[["respo.core",":refer",["div"]]]"#, SyntaxInputFormat::JsonAst)
3589      .expect_err("explicit JSON AST should require the full imports vector node");
3590
3591    assert!(error.contains("expected an imports vector node headed by `[]`"), "error: {error}");
3592  }
3593
3594  #[test]
3595  fn imports_quoted_list_requires_each_rule_to_be_an_expression() {
3596    let error =
3597      parse_import_rules_input("quote $ [] respo.core", SyntaxInputFormat::Auto).expect_err("flat quoted imports should fail");
3598
3599    assert!(error.contains("rule 1"), "error: {error}");
3600    assert!(error.contains("must be an expression"), "error: {error}");
3601  }
3602
3603  #[test]
3604  fn add_import_rejects_malformed_rule_without_writing_snapshot() {
3605    let fixture = TestSnapshot::from_fixture();
3606    let original = fs::read(&fixture.path).expect("fixture should read");
3607    let opts = EditAddImportCommand {
3608      namespace: "app.main".to_string(),
3609      file: None,
3610      code: Some("quote (audit.invalid :as)".to_string()),
3611      input_format: SyntaxInputFormat::Auto,
3612      overwrite: false,
3613    };
3614
3615    let error = handle_add_import(&opts, &fixture.snapshot_string()).expect_err("malformed import rule should fail");
3616
3617    assert!(error.contains("import rule 1"), "error: {error}");
3618    assert!(error.contains("exactly 3 items"), "error: {error}");
3619    assert_eq!(fs::read(&fixture.path).expect("fixture should remain"), original);
3620  }
3621
3622  #[test]
3623  fn defimpl_move_stays_in_an_owner_namespace() {
3624    let project = TestSnapshot::from_fixture();
3625    let path = project.snapshot_string();
3626    let mut snapshot = load_snapshot(&path).expect("load fixture");
3627    for namespace in ["app.model", "app.traits", "app.other"] {
3628      let mut file = snapshot.files["app.main"].clone();
3629      file.ns.code = list(vec![leaf("ns"), leaf(namespace)]);
3630      file.defs.clear();
3631      snapshot.files.insert(namespace.to_owned(), file);
3632    }
3633    let code = parse_input_to_cirru("quote $ defimpl app.model/Point app.traits/Label").expect("read definition");
3634    for target in ["app.model", "app.traits"] {
3635      super::check_defimpl_destination(&path, &snapshot, &snapshot, "app.main", target, &code).expect("allow an owner namespace");
3636    }
3637    let error = super::check_defimpl_destination(&path, &snapshot, &snapshot, "app.main", "app.other", &code)
3638      .expect_err("implementation discovery cannot find a third namespace");
3639    assert!(error.contains("receiver and trait are declared"), "{error}");
3640
3641    let entry = |code: &Cirru| {
3642      let mut entry = snapshot.files["app.main"].defs.values().next().expect("fixture definition").clone();
3643      entry.code = code.clone();
3644      entry
3645    };
3646    let mut staged = snapshot.clone();
3647    staged
3648      .files
3649      .get_mut("app.model")
3650      .unwrap()
3651      .defs
3652      .insert("defimpl".to_owned(), entry(&code));
3653    let error = super::check_defimpl_destination(&path, &snapshot, &staged, "app.main", "app.model", &code)
3654      .expect_err("inserting the destination key shadows the core macro");
3655    assert!(error.contains("no longer resolve to the core defimpl"), "{error}");
3656
3657    let code = parse_input_to_cirru("quote $ defimpl app.model/Point app.traits/Label (.label helper)").unwrap();
3658    let helper = entry(&parse_input_to_cirru("quote $ defn helper (self) |label").unwrap());
3659    let mut original = snapshot.clone();
3660    original.files.get_mut("app.main").unwrap().defs.insert("helper".to_owned(), helper);
3661    let error = super::check_defimpl_destination(&path, &original, &original, "app.main", "app.model", &code)
3662      .expect_err("unqualified method function would change resolution");
3663    assert!(error.contains("symbol 'helper' would resolve differently"), "{error}");
3664    let qualified = parse_input_to_cirru("quote $ defimpl app.model/Point app.traits/Label (.label app.main/helper)").unwrap();
3665    super::check_defimpl_destination(&path, &original, &original, "app.main", "app.model", &qualified)
3666      .expect("qualified method function keeps its resolution");
3667
3668    let reference = entry(&parse_input_to_cirru("quote $ defref *label |label").unwrap());
3669    for namespace in ["app.main", "app.model"] {
3670      original
3671        .files
3672        .get_mut(namespace)
3673        .unwrap()
3674        .defs
3675        .insert("*label".to_owned(), reference.clone());
3676    }
3677    let deref = parse_input_to_cirru("quote $ defimpl app.model/Point app.traits/Label (.label $ fn (self) , @*label)").unwrap();
3678    let error = super::check_defimpl_destination(&path, &original, &original, "app.main", "app.model", &deref)
3679      .expect_err("a dereferenced symbol would bind to the destination state");
3680    assert!(error.contains("symbol '*label' would resolve differently"), "{error}");
3681    let qualified =
3682      parse_input_to_cirru("quote $ defimpl app.model/Point app.traits/Label (.label $ fn (self) , @app.main/*label)").unwrap();
3683    super::check_defimpl_destination(&path, &original, &original, "app.main", "app.model", &qualified)
3684      .expect("qualified dereference keeps its resolution");
3685
3686    let ns_with_default = |namespace, module| {
3687      list(vec![
3688        leaf("ns"),
3689        leaf(namespace),
3690        list(vec![
3691          leaf(":require"),
3692          list(vec![leaf(module), leaf(":default"), leaf("formatter")]),
3693        ]),
3694      ])
3695    };
3696    original.files.get_mut("app.main").unwrap().ns.code = ns_with_default("app.main", "|module-a");
3697    original.files.get_mut("app.model").unwrap().ns.code = ns_with_default("app.model", "|module-b");
3698    let default_import =
3699      parse_input_to_cirru("quote $ defimpl app.model/Point app.traits/Label (.label $ fn (self) formatter self)").unwrap();
3700    let error = super::check_defimpl_destination(&path, &original, &original, "app.main", "app.model", &default_import)
3701      .expect_err("a default import from another module changes the binding");
3702    assert!(error.contains("symbol 'formatter' would resolve differently"), "{error}");
3703    original.files.get_mut("app.model").unwrap().ns.code = ns_with_default("app.model", "|module-a");
3704    super::check_defimpl_destination(&path, &original, &original, "app.main", "app.model", &default_import)
3705      .expect("the same module's default export keeps its resolution");
3706  }
3707
3708  fn rename_fixture_declaration(code: &Cirru, old_name: &str, new_name: &str) -> Result<(Cirru, bool), String> {
3709    let project = TestSnapshot::from_fixture();
3710    let path = project.snapshot_string();
3711    let snapshot = load_snapshot(&path).expect("load fixture");
3712    rename_definition_declaration(&path, &snapshot, "app.main", code, old_name, new_name)
3713  }
3714
3715  #[test]
3716  fn rename_preserves_core_defimpl_receiver_and_trait() {
3717    for source in [
3718      "quote $ defimpl model/Point Label (.label label-point)",
3719      "quote $ calcit.core/defimpl model/Point Label (.label label-point)",
3720    ] {
3721      let code = parse_input_to_cirru(source).expect("read quoted definition");
3722      let (renamed, changed) = rename_fixture_declaration(&code, "PointLabelImpl", "RenamedImpl").expect("rename storage key");
3723      assert_eq!(renamed, code);
3724      assert!(!changed);
3725    }
3726  }
3727
3728  #[test]
3729  fn rename_updates_definition_declaration_name() {
3730    let code = list(vec![leaf("defref"), leaf("*old"), list(vec![leaf("{}")])]);
3731    let (renamed, changed) = rename_fixture_declaration(&code, "*old", "*next").expect("rename should work");
3732
3733    assert!(changed);
3734    assert_eq!(renamed, list(vec![leaf("defref"), leaf("*next"), list(vec![leaf("{}")])]));
3735  }
3736
3737  #[test]
3738  fn transaction_parses_json_and_cirru_argument_lists() {
3739    let expected = vec![
3740      vec![
3741        "edit".to_string(),
3742        "meta".to_string(),
3743        "app.main/main!".to_string(),
3744        "--doc".to_string(),
3745        "hello".to_string(),
3746      ],
3747      vec![
3748        "tree".to_string(),
3749        "delete".to_string(),
3750        "app.main/main!".to_string(),
3751        "--path".to_string(),
3752        "@3".to_string(),
3753      ],
3754    ];
3755    let json = r#"[["edit","meta","app.main/main!","--doc","hello"],["tree","delete","app.main/main!","--path","@3"]]"#;
3756    let cirru = "[]\n  [] |edit |meta |app.main/main! |--doc |hello\n  [] |tree |delete |app.main/main! |--path |@3";
3757
3758    assert_eq!(parse_transaction_operations(json).expect("JSON transaction should parse"), expected);
3759    assert_eq!(
3760      parse_transaction_operations(cirru).expect("Cirru transaction should parse"),
3761      expected
3762    );
3763  }
3764
3765  #[test]
3766  fn transaction_cirru_embeds_quoted_code_without_string_escaping() {
3767    let cirru = "[]\n  []\n    , |tree\n    , |replace\n    , |app.main/main!\n    , |--path\n    , |@3.2\n    , |--code\n    quote $ println |done";
3768    let operations = parse_transaction_operations(cirru).expect("Cirru transaction with quoted code should parse");
3769    let code = operations[0].get(6).expect("formatted --code argument should exist");
3770
3771    assert_eq!(
3772      parse_input_to_cirru(code).expect("embedded quoted code should remain valid edit input"),
3773      list(vec![leaf("println"), leaf("|done")])
3774    );
3775  }
3776
3777  #[test]
3778  fn transaction_cirru_round_trips_quoted_empty_list() {
3779    let cirru = "[]\n  []\n    , |tree\n    , |insert\n    , |app.main/main!\n    , |--at\n    , |after\n    , |--path\n    , |@1\n    , |--code\n    quote ()";
3780    let operations = parse_transaction_operations(cirru).expect("Cirru transaction with an empty quoted list should parse");
3781    let code = operations[0].get(8).expect("formatted --code argument should exist");
3782
3783    assert_eq!(
3784      parse_input_to_cirru(code).expect("quoted empty list should remain valid edit input"),
3785      list(vec![])
3786    );
3787  }
3788
3789  #[test]
3790  fn transaction_rejects_unsupported_and_nested_commands() {
3791    let unsupported =
3792      parse_transaction_operations(r#"[["query","def","app.main/main!"]]"#).expect_err("read-only command should be rejected");
3793    assert!(unsupported.contains("Only edit, tree, and config"), "error: {unsupported}");
3794
3795    let nested = parse_transaction_operations(r#"[["edit","transaction","--file","again.cirru"]]"#)
3796      .expect_err("nested transaction should be rejected");
3797    assert!(nested.contains("nested edit transaction"), "error: {nested}");
3798
3799    let unsupported_edit = parse_transaction_operations(r#"[["edit","merge","--source","other.cirru"]]"#)
3800      .expect_err("non-transactional edit should be rejected");
3801    assert!(
3802      unsupported_edit.contains("unsupported staged mutation"),
3803      "error: {unsupported_edit}"
3804    );
3805
3806    let removed_edit = parse_transaction_operations(r#"[["edit","inc","--changed","app.main/main!"]]"#)
3807      .expect_err("removed edit subcommand should be rejected");
3808    assert!(removed_edit.contains("removed in 0.53.0"), "error: {removed_edit}");
3809
3810    let read_only =
3811      parse_transaction_operations(r#"[["tree","show","app.main/main!"]]"#).expect_err("read-only command should be rejected");
3812    assert!(read_only.contains("unsupported staged mutation"), "error: {read_only}");
3813  }
3814
3815  #[test]
3816  fn transaction_rejects_stale_revision_without_running_operations() {
3817    let fixture = TestSnapshot::from_fixture();
3818    let original = fs::read_to_string(&fixture.path).expect("fixture should read");
3819    let operations = vec![vec!["config".to_string(), "package".to_string(), "transaction-test".to_string()]];
3820    let mut called = false;
3821
3822    let error = run_staged_transaction_with(&fixture.path, &operations, Some("md5:stale"), false, |_, _, _| {
3823      called = true;
3824      Err("must not run".to_string())
3825    })
3826    .expect_err("stale transaction should fail");
3827
3828    assert!(!called);
3829    assert!(error.contains("revision mismatch"), "error: {error}");
3830    assert_eq!(fs::read_to_string(&fixture.path).expect("fixture should remain"), original);
3831  }
3832
3833  #[test]
3834  fn empty_fix_plan_still_rejects_a_stale_planning_revision() {
3835    let fixture = TestSnapshot::from_fixture();
3836
3837    let error = run_staged_fix_transaction(&fixture.path, &[], Some("md5:stale"), true, "browser", &[], None)
3838      .expect_err("an empty fix plan should still be bound to its planning revision");
3839
3840    assert!(error.contains("revision mismatch"), "error: {error}");
3841  }
3842
3843  #[test]
3844  fn staged_fix_validation_preserves_selected_entry_before_snapshot_path() {
3845    let args = staged_fix_validation_args(
3846      Path::new("/tmp/project/calcit.cirru.staged"),
3847      "browser",
3848      &[
3849        "--ns".to_owned(),
3850        "app.browser".to_owned(),
3851        "--preset".to_owned(),
3852        "surface-latest-v2".to_owned(),
3853      ],
3854    );
3855
3856    assert_eq!(
3857      args,
3858      vec![
3859        "--tips-level",
3860        "none",
3861        "--entry",
3862        "browser",
3863        "/tmp/project/calcit.cirru.staged",
3864        "fix",
3865        "--ns",
3866        "app.browser",
3867        "--preset",
3868        "surface-latest-v2",
3869      ]
3870      .into_iter()
3871      .map(OsString::from)
3872      .collect::<Vec<_>>()
3873    );
3874  }
3875
3876  #[test]
3877  fn staged_warning_difference_allows_baseline_warnings_but_rejects_new_multiplicity() {
3878    let baseline = vec!["warning-a".to_owned(), "warning-b".to_owned()];
3879    assert!(staged_warning_difference(&baseline, &["warning-a".to_owned()]).is_empty());
3880    assert_eq!(
3881      staged_warning_difference(&baseline, &["warning-a".to_owned(), "warning-a".to_owned()]),
3882      vec!["warning-a".to_owned()]
3883    );
3884    assert_eq!(
3885      staged_warning_difference(&baseline, &["warning-c".to_owned()]),
3886      vec!["warning-c".to_owned()]
3887    );
3888  }
3889
3890  #[test]
3891  fn transaction_dry_run_validates_but_keeps_original_snapshot() {
3892    let fixture = TestSnapshot::from_fixture();
3893    let original = fs::read_to_string(&fixture.path).expect("fixture should read");
3894    let operations = vec![vec!["config".to_string(), "package".to_string(), "transaction-test".to_string()]];
3895
3896    let report = run_staged_transaction_with(&fixture.path, &operations, None, true, fake_package_operation)
3897      .expect("dry-run transaction should validate");
3898
3899    assert!(report.dry_run);
3900    assert!(report.changed);
3901    assert_ne!(report.original_revision, report.new_revision);
3902    assert_eq!(fs::read_to_string(&fixture.path).expect("fixture should remain"), original);
3903  }
3904
3905  #[test]
3906  fn transaction_failure_discards_prior_staged_operations() {
3907    let fixture = TestSnapshot::from_fixture();
3908    let original = fs::read_to_string(&fixture.path).expect("fixture should read");
3909    let operations = vec![
3910      vec!["config".to_string(), "package".to_string(), "transaction-test".to_string()],
3911      vec!["config".to_string(), "package".to_string(), "transaction-test-2".to_string()],
3912    ];
3913
3914    let error = run_staged_transaction_with(&fixture.path, &operations, None, false, |path, index, args| {
3915      if index == 0 {
3916        fake_package_operation(path, index, args)
3917      } else {
3918        Err("simulated second operation failure".to_string())
3919      }
3920    })
3921    .expect_err("failed operation should abort transaction");
3922
3923    assert!(error.contains("simulated second operation failure"), "error: {error}");
3924    assert_eq!(fs::read_to_string(&fixture.path).expect("fixture should remain"), original);
3925  }
3926
3927  #[test]
3928  fn successful_transaction_replaces_snapshot_once() {
3929    let fixture = TestSnapshot::from_fixture();
3930    let operations = vec![vec!["config".to_string(), "package".to_string(), "transaction-test".to_string()]];
3931
3932    let report =
3933      run_staged_transaction_with(&fixture.path, &operations, None, false, fake_package_operation).expect("transaction should commit");
3934
3935    assert!(!report.dry_run);
3936    assert!(report.changed);
3937    assert_eq!(
3938      load_snapshot(&fixture.path.to_string_lossy())
3939        .expect("committed snapshot should load")
3940        .package,
3941      "transaction-test"
3942    );
3943    assert!(
3944      !fs::read_to_string(&fixture.path)
3945        .expect("committed snapshot should read")
3946        .contains(":version")
3947    );
3948  }
3949
3950  #[test]
3951  fn rename_rejects_mismatched_definition_key_and_declaration() {
3952    let code = list(vec![leaf("defn"), leaf("actual"), list(vec![]), leaf("nil")]);
3953    let error = rename_fixture_declaration(&code, "stored-key", "next").expect_err("mismatch should fail");
3954
3955    assert!(error.contains("does not match declaration name"), "error: {error}");
3956  }
3957
3958  #[test]
3959  fn rename_keeps_anonymous_payloads_unchanged() {
3960    let code = list(vec![leaf("fn"), list(vec![]), leaf("nil")]);
3961    let (renamed, changed) = rename_fixture_declaration(&code, "old", "next").expect("anonymous value should be movable");
3962
3963    assert!(!changed);
3964    assert_eq!(renamed, code);
3965  }
3966
3967  #[test]
3968  fn examples_require_one_quote_per_ast_node() {
3969    let error = parse_examples_input("inc 1").expect_err("bare examples should fail");
3970    assert!(error.contains("needs its own `quote`"), "error: {error}");
3971  }
3972
3973  #[test]
3974  fn examples_preserve_quoted_expressions_and_leaves() {
3975    let examples = parse_examples_input("quote $ inc 1\nquote |literal").expect("examples should parse");
3976
3977    assert_eq!(examples, vec![list(vec![leaf("inc"), leaf("1")]), leaf("|literal")]);
3978  }
3979
3980  #[test]
3981  fn named_tests_can_be_added_and_removed_without_indexing() {
3982    let fixture = TestSnapshot::from_fixture();
3983    let path = fixture.snapshot_string();
3984    let add = EditAddTestCommand {
3985      target: "app.main/test-fn".to_owned(),
3986      name: "empty-call".to_owned(),
3987      tags: Some("unit,fast".to_owned()),
3988      file: None,
3989      code: Some("quote $ assert= nil (fn)".to_owned()),
3990      input_format: SyntaxInputFormat::Auto,
3991      overwrite: false,
3992    };
3993    handle_add_test(&add, &path).expect("named test should be added");
3994    let snapshot = load_snapshot(&path).expect("edited snapshot should load");
3995    let test = &snapshot.files["app.main"].defs["test-fn"].tests[0];
3996    assert_eq!(test.name, "empty-call");
3997    assert_eq!(test.tags.len(), 2);
3998
3999    let duplicate = handle_add_test(&add, &path).expect_err("duplicate test name should fail");
4000    assert!(duplicate.contains("already exists"), "unexpected error: {duplicate}");
4001
4002    let mut replacement = add.clone();
4003    replacement.overwrite = true;
4004    replacement.code = Some("quote $ assert= true true".to_owned());
4005    handle_add_test(&replacement, &path).expect("explicit overwrite should replace named test");
4006    let snapshot = load_snapshot(&path).expect("overwritten snapshot should load");
4007    assert_ne!(snapshot.files["app.main"].defs["test-fn"].tests[0].code, test.code);
4008
4009    handle_meta(
4010      &EditMetaCommand {
4011        target: add.target,
4012        doc: None,
4013        tags: None,
4014        add_tags: Vec::new(),
4015        rm_tags: Vec::new(),
4016        clear_tags: false,
4017        examples: false,
4018        add_example: false,
4019        at: None,
4020        clear_examples: false,
4021        file: None,
4022        code: None,
4023        input_format: SyntaxInputFormat::Auto,
4024        rm_tests: vec![add.name],
4025        expect_revision: None,
4026        dry_run: false,
4027        format: "human".to_owned(),
4028      },
4029      &path,
4030    )
4031    .expect("named test should be removed");
4032    let snapshot = load_snapshot(&path).expect("edited snapshot should load");
4033    assert!(snapshot.files["app.main"].defs["test-fn"].tests.is_empty());
4034  }
4035
4036  #[test]
4037  fn schema_input_requires_quote_for_leaf_and_expression() {
4038    let expected = list(vec![leaf("::"), leaf(":ref"), leaf(":bool")]);
4039
4040    assert_eq!(
4041      parse_schema_input("quote $ :: :ref :bool", SyntaxInputFormat::Auto).expect("quoted schema should parse"),
4042      expected
4043    );
4044    assert_eq!(
4045      parse_schema_input("quote :string", SyntaxInputFormat::Auto).expect("primitive schema should parse"),
4046      leaf(":string")
4047    );
4048    let error = parse_schema_input(":: :ref :bool", SyntaxInputFormat::Auto).expect_err("bare schema should fail");
4049    assert!(error.contains("Schema examples: `quote String`"), "error: {error}");
4050  }
4051
4052  #[test]
4053  fn schema_edit_preserves_explicit_dynamic_container_arguments() {
4054    let fixture = TestSnapshot::from_fixture();
4055    let path = fixture.snapshot_string();
4056    let opts = EditSchemaCommand {
4057      target: "app.main/test-fn".to_owned(),
4058      file: None,
4059      code: Some("quote $ Fn (List Dynamic) (-> $ List Dynamic)".to_owned()),
4060      input_format: SyntaxInputFormat::Auto,
4061      clear: false,
4062      add_feature: None,
4063    };
4064
4065    handle_schema(&opts, &path).expect("explicit List<Dynamic> schema should be written");
4066    let snapshot = load_snapshot(&path).expect("edited snapshot should load");
4067    let schema = &snapshot.files["app.main"].defs["test-fn"].schema;
4068    let CalcitTypeAnnotation::Fn(signature) = schema.as_ref() else {
4069      panic!("expected Fn schema, got {schema:?}")
4070    };
4071    let explicit_list = Edn::enum_value("List", vec![Edn::Symbol(Arc::from("Dynamic"))]);
4072    assert_eq!(signature.arg_types[0].to_type_edn(), explicit_list);
4073    assert_eq!(signature.return_type.to_type_edn(), explicit_list);
4074  }
4075
4076  #[test]
4077  fn schema_edit_stores_retired_input_in_the_compact_spelling() {
4078    let fixture = TestSnapshot::from_fixture();
4079    let path = fixture.snapshot_string();
4080    let opts = EditSchemaCommand {
4081      target: "app.main/test-fn".to_owned(),
4082      file: None,
4083      code: Some("quote $ :: 'Fn $ {} (:args $ [] 'Number) (:return 'Number)".to_owned()),
4084      input_format: SyntaxInputFormat::Auto,
4085      clear: false,
4086      add_feature: None,
4087    };
4088
4089    handle_schema(&opts, &path).expect("retired schema input is still accepted");
4090    let written = fs::read_to_string(&fixture.path).expect("read snapshot");
4091    assert!(written.contains(":schema $ quote $ Fn Number (-> Number)"), "snapshot:\n{written}");
4092    assert!(!written.contains(":: 'Fn"), "snapshot:\n{written}");
4093  }
4094
4095  #[test]
4096  fn schema_add_js_ffi_feature_preserves_signature_and_rejects_unstructured_schema() {
4097    let fixture = TestSnapshot::from_fixture();
4098    let path = fixture.snapshot_string();
4099    let target = "app.main/test-fn".to_owned();
4100    let declared = EditSchemaCommand {
4101      target: target.clone(),
4102      file: None,
4103      code: Some("quote $ Fn T (-> T) (:generics T) (:features :async)".to_owned()),
4104      input_format: SyntaxInputFormat::Auto,
4105      clear: false,
4106      add_feature: None,
4107    };
4108    handle_schema(&declared, &path).expect("generic Fn schema should be accepted");
4109    let before = load_snapshot(&path).expect("original schema should load");
4110    let original = &before.files["app.main"].defs["test-fn"];
4111
4112    let feature = EditSchemaCommand {
4113      target: target.clone(),
4114      file: None,
4115      code: None,
4116      input_format: SyntaxInputFormat::Auto,
4117      clear: false,
4118      add_feature: Some("js-ffi".to_owned()),
4119    };
4120    handle_schema(&feature, &path).expect("feature should be added locally");
4121    let after = load_snapshot(&path).expect("updated schema should load");
4122    let updated = &after.files["app.main"].defs["test-fn"];
4123    let (CalcitTypeAnnotation::Fn(old_signature), CalcitTypeAnnotation::Fn(new_signature)) =
4124      (original.schema.as_ref(), updated.schema.as_ref())
4125    else {
4126      panic!("both schemas should be Fn annotations");
4127    };
4128    assert_eq!(new_signature.generics, old_signature.generics);
4129    assert_eq!(new_signature.arg_types, old_signature.arg_types);
4130    assert_eq!(new_signature.return_type, old_signature.return_type);
4131    assert_eq!(new_signature.where_bounds, old_signature.where_bounds);
4132    assert_eq!(new_signature.rest_type, old_signature.rest_type);
4133    assert!(new_signature.features.iter().any(|item| item.ref_str() == "async"));
4134    assert!(new_signature.features.iter().any(|item| item.ref_str() == "js-ffi"));
4135    assert_eq!(updated.code, original.code);
4136    assert_eq!(updated.doc, original.doc);
4137    assert_eq!(updated.examples, original.examples);
4138    assert_eq!(updated.tests, original.tests);
4139    assert_eq!(updated.tags, original.tags);
4140    assert_eq!(updated.ffi, original.ffi);
4141
4142    let erased_cache = EditSchemaCommand {
4143      add_feature: Some("erased-cache".to_owned()),
4144      ..feature.clone()
4145    };
4146    handle_schema(&erased_cache, &path).expect("erased-cache feature should be added locally");
4147    let after_cache = load_snapshot(&path).expect("updated schema should load");
4148    let CalcitTypeAnnotation::Fn(cache_signature) = after_cache.files["app.main"].defs["test-fn"].schema.as_ref() else {
4149      panic!("schema should stay an Fn annotation");
4150    };
4151    assert!(cache_signature.features.iter().any(|item| item.ref_str() == "erased-cache"));
4152    assert!(cache_signature.features.iter().any(|item| item.ref_str() == "js-ffi"));
4153    let unsupported = EditSchemaCommand {
4154      add_feature: Some("host-io".to_owned()),
4155      ..erased_cache
4156    };
4157    assert!(
4158      handle_schema(&unsupported, &path)
4159        .unwrap_err()
4160        .contains("Unsupported schema feature")
4161    );
4162
4163    let clear = EditSchemaCommand {
4164      target,
4165      clear: true,
4166      add_feature: None,
4167      ..feature.clone()
4168    };
4169    handle_schema(&clear, &path).expect("schema should clear");
4170    let error = handle_schema(&feature, &path).expect_err("dynamic schema must not gain a lexical capability");
4171    assert!(error.contains("needs a structured Fn schema"), "error: {error}");
4172    assert!(error.contains("`calcit edit ffi` changes export metadata"), "error: {error}");
4173  }
4174
4175  #[test]
4176  fn schema_edit_tag_value_survives_canonical_snapshot_formatting() {
4177    let fixture = TestSnapshot::from_fixture();
4178    let path = fixture.snapshot_string();
4179    let opts = EditSchemaCommand {
4180      target: "app.main/test-fn".to_owned(),
4181      file: None,
4182      code: Some("quote 'Tag".to_owned()),
4183      input_format: SyntaxInputFormat::Auto,
4184      clear: false,
4185      add_feature: None,
4186    };
4187
4188    handle_schema(&opts, &path).expect("Tag value schema should be written");
4189    let snapshot = load_snapshot(&path).expect("edited snapshot should load");
4190    assert!(matches!(
4191      snapshot.files["app.main"].defs["test-fn"].schema.as_ref(),
4192      CalcitTypeAnnotation::Tag
4193    ));
4194
4195    handle_format(
4196      &EditFormatCommand {
4197        drop_legacy_entry_fields: vec![],
4198      },
4199      &path,
4200    )
4201    .expect("edit format should preserve the Tag schema");
4202    let formatted = load_snapshot(&path).expect("canonically formatted snapshot should reload");
4203    assert!(matches!(
4204      formatted.files["app.main"].defs["test-fn"].schema.as_ref(),
4205      CalcitTypeAnnotation::Tag
4206    ));
4207  }
4208
4209  #[test]
4210  fn schema_edit_preserves_unrelated_legacy_schema_serialization() {
4211    let fixture = TestSnapshot::from_fixture();
4212    let source = r#"#! /usr/bin/env calcit
4213{} (:package |demo) (:version |0.0.1)
4214  :entries $ {}
4215    :default $ {} (:description |) (:init-fn 'app.main/target) (:mode :native) (:reload-fn 'app.main/target)
4216      :modules $ []
4217      :type-slots $ {}
4218  :files $ {}
4219    |app.main $ %{} :FileEntry
4220      :defs $ {}
4221        |legacy $ %{} :CodeEntry
4222          :code $ quote $ defn legacy (x) x
4223          :schema $ quote $ Fn (JsNullish String) (-> Dynamic)
4224        |target $ %{} :CodeEntry
4225          :code $ quote $ defn target () nil
4226          :schema $ quote Dynamic
4227      :ns $ %{} :CodeEntry (:code $ quote $ ns app.main)
4228"#;
4229    fs::write(&fixture.path, source).expect("write snapshot");
4230    let before = cirru_edn::parse(source.strip_prefix("#! /usr/bin/env calcit\n").expect("shebang")).expect("parse source");
4231    let schema = calcit_core::snapshot::parse_schema_annotation_for_write(&leaf(":string")).expect("parse schema");
4232
4233    save_schema_preserving_snapshot(&fixture.snapshot_string(), "app.main", "target", Some(schema.as_ref()))
4234      .expect("save target schema");
4235
4236    let output = fs::read_to_string(&fixture.path).expect("read snapshot");
4237    assert!(output.starts_with("#! /usr/bin/env calcit\n"));
4238    let after = cirru_edn::parse(output.strip_prefix("#! /usr/bin/env calcit\n").expect("shebang")).expect("parse output");
4239    let schema_for = |snapshot: &cirru_edn::Edn, definition_name: &str| {
4240      let cirru_edn::Edn::Map(root) = snapshot else { panic!("root") };
4241      let cirru_edn::Edn::Map(files) = root.get_or_nil("files") else {
4242        panic!("files")
4243      };
4244      let cirru_edn::Edn::Struct(file) = files.get_or_nil("app.main") else {
4245        panic!("namespace")
4246      };
4247      let cirru_edn::Edn::Map(defs) = file["defs"].clone() else {
4248        panic!("defs")
4249      };
4250      let cirru_edn::Edn::Struct(definition) = defs.get_or_nil(definition_name) else {
4251        panic!("definition")
4252      };
4253      definition
4254        .pairs
4255        .iter()
4256        .find(|(key, _)| key.ref_str() == "schema")
4257        .map(|(_, value)| value.clone())
4258    };
4259
4260    assert_eq!(schema_for(&before, "legacy"), schema_for(&after, "legacy"));
4261    assert_ne!(schema_for(&before, "target"), schema_for(&after, "target"));
4262
4263    save_schema_preserving_snapshot(&fixture.snapshot_string(), "app.main", "target", None).expect("clear target schema");
4264    let cleared_text = fs::read_to_string(&fixture.path).expect("read cleared snapshot");
4265    let cleared = cirru_edn::parse(cleared_text.strip_prefix("#! /usr/bin/env calcit\n").expect("shebang")).expect("parse cleared");
4266    assert_eq!(schema_for(&before, "legacy"), schema_for(&cleared, "legacy"));
4267    assert_eq!(schema_for(&cleared, "target"), None);
4268  }
4269
4270  #[test]
4271  fn bumps_patch_version() {
4272    assert_eq!(bump_semver_value("0.0.0", "patch"), Ok("0.0.1".to_string()));
4273  }
4274
4275  #[test]
4276  fn bumps_minor_version() {
4277    assert_eq!(bump_semver_value("1.2.3", "minor"), Ok("1.3.0".to_string()));
4278  }
4279
4280  #[test]
4281  fn bumps_major_version() {
4282    assert_eq!(bump_semver_value("1.2.3", "major"), Ok("2.0.0".to_string()));
4283  }
4284
4285  #[test]
4286  fn rejects_unknown_bump_level() {
4287    assert_eq!(
4288      bump_semver_value("1.2.3", "build"),
4289      Err("Unknown bump level 'build'. Valid levels: patch, minor, major".to_string())
4290    );
4291  }
4292
4293  #[test]
4294  fn clears_prerelease_and_build_metadata_when_bumping() {
4295    assert_eq!(bump_semver_value("1.2.3-alpha.1+build.2", "patch"), Ok("1.2.4".to_string()));
4296  }
4297}