aft-base 0.67.1

Shared foundation for Agent Foundational Toolkit
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
//! Bounded, line-oriented delivery for opt-in asynchronous watches.

use std::collections::HashMap;
use std::time::{Duration, Instant};

use serde::{Deserialize, Serialize};

use crate::task_watches::WatchPattern;

pub const MAX_LINES_PER_NOTIFICATION: usize = 50;
pub const MAX_NOTIFICATIONS_PER_MINUTE: usize = 12;
pub const NOTIFICATION_WINDOW: Duration = Duration::from_secs(60);
pub const MAX_LINE_BYTES: usize = 64 * 1024;
pub const MASKING_LINE_CAP_BYTES: usize = 8 * 1024;
pub const UNAVAILABLE_MATCH_SINGULAR: &str = "1 matching line over {limit} KiB was not shown; AFT can check lines only up to {limit} KiB for secrets.";
pub const UNAVAILABLE_MATCH_PLURAL: &str = "{count} matching lines over {limit} KiB were not shown; AFT can check lines only up to {limit} KiB for secrets.";
pub const UNAVAILABLE_PAGE_SINGULAR: &str = "1 line in this page over {limit} KiB was not shown; AFT can check lines only up to {limit} KiB for secrets.";
pub const UNAVAILABLE_PAGE_PLURAL: &str = "{count} lines in this page over {limit} KiB were not shown; AFT can check lines only up to {limit} KiB for secrets.";

pub fn unavailable_match_text(count: u64, limit: usize) -> String {
    unavailable_text(
        if count == 1 {
            UNAVAILABLE_MATCH_SINGULAR
        } else {
            UNAVAILABLE_MATCH_PLURAL
        },
        count,
        limit,
    )
}

pub fn unavailable_page_text(count: u64) -> String {
    unavailable_text(
        if count == 1 {
            UNAVAILABLE_PAGE_SINGULAR
        } else {
            UNAVAILABLE_PAGE_PLURAL
        },
        count,
        MASKING_LINE_CAP_BYTES,
    )
}

fn unavailable_text(template: &str, count: u64, limit: usize) -> String {
    template
        .replace("{count}", &count.to_string())
        .replace("{limit}", &limit.div_ceil(1024).to_string())
}
pub const EACH_LINE_NEEDS_BACKGROUND: &str =
    "bash_watch: deliver: \"each_line\" needs background: true.";

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WatchLine {
    pub stream: String,
    pub offset: u64,
    pub end_offset: u64,
    pub text: String,
    pub count: u64,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub unavailable: bool,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RetryGap {
    pub reason: String,
    pub dropped_notifications: u64,
    pub known_missing_occurrences: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub first_offset: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_offset: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stream: Option<String>,
    #[serde(default)]
    pub evicted_through: u64,
    #[serde(default)]
    pub eviction_epoch: String,
    #[serde(default)]
    pub last_match_version: u64,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct LineBatch {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub acknowledged_version: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retry_gap: Option<RetryGap>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub masking_limit_bytes: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pending_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<u64>,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub snapshot: bool,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub terminal_summary: bool,
    pub lines: Vec<WatchLine>,
    pub dropped_lines: u64,
    pub first_dropped_offset: Option<u64>,
    pub first_dropped_stream: Option<String>,
    pub skipped_long_lines: u64,
}

impl LineBatch {
    pub fn has_matches(&self) -> bool {
        !self.lines.is_empty() || self.dropped_lines > 0
    }

    pub fn merge(&mut self, next: LineBatch) {
        if next.retry_gap.is_some() {
            self.retry_gap = next.retry_gap.clone();
        }
        self.masking_limit_bytes = next.masking_limit_bytes.or(self.masking_limit_bytes);
        self.terminal_summary = next.terminal_summary;
        let mut retained = self.lines.iter().map(|line| line.count).sum::<u64>();
        for mut line in next.lines {
            let keep = line
                .count
                .min((MAX_LINES_PER_NOTIFICATION as u64).saturating_sub(retained));
            let dropped = line.count - keep;
            if dropped > 0 {
                let offset = line.offset + keep * (line.end_offset - line.offset);
                self.drop_line(&line.stream, offset);
                self.dropped_lines = self.dropped_lines.saturating_add(dropped - 1);
            }
            if keep > 0 {
                line.count = keep;
                self.lines.push(line);
                retained += keep;
            }
        }
        self.dropped_lines = self.dropped_lines.saturating_add(next.dropped_lines);
        self.skipped_long_lines = self
            .skipped_long_lines
            .saturating_add(next.skipped_long_lines);
        if self.first_dropped_offset.is_none() {
            self.first_dropped_offset = next.first_dropped_offset;
            self.first_dropped_stream = next.first_dropped_stream;
        }
    }

    fn drop_line(&mut self, stream: &str, offset: u64) {
        self.dropped_lines = self.dropped_lines.saturating_add(1);
        if self.first_dropped_offset.is_none() {
            self.first_dropped_offset = Some(offset);
            self.first_dropped_stream = Some(stream.to_string());
        }
    }

    fn is_empty(&self) -> bool {
        self.lines.is_empty()
            && self.dropped_lines == 0
            && self.skipped_long_lines == 0
            && self
                .retry_gap
                .as_ref()
                .is_none_or(|gap| gap.dropped_notifications == 0)
    }
}

#[derive(Debug, Default)]
struct PartialLine {
    bytes: Vec<u8>,
    offset: u64,
    oversized: bool,
}

#[derive(Debug, Default)]
pub(super) struct LineDelivery {
    streams: HashMap<String, PartialLine>,
    batch: LineBatch,
    retained: usize,
    window: Option<Instant>,
    sent: usize,
}

impl LineDelivery {
    pub fn replay_cursor(&self, stream: &str, cursor: u64) -> u64 {
        let partial = self
            .streams
            .get(stream)
            .filter(|line| !line.bytes.is_empty() || line.oversized)
            .map(|line| line.offset)
            .unwrap_or(cursor);
        let dropped = if self.batch.first_dropped_stream.as_deref() == Some(stream) {
            self.batch.first_dropped_offset.unwrap_or(cursor)
        } else {
            cursor
        };
        self.batch
            .lines
            .iter()
            .filter(|line| line.stream == stream)
            .map(|line| line.offset)
            .fold(cursor.min(partial).min(dropped), u64::min)
    }

    pub fn scan(&mut self, stream: &str, bytes: &[u8], base: u64, pattern: &WatchPattern) {
        let mut partial = self.streams.remove(stream).unwrap_or_else(|| PartialLine {
            offset: base,
            ..PartialLine::default()
        });
        let mut consumed = 0;
        for fragment in bytes.split_inclusive(|byte| *byte == b'\n') {
            let complete = fragment.last() == Some(&b'\n');
            let content = if complete {
                &fragment[..fragment.len() - 1]
            } else {
                fragment
            };
            if !partial.oversized {
                if partial.bytes.len().saturating_add(content.len()) > MAX_LINE_BYTES {
                    partial.bytes.clear();
                    partial.oversized = true;
                } else {
                    partial.bytes.extend_from_slice(content);
                }
            }
            consumed += fragment.len();
            if complete {
                self.finish_line(stream, &partial, base + consumed as u64, pattern);
                partial = PartialLine {
                    offset: base + consumed as u64,
                    ..PartialLine::default()
                };
            }
        }
        self.streams.insert(stream.to_string(), partial);
    }

    fn finish_line(
        &mut self,
        stream: &str,
        partial: &PartialLine,
        end: u64,
        pattern: &WatchPattern,
    ) {
        if partial.oversized {
            self.batch.skipped_long_lines = self.batch.skipped_long_lines.saturating_add(1);
            if self.batch.first_dropped_offset.is_none() {
                self.batch.first_dropped_offset = Some(partial.offset);
                self.batch.first_dropped_stream = Some(stream.to_string());
            }
            return;
        }
        let text = String::from_utf8_lossy(&partial.bytes);
        let matched = match pattern {
            WatchPattern::Substring(needle) => !needle.is_empty() && text.contains(needle),
            WatchPattern::Regex(regex) => regex.is_match(&text),
        };
        if !matched {
            return;
        }
        // Count source lines, not folded rows, so repetition cannot bypass the cap.
        if self.retained >= MAX_LINES_PER_NOTIFICATION {
            self.batch.drop_line(stream, partial.offset);
            return;
        }
        self.retained += 1;
        if let Some(previous) = self.batch.lines.last_mut() {
            if previous.stream == stream
                && previous.offset.saturating_add(
                    previous
                        .count
                        .saturating_mul(previous.end_offset - previous.offset),
                ) == partial.offset
                && previous.text == text
            {
                previous.count = previous.count.saturating_add(1);
                return;
            }
        }
        self.batch.lines.push(WatchLine {
            stream: stream.to_string(),
            offset: partial.offset,
            end_offset: end,
            text: text.into_owned(),
            count: 1,
            unavailable: false,
        });
    }

    pub fn take(
        &mut self,
        now: Instant,
        terminal: bool,
        pattern: &WatchPattern,
    ) -> Option<LineBatch> {
        if terminal {
            for (stream, partial) in std::mem::take(&mut self.streams) {
                if !partial.bytes.is_empty() || partial.oversized {
                    let end = partial.offset.saturating_add(partial.bytes.len() as u64);
                    self.finish_line(&stream, &partial, end, pattern);
                }
            }
        }
        if self
            .window
            .is_none_or(|start| now.saturating_duration_since(start) >= NOTIFICATION_WINDOW)
        {
            self.window = Some(now);
            self.sent = 0;
        }
        if self.sent >= MAX_NOTIFICATIONS_PER_MINUTE {
            for line in std::mem::take(&mut self.batch.lines) {
                self.batch.drop_line(&line.stream, line.offset);
                self.batch.dropped_lines = self.batch.dropped_lines.saturating_add(line.count - 1);
            }
            self.retained = 0;
            if !terminal {
                return None;
            }
            self.batch.terminal_summary = true;
        }
        if self.batch.is_empty() {
            return None;
        }
        self.sent += 1;
        self.retained = 0;
        Some(std::mem::take(&mut self.batch))
    }
}

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

    fn pattern() -> WatchPattern {
        WatchPattern::Substring("ERROR".into())
    }

    #[test]
    fn each_line_delivers_all_matches_in_one_block() {
        for pattern in [pattern(), WatchPattern::regex("ERROR.*").unwrap()] {
            let mut delivery = LineDelivery::default();
            delivery.scan("stdout", b"ERROR a\nok\nERROR b\nERROR c\n", 0, &pattern);
            let batch = delivery.take(Instant::now(), false, &pattern).unwrap();
            assert_eq!(
                batch
                    .lines
                    .iter()
                    .map(|line| (line.offset, line.text.as_str()))
                    .collect::<Vec<_>>(),
                vec![(0, "ERROR a"), (11, "ERROR b"), (19, "ERROR c")]
            );
        }
    }

    #[test]
    fn each_line_split_across_blocks_delivered_once() {
        let mut delivery = LineDelivery::default();
        delivery.scan("stdout", b"ER", 40, &pattern());
        assert!(delivery.take(Instant::now(), false, &pattern()).is_none());
        delivery.scan("stdout", b"ROR a\n", 42, &pattern());
        let batch = delivery.take(Instant::now(), false, &pattern()).unwrap();
        assert_eq!(batch.lines[0].text, "ERROR a");
        assert_eq!(batch.lines[0].offset, 40);
        assert!(delivery.take(Instant::now(), true, &pattern()).is_none());
    }

    #[test]
    fn each_line_cap_reports_exact_count_and_offset() {
        let mut delivery = LineDelivery::default();
        for index in 0..53 {
            delivery.scan("stderr", b"ERROR\n", index * 6, &pattern());
        }
        let batch = delivery.take(Instant::now(), false, &pattern()).unwrap();
        assert_eq!(batch.lines.iter().map(|line| line.count).sum::<u64>(), 50);
        assert_eq!(batch.dropped_lines, 3);
        assert_eq!(batch.first_dropped_offset, Some(300));
        assert_eq!(batch.first_dropped_stream.as_deref(), Some("stderr"));
    }

    #[test]
    fn each_line_rate_cap_and_terminal_summary() {
        let now = Instant::now();
        let mut delivery = LineDelivery::default();
        for index in 0..12 {
            delivery.scan("stdout", b"ERROR\n", index * 6, &pattern());
            assert!(delivery.take(now, false, &pattern()).is_some());
        }
        delivery.scan("stdout", b"ERROR\nERROR\n", 72, &pattern());
        assert!(delivery.take(now, false, &pattern()).is_none());
        let batch = delivery.take(now, true, &pattern()).unwrap();
        assert_eq!(batch.dropped_lines, 2);
        assert_eq!(batch.first_dropped_offset, Some(72));
        assert!(batch.lines.is_empty());
        assert!(delivery
            .take(now + NOTIFICATION_WINDOW, false, &pattern())
            .is_none());
        delivery.scan("stdout", b"ERROR\n", 84, &pattern());
        assert_eq!(
            delivery
                .take(now + NOTIFICATION_WINDOW, false, &pattern())
                .unwrap()
                .lines
                .len(),
            1
        );
    }

    #[test]
    fn each_line_folds_only_consecutive_identical_lines() {
        let mut delivery = LineDelivery::default();
        delivery.scan(
            "stdout",
            b"ERROR a\nERROR a\nignore\nERROR a\n",
            0,
            &pattern(),
        );
        let batch = delivery.take(Instant::now(), false, &pattern()).unwrap();
        assert_eq!(batch.lines.len(), 2);
        assert_eq!(batch.lines[0].count, 2);
        assert_eq!(batch.lines[1].count, 1);
    }

    #[test]
    fn each_line_oversized_line_is_bounded_and_explicit() {
        let mut delivery = LineDelivery::default();
        delivery.scan("stdout", &vec![b'x'; MAX_LINE_BYTES], 0, &pattern());
        delivery.scan(
            "stdout",
            b"x\nERROR final",
            MAX_LINE_BYTES as u64,
            &pattern(),
        );
        let batch = delivery.take(Instant::now(), true, &pattern()).unwrap();
        assert_eq!(batch.skipped_long_lines, 1);
        assert_eq!(batch.first_dropped_offset, Some(0));
        assert_eq!(batch.lines[0].text, "ERROR final");
    }
}
/// Render a bounded line batch; offsets refer to the original, unmasked stream.
pub fn format_watch_line_batch(task_id: &str, batch: &LineBatch) -> String {
    let mut text = String::new();
    for line in &batch.lines {
        let body = if line.unavailable {
            crate::task_watch_lines::unavailable_match_text(
                line.count,
                batch
                    .masking_limit_bytes
                    .map(|limit| limit as usize)
                    .unwrap_or(crate::task_watch_lines::MASKING_LINE_CAP_BYTES),
            )
        } else {
            line.text.clone()
        };
        let repeats = if line.count > 1 {
            format!(" ×{}", line.count)
        } else {
            String::new()
        };
        text.push_str(&format!(
            "{} byte {}{repeats}: {}\n",
            line.stream, line.offset, body
        ));
    }
    if batch.dropped_lines > 0 || batch.skipped_long_lines > 0 {
        let incomplete = if batch.skipped_long_lines > 0 {
            format!(
                " {} lines longer than 64 KiB were skipped, so the scan is incomplete.",
                batch.skipped_long_lines
            )
        } else {
            String::new()
        };
        let cursor = if batch.first_dropped_stream.as_deref() == Some("stderr") {
            "stderr_offset"
        } else {
            "output_offset"
        };
        text.push_str(&format!("{} matching lines dropped.{incomplete} Read them with bash_status({{ task_id: {}, {cursor}: {} }}).\n", batch.dropped_lines, serde_json::to_string(task_id).unwrap_or_default(), batch.first_dropped_offset.unwrap_or(0)));
    }
    if let Some(gap) = &batch.retry_gap {
        let missing = match gap.known_missing_occurrences {
            0 => "Some matches may be missing.".to_string(),
            1 => "At least 1 match is missing.".to_string(),
            count => format!("At least {count} matches are missing."),
        };
        let cursor = if gap.stream.as_deref() == Some("stderr") {
            "stderr_offset"
        } else {
            "output_offset"
        };
        text.push_str(&format!("Some watch notices were lost: a stalled connection dropped {} of them, and they cannot be recovered. {missing} Read the task output with bash_status({{ task_id: {}, {cursor}: {} }}).\n", gap.dropped_notifications, serde_json::to_string(task_id).unwrap_or_default(), gap.first_offset.unwrap_or(0)));
    }
    text.trim_end().to_string()
}

static NEXT_EVICTION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
static EVICTION_EPOCH: std::sync::OnceLock<String> = std::sync::OnceLock::new();

pub fn eviction_epoch() -> &'static str {
    EVICTION_EPOCH.get_or_init(|| {
        format!(
            "{}:{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos()
        )
    })
}

#[derive(Clone)]
pub struct Candidate {
    pub eviction_epoch: String,
    pub last_eviction: u64,
    pub fingerprint: Vec<u8>,
    pub frame: crate::protocol::BashPatternMatchFrame,
    pub notifications: u64,
    pub first_version: u64,
    pub last_version: u64,
    pub first_offset: Option<u64>,
    pub last_offset: Option<u64>,
    pub stream: Option<String>,
    pub same_generation: bool,
    pub same_occurrence: bool,
}

impl Candidate {
    pub fn new(mut frame: crate::protocol::BashPatternMatchFrame) -> Self {
        use sha2::Digest;
        let fingerprint = sha2::Sha256::digest(frame.match_text.as_bytes()).to_vec();
        let (first_offset, last_offset, stream) = if let Some(batch) = &frame.batch {
            let stream = batch.lines.first().map(|line| line.stream.clone());
            if batch
                .lines
                .iter()
                .all(|line| Some(&line.stream) == stream.as_ref())
            {
                (
                    batch
                        .lines
                        .first()
                        .map(|line| line.offset)
                        .or(batch.first_dropped_offset),
                    batch.lines.last().map(|line| {
                        line.offset.saturating_add(
                            line.count
                                .saturating_mul(line.end_offset.saturating_sub(line.offset)),
                        )
                    }),
                    stream.or(batch.first_dropped_stream.clone()),
                )
            } else {
                (None, None, None)
            }
        } else {
            (Some(frame.match_offset), Some(frame.match_offset), None)
        };
        let version = frame.match_offset;
        frame.match_text = String::new();
        frame.context = String::new();
        if let Some(batch) = &mut frame.batch {
            batch.lines = Vec::new();
        }
        Self {
            eviction_epoch: eviction_epoch().to_string(),
            last_eviction: NEXT_EVICTION.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
            fingerprint,
            frame,
            notifications: 1,
            first_version: version,
            last_version: version,
            first_offset,
            last_offset,
            stream,
            same_generation: true,
            same_occurrence: true,
        }
    }

    pub fn merge(&mut self, next: Self) {
        self.same_occurrence &= next.same_occurrence
            && self.fingerprint == next.fingerprint
            && self.first_version == next.first_version;
        self.last_eviction = self.last_eviction.max(next.last_eviction);
        self.notifications = self.notifications.saturating_add(next.notifications);
        self.first_version = self.first_version.min(next.first_version);
        self.last_version = self.last_version.max(next.last_version);
        self.same_generation &= next.same_generation
            && self
                .frame
                .batch
                .as_ref()
                .and_then(|b| b.pending_id.as_ref())
                == next
                    .frame
                    .batch
                    .as_ref()
                    .and_then(|b| b.pending_id.as_ref());
        if self.stream == next.stream {
            self.first_offset = self
                .first_offset
                .zip(next.first_offset)
                .map(|(a, b)| a.min(b));
            self.last_offset = self
                .last_offset
                .zip(next.last_offset)
                .map(|(a, b)| a.max(b));
        } else {
            self.first_offset = None;
            self.last_offset = None;
            self.stream = None;
        }
    }
}