Skip to main content

aft/
lib.rs

1#![allow(
2    clippy::collapsible_if,
3    clippy::double_ended_iterator_last,
4    clippy::int_plus_one,
5    clippy::large_enum_variant,
6    clippy::len_without_is_empty,
7    clippy::let_and_return,
8    clippy::manual_contains,
9    clippy::manual_pattern_char_comparison,
10    clippy::manual_repeat_n,
11    clippy::manual_strip,
12    clippy::manual_unwrap_or_default,
13    clippy::map_clone,
14    clippy::needless_borrow,
15    clippy::needless_borrows_for_generic_args,
16    clippy::needless_range_loop,
17    clippy::new_without_default,
18    clippy::obfuscated_if_else,
19    clippy::ptr_arg,
20    clippy::question_mark,
21    clippy::same_item_push,
22    clippy::should_implement_trait,
23    clippy::single_match,
24    clippy::too_many_arguments,
25    clippy::type_complexity,
26    clippy::unnecessary_cast,
27    clippy::unnecessary_lazy_evaluations,
28    clippy::unnecessary_map_or
29)]
30
31// ## Note on `.unwrap()` / `.expect()` usage
32//
33// The remaining `.unwrap()` and `.expect()` calls in `src/` are in:
34// - **Tree-sitter query operations** (parser.rs, zoom.rs, extract.rs, inline.rs,
35//   outline.rs): These operate on AFT's own compiled grammars and query patterns, which
36//   are compile-time constants. Pattern captures and node kinds are guaranteed to exist.
37// - **Checkpoint serialization** (checkpoint.rs): serde_json::to_value on known-good
38//   HashMap<PathBuf, String> types cannot fail.
39// - **lib.rs main loop**: JSON parsing of stdin lines — a malformed line is logged and
40//   skipped, not unwrapped.
41//
42// All production command handlers that process user/agent input return Result or
43// Response::error instead of panicking. Confirmed zero .unwrap()/.expect() in
44// production error paths as of v0.6.3 audit.
45
46pub mod ast_grep_hints;
47pub mod ast_grep_lang;
48pub mod backup;
49pub mod bash_background;
50pub mod bash_permissions;
51pub mod bash_rewrite;
52pub mod callgraph;
53pub mod calls;
54pub mod checkpoint;
55pub mod commands;
56pub mod compress;
57pub mod config;
58pub mod context;
59pub mod edit;
60pub mod error;
61pub mod extract;
62pub mod format;
63pub mod fuzzy_match;
64pub mod imports;
65pub mod indent;
66pub mod language;
67pub mod log_ctx;
68pub mod lsp;
69pub mod lsp_hints;
70pub mod parser;
71pub mod protocol;
72pub mod query_shape;
73pub mod search_index;
74pub mod semantic_index;
75pub mod symbol_cache_disk;
76pub mod symbols;
77// Compiled on all platforms so cross-platform unit tests in
78// `commands::bash::try_spawn_with_fallback` can exercise the retry
79// decision logic without a real Windows runtime. The module itself only
80// uses portable APIs; only its callers are Windows-gated.
81pub mod windows_shell;
82
83#[cfg(test)]
84mod tests {
85    use super::*;
86    use config::Config;
87    use error::AftError;
88    use protocol::{RawRequest, Response};
89
90    // --- Protocol serialization ---
91
92    #[test]
93    fn raw_request_deserializes_ping() {
94        let json = r#"{"id":"1","command":"ping"}"#;
95        let req: RawRequest = serde_json::from_str(json).unwrap();
96        assert_eq!(req.id, "1");
97        assert_eq!(req.command, "ping");
98        assert!(req.lsp_hints.is_none());
99    }
100
101    #[test]
102    fn raw_request_deserializes_echo_with_params() {
103        let json = r#"{"id":"2","command":"echo","message":"hello"}"#;
104        let req: RawRequest = serde_json::from_str(json).unwrap();
105        assert_eq!(req.id, "2");
106        assert_eq!(req.command, "echo");
107        // "message" is captured in the flattened params
108        assert_eq!(req.params["message"], "hello");
109    }
110
111    #[test]
112    fn raw_request_preserves_unknown_fields() {
113        let json = r#"{"id":"3","command":"ping","future_field":"abc","nested":{"x":1}}"#;
114        let req: RawRequest = serde_json::from_str(json).unwrap();
115        assert_eq!(req.params["future_field"], "abc");
116        assert_eq!(req.params["nested"]["x"], 1);
117    }
118
119    #[test]
120    fn raw_request_with_lsp_hints() {
121        let json = r#"{"id":"4","command":"ping","lsp_hints":{"completions":["foo","bar"]}}"#;
122        let req: RawRequest = serde_json::from_str(json).unwrap();
123        assert!(req.lsp_hints.is_some());
124        let hints = req.lsp_hints.unwrap();
125        assert_eq!(hints["completions"][0], "foo");
126    }
127
128    #[test]
129    fn response_success_round_trip() {
130        let resp = Response::success("42", serde_json::json!({"command": "pong"}));
131        let json_str = serde_json::to_string(&resp).unwrap();
132        let v: serde_json::Value = serde_json::from_str(&json_str).unwrap();
133        assert_eq!(v["id"], "42");
134        assert_eq!(v["success"], true);
135        assert_eq!(v["command"], "pong");
136    }
137
138    #[test]
139    fn response_error_round_trip() {
140        let resp = Response::error("99", "unknown_command", "unknown command: foo");
141        let json_str = serde_json::to_string(&resp).unwrap();
142        let v: serde_json::Value = serde_json::from_str(&json_str).unwrap();
143        assert_eq!(v["id"], "99");
144        assert_eq!(v["success"], false);
145        assert_eq!(v["code"], "unknown_command");
146        assert_eq!(v["message"], "unknown command: foo");
147    }
148
149    // --- Error formatting ---
150
151    #[test]
152    fn error_display_symbol_not_found() {
153        let err = AftError::SymbolNotFound {
154            name: "foo".into(),
155            file: "bar.rs".into(),
156        };
157        assert_eq!(err.to_string(), "symbol 'foo' not found in bar.rs");
158        assert_eq!(err.code(), "symbol_not_found");
159    }
160
161    #[test]
162    fn error_display_ambiguous_symbol() {
163        let err = AftError::AmbiguousSymbol {
164            name: "Foo".into(),
165            candidates: vec!["a.rs:10".into(), "b.rs:20".into()],
166        };
167        let s = err.to_string();
168        assert!(s.contains("Foo"));
169        assert!(s.contains("a.rs:10, b.rs:20"));
170    }
171
172    #[test]
173    fn error_display_parse_error() {
174        let err = AftError::ParseError {
175            message: "unexpected token".into(),
176        };
177        assert_eq!(err.to_string(), "parse error: unexpected token");
178    }
179
180    #[test]
181    fn error_display_file_not_found() {
182        let err = AftError::FileNotFound {
183            path: "/tmp/missing.rs".into(),
184        };
185        assert_eq!(err.to_string(), "file not found: /tmp/missing.rs");
186    }
187
188    #[test]
189    fn error_display_invalid_request() {
190        let err = AftError::InvalidRequest {
191            message: "missing field".into(),
192        };
193        assert_eq!(err.to_string(), "invalid request: missing field");
194    }
195
196    #[test]
197    fn error_display_checkpoint_not_found() {
198        let err = AftError::CheckpointNotFound {
199            name: "pre-refactor".into(),
200        };
201        assert_eq!(err.to_string(), "checkpoint not found: pre-refactor");
202        assert_eq!(err.code(), "checkpoint_not_found");
203    }
204
205    #[test]
206    fn error_display_no_undo_history() {
207        let err = AftError::NoUndoHistory {
208            path: "src/main.rs".into(),
209        };
210        assert_eq!(err.to_string(), "no undo history for: src/main.rs");
211        assert_eq!(err.code(), "no_undo_history");
212    }
213
214    #[test]
215    fn error_display_ambiguous_match() {
216        let err = AftError::AmbiguousMatch {
217            pattern: "TODO".into(),
218            count: 5,
219        };
220        assert_eq!(
221            err.to_string(),
222            "pattern 'TODO' matches 5 occurrences, expected exactly 1"
223        );
224        assert_eq!(err.code(), "ambiguous_match");
225    }
226
227    #[test]
228    fn error_display_project_too_large() {
229        let err = AftError::ProjectTooLarge {
230            count: 20001,
231            max: 20000,
232        };
233        assert_eq!(
234            err.to_string(),
235            "project has 20001 source files, exceeding max_callgraph_files=20000. Call-graph operations (callers, trace_to, trace_data, impact) are disabled for this root. Open a specific subdirectory or raise max_callgraph_files in config."
236        );
237        assert_eq!(err.code(), "project_too_large");
238    }
239
240    #[test]
241    fn error_to_json_has_code_and_message() {
242        let err = AftError::FileNotFound { path: "/x".into() };
243        let j = err.to_error_json();
244        assert_eq!(j["code"], "file_not_found");
245        assert!(j["message"].as_str().unwrap().contains("/x"));
246    }
247
248    // --- Config defaults ---
249
250    #[test]
251    fn config_default_values() {
252        let cfg = Config::default();
253        assert!(cfg.project_root.is_none());
254        assert_eq!(cfg.validation_depth, 1);
255        assert_eq!(cfg.checkpoint_ttl_hours, 24);
256        assert_eq!(cfg.max_symbol_depth, 10);
257        assert_eq!(cfg.formatter_timeout_secs, 10);
258        assert_eq!(cfg.type_checker_timeout_secs, 30);
259        assert_eq!(cfg.max_callgraph_files, 5_000);
260    }
261}