Skip to main content

onerig_core/
run.rs

1//! The run state machine of design sections 5 and 6: plan, execute, review,
2//! commit, pause and resume. It talks to harnesses only through `Runner`, so
3//! it is tested with the scripted runner.
4
5use std::collections::{BTreeMap, HashSet};
6use std::path::{Path, PathBuf};
7
8use crate::config::Config;
9use crate::halt::Halt;
10use crate::plan::{
11    FormatError, PLAN_SCHEMA, Plan, Task, VERDICT_SCHEMA, Verdict, VerdictKind, parse_plan,
12    parse_verdict,
13};
14use crate::policy::{self, AfterFailure, LaneView, Selected, Selection};
15use crate::prompt::{self, Previous, WorkerPrompt};
16use crate::runner::{FailureKind, HarnessEvent, Job, Outcome, ProbeError, Role, Runner};
17use crate::store::{
18    LaneMark, LastEnd, Lock, LockError, LogEntry, LogRecord, PauseReason, Paused, Phase,
19    PolicyEvent, RunDir, STATE_VERSION, State, StateEvent, StoreError,
20};
21use crate::worktree::{Committed, Git, GitError, worktree_path};
22
23/// How many times a planner or reviewer job is tried before the run gives up.
24const ASK_TRIES: usize = 2;
25
26/// What a run needs from the world. The binary passes the real things; tests
27/// pass a scripted runner, a fixed clock and a temporary data home.
28pub struct Env<'a> {
29    pub git: &'a Git,
30    pub runner: &'a mut dyn Runner,
31    /// Unix milliseconds.
32    pub clock: &'a dyn Fn() -> u64,
33    pub pid: u32,
34    pub stop: &'a Halt,
35    /// Receives every log record as it is written.
36    pub sink: &'a mut dyn FnMut(&LogRecord),
37    /// `$XDG_DATA_HOME` or its default; worktrees go below it.
38    pub data_home: &'a Path,
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum Exit {
43    Done,
44    Failed,
45    Paused,
46}
47
48#[derive(Debug)]
49pub struct Finished {
50    pub exit: Exit,
51    pub run_id: String,
52    pub state: State,
53}
54
55#[derive(Debug, thiserror::Error)]
56pub enum RunError {
57    #[error(transparent)]
58    Git(#[from] GitError),
59    #[error(transparent)]
60    Store(#[from] StoreError),
61    #[error(transparent)]
62    Lock(#[from] LockError),
63    #[error("lane {lane} cannot run: {message}")]
64    Probe { lane: String, message: String },
65    #[error("there is no run to resume in this repository")]
66    NothingToResume,
67    #[error("run {0} has already finished")]
68    AlreadyFinished(String),
69}
70
71/// What a new run starts from.
72#[derive(Debug, Clone)]
73pub struct NewRun<'g> {
74    pub goal: &'g str,
75    /// A plan the owner already approved; the run then skips planning.
76    pub plan: Option<Plan>,
77    /// The ref the run's branch starts from; the main checkout's HEAD if `None`.
78    pub base: Option<&'g str>,
79}
80
81/// Starts a new run for `goal` in the repository that contains `cwd`.
82pub fn start<'a>(
83    config: &'a Config,
84    cwd: &Path,
85    goal: &str,
86    env: Env<'a>,
87) -> Result<Finished, RunError> {
88    let new = NewRun {
89        goal,
90        plan: None,
91        base: None,
92    };
93    start_with(config, cwd, new, env)
94}
95
96/// Starts a new run as `new` describes.
97pub fn start_with<'a>(
98    config: &'a Config,
99    cwd: &Path,
100    new: NewRun<'_>,
101    env: Env<'a>,
102) -> Result<Finished, RunError> {
103    let main = env.git.main_checkout(cwd)?;
104    env.git.preflight(&main)?;
105    let probes = probe_lanes(config, env.runner)?;
106    let (dir, lock, state) = create_run(&env, main, new.goal, new.base)?;
107    let mut machine = Machine::new(config, env, dir, lock, state, probes, None);
108    machine.note_run();
109    machine.begin(new.plan)?;
110    machine.finish()
111}
112
113/// Creates the run's directory, lock, branch and worktree.
114fn create_run(
115    env: &Env<'_>,
116    main: PathBuf,
117    goal: &str,
118    base: Option<&str>,
119) -> Result<(RunDir, Lock, State), RunError> {
120    let now = (env.clock)();
121    let run_id = crate::store::run_id(now, env.pid);
122    let dir = RunDir::create(&main, &run_id)?;
123    let lock = Lock::acquire(&dir)?;
124    env.git.ensure_excluded(&main)?;
125    let worktree = worktree_path(env.data_home, &main, &run_id);
126    let branch = format!("onerig/{run_id}");
127    env.git
128        .create_run_worktree(&main, &worktree, &branch, base.unwrap_or("HEAD"))?;
129    let state = new_state(&run_id, goal, now, main, worktree, branch);
130    Ok((dir, lock, state))
131}
132
133/// Continues the given run, or the latest one that has not finished.
134pub fn resume<'a>(
135    config: &'a Config,
136    cwd: &Path,
137    run_id: Option<&str>,
138    env: Env<'a>,
139) -> Result<Finished, RunError> {
140    let (dir, lock, mut state) = open_run(env.git, cwd, run_id)?;
141    let probes = probe_lanes(config, env.runner)?;
142    let plan = state.task_index.map(|_| dir.read_plan()).transpose()?;
143    prepare_resume(&mut state);
144    let mut machine = Machine::new(config, env, dir, lock, state, probes, plan);
145    machine.note_run();
146    machine.note_plan();
147    machine.note(LogEntry::State(StateEvent::Phase {
148        phase: machine.state.phase,
149    }));
150    machine.save()?;
151    machine.finish()
152}
153
154/// Finds the run, takes its lock and reads its state.
155fn open_run(
156    git: &Git,
157    cwd: &Path,
158    run_id: Option<&str>,
159) -> Result<(RunDir, Lock, State), RunError> {
160    let main = git.main_checkout(cwd)?;
161    let run_id = given_or_latest(&main, run_id)?;
162    let dir = RunDir::open(&main, &run_id)?;
163    let lock = Lock::acquire(&dir)?;
164    let state = dir.read_state()?;
165    if exit_of(state.phase).is_some_and(|exit| exit != Exit::Paused) {
166        return Err(RunError::AlreadyFinished(run_id));
167    }
168    Ok((dir, lock, state))
169}
170
171fn given_or_latest(main: &Path, run_id: Option<&str>) -> Result<String, RunError> {
172    match run_id {
173        Some(id) => Ok(id.to_string()),
174        None => crate::store::latest_resumable(main)?.ok_or(RunError::NothingToResume),
175    }
176}
177
178fn new_state(
179    run_id: &str,
180    goal: &str,
181    now: u64,
182    repo: PathBuf,
183    worktree: PathBuf,
184    branch: String,
185) -> State {
186    State {
187        v: STATE_VERSION,
188        run_id: run_id.to_string(),
189        goal: goal.to_string(),
190        updated_at: now,
191        repo,
192        worktree,
193        branch,
194        phase: Phase::Planning,
195        paused: None,
196        task_index: None,
197        task_base: None,
198        attempt: None,
199        attempts_used: 0,
200        lane: None,
201        unknown_streak: 0,
202        skipped: Vec::new(),
203        last_end: None,
204        approved: false,
205        issues: Vec::new(),
206        last_output_tail: String::new(),
207        job_seq: 0,
208        lanes: BTreeMap::new(),
209    }
210}
211
212/// A run found in a working phase had no live process: it was interrupted.
213fn prepare_resume(state: &mut State) {
214    let resume_phase = match state.paused.take() {
215        Some(paused) if state.phase == Phase::Paused => paused.resume_phase,
216        _ => {
217            if state.phase == Phase::Executing {
218                state.last_end = Some(LastEnd::Interrupted);
219            }
220            state.phase
221        }
222    };
223    state.phase = resume_phase;
224    state
225        .lanes
226        .values_mut()
227        .for_each(|mark| *mark = LaneMark::default());
228    state.skipped.clear();
229    state.unknown_streak = 0;
230    state.attempts_used = 0;
231}
232
233/// Planner and reviewer must be usable, or the run cannot start; a worker
234/// lane that fails its probe is only unavailable. Manual and off lanes are
235/// never probed.
236fn probe_lanes(config: &Config, runner: &mut dyn Runner) -> Result<Probes, RunError> {
237    let mut probes = Probes::default();
238    let mut seen = HashSet::new();
239    for lane in [&config.roles.planner, &config.roles.reviewer] {
240        if !seen.insert(lane.clone()) {
241            continue;
242        }
243        let result = runner.preflight(lane);
244        if let Err(error) = &result {
245            return Err(RunError::Probe {
246                lane: lane.clone(),
247                message: error.to_string(),
248            });
249        }
250        probes.results.push((lane.clone(), result));
251    }
252    for name in &config.roles.worker {
253        if !seen.insert(name.clone()) {
254            continue;
255        }
256        let lane = &config.lanes[name];
257        if lane.is_off() || lane.is_manual() {
258            continue;
259        }
260        let result = runner.preflight(name);
261        if let Err(error) = &result {
262            probes.failed.insert(name.clone(), error.to_string());
263        }
264        probes.results.push((name.clone(), result));
265    }
266    Ok(probes)
267}
268
269#[derive(Default)]
270struct Probes {
271    results: Vec<(String, Result<crate::runner::Probe, ProbeError>)>,
272    /// Worker lanes whose probe failed, with the message.
273    failed: BTreeMap<String, String>,
274}
275
276/// Appends records to the run log and passes them to the sink. A write error
277/// is kept and reported when the current step ends.
278struct Log<'a> {
279    dir: RunDir,
280    sink: &'a mut dyn FnMut(&LogRecord),
281    clock: &'a dyn Fn() -> u64,
282    error: Option<StoreError>,
283}
284
285impl Log<'_> {
286    fn record(
287        &mut self,
288        task: Option<usize>,
289        attempt: Option<u32>,
290        lane: Option<&str>,
291        entry: LogEntry,
292    ) {
293        let record = LogRecord {
294            ts: (self.clock)(),
295            task,
296            attempt,
297            lane: lane.map(str::to_string),
298            entry,
299        };
300        if let Err(error) = self.dir.append_log(&record) {
301            self.error.get_or_insert(error);
302        }
303        (self.sink)(&record);
304    }
305}
306
307/// The answer of a planner or reviewer job.
308enum Asked<T> {
309    Answer(T),
310    Pause(PauseReason, String, Option<u64>),
311    Failed(String),
312    Stopped,
313}
314
315/// Why a planner or reviewer answer cannot be used.
316enum Unusable {
317    Pause(PauseReason, String, Option<u64>),
318    Retry(String),
319}
320
321fn classify<T>(
322    outcome: Outcome,
323    parse: fn(&serde_json::Value) -> Result<T, FormatError>,
324) -> Result<T, Unusable> {
325    match outcome {
326        Outcome::Failed {
327            kind: FailureKind::Quota,
328            message,
329            reset_at,
330        } => Err(Unusable::Pause(PauseReason::Quota, message, reset_at)),
331        Outcome::Failed {
332            kind: FailureKind::Auth,
333            message,
334            ..
335        } => Err(Unusable::Pause(PauseReason::Auth, message, None)),
336        Outcome::Failed { message, .. } => Err(Unusable::Retry(message)),
337        Outcome::Done {
338            structured: Some(value),
339            ..
340        } => parse(&value).map_err(|error| Unusable::Retry(error.to_string())),
341        Outcome::Done {
342            structured: None, ..
343        } => Err(Unusable::Retry(
344            "the answer had no structured result".to_string(),
345        )),
346    }
347}
348
349struct Machine<'a> {
350    config: &'a Config,
351    git: &'a Git,
352    runner: &'a mut dyn Runner,
353    stop: &'a Halt,
354    clock: &'a dyn Fn() -> u64,
355    log: Log<'a>,
356    /// Held for the whole run; records the running harness's process group.
357    lock: Lock,
358    probes: Probes,
359    plan: Option<Plan>,
360    state: State,
361}
362
363impl<'a> Machine<'a> {
364    fn new(
365        config: &'a Config,
366        env: Env<'a>,
367        dir: RunDir,
368        lock: Lock,
369        state: State,
370        probes: Probes,
371        plan: Option<Plan>,
372    ) -> Machine<'a> {
373        let mut machine = Machine {
374            config,
375            git: env.git,
376            runner: env.runner,
377            stop: env.stop,
378            clock: env.clock,
379            log: Log {
380                dir,
381                sink: env.sink,
382                clock: env.clock,
383                error: None,
384            },
385            lock,
386            probes,
387            plan,
388            state,
389        };
390        machine.log_probes();
391        machine
392    }
393
394    fn log_probes(&mut self) {
395        let results = std::mem::take(&mut self.probes.results);
396        for (lane, result) in results {
397            let (ok, message) = match result {
398                Ok(probe) => (true, probe.version),
399                Err(error) => (false, error.to_string()),
400            };
401            self.note(LogEntry::Policy(PolicyEvent::Probe { lane, ok, message }));
402        }
403    }
404
405    fn finish(mut self) -> Result<Finished, RunError> {
406        let exit = self.drive()?;
407        Ok(Finished {
408            exit,
409            run_id: self.state.run_id.clone(),
410            state: self.state,
411        })
412    }
413
414    fn drive(&mut self) -> Result<Exit, RunError> {
415        loop {
416            if let Some(exit) = exit_of(self.state.phase) {
417                return Ok(exit);
418            }
419            if self.stop.is_set() {
420                self.pause_interrupted()?;
421                continue;
422            }
423            self.step()?;
424            if let Some(error) = self.log.error.take() {
425                return Err(error.into());
426            }
427        }
428    }
429
430    fn step(&mut self) -> Result<(), RunError> {
431        match self.state.phase {
432            Phase::Planning => self.plan(),
433            Phase::Executing => self.execute(),
434            Phase::Reviewing => self.review(),
435            Phase::Paused | Phase::Done | Phase::Failed => Ok(()),
436        }
437    }
438
439    fn now(&self) -> u64 {
440        (self.clock)()
441    }
442
443    fn note(&mut self, entry: LogEntry) {
444        let lane = self.state.lane.clone();
445        self.log.record(
446            self.state.task_index,
447            self.state.attempt,
448            lane.as_deref(),
449            entry,
450        );
451    }
452
453    fn note_run(&mut self) {
454        let state = &self.state;
455        let entry = LogEntry::State(StateEvent::Run {
456            run_id: state.run_id.clone(),
457            goal: state.goal.clone(),
458            branch: state.branch.clone(),
459        });
460        self.note(entry);
461    }
462
463    /// Nothing before the plan exists.
464    fn note_plan(&mut self) {
465        let Some(plan) = &self.plan else {
466            return;
467        };
468        let titles: Vec<String> = plan.tasks.iter().map(|task| task.title.clone()).collect();
469        self.note(LogEntry::State(StateEvent::Plan {
470            tasks: titles.len(),
471            titles,
472        }));
473    }
474
475    fn set_phase(&mut self, phase: Phase) {
476        self.state.phase = phase;
477        self.note(LogEntry::State(StateEvent::Phase { phase }));
478    }
479
480    fn save(&mut self) -> Result<(), RunError> {
481        self.state.updated_at = self.now();
482        self.log.dir.write_state(&self.state)?;
483        Ok(())
484    }
485
486    fn task(&self) -> Option<&Task> {
487        let index = self.state.task_index?;
488        self.plan.as_ref()?.tasks.get(index.checked_sub(1)?)
489    }
490
491    // ---- planning
492
493    fn plan(&mut self) -> Result<(), RunError> {
494        let lane = self.config.roles.planner.clone();
495        let prompt = prompt::planner_prompt(&self.state.goal);
496        match self.ask(&lane, Role::Planner, &prompt, PLAN_SCHEMA, parse_plan)? {
497            Asked::Answer(plan) => self.accept_plan(plan),
498            Asked::Pause(reason, message, until) => {
499                self.pause(reason, Phase::Planning, message, until)
500            }
501            Asked::Failed(problem) => self.fail(format!("the planner failed twice: {problem}")),
502            Asked::Stopped => Ok(()),
503        }
504    }
505
506    /// A new run plans first, or starts from a plan the owner approved.
507    fn begin(&mut self, plan: Option<Plan>) -> Result<(), RunError> {
508        let Some(plan) = plan else {
509            self.note(LogEntry::State(StateEvent::Phase {
510                phase: Phase::Planning,
511            }));
512            return self.save();
513        };
514        self.accept_plan(plan)
515    }
516
517    fn accept_plan(&mut self, plan: Plan) -> Result<(), RunError> {
518        self.log.dir.write_plan(&plan)?;
519        self.plan = Some(plan);
520        self.note_plan();
521        self.start_task(1)
522    }
523
524    fn start_task(&mut self, index: usize) -> Result<(), RunError> {
525        let state = &mut self.state;
526        state.task_index = Some(index);
527        state.task_base = None;
528        state.attempt = None;
529        state.attempts_used = 0;
530        // Clearing the lane also restarts the Unknown streak at the next attempt.
531        state.lane = None;
532        state.skipped.clear();
533        state.issues.clear();
534        state.last_output_tail.clear();
535        state.last_end = None;
536        state.approved = false;
537        self.set_phase(Phase::Executing);
538        self.save()
539    }
540
541    /// Runs a planner or reviewer job, retried once, and parses its answer.
542    fn ask<T>(
543        &mut self,
544        lane: &str,
545        role: Role,
546        prompt: &str,
547        schema: &'static str,
548        parse: fn(&serde_json::Value) -> Result<T, FormatError>,
549    ) -> Result<Asked<T>, RunError> {
550        let mut problem = String::new();
551        for _ in 0..ASK_TRIES {
552            let Some((outcome, _)) = self.job(lane, role, prompt.to_string(), Some(schema))? else {
553                return Ok(Asked::Stopped);
554            };
555            match classify(outcome, parse) {
556                Ok(answer) => return Ok(Asked::Answer(answer)),
557                Err(Unusable::Pause(reason, message, until)) => {
558                    return Ok(Asked::Pause(reason, message, until));
559                }
560                Err(Unusable::Retry(message)) => problem = message,
561            }
562        }
563        Ok(Asked::Failed(problem))
564    }
565
566    /// Runs one job. `None` means the stop flag was set: the outcome is
567    /// discarded and the caller returns so the loop can pause.
568    fn job(
569        &mut self,
570        lane: &str,
571        role: Role,
572        prompt: String,
573        schema: Option<&'static str>,
574    ) -> Result<Option<(Outcome, String)>, RunError> {
575        self.state.job_seq += 1;
576        self.save()?;
577        let job = Job {
578            role,
579            prompt,
580            cwd: self.state.worktree.clone(),
581            run_dir: self.log.dir.path().to_path_buf(),
582            raw_log: self.log.dir.raw_log_path(self.state.job_seq),
583            schema,
584        };
585        let (task, attempt) = (self.state.task_index, self.state.attempt);
586        let mut texts: Vec<String> = Vec::new();
587        let log = &mut self.log;
588        let lock = &mut self.lock;
589        // A lock that cannot be updated only weakens the orphan check of the
590        // next start, so the job goes on.
591        let outcome = self.runner.run(
592            lane,
593            &job,
594            &mut |pgid| {
595                let _ = lock.set_pgid(Some(pgid));
596            },
597            &mut |event| {
598                if let HarnessEvent::Text { text } = &event {
599                    texts.push(text.clone());
600                }
601                log.record(task, attempt, Some(lane), LogEntry::Harness(event));
602            },
603        );
604        let _ = self.lock.set_pgid(None);
605        if self.stop.is_set() {
606            return Ok(None);
607        }
608        self.log.record(
609            task,
610            attempt,
611            Some(lane),
612            LogEntry::Outcome(outcome.clone()),
613        );
614        Ok(Some((outcome, texts.join("\n"))))
615    }
616
617    // ---- ending
618
619    fn fail(&mut self, message: String) -> Result<(), RunError> {
620        self.set_phase(Phase::Failed);
621        self.note(LogEntry::State(StateEvent::Failed { message }));
622        self.save()
623    }
624
625    fn pause_interrupted(&mut self) -> Result<(), RunError> {
626        let phase = self.state.phase;
627        if phase == Phase::Executing {
628            self.state.last_end = Some(LastEnd::Interrupted);
629        }
630        let message = "stopped by the user or a signal".to_string();
631        self.pause(PauseReason::Interrupted, phase, message, None)
632    }
633
634    /// When the next step is a worker attempt, the hand-over it would get is
635    /// written first, so a person can continue by hand.
636    fn pause(
637        &mut self,
638        reason: PauseReason,
639        resume_phase: Phase,
640        mut message: String,
641        until: Option<u64>,
642    ) -> Result<(), RunError> {
643        if resume_phase == Phase::Executing && self.write_pause_handover()? {
644            message.push_str(&format!(
645                "\nBy hand: cd {}, then tell any agent: Read .onerig/handover.md and follow its \
646                 Instruction section.\nAfterwards: onerig resume {}",
647                self.state.worktree.display(),
648                self.state.run_id
649            ));
650        }
651        self.state.phase = Phase::Paused;
652        self.state.paused = Some(Paused {
653            reason,
654            resume_phase,
655            message: message.clone(),
656            until,
657        });
658        self.note(LogEntry::State(StateEvent::Paused { reason, message }));
659        self.save()
660    }
661
662    /// False when there is no task yet, or git cannot give the diff.
663    fn write_pause_handover(&mut self) -> Result<bool, RunError> {
664        let next = self.state.attempt.unwrap_or(0) + 1;
665        match self.worker_prompt(next, true) {
666            Ok(prompt) => self.write_handover(next, &prompt).map(|()| true),
667            Err(_) => Ok(false),
668        }
669    }
670}
671
672/// The phases a run stops in; the others are working phases.
673fn exit_of(phase: Phase) -> Option<Exit> {
674    match phase {
675        Phase::Paused => Some(Exit::Paused),
676        Phase::Done => Some(Exit::Done),
677        Phase::Failed => Some(Exit::Failed),
678        Phase::Planning | Phase::Executing | Phase::Reviewing => None,
679    }
680}
681
682fn handover_note(worktree: &Path) -> PathBuf {
683    worktree.join(".onerig").join("handover.md")
684}
685
686fn remove_if_present(path: &Path) -> Result<(), StoreError> {
687    match std::fs::remove_file(path) {
688        Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(StoreError::Io {
689            path: path.to_path_buf(),
690            message: e.to_string(),
691        }),
692        _ => Ok(()),
693    }
694}
695
696mod execute;
697mod review;
698#[cfg(test)]
699mod tests;