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