artifactize-core 0.26.0

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
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
//! Bounded runtime evidence queries. Full captures stay on disk, never in a tool result.
use crate::{platform, store, types::RequestId};
use serde::{Deserialize, Serialize};
use std::{
    collections::VecDeque,
    ffi::OsStr,
    io::{self, BufRead, BufReader, Cursor, Read},
    path::Path,
};

/// Keep two streams, including JSON escaping and MCP's text mirror, below 64 KiB.
const STREAM_BYTES: usize = 10 * 1024;
/// One query is a diagnostic excerpt, not a replacement for the saved log.
const MAX_LINES: usize = 200;
/// A short default tail supplies diagnostic context without filling an agent context.
pub const DEFAULT_TAIL: usize = 50;
/// Bound one unusually long line independently of the stream page.
const LINE_BYTES: usize = 2048;

#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, clap::ValueEnum)]
#[serde(rename_all = "lowercase")]
pub enum Stream {
    Stdout,
    Stderr,
    #[default]
    Both,
}

#[derive(Debug, Clone, Default, Deserialize, clap::Args)]
#[serde(deny_unknown_fields)]
pub struct LogOptions {
    /// Select stdout, stderr, or both (default).
    #[arg(long, value_enum, default_value = "both")]
    #[serde(default)]
    pub stream: Stream,
    /// Last N matching lines; defaults to 50 when no range is given (maximum 200).
    #[arg(long, conflicts_with_all = ["start", "end"])]
    pub tail: Option<usize>,
    /// First line, inclusive and one-based, in the original retained stream.
    #[arg(long, conflicts_with = "tail")]
    pub start: Option<usize>,
    /// Last line, inclusive and one-based.
    #[arg(long, conflicts_with = "tail")]
    pub end: Option<usize>,
    /// Literal, case-sensitive search; line numbers remain original.
    #[arg(long)]
    pub search: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Evidence {
    Complete,
    Partial,
    SavedAudit,
    Missing,
    NotRuntime,
}
#[derive(Debug, Serialize)]
pub struct Line {
    pub number: usize,
    pub text: String,
    pub clipped: bool,
}
#[derive(Debug, Serialize)]
pub struct LogExcerpt {
    pub stream: Stream,
    pub evidence: Evidence,
    pub note: String,
    pub lines: Vec<Line>,
    /// Continue a forward range/search at this original line; null for a tail query.
    pub next_start: Option<usize>,
}
#[derive(Debug, Serialize)]
pub struct Logs {
    pub request: RequestId,
    pub producer: RequestId,
    pub streams: Vec<LogExcerpt>,
}

#[derive(Debug, Clone)]
pub struct LogQuery {
    stream: Stream,
    selection: Selection,
    search: Option<String>,
}

#[derive(Debug, Clone)]
enum Selection {
    Tail(usize),
    Range { start: usize, end: Option<usize> },
}

impl Default for LogQuery {
    fn default() -> Self {
        Self {
            stream: Stream::Both,
            selection: Selection::Tail(DEFAULT_TAIL),
            search: None,
        }
    }
}

pub async fn logs(state: &Path, id: &RequestId, query: LogQuery) -> Result<Logs, String> {
    let view = store::read_request_id(state, id).await?;
    // Reused/joined results point at the execution's original request, not this Run's output.
    let producer = view
        .request
        .provenance
        .as_ref()
        .map_or(id, |p| &p.request_id)
        .clone();
    let source = if view.request.origin.is_some() {
        None
    } else if producer == *id {
        Some(view.clone())
    } else {
        // Remote mirrors need not carry the original local request.
        store::read_request_id(state, &producer).await.ok()
    };
    let runtime = matches!(
        view.request.result(),
        Some(store::ExecutionResult::Runtime(_))
    ) || matches!(
        view.request.profile,
        crate::config::StoredProfile::Runtime { .. }
    );
    let state = state.to_path_buf();
    let id = id.clone();
    crate::task::joined(
        tokio::task::spawn_blocking(move || {
            let streams = match query.stream {
                Stream::Both => vec![Stream::Stdout, Stream::Stderr],
                stream => vec![stream],
            }
            .into_iter()
            .map(|stream| excerpt(&state, source.as_ref(), &view, runtime, stream, &query))
            .collect::<Result<_, _>>()?;
            Ok(Logs {
                request: id,
                producer,
                streams,
            })
        })
        .await,
    )
    .map_err(|e| e.to_string())?
}

impl TryFrom<LogOptions> for LogQuery {
    type Error = String;

    fn try_from(query: LogOptions) -> Result<Self, String> {
        if query.tail.is_some_and(|n| n == 0 || n > MAX_LINES)
            || query.start == Some(0)
            || query.end == Some(0)
            || query.start.zip(query.end).is_some_and(|(a, b)| a > b)
            || (query.tail.is_some() && (query.start.is_some() || query.end.is_some()))
            || query
                .search
                .as_ref()
                .is_some_and(|s| s.is_empty() || s.len() > LINE_BYTES)
        {
            return Err(format!(
                "Use positive line numbers, tail 1–{MAX_LINES}, an ordered range, and a nonempty search up to {LINE_BYTES} bytes; tail and range are exclusive."
            ));
        }
        let selection = match (query.tail, query.start, query.end) {
            (Some(tail), _, _) => Selection::Tail(tail),
            (None, None, None) => Selection::Tail(DEFAULT_TAIL),
            (None, start, end) => Selection::Range {
                start: start.unwrap_or(1),
                end,
            },
        };
        Ok(Self {
            stream: query.stream,
            search: query.search,
            selection,
        })
    }
}

fn excerpt(
    state: &Path,
    source: Option<&store::RequestView>,
    view: &store::RequestView,
    runtime: bool,
    stream: Stream,
    query: &LogQuery,
) -> Result<LogExcerpt, String> {
    let absent = |evidence, note: &str| LogExcerpt {
        stream,
        evidence,
        note: note.into(),
        lines: vec![],
        next_start: None,
    };
    if !runtime {
        return Ok(absent(
            Evidence::NotRuntime,
            "No runtime stdout/stderr; inspect request/session evidence.",
        ));
    }
    let name = match stream {
        Stream::Stdout => "stdout",
        Stream::Stderr => "stderr",
        Stream::Both => unreachable!(),
    };
    if let Some(directory) = source.and_then(|v| v.request.run_dir.as_ref()) {
        let path = directory.join(format!("runtime.{name}"));
        // Saved paths are not authority to read outside this state's Run output.
        let opened = match platform::paths::open_regular_beneath(&state.join("runs"), &path) {
            Ok(opened) => Some(opened),
            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
            Err(error) => return Err(error.to_string()),
        };
        if let Some((directory, file)) = opened {
            let marker = format!("runtime.{name}.complete");
            let complete = matches!(
                platform::entry_kind(&directory, OsStr::new(&marker)),
                Ok(platform::FileKind::File)
            );
            // A live producer may keep appending: query only the bytes present at open.
            let length = file.metadata().map_err(|e| e.to_string())?.len();
            let (lines, next_start) = select(BufReader::new(file.take(length)), query)?;
            return Ok(LogExcerpt {
                stream,
                evidence: if complete {
                    Evidence::Complete
                } else {
                    Evidence::Partial
                },
                note: if complete {
                    "Full local stream retained until Run output is pruned."
                } else {
                    "Capture is active or ended without confirmed EOF; retained bytes only."
                }
                .into(),
                lines,
                next_start,
            });
        }
    }
    let result = view
        .request
        .result()
        .or_else(|| source.and_then(|v| v.request.result()));
    if let Some(store::ExecutionResult::Runtime(result)) = result {
        let audit = match stream {
            Stream::Stdout => result.stdout.value(),
            _ => result.stderr.value(),
        };
        if let Some(text) = audit {
            let (lines, next_start) = select(Cursor::new(text.as_bytes()), query)?;
            let note = match result.truncated.value() {
                Some(false) => {
                    "Full capture unavailable (older, remote or pruned); saved cleaned audit reports no truncation."
                }
                _ => {
                    "Full capture unavailable (older, remote or pruned); audit may contain only the first 128 KiB. Missing tail cannot be recovered."
                }
            };
            return Ok(LogExcerpt {
                stream,
                evidence: Evidence::SavedAudit,
                note: note.into(),
                lines,
                next_start,
            });
        }
    }
    Ok(absent(
        Evidence::Missing,
        "No retained stream or saved audit: not started, remote, older or pruned evidence.",
    ))
}

/// Scan bounded chunks even for newline-free output. Search overlaps chunks so a
/// literal crossing a buffer boundary is found without retaining the entire line.
fn select(
    mut reader: impl BufRead,
    query: &LogQuery,
) -> Result<(Vec<Line>, Option<usize>), String> {
    let (tail, start, end) = match query.selection {
        Selection::Tail(tail) => (Some(tail), 1, None),
        Selection::Range { start, end } => (None, start, end),
    };
    let mut selected = VecDeque::new();
    let mut bytes = 0;
    let mut number = 0;
    loop {
        let mut text = Vec::new();
        let mut suffix = VecDeque::new();
        let mut overlap = Vec::new();
        let mut length = 0;
        let mut matched = query.search.is_none();
        loop {
            let chunk = reader.fill_buf().map_err(|e| e.to_string())?;
            if chunk.is_empty() {
                break;
            }
            let end = chunk.iter().position(|&b| b == b'\n').map(|n| n + 1);
            let chunk = &chunk[..end.unwrap_or(chunk.len())];
            length += chunk.len();
            text.extend_from_slice(
                &chunk[..chunk.len().min(LINE_BYTES.saturating_sub(text.len()))],
            );
            suffix.extend(chunk.iter().copied());
            suffix.drain(..suffix.len().saturating_sub(LINE_BYTES / 2));
            if let Some(search) = &query.search {
                overlap.extend_from_slice(chunk);
                matched |= overlap
                    .windows(search.len())
                    .any(|w| w == search.as_bytes());
                let keep = overlap.len().saturating_sub(search.len().saturating_sub(1));
                overlap.drain(..keep);
            }
            let consumed = chunk.len();
            reader.consume(consumed);
            if end.is_some() {
                break;
            }
        }
        if length == 0 {
            break;
        }
        number += 1;
        if end.is_some_and(|end| number > end) {
            break;
        }
        if number < start || !matched {
            continue;
        }
        let text = if length > LINE_BYTES {
            text.truncate(LINE_BYTES / 2);
            text.extend_from_slice(b"\n[... line clipped ...]\n");
            text.extend(suffix);
            text
        } else {
            text
        };
        let cleaned = crate::runtime::clean_output(&text);
        let text =
            crate::platform::output_text(crate::platform::output_line(&cleaned)).into_owned();
        let line = Line {
            number,
            text,
            clipped: length > LINE_BYTES,
        };
        let size = serde_json::to_vec(&line).map_err(|e| e.to_string())?.len();
        if tail.is_none() && (selected.len() == MAX_LINES || bytes + size > STREAM_BYTES) {
            return Ok((selected.into(), Some(number)));
        }
        bytes += size;
        selected.push_back(line);
        while selected.len() > tail.unwrap_or(MAX_LINES) || bytes > STREAM_BYTES {
            let removed = selected.pop_front().expect("nonempty page");
            bytes -= serde_json::to_vec(&removed).expect("line serializes").len();
        }
    }
    Ok((selected.into(), None))
}

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

    #[test]
    fn runtime_evidence_requires_a_regular_completion_marker() {
        let state = crate::test_os::tempdir();
        let run = state.path().join("runs/run-1");
        fs::create_dir_all(&run).unwrap();
        let capture = run.join("runtime.stdout");
        fs::write(&capture, "output\n").unwrap();
        let marker = run.join("runtime.stdout.complete");
        let view = crate::test_request::request(
            "app/check",
            "RUNNING",
            serde_json::json!({"runDir": platform::path_text(&run)}),
        );
        let inspect = || {
            excerpt(
                state.path(),
                Some(&view),
                &view,
                true,
                Stream::Stdout,
                &LogQuery::default(),
            )
        };
        let evidence = || {
            let excerpt = inspect().unwrap();
            assert_eq!(excerpt.lines[0].text, "output");
            excerpt.evidence
        };
        assert!(matches!(evidence(), Evidence::Partial));
        let outside = state.path().join("outside");
        fs::write(&outside, "").unwrap();
        crate::test_os::file_link(&outside, &marker);
        assert!(matches!(evidence(), Evidence::Partial));
        crate::test_os::remove_file_link(&marker);
        fs::write(marker, "").unwrap();
        assert!(matches!(evidence(), Evidence::Complete));

        fs::remove_file(&capture).unwrap();
        assert!(matches!(inspect().unwrap().evidence, Evidence::Missing));
        crate::test_os::file_link(&outside, &capture);
        assert!(
            inspect().is_err(),
            "a linked capture must not expose its target"
        );
    }
}