devflow_core/mode.rs
1//! Execution mode and the mode-driven gate decision.
2//!
3//! Mode is a per-session CLI flag on `devflow start` — there is no config file
4//! and no per-phase toggling.
5//!
6//! - **Auto:** Define and Plan run once. Code ↔ Validate auto-loop until clean.
7//! Then Ship. The only human gate is at Ship — unless Validate fails
8//! [`MAX_CONSECUTIVE_FAILURES`] times in a row, which forces a gate.
9//! - **Supervise:** Same pipeline, but Validate always fires a gate to Hermes →
10//! Human before advancing to Ship.
11
12use crate::stage::Stage;
13use serde::{Deserialize, Serialize};
14use std::fmt;
15use std::str::FromStr;
16
17/// Number of consecutive Validate failures in Auto mode before a gate is forced.
18pub const MAX_CONSECUTIVE_FAILURES: u32 = 3;
19
20/// Ceiling for [`crate::state::State::infra_failures`] before an
21/// infrastructure-class fault chain (OOM/`ResourceKilled`, missing agent
22/// binary/`AgentUnavailable`) forces a terminal gate (D-08, 17-01).
23///
24/// Deliberately more lenient than [`MAX_CONSECUTIVE_FAILURES`] (3): infra
25/// faults are not the agent's fault, so a higher ceiling tolerates transient
26/// cloud outages/OOM blips that a 3-ceiling would abort prematurely, while
27/// still bounding a stuck loop to at most 5 unobserved cycles before a
28/// terminal abort. Any increment of `infra_failures` must use
29/// `saturating_add` so a long-running stuck loop cannot overflow `u32`. The
30/// CLI's `transition()` resets `infra_failures` to 0 unconditionally on
31/// every successful stage transition (CR-01, 17-06 gap closure) — this
32/// reset is what makes the "5 unobserved cycles" ceiling bound a stuck loop
33/// rather than a phase's entire lifetime. Unlike `infra_failures`,
34/// `consecutive_failures`' reset is conditional — see
35/// [`transition_resets_consecutive_failures`] — the two counters no longer
36/// share a single reset condition (18d, WR-11).
37pub const MAX_INFRA_FAILURES: u32 = 5;
38
39/// Ceiling for [`crate::state::State::preflight_retries`] before a
40/// preflight gate's `GateAction::LoopBack` recursion aborts rather than
41/// polling another 7-day gate timeout (18f, D-18f backstop). A failing
42/// preflight is a readiness problem the operator is actively being asked
43/// about right now, not a transient infrastructure blip, so this takes the
44/// tighter [`MAX_CONSECUTIVE_FAILURES`]-style ceiling rather than the more
45/// lenient [`MAX_INFRA_FAILURES`]. Unlike those two counters, this one is
46/// NOT reset by `transition()` — it is reset by preflight success and by
47/// human approval (`GateAction::Advance`), both inside `run_preflight`
48/// (`devflow-cli/src/main.rs`).
49pub const MAX_PREFLIGHT_RETRIES: u32 = 3;
50
51/// Ceiling for [`crate::state::State::checkpoint_resumes`] before a
52/// checkpoint auto-decide relaunch (D-03/D-04, 28-03) stops resuming and
53/// falls through to the never-silent gate instead, its context naming the
54/// exhaustion. Bounds consecutive `claude --resume` relaunches for one
55/// stage's agent run against a checkpoint that keeps re-firing.
56///
57/// Takes the tighter [`MAX_CONSECUTIVE_FAILURES`]-style ceiling rather than
58/// the more lenient [`MAX_INFRA_FAILURES`]: a re-firing checkpoint is a
59/// decision the agent is failing to close on its own, not a transient
60/// infrastructure blip, so it does not deserve the same tolerance an OOM
61/// blip or a missing binary gets. An unbounded resume loop here would be
62/// structurally the same "gates hang forever" failure class D-09
63/// (`28-CONTEXT.md`) documents — this ceiling is what keeps it from becoming
64/// that.
65///
66/// Any increment of `checkpoint_resumes` must use `saturating_add`, exactly
67/// like [`Self::infra_failures`] and [`Self::preflight_retries`], so a stuck
68/// loop cannot overflow `u32`. Reset to 0 by every ORDINARY fresh stage
69/// launch (`pipeline_launch::launch_stage_inner`) — never by `transition()`
70/// — so the ceiling bounds one stage's resume budget, not a phase's entire
71/// lifetime, the same distinction [`MAX_INFRA_FAILURES`]'s doc comment draws
72/// for `infra_failures`. On exhaustion: fall through to the never-silent
73/// gate with a reason naming the exhaustion — never a silent stop, never an
74/// unbounded loop.
75pub const MAX_CHECKPOINT_RESUMES: u32 = 3;
76
77/// 28-03 (Task 1): the ceiling must be a small, positive, bounded number —
78/// greater than zero (or a checkpoint could never resume even once) and no
79/// larger than the more lenient infra ceiling (a re-firing checkpoint gets
80/// LESS tolerance than a transient infra blip, not more). A compile-time
81/// assertion rather than a runtime `#[test]` because both operands are
82/// `const` — clippy's `assertions_on_constants` correctly flags a runtime
83/// test here as unable to ever fail at runtime; this const block still
84/// fails the BUILD if a future edit violates the invariant.
85const _: () = assert!(MAX_CHECKPOINT_RESUMES > 0 && MAX_CHECKPOINT_RESUMES <= MAX_INFRA_FAILURES);
86
87/// Whether `transition()` should zero
88/// [`crate::state::State::consecutive_failures`] when moving from `from` to
89/// `to`.
90///
91/// `consecutive_failures` is meant to count repeated Code↔Validate CYCLES —
92/// each cycle is a full loop through Code, then Validate, then (on failure)
93/// back to Code again. But the Code→Validate hop is crossed on *every
94/// single cycle*, including the ones that are about to fail. Resetting the
95/// counter on that specific hop means it can never accumulate past 1, so
96/// [`MAX_CONSECUTIVE_FAILURES`] — the ceiling that exists specifically to
97/// bound this loop — is unreachable (18d). Every other transition is
98/// genuine forward progress out of the Code↔Validate loop (or the initial
99/// Define→Plan→Code entry into it) and correctly clears the counter.
100///
101/// This rule deliberately does NOT apply to
102/// [`crate::state::State::infra_failures`], whose unconditional reset in
103/// `transition()` is correct for its own semantics: infra faults accumulate
104/// within a single stage's repeated failures and are routed through
105/// `handle_infra_outcome` → `gate_or_abort_infra` → `handle_stage_failure`,
106/// whose retry arms call `launch_stage` directly and never cross
107/// `transition()` at all. Widening this predicate's shape onto
108/// `infra_failures` would silently convert [`MAX_INFRA_FAILURES`] from a
109/// stuck-loop bound into a phase-lifetime bound — the exact regression
110/// 17-06 was written to prevent.
111pub fn transition_resets_consecutive_failures(from: Stage, to: Stage) -> bool {
112 !matches!((from, to), (Stage::Code, Stage::Validate))
113}
114
115/// Whether a Validate failure represents forward progress since the last
116/// recorded failure (999.66, D-03) — i.e. whether Code produced new commits
117/// on the phase's feature branch since
118/// [`crate::state::State::last_validate_failure_commit_count`] was last
119/// observed.
120///
121/// `previous` is the baseline recorded at the prior failure;
122/// `current` is the commit count observed at THIS failure.
123///
124/// `None` for `previous` reports progress: it means no prior failure has
125/// been recorded, so there is no streak to continue — the first failure of
126/// a phase, and the first failure observed after resuming state written
127/// before this baseline field existed, must both begin a fresh streak
128/// rather than extend a nonexistent one.
129///
130/// The comparison is strictly greater, not merely not-equal: a count that
131/// went DOWN means the branch was rewound or rebuilt, which is not evidence
132/// that the problem Validate reported was addressed. Treating a decrease as
133/// progress would hand a free counter reset to exactly the situation least
134/// likely to deserve one.
135///
136/// **What this predicate does not establish.** A `true` result means new
137/// commits exist, not that those commits addressed anything. An agent that
138/// commits something trivial on every cycle resets the streak every cycle
139/// and never reaches [`MAX_CONSECUTIVE_FAILURES`]. This is the accepted,
140/// documented weakness of the commit-count signal recorded in
141/// `33-RESEARCH.md`'s D-03 Recommendation and Assumptions Log A1 — the same
142/// weakness `evaluate_layer2`'s own "no work done" gate already carries,
143/// which a single trivial commit also already defeats today. It is a real
144/// narrowing of the guarantee that `MAX_CONSECUTIVE_FAILURES` bounds a
145/// genuinely stuck loop, and it is deliberately NOT strengthened here with a
146/// lines-changed or files-touched threshold — that is a follow-up if the
147/// assumption proves wrong, not a speculative heuristic to add to the
148/// safety gate's path now.
149pub fn consecutive_failures_made_progress(previous: Option<u32>, current: u32) -> bool {
150 previous.is_none_or(|p| current > p)
151}
152
153/// How DevFlow drives the pipeline for a session.
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
155#[serde(rename_all = "lowercase")]
156pub enum Mode {
157 /// Run the pipeline without human gates until Ship (or repeated failure).
158 Auto,
159 /// Fire a Validate gate to Hermes → Human before Ship.
160 Supervise,
161}
162
163impl Mode {
164 /// Whether `stage` should fire a gate, given how many consecutive Validate
165 /// failures have already occurred this session.
166 ///
167 /// - Ship always gates (both modes).
168 /// - Supervise gates at every Validate.
169 /// - Auto gates at Validate only after [`MAX_CONSECUTIVE_FAILURES`] failures.
170 pub fn should_gate(self, stage: Stage, consecutive_failures: u32) -> bool {
171 match stage {
172 Stage::Ship => true,
173 Stage::Validate => match self {
174 Mode::Supervise => true,
175 Mode::Auto => consecutive_failures >= MAX_CONSECUTIVE_FAILURES,
176 },
177 _ => false,
178 }
179 }
180
181 /// Whether a failed Validate at `stage` may auto-loop back to Code without a
182 /// human gate. Auto loops Code↔Validate; Supervise requires human approval.
183 pub fn should_auto_loop(self, stage: Stage) -> bool {
184 matches!(stage, Stage::Validate) && matches!(self, Mode::Auto)
185 }
186}
187
188impl fmt::Display for Mode {
189 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190 let name = match self {
191 Mode::Auto => "auto",
192 Mode::Supervise => "supervise",
193 };
194 f.write_str(name)
195 }
196}
197
198impl FromStr for Mode {
199 type Err = ModeParseError;
200
201 fn from_str(value: &str) -> Result<Self, Self::Err> {
202 match value.to_ascii_lowercase().as_str() {
203 "auto" => Ok(Mode::Auto),
204 "supervise" | "supervised" => Ok(Mode::Supervise),
205 other => Err(ModeParseError(other.to_string())),
206 }
207 }
208}
209
210/// Error returned when parsing an unsupported mode name.
211#[derive(Debug, Clone, thiserror::Error)]
212#[error("unsupported mode `{0}`; expected auto or supervise")]
213pub struct ModeParseError(String);
214
215#[cfg(test)]
216mod tests {
217 use super::*;
218
219 #[test]
220 fn from_str_accepts_canonical_and_alias() {
221 assert_eq!("auto".parse::<Mode>().unwrap(), Mode::Auto);
222 assert_eq!("AUTO".parse::<Mode>().unwrap(), Mode::Auto);
223 assert_eq!("supervise".parse::<Mode>().unwrap(), Mode::Supervise);
224 assert_eq!("supervised".parse::<Mode>().unwrap(), Mode::Supervise);
225 }
226
227 #[test]
228 fn from_str_rejects_unknown() {
229 let err = "yolo".parse::<Mode>().unwrap_err();
230 assert!(err.to_string().contains("yolo"));
231 }
232
233 #[test]
234 fn auto_does_not_gate_validate_until_failure_threshold() {
235 assert!(!Mode::Auto.should_gate(Stage::Validate, 0));
236 assert!(!Mode::Auto.should_gate(Stage::Validate, 2));
237 assert!(Mode::Auto.should_gate(Stage::Validate, MAX_CONSECUTIVE_FAILURES));
238 assert!(Mode::Auto.should_gate(Stage::Validate, 9));
239 }
240
241 #[test]
242 fn supervise_always_gates_validate() {
243 assert!(Mode::Supervise.should_gate(Stage::Validate, 0));
244 assert!(Mode::Supervise.should_gate(Stage::Validate, 5));
245 }
246
247 #[test]
248 fn ship_always_gates_in_both_modes() {
249 assert!(Mode::Auto.should_gate(Stage::Ship, 0));
250 assert!(Mode::Supervise.should_gate(Stage::Ship, 0));
251 }
252
253 #[test]
254 fn non_gate_stages_never_gate() {
255 for stage in [Stage::Define, Stage::Plan, Stage::Code] {
256 assert!(!Mode::Auto.should_gate(stage, 99));
257 assert!(!Mode::Supervise.should_gate(stage, 99));
258 }
259 }
260
261 #[test]
262 fn auto_loops_validate_supervise_does_not() {
263 assert!(Mode::Auto.should_auto_loop(Stage::Validate));
264 assert!(!Mode::Supervise.should_auto_loop(Stage::Validate));
265 assert!(!Mode::Auto.should_auto_loop(Stage::Code));
266 }
267
268 #[test]
269 fn display_round_trips_through_from_str() {
270 for mode in [Mode::Auto, Mode::Supervise] {
271 assert_eq!(mode.to_string().parse::<Mode>().unwrap(), mode);
272 }
273 }
274
275 #[test]
276 fn consecutive_reset_skips_the_code_to_validate_hop() {
277 assert!(!transition_resets_consecutive_failures(
278 Stage::Code,
279 Stage::Validate
280 ));
281 }
282
283 #[test]
284 fn consecutive_reset_fires_on_every_other_transition() {
285 // Enumerated explicitly (not a negation of the skip case above) so a
286 // future Stage variant added to the linear chain doesn't silently
287 // fall through un-asserted.
288 assert!(transition_resets_consecutive_failures(
289 Stage::Define,
290 Stage::Plan
291 ));
292 assert!(transition_resets_consecutive_failures(
293 Stage::Plan,
294 Stage::Code
295 ));
296 assert!(transition_resets_consecutive_failures(
297 Stage::Validate,
298 Stage::Ship
299 ));
300 }
301
302 #[test]
303 fn made_progress_treats_no_prior_record_as_progress() {
304 // No prior record with a zero current count: the state of a
305 // brand-new phase whose feature branch does not exist yet. This is
306 // the case that matters most — it must report progress so the very
307 // first failure of a phase never mis-accumulates.
308 assert!(consecutive_failures_made_progress(None, 0));
309 // No prior record with a non-zero current count.
310 assert!(consecutive_failures_made_progress(None, 5));
311 }
312
313 #[test]
314 fn made_progress_requires_a_strictly_higher_count() {
315 // Strictly greater: progress.
316 assert!(consecutive_failures_made_progress(Some(2), 3));
317 // Equal, both non-zero: no progress.
318 assert!(!consecutive_failures_made_progress(Some(2), 2));
319 // Equal, both zero: no progress. This is the case
320 // `consecutive_failures_reaches_ceiling_across_cycles` (devflow-cli)
321 // actually exercises — a repo with no feature branch, counting zero
322 // commits every cycle — and it is the single case
323 // MAX_CONSECUTIVE_FAILURES most depends on remaining reachable.
324 assert!(!consecutive_failures_made_progress(Some(0), 0));
325 // Lower: no progress. A count that went down means the branch was
326 // rewound or rebuilt, not that the reported problem was addressed.
327 assert!(!consecutive_failures_made_progress(Some(3), 2));
328 }
329}