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 agent_child_env;
50pub mod alert_records;
51pub mod alert_state;
52pub mod alias;
53pub mod artifact_owner;
54pub mod ast_grep_hints;
55pub mod ast_grep_lang;
56pub mod backup;
57pub mod bash_background;
58pub mod bash_permissions;
59pub mod bash_rewrite;
60pub mod blob_store;
61pub mod build_breaker;
62pub mod cache_freshness;
63pub mod callgraph;
64pub mod callgraph_store;
65pub mod calls;
66pub mod checkpoint;
67pub mod cold_build_limiter;
68pub mod commands;
69pub mod compress;
70pub mod config;
71pub mod config_resolve;
72pub mod context;
73pub mod db;
74pub mod edit;
75pub mod effective_path;
76#[doc(hidden)]
77pub mod environment;
78pub mod error;
79pub mod executor;
80pub mod extract;
81pub mod fleet_status;
82pub mod format;
83pub mod fs_lock;
84pub mod fuzzy_match;
85pub mod gc;
86pub mod gh_shim;
87pub mod github_read;
88pub mod grep_executor;
89pub mod harness;
90pub mod hashline;
91pub mod imports;
92pub mod indent;
93pub mod inspect;
94pub mod jsonc;
95pub mod language;
96pub mod legacy_partitions;
97pub(crate) mod lifecycle_census;
98pub mod list_envelope;
99pub mod list_surfaces;
100pub mod local_embed;
101pub mod log_ctx;
102pub mod logging;
103pub mod lsp;
104pub mod lsp_hints;
105pub mod memory;
106pub mod migrate_storage;
107pub mod migration;
108pub mod ndjson_text;
109pub mod parser;
110pub mod patch;
111pub mod path_identity;
112pub mod path_status;
113pub mod pattern_compile;
114pub mod pins;
115mod platform_tls;
116pub mod process_io;
117pub mod protocol;
118pub mod pty_render;
119pub mod query_shape;
120pub mod readonly_artifacts;
121pub mod refresh;
122pub mod response_finalize;
123pub mod root_cache;
124pub mod run_tool_call;
125pub mod runtime_drain;
126pub mod runtime_registry;
127pub mod sandbox_profile;
128pub mod sandbox_spawn;
129pub mod scoped_key;
130pub mod search_b2;
131pub mod search_index;
132pub mod semantic_index;
133pub mod standing_roots;
134pub mod subc;
135pub mod subc_config;
136pub mod subc_format;
137pub mod subc_translate;
138pub mod symbol_cache_disk;
139pub mod symbol_diff;
140pub mod symbols;
141pub mod synapse_embed;
142pub mod tool_path;
143pub mod url_fetch;
144pub mod views;
145pub(crate) mod walk_boundary;
146pub mod watcher;
147pub(crate) mod watcher_backend;
148pub mod watcher_filter;
149// Compiled on all platforms so cross-platform unit tests in
150// `commands::bash::try_spawn_with_fallback` can exercise the retry
151// decision logic without a real Windows runtime. The module itself only
152// uses portable APIs; only its callers are Windows-gated.
153pub(crate) mod windows_command;
154pub mod windows_path;
155pub mod windows_shell;
156
157#[cfg(test)]
158pub(crate) mod test_allocations;
159#[cfg(test)]
160pub(crate) mod test_env;
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165    use config::Config;
166    use error::AftError;
167    use protocol::{RawRequest, Response};
168
169    // --- Protocol serialization ---
170
171    #[test]
172    fn raw_request_deserializes_ping() {
173        let json = r#"{"id":"1","command":"ping"}"#;
174        let req: RawRequest = serde_json::from_str(json).unwrap();
175        assert_eq!(req.id, "1");
176        assert_eq!(req.command, "ping");
177        assert!(req.lsp_hints.is_none());
178    }
179
180    #[test]
181    fn raw_request_deserializes_echo_with_params() {
182        let json = r#"{"id":"2","command":"echo","message":"hello"}"#;
183        let req: RawRequest = serde_json::from_str(json).unwrap();
184        assert_eq!(req.id, "2");
185        assert_eq!(req.command, "echo");
186        // "message" is captured in the flattened params
187        assert_eq!(req.params["message"], "hello");
188    }
189
190    #[test]
191    fn raw_request_preserves_unknown_fields() {
192        let json = r#"{"id":"3","command":"ping","future_field":"abc","nested":{"x":1}}"#;
193        let req: RawRequest = serde_json::from_str(json).unwrap();
194        assert_eq!(req.params["future_field"], "abc");
195        assert_eq!(req.params["nested"]["x"], 1);
196    }
197
198    #[test]
199    fn raw_request_with_lsp_hints() {
200        let json = r#"{"id":"4","command":"ping","lsp_hints":{"completions":["foo","bar"]}}"#;
201        let req: RawRequest = serde_json::from_str(json).unwrap();
202        assert!(req.lsp_hints.is_some());
203        let hints = req.lsp_hints.unwrap();
204        assert_eq!(hints["completions"][0], "foo");
205    }
206
207    #[test]
208    fn response_success_round_trip() {
209        let resp = Response::success("42", serde_json::json!({"command": "pong"}));
210        let json_str = serde_json::to_string(&resp).unwrap();
211        let v: serde_json::Value = serde_json::from_str(&json_str).unwrap();
212        assert_eq!(v["id"], "42");
213        assert_eq!(v["success"], true);
214        assert_eq!(v["command"], "pong");
215    }
216
217    #[test]
218    fn response_error_round_trip() {
219        let resp = Response::error("99", "unknown_command", "unknown command: foo");
220        let json_str = serde_json::to_string(&resp).unwrap();
221        let v: serde_json::Value = serde_json::from_str(&json_str).unwrap();
222        assert_eq!(v["id"], "99");
223        assert_eq!(v["success"], false);
224        assert_eq!(v["code"], "unknown_command");
225        assert_eq!(v["message"], "unknown command: foo");
226    }
227
228    // --- Error formatting ---
229
230    #[test]
231    fn error_display_symbol_not_found() {
232        let err = AftError::SymbolNotFound {
233            name: "foo".into(),
234            file: "bar.rs".into(),
235        };
236        assert_eq!(err.to_string(), "symbol 'foo' not found in bar.rs");
237        assert_eq!(err.code(), "symbol_not_found");
238    }
239
240    #[test]
241    fn error_display_ambiguous_symbol() {
242        let err = AftError::AmbiguousSymbol {
243            name: "Foo".into(),
244            candidates: vec!["a.rs:10".into(), "b.rs:20".into()],
245        };
246        let s = err.to_string();
247        assert!(s.contains("Foo"));
248        assert!(s.contains("a.rs:10, b.rs:20"));
249    }
250
251    #[test]
252    fn error_display_parse_error() {
253        let err = AftError::ParseError {
254            message: "unexpected token".into(),
255        };
256        assert_eq!(err.to_string(), "parse error: unexpected token");
257    }
258
259    #[test]
260    fn error_display_file_not_found() {
261        let err = AftError::FileNotFound {
262            path: "/tmp/missing.rs".into(),
263        };
264        assert_eq!(err.to_string(), "file not found: /tmp/missing.rs");
265    }
266
267    #[test]
268    fn error_display_invalid_request() {
269        let err = AftError::InvalidRequest {
270            message: "missing field".into(),
271        };
272        assert_eq!(err.to_string(), "invalid request: missing field");
273    }
274
275    #[test]
276    fn error_display_checkpoint_not_found() {
277        let err = AftError::CheckpointNotFound {
278            name: "pre-refactor".into(),
279        };
280        assert_eq!(err.to_string(), "checkpoint not found: pre-refactor");
281        assert_eq!(err.code(), "checkpoint_not_found");
282    }
283
284    #[test]
285    fn error_display_no_undo_history() {
286        let err = AftError::NoUndoHistory {
287            path: "src/main.rs".into(),
288        };
289        assert_eq!(err.to_string(), "no undo history for: src/main.rs");
290        assert_eq!(err.code(), "no_undo_history");
291    }
292
293    #[test]
294    fn error_display_ambiguous_match() {
295        let err = AftError::AmbiguousMatch {
296            pattern: "TODO".into(),
297            count: 5,
298        };
299        assert_eq!(
300            err.to_string(),
301            "pattern 'TODO' matches 5 occurrences, expected exactly 1"
302        );
303        assert_eq!(err.code(), "ambiguous_match");
304    }
305
306    #[test]
307    fn error_to_json_has_code_and_message() {
308        let err = AftError::FileNotFound { path: "/x".into() };
309        let j = err.to_error_json();
310        assert_eq!(j["code"], "file_not_found");
311        assert!(j["message"].as_str().unwrap().contains("/x"));
312    }
313
314    // --- Config defaults ---
315
316    #[test]
317    fn config_default_values() {
318        let cfg = Config::default();
319        assert!(cfg.project_root.is_none());
320        assert_eq!(cfg.validation_depth, 1);
321        assert_eq!(cfg.checkpoint_ttl_hours, 24);
322        assert_eq!(cfg.max_symbol_depth, 10);
323        assert_eq!(cfg.formatter_timeout_secs, 10);
324        assert_eq!(cfg.type_checker_timeout_secs, 30);
325    }
326}
327
328#[cfg(all(test, target_os = "macos"))]
329mod disk_write_hunt;