Skip to main content

adk_harness/shell/
output.rs

1//! Where the harness keeps command output (spec 3.1 §7.29, §7.33 fix 8): the whole output of
2//! a `bash` call whose result was cut, in `<session scratch>/shells/<id>.log`, read back with
3//! `shell_output`.
4
5use std::collections::HashMap;
6use std::io::{Read, Seek, SeekFrom};
7use std::path::{Path, PathBuf};
8use std::sync::{Arc, Mutex};
9use std::time::{Duration, Instant};
10
11use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result, Tool, ToolContext};
12use adk_devtools::{INLINE_OUTPUT_CHARS, OutputFile, OutputStore};
13use async_trait::async_trait;
14use serde_json::{Value, json};
15
16use super::background::{ShellStatus, ShellSupervisor};
17
18/// Bytes read from a log for one answer: enough for every character of it at four bytes
19/// each.
20const WINDOW_BYTES: u64 = INLINE_OUTPUT_CHARS as u64 * 4;
21
22/// The most output records kept per process; the oldest go first.
23const MAX_RECORDS: usize = 4096;
24
25/// What the harness knows about one kept output.
26#[derive(Clone, Debug)]
27pub(crate) struct OutputRecord {
28    pub(crate) command: String,
29    pub(crate) started: Instant,
30    /// The exit code and how long the command ran, once it has finished.
31    pub(crate) finished: Option<(Option<i32>, Duration)>,
32}
33
34/// The output files of every session of a harness: `<root>/<session key>/shells/<id>.log`,
35/// outside the workspace and outside the sandbox's writable scratch (spec 3.1 §7.29), with
36/// ids numbered per session.
37///
38/// It is the [`OutputStore`] of the harness `bash`: a call whose output does not fit its
39/// result keeps the whole of it here, and `shell_output` reads it by id.
40///
41/// # Example
42///
43/// ```rust
44/// use adk_harness::ShellOutputs;
45///
46/// let outputs = ShellOutputs::new(std::env::temp_dir().join("adk-harness-output-doc"));
47/// let dir = outputs.session_dir("app", "alice", "s1");
48/// assert!(dir.ends_with("shells"));
49/// assert_ne!(dir, outputs.session_dir("app", "bob", "s1"));
50/// ```
51#[derive(Debug)]
52pub struct ShellOutputs {
53    root: PathBuf,
54    /// The next id per session directory.
55    next: Mutex<HashMap<PathBuf, u64>>,
56    records: Mutex<HashMap<(PathBuf, String), OutputRecord>>,
57}
58
59impl Default for ShellOutputs {
60    /// Output under `adk-harness-output` in the system's temporary directory; on Unix,
61    /// `adk-harness-output-<uid>`, so users sharing `/tmp` never share a directory.
62    fn default() -> Self {
63        #[cfg(unix)]
64        // SAFETY: `geteuid` takes no arguments and cannot fail.
65        let name = format!("adk-harness-output-{}", unsafe { libc::geteuid() });
66        #[cfg(not(unix))]
67        let name = "adk-harness-output".to_string();
68        Self::new(std::env::temp_dir().join(name))
69    }
70}
71
72impl ShellOutputs {
73    /// Output files under `root`.
74    pub fn new(root: impl Into<PathBuf>) -> Self {
75        Self { root: root.into(), next: Mutex::default(), records: Mutex::default() }
76    }
77
78    /// The directory of (`app`, `user`, `session`)'s output files.
79    pub fn session_dir(&self, app: &str, user: &str, session: &str) -> PathBuf {
80        let key = crate::fsutil::sha256_hex(&format!("{app}\u{1f}{user}\u{1f}{session}"));
81        self.root.join(&key[..32]).join("shells")
82    }
83
84    /// The path of output `id` in `dir`, or `None` for an id the harness never gives: ids
85    /// are decimal numbers.
86    fn path_of(dir: &Path, id: &str) -> Option<PathBuf> {
87        (!id.is_empty() && id.len() <= 20 && id.bytes().all(|byte| byte.is_ascii_digit()))
88            .then(|| dir.join(format!("{id}.log")))
89    }
90
91    /// Creates `dir` private to this user, refusing one another user owns.
92    fn prepare(dir: &Path) -> std::io::Result<()> {
93        std::fs::create_dir_all(dir)?;
94        #[cfg(unix)]
95        {
96            use std::os::unix::fs::{MetadataExt, PermissionsExt};
97            let session = dir.parent().unwrap_or(dir);
98            for path in [dir, session, session.parent().unwrap_or(session)] {
99                let meta = std::fs::symlink_metadata(path)?;
100                // SAFETY: `geteuid` takes no arguments and cannot fail.
101                let me = unsafe { libc::geteuid() };
102                if !meta.is_dir() || meta.uid() != me {
103                    return Err(std::io::Error::other(format!(
104                        "{} is not a directory this user owns",
105                        path.display()
106                    )));
107                }
108                std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))?;
109            }
110        }
111        Ok(())
112    }
113
114    /// Creates the next output file of (`app`, `user`, `session`) for `command`.
115    pub(crate) fn allocate(
116        &self,
117        app: &str,
118        user: &str,
119        session: &str,
120        command: &str,
121    ) -> std::io::Result<OutputFile> {
122        let dir = self.session_dir(app, user, session);
123        Self::prepare(&dir)?;
124        let mut next = self.next.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
125        let counter = next.entry(dir.clone()).or_insert_with(|| highest_id(&dir) + 1);
126        // A file an earlier process left under the same number is never reused.
127        let (id, path, file) = loop {
128            let id = counter.to_string();
129            *counter += 1;
130            let path = dir.join(format!("{id}.log"));
131            let mut options = std::fs::File::options();
132            options.write(true).create_new(true);
133            #[cfg(unix)]
134            {
135                use std::os::unix::fs::OpenOptionsExt;
136                options.mode(0o600);
137            }
138            match options.open(&path) {
139                Ok(file) => break (id, path, file),
140                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
141                Err(error) => return Err(error),
142            }
143        };
144        drop(next);
145        let mut records = self.records.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
146        if records.len() >= MAX_RECORDS {
147            let oldest =
148                records.iter().min_by_key(|(_, record)| record.started).map(|(k, _)| k.clone());
149            if let Some(oldest) = oldest {
150                records.remove(&oldest);
151            }
152        }
153        records.insert(
154            (dir, id.clone()),
155            OutputRecord { command: command.to_string(), started: Instant::now(), finished: None },
156        );
157        Ok(OutputFile { id, path, file })
158    }
159
160    /// Records that the command of output `id` finished with `exit_code` after `duration`.
161    pub(crate) fn finish(
162        &self,
163        (app, user, session): (&str, &str, &str),
164        id: &str,
165        exit_code: Option<i32>,
166        duration: Duration,
167    ) {
168        let key = (self.session_dir(app, user, session), id.to_string());
169        let mut records = self.records.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
170        if let Some(record) = records.get_mut(&key) {
171            record.finished = Some((exit_code, duration));
172        }
173    }
174
175    /// What is known about output `id` of the session.
176    pub(crate) fn record(
177        &self,
178        (app, user, session): (&str, &str, &str),
179        id: &str,
180    ) -> Option<OutputRecord> {
181        let key = (self.session_dir(app, user, session), id.to_string());
182        self.records.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&key).cloned()
183    }
184
185    /// Reads `slice` of output `id` of the session.
186    ///
187    /// # Errors
188    ///
189    /// `NotFound` when the session has no output `id`, or the I/O error.
190    pub(crate) fn read(
191        &self,
192        (app, user, session): (&str, &str, &str),
193        id: &str,
194        slice: &Slice,
195    ) -> std::io::Result<OutputRead> {
196        let dir = self.session_dir(app, user, session);
197        let not_found =
198            || std::io::Error::new(std::io::ErrorKind::NotFound, format!("no output {id}"));
199        let path = Self::path_of(&dir, id).ok_or_else(not_found)?;
200        // The directory is this user's own, and a link in it is never followed.
201        match std::fs::symlink_metadata(&path) {
202            Ok(meta) if meta.is_file() => {}
203            Ok(_) => return Err(not_found()),
204            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Err(not_found()),
205            Err(error) => return Err(error),
206        }
207        let mut file = std::fs::File::open(&path)?;
208        let total = file.metadata()?.len();
209        read_slice(&mut file, total, slice)
210    }
211}
212
213impl OutputStore for ShellOutputs {
214    fn create(&self, ctx: &dyn ToolContext, command: &str) -> std::io::Result<OutputFile> {
215        self.allocate(ctx.app_name(), ctx.user_id(), ctx.session_id(), command)
216    }
217}
218
219/// The name of the tool that reads kept output.
220///
221/// # Example
222///
223/// ```rust
224/// assert_eq!(adk_harness::SHELL_OUTPUT, "shell_output");
225/// ```
226pub const SHELL_OUTPUT: &str = "shell_output";
227
228/// `shell_output { shell_id, tail_lines?, offset?, limit?, pattern? }`: reads output the
229/// harness kept, by id (spec 3.1 §7.29, §7.33 fix 8).
230///
231/// Reads a background shell's output, or the whole output of a `bash` call whose result
232/// was cut, which names an `output_id`: at most 30,000 characters per call, by default its
233/// end; from `offset` the next `limit` bytes; the last `tail_lines` lines; or the lines
234/// matching `pattern`, a regular expression, numbered. Reports the status, exit code and
235/// duration. It reads only the calling session's output, and a background shell that ended
236/// leaves the reminder once read. Class `Read`.
237///
238/// # Example
239///
240/// ```rust
241/// use std::sync::Arc;
242///
243/// use adk_core::Tool;
244/// use adk_harness::{BackgroundShellConfig, ShellOutputTool, ShellOutputs, ShellSupervisor};
245///
246/// let shells = ShellSupervisor::new(Arc::new(ShellOutputs::default()), BackgroundShellConfig::default());
247/// let tool = ShellOutputTool::new(Arc::new(shells));
248/// assert_eq!(tool.name(), "shell_output");
249/// assert!(tool.is_read_only());
250/// ```
251#[derive(Debug)]
252pub struct ShellOutputTool {
253    shells: Arc<ShellSupervisor>,
254}
255
256impl ShellOutputTool {
257    /// A tool reading the output `shells` keeps.
258    pub fn new(shells: Arc<ShellSupervisor>) -> Self {
259        Self { shells }
260    }
261}
262
263fn invalid(code: &'static str, message: impl Into<String>) -> AdkError {
264    AdkError::new(ErrorComponent::Tool, ErrorCategory::InvalidInput, code, message)
265}
266
267#[async_trait]
268impl Tool for ShellOutputTool {
269    fn name(&self) -> &str {
270        SHELL_OUTPUT
271    }
272
273    /// Reads output the harness kept.
274    fn egress(&self, _args: &serde_json::Value) -> adk_core::egress::ToolEgress {
275        adk_core::egress::ToolEgress::None
276    }
277
278    fn description(&self) -> &str {
279        "Read the output of a background shell by its shell_id, or the whole output of a bash \
280         call whose result was cut by its output_id. Returns the status, exit code, duration \
281         and at most 30,000 characters of the output: by default its end; offset and limit \
282         read bytes from a position, such as the bytes a cut result left out; tail_lines reads \
283         the last lines; pattern, a regular expression, returns the matching lines with their \
284         numbers."
285    }
286
287    fn parameters_schema(&self) -> Option<Value> {
288        Some(json!({
289            "type": "object",
290            "properties": {
291                "shell_id": { "type": "string", "description": "The shell_id or output_id a bash result named." },
292                "tail_lines": { "type": "integer", "minimum": 1, "description": "Read the last N lines." },
293                "offset": { "type": "integer", "minimum": 0, "description": "Read from this byte offset." },
294                "limit": { "type": "integer", "minimum": 1, "description": "With offset: how many bytes to read (default and most 30000 characters' worth)." },
295                "pattern": { "type": "string", "description": "Return only the lines matching this regular expression." }
296            },
297            "required": ["shell_id"]
298        }))
299    }
300
301    fn is_read_only(&self) -> bool {
302        true
303    }
304
305    fn is_concurrency_safe(&self) -> bool {
306        true
307    }
308
309    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
310        let id = match args.get("shell_id") {
311            Some(Value::String(id)) => id.trim().to_string(),
312            Some(Value::Number(id)) => id.to_string(),
313            _ => {
314                return Err(invalid("harness.shell_output.no_id", "shell_output needs a shell_id"));
315            }
316        };
317        let pattern = match args.get("pattern").and_then(Value::as_str) {
318            Some(pattern) => Some(regex::Regex::new(pattern).map_err(|error| {
319                invalid(
320                    "harness.shell_output.bad_pattern",
321                    format!("the pattern is not a valid regular expression: {error}"),
322                )
323            })?),
324            None => None,
325        };
326        let slice = Slice {
327            pattern,
328            offset: args.get("offset").and_then(Value::as_u64),
329            limit: args.get("limit").and_then(Value::as_u64),
330            tail_lines: args
331                .get("tail_lines")
332                .and_then(Value::as_u64)
333                .map(|n| usize::try_from(n).unwrap_or(usize::MAX)),
334        };
335        let session = (ctx.app_name(), ctx.user_id(), ctx.session_id());
336        let outputs = self.shells.outputs();
337        let read = outputs.read(session, &id, &slice).map_err(|error| {
338            if error.kind() == std::io::ErrorKind::NotFound {
339                AdkError::new(
340                    ErrorComponent::Tool,
341                    ErrorCategory::NotFound,
342                    "harness.shell_output.unknown",
343                    format!("this session has no output {id}"),
344                )
345            } else {
346                AdkError::tool(format!("output {id} could not be read: {error}"))
347            }
348        })?;
349        let key = (session.0.to_string(), session.1.to_string(), session.2.to_string());
350        let shell = self.shells.read(&key, &id).await;
351        let record = outputs.record(session, &id);
352        let mut result = json!({
353            "shell_id": id,
354            "total_bytes": read.total_bytes,
355            "output": read.text,
356        });
357        if slice.pattern.is_some() {
358            result["more_matches"] = json!(read.cut);
359        } else {
360            result["offset"] = json!(read.range.0);
361            result["next_offset"] = json!(read.range.1);
362            result["truncated"] = json!(read.cut);
363        }
364        let millis = |duration: Duration| u64::try_from(duration.as_millis()).unwrap_or(u64::MAX);
365        match (shell, record) {
366            (Some(shell), _) => {
367                result["status"] = json!(shell.status.name());
368                result["command"] = json!(shell.command);
369                result["duration_ms"] = json!(millis(shell.elapsed));
370                match shell.status {
371                    ShellStatus::Exited { exit_code } => result["exit_code"] = json!(exit_code),
372                    ShellStatus::Killed { cause } => result["killed_by"] = json!(cause),
373                    ShellStatus::Running => {}
374                }
375            }
376            (None, Some(record)) => {
377                result["command"] = json!(record.command);
378                match record.finished {
379                    Some((exit_code, duration)) => {
380                        result["status"] = json!("exited");
381                        result["exit_code"] = json!(exit_code);
382                        result["duration_ms"] = json!(millis(duration));
383                    }
384                    None => result["status"] = json!("running"),
385                }
386            }
387            (None, None) => result["status"] = json!("exited"),
388        }
389        Ok(result)
390    }
391}
392
393/// The highest output id in `dir`, 0 when there is none.
394fn highest_id(dir: &Path) -> u64 {
395    std::fs::read_dir(dir)
396        .into_iter()
397        .flatten()
398        .flatten()
399        .filter_map(|entry| entry.file_name().to_str()?.strip_suffix(".log")?.parse::<u64>().ok())
400        .max()
401        .unwrap_or(0)
402}
403
404/// Which part of an output to read; at most [`INLINE_OUTPUT_CHARS`] characters of it.
405#[derive(Clone, Debug, Default)]
406pub(crate) struct Slice {
407    /// Lines matching this pattern, with their numbers.
408    pub(crate) pattern: Option<regex::Regex>,
409    /// Bytes from this offset.
410    pub(crate) offset: Option<u64>,
411    /// How many bytes from `offset`.
412    pub(crate) limit: Option<u64>,
413    /// The last lines.
414    pub(crate) tail_lines: Option<usize>,
415}
416
417/// What a read returned.
418#[derive(Clone, Debug, PartialEq, Eq)]
419pub(crate) struct OutputRead {
420    /// The text: a byte range, or matching lines.
421    pub(crate) text: String,
422    /// Bytes in the file.
423    pub(crate) total_bytes: u64,
424    /// The byte range the text covers; for a pattern, the whole file.
425    pub(crate) range: (u64, u64),
426    /// Whether more matches, or more lines of the range asked for, were left out.
427    pub(crate) cut: bool,
428}
429
430fn read_slice(file: &mut std::fs::File, total: u64, slice: &Slice) -> std::io::Result<OutputRead> {
431    if let Some(pattern) = &slice.pattern {
432        return grep(file, total, pattern);
433    }
434    if let Some(offset) = slice.offset {
435        let offset = offset.min(total);
436        let limit = slice.limit.unwrap_or(INLINE_OUTPUT_CHARS as u64).min(WINDOW_BYTES);
437        let window = read_at(file, offset, limit.min(total - offset))?;
438        // A range starting or ending inside a character leaves those bytes to its neighbour.
439        let skipped = if offset > 0 {
440            window.iter().take(3).take_while(|&&b| b & 0xC0 == 0x80).count()
441        } else {
442            0
443        };
444        let end = if offset + window.len() as u64 == total {
445            window.len()
446        } else {
447            complete_end(&window)
448        };
449        let body = &window[skipped..end.max(skipped)];
450        let used = prefix_len(body, INLINE_OUTPUT_CHARS);
451        let start = offset + skipped as u64;
452        return Ok(OutputRead {
453            text: String::from_utf8_lossy(&body[..used]).into_owned(),
454            total_bytes: total,
455            range: (start, start + used as u64),
456            cut: used < body.len(),
457        });
458    }
459    // The end of the output: its last lines, or its last characters.
460    let start = total.saturating_sub(WINDOW_BYTES);
461    let window = read_at(file, start, total - start)?;
462    let skipped = if start > 0 {
463        window.iter().take(3).take_while(|&&b| b & 0xC0 == 0x80).count()
464    } else {
465        0
466    };
467    let window = &window[skipped..];
468    let mut from = suffix_start(window, INLINE_OUTPUT_CHARS);
469    let mut cut = false;
470    if let Some(lines) = slice.tail_lines {
471        // Lines that begin before the window, or past the characters an answer holds, are cut.
472        let line_start = nth_line_from_end(window, lines);
473        let wanted = line_start.unwrap_or(0);
474        cut = wanted < from || (line_start.is_none() && start > 0);
475        from = from.max(wanted);
476    }
477    let begin = start + (skipped + from) as u64;
478    Ok(OutputRead {
479        text: String::from_utf8_lossy(&window[from..]).into_owned(),
480        total_bytes: total,
481        range: (begin, total),
482        cut,
483    })
484}
485
486/// Lines of the file matching `pattern`, numbered from 1, up to [`INLINE_OUTPUT_CHARS`].
487fn grep(
488    file: &mut std::fs::File,
489    total: u64,
490    pattern: &regex::Regex,
491) -> std::io::Result<OutputRead> {
492    use std::io::BufRead;
493    file.seek(SeekFrom::Start(0))?;
494    let mut reader = std::io::BufReader::new(file);
495    let mut text = String::new();
496    let mut chars = 0;
497    let mut cut = false;
498    let mut line = Vec::new();
499    let mut number = 0usize;
500    loop {
501        line.clear();
502        if reader.read_until(b'\n', &mut line)? == 0 {
503            break;
504        }
505        number += 1;
506        let decoded = String::from_utf8_lossy(&line);
507        let decoded = decoded.trim_end_matches(['\n', '\r']);
508        if !pattern.is_match(decoded) {
509            continue;
510        }
511        let entry = format!("{number}: {decoded}\n");
512        let length = entry.chars().count();
513        if chars + length > INLINE_OUTPUT_CHARS {
514            cut = true;
515            break;
516        }
517        chars += length;
518        text.push_str(&entry);
519    }
520    Ok(OutputRead { text, total_bytes: total, range: (0, total), cut })
521}
522
523fn read_at(file: &mut std::fs::File, offset: u64, len: u64) -> std::io::Result<Vec<u8>> {
524    file.seek(SeekFrom::Start(offset))?;
525    let mut buf = Vec::with_capacity(usize::try_from(len).unwrap_or(0));
526    file.take(len).read_to_end(&mut buf)?;
527    Ok(buf)
528}
529
530/// Where `bytes` ends without a character cut short at its end.
531fn complete_end(bytes: &[u8]) -> usize {
532    let n = bytes.len();
533    for back in 1..=n.min(4) {
534        let byte = bytes[n - back];
535        if byte & 0xC0 == 0x80 {
536            continue;
537        }
538        let needs = match byte {
539            0xF0..=0xF7 => 4,
540            0xE0..=0xEF => 3,
541            0xC0..=0xDF => 2,
542            _ => 1,
543        };
544        return if needs > back { n - back } else { n };
545    }
546    n
547}
548
549/// Where the last `lines` lines of `bytes` begin, or `None` when it holds fewer; a final
550/// newline ends the last line.
551fn nth_line_from_end(bytes: &[u8], lines: usize) -> Option<usize> {
552    if lines == 0 {
553        return Some(bytes.len());
554    }
555    let body = bytes.strip_suffix(b"\n").unwrap_or(bytes);
556    body.iter()
557        .enumerate()
558        .rev()
559        .filter(|(_, byte)| **byte == b'\n')
560        .nth(lines - 1)
561        .map(|(index, _)| index + 1)
562}
563
564/// The characters of `bytes` decoded lossily: each invalid sequence is one character.
565fn char_count(bytes: &[u8]) -> usize {
566    bytes
567        .utf8_chunks()
568        .map(|chunk| chunk.valid().chars().count() + usize::from(!chunk.invalid().is_empty()))
569        .sum()
570}
571
572/// The bytes of the first `chars` characters of `bytes` decoded lossily.
573fn prefix_len(bytes: &[u8], chars: usize) -> usize {
574    let mut left = chars;
575    let mut at = 0;
576    for chunk in bytes.utf8_chunks() {
577        let valid = chunk.valid();
578        if let Some((index, _)) = valid.char_indices().nth(left) {
579            return at + index;
580        }
581        left -= valid.chars().count();
582        at += valid.len();
583        if !chunk.invalid().is_empty() {
584            if left == 0 {
585                return at;
586            }
587            left -= 1;
588            at += chunk.invalid().len();
589        }
590    }
591    at
592}
593
594/// Where the last `chars` characters of `bytes`, decoded lossily, begin.
595fn suffix_start(bytes: &[u8], chars: usize) -> usize {
596    let total = char_count(bytes);
597    if chars >= total { 0 } else { prefix_len(bytes, total - chars) }
598}
599
600#[cfg(test)]
601mod tests {
602    use super::*;
603    use std::io::Write;
604
605    fn file_with(bytes: &[u8]) -> (tempfile::NamedTempFile, std::fs::File, u64) {
606        let mut temp = tempfile::NamedTempFile::new().unwrap();
607        temp.write_all(bytes).unwrap();
608        let file = temp.reopen().unwrap();
609        (temp, file, bytes.len() as u64)
610    }
611
612    fn numbered(lines: usize) -> String {
613        (0..lines).map(|i| format!("{i:015}\n")).collect()
614    }
615
616    #[test]
617    fn an_offset_reads_bytes_from_the_middle() {
618        let text = numbered(327_680);
619        let (_temp, mut file, total) = file_with(text.as_bytes());
620        let slice = Slice { offset: Some(2_621_440), limit: Some(32), ..Slice::default() };
621        let read = read_slice(&mut file, total, &slice).unwrap();
622        assert_eq!(
623            read,
624            OutputRead {
625                text: format!("{:015}\n{:015}\n", 163_840, 163_841),
626                total_bytes: total,
627                range: (2_621_440, 2_621_472),
628                cut: false,
629            }
630        );
631    }
632
633    #[test]
634    fn the_default_is_the_last_characters_and_tail_lines_the_last_lines() {
635        let text = numbered(10_000);
636        let (_temp, mut file, total) = file_with(text.as_bytes());
637        let read = read_slice(&mut file, total, &Slice::default()).unwrap();
638        assert_eq!(read.text, text[text.len() - INLINE_OUTPUT_CHARS..]);
639        let lines = Slice { tail_lines: Some(2), ..Slice::default() };
640        let read = read_slice(&mut file, total, &lines).unwrap();
641        assert_eq!(read.text, format!("{:015}\n{:015}\n", 9_998, 9_999));
642        assert_eq!(read.range, (total - 32, total));
643    }
644
645    #[test]
646    fn a_pattern_returns_numbered_matching_lines() {
647        let (_temp, mut file, total) = file_with(b"ok\nerror[E0308]: mismatched\nok\nerror: x\n");
648        let slice =
649            Slice { pattern: Some(regex::Regex::new("^error").unwrap()), ..Slice::default() };
650        let read = read_slice(&mut file, total, &slice).unwrap();
651        assert_eq!(read.text, "2: error[E0308]: mismatched\n4: error: x\n");
652        assert!(!read.cut);
653    }
654
655    #[test]
656    fn a_range_inside_characters_moves_to_their_boundaries() {
657        let text = "€".repeat(10);
658        let (_temp, mut file, total) = file_with(text.as_bytes());
659        let slice = Slice { offset: Some(1), limit: Some(7), ..Slice::default() };
660        let read = read_slice(&mut file, total, &slice).unwrap();
661        // Bytes 1..8: the rest of the first `€` is skipped, the third is cut short.
662        assert_eq!((read.text.as_str(), read.range), ("€", (3, 6)));
663    }
664
665    #[test]
666    fn ids_are_numbers_and_never_reuse_an_earlier_file() {
667        let root = tempfile::tempdir().unwrap();
668        let outputs = ShellOutputs::new(root.path());
669        let first = outputs.allocate("app", "alice", "s1", "make").unwrap();
670        assert_eq!(first.id, "1");
671        let again = ShellOutputs::new(root.path());
672        assert_eq!(again.allocate("app", "alice", "s1", "make").unwrap().id, "2");
673        assert_eq!(again.allocate("app", "bob", "s1", "make").unwrap().id, "1");
674        assert!(ShellOutputs::path_of(Path::new("/x"), "../1").is_none());
675        let error = outputs.read(("app", "bob", "s2"), "1", &Slice::default()).unwrap_err();
676        assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
677    }
678
679    #[cfg(unix)]
680    #[test]
681    fn a_link_in_place_of_an_output_is_not_followed() {
682        let root = tempfile::tempdir().unwrap();
683        let outputs = ShellOutputs::new(root.path());
684        let dir = outputs.session_dir("app", "alice", "s1");
685        ShellOutputs::prepare(&dir).unwrap();
686        let secret = root.path().join("secret");
687        std::fs::write(&secret, "token").unwrap();
688        std::os::unix::fs::symlink(&secret, dir.join("7.log")).unwrap();
689        let error = outputs.read(("app", "alice", "s1"), "7", &Slice::default()).unwrap_err();
690        assert_eq!(error.kind(), std::io::ErrorKind::NotFound);
691    }
692}