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 protocol;
117pub mod pty_render;
118pub mod query_shape;
119pub mod readonly_artifacts;
120pub mod refresh;
121pub mod response_finalize;
122pub mod root_cache;
123pub mod run_tool_call;
124pub mod runtime_drain;
125pub mod runtime_registry;
126pub mod sandbox_profile;
127pub mod sandbox_spawn;
128pub mod scoped_key;
129pub mod search_b2;
130pub mod search_index;
131pub mod semantic_index;
132pub mod standing_roots;
133pub mod subc;
134pub mod subc_config;
135pub mod subc_format;
136pub mod subc_translate;
137pub mod symbol_cache_disk;
138pub mod symbol_diff;
139pub mod symbols;
140pub mod synapse_embed;
141pub mod tool_path;
142pub mod url_fetch;
143pub mod views;
144pub(crate) mod walk_boundary;
145pub mod watcher;
146pub(crate) mod watcher_backend;
147pub mod watcher_filter;
148// Compiled on all platforms so cross-platform unit tests in
149// `commands::bash::try_spawn_with_fallback` can exercise the retry
150// decision logic without a real Windows runtime. The module itself only
151// uses portable APIs; only its callers are Windows-gated.
152pub(crate) mod windows_command;
153pub mod windows_path;
154pub mod windows_shell;
155
156#[cfg(test)]
157pub(crate) mod test_allocations;
158#[cfg(test)]
159pub(crate) mod test_env;
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164    use config::Config;
165    use error::AftError;
166    use protocol::{RawRequest, Response};
167
168    // --- Protocol serialization ---
169
170    #[test]
171    fn raw_request_deserializes_ping() {
172        let json = r#"{"id":"1","command":"ping"}"#;
173        let req: RawRequest = serde_json::from_str(json).unwrap();
174        assert_eq!(req.id, "1");
175        assert_eq!(req.command, "ping");
176        assert!(req.lsp_hints.is_none());
177    }
178
179    #[test]
180    fn raw_request_deserializes_echo_with_params() {
181        let json = r#"{"id":"2","command":"echo","message":"hello"}"#;
182        let req: RawRequest = serde_json::from_str(json).unwrap();
183        assert_eq!(req.id, "2");
184        assert_eq!(req.command, "echo");
185        // "message" is captured in the flattened params
186        assert_eq!(req.params["message"], "hello");
187    }
188
189    #[test]
190    fn raw_request_preserves_unknown_fields() {
191        let json = r#"{"id":"3","command":"ping","future_field":"abc","nested":{"x":1}}"#;
192        let req: RawRequest = serde_json::from_str(json).unwrap();
193        assert_eq!(req.params["future_field"], "abc");
194        assert_eq!(req.params["nested"]["x"], 1);
195    }
196
197    #[test]
198    fn raw_request_with_lsp_hints() {
199        let json = r#"{"id":"4","command":"ping","lsp_hints":{"completions":["foo","bar"]}}"#;
200        let req: RawRequest = serde_json::from_str(json).unwrap();
201        assert!(req.lsp_hints.is_some());
202        let hints = req.lsp_hints.unwrap();
203        assert_eq!(hints["completions"][0], "foo");
204    }
205
206    #[test]
207    fn response_success_round_trip() {
208        let resp = Response::success("42", serde_json::json!({"command": "pong"}));
209        let json_str = serde_json::to_string(&resp).unwrap();
210        let v: serde_json::Value = serde_json::from_str(&json_str).unwrap();
211        assert_eq!(v["id"], "42");
212        assert_eq!(v["success"], true);
213        assert_eq!(v["command"], "pong");
214    }
215
216    #[test]
217    fn response_error_round_trip() {
218        let resp = Response::error("99", "unknown_command", "unknown command: foo");
219        let json_str = serde_json::to_string(&resp).unwrap();
220        let v: serde_json::Value = serde_json::from_str(&json_str).unwrap();
221        assert_eq!(v["id"], "99");
222        assert_eq!(v["success"], false);
223        assert_eq!(v["code"], "unknown_command");
224        assert_eq!(v["message"], "unknown command: foo");
225    }
226
227    // --- Error formatting ---
228
229    #[test]
230    fn error_display_symbol_not_found() {
231        let err = AftError::SymbolNotFound {
232            name: "foo".into(),
233            file: "bar.rs".into(),
234        };
235        assert_eq!(err.to_string(), "symbol 'foo' not found in bar.rs");
236        assert_eq!(err.code(), "symbol_not_found");
237    }
238
239    #[test]
240    fn error_display_ambiguous_symbol() {
241        let err = AftError::AmbiguousSymbol {
242            name: "Foo".into(),
243            candidates: vec!["a.rs:10".into(), "b.rs:20".into()],
244        };
245        let s = err.to_string();
246        assert!(s.contains("Foo"));
247        assert!(s.contains("a.rs:10, b.rs:20"));
248    }
249
250    #[test]
251    fn error_display_parse_error() {
252        let err = AftError::ParseError {
253            message: "unexpected token".into(),
254        };
255        assert_eq!(err.to_string(), "parse error: unexpected token");
256    }
257
258    #[test]
259    fn error_display_file_not_found() {
260        let err = AftError::FileNotFound {
261            path: "/tmp/missing.rs".into(),
262        };
263        assert_eq!(err.to_string(), "file not found: /tmp/missing.rs");
264    }
265
266    #[test]
267    fn error_display_invalid_request() {
268        let err = AftError::InvalidRequest {
269            message: "missing field".into(),
270        };
271        assert_eq!(err.to_string(), "invalid request: missing field");
272    }
273
274    #[test]
275    fn error_display_checkpoint_not_found() {
276        let err = AftError::CheckpointNotFound {
277            name: "pre-refactor".into(),
278        };
279        assert_eq!(err.to_string(), "checkpoint not found: pre-refactor");
280        assert_eq!(err.code(), "checkpoint_not_found");
281    }
282
283    #[test]
284    fn error_display_no_undo_history() {
285        let err = AftError::NoUndoHistory {
286            path: "src/main.rs".into(),
287        };
288        assert_eq!(err.to_string(), "no undo history for: src/main.rs");
289        assert_eq!(err.code(), "no_undo_history");
290    }
291
292    #[test]
293    fn error_display_ambiguous_match() {
294        let err = AftError::AmbiguousMatch {
295            pattern: "TODO".into(),
296            count: 5,
297        };
298        assert_eq!(
299            err.to_string(),
300            "pattern 'TODO' matches 5 occurrences, expected exactly 1"
301        );
302        assert_eq!(err.code(), "ambiguous_match");
303    }
304
305    #[test]
306    fn error_to_json_has_code_and_message() {
307        let err = AftError::FileNotFound { path: "/x".into() };
308        let j = err.to_error_json();
309        assert_eq!(j["code"], "file_not_found");
310        assert!(j["message"].as_str().unwrap().contains("/x"));
311    }
312
313    // --- Config defaults ---
314
315    #[test]
316    fn config_default_values() {
317        let cfg = Config::default();
318        assert!(cfg.project_root.is_none());
319        assert_eq!(cfg.validation_depth, 1);
320        assert_eq!(cfg.checkpoint_ttl_hours, 24);
321        assert_eq!(cfg.max_symbol_depth, 10);
322        assert_eq!(cfg.formatter_timeout_secs, 10);
323        assert_eq!(cfg.type_checker_timeout_secs, 30);
324    }
325}
326
327#[cfg(all(test, target_os = "macos"))]
328mod disk_write_hunt;