artifactize-core 0.33.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
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
use std::{
    path::{Path, PathBuf},
    time::Duration,
};

use rusqlite::OpenFlags;
use serde::Serialize;
use time::OffsetDateTime;

use super::{DATABASE, STATE_SCHEMA_VERSION, receipts::check_files};
use crate::{platform, process, workspace};

#[derive(Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PruneReport {
    #[serde(serialize_with = "crate::platform::serialize_paths")]
    pub removed: Vec<PathBuf>,
    #[serde(serialize_with = "crate::platform::serialize_paths")]
    pub would_remove: Vec<PathBuf>,
    pub skipped_runs: Vec<crate::types::RunId>,
    /// Agent sessions the size-bound collection deleted, oldest first.
    pub removed_sessions: Vec<crate::types::SessionId>,
    /// With `--dry-run`, the Agent sessions it would delete.
    pub would_remove_sessions: Vec<crate::types::SessionId>,
}

// `--older-than` units in seconds, each built from the one below it. A day is a fixed
// 24 hours because pruning compares elapsed time, not calendar dates.
/// 60 seconds in a minute.
const SECONDS_PER_MINUTE: u64 = 60;
/// 60 minutes in an hour.
const SECONDS_PER_HOUR: u64 = 60 * SECONDS_PER_MINUTE;
/// 24 hours in a day.
const SECONDS_PER_DAY: u64 = 24 * SECONDS_PER_HOUR;
/// 7 days in a week.
const SECONDS_PER_WEEK: u64 = 7 * SECONDS_PER_DAY;

pub fn parse_duration(value: &str) -> Result<Duration, String> {
    let error = || "Use a whole-number duration with s, m, h, d or w (for example 7d).".to_owned();
    let split = value
        .find(|c: char| !c.is_ascii_digit())
        .ok_or_else(error)?;
    let multiplier = match &value[split..] {
        "s" => 1,
        "m" => SECONDS_PER_MINUTE,
        "h" => SECONDS_PER_HOUR,
        "d" => SECONDS_PER_DAY,
        "w" => SECONDS_PER_WEEK,
        _ => return Err(error()),
    };
    let seconds = value[..split]
        .parse::<u64>()
        .ok()
        .and_then(|amount| amount.checked_mul(multiplier))
        // `time::Duration` holds whole seconds as an `i64`; the cutoff converts into it.
        .filter(|seconds| *seconds <= i64::MAX as u64)
        .ok_or_else(error)?;
    Ok(Duration::from_secs(seconds))
}

/// Prune only known scratch directories. Terminal Runs never reacquire an owner.
pub fn prune(
    state: &Path,
    repo: Option<&Path>,
    older_than: Option<Duration>,
    dry_run: bool,
) -> Result<PruneReport, String> {
    // Canonical like the repositories it is compared with: on Windows, a state path typed in
    // another case, or with 8.3 short names, would otherwise slip past `outside_workspace`.
    // System aliases such as macOS /tmp are OS-owned boundaries, not operator-made links.
    let state = platform::resolve_system_aliases(state).map_err(|e| e.to_string())?;
    let state = workspace::canonical_target(&real_path(&state)?).map_err(|e| e.to_string())?;
    let mut report = PruneReport::default();
    let mut repositories = Vec::new();
    if let Some(repo) = repo {
        repositories.push(workspace::canonical_target(repo).map_err(|e| e.to_string())?);
    }
    for repo in &repositories {
        workspace::outside_workspace(repo, &state).map_err(|e| e.to_string())?;
    }
    check_files(&state)?;
    // Saved Agent conversations past their size bound (limits.json agentSessions).
    let bounds = crate::limits::Limits::read(&state)?.agent_sessions();
    let sessions = crate::agent::session::collect(&state, bounds, dry_run)?;
    if dry_run {
        report.would_remove_sessions = sessions.removed.into_iter().collect();
    } else {
        report.removed_sessions = sessions.removed.into_iter().collect();
    }
    if !state
        .join(DATABASE)
        .try_exists()
        .map_err(|e| e.to_string())?
    {
        return Ok(report);
    }
    let mut db = rusqlite::Connection::open_with_flags(
        state.join(DATABASE),
        OpenFlags::SQLITE_OPEN_READ_ONLY,
    )
    .map_err(|e| e.to_string())?;
    super::wait_when_busy(&db).map_err(|e| e.to_string())?;
    let cutoff = older_than
        .map(|age| {
            time::Duration::try_from(age)
                .ok()
                .and_then(|age| OffsetDateTime::now_utc().checked_sub(age))
                .ok_or_else(|| "Prune duration is too large.".to_owned())
        })
        .transpose()?;
    // List existing `<state>/runs/` directory entries BEFORE opening the read snapshot:
    // every Run commits its `runs` row before creating its run directory, so any `run-*`
    // directory listed here that is absent from `known_runs` is genuinely orphaned.
    let runs_dir = state.join("runs");
    let existing_run_dirs = if directory(&runs_dir)? {
        list_run_dir_ids(&runs_dir)?
    } else {
        Vec::new()
    };
    // Keep the read snapshot strictly bounded to indexed SQL queries — never run OS
    // path canonicalization, JSON decoding, or process-liveness checks while pinning a WAL
    // read snapshot.
    struct RawRunRow {
        id: crate::types::RunId,
        repo_text: String,
        data: String,
        status: crate::types::RunStatus,
        requests_terminal: bool,
        has_active_execution: bool,
        execution_owners: Vec<process::ChildIdentity>,
    }
    let (raw_rows, known_runs) = {
        let transaction = db.transaction().map_err(|e| e.to_string())?;
        let version: u32 = transaction
            .pragma_query_value(None, "user_version", |row| row.get(0))
            .map_err(|e| e.to_string())?;
        if version != STATE_SCHEMA_VERSION {
            return Err(super::schema_error(version));
        }
        // One indexed scan of currently active executions (RUNNING / WAITING_HUMAN) replaces
        // the per-Run full-table scan over `executions.data`.
        let mut active_runs = std::collections::BTreeSet::<crate::types::RunId>::new();
        {
            let mut statement = transaction
                .prepare(
                    "SELECT json_extract(data,'$.provenance.runId') FROM executions WHERE status IN ('RUNNING','WAITING_HUMAN') AND json_valid(data)",
                )
                .map_err(|e| e.to_string())?;
            let rows = statement
                .query_map([], |row| row.get::<_, Option<String>>(0))
                .map_err(|e| e.to_string())?;
            for row in rows {
                if let Some(id) = row
                    .map_err(|e| e.to_string())?
                    .and_then(|text| text.parse().ok())
                {
                    active_runs.insert(id);
                }
            }
        }
        let runs = {
            let mut statement = transaction
                .prepare("SELECT id,repo,data,status FROM runs ORDER BY id")
                .map_err(|e| e.to_string())?;
            statement
                .query_map([], |row| {
                    Ok((
                        row.get::<_, crate::types::RunId>(0)?,
                        row.get::<_, String>(1)?,
                        row.get::<_, String>(2)?,
                        row.get::<_, crate::types::RunStatus>(3)?,
                    ))
                })
                .map_err(|e| e.to_string())?
                .collect::<Result<Vec<_>, _>>()
                .map_err(|e| e.to_string())?
        };
        let mut terminal_check = transaction
            .prepare(
                "SELECT NOT EXISTS(SELECT 1 FROM requests WHERE run_id=? AND status NOT IN ('GREEN','RED','ERROR','INCOMPLETE','BLOCKED','BUDGET_EXHAUSTED'))",
            )
            .map_err(|e| e.to_string())?;
        let mut execution_owners_query = transaction
            .prepare(
                "SELECT DISTINCT e.owner_pid,e.owner_start_time,e.status
                 FROM requests q JOIN executions e ON e.id=q.execution_id
                 WHERE q.run_id=? AND q.execution_id IS NOT NULL",
            )
            .map_err(|e| e.to_string())?;
        let mut known_runs = std::collections::BTreeSet::new();
        let mut raw_rows = Vec::with_capacity(runs.len());
        for (id, repo_text, data, status) in runs {
            known_runs.insert(id.clone());
            let mut has_active_execution = active_runs.contains(&id);
            let status_terminal = matches!(
                status,
                crate::types::RunStatus::Green
                    | crate::types::RunStatus::Red
                    | crate::types::RunStatus::Error
                    | crate::types::RunStatus::Incomplete
            );
            let requests_terminal = if status_terminal {
                terminal_check
                    .query_row([&id], |row| row.get(0))
                    .map_err(|e| e.to_string())?
            } else {
                false
            };
            let mut execution_owners = Vec::new();
            if status_terminal && requests_terminal && !has_active_execution {
                let rows = execution_owners_query
                    .query_map([&id], |row| {
                        let pid: u32 = row.get(0)?;
                        let start_time = row.get::<_, i64>(1)? as u64;
                        let owner =
                            std::num::NonZeroU32::new(pid).map(|pid| process::ChildIdentity {
                                pid: process::ProcessId::from(pid),
                                start_time,
                            });
                        Ok((owner, row.get::<_, crate::types::ExecutionStatus>(2)?))
                    })
                    .map_err(|e| e.to_string())?;
                for row in rows {
                    let (owner, execution_status) = row.map_err(|e| e.to_string())?;
                    if !matches!(
                        execution_status,
                        crate::types::ExecutionStatus::Green
                            | crate::types::ExecutionStatus::Red
                            | crate::types::ExecutionStatus::Error
                    ) {
                        has_active_execution = true;
                    }
                    if let Some(owner) = owner {
                        execution_owners.push(owner);
                    }
                }
            }
            raw_rows.push(RawRunRow {
                id,
                repo_text,
                data,
                status,
                requests_terminal,
                has_active_execution,
                execution_owners,
            });
        }
        drop(terminal_check);
        drop(execution_owners_query);
        transaction.commit().map_err(|e| e.to_string())?;
        (raw_rows, known_runs)
    };
    drop(db);

    let mut eligible = Vec::new();
    // Deduplicate OS process-liveness probes across Runs that shared an owner process.
    let mut alive_cache = std::collections::BTreeMap::<(u32, u64), bool>::new();
    for row in raw_rows {
        let repo =
            artifactize_tools::files::path_from_text(&row.repo_text).map_err(|e| e.to_string())?;
        let repo = workspace::canonical_target(&repo).map_err(|e| e.to_string())?;
        workspace::outside_workspace(&repo, &state).map_err(|e| e.to_string())?;
        repositories.push(repo);
        let Some(run) = super::unreadable::evidence::<super::Run>("run", &row.data) else {
            report.skipped_runs.push(row.id);
            continue;
        };
        let finished = run.completed_at().map(crate::types::Timestamp::time);
        let mut owners = row.execution_owners;
        if let Some(control) = &run.control {
            match control.worker {
                crate::runs::Worker::Starting { launcher } => owners.push(launcher),
                crate::runs::Worker::Admitted { owner } => owners.push(owner),
                crate::runs::Worker::Legacy => {}
            }
            owners.extend(control.supervisor);
        }
        let mut owned = row.has_active_execution;
        if !owned
            && row.requests_terminal
            && finished.is_some_and(|date| cutoff.is_none_or(|cutoff| date <= cutoff))
        {
            for owner in owners {
                let key = (owner.pid.get(), owner.start_time);
                let alive = match alive_cache.get(&key) {
                    Some(&alive) => alive,
                    None => {
                        let alive = process::is_alive(Some(owner)).map_err(|e| e.to_string())?;
                        alive_cache.insert(key, alive);
                        alive
                    }
                };
                if alive {
                    owned = true;
                    break;
                }
            }
        }
        if !eligible_to_prune(row.status, finished, cutoff, row.requests_terminal, owned) {
            report.skipped_runs.push(row.id);
        } else {
            eligible.push(row.id);
        }
    }

    if !directory(&runs_dir)? {
        return Ok(report);
    }
    let mut targets = Vec::new();
    for id in eligible {
        let path = runs_dir.join(id.as_str());
        if directory(&path)? {
            collect(&path, &mut targets)?;
        }
    }
    // Also prune orphaned `<state>/runs/<id>` trees whose Run row was removed by retention.
    for id in existing_run_dirs {
        if known_runs.contains(&id) {
            continue;
        }
        let path = runs_dir.join(id.as_str());
        if !directory(&path)? {
            continue;
        }
        if let Some(cutoff) = cutoff {
            let modified = std::fs::symlink_metadata(&path)
                .ok()
                .and_then(|meta| meta.modified().ok())
                .map(OffsetDateTime::from);
            if !modified.is_some_and(|time| time <= cutoff) {
                continue;
            }
        }
        targets.push(path);
    }
    // Validate the complete deletion set before removing anything; never follow links.
    for path in &targets {
        validate_tree(path, &runs_dir, &repositories)?;
    }
    for path in targets {
        if dry_run {
            report.would_remove.push(path);
        } else {
            real_path(&path)?;
            validate_tree(&path, &runs_dir, &repositories)?;
            platform::remove_tree(&path)
                .map_err(|e| format!("Cannot prune {}: {e}", crate::platform::path_text(&path)))?;
            report.removed.push(path);
        }
    }
    Ok(report)
}

/// Safely remove `<state>/runs/<id>` trees for Runs already deleted from SQLite by retention.
pub(super) fn remove_expired_run_dirs(
    state: &Path,
    ids: &[crate::types::RunId],
) -> Result<(), String> {
    let state = platform::resolve_system_aliases(state).map_err(|e| e.to_string())?;
    let state = workspace::canonical_target(&real_path(&state)?).map_err(|e| e.to_string())?;
    let runs_dir = state.join("runs");
    if !directory(&runs_dir)? {
        return Ok(());
    }
    for id in ids {
        let path = runs_dir.join(id.as_str());
        if !directory(&path)? {
            continue;
        }
        real_path(&path)?;
        validate_tree(&path, &runs_dir, &[])?;
        platform::remove_tree(&path).map_err(|e| {
            format!(
                "Cannot remove expired Run directory {}: {e}",
                crate::platform::path_text(&path)
            )
        })?;
    }
    Ok(())
}

fn list_run_dir_ids(runs_dir: &Path) -> Result<Vec<crate::types::RunId>, String> {
    let handle = platform::open_directory(runs_dir).map_err(|e| e.to_string())?;
    let mut ids = Vec::new();
    for entry in platform::read_dir(&handle).map_err(|e| e.to_string())? {
        let entry = entry.map_err(|e| e.to_string())?;
        let name = entry.file_name();
        if let Some(text) = crate::platform::os_text(&name)
            && let Ok(id) = text.parse::<crate::types::RunId>()
        {
            ids.push(id);
        }
    }
    ids.sort();
    Ok(ids)
}

fn eligible_to_prune(
    status: crate::types::RunStatus,
    finished: Option<time::OffsetDateTime>,
    cutoff: Option<time::OffsetDateTime>,
    requests_terminal: bool,
    owned: bool,
) -> bool {
    use crate::types::RunStatus;
    matches!(
        status,
        RunStatus::Green | RunStatus::Red | RunStatus::Error | RunStatus::Incomplete
    ) && finished.is_some_and(|date| cutoff.is_none_or(|cutoff| date <= cutoff))
        && requests_terminal
        && !owned
}

fn segment(value: &str) -> bool {
    !value.is_empty()
        && value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
}

fn prefixed(name: &str, prefix: &str) -> bool {
    name.strip_prefix(prefix).is_some_and(segment)
}

fn collect(parent: &Path, targets: &mut Vec<PathBuf>) -> Result<(), String> {
    let parent_handle = platform::open_directory(parent).map_err(|e| e.to_string())?;
    let mut entries = platform::read_dir(&parent_handle)
        .map_err(|e| e.to_string())?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|e| e.to_string())?;
    entries.sort_by_key(|entry| entry.file_name());
    for entry in entries {
        let name = entry.file_name();
        let Some(name) = crate::platform::os_text(&name) else {
            continue;
        };
        let path = parent.join(entry.file_name());
        if matches!(name, "output" | "tmp" | "home" | "cache" | "human-tools")
            || ["tool-output-", "tool-"]
                .iter()
                .any(|prefix| prefixed(name, prefix))
        {
            if directory(&path)? {
                targets.push(path);
            }
        } else if ["runtime-", "fingerprint-"]
            .iter()
            .any(|prefix| prefixed(name, prefix))
            && directory(&path)?
        {
            collect(&path, targets)?;
        }
    }
    Ok(())
}

fn directory(path: &Path) -> Result<bool, String> {
    match platform::path_kind(path) {
        Ok(platform::FileKind::Directory) => {
            reject_repository(path)?;
            Ok(true)
        }
        Ok(_) => Err(format!(
            "Prune requires a real directory, not a symlink or file: {}",
            crate::platform::path_text(path)
        )),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
        Err(error) => Err(error.to_string()),
    }
}

fn real_path(path: &Path) -> Result<PathBuf, String> {
    platform::paths::absolute_without_links(path).map_err(|refusal| match refusal {
        platform::paths::LinkedPath::ParentTraversal => {
            "Prune paths must not contain parent traversal.".to_owned()
        }
        platform::paths::LinkedPath::Link(path) => {
            format!("Prune refuses symlinks: {}", platform::path_text(&path))
        }
        platform::paths::LinkedPath::Io(error) => error.to_string(),
    })
}

fn reject_repository(path: &Path) -> Result<(), String> {
    if workspace::has_artifact_marker(path).map_err(|error| error.to_string())? {
        return Err(format!(
            "Prune refuses repository content: {}",
            crate::platform::path_text(path)
        ));
    }
    match platform::path_kind(&path.join(".git")) {
        Ok(_) => Err(format!(
            "Prune refuses repository content: {}",
            crate::platform::path_text(path)
        )),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error.to_string()),
    }
}

fn validate_tree(path: &Path, runs: &Path, repositories: &[PathBuf]) -> Result<(), String> {
    // A link is refused first: the identity checks below would see where it leads.
    let kind = platform::path_kind(path).map_err(|e| e.to_string())?;
    if matches!(
        kind,
        platform::FileKind::Symlink | platform::FileKind::Other
    ) {
        return Err(format!(
            "Prune refuses symlinks: {}",
            crate::platform::path_text(path)
        ));
    }
    if !platform::is_within(path, runs)
        || platform::paths_equal(path, runs)
        || repositories
            .iter()
            .any(|repo| platform::is_within(path, repo) || platform::is_within(repo, path))
    {
        return Err(format!(
            "Prune target is outside Run output or overlaps a repository: {}",
            crate::platform::path_text(path)
        ));
    }
    if kind == platform::FileKind::Directory {
        reject_repository(path)?;
        let directory = platform::open_directory(path).map_err(|e| e.to_string())?;
        for entry in platform::read_dir(&directory).map_err(|e| e.to_string())? {
            validate_tree(
                &path.join(entry.map_err(|e| e.to_string())?.file_name()),
                runs,
                repositories,
            )?;
        }
    }
    Ok(())
}