agent-file-tools 0.42.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
use std::time::{Duration, Instant};

pub const TIER2_REFRESH_DEBOUNCE: Duration = Duration::from_secs(45);
// Ceiling that forces a Tier-2 refresh during CONTINUOUS editing (when the
// debounce never gets its quiet window). Set high: mid-session refreshes show
// churning, half-applied numbers and cost a scan with no value until changes
// land — a normal continuous-coding stretch should not trigger one.
pub const TIER2_REFRESH_MAX_STALENESS: Duration = Duration::from_secs(30 * 60);
pub const TIER2_REFRESH_MIN_INTERVAL: Duration = Duration::from_secs(5 * 60);
pub const TIER2_REFRESH_COLD_CACHE_DELAY: Duration = Duration::from_secs(90);
pub const TIER2_REFRESH_STORM_DEBOUNCE: Duration = Duration::from_secs(120);
pub const TIER2_REFRESH_STORM_PATH_THRESHOLD: usize = 200;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tier2TriggerReason {
    Debounce,
    Ceiling,
    Pull,
    ConfigureWarm,
}

impl Tier2TriggerReason {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Debounce => "debounce",
            Self::Ceiling => "ceiling",
            Self::Pull => "pull",
            Self::ConfigureWarm => "configure_warm",
        }
    }
}

#[derive(Debug, Clone)]
pub struct Tier2RefreshScheduler {
    configured_at: Option<Instant>,
    last_change_at: Option<Instant>,
    activity_started_at: Option<Instant>,
    debounce_delay: Duration,
    last_scan_started_at: Option<Instant>,
    pull_demand_pending: bool,
    configure_warm_pending: bool,
    last_trigger_reason: Option<Tier2TriggerReason>,
}

impl Tier2RefreshScheduler {
    pub fn new() -> Self {
        Self {
            configured_at: None,
            last_change_at: None,
            activity_started_at: None,
            debounce_delay: TIER2_REFRESH_DEBOUNCE,
            last_scan_started_at: None,
            pull_demand_pending: false,
            configure_warm_pending: false,
            last_trigger_reason: None,
        }
    }

    pub fn reset_after_configure(&mut self, now: Instant) {
        self.configured_at = Some(now);
        self.last_change_at = None;
        self.activity_started_at = None;
        self.debounce_delay = TIER2_REFRESH_DEBOUNCE;
        self.last_scan_started_at = None;
        self.pull_demand_pending = false;
        self.configure_warm_pending = true;
        self.last_trigger_reason = None;
    }

    pub fn request_pull(&mut self, can_write: bool) -> bool {
        if !can_write {
            return false;
        }
        self.pull_demand_pending = true;
        true
    }

    pub fn tick(
        &mut self,
        now: Instant,
        changed_path_count: usize,
        can_write: bool,
        in_flight: bool,
    ) -> Option<Tier2TriggerReason> {
        self.tick_with_semantic_gate(now, changed_path_count, can_write, in_flight, false)
    }

    pub fn tick_with_semantic_gate(
        &mut self,
        now: Instant,
        changed_path_count: usize,
        can_write: bool,
        in_flight: bool,
        semantic_cold_seed_active: bool,
    ) -> Option<Tier2TriggerReason> {
        if changed_path_count > 0 {
            self.record_changes(now, changed_path_count);
        }

        if !can_write || in_flight || !self.min_interval_elapsed(now) {
            return None;
        }

        if semantic_cold_seed_active {
            return None;
        }

        if self.pull_demand_pending {
            return Some(self.record_scan_start(now, Tier2TriggerReason::Pull));
        }

        let cold_delay_elapsed = self.cold_delay_elapsed(now);
        if cold_delay_elapsed {
            if self.ceiling_elapsed(now) {
                return Some(self.record_scan_start(now, Tier2TriggerReason::Ceiling));
            }
            if self.debounce_elapsed(now) {
                return Some(self.record_scan_start(now, Tier2TriggerReason::Debounce));
            }
            if self.configure_warm_pending && self.last_change_at.is_none() {
                return Some(self.record_scan_start(now, Tier2TriggerReason::ConfigureWarm));
            }
        }

        None
    }

    pub fn note_external_scan_started(&mut self, now: Instant) {
        self.last_scan_started_at = Some(now);
        self.pull_demand_pending = false;
        self.configure_warm_pending = false;
        self.clear_activity_window();
    }

    pub fn last_trigger_reason(&self) -> Option<Tier2TriggerReason> {
        self.last_trigger_reason
    }

    pub fn pull_demand_pending(&self) -> bool {
        self.pull_demand_pending
    }

    fn record_changes(&mut self, now: Instant, changed_path_count: usize) {
        if self.activity_started_at.is_none() {
            self.activity_started_at = Some(now);
            self.debounce_delay = TIER2_REFRESH_DEBOUNCE;
        }
        self.last_change_at = Some(now);
        if changed_path_count > TIER2_REFRESH_STORM_PATH_THRESHOLD {
            self.debounce_delay = self.debounce_delay.max(TIER2_REFRESH_STORM_DEBOUNCE);
        }
    }

    fn min_interval_elapsed(&self, now: Instant) -> bool {
        self.last_scan_started_at
            .map(|started| elapsed_since(now, started) >= TIER2_REFRESH_MIN_INTERVAL)
            .unwrap_or(true)
    }

    fn cold_delay_elapsed(&self, now: Instant) -> bool {
        self.last_scan_started_at.is_some()
            || self
                .configured_at
                .map(|configured| elapsed_since(now, configured) >= TIER2_REFRESH_COLD_CACHE_DELAY)
                .unwrap_or(false)
    }

    fn ceiling_elapsed(&self, now: Instant) -> bool {
        self.activity_started_at
            .map(|started| elapsed_since(now, started) >= TIER2_REFRESH_MAX_STALENESS)
            .unwrap_or(false)
    }

    fn debounce_elapsed(&self, now: Instant) -> bool {
        self.last_change_at
            .map(|changed| elapsed_since(now, changed) >= self.debounce_delay)
            .unwrap_or(false)
    }

    fn record_scan_start(
        &mut self,
        now: Instant,
        reason: Tier2TriggerReason,
    ) -> Tier2TriggerReason {
        self.last_scan_started_at = Some(now);
        self.pull_demand_pending = false;
        self.configure_warm_pending = false;
        self.last_trigger_reason = Some(reason);
        self.clear_activity_window();
        reason
    }

    fn clear_activity_window(&mut self) {
        self.last_change_at = None;
        self.activity_started_at = None;
        self.debounce_delay = TIER2_REFRESH_DEBOUNCE;
    }
}

impl Default for Tier2RefreshScheduler {
    fn default() -> Self {
        Self::new()
    }
}

fn elapsed_since(now: Instant, earlier: Instant) -> Duration {
    now.checked_duration_since(earlier)
        .unwrap_or(Duration::ZERO)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn configured_scheduler() -> (Tier2RefreshScheduler, Instant) {
        let base = Instant::now();
        let mut scheduler = Tier2RefreshScheduler::new();
        scheduler.reset_after_configure(base);
        (scheduler, base)
    }

    #[test]
    fn debounce_resets_on_each_change() {
        let (mut scheduler, base) = configured_scheduler();
        let warm = base + TIER2_REFRESH_COLD_CACHE_DELAY;

        assert_eq!(scheduler.tick(warm, 1, true, false), None);
        assert_eq!(
            scheduler.tick(
                warm + TIER2_REFRESH_DEBOUNCE - Duration::from_secs(1),
                1,
                true,
                false
            ),
            None
        );
        assert_eq!(
            scheduler.tick(warm + TIER2_REFRESH_DEBOUNCE, 0, true, false),
            None,
            "second change should reset the debounce deadline"
        );
        assert_eq!(
            scheduler.tick(
                warm + TIER2_REFRESH_DEBOUNCE + TIER2_REFRESH_DEBOUNCE,
                0,
                true,
                false,
            ),
            Some(Tier2TriggerReason::Debounce)
        );
    }

    #[test]
    fn ceiling_fires_during_continuous_activity() {
        let (mut scheduler, base) = configured_scheduler();
        let start = base + TIER2_REFRESH_COLD_CACHE_DELAY;
        assert_eq!(scheduler.tick(start, 1, true, false), None);

        let mut now = start;
        while now < start + TIER2_REFRESH_MAX_STALENESS {
            now += Duration::from_secs(30);
            let changed_paths = if now < start + TIER2_REFRESH_MAX_STALENESS {
                1
            } else {
                0
            };
            let decision = scheduler.tick(now, changed_paths, true, false);
            if now < start + TIER2_REFRESH_MAX_STALENESS {
                assert_eq!(decision, None);
            } else {
                assert_eq!(decision, Some(Tier2TriggerReason::Ceiling));
            }
        }
    }

    #[test]
    fn min_interval_throttles_second_scan() {
        let (mut scheduler, base) = configured_scheduler();
        let first = base + TIER2_REFRESH_COLD_CACHE_DELAY;
        assert_eq!(
            scheduler.tick(first, 0, true, false),
            Some(Tier2TriggerReason::ConfigureWarm)
        );

        let change = first + Duration::from_secs(1);
        assert_eq!(scheduler.tick(change, 1, true, false), None);
        assert_eq!(
            scheduler.tick(change + TIER2_REFRESH_DEBOUNCE, 0, true, false),
            None,
            "min interval should throttle scans inside five minutes"
        );
        assert_eq!(
            scheduler.tick(first + TIER2_REFRESH_MIN_INTERVAL, 0, true, false),
            Some(Tier2TriggerReason::Debounce)
        );
    }

    #[test]
    fn storm_extends_debounce_window() {
        let (mut scheduler, base) = configured_scheduler();
        let warm = base + TIER2_REFRESH_COLD_CACHE_DELAY;
        assert_eq!(
            scheduler.tick(warm, TIER2_REFRESH_STORM_PATH_THRESHOLD + 1, true, false),
            None
        );
        assert_eq!(
            scheduler.tick(
                warm + TIER2_REFRESH_STORM_DEBOUNCE - Duration::from_secs(1),
                0,
                true,
                false
            ),
            None
        );
        assert_eq!(
            scheduler.tick(warm + TIER2_REFRESH_STORM_DEBOUNCE, 0, true, false),
            Some(Tier2TriggerReason::Debounce)
        );
    }

    #[test]
    fn semantic_cold_seed_gate_defers_without_consuming_pending_work() {
        let (mut scheduler, base) = configured_scheduler();
        let warm = base + TIER2_REFRESH_COLD_CACHE_DELAY;

        assert_eq!(
            scheduler.tick_with_semantic_gate(warm, 0, true, false, true),
            None
        );
        assert!(
            scheduler.configure_warm_pending,
            "configure-warm scan must remain pending while a cold semantic seed is active"
        );
        assert_eq!(
            scheduler.tick_with_semantic_gate(warm + Duration::from_secs(1), 0, true, false, false),
            Some(Tier2TriggerReason::ConfigureWarm)
        );

        assert!(scheduler.request_pull(true));
        assert_eq!(
            scheduler.tick_with_semantic_gate(
                warm + TIER2_REFRESH_MIN_INTERVAL,
                0,
                true,
                false,
                true
            ),
            None
        );
        assert!(
            scheduler.pull_demand_pending(),
            "pull demand must not be consumed while a cold semantic seed is active"
        );
        assert_eq!(
            scheduler.tick_with_semantic_gate(
                warm + TIER2_REFRESH_MIN_INTERVAL + Duration::from_secs(1),
                0,
                true,
                false,
                false,
            ),
            Some(Tier2TriggerReason::Pull)
        );
    }

    #[test]
    fn worktree_bridge_never_schedules_write() {
        let (mut scheduler, base) = configured_scheduler();
        let warm = base + TIER2_REFRESH_COLD_CACHE_DELAY;
        assert_eq!(scheduler.tick(warm, 1, false, false), None);
        assert_eq!(
            scheduler.tick(warm + TIER2_REFRESH_MAX_STALENESS, 0, false, false),
            None
        );
        assert!(!scheduler.request_pull(false));
        assert_eq!(
            scheduler.tick(warm + TIER2_REFRESH_MAX_STALENESS * 2, 0, false, false),
            None
        );
    }

    #[test]
    fn pull_demand_sets_but_respects_min_interval_and_in_flight() {
        let (mut scheduler, base) = configured_scheduler();
        let first = base + TIER2_REFRESH_COLD_CACHE_DELAY;
        assert_eq!(
            scheduler.tick(first, 0, true, false),
            Some(Tier2TriggerReason::ConfigureWarm)
        );

        assert!(scheduler.request_pull(true));
        assert!(scheduler.pull_demand_pending());
        assert_eq!(
            scheduler.tick(first + Duration::from_secs(60), 0, true, false),
            None,
            "pull demand should wait for the min interval"
        );
        assert!(scheduler.pull_demand_pending());
        assert_eq!(
            scheduler.tick(first + TIER2_REFRESH_MIN_INTERVAL, 0, true, true),
            None,
            "pull demand should wait for in-flight tier2 work to finish"
        );
        assert!(scheduler.pull_demand_pending());
        assert_eq!(
            scheduler.tick(first + TIER2_REFRESH_MIN_INTERVAL, 0, true, false),
            Some(Tier2TriggerReason::Pull)
        );
    }
}