apoc 0.9.1

Agentic process control for LLMs
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
//! Fail-closed managed-run log storage.

use std::io::{Read, Seek};
use std::path::Path;

const REDACTION_MARKER: &str = "redaction.required";

pub(crate) fn require_redaction(directory: &Path) -> Result<(), String> {
    std::fs::write(directory.join(REDACTION_MARKER), []).map_err(|error| error.to_string())
}

pub(crate) fn redaction_pending(path: Option<&str>) -> bool {
    path.and_then(|path| Path::new(path).parent())
        .is_some_and(|directory| directory.join(REDACTION_MARKER).exists())
}

pub(crate) fn finalize_redaction(paths: &[&Path], secrets: &[&String]) -> Result<(), String> {
    let Some(marker) = paths
        .first()
        .and_then(|path| path.parent())
        .map(|directory| directory.join(REDACTION_MARKER))
    else {
        return Ok(());
    };
    if !marker.exists() {
        return Ok(());
    }
    if paths.iter().all(|path| {
        path.metadata()
            .map(|metadata| metadata.is_file() && metadata.len() == 0)
            .unwrap_or_else(|_| !path.exists())
    }) {
        std::fs::remove_file(marker).map_err(|error| error.to_string())?;
        return Ok(());
    }

    let result = if secrets.iter().all(|secret| secret.is_empty()) {
        rewrite_or_remove(paths, |_| {
            Err("resolved secrets are unavailable after recovery".to_string())
        })
    } else {
        rewrite_or_remove(paths, |path| redact(path, secrets))
    };
    if result.is_ok() || paths.iter().all(|path| !path.exists()) {
        std::fs::remove_file(marker).map_err(|error| error.to_string())?;
    }
    result
}

pub(crate) fn read_tail(path: Option<&str>, bytes: usize) -> Result<(String, bool), String> {
    let Some(path) = path else {
        return Ok((String::new(), false));
    };
    let mut file = match std::fs::File::open(path) {
        Ok(file) => file,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            return Ok((String::new(), false));
        }
        Err(error) => return Err(error.to_string()),
    };
    let length = file.metadata().map_err(|error| error.to_string())?.len();
    file.seek(std::io::SeekFrom::Start(
        length.saturating_sub(bytes as u64),
    ))
    .map_err(|error| error.to_string())?;
    let mut value = Vec::new();
    file.read_to_end(&mut value)
        .map_err(|error| error.to_string())?;
    Ok((
        String::from_utf8_lossy(&value).into_owned(),
        length > bytes as u64,
    ))
}

/// Returns numbered lines matching a pattern, with bounded surrounding context.
///
/// Matching runs where the log lives so an oversized file is never shipped whole to a caller
/// that only wants a handful of lines.
pub(crate) fn read_matches(
    path: Option<&str>,
    stream: &str,
    pattern: &regex::Regex,
    context: usize,
    max_matches: usize,
) -> Result<(Vec<crate::run::LogLine>, usize, usize), String> {
    let (text, total) = read_all(path)?;
    let lines = text.lines().collect::<Vec<_>>();
    let mut selected = std::collections::BTreeSet::new();
    let mut matches = 0;
    for (index, line) in lines.iter().enumerate() {
        if !pattern.is_match(line) {
            continue;
        }
        matches += 1;
        if matches > max_matches {
            continue;
        }
        let start = index.saturating_sub(context);
        let end = (index + context).min(lines.len().saturating_sub(1));
        for number in start..=end {
            selected.insert(number);
        }
    }
    Ok((
        selected
            .into_iter()
            .map(|index| crate::run::LogLine {
                number: index + 1,
                stream: stream.to_string(),
                text: lines[index].to_string(),
            })
            .collect(),
        matches,
        total,
    ))
}

/// Returns one inclusive, one-based line range.
pub(crate) fn read_lines(
    path: Option<&str>,
    stream: &str,
    start: usize,
    end: usize,
) -> Result<(Vec<crate::run::LogLine>, usize), String> {
    let (text, total) = read_all(path)?;
    let lines = text
        .lines()
        .enumerate()
        .filter(|(index, _)| {
            let number = index + 1;
            number >= start && number <= end
        })
        .map(|(index, line)| crate::run::LogLine {
            number: index + 1,
            stream: stream.to_string(),
            text: line.to_string(),
        })
        .collect();
    Ok((lines, total))
}

/// Returns the whole log and its line count, or empty when it does not exist.
fn read_all(path: Option<&str>) -> Result<(String, usize), String> {
    let Some(path) = path else {
        return Ok((String::new(), 0));
    };
    let bytes = match std::fs::read(path) {
        Ok(bytes) => bytes,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
            return Ok((String::new(), 0));
        }
        Err(error) => return Err(error.to_string()),
    };
    let text = String::from_utf8_lossy(&bytes).into_owned();
    let total = text.lines().count();
    Ok((text, total))
}

fn redact(path: &Path, secrets: &[&String]) -> Result<(), String> {
    let mut bytes = match std::fs::read(path) {
        Ok(bytes) => bytes,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(error) => return Err(error.to_string()),
    };
    for secret in secrets {
        if !secret.is_empty() {
            bytes = replace_bytes(&bytes, secret.as_bytes(), b"[REDACTED]");
        }
    }
    std::fs::write(path, bytes).map_err(|error| error.to_string())
}

fn replace_bytes(input: &[u8], pattern: &[u8], replacement: &[u8]) -> Vec<u8> {
    if pattern.is_empty() {
        return input.to_vec();
    }
    let mut output = Vec::with_capacity(input.len());
    let mut remaining = input;
    while let Some(index) = remaining
        .windows(pattern.len())
        .position(|window| window == pattern)
    {
        output.extend_from_slice(&remaining[..index]);
        output.extend_from_slice(replacement);
        remaining = &remaining[index + pattern.len()..];
    }
    output.extend_from_slice(remaining);
    output
}

fn rewrite_or_remove(
    paths: &[&Path],
    mut rewrite: impl FnMut(&Path) -> Result<(), String>,
) -> Result<(), String> {
    let errors = paths
        .iter()
        .filter_map(|path| {
            rewrite(path)
                .err()
                .map(|error| format!("{}: {error}", path.display()))
        })
        .collect::<Vec<_>>();
    if errors.is_empty() {
        return Ok(());
    }

    let cleanup_errors = paths
        .iter()
        .filter_map(|path| match std::fs::remove_file(path) {
            Ok(()) => None,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
            Err(error) => Some(format!("{}: {error}", path.display())),
        })
        .collect::<Vec<_>>();
    if cleanup_errors.is_empty() {
        Err(errors.join("; "))
    } else {
        Err(format!(
            "{}; cleanup failed: {}",
            errors.join("; "),
            cleanup_errors.join("; ")
        ))
    }
}

#[cfg(test)]
mod tests {
    use tempfile::tempdir;

    use super::*;

    #[test]
    fn sanitizes_every_log() {
        let directory = tempdir().unwrap();
        let stdout = directory.path().join("stdout.log");
        let stderr = directory.path().join("stderr.log");
        let secret = "synthetic-secret".to_string();
        std::fs::write(&stdout, format!("before {secret} after")).unwrap();
        std::fs::write(&stderr, format!("{secret} twice {secret}")).unwrap();

        require_redaction(directory.path()).unwrap();
        finalize_redaction(&[&stdout, &stderr], &[&secret]).unwrap();

        assert_eq!(
            std::fs::read_to_string(stdout).unwrap(),
            "before [REDACTED] after"
        );
        assert_eq!(
            std::fs::read_to_string(stderr).unwrap(),
            "[REDACTED] twice [REDACTED]"
        );
        assert!(!directory.path().join(REDACTION_MARKER).exists());
    }

    #[test]
    fn redaction_preserves_non_utf8_bytes() {
        let directory = tempdir().unwrap();
        let stdout = directory.path().join("stdout.log");
        let stderr = directory.path().join("stderr.log");
        let secret = "synthetic-secret".to_string();
        let mut bytes = vec![0xff];
        bytes.extend_from_slice(secret.as_bytes());
        bytes.push(0xfe);
        std::fs::write(&stdout, bytes).unwrap();
        std::fs::write(&stderr, []).unwrap();

        require_redaction(directory.path()).unwrap();
        finalize_redaction(&[&stdout, &stderr], &[&secret]).unwrap();

        assert_eq!(
            std::fs::read(stdout).unwrap(),
            [vec![0xff], b"[REDACTED]".to_vec(), vec![0xfe]].concat()
        );
    }

    #[test]
    fn missing_logs_complete_redaction() {
        let directory = tempdir().unwrap();
        let stdout = directory.path().join("stdout.log");
        let stderr = directory.path().join("stderr.log");
        require_redaction(directory.path()).unwrap();

        finalize_redaction(&[&stdout, &stderr], &[]).unwrap();

        assert!(!directory.path().join(REDACTION_MARKER).exists());
    }

    #[test]
    fn rewrite_failure_removes_every_log() {
        let directory = tempdir().unwrap();
        let stdout = directory.path().join("stdout.log");
        let stderr = directory.path().join("stderr.log");
        std::fs::write(&stdout, "secret").unwrap();
        std::fs::write(&stderr, "secret").unwrap();

        let error = rewrite_or_remove(&[&stdout, &stderr], |_| Err("synthetic failure".into()))
            .unwrap_err();

        assert!(error.contains("synthetic failure"));
        assert!(!stdout.exists());
        assert!(!stderr.exists());
    }

    #[test]
    fn recovery_without_secret_values_removes_every_log() {
        let directory = tempdir().unwrap();
        let stdout = directory.path().join("stdout.log");
        let stderr = directory.path().join("stderr.log");
        std::fs::write(&stdout, "secret").unwrap();
        std::fs::write(&stderr, "secret").unwrap();
        require_redaction(directory.path()).unwrap();

        let error = finalize_redaction(&[&stdout, &stderr], &[]).unwrap_err();

        assert!(error.contains("unavailable after recovery"));
        assert!(!stdout.exists());
        assert!(!stderr.exists());
        assert!(!directory.path().join(REDACTION_MARKER).exists());
    }

    #[test]
    fn addressed_reads_cover_empty_missing_bounded_and_error_paths() {
        let directory = tempdir().unwrap();
        let missing = directory.path().join("missing.log");
        let path = directory.path().join("output.log");
        std::fs::write(&path, "before\nhit one\nmiddle\nhit two\nafter\n").unwrap();

        assert_eq!(read_tail(None, 8).unwrap(), (String::new(), false));
        assert_eq!(
            read_tail(Some(missing.to_str().unwrap()), 8).unwrap(),
            (String::new(), false)
        );
        let (tail, truncated) = read_tail(Some(path.to_str().unwrap()), 6).unwrap();
        assert_eq!(tail, "after\n");
        assert!(truncated);

        let pattern = regex::Regex::new("hit").unwrap();
        let (matches, total_matches, total_lines) =
            read_matches(Some(path.to_str().unwrap()), "stdout", &pattern, 1, 1).unwrap();
        assert_eq!(total_matches, 2);
        assert_eq!(total_lines, 5);
        assert_eq!(matches.len(), 3);
        assert_eq!(matches[0].number, 1);
        assert_eq!(matches[2].number, 3);

        let (lines, total) = read_lines(Some(path.to_str().unwrap()), "stderr", 2, 4).unwrap();
        assert_eq!(total, 5);
        assert_eq!(lines.len(), 3);
        assert_eq!(lines[0].stream, "stderr");
        assert_eq!(lines[2].number, 4);
        assert_eq!(read_lines(None, "stdout", 1, 2).unwrap().1, 0);
        assert_eq!(
            read_lines(Some(missing.to_str().unwrap()), "stdout", 1, 2)
                .unwrap()
                .1,
            0
        );

        assert!(read_tail(Some(directory.path().to_str().unwrap()), 8).is_err());
        assert!(read_lines(Some(directory.path().to_str().unwrap()), "stdout", 1, 2).is_err());
    }

    #[test]
    fn redaction_and_cleanup_helpers_cover_absence_and_composed_failures() {
        let directory = tempdir().unwrap();
        let missing = directory.path().join("missing.log");
        let output = directory.path().join("output.log");
        let empty = String::new();

        assert!(!redaction_pending(None));
        assert!(finalize_redaction(&[], &[]).is_ok());
        assert!(require_redaction(&directory.path().join("missing-directory")).is_err());
        assert!(redact(&missing, &[]).is_ok());
        assert!(redact(directory.path(), &[]).is_err());

        std::fs::write(&output, "unchanged").unwrap();
        redact(&output, &[&empty]).unwrap();
        assert_eq!(std::fs::read_to_string(&output).unwrap(), "unchanged");
        assert!(rewrite_or_remove(&[&output], |_| Ok(())).is_ok());

        let missing_error =
            rewrite_or_remove(&[&missing], |_| Err("rewrite failed".to_string())).unwrap_err();
        assert!(missing_error.contains("rewrite failed"));
        assert!(!missing_error.contains("cleanup failed"));

        let cleanup_error =
            rewrite_or_remove(&[directory.path()], |_| Err("rewrite failed".to_string()))
                .unwrap_err();
        assert!(cleanup_error.contains("rewrite failed"));
        assert!(cleanup_error.contains("cleanup failed"));

        let missing_marker_directory = tempdir().unwrap();
        std::fs::create_dir(missing_marker_directory.path().join(REDACTION_MARKER)).unwrap();
        let absent_log = missing_marker_directory.path().join("absent.log");
        assert!(finalize_redaction(&[&absent_log], &[]).is_err());

        let existing_marker_directory = tempdir().unwrap();
        std::fs::create_dir(existing_marker_directory.path().join(REDACTION_MARKER)).unwrap();
        let existing_log = existing_marker_directory.path().join("output.log");
        std::fs::write(&existing_log, "safe").unwrap();
        assert!(finalize_redaction(&[&existing_log], &[&empty]).is_err());

        let loop_path = directory.path().join("loop");
        std::os::unix::fs::symlink(&loop_path, &loop_path).unwrap();
        assert!(read_tail(Some(loop_path.to_str().unwrap()), 8).is_err());

        let retained = tempdir().unwrap();
        require_redaction(retained.path()).unwrap();
        let directory_log = retained.path().join("output.log");
        std::fs::create_dir(&directory_log).unwrap();
        let error = finalize_redaction(&[&directory_log], &[]).unwrap_err();
        assert!(error.contains("cleanup failed"));
        assert!(directory_log.exists());
        assert!(retained.path().join(REDACTION_MARKER).exists());
    }
}