Skip to main content

onerig_core/
store.rs

1//! What a run keeps on disk (design section 12): its state, its plan, its log
2//! and its lock, plus the run id and time formats.
3
4use std::collections::BTreeMap;
5use std::fs::{File, OpenOptions};
6use std::io::{Read, Seek, SeekFrom, Write};
7use std::os::fd::AsRawFd;
8use std::path::{Path, PathBuf};
9
10use serde::de::DeserializeOwned;
11use serde::{Deserialize, Serialize};
12
13use crate::plan::{Issue, Plan, VerdictKind};
14use crate::runner::{HarnessEvent, Outcome};
15
16/// Version of the `state.json` and `plan.json` format other tools may read.
17/// Within one version fields are only added.
18pub const STATE_VERSION: u32 = 1;
19
20#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
21pub struct State {
22    pub v: u32,
23    pub run_id: String,
24    pub goal: String,
25    /// Unix milliseconds; set on every write.
26    pub updated_at: u64,
27    /// The main checkout.
28    pub repo: PathBuf,
29    pub worktree: PathBuf,
30    pub branch: String,
31    pub phase: Phase,
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub paused: Option<Paused>,
34    /// 1-based position in the plan's tasks; `None` before the first task.
35    pub task_index: Option<usize>,
36    /// The worktree's `HEAD` when the current task started.
37    pub task_base: Option<String>,
38    /// The task's running attempt number, 1-based; never reset by resume.
39    pub attempt: Option<u32>,
40    /// What the attempt budget counts; resume and a new task set it to 0.
41    pub attempts_used: u32,
42    pub lane: Option<String>,
43    pub unknown_streak: u32,
44    /// Lanes skipped for the current task.
45    pub skipped: Vec<String>,
46    pub last_end: Option<LastEnd>,
47    /// True between an approve verdict and the task commit.
48    pub approved: bool,
49    pub issues: Vec<Issue>,
50    pub last_output_tail: String,
51    /// Numbers every job of the run; names the raw log files.
52    pub job_seq: u64,
53    pub lanes: BTreeMap<String, LaneMark>,
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
57#[serde(rename_all = "snake_case")]
58pub enum Phase {
59    Planning,
60    Executing,
61    Reviewing,
62    Paused,
63    Done,
64    Failed,
65}
66
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68pub struct Paused {
69    pub reason: PauseReason,
70    pub resume_phase: Phase,
71    pub message: String,
72    /// Earliest known reset time, unix milliseconds.
73    #[serde(default, skip_serializing_if = "Option::is_none")]
74    pub until: Option<u64>,
75}
76
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
78#[serde(rename_all = "snake_case")]
79pub enum PauseReason {
80    NoLane,
81    Handover,
82    Quota,
83    Auth,
84    AttemptsExhausted,
85    JobFailed,
86    GitError,
87    Interrupted,
88}
89
90/// How the last worker attempt ended; gives the next hand-over its reason.
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
92#[serde(rename_all = "snake_case")]
93pub enum LastEnd {
94    Quota,
95    Timeout,
96    Failed,
97    Interrupted,
98    Revise,
99}
100
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
102pub struct LaneMark {
103    #[serde(default)]
104    pub exhausted: bool,
105    /// Unix milliseconds; `None` with `exhausted` means until the next resume.
106    #[serde(default)]
107    pub exhausted_until: Option<u64>,
108}
109
110/// One line of `log.jsonl`.
111#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
112pub struct LogRecord {
113    /// Unix milliseconds.
114    pub ts: u64,
115    #[serde(default, skip_serializing_if = "Option::is_none")]
116    pub task: Option<usize>,
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub attempt: Option<u32>,
119    #[serde(default, skip_serializing_if = "Option::is_none")]
120    pub lane: Option<String>,
121    #[serde(flatten)]
122    pub entry: LogEntry,
123}
124
125#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
126#[serde(tag = "kind", content = "data", rename_all = "snake_case")]
127pub enum LogEntry {
128    State(StateEvent),
129    Policy(PolicyEvent),
130    Harness(HarnessEvent),
131    Outcome(Outcome),
132}
133
134#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
135#[serde(tag = "type", rename_all = "snake_case")]
136pub enum StateEvent {
137    /// Written when a run starts or resumes, so a reader of the log knows it.
138    Run {
139        run_id: String,
140        goal: String,
141        branch: String,
142    },
143    Plan {
144        tasks: usize,
145        #[serde(default)]
146        titles: Vec<String>,
147    },
148    Phase {
149        phase: Phase,
150    },
151    Verdict {
152        verdict: VerdictKind,
153        summary: String,
154        issues: Vec<Issue>,
155    },
156    Commit {
157        hash: String,
158        title: String,
159    },
160    Paused {
161        reason: PauseReason,
162        message: String,
163    },
164    Done {
165        branch: String,
166    },
167    Failed {
168        message: String,
169    },
170}
171
172#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
173#[serde(tag = "type", rename_all = "snake_case")]
174pub enum PolicyEvent {
175    /// What a harness reported about its quota before a lane was chosen.
176    Quota {
177        lane: String,
178        remaining_fraction: f64,
179        reset_at: Option<u64>,
180    },
181    Probe {
182        lane: String,
183        ok: bool,
184        message: String,
185    },
186    LaneSelected {
187        lane: String,
188        manual: bool,
189    },
190    LaneExhausted {
191        lane: String,
192        until: Option<u64>,
193    },
194    LaneSkipped {
195        lane: String,
196    },
197    Handover {
198        path: PathBuf,
199    },
200}
201
202const MS_PER_DAY: u64 = 86_400_000;
203
204/// `YYYYMMDD-HHMMSS-<4 hex>` in UTC. The hex digits mix the clock and the
205/// process id so two runs started in the same second differ.
206pub fn run_id(now_ms: u64, pid: u32) -> String {
207    let (year, month, day) = civil_from_days(now_ms / MS_PER_DAY);
208    let mix = ((now_ms % 1000) as u32).wrapping_mul(2_654_435_761) ^ pid;
209    format!(
210        "{year:04}{month:02}{day:02}-{}-{:04x}",
211        format_time(now_ms).replace(':', ""),
212        mix & 0xffff
213    )
214}
215
216/// `HH:MM:SS` in UTC.
217pub fn format_time(now_ms: u64) -> String {
218    let seconds = (now_ms % MS_PER_DAY) / 1000;
219    format!(
220        "{:02}:{:02}:{:02}",
221        seconds / 3600,
222        seconds / 60 % 60,
223        seconds % 60
224    )
225}
226
227/// `YYYY-MM-DDTHH:MM:SSZ` to unix milliseconds; `None` for any other form.
228pub fn parse_utc_ms(text: &str) -> Option<u64> {
229    let [year, month, day, hour, minute, second] = utc_fields(text)?;
230    let ranges = [
231        (month, 1, 12),
232        (day, 1, 31),
233        (hour, 0, 23),
234        (minute, 0, 59),
235        (second, 0, 59),
236    ];
237    if !ranges
238        .iter()
239        .all(|&(value, low, high)| (low..=high).contains(&value))
240    {
241        return None;
242    }
243    let days = days_from_civil(year, month, day)?;
244    Some((days * 86_400 + hour * 3600 + minute * 60 + second) * 1000)
245}
246
247/// The six numbers of a timestamp in exactly the form `YYYY-MM-DDTHH:MM:SSZ`.
248fn utc_fields(text: &str) -> Option<[u64; 6]> {
249    let bytes = text.as_bytes();
250    let separators = [
251        (4, b'-'),
252        (7, b'-'),
253        (10, b'T'),
254        (13, b':'),
255        (16, b':'),
256        (19, b'Z'),
257    ];
258    if bytes.len() != 20 || separators.iter().any(|&(i, c)| bytes[i] != c) {
259        return None;
260    }
261    let spans = [(0, 4), (5, 7), (8, 10), (11, 13), (14, 16), (17, 19)];
262    let mut fields = [0u64; 6];
263    for (field, (from, to)) in fields.iter_mut().zip(spans) {
264        let digits = &text[from..to];
265        if !digits.bytes().all(|b| b.is_ascii_digit()) {
266            return None;
267        }
268        *field = digits.parse().ok()?;
269    }
270    Some(fields)
271}
272
273/// The inverse of `civil_from_days`, for dates from 1970 on.
274fn days_from_civil(year: u64, month: u64, day: u64) -> Option<u64> {
275    let year = year.checked_sub(u64::from(month <= 2))?;
276    let era = year / 400;
277    let year_of_era = year % 400;
278    let month_index = if month > 2 { month - 3 } else { month + 9 };
279    let day_of_year = (153 * month_index + 2) / 5 + day - 1;
280    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
281    (era * 146_097 + day_of_era).checked_sub(719_468)
282}
283
284/// Days since 1970-01-01 to a proleptic Gregorian date (Howard Hinnant's
285/// `civil_from_days`, for non-negative days).
286fn civil_from_days(days: u64) -> (u64, u64, u64) {
287    let z = days + 719_468;
288    let era = z / 146_097;
289    let day_of_era = z % 146_097;
290    let year_of_era =
291        (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
292    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
293    let month_index = (5 * day_of_year + 2) / 153;
294    let day = day_of_year - (153 * month_index + 2) / 5 + 1;
295    let month = if month_index < 10 {
296        month_index + 3
297    } else {
298        month_index - 9
299    };
300    let year = year_of_era + era * 400 + u64::from(month <= 2);
301    (year, month, day)
302}
303
304#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
305pub enum StoreError {
306    #[error("there is no run {0} in this repository")]
307    NoRun(String),
308    #[error("run {0} already exists")]
309    Exists(String),
310    #[error("{}: {message}", path.display())]
311    Io { path: PathBuf, message: String },
312    #[error("{} is not a file onerig can read: {message}", path.display())]
313    Format { path: PathBuf, message: String },
314    #[error("{} has format version {found}, which this onerig does not know; upgrade onerig", path.display())]
315    Version { path: PathBuf, found: u64 },
316}
317
318pub(crate) fn io_error(path: &Path, error: std::io::Error) -> StoreError {
319    build_store_error(true, path, error)
320}
321
322pub(crate) fn format_error(path: &Path, error: impl std::fmt::Display) -> StoreError {
323    build_store_error(false, path, error)
324}
325
326fn build_store_error(is_io: bool, path: &Path, error: impl std::fmt::Display) -> StoreError {
327    let path = path.to_path_buf();
328    let message = error.to_string();
329    if is_io {
330        StoreError::Io { path, message }
331    } else {
332        StoreError::Format { path, message }
333    }
334}
335
336pub(crate) fn append_jsonl(path: &Path, value: &impl Serialize) -> Result<(), StoreError> {
337    let line = serde_json::to_string(value).map_err(|e| format_error(path, e))?;
338    let mut file = OpenOptions::new()
339        .create(true)
340        .append(true)
341        .open(path)
342        .map_err(|e| io_error(path, e))?;
343    writeln!(file, "{line}").map_err(|e| io_error(path, e))
344}
345
346pub(crate) fn open_dir(path: PathBuf, id: &str) -> Result<PathBuf, StoreError> {
347    if path.is_dir() {
348        Ok(path)
349    } else {
350        Err(StoreError::NoRun(id.to_string()))
351    }
352}
353
354pub(crate) fn create_sub_dir(root: &Path, id: &str) -> Result<PathBuf, StoreError> {
355    std::fs::create_dir_all(root).map_err(|e| io_error(root, e))?;
356    let path = root.join(id);
357    match std::fs::create_dir(&path) {
358        Ok(()) => Ok(path),
359        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
360            Err(StoreError::Exists(id.to_string()))
361        }
362        Err(e) => Err(io_error(&path, e)),
363    }
364}
365
366/// `<repo>/.onerig/runs`.
367pub fn runs_root(repo: &Path) -> PathBuf {
368    repo.join(".onerig").join("runs")
369}
370
371/// One run's directory, `<repo>/.onerig/runs/<run id>`.
372#[derive(Debug, Clone, PartialEq, Eq)]
373pub struct RunDir {
374    path: PathBuf,
375}
376
377impl RunDir {
378    pub fn create(repo: &Path, run_id: &str) -> Result<RunDir, StoreError> {
379        let path = create_sub_dir(&runs_root(repo), run_id)?;
380        Ok(RunDir { path })
381    }
382
383    pub fn open(repo: &Path, run_id: &str) -> Result<RunDir, StoreError> {
384        let path = open_dir(runs_root(repo).join(run_id), run_id)?;
385        Ok(RunDir { path })
386    }
387
388    pub fn path(&self) -> &Path {
389        &self.path
390    }
391
392    pub fn handover_path(&self, task_index: usize, attempt: u32) -> PathBuf {
393        self.path
394            .join(format!("handover-{task_index}-{attempt}.md"))
395    }
396
397    pub fn raw_log_path(&self, job_seq: u64) -> PathBuf {
398        self.path.join(format!("raw-{job_seq}.log"))
399    }
400
401    fn state_path(&self) -> PathBuf {
402        self.path.join("state.json")
403    }
404
405    fn plan_path(&self) -> PathBuf {
406        self.path.join("plan.json")
407    }
408
409    /// Replaces `state.json` atomically: a reader sees the old or the new file.
410    pub fn write_state(&self, state: &State) -> Result<(), StoreError> {
411        write_atomically(&self.state_path(), state)
412    }
413
414    pub fn read_state(&self) -> Result<State, StoreError> {
415        let path = self.state_path();
416        let value: serde_json::Value = read_json(&path)?;
417        let found = value
418            .get("v")
419            .and_then(serde_json::Value::as_u64)
420            .unwrap_or(0);
421        if found != u64::from(STATE_VERSION) {
422            return Err(StoreError::Version { path, found });
423        }
424        serde_json::from_value(value).map_err(|e| format_error(&path, e))
425    }
426
427    pub fn write_plan(&self, plan: &Plan) -> Result<(), StoreError> {
428        write_atomically(&self.plan_path(), plan)
429    }
430
431    pub fn read_plan(&self) -> Result<Plan, StoreError> {
432        read_json(&self.plan_path())
433    }
434
435    pub fn append_log(&self, record: &LogRecord) -> Result<(), StoreError> {
436        append_jsonl(&self.path.join("log.jsonl"), record)
437    }
438
439    pub fn read_log(&self) -> Result<Vec<LogRecord>, StoreError> {
440        read_jsonl(&self.path.join("log.jsonl"))
441    }
442}
443
444fn write_atomically(path: &Path, value: &impl Serialize) -> Result<(), StoreError> {
445    let text = serde_json::to_string_pretty(value).map_err(|e| format_error(path, e))?;
446    write_text_atomically(path, &text).map_err(|e| io_error(path, e))
447}
448
449/// Replaces `path` atomically with `text`, appending a trailing newline if absent.
450pub(crate) fn write_text_atomically(path: &Path, text: &str) -> std::io::Result<()> {
451    let mut tmp_name = path.as_os_str().to_os_string();
452    tmp_name.push(".tmp");
453    let temporary = PathBuf::from(tmp_name);
454    let mut file = File::create(&temporary)?;
455    file.write_all(text.as_bytes())?;
456    if !text.ends_with('\n') {
457        file.write_all(b"\n")?;
458    }
459    file.sync_all()?;
460    std::fs::rename(&temporary, path)
461}
462
463fn read_json<T: DeserializeOwned>(path: &Path) -> Result<T, StoreError> {
464    let text = std::fs::read_to_string(path).map_err(|e| io_error(path, e))?;
465    serde_json::from_str(&text).map_err(|e| format_error(path, e))
466}
467
468/// Reads newline-delimited JSON records, returning empty if `path` does not exist.
469pub(crate) fn read_jsonl<T: DeserializeOwned>(path: &Path) -> Result<Vec<T>, StoreError> {
470    let text = match std::fs::read_to_string(path) {
471        Ok(text) => text,
472        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
473        Err(e) => return Err(io_error(path, e)),
474    };
475    text.lines()
476        .filter(|line| !line.trim().is_empty())
477        .map(|line| serde_json::from_str(line).map_err(|e| format_error(path, e)))
478        .collect()
479}
480
481/// Directory entry names inside `root`, sorted descending; empty if `root` does not exist.
482pub(crate) fn sorted_entries(root: &Path) -> Result<Vec<String>, StoreError> {
483    let entries = match std::fs::read_dir(root) {
484        Ok(entries) => entries,
485        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
486        Err(e) => return Err(io_error(root, e)),
487    };
488    let mut ids: Vec<String> = entries
489        .filter_map(Result::ok)
490        .filter_map(|entry| entry.file_name().into_string().ok())
491        .collect();
492    ids.sort_unstable_by(|a, b| b.cmp(a));
493    Ok(ids)
494}
495
496/// The greatest run id whose phase is neither done nor failed. Runs that
497/// cannot be read are skipped.
498pub fn latest_resumable(repo: &Path) -> Result<Option<String>, StoreError> {
499    let ids = sorted_entries(&runs_root(repo))?;
500    Ok(ids.into_iter().find(|id| is_resumable(repo, id)))
501}
502
503fn is_resumable(repo: &Path, run_id: &str) -> bool {
504    RunDir::open(repo, run_id)
505        .and_then(|dir| dir.read_state())
506        .is_ok_and(|state| !matches!(state.phase, Phase::Done | Phase::Failed))
507}
508
509#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
510pub enum LockError {
511    #[error("another onerig process is working on this run (lock {})", path.display())]
512    Held { path: PathBuf },
513    #[error(
514        "process group {pgid}, started by an earlier onerig process for this run, still exists \
515         and may still be editing the worktree; stop it and try again (lock {})",
516        path.display()
517    )]
518    OrphanGroup { pgid: i32, path: PathBuf },
519    #[error("cannot use the lock file {}: {message}", path.display())]
520    Io { path: PathBuf, message: String },
521}
522
523#[derive(Debug, Serialize, Deserialize)]
524struct LockContent {
525    pid: u32,
526    pgid: Option<i32>,
527}
528
529/// Exclusive hold on a run, released by the kernel however the process ends.
530#[derive(Debug)]
531pub struct Lock {
532    file: File,
533    path: PathBuf,
534}
535
536impl Lock {
537    pub fn acquire(run_dir: &RunDir) -> Result<Lock, LockError> {
538        Self::acquire_file(run_dir.path().join("lock"))
539    }
540
541    /// Takes an exclusive non-blocking lock on an arbitrary lock file path.
542    pub fn acquire_file(path: PathBuf) -> Result<Lock, LockError> {
543        let lock_io = |e: std::io::Error| LockError::Io {
544            path: path.clone(),
545            message: e.to_string(),
546        };
547        let file = OpenOptions::new()
548            .read(true)
549            .write(true)
550            .create(true)
551            .truncate(false)
552            .open(&path)
553            .map_err(lock_io)?;
554        if !try_flock(&file) {
555            return Err(LockError::Held { path });
556        }
557        let mut lock = Lock { file, path };
558        if let Some(pgid) = lock.previous_pgid().filter(|&pgid| group_exists(pgid)) {
559            return Err(LockError::OrphanGroup {
560                pgid,
561                path: lock.path,
562            });
563        }
564        lock.set_pgid(None)?;
565        Ok(lock)
566    }
567
568    /// Records the running child's process group, or `None` once it is reaped.
569    pub fn set_pgid(&mut self, pgid: Option<i32>) -> Result<(), LockError> {
570        let content = LockContent {
571            pid: std::process::id(),
572            pgid,
573        };
574        let text = serde_json::to_string(&content).unwrap_or_default();
575        let mut write = || -> std::io::Result<()> {
576            self.file.seek(SeekFrom::Start(0))?;
577            self.file.write_all(text.as_bytes())?;
578            self.file.set_len(text.len() as u64)?;
579            self.file.sync_data()
580        };
581        write().map_err(|e| LockError::Io {
582            path: self.path.clone(),
583            message: e.to_string(),
584        })
585    }
586
587    fn previous_pgid(&mut self) -> Option<i32> {
588        let mut text = String::new();
589        self.file.read_to_string(&mut text).ok()?;
590        serde_json::from_str::<LockContent>(&text).ok()?.pgid
591    }
592}
593
594fn try_flock(file: &File) -> bool {
595    // SAFETY: the descriptor belongs to `file`, which outlives this call.
596    unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) == 0 }
597}
598
599/// Signal 0 checks that a process group exists without touching it.
600fn group_exists(pgid: i32) -> bool {
601    // 0 would address this process's own group and 1 every process.
602    if pgid <= 1 {
603        return false;
604    }
605    // SAFETY: kill with signal 0 sends nothing; it only checks the target.
606    let result = unsafe { libc::kill(-pgid, 0) };
607    result == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
608}
609
610#[cfg(test)]
611mod tests {
612    use super::*;
613    use crate::runner::FailureKind;
614    use serde_json::json;
615
616    // These are the log lines the design document shows; other tools and the
617    // plain output depend on them.
618    #[test]
619    fn log_records_have_the_documented_shape() {
620        let harness = LogRecord {
621            ts: 1_763_929_001_000,
622            task: Some(1),
623            attempt: Some(1),
624            lane: Some("deepseek".into()),
625            entry: LogEntry::Harness(HarnessEvent::Tool {
626                name: "edit".into(),
627                detail: "src/http.rs".into(),
628            }),
629        };
630        let policy = LogRecord {
631            ts: 1_763_929_090_001,
632            task: Some(1),
633            attempt: None,
634            lane: None,
635            entry: LogEntry::Policy(PolicyEvent::LaneExhausted {
636                lane: "deepseek".into(),
637                until: None,
638            }),
639        };
640
641        assert_eq!(
642            serde_json::to_value(&harness).unwrap(),
643            json!({ "ts": 1_763_929_001_000u64, "task": 1, "attempt": 1, "lane": "deepseek",
644                    "kind": "harness", "data": { "type": "tool", "name": "edit", "detail": "src/http.rs" } })
645        );
646        assert_eq!(
647            serde_json::to_value(&policy).unwrap(),
648            json!({ "ts": 1_763_929_090_001u64, "task": 1,
649                    "kind": "policy", "data": { "type": "lane_exhausted", "lane": "deepseek", "until": null } })
650        );
651    }
652
653    #[test]
654    fn a_log_record_survives_a_round_trip() {
655        let record = LogRecord {
656            ts: 5,
657            task: Some(2),
658            attempt: Some(3),
659            lane: Some("gemini".into()),
660            entry: LogEntry::Outcome(Outcome::Failed {
661                kind: FailureKind::Quota,
662                message: "empty".into(),
663                reset_at: Some(9),
664            }),
665        };
666
667        let line = serde_json::to_string(&record).unwrap();
668
669        assert_eq!(serde_json::from_str::<LogRecord>(&line).unwrap(), record);
670    }
671
672    #[test]
673    fn a_paused_state_reads_back_with_optional_fields_absent() {
674        let text = json!({
675            "v": 1, "run_id": "20261123-201500-a1f3", "goal": "g", "updated_at": 1,
676            "repo": "/r", "worktree": "/w", "branch": "onerig/20261123-201500-a1f3",
677            "phase": "paused",
678            "paused": { "reason": "no_lane", "resume_phase": "executing", "message": "m" },
679            "task_index": 2, "task_base": "3f2a", "attempt": 2, "attempts_used": 2,
680            "lane": "deepseek", "unknown_streak": 0, "skipped": [], "last_end": "quota",
681            "approved": false, "issues": [], "last_output_tail": "", "job_seq": 7,
682            "lanes": { "deepseek": { "exhausted": true, "exhausted_until": null }, "gemini": {} }
683        });
684
685        let state: State = serde_json::from_value(text).unwrap();
686
687        assert_eq!(state.phase, Phase::Paused);
688        assert_eq!(state.paused.as_ref().unwrap().reason, PauseReason::NoLane);
689        assert_eq!(state.paused.as_ref().unwrap().until, None);
690        assert_eq!(state.last_end, Some(LastEnd::Quota));
691        assert!(state.lanes["deepseek"].exhausted);
692        assert_eq!(state.lanes["gemini"], LaneMark::default());
693    }
694
695    fn sample_state(run_id: &str, phase: Phase) -> State {
696        State {
697            v: STATE_VERSION,
698            run_id: run_id.into(),
699            goal: "g".into(),
700            updated_at: 1,
701            repo: "/r".into(),
702            worktree: "/w".into(),
703            branch: format!("onerig/{run_id}"),
704            phase,
705            paused: None,
706            task_index: None,
707            task_base: None,
708            attempt: None,
709            attempts_used: 0,
710            lane: None,
711            unknown_streak: 0,
712            skipped: vec![],
713            last_end: None,
714            approved: false,
715            issues: vec![],
716            last_output_tail: String::new(),
717            job_seq: 0,
718            lanes: BTreeMap::new(),
719        }
720    }
721
722    #[test]
723    fn a_run_id_is_the_utc_date_and_time_plus_four_hex_digits() {
724        let id = run_id(1_795_464_900_000, 4242);
725
726        assert!(id.starts_with("20261123-201500-"), "{id}");
727        assert_eq!(id.len(), "20261123-201500-a1f3".len());
728        assert!(id[16..].chars().all(|c| c.is_ascii_hexdigit()));
729    }
730
731    #[test]
732    fn run_ids_get_calendar_edges_right() {
733        let cases = [
734            (0, "19700101-000000"),
735            (1_709_210_096_000, "20240229-123456"),
736            (1_767_225_599_000, "20251231-235959"),
737            (1_767_225_600_000, "20260101-000000"),
738            (4_107_542_400_000, "21000301-000000"),
739        ];
740
741        for (ms, expected) in cases {
742            assert_eq!(&run_id(ms, 1)[..15], expected, "{ms}");
743        }
744    }
745
746    #[test]
747    fn run_ids_from_two_processes_in_the_same_second_differ() {
748        assert_ne!(
749            run_id(1_795_464_900_123, 100),
750            run_id(1_795_464_900_123, 101)
751        );
752    }
753
754    #[test]
755    fn times_print_as_utc_clock_time() {
756        assert_eq!(format_time(1_795_464_901_999), "20:15:01");
757        assert_eq!(format_time(0), "00:00:00");
758    }
759
760    #[test]
761    fn a_run_directory_is_created_once_and_opened_after() {
762        let repo = tempfile::tempdir().unwrap();
763
764        let created = RunDir::create(repo.path(), "r1").unwrap();
765
766        assert!(created.path().ends_with(".onerig/runs/r1"));
767        assert_eq!(
768            RunDir::create(repo.path(), "r1"),
769            Err(StoreError::Exists("r1".into()))
770        );
771        assert_eq!(RunDir::open(repo.path(), "r1").unwrap(), created);
772        assert_eq!(
773            RunDir::open(repo.path(), "r2"),
774            Err(StoreError::NoRun("r2".into()))
775        );
776    }
777
778    #[test]
779    fn run_files_are_named_as_documented() {
780        let repo = tempfile::tempdir().unwrap();
781        let dir = RunDir::create(repo.path(), "r1").unwrap();
782
783        assert_eq!(
784            dir.handover_path(2, 3).file_name().unwrap(),
785            "handover-2-3.md"
786        );
787        assert_eq!(dir.raw_log_path(7).file_name().unwrap(), "raw-7.log");
788    }
789
790    #[test]
791    fn state_and_plan_are_written_and_read_back() {
792        let repo = tempfile::tempdir().unwrap();
793        let dir = RunDir::create(repo.path(), "r1").unwrap();
794        let state = sample_state("r1", Phase::Executing);
795        let plan = Plan { tasks: vec![] };
796
797        dir.write_state(&state).unwrap();
798        dir.write_plan(&plan).unwrap();
799
800        assert_eq!(dir.read_state().unwrap(), state);
801        assert_eq!(dir.read_plan().unwrap(), plan);
802        assert!(!dir.path().join("state.json.tmp").exists());
803    }
804
805    #[test]
806    fn a_state_of_another_version_is_refused() {
807        let repo = tempfile::tempdir().unwrap();
808        let dir = RunDir::create(repo.path(), "r1").unwrap();
809        let mut value = serde_json::to_value(sample_state("r1", Phase::Done)).unwrap();
810        value["v"] = json!(2);
811        std::fs::write(dir.path().join("state.json"), value.to_string()).unwrap();
812
813        assert!(matches!(
814            dir.read_state(),
815            Err(StoreError::Version { found: 2, .. })
816        ));
817    }
818
819    #[test]
820    fn a_damaged_state_is_a_format_error() {
821        let repo = tempfile::tempdir().unwrap();
822        let dir = RunDir::create(repo.path(), "r1").unwrap();
823        std::fs::write(dir.path().join("state.json"), "{\"v\": 1}").unwrap();
824
825        assert!(matches!(dir.read_state(), Err(StoreError::Format { .. })));
826    }
827
828    #[test]
829    fn log_records_are_appended_one_per_line() {
830        let repo = tempfile::tempdir().unwrap();
831        let dir = RunDir::create(repo.path(), "r1").unwrap();
832        let record = |tasks| LogRecord {
833            ts: 1,
834            task: None,
835            attempt: None,
836            lane: None,
837            entry: LogEntry::State(StateEvent::Plan {
838                tasks,
839                titles: vec![],
840            }),
841        };
842
843        dir.append_log(&record(1)).unwrap();
844        dir.append_log(&record(2)).unwrap();
845
846        assert_eq!(dir.read_log().unwrap(), [record(1), record(2)]);
847        assert_eq!(
848            RunDir::create(repo.path(), "r2")
849                .unwrap()
850                .read_log()
851                .unwrap(),
852            []
853        );
854    }
855
856    #[test]
857    fn the_latest_resumable_run_skips_finished_and_unreadable_runs() {
858        let repo = tempfile::tempdir().unwrap();
859        for (id, phase) in [
860            ("r1", Phase::Paused),
861            ("r2", Phase::Executing),
862            ("r3", Phase::Done),
863            ("r5", Phase::Failed),
864        ] {
865            RunDir::create(repo.path(), id)
866                .unwrap()
867                .write_state(&sample_state(id, phase))
868                .unwrap();
869        }
870        RunDir::create(repo.path(), "r4").unwrap();
871
872        assert_eq!(latest_resumable(repo.path()).unwrap(), Some("r2".into()));
873    }
874
875    #[test]
876    fn no_runs_means_nothing_to_resume() {
877        let repo = tempfile::tempdir().unwrap();
878
879        assert_eq!(latest_resumable(repo.path()).unwrap(), None);
880    }
881
882    fn lock_content(dir: &RunDir) -> serde_json::Value {
883        serde_json::from_str(&std::fs::read_to_string(dir.path().join("lock")).unwrap()).unwrap()
884    }
885
886    #[test]
887    fn a_held_lock_refuses_a_second_holder_until_it_is_dropped() {
888        let repo = tempfile::tempdir().unwrap();
889        let dir = RunDir::create(repo.path(), "r1").unwrap();
890
891        let first = Lock::acquire(&dir).unwrap();
892
893        assert!(matches!(Lock::acquire(&dir), Err(LockError::Held { .. })));
894        drop(first);
895        // Other tests fork children in parallel; a child between fork and exec
896        // briefly holds a copy of the descriptor, and with it the lock.
897        let reacquired = (0..200).any(|_| {
898            std::thread::sleep(std::time::Duration::from_millis(10));
899            Lock::acquire(&dir).is_ok()
900        });
901        assert!(reacquired);
902    }
903
904    #[test]
905    fn the_lock_records_the_pid_and_the_childs_group() {
906        let repo = tempfile::tempdir().unwrap();
907        let dir = RunDir::create(repo.path(), "r1").unwrap();
908        let mut lock = Lock::acquire(&dir).unwrap();
909
910        assert_eq!(
911            lock_content(&dir),
912            json!({ "pid": std::process::id(), "pgid": null })
913        );
914        lock.set_pgid(Some(12345)).unwrap();
915        assert_eq!(
916            lock_content(&dir),
917            json!({ "pid": std::process::id(), "pgid": 12345 })
918        );
919    }
920
921    #[test]
922    fn a_recorded_group_that_still_exists_is_reported_not_signalled() {
923        let repo = tempfile::tempdir().unwrap();
924        let dir = RunDir::create(repo.path(), "r1").unwrap();
925        // SAFETY: getpgrp has no preconditions.
926        let own_group = unsafe { libc::getpgrp() };
927        std::fs::write(
928            dir.path().join("lock"),
929            json!({ "pid": 1, "pgid": own_group }).to_string(),
930        )
931        .unwrap();
932
933        let result = Lock::acquire(&dir);
934
935        assert!(matches!(result, Err(LockError::OrphanGroup { pgid, .. }) if pgid == own_group));
936    }
937
938    #[test]
939    fn a_recorded_group_that_is_gone_is_cleared() {
940        let repo = tempfile::tempdir().unwrap();
941        let dir = RunDir::create(repo.path(), "r1").unwrap();
942        std::fs::write(
943            dir.path().join("lock"),
944            json!({ "pid": 1, "pgid": 2_000_000_000 }).to_string(),
945        )
946        .unwrap();
947
948        let _lock = Lock::acquire(&dir).unwrap();
949
950        assert_eq!(lock_content(&dir)["pgid"], json!(null));
951    }
952
953    #[test]
954    fn a_state_without_a_version_is_refused_as_version_zero() {
955        let repo = tempfile::tempdir().unwrap();
956        let dir = RunDir::create(repo.path(), "r1").unwrap();
957        std::fs::write(dir.path().join("state.json"), "{}").unwrap();
958
959        assert!(matches!(
960            dir.read_state(),
961            Err(StoreError::Version { found: 0, .. })
962        ));
963    }
964
965    #[test]
966    fn a_shorter_lock_content_replaces_a_longer_one_completely() {
967        let repo = tempfile::tempdir().unwrap();
968        let dir = RunDir::create(repo.path(), "r1").unwrap();
969        let mut lock = Lock::acquire(&dir).unwrap();
970
971        lock.set_pgid(Some(1_234_567)).unwrap();
972        lock.set_pgid(None).unwrap();
973
974        assert_eq!(lock_content(&dir)["pgid"], json!(null));
975    }
976
977    #[test]
978    fn only_a_real_process_group_counts_as_existing() {
979        // SAFETY: getpgrp has no preconditions.
980        let own_group = unsafe { libc::getpgrp() };
981        let mut child = std::process::Command::new("sleep")
982            .arg("5")
983            .spawn()
984            .unwrap();
985        let child_pid = child.id() as i32;
986
987        let results = [
988            group_exists(0),
989            group_exists(1),
990            group_exists(own_group),
991            group_exists(child_pid),
992        ];
993        child.kill().unwrap();
994        child.wait().unwrap();
995
996        // The child shares this process's group, so no group has its pid as id.
997        assert_eq!(results, [false, false, true, false]);
998    }
999
1000    #[test]
1001    fn utc_timestamps_parse_to_milliseconds_and_round_trip_with_the_run_id_date() {
1002        assert_eq!(
1003            parse_utc_ms("2026-11-23T20:15:00Z"),
1004            Some(1_795_464_900_000)
1005        );
1006        assert_eq!(
1007            parse_utc_ms("2024-02-29T12:34:56Z"),
1008            Some(1_709_210_096_000)
1009        );
1010        assert_eq!(parse_utc_ms("1970-01-01T00:00:00Z"), Some(0));
1011        assert_eq!(
1012            parse_utc_ms("2100-03-01T00:00:00Z"),
1013            Some(4_107_542_400_000)
1014        );
1015        assert_eq!(
1016            &run_id(parse_utc_ms("2026-01-01T00:00:00Z").unwrap(), 1)[..15],
1017            "20260101-000000"
1018        );
1019    }
1020
1021    #[test]
1022    fn other_timestamp_forms_are_refused() {
1023        for text in [
1024            "",
1025            "2026-11-23 20:15:00Z",
1026            "2026-11-23T20:15:00",
1027            "2026-13-01T00:00:00Z",
1028            "2026-11-23T24:00:00Z",
1029            "2026-11-32T00:00:00Z",
1030            "2026-1x-23T20:15:00Z",
1031            "1969-12-31T23:59:59Z",
1032        ] {
1033            assert_eq!(parse_utc_ms(text), None, "{text}");
1034        }
1035    }
1036
1037    #[test]
1038    fn write_text_atomically_normalizes_trailing_newline_and_io_error_is_io_variant() {
1039        let dir = tempfile::tempdir().unwrap();
1040        let no_nl = dir.path().join("a.txt");
1041        let has_nl = dir.path().join("b.txt");
1042        write_text_atomically(&no_nl, "hi").unwrap();
1043        write_text_atomically(&has_nl, "hi\n").unwrap();
1044        assert_eq!(std::fs::read_to_string(&no_nl).unwrap(), "hi\n");
1045        assert_eq!(std::fs::read_to_string(&has_nl).unwrap(), "hi\n");
1046
1047        let err = read_json::<serde_json::Value>(&dir.path().join("missing.json")).unwrap_err();
1048        assert!(matches!(err, StoreError::Io { .. }));
1049    }
1050}