Skip to main content

agentmux_srv_core/backend/wconfig/
unrecognized.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which keys of `settings.json` AgentMux does not recognise, and what each was probably meant to be
5//! (docs/specs/SPEC_SETTINGS_JSON_EVERY_KEY_ONE_TO_ONE_2026_11_01.md §5.6, case 4).
6//!
7//! A key the schema does not list is kept in the file and has no effect. It is listed in the
8//! Settings view with a "did you mean" when another key is a few characters away (a typo), so the
9//! person can fix or remove it. The app never deletes one on its own.
10
11use std::collections::HashMap;
12
13use serde::{Deserialize, Serialize};
14
15/// One key of `settings.json` that is not a setting.
16#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
17pub struct UnrecognizedSetting {
18    pub key: String,
19    /// The recognised key it is closest to, when it is close enough to be a typo.
20    #[serde(default, skip_serializing_if = "Option::is_none")]
21    pub suggestion: Option<String>,
22    /// Where the key is in the file (1-based), when known.
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub line: Option<u32>,
25}
26
27/// Top-level members of `settings.json` that are not in the schema and are not mistakes: the per-connection
28/// settings AgentMux writes (`connections.<name>`, typed in `SettingsType`), and the editor hint `$schema`.
29const NOT_SETTINGS: [&str; 2] = ["connections", "$schema"];
30
31/// How many single-character edits away a key may be from a recognised one to be offered as it:
32/// one for a short key, up to three for a long one.
33fn allowed_distance(len: usize) -> usize {
34    (len / 8).clamp(1, 3)
35}
36
37/// The edit distance between `a` and `b` (insert, delete, replace, one character each), or `None`
38/// when it is more than `max`. Works on characters, so a non-ASCII key is not cut in half.
39fn distance(a: &[char], b: &[char], max: usize) -> Option<usize> {
40    if a.len().abs_diff(b.len()) > max {
41        return None;
42    }
43    let mut previous: Vec<usize> = (0..=b.len()).collect();
44    for (i, ca) in a.iter().enumerate() {
45        let mut row = vec![i + 1];
46        for (j, cb) in b.iter().enumerate() {
47            let replace = previous[j] + usize::from(ca != cb);
48            row.push(replace.min(previous[j + 1] + 1).min(row[j] + 1));
49        }
50        previous = row;
51    }
52    let d = previous[b.len()];
53    (d <= max).then_some(d)
54}
55
56/// The recognised key `key` is closest to, if it is close enough: a key that differs only in case
57/// is always offered. Ties go to the key that sorts first, so the answer does not depend on map order.
58fn closest<'a>(key: &str, known: &[&'a str]) -> Option<&'a str> {
59    let lower: Vec<char> = key.to_lowercase().chars().collect();
60    let max = allowed_distance(lower.len());
61    known
62        .iter()
63        .filter(|k| !k.ends_with('*'))
64        .filter_map(|k| {
65            let other: Vec<char> = k.to_lowercase().chars().collect();
66            distance(&lower, &other, max).map(|d| (d, *k))
67        })
68        .min()
69        .map(|(_, k)| k)
70}
71
72/// The keys of `keys` that `known` (the schema's keys) does not list, in the order the file has them
73/// when `lines` says where each is, otherwise by name. `lines` maps a key to its 1-based line.
74pub fn find<'a>(keys: impl IntoIterator<Item = &'a String>, known: &[&str], lines: &HashMap<String, u32>) -> Vec<UnrecognizedSetting> {
75    let mut found: Vec<UnrecognizedSetting> = keys
76        .into_iter()
77        .filter(|key| !known.contains(&key.as_str()) && !NOT_SETTINGS.contains(&key.as_str()))
78        .map(|key| UnrecognizedSetting { key: key.clone(), suggestion: closest(key, known).map(str::to_string), line: lines.get(key).copied() })
79        .collect();
80    found.sort_by(|a, b| (a.line.unwrap_or(u32::MAX), &a.key).cmp(&(b.line.unwrap_or(u32::MAX), &b.key)));
81    found
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87
88    const KNOWN: [&str; 6] = ["term:fontsize", "term:theme", "term:scrollback", "app:*", "window:zoom", "agent:livefeedturns"];
89
90    fn keys(list: &[&str]) -> Vec<String> {
91        list.iter().map(|s| s.to_string()).collect()
92    }
93
94    fn found(list: &[&str]) -> Vec<UnrecognizedSetting> {
95        find(&keys(list), &KNOWN, &HashMap::new())
96    }
97
98    #[test]
99    fn a_recognised_key_is_not_listed_and_a_family_key_is_recognised_as_written() {
100        assert!(found(&["term:fontsize", "app:*", "window:zoom"]).is_empty());
101    }
102
103    #[test]
104    fn what_agentmux_writes_into_the_file_beside_the_settings_is_not_listed() {
105        assert!(found(&["connections", "$schema"]).is_empty());
106    }
107
108    #[test]
109    fn a_typo_is_listed_with_the_key_it_was_probably_meant_to_be() {
110        let list = found(&["term:fontsise"]);
111        assert_eq!(list, vec![UnrecognizedSetting { key: "term:fontsise".into(), suggestion: Some("term:fontsize".into()), line: None }]);
112    }
113
114    #[test]
115    fn a_key_that_differs_only_in_case_is_offered_as_the_right_one() {
116        assert_eq!(found(&["Term:FontSize"])[0].suggestion.as_deref(), Some("term:fontsize"));
117    }
118
119    #[test]
120    fn a_key_far_from_everything_is_listed_with_no_suggestion() {
121        assert_eq!(found(&["my:own:note"])[0].suggestion, None);
122        assert_eq!(found(&["zzzzzz"])[0].suggestion, None);
123    }
124
125    #[test]
126    fn a_short_key_is_offered_only_one_edit_away_and_a_long_one_up_to_three() {
127        // "app:*" is a family and never offered; a two-edit typo of a short key is not close enough.
128        assert_eq!(found(&["term:thme"])[0].suggestion.as_deref(), Some("term:theme"));
129        assert_eq!(found(&["term:tm"])[0].suggestion, None);
130        assert_eq!(found(&["agent:livefeedturnz"])[0].suggestion.as_deref(), Some("agent:livefeedturns"));
131        assert_eq!(found(&["agent:livefedtrns"])[0].suggestion.as_deref(), Some("agent:livefeedturns"));
132    }
133
134    #[test]
135    fn a_family_key_is_never_the_suggestion() {
136        assert_eq!(found(&["app:x"])[0].suggestion, None);
137    }
138
139    #[test]
140    fn the_answer_follows_the_file_order_then_the_name_and_does_not_depend_on_map_order() {
141        let lines: HashMap<String, u32> = [("b:key".to_string(), 3), ("a:key".to_string(), 9)].into_iter().collect();
142        let list = find(&keys(&["a:key", "b:key", "c:key"]), &KNOWN, &lines);
143        assert_eq!(list.iter().map(|u| u.key.as_str()).collect::<Vec<_>>(), ["b:key", "a:key", "c:key"]);
144        assert_eq!(list[0].line, Some(3));
145        assert_eq!(list[2].line, None);
146    }
147
148    #[test]
149    fn a_non_ascii_key_is_compared_by_characters() {
150        let list = found(&["term:théme"]);
151        assert_eq!(list[0].suggestion.as_deref(), Some("term:theme"));
152    }
153
154    #[test]
155    fn distance_stops_early_when_the_lengths_alone_are_too_far_apart() {
156        let a: Vec<char> = "abc".chars().collect();
157        let b: Vec<char> = "abcdefgh".chars().collect();
158        assert_eq!(distance(&a, &b, 3), None);
159        assert_eq!(distance(&a, &a, 3), Some(0));
160    }
161}