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 calls;
58pub mod checkpoint;
59pub mod commands;
60pub mod compress;
61pub mod config;
62pub mod context;
63pub mod db;
64pub mod edit;
65pub mod error;
66pub mod extract;
67pub mod format;
68pub mod fs_lock;
69pub mod fuzzy_match;
70pub mod grep_executor;
71pub mod harness;
72pub mod imports;
73pub mod indent;
74pub mod inspect;
75pub mod language;
76pub mod local_embed;
77pub mod log_ctx;
78pub mod lsp;
79pub mod lsp_hints;
80pub mod migrate_storage;
81pub mod parser;
82pub mod pattern_compile;
83pub mod protocol;
84pub mod query_shape;
85pub mod search_index;
86pub mod semantic_index;
87pub mod symbol_cache_disk;
88pub mod symbols;
89pub mod tool_path;
90pub mod url_fetch;
91// Compiled on all platforms so cross-platform unit tests in
92// `commands::bash::try_spawn_with_fallback` can exercise the retry
93// decision logic without a real Windows runtime. The module itself only
94// uses portable APIs; only its callers are Windows-gated.
95pub mod windows_shell;
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100    use config::Config;
101    use error::AftError;
102    use protocol::{RawRequest, Response};
103
104    // --- Protocol serialization ---
105
106    #[test]
107    fn raw_request_deserializes_ping() {
108        let json = r#"{"id":"1","command":"ping"}"#;
109        let req: RawRequest = serde_json::from_str(json).unwrap();
110        assert_eq!(req.id, "1");
111        assert_eq!(req.command, "ping");
112        assert!(req.lsp_hints.is_none());
113    }
114
115    #[test]
116    fn raw_request_deserializes_echo_with_params() {
117        let json = r#"{"id":"2","command":"echo","message":"hello"}"#;
118        let req: RawRequest = serde_json::from_str(json).unwrap();
119        assert_eq!(req.id, "2");
120        assert_eq!(req.command, "echo");
121        // "message" is captured in the flattened params
122        assert_eq!(req.params["message"], "hello");
123    }
124
125    #[test]
126    fn raw_request_preserves_unknown_fields() {
127        let json = r#"{"id":"3","command":"ping","future_field":"abc","nested":{"x":1}}"#;
128        let req: RawRequest = serde_json::from_str(json).unwrap();
129        assert_eq!(req.params["future_field"], "abc");
130        assert_eq!(req.params["nested"]["x"], 1);
131    }
132
133    #[test]
134    fn raw_request_with_lsp_hints() {
135        let json = r#"{"id":"4","command":"ping","lsp_hints":{"completions":["foo","bar"]}}"#;
136        let req: RawRequest = serde_json::from_str(json).unwrap();
137        assert!(req.lsp_hints.is_some());
138        let hints = req.lsp_hints.unwrap();
139        assert_eq!(hints["completions"][0], "foo");
140    }
141
142    #[test]
143    fn response_success_round_trip() {
144        let resp = Response::success("42", serde_json::json!({"command": "pong"}));
145        let json_str = serde_json::to_string(&resp).unwrap();
146        let v: serde_json::Value = serde_json::from_str(&json_str).unwrap();
147        assert_eq!(v["id"], "42");
148        assert_eq!(v["success"], true);
149        assert_eq!(v["command"], "pong");
150    }
151
152    #[test]
153    fn response_error_round_trip() {
154        let resp = Response::error("99", "unknown_command", "unknown command: foo");
155        let json_str = serde_json::to_string(&resp).unwrap();
156        let v: serde_json::Value = serde_json::from_str(&json_str).unwrap();
157        assert_eq!(v["id"], "99");
158        assert_eq!(v["success"], false);
159        assert_eq!(v["code"], "unknown_command");
160        assert_eq!(v["message"], "unknown command: foo");
161    }
162
163    // --- Error formatting ---
164
165    #[test]
166    fn error_display_symbol_not_found() {
167        let err = AftError::SymbolNotFound {
168            name: "foo".into(),
169            file: "bar.rs".into(),
170        };
171        assert_eq!(err.to_string(), "symbol 'foo' not found in bar.rs");
172        assert_eq!(err.code(), "symbol_not_found");
173    }
174
175    #[test]
176    fn error_display_ambiguous_symbol() {
177        let err = AftError::AmbiguousSymbol {
178            name: "Foo".into(),
179            candidates: vec!["a.rs:10".into(), "b.rs:20".into()],
180        };
181        let s = err.to_string();
182        assert!(s.contains("Foo"));
183        assert!(s.contains("a.rs:10, b.rs:20"));
184    }
185
186    #[test]
187    fn error_display_parse_error() {
188        let err = AftError::ParseError {
189            message: "unexpected token".into(),
190        };
191        assert_eq!(err.to_string(), "parse error: unexpected token");
192    }
193
194    #[test]
195    fn error_display_file_not_found() {
196        let err = AftError::FileNotFound {
197            path: "/tmp/missing.rs".into(),
198        };
199        assert_eq!(err.to_string(), "file not found: /tmp/missing.rs");
200    }
201
202    #[test]
203    fn error_display_invalid_request() {
204        let err = AftError::InvalidRequest {
205            message: "missing field".into(),
206        };
207        assert_eq!(err.to_string(), "invalid request: missing field");
208    }
209
210    #[test]
211    fn error_display_checkpoint_not_found() {
212        let err = AftError::CheckpointNotFound {
213            name: "pre-refactor".into(),
214        };
215        assert_eq!(err.to_string(), "checkpoint not found: pre-refactor");
216        assert_eq!(err.code(), "checkpoint_not_found");
217    }
218
219    #[test]
220    fn error_display_no_undo_history() {
221        let err = AftError::NoUndoHistory {
222            path: "src/main.rs".into(),
223        };
224        assert_eq!(err.to_string(), "no undo history for: src/main.rs");
225        assert_eq!(err.code(), "no_undo_history");
226    }
227
228    #[test]
229    fn error_display_ambiguous_match() {
230        let err = AftError::AmbiguousMatch {
231            pattern: "TODO".into(),
232            count: 5,
233        };
234        assert_eq!(
235            err.to_string(),
236            "pattern 'TODO' matches 5 occurrences, expected exactly 1"
237        );
238        assert_eq!(err.code(), "ambiguous_match");
239    }
240
241    #[test]
242    fn error_display_project_too_large() {
243        let err = AftError::ProjectTooLarge {
244            count: 20001,
245            max: 20000,
246        };
247        assert_eq!(
248            err.to_string(),
249            "project has 20001 source files, exceeding max_callgraph_files=20000. Call-graph operations (callers, trace_to, trace_to_symbol, trace_data, impact) are disabled for this root. Open a specific subdirectory or raise max_callgraph_files in config."
250        );
251        assert_eq!(err.code(), "project_too_large");
252    }
253
254    #[test]
255    fn error_to_json_has_code_and_message() {
256        let err = AftError::FileNotFound { path: "/x".into() };
257        let j = err.to_error_json();
258        assert_eq!(j["code"], "file_not_found");
259        assert!(j["message"].as_str().unwrap().contains("/x"));
260    }
261
262    // --- Config defaults ---
263
264    #[test]
265    fn config_default_values() {
266        let cfg = Config::default();
267        assert!(cfg.project_root.is_none());
268        assert_eq!(cfg.validation_depth, 1);
269        assert_eq!(cfg.checkpoint_ttl_hours, 24);
270        assert_eq!(cfg.max_symbol_depth, 10);
271        assert_eq!(cfg.formatter_timeout_secs, 10);
272        assert_eq!(cfg.type_checker_timeout_secs, 30);
273        assert_eq!(cfg.max_callgraph_files, 5_000);
274    }
275}