diff --git a/atomic-cli/src/commands/intent/list.rs b/atomic-cli/src/commands/intent/list.rs index ce99403e..8c2c7cf4 100644 --- a/atomic-cli/src/commands/intent/list.rs +++ b/atomic-cli/src/commands/intent/list.rs @@ -80,7 +80,11 @@ pub struct IntentList { /// `atomic intent list --sort` keys. #[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)] pub enum IntentSort { + /// Sort by the human key (the existing default). Id, + /// Sort human keys by prefix and numeric sequence (2 before 10). + #[value(alias = "humanKey")] + HumanKey, Title, Status, Kind, @@ -94,7 +98,7 @@ impl IntentSort { pub(crate) fn wire(self) -> atomic_client::proto::VaultListSort { use atomic_client::proto::VaultListSort as W; match self { - IntentSort::Id => W::Id, + IntentSort::Id | IntentSort::HumanKey => W::Id, IntentSort::Title => W::Title, IntentSort::Status => W::Status, IntentSort::Kind => W::Kind, @@ -111,6 +115,7 @@ pub(crate) fn sort_rows(rows: &mut [Row], key: IntentSort, reverse: bool) { rows.sort_by(|a, b| { let ord = match key { IntentSort::Id => a.human_key.cmp(&b.human_key), + IntentSort::HumanKey => compare_human_keys(&a.human_key, &b.human_key), IntentSort::Title => a.title.cmp(&b.title), IntentSort::Status => a.status.cmp(&b.status), IntentSort::Kind => a.kind.cmp(&b.kind), @@ -121,6 +126,41 @@ pub(crate) fn sort_rows(rows: &mut [Row], key: IntentSort, reverse: bool) { }); } +/// Compare the last key component numerically without imposing an integer limit. +/// Invalid suffixes remain deterministic and group with their own prefix. +fn compare_human_keys(a: &str, b: &str) -> std::cmp::Ordering { + fn parts(key: &str) -> (&str, Option<&str>) { + let split = key + .rfind("::") + .map(|i| i + 2) + .or_else(|| key.rfind('-').map(|i| i + 1)); + match split { + Some(i) => (&key[..i], Some(&key[i..])), + None => (key, None), + } + } + fn numeric(s: &str) -> Option<&str> { + if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + Some(s.trim_start_matches('0')) + } + + let (a_prefix, a_suffix) = parts(a); + let (b_prefix, b_suffix) = parts(b); + a_prefix + .cmp(b_prefix) + .then_with( + || match (a_suffix.and_then(numeric), b_suffix.and_then(numeric)) { + (Some(a), Some(b)) => a.len().cmp(&b.len()).then_with(|| a.cmp(b)), + (Some(_), None) => std::cmp::Ordering::Less, + (None, Some(_)) => std::cmp::Ordering::Greater, + (None, None) => a_suffix.cmp(&b_suffix), + }, + ) + .then_with(|| a.cmp(b)) +} + impl IntentList { /// The effective `kind` filter: `--review` is sugar for `--kind review`. pub(crate) fn kind_filter(&self) -> Option { @@ -831,6 +871,47 @@ mod tests { assert_eq!(keys(&rows), ["A-3", "A-2", "A-1"]); } + #[test] + fn human_key_sort_is_natural_and_deterministic() { + for spelling in ["human-key", "humanKey"] { + let key = IntentSort::from_str(spelling, false).expect("human key sort spelling"); + assert_eq!(key.wire(), atomic_client::proto::VaultListSort::Id); + let expected = [ + "A-1", + "A-2", + "A-10", + "A::alice::001", + "A::alice::1", + "A::alice::2", + "A::alice::10", + "A::alice::999999999999999999999999999999", + "A::alice::1000000000000000000000000000000", + "A::alice::oops", + "A::bob::1", + "B-1", + ]; + for reverse in [false, true] { + let mut actual: Vec<_> = expected + .iter() + .rev() + .map(|id| sort_row(id, "title", "bug", Attested::None)) + .collect(); + sort_rows(&mut actual, key, reverse); + let mut wanted = expected.to_vec(); + if reverse { + wanted.reverse(); + } + assert_eq!(keys(&actual), wanted, "{spelling}, reverse={reverse}"); + } + } + let mut lexical = vec![ + sort_row("A-2", "", "", Attested::None), + sort_row("A-10", "", "", Attested::None), + ]; + sort_rows(&mut lexical, IntentSort::Id, false); + assert_eq!(keys(&lexical), ["A-10", "A-2"]); + } + #[test] fn review_flag_is_kind_review_shortcut() { // `--review` and `--kind review` resolve to the same filter. diff --git a/atomic-cli/src/commands/rpc.rs b/atomic-cli/src/commands/rpc.rs index 1c23c38d..decb63dd 100644 --- a/atomic-cli/src/commands/rpc.rs +++ b/atomic-cli/src/commands/rpc.rs @@ -999,6 +999,11 @@ pub fn intent_list(args: &super::intent::list::IntentList) -> CliResult { if let Some(kind) = &filter { rows.retain(|row| &row.kind == kind); } + // This request is unbudgeted and returns the full intent listing. Keep the + // existing wire ID order for older services, then apply the new CLI sort. + if args.sort == super::intent::list::IntentSort::HumanKey { + super::intent::list::sort_rows(&mut rows, args.sort, args.reverse); + } super::intent::list::IntentList::render(&rows, args.json); Ok(true) } diff --git a/atomic-cli/tests/it/routing_parity_test.rs b/atomic-cli/tests/it/routing_parity_test.rs index 159b157b..b0bd8453 100644 --- a/atomic-cli/tests/it/routing_parity_test.rs +++ b/atomic-cli/tests/it/routing_parity_test.rs @@ -111,6 +111,92 @@ fn intent_list_json_carries_attestation_columns_over_the_wire() { assert!(table.contains(&id)); } +#[test] +fn intent_human_key_sort_is_natural_in_service_output() { + let repo = TempDir::new().unwrap(); + let home = TempDir::new().unwrap(); + let run_isolated = |args: &[&str]| { + let mut command = Command::new(ATOMIC_BIN); + for (key, _) in std::env::vars_os() { + let name = key.to_string_lossy(); + if name.starts_with("ATOMIC_") || name.starts_with("OPENCODE_") { + command.env_remove(key); + } + } + let output = command + .args(args) + .current_dir(repo.path()) + .env("HOME", home.path()) + .env("ATOMIC_CONFIG_DIR", home.path().join(".atomic")) + .env("ATOMIC_SERVICE", "local") + .output() + .expect("run isolated atomic"); + assert!( + output.status.success(), + "{args:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap() + }; + + run_isolated(&["init", "--vault"]); + let ids: Vec<_> = (1..=11) + .map(|n| { + let output = run_isolated(&["intent", "new", &format!("Intent {n}")]); + output + .lines() + .find_map(|line| line.strip_prefix("Created intent: ")) + .unwrap() + .to_owned() + }) + .collect(); + let help = run_isolated(&["intent", "list", "--help"]); + assert!(help.contains("human-key"), "{help}"); + for (spelling, reverse, json) in [ + ("human-key", false, true), + ("humanKey", true, true), + ("human-key", false, false), + ("humanKey", true, false), + ] { + let mut args = vec!["intent", "list", "--sort", spelling]; + if reverse { + args.push("--reverse"); + } + if json { + args.push("--json"); + } + let output = run_isolated(&args); + let actual: Vec = if json { + serde_json::from_str::>(&output) + .unwrap() + .iter() + .map(|row| row["id"].as_str().unwrap().to_owned()) + .collect() + } else { + output + .lines() + .skip(1) + .filter_map(|line| line.split_whitespace().next()) + .map(str::to_owned) + .collect() + }; + let mut expected = ids.clone(); + if reverse { + expected.reverse(); + } + assert_eq!(actual, expected, "{args:?}"); + } + let lexical = run_isolated(&["intent", "list", "--sort", "id", "--json"]); + let actual: Vec<_> = serde_json::from_str::>(&lexical) + .unwrap() + .iter() + .map(|row| row["id"].as_str().unwrap().to_owned()) + .collect(); + let mut expected = ids; + expected.sort(); + assert_eq!(actual, expected); +} + #[test] fn memory_new_json_outputs_only_the_created_memory_object() { let (repo, home) = fixture("memory-new-json");