Skip to main content

calcit_cli/cli_handlers/
cursor.rs

1use crate::cli_args::{
2  CursorApplyCommand, CursorCommand, TreeCommand, TreeDeleteCommand, TreeInsertCommand, TreeRaiseCommand, TreeReplaceCommand,
3  TreeSubcommand, TreeSwapCommand, TreeUnwrapCommand, TreeWrapCommand,
4};
5use calcit_core::project_state::{self, CURSOR_STATE_FILE};
6use calcit_core::snapshot;
7use cirru_edn::{Edn, EdnListView};
8use cirru_parser::Cirru;
9use colored::Colorize;
10use md5::{Digest, Md5};
11use std::collections::BTreeMap;
12use std::fs;
13use std::path::{Path, PathBuf};
14use std::sync::atomic::{AtomicU8, Ordering};
15
16use super::atomic_write::{StagedFile, stage_atomic_file};
17use super::common::{cirru_to_json_value, format_path, guard_snapshot_mutation_toolchain, parse_path};
18use super::edit::{apply_operation_at_path, check_ns_editable, load_snapshot, navigate_to_path, parse_target};
19use super::normalize::CursorAction;
20use super::structured_output::StructuredOutputFormat;
21use super::tree_mutation::{
22  TreeCursorMutation, TreeOperation, adjusted_source_path_after_insertion, transform_cursor_path, transform_delete,
23};
24
25const LEGACY_CURSOR_FILE: &str = ".calcit-cursor.cirru";
26const DEFAULT_CURSOR: &str = "default";
27const CURSOR_MAINTENANCE_ENV: &str = "CALCIT_CURSOR_MAINTENANCE";
28const CURSOR_SCHEMA_VERSION: u8 = 4;
29const CURSOR_HISTORY_LIMIT: usize = 32;
30const CURSOR_MARK_LIMIT: usize = 16;
31const CURSOR_FILE_MAX_BYTES: usize = 64 * 1024;
32
33/// 0 = none, 1 = summary, 2 = focus.
34static CURSOR_AFTER_MODE: AtomicU8 = AtomicU8::new(1);
35
36#[derive(Debug, Clone, PartialEq)]
37struct CursorState {
38  snapshot: String,
39  target: String,
40  path: Vec<usize>,
41  definition_revision: String,
42  fingerprint: String,
43}
44
45#[derive(Debug, Clone, PartialEq)]
46struct CursorClipboard {
47  mode: String,
48  source_target: String,
49  source_path: Vec<usize>,
50  fingerprint: String,
51  tree: Cirru,
52}
53
54#[derive(Debug, Clone, PartialEq)]
55pub(crate) struct CursorLastQuery {
56  pub command: String,
57  pub pattern: String,
58  pub filter: Option<String>,
59  pub exact: bool,
60  pub regex: bool,
61  pub max_depth: usize,
62  pub start_path: Option<String>,
63  pub entry: Option<String>,
64  pub source: String,
65  pub pattern_is_json: bool,
66  pub selected_index: usize,
67  pub snapshot_revision: String,
68}
69
70#[derive(Debug, Clone, PartialEq)]
71struct CursorDocument {
72  active_name: String,
73  active: CursorState,
74  inactive_cursors: BTreeMap<String, CursorState>,
75  history: Vec<CursorState>,
76  stack: Vec<CursorState>,
77  anchor: Option<CursorState>,
78  marks: BTreeMap<String, CursorState>,
79  last_query: Option<CursorLastQuery>,
80  clipboard: Option<CursorClipboard>,
81}
82
83pub fn set_cursor_after_mode(mode: &str) -> Result<(), String> {
84  let value = match mode {
85    "none" => 0,
86    "summary" => 1,
87    "focus" => 2,
88    other => {
89      return Err(format!(
90        "Unsupported --cursor-after mode '{other}'. Expected none, summary, or focus."
91      ));
92    }
93  };
94  CURSOR_AFTER_MODE.store(value, Ordering::Relaxed);
95  Ok(())
96}
97
98pub fn handle_cursor_command(cmd: &CursorCommand, snapshot_file: &str) -> Result<(), String> {
99  let action = super::normalize::normalize_cursor_subcommand(&cmd.subcommand)?;
100  let mutates_snapshot = matches!(
101    &action,
102    CursorAction::Apply(_)
103      | CursorAction::SlurpNext
104      | CursorAction::SlurpPrev
105      | CursorAction::BarfLast
106      | CursorAction::BarfFirst
107      | CursorAction::Duplicate(_)
108  );
109  let _writer = if mutates_snapshot {
110    Some(calcit_core::util::atomic_write::SnapshotWriteGuard::acquire(snapshot_file)?)
111  } else {
112    None
113  };
114  if mutates_snapshot {
115    guard_snapshot_mutation_toolchain(snapshot_file)?;
116  }
117  match &action {
118    CursorAction::Set(opts) => {
119      if opts.path == "@cursor" {
120        return Err("`cursor set --path` requires a concrete path, not `@cursor`.".to_string());
121      }
122      let path = parse_path(&opts.path)?;
123      let state = set_cursor_selection(snapshot_file, &opts.target, path)?;
124      warn_cursor_gitignore(snapshot_file);
125      println!("{} Cursor set: {} {}", "✓".green(), state.target, format_path(&state.path));
126      emit_focus_after_cursor_action(snapshot_file, &state, "cursor selected")
127    }
128    CursorAction::Show(opts) => handle_cursor_show(snapshot_file, &opts.format, &opts.view),
129    CursorAction::Clear => {
130      let file = cursor_file_path(snapshot_file);
131      let legacy_file = legacy_cursor_file_path(snapshot_file);
132      let mut removed = false;
133      if file.exists() {
134        fs::remove_file(&file).map_err(|error| format!("Failed to remove cursor file '{}': {error}", file.display()))?;
135        removed = true;
136      }
137      if legacy_file.exists() {
138        fs::remove_file(&legacy_file)
139          .map_err(|error| format!("Failed to remove legacy cursor file '{}': {error}", legacy_file.display()))?;
140        removed = true;
141      }
142      if removed {
143        println!("{} Cursor cleared", "✓".green());
144      } else {
145        println!("{} No cursor is set", "•".dimmed());
146      }
147      Ok(())
148    }
149    CursorAction::Parent => move_cursor(snapshot_file, |path| {
150      if path.is_empty() {
151        Err("Cursor is already at the definition root.".to_string())
152      } else {
153        path.pop();
154        Ok(())
155      }
156    }),
157    CursorAction::Child { index, last } => move_cursor_to_child(snapshot_file, *index, *last),
158    CursorAction::Next(count) => move_cursor_across_siblings(snapshot_file, *count, true),
159    CursorAction::Prev(count) => move_cursor_across_siblings(snapshot_file, *count, false),
160    CursorAction::Back(count) => restore_cursor(snapshot_file, RestoreSource::History, *count),
161    CursorAction::Apply(opts) => apply_at_cursor(snapshot_file, opts),
162    CursorAction::SlurpNext => slurp_next(snapshot_file),
163    CursorAction::SlurpPrev => slurp_prev(snapshot_file),
164    CursorAction::BarfLast => barf_last(snapshot_file),
165    CursorAction::BarfFirst => barf_first(snapshot_file),
166    CursorAction::Duplicate(at) => duplicate_cursor(snapshot_file, at),
167    CursorAction::Forward(count) => move_cursor_depth_first(snapshot_file, *count, true),
168    CursorAction::Backward(count) => move_cursor_depth_first(snapshot_file, *count, false),
169  }
170}
171
172fn set_cursor_selection(snapshot_file: &str, target: &str, path: Vec<usize>) -> Result<CursorState, String> {
173  set_cursor_selection_with_last_query(snapshot_file, target, path, None)
174}
175
176fn set_cursor_selection_with_last_query(
177  snapshot_file: &str,
178  target: &str,
179  path: Vec<usize>,
180  last_query: Option<CursorLastQuery>,
181) -> Result<CursorState, String> {
182  let mut state = CursorState {
183    snapshot: snapshot_file.to_string(),
184    target: target.to_string(),
185    path,
186    definition_revision: String::new(),
187    fingerprint: String::new(),
188  };
189  refresh_cursor_state(&mut state, snapshot_file)?;
190  let mut document = load_cursor_document_optional(snapshot_file)?.unwrap_or_else(|| CursorDocument {
191    active_name: DEFAULT_CURSOR.to_string(),
192    active: state.clone(),
193    inactive_cursors: BTreeMap::new(),
194    history: vec![],
195    stack: vec![],
196    anchor: None,
197    marks: BTreeMap::new(),
198    last_query: None,
199    clipboard: None,
200  });
201  if document.active.target != state.target || document.active.path != state.path {
202    push_bounded(&mut document.history, document.active.clone(), CURSOR_HISTORY_LIMIT);
203  }
204  document.active = state.clone();
205  if let Some(last_query) = last_query {
206    document.last_query = Some(last_query);
207  }
208  save_cursor_document(snapshot_file, &document)?;
209  Ok(state)
210}
211
212pub(crate) fn set_cursor_from_query_match(
213  snapshot_file: &str,
214  target: &str,
215  path: Vec<usize>,
216  match_index: usize,
217  last_query: CursorLastQuery,
218) -> Result<(), String> {
219  let state = set_cursor_selection_with_last_query(snapshot_file, target, path, Some(last_query))
220    .map_err(|error| format!("Search match #{match_index} cannot become the project cursor: {error}"))?;
221  warn_cursor_gitignore(snapshot_file);
222  eprintln!(
223    "{} Cursor set from search match #{}: {} {}",
224    "✓".green(),
225    match_index,
226    state.target,
227    format_path(&state.path)
228  );
229  emit_focus_after_cursor_action(snapshot_file, &state, "cursor selected from search")
230}
231
232fn concrete_cursor_path(path: &[usize]) -> String {
233  if path.is_empty() { String::new() } else { format_path(path) }
234}
235
236fn apply_at_cursor(snapshot_file: &str, opts: &CursorApplyCommand) -> Result<(), String> {
237  let state = validate_cursor(snapshot_file, true)?;
238  let target = state.target;
239  let path = concrete_cursor_path(&state.path);
240  let accepts_code = matches!(
241    opts.operation.as_str(),
242    "replace" | "wrap" | "insert-before" | "insert-after" | "insert-child" | "append-child"
243  );
244  if !accepts_code && (opts.file.is_some() || opts.code.is_some() || opts.input_format != crate::cli_args::SyntaxInputFormat::Auto) {
245    return Err(format!(
246      "Cursor operation '{}' does not accept --file, --code, or --input-format.",
247      opts.operation
248    ));
249  }
250
251  let subcommand = match opts.operation.as_str() {
252    "delete" => TreeSubcommand::Delete(TreeDeleteCommand {
253      target,
254      path,
255      expect: None,
256      depth: opts.depth,
257    }),
258    "swap-next" | "swap-prev" => TreeSubcommand::Swap(TreeSwapCommand {
259      target,
260      path,
261      with: opts.operation.trim_start_matches("swap-").to_owned(),
262      depth: opts.depth,
263    }),
264    "unwrap" | "splice" => TreeSubcommand::Unwrap(TreeUnwrapCommand {
265      target,
266      path,
267      depth: opts.depth,
268    }),
269    "raise" => TreeSubcommand::Raise(TreeRaiseCommand {
270      target,
271      path,
272      depth: opts.depth,
273    }),
274    "replace" => TreeSubcommand::Replace(TreeReplaceCommand {
275      target,
276      path,
277      file: opts.file.clone(),
278      code: opts.code.clone(),
279      input_format: opts.input_format,
280      expect: None,
281      depth: opts.depth,
282    }),
283    "wrap" => TreeSubcommand::Wrap(TreeWrapCommand {
284      target,
285      path,
286      code: opts.code.clone(),
287      file: opts.file.clone(),
288      input_format: opts.input_format,
289      depth: opts.depth,
290    }),
291    "insert-before" => TreeSubcommand::Insert(TreeInsertCommand {
292      target,
293      path,
294      at: "before".to_owned(),
295      file: opts.file.clone(),
296      code: opts.code.clone(),
297      input_format: opts.input_format,
298      expect: None,
299      depth: opts.depth,
300    }),
301    "insert-after" => TreeSubcommand::Insert(TreeInsertCommand {
302      target,
303      path,
304      at: "after".to_owned(),
305      file: opts.file.clone(),
306      code: opts.code.clone(),
307      input_format: opts.input_format,
308      expect: None,
309      depth: opts.depth,
310    }),
311    "insert-child" => TreeSubcommand::Insert(TreeInsertCommand {
312      target,
313      path,
314      at: "prepend-child".to_owned(),
315      file: opts.file.clone(),
316      code: opts.code.clone(),
317      input_format: opts.input_format,
318      expect: None,
319      depth: opts.depth,
320    }),
321    "append-child" => TreeSubcommand::Insert(TreeInsertCommand {
322      target,
323      path,
324      at: "append-child".to_owned(),
325      file: opts.file.clone(),
326      code: opts.code.clone(),
327      input_format: opts.input_format,
328      expect: None,
329      depth: opts.depth,
330    }),
331    other => {
332      return Err(format!(
333        "Unsupported cursor operation '{other}'. Use delete, swap-next, swap-prev, unwrap, splice, raise, replace, wrap, insert-before, insert-after, insert-child, append-child, slurp-next, slurp-prev, barf-last, barf-first, or duplicate."
334      ));
335    }
336  };
337  super::tree::handle_tree_command(&TreeCommand { subcommand }, snapshot_file)
338}
339
340fn move_node_for_paredit(snapshot_file: &str, state: &CursorState, from_path: &[usize], at: &str) -> Result<(), String> {
341  super::edit::move_node(
342    &state.target,
343    &concrete_cursor_path(from_path),
344    &concrete_cursor_path(&state.path),
345    at,
346    snapshot_file,
347  )
348}
349
350fn slurp_next(snapshot_file: &str) -> Result<(), String> {
351  let state = validate_cursor(snapshot_file, true)?;
352  if state.path.is_empty() {
353    return Err("Definition root has no next sibling to slurp.".to_string());
354  }
355  let (selected, _) = read_cursor_target(snapshot_file, &state.target, &state.path)?;
356  if !matches!(selected, Cirru::List(_)) {
357    return Err("`cursor apply slurp-next` requires the selected node to be a list.".to_string());
358  }
359  let mut next_path = state.path.clone();
360  let current_index = *next_path.last().expect("non-root cursor has a final index");
361  let parent_path = &state.path[..state.path.len() - 1];
362  let (parent, _) = read_cursor_target(snapshot_file, &state.target, parent_path)?;
363  let Cirru::List(siblings) = parent else {
364    return Err("Cursor parent is not a list and has no sibling sequence.".to_string());
365  };
366  if current_index + 1 >= siblings.len() {
367    return Err("Selected list has no next sibling to slurp.".to_string());
368  }
369  *next_path.last_mut().expect("non-root cursor has a final index") += 1;
370  move_node_for_paredit(snapshot_file, &state, &next_path, "append-child")
371}
372
373fn slurp_prev(snapshot_file: &str) -> Result<(), String> {
374  let state = validate_cursor(snapshot_file, true)?;
375  if state.path.is_empty() {
376    return Err("Definition root has no previous sibling to slurp.".to_string());
377  }
378  let (selected, _) = read_cursor_target(snapshot_file, &state.target, &state.path)?;
379  if !matches!(selected, Cirru::List(_)) {
380    return Err("`cursor apply slurp-prev` requires the selected node to be a list.".to_string());
381  }
382  let mut previous_path = state.path.clone();
383  let current_index = *previous_path.last().expect("non-root cursor has a final index");
384  if current_index == 0 {
385    return Err("Selected list has no previous sibling to slurp.".to_string());
386  }
387  *previous_path.last_mut().expect("non-root cursor has a final index") -= 1;
388  move_node_for_paredit(snapshot_file, &state, &previous_path, "prepend-child")
389}
390
391fn barf_last(snapshot_file: &str) -> Result<(), String> {
392  let state = validate_cursor(snapshot_file, true)?;
393  if state.path.is_empty() {
394    return Err("Cannot barf a child out of the definition root.".to_string());
395  }
396  let (selected, _) = read_cursor_target(snapshot_file, &state.target, &state.path)?;
397  let Cirru::List(children) = selected else {
398    return Err("`cursor apply barf-last` requires the selected node to be a list.".to_string());
399  };
400  let Some(last_index) = children.len().checked_sub(1) else {
401    return Err("Selected list has no child to barf.".to_string());
402  };
403  let mut child_path = state.path.clone();
404  child_path.push(last_index);
405  move_node_for_paredit(snapshot_file, &state, &child_path, "after")
406}
407
408fn barf_first(snapshot_file: &str) -> Result<(), String> {
409  let state = validate_cursor(snapshot_file, true)?;
410  if state.path.is_empty() {
411    return Err("Cannot barf a child out of the definition root.".to_string());
412  }
413  let (selected, _) = read_cursor_target(snapshot_file, &state.target, &state.path)?;
414  let Cirru::List(children) = selected else {
415    return Err("`cursor apply barf-first` requires the selected node to be a list.".to_string());
416  };
417  if children.is_empty() {
418    return Err("Selected list has no child to barf.".to_string());
419  }
420  let mut child_path = state.path.clone();
421  child_path.push(0);
422  let first_child = children[0].clone();
423  let mut document = load_cursor_document(snapshot_file)?;
424  let (namespace, definition) = parse_target(&state.target)?;
425  let mut snapshot = load_snapshot(snapshot_file)?;
426  check_ns_editable(&snapshot, namespace)?;
427  let entry = snapshot
428    .files
429    .get_mut(namespace)
430    .and_then(|file| file.defs.get_mut(definition))
431    .ok_or_else(|| format!("Definition '{}' not found", state.target))?;
432  let without_first = apply_operation_at_path(&entry.code, &child_path, TreeOperation::Delete, None)?;
433  entry.code = apply_operation_at_path(&without_first, &state.path, TreeOperation::InsertBefore, Some(&first_child))?;
434
435  let mut selected_path = state.path.clone();
436  *selected_path.last_mut().expect("root was rejected above") += 1;
437  push_bounded(&mut document.history, state.clone(), CURSOR_HISTORY_LIMIT);
438  document.active.path = selected_path;
439  refresh_cursor_state_from_snapshot(&mut document.active, snapshot_file, &snapshot)?;
440
441  let staged_snapshot = stage_snapshot(snapshot_file, &snapshot)?;
442  let staged_cursor = stage_cursor_document(snapshot_file, &document)?;
443  commit_snapshot_then_cursor_staged_files(staged_snapshot, staged_cursor, "Barf-first", false)?;
444  println!(
445    "{} Moved the selected list's first child out before it; cursor now at {}",
446    "✓".green(),
447    format_path(&document.active.path)
448  );
449  emit_cursor_after(snapshot_file, &document.active, "cursor follows list after barf-first")?;
450  Ok(())
451}
452
453fn duplicate_cursor(snapshot_file: &str, at: &str) -> Result<(), String> {
454  if !matches!(at, "before" | "after") {
455    return Err(format!("Unsupported duplicate position '{at}'. Use before or after."));
456  }
457  let state = validate_cursor(snapshot_file, true)?;
458  if state.path.is_empty() {
459    return Err("Cannot duplicate the definition root as a sibling.".to_string());
460  }
461  let mut document = load_cursor_document(snapshot_file)?;
462  let (namespace, definition) = parse_target(&state.target)?;
463  let mut snapshot = load_snapshot(snapshot_file)?;
464  check_ns_editable(&snapshot, namespace)?;
465  let entry = snapshot
466    .files
467    .get_mut(namespace)
468    .and_then(|file| file.defs.get_mut(definition))
469    .ok_or_else(|| format!("Definition '{}' not found", state.target))?;
470  let selected = navigate_to_path(&entry.code, &state.path)?;
471  entry.code = apply_operation_at_path(
472    &entry.code,
473    &state.path,
474    if at == "before" {
475      TreeOperation::InsertBefore
476    } else {
477      TreeOperation::InsertAfter
478    },
479    Some(&selected),
480  )?;
481
482  let mut duplicated_path = state.path.clone();
483  if at == "after" {
484    *duplicated_path.last_mut().expect("root was rejected above") += 1;
485  }
486  push_bounded(&mut document.history, state, CURSOR_HISTORY_LIMIT);
487  document.active.path = duplicated_path;
488  refresh_cursor_state_from_snapshot(&mut document.active, snapshot_file, &snapshot)?;
489
490  let staged_snapshot = stage_snapshot(snapshot_file, &snapshot)?;
491  let staged_cursor = stage_cursor_document(snapshot_file, &document)?;
492  commit_snapshot_then_cursor_staged_files(staged_snapshot, staged_cursor, "Duplicate", false)?;
493  println!(
494    "{} Duplicated selection {} cursor; cursor now at {}",
495    "✓".green(),
496    at,
497    format_path(&document.active.path)
498  );
499  emit_cursor_after(snapshot_file, &document.active, "cursor follows duplicated expression")?;
500  Ok(())
501}
502
503fn handle_cursor_show(snapshot_file: &str, format: &str, view: &str) -> Result<(), String> {
504  let format = StructuredOutputFormat::parse(format, "cursor")?;
505  if !matches!(view, "focus" | "node" | "full") {
506    return Err(format!("Unsupported cursor view '{view}'. Expected focus, node, or full."));
507  }
508  let (state, status) = validate_cursor_with_status(snapshot_file, true)?;
509  let document = load_cursor_document(snapshot_file)?;
510  let (definition, node, _) = read_cursor_context(snapshot_file, &state.target, &state.path)?;
511  let preview = build_cursor_preview_from_tree(&definition, &node, &state.path, view)?;
512
513  if format != StructuredOutputFormat::Human {
514    format.print_value(&serde_json::json!({
515      "schema_version": 3,
516      "command": "cursor.show",
517      "status": status,
518      "view": view,
519      "target": state.target,
520      "path": format_path(&state.path),
521      "definition_revision": state.definition_revision,
522      "fingerprint": state.fingerprint,
523      "state_file": cursor_file_path(snapshot_file),
524      "anchor": document.anchor.as_ref().map(|anchor| serde_json::json!({
525        "target": anchor.target,
526        "path": format_path(&anchor.path),
527        "fingerprint": anchor.fingerprint,
528      })),
529      "marks": document.marks.iter().map(|(name, mark)| serde_json::json!({
530        "name": name,
531        "target": mark.target,
532        "path": format_path(&mark.path),
533        "fingerprint": mark.fingerprint,
534      })).collect::<Vec<_>>(),
535      "last_query": document.last_query.as_ref().map(|query| serde_json::json!({
536        "command": query.command,
537        "pattern": query.pattern,
538        "filter": query.filter,
539        "selected_index": query.selected_index,
540        "snapshot_revision": query.snapshot_revision,
541      })),
542      "tree": cirru_to_json_value(&node),
543      "preview_tree": cirru_to_json_value(&preview),
544    }))?;
545  } else {
546    println!("{}", render_cursor_human(&state, &document, status, &preview)?);
547  }
548  Ok(())
549}
550
551fn move_cursor<F>(snapshot_file: &str, update: F) -> Result<(), String>
552where
553  F: FnOnce(&mut Vec<usize>) -> Result<(), String>,
554{
555  let mut state = validate_cursor(snapshot_file, true)?;
556  let old_state = state.clone();
557  update(&mut state.path)?;
558  commit_cursor_move(snapshot_file, old_state, state)
559}
560
561fn commit_cursor_move(snapshot_file: &str, old_state: CursorState, mut state: CursorState) -> Result<(), String> {
562  let old_path = old_state.path.clone();
563  refresh_cursor_state(&mut state, snapshot_file)?;
564  let mut document = load_cursor_document(snapshot_file)?;
565  push_bounded(&mut document.history, old_state, CURSOR_HISTORY_LIMIT);
566  document.active = state.clone();
567  save_cursor_document(snapshot_file, &document)?;
568  println!(
569    "{} Cursor moved: {} → {}",
570    "✓".green(),
571    format_path(&old_path),
572    format_path(&state.path)
573  );
574  emit_focus_after_cursor_action(snapshot_file, &state, "cursor moved")
575}
576
577fn move_cursor_to_child(snapshot_file: &str, index: Option<usize>, last: bool) -> Result<(), String> {
578  if last && index.is_some() {
579    return Err("`cursor move child` accepts either an index or `--last`, not both.".to_string());
580  }
581  let mut state = validate_cursor(snapshot_file, true)?;
582  let old_state = state.clone();
583  let (node, _) = read_cursor_target(snapshot_file, &state.target, &state.path)?;
584  let Cirru::List(children) = node else {
585    return Err("Selected leaf has no children.".to_string());
586  };
587  if children.is_empty() {
588    return Err("Selected list has no children.".to_string());
589  }
590  let child_index = if last { children.len() - 1 } else { index.unwrap_or(0) };
591  if child_index >= children.len() {
592    return Err(format!(
593      "Child index {child_index} is out of range; selected list has {} child(ren).",
594      children.len()
595    ));
596  }
597  state.path.push(child_index);
598  commit_cursor_move(snapshot_file, old_state, state)
599}
600
601fn move_cursor_across_siblings(snapshot_file: &str, count: usize, forward: bool) -> Result<(), String> {
602  if count == 0 {
603    return Err("`--count` must be greater than zero.".to_string());
604  }
605  let mut state = validate_cursor(snapshot_file, true)?;
606  let old_state = state.clone();
607  let Some(&current_index) = state.path.last() else {
608    return Err(format!(
609      "Definition root has no {} sibling.",
610      if forward { "next" } else { "previous" }
611    ));
612  };
613  let parent_path = &state.path[..state.path.len() - 1];
614  let (parent, _) = read_cursor_target(snapshot_file, &state.target, parent_path)?;
615  let Cirru::List(siblings) = parent else {
616    return Err("Cursor parent is not a list and has no sibling sequence.".to_string());
617  };
618  let new_index = if forward {
619    current_index.checked_add(count).ok_or("Sibling index overflowed.")?
620  } else {
621    current_index.checked_sub(count).ok_or_else(|| {
622      format!("Cannot move back {count} sibling(s) from index {current_index}; only {current_index} previous sibling(s) exist.")
623    })?
624  };
625  if new_index >= siblings.len() {
626    return Err(format!(
627      "Cannot move forward {count} sibling(s) from index {current_index}; only {} next sibling(s) exist.",
628      siblings.len().saturating_sub(current_index + 1)
629    ));
630  }
631  *state.path.last_mut().expect("non-root cursor path has a final index") = new_index;
632  commit_cursor_move(snapshot_file, old_state, state)
633}
634
635fn depth_first_step(root: &Cirru, path: &[usize], forward: bool) -> Result<Option<Vec<usize>>, String> {
636  if forward {
637    if let Cirru::List(children) = navigate_to_path(root, path)?
638      && !children.is_empty()
639    {
640      let mut child = path.to_vec();
641      child.push(0);
642      return Ok(Some(child));
643    }
644
645    let mut candidate = path.to_vec();
646    while let Some(index) = candidate.pop() {
647      let Cirru::List(siblings) = navigate_to_path(root, &candidate)? else {
648        return Err(format!("Cursor parent {} is not a list.", format_path(&candidate)));
649      };
650      if index + 1 < siblings.len() {
651        candidate.push(index + 1);
652        return Ok(Some(candidate));
653      }
654    }
655    Ok(None)
656  } else {
657    let mut candidate = path.to_vec();
658    let Some(index) = candidate.pop() else {
659      return Ok(None);
660    };
661    if index == 0 {
662      return Ok(Some(candidate));
663    }
664    candidate.push(index - 1);
665    loop {
666      match navigate_to_path(root, &candidate)? {
667        Cirru::List(children) if !children.is_empty() => candidate.push(children.len() - 1),
668        _ => return Ok(Some(candidate)),
669      }
670    }
671  }
672}
673
674fn move_cursor_depth_first(snapshot_file: &str, count: usize, forward: bool) -> Result<(), String> {
675  if count == 0 {
676    return Err("`--count` must be greater than zero.".to_string());
677  }
678  let mut state = validate_cursor(snapshot_file, true)?;
679  let old_state = state.clone();
680  let (definition, _) = read_cursor_definition(snapshot_file, &state.target)?;
681  for completed in 0..count {
682    let Some(next) = depth_first_step(&definition, &state.path, forward)? else {
683      return Err(format!(
684        "Cannot move {} {count} structural node(s) from {}; reached the definition {} after {completed} step(s).",
685        if forward { "forward" } else { "backward" },
686        format_path(&old_state.path),
687        if forward { "end" } else { "start" }
688      ));
689    };
690    state.path = next;
691  }
692  commit_cursor_move(snapshot_file, old_state, state)
693}
694
695fn build_cursor_preview(snapshot_file: &str, state: &CursorState, view: &str) -> Result<Cirru, String> {
696  let (definition, node, _) = read_cursor_context(snapshot_file, &state.target, &state.path)?;
697  build_cursor_preview_from_tree(&definition, &node, &state.path, view)
698}
699
700fn build_cursor_preview_from_tree(definition: &Cirru, node: &Cirru, path: &[usize], view: &str) -> Result<Cirru, String> {
701  if view == "node" {
702    return Ok(Cirru::List(vec![Cirru::leaf("CURSOR"), node.clone()]));
703  }
704
705  if view == "focus" {
706    let options = cirru_parser::CirruFocusOptions::default()
707      .with_focus_marker("CURSOR")
708      .with_root_prefix(3);
709    Ok(cirru_parser::focus_cirru_preview_with_options(definition, path, &options))
710  } else {
711    let marker = Cirru::List(vec![Cirru::leaf("CURSOR"), node.clone()]);
712    apply_operation_at_path(definition, path, TreeOperation::Replace, Some(&marker))
713  }
714}
715
716fn render_cursor_human(state: &CursorState, document: &CursorDocument, status: &str, preview: &Cirru) -> Result<String, String> {
717  let rendered = cirru_parser::format(
718    std::slice::from_ref(preview),
719    cirru_parser::CirruWriterOptions { use_inline: false },
720  )
721  .map_err(|error| format!("Failed to render cursor preview: {error}"))?;
722  Ok(format!(
723    "{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}\n{}: {}/{}\n{}: {}\n\n{}",
724    "Target".green().bold(),
725    state.target,
726    "Path".green().bold(),
727    format_path(&state.path),
728    "Revision".green().bold(),
729    state.definition_revision,
730    "Status".green().bold(),
731    status,
732    "Anchor".green().bold(),
733    document
734      .anchor
735      .as_ref()
736      .map(|anchor| format!("{} {}", anchor.target, format_path(&anchor.path)))
737      .unwrap_or_else(|| "(none)".to_string()),
738    "Marks".green().bold(),
739    document.marks.len(),
740    CURSOR_MARK_LIMIT,
741    "Last query".green().bold(),
742    document
743      .last_query
744      .as_ref()
745      .map(|query| format!("{} #{}", query.command, query.selected_index))
746      .unwrap_or_else(|| "(none)".to_string()),
747    rendered
748  ))
749}
750
751fn push_bounded<T>(items: &mut Vec<T>, value: T, limit: usize) {
752  while items.len() >= limit && !items.is_empty() {
753    items.remove(0);
754  }
755  items.push(value);
756}
757
758#[derive(Clone, Copy)]
759enum RestoreSource {
760  History,
761}
762
763fn restore_cursor(snapshot_file: &str, source: RestoreSource, count: usize) -> Result<(), String> {
764  if count == 0 {
765    return Err("`--count` must be greater than zero.".to_string());
766  }
767  let mut document = load_cursor_document(snapshot_file)?;
768  let available = match source {
769    RestoreSource::History => document.history.len(),
770  };
771  if count > available {
772    return Err(format!(
773      "Cannot restore {count} cursor location(s); only {available} history entr{} available.",
774      if available == 1 { "y is" } else { "ies are" }
775    ));
776  }
777  let mut restored = None;
778  for _ in 0..count {
779    restored = Some(match source {
780      RestoreSource::History => document.history.pop().expect("history length checked"),
781    });
782  }
783  let restored = restored.expect("positive restore count");
784  let restored = relocate_saved_state(snapshot_file, restored)?;
785  document.active = restored.clone();
786  save_cursor_document(snapshot_file, &document)?;
787  let action = match source {
788    RestoreSource::History => "Cursor moved back",
789  };
790  println!(
791    "{} {action}{}: {} {}",
792    "✓".green(),
793    if count == 1 { String::new() } else { format!(" {count} steps") },
794    restored.target,
795    format_path(&restored.path)
796  );
797  emit_focus_after_cursor_action(snapshot_file, &restored, "cursor restored")
798}
799
800pub(crate) fn resolve_cursor_path_argument(snapshot_file: &str, target: &str, path: &str) -> Result<String, String> {
801  if path != "@cursor" {
802    return Ok(path.to_string());
803  }
804  let (cursor_target, cursor_path) = resolve_active_cursor_reference(snapshot_file)?;
805  if cursor_target != target {
806    return Err(format!(
807      "Cursor target mismatch: cursor points to '{cursor_target}', but command targets '{target}'."
808    ));
809  }
810  Ok(cursor_path)
811}
812
813pub(crate) fn resolve_cursor_target_argument(snapshot_file: &str, target: &str) -> Result<String, String> {
814  if target != "@cursor" {
815    return Ok(target.to_string());
816  }
817  Ok(resolve_active_cursor_reference(snapshot_file)?.0)
818}
819
820pub(crate) fn resolve_active_cursor_reference(snapshot_file: &str) -> Result<(String, String), String> {
821  let state = validate_cursor(snapshot_file, true)?;
822  let path = if state.path.is_empty() {
823    String::new()
824  } else {
825    format_path(&state.path)
826  };
827  Ok((state.target, path))
828}
829
830pub(crate) fn maintain_cursor_after_tree_mutation(
831  snapshot_file: &str,
832  target: &str,
833  mutation: &TreeCursorMutation,
834) -> Result<(), String> {
835  if std::env::var(CURSOR_MAINTENANCE_ENV).is_ok_and(|value| value == "disabled") {
836    return Ok(());
837  }
838  if !cursor_state_exists(snapshot_file) {
839    return Ok(());
840  }
841
842  let mut document = load_cursor_document(snapshot_file)?;
843  if document.active.target != target {
844    let has_auxiliary_target = document.anchor.as_ref().is_some_and(|state| state.target == target)
845      || document.marks.values().any(|state| state.target == target);
846    if !has_auxiliary_target {
847      return Ok(());
848    }
849  }
850
851  let snapshot = load_snapshot(snapshot_file)?;
852  let old_path = document.active.path.clone();
853  let mut note = "auxiliary cursor state updated";
854  if document.active.target == target {
855    let (new_path, active_note) = transform_cursor_path(&document.active.path, mutation);
856    document.active.path = new_path;
857    note = active_note;
858    refresh_cursor_state_from_snapshot(&mut document.active, snapshot_file, &snapshot).map_err(|error| {
859      format!("Snapshot mutation succeeded, but cursor maintenance failed: {error}. Run `calcit cursor set` to select it again.")
860    })?;
861  }
862  transform_auxiliary_positions(&mut document, target, snapshot_file, &snapshot, |path| {
863    transform_cursor_path(path, mutation).0
864  })?;
865  save_cursor_document(snapshot_file, &document).map_err(|error| {
866    format!("Snapshot mutation succeeded, but cursor state could not be saved: {error}. Run `calcit cursor show` before editing again.")
867  })?;
868
869  let detail = if document.active.target != target {
870    note.to_string()
871  } else if old_path != document.active.path {
872    format!("{} → {} ({note})", format_path(&old_path), format_path(&document.active.path))
873  } else {
874    format!("{} ({note})", format_path(&document.active.path))
875  };
876  emit_cursor_after(snapshot_file, &document.active, &detail)?;
877  Ok(())
878}
879
880pub(crate) fn maintain_cursor_after_definition_move(snapshot_file: &str, source: &str, target: &str) -> Result<(), String> {
881  if std::env::var(CURSOR_MAINTENANCE_ENV).is_ok_and(|value| value == "disabled") || !cursor_state_exists(snapshot_file) {
882    return Ok(());
883  }
884  let mut document = load_cursor_document(snapshot_file)?;
885  let has_auxiliary_target =
886    document.anchor.as_ref().is_some_and(|state| state.target == source) || document.marks.values().any(|state| state.target == source);
887  if document.active.target != source && !has_auxiliary_target {
888    return Ok(());
889  }
890  let snapshot = load_snapshot(snapshot_file)?;
891  if document.active.target == source {
892    document.active.target = target.to_string();
893    refresh_cursor_state_from_snapshot(&mut document.active, snapshot_file, &snapshot).map_err(|error| {
894      format!("Definition move succeeded, but cursor maintenance failed: {error}. Run `calcit cursor set` to select it again.")
895    })?;
896  }
897  retarget_auxiliary_positions(&mut document, source, target, snapshot_file, &snapshot)?;
898  save_cursor_document(snapshot_file, &document)?;
899  emit_cursor_after(snapshot_file, &document.active, &format!("target updated: {source} → {target}"))
900}
901
902fn transform_auxiliary_positions<F>(
903  document: &mut CursorDocument,
904  target: &str,
905  snapshot_file: &str,
906  snapshot: &snapshot::Snapshot,
907  transform: F,
908) -> Result<(), String>
909where
910  F: Fn(&[usize]) -> Vec<usize>,
911{
912  if let Some(anchor) = document.anchor.as_mut()
913    && anchor.target == target
914  {
915    let mut updated = anchor.clone();
916    updated.path = transform(&updated.path);
917    match refresh_cursor_state_from_snapshot(&mut updated, snapshot_file, snapshot) {
918      Ok(()) => *anchor = updated,
919      Err(error) => eprintln!("{} Retained stale cursor anchor: {error}", "[Cursor]".yellow().bold()),
920    }
921  }
922  for (name, mark) in &mut document.marks {
923    if mark.target == target {
924      let mut updated = mark.clone();
925      updated.path = transform(&updated.path);
926      match refresh_cursor_state_from_snapshot(&mut updated, snapshot_file, snapshot) {
927        Ok(()) => *mark = updated,
928        Err(error) => {
929          eprintln!("{} Retained stale cursor mark '{name}': {error}", "[Cursor]".yellow().bold());
930        }
931      }
932    }
933  }
934  Ok(())
935}
936
937fn retarget_auxiliary_positions(
938  document: &mut CursorDocument,
939  source: &str,
940  target: &str,
941  snapshot_file: &str,
942  snapshot: &snapshot::Snapshot,
943) -> Result<(), String> {
944  if let Some(anchor) = document.anchor.as_mut()
945    && anchor.target == source
946  {
947    let mut updated = anchor.clone();
948    updated.target = target.to_string();
949    match refresh_cursor_state_from_snapshot(&mut updated, snapshot_file, snapshot) {
950      Ok(()) => *anchor = updated,
951      Err(error) => eprintln!("{} Retained stale cursor anchor: {error}", "[Cursor]".yellow().bold()),
952    }
953  }
954  for (name, mark) in &mut document.marks {
955    if mark.target == source {
956      let mut updated = mark.clone();
957      updated.target = target.to_string();
958      match refresh_cursor_state_from_snapshot(&mut updated, snapshot_file, snapshot) {
959        Ok(()) => *mark = updated,
960        Err(error) => {
961          eprintln!("{} Retained stale cursor mark '{name}': {error}", "[Cursor]".yellow().bold());
962        }
963      }
964    }
965  }
966  Ok(())
967}
968
969pub(crate) fn maintain_cursor_after_definition_replace(snapshot_file: &str, target: &str) -> Result<(), String> {
970  maintain_cursor_after_tree_mutation(snapshot_file, target, &TreeCursorMutation::Replace { path: vec![] })
971}
972
973pub(crate) fn maintain_cursor_after_definition_delete(snapshot_file: &str, target: &str) -> Result<(), String> {
974  if std::env::var(CURSOR_MAINTENANCE_ENV).is_ok_and(|value| value == "disabled") || !cursor_state_exists(snapshot_file) {
975    return Ok(());
976  }
977  let document = load_cursor_document(snapshot_file)?;
978  if document.active.target == target && CURSOR_AFTER_MODE.load(Ordering::Relaxed) != 0 {
979    eprintln!(
980      "{} Selected definition '{target}' was deleted; the cursor is stale. Use `calcit cursor move back` or `calcit cursor set`.",
981      "[Cursor]".yellow().bold()
982    );
983  }
984  Ok(())
985}
986
987pub(crate) fn maintain_cursor_after_namespace_delete(snapshot_file: &str, namespace: &str) -> Result<(), String> {
988  if std::env::var(CURSOR_MAINTENANCE_ENV).is_ok_and(|value| value == "disabled") || !cursor_state_exists(snapshot_file) {
989    return Ok(());
990  }
991  let document = load_cursor_document(snapshot_file)?;
992  let cursor_namespace = parse_target(&document.active.target)?.0;
993  if cursor_namespace == namespace && CURSOR_AFTER_MODE.load(Ordering::Relaxed) != 0 {
994    eprintln!(
995      "{} Selected namespace '{namespace}' was deleted; the cursor is stale. Use `calcit cursor move back` or `calcit cursor set`.",
996      "[Cursor]".yellow().bold()
997    );
998  }
999  Ok(())
1000}
1001
1002pub(crate) fn maintain_cursor_after_split_definition(
1003  snapshot_file: &str,
1004  source: &str,
1005  split_path: &[usize],
1006  target: &str,
1007) -> Result<(), String> {
1008  if std::env::var(CURSOR_MAINTENANCE_ENV).is_ok_and(|value| value == "disabled") || !cursor_state_exists(snapshot_file) {
1009    return Ok(());
1010  }
1011  let mut document = load_cursor_document(snapshot_file)?;
1012  if document.active.target != source {
1013    return Ok(());
1014  }
1015  let detail = if document.active.path.starts_with(split_path) {
1016    document.active.target = target.to_string();
1017    document.active.path = document.active.path[split_path.len()..].to_vec();
1018    format!("followed extracted subtree: {source} → {target}")
1019  } else {
1020    document.active.path = transform_cursor_path(&document.active.path, &TreeCursorMutation::Replace { path: split_path.to_vec() }).0;
1021    "split expression replaced by new definition reference".to_string()
1022  };
1023  refresh_cursor_state(&mut document.active, snapshot_file)?;
1024  save_cursor_document(snapshot_file, &document)?;
1025  emit_cursor_after(snapshot_file, &document.active, &detail)
1026}
1027
1028pub(crate) fn maintain_cursor_after_node_move(
1029  snapshot_file: &str,
1030  target: &str,
1031  source_path: &[usize],
1032  destination_path: &[usize],
1033  operation: TreeOperation,
1034  append_index: usize,
1035) -> Result<(), String> {
1036  if std::env::var(CURSOR_MAINTENANCE_ENV).is_ok_and(|value| value == "disabled") || !cursor_state_exists(snapshot_file) {
1037    return Ok(());
1038  }
1039  let mut document = load_cursor_document(snapshot_file)?;
1040  if document.active.target != target {
1041    return Ok(());
1042  }
1043
1044  let inserted_path = operation.inserted_path(destination_path, append_index)?;
1045  let insertion = operation.cursor_mutation(destination_path.to_vec());
1046  let adjusted_source = adjusted_source_path_after_insertion(source_path, destination_path, operation);
1047  let next_path = if document.active.path.starts_with(source_path) {
1048    let mut moved = inserted_path;
1049    moved.extend_from_slice(&document.active.path[source_path.len()..]);
1050    transform_delete(&moved, &adjusted_source).0
1051  } else {
1052    let after_insert = transform_cursor_path(&document.active.path, &insertion).0;
1053    transform_delete(&after_insert, &adjusted_source).0
1054  };
1055  document.active.path = next_path;
1056  refresh_cursor_state(&mut document.active, snapshot_file)?;
1057  save_cursor_document(snapshot_file, &document)?;
1058  emit_cursor_after(snapshot_file, &document.active, "cursor followed node move")
1059}
1060
1061pub(crate) fn maintain_cursor_after_any_mutation(snapshot_file: &str, detail: &str) -> Result<(), String> {
1062  if std::env::var(CURSOR_MAINTENANCE_ENV).is_ok_and(|value| value == "disabled") || !cursor_state_exists(snapshot_file) {
1063    return Ok(());
1064  }
1065  match validate_cursor(snapshot_file, true) {
1066    Ok(state) => emit_cursor_after(snapshot_file, &state, detail),
1067    Err(error) => {
1068      if CURSOR_AFTER_MODE.load(Ordering::Relaxed) != 0 {
1069        eprintln!(
1070          "{} Transaction committed, but the cursor needs attention: {error} Use `calcit cursor move back` or `calcit cursor set`.",
1071          "[Cursor]".yellow().bold()
1072        );
1073      }
1074      Ok(())
1075    }
1076  }
1077}
1078
1079fn emit_focus_after_cursor_action(snapshot_file: &str, state: &CursorState, detail: &str) -> Result<(), String> {
1080  if CURSOR_AFTER_MODE.load(Ordering::Relaxed) == 2 {
1081    emit_cursor_after(snapshot_file, state, detail)
1082  } else {
1083    Ok(())
1084  }
1085}
1086
1087fn emit_cursor_after(snapshot_file: &str, state: &CursorState, detail: &str) -> Result<(), String> {
1088  match CURSOR_AFTER_MODE.load(Ordering::Relaxed) {
1089    0 => Ok(()),
1090    1 => {
1091      eprintln!(
1092        "{} {} {} — {detail}",
1093        "[Cursor]".cyan().bold(),
1094        state.target,
1095        format_path(&state.path)
1096      );
1097      Ok(())
1098    }
1099    2 => {
1100      let preview = build_cursor_preview(snapshot_file, state, "focus")?;
1101      let rendered = cirru_parser::format(
1102        std::slice::from_ref(&preview),
1103        cirru_parser::CirruWriterOptions { use_inline: false },
1104      )
1105      .map_err(|error| format!("Failed to render automatic cursor preview: {error}"))?;
1106      eprintln!(
1107        "{} {} {} — {detail}\n{}",
1108        "[Cursor]".cyan().bold(),
1109        state.target,
1110        format_path(&state.path),
1111        rendered
1112      );
1113      Ok(())
1114    }
1115    _ => unreachable!(),
1116  }
1117}
1118
1119fn cursor_file_path(snapshot_file: &str) -> PathBuf {
1120  project_state::state_file_for_snapshot(snapshot_file, CURSOR_STATE_FILE)
1121}
1122
1123fn legacy_cursor_file_path(snapshot_file: &str) -> PathBuf {
1124  project_state::project_directory_for_snapshot(snapshot_file).join(LEGACY_CURSOR_FILE)
1125}
1126
1127fn migrate_legacy_cursor(snapshot_file: &str) -> Result<bool, String> {
1128  let legacy = legacy_cursor_file_path(snapshot_file);
1129  let destination = cursor_file_path(snapshot_file);
1130  project_state::migrate_legacy_file(&legacy, &destination).map_err(|error| {
1131    format!(
1132      "Failed to migrate legacy cursor file '{}' to '{}': {error}",
1133      legacy.display(),
1134      destination.display()
1135    )
1136  })
1137}
1138
1139fn cursor_state_exists(snapshot_file: &str) -> bool {
1140  cursor_file_path(snapshot_file).exists() || legacy_cursor_file_path(snapshot_file).exists()
1141}
1142
1143fn node_fingerprint(node: &Cirru) -> String {
1144  let encoded = cirru_to_json_value(node).to_string();
1145  let mut hasher = Md5::new();
1146  hasher.update(encoded.as_bytes());
1147  format!("md5:{}", hex::encode(hasher.finalize()))
1148}
1149
1150fn read_cursor_context(snapshot_file: &str, target: &str, path: &[usize]) -> Result<(Cirru, Cirru, String), String> {
1151  let (namespace, definition_name) = parse_target(target)?;
1152  let snapshot = load_snapshot(snapshot_file)?;
1153  let file = snapshot
1154    .files
1155    .get(namespace)
1156    .ok_or_else(|| format!("Cursor namespace '{namespace}' no longer exists."))?;
1157  let entry = file
1158    .defs
1159    .get(definition_name)
1160    .ok_or_else(|| format!("Cursor definition '{target}' no longer exists."))?;
1161  let node = navigate_to_path(&entry.code, path)
1162    .map_err(|error| format!("Cursor path {} is no longer valid in '{}': {error}", format_path(path), target))?;
1163  Ok((entry.code.clone(), node, snapshot::definition_revision(entry)?))
1164}
1165
1166fn read_cursor_target(snapshot_file: &str, target: &str, path: &[usize]) -> Result<(Cirru, String), String> {
1167  let (_, node, revision) = read_cursor_context(snapshot_file, target, path)?;
1168  Ok((node, revision))
1169}
1170
1171fn read_cursor_definition(snapshot_file: &str, target: &str) -> Result<(Cirru, String), String> {
1172  let (namespace, definition) = parse_target(target)?;
1173  let snapshot = load_snapshot(snapshot_file)?;
1174  let file = snapshot
1175    .files
1176    .get(namespace)
1177    .ok_or_else(|| format!("Cursor namespace '{namespace}' no longer exists."))?;
1178  let entry = file
1179    .defs
1180    .get(definition)
1181    .ok_or_else(|| format!("Cursor definition '{target}' no longer exists."))?;
1182  Ok((entry.code.clone(), snapshot::definition_revision(entry)?))
1183}
1184
1185fn refresh_cursor_state(state: &mut CursorState, snapshot_file: &str) -> Result<(), String> {
1186  let snapshot = load_snapshot(snapshot_file)?;
1187  refresh_cursor_state_from_snapshot(state, snapshot_file, &snapshot)
1188}
1189
1190fn refresh_cursor_state_from_snapshot(state: &mut CursorState, snapshot_file: &str, value: &snapshot::Snapshot) -> Result<(), String> {
1191  let (namespace, definition_name) = parse_target(&state.target)?;
1192  let file = value
1193    .files
1194    .get(namespace)
1195    .ok_or_else(|| format!("Cursor namespace '{namespace}' no longer exists."))?;
1196  let entry = file
1197    .defs
1198    .get(definition_name)
1199    .ok_or_else(|| format!("Cursor definition '{}' no longer exists.", state.target))?;
1200  let node = navigate_to_path(&entry.code, &state.path).map_err(|error| {
1201    format!(
1202      "Cursor path {} is no longer valid in '{}': {error}",
1203      format_path(&state.path),
1204      state.target
1205    )
1206  })?;
1207  state.snapshot = snapshot_file.to_string();
1208  state.definition_revision = snapshot::definition_revision(entry)?;
1209  state.fingerprint = node_fingerprint(&node);
1210  Ok(())
1211}
1212
1213fn validate_cursor(snapshot_file: &str, announce: bool) -> Result<CursorState, String> {
1214  Ok(validate_cursor_with_status(snapshot_file, announce)?.0)
1215}
1216
1217fn validate_cursor_with_status(snapshot_file: &str, announce: bool) -> Result<(CursorState, &'static str), String> {
1218  let mut document = load_cursor_document(snapshot_file)?;
1219  let mut state = document.active.clone();
1220  let (namespace, definition) = parse_target(&state.target)?;
1221  let snapshot = load_snapshot(snapshot_file)?;
1222  let file = snapshot
1223    .files
1224    .get(namespace)
1225    .ok_or_else(|| format!("Cursor namespace '{namespace}' no longer exists."))?;
1226  let entry = file
1227    .defs
1228    .get(definition)
1229    .ok_or_else(|| format!("Cursor definition '{}' no longer exists.", state.target))?;
1230
1231  if let Ok(node) = navigate_to_path(&entry.code, &state.path)
1232    && node_fingerprint(&node) == state.fingerprint
1233  {
1234    let revision = snapshot::definition_revision(entry)?;
1235    let status = if state.definition_revision != revision || state.snapshot != snapshot_file {
1236      "verified-at-path"
1237    } else {
1238      "exact"
1239    };
1240    if state.definition_revision != revision || state.snapshot != snapshot_file {
1241      state.definition_revision = revision;
1242      state.snapshot = snapshot_file.to_string();
1243      document.active = state.clone();
1244      save_cursor_document(snapshot_file, &document)?;
1245    }
1246    return Ok((state, status));
1247  }
1248
1249  let mut matches = vec![];
1250  collect_fingerprint_paths(&entry.code, &state.fingerprint, &mut vec![], &mut matches);
1251  if matches.len() == 1 {
1252    let old_path = state.path.clone();
1253    state.path = matches.remove(0);
1254    refresh_cursor_state(&mut state, snapshot_file)?;
1255    document.active = state.clone();
1256    save_cursor_document(snapshot_file, &document)?;
1257    if announce {
1258      eprintln!(
1259        "{} Cursor relocated: {} → {} after external tree changes",
1260        "[Cursor]".cyan().bold(),
1261        format_path(&old_path),
1262        format_path(&state.path)
1263      );
1264    }
1265    Ok((state, "relocated"))
1266  } else {
1267    Err(format!(
1268      "Cursor is stale: saved node at {} in '{}' has {} fingerprint match(es). Refusing to guess; run `calcit cursor set <target> --path <path>`.",
1269      format_path(&state.path),
1270      state.target,
1271      matches.len()
1272    ))
1273  }
1274}
1275
1276fn relocate_saved_state(snapshot_file: &str, state: CursorState) -> Result<CursorState, String> {
1277  let snapshot = load_snapshot(snapshot_file)?;
1278  relocate_saved_state_from_snapshot(snapshot_file, state, &snapshot)
1279}
1280
1281fn relocate_saved_state_from_snapshot(
1282  snapshot_file: &str,
1283  mut state: CursorState,
1284  snapshot: &snapshot::Snapshot,
1285) -> Result<CursorState, String> {
1286  let (namespace, definition_name) = parse_target(&state.target)?;
1287  let definition = &snapshot
1288    .files
1289    .get(namespace)
1290    .ok_or_else(|| format!("Saved cursor namespace '{namespace}' no longer exists."))?
1291    .defs
1292    .get(definition_name)
1293    .ok_or_else(|| format!("Saved cursor definition '{}' no longer exists.", state.target))?
1294    .code;
1295  if let Ok(node) = navigate_to_path(definition, &state.path)
1296    && node_fingerprint(&node) == state.fingerprint
1297  {
1298    refresh_cursor_state_from_snapshot(&mut state, snapshot_file, snapshot)?;
1299    return Ok(state);
1300  }
1301
1302  let mut matches = vec![];
1303  collect_fingerprint_paths(definition, &state.fingerprint, &mut vec![], &mut matches);
1304  if matches.len() != 1 {
1305    return Err(format!(
1306      "Saved cursor location {} in '{}' has {} fingerprint match(es); refusing to restore ambiguously.",
1307      format_path(&state.path),
1308      state.target,
1309      matches.len()
1310    ));
1311  }
1312  state.path = matches.remove(0);
1313  refresh_cursor_state_from_snapshot(&mut state, snapshot_file, snapshot)?;
1314  Ok(state)
1315}
1316
1317fn collect_fingerprint_paths(node: &Cirru, fingerprint: &str, path: &mut Vec<usize>, output: &mut Vec<Vec<usize>>) {
1318  if node_fingerprint(node) == fingerprint {
1319    output.push(path.clone());
1320  }
1321  if let Cirru::List(children) = node {
1322    for (index, child) in children.iter().enumerate() {
1323      path.push(index);
1324      collect_fingerprint_paths(child, fingerprint, path, output);
1325      path.pop();
1326    }
1327  }
1328}
1329
1330fn load_cursor_document_optional(snapshot_file: &str) -> Result<Option<CursorDocument>, String> {
1331  if migrate_legacy_cursor(snapshot_file)? {
1332    eprintln!(
1333      "{} Moved legacy cursor state into '{}'.",
1334      "[Cursor]".cyan().bold(),
1335      cursor_file_path(snapshot_file).display()
1336    );
1337  }
1338  let file = cursor_file_path(snapshot_file);
1339  let content = match fs::read_to_string(&file) {
1340    Ok(content) => content,
1341    Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1342    Err(error) => return Err(format!("Failed to read cursor file '{}': {error}", file.display())),
1343  };
1344  let edn = cirru_edn::parse(&content).map_err(|error| format!("Failed to parse cursor Cirru EDN '{}': {error}", file.display()))?;
1345  let root = edn.view_map().map_err(|error| format!("Cursor root must be a map: {error}"))?;
1346  let version = root
1347    .tag_get("schema-version")
1348    .ok_or("Cursor file is missing :schema-version")?
1349    .read_number()?;
1350  if ![1.0, 2.0, 3.0, f64::from(CURSOR_SCHEMA_VERSION)]
1351    .iter()
1352    .any(|supported| (version - supported).abs() <= f64::EPSILON)
1353  {
1354    return Err(format!("Unsupported cursor schema version {version}."));
1355  }
1356  let active_name = root
1357    .tag_get("active")
1358    .ok_or("Cursor file is missing :active")?
1359    .read_tag_str()?
1360    .to_string();
1361  let cursors = root.tag_get("cursors").ok_or("Cursor file is missing :cursors")?.view_map()?;
1362  let mut cursor_states = cursors
1363    .0
1364    .iter()
1365    .map(|(name, value)| Ok((name.read_tag_str()?.to_string(), cursor_state_from_edn(value)?)))
1366    .collect::<Result<BTreeMap<_, _>, String>>()?;
1367  let active = cursor_states
1368    .remove(&active_name)
1369    .ok_or_else(|| format!("Cursor file has no entry for active cursor :{active_name}"))?;
1370  let history = optional_state_list(&root, "history")?;
1371  let stack = optional_state_list(&root, "stack")?;
1372  let anchor = match root.tag_get("anchor") {
1373    None | Some(Edn::Nil) => None,
1374    Some(value) => Some(cursor_state_from_edn(value)?),
1375  };
1376  let marks = optional_marks(&root)?;
1377  let last_query = match root.tag_get("last-query") {
1378    None | Some(Edn::Nil) => None,
1379    Some(value) => Some(cursor_last_query_from_edn(value)?),
1380  };
1381  let clipboard = match root.tag_get("clipboard") {
1382    None | Some(Edn::Nil) => None,
1383    Some(value) => Some(cursor_clipboard_from_edn(value)?),
1384  };
1385
1386  Ok(Some(CursorDocument {
1387    active_name,
1388    active,
1389    inactive_cursors: cursor_states,
1390    history,
1391    stack,
1392    anchor,
1393    marks,
1394    last_query,
1395    clipboard,
1396  }))
1397}
1398
1399fn load_cursor_document(snapshot_file: &str) -> Result<CursorDocument, String> {
1400  load_cursor_document_optional(snapshot_file)?.ok_or_else(|| {
1401    format!(
1402      "No cursor is set. Use `calcit cursor set <target> --path <path>` first (expected '{}').",
1403      cursor_file_path(snapshot_file).display()
1404    )
1405  })
1406}
1407
1408#[cfg(test)]
1409fn load_cursor_state(snapshot_file: &str) -> Result<CursorState, String> {
1410  Ok(load_cursor_document(snapshot_file)?.active)
1411}
1412
1413fn cursor_state_from_edn(value: &Edn) -> Result<CursorState, String> {
1414  let entry = value.view_map()?;
1415  let section = entry.tag_get("section").ok_or("Cursor entry is missing :section")?.read_tag_str()?;
1416  if section.as_ref() != "code" {
1417    return Err(format!("Unsupported cursor section :{section}; expected :code."));
1418  }
1419  let path = entry
1420    .tag_get("path")
1421    .ok_or("Cursor entry is missing :path")?
1422    .view_list()?
1423    .0
1424    .iter()
1425    .map(|value| {
1426      let number = value.read_number()?;
1427      if number < 0.0 || number.fract().abs() > f64::EPSILON {
1428        Err(format!("Cursor path index must be a non-negative integer, got {number}."))
1429      } else {
1430        Ok(number as usize)
1431      }
1432    })
1433    .collect::<Result<Vec<_>, _>>()?;
1434
1435  Ok(CursorState {
1436    snapshot: required_string(&entry, "snapshot")?,
1437    target: required_string(&entry, "target")?,
1438    path,
1439    definition_revision: required_string(&entry, "definition-revision")?,
1440    fingerprint: required_string(&entry, "fingerprint")?,
1441  })
1442}
1443
1444fn cursor_clipboard_from_edn(value: &Edn) -> Result<CursorClipboard, String> {
1445  let entry = value.view_map()?;
1446  Ok(CursorClipboard {
1447    mode: required_string(&entry, "mode")?,
1448    source_target: required_string(&entry, "source-target")?,
1449    source_path: required_path(&entry, "source-path")?,
1450    fingerprint: required_string(&entry, "fingerprint")?,
1451    tree: entry
1452      .tag_get("tree")
1453      .ok_or("Cursor clipboard is missing :tree")?
1454      .read_quoted_cirru()?,
1455  })
1456}
1457
1458fn cursor_last_query_from_edn(value: &Edn) -> Result<CursorLastQuery, String> {
1459  let entry = value.view_map()?;
1460  Ok(CursorLastQuery {
1461    command: required_string(&entry, "command")?,
1462    pattern: required_string(&entry, "pattern")?,
1463    filter: optional_string(&entry, "filter")?,
1464    exact: required_bool(&entry, "exact")?,
1465    regex: required_bool(&entry, "regex")?,
1466    max_depth: required_usize(&entry, "max-depth")?,
1467    start_path: optional_string(&entry, "start-path")?,
1468    entry: optional_string(&entry, "entry")?,
1469    source: optional_string(&entry, "source")?.unwrap_or_else(|| "all".to_owned()),
1470    pattern_is_json: required_bool(&entry, "pattern-is-json")?,
1471    selected_index: required_usize(&entry, "selected-index")?,
1472    snapshot_revision: required_string(&entry, "snapshot-revision")?,
1473  })
1474}
1475
1476fn validate_mark_name(name: &str) -> Result<(), String> {
1477  if name.is_empty()
1478    || name.len() > 32
1479    || !name
1480      .chars()
1481      .all(|character| character.is_ascii_alphanumeric() || matches!(character, '_' | '-'))
1482  {
1483    return Err("Mark name must contain 1..32 ASCII letters, digits, underscores, or hyphens.".to_string());
1484  }
1485  Ok(())
1486}
1487
1488fn optional_marks(map: &cirru_edn::EdnMapView) -> Result<BTreeMap<String, CursorState>, String> {
1489  let Some(value) = map.tag_get("marks") else {
1490    return Ok(BTreeMap::new());
1491  };
1492  let values = value.view_map()?;
1493  if values.0.len() > CURSOR_MARK_LIMIT {
1494    return Err(format!(
1495      "Cursor file contains {} marks, exceeding the supported limit of {CURSOR_MARK_LIMIT}.",
1496      values.0.len()
1497    ));
1498  }
1499  values
1500    .0
1501    .iter()
1502    .map(|(key, value)| {
1503      let name = key.read_tag_str()?.to_string();
1504      validate_mark_name(&name)?;
1505      Ok((name, cursor_state_from_edn(value)?))
1506    })
1507    .collect()
1508}
1509
1510fn optional_state_list(map: &cirru_edn::EdnMapView, key: &str) -> Result<Vec<CursorState>, String> {
1511  let Some(value) = map.tag_get(key) else {
1512    return Ok(vec![]);
1513  };
1514  value
1515    .view_list()?
1516    .0
1517    .iter()
1518    .map(cursor_state_from_edn)
1519    .collect::<Result<Vec<_>, _>>()
1520}
1521
1522fn required_path(map: &cirru_edn::EdnMapView, key: &str) -> Result<Vec<usize>, String> {
1523  map
1524    .tag_get(key)
1525    .ok_or_else(|| format!("Cursor entry is missing :{key}"))?
1526    .view_list()?
1527    .0
1528    .iter()
1529    .map(|value| {
1530      let number = value.read_number()?;
1531      if number < 0.0 || number.fract().abs() > f64::EPSILON {
1532        Err(format!("Cursor path index must be a non-negative integer, got {number}."))
1533      } else {
1534        Ok(number as usize)
1535      }
1536    })
1537    .collect::<Result<Vec<_>, _>>()
1538}
1539
1540fn required_string(map: &cirru_edn::EdnMapView, key: &str) -> Result<String, String> {
1541  map
1542    .tag_get(key)
1543    .ok_or_else(|| format!("Cursor entry is missing :{key}"))?
1544    .read_string()
1545}
1546
1547fn optional_string(map: &cirru_edn::EdnMapView, key: &str) -> Result<Option<String>, String> {
1548  match map.tag_get(key) {
1549    None | Some(Edn::Nil) => Ok(None),
1550    Some(value) => value.read_string().map(Some),
1551  }
1552}
1553
1554fn required_bool(map: &cirru_edn::EdnMapView, key: &str) -> Result<bool, String> {
1555  match map.tag_get(key) {
1556    Some(Edn::Bool(value)) => Ok(*value),
1557    Some(value) => Err(format!("Cursor entry :{key} must be a boolean, got {value:?}.")),
1558    None => Err(format!("Cursor entry is missing :{key}")),
1559  }
1560}
1561
1562fn required_usize(map: &cirru_edn::EdnMapView, key: &str) -> Result<usize, String> {
1563  let number = map
1564    .tag_get(key)
1565    .ok_or_else(|| format!("Cursor entry is missing :{key}"))?
1566    .read_number()?;
1567  if number < 0.0 || number.fract().abs() > f64::EPSILON {
1568    Err(format!("Cursor entry :{key} must be a non-negative integer, got {number}."))
1569  } else {
1570    Ok(number as usize)
1571  }
1572}
1573
1574fn cursor_state_to_edn(state: &CursorState) -> Edn {
1575  Edn::map_from_iter([
1576    (Edn::tag("snapshot"), Edn::str(state.snapshot.as_str())),
1577    (Edn::tag("target"), Edn::str(state.target.as_str())),
1578    (Edn::tag("section"), Edn::tag("code")),
1579    (
1580      Edn::tag("path"),
1581      Edn::List(EdnListView(state.path.iter().copied().map(Edn::from).collect())),
1582    ),
1583    (Edn::tag("definition-revision"), Edn::str(state.definition_revision.as_str())),
1584    (Edn::tag("fingerprint"), Edn::str(state.fingerprint.as_str())),
1585  ])
1586}
1587
1588fn cursor_clipboard_to_edn(clipboard: &CursorClipboard) -> Edn {
1589  Edn::map_from_iter([
1590    (Edn::tag("mode"), Edn::str(clipboard.mode.as_str())),
1591    (Edn::tag("source-target"), Edn::str(clipboard.source_target.as_str())),
1592    (
1593      Edn::tag("source-path"),
1594      Edn::List(EdnListView(clipboard.source_path.iter().copied().map(Edn::from).collect())),
1595    ),
1596    (Edn::tag("fingerprint"), Edn::str(clipboard.fingerprint.as_str())),
1597    (Edn::tag("tree"), Edn::Quote(clipboard.tree.clone())),
1598  ])
1599}
1600
1601fn cursor_last_query_to_edn(query: &CursorLastQuery) -> Edn {
1602  Edn::map_from_iter([
1603    (Edn::tag("command"), Edn::str(query.command.as_str())),
1604    (Edn::tag("pattern"), Edn::str(query.pattern.as_str())),
1605    (
1606      Edn::tag("filter"),
1607      query.filter.as_ref().map(|value| Edn::str(value.as_str())).unwrap_or(Edn::Nil),
1608    ),
1609    (Edn::tag("exact"), Edn::Bool(query.exact)),
1610    (Edn::tag("regex"), Edn::Bool(query.regex)),
1611    (Edn::tag("max-depth"), Edn::from(query.max_depth)),
1612    (
1613      Edn::tag("start-path"),
1614      query.start_path.as_ref().map(|value| Edn::str(value.as_str())).unwrap_or(Edn::Nil),
1615    ),
1616    (
1617      Edn::tag("entry"),
1618      query.entry.as_ref().map(|value| Edn::str(value.as_str())).unwrap_or(Edn::Nil),
1619    ),
1620    (Edn::tag("source"), Edn::str(query.source.as_str())),
1621    (Edn::tag("pattern-is-json"), Edn::Bool(query.pattern_is_json)),
1622    (Edn::tag("selected-index"), Edn::from(query.selected_index)),
1623    (Edn::tag("snapshot-revision"), Edn::str(query.snapshot_revision.as_str())),
1624  ])
1625}
1626
1627#[cfg(test)]
1628fn save_cursor_state(snapshot_file: &str, state: &CursorState) -> Result<(), String> {
1629  let mut document = load_cursor_document_optional(snapshot_file)?.unwrap_or_else(|| CursorDocument {
1630    active_name: DEFAULT_CURSOR.to_string(),
1631    active: state.clone(),
1632    inactive_cursors: BTreeMap::new(),
1633    history: vec![],
1634    stack: vec![],
1635    anchor: None,
1636    marks: BTreeMap::new(),
1637    last_query: None,
1638    clipboard: None,
1639  });
1640  document.active = state.clone();
1641  save_cursor_document(snapshot_file, &document)
1642}
1643
1644fn render_cursor_document(document: &CursorDocument) -> Result<String, String> {
1645  let mut cursors = document.inactive_cursors.clone();
1646  cursors.insert(document.active_name.clone(), document.active.clone());
1647  let mut content = cirru_edn::format(
1648    &Edn::map_from_iter([
1649      (Edn::tag("schema-version"), Edn::from(CURSOR_SCHEMA_VERSION)),
1650      (Edn::tag("active"), Edn::tag(document.active_name.as_str())),
1651      (
1652        Edn::tag("cursors"),
1653        Edn::map_from_iter(
1654          cursors
1655            .iter()
1656            .map(|(name, state)| (Edn::tag(name.as_str()), cursor_state_to_edn(state))),
1657        ),
1658      ),
1659      (
1660        Edn::tag("history"),
1661        Edn::List(EdnListView(document.history.iter().map(cursor_state_to_edn).collect())),
1662      ),
1663      (
1664        Edn::tag("stack"),
1665        Edn::List(EdnListView(document.stack.iter().map(cursor_state_to_edn).collect())),
1666      ),
1667      (
1668        Edn::tag("anchor"),
1669        document.anchor.as_ref().map(cursor_state_to_edn).unwrap_or(Edn::Nil),
1670      ),
1671      (
1672        Edn::tag("marks"),
1673        Edn::map_from_iter(
1674          document
1675            .marks
1676            .iter()
1677            .map(|(name, state)| (Edn::tag(name.as_str()), cursor_state_to_edn(state))),
1678        ),
1679      ),
1680      (
1681        Edn::tag("last-query"),
1682        document.last_query.as_ref().map(cursor_last_query_to_edn).unwrap_or(Edn::Nil),
1683      ),
1684      (
1685        Edn::tag("clipboard"),
1686        document.clipboard.as_ref().map(cursor_clipboard_to_edn).unwrap_or(Edn::Nil),
1687      ),
1688    ]),
1689    false,
1690  )
1691  .map_err(|error| format!("Failed to format cursor Cirru EDN: {error}"))?;
1692  content.push('\n');
1693  if content.len() > CURSOR_FILE_MAX_BYTES {
1694    return Err(format!(
1695      "Cursor state is {} bytes, exceeding the {} byte limit. Back up the cursor file. Before clearing, check whether a `:clipboard` cut was already pasted and recover any pending tree as described in docs/run/upgrade.md. Then run `calcit cursor clear` and select the target again with `calcit cursor set`.",
1696      content.len(),
1697      CURSOR_FILE_MAX_BYTES
1698    ));
1699  }
1700  Ok(content)
1701}
1702
1703fn stage_cursor_document(snapshot_file: &str, document: &CursorDocument) -> Result<StagedFile, String> {
1704  let destination = cursor_file_path(snapshot_file);
1705  let content = render_cursor_document(document)?;
1706  stage_atomic_file(&destination, content.as_bytes(), "cursor")
1707}
1708
1709fn stage_snapshot(snapshot_file: &str, value: &snapshot::Snapshot) -> Result<StagedFile, String> {
1710  let content = snapshot::render_snapshot_content(value)?;
1711  stage_atomic_file(Path::new(snapshot_file), content.as_bytes(), "snapshot")
1712}
1713
1714fn commit_snapshot_then_cursor_staged_files(
1715  staged_snapshot: StagedFile,
1716  staged_cursor: StagedFile,
1717  action: &str,
1718  clipboard_available: bool,
1719) -> Result<(), String> {
1720  staged_snapshot
1721    .commit()
1722    .map_err(|error| format!("{action} was not applied: {error}"))?;
1723  staged_cursor.commit().map_err(|error| {
1724    format!(
1725      "{action} succeeded in the snapshot, but cursor state could not be updated: {error}. Do not retry blindly; run `calcit cursor show` or `calcit cursor set` first.{}",
1726      if clipboard_available {
1727        " The clipboard remains available."
1728      } else {
1729        ""
1730      }
1731    )
1732  })
1733}
1734
1735fn save_cursor_document(snapshot_file: &str, document: &CursorDocument) -> Result<(), String> {
1736  stage_cursor_document(snapshot_file, document)?.commit()
1737}
1738
1739fn warn_cursor_gitignore(snapshot_file: &str) {
1740  let project_dir = project_state::project_directory_for_snapshot(snapshot_file);
1741  let gitignore = project_dir.join(".gitignore");
1742  let ignored = fs::read_to_string(&gitignore).is_ok_and(|content| {
1743    content.lines().any(|line| {
1744      let pattern = line.trim();
1745      matches!(
1746        pattern,
1747        ".calcit" | ".calcit/" | "/.calcit" | "/.calcit/" | "**/.calcit/" | ".calcit/cursor.cirru" | "*.cirru"
1748      )
1749    })
1750  });
1751  if !ignored {
1752    eprintln!(
1753      "{} Add `.calcit/` to '{}' so local Calcit state is not committed.",
1754      "[Cursor]".yellow().bold(),
1755      gitignore.display()
1756    );
1757  }
1758}
1759
1760#[cfg(test)]
1761mod tests {
1762  use super::{
1763    CursorClipboard, CursorDocument, CursorLastQuery, CursorState, DEFAULT_CURSOR, RestoreSource, TreeCursorMutation, TreeOperation,
1764    apply_at_cursor, barf_first, barf_last, build_cursor_preview, commit_snapshot_then_cursor_staged_files, cursor_file_path,
1765    cursor_state_to_edn, duplicate_cursor, legacy_cursor_file_path, load_cursor_document, load_cursor_state,
1766    maintain_cursor_after_node_move, maintain_cursor_after_tree_mutation, move_cursor_across_siblings, move_cursor_depth_first,
1767    move_cursor_to_child, node_fingerprint, push_bounded, read_cursor_target, render_cursor_document, restore_cursor,
1768    save_cursor_document, save_cursor_state, set_cursor_selection, slurp_next, slurp_prev, stage_atomic_file, transform_cursor_path,
1769  };
1770  use crate::cli_args::CursorApplyCommand;
1771  use crate::cli_handlers::edit::{apply_operation_at_path, load_snapshot, save_snapshot};
1772  use crate::cli_handlers::test_support::TestProject;
1773  use cirru_edn::Edn;
1774  use cirru_parser::Cirru;
1775  use std::collections::BTreeMap;
1776  use std::fs;
1777
1778  type TestCursorSnapshot = TestProject;
1779
1780  #[test]
1781  fn stale_anchor_does_not_block_other_cursor_positions() {
1782    let fixture = TestCursorSnapshot::from_fixture();
1783    let snapshot_file = fixture.snapshot_string();
1784    let path = vec![fixture.main_tail, 1];
1785    let (node, revision) = read_cursor_target(&snapshot_file, "app.main/main!", &path).expect("target exists");
1786    let valid = CursorState {
1787      snapshot: snapshot_file.clone(),
1788      target: "app.main/main!".to_string(),
1789      path,
1790      definition_revision: revision,
1791      fingerprint: node_fingerprint(&node),
1792    };
1793    let stale = CursorState {
1794      path: vec![9999],
1795      ..valid.clone()
1796    };
1797    let mut document = CursorDocument {
1798      active_name: DEFAULT_CURSOR.to_string(),
1799      active: valid.clone(),
1800      inactive_cursors: BTreeMap::new(),
1801      history: vec![],
1802      stack: vec![],
1803      anchor: Some(stale.clone()),
1804      marks: BTreeMap::from([("valid".to_string(), valid.clone())]),
1805      last_query: None,
1806      clipboard: None,
1807    };
1808    let snapshot = load_snapshot(&snapshot_file).expect("fixture snapshot");
1809    super::transform_auxiliary_positions(&mut document, "app.main/main!", &snapshot_file, &snapshot, |path| path.to_vec())
1810      .expect("stale anchor must not prevent maintenance");
1811    assert_eq!(document.anchor, Some(stale.clone()));
1812    assert_eq!(document.marks.get("valid"), Some(&valid));
1813    super::retarget_auxiliary_positions(&mut document, "app.main/main!", "app.main/test-fn", &snapshot_file, &snapshot)
1814      .expect("stale anchor must not prevent retargeting");
1815    assert_eq!(document.anchor, Some(stale));
1816  }
1817
1818  #[test]
1819  fn bounded_push_trims_oversized_persisted_state() {
1820    let mut items = vec![1, 2, 3, 4];
1821    push_bounded(&mut items, 5, 3);
1822    assert_eq!(items, vec![3, 4, 5]);
1823  }
1824
1825  #[test]
1826  fn insertion_before_cursor_shifts_matching_sibling_branch() {
1827    let mutation = TreeCursorMutation::InsertBefore { path: vec![3, 2] };
1828    assert_eq!(transform_cursor_path(&[3, 4, 1], &mutation).0, vec![3, 5, 1]);
1829    assert_eq!(transform_cursor_path(&[2, 4], &mutation).0, vec![2, 4]);
1830  }
1831
1832  #[test]
1833  fn deletion_before_cursor_shifts_and_selected_delete_moves_parent() {
1834    let before = TreeCursorMutation::Delete { path: vec![3, 2] };
1835    assert_eq!(transform_cursor_path(&[3, 4, 1], &before).0, vec![3, 3, 1]);
1836
1837    let selected = TreeCursorMutation::Delete { path: vec![3, 4] };
1838    assert_eq!(transform_cursor_path(&[3, 4, 1], &selected).0, vec![3]);
1839  }
1840
1841  #[test]
1842  fn swap_and_unwrap_keep_cursor_attached_to_subtree() {
1843    let swap = TreeCursorMutation::SwapPrev { path: vec![3, 4] };
1844    assert_eq!(transform_cursor_path(&[3, 3, 1], &swap).0, vec![3, 4, 1]);
1845
1846    let unwrap = TreeCursorMutation::Unwrap {
1847      path: vec![3, 2],
1848      child_count: 3,
1849    };
1850    assert_eq!(transform_cursor_path(&[3, 2, 1, 4], &unwrap).0, vec![3, 3, 4]);
1851    assert_eq!(transform_cursor_path(&[3, 5], &unwrap).0, vec![3, 7]);
1852  }
1853
1854  #[test]
1855  fn cursor_state_round_trips_as_cirru_edn() {
1856    let fixture = TestCursorSnapshot::from_fixture();
1857    let snapshot_file = fixture.snapshot_string();
1858    let path = vec![fixture.main_tail, 1];
1859    let (node, revision) = read_cursor_target(&snapshot_file, "app.main/main!", &path).expect("fixture cursor target should exist");
1860    let state = CursorState {
1861      snapshot: snapshot_file.clone(),
1862      target: "app.main/main!".to_string(),
1863      path,
1864      definition_revision: revision,
1865      fingerprint: node_fingerprint(&node),
1866    };
1867
1868    save_cursor_state(&snapshot_file, &state).expect("cursor state should save");
1869    assert_eq!(load_cursor_state(&snapshot_file).expect("cursor state should load"), state);
1870    let content = fs::read_to_string(cursor_file_path(&snapshot_file)).expect("cursor state file should read");
1871    let root = cirru_edn::parse(&content)
1872      .expect("cursor state should parse")
1873      .view_map()
1874      .expect("cursor state should be a map");
1875    assert_eq!(
1876      root
1877        .tag_get("active")
1878        .expect("cursor active name should exist")
1879        .read_tag_str()
1880        .expect("cursor active name should be a tag")
1881        .as_ref(),
1882      DEFAULT_CURSOR,
1883    );
1884    assert_eq!(
1885      root
1886        .tag_get("schema-version")
1887        .expect("cursor schema version should exist")
1888        .read_number()
1889        .expect("cursor schema version should be numeric"),
1890      4.0
1891    );
1892    assert!(
1893      !content.contains(":preview"),
1894      "cursor history should not persist full subtree previews"
1895    );
1896  }
1897
1898  #[test]
1899  fn staged_cursor_commit_reports_snapshot_success_when_cursor_commit_fails() {
1900    let fixture = TestCursorSnapshot::from_fixture();
1901    let snapshot_destination = fixture.directory.join("paste-snapshot.cirru");
1902    let cursor_destination = fixture.directory.join("paste-cursor.cirru");
1903    fs::write(&snapshot_destination, "source").expect("paste snapshot destination should initialize");
1904    fs::write(&cursor_destination, "cursor").expect("paste cursor destination should initialize");
1905    let staged_snapshot = stage_atomic_file(&snapshot_destination, b"pasted", "test snapshot").expect("snapshot should stage");
1906    let staged_cursor = stage_atomic_file(&cursor_destination, b"next cursor", "test cursor").expect("cursor should stage");
1907    fs::remove_file(&cursor_destination).expect("cursor destination should be replaced for failure injection");
1908    fs::create_dir(&cursor_destination).expect("cursor failure directory should be created");
1909
1910    let error = commit_snapshot_then_cursor_staged_files(staged_snapshot, staged_cursor, "Duplicate", false)
1911      .expect_err("cursor commit should fail");
1912    assert!(error.contains("Duplicate succeeded in the snapshot"), "error: {error}");
1913    assert!(error.contains("Do not retry blindly"), "error: {error}");
1914    assert_eq!(
1915      fs::read_to_string(&snapshot_destination).expect("pasted snapshot should persist"),
1916      "pasted"
1917    );
1918  }
1919
1920  #[test]
1921  fn persisted_cursor_moves_after_insertion_before_it() {
1922    let fixture = TestCursorSnapshot::from_fixture();
1923    let snapshot_file = fixture.snapshot_string();
1924    let cursor_path = vec![fixture.main_tail, 1];
1925    let (node, revision) =
1926      read_cursor_target(&snapshot_file, "app.main/main!", &cursor_path).expect("fixture cursor target should exist");
1927    let state = CursorState {
1928      snapshot: snapshot_file.clone(),
1929      target: "app.main/main!".to_string(),
1930      path: cursor_path,
1931      definition_revision: revision,
1932      fingerprint: node_fingerprint(&node),
1933    };
1934    save_cursor_document(
1935      &snapshot_file,
1936      &CursorDocument {
1937        active_name: DEFAULT_CURSOR.to_string(),
1938        active: state.clone(),
1939        inactive_cursors: BTreeMap::new(),
1940        history: vec![],
1941        stack: vec![],
1942        anchor: Some(state.clone()),
1943        marks: BTreeMap::from([("insertion".to_string(), state)]),
1944        last_query: None,
1945        clipboard: None,
1946      },
1947    )
1948    .expect("cursor document should save");
1949
1950    let mut snapshot = load_snapshot(&snapshot_file).expect("fixture snapshot should load");
1951    let entry = snapshot
1952      .files
1953      .get_mut("app.main")
1954      .and_then(|file| file.defs.get_mut("main!"))
1955      .expect("fixture main definition should exist");
1956    entry.code = apply_operation_at_path(
1957      &entry.code,
1958      &[fixture.main_tail, 1],
1959      TreeOperation::InsertBefore,
1960      Some(&cirru_parser::Cirru::leaf("false")),
1961    )
1962    .expect("fixture insertion should succeed");
1963    save_snapshot(&snapshot, &snapshot_file).expect("mutated fixture should save");
1964
1965    maintain_cursor_after_tree_mutation(
1966      &snapshot_file,
1967      "app.main/main!",
1968      &TreeCursorMutation::InsertBefore {
1969        path: vec![fixture.main_tail, 1],
1970      },
1971    )
1972    .expect("cursor maintenance should succeed");
1973    let updated = load_cursor_state(&snapshot_file).expect("updated cursor should load");
1974    assert_eq!(updated.path, vec![fixture.main_tail, 2]);
1975    let document = load_cursor_document(&snapshot_file).expect("cursor document should load");
1976    assert_eq!(
1977      document.anchor.as_ref().map(|state| state.path.as_slice()),
1978      Some([fixture.main_tail, 2].as_slice())
1979    );
1980    assert_eq!(
1981      document.marks.get("insertion").map(|state| state.path.as_slice()),
1982      Some([fixture.main_tail, 2].as_slice())
1983    );
1984    assert_eq!(
1985      read_cursor_target(&snapshot_file, "app.main/main!", &updated.path)
1986        .expect("updated cursor target should exist")
1987        .0,
1988      cirru_parser::Cirru::leaf("true")
1989    );
1990  }
1991
1992  #[test]
1993  fn cursor_maintenance_isolates_stale_mark_and_saves_valid_updates() {
1994    let fixture = TestCursorSnapshot::from_fixture();
1995    let snapshot_file = fixture.snapshot_string();
1996    let anchor_path = vec![fixture.main_tail, 1];
1997    let (node, revision) = read_cursor_target(&snapshot_file, "app.main/main!", &anchor_path).expect("target should exist");
1998    let valid_state = CursorState {
1999      snapshot: snapshot_file.clone(),
2000      target: "app.main/main!".to_string(),
2001      path: anchor_path,
2002      definition_revision: revision.clone(),
2003      fingerprint: node_fingerprint(&node),
2004    };
2005    let stale_mark = CursorState {
2006      snapshot: snapshot_file.clone(),
2007      target: "app.main/main!".to_string(),
2008      path: vec![fixture.main_tail, 99],
2009      definition_revision: revision,
2010      fingerprint: "stale".to_string(),
2011    };
2012    let document = CursorDocument {
2013      active_name: DEFAULT_CURSOR.to_string(),
2014      active: valid_state.clone(),
2015      inactive_cursors: BTreeMap::new(),
2016      history: vec![],
2017      stack: vec![],
2018      anchor: Some(valid_state.clone()),
2019      marks: BTreeMap::from([("valid".to_string(), valid_state), ("stale".to_string(), stale_mark.clone())]),
2020      last_query: None,
2021      clipboard: None,
2022    };
2023    save_cursor_document(&snapshot_file, &document).expect("cursor document should save");
2024
2025    let mut snapshot = load_snapshot(&snapshot_file).expect("fixture should load");
2026    let code_entry = snapshot
2027      .files
2028      .get_mut("app.main")
2029      .and_then(|file| file.defs.get_mut("main!"))
2030      .expect("main! should exist");
2031    code_entry.code = apply_operation_at_path(
2032      &code_entry.code,
2033      &[fixture.main_tail, 1],
2034      TreeOperation::InsertBefore,
2035      Some(&cirru_parser::Cirru::leaf("false")),
2036    )
2037    .expect("fixture insertion should succeed");
2038    save_snapshot(&snapshot, &snapshot_file).expect("mutated fixture should save");
2039
2040    maintain_cursor_after_tree_mutation(
2041      &snapshot_file,
2042      "app.main/main!",
2043      &TreeCursorMutation::InsertBefore {
2044        path: vec![fixture.main_tail, 1],
2045      },
2046    )
2047    .expect("stale mark should not fail cursor maintenance");
2048
2049    let updated = load_cursor_document(&snapshot_file).expect("updated cursor document should save and load");
2050    assert_eq!(updated.active.path, vec![fixture.main_tail, 2]);
2051    assert_eq!(
2052      updated.anchor.as_ref().map(|state| state.path.as_slice()),
2053      Some([fixture.main_tail, 2].as_slice())
2054    );
2055    assert_eq!(
2056      updated.marks.get("valid").map(|state| state.path.as_slice()),
2057      Some([fixture.main_tail, 2].as_slice())
2058    );
2059    assert_eq!(updated.marks.get("stale"), Some(&stale_mark));
2060  }
2061
2062  #[test]
2063  fn cursor_document_round_trips_named_cursors_history_stack_and_clipboard() {
2064    let fixture = TestCursorSnapshot::from_fixture();
2065    let snapshot_file = fixture.snapshot_string();
2066    let path = vec![fixture.main_tail, 1];
2067    let (node, revision) = read_cursor_target(&snapshot_file, "app.main/main!", &path).expect("fixture cursor target should exist");
2068    let state = CursorState {
2069      snapshot: snapshot_file.clone(),
2070      target: "app.main/main!".to_string(),
2071      path: path.clone(),
2072      definition_revision: revision,
2073      fingerprint: node_fingerprint(&node),
2074    };
2075    let inactive_path = vec![fixture.main_tail, 0];
2076    let (inactive_node, inactive_revision) =
2077      read_cursor_target(&snapshot_file, "app.main/main!", &inactive_path).expect("inactive cursor target should exist");
2078    let inactive_state = CursorState {
2079      snapshot: snapshot_file.clone(),
2080      target: "app.main/main!".to_string(),
2081      path: inactive_path,
2082      definition_revision: inactive_revision,
2083      fingerprint: node_fingerprint(&inactive_node),
2084    };
2085    let document = CursorDocument {
2086      active_name: "agent-a".to_string(),
2087      active: state.clone(),
2088      inactive_cursors: BTreeMap::from([("agent-b".to_string(), inactive_state.clone())]),
2089      history: vec![state.clone()],
2090      stack: vec![state.clone()],
2091      anchor: Some(state.clone()),
2092      marks: BTreeMap::from([("main".to_string(), state.clone())]),
2093      last_query: Some(CursorLastQuery {
2094        command: "search".to_string(),
2095        pattern: "true".to_string(),
2096        filter: Some("app.main/main!".to_string()),
2097        exact: true,
2098        regex: false,
2099        max_depth: 0,
2100        start_path: None,
2101        entry: None,
2102        source: "all".to_string(),
2103        pattern_is_json: false,
2104        selected_index: 0,
2105        snapshot_revision: "md5:test".to_string(),
2106      }),
2107      clipboard: Some(CursorClipboard {
2108        mode: "copy".to_string(),
2109        source_target: state.target.clone(),
2110        source_path: path,
2111        fingerprint: node_fingerprint(&node),
2112        tree: node,
2113      }),
2114    };
2115
2116    save_cursor_document(&snapshot_file, &document).expect("cursor document should save");
2117    let loaded = load_cursor_document(&snapshot_file).expect("cursor document should load");
2118    assert_eq!(loaded.active, state);
2119    assert_eq!(loaded.inactive_cursors.get("agent-b"), Some(&inactive_state));
2120    assert_eq!(loaded, document);
2121  }
2122
2123  #[test]
2124  fn oversized_cursor_clipboard_is_rejected_before_writing() {
2125    let fixture = TestCursorSnapshot::from_fixture();
2126    let snapshot_file = fixture.snapshot_string();
2127    let path = vec![fixture.main_tail, 1];
2128    let (node, revision) = read_cursor_target(&snapshot_file, "app.main/main!", &path).expect("fixture cursor target should exist");
2129    let state = CursorState {
2130      snapshot: snapshot_file,
2131      target: "app.main/main!".to_string(),
2132      path: path.clone(),
2133      definition_revision: revision,
2134      fingerprint: node_fingerprint(&node),
2135    };
2136    let document = CursorDocument {
2137      active_name: DEFAULT_CURSOR.to_string(),
2138      active: state.clone(),
2139      inactive_cursors: BTreeMap::new(),
2140      history: vec![],
2141      stack: vec![],
2142      anchor: None,
2143      marks: BTreeMap::new(),
2144      last_query: None,
2145      clipboard: Some(CursorClipboard {
2146        mode: "copy".to_string(),
2147        source_target: state.target,
2148        source_path: path,
2149        fingerprint: state.fingerprint,
2150        tree: Cirru::leaf(format!("|{}", "x".repeat(70 * 1024))),
2151      }),
2152    };
2153
2154    let error = render_cursor_document(&document).expect_err("oversized clipboard should fail");
2155    assert!(error.contains("exceeding the 65536 byte limit"), "error: {error}");
2156    assert!(
2157      error.contains("calcit cursor clear") && error.contains("calcit cursor set"),
2158      "error: {error}"
2159    );
2160    assert!(
2161      error.contains("recover any pending tree") && error.contains("docs/run/upgrade.md"),
2162      "error: {error}"
2163    );
2164    assert!(!error.contains("oversized clipboard"), "error: {error}");
2165  }
2166
2167  #[test]
2168  fn legacy_v1_cursor_document_loads_with_empty_extensions() {
2169    let fixture = TestCursorSnapshot::from_fixture();
2170    let snapshot_file = fixture.snapshot_string();
2171    let path = vec![fixture.main_tail, 1];
2172    let (node, revision) = read_cursor_target(&snapshot_file, "app.main/main!", &path).expect("fixture cursor target should exist");
2173    let state = CursorState {
2174      snapshot: snapshot_file.clone(),
2175      target: "app.main/main!".to_string(),
2176      path,
2177      definition_revision: revision,
2178      fingerprint: node_fingerprint(&node),
2179    };
2180    let legacy = cirru_edn::format(
2181      &Edn::map_from_iter([
2182        (Edn::tag("schema-version"), Edn::from(1_u8)),
2183        (Edn::tag("active"), Edn::tag("main")),
2184        (
2185          Edn::tag("cursors"),
2186          Edn::map_from_iter([(Edn::tag("main"), cursor_state_to_edn(&state))]),
2187        ),
2188      ]),
2189      false,
2190    )
2191    .expect("legacy cursor should format");
2192    fs::write(legacy_cursor_file_path(&snapshot_file), legacy).expect("legacy cursor should write");
2193
2194    let loaded = load_cursor_document(&snapshot_file).expect("legacy cursor should load");
2195    assert_eq!(loaded.active, state);
2196    assert!(loaded.history.is_empty());
2197    assert!(loaded.stack.is_empty());
2198    assert!(loaded.anchor.is_none());
2199    assert!(loaded.marks.is_empty());
2200    assert!(loaded.last_query.is_none());
2201    assert!(loaded.clipboard.is_none());
2202  }
2203
2204  #[test]
2205  fn focused_preview_preserves_definition_signature() {
2206    let fixture = TestCursorSnapshot::from_fixture();
2207    let snapshot_file = fixture.snapshot_string();
2208    let path = vec![fixture.main_tail, 1];
2209    let (node, revision) = read_cursor_target(&snapshot_file, "app.main/main!", &path).expect("fixture cursor target should exist");
2210    let state = CursorState {
2211      snapshot: snapshot_file.clone(),
2212      target: "app.main/main!".to_string(),
2213      path,
2214      definition_revision: revision,
2215      fingerprint: node_fingerprint(&node),
2216    };
2217
2218    let preview = build_cursor_preview(&snapshot_file, &state, "focus").expect("focused preview should build");
2219    let Cirru::List(items) = preview else {
2220      panic!("definition preview should remain a list")
2221    };
2222    assert_eq!(items[0], Cirru::leaf("defn"));
2223    assert_eq!(items[1], Cirru::leaf("main!"));
2224    assert!(matches!(&items[2], Cirru::List(_)));
2225    let rendered = cirru_parser::format(&[Cirru::List(items)], false.into()).expect("focused preview should render");
2226    assert!(rendered.contains("CURSOR"));
2227    assert!(!rendered.contains("FOCUSED"));
2228  }
2229
2230  #[test]
2231  fn cursor_follows_moved_subtree_even_when_fingerprint_is_duplicated() {
2232    let fixture = TestCursorSnapshot::from_fixture();
2233    let snapshot_file = fixture.snapshot_string();
2234    let path = vec![fixture.main_tail, 1];
2235    let (node, revision) = read_cursor_target(&snapshot_file, "app.main/main!", &path).expect("fixture cursor target should exist");
2236    save_cursor_state(
2237      &snapshot_file,
2238      &CursorState {
2239        snapshot: snapshot_file.clone(),
2240        target: "app.main/main!".to_string(),
2241        path: path.clone(),
2242        definition_revision: revision,
2243        fingerprint: node_fingerprint(&node),
2244      },
2245    )
2246    .expect("cursor state should save");
2247
2248    let mut snapshot = load_snapshot(&snapshot_file).expect("fixture snapshot should load");
2249    let entry = snapshot
2250      .files
2251      .get_mut("app.main")
2252      .and_then(|file| file.defs.get_mut("main!"))
2253      .expect("fixture main definition should exist");
2254    let duplicated = apply_operation_at_path(&entry.code, &[fixture.main_tail, 1], TreeOperation::InsertAfter, Some(&node))
2255      .expect("duplicate should insert");
2256    let after_move_insert = apply_operation_at_path(&duplicated, &[fixture.main_tail, 0], TreeOperation::InsertAfter, Some(&node))
2257      .expect("move destination should insert");
2258    entry.code = apply_operation_at_path(&after_move_insert, &[fixture.main_tail, 2], TreeOperation::Delete, None)
2259      .expect("old source should delete");
2260    save_snapshot(&snapshot, &snapshot_file).expect("mutated fixture should save");
2261
2262    maintain_cursor_after_node_move(
2263      &snapshot_file,
2264      "app.main/main!",
2265      &[fixture.main_tail, 1],
2266      &[fixture.main_tail, 0],
2267      TreeOperation::InsertAfter,
2268      0,
2269    )
2270    .expect("cursor should follow the moved duplicate deterministically");
2271    assert_eq!(load_cursor_state(&snapshot_file).expect("moved cursor should load").path, path);
2272  }
2273
2274  #[test]
2275  fn cursor_navigation_supports_last_child_sibling_counts_and_multi_back() {
2276    let fixture = TestCursorSnapshot::from_fixture();
2277    let snapshot_file = fixture.snapshot_string();
2278    set_cursor_selection(&snapshot_file, "app.main/main!", vec![fixture.main_tail]).expect("cursor should select parent list");
2279
2280    move_cursor_to_child(&snapshot_file, None, true).expect("cursor should enter the last child");
2281    assert_eq!(
2282      load_cursor_state(&snapshot_file).expect("last child cursor should load").path,
2283      vec![fixture.main_tail, 1]
2284    );
2285
2286    restore_cursor(&snapshot_file, RestoreSource::History, 1).expect("cursor should return to parent");
2287    move_cursor_to_child(&snapshot_file, Some(0), false).expect("cursor should enter the first child");
2288    move_cursor_across_siblings(&snapshot_file, 1, true).expect("cursor should skip one sibling forward");
2289    assert_eq!(
2290      load_cursor_state(&snapshot_file).expect("next cursor should load").path,
2291      vec![fixture.main_tail, 1]
2292    );
2293
2294    restore_cursor(&snapshot_file, RestoreSource::History, 2).expect("cursor should rewind two recorded locations");
2295    assert_eq!(
2296      load_cursor_state(&snapshot_file).expect("rewound cursor should load").path,
2297      vec![fixture.main_tail]
2298    );
2299
2300    set_cursor_selection(&snapshot_file, "app.main/main!", vec![fixture.main_tail, 0]).expect("cursor should select first sibling");
2301    let error = move_cursor_across_siblings(&snapshot_file, 2, true).expect_err("out-of-range skip should fail");
2302    assert!(error.contains("only 1 next sibling"), "error: {error}");
2303    assert_eq!(
2304      load_cursor_state(&snapshot_file).expect("failed move should preserve cursor").path,
2305      vec![fixture.main_tail, 0]
2306    );
2307  }
2308
2309  #[test]
2310  fn cursor_native_swap_paredit_and_duplicate_keep_selection_attached() {
2311    let fixture = TestCursorSnapshot::from_fixture();
2312    let snapshot_file = fixture.snapshot_string();
2313    let mut snapshot = load_snapshot(&snapshot_file).expect("cursor paredit fixture should load");
2314    let entry = snapshot
2315      .files
2316      .get_mut("app.main")
2317      .and_then(|file| file.defs.get_mut("main!"))
2318      .expect("cursor paredit definition should exist");
2319    entry.code = Cirru::List(vec![
2320      Cirru::leaf("head"),
2321      Cirru::List(vec![Cirru::leaf("a"), Cirru::leaf("b")]),
2322      Cirru::leaf("tail"),
2323    ]);
2324    save_snapshot(&snapshot, &snapshot_file).expect("cursor paredit fixture should save");
2325
2326    set_cursor_selection(&snapshot_file, "app.main/main!", vec![1, 0]).expect("cursor should select first list child");
2327    apply_at_cursor(
2328      &snapshot_file,
2329      &CursorApplyCommand {
2330        operation: "swap-next".to_string(),
2331        file: None,
2332        code: None,
2333        input_format: crate::cli_args::SyntaxInputFormat::Auto,
2334        depth: 2,
2335        at: None,
2336      },
2337    )
2338    .expect("cursor-native swap should succeed");
2339    assert_eq!(
2340      load_cursor_state(&snapshot_file).expect("swapped cursor should load").path,
2341      vec![1, 1]
2342    );
2343
2344    set_cursor_selection(&snapshot_file, "app.main/main!", vec![1]).expect("cursor should select list");
2345    slurp_next(&snapshot_file).expect("selected list should slurp its next sibling");
2346    assert_eq!(load_cursor_state(&snapshot_file).expect("slurped cursor should load").path, vec![1]);
2347    assert_eq!(
2348      read_cursor_target(&snapshot_file, "app.main/main!", &[1])
2349        .expect("slurped list should exist")
2350        .0,
2351      Cirru::List(vec![Cirru::leaf("b"), Cirru::leaf("a"), Cirru::leaf("tail")])
2352    );
2353
2354    barf_last(&snapshot_file).expect("selected list should barf its last child");
2355    assert_eq!(load_cursor_state(&snapshot_file).expect("barfed cursor should load").path, vec![1]);
2356    slurp_prev(&snapshot_file).expect("selected list should slurp its previous sibling");
2357    assert_eq!(
2358      load_cursor_state(&snapshot_file).expect("backward-slurped cursor should load").path,
2359      vec![0]
2360    );
2361    assert_eq!(
2362      read_cursor_target(&snapshot_file, "app.main/main!", &[0])
2363        .expect("backward-slurped list should exist")
2364        .0,
2365      Cirru::List(vec![Cirru::leaf("head"), Cirru::leaf("b"), Cirru::leaf("a")])
2366    );
2367
2368    barf_first(&snapshot_file).expect("selected list should barf its first child");
2369    assert_eq!(
2370      load_cursor_state(&snapshot_file).expect("first-barfed cursor should load").path,
2371      vec![1]
2372    );
2373    duplicate_cursor(&snapshot_file, "after").expect("cursor duplicate should succeed");
2374    assert_eq!(
2375      load_cursor_state(&snapshot_file).expect("duplicate cursor should load").path,
2376      vec![2]
2377    );
2378    assert_eq!(
2379      read_cursor_target(&snapshot_file, "app.main/main!", &[])
2380        .expect("duplicated definition should exist")
2381        .0,
2382      Cirru::List(vec![
2383        Cirru::leaf("head"),
2384        Cirru::List(vec![Cirru::leaf("b"), Cirru::leaf("a")]),
2385        Cirru::List(vec![Cirru::leaf("b"), Cirru::leaf("a")]),
2386        Cirru::leaf("tail"),
2387      ])
2388    );
2389  }
2390
2391  #[test]
2392  fn cursor_depth_first_navigation_crosses_list_boundaries_once_per_command() {
2393    let fixture = TestCursorSnapshot::from_fixture();
2394    let snapshot_file = fixture.snapshot_string();
2395    let mut snapshot = load_snapshot(&snapshot_file).expect("cursor traversal fixture should load");
2396    let entry = snapshot
2397      .files
2398      .get_mut("app.main")
2399      .and_then(|file| file.defs.get_mut("main!"))
2400      .expect("cursor traversal definition should exist");
2401    entry.code = Cirru::List(vec![
2402      Cirru::leaf("a"),
2403      Cirru::List(vec![Cirru::leaf("b"), Cirru::List(vec![Cirru::leaf("c")])]),
2404      Cirru::leaf("d"),
2405    ]);
2406    save_snapshot(&snapshot, &snapshot_file).expect("cursor traversal fixture should save");
2407
2408    set_cursor_selection(&snapshot_file, "app.main/main!", vec![]).expect("cursor should select definition root");
2409    move_cursor_depth_first(&snapshot_file, 5, true).expect("cursor should cross into a nested list");
2410    assert_eq!(
2411      load_cursor_state(&snapshot_file).expect("forward cursor should load").path,
2412      vec![1, 1, 0]
2413    );
2414
2415    move_cursor_depth_first(&snapshot_file, 3, false).expect("cursor should cross back out of a nested list");
2416    assert_eq!(
2417      load_cursor_state(&snapshot_file).expect("backward cursor should load").path,
2418      vec![1]
2419    );
2420
2421    let error = move_cursor_depth_first(&snapshot_file, 10, true).expect_err("cursor should not move past definition end");
2422    assert!(error.contains("reached the definition end"), "error: {error}");
2423    assert_eq!(
2424      load_cursor_state(&snapshot_file)
2425        .expect("failed traversal should preserve cursor")
2426        .path,
2427      vec![1]
2428    );
2429  }
2430
2431  #[test]
2432  fn cursor_native_edits_reject_invalid_boundaries_without_changing_snapshot() {
2433    let fixture = TestCursorSnapshot::from_fixture();
2434    let snapshot_file = fixture.snapshot_string();
2435    let mut snapshot = load_snapshot(&snapshot_file).expect("cursor boundary fixture should load");
2436    let entry = snapshot
2437      .files
2438      .get_mut("app.main")
2439      .and_then(|file| file.defs.get_mut("main!"))
2440      .expect("cursor boundary definition should exist");
2441    entry.code = Cirru::List(vec![Cirru::leaf("a"), Cirru::List(vec![])]);
2442    save_snapshot(&snapshot, &snapshot_file).expect("cursor boundary fixture should save");
2443    let original = fs::read_to_string(&snapshot_file).expect("cursor boundary fixture should read");
2444
2445    set_cursor_selection(&snapshot_file, "app.main/main!", vec![]).expect("cursor should select definition root");
2446    assert!(
2447      slurp_next(&snapshot_file)
2448        .expect_err("root cannot slurp")
2449        .contains("Definition root")
2450    );
2451    assert!(barf_last(&snapshot_file).expect_err("root cannot barf").contains("definition root"));
2452    assert!(
2453      barf_first(&snapshot_file)
2454        .expect_err("root cannot barf first")
2455        .contains("definition root")
2456    );
2457    assert!(
2458      duplicate_cursor(&snapshot_file, "after")
2459        .expect_err("root cannot duplicate")
2460        .contains("definition root")
2461    );
2462    assert!(
2463      duplicate_cursor(&snapshot_file, "sideways")
2464        .expect_err("invalid duplicate position should fail")
2465        .contains("Use before or after")
2466    );
2467
2468    set_cursor_selection(&snapshot_file, "app.main/main!", vec![0]).expect("cursor should select leaf");
2469    assert!(
2470      slurp_next(&snapshot_file)
2471        .expect_err("leaf cannot slurp")
2472        .contains("requires the selected node to be a list")
2473    );
2474    assert!(
2475      slurp_prev(&snapshot_file)
2476        .expect_err("first sibling cannot slurp previous")
2477        .contains("requires the selected node to be a list")
2478    );
2479    let error = apply_at_cursor(
2480      &snapshot_file,
2481      &CursorApplyCommand {
2482        operation: "swap-next".to_string(),
2483        file: None,
2484        code: Some("quote ignored".to_string()),
2485        input_format: crate::cli_args::SyntaxInputFormat::Auto,
2486        depth: 2,
2487        at: None,
2488      },
2489    )
2490    .expect_err("code should be rejected for a code-free operation");
2491    assert!(
2492      error.contains("does not accept --file, --code, or --input-format"),
2493      "error: {error}"
2494    );
2495
2496    set_cursor_selection(&snapshot_file, "app.main/main!", vec![1]).expect("cursor should select empty list");
2497    assert!(
2498      slurp_next(&snapshot_file)
2499        .expect_err("last sibling cannot slurp")
2500        .contains("no next sibling")
2501    );
2502    assert!(barf_last(&snapshot_file).expect_err("empty list cannot barf").contains("no child"));
2503    assert!(
2504      barf_first(&snapshot_file)
2505        .expect_err("empty list cannot barf first")
2506        .contains("no child")
2507    );
2508    assert_eq!(
2509      fs::read_to_string(&snapshot_file).expect("cursor boundary fixture should reread"),
2510      original
2511    );
2512  }
2513}