Skip to main content

speccoder_runtime/
resume.rs

1//! Resuming an attempt a killed process left behind.
2//!
3//! Before an attempt, a marker records its admission key, the checkpoint it
4//! started from and the acceptance tests it is judged by. A run that ends in
5//! any ordinary way removes it ([`Guard`]); a killed process cannot, so a
6//! marker on disk means an attempt was interrupted. The next run then keeps
7//! the worktree as the attempt left it and admits the attempt under the same
8//! key: agentplane finds the interrupted run and resumes it from its journal
9//! — model calls and tool calls that finished are read back, not repeated —
10//! and a run that had already finished is read back whole and judged again
11//! (a task that passed just before the kill is ticked now).
12
13use std::path::{Path, PathBuf};
14
15use serde::{Deserialize, Serialize};
16use sha2::{Digest as _, Sha256};
17
18/// An attempt in progress.
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20pub struct Marker {
21    /// The agentplane admission key.
22    pub key: String,
23    /// The checkpoint the attempt started from.
24    pub before: String,
25    /// The worktree's HEAD then; a different HEAD means the marker is stale.
26    pub head: String,
27    /// Which attempt of the task run.
28    pub attempt: u32,
29    /// Which best-of-n sample (0-based).
30    pub sample: usize,
31    /// The acceptance tests prepared for the task run.
32    pub acceptance: Option<serde_json::Value>,
33}
34
35/// Where the marker of `feature/task` lives.
36#[must_use]
37pub fn path(plane_dir: &Path, feature: &str, task: &str) -> PathBuf {
38    plane_dir
39        .join("resume")
40        .join(feature)
41        .join(format!("{task}.json"))
42}
43
44/// The marker, if an attempt was interrupted.
45#[must_use]
46pub fn load(path: &Path) -> Option<Marker> {
47    serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
48}
49
50/// Records `marker` (written whole, then renamed: never half a marker).
51pub fn save(path: &Path, marker: &Marker) -> std::io::Result<()> {
52    if let Some(dir) = path.parent() {
53        std::fs::create_dir_all(dir)?;
54    }
55    let tmp = path.with_extension("json.tmp");
56    std::fs::write(
57        &tmp,
58        serde_json::to_vec(marker).map_err(std::io::Error::other)?,
59    )?;
60    std::fs::rename(tmp, path)
61}
62
63/// A fresh admission key: unique per attempt, so an ordinary rerun never
64/// meets an old attempt's run.
65#[must_use]
66pub fn new_key(feature: &str, task: &str) -> String {
67    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
68    let nanos = std::time::SystemTime::now()
69        .duration_since(std::time::UNIX_EPOCH)
70        .map_or(0, |d| d.as_nanos());
71    let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
72    let digest = Sha256::digest(format!(
73        "{feature}/{task}/{nanos}/{}/{n}",
74        std::process::id()
75    ));
76    let hex: String = digest.iter().take(16).map(|b| format!("{b:02x}")).collect();
77    format!("attempt-{hex}")
78}
79
80/// Removes the marker when a task run that started an attempt ends in any
81/// ordinary way. A run refused before its attempt starts (a session check,
82/// a worktree held by a waiting call) leaves an interrupted or waiting
83/// attempt's marker alone: that attempt still resumes.
84#[derive(Debug)]
85pub struct Guard {
86    path: PathBuf,
87    armed: std::cell::Cell<bool>,
88}
89
90impl Guard {
91    /// A guard for the marker at `path`, not yet armed.
92    #[must_use]
93    pub fn new(path: PathBuf) -> Self {
94        Self {
95            path,
96            armed: std::cell::Cell::new(false),
97        }
98    }
99
100    /// An attempt is starting: the marker goes when the run ends.
101    pub fn arm(&self) {
102        self.armed.set(true);
103    }
104
105    /// Leaves the marker in place: the attempt waits for a person and the
106    /// next run resumes it.
107    pub fn keep(self) {
108        self.armed.set(false);
109    }
110}
111
112impl Drop for Guard {
113    fn drop(&mut self) {
114        if self.armed.get() {
115            let _ = std::fs::remove_file(&self.path);
116        }
117    }
118}