Skip to main content

aft/commands/
status.rs

1//! AFT status command — returns the current state of indexes, features, and configuration.
2
3use crate::context::AppContext;
4use crate::context::SemanticIndexStatus;
5use crate::db::compression_events::CompressionAggregate;
6use crate::protocol::{RawRequest, Response, StatusPayload, DEFAULT_SESSION_ID};
7
8#[derive(Debug, Clone, Default, serde::Serialize)]
9pub struct CompressionStats {
10    pub project: CompressionAggregateSerde,
11    pub session: CompressionAggregateSerde,
12}
13
14#[derive(Debug, Clone, Default, serde::Serialize)]
15pub struct CompressionAggregateSerde {
16    pub events: u64,
17    pub original_tokens: u64,
18    pub compressed_tokens: u64,
19    pub savings_tokens: u64,
20}
21
22impl From<CompressionAggregate> for CompressionAggregateSerde {
23    fn from(agg: CompressionAggregate) -> Self {
24        Self {
25            events: agg.events,
26            original_tokens: agg.original_tokens,
27            compressed_tokens: agg.compressed_tokens,
28            savings_tokens: agg.savings_tokens(),
29        }
30    }
31}
32
33pub fn handle_status(req: &RawRequest, ctx: &AppContext) -> Response {
34    Response::success(
35        &req.id,
36        ctx.build_status_snapshot_for_session(req.session()),
37    )
38}
39
40impl AppContext {
41    pub fn build_status_snapshot(&self) -> StatusPayload {
42        self.build_status_snapshot_for_session(DEFAULT_SESSION_ID)
43    }
44
45    pub fn build_status_snapshot_for_session(&self, session_id: &str) -> StatusPayload {
46        let config = self.config();
47
48        // Search index status
49        let search_index_info = {
50            let index = self
51                .search_index()
52                .read()
53                .unwrap_or_else(std::sync::PoisonError::into_inner);
54            match index.as_ref() {
55                Some(idx) if idx.ready => {
56                    let file_count = idx.file_count();
57                    let trigram_count = idx.trigram_count();
58                    serde_json::json!({
59                        "status": "ready",
60                        "files": file_count,
61                        "trigrams": trigram_count,
62                    })
63                }
64                Some(_) => serde_json::json!({ "status": "building" }),
65                None => {
66                    let status = if config.search_index {
67                        "loading"
68                    } else {
69                        "disabled"
70                    };
71                    serde_json::json!({ "status": status })
72                }
73            }
74        };
75
76        // Semantic index status
77        let semantic_index_info = {
78            let status = self
79                .semantic_index_status()
80                .read()
81                .unwrap_or_else(std::sync::PoisonError::into_inner)
82                .clone();
83            let refreshing_count = status.refreshing_count();
84            let index = self
85                .semantic_index()
86                .read()
87                .unwrap_or_else(std::sync::PoisonError::into_inner);
88            match index.as_ref() {
89                Some(idx) => {
90                    let status_label = match status {
91                        SemanticIndexStatus::Ready { .. } => "ready",
92                        _ => idx.status_label(),
93                    };
94                    serde_json::json!({
95                        "status": status_label,
96                        "state": status_label,
97                        "refreshing_count": refreshing_count,
98                        "entries": idx.entry_count(),
99                        "dimension": idx.dimension(),
100                        "backend": idx.backend_label().unwrap_or(config.semantic_backend_label()),
101                        "model": idx.model_label().unwrap_or(config.semantic.model.as_str()),
102                    })
103                }
104                None => match status {
105                    SemanticIndexStatus::Disabled => serde_json::json!({
106                        "status": "disabled",
107                        "state": "disabled",
108                        "refreshing_count": 0,
109                        "backend": config.semantic_backend_label(),
110                        "model": config.semantic.model.as_str(),
111                    }),
112                    SemanticIndexStatus::Building {
113                        stage,
114                        files,
115                        entries_done,
116                        entries_total,
117                    } => serde_json::json!({
118                        "status": "loading",
119                        "state": "loading",
120                        "refreshing_count": 0,
121                        "stage": stage,
122                        "files": files,
123                        "entries_done": entries_done,
124                        "entries_total": entries_total,
125                        "backend": config.semantic_backend_label(),
126                        "model": config.semantic.model.as_str(),
127                    }),
128                    SemanticIndexStatus::Ready { refreshing, .. } => serde_json::json!({
129                        "status": "ready",
130                        "state": "ready",
131                        "refreshing_count": refreshing.len(),
132                        "backend": config.semantic_backend_label(),
133                        "model": config.semantic.model.as_str(),
134                    }),
135                    SemanticIndexStatus::Failed(error) => serde_json::json!({
136                        "status": "failed",
137                        "state": "failed",
138                        "refreshing_count": 0,
139                        "error": error,
140                        "backend": config.semantic_backend_label(),
141                        "model": config.semantic.model.as_str(),
142                    }),
143                },
144            }
145        };
146
147        // Disk cache sizes — scoped to the **current project** only.
148        //
149        // Both trigram (`<storage_dir>/index/<key>/`) and semantic
150        // (`<storage_dir>/semantic/<key>/`) caches are partitioned per project by
151        // `project_cache_key(project_root)`. Earlier this function reported the
152        // recursive size of the entire `index/` and `semantic/` directories,
153        // which summed disk usage across **every** project the user had ever
154        // opened. The TUI sidebar surfaced that total as if it were the current
155        // project's footprint, which was misleading (e.g. a 4.8 MB project with
156        // 9 sibling projects appeared to use 16+ GB).
157        //
158        // We now resolve the per-project key from `config.project_root` and
159        // size only that project's slice. When the project key can't be
160        // resolved (no project_root), fall back to zeros — the cross-project
161        // total is never the right answer to display per-session.
162        let storage_dir = config.storage_dir.as_ref().map(|d| d.display().to_string());
163        let disk_info = match (&config.storage_dir, &config.project_root) {
164            (Some(dir), Some(root)) => {
165                let key = crate::search_index::artifact_cache_key(root);
166                let trigram_size = dir_size(&dir.join("index").join(&key));
167                let semantic_size = dir_size(&dir.join("semantic").join(&key));
168                serde_json::json!({
169                    "storage_dir": dir.display().to_string(),
170                    "project_cache_key": key,
171                    "trigram_disk_bytes": trigram_size,
172                    "semantic_disk_bytes": semantic_size,
173                })
174            }
175            (Some(dir), None) => serde_json::json!({
176                "storage_dir": dir.display().to_string(),
177                "project_cache_key": null,
178                "trigram_disk_bytes": 0,
179                "semantic_disk_bytes": 0,
180            }),
181            _ => serde_json::json!({
182                "storage_dir": null,
183                "project_cache_key": null,
184                "trigram_disk_bytes": 0,
185                "semantic_disk_bytes": 0,
186            }),
187        };
188
189        // LSP servers
190        let lsp_count = self.lsp_server_count();
191
192        // Symbol cache stats
193        let symbol_cache_stats = self.symbol_cache_stats();
194
195        // Per-session undo/checkpoint counts (issue #14 — one shared bridge serves
196        // many sessions; surface both the global footprint and the current
197        // session's own slice so `/aft-status` can split them in the UI).
198        let checkpoint_total = self.checkpoint().lock().total_count();
199        let session_checkpoints = self.checkpoint().lock().list(session_id).len();
200        let session_tracked_files = self.backup().lock().tracked_files(session_id).len();
201        let compression = self.compression_stats_for_session(session_id);
202
203        // Degraded-mode reasons recorded by `handle_configure` when the
204        // project root doesn't look like a real project (`home_root`). Heavy
205        // subsystems are auto-disabled in that mode; the plugin / TUI sidebar
206        // surface the reason so users know why and can decide whether to open a
207        // project subdirectory. Empty list = full-featured mode.
208        let degraded_reasons = self.degraded_reasons();
209        let degraded = !degraded_reasons.is_empty();
210
211        // Agent status-bar counts (the `[AFT E· W· | D· U· C· | T·]` glance).
212        // Surfaced for the TUI sidebar so users see the same code-health view
213        // agents get. `None` until the Tier-2 cache is populated at least once
214        // (so we never render fabricated zeros) — emitted as JSON null then,
215        // and the sidebar hides the section.
216        let status_bar = match self.status_bar_counts() {
217            Some(counts) => serde_json::json!({
218                "errors": counts.errors,
219                "warnings": counts.warnings,
220                "dead_code": counts.dead_code,
221                "unused_exports": counts.unused_exports,
222                "duplicates": counts.duplicates,
223                "todos": counts.todos,
224                "tier2_stale": counts.tier2_stale,
225            }),
226            None => serde_json::Value::Null,
227        };
228
229        serde_json::json!({
230            "version": env!("CARGO_PKG_VERSION"),
231            "project_root": config.project_root.as_ref().map(|p| p.display().to_string()),
232            "canonical_root": self.canonical_cache_root_opt().map(|p| p.display().to_string()),
233            "cache_role": self.cache_role(),
234            "degraded": degraded,
235            "degraded_reasons": degraded_reasons,
236            "features": {
237                "format_on_edit": config.format_on_edit,
238                "validate_on_edit": config.validate_on_edit.as_deref().unwrap_or("off"),
239                "restrict_to_project_root": config.restrict_to_project_root,
240                "search_index": config.search_index,
241                "semantic_search": config.semantic_search,
242                "callgraph_store": config.callgraph_store,
243            },
244            "search_index": search_index_info,
245            "semantic_index": semantic_index_info,
246            "status_bar": status_bar,
247            "disk": disk_info,
248            "lsp_servers": lsp_count,
249            "symbol_cache": symbol_cache_stats,
250            "compression": compression,
251            "storage_dir": storage_dir,
252            // Project-wide (all sessions): total in-memory checkpoint count.
253            "checkpoints_total": checkpoint_total,
254            // Current session slice: only when the caller passed `session_id`.
255            "session": {
256                "id": session_id,
257                "tracked_files": session_tracked_files,
258                "checkpoints": session_checkpoints,
259            },
260        })
261    }
262
263    fn compression_stats_for_session(&self, session_id: &str) -> CompressionStats {
264        let mut compression = CompressionStats::default();
265        let Some(project_root) = self.config().project_root.clone() else {
266            return compression;
267        };
268        let Some(db) = self.db() else {
269            return compression;
270        };
271        let Ok(conn) = db.lock() else {
272            return compression;
273        };
274
275        let harness = self.harness().storage_segment();
276        let project_key = crate::path_identity::project_scope_key(&project_root);
277        if let Ok(project_agg) =
278            crate::db::compression_events::aggregate_for_project(&conn, &harness, &project_key)
279        {
280            compression.project = project_agg.into();
281        }
282        if let Ok(session_agg) = crate::db::compression_events::aggregate_for_session(
283            &conn,
284            &harness,
285            &project_key,
286            session_id,
287        ) {
288            compression.session = session_agg.into();
289        }
290
291        compression
292    }
293}
294
295/// Recursively compute the total size of a directory.
296fn dir_size(path: &std::path::Path) -> u64 {
297    if !path.exists() {
298        return 0;
299    }
300    dir_size_recursive(path)
301}
302
303fn dir_size_recursive(path: &std::path::Path) -> u64 {
304    let mut total = 0u64;
305    let entries = match std::fs::read_dir(path) {
306        Ok(e) => e,
307        Err(_) => return 0,
308    };
309    for entry in entries.flatten() {
310        let ft = match entry.file_type() {
311            Ok(ft) => ft,
312            Err(_) => continue,
313        };
314        if ft.is_file() {
315            total += entry.metadata().map(|m| m.len()).unwrap_or(0);
316        } else if ft.is_dir() {
317            total += dir_size_recursive(&entry.path());
318        }
319    }
320    total
321}
322
323#[cfg(test)]
324mod tests {
325    use super::handle_status;
326    use crate::config::Config;
327    use crate::context::AppContext;
328    use crate::parser::TreeSitterProvider;
329    use crate::protocol::RawRequest;
330    use serde_json::json;
331
332    fn request() -> RawRequest {
333        RawRequest {
334            id: "status".to_string(),
335            command: "status".to_string(),
336            lsp_hints: None,
337            session_id: None,
338            params: json!({}),
339        }
340    }
341
342    #[test]
343    fn status_exposes_cache_role_and_canonical_root() {
344        let ctx = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
345        let response = handle_status(&request(), &ctx);
346        assert_eq!(response.data["cache_role"], "not_initialized");
347        assert!(response.data["canonical_root"].is_null());
348
349        let temp = tempfile::tempdir().unwrap();
350        ctx.update_config(|config| {
351            config.project_root = Some(temp.path().to_path_buf());
352        });
353        ctx.set_canonical_cache_root(std::fs::canonicalize(temp.path()).unwrap());
354        ctx.set_cache_role(false, None);
355        let response = handle_status(&request(), &ctx);
356        assert_eq!(response.data["cache_role"], "main");
357        assert!(response.data["canonical_root"].as_str().is_some());
358
359        ctx.set_cache_role(true, None);
360        let response = handle_status(&request(), &ctx);
361        assert_eq!(response.data["cache_role"], "worktree");
362    }
363
364    #[test]
365    fn status_status_bar_is_null_until_tier2_populated() {
366        let ctx = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
367        let response = handle_status(&request(), &ctx);
368        // No Tier-2 scan has run yet, so the status-bar glance must be null
369        // (never fabricated zeros). The key is always present so the TS
370        // coercion can distinguish "field absent" from "not populated".
371        assert!(response.data.get("status_bar").is_some());
372        assert!(response.data["status_bar"].is_null());
373
374        // Once Tier-2 counts are populated, the snapshot carries the glance.
375        ctx.update_status_bar_tier2(Some(3), Some(2), Some(1), Some(5), false);
376        let response = handle_status(&request(), &ctx);
377        assert_eq!(response.data["status_bar"]["dead_code"], 3);
378        assert_eq!(response.data["status_bar"]["unused_exports"], 2);
379        assert_eq!(response.data["status_bar"]["duplicates"], 1);
380        assert_eq!(response.data["status_bar"]["tier2_stale"], false);
381    }
382}