Skip to main content

aft/
lib.rs

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