Skip to main content

calcit_cli/cli_handlers/
tree.rs

1use cirru_parser::Cirru;
2use colored::Colorize;
3use std::fmt::Write as _;
4
5use super::chunk_display::{ChunkDisplayOptions, ChunkedDisplay, fragment_nesting_level, maybe_chunk_node};
6use super::common::{
7  ERR_CODE_INPUT_REQUIRED, cirru_to_json_value, decode_mutation_syntax_input, emit_cli_output, format_path,
8  guard_snapshot_mutation_toolchain, markdown_cirru_section, markdown_fenced_block, parse_input_to_cirru, parse_path,
9  print_cli_warning_block, read_code_input, resolve_definition_lookup, shell_quote,
10};
11use super::cursor::{
12  maintain_cursor_after_tree_mutation, resolve_active_cursor_reference, resolve_cursor_path_argument, resolve_cursor_target_argument,
13};
14use super::structured_output::StructuredOutputFormat;
15use super::tips::{TipPriority, Tips, command_guidance_enabled, tip_prefer_oneliner_json_markdown, tip_root_edit};
16use crate::cli_args::SyntaxInputFormat;
17use crate::cli_args::{
18  TreeCommand, TreeDeleteCommand, TreeInsertCommand, TreeRaiseCommand, TreeReplaceCommand, TreeReplaceLeafCommand,
19  TreeSearchReplaceCommand, TreeShowCommand, TreeStructuralCommand, TreeSubcommand, TreeSwapCommand, TreeUnwrapCommand,
20  TreeWrapCommand,
21};
22
23// Import shared functions from edit module
24use super::edit::{
25  apply_operation_at_path, check_ns_editable, load_snapshot, navigate_to_path, parse_target, process_node_with_references,
26  save_snapshot,
27};
28use super::query::resolve_path_expression;
29use super::tree_mutation::{TreeCursorMutation, TreeOperation};
30
31/// Validate the changed root without blocking repairs to unrelated old source.
32fn save_definition_tree(
33  snapshot: &calcit_core::snapshot::Snapshot,
34  snapshot_file: &str,
35  namespace: &str,
36  definition: &str,
37) -> Result<(), String> {
38  let entry = snapshot
39    .files
40    .get(namespace)
41    .and_then(|file| file.defs.get(definition))
42    .ok_or_else(|| format!("Definition '{namespace}/{definition}' not found"))?;
43  calcit_core::snapshot::validate_definition_root(&entry.code, &format!("{namespace}/{definition}"))?;
44  save_snapshot(snapshot, snapshot_file)
45}
46
47// ═══════════════════════════════════════════════════════════════════════════════
48// Helper functions
49// ═══════════════════════════════════════════════════════════════════════════════
50
51/// Main handler for code command
52pub fn handle_tree_command(cmd: &TreeCommand, snapshot_file: &str) -> Result<(), String> {
53  // Reject an unknown `--at` / `--with` value before any file is touched.
54  match &cmd.subcommand {
55    TreeSubcommand::Insert(opts) => {
56      insert_operation(&opts.at)?;
57    }
58    TreeSubcommand::Swap(opts) => {
59      swap_operation(&opts.with)?;
60    }
61    _ => {}
62  }
63  let _writer = if !matches!(&cmd.subcommand, TreeSubcommand::Show(_)) {
64    Some(calcit_core::util::atomic_write::SnapshotWriteGuard::acquire(snapshot_file)?)
65  } else {
66    None
67  };
68  if !matches!(&cmd.subcommand, TreeSubcommand::Show(_)) {
69    guard_snapshot_mutation_toolchain(snapshot_file)?;
70  }
71  let mut resolved = cmd.clone();
72  resolve_tree_cursor_references(&mut resolved, snapshot_file)?;
73  let cursor_mutation = prepare_cursor_mutation(&resolved, snapshot_file)?;
74
75  let result = match &resolved.subcommand {
76    TreeSubcommand::Show(opts) => handle_show(opts, snapshot_file),
77    TreeSubcommand::Replace(opts) => handle_replace(opts, snapshot_file),
78    TreeSubcommand::ReplaceLeaf(opts) => handle_replace_leaf(opts, snapshot_file),
79    TreeSubcommand::Delete(opts) => handle_delete(opts, snapshot_file),
80    TreeSubcommand::Insert(opts) => handle_insert(opts, snapshot_file),
81    TreeSubcommand::Swap(opts) => handle_swap(opts, snapshot_file),
82    TreeSubcommand::Unwrap(opts) => handle_unwrap(opts, snapshot_file),
83    TreeSubcommand::Raise(opts) => handle_raise(opts, snapshot_file),
84    TreeSubcommand::Wrap(opts) => handle_wrap(opts, snapshot_file),
85    TreeSubcommand::SearchReplace(opts) => handle_search_replace(opts, snapshot_file),
86    TreeSubcommand::Rewrite(opts) => handle_rewrite(opts, snapshot_file),
87  };
88
89  if let Err(error) = result {
90    if error.starts_with("# Error:") {
91      eprintln!("{error}");
92      return Err("Tree mutation rejected; details were written to stderr.".to_owned());
93    }
94    return Err(error);
95  }
96  if let Some((target, mutation)) = cursor_mutation {
97    maintain_cursor_after_tree_mutation(snapshot_file, &target, &mutation)?;
98  }
99  Ok(())
100}
101
102fn verify_expected_node(actual: &Cirru, expected_input: Option<&str>, path: &[usize]) -> Result<(), String> {
103  let Some(expected_input) = expected_input else {
104    return Ok(());
105  };
106  let expected = parse_input_to_cirru(expected_input).map_err(|error| format!("Invalid --expect value: {error}"))?;
107  if actual == &expected {
108    return Ok(());
109  }
110  Err(format!(
111    "# Error: node guard failed\n\n- path: `{}`\n- changed: `false`\n\n{}\n{}\nNo changes were written. Re-run `calcit tree show ... --path {}` and update `--expect` or the path.",
112    format_path(path),
113    markdown_cirru_section(2, "Expected", &expected, 6)?,
114    markdown_cirru_section(2, "Actual", actual, 6)?,
115    format_path(path),
116  ))
117}
118
119fn resolve_tree_cursor_references(cmd: &mut TreeCommand, snapshot_file: &str) -> Result<(), String> {
120  let target = match &mut cmd.subcommand {
121    TreeSubcommand::Show(opts) => &mut opts.target,
122    TreeSubcommand::Replace(opts) => &mut opts.target,
123    TreeSubcommand::ReplaceLeaf(opts) => &mut opts.target,
124    TreeSubcommand::Delete(opts) => &mut opts.target,
125    TreeSubcommand::Insert(opts) => &mut opts.target,
126    TreeSubcommand::Swap(opts) => &mut opts.target,
127    TreeSubcommand::Unwrap(opts) => &mut opts.target,
128    TreeSubcommand::Raise(opts) => &mut opts.target,
129    TreeSubcommand::Wrap(opts) => &mut opts.target,
130    TreeSubcommand::SearchReplace(opts) => &mut opts.target,
131    TreeSubcommand::Rewrite(opts) => &mut opts.target,
132  };
133  let active_reference = if target == "@cursor" {
134    Some(resolve_active_cursor_reference(snapshot_file)?)
135  } else {
136    None
137  };
138  *target = match &active_reference {
139    Some((active_target, _)) => active_target.clone(),
140    None => resolve_cursor_target_argument(snapshot_file, target)?,
141  };
142
143  let resolve = |target: &str, path: &mut String| -> Result<(), String> {
144    *path = if path == "@cursor"
145      && let Some((active_target, active_path)) = &active_reference
146    {
147      if active_target != target {
148        return Err(format!(
149          "Cursor target mismatch: cursor points to '{active_target}', but command targets '{target}'."
150        ));
151      }
152      active_path.clone()
153    } else {
154      resolve_cursor_path_argument(snapshot_file, target, path)?
155    };
156    Ok(())
157  };
158
159  match &mut cmd.subcommand {
160    TreeSubcommand::Show(opts) => {
161      if let Some(path) = &mut opts.path {
162        resolve(&opts.target, path)?;
163      }
164    }
165    TreeSubcommand::Replace(opts) => resolve(&opts.target, &mut opts.path)?,
166    TreeSubcommand::ReplaceLeaf(_) | TreeSubcommand::SearchReplace(_) => {}
167    TreeSubcommand::Delete(opts) => resolve(&opts.target, &mut opts.path)?,
168    TreeSubcommand::Insert(opts) => resolve(&opts.target, &mut opts.path)?,
169    TreeSubcommand::Swap(opts) => resolve(&opts.target, &mut opts.path)?,
170    TreeSubcommand::Unwrap(opts) => resolve(&opts.target, &mut opts.path)?,
171    TreeSubcommand::Raise(opts) => resolve(&opts.target, &mut opts.path)?,
172    TreeSubcommand::Wrap(opts) => resolve(&opts.target, &mut opts.path)?,
173    TreeSubcommand::Rewrite(opts) => resolve(&opts.target, &mut opts.path)?,
174  }
175  Ok(())
176}
177
178fn prepare_cursor_mutation(cmd: &TreeCommand, snapshot_file: &str) -> Result<Option<(String, TreeCursorMutation)>, String> {
179  let prepared = match &cmd.subcommand {
180    TreeSubcommand::Show(_) => return Ok(None),
181    TreeSubcommand::Replace(opts) => (
182      opts.target.clone(),
183      TreeCursorMutation::Replace {
184        path: parse_path(&opts.path)?,
185      },
186    ),
187    TreeSubcommand::ReplaceLeaf(opts) => (opts.target.clone(), TreeCursorMutation::NoPathShift),
188    TreeSubcommand::Delete(opts) => (
189      opts.target.clone(),
190      TreeCursorMutation::Delete {
191        path: parse_path(&opts.path)?,
192      },
193    ),
194    TreeSubcommand::Insert(opts) => {
195      let path = parse_path(&opts.path)?;
196      let mutation = match insert_operation(&opts.at)? {
197        TreeOperation::InsertBefore => TreeCursorMutation::InsertBefore { path },
198        TreeOperation::InsertAfter => TreeCursorMutation::InsertAfter { path },
199        TreeOperation::InsertChild => TreeCursorMutation::InsertChild { path },
200        _ => TreeCursorMutation::NoPathShift,
201      };
202      (opts.target.clone(), mutation)
203    }
204    TreeSubcommand::Swap(opts) => {
205      let path = parse_path(&opts.path)?;
206      let mutation = match swap_operation(&opts.with)? {
207        TreeOperation::SwapNextSibling => TreeCursorMutation::SwapNext { path },
208        _ => TreeCursorMutation::SwapPrev { path },
209      };
210      (opts.target.clone(), mutation)
211    }
212    TreeSubcommand::Unwrap(opts) => {
213      let path = parse_path(&opts.path)?;
214      let (namespace, definition) = parse_target(&opts.target)?;
215      let snapshot = load_snapshot(snapshot_file)?;
216      let entry = snapshot
217        .files
218        .get(namespace)
219        .and_then(|file| file.defs.get(definition))
220        .ok_or_else(|| format!("Definition '{}' not found", opts.target))?;
221      let child_count = match navigate_to_path(&entry.code, &path)? {
222        Cirru::List(children) => children.len(),
223        Cirru::Leaf(_) => 0,
224      };
225      (opts.target.clone(), TreeCursorMutation::Unwrap { path, child_count })
226    }
227    TreeSubcommand::Raise(opts) => (
228      opts.target.clone(),
229      TreeCursorMutation::Raise {
230        path: parse_path(&opts.path)?,
231      },
232    ),
233    TreeSubcommand::Wrap(opts) => (
234      opts.target.clone(),
235      TreeCursorMutation::Wrap {
236        path: parse_path(&opts.path)?,
237      },
238    ),
239    TreeSubcommand::SearchReplace(opts) => (opts.target.clone(), TreeCursorMutation::NoPathShift),
240    TreeSubcommand::Rewrite(opts) => (
241      opts.target.clone(),
242      TreeCursorMutation::Replace {
243        path: parse_path(&opts.path)?,
244      },
245    ),
246  };
247  Ok(Some(prepared))
248}
249
250fn parse_with_references(with_strs: &[String], original_node: &Cirru) -> Result<std::collections::BTreeMap<String, Cirru>, String> {
251  let mut references = std::collections::BTreeMap::new();
252
253  for s in with_strs {
254    let (name, path_str) = s
255      .split_once('=')
256      .ok_or_else(|| format!("Invalid --with format '{s}'. Expected 'name=path', e.g. --with self=. --with arg=1,0"))?;
257
258    if name.trim().is_empty() {
259      return Err(format!("Invalid --with format '{s}': name cannot be empty"));
260    }
261
262    let path = if path_str.trim() == "." {
263      vec![]
264    } else {
265      parse_path(path_str.trim())?
266    };
267
268    let node = navigate_to_path(original_node, &path)?;
269    references.insert(name.trim().to_string(), node);
270  }
271
272  Ok(references)
273}
274
275/// Format a Cirru node for preview display
276fn format_preview(node: &Cirru, max_lines: usize) -> String {
277  let formatted = match node {
278    Cirru::Leaf(s) => {
279      // For leaf nodes, just show the value
280      format!("  {:?}", s.as_ref())
281    }
282    Cirru::List(_) => {
283      // For list nodes, use the Cirru formatter
284      match cirru_parser::format(std::slice::from_ref(node), cirru_parser::CirruWriterOptions { use_inline: false }) {
285        Ok(cirru_str) => {
286          let lines: Vec<&str> = cirru_str.lines().collect();
287          if lines.len() > max_lines {
288            let mut result = String::new();
289            for line in lines.iter().take(max_lines) {
290              result.push_str("  ");
291              result.push_str(line);
292              result.push('\n');
293            }
294            result.push_str(&format!("  {}\n", format!("... ({} more lines)", lines.len() - max_lines).dimmed()));
295            result
296          } else {
297            lines.iter().map(|line| format!("  {line}\n")).collect()
298          }
299        }
300        Err(e) => format!("  {}\n", format!("(failed to format: {e})").red()),
301      }
302    }
303  };
304  formatted.trim_end().to_string()
305}
306
307fn print_preview_block(label: &str, node: &Cirru, max_lines: usize, _color: &str) {
308  match markdown_cirru_section(2, label, node, max_lines) {
309    Ok(section) => println!("{section}"),
310    Err(error) => println!("## {label}\n\n_Unable to render preview: {error}_"),
311  }
312}
313
314/// Find the first leaf (preorder) and format for preview
315fn first_leaf_preview(node: &Cirru) -> Option<String> {
316  match node {
317    Cirru::Leaf(s) => Some(format!("{:?}", s.as_ref())),
318    Cirru::List(items) => items.iter().find_map(first_leaf_preview),
319  }
320}
321
322/// Format a child node for list preview (leaf or list with first leaf)
323fn format_child_preview(node: &Cirru) -> String {
324  match node {
325    Cirru::Leaf(s) => format!("{:?}", s.as_ref()),
326    Cirru::List(items) => {
327      if items.is_empty() {
328        "(empty)".to_string()
329      } else {
330        let head = first_leaf_preview(node).unwrap_or_else(|| "<expr>".to_string());
331        format!("({head} ...)")
332      }
333    }
334  }
335}
336
337/// Single-line Cirru text for a node, or `None` when it needs several lines.
338fn inline_cirru(node: &Cirru) -> Option<String> {
339  let text = match node {
340    Cirru::Leaf(leaf) => cirru_parser::generate_leaf(leaf),
341    Cirru::List(_) => cirru_parser::format_expr_one_liner(node).ok()?,
342  };
343  (!text.contains('\n') && text.len() <= 100).then_some(text)
344}
345
346/// Show the change: operation, location, and before/after nodes. Short nodes stay
347/// on one line; larger nodes keep fenced Before/After sections.
348fn show_diff_preview(old_node: &Cirru, new_node: &Cirru, operation: &str, path: &[usize]) -> String {
349  let mut output = String::new();
350  let location = if path.is_empty() { "root".to_owned() } else { format_path(path) };
351  let _ = writeln!(
352    &mut output,
353    "# Tree mutation `{operation}` at `{location}`
354"
355  );
356  if let (Some(before), Some(after)) = (inline_cirru(old_node), inline_cirru(new_node)) {
357    let _ = writeln!(&mut output, "- before: `{before}`");
358    let _ = writeln!(&mut output, "- after: `{after}`");
359    return output;
360  }
361  match markdown_cirru_section(2, "Before", old_node, 10) {
362    Ok(section) => output.push_str(&section),
363    Err(error) => output.push_str(&format!("## Before\n\n_Unable to render preview: {error}_\n")),
364  }
365  output.push('\n');
366  match markdown_cirru_section(2, "After", new_node, 10) {
367    Ok(section) => output.push_str(&section),
368    Err(error) => output.push_str(&format!("## After\n\n_Unable to render preview: {error}_\n")),
369  }
370
371  output
372}
373
374fn render_chunked_display(display: &ChunkedDisplay, chunk_expand_depth: usize) -> (String, usize) {
375  let mut out = String::new();
376  let _ = writeln!(&mut out, "## Chunked preview\n");
377  let _ = writeln!(
378    &mut out,
379    "nodes: {}, branches: {}, leaves: {}, max depth: {}, fragments: {}",
380    display.total.nodes,
381    display.total.branches,
382    display.total.leaves,
383    display.total.max_depth,
384    display.fragments.len()
385  );
386  let _ = writeln!(&mut out);
387
388  let visible_fragments: Vec<_> = display
389    .fragments
390    .iter()
391    .filter(|fragment| fragment_nesting_level(fragment, &display.fragments) <= chunk_expand_depth)
392    .collect();
393
394  if visible_fragments.len() < display.fragments.len() {
395    let _ = writeln!(
396      &mut out,
397      "showing {}/{} fragments; nested chunks beyond level {} are hidden",
398      visible_fragments.len(),
399      display.fragments.len(),
400      chunk_expand_depth
401    );
402    let _ = writeln!(&mut out);
403  }
404
405  for fragment in &visible_fragments {
406    let _ = writeln!(&mut out, "### Fragment `{}`\n", fragment.id);
407    let _ = writeln!(
408      &mut out,
409      "- Coordinate: `{}`\n- Nodes: {}\n- Max depth: {}\n",
410      fragment.coord, fragment.nodes, fragment.depth
411    );
412    out.push_str(&markdown_fenced_block("cirru", &fragment.cirru));
413    let _ = writeln!(&mut out);
414  }
415
416  (out, visible_fragments.len())
417}
418
419/// Recursively annotate each list node with its path index as a trailing comment.
420/// Appends `; "previous node path: X.Y.Z"` as the last child of each list.
421fn annotate_paths(node: &mut Cirru, current_path: &[usize], annotate_root: bool) {
422  if let Cirru::List(children) = node {
423    // Recurse into children first, tracking their paths
424    for (i, child) in children.iter_mut().enumerate() {
425      let mut child_path = current_path.to_vec();
426      child_path.push(i);
427      annotate_paths(child, &child_path, true);
428    }
429    // Append path comment at the end (skip root if annotate_root is false)
430    if annotate_root && !current_path.is_empty() {
431      let path_str = format_path(current_path);
432      let comment = Cirru::List(vec![
433        Cirru::Leaf(";".into()),
434        Cirru::Leaf(format!("previous node path: {path_str}").into()),
435      ]);
436      children.push(comment);
437    }
438  }
439}
440
441// ============================================================================
442// Command handlers
443// ============================================================================
444
445fn handle_show(opts: &TreeShowCommand, snapshot_file: &str) -> Result<(), String> {
446  let output_format = StructuredOutputFormat::parse(&opts.format, "tree show")?;
447  let (namespace, definition) = parse_target(&opts.target)?;
448  let path = match &opts.path {
449    Some(p) => parse_path(p)?,
450    None => {
451      eprintln!(
452        "{}",
453        "[Warn] No --path specified; showing from root. Use --path '0' to start from a child node.".yellow()
454      );
455      vec![]
456    }
457  };
458
459  let snapshot = load_snapshot(snapshot_file)?;
460
461  let file_data = snapshot
462    .files
463    .get(namespace)
464    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
465
466  let lookup = resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), true)?;
467  let render_to_stderr = lookup.warning.is_some();
468  if let Some(warning) = lookup.warning.as_deref() {
469    print_cli_warning_block(warning);
470  }
471  let resolved_definition = lookup.resolved;
472  let resolved_target = format!("{namespace}/{resolved_definition}");
473
474  let code_entry = file_data
475    .defs
476    .get(resolved_definition.as_str())
477    .expect("resolved definition exists");
478
479  // Try to navigate to path, provide enhanced error message on failure
480  let mut node = match navigate_to_path(&code_entry.code, &path) {
481    Ok(n) => n,
482    Err(original_error) => {
483      // Find the longest valid path
484      let mut valid_depth = 0;
485      let mut current = &code_entry.code;
486
487      for (depth, &idx) in path.iter().enumerate() {
488        match current {
489          Cirru::Leaf(_) => {
490            valid_depth = depth;
491            break;
492          }
493          Cirru::List(items) => {
494            if idx >= items.len() {
495              valid_depth = depth;
496              break;
497            }
498            current = &items[idx];
499            valid_depth = depth + 1;
500          }
501        }
502      }
503
504      // Get the node at the longest valid path
505      let valid_path = &path[..valid_depth];
506      let valid_node = navigate_to_path(&code_entry.code, valid_path).unwrap();
507
508      // Format the valid path display
509      let valid_path_display = format_path(valid_path);
510
511      let node_preview = format_preview(&valid_node, 6);
512      let node_kind = match &valid_node {
513        Cirru::Leaf(_) => "leaf".to_owned(),
514        Cirru::List(items) => format!("list, {} items", items.len()),
515      };
516
517      // Print enhanced error message
518      eprintln!("# Error: invalid path\n\n{original_error}\n");
519      eprintln!("- Longest valid path: `{valid_path_display}`");
520      eprintln!("- Node kind: `{node_kind}`\n");
521      eprintln!("## Node at longest valid path\n");
522      eprint!("{}", markdown_fenced_block("cirru", &node_preview));
523
524      // Show next steps based on node type
525      match &valid_node {
526        Cirru::Leaf(_) => {
527          eprintln!("\nThis is a leaf node and cannot be navigated further.\n");
528          eprintln!(
529            "- View it with: `calcit tree show '{}' --path '{}'`",
530            resolved_target,
531            format_path(valid_path)
532          );
533        }
534        Cirru::List(items) => {
535          eprintln!(
536            "\nThis node has {} children (indices 0–{}).\n",
537            items.len(),
538            items.len().saturating_sub(1)
539          );
540          eprintln!(
541            "- View it with: `calcit tree show '{}' --path '{}'`",
542            resolved_target,
543            format_path(valid_path)
544          );
545
546          // Show first few children as hints
547          if !items.is_empty() {
548            eprintln!();
549            eprintln!("## First children\n");
550            for (i, item) in items.iter().enumerate().take(3) {
551              let child_preview = format_child_preview(item);
552              let child_path = if valid_path.is_empty() {
553                i.to_string()
554              } else {
555                format!("{}.{}", format_path(valid_path), i)
556              };
557              eprintln!("- [{i}] `{child_preview}` → `--path '{child_path}'`");
558            }
559            if items.len() > 3 {
560              eprintln!("- _... and {} more._", items.len() - 3);
561            }
562          }
563        }
564      }
565
566      return Err(String::new()); // Empty error since we already printed detailed message
567    }
568  };
569
570  // Apply path annotations if requested
571  if opts.path_annotations {
572    annotate_paths(&mut node, &path, !path.is_empty());
573  }
574
575  if output_format != StructuredOutputFormat::Human {
576    let tree = cirru_to_json_value(&node);
577    return output_format.print_value(&serde_json::json!({
578      "schema_version": 1,
579      "command": "tree.show",
580      "target": resolved_target,
581      "path": format_path(&path),
582      "type": if matches!(node, Cirru::Leaf(_)) { "leaf" } else { "list" },
583      "tree": tree,
584    }));
585  }
586
587  let node_type = match &node {
588    Cirru::Leaf(_) => "leaf",
589    Cirru::List(items) => {
590      let chunk_options = ChunkDisplayOptions {
591        trigger_nodes: opts.chunk_trigger_nodes,
592        target_nodes: opts.chunk_target_nodes,
593        max_nodes: opts.chunk_max_nodes,
594        max_branches: 64,
595      };
596      let chunked_display = if opts.raw { None } else { maybe_chunk_node(&node, &chunk_options)? };
597
598      let mut out = String::new();
599      let _ = writeln!(&mut out, "# Tree node `{resolved_target}`\n");
600      let _ = writeln!(&mut out, "- Path: `{}`", format_path(&path));
601      let _ = writeln!(&mut out, "- Type: `list`");
602      let _ = writeln!(&mut out, "- Items: {}\n", items.len());
603      let shown_fragments = if let Some(display) = chunked_display {
604        let (chunked, shown) = render_chunked_display(&display, opts.chunk_expand_depth);
605        out.push_str(&chunked);
606        Some((shown, display.fragments.len()))
607      } else {
608        let _ = writeln!(&mut out, "## Cirru preview\n");
609        let cirru_str = cirru_parser::format(std::slice::from_ref(&node), cirru_parser::CirruWriterOptions { use_inline: true })
610          .map_err(|e| format!("Failed to format Cirru: {e}"))?;
611        out.push_str(&markdown_fenced_block("cirru", &cirru_str));
612        let _ = writeln!(&mut out);
613        None
614      };
615
616      let mut tips = Tips::new();
617      // Tip: suggest path-annotations for nodes with many children
618      if items.len() > 8 && !opts.path_annotations {
619        tips.add_with_priority(
620          TipPriority::High,
621          format!(
622            "This node has {} children. Use `--path-annotations` to annotate each nested list with its path index for easier editing.",
623            items.len()
624          ),
625        );
626      }
627      if let Some((shown_fragments, total_fragments)) = shown_fragments
628        && shown_fragments < total_fragments
629      {
630        tips.add_with_priority(
631          TipPriority::High,
632          format!(
633            "Showing ROOT plus {} chunk layer(s). Use `--chunk-expand-depth {}` to reveal deeper nested fragments, or `--raw` to disable chunking.",
634            opts.chunk_expand_depth,
635            opts.chunk_expand_depth + 1
636          ),
637        );
638      }
639      tips.append(tip_prefer_oneliner_json_markdown());
640      emit_cli_output(&out, render_to_stderr);
641      tips.print_markdown(render_to_stderr);
642
643      return Ok(());
644    }
645  };
646
647  if matches!(node_type, "leaf") {
648    let mut out = String::new();
649    let _ = writeln!(&mut out, "# Tree node `{resolved_target}`\n");
650    let _ = writeln!(&mut out, "- Path: `{}`", format_path(&path));
651    let _ = writeln!(&mut out, "- Type: `leaf`\n");
652    if let Cirru::Leaf(s) = &node {
653      let _ = writeln!(&mut out, "## Value\n");
654      out.push_str(&markdown_fenced_block("cirru", s.as_ref()));
655      let _ = writeln!(&mut out);
656      if command_guidance_enabled() {
657        let _ = writeln!(
658          &mut out,
659          "{}: Use {} for symbols, {} for strings",
660          "Tip".blue().bold(),
661          "-e 'symbol'".yellow(),
662          "-e '|text'".yellow()
663        );
664      }
665    }
666    emit_cli_output(&out, render_to_stderr);
667  }
668
669  Ok(())
670}
671
672fn handle_replace(opts: &TreeReplaceCommand, snapshot_file: &str) -> Result<(), String> {
673  let (namespace, definition) = parse_target(&opts.target)?;
674  let path = parse_path(&opts.path)?;
675
676  let code_input = read_code_input(&opts.file, &opts.code)?;
677
678  let raw = code_input.as_deref().ok_or(ERR_CODE_INPUT_REQUIRED)?;
679
680  let new_node = decode_mutation_syntax_input(raw, opts.input_format)?;
681
682  let mut snapshot = load_snapshot(snapshot_file)?;
683  check_ns_editable(&snapshot, namespace)?;
684
685  let file_data = snapshot
686    .files
687    .get_mut(namespace)
688    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
689
690  let code_entry = file_data
691    .defs
692    .get_mut(definition)
693    .ok_or_else(|| format!("Definition '{definition}' not found"))?;
694
695  // Save original for comparison
696  let old_node = navigate_to_path(&code_entry.code, &path)?;
697  verify_expected_node(&old_node, opts.expect.as_deref(), &path)?;
698  // Tips: root-edit guidance
699  if let Some(t) = tip_root_edit(path.is_empty()) {
700    let mut tips = Tips::new();
701    tips.add_with_priority(TipPriority::High, t);
702    tips.print();
703  }
704
705  let new_code = apply_operation_at_path(&code_entry.code, &path, TreeOperation::Replace, Some(&new_node))?;
706  code_entry.code = new_code.clone();
707
708  save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
709
710  let replaced_node = navigate_to_path(&new_code, &path)?;
711
712  println!("# Tree mutation\n");
713  println!("- operation: `replace`");
714  println!("- target: `{}`", opts.target);
715  println!("- path: `{}`", format_path(&path));
716  println!("- changed: `true`\n");
717  print_preview_block("Before", &old_node, opts.depth, "yellow");
718  println!();
719  print_preview_block("After", &replaced_node, opts.depth, "green");
720
721  if !path.is_empty() {
722    let parent_path = &path[..path.len() - 1];
723    let parent_after = if parent_path.is_empty() {
724      new_code
725    } else {
726      navigate_to_path(&new_code, parent_path)?
727    };
728    println!();
729    print_preview_block("Containing expression after", &parent_after, opts.depth, "cyan");
730  }
731
732  Ok(())
733}
734
735fn handle_rewrite(opts: &TreeStructuralCommand, snapshot_file: &str) -> Result<(), String> {
736  if opts.with.is_empty() {
737    return Err("`tree rewrite` needs at least one `--with name=path`; for plain replacement use `tree replace`.".to_string());
738  }
739
740  let (namespace, definition) = parse_target(&opts.target)?;
741  let path = parse_path(&opts.path)?;
742
743  let code_input = read_code_input(&opts.file, &opts.code)?;
744
745  let raw = code_input.as_deref().ok_or(ERR_CODE_INPUT_REQUIRED)?;
746
747  let new_node = decode_mutation_syntax_input(raw, opts.input_format)?;
748
749  let mut snapshot = load_snapshot(snapshot_file)?;
750  check_ns_editable(&snapshot, namespace)?;
751
752  let file_data = snapshot
753    .files
754    .get_mut(namespace)
755    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
756
757  let code_entry = file_data
758    .defs
759    .get_mut(definition)
760    .ok_or_else(|| format!("Definition '{definition}' not found"))?;
761
762  let original_node = navigate_to_path(&code_entry.code, &path)?;
763  let references = parse_with_references(&opts.with, &original_node)?;
764  let processed_node = process_node_with_references(&new_node, &references)?;
765
766  // Save original for comparison
767  let old_node = navigate_to_path(&code_entry.code, &path)?;
768
769  // Show diff preview
770  println!("{}", show_diff_preview(&old_node, &processed_node, "rewrite", &path));
771  // Tips: root-edit guidance
772  if let Some(t) = tip_root_edit(path.is_empty()) {
773    let mut tips = Tips::new();
774    tips.add_with_priority(TipPriority::High, t);
775    tips.print();
776  }
777
778  let new_code = apply_operation_at_path(&code_entry.code, &path, TreeOperation::Replace, Some(&processed_node))?;
779  code_entry.code = new_code;
780
781  save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
782
783  println!("\n## Result\n\n- status: `applied`");
784  Ok(())
785}
786
787fn handle_replace_leaf(opts: &TreeReplaceLeafCommand, snapshot_file: &str) -> Result<(), String> {
788  let (namespace, definition) = parse_target(&opts.target)?;
789
790  let code_input = read_code_input(&opts.file, &opts.code)?;
791  let raw = code_input.as_deref().ok_or(ERR_CODE_INPUT_REQUIRED)?;
792
793  let replacement_node = decode_mutation_syntax_input(raw, opts.input_format)?;
794
795  let mut snapshot = load_snapshot(snapshot_file)?;
796  check_ns_editable(&snapshot, namespace)?;
797
798  let file_data = snapshot
799    .files
800    .get_mut(namespace)
801    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
802
803  let code_entry = file_data
804    .defs
805    .get_mut(definition)
806    .ok_or_else(|| format!("Definition '{definition}' not found"))?;
807
808  // Find all leaf nodes that match the pattern
809  let matches = find_all_leaf_matches(&code_entry.code, &opts.pattern, opts.regex, &[]);
810
811  if matches.is_empty() {
812    println!("{}", "No matches found.".yellow());
813    return Ok(());
814  }
815
816  println!("# Tree mutation\n");
817  println!("- operation: `replace-leaf`");
818  println!("- target: `{}`", opts.target);
819  println!("- matches: `{}`", matches.len());
820  println!("- changed: `true`\n");
821  println!("## Matched paths\n");
822
823  // Show preview of matches
824  for (i, (path, old_value)) in matches.iter().enumerate().take(20) {
825    println!("{}. `{}`: `{old_value}`", i + 1, format_path(path));
826  }
827
828  if matches.len() > 20 {
829    println!("\n_... and {} more._", matches.len() - 20);
830  }
831  println!();
832
833  // Replace all matches (from end to beginning to maintain path validity)
834  let mut new_code = code_entry.code.clone();
835  let mut replaced_count = 0;
836
837  // Sort paths in reverse order to replace from deepest/rightmost first
838  let mut sorted_matches = matches;
839  sorted_matches.sort_by(|a, b| b.0.cmp(&a.0));
840
841  for (path, _) in sorted_matches {
842    match apply_operation_at_path(&new_code, &path, TreeOperation::Replace, Some(&replacement_node)) {
843      Ok(updated_code) => {
844        new_code = updated_code;
845        replaced_count += 1;
846      }
847      Err(e) => {
848        eprintln!("{} Failed to replace at path {}: {}", "Warning:".yellow(), format_path(&path), e);
849      }
850    }
851  }
852
853  // Update the code entry
854  code_entry.code = new_code;
855  save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
856
857  println!("- replaced: `{replaced_count}`\n");
858  print_preview_block("Replacement", &replacement_node, 0, "green");
859  Ok(())
860}
861
862fn handle_search_replace(opts: &TreeSearchReplaceCommand, snapshot_file: &str) -> Result<(), String> {
863  let (namespace, definition) = parse_target(&opts.target)?;
864
865  let code_input = read_code_input(&opts.file, &opts.code)?;
866  let raw = code_input.as_deref().ok_or(ERR_CODE_INPUT_REQUIRED)?;
867
868  let replacement_node = decode_mutation_syntax_input(raw, opts.input_format)?;
869
870  let mut snapshot = load_snapshot(snapshot_file)?;
871  check_ns_editable(&snapshot, namespace)?;
872
873  let file_data = snapshot
874    .files
875    .get_mut(namespace)
876    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
877
878  let code_entry = file_data
879    .defs
880    .get_mut(definition)
881    .ok_or_else(|| format!("Definition '{definition}' not found"))?;
882
883  // L3: resolve search scope via --selector
884  let (search_root_path, search_root) = if let Some(selector) = &opts.selector {
885    let path = resolve_path_expression(&code_entry.code, selector)?;
886    let root = navigate_to_path(&code_entry.code, &path)?;
887    (path, root)
888  } else {
889    (vec![], code_entry.code.clone())
890  };
891
892  // Find all leaf nodes that match the pattern within the search scope
893  let matches = find_all_leaf_matches(&search_root, &opts.pattern, opts.regex, &[]);
894
895  // Compose full paths: prefix search_root_path to each match path
896  let compose_path = |rel: &[usize]| -> Vec<usize> {
897    let mut full = search_root_path.clone();
898    full.extend_from_slice(rel);
899    full
900  };
901
902  if matches.is_empty() {
903    return Err(search_replace_no_match_error(opts, snapshot_file));
904  }
905
906  if matches.len() > 1 {
907    // If --pick is specified, use that candidate directly
908    if let Some(pick_index) = opts.pick {
909      if pick_index >= matches.len() {
910        return Err(format!(
911          "--pick {} is out of range (found {} matches, valid indices: 0-{})",
912          pick_index,
913          matches.len(),
914          matches.len() - 1
915        ));
916      }
917      let (path, old_value) = &matches[pick_index];
918      let full_path = compose_path(path);
919      let old_node = Cirru::Leaf(old_value.to_string().into());
920      println!("{}", show_diff_preview(&old_node, &replacement_node, "search-replace", &full_path));
921
922      let new_code = apply_operation_at_path(&code_entry.code, &full_path, TreeOperation::Replace, Some(&replacement_node))?;
923      code_entry.code = new_code;
924      save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
925      println!("{} Replaced occurrence [{}]", "✓".green(), pick_index);
926      return Ok(());
927    }
928
929    // No --pick: show candidates with context
930    println!("# Search-replace candidates\n");
931    println!("- target: `{}`", opts.target);
932    println!("- pattern: `{}`", opts.pattern);
933    println!("- matches: `{}`", matches.len());
934    println!("- changed: `false`");
935
936    let replacement_arg = if let Some(c) = &opts.code {
937      format!("--code '{c}'")
938    } else if let Some(f) = &opts.file {
939      format!("--file '{f}'")
940    } else {
941      "--code '...'".to_string()
942    };
943
944    for (i, (path, value)) in matches.iter().enumerate().take(20) {
945      let full_path = compose_path(path);
946      let path_str = format_path(&full_path);
947      println!("\n## Candidate {i}\n");
948      println!("- path: `{path_str}`");
949      println!("- value: `{value}`");
950      // Show context: get the parent node for a quick preview
951      if !full_path.is_empty() {
952        let parent_path = &full_path[..full_path.len() - 1];
953        if let Ok(parent) = navigate_to_path(&code_entry.code, parent_path) {
954          print_preview_block("Context", &parent, 6, "");
955        }
956      }
957      println!(
958        "\n- command: `calcit tree search-replace {} --pattern '{}' {} --pick {}`",
959        opts.target, opts.pattern, replacement_arg, i
960      );
961    }
962
963    if matches.len() > 20 {
964      println!("  ... and {} more", matches.len() - 20);
965    }
966    println!();
967    if command_guidance_enabled() {
968      println!(
969        "{}",
970        "Tip: Use --pick <index> to select a candidate, or use 'tree replace-leaf' to replace ALL occurrences.".blue()
971      );
972    }
973
974    return Err(format!(
975      "Found {} matches for pattern '{}'. Use --pick <index> to select one (see candidates above).",
976      matches.len(),
977      opts.pattern
978    ));
979  }
980
981  // Exactly one match
982  let (path, old_value) = &matches[0];
983  let full_path = compose_path(path);
984  let old_node = Cirru::Leaf(old_value.to_string().into());
985
986  // Show diff preview
987  println!("{}", show_diff_preview(&old_node, &replacement_node, "search-replace", &full_path));
988
989  let new_code = apply_operation_at_path(&code_entry.code, &full_path, TreeOperation::Replace, Some(&replacement_node))?;
990  code_entry.code = new_code;
991
992  save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
993
994  println!("{} Replaced unique occurrence", "✓".green());
995
996  Ok(())
997}
998
999fn search_replace_no_match_error(opts: &TreeSearchReplaceCommand, snapshot_file: &str) -> String {
1000  let parses_as_expression = if opts.regex {
1001    false
1002  } else {
1003    cirru_parser::parse(&opts.pattern)
1004      .map(|nodes| {
1005        nodes.len() != 1
1006          || matches!(nodes.first(), Some(Cirru::List(items)) if !(items.len() == 1 && matches!(items.first(), Some(Cirru::Leaf(_)))))
1007      })
1008      .unwrap_or(false)
1009  };
1010  if !parses_as_expression {
1011    return format!(
1012      "[E_TREE_SEARCH_REPLACE_LEAF_NOT_FOUND] No leaf nodes matched target pattern {:?}; search-replace searches leaf nodes only. No changes were written.",
1013      opts.pattern
1014    );
1015  }
1016
1017  let snapshot_arg = if snapshot_file == "calcit.cirru" {
1018    String::new()
1019  } else {
1020    format!(" {}", shell_quote(snapshot_file))
1021  };
1022  let replacement_arg = match (&opts.code, &opts.file) {
1023    (Some(code), _) => format!("--code {}", shell_quote(code)),
1024    (_, Some(file)) => format!("--file {}", shell_quote(file)),
1025    _ => "--code 'quote $ <replacement-expression>'".to_string(),
1026  };
1027  format!(
1028    "[E_TREE_SEARCH_REPLACE_EXPRESSION_PATTERN] search-replace matches one leaf, but --pattern parses as a Cirru expression. No changes were written.\n\
1029     Recovery: calcit{snapshot_arg} query search-expr {} --filter {} --set-cursor 0\n\
1030     Then replace the selected expression with: calcit{snapshot_arg} cursor apply replace {replacement_arg}\n\
1031     Or use tree replace with the returned path and an --expect guard.",
1032    shell_quote(&opts.pattern),
1033    shell_quote(&opts.target)
1034  )
1035}
1036
1037/// Find leaf nodes matching the pattern; uses exact match or regex based on flag
1038fn find_all_leaf_matches(node: &Cirru, pattern: &str, regex: bool, current_path: &[usize]) -> Vec<(Vec<usize>, String)> {
1039  let mut results = Vec::new();
1040
1041  // Compile regex once if needed
1042  let regex_pattern = if regex {
1043    match regex::Regex::new(pattern) {
1044      Ok(r) => Some(r),
1045      Err(e) => {
1046        eprintln!("{} Invalid regex '{}': {}", "Error:".red().bold(), pattern, e);
1047        return results;
1048      }
1049    }
1050  } else {
1051    None
1052  };
1053
1054  match node {
1055    Cirru::Leaf(s) => {
1056      let matched = if regex {
1057        regex_pattern.as_ref().is_some_and(|r| r.is_match(s))
1058      } else {
1059        // Exact match (default)
1060        s.as_ref() == pattern
1061      };
1062
1063      if matched {
1064        results.push((current_path.to_vec(), s.to_string()));
1065      }
1066    }
1067    Cirru::List(items) => {
1068      // Recursively search children
1069      for (i, item) in items.iter().enumerate() {
1070        let mut new_path = current_path.to_vec();
1071        new_path.push(i);
1072        results.extend(find_all_leaf_matches(item, pattern, regex, &new_path));
1073      }
1074    }
1075  }
1076
1077  results
1078}
1079
1080fn handle_delete(opts: &TreeDeleteCommand, snapshot_file: &str) -> Result<(), String> {
1081  let (namespace, definition) = parse_target(&opts.target)?;
1082  let path = parse_path(&opts.path)?;
1083
1084  let mut snapshot = load_snapshot(snapshot_file)?;
1085  check_ns_editable(&snapshot, namespace)?;
1086
1087  let file_data = snapshot
1088    .files
1089    .get_mut(namespace)
1090    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
1091
1092  let code_entry = file_data
1093    .defs
1094    .get_mut(definition)
1095    .ok_or_else(|| format!("Definition '{definition}' not found"))?;
1096
1097  // Save original node and parent for comparison
1098  let old_node = navigate_to_path(&code_entry.code, &path)?;
1099  verify_expected_node(&old_node, opts.expect.as_deref(), &path)?;
1100  let parent_path: Vec<usize> = if path.is_empty() { vec![] } else { path[..path.len() - 1].to_vec() };
1101  if let Some(t) = tip_root_edit(path.is_empty()) {
1102    let mut tips = Tips::new();
1103    tips.add_with_priority(TipPriority::High, t);
1104    tips.print();
1105  }
1106
1107  let new_code = apply_operation_at_path(&code_entry.code, &path, TreeOperation::Delete, None)?;
1108  code_entry.code = new_code.clone();
1109
1110  save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
1111
1112  println!("# Tree mutation\n");
1113  println!("- operation: `delete`");
1114  println!("- target: `{}`", opts.target);
1115  println!("- path: `{}`", format_path(&path));
1116  println!("- changed: `true`\n");
1117  print_preview_block("Deleted node", &old_node, opts.depth, "yellow");
1118  println!();
1119  let new_parent = if parent_path.is_empty() {
1120    new_code
1121  } else {
1122    navigate_to_path(&new_code, &parent_path)?
1123  };
1124  print_preview_block("Parent after deletion", &new_parent, opts.depth, "green");
1125
1126  // Warn about index changes
1127  if !path.is_empty() {
1128    let deleted_index = path[path.len() - 1];
1129    println!(
1130      "{}: Sibling nodes after index {} have shifted down by 1",
1131      "⚠️  Index change".yellow().bold(),
1132      deleted_index
1133    );
1134    println!(
1135      "   Example: path {}.{} is now {}.{}",
1136      format_path(&parent_path),
1137      deleted_index + 1,
1138      format_path(&parent_path),
1139      deleted_index
1140    );
1141    println!(
1142      "   {}: Re-run {} to get updated paths",
1143      "Tip".blue().bold(),
1144      "calcit query search".cyan()
1145    );
1146  }
1147
1148  Ok(())
1149}
1150
1151/// Maps `tree insert --at <position>` to its tree operation.
1152fn insert_operation(at: &str) -> Result<TreeOperation, String> {
1153  match at {
1154    "before" => Ok(TreeOperation::InsertBefore),
1155    "after" => Ok(TreeOperation::InsertAfter),
1156    "prepend-child" => Ok(TreeOperation::InsertChild),
1157    "append-child" => Ok(TreeOperation::AppendChild),
1158    other => Err(format!(
1159      "Unsupported `tree insert --at {other}`. Use: before, after, prepend-child, append-child."
1160    )),
1161  }
1162}
1163
1164/// Maps `tree swap --with <sibling>` to its tree operation.
1165fn swap_operation(with: &str) -> Result<TreeOperation, String> {
1166  match with {
1167    "next" => Ok(TreeOperation::SwapNextSibling),
1168    "prev" => Ok(TreeOperation::SwapPrevSibling),
1169    other => Err(format!("Unsupported `tree swap --with {other}`. Use: next, prev.")),
1170  }
1171}
1172
1173fn handle_insert(opts: &TreeInsertCommand, snapshot_file: &str) -> Result<(), String> {
1174  let operation = insert_operation(&opts.at)?;
1175  generic_insert_handler(&opts.target, &opts.path, operation, opts, snapshot_file, opts.depth)
1176}
1177
1178// Generic trait for insert-like operations
1179trait InsertOperation {
1180  fn file(&self) -> &Option<String>;
1181  fn code(&self) -> &Option<String>;
1182  fn input_format(&self) -> SyntaxInputFormat;
1183  fn expect(&self) -> Option<&str>;
1184  fn with(&self) -> &[String] {
1185    &[]
1186  }
1187}
1188
1189impl InsertOperation for TreeInsertCommand {
1190  fn file(&self) -> &Option<String> {
1191    &self.file
1192  }
1193  fn code(&self) -> &Option<String> {
1194    &self.code
1195  }
1196  fn input_format(&self) -> SyntaxInputFormat {
1197    self.input_format
1198  }
1199  fn expect(&self) -> Option<&str> {
1200    self.expect.as_deref()
1201  }
1202}
1203
1204impl InsertOperation for TreeSearchReplaceCommand {
1205  fn file(&self) -> &Option<String> {
1206    &self.file
1207  }
1208  fn code(&self) -> &Option<String> {
1209    &self.code
1210  }
1211  fn input_format(&self) -> SyntaxInputFormat {
1212    self.input_format
1213  }
1214  fn expect(&self) -> Option<&str> {
1215    None
1216  }
1217}
1218
1219impl InsertOperation for TreeStructuralCommand {
1220  fn file(&self) -> &Option<String> {
1221    &self.file
1222  }
1223  fn code(&self) -> &Option<String> {
1224    &self.code
1225  }
1226  fn input_format(&self) -> SyntaxInputFormat {
1227    self.input_format
1228  }
1229  fn expect(&self) -> Option<&str> {
1230    None
1231  }
1232  fn with(&self) -> &[String] {
1233    &self.with
1234  }
1235}
1236
1237fn generic_insert_handler<T: InsertOperation>(
1238  target: &str,
1239  path_str: &str,
1240  operation: TreeOperation,
1241  opts: &T,
1242  snapshot_file: &str,
1243  depth: usize,
1244) -> Result<(), String> {
1245  let (namespace, definition) = parse_target(target)?;
1246  let path = parse_path(path_str)?;
1247
1248  let code_input = read_code_input(opts.file(), opts.code())?;
1249
1250  let raw = code_input.as_deref().ok_or(ERR_CODE_INPUT_REQUIRED)?;
1251
1252  let new_node = decode_mutation_syntax_input(raw, opts.input_format())?;
1253
1254  let mut snapshot = load_snapshot(snapshot_file)?;
1255  check_ns_editable(&snapshot, namespace)?;
1256
1257  let file_data = snapshot
1258    .files
1259    .get_mut(namespace)
1260    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
1261
1262  let code_entry = file_data
1263    .defs
1264    .get_mut(definition)
1265    .ok_or_else(|| format!("Definition '{definition}' not found"))?;
1266
1267  let processed_node = if opts.with().is_empty() {
1268    new_node
1269  } else {
1270    let original_node = navigate_to_path(&code_entry.code, &path)?;
1271    let references = parse_with_references(opts.with(), &original_node)?;
1272    process_node_with_references(&new_node, &references)?
1273  };
1274
1275  let anchor_node = navigate_to_path(&code_entry.code, &path)?;
1276  verify_expected_node(&anchor_node, opts.expect(), &path)?;
1277
1278  let parent_path: Vec<usize> = if path.is_empty() { vec![] } else { path[..path.len() - 1].to_vec() };
1279  let context_path = match operation {
1280    TreeOperation::InsertChild | TreeOperation::AppendChild => &path,
1281    TreeOperation::InsertBefore | TreeOperation::InsertAfter => &parent_path,
1282    _ => unreachable!("generic_insert_handler only accepts insert operations"),
1283  };
1284  if let Some(t) = tip_root_edit(path.is_empty()) {
1285    let mut tips = Tips::new();
1286    tips.add_with_priority(TipPriority::High, t);
1287    tips.print();
1288  }
1289
1290  let new_code = apply_operation_at_path(&code_entry.code, &path, operation, Some(&processed_node))?;
1291  code_entry.code = new_code.clone();
1292
1293  save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
1294
1295  println!("# Tree mutation\n");
1296  println!("- operation: `{}`", operation.as_str());
1297  println!("- target: `{target}`");
1298  println!("- path: `{}`", format_path(&path));
1299  println!("- changed: `true`\n");
1300  print_preview_block("Inserted node", &processed_node, depth, "cyan");
1301  println!();
1302  let new_parent = if context_path.is_empty() {
1303    new_code
1304  } else {
1305    navigate_to_path(&new_code, context_path)?
1306  };
1307  print_preview_block("Containing node after", &new_parent, depth, "green");
1308
1309  // Explain index impact based on operation
1310  match operation {
1311    TreeOperation::InsertBefore => {
1312      if !path.is_empty() {
1313        let insert_index = path[path.len() - 1];
1314        println!(
1315          "{}: Node inserted at index {}, original node and siblings shifted up by 1",
1316          "Index impact".yellow().bold(),
1317          insert_index
1318        );
1319        println!(
1320          "   Old path {}.{} → New path {}.{}",
1321          format_path(&parent_path),
1322          insert_index,
1323          format_path(&parent_path),
1324          insert_index + 1
1325        );
1326      }
1327    }
1328    TreeOperation::InsertAfter => {
1329      if !path.is_empty() {
1330        let ref_index = path[path.len() - 1];
1331        println!(
1332          "{}: Node inserted at index {}, nodes after reference shifted up by 1",
1333          "Index impact".yellow().bold(),
1334          ref_index + 1
1335        );
1336      }
1337    }
1338    TreeOperation::InsertChild => {
1339      println!(
1340        "{}: Node inserted as first child (index 0), all existing children shifted up by 1",
1341        "Index impact".yellow().bold()
1342      );
1343      println!("   Old child [0] → New child [1], [1] → [2], etc.");
1344    }
1345    TreeOperation::AppendChild => {
1346      println!(
1347        "{}: Node appended as last child, no index changes to existing nodes",
1348        "Index impact".green().bold()
1349      );
1350      println!("   {}:  Use this for multiple insertions to keep paths stable", "Tip".blue().bold());
1351    }
1352    _ => unreachable!("generic_insert_handler only accepts insert operations"),
1353  }
1354
1355  Ok(())
1356}
1357
1358fn handle_swap(opts: &TreeSwapCommand, snapshot_file: &str) -> Result<(), String> {
1359  let operation = swap_operation(&opts.with)?;
1360  generic_swap_handler(&opts.target, &opts.path, operation, snapshot_file, opts.depth)
1361}
1362
1363fn generic_swap_handler(
1364  target: &str,
1365  path_str: &str,
1366  operation: TreeOperation,
1367  snapshot_file: &str,
1368  _depth: usize,
1369) -> Result<(), String> {
1370  let (namespace, definition) = parse_target(target)?;
1371  let path = parse_path(path_str)?;
1372
1373  let mut snapshot = load_snapshot(snapshot_file)?;
1374  check_ns_editable(&snapshot, namespace)?;
1375
1376  let file_data = snapshot
1377    .files
1378    .get_mut(namespace)
1379    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
1380
1381  let code_entry = file_data
1382    .defs
1383    .get_mut(definition)
1384    .ok_or_else(|| format!("Definition '{definition}' not found"))?;
1385
1386  // Save parent before swap for comparison
1387  let parent_path: Vec<usize> = if path.is_empty() { vec![] } else { path[..path.len() - 1].to_vec() };
1388  let old_parent = if parent_path.is_empty() {
1389    code_entry.code.clone()
1390  } else {
1391    navigate_to_path(&code_entry.code, &parent_path)?
1392  };
1393
1394  let new_code = apply_operation_at_path(&code_entry.code, &path, operation, None)?;
1395  code_entry.code = new_code.clone();
1396
1397  save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
1398
1399  println!("# Tree mutation\n");
1400  println!("- operation: `{}`", operation.as_str());
1401  println!("- target: `{target}`");
1402  println!("- path: `{}`", format_path(&path));
1403  println!("- changed: `true`\n");
1404
1405  // Explain what was swapped
1406  if !path.is_empty() {
1407    let current_index = path[path.len() - 1];
1408    let parent_display = if parent_path.is_empty() {
1409      "root".to_string()
1410    } else {
1411      format!("@{}", parent_path.iter().map(|i| i.to_string()).collect::<Vec<_>>().join("."))
1412    };
1413
1414    match operation {
1415      TreeOperation::SwapNextSibling => {
1416        println!(
1417          "{}: Swapped child [{}] with [{}] under parent {}",
1418          "Index change".yellow().bold(),
1419          current_index,
1420          current_index + 1,
1421          parent_display
1422        );
1423      }
1424      TreeOperation::SwapPrevSibling => {
1425        println!(
1426          "{}: Swapped child [{}] with [{}] under parent {}",
1427          "Index change".yellow().bold(),
1428          current_index,
1429          current_index - 1,
1430          parent_display
1431        );
1432      }
1433      _ => unreachable!("generic_swap_handler only accepts swap operations"),
1434    }
1435    println!();
1436  }
1437
1438  print_preview_block("Parent before swap", &old_parent, 15, "yellow");
1439  println!();
1440  if let Some(t) = tip_root_edit(path.is_empty()) {
1441    let mut tips = Tips::new();
1442    tips.add_with_priority(TipPriority::High, t);
1443    tips.print();
1444  }
1445  let new_parent = if parent_path.is_empty() {
1446    new_code
1447  } else {
1448    navigate_to_path(&new_code, &parent_path)?
1449  };
1450  print_preview_block("Parent after swap", &new_parent, 15, "green");
1451
1452  Ok(())
1453}
1454
1455/// Splice all children of the node at `path` into the parent list, removing the wrapper node.
1456/// e.g. parent `(foo (a b c) d)` with unwrap of `(a b c)` gives `(foo a b c d)`.
1457fn splice_at_path(code: &Cirru, path: &[usize]) -> Result<Cirru, String> {
1458  if path.is_empty() {
1459    return Err("Cannot unwrap root node (no parent to splice into)".to_string());
1460  }
1461  splice_recursive(code, path, 0)
1462}
1463
1464fn splice_recursive(code: &Cirru, path: &[usize], depth: usize) -> Result<Cirru, String> {
1465  match code {
1466    Cirru::Leaf(_) => Err(format!("Cannot navigate into leaf node at depth {depth}")),
1467    Cirru::List(items) => {
1468      let idx = path[depth];
1469      if idx >= items.len() {
1470        return Err(format!("Path index {} out of bounds (list has {} items)", idx, items.len()));
1471      }
1472      if depth == path.len() - 1 {
1473        // At parent level: splice children of items[idx] in place
1474        let splice_children = match &items[idx] {
1475          Cirru::List(children) => children.clone(),
1476          Cirru::Leaf(_) => return Err("Node at path is a leaf; cannot unwrap".to_string()),
1477        };
1478        let mut new_items: Vec<Cirru> = Vec::with_capacity(items.len() - 1 + splice_children.len());
1479        new_items.extend_from_slice(&items[..idx]);
1480        new_items.extend(splice_children);
1481        new_items.extend_from_slice(&items[idx + 1..]);
1482        Ok(Cirru::List(new_items))
1483      } else {
1484        let mut new_items = items.clone();
1485        new_items[idx] = splice_recursive(&items[idx], path, depth + 1)?;
1486        Ok(Cirru::List(new_items))
1487      }
1488    }
1489  }
1490}
1491
1492fn handle_unwrap(opts: &TreeUnwrapCommand, snapshot_file: &str) -> Result<(), String> {
1493  let (namespace, definition) = parse_target(&opts.target)?;
1494  let path = parse_path(&opts.path)?;
1495
1496  if path.is_empty() {
1497    return Err("Cannot unwrap root node (no parent to splice into)".to_string());
1498  }
1499
1500  let mut snapshot = load_snapshot(snapshot_file)?;
1501  check_ns_editable(&snapshot, namespace)?;
1502
1503  let file_data = snapshot
1504    .files
1505    .get_mut(namespace)
1506    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
1507
1508  let code_entry = file_data
1509    .defs
1510    .get_mut(definition)
1511    .ok_or_else(|| format!("Definition '{definition}' not found"))?;
1512
1513  let node = navigate_to_path(&code_entry.code, &path)?;
1514  let children = match &node {
1515    Cirru::List(children) => children.clone(),
1516    _ => return Err(format!("Node at path [{}] is a leaf; cannot unwrap", opts.path)),
1517  };
1518
1519  if children.is_empty() {
1520    return Err(format!("Node at path [{}] has no children to splice", opts.path));
1521  }
1522
1523  let new_code = splice_at_path(&code_entry.code, &path)?;
1524  let parent_path = &path[..path.len() - 1];
1525  let parent_after = if parent_path.is_empty() {
1526    new_code.clone()
1527  } else {
1528    navigate_to_path(&new_code, parent_path)?
1529  };
1530  code_entry.code = new_code;
1531
1532  save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
1533
1534  println!("# Tree mutation\n");
1535  println!("- operation: `unwrap`");
1536  println!("- target: `{}`", opts.target);
1537  println!("- path: `{}`", format_path(&path));
1538  println!("- changed: `true`");
1539  println!("- spliced children: `{}`\n", children.len());
1540  print_preview_block("Before", &node, opts.depth, "yellow");
1541  println!();
1542  print_preview_block("Parent after", &parent_after, opts.depth, "green");
1543
1544  Ok(())
1545}
1546
1547fn handle_raise(opts: &TreeRaiseCommand, snapshot_file: &str) -> Result<(), String> {
1548  let (namespace, definition) = parse_target(&opts.target)?;
1549  let path = parse_path(&opts.path)?;
1550
1551  if path.is_empty() {
1552    return Err("Cannot raise root node (no parent to replace). Path must have at least one element.".to_string());
1553  }
1554
1555  let parent_path = &path[..path.len() - 1];
1556
1557  let mut snapshot = load_snapshot(snapshot_file)?;
1558  check_ns_editable(&snapshot, namespace)?;
1559
1560  let file_data = snapshot
1561    .files
1562    .get_mut(namespace)
1563    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
1564
1565  let code_entry = file_data
1566    .defs
1567    .get_mut(definition)
1568    .ok_or_else(|| format!("Definition '{definition}' not found"))?;
1569
1570  let child_node = navigate_to_path(&code_entry.code, &path)?;
1571  let parent_node = navigate_to_path(&code_entry.code, parent_path)?;
1572
1573  let new_code = apply_operation_at_path(&code_entry.code, parent_path, TreeOperation::Replace, Some(&child_node))?;
1574  code_entry.code = new_code;
1575
1576  save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
1577
1578  println!("# Tree mutation\n");
1579  println!("- operation: `raise`");
1580  println!("- target: `{}`", opts.target);
1581  println!("- path: `{}`", format_path(&path));
1582  println!("- changed: `true`\n");
1583  print_preview_block("Before (parent)", &parent_node, opts.depth, "yellow");
1584  println!();
1585  print_preview_block("After (raised child)", &child_node, opts.depth, "green");
1586
1587  Ok(())
1588}
1589
1590fn handle_wrap(opts: &TreeWrapCommand, snapshot_file: &str) -> Result<(), String> {
1591  let (namespace, definition) = parse_target(&opts.target)?;
1592  let path = parse_path(&opts.path)?;
1593
1594  let raw = read_code_input(&opts.file, &opts.code)?.ok_or(ERR_CODE_INPUT_REQUIRED)?;
1595  let template = decode_mutation_syntax_input(&raw, opts.input_format)?;
1596
1597  let mut snapshot = load_snapshot(snapshot_file)?;
1598  check_ns_editable(&snapshot, namespace)?;
1599
1600  let file_data = snapshot
1601    .files
1602    .get_mut(namespace)
1603    .ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
1604
1605  let code_entry = file_data
1606    .defs
1607    .get_mut(definition)
1608    .ok_or_else(|| format!("Definition '{definition}' not found"))?;
1609
1610  let original_node = navigate_to_path(&code_entry.code, &path)?;
1611
1612  // `self` always refers to the original node (equivalent to rewrite --with self=.)
1613  let mut references = std::collections::BTreeMap::new();
1614  references.insert("self".to_string(), original_node.clone());
1615
1616  let new_node = process_node_with_references(&template, &references)?;
1617
1618  let new_code = apply_operation_at_path(&code_entry.code, &path, TreeOperation::Replace, Some(&new_node))?;
1619  code_entry.code = new_code;
1620
1621  save_definition_tree(&snapshot, snapshot_file, namespace, definition)?;
1622
1623  println!("# Tree mutation\n");
1624  println!("- operation: `wrap`");
1625  println!("- target: `{}`", opts.target);
1626  println!("- path: `{}`", format_path(&path));
1627  println!("- changed: `true`\n");
1628  print_preview_block("Before", &original_node, opts.depth, "yellow");
1629  println!();
1630  print_preview_block("After", &new_node, opts.depth, "green");
1631
1632  Ok(())
1633}
1634
1635#[cfg(test)]
1636mod tests {
1637  use super::{find_all_leaf_matches, search_replace_no_match_error, verify_expected_node};
1638  use crate::cli_args::{SyntaxInputFormat, TreeSearchReplaceCommand};
1639  use cirru_parser::Cirru;
1640
1641  fn leaf(text: &str) -> Cirru {
1642    Cirru::Leaf(text.into())
1643  }
1644
1645  fn list(items: Vec<Cirru>) -> Cirru {
1646    Cirru::List(items)
1647  }
1648
1649  fn search_replace(pattern: &str, regex: bool) -> TreeSearchReplaceCommand {
1650    TreeSearchReplaceCommand {
1651      target: "app.main/demo".to_string(),
1652      pattern: pattern.to_string(),
1653      regex,
1654      file: None,
1655      code: Some("quote replacement".to_string()),
1656      input_format: SyntaxInputFormat::Auto,
1657      depth: 2,
1658      pick: None,
1659      selector: None,
1660    }
1661  }
1662
1663  #[test]
1664  fn expression_pattern_error_provides_structural_recovery_without_mutation_claims() {
1665    let error = search_replace_no_match_error(&search_replace("js/document.querySelector |.app", false), "fixture.cirru");
1666    assert!(error.contains("E_TREE_SEARCH_REPLACE_EXPRESSION_PATTERN"));
1667    assert!(error.contains("searches one leaf") || error.contains("matches one leaf"));
1668    assert!(error.contains("calcit 'fixture.cirru' query search-expr 'js/document.querySelector |.app'"));
1669    assert!(error.contains("--filter 'app.main/demo' --set-cursor 0"));
1670    assert!(error.contains("cursor apply replace --code 'quote replacement'"));
1671    assert!(error.contains("No changes were written"));
1672  }
1673
1674  #[test]
1675  fn absent_leaf_error_names_the_leaf_only_search_scope() {
1676    let error = search_replace_no_match_error(&search_replace("missing-leaf", false), "calcit.cirru");
1677    assert!(error.contains("E_TREE_SEARCH_REPLACE_LEAF_NOT_FOUND"));
1678    assert!(error.contains("search-replace searches leaf nodes only"));
1679    assert!(error.contains("No changes were written"));
1680  }
1681
1682  #[test]
1683  fn regex_leaf_search_stays_on_the_leaf_matching_path() {
1684    let tree = list(vec![leaf("alpha-1"), list(vec![leaf("beta"), leaf("alpha-2")])]);
1685    let matches = find_all_leaf_matches(&tree, r"^alpha-\d$", true, &[]);
1686    assert_eq!(matches.len(), 2);
1687    assert_eq!(matches[0].0, vec![0]);
1688    assert_eq!(matches[1].0, vec![1, 1]);
1689    assert_eq!(matches[0].1, "alpha-1");
1690    assert_eq!(matches[1].1, "alpha-2");
1691  }
1692
1693  #[test]
1694  fn expected_node_guard_accepts_exact_expression() {
1695    let actual = list(vec![leaf("test-methods")]);
1696    verify_expected_node(&actual, Some("quote (test-methods)"), &[4]).expect("matching guard should pass");
1697  }
1698
1699  #[test]
1700  fn expected_node_guard_rejects_wrong_path_content() {
1701    let actual = list(vec![leaf("test-lisp-style")]);
1702    let error = verify_expected_node(&actual, Some("quote (test-methods)"), &[8]).expect_err("mismatched guard should fail");
1703    assert!(error.contains("# Error: node guard failed"), "error: {error}");
1704    assert!(error.contains("- path: `@8`"), "error: {error}");
1705    assert!(
1706      error.contains("## Expected\n\n- node kind: `expression`\n\n```cirru"),
1707      "error: {error}"
1708    );
1709    assert!(
1710      error.contains("## Actual\n\n- node kind: `expression`\n\n```cirru"),
1711      "error: {error}"
1712    );
1713    assert!(error.contains("No changes were written"), "error: {error}");
1714  }
1715}