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