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