Skip to main content

agentmux_srv_core/backend/
editor_search.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `filesearchbytes`: the next match of a byte pattern in a file, for the hex
5//! viewer's find. The file is read here, in blocks, so one bigger than memory
6//! can be searched; each call does a bounded amount of work and says where to
7//! go on from, so a search of a very large file never holds a worker.
8//!
9//! docs/specs/SPEC_EDITOR_REVAMP_UNIFIED_VIEWERS_2026_10_15.md ยง4.4.5.
10
11use std::io::{Read, Seek, SeekFrom};
12use std::path::Path;
13use std::time::{Duration, Instant};
14
15use crate::backend::base::expand_home_dir_safe;
16use crate::backend::rpc::engine::WshRpcEngine;
17use crate::backend::rpc_types::{FileSearchBytesReq, FileSearchBytesResult};
18
19/// The longest pattern.
20const MAX_PATTERN: usize = 256;
21/// One read.
22const BLOCK: u64 = 1 << 20;
23/// The most a call reads before it hands back where it got to.
24const BUDGET_BYTES: u64 = 256 << 20;
25/// The longest a call goes on before it hands back where it got to.
26const BUDGET_TIME: Duration = Duration::from_millis(1500);
27
28/// A pattern of bytes, some of which match any byte.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct Pattern {
31    bytes: Vec<u8>,
32    /// Per byte: it must match (false for `??`).
33    literal: Vec<bool>,
34    /// A match starts at a multiple of this (1: anywhere; 2: UTF-16 text, whose
35    /// matches begin on a code unit).
36    align: u64,
37}
38
39impl Pattern {
40    /// "DE AD ?? EF", with or without the spaces.
41    pub fn parse(text: &str) -> Result<Pattern, String> {
42        let digits: Vec<char> = text.chars().filter(|c| !c.is_whitespace()).collect();
43        if digits.is_empty() {
44            return Err("the pattern is empty".into());
45        }
46        if digits.len() % 2 != 0 {
47            return Err("a pattern is whole bytes: two hex digits each, or ??".into());
48        }
49        let mut bytes = Vec::new();
50        let mut literal = Vec::new();
51        for pair in digits.chunks(2) {
52            match (pair[0], pair[1]) {
53                ('?', '?') => {
54                    bytes.push(0);
55                    literal.push(false);
56                }
57                (a, b) => {
58                    let hex = |c: char| c.to_digit(16).ok_or_else(|| format!("'{c}' is not a hex digit"));
59                    bytes.push((hex(a)? * 16 + hex(b)?) as u8);
60                    literal.push(true);
61                }
62            }
63        }
64        if bytes.len() > MAX_PATTERN {
65            return Err(format!("a pattern is at most {MAX_PATTERN} bytes"));
66        }
67        if !literal.iter().any(|l| *l) {
68            return Err("a pattern of only ?? matches everywhere".into());
69        }
70        Ok(Pattern { bytes, literal, align: 1 })
71    }
72
73    /// The same pattern, matching only at offsets that are a multiple of `align` (0 and 1 mean anywhere).
74    pub fn aligned(mut self, align: u64) -> Pattern {
75        self.align = align.max(1);
76        self
77    }
78
79    pub fn len(&self) -> usize {
80        self.bytes.len()
81    }
82
83    pub fn is_empty(&self) -> bool {
84        self.bytes.is_empty()
85    }
86
87    /// The index of the byte the scan looks for with memchr: the first one that must match.
88    fn anchor(&self) -> usize {
89        self.literal.iter().position(|l| *l).unwrap_or(0)
90    }
91
92    /// Does the pattern match `window` (exactly its length)?
93    fn matches(&self, window: &[u8]) -> bool {
94        window.iter().zip(&self.bytes).zip(&self.literal).all(|((w, b), lit)| !lit || w == b)
95    }
96}
97
98/// Every start in `buf[..starts]` where the pattern matches (at an offset its
99/// alignment allows; `base` is the file offset of `buf[0]`), first or last of
100/// them. `buf` holds at least `starts - 1 + pattern.len()` bytes.
101fn scan(buf: &[u8], starts: usize, pat: &Pattern, last: bool, base: u64) -> Option<usize> {
102    let k = pat.anchor();
103    let lit = pat.bytes[k];
104    let hay = &buf[k..k + starts];
105    let hit = |i: &usize| (base + *i as u64) % pat.align == 0 && pat.matches(&buf[*i..*i + pat.len()]);
106    if last {
107        memchr::memrchr_iter(lit, hay).find(hit)
108    } else {
109        memchr::memchr_iter(lit, hay).find(hit)
110    }
111}
112
113/// The search over `file` (`size` bytes). Forward: the first match starting
114/// at or after `from`; backward: the last one starting at or before it.
115pub fn search<F: Read + Seek>(
116    file: &mut F,
117    size: u64,
118    pat: &Pattern,
119    from: u64,
120    backward: bool,
121    budget_bytes: u64,
122    budget_time: Duration,
123) -> std::io::Result<FileSearchBytesResult> {
124    let plen = pat.len() as u64;
125    let length = plen;
126    let not_found = |done: bool, next_from: u64| FileSearchBytesResult { found: false, offset: 0, length, done, next_from };
127    if size < plen {
128        return Ok(not_found(true, 0));
129    }
130    // The last place a match can start.
131    let last_start = size - plen;
132    let started = Instant::now();
133    let mut read = 0u64;
134    let mut buf = Vec::new();
135    if !backward {
136        let mut at = from;
137        while at <= last_start {
138            let starts = BLOCK.min(last_start - at + 1);
139            let want = (starts - 1 + plen) as usize;
140            buf.resize(want, 0);
141            file.seek(SeekFrom::Start(at))?;
142            file.read_exact(&mut buf)?;
143            if let Some(i) = scan(&buf, starts as usize, pat, false, at) {
144                return Ok(FileSearchBytesResult { found: true, offset: at + i as u64, length, done: false, next_from: 0 });
145            }
146            at += starts;
147            read += want as u64;
148            if at <= last_start && (read >= budget_bytes || started.elapsed() >= budget_time) {
149                return Ok(not_found(false, at));
150            }
151        }
152        return Ok(not_found(true, size));
153    }
154    // Backward: windows of starts [lo, hi], going down.
155    let mut hi = from.min(last_start);
156    loop {
157        let lo = hi.saturating_sub(BLOCK - 1);
158        let starts = hi - lo + 1;
159        let want = (starts - 1 + plen) as usize;
160        buf.resize(want, 0);
161        file.seek(SeekFrom::Start(lo))?;
162        file.read_exact(&mut buf)?;
163        if let Some(i) = scan(&buf, starts as usize, pat, true, lo) {
164            return Ok(FileSearchBytesResult { found: true, offset: lo + i as u64, length, done: false, next_from: 0 });
165        }
166        if lo == 0 {
167            return Ok(not_found(true, 0));
168        }
169        hi = lo - 1;
170        read += want as u64;
171        if read >= budget_bytes || started.elapsed() >= budget_time {
172            return Ok(not_found(false, hi));
173        }
174    }
175}
176
177/// `filesearchbytes`. This computer's files only, like `fileprobe`.
178pub fn register(engine: &std::sync::Arc<WshRpcEngine>) {
179    engine.register_typed("filesearchbytes", move |cmd: FileSearchBytesReq, _ctx| async move {
180        let pattern = Pattern::parse(&cmd.pattern).map_err(|e| format!("filesearchbytes: {e}"))?.aligned(cmd.align.unwrap_or(1));
181        let path = expand_home_dir_safe(&cmd.path);
182        tokio::task::spawn_blocking(move || search_path(&path, &pattern, cmd.from, cmd.backward).map_err(|e| format!("filesearchbytes: {e}")))
183            .await
184            .map_err(|e| format!("filesearchbytes: {e}"))?
185    });
186}
187
188fn search_path(path: &Path, pat: &Pattern, from: u64, backward: bool) -> std::io::Result<FileSearchBytesResult> {
189    let meta = std::fs::metadata(path)?;
190    if meta.is_dir() {
191        return Err(std::io::Error::other("is a directory"));
192    }
193    let mut file = std::fs::File::open(path)?;
194    search(&mut file, meta.len(), pat, from, backward, BUDGET_BYTES, BUDGET_TIME)
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200    use std::io::Cursor;
201
202    fn find(data: &[u8], pattern: &str, from: u64, backward: bool) -> FileSearchBytesResult {
203        let pat = Pattern::parse(pattern).unwrap();
204        search(&mut Cursor::new(data.to_vec()), data.len() as u64, &pat, from, backward, u64::MAX, Duration::from_secs(60)).unwrap()
205    }
206
207    #[test]
208    fn parses_hex_with_wildcards_and_refuses_the_rest() {
209        let p = Pattern::parse("DE AD ?? ef").unwrap();
210        assert_eq!(p.bytes, vec![0xde, 0xad, 0, 0xef]);
211        assert_eq!(p.literal, vec![true, true, false, true]);
212        assert_eq!(Pattern::parse("DEAD??EF").unwrap(), p);
213        assert!(Pattern::parse("").is_err());
214        assert!(Pattern::parse("DEA").is_err());
215        assert!(Pattern::parse("ZZ").is_err());
216        assert!(Pattern::parse("?? ??").is_err());
217        assert!(Pattern::parse(&"AA".repeat(257)).is_err());
218        assert!(Pattern::parse(&"AA".repeat(256)).is_ok());
219    }
220
221    #[test]
222    fn finds_the_next_match_forward_and_the_one_before_backward() {
223        let mut data = vec![0u8; 100];
224        data[10..14].copy_from_slice(&[0xde, 0xad, 0x00, 0xef]);
225        data[50..54].copy_from_slice(&[0xde, 0xad, 0x77, 0xef]);
226        let a = find(&data, "DE AD ?? EF", 0, false);
227        assert!(a.found);
228        assert_eq!((a.offset, a.length), (10, 4));
229        // From just after the first: the second.
230        assert_eq!(find(&data, "DE AD ?? EF", 11, false).offset, 50);
231        // The match may start exactly at `from`.
232        assert_eq!(find(&data, "DE AD ?? EF", 50, false).offset, 50);
233        assert!(find(&data, "DE AD ?? EF", 51, false).done);
234        assert_eq!(find(&data, "DE AD ?? EF", 99, true).offset, 50);
235        assert_eq!(find(&data, "DE AD ?? EF", 49, true).offset, 10);
236        assert!(!find(&data, "DE AD ?? EF", 9, true).found);
237        assert!(find(&data, "DE AD ?? EF", 9, true).done);
238    }
239
240    #[test]
241    fn a_match_across_a_block_boundary_and_at_the_very_end_is_found() {
242        let edge = BLOCK as usize;
243        let mut data = vec![0u8; edge * 2 + 10];
244        data[edge - 2..edge + 2].copy_from_slice(&[1, 2, 3, 4]);
245        let end = data.len();
246        data[end - 3..].copy_from_slice(&[9, 8, 7]);
247        assert_eq!(find(&data, "01 02 03 04", 0, false).offset, (edge - 2) as u64);
248        assert_eq!(find(&data, "01 02 03 04", (edge * 2) as u64, true).offset, (edge - 2) as u64);
249        assert_eq!(find(&data, "09 08 07", 0, false).offset, (end - 3) as u64);
250        assert_eq!(find(&data, "09 08 07", end as u64, true).offset, (end - 3) as u64);
251        assert!(!find(&data, "09 08 06", 0, false).found);
252    }
253
254    /// `00 62` repeated: "b" is 62 00, and it starts at every odd offset, between two code units.
255    fn utf16_with_misaligned_hits(units: usize) -> Vec<u8> {
256        let mut data = Vec::new();
257        for _ in 0..units {
258            data.extend_from_slice(&[0x00, 0x62]);
259        }
260        data
261    }
262
263    #[test]
264    fn an_alignment_skips_matches_between_code_units_forward_and_backward() {
265        let mut data = utf16_with_misaligned_hits(5);
266        data.extend_from_slice(&[0x62, 0x00]); // a real "b", at an even offset
267        let at = (data.len() - 2) as u64;
268        assert_eq!(at % 2, 0);
269        let pat = Pattern::parse("62 00").unwrap();
270        let run = |pat: &Pattern, from: u64, backward: bool| search(&mut Cursor::new(data.clone()), data.len() as u64, pat, from, backward, u64::MAX, Duration::from_secs(60)).unwrap();
271        // Unaligned: the first stray pair, at offset 1.
272        assert_eq!(run(&pat, 0, false).offset, 1);
273        // Aligned to 2: every stray pair is skipped in the scan, in one call, to the real one.
274        let aligned = pat.clone().aligned(2);
275        assert_eq!(run(&aligned, 0, false).offset, at);
276        assert_eq!(run(&aligned, data.len() as u64, true).offset, at);
277        // Nothing aligned before the real one, going back from just ahead of it.
278        let r = run(&aligned, at - 1, true);
279        assert!(!r.found && r.done);
280    }
281
282    #[test]
283    fn an_alignment_holds_across_a_block_edge() {
284        let edge = BLOCK as usize;
285        // The block edge is even: a match one byte before it is misaligned, the next block's start is not.
286        let mut data = vec![0xAAu8; edge * 2 + 8];
287        data[edge - 1..edge + 1].copy_from_slice(&[0x62, 0x00]);
288        data[edge + 4..edge + 6].copy_from_slice(&[0x62, 0x00]);
289        let pat = Pattern::parse("62 00").unwrap().aligned(2);
290        let size = data.len() as u64;
291        let run = |from: u64, backward: bool| search(&mut Cursor::new(data.clone()), size, &pat, from, backward, u64::MAX, Duration::from_secs(60)).unwrap();
292        assert_eq!(run(0, false).offset, (edge + 4) as u64);
293        assert_eq!(run(size, true).offset, (edge + 4) as u64);
294        assert!(!run(edge as u64 + 3, true).found);
295    }
296
297    #[test]
298    fn a_pattern_longer_than_the_file_is_not_found_and_done() {
299        let r = find(&[1, 2], "01 02 03", 0, false);
300        assert!(!r.found && r.done);
301        let r = find(&[], "01", 0, true);
302        assert!(!r.found && r.done);
303    }
304
305    #[test]
306    fn hands_back_where_it_got_to_when_its_budget_runs_out() {
307        let data = vec![0u8; (BLOCK as usize) * 4];
308        let pat = Pattern::parse("01").unwrap();
309        // A budget of one block: one block read, then the way on.
310        let r = search(&mut Cursor::new(data.clone()), data.len() as u64, &pat, 0, false, 1, Duration::from_secs(60)).unwrap();
311        assert!(!r.found && !r.done);
312        assert_eq!(r.next_from, BLOCK);
313        let r = search(&mut Cursor::new(data.clone()), data.len() as u64, &pat, data.len() as u64, true, 1, Duration::from_secs(60)).unwrap();
314        assert!(!r.found && !r.done);
315        assert_eq!(r.next_from, BLOCK * 3 - 1);
316    }
317
318    #[test]
319    fn searches_a_real_file_and_refuses_a_folder() {
320        let dir = tempfile::tempdir().unwrap();
321        let file = dir.path().join("a.bin");
322        std::fs::write(&file, [0u8, 1, 2, 3, 4, 5]).unwrap();
323        let pat = Pattern::parse("03 ?? 05").unwrap();
324        assert_eq!(search_path(&file, &pat, 0, false).unwrap().offset, 3);
325        assert!(search_path(dir.path(), &pat, 0, false).is_err());
326    }
327
328    #[tokio::test]
329    async fn filesearchbytes_records_its_types() {
330        let (engine, _rx) = WshRpcEngine::new();
331        register(&engine);
332        let schema = engine.schema_json();
333        let row = schema.as_array().unwrap().iter().find(|r| r["command"] == "filesearchbytes").expect("filesearchbytes missing from the schema");
334        assert_eq!(row["requestName"], "FileSearchBytesReq");
335        assert_eq!(row["responseName"], "FileSearchBytesResult");
336    }
337}