Skip to main content

RunState

Struct RunState 

Source
pub struct RunState {
Show 36 fields pub schema: u32, pub id: String, pub repo: PathBuf, pub base_branch: String, pub base_commit: String, pub instruction: String, pub created_at: Timestamp, pub updated_at: Timestamp, pub status: RunStatus, pub seed: u64, pub config: Config, pub enabled_worktree_config: bool, pub candidates: Vec<Candidate>, pub judgements: Vec<Judgement>, pub judge_skipped: bool, pub deliberation: Vec<DeliberationRound>, pub votes: Vec<VoteRecord>, pub tally: Option<Tally>, pub reviews: Vec<ReviewRound>, pub gate: Vec<CommandOutcome>, pub gate_ran: bool, pub merge: Option<MergeOutcome>, pub leaks: Vec<Leak>, pub quota: Vec<QuotaLoss>, pub parked: bool, pub seats: BTreeMap<String, SeatState>, pub active: BTreeMap<String, ActiveSeat>, pub driver_pid: Option<u32>, pub driver_started_at: Option<String>, pub pr: Option<PrRecord>, pub base_sync: Option<BaseSync>, pub advice: Option<Advice>, pub advise_attempted: bool, pub events: Vec<Event>, pub jobs: Vec<JobRecord>, pub operator_fixes: Vec<OperatorFixRequest>,
}
Expand description

The whole run.

Fields§

§schema: u32

On-disk format version.

§id: String

Run id, e.g. 20260830-153012-a1b2.

§repo: PathBuf

Repository the run operates on.

§base_branch: String

Branch the run started from.

§base_commit: String

Commit the run started from.

§instruction: String

The task, verbatim.

§created_at: Timestamp

When the run was created.

§updated_at: Timestamp

Last state flush.

§status: RunStatus

Current status.

§seed: u64

Seed for labels and session ids.

§config: Config

Config snapshot, so a resumed run behaves like the original.

§enabled_worktree_config: bool

Did this run take a reference on extensions.worktreeConfig being on (see crate::git::acquire_worktree_config)? If so, cleanup releases it - which only actually turns the setting back off once every other run sharing this repository has released its own reference too.

§candidates: Vec<Candidate>

Candidates.

§judgements: Vec<Judgement>

Initial blind rankings.

§judge_skipped: bool

judge decided a solo candidate needs no panel and only logged it.

judgements stays empty in that case — nothing to distinguish from “not yet judged” — so this is the record that makes the skip idempotent: without it, every reentry re-ran judge, re-logged the same event, and rewrote status to Judging over whatever a later node had already concluded.

§deliberation: Vec<DeliberationRound>

Deliberation, if it happened.

§votes: Vec<VoteRecord>

Private final votes.

§tally: Option<Tally>

The count.

§reviews: Vec<ReviewRound>

Review rounds.

§gate: Vec<CommandOutcome>

Final gate.

Never derive whether the gate has run from gate.is_empty() alone — use Self::gate_status instead. An empty list is ambiguous on its own: it is what an unattempted gate looks like, what a resource-blocked attempt leaves behind (see graph::Runner::gate’s own doc), and also what a repo with no verify.gate commands configured produces once it has run. Self::gate_ran is what tells the third case apart from the first two.

§gate_ran: bool

Did gate() actually record an attempt — zero commands configured and vacuously passed, or one or more commands that ran to completion — as opposed to never having run, or having last hit a resource-blocked retry?

gate.is_empty() cannot tell those apart by itself: a repo with no verify.gate commands leaves gate empty exactly like an unattempted or resource-blocked one does, and reading that empty list as “not yet run” is what stranded a review-only run in RunStatus::Gating forever on such a repo — see SCHEMA’s doc for schema 7. A record written before this field existed defaults to false and is migrated in [migrate_schema].

§merge: Option<MergeOutcome>

Merge outcome.

§leaks: Vec<Leak>

Vendor tokens seen in judged material.

§quota: Vec<QuotaLoss>

Seats lost to a CLI rate limit / quota, in the order they hit.

§parked: bool

Parked at a node boundary, waiting to be resumed.

A run that is neither finished nor being worked on is otherwise indistinguishable from one whose daemon was killed, and the two want opposite things from an operator: the first is expected to be resumed, the second is a leftover. Cleared by the resume that carries it on.

§seats: BTreeMap<String, SeatState>

Per-seat conversation state.

§active: BTreeMap<String, ActiveSeat>

Seats currently mid-answer, keyed by seat.

An entry exists from the moment a prompt is sent until a reply (of any kind — success, failure, quota, drop) comes back, so its keys are exactly “who hasn’t answered yet” for whichever node populated it. See ActiveSeat for why a reader still has to check a live daemon before trusting one of these as “running” rather than “abandoned”.

§driver_pid: Option<u32>

Process id of whichever execute() call last drove this run — written at the very top of that method, the same place Self::clear_active runs, so a fresh reentry always overwrites the pid a previous, possibly-dead process left behind.

A daemon-claimed run already has a stronger signal (daemon::is_working_on), but a magi run / magi review typed straight into a terminal claims nothing there — before this field existed, [report::active_seats] had no way to tell that run apart from one a killed process abandoned, and printed the same “no live daemon claims this run” warning over a run that was, in fact, still answering. See Liveness for how this and the daemon claim combine.

§driver_started_at: Option<String>

The OS-reported moment Self::driver_pid started, recorded in the same breath as the pid itself — an opaque marker (crate::proc::process_started_at), compared only for equality.

A pid alone never proves a live process is this run’s driver: pids get reused, sometimes within minutes on a busy machine, and a killed manual magi run whose pid a later, wholly unrelated process happens to receive would otherwise read back as Liveness::Live from that coincidence alone. Self::liveness re-queries the current holder of driver_pid and requires this marker to still match before trusting a live answer — a mismatch means a different process now answers to that number, and no marker to compare (an old run, or a platform this build could not ask at record time) means neither extreme can be proven.

§pr: Option<PrRecord>

Last observation of the winner’s pull request, when a land loop ran.

Persisted rather than derived from the event log because the phone asks two questions about a run that has opened a PR - how are its checks and which round is it on - and parsing prose out of events to answer them would break the first time an event message was reworded.

§base_sync: Option<BaseSync>

The last look at how far the winner’s tree trailed the landing base, and the rebase(s) tried to close that gap. None until the tree has a winner to check.

§advice: Option<Advice>

The design-deliberation stage’s output, when [graph] advise ran it: one record per advisor seat, plus the synthesis blended into the implementer’s prompt. None when the stage is off, has not run yet, or could not even resolve its seats - see crate::graph::Runner::advise.

§advise_attempted: bool

Whether the design-deliberation stage has already been attempted this run, whatever it produced. The idempotency marker Runner::advise checks on reentry, the same role Self::judge_skipped plays for judge - without it a resumed run whose stage failed (a misconfigured [roles] advisors, every seat quota’d) would re-run it, and re-spend the agent calls, on every single reentry before implement.

§events: Vec<Event>

Node log.

§jobs: Vec<JobRecord>

Commands seats’ own CLIs reported running, across every node — see JobRecord. Populated in [crate::graph::wave] as each seat answers, so a resumed run keeps what earlier waves already collected rather than losing it to a reentry. Empty on a record written before this existed, or wherever no adapter reads structured job events for the backend a seat used — both read as “no evidence”, not “nothing ran”.

§operator_fixes: Vec<OperatorFixRequest>

Operator-triggered targeted fixes — see OperatorFixRequest and SCHEMA’s doc for schema 9. Empty on every record written before this existed, which reads correctly as “no operator fix ever requested”.

Implementations§

Source§

impl RunState

Source

pub fn new( repo: PathBuf, base_branch: String, base_commit: String, instruction: String, config: Config, ) -> Self

A fresh run.

Source

pub fn dir(&self) -> PathBuf

Directory holding this run’s state and artifacts.

Source

pub fn short(&self) -> &str

Short form used in branch names and reports.

Source

pub fn branch_for(&self, label: char) -> String

Branch name for a label.

Source

pub fn worktree_root(&self) -> PathBuf

Root of this run’s worktrees.

Source

pub fn event(&mut self, node: &str, message: impl Into<String>)

Note something in the run log and on the tracing stream.

Source

pub fn gate_status(&self) -> GateStatus

The honest state of the final gate.

Never derive this from gate.is_empty() alone anywhere else in the codebase — NotRun and PassedWithNoCommands both leave gate empty, and only this method (backed by Self::gate_ran) tells them apart. See SCHEMA’s doc for schema 7 for what conflating them used to do.

Source

pub fn seat_started( &mut self, node: &str, seat: &str, timeout: Duration, attempt: usize, )

Record that seat was just sent a prompt for node, with the given wall-clock budget. attempt is 0 for the first ask and N for the Nth nudge or resume, purely for display — it does not change how the seat is treated.

Source

pub fn seat_finished(&mut self, seat: &str)

Record that seat has answered, whatever the answer was.

Source

pub fn task_command( &mut self, task: &str, node: &str, attempt: usize, command: &str, index: usize, total: usize, timeout: Duration, )

Record that task ("e2e" or "gate" — a shell-command list run outside any seat) has just started command, the index-th of total. Called at every command boundary, not once for the whole list: verify.e2e / verify.gate apply timeout per command, so this is the only way a reader can tell “how long is left” for whichever command is actually running right now, rather than a stale budget left over from the first one.

Source

pub fn task_finished(&mut self, task: &str)

Record that task has finished its whole command list for this attempt.

Source

pub fn seats_active(&self) -> impl Iterator<Item = (&String, &ActiveSeat)>

The seats — never task entries — currently mid-answer. What report::active_seats and the phone’s “who has not answered yet” note need: a seat’s identifier is safe to show (ActiveSeat’s doc), so nothing here filters anything out beyond the type tag itself.

Source

pub fn tasks_active(&self) -> impl Iterator<Item = (&String, &ActiveSeat)>

The command-list tasks — never seat entries — currently running. Counterpart to Self::seats_active; see ActiveSeat::task for the tag both read.

Source

pub fn clear_active(&mut self) -> bool

Drop every seat this state still lists as answering, reporting whether anything was dropped.

Called first thing in execute, on every entry — fresh, resumed, or recovering a stall — because an entry here only means something while the process that wrote it is still asking that seat something. A process killed mid-wave leaves its last batch of seats here with nobody left to clear them, and the next process to touch this run must not let that leftover read as “still going” before it has asked anyone anything.

Source

pub fn active_all_overrun(&self, now: Timestamp) -> bool

Does every seat this run still lists as Self::active sit past its own ActiveSeat::timeout_secs? false when nothing is active at all — an empty map is not evidence of anything overrunning.

This alone is not proof the run is dead: a seat’s own attempt can legitimately run a little past its budget while the process driving it is still tearing the attempt down. Every caller pairs this with its own !live reading (daemon::is_working_on) before treating the run as abandoned — this module cannot check that itself without depending on crate::daemon, and callers already have to ask that question anyway.

Source

pub fn liveness_with<F, G>( &self, daemon_claims: bool, query: F, identity: G, ) -> Liveness
where F: FnOnce(u32) -> Option<bool>, G: FnOnce(u32) -> Option<String>,

Whether a process is actually still driving this run, given whether a daemon’s heartbeat claims it and process-liveness/identity queries for Self::driver_pid.

A daemon claim wins outright when present — it is the stronger, independently-heartbeating signal. Absent that (every manual magi run / magi review, and every daemon-driven run whose daemon has since exited cleanly), driver_pid is asked directly. A live answer alone is not enough to trust, though: pids get reused, so identity re-queries whoever currently holds that pid and the result must still match Self::driver_started_at — the marker recorded at the same moment driver_pid was — before this reads Live. A mismatch means a different process now answers to that number, which is exactly as good as proof the original driver is gone, so that reads Dead; no marker to compare against (an old run, or a platform this build could not ask at record time) or a None from either query, and this cannot tell either way, so it reads Liveness::Unknown — never guessed as Liveness::Dead out of mere silence. A display that guessed “dead” out of missing information would be exactly the mtime-and-task-manager guessing this type exists to replace.

Kept generic over query and identity so a test can inject answers without spawning a real process query — production code goes through Self::liveness, which supplies crate::proc::pid_status and crate::proc::process_started_at.

Source

pub fn liveness(&self, daemon_claims: bool) -> Liveness

Self::liveness_with, backed by the real process-liveness and identity queries.

Source

pub fn abandon(&mut self, by: &str)

Clear every seat this run still lists as active and fail it, unless it had already reached a terminal status some other way.

Callers must already have proven this run is dead — Self::active_all_overrun plus their own !live reading — before calling this; it does not check either itself. Unlike Self::clear_active (dropping a resumed run’s own stale wave before repopulating it, called unconditionally at the top of every execute()), this is a verdict: a run left this way has nothing left to repopulate the wave, ever, and must stop reading as implementing (or whichever node) forever.

Source

pub fn save(&mut self) -> Result<()>

Flush to run.json, atomically, under the process-global home.

Source

pub fn save_under(&mut self, home: &Path) -> Result<()>

Self::save, rooted at an explicit home instead of the process-global one.

For a caller that was already handed its own home explicitly — a housekeeping pass, mainly, for the same reason Queue::at and the daemon status path are parameters rather than resolved here (see daemon::drive’s own doc) — falling through to the global would write back through whichever directory some other process or test pinned into that OnceLock first, not the one this call was actually handed.

Source

pub fn load(id: &str) -> Result<Self>

Load a run by id or unambiguous id prefix.

Source§

impl RunState

Source

pub fn winner(&self) -> Option<&Candidate>

The winning candidate, once the tally has run.

Source

pub fn viable(&self) -> Vec<&Candidate>

Candidates eligible for judging.

Source

pub fn all_candidates_verified_noop(&self) -> bool

Did every candidate write nothing, and every one of them back it with evidence crate::graph’s adoption guard accepted?

All-or-nothing on purpose: one candidate declaring NO CHANGE NEEDED while another simply failed to produce anything is not agreement, it is one candidate’s unverified claim next to an ordinary loss, and the run must still read as the Failed it is. Only ever meaningful when Self::viable is already empty — a run with any real patch to judge never reaches the caller that asks this.

Source

pub fn open_findings(&self) -> Vec<&Finding>

Findings still open when the review loop stopped trying: the last round’s, exactly when that round was not clean. Empty on a run that never reviewed, or whose last round was clean.

This is the last round’s findings regardless of what the fixer claims to have addressed in that same round: a round that stopped the loop (round budget spent, or no tree progress for [crate::graph::STAGNANT_LIMIT] rounds) never had a following round to confirm the fix actually landed, and the self-reported adoption count is not trusted for that judgement either — see ReviewRound::progressed.

Source

pub fn last_round_findings(&self) -> Vec<&Finding>

Every finding raised in the most recent review round, regardless of that round’s own severity mix — unlike Self::open_findings, not filtered to a round that was not clean. This is the pool magi fix reports as available to pick from: a round can conclude clean (no finding blocked merge) while still carrying minor findings nobody has acted on.

Source

pub fn finding( &self, id: &str, ) -> Option<(&ReviewRound, &ReviewRecord, &Finding)>

Look up a finding by id anywhere in this run’s review history, together with the round and reviewer record that raised it — the provenance magi fix snapshots onto OperatorFixFinding.

Source

pub fn handed_off_with_open_findings(&self) -> bool

Did this run reach a mergeable status (Ready or Merged) with review findings still open?

That combination is the point of the review hand-off: the review round budget (or an unproductive round, see ReviewRound::progressed) was spent while gate and e2e stayed green, so the run was handed off rather than blocked — but the findings did not disappear, and whoever reads the result should be told they are still there.

Source

pub fn unmerged_by_design(&self) -> bool

Reached Ready because [merge] mode = "none" left it there by design, never to be picked up by the PR-polling merge watcher — as opposed to a Ready that is still a plausible landing candidate (a PR closed without merging, or a re-entry onto an already-concluded node). Both leave status at Ready; only this one leaves the winning branch permanently unwatched, which is what a caller needs to know before labelling the run in a listing.

Source

pub fn created_local(&self) -> String

Local-time creation stamp for reports.

Source

pub fn ensure_can_delete(&self, in_flight: bool) -> Result<()>

Assert that this run is safe to delete.

Refuses a run a live daemon is working on, and refuses any run whose candidate worktrees and branches have not been folded away with magi fold. The fold requirement is the real protection: it is what makes “delete” mean “remove a record” rather than “throw away a worktree somebody may still be editing”.

in_flight has to come from the caller, because a run’s own status cannot answer the question. A daemon killed mid-run leaves its status at implementing forever, and a guard that trusted that would make every interrupted run permanently undeletable - the operator’s only recourse being to edit run.json by hand, which is exactly the sort of thing this command exists to avoid. The queue already treats an orphaned .lock from a SIGKILLed daemon the same way; this is that rule for runs.

Trait Implementations§

Source§

impl Clone for RunState

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for RunState

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for RunState

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for RunState

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more