//! Boundary laws and regression fixtures; these tests never load a model or execute Lisp. use super::*; /// A literal designed to expose any confusion between data and executable syntax. const ARGUMENT: &str = "Notes\") (delete-file \"secret\") ; \\ 笔记\n"; /// Construct a valid representative in each action's typed argument domain. fn fixture_action(kind: ActionKind) -> Result { let value = match kind { ActionKind::BrowserUrl => Some("HTTPS://Example.org:443/a%20b?q=%22literal%22#section"), ActionKind::FinderNewFolder => Some("Notes-笔记"), _ if kind.argument_name().is_some() => Some(ARGUMENT), _ => None, }; Action::new(kind, value.map(str::to_owned)) } /// Parse fixtures without forcing a model prediction for their natural-language text. fn clause(text: &str, name: Option<&str>) -> ParsedClause { ParsedClause { text: text.to_owned(), name: name.map(str::to_owned), } } /// Catalog order is a serialization contract shared with the checkpoint's output layer. #[test] fn labels_have_the_python_order_and_round_trip() -> Result<(), InputError> { let expected = [ "split-window-right", "split-window-below", "other-window", "delete-other-windows", "balance-windows", "beginning-of-buffer", "end-of-buffer", "switch-to-buffer", "previous-window", "delete-window", "save-buffer", "undo-only", "undo-redo", "beginning-of-line", "end-of-line", "forward-word", "backward-word", "scroll-up-command", "scroll-down-command", "mark-whole-buffer", "yank", "kill-line", "find-file", "search-forward", "lispm-finder-home", "lispm-finder-open-directory", "lispm-finder-back", "lispm-finder-forward", "lispm-finder-up", "lispm-finder-refresh", "lispm-finder-new-folder", "lispm-browser", "lispm-browser-open-url", "lispm-browser-back", "lispm-browser-forward", "lispm-browser-reload", "lispm-browser-new-tab", "lispm-browser-next-tab", "lispm-browser-previous-tab", "lispm-browser-close-shown-tab", "lispm-stickies", "lispm-stickies-new-note", "lispm-stickies-next-note", "lispm-stickies-previous-note", "lispm-rotom", "lispm-comfyui", "lispm-office", "lispm-mail", ]; assert_eq!(ACTION_LABELS, expected); for (kind, label) in ActionKind::ALL.into_iter().zip(expected) { assert_eq!(ActionKind::from_label(label)?, kind); assert_eq!(kind.label(), label); } for invalid in [ "reject", "delete-file", "SPLIT-WINDOW-RIGHT", "", "other-window -1", ] { assert_eq!( ActionKind::from_label(invalid), Err(InputError::UnknownAction) ); } Ok(()) } /// Fixed arguments and argument-free symbols are not supplied by the model. #[test] fn fixed_forms_match_the_whitelist() -> Result<(), InputError> { let forms = [ ("split-window-right", "(split-window-right)"), ("split-window-below", "(split-window-below)"), ("other-window", "(other-window 1)"), ("delete-other-windows", "(delete-other-windows)"), ("balance-windows", "(balance-windows)"), ("beginning-of-buffer", "(beginning-of-buffer)"), ("end-of-buffer", "(end-of-buffer)"), ("previous-window", "(other-window -1)"), ("delete-window", "(delete-window)"), ("save-buffer", "(save-buffer)"), ("undo-only", "(undo-only 1)"), ("undo-redo", "(undo-redo 1)"), ("beginning-of-line", "(beginning-of-line)"), ("end-of-line", "(end-of-line)"), ("forward-word", "(forward-word 1)"), ("backward-word", "(backward-word 1)"), ("scroll-up-command", "(scroll-up-command)"), ("scroll-down-command", "(scroll-down-command)"), ("mark-whole-buffer", "(mark-whole-buffer)"), ("yank", "(yank)"), ("kill-line", "(kill-line)"), ("lispm-finder-home", "(lispm-finder-home)"), ("lispm-finder-back", "(lispm-finder-back)"), ("lispm-finder-forward", "(lispm-finder-forward)"), ("lispm-finder-up", "(lispm-finder-up)"), ("lispm-finder-refresh", "(lispm-finder-refresh)"), ("lispm-browser", "(lispm-browser)"), ("lispm-browser-back", "(lispm-browser-back)"), ("lispm-browser-forward", "(lispm-browser-forward)"), ("lispm-browser-reload", "(lispm-browser-reload)"), ( "lispm-browser-new-tab", "(lispm-browser-new-tab \"about:blank\")", ), ("lispm-browser-next-tab", "(lispm-browser-next-tab)"), ("lispm-browser-previous-tab", "(lispm-browser-previous-tab)"), ( "lispm-browser-close-shown-tab", "(lispm-browser-close-shown-tab)", ), ("lispm-stickies", "(lispm-stickies)"), ("lispm-stickies-next-note", "(lispm-stickies-next-note)"), ( "lispm-stickies-previous-note", "(lispm-stickies-previous-note)", ), ("lispm-rotom", "(lispm-rotom)"), ("lispm-comfyui", "(lispm-comfyui)"), ("lispm-office", "(lispm-office)"), ("lispm-mail", "(lispm-mail)"), ]; assert_eq!(forms.len(), 41); for (label, expected) in forms { let action = Action::new(ActionKind::from_label(label)?, None)?; assert_eq!(action.to_lisp(), expected); assert!(action.name().is_none()); } Ok(()) } /// Every constructor enforces its exact argument cardinality and typed JSON field. #[test] fn typed_string_fields_are_required_only_for_the_seven_parameterized_actions() -> Result<(), InputError> { let fields = [ (ActionKind::SwitchBuffer, "name"), (ActionKind::OpenFile, "path"), (ActionKind::SearchForward, "text"), (ActionKind::FinderDirectory, "path"), (ActionKind::FinderNewFolder, "name"), (ActionKind::BrowserUrl, "url"), (ActionKind::StickiesNewNote, "text"), ]; for kind in ActionKind::ALL { let expected = fields .iter() .find(|(entry, _)| *entry == kind) .map(|(_, field)| *field); assert_eq!(kind.argument_name(), expected); if let Some(field) = expected { for value in [None, Some(String::new()), Some("a\0b".to_owned())] { assert!(Action::new(kind, value).is_err(), "{kind:?}"); } let action = fixture_action(kind)?; assert_eq!( action.to_json().get(field).and_then(Value::as_str), action.name() ); assert_eq!(action.to_json().as_object().map(Map::len), Some(2)); } else { assert_eq!( Action::new(kind, Some("unexpected".to_owned())), Err(InputError::UnexpectedArgument) ); } } Ok(()) } /// Each Unicode scalar remains literal data; all JSON control escapes round-trip. #[test] fn rendered_strings_preserve_data_and_escape_code_delimiters() -> Result<(), InputError> { let values = [ ARGUMENT, "a\u{1}b\u{8}\u{c}\r\t\n", "📝 笔记\u{2028}\u{7f}", " ", "NAME", "a/b", ]; for value in values { let literal = quote_lisp_string(value); assert_eq!( serde_json::from_str::(&literal).ok().as_deref(), Some(value) ); for kind in [ ActionKind::SwitchBuffer, ActionKind::OpenFile, ActionKind::SearchForward, ActionKind::FinderDirectory, ActionKind::StickiesNewNote, ] { assert_eq!( Action::new(kind, Some(value.to_owned()))?.to_lisp(), format!("({} {literal})", kind.label()) ); } } assert_eq!( quote_lisp_string("\u{1}\u{8}\u{c}\n\r\t\"\\"), "\"\\u0001\\b\\f\\n\\r\\t\\\"\\\\\"" ); Ok(()) } /// Python's intentionally permissive host validation is preserved without URL rewriting. #[test] fn browser_url_domain_matches_reference_edge_cases() -> Result<(), InputError> { let accepted = [ "https://example.org/", "HTTP://LOCALHOST:8080/path?q=one#two", "https://example.org:", "https://user:password@example.org:00080/path", "https://example.org:0/", "https://example.org:65535/", "https://例え.テスト/路径", "https://[::1]:8080/", "http://[fe80::1%25en0]/", "http://[v1.arbitrary:future]/", "http://a_b/", "http://-odd-./", "http://%zz/", "http://a\\b/", "http://a\"b/", "http://a|b/", "http://a/", "http://host/[]", "https://example.org/a%20b?q=%22text%22", ]; for value in accepted { let action = Action::new(ActionKind::BrowserUrl, Some(value.to_owned()))?; assert_eq!(action.name(), Some(value)); assert_eq!( action.to_lisp(), format!("(lispm-browser-open-url {})", quote_lisp_string(value)) ); } let rejected = [ "example.org", "/relative", "file:///tmp/notes", "javascript:alert(1)", "data:text/plain,hello", "https://", "http:///path", "http:example.org", "http://@/", "http://:80/", "https://[invalid]/", "http://[127.0.0.1]/", "http://[V1.foo]/", "http://[v1.]/", "http://[::1]suffix/", "http://prefix[::1]/", "http://[::1", "http://::1/", "http://[fe80::1%]/", "http://[fe80::1%a%b]/", "https://example.org/a b", "https://example.org/\nvalue", "https://example.org/\tvalue", "https://example.org/\u{1}value", "https://example.org/\u{7f}value", "https://example.org/\u{a0}value", "https://example.org:bad/", "https://example.org:-1/", "https://example.org:99999/", "https://example.org:12/", "https://example.org:80:90/", "http://exam/ple.org/", "http://exam:ple.org/", "http://exam℀ple.org/", "http://]/@host/", ]; for value in rejected { assert_eq!( Action::new(ActionKind::BrowserUrl, Some(value.to_owned())), Err(InputError::InvalidBrowserUrl), "{value}" ); } Ok(()) } /// Finder accepts one trimmed child basename and leaves its literal contents intact. #[test] fn folder_domain_matches_python_whitespace_and_path_rules() -> Result<(), InputError> { for value in [ "Project notes", "文件夹", "quoted \"folder\"", "..cache", "a\nb", "a\u{1c}b", ] { assert_eq!( Action::new(ActionKind::FinderNewFolder, Some(value.to_owned()))?.name(), Some(value) ); } for value in [ ".", "..", "/", "../folder", "nested/folder", "nested\\folder", "/tmp/folder", " Notes", "Notes ", "\u{1c}Notes", "Notes\u{a0}", ] { assert_eq!( Action::new(ActionKind::FinderNewFolder, Some(value.to_owned())), Err(InputError::InvalidFolderName) ); } Ok(()) } /// The grammar admits every allowed composition, including fixed and dynamic string data. #[test] fn all_2304_program_shapes_stay_within_the_closed_lisp_grammar() -> Result<(), InputError> { let string = r#""(?:\\["\\/bfnrt]|\\u[0-9a-fA-F]{4}|[^"\\\x00-\x1f])*""#; let nullary = concat!( "(?:split-window-right|split-window-below|delete-other-windows|balance-windows|", "beginning-of-buffer|end-of-buffer|delete-window|save-buffer|beginning-of-line|end-of-line|", "scroll-up-command|scroll-down-command|mark-whole-buffer|yank|kill-line|lispm-finder-home|", "lispm-finder-back|lispm-finder-forward|lispm-finder-up|lispm-finder-refresh|lispm-browser|", "lispm-browser-back|lispm-browser-forward|lispm-browser-reload|lispm-browser-next-tab|", "lispm-browser-previous-tab|lispm-browser-close-shown-tab|lispm-stickies|lispm-stickies-next-note|", "lispm-stickies-previous-note|lispm-rotom|lispm-comfyui|lispm-office|lispm-mail)" ); let counted = r"(?:\(other-window -?1\)|\((?:undo-only|undo-redo|forward-word|backward-word) 1\))"; let named = format!( r"\((?:switch-to-buffer|find-file|search-forward|lispm-finder-open-directory|lispm-finder-new-folder|lispm-browser-open-url|lispm-stickies-new-note) {string}\)" ); let atom = format!(r#"(?:\({nullary}\)|{counted}|{named}|\(lispm-browser-new-tab "about:blank"\))"#); let grammar = regex::Regex::new(&format!(r"\A(?:{atom}|\(progn {atom} {atom}\))\z")).ok(); assert!(grammar.is_some()); let mut checked = 0; for first in ActionKind::ALL { let one = Program::new(vec![fixture_action(first)?])?; assert!( grammar .as_ref() .is_some_and(|rule| rule.is_match(&one.to_lisp())), "{}", one.to_lisp() ); checked += 1; for second in ActionKind::ALL { if first == second { continue; } let pair = Program::new(vec![fixture_action(first)?, fixture_action(second)?])?; assert!( grammar .as_ref() .is_some_and(|rule| rule.is_match(&pair.to_lisp())), "{}", pair.to_lisp() ); let expected = format!( "(progn {} {})", fixture_action(first)?.to_lisp(), fixture_action(second)?.to_lisp() ); assert_eq!(pair.to_lisp(), expected); assert_eq!(pair.actions().len(), 2); checked += 1; } } assert_eq!(checked, 2304); Ok(()) } /// Invalid sequence lengths and repeated kinds cannot produce a program value. #[test] fn program_constructor_rejects_invalid_shapes() -> Result<(), InputError> { assert_eq!(Program::new(vec![]), Err(InputError::InvalidProgramLength)); assert_eq!( Program::new(vec![ fixture_action(ActionKind::SplitRight)?, fixture_action(ActionKind::SplitRight)? ]), Err(InputError::RepeatedOperation) ); assert_eq!( Program::new(vec![ fixture_action(ActionKind::SplitRight)?, fixture_action(ActionKind::SplitBelow)?, fixture_action(ActionKind::Yank)? ]), Err(InputError::InvalidProgramLength) ); let repeated = vec![ Action::new(ActionKind::SwitchBuffer, Some("a".to_owned()))?, Action::new(ActionKind::SwitchBuffer, Some("b".to_owned()))?, ]; assert_eq!(Program::new(repeated), Err(InputError::RepeatedOperation)); Ok(()) } /// Serialization preserves action order and the semantic name of each argument. #[test] fn json_proposals_match_the_python_facade() -> Result<(), InputError> { let program = Program::new(vec![ Action::new(ActionKind::OpenFile, Some("目录/笔记".to_owned()))?, Action::new( ActionKind::SearchForward, Some("literal then text".to_owned()), )?, ])?; assert_eq!( program.to_json(), serde_json::json!({"actions": [ {"action": "find-file", "path": "目录/笔记"}, {"action": "search-forward", "text": "literal then text"}, ]}) ); let blank = Program::new(vec![Action::new(ActionKind::BrowserNewTab, None)?])?; assert_eq!( blank.to_json(), serde_json::json!({"actions": [{"action": "lispm-browser-new-tab"}]}) ); Ok(()) } /// Accepted normalization preserves meaning and does not reject merely novel words. #[test] fn parser_normalizes_only_supported_prose_syntax() -> Result<(), InputError> { for value in [ " SPLIT\t RIGHT! ", "\u{a0}split right\u{1c}", "split right.", "split right ?", ] { assert_eq!(parse_command(value)?, vec![clause("split right", None)]); } for value in [ "quuxify the frobnicated panes", "flibbertigibbet", "show NAME buffer", "navigate long-term view", ] { assert_eq!(parse_command(value)?.len(), 1); } for connector in [" then ", " and then ", "\tand\tthen\t"] { assert_eq!( parse_command(&format!("split right{connector}balance the windows"))?, vec![ clause("split right", None), clause("balance the windows", None) ] ); } Ok(()) } /// Literal content is excluded from negation, connector and English-language parsing. #[test] fn json_strings_keep_exact_content_and_clause_ownership() -> Result<(), InputError> { let first = "目录/then \"notes\".txt"; let second = "find \\ this and then that"; for connector in [" then ", " and then "] { let command = format!( "open file {}{connector}search for {}", quote_lisp_string(first), quote_lisp_string(second) ); assert_eq!( parse_command(&command)?, vec![ clause("open file NAME", Some(first)), clause("search for NAME", Some(second)) ] ); } let literal = "笔记 then do not split right and then \"other\" \\ Notes"; assert_eq!( parse_command(&format!( "show buffer {} then split right", quote_lisp_string(literal) ))?, vec![ clause("show buffer NAME", Some(literal)), clause("split right", None) ] ); for name in ["a\"b", "C:\\notes", "a\nb", "a\tb", "NAME", "📝 笔记"] { assert_eq!( parse_command(&format!("show buffer {}", quote_lisp_string(name)))?, vec![clause("show buffer NAME", Some(name))] ); } assert_eq!( parse_command(r#"show buffer "\ud83d\udcdd \u7b14\u8bb0""#)?, vec![clause("show buffer NAME", Some("📝 笔记"))] ); assert_eq!( parse_command(r#"show buffer "a\/b""#)?, vec![clause("show buffer NAME", Some("a/b"))] ); Ok(()) } /// An argument may appear inside a clause or before a polite suffix. #[test] fn interior_arguments_stay_bound_to_the_original_clause() -> Result<(), InputError> { for (text, expected) in [ ("show buffer \"Notes\" please", "show buffer NAME please"), ("show \"Notes\" buffer", "show NAME buffer"), ( "make \"Notes\" the current buffer", "make NAME the current buffer", ), ] { assert_eq!(parse_command(text)?, vec![clause(expected, Some("Notes"))]); } assert_eq!( parse_command("make \"Notes\" the current buffer then find \"needle\" please")?, vec![ clause("make NAME the current buffer", Some("Notes")), clause("find NAME please", Some("needle")) ] ); assert_eq!( parse_command("show buffer \"a\" then show buffer \"b\"")?, vec![ clause("show buffer NAME", Some("a")), clause("show buffer NAME", Some("b")) ] ); Ok(()) } /// Invalid quoting never truncates an argument or silently discards following text. #[test] fn malformed_quotes_and_multiple_arguments_are_rejected() { for command in [ "show buffer \"Notes", "show buffer \"C:\\path\"", "show buffer \"a\" \"b\"", "open file \"a\" then search for \"b\" \"c\"", "open file \"a\" \"b\" then search for \"c\"", "show buffer \"\"", "show buffer \"a\"suffix", "show buffer\"a\"", "\"Notes\"", "show buffer 'a'", "show buffer \"a\". please", "show buffer \"a\"-please", "show buffer \"a\"\"b\"", "show buffer \"a\nvalue\"", "show buffer \"\\u0000\"", "show buffer \"\\ud800\"", ] { assert!(parse_command(command).is_err(), "{command:?}"); } } /// Unsupported syntax cannot be converted into a shorter accepted command. #[test] fn punctuation_negation_and_connective_rejections_match_python() { for command in [ "", " \t\n ", "!!!", "你好", ".", "---", "split right; split below", "split right\nsplit below", "split right!!", "split_right", "split 2 panes", "split -right", "split right-", "split--right", "do not split right", "don't split right", "never split right", "split right before split below", "split right after split below", "split right if needed", "split right or split below", "split right and split below", "then split right", "split right then", "split right then split below then balance the windows", "split right then then balance", "split right and then and then balance", "split right\u{a0}please", "split right\u{1c}please", ] { assert!(parse_command(command).is_err(), "{command:?}"); } for blocked in BLOCKED_WORDS { assert!( parse_command(&format!("{blocked} split right")).is_err(), "{blocked}" ); } } /// The limit counts the entire request, with a literal counted as one placeholder word. #[test] fn prompt_limit_is_global_and_literal_contents_do_not_consume_words() -> Result<(), InputError> { assert!(parse_command(&"word ".repeat(58)).is_ok()); assert_eq!( parse_command(&"word ".repeat(59)), Err(InputError::PromptTooLong) ); assert!( parse_command(&format!( "{}then {}", "word ".repeat(29), "word ".repeat(29) )) .is_err() ); let long_literal = "then not no if ".repeat(100); assert_eq!( parse_command(&format!("show buffer {}", quote_lisp_string(&long_literal)))?, vec![clause("show buffer NAME", Some(&long_literal))] ); Ok(()) } /// The port agrees with frozen Python parsing results and typed-argument decisions. #[test] fn python_boundary_reference_matches_without_running_python() -> Result<(), InputError> { let reference = serde_json::from_str::(include_str!( "../tests/fixtures/python-boundary-reference.json" )) .map_err(|_| InputError::MalformedQuotedArgument)?; let parser = reference .get("parser") .and_then(Value::as_array) .ok_or(InputError::MalformedQuotedArgument)?; assert!(parser.len() > 1000); for row in parser { let input = row .get("input") .and_then(Value::as_str) .ok_or(InputError::InstructionRequired)?; match parse_command(input) { Ok(clauses) => { let actual: Vec<_> = clauses .iter() .map(|clause| { serde_json::json!({ "text": clause.text, "name": clause.name, }) }) .collect(); assert_eq!(row.get("clauses"), Some(&Value::Array(actual)), "{input:?}"); } Err(error) => assert!( row.get("error").and_then(Value::as_str).is_some(), "Rust rejected Python-accepted input {input:?}: {error}" ), } } let arguments = reference .get("arguments") .and_then(Value::as_array) .ok_or(InputError::MalformedQuotedArgument)?; assert!(arguments.len() > 1000); for row in arguments { let label = row .get("label") .and_then(Value::as_str) .ok_or(InputError::UnknownAction)?; let name = row .get("argument") .and_then(Value::as_str) .map(str::to_owned); match Action::new(ActionKind::from_label(label)?, name) { Ok(action) => assert_eq!( row.get("expected").and_then(Value::as_str), Some(action.to_lisp().as_str()), "{row}" ), Err(error) => assert_eq!( row.get("error").and_then(Value::as_str), Some(error.to_string().as_str()), "{row}" ), } } Ok(()) }