agent-file-tools 0.47.0

Agent File Tools — tree-sitter powered code analysis for AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! AFT status command — returns the current state of indexes, features, and configuration.

use crate::context::AppContext;
use crate::context::SemanticIndexStatus;
use crate::db::compression_events::CompressionAggregate;
use crate::protocol::{RawRequest, Response, StatusPayload, DEFAULT_SESSION_ID};

#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct CompressionStats {
    pub project: CompressionAggregateSerde,
    pub session: CompressionAggregateSerde,
}

#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct CompressionAggregateSerde {
    pub events: u64,
    pub original_tokens: u64,
    pub compressed_tokens: u64,
    pub savings_tokens: u64,
}

impl From<CompressionAggregate> for CompressionAggregateSerde {
    fn from(agg: CompressionAggregate) -> Self {
        Self {
            events: agg.events,
            original_tokens: agg.original_tokens,
            compressed_tokens: agg.compressed_tokens,
            savings_tokens: agg.savings_tokens(),
        }
    }
}

pub fn handle_status(req: &RawRequest, ctx: &AppContext) -> Response {
    Response::success(
        &req.id,
        ctx.build_status_snapshot_for_session(req.session()),
    )
}

impl AppContext {
    pub fn build_status_snapshot(&self) -> StatusPayload {
        self.build_status_snapshot_for_session(DEFAULT_SESSION_ID)
    }

    pub fn build_status_snapshot_for_session(&self, session_id: &str) -> StatusPayload {
        let config = self.config();

        // Search index status. Status is a control-path snapshot, so lock
        // pressure is represented directly instead of delaying the caller.
        let search_index_info = match self.search_index().try_read() {
            Ok(index) => match index.as_ref() {
                Some(idx) if idx.ready => {
                    let file_count = idx.file_count();
                    let trigram_count = idx.trigram_count();
                    serde_json::json!({
                        "status": "ready",
                        "files": file_count,
                        "trigrams": trigram_count,
                    })
                }
                Some(_) => serde_json::json!({ "status": "building" }),
                None => {
                    let status = if config.search_index {
                        "loading"
                    } else {
                        "disabled"
                    };
                    serde_json::json!({ "status": status })
                }
            },
            Err(_) => serde_json::json!({ "status": "busy" }),
        };

        let semantic_status = self
            .semantic_index_status()
            .try_read()
            .ok()
            .map(|status| status.clone());
        let semantic_index_info = match semantic_status {
            None => serde_json::json!({ "status": "busy", "state": "busy" }),
            Some(status) => match self.semantic_index().try_read() {
                Err(_) => serde_json::json!({ "status": "busy", "state": "busy" }),
                Ok(index) => {
                    let refreshing_count = status.refreshing_count();
                    match index.as_ref() {
                        Some(idx) => {
                            let status_label = match status {
                                SemanticIndexStatus::Ready { .. } => "ready",
                                _ => idx.status_label(),
                            };
                            serde_json::json!({
                                "status": status_label,
                                "state": status_label,
                                "refreshing_count": refreshing_count,
                                "entries": idx.entry_count(),
                                "dimension": idx.dimension(),
                                "backend": idx.backend_label().unwrap_or(config.semantic_backend_label()),
                                "model": idx.model_label().unwrap_or(config.semantic.model.as_str()),
                            })
                        }
                        None => match status {
                            SemanticIndexStatus::Disabled => serde_json::json!({
                                "status": "disabled",
                                "state": "disabled",
                                "refreshing_count": 0,
                                "backend": config.semantic_backend_label(),
                                "model": config.semantic.model.as_str(),
                            }),
                            SemanticIndexStatus::Building {
                                stage,
                                files,
                                entries_done,
                                entries_total,
                            } => serde_json::json!({
                                "status": "loading",
                                "state": "loading",
                                "refreshing_count": 0,
                                "stage": stage,
                                "files": files,
                                "entries_done": entries_done,
                                "entries_total": entries_total,
                                "backend": config.semantic_backend_label(),
                                "model": config.semantic.model.as_str(),
                            }),
                            SemanticIndexStatus::Ready { refreshing, .. } => serde_json::json!({
                                "status": "ready",
                                "state": "ready",
                                "refreshing_count": refreshing.len(),
                                "backend": config.semantic_backend_label(),
                                "model": config.semantic.model.as_str(),
                            }),
                            SemanticIndexStatus::Failed(error) => serde_json::json!({
                                "status": "failed",
                                "state": "failed",
                                "refreshing_count": 0,
                                "error": error,
                                "backend": config.semantic_backend_label(),
                                "model": config.semantic.model.as_str(),
                            }),
                        },
                    }
                }
            },
        };

        // Disk cache sizes — scoped to the **current project** only.
        //
        // Both trigram (`<storage_dir>/index/<key>/`) and semantic
        // (`<storage_dir>/semantic/<key>/`) caches are partitioned per project by
        // `project_cache_key(project_root)`. Earlier this function reported the
        // recursive size of the entire `index/` and `semantic/` directories,
        // which summed disk usage across **every** project the user had ever
        // opened. The TUI sidebar surfaced that total as if it were the current
        // project's footprint, which was misleading (e.g. a 4.8 MB project with
        // 9 sibling projects appeared to use 16+ GB).
        //
        // We now resolve the per-project key from `config.project_root` and
        // size only that project's slice. When the project key can't be
        // resolved (no project_root), fall back to zeros — the cross-project
        // total is never the right answer to display per-session.
        let storage_dir = config.storage_dir.as_ref().map(|d| d.display().to_string());
        let disk_info = match (&config.storage_dir, &config.project_root) {
            (Some(dir), Some(root)) => {
                let key_root = self
                    .canonical_cache_root_opt()
                    .unwrap_or_else(|| root.clone());
                // Passive read only: status must never trigger a key
                // derivation (git probe). Artifact-backed features derive and
                // memoize the key at configure; when none are enabled there is
                // no per-project artifact slice to size.
                match self.cached_artifact_cache_key(&key_root) {
                    Some(key) => {
                        let trigram_size = dir_size(&dir.join("index").join(&key));
                        let semantic_size = dir_size(&dir.join("semantic").join(&key));
                        serde_json::json!({
                            "storage_dir": dir.display().to_string(),
                            "project_cache_key": key,
                            "trigram_disk_bytes": trigram_size,
                            "semantic_disk_bytes": semantic_size,
                        })
                    }
                    None => serde_json::json!({
                        "storage_dir": dir.display().to_string(),
                        "project_cache_key": null,
                        "trigram_disk_bytes": 0,
                        "semantic_disk_bytes": 0,
                    }),
                }
            }
            (Some(dir), None) => serde_json::json!({
                "storage_dir": dir.display().to_string(),
                "project_cache_key": null,
                "trigram_disk_bytes": 0,
                "semantic_disk_bytes": 0,
            }),
            _ => serde_json::json!({
                "storage_dir": null,
                "project_cache_key": null,
                "trigram_disk_bytes": 0,
                "semantic_disk_bytes": 0,
            }),
        };

        // LSP servers
        let lsp_count = self.lsp_server_count();

        // Symbol cache stats
        let symbol_cache_stats = self.symbol_cache_stats();

        // Per-session undo/checkpoint counts (issue #14 — one shared bridge serves
        // many sessions; surface both the global footprint and the current
        // session's own slice so `/aft-status` can split them in the UI).
        let backups_enabled = config.backup.enabled.unwrap_or(true);
        let checkpoint_total = if backups_enabled {
            self.checkpoint().lock().total_count()
        } else {
            0
        };
        let session_checkpoints = if backups_enabled {
            self.checkpoint().lock().list(session_id).len()
        } else {
            0
        };
        let session_tracked_files = if backups_enabled {
            self.backup().lock().tracked_files(session_id).len()
        } else {
            0
        };
        let compression = self.compression_stats_for_session(session_id);

        // Degraded-mode reasons recorded by `handle_configure` when the
        // project root doesn't look like a real project (`home_root`). Heavy
        // subsystems are auto-disabled in that mode; the plugin / TUI sidebar
        // surface the reason so users know why and can decide whether to open a
        // project subdirectory. Empty list = full-featured mode.
        let degraded_reasons = self.degraded_reasons();
        let degraded = !degraded_reasons.is_empty();
        let artifact_owner = self
            .artifact_owner_status()
            .map(|status| serde_json::to_value(status).unwrap_or(serde_json::Value::Null))
            .unwrap_or(serde_json::Value::Null);

        // Agent status-bar counts (the `[AFT E· W· | D· U· C· | T·]` glance).
        // Surfaced for the TUI sidebar so users see the same code-health view
        // agents get. `None` until the Tier-2 cache is populated at least once
        // (so we never render fabricated zeros) — emitted as JSON null then,
        // and the sidebar hides the section.
        let status_bar = match self.status_bar_counts() {
            Some(counts) => serde_json::json!({
                "errors": counts.errors,
                "warnings": counts.warnings,
                "dead_code": counts.dead_code,
                "unused_exports": counts.unused_exports,
                "duplicates": counts.duplicates,
                "todos": counts.todos,
                "tier2_stale": counts.tier2_stale,
            }),
            None => serde_json::Value::Null,
        };
        let memory_root = self
            .canonical_cache_root_opt()
            .or_else(|| config.project_root.clone());
        let memory = serde_json::to_value(self.memory_snapshot(memory_root.as_deref()))
            .unwrap_or(serde_json::Value::Null);

        serde_json::json!({
            "version": env!("CARGO_PKG_VERSION"),
            "project_root": config.project_root.as_ref().map(|p| p.display().to_string()),
            "canonical_root": self.canonical_cache_root_opt().map(|p| p.display().to_string()),
            "cache_role": self.cache_role(),
            "artifact_owner": artifact_owner,
            "degraded": degraded,
            "degraded_reasons": degraded_reasons,
            "features": {
                "format_on_edit": config.format_on_edit,
                "validate_on_edit": config.validate_on_edit.as_deref().unwrap_or("off"),
                "restrict_to_project_root": config.restrict_to_project_root,
                "search_index": config.search_index,
                "semantic_search": config.semantic_search,
                "callgraph_store": config.callgraph_store,
                "backup": backups_enabled,
            },
            "search_index": search_index_info,
            "semantic_index": semantic_index_info,
            "status_bar": status_bar,
            "disk": disk_info,
            "lsp_servers": lsp_count,
            "symbol_cache": symbol_cache_stats,
            "memory": memory,
            "compression": compression,
            "storage_dir": storage_dir,
            // Project-wide (all sessions): total in-memory checkpoint count.
            "checkpoints_total": checkpoint_total,
            // Current session slice: only when the caller passed `session_id`.
            "session": {
                "id": session_id,
                "tracked_files": session_tracked_files,
                "checkpoints": session_checkpoints,
            },
        })
    }

    fn compression_stats_for_session(&self, session_id: &str) -> CompressionStats {
        let mut compression = CompressionStats::default();
        let Some(project_root) = self.config().project_root.clone() else {
            return compression;
        };
        let Some(db) = self.db() else {
            return compression;
        };
        let Ok(conn) = db.lock() else {
            return compression;
        };

        let harness = self.harness().storage_segment();
        let project_key = crate::path_identity::project_scope_key(&project_root);
        if let Ok(project_agg) =
            crate::db::compression_events::aggregate_for_project(&conn, &harness, &project_key)
        {
            compression.project = project_agg.into();
        }
        if let Ok(session_agg) = crate::db::compression_events::aggregate_for_session(
            &conn,
            &harness,
            &project_key,
            session_id,
        ) {
            compression.session = session_agg.into();
        }

        compression
    }
}

/// Recursively compute the total size of a directory.
fn dir_size(path: &std::path::Path) -> u64 {
    if !path.exists() {
        return 0;
    }
    dir_size_recursive(path)
}

fn dir_size_recursive(path: &std::path::Path) -> u64 {
    let mut total = 0u64;
    let entries = match std::fs::read_dir(path) {
        Ok(e) => e,
        Err(_) => return 0,
    };
    for entry in entries.flatten() {
        let ft = match entry.file_type() {
            Ok(ft) => ft,
            Err(_) => continue,
        };
        if ft.is_file() {
            total += entry.metadata().map(|m| m.len()).unwrap_or(0);
        } else if ft.is_dir() {
            total += dir_size_recursive(&entry.path());
        }
    }
    total
}

#[cfg(test)]
mod tests {
    use super::handle_status;
    use crate::config::Config;
    use crate::context::AppContext;
    use crate::parser::TreeSitterProvider;
    use crate::protocol::RawRequest;
    use serde_json::json;

    fn request() -> RawRequest {
        RawRequest {
            id: "status".to_string(),
            command: "status".to_string(),
            lsp_hints: None,
            session_id: None,
            params: json!({}),
        }
    }

    #[test]
    fn status_exposes_cache_role_and_canonical_root() {
        let ctx = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
        let response = handle_status(&request(), &ctx);
        assert_eq!(response.data["cache_role"], "not_initialized");
        assert!(response.data["canonical_root"].is_null());

        let temp = tempfile::tempdir().unwrap();
        ctx.update_config(|config| {
            config.project_root = Some(temp.path().to_path_buf());
        });
        ctx.set_canonical_cache_root(std::fs::canonicalize(temp.path()).unwrap());
        ctx.set_cache_role(false, None);
        let response = handle_status(&request(), &ctx);
        assert_eq!(response.data["cache_role"], "main");
        assert!(response.data["canonical_root"].as_str().is_some());

        ctx.set_cache_role(true, None);
        let response = handle_status(&request(), &ctx);
        assert_eq!(response.data["cache_role"], "worktree");
    }

    #[test]
    fn memory_snapshot_reports_contended_subsystem_as_busy() {
        let ctx = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
        let _semantic_writer = ctx.semantic_index().write().unwrap();
        let status = ctx.build_status_snapshot();
        assert_eq!(status["semantic_index"]["status"], "busy");
        assert_eq!(
            status["memory"]["roots"]["<unconfigured>"]["semantic"]["status"],
            "busy"
        );
        assert_eq!(status["memory"]["process"]["sqlite"]["status"], "measured");
        assert!(status["memory"]["process"]["allocator"]["status"].is_string());
        assert!(status["memory"]["process"]["allocator"]
            .get("retained_slack_bytes")
            .is_some());
    }

    #[test]
    fn status_status_bar_is_null_until_tier2_populated() {
        let ctx = AppContext::new(Box::new(TreeSitterProvider::new()), Config::default());
        let response = handle_status(&request(), &ctx);
        // No Tier-2 scan has run yet, so the status-bar glance must be null
        // (never fabricated zeros). The key is always present so the TS
        // coercion can distinguish "field absent" from "not populated".
        assert!(response.data.get("status_bar").is_some());
        assert!(response.data["status_bar"].is_null());

        // Once Tier-2 counts are populated, the snapshot carries the glance.
        ctx.update_status_bar_tier2(Some(3), Some(2), Some(1), Some(5), false);
        let response = handle_status(&request(), &ctx);
        assert_eq!(response.data["status_bar"]["dead_code"], 3);
        assert_eq!(response.data["status_bar"]["unused_exports"], 2);
        assert_eq!(response.data["status_bar"]["duplicates"], 1);
        assert_eq!(response.data["status_bar"]["tier2_stale"], false);
    }
}